commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
4c29471af61989e852a813999cf37aa9a8acf76d
test anon to /users endpoint
onadata/apps/api/tests/viewsets/test_user_viewset.py
onadata/apps/api/tests/viewsets/test_user_viewset.py
import json from onadata.apps.api.tests.viewsets.test_abstract_viewset import\ TestAbstractViewSet from onadata.apps.api.viewsets.user_viewset import UserViewSet class TestUserViewSet(TestAbstractViewSet): def setUp(self): super(self.__class__, self).setUp() def test_user_list(self): view = UserViewSet.as_view({'get': 'list'}) request = self.factory.get('/', **self.extra) response = view(request) data = [{'username': u'bob', 'first_name': u'Bob', 'last_name': u''}] self.assertContains(response, json.dumps(data)) def test_user_get(self): view = UserViewSet.as_view({'get': 'retrieve'}) request = self.factory.get('/', **self.extra) response = view(request, username='bob') data = {'username': u'bob', 'first_name': u'Bob', 'last_name': u''} self.assertContains(response, json.dumps(data)) def test_user_anon_get(self): view = UserViewSet.as_view({'get': 'retrieve'}) request = self.factory.get('/') response = view(request, username='bob') data = {'username': u'bob', 'first_name': u'Bob', 'last_name': u''} self.assertContains(response, json.dumps(data))
Python
0.000001
@@ -568,32 +568,327 @@ n.dumps(data))%0A%0A + def test_user_list_anon(self):%0A view = UserViewSet.as_view(%7B'get': 'list'%7D)%0A request = self.factory.get('/')%0A response = view(request)%0A data = %5B%7B'username': u'bob', 'first_name': u'Bob', 'last_name': u''%7D%5D%0A self.assertContains(response, json.dumps(data))%0A%0A def test_use
84eff383a42784400261c39c87b9455133771bea
correct role & add image
data/upload/backend/parser.py
data/upload/backend/parser.py
import re import csv from data.upload.backend.xlrd import xlrd_dict_reader from data.upload.backend.csv import csv_dict_reader from data.upload.models import (SpreadsheetUpload, SpreadsheetPerson, SpreadsheetSource, SpreadsheetLink, SpreadsheetContactDetail) from contextlib import contextmanager from pupa.scrape.helpers import Legislator from pupa.scrape.popolo import Organization OCD_SOURCE_URL = "http://opencivicdata.org/manual-data/source-notice" def people_to_pupa(stream, transaction): org = Organization( name=transaction.jurisdiction.name, classification='legislature', ) for person in stream: name = person.name position = person.position district = person.district image = person.image if not name or not district: raise ValueError("A name and district is required for each entry.") if position is None: position = "member" obj = Legislator(name=name, district=district) if image: obj.image = image org.add_post(label=district, role=position) for detail in person.contacts.all(): obj.add_contact_detail( type=detail.type, value=detail.value, note=detail.note, ) for link in person.links.all(): obj.add_link( url=link.url, note=link.url ) for source in person.sources.all(): obj.add_source( url=source.url, note=source.note, ) obj.validate() obj.pre_save(transaction.jurisdiction.id) yield obj for related in obj._related: yield related for related in org._related: yield related yield org def import_parsed_stream(stream, user, jurisdiction): upload = SpreadsheetUpload(user=user, jurisdiction=jurisdiction) upload.save() for person in stream: if (not person['District'] or not person['Name'] or not person['Position']): raise ValueError("Bad district or name") who = SpreadsheetPerson( name=person.pop('Name'), spreadsheet=upload, position=person.pop('Position'), district=person.pop('District'), ) who.save() contact_details = { "Address": "address", "Phone": "voice", "Email": "email", "Fax": "fax", "Cell": "voice", "Twitter": "twitter", "Facebook": "facebook" } links = ["Website", "Homepage"] sources = ["Source"] for key, value in person.items(): match = re.match("(?P<key>.*) (?P<label>\(.*\))?", key) root = key label = None if match: d = match.groupdict() root = d['key'] label = d['label'].rstrip(")").lstrip("(") if root in sources: a = SpreadsheetSource( person=who, url=value, note=key ) a.save() continue # If we've got a link. if root in links: a = SpreadsheetLink( person=who, url=value, note=key, ) a.save() continue # If we've got a contact detail. if root in contact_details: type_ = contact_details[root] a = SpreadsheetContactDetail( person=who, type=type_, value=value, label=label or "", note=key, ) a.save() continue raise ValueError("Unknown spreadhseet key: %s" % (key)) return upload def import_stream(stream, extension, user, jurisdiction): reader = {"csv": csv_dict_reader, "xlsx": xlrd_dict_reader, "xls": xlrd_dict_reader}[extension] return import_parsed_stream(reader(stream), user, jurisdiction) @contextmanager def import_file_stream(fpath, user, jurisdiction): _, xtn = fpath.rsplit(".", 1) with open(fpath, 'br') as fd: yield import_stream(fd, xtn, user, jurisdiction)
Python
0
@@ -1135,24 +1135,46 @@ t(label= +%22%25s, %25s%22 %25 (position, district , role=p @@ -1165,16 +1165,17 @@ district +) , role=p @@ -2424,32 +2424,106 @@ ct'),%0A )%0A + if 'Image' in person:%0A who.image = person.pop(%22Image%22)%0A who.save
9e30bc38cfa3cb000ab2d84730552d50ea604ac1
configure wsgi file to use whitenoise
heroku-libsass-python/wsgi.py
heroku-libsass-python/wsgi.py
""" WSGI config for project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = ".settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config") os.environ.setdefault("DJANGO_CONFIGURATION", "Production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from configurations.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Python
0
@@ -1287,43 +1287,135 @@ ion%0A -application = get_wsgi_application( +from whitenoise.django import DjangoWhiteNoise%0A%0Aapplication = get_wsgi_application()%0Aapplication = DjangoWhiteNoise(application )%0A%0A#
92f0256a1a8c44cf9ed7e5966f254de1d2f5c72b
fix HsJoinFairShare.selectedOneHot driver
hwtLib/handshaked/joinFair.py
hwtLib/handshaked/joinFair.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from copy import copy from hwt.code import Or, rol, SwitchLogic from hwt.hdl.types.bits import Bits from hwt.interfaces.std import VldSynced from hwt.interfaces.utils import addClkRstn from hwt.synthesizer.param import Param from hwt.synthesizer.vectorUtils import iterBits from hwtLib.handshaked.joinPrioritized import HsJoinPrioritized from hwtLib.handshaked.streamNode import StreamNode class HsJoinFairShare(HsJoinPrioritized): """ Join multiple input streams into single output stream. Priority is changing every clock period. If prioritized input is not sending valid data, input with lowest index and valid is used. :note: combinational .. hwt-schematic: _example_HsJoinFairShare """ def _config(self): HsJoinPrioritized._config(self) self.EXPORT_SELECTED = Param(True) def _declr(self): HsJoinPrioritized._declr(self) addClkRstn(self) if self.EXPORT_SELECTED: s = self.selectedOneHot = VldSynced()._m() s.DATA_WIDTH = self.INPUTS @staticmethod def priorityAck(priorityReg, vldSignals, index): """ Generate ack logic for selected input :param priorityReg: priority register with one hot encoding, 1 means input of this index should have be prioritized. :param vldSignals: list of vld signals of input :param index: index of input for which you wont get ack logic :return: ack signal for this input """ priorityOverdrives = [] vldWithHigherPriority = list(vldSignals[:index]) for i, (p, vld) in enumerate(zip(iterBits(priorityReg), vldSignals)): if i > index: priorityOverdrives.append(p & vld) # ack when no one with higher priority has vld or this input have the # priority ack = ~Or(*priorityOverdrives, * vldWithHigherPriority) | priorityReg[index] return ack def isSelectedLogic(self, din_vlds, dout_rd, selectedOneHot): """ Resolve isSelected signal flags for each input, when isSelected flag signal is 1 it means input has clearance to make transaction """ assert din_vlds if len(din_vlds) == 1: isSelectedFlags = copy(din_vlds) if selectedOneHot is not None: selectedOneHot.data(1) else: priority = self._reg("priority", Bits(len(din_vlds)), def_val=1) priority(rol(priority, 1)) isSelectedFlags = [] for i, din_vld in enumerate(din_vlds): isSelected = self._sig("isSelected_%d" % i) isSelected(self.priorityAck(priority, din_vlds, i)) isSelectedFlags.append(isSelected) if selectedOneHot is not None: selectedOneHot.data[i](isSelected & din_vld) if selectedOneHot is not None: selectedOneHot.vld(Or(*din_vlds) & dout_rd) return isSelectedFlags def inputMuxLogic(self, isSelectedFlags): vld = self.get_valid_signal dout = self.dataOut # data out mux dataCases = [] for isSelected, din in zip(isSelectedFlags, self.dataIn): dataConnectExpr = self.dataConnectionExpr(din, dout) cond = vld(din) & isSelected dataCases.append((cond, dataConnectExpr)) dataDefault = self.dataConnectionExpr(None, dout) SwitchLogic(dataCases, dataDefault) def _impl(self): if self.EXPORT_SELECTED: selectedOneHot = None else: selectedOneHot = self.selectedOneHot rd = self.get_ready_signal vld = self.get_valid_signal dout = self.dataOut din_vlds = [vld(d) for d in self.dataIn] # round-robin isSelectedFlags = self.isSelectedLogic( din_vlds, rd(dout), selectedOneHot) self.inputMuxLogic(isSelectedFlags) # handshake logic with injected round-robin for din, isSelected in zip(self.dataIn, isSelectedFlags): rd(din)(isSelected & rd(dout)) vld(dout)(Or(*din_vlds)) def _example_HsJoinFairShare(): from hwt.interfaces.std import Handshaked u = HsJoinFairShare(Handshaked) u.INPUTS = 3 return u if __name__ == "__main__": from hwt.synthesizer.utils import toRtl u = _example_HsJoinFairShare() print(toRtl(u))
Python
0
@@ -3641,20 +3641,35 @@ neHot = -None +self.selectedOneHot %0A @@ -3704,35 +3704,20 @@ neHot = -self.selectedOneHot +None %0A
e5b1221598e27c0b871f6afa34bd9dfa06a72845
clean up artifacts at the end of doc build
docs/build.py
docs/build.py
#!/usr/bin/env python """Build scriptharness documentation. At some point it would be good to automate all CI/Release tasks for scriptharness; this is a good start. """ from __future__ import print_function, division, absolute_import, \ unicode_literals from jinja2 import Template import os import shutil import subprocess import sys READTHEDOCS_LINK = """.. image:: https://readthedocs.org/projects/python-scriptharness/badge/?version=latest :target: https://readthedocs.org/projects/python-scriptharness/?badge=latest :alt: Documentation Status""" def cleanup(*args): """Cleanliness.""" for path in args: if os.path.exists(path): os.remove(path) def build_readme_rst(): with open("README.rst.j2") as filehandle: contents = filehandle.read() template = Template(contents) with open("../README.rst", "w") as filehandle: filehandle.write(template.render(readthedocs_link=READTHEDOCS_LINK)) with open("README.rst", "w") as filehandle: filehandle.write(template.render()) def indent_output(command, required_string="INFO", **kwargs): output = "" kwargs.setdefault('stderr', subprocess.STDOUT) for line in subprocess.check_output(command, **kwargs).splitlines(): output += " {}{}".format(line.decode(), os.linesep) assert required_string in output return output def build_quickstart(): for line in subprocess.check_output(['git', 'branch', '--no-color'], stderr=subprocess.PIPE).splitlines(): if line.startswith(b'*'): _, branch = line.split() branch = branch.decode() with open("quickstart.rst.j2") as filehandle: contents = filehandle.read() template = Template(contents) quickstart_contents = "" with open("../examples/quickstart.py") as filehandle: for line in filehandle.readlines(): quickstart_contents += " {}".format(line) run_output = indent_output( [sys.executable, "../examples/quickstart.py"], ) actions_output = indent_output( [sys.executable, "../examples/quickstart.py", "--actions", "package", "upload", "notify"], ) list_actions_output = indent_output( [sys.executable, "../examples/quickstart.py", "--list-actions"], required_string="clobber", ) dump_config_output = indent_output( [sys.executable, "../examples/quickstart.py", "--new-argument", "foo", "--dump-config"], required_string="Dumping", ) help_output = indent_output( [sys.executable, "../examples/quickstart.py", "--help"], required_string="usage:" ) with open("quickstart.rst", "w") as filehandle: filehandle.write( template.render( git_branch=branch, quickstart_contents=quickstart_contents, run_output=run_output, actions_output=actions_output, list_actions_output=list_actions_output, dump_config_output=dump_config_output, help_output=help_output, ) ) def main(): """Main function""" os.chdir(os.path.dirname(__file__)) subprocess.check_call("sphinx-apidoc -f -o . ../scriptharness".split()) cleanup("modules.rst") build_readme_rst() build_quickstart() subprocess.check_call(["make", "html"]) subprocess.check_call(["make", "text"]) subprocess.check_call(["cp", "_build/text/README.txt", "../README"]) if __name__ == '__main__': main()
Python
0
@@ -3542,16 +3542,87 @@ EADME%22%5D) +%0A if os.path.exists(%22artifacts%22):%0A shutil.rmtree(%22artifacts%22) %0A%0Aif __n
8e0550d405230be25a2e8fe19cf86a4f27881ffa
add energy_per_formula_unit to ComputedEntry
pymatgen/entries/computed_entries.py
pymatgen/entries/computed_entries.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import json from monty.json import MontyEncoder, MontyDecoder from pymatgen.core.composition import Composition from monty.json import MSONable """ This module implements equivalents of the basic ComputedEntry objects, which is the basic entity that can be used to perform many analyses. ComputedEntries contain calculated information, typically from VASP or other electronic structure codes. For example, ComputedEntries can be used as inputs for phase diagram analysis. """ __author__ = "Shyue Ping Ong, Anubhav Jain" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "1.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Production" __date__ = "Apr 30, 2012" class ComputedEntry(MSONable): """ An lightweight ComputedEntry object containing key computed data for many purposes. Extends a PDEntry so that it can be used for phase diagram generation. The difference between a ComputedEntry and a standard PDEntry is that it includes additional parameters like a correction and run_parameters. """ def __init__(self, composition, energy, correction=0.0, parameters=None, data=None, entry_id=None, attribute=None): """ Initializes a ComputedEntry. Args: composition (Composition): Composition of the entry. For flexibility, this can take the form of all the typical input taken by a Composition, including a {symbol: amt} dict, a string formula, and others. energy (float): Energy of the entry. Usually the final calculated energy from VASP or other electronic structure codes. correction (float): A correction to be applied to the energy. This is used to modify the energy for certain analyses. Defaults to 0.0. parameters (dict): An optional dict of parameters associated with the entry. Defaults to None. data (dict): An optional dict of any additional data associated with the entry. Defaults to None. entry_id (obj): An optional id to uniquely identify the entry. attribute: Optional attribute of the entry. This can be used to specify that the entry is a newly found compound, or to specify a particular label for the entry, or else ... Used for further analysis and plotting purposes. An attribute can be anything but must be MSONable. """ self.uncorrected_energy = energy self.composition = Composition(composition) self.correction = correction self.parameters = parameters if parameters else {} self.data = data if data else {} self.entry_id = entry_id self.name = self.composition.reduced_formula self.attribute = attribute @property def is_element(self): return self.composition.is_element @property def energy(self): """ Returns the *corrected* energy of the entry. """ return self.uncorrected_energy + self.correction @property def energy_per_atom(self): return self.energy / self.composition.num_atoms def __repr__(self): output = ["ComputedEntry {} - {}".format(self.entry_id, self.composition.formula), "Energy = {:.4f}".format(self.uncorrected_energy), "Correction = {:.4f}".format(self.correction), "Parameters:"] for k, v in self.parameters.items(): output.append("{} = {}".format(k, v)) output.append("Data:") for k, v in self.data.items(): output.append("{} = {}".format(k, v)) return "\n".join(output) def __str__(self): return self.__repr__() @classmethod def from_dict(cls, d): dec = MontyDecoder() return cls(d["composition"], d["energy"], d["correction"], parameters={k: dec.process_decoded(v) for k, v in d.get("parameters", {}).items()}, data={k: dec.process_decoded(v) for k, v in d.get("data", {}).items()}, entry_id=d.get("entry_id", None), attribute=d["attribute"] if "attribute" in d else None) def as_dict(self): return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "energy": self.uncorrected_energy, "composition": self.composition.as_dict(), "correction": self.correction, "parameters": json.loads(json.dumps(self.parameters, cls=MontyEncoder)), "data": json.loads(json.dumps(self.data, cls=MontyEncoder)), "entry_id": self.entry_id, "attribute": self.attribute} class ComputedStructureEntry(ComputedEntry): """ A heavier version of ComputedEntry which contains a structure as well. The structure is needed for some analyses. """ def __init__(self, structure, energy, correction=0.0, parameters=None, data=None, entry_id=None): """ Initializes a ComputedStructureEntry. Args: structure (Structure): The actual structure of an entry. energy (float): Energy of the entry. Usually the final calculated energy from VASP or other electronic structure codes. correction (float): A correction to be applied to the energy. This is used to modify the energy for certain analyses. Defaults to 0.0. parameters (dict): An optional dict of parameters associated with the entry. Defaults to None. data (dict): An optional dict of any additional data associated with the entry. Defaults to None. entry_id (obj): An optional id to uniquely identify the entry. """ super().__init__( structure.composition, energy, correction=correction, parameters=parameters, data=data, entry_id=entry_id) self.structure = structure def __repr__(self): output = ["ComputedStructureEntry {} - {}".format( self.entry_id, self.composition.formula), "Energy = {:.4f}".format(self.uncorrected_energy), "Correction = {:.4f}".format(self.correction), "Parameters:"] for k, v in self.parameters.items(): output.append("{} = {}".format(k, v)) output.append("Data:") for k, v in self.data.items(): output.append("{} = {}".format(k, v)) return "\n".join(output) def __str__(self): return self.__repr__() def as_dict(self): d = super().as_dict() d["@module"] = self.__class__.__module__ d["@class"] = self.__class__.__name__ d["structure"] = self.structure.as_dict() return d @classmethod def from_dict(cls, d): dec = MontyDecoder() return cls(dec.process_decoded(d["structure"]), d["energy"], d["correction"], parameters={k: dec.process_decoded(v) for k, v in d.get("parameters", {}).items()}, data={k: dec.process_decoded(v) for k, v in d.get("data", {}).items()}, entry_id=d.get("entry_id", None))
Python
0.00006
@@ -3376,16 +3376,156 @@ _atoms%0A%0A + @property%0A def energy_per_formula_unit(self):%0A return self.energy / self.composition.get_reduced_composition_and_factor()%5B1%5D%0A%0A def
087b73ea523213d29430801eac4156d789b78bbc
Remove redundant select parameters
models/hr_complaint.py
models/hr_complaint.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from datetime import date from odoo import api, fields, models from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT as DF class HrComplaint(models.Model): _name = "hr_complaint.complaint" _description = "Employee Complaint" _inherit = "mail.thread" name = fields.Char("Name") complaint_date = fields.Date("Date of Complaint", required=True, select=True, default=date.today()) employee_id = fields.Many2one('hr.employee', "Employee", required=True) complaint_mode = fields.Selection([ ('0', 'Telephone'), ('1', 'Other Verbal'), ('2', 'In writing')], "Method of Complaint", help="This is the mode by which the complaint was received.") complaint_type = fields.Selection([ ('0', 'Formal'), ('1', 'Informal')], "Type of Complaint") complaint_source = fields.Selection([ ('0', 'Client'), ('1', 'Public'), ('2', 'Other Employee'), ('3', 'Management')], "Source of Complaint") complaint_source_text = fields.Char('Complainant',size=100) complaint_outline = fields.Text('Outline of Complaint') complaint_evidence = fields.Text('Evidence') complaint_witnesses = fields.Text('Witnesses') recorded_by = fields.Many2one('hr.employee',"Complaint Recorded By",required=True) complaint_assessment = fields.Selection([ ('0', 'Trivial'), ('1', 'Minor'), ('2', 'Moderate'), ('3', 'Serious'), ('4', 'Very Serious')], "Seriousness of complaint") #allegations questions stealing = fields.Boolean('Stealing') fraud = fields.Boolean('Fraud') violence = fields.Boolean('Threats and/or violence') safety = fields.Boolean('Safety breaches') discrimination = fields.Boolean('Discrimination') #indicator question policy = fields.Boolean('Breach of contract/policy') client_contract = fields.Boolean('Breach of the company\'s contracts with clients') directions = fields.Boolean('Refusal to follow reasonable directions') performance = fields.Boolean('Unsatisfactory performance') behaviour = fields.Boolean('Inappropriate behaviour') property = fields.Boolean('Misuse of company property') evidence_sufficient = fields.Boolean('Is there sufficient evidence to investigate?') investigation_required =fields.Selection([ ('1', 'Yes - Formal'), ('2', 'Yes - Informal'), ('3', 'No')], 'Does the complaint require investigation?') complaint_refer = fields.Boolean('Does the complaint have to be referred to another organisation?') investigation_plan = fields.Text('Investigation methods/plan') assigned_to = fields.Many2one('hr.employee',"Investigator") assessor = fields.Many2one('hr.employee',"Assessor") assess_date = fields.Date('Assessment Completed') substantiated = fields.Boolean('Has the complaint been substantitated?') action_detail = fields.Text('Details') issues = fields.Text('Issues discovered') action_taken = fields.Selection([ ('1', 'Disciplinary Action'), ('2', 'Formal Warning'), ('3', 'Informal Warning'), ('4', 'Record without warning'), ('5', 'Remedial'), ('6', 'No action')], 'Action to be taken', track_visibility='onchange') record_employee = fields.Boolean('Record on employee file', track_visibility='onchange') notes = fields.Text('Notes', track_visibility='onchange') completed_by = fields.Many2one('hr.employee','Completed By') state = fields.Selection([ ('draft', 'New'), ('insufficient', 'Insufficient Evidence'), ('progress', 'Investigation in progress'), ('wait', 'Waiting for external investigation'), ('unsubstantiated','Unsubstantiated'), ('done', 'Done')], 'Status', required=True, readonly=True, track_visibility='onchange', copy=False, default='draft') date_eta = fields.Date('To be completed') date_close = fields.Date('Date closed', select=True) @api.onchange('employee_id','complaint_date') def change_complaint(self): if self.employee_id: self.name = self.employee_id.name else: self.name = '' if self.complaint_date: self.name += ' (' + str(self.complaint_date) + ')' _order = 'complaint_date desc' class HrEmployee(models.Model): _inherit="hr.employee" complaint_count = fields.Integer(compute='_compute_ccount', store=False, string='Complaints') @api.multi def _compute_ccount(self): Complaint = self.env['hr_complaint.complaint'] self.complaint_count = Complaint.search_count([('employee_id','=',self.id)])
Python
0.000002
@@ -1371,21 +1371,8 @@ rue, - select=True, def @@ -4846,21 +4846,8 @@ sed' -, select=True )%0A
0306b2631260c115f99b8a1f73322277e1c50989
Remove fetal anomaly scans from ARPKD
scripts/fixtures/radar_fixtures/cohorts.py
scripts/fixtures/radar_fixtures/cohorts.py
from radar.models.groups import Group, GROUP_TYPE from radar.pages import PAGE from radar_fixtures.utils import add COHORTS = [ { 'code': 'BONEITIS', 'name': 'Bone-itis', 'short_name': 'Bone-itis', 'pages': [ PAGE.PRIMARY_DIAGNOSIS, PAGE.DIAGNOSES, ], }, { 'code': 'CIRCUSITIS', 'name': 'Circusitis', 'short_name': 'Circusitis', 'pages': [ PAGE.PRIMARY_DIAGNOSIS, PAGE.DIAGNOSES, ], }, { 'code': 'ADTKD, 'name': 'Autosomal Dominant Tubulointerstitial Kidney Disease (FUAN)', 'short_name': 'ADTKD (FUAN)', 'pages': [ PAGE.PRIMARY_DIAGNOSIS, PAGE.DIAGNOSES, PAGE.GENETICS, PAGE.FAMILY_HISTORY, PAGE.FUAN_CLINICAL_PICTURES, PAGE.RESULTS, PAGE.DIALYSIS, PAGE.TRANSPLANTS, ] }, { 'code': 'ADPKD', 'name': 'Autosomal Dominant Polycystic Kidney Disease', 'short_name': 'ADPKD', 'pages': [ PAGE.PRIMARY_DIAGNOSIS, PAGE.DIAGNOSES, PAGE.GENETICS, PAGE.FAMILY_HISTORY, PAGE.RENAL_IMAGING, PAGE.LIVER_IMAGING, PAGE.LIVER_DISEASES, PAGE.RESULTS, PAGE.TRANSPLANTS, PAGE.LIVER_TRANSPLANTS, ] }, { 'code': 'ARPKD', 'name': 'Autosomal Recessive Polycystic Kidney Disease', 'short_name': 'ARPKD', 'pages': [ PAGE.PRIMARY_DIAGNOSIS, PAGE.DIAGNOSES, PAGE.GENETICS, PAGE.FAMILY_HISTORY, PAGE.FETAL_ULTRASOUNDS, PAGE.FETAL_ANOMALY_SCANS, PAGE.RENAL_IMAGING, PAGE.LIVER_IMAGING, PAGE.LIVER_DISEASES, PAGE.RESULTS, PAGE.NUTRITION, PAGE.LIVER_TRANSPLANTS, PAGE.NEPHRECTOMIES, ] } ] def create_cohorts(): for x in COHORTS: group = Group() group.type = GROUP_TYPE.COHORT group.code = x['code'] group.name = x['name'] group.short_name = x['short_name'] group.pages = x['pages'] add(group)
Python
0
@@ -1742,46 +1742,8 @@ DS,%0A - PAGE.FETAL_ANOMALY_SCANS,%0A
db8061ebd89b889c08f2710f851d1086dcacffe2
add comment
models/pypi_project.py
models/pypi_project.py
from app import db from sqlalchemy.dialects.postgresql import JSONB from models.github_api import ZipGetter import requests import re import pickle from pathlib import Path from time import time from util import elapsed class PypiProject(db.Model): project_name = db.Column(db.Text, primary_key=True) owner_name = db.Column(db.Text) github_owner = db.Column(db.Text) github_repo_name = db.Column(db.Text) api_raw = db.Column(JSONB) reverse_deps = db.Column(JSONB) deps = db.Column(JSONB) zip_download_elapsed = db.Column(db.Float) zip_download_size = db.Column(db.Integer) zip_download_error = db.Column(db.Text) dependency_lines = db.Column(db.Text) zip_grep_elapsed = db.Column(db.Float) def __repr__(self): return u'<PypiProject {project_name}>'.format( project_name=self.project_name) @property def language(self): return "python" #def set_dependency_lines(self): # getter = github_zip_getter_factory(self.login, self.repo_name) # getter.get_dep_lines(self.language) # # self.dependency_lines = getter.dep_lines # self.zip_download_elapsed = getter.download_elapsed # self.zip_download_size = getter.download_kb # self.zip_download_error = getter.error # self.zip_grep_elapsed = getter.grep_elapsed # # return self.dependency_lines # # #def zip_getter(self): # if not self.api_raw: # return None # if not "url" in self.api_raw: # return None # # url = self.api_raw["url"] # getter = ZipGetter(url) # return getter """ add pypi dependency lines """ def add_pypi_dependency_lines(project_name): project = db.session.query(PypiProject).get(project_name) if project is None: print "there's no pypi project called {}".format(project_name) return False project.set_dependency_lines() db.session.commit() def add_all_pypi_dependency_lines(): q = db.session.query(PypiProject.project_name) q = q.filter(~PypiProject.api_raw.has_key('error_code')) q = q.filter(PypiProject.dependency_lines == None, PypiProject.zip_download_error == None, PypiProject.zip_download_elapsed == None) q = q.order_by(PypiProject.project_name) for row in q.all(): #print "setting this row", row add_pypi_dependency_lines(row[0], row[1]) """ database and file operations. """ class PythonStandardLibs(): url = "https://docs.python.org/2.7/py-modindex.html" data_dir = Path(__file__, "../../data").resolve() pickle_path = Path(data_dir, "python_standard_libs.pickle") @classmethod def save_from_web(cls): # only needs to be used once ever, here for tidiness html = requests.get(cls.url).text exp = r'<tt class="xref">([^<]+)' matches = re.findall(exp, html) libs = [m for m in matches if '.' not in m] with open(str(cls.pickle_path), "w") as f: pickle.dump(libs, f) print "saved these to file: {}".format(libs) @classmethod def get(cls): with open(str(cls.pickle_path), "r") as f: return pickle.load(f) def save_python_standard_libs(): PythonStandardLibs.save_from_web() # to show the thing works print "got these from pickled file: {}".format(PythonStandardLibs.get()) def get_pypi_package_names(): start_time = time() pypi_q = db.session.query(PypiProject.project_name) pypi_lib_names = [r[0] for r in pypi_q.all()] print "got {} PyPi project names in {}sec.".format( len(pypi_lib_names), elapsed(start_time) ) return pypi_lib_names
Python
0
@@ -2734,16 +2734,25 @@ (cls): +%0A # only n @@ -2796,16 +2796,96 @@ idiness%0A + # checked the result into source control as python_standard_libs.pickle%0A
d6371341c13ffe623755cf89ff03733c111bb994
change to rga2
profile_collection/startup/12-rga.py
profile_collection/startup/12-rga.py
from ophyd import Device, Component as Cpt class RGA(Device): startRGA = Cpt(EpicsSignal, 'Cmd:MID_Start-Cmd') stopRGA = Cpt(EpicsSignal, 'Cmd:ScanAbort-Cmd') mass1 = Cpt(EpicsSignalRO, 'P:MID1-I') mass2 = Cpt(EpicsSignalRO, 'P:MID2-I') mass3 = Cpt(EpicsSignalRO, 'P:MID3-I') mass4 = Cpt(EpicsSignalRO, 'P:MID4-I') mass5 = Cpt(EpicsSignalRO, 'P:MID5-I') mass6 = Cpt(EpicsSignalRO, 'P:MID6-I') mass7 = Cpt(EpicsSignalRO, 'P:MID7-I') mass8 = Cpt(EpicsSignalRO, 'P:MID8-I') mass9 = Cpt(EpicsSignalRO, 'P:MID9-I') ## We don't want the RGA to start and stop by any bluseky plan### """ def stage(self): self.startRGA.put(1) def unstage(self): self.stopRGA.put(1) def describe(self): res = super().describe() # This precision should be configured correctly in EPICS. for key in res: res[key]['precision'] = 12 return res """ rga = RGA('XF:28IDA-VA{RGA:1}', name='rga', read_attrs=['mass1', 'mass2', 'mass3', 'mass4','mass5', 'mass6', 'mass7', 'mass8', 'mass9'])
Python
0.998462
@@ -1,8 +1,84 @@ +### This is RGA:2 configured for ExQ new RGA connected at 10.28.2.142 #####%0A from oph @@ -692,16 +692,17 @@ plan###%0A +%0A %22%22%22%0A @@ -1055,17 +1055,17 @@ 28ID -A +C -VA%7BRGA: 1%7D', @@ -1060,17 +1060,17 @@ -VA%7BRGA: -1 +2 %7D',%0A
99c02cfc36660838e5250e62d1c6f390994dda9b
Attach metadata class instance to class attribute.
pyramid_jsonapi/metadata/__init__.py
pyramid_jsonapi/metadata/__init__.py
"""This package contains metadata 'plugin' modules that provide extra information related to the API being generated, such as documentation, schemas etc. Such plugins can optionally be offered as pyramid routes and views under the 'metadata' endpoint.""" import collections import importlib import os.path import pkgutil from pyramid.settings import aslist class MetaData(): """Adds routes and views for all metadata modules. Plugins are added by the module name being added to self.modules This may be overriden in the pyramid inifile config option 'pyramid_jsonapi.metadata_modules' Modules specified in thbis wasy should be space or newline separated (see pyramid.settings aslist()) All modules MUST have a class with the same name as the package. This class MAY contain a 'views' attribute, which contains a list of 'VIEWS' namedtuple instances, which will be converted into pyramid routes and views. """ def __init__(self, api): self.api = api # aslist expects space-separated strings to convert to lists. # iter_modules returns a list of tuples - we only want name ([1]) self.modules = aslist( self.api.config.registry.settings.get( 'pyramid_jsonapi.metadata_modules', ' '.join( [ x[1] for x in pkgutil.iter_modules( [os.path.dirname(__file__)] ) ] ) ), flatten=True ) self.make_routes_views() def make_routes_views(self): """Generate routes and views for plugin modules.""" for mod_name in self.modules: # Import the module from the name provided module = importlib.import_module("{}.{}".format(__name__, mod_name)) # Each module should have a class with the same name class_name = mod_name mclass = getattr(module, class_name)(self.api) views = getattr(mclass, 'views', []) for view in views: rp_constructor = self.api.endpoint_data.rp_constructor route_name = self.api.endpoint_data.make_route_name( class_name, suffix=view.route_name ) route_pattern = rp_constructor.metadata_pattern( class_name, view.route_name ) self.api.config.add_route( route_name, route_pattern ) self.api.config.add_view( mclass, attr=str(view.attr), route_name=route_name, request_method=view.request_method or 'GET', renderer=view.renderer or 'json', ) VIEWS = collections.namedtuple('Views', 'attr request_method route_name renderer')
Python
0
@@ -2023,16 +2023,132 @@ lf.api)%0A + # Attach the instance as an attribute named after the class%0A setattr(self, mod_name, mclass)%0A
ec46226b0ae5e9d2c29aa07f2ec6749f96a36804
add str isValidPalindrome
str/string_function.py
str/string_function.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from __future__ import division from __future__ import unicode_literals from __future__ import print_function def reverseStr(input_str, begin, end): # Pythonic way should be input_str[::-1] str_list = list(input_str) while begin < end: str_list[begin], str_list[end] = str_list[end], str_list[begin] begin += 1 end -= 1 return ''.join(str_list) def reveseWord(input_str): input_str = input_str[::-1] str_list = input_str.split() for i in xrange(len(str_list)): str_list[i] = str_list[i][::-1] return ' '.join(str_list) def atoi(str): # check is None first if not str: return 0 # Second, strip str index = 0 while str[index] == ' ': index += 1 # Third, check sign positive = True if str[index] == '-': positive = False index += 1 if str[index] == '+': index += 1 # loop, get the result result = 0 for i in xrange(index, len(str)): # if not a digit, break, return current result # Question: What about "213k"? # return 0 or 213? if not str[i].isdigit(): break digit = ord(str[i]) - ord('0') result = result * 10 + digit # check overflow if positive: if result > 2147483647: return 2147483647 return result else: if -result < -2147483648: return -2147483648 return -result if __name__ == '__main__': test = "I am a student." result = reveseWord(test) test1 = "World" result = reveseWord(test1) # result = reverseStr(test, 0, len(test) - 1) print(result)
Python
0.999996
@@ -1497,16 +1497,398 @@ result%0A%0A +%0Adef isPalindrome(self, s):%0A start = 0%0A end = len(s) - 1%0A%0A while start %3C end:%0A while not s%5Bstart%5D.isalnum() and start %3C end:%0A start += 1%0A%0A while not s%5Bend%5D.isalnum() and start %3C end:%0A end -= 1%0A%0A if start %3C end and s%5Bstart%5D.lower() != s%5Bend%5D.lower():%0A return False%0A end -= 1%0A start += 1%0A%0A return True%0A%0A%0A if __nam
95a8a85aab19cad08703ec1adbb42ca1437119b0
Fix gprof2dot not found error
pytest-profiling/pytest_profiling.py
pytest-profiling/pytest_profiling.py
from __future__ import absolute_import import sys import os import cProfile import pstats import pipes import errno from hashlib import md5 import six import pytest LARGE_FILENAME_HASH_LEN = 8 def clean_filename(s): forbidden_chars = set('/?<>\:*|"') return six.text_type("".join(c if c not in forbidden_chars and ord(c) < 127 else '_' for c in s)) class Profiling(object): """Profiling plugin for pytest.""" svg = False svg_name = None profs = [] combined = None def __init__(self, svg): self.svg = svg self.profs = [] self.gprof2dot = os.path.abspath(os.path.join(os.path.dirname(sys.executable), 'gprof2dot')) if os.path.isfile(self.gprof2dot): # Can't see gprof in the local bin dir, we'll just have to hope it's on the path somewhere self.gprof2dot = 'gprof2dot' def pytest_sessionstart(self, session): # @UnusedVariable try: os.makedirs("prof") except OSError: pass def pytest_sessionfinish(self, session, exitstatus): # @UnusedVariable if self.profs: combined = pstats.Stats(self.profs[0]) for prof in self.profs[1:]: combined.add(prof) self.combined = os.path.abspath(os.path.join("prof", "combined.prof")) combined.dump_stats(self.combined) if self.svg: self.svg_name = os.path.abspath(os.path.join("prof", "combined.svg")) t = pipes.Template() t.append("{} -f pstats $IN".format(self.gprof2dot), "f-") t.append("dot -Tsvg -o $OUT", "-f") t.copy(self.combined, self.svg_name) def pytest_terminal_summary(self, terminalreporter): if self.combined: terminalreporter.write("Profiling (from {prof}):\n".format(prof=self.combined)) pstats.Stats(self.combined, stream=terminalreporter).strip_dirs().sort_stats('cumulative').print_stats(20) if self.svg_name: terminalreporter.write("SVG profile in {svg}.\n".format(svg=self.svg_name)) @pytest.hookimpl(hookwrapper=True) def pytest_runtest_call(self, item): prof_filename = os.path.abspath(os.path.join("prof", clean_filename(item.name) + ".prof")) try: os.makedirs(os.path.dirname(prof_filename)) except OSError: pass prof = cProfile.Profile() prof.enable() yield prof.disable() try: prof.dump_stats(prof_filename) except EnvironmentError as err: if err.errno != errno.ENAMETOOLONG: raise if len(item.name) < LARGE_FILENAME_HASH_LEN: raise hash_str = md5(item.name.encode('utf-8')).hexdigest()[:LARGE_FILENAME_HASH_LEN] prof_filename = os.path.join("prof", hash_str + ".prof") prof.dump_stats(prof_filename) self.profs.append(prof_filename) def pytest_addoption(parser): """pytest_addoption hook for profiling plugin""" group = parser.getgroup('Profiling') group.addoption("--profile", action="store_true", help="generate profiling information") group.addoption("--profile-svg", action="store_true", help="generate profiling graph (using gprof2dot and dot -Tsvg)") def pytest_configure(config): """pytest_configure hook for profiling plugin""" profile_enable = any(config.getvalue(x) for x in ('profile', 'profile_svg')) if profile_enable: config.pluginmanager.register(Profiling(config.getvalue('profile_svg')))
Python
0.000002
@@ -714,16 +714,20 @@ if +not os.path.
e7bc550f3631d9fc447fa30cc925e271ad72063e
Rename misnamed test
provider/tests/test_provider.py
provider/tests/test_provider.py
import pytest from provider.provider import Provider, Item from provider.exceptions import UnknownArgumentException from . import fixture @pytest.fixture def provider(): return Provider() def test_provider_register_callable(provider): def abc(): pass provider.register(abc, name='fixture') assert provider.has('fixture') def test_provider_register_callable_implied(provider): def abc(): pass provider.register(abc) assert provider.has('abc') @pytest.mark.parametrize('thing', [None, 123, 'abc']) def test_provider_register_uncallable(provider, thing): with pytest.raises(ValueError): provider.register(thing) def test_provider_register_callable_class(provider): class Test(object): def __call__(self): return 1 provider.register(Test()) assert provider.has('Test') assert provider.get('Test') == 1 def test_provider_get(provider): def abc(): return 1 provider.register(abc) result = provider.get('abc') assert result == 1 def test_provider_get_cached(provider): counter = 0 def abc(): nonlocal counter counter += 1 return counter provider.register(abc) for i in range(2): result = provider.get('abc') assert result == 1 def test_provider_get_nonexistent(provider): with pytest.raises(NameError): provider.get('abc') def test_scan(provider): # see fixture.py. from . import fixture provider.scan(fixture) assert provider.has('decorated_fixture') assert provider.get('decorated_fixture') == 1 def test_scan_order_independent(provider): from . import order_fixture provider.scan(order_fixture) assert provider.has('a') assert provider.has('b') assert provider.has('c') assert provider.get('a') == 'a' assert provider.get('c') == 'c' def test_scan_missing_dependency(provider): from .dep_fixture import missing with pytest.raises(UnknownArgumentException): provider.scan(missing) def test_scan_circular_dependency(provider): from .dep_fixture import circular with pytest.raises(UnknownArgumentException): provider.scan(circular) def test_apply_call(provider): def abc(): return 123 def efg(): return 456 def test(abc): assert abc == 123 def with_args(something, abc, efg, another): assert something == 'something' assert another == 'another' assert abc == 123 assert efg == 456 provider.register(abc) provider.register(efg) # Provided function with no other args provider.call(test) # Provided function with other args provider.call(with_args, 'something', another='another') # Caller can always override provides provider.call(with_args, 'something', 123, 456, another='another') provider.call(with_args, 'something', 123, 456, 'another') # Missing positional argument with pytest.raises(UnknownArgumentException): provider.call(with_args, another='another') # Missing keyword argument with pytest.raises(UnknownArgumentException): provider.call(with_args, 'something') def test_apply_call_class(provider): def abc(): return 123 class Something(object): def __call__(self, abc): self.test(abc) def test(self, abc): assert abc == 123 provider.register(abc) provider.call(Something()) provider.call(Something().test) def test_dependency(provider): def one(): return 1 def also_one(one): return one def two(one, also_one): return one + also_one provider.register(one) provider.register(also_one) provider.register(two) assert provider.get('also_one') == 1 assert provider.get('two') == 2 def test_apply_unsatisfied_dependency(provider): def test(abc): pass with pytest.raises(UnknownArgumentException): provider.register(test) def test_item_from_function(): def func(): return 'func' item = Item.create_from(func) assert item.callable == func assert item.callable() == 'func' assert item.name == 'func' assert not item.klass assert not item.deps def test_item_from_function_deps(): def func(a, b, c): pass item = Item.create_from(func) for dep in ['a', 'b', 'c']: assert dep in item.deps def test_item_from_class_instance(): # Not callable with pytest.raises(ValueError): Item.create_from(object()) class Callable(object): def __call__(self, a): return a item = Item.create_from(Callable()) assert item.callable('Callable') == 'Callable' assert item.name == 'Callable' assert item.klass assert len(item.deps) == 1 assert 'a' in item.deps def test_item_from_bound_method(): class Klass(object): def method(self, a): return a item = Item.create_from(Klass().method) assert item.callable('Klass') == 'Klass' assert item.name == 'method' assert item.klass assert len(item.deps) == 1 assert 'a' in item.deps
Python
0.000004
@@ -3870,22 +3870,16 @@ ef test_ -apply_ unsatisf
72171897071bf4b88013b74a13e45231fbc8d7ff
Remove feedback from response serializer.
studies/serializers.py
studies/serializers.py
from accounts.models import Child, DemographicData, Organization, User from api.serializers import (ModelSerializer, UUIDResourceRelatedField, UUIDSerializerMixin) from rest_framework_json_api import serializers from studies.models import Response, Study, Feedback class StudySerializer(UUIDSerializerMixin, ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='study-detail', lookup_field='uuid' ) organization = UUIDResourceRelatedField( queryset=Organization.objects, related_link_view_name='organization-detail', related_link_lookup_field='uuid', many=False ) creator = UUIDResourceRelatedField( queryset=User.objects, related_link_view_name='user-detail', related_link_lookup_field='uuid', many=False ) responses = UUIDResourceRelatedField( queryset=Response.objects, many=True, related_link_view_name='study-responses-list', related_link_url_kwarg='study_uuid', related_link_lookup_field='uuid', ) class Meta: model = Study fields = ( 'url', 'name', 'date_modified', 'short_description', 'long_description', 'criteria', 'duration', 'contact_info', 'image', 'structure', 'display_full_screen', 'exit_url', 'state', 'public', 'organization', 'creator', 'responses', ) class FeedbackSerializer(UUIDSerializerMixin, ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='feedback-detail', lookup_field='uuid' ) response = UUIDResourceRelatedField( queryset=Response.objects, many=False, related_link_view_name='response-detail', related_link_lookup_field='uuid', ) researcher = UUIDResourceRelatedField( queryset=User.objects, many=False, related_link_view_name='user-detail', related_link_lookup_field='uuid', ) class Meta: model = Feedback fields = ( 'url', 'comment', 'researcher', 'response' ) class ResponseSerializer(UUIDSerializerMixin, ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='response-detail', lookup_field='uuid' ) feedback = UUIDResourceRelatedField( queryset=Feedback.objects, many=True, related_link_view_name='response-feedback-list', related_link_url_kwarg='response_uuid', related_link_lookup_field='uuid', ) study = UUIDResourceRelatedField( queryset=Study.objects, many=False, related_link_view_name='study-detail', related_link_lookup_field='uuid', ) user = UUIDResourceRelatedField( source='child.user', queryset=User.objects, many=False, related_link_view_name='user-list', related_link_lookup_field='uuid', required=False ) child = UUIDResourceRelatedField( queryset=Child.objects, many=False, related_link_view_name='child-detail', related_link_lookup_field='uuid', ) demographic_snapshot = UUIDResourceRelatedField( queryset=DemographicData.objects, many=False, related_link_view_name='demographicdata-detail', related_link_lookup_field='uuid', required=False ) class Meta: model = Response fields = ( 'url', 'conditions', 'global_event_timings', 'exp_data', 'sequence', 'completed', 'child', 'user', 'study', 'feedback', 'demographic_snapshot', ) class ResponseWriteableSerializer(ResponseSerializer): def create(self, validated_data): """ Use the ids for objects so django rest framework doesn't try to create new objects out of spite """ study = validated_data.pop('study') validated_data['study_id'] = study.id # implicitly set the demographic data because we know what it will be validated_data['demographic_snapshot_id'] = validated_data.get('child').user.latest_demographics.id child = validated_data.pop('child') validated_data['child_id'] = child.id return super().create(validated_data)
Python
0
@@ -2502,257 +2502,8 @@ )%0A%0A - feedback = UUIDResourceRelatedField(%0A queryset=Feedback.objects,%0A many=True,%0A related_link_view_name='response-feedback-list',%0A related_link_url_kwarg='response_uuid',%0A related_link_lookup_field='uuid',%0A )%0A%0A @@ -3624,32 +3624,8 @@ y',%0A - 'feedback',%0A
c128355193d3f0339e24ee70f685d31dbf5b6bb9
Add stub for search()
sudoku/puzzlesolver.py
sudoku/puzzlesolver.py
""" puzzlesolver.py :created on: 20160624 __author__ = 'Frederic Dupont' :License: GPL3 """ __author__ = 'Fred Dupont' import sys from sudoku import puzzleconstants as p_const from sudoku.puzzle import Puzzle, make_grid_from_string class PuzzleSolver(object): """ class that solves a sudoku puzzle takes the clone of a puzzle and solves it """ def __init__(self, puzzle_clone): self._puzzle = puzzle_clone def eliminate_candidates(self): """For each square in the grid that has a single assigned value, run through the PEERS and eliminate this value from the candidates *** This will have to be redone each time the puzzle is cloned *** :return: False if an inconsistency is discovered --> makes the puzzle invalid True otherwise """ for square in p_const.SQUARES: current_value = self._puzzle.grid[square] if current_value not in '.0': # this says is there is an inconsistency # that means it must return False to signal it if self._puzzle.candidates[square] != p_const.VALUE_TO_CANDIDATES[current_value]: return False for peer in p_const.PEERS[square]: self._puzzle.candidates[peer] = self._puzzle.candidates[peer].replace(current_value, '.') return True def propagate(self): """if a UNIT has only one possible place for a value, assign this value there, and adjust the candidates for this place """ for unit in p_const.UNIT_LISTS: for digit in p_const.DIGITS: result = [] for square in unit: if digit in self._puzzle.candidates[square]: result.append(square) if len(result) == 1: self._puzzle.grid[result[0]] = digit self._puzzle.candidates[result[0]] = p_const.VALUE_TO_CANDIDATES[digit] def fill_singles(self): """ completes a unit that is missing only one value by updating the grid and the candidates values """ for unit in p_const.UNIT_LISTS: result = [] res_string = [str(_) for _ in range(1, 10)] for square in unit: val = self._puzzle.grid[square] if val in '.0': result.append(square) else: res_string[int(val) - 1] = '.' if len(result) == 1: self._puzzle.grid[result[0]] = p_const.CANDIDATES_TO_VALUE[''.join(res_string)] self._puzzle.candidates[result[0]] = ''.join(res_string) def eliminate_propagate_fill(self): """ Propagates the constraints by successively eliminating, propagating and filling the solved squares until all constraints have been propagated. (no more change in the puzzle states) ...or the puzzle is solved :return: False if an inconsistency is discovered, True otherwise """ while not self._puzzle.is_solved(): pre_grid_state, pre_candidates_state = repr(self._puzzle), str(self._puzzle) if not self.eliminate_candidates(): return False self.propagate() self.fill_singles() post_grid_state, post_candidates_state = repr(self._puzzle), str(self._puzzle) if pre_grid_state == post_grid_state and pre_candidates_state == post_candidates_state: break print(repr(self._puzzle)) return True def solve(self): """ manages the operations to conduct in order to solve a puzzla :print: the repr of a solved puzzle (as far as could go with constraint propagation) :return: nothing at the moment """ self.eliminate_propagate_fill() return repr(self._puzzle) # def main(argv): # if __name__ == '__main__': # sys.exit(main(sys.argv))
Python
0
@@ -3630,32 +3630,325 @@ return True%0A%0A + def search(self):%0A %22%22%22%0A clones the puzzle%0A creates a new solver%0A assigns the next candidate value to the empty square with the less candidates%0A recursively calls solve() on the new puzzle%0A :return: a solved puzzle repr()%0A %22%22%22%0A pass%0A%0A def solve(se @@ -4217,16 +4217,17 @@ _fill()%0A +%0A
7874cb87583e32d5597d0c9884e89408997ce9a1
Fix missing self in geomaps
geomaps.py
geomaps.py
""" Cyril Robin -- LAAS-CNRS -- 2014 TODO Descriptif """ import gdal import random import bisect import operator as operator import numpy as np from math import sqrt VERBOSE = False def accumulate(iterable, func=operator.add): 'Return running totals (itertools.accumulate() in Python2)' # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 it = iter(iterable) total = next(it) yield total for element in it: total = func(total, element) yield total class WeightedRandomGenerator(object): 'Class of random generator on 2D numpy array distribution' """ Init the weighted random generator by computing the flat 1D array of cumulative weights. This allows to quickly generate weight random value. """ def __init__(self, weights): self.totals = [] running_total = 0 #for w in weights.reshape(-1): # flattening (1D) #running_total += w #self.totals.append(running_total) # OR # TODO tic toc weights_uint64 = np.uint64(weights) self.totals=list( accumulate(weights_uint64.flat, func=operator.add) ) """ Generate one weighted random item """ def next(self): rnd = random.random() * self.totals[-1] idx = bisect.bisect_right(self.totals, rnd) return idx def __call__(self): return self.next() class Geomap: 'Class storing geofile data' global VERBOSE """ Load a geofile (tiff + xml description) """ def __init__(self, geofile): # get GeoTiff for scale info self.geotiff = gdal.Open(geofile) self.meta = self.geotiff.GetMetadata() if not 'CUSTOM_X_ORIGIN' in self.meta: print('error: %s.aux.xml missing' % self.geofile) exit(1) self.tf = self.geotiff.GetGeoTransform() self.band = self.geotiff.GetRasterBand(1) self.image = self.band.ReadAsArray() # numpy array self.width = self.geotiff.RasterXSize self.height = self.geotiff.RasterYSize self.scale_x = self.tf[1] self.scale_y = self.tf[5] self.utm_x = self.tf[0] self.utm_y = self.tf[3] self.custom_x_origin = float(self.meta['CUSTOM_X_ORIGIN']) self.custom_y_origin = float(self.meta['CUSTOM_Y_ORIGIN']) # TODO it seems this is not necessary #negative = np.vectorize( lambda x : 255 - x ) #self.image = negative( self.image ) if VERBOSE: print "Image is {}x{}".format(self.width,self.height) """ Translate pixel coordinates into utm """ def point_pix2utm(self, x, y): return [ x * self.scale_x + self.utm_x , y * self.scale_y + self.utm_y ] """ Translate pixel coordinates into utm with custom origin """ def point_pix2custom(self, x, y): p = point_pix2utm(x, y) return [p[0] - self.custom_x_origin, p[1] - self.custom_y_origin] """ Transform pixels coordinates into one-liner index """ #def point_pix2idx(x, y): #return y*self.width + x #TODO use flat / ravel instead ? zith coords ? #return image.ravel( """ Transform one-liner index into image pixels coordinates """ def point_idx2pix( self, idx ): return np.unravel_index( idx, (self.height,self.width) ) """ Return the distance beween two 2D points, on the map. Currently use the Euclidian distance. """ def dist( self, (x1,y1), (x2,y2) ): return sqrt( (x1-x2)**2 + (y1-y2)**2 ) """ Sample <n> points in the <geomap>. Consider the geomap has a discrete distribution of probability used for the sampling.""" def sample_points( geomap, n ): points = [] wrg = WeightedRandomGenerator(geomap.image) for i in range(n): idx = wrg() # Beware of the order (height,width) (set empirically...) points.append( np.unravel_index( idx, \ (geomap.height, geomap.width ) ) ) return points """ Return the existing connections between the <points> in the <geomap>. <paths> refers to the positions in self.points and may be seen as a sparse matrix indicating the connections between the accessible points. One may set a limit for the number of connections by points, setting a maximum branching factor. The choice of the connexions are related to their cost, computed through the <f_cost> function.""" def compute_paths( geomap, points, f_cost, branching_factor = 3 ): paths = {} # TODO It currently use the distance, which obviously not reliable (and # costly?) => use a djikstra 1 to all, which stop after the first three (=> # get path !) #The first element of <points> is considered as 'non-return' position for p in points: links = sorted(points, key=lambda x: f_cost(p,x)) paths[p] = links[1:branching_factor+1] return paths
Python
0.009318
@@ -2907,16 +2907,21 @@ p = +self. point_pi @@ -3108,16 +3108,22 @@ pix2idx( +self, x, y):%0A
4c55c5f52ba719702accacef387f23bbb4048734
normalize command dispatch to a single function
git-sap.py
git-sap.py
#!/usr/bin/python import git import gitsap import optparse import os def usage(message, *args): print message % args exit(1) def open_repo(): try: return git.Repo() except git.exc.InvalidGitRepositoryError: usage("Must be inside a git repository") def open_config(repo): config_path = os.path.join(repo.working_tree_dir, '.saplings') if os.path.exists(config_path): with open(config_path, 'r') as config: try: return gitsap.Config(repo, config.read()) except gitsap.ConfigError as e: usage("Problem loading .saplings config: %s" % e) else: return gitsap.Config(repo) def list(repo, split_config, verbose): for split in split_config.splits.values(): if not verbose: print split.name else: paths = ( "%s/" % os.path.relpath(os.path.join(repo.working_tree_dir, path)) for path in split.paths ) print "%s\t%s\t%d\n\t%s" % (split.name, split.remote, len(split.paths), "\n\t".join(paths)) def get_splits(split_config, names): splits = split_config.splits for name in set(names): yield splits[name] def split(splits, verbose): for split in splits: if (verbose): print "Operating on split: %s" % split # parent = None # branch_name = 'sapling_split_%s' % split.name # branch = find(repo.branches, # lambda branch: branch.name is branch_name, # repo.create_head(branch_name)) # # index = git.IndexFile(repo, '/tmp/%s.index' % split.name) # for subtree in split.subtrees(): # print "Adding subtree %s to index %s" % (subtree, index) # index.add(subtree) # synthetic_tree = index.write_tree() # # parent = git.Commit.create_from_tree(repo, synthetic_tree, "git-sap split", # parent_commits = parent, head = True) # branch.commit = parent def main(): repo = open_repo() split_config = open_config(repo) usage = """ %prog (-d) --list %prog (-d) --split [splitname...]""" parser = optparse.OptionParser(usage = usage, version = "%prog 0.1") parser.add_option("-d", "--debug", dest = "debug", action = "store_true", default = False, help = "prints extra debugging information") parser.add_option("-v", "--verbose", dest = "verbose", action = "store_true", default = False, help = "prints extra information") parser.add_option("--list", dest = "subcommand", default = "list", action = "store_const", const = "list", help = """lists the defined splits""") parser.add_option("--split", dest = "subcommand", action = "store_const", const = "split", help = """populates the [splitname] branch with commits intersecting the split""") (options, args) = parser.parse_args() if options.debug: print "repo\t[%s]\t%s" % (repo.active_branch, repo.working_tree_dir) if options.subcommand is "list": if len(args) != 0: parser.error("list takes no arguments") list(repo, split_config, options.verbose) elif options.subcommand is "split": if len(args) == 0: parser.error("At least 1 split must be specified") try: split(get_splits(split_config, args), options.verbose) except KeyError as e: parser.error("split not defined: %s" % e) try: main() exit(0) except object as e: usage(e) # TODO(jsirois): kill this cruft #def find(iterable, predicate, default = None): # for item in iterable: # if (predicate(item)): # return item # if default is None: # raise KeyError # return default #for name, split in splitConfig.splits.items(): # print "Found split: %s" % name # # for i, commit in enumerate(split.commits()): # fileinfos = map(lambda obj: obj.path, # commit.tree.traverse(predicate = lambda obj, depth: isinstance(obj, git.Blob), # visit_once = True)) # # print "[%d] %s %s %s\n%s\t%s" % (i, commit.hexsha, commit.committed_date, commit.committer, # commit.message, "\n\t".join(fileinfos))
Python
0.000018
@@ -986,26 +986,21 @@ ))%0A%0Adef -get_ split -s (split_c @@ -1015,22 +1015,36 @@ ames +, verbose ):%0A +for split -s = + in ( spli @@ -1058,18 +1058,22 @@ g.splits -%0A +%5Bname%5D for nam @@ -1081,20 +1081,16 @@ in -set( names):%0A @@ -1089,83 +1089,8 @@ s):%0A - yield splits%5Bname%5D%0A%0Adef split(splits, verbose):%0A for split in splits:%0A @@ -3246,19 +3246,8 @@ lit( -get_splits( spli @@ -3260,17 +3260,16 @@ ig, args -) , option
df56f113b35b011382930ceea0453e46adc8acb2
Update the cookies dict, do not replace it
eduxator/io.py
eduxator/io.py
import re import os from lxml import etree import requests COOKIE = '~/.edux.cookie' EDUX = 'https://edux.fit.cvut.cz/' COURSES = 'courses/' CLASSIFICATION = '/classification/view/' EDIT = '?do=edit' class EduxIO: '''Class providing the interface for reading and writing Edux classification''' def __init__(self, *, cookie_file=None, cookie_dict=None): if cookie_file and cookie_dict: raise ValueError('cookie_file and cookie_dict cannot be used at teh same time') if cookie_dict is not None: self.cookies = cookie_dict else: cookie_file = cookie_file or COOKIE try: self.cookies = self.cookie_from_file(cookie_file) except Exception as e: raise ValueError('File {} probably does not contain a ' 'cookie in name=value syntax'.format(cookie_file)) from e @classmethod def cookie_from_file(cls, path): with open(os.path.expanduser(path)) as f: lines = f.readlines() cookies = {} for line in lines: parts = line.split('=') cookies[parts[0]] = parts[1].rstrip() return cookies def save_cookie(self, path=COOKIE): with open(os.path.expanduser(path), 'w') as f: for name in self.cookies: f.write(name + '=' + self.cookies[name] + '\n') break def get(self, url): r = requests.get(url, cookies=self.cookies) self.cookies = r.cookies.get_dict() # Hear about return codes, Edux? if ('id="nepovolena_akce"' in r.text or 'id="permission_denied"' in r.text): raise ValueError('Your cookie does not work on requested page, permission denied') if ('id="stranka_s_timto_nazvem_jeste_neexistuje"' in r.text or 'id="this_topic_does_not_exist_yet"' in r.text): raise ValueError('Requested URL does not exist') return r def post(self, url, data): return requests.post(url, data, cookies=self.cookies) def parse_courses_list(self): ''' Returns all available courses from Edux ''' r = requests.get(EDUX) # do not use our get method, simply grab it without cookies return tuple(x[len(COURSES):] for x in set(re.findall(COURSES + r'[^<"]*', r.text)) if not x.endswith('KOD-PREDMETU')) def course_from_url(self, url): ''' Parses the course name form URL This is needed bacuase some sourses, such as BI-3DT.1, only redirects (e.g. to BI-3DT) ''' return url.split('/')[4] # ['https:', '', 'edux.fit.cvut.cz', 'courses', 'HERE'... def parse_classification_tree(self): ''' Parse all classification types for our course If self.course is not set, it blows up Returns a weird dict-based tree where leaves contains empty dicts ''' self.check_attr('course') classification = EDUX + COURSES + self.course + CLASSIFICATION r = self.get(classification + 'start') self.course = self.course_from_url(r.url) # link is HTML are without EDUX address classification = '/' + COURSES + self.course + CLASSIFICATION strings = tuple(x[len(classification):] for x in set(re.findall(classification + r'[^ <"\?#]*', r.text)) if not x.startswith(classification + 'start') and not x.endswith('start') and not x.endswith('void')) tree = {} for string in strings: walk = tree for part in string.split('/'): if part not in walk: walk[part] = {} walk = walk[part] return tree def check_attr(self, attribute): if not hasattr(self, attribute): raise AttributeError(attribute + ' attribute was not provided, cannot continue') def construct_form_url(self, *, edit=False): self.check_attr('course') self.check_attr('classpath') extra = EDIT if edit else '' return EDUX + COURSES + self.course + CLASSIFICATION + '/'.join(self.classpath) + extra def parse_form_edit_score(self): ''' Parse the classification form course and classpath attributes have to be set classpath is supposed to be list of strings Returns a dict of all current values ''' url = self.construct_form_url(edit=True) r = self.get(url) tree = etree.HTML(r.text) scores_form = None for form in tree.findall('.//form'): if form.attrib.get('id') in ['cs_form_edit_score', 'en_form_edit_score']: scores_form = form break if scores_form is None: raise ValueError('Could not find scores form on parsed page') values = {} for inp in form.findall('.//input'): values[inp.attrib.get('name')] = inp.attrib.get('value', '') values.pop(None, None) # Remove bogus value, such as 'nastavit svislý posun' return values def submit_form_edit_score(self, data): url = self.construct_form_url() return self.post(url, data) @classmethod def parse_form_key(cls, key): return tuple(x[:-1] for x in key.split('[')[1:]) @classmethod def all_of_index(cls, data, index): results = set() for key in data.keys(): triplet = cls.parse_form_key(key) if len(triplet) == 3: results.add(triplet[index]) return results @classmethod def all_usernames(cls, data): return cls.all_of_index(data, 0) @classmethod def all_columns(cls, data): return cls.all_of_index(data, 2)
Python
0
@@ -1524,19 +1524,24 @@ .cookies - = +.update( r.cookie @@ -1552,16 +1552,17 @@ t_dict() +) %0A%0A
39bf1b019897b71a3269e46816f11eefa32de507
Fix argument order
elm_package.py
elm_package.py
#! /usr/bin/env python """ Load and save elm-package.json safely. """ # from typing import Dict, Tuple, IO import copy from collections import OrderedDict import json def load(fileobj): # type: (IO[str]) -> Dict return json.load(fileobj, object_pairs_hook=OrderedDict) def dump(package, fileobj): # type: (Dict, IO[str]) -> None to_save = copy.deepcopy(package) to_save['dependencies'] = sorted_deps(to_save['dependencies']) json.dump(to_save, fileobj, sort_keys=False, indent=4, separators=(',', ': ')) def sorted_deps(deps): # type: (Dict) -> Dict return OrderedDict(sorted(deps.items())) def sync_deps(from_deps, to_deps): # type: (Dict, Dict) -> Tuple[List[str], Dict] messages = [] result = copy.deepcopy(to_deps) for (package_name, package_version) in from_deps.items(): if package_name not in to_deps: result[package_name] = package_version messages.append('Inserting new package {package_name} at version {package_version}'.format( package_name=package_name, package_version=package_version) ) elif to_deps[package_name] != package_version: result[package_name] = package_version messages.append('Changing {package_name} from version {package_version} to {other_package_version}'.format( package_version=package_version, package_name=package_name, other_package_version=to_deps[package_name]) ) return messages, result
Python
0.002367
@@ -1280,32 +1280,38 @@ %7D from version %7B +other_ package_version%7D @@ -1315,22 +1315,16 @@ on%7D to %7B -other_ package_
9f5e93ec317f79f6428d25b2ed3980074590b12d
Disable project commands when missing config
elm_project.py
elm_project.py
import sublime import sublime_plugin import json import os.path as fs PROJECT_NOT_FOUND_MSG = 'Valid elm-package.json NOT found for updating' PROJECT_UPDATED_MSG = 'elm-package.json updated : {0} = {1}' class ElmProjectCommand(sublime_plugin.TextCommand): def run(self, edit, prop_name=None, choices=None, caption=None): self.project = ElmProject(self.view.file_name()) if not self.project.exists: return sublime.status_message(PROJECT_NOT_FOUND_MSG) window = self.view.window() if not prop_name: return window.open_file(self.project.json_path, sublime.TRANSIENT) self.prop_name = prop_name initial_value = getattr(self.project, prop_name) if not choices: return window.show_input_panel(caption, initial_value, self.on_finished, None, None) self.choices = choices if int(sublime.version()) < 3000: return window.show_quick_panel(choices, self.on_option) try: initial_index = [choice.lower() for choice in choices].index(initial_value.lower()) except: initial_index = -1 window.show_quick_panel(choices, self.on_option, selected_index=initial_index) def on_finished(self, value): setattr(self.project, self.prop_name, value) sublime.status_message(PROJECT_UPDATED_MSG.format(self.prop_name, value)) def on_option(self, index): if index != -1: self.on_finished(self.choices[index].lower()) BUILD_KEY = ('sublime-build',) MAIN_KEY = BUILD_KEY + ('main',) OUTPUT_KEY = BUILD_KEY + ('output',) OUTPUT_PATH_KEY = OUTPUT_KEY + ('path',) OUTPUT_COMP_KEY = OUTPUT_KEY + ('components',) OUTPUT_DIR_KEY = OUTPUT_COMP_KEY + ('dir',) OUTPUT_NAME_KEY = OUTPUT_COMP_KEY + ('name',) OUTPUT_EXT_KEY = OUTPUT_COMP_KEY + ('ext',) class ElmProject(object): @classmethod def find_json(cls, dir_path): if not fs.isdir(fs.abspath(dir_path)): return None file_path = fs.abspath(fs.join(dir_path, 'elm-package.json')) if fs.isfile(file_path): return file_path parent_path = fs.join(dir_path, fs.pardir) if fs.abspath(parent_path) == fs.abspath(dir_path): return None return cls.find_json(parent_path) def __init__(self, file_path): self.file_path = file_path self.json_path = self.find_json(fs.dirname(file_path)) try: with open(self.json_path) as json_file: self.data_dict = json.load(json_file) except: pass def __getitem__(self, keys): if not self.exists: return None item = self.data_dict for key in keys: item = item.get(key) if not item: break return item def __setitem__(self, keys, value): if not self.exists: return sublime.error_message(PROJECT_NOT_FOUND_MSG) item = self.data_dict for key in keys[0:-1]: item = item.setdefault(key, {}) item[keys[-1]] = value with open(self.json_path, 'w') as json_file: json.dump(self.data_dict, json_file, indent=4, separators=(',', ': '), sort_keys=True) @property def exists(self): return hasattr(self, 'data_dict') @property def working_dir(self): return fs.dirname(self.json_path) @property def main_path(self): return self[MAIN_KEY] or fs.relpath(self.file_path, self.working_dir) @main_path.setter def main_path(self, value): self[MAIN_KEY] = value @property def output_path(self): formatted_path = fs.join(self.output_dir, self.output_name + '.' + self.output_ext) return self[OUTPUT_PATH_KEY] or fs.normpath(formatted_path) @output_path.setter def output_path(self, value): self[OUTPUT_PATH_KEY] = value @property def output_dir(self): return self[OUTPUT_DIR_KEY] or 'build' @output_dir.setter def output_dir(self, value): self[OUTPUT_DIR_KEY] = value @property def output_name(self): return self[OUTPUT_NAME_KEY] or fs.splitext(fs.basename(self.main_path))[0] @output_name.setter def output_name(self, value): self[OUTPUT_NAME_KEY] = value @property def output_ext(self): return self[OUTPUT_EXT_KEY] or 'html' @output_ext.setter def output_ext(self, value): self[OUTPUT_EXT_KEY] = value
Python
0.000002
@@ -325,166 +325,8 @@ e):%0A - self.project = ElmProject(self.view.file_name())%0A if not self.project.exists:%0A return sublime.status_message(PROJECT_NOT_FOUND_MSG)%0A @@ -1060,16 +1060,135 @@ index)%0A%0A + def is_enabled(self):%0A self.project = ElmProject(self.view.file_name())%0A return self.project.exists%0A%0A def
c4670a1b6eb1bbd546369be185cd1fb69dfa3ec0
fix race condition that would drop certain messages on the floor.
emailparser.py
emailparser.py
#!/usr/bin/python import imaplib, time, email.utils, email.parser, calendar import re class EmailParser: def __init__(self, server, username, password, port=None, use_ssl=False, last_check=time.time()): self.server = server if not port: if use_ssl: self.port = 993 else: self.port = 110 else: self.port = port if use_ssl: self.imap = imaplib.IMAP4_SSL(self.server, self.port) else: self.imap = imaplib.IMAP4(self.server, self.port) self.imap.login(username, password) self.last_check = last_check self.set_last_uids() def set_last_uids(self): self.last_uid = {} for folder in self.get_folders(): if "[Gmail]" in folder: continue print "running on %s" % folder selection = self.imap.select(folder, True) # open read-only if selection[0] == "NO": continue if selection[1][0] == '0': self.last_uid[folder] = 0 continue last_msgid = selection[1][0] uid_text = self.imap.fetch(last_msgid, "UID")[1][0] self.last_uid[folder] = int(re.search("\(UID (\d+)\)", uid_text).group(1)) def get_folders(self): # folders are indicated like (\\HasNoChildren) "." "INBOX.Foo"; we just want INBOX.Foo folder_re = re.compile(r'\(.*?\) ".*" (?P<name>.*)') return [folder_re.match(f_str).groups()[0].strip('"') for f_str in self.imap.list()[1]] def check(self): """ Check for messages received since the last check. Return the number of unread messages. """ headers = [] for folder in self.get_folders(): if "[Gmail]" in folder: continue if self.imap.select(folder, True)[0] == "NO": continue # open read-only # XXX: large number is because * will always return the last message throwaway, new = self.imap.search(None, 'UNSEEN', "(UID %d:99999999)" % (self.last_uid[folder] + 1)) if new == ['']: continue # skip all-read folders indices = ','.join(new[0].split(' ')) # for some reason, I get )s mixed in with actual header/response pair information. new_headers = [parse_headers(x[1]) for x in self.imap.fetch(indices, "(BODY[HEADER.FIELDS (FROM SUBJECT)])")[1] if x != ')'] for new_header in new_headers: new_header["folder"] = folder headers += new_headers self.set_last_uids() return headers def parse_headers(header): return {"from": get_field("from", header), "subject" : get_field("subject", header)} def get_field(name, field_string): # TODO: replace this with a real e-mail parser fields = filter(lambda x: x.startswith(name.capitalize() + ":"), field_string.split("\r\n")) if fields == []: return None else: return fields[0].replace(name.capitalize() + ": ", "", 1)
Python
0
@@ -1794,26 +1794,44 @@ -if +response, %5Bnmesgs%5D = self.imap.s @@ -1849,19 +1849,40 @@ r, True) -%5B0%5D +%0A if response == %22NO%22 @@ -2566,25 +2566,73 @@ -%0A +uid_text = self.imap.fetch(nmesgs, %22UID%22)%5B1%5D%5B0%5D%0A self.set @@ -2623,33 +2623,32 @@ + self. -set_ last_uid s()%0A @@ -2631,35 +2631,107 @@ self.last_uid -s() +%5Bfolder%5D = int(re.search(%22%5C(UID (%5Cd+)%5C)%22, uid_text).group(1))%0A %0A return
e33f4bf8aab41a3bcb564e582c64e2d5e1986187
Fix name/username match
modules/sfp_myspace.py
modules/sfp_myspace.py
#------------------------------------------------------------------------------- # Name: sfp_myspace # Purpose: Query MySpace for username and location information. # # Author: Brendan Coles <bcoles@gmail.com> # # Created: 2018-10-07 # Copyright: (c) Brendan Coles 2018 # Licence: GPL #------------------------------------------------------------------------------- import re from sflib import SpiderFoot, SpiderFootPlugin, SpiderFootEvent class sfp_myspace(SpiderFootPlugin): """MySpace:Footprint,Investigate,Passive:Social Media::Gather username and location from MySpace.com profiles.""" # Default options opts = { } # Option descriptions optdescs = { } def setup(self, sfc, userOpts=dict()): self.sf = sfc self.__dataSource__ = "MySpace.com" self.results = list() for opt in userOpts.keys(): self.opts[opt] = userOpts[opt] # What events is this module interested in for input def watchedEvents(self): return [ "EMAILADDR", "SOCIAL_MEDIA" ] # What events this module produces def producedEvents(self): return [ "SOCIAL_MEDIA", "GEOINFO" ] # Handle events sent to this module def handleEvent(self, event): eventName = event.eventType srcModuleName = event.module eventData = event.data if eventData in self.results: return None else: self.results.append(eventData) self.sf.debug("Received event, " + eventName + ", from " + srcModuleName) # Search by email address if eventName == "EMAILADDR": email = eventData res = self.sf.fetchUrl("https://myspace.com/search/people?q=" + email, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent']) if res['content'] is None: return None # The first result is the closest match, but whether it's an exact match is unknown. # As such, we check for email address as name, at the risk of missed results. profiles = re.findall(r'<a href="/([a-zA-Z0-9_]+)">' + email.lower() + '</a></h6>', res['content'].lower()) if not profiles: return None name = profiles[0] e = SpiderFootEvent("SOCIAL_MEDIA", "MySpace: " + name, self.__name__, event) self.notifyListeners(e) # Retrieve location from MySpace profile if eventName == "SOCIAL_MEDIA": network = eventData.split(": ")[0] name = eventData.split(": ")[1] if network != "MySpace": self.sf.debug("Skipping social network profile, " + name + ", as not a MySpace profile") return None res = self.sf.fetchUrl("https://myspace.com/" + name, timeout=self.opts['_fetchtimeout'], useragent=self.opts['_useragent']) if res['content'] is None: return None data = re.findall(r'<div class="location_[^"]+" data-display-text="(.+?)"', res['content']) if not data: return None location = data[0] if len(location) < 5 or len(location) > 100: self.sf.debug("Skipping likely invalid location.") return None e = SpiderFootEvent("GEOINFO", location, self.__name__, event) self.notifyListeners(e) # End of sfp_myspace class
Python
0.033851
@@ -1879,32 +1879,249 @@ return None%0A%0A + # Extract HTML containing potential profile matches%0A profiles = re.findall(r'%3Ca href=%22/%5Ba-zA-Z0-9_%5D+%22%3E%5B%5E%3C%5D+%3C/a%3E%3C/h6%3E', res%5B'content'%5D)%0A%0A if not profiles:%0A return None%0A%0A # Th @@ -2217,23 +2217,46 @@ -# As such, we c +profile = profiles%5B0%5D%0A%0A # C heck @@ -2318,38 +2318,37 @@ ts.%0A -profil +match es = re.findall( @@ -2389,54 +2389,32 @@ mail -.lower() + '%3C/a%3E%3C/h6%3E', res%5B'content'%5D.lower() +, profile, re.IGNORECASE )%0A%0A @@ -2423,38 +2423,37 @@ if not -profil +match es:%0A @@ -2484,30 +2484,29 @@ name = -profil +match es%5B0%5D%0A%0A
552a9e958443ffdff4b28e6e432c09e7d011df6a
Update tesselate_shapes_frame docstring
svg_model/tesselate.py
svg_model/tesselate.py
# coding: utf-8 import types import pandas as pd from .seidel import Triangulator def tesselate_shapes_frame(df_shapes, shape_i_columns): ''' Tesselate each shape path into one or more triangles. Return `pandas.DataFrame` with columns storing the following fields for each row (where each row corresponds to a triangle vertex): - `shape_i_columns`: The shape path index column(s). - `triangle_i`: The integer triangle index within each electrode path. - `vertex_i`: The integer vertex index within each triangle. ''' frames = [] if isinstance(shape_i_columns, types.StringType): shape_i_columns = [shape_i_columns] for shape_i, df_path in df_shapes.groupby(shape_i_columns): points_i = df_path[['x', 'y']].values if (points_i[0] == points_i[-1]).all(): # XXX End point is the same as the start point (do not include it). points_i = points_i[:-1] triangulator = Triangulator(points_i) if not isinstance(shape_i, (types.ListType, types.TupleType)): shape_i = [shape_i] for i, triangle_i in enumerate(triangulator.triangles()): triangle_points_i = [shape_i + [i] + [j, x, y] for j, (x, y) in enumerate(triangle_i)] frames.extend(triangle_points_i) frames = None if not frames else frames return pd.DataFrame(frames, columns=shape_i_columns + ['triangle_i', 'vertex_i', 'x', 'y'])
Python
0
@@ -209,94 +209,468 @@ -Return %60pandas.DataFrame%60 with columns storing the following fields%0A for each row ( +Parameters%0A ----------%0A df_shapes : pandas.DataFrame%0A Table containing vertices of shapes, one row per vertex, with the *at%0A least* the following columns:%0A - %60%60x%60%60: The x-coordinate of the vertex.%0A - %60%60y%60%60: The y-coordinate of the vertex.%0A shape_i_columns : str or list%0A Column(s) forming key to differentiate rows/vertices for each distinct%0A shape.%0A%0A Returns%0A -------%0A pandas.DataFrame%0A%0A Table wher @@ -712,17 +712,48 @@ e vertex -) +, with the following%0A columns :%0A%0A @@ -754,16 +754,17 @@ %0A - +%60 %60shape_i @@ -771,16 +771,19 @@ _columns +%5B%5D%60 %60: The s @@ -816,16 +816,17 @@ %0A - +%60 %60triangl @@ -829,16 +829,17 @@ angle_i%60 +%60 : The in @@ -894,16 +894,17 @@ %0A - +%60 %60vertex_ @@ -905,16 +905,17 @@ ertex_i%60 +%60 : The in
9a744080454cd2577af0935ca9e8b5efccabeb8c
Fix typo hexify -> hexlify
stratatools/helper/rpi_daemon.py
stratatools/helper/rpi_daemon.py
#!/usr/bin/env python2 import argparse import binascii import pyudev import sys import time import traceback from stratatools import * from stratatools import machine,cartridge,manager,crypto,checksum,cartridge_pb2 from google.protobuf.text_format import MessageToString, Merge cartridge_manager = None machine_number = None cartridge_template = None def read_bytes(path): data = None with open(path, "r") as f: data = bytearray(f.read()) return data def write_bytes(path, data): with open(path, "w", buffering=0) as f: f.write(data) def on_new_cartridge(device): eeprom_path = "/sys/" + device.device_path + "/eeprom" eeprom_uid = read_bytes("/sys/" + device.device_path + "/id") print("New device detected <" + binascii.hexify(eeprom_uid) + ">.") try: c = cartridge_template if c is None: c = cartridge_manager.decode(machine_number, eeprom_uid, read_bytes(eeprom_path)) print("Device is a valid cartridge.") c = cartridge.refill(c) write_bytes(eeprom_path, cartridge_manager.encode(machine_number, eeprom_uid, c)) print("Refill complete!") print("You can safely disconnect the cartridge.") except Exception as e: print("Error! verify machine type?") print("Details:") traceback.print_exc() def read_cartridge_template(path): catridge = None with open(path, "r") as f: cartridge = cartridge_pb2.Cartridge() Merge(f.read(), cartridge) return cartridge def main(): global cartridge_manager global machine_number global cartridge_template parser = argparse.ArgumentParser(description="Raspberry Pi Flasher Daemon") parser.add_argument("-t", "--template", action="store", type=str, dest="template", help="Path to cartridge configuration") parser.add_argument("machine_type", action="store", choices=machine.get_machine_types()) args = parser.parse_args() cartridge_manager = manager.Manager(crypto.Desx_Crypto(), checksum.Crc16_Checksum()) machine_number = machine.get_number_from_type(args.machine_type) cartridge_template = None if args.template: cartridge_template = read_cartridge_template(args.template) print("Fill cartridge using template from <" + args.template + ">.") context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by('w1') observer = pyudev.MonitorObserver(monitor, callback=on_new_cartridge) observer.start() try: print("Listening to new device ... ^c to quit") while True: time.sleep(0.1) except KeyboardInterrupt: pass observer.stop() if __name__ == "__main__": main()
Python
0.000336
@@ -769,16 +769,17 @@ scii.hex +l ify(eepr
dfee7e1c89df879f187921752485153fd6214445
Fix typo
IPython/extensions/cythonmagic.py
IPython/extensions/cythonmagic.py
# -*- coding: utf-8 -*- """ The cython magic has been integrated into Cython itself, which is now released in version 0.21. cf github `Cython` organisation, `Cython` repo, under the file `Cython/Build/IpythonMagic.py` """ #----------------------------------------------------------------------------- # Copyright (C) 2010-2011, IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- from __future__ import print_function import IPython.utils.version as version try: import Cython except: Cython = None try: from Cython.Build.IpythonMagic import CythonMagics except : pass ## still load the magic in IPython 3.x, remove completely in future versions. def load_ipython_extension(ip): """Load the extension in IPython.""" print("""The Cython magic has been move to the Cython package, hence """) print("""`%load_ext cythonmagic` is deprecated; Please use `%load_ext Cython` instead.""") if Cython is None or not version.check_version(Cython.__version__, "0.21"): print("You need Cython version >=0.21 to use the Cython magic") return print("""\nThough, because I am nice, I'll still try to load it for you this time.""") Cython.load_ipython_extension(ip)
Python
0.000073
@@ -981,16 +981,17 @@ een move +d to the @@ -1069,17 +1069,17 @@ ecated; -P +p lease us
9f56f877705bdc0171c3afddadc6d58fb867cefc
Fix PEP 8 issue.
test/units/modules/system/test_systemd.py
test/units/modules/system/test_systemd.py
import os import tempfile from ansible.compat.tests import unittest from ansible.modules.system.systemd import parse_systemctl_show class ParseSystemctlShowTestCase(unittest.TestCase): def test_simple(self): lines = [ 'Type=simple', 'Restart=no', 'Requires=system.slice sysinit.target', 'Description=Blah blah blah', ] parsed = parse_systemctl_show(lines) self.assertEqual(parsed, { 'Type': 'simple', 'Restart': 'no', 'Requires': 'system.slice sysinit.target', 'Description': 'Blah blah blah', }) def test_multiline_exec(self): # This was taken from a real service that specified "ExecStart=/bin/echo foo\nbar" lines = [ 'Type=simple', 'ExecStart={ path=/bin/echo ; argv[]=/bin/echo foo', 'bar ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }', 'Description=blah', ] parsed = parse_systemctl_show(lines) self.assertEqual(parsed, { 'Type': 'simple', 'ExecStart': '{ path=/bin/echo ; argv[]=/bin/echo foo\nbar ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }', 'Description': 'blah', }) def test_single_line_with_brace(self): lines = [ 'Type=simple', 'Description={ this is confusing', 'Restart=no', ] parsed = parse_systemctl_show(lines) self.assertEqual(parsed, { 'Type': 'simple', 'Description': '{ this is confusing', 'Restart': 'no', })
Python
0
@@ -1202,16 +1202,44 @@ ho foo%5Cn +'%0A ' bar ; ig
40f1374cab0f8188036993875ce82512828f177d
allow 0 offset
testbeam_analysis/tools/data_selection.py
testbeam_analysis/tools/data_selection.py
''' Helper functions to select and combine data ''' import numpy as np import tables as tb import numexpr as ne import re import logging import progressbar from numba import njit from testbeam_analysis.tools import analysis_utils # Hit data dtype hit_dcr = np.dtype([('event_number', np.int64), ('frame', np.uint8), ('column', np.uint16), ('row', np.uint16), ('charge', np.uint16)]) def combine_hit_files(hit_files, combined_file, event_number_offsets=None, chunk_size=10000000): ''' Combine hit files of runs with same parameters to increase statistics. Parameters ---------- hit_files : iterable Filenames of files containing the hit array. combined_file : string Filename of the output file containing the combined hit array. event_number_offsets : iterable Manually set start event number offset for each hit array. The event number is increased by the given number. If None, the event number will be generated automatically. chunk_size : int Chunk size of the data when reading from file. ''' used_event_number_offsets = [] with tb.open_file(combined_file, mode="w") as out_file: hits_out = out_file.create_table(out_file.root, name='Hits', description=hit_dcr, title='Selected FE-I4 hits', filters=tb.Filters(complib='blosc', complevel=5, fletcher32=False)) for index, hit_file in enumerate(hit_files): if event_number_offsets and event_number_offsets[index]: event_number_offset = event_number_offsets[index] elif index == 0: event_number_offset = 0 # by default no offset for the first file else: event_number_offset += last_event_number + 1 # increase by 1 to avoid duplicate numbers with tb.open_file(hit_file, mode='r') as in_file_h5: for hits, _ in analysis_utils.data_aligned_at_events( in_file_h5.root.Hits, chunk_size=chunk_size): hits[:]['event_number'] += event_number_offset hits_out.append(hits) last_event_number = hits[-1]['event_number'] used_event_number_offsets.append(event_number_offset) return used_event_number_offsets @njit() def _delete_events(data, fraction): result = np.zeros_like(data) index_result = 0 for index in range(data.shape[0]): if data[index]['event_number'] % fraction == 0: result[index_result] = data[index] index_result += 1 return result[:index_result] def reduce_hit_files(hit_files, fraction=10, chunk_size=10000000): ''' Delete a fraction of events to allow faster testing of analysis functions. Parameters ---------- hit_files : iterable Filenames of files containing the hit array. fraction : uint The fraction of leftover events, e.g.: 10 would correspond to n_events = total_events / fraction. chunk_size : int Chunk size of the data when reading from file. ''' for hit_file in hit_files: with tb.open_file(hit_file, mode='r') as in_file: with tb.open_file(hit_file[:-3] + '_reduced.h5', mode="w") as out_file: filters = tb.Filters(complib='blosc', complevel=5, fletcher32=False) hits_out = out_file.create_table(out_file.root, name='Hits', description=hit_dcr, title='Selected FE-I4 hits', filters=filters) for hits, _ in analysis_utils.data_aligned_at_events( in_file.root.Hits, chunk_size=chunk_size): hits_out.append(_delete_events(hits, fraction)) def select_hits(hit_file, max_hits=None, condition=None, track_quality=None, track_quality_mask=None, output_file=None, chunk_size=10000000): ''' Function to select a fraction of hits fulfilling a given condition. Needed for analysis speed up, when very large runs are used. Parameters ---------- hit_file : string Filename of the input hits file. max_hits : uint Number of maximum hits with selection. For data reduction. condition : string A condition that is applied to the hits in numexpr. Only if the expression evaluates to True the hit is taken. E.g.: condition = 'track_quality == 2 & event_number < 1000' chunk_size : int Chunk size of the data when reading from file. ''' with tb.open_file(hit_file, mode='r') as in_file: if not output_file: output_file = hit_file[:-3] + '_reduced.h5' with tb.open_file(output_file, mode="w") as out_file: for node in in_file.root: total_hits = node.shape[0] widgets = ['', progressbar.Percentage(), ' ', progressbar.Bar(marker='*', left='|', right='|'), ' ', progressbar.AdaptiveETA()] progress_bar = progressbar.ProgressBar(widgets=widgets, maxval=total_hits, term_width=80) progress_bar.start() hits_out = out_file.create_table(out_file.root, name=node.name, description=node.dtype, title=node.title, filters=tb.Filters( complib='blosc', complevel=5, fletcher32=False)) for hits, i in analysis_utils.data_aligned_at_events(node, chunk_size=chunk_size): n_hits = hits.shape[0] if condition: hits = _select_hits_with_condition(hits, condition) if track_quality: # If no mask is defined select all quality bits if not track_quality_mask: track_quality_mask = int(0xFFFFFFFF) sel = (hits['track_quality'] & track_quality_mask) == (track_quality) hits = hits[sel] if hits.shape[0] == 0: logging.warning('No hits selected') # Reduce the number of added hits of this chunk to not # exeed max_hits if max_hits: # Calculate number of hits to add for this chunk # Fraction of hits to add per chunk hit_fraction = max_hits / float(total_hits) sel = np.ceil(np.linspace(0, hits.shape[0], int(hit_fraction * n_hits), endpoint=False)).astype( np.int) sel = sel[sel < hits.shape[0]] hits = hits[sel] hits_out.append(hits) progress_bar.update(i) progress_bar.finish() def _select_hits_with_condition(hits_array, condition): for variable in set(re.findall(r'[a-zA-Z_]+', condition)): exec(variable + ' = hits_array[\'' + variable + '\']') return hits_array[ne.evaluate(condition)]
Python
0.000393
@@ -1782,16 +1782,28 @@ s%5Bindex%5D + is not None :%0A
2150ced1552c0d8cfcb537962fb19159b0480767
improve plugin error messages
imgfac/PluginManager.py
imgfac/PluginManager.py
# encoding: utf-8 # Copyright 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import sys import os import json from Singleton import Singleton from ImageFactoryException import ImageFactoryException PLUGIN_TYPES = ('OS', 'CLOUD') INFO_FILE_EXTENSION = '.info' PKG_STR = 'imagefactory_plugins' class PluginManager(Singleton): """ Registers and manages ImageFactory plugins. """ @property def plugins(self): """ The property plugins """ return self._plugins def _singleton_init(self, plugin_path): self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__)) sys.path.append(plugin_path) if os.path.exists(plugin_path): self.path = plugin_path else: msg = 'Plugin path (%s) does not exist! No plugins loaded.' % plugin_path self.log.exception(msg) raise Exception(msg) self._plugins = dict() self._targets = dict() self._types = dict().fromkeys(PLUGIN_TYPES, list()) def load(self): """ Enumerates through installed plugins and registers each according to the features provided. Only one plugin may be registered per feature. When more than one plugin is found, the first will be registered and all others listed as inactive. """ info_files = list() directory_listing = os.listdir(self.path) for _file in directory_listing: if _file.endswith(INFO_FILE_EXTENSION): info_files.append(_file) for filename in info_files: plugin_name = filename[:-len(INFO_FILE_EXTENSION)] md = self.metadata_for_plugin(plugin_name) try: if md['type'].upper() in PLUGIN_TYPES: for target in md['targets']: target = target if isinstance(target, str) else tuple(target) if not target in self._targets: self._targets[target] = plugin_name else: msg = 'Did not register %s for %s. Plugin %s already registered.' % (plugin_name, target, self._targets[target]) self._register_plugin_with_error(plugin_name, msg) self.log.warn(msg) self._plugins[plugin_name] = md self._types[md['type'].upper()].append(plugin_name) self.log.info('Plugin (%s) loaded...' % plugin_name) except KeyError as e: msg = 'Invalid metadata for plugin (%s). Missing entry for %s.' % (plugin_name, e) self._register_plugin_with_error(plugin_name, msg) self.log.exception(msg) except Exception as e: msg = 'Loading plugin (%s) failed with exception: %s' % (plugin_name, e) self._register_plugin_with_error(plugin_name, msg) self.log.exception(msg) def _register_plugin_with_error(self, plugin_name, error_msg): self._plugins[plugin_name] = dict(ERROR=error_msg) def metadata_for_plugin(self, plugin): """ Returns the metadata dictionary for the plugin. @param plugin name of the plugin or the plugin's info file @return dictionary containing the plugin's metadata """ if plugin in self._plugins: return self._plugins[plugin] else: fp = None metadata = None info_file = plugin + INFO_FILE_EXTENSION try: fp = open(os.path.join(self.path, info_file), 'r') metadata = json.load(fp) except Exception as e: self.log.exception('Exception caught while loading plugin metadata: %s' % e) raise e finally: if fp: fp.close() return metadata def plugin_for_target(self, target): """ Looks up the plugin for a given target and returns an instance of the delegate class or None if no plugin is registered for the given target. Matches are done from left to right, ie. ('Fedora', '16', 'x86_64') will match a plugin with a target of ('Fedora', None, None) but not ('Fedora', None, 'x86_64') @param target A list or string matching the target field of the plugin's .info file. @return An instance of the delegate class of the plugin or None. """ try: if isinstance(target, str): self.log.debug("Attempting to match string target (%s)" % target) plugin_name = self._targets.get(tuple([target])) plugin = __import__('%s.%s' % (PKG_STR, plugin_name), fromlist=['delegate_class']) return plugin.delegate_class() elif isinstance(target, tuple): _target = list(target) self.log.debug("Attempting to match list target (%s)" % (str(_target))) for index in range(1, len(target) + 1): plugin_name = self._targets.get(tuple(_target)) if not plugin_name: _target[-index] = None else: plugin = __import__('%s.%s' % (PKG_STR, plugin_name), fromlist=['delegate_class']) return plugin.delegate_class() except ImportError: raise ImageFactoryException("Unable to find plugin for target: %s" % str(target))
Python
0.000008
@@ -5512,16 +5512,157 @@ rget%5D))%0A + if not plugin_name:%0A raise ImageFactoryException(%22No plugin .info file loaded for target: %25s%22 %25 (target))%0A @@ -6395,18 +6395,57 @@ ortError + as e :%0A + self.log.exception(e)%0A @@ -6491,12 +6491,14 @@ to -find +import plu @@ -6523,16 +6523,18 @@ %22 %25 str(target)) +%0A%0A
9bdb3a5e6e2f241a39269d992f1ca5c9f37440ae
add wlm source
importer/SeFornminSv.py
importer/SeFornminSv.py
from Monument import Monument import importer_utils as utils from os import path MAPPING_DIR = "mappings" class SeFornminSv(Monument): def update_labels(self): if len(self.namn) == 0: self.add_label("sv", self.raa_nr) else: self.add_label("sv", self.namn) def set_descriptions(self): """ """ DESC_BASE = "fornminne" description = "" if len(self.typ) > 0: description = self.typ.lower() else: description = DESC_BASE description += " i " + self.landskap self.add_description("sv", description) def set_raa(self): """ With registrant_url as source, to test source uploading mechanism """ self.add_statement("raa-nr", self.raa_nr, refs=[self.registrant_url]) def set_adm_location(self): municip_dict = utils.load_json(path.join( MAPPING_DIR, "sweden_municipalities.json")) if self.kommun == "Göteborg": municip_name = "Gothenburg" else: municip_name = self.kommun pattern = municip_name.lower() + " municipality" try: municipality = [x["item"] for x in municip_dict if x[ "en"].lower() == pattern][0] self.add_statement("located_adm", municipality) except IndexError: print("Could not parse municipality: {}.".format(self.kommun)) return def set_type(self): """ Replace the original P31 rather than adding to it. """ if self.has_non_empty_attribute("typ"): table = self.data_files["types"]["mappings"] type_to_search_for = self.typ.lower() try: special_type = [table[x]["items"] for x in table if x.lower() == type_to_search_for][0][0] self.substitute_statement("is", special_type) except IndexError: return def get_socken(self, socken_name, landskap_name): return utils.socken_to_q(socken_name, landskap_name) def set_location(self): if self.has_non_empty_attribute("plats"): if "[[" in self.plats: wikilinks = utils.get_wikilinks(self.plats) if len(wikilinks) == 1: target_page = wikilinks[0].title wd_item = utils.q_from_wikipedia("sv", target_page) self.add_statement("location", wd_item) if self.has_non_empty_attribute("socken"): self.add_statement("location", self.get_socken( self.socken, self.landskap)) def set_inception(self): # TODO # This is messy and not super prioritized... return def __init__(self, db_row_dict, mapping, data_files, existing): Monument.__init__(self, db_row_dict, mapping, data_files, existing) self.set_image("bild") self.update_labels() self.set_descriptions() self.set_raa() self.set_adm_location() self.set_type() self.set_location() self.set_inception() # self.exists("sv", "artikel") self.set_coords(("lat", "lon")) self.set_commonscat() # self.exists_with_prop(mapping)
Python
0
@@ -742,32 +742,62 @@ ism%0A %22%22%22%0A + ref = self.wlm_source%0A self.add @@ -840,27 +840,11 @@ fs=%5B -self.registrant_url +ref %5D)%0A%0A @@ -1289,24 +1289,58 @@ pattern%5D%5B0%5D%0A + ref = self.wlm_source%0A @@ -1385,16 +1385,28 @@ cipality +, refs=%5Bref%5D )%0A @@ -2542,16 +2542,58 @@ t_page)%0A + ref = self.wlm_source%0A @@ -2642,16 +2642,28 @@ wd_item +, refs=%5Bref%5D )%0A @@ -2703,24 +2703,58 @@ (%22socken%22):%0A + ref = self.wlm_source%0A @@ -2844,16 +2844,28 @@ andskap) +, refs=%5Bref%5D )%0A%0A d @@ -2964,32 +2964,109 @@ return%0A%0A + def set_monuments_all_id(self):%0A self.monuments_all_id = self.id%0A%0A def __init__ @@ -3193,16 +3193,288 @@ isting)%0A + self.set_monuments_all_id()%0A self.set_changed()%0A self.wlm_source = self.create_wlm_source(self.monuments_all_id)%0A self.set_country()%0A self.set_is()%0A self.set_heritage()%0A self.set_source()%0A self.set_registrant_url()%0A
a5c34443353cc9dcfed4b567a240eb22c02d6496
Use correct add method
core/src/main/scripts/cbioportalImporter.py
core/src/main/scripts/cbioportalImporter.py
#! /usr/bin/env python # ------------------------------------------------------------------------------ # Script which imports portal data. # # ------------------------------------------------------------------------------ import os import sys import getopt from cbioportal_common import * # ------------------------------------------------------------------------------ # globals # commands IMPORT_CANCER_TYPE = "import-cancer-type" IMPORT_STUDY = "import-study" REMOVE_STUDY = "remove-study" IMPORT_STUDY_DATA = "import-study-data" IMPORT_CASE_LIST = "import-case-list" COMMANDS = [IMPORT_STUDY, REMOVE_STUDY] # ------------------------------------------------------------------------------ # sub-routines def import_cancer_type(jvm_args, meta_filename): args = jvm_args.split(' ') args.append(IMPORT_CANCER_TYPE_CLASS); args.append(meta_filename) args.append("false") # don't clobber existing table run_java(*args) def import_study(jvm_args, meta_filename): args = jvm_args.split(' ') args.append(IMPORT_STUDY_CLASS); args.append(meta_filename) run_java(*args) def remove_study(jvm_args, meta_filename): args = jvm_args.split(' ') args.append(REMOVE_STUDY_CLASS); metastudy_properties = get_metastudy_properties(meta_filename) args.append(metastudy_properties.cancer_study_identifier) run_java(*args) def import_study_data(jvm_args, meta_filename, data_filename): args = jvm_args.split(' ') metafile_properties = get_metafile_properties(meta_filename) importer = IMPORTER_CLASSNAME_BY_ALTERATION_TYPE[metafile_properties.genetic_alteration_type] args.append(importer) if IMPORTER_REQUIRES_METADATA[importer]: args.append("--meta") args.append(meta_filename) args.append("--loadMode") args.append("bulkload") if metafile_properties.genetic_alteration_type == 'CLINICAL': args.append(data_filename) args.append(metafile_properties.cancer_study_identifier) else: args.append("--data") args.append(data_filename) run_java(*args) def import_case_list(jvm_args, meta_filename): args = jvm_args.split(' ') args.append(IMPORT_CASE_LIST_CLASS); args.append(meta_filename) run_java(*args) def create_cancer_type_file(study_meta, study_directory): cancer_type_file = open(study_directory + '/' + 'cancer_type.txt','w') cancer_type_file.write(study_meta.get('type_of_cancer') + '\t' + study_meta.get('type_of_cancer') + '\t' + study_meta.get('type_of_cancer') + '\t' + study_meta.get('dedicated_color') + '\t' + study_meta.get('type_of_cancer')) cancer_type_file.close() def process_case_lists(jvm_args,study_files): case_list_files = [] # see if there are any case lists first for f in study_files: if 'case_lists' in f: if os.path.isdir(f): case_list_files = [f + '/' + x for x in os.listdir(f)] for case_list in case_list_files: import_case_list(jvm_args,case_list) def process(jvm_args, study_directory, command): study_files = [study_directory + '/' + x for x in os.listdir(study_directory)] meta_filename = '' study_meta = {} for f in study_files: if 'meta' in f: metadata = get_properties(f); if 'meta_study' in metadata.values(): study_meta = metadata meta_filename = f if len(study_meta) == 0: print >> ERROR_FILE, 'No meta_study file found' sys.exit(1) if command == REMOVE_STUDY: remove_study(jvm_args, meta_filename) return create_cancer_type_file(study_meta, study_directory) # First, import cancer type import_cancer_type(jvm_args,study_directory + '/' + 'cancer_type.txt') non_clinical_metafiles = [] files_found = [] # Next, we need to import clinical files for f in study_files: if 'meta' in f: metadata = get_properties(f) if metadata.get('meta_file_type') == 'meta_clinical': import_study_data(jvm_args, f, metadata.get('data_file_path')) else: non_clinical_metafiles.add(f) # Now, import everything else for f in non_clinical_metafiles: meta_file = open(f, 'r') metadata = get_properties(f) files_found.append import_study_data(jvm_args, f, metadata.get('data_file_path')) # do the case lists process_case_lists(jvm_args,study_files) def usage(): print >> OUTPUT_FILE, ('cbioportalImporter.py --jvm-args (args to jvm) ' + '--command [%s] --study-directory <path to directory> ' % (COMMANDS)) def check_args(command, jvm_args, study_directory): if (jvm_args == '' or command not in COMMANDS or study_directory == ''): usage() sys.exit(2) def check_files(study_directory): # check existence of directory if not os.path.exists(study_directory): print >> ERROR_FILE, 'Study cannot be found: ' + study_directory sys.exit(2) def main(): # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['command=', 'jvm-args=','study-directory=']) except getopt.error, msg: print >> ERROR_FILE, msg usage() sys.exit(2) # process the options jvm_args = '' study_directory = '' command = '' for o, a in opts: if o == '--jvm-args': jvm_args = a elif o == '--study-directory': study_directory = a elif o == '--command': command = a check_args(command, jvm_args, study_directory) check_files(study_directory) process(jvm_args, study_directory, command) # ------------------------------------------------------------------------------ # ready to roll if __name__ == '__main__': main()
Python
0.000065
@@ -4131,17 +4131,20 @@ afiles.a -d +ppen d(f)%0A%0A
ce1e52336fa298d52aac264d8ccd3887fc8e18e4
Bump binaryen to version 81.
src/funfuzz/js/with_binaryen.py
src/funfuzz/js/with_binaryen.py
# coding=utf-8 # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. """Run seeds with binaryen to get a wasm file, then run the shell with the translated wasm binary using a js file wrapper """ import io from pathlib import Path import platform import subprocess import tarfile import threading from time import sleep import fasteners import requests from ..util import sm_compile_helpers BINARYEN_VERSION = 72 BINARYEN_URL = (f"https://github.com/WebAssembly/binaryen/releases/download/version_{BINARYEN_VERSION}/" f"binaryen-version_{BINARYEN_VERSION}-{platform.uname()[4]}-linux.tar.gz") def ensure_binaryen(url, version): """Download and use a compiled binaryen to generate WebAssembly files if it does not exist. Args: url (str): URL of the compressed binaryen binary package version (int): Version of the compressed binaryen binary package Returns: Path: Path of the extracted wasm-opt binary """ shell_cache = sm_compile_helpers.ensure_cache_dir(Path.home()) wasmopt_path = Path(shell_cache / f"binaryen-version_{version}" / "wasm-opt").resolve() sleep_time = 2 t_lock = threading.Lock() with fasteners.try_lock(t_lock) as gotten: while not wasmopt_path.is_file(): if gotten: with requests.get(url, allow_redirects=True, stream=True) as binaryen_gzip_request: try: with tarfile.open(fileobj=io.BytesIO(binaryen_gzip_request.content), mode="r:gz") as f: f.extractall(str(shell_cache.resolve())) except OSError: print("binaryen tarfile threw an OSError") break sleep(sleep_time) sleep_time *= 2 return wasmopt_path def wasmopt_run(seed): """Runs binaryen with the generated seed. Args: seed (Path): Generated jsfunfuzz file (acts as the seed for binaryen) Returns: bool: Returns True on successful wasm-opt execution, False otherwise """ assert platform.system() == "Linux" assert seed.is_file() seed_wrapper_output = seed.resolve().with_suffix(".wrapper") seed_wasm_output = seed.resolve().with_suffix(".wasm") sleep_time = 2 t_lock = threading.Lock() with fasteners.try_lock(t_lock) as gotten: while True: if gotten: try: subprocess.run([ensure_binaryen(BINARYEN_URL, BINARYEN_VERSION), seed, "--translate-to-fuzz", "--disable-simd", "--output", seed_wasm_output, f"--emit-js-wrapper={seed_wrapper_output}"], check=True) except subprocess.CalledProcessError: print("wasm-opt aborted with a CalledProcessError") break sleep(sleep_time) sleep_time *= 2 assert seed_wrapper_output.is_file() assert seed_wasm_output.is_file() return (seed_wrapper_output, seed_wasm_output)
Python
0
@@ -559,10 +559,10 @@ N = -72 +81 %0ABIN
52c6efa0a84334522cdd76e1e85ffe6bf601ea02
Annotate commands/export_single_user.py.
zerver/management/commands/export_single_user.py
zerver/management/commands/export_single_user.py
from __future__ import absolute_import from __future__ import print_function from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ValidationError import os import shutil import subprocess import tempfile import ujson from zerver.lib.export import do_export_user from zerver.models import UserProfile, get_user_profile_by_email class Command(BaseCommand): help = """Exports message data from a Zulip user This command exports the message history for a single Zulip user. Note that this only exports the user's message history and realm-public metadata needed to understand it; it does nothing with (for example) any bots owned by the user.""" def add_arguments(self, parser): parser.add_argument('email', metavar='<email>', type=str, help="email of user to export") parser.add_argument('--output', dest='output_dir', action="store", default=None, help='Directory to write exported data to.') def handle(self, *args, **options): try: user_profile = get_user_profile_by_email(options["email"]) except UserProfile.DoesNotExist: raise CommandError("No such user.") output_dir = options["output_dir"] if output_dir is None: output_dir = tempfile.mkdtemp(prefix="/tmp/zulip-export-") if os.path.exists(output_dir): shutil.rmtree(output_dir) os.makedirs(output_dir) print("Exporting user %s" % (user_profile.email,)) do_export_user(user_profile, output_dir) print("Finished exporting to %s; tarring" % (output_dir,)) tarball_path = output_dir.rstrip('/') + '.tar.gz' subprocess.check_call(["tar", "--strip-components=1", "-czf", tarball_path, output_dir]) print("Tarball written to %s" % (tarball_path,))
Python
0
@@ -67,24 +67,84 @@ t_function%0A%0A +from typing import Any%0A%0Afrom argparse import ArgumentParser%0A from django. @@ -803,24 +803,65 @@ f, parser):%0A + # type: (ArgumentParser) -%3E None%0A pars @@ -1261,16 +1261,54 @@ tions):%0A + # type: (*Any, **Any) -%3E None%0A
2a2309bb4f3a8ae231106123855959d44a0e7551
Fix linter
cartoframes/viz/helpers/size_continuous_layer.py
cartoframes/viz/helpers/size_continuous_layer.py
from __future__ import absolute_import from ..layer import Layer def size_continuous_layer(source, value, title='', size=None, color=None): return Layer( source, style={ 'point': { 'width': 'ramp(linear(sqrt(${0}), sqrt(globalMin(${0})), sqrt(globalMax(${0}))), {1})'.format(value, size or [2, 50]), 'color': 'opacity({0}, 0.8)'.format(color or '#F46D43') }, 'line': { 'width': 'ramp(linear(${0}), {1})'.format(value, size or [1, 10]), 'color': 'opacity({0}, 0.8)'.format(color or '#4CC8A3') } }, popup={ 'hover': { 'title': title or value, 'value': '$' + value } }, legend={ 'type': { 'point': 'size-continuous-point', 'line': 'size-continuous-line', 'polygon': 'size-continuous-polygon' }, 'title': title or value, 'description': '' } )
Python
0.000002
@@ -311,32 +311,53 @@ ), %7B1%7D)'.format( +%0A value, size or %5B
c426ae514227adaf9dd86f6ada6ce05bc76298c2
Make portal_config fetch config from a URL
catkin/src/portal_config/scripts/serve_config.py
catkin/src/portal_config/scripts/serve_config.py
#!/usr/bin/env python import rospy from portal_config.srv import * class ConfigRequestHandler(): def __init__(self, url): self.url = url def get_config(self): return '{"foo": "bar"}' def handle_request(self, request): config = self.get_config() return PortalConfigResponse(config) def main(): rospy.init_node('portal_config') url = rospy.get_param('~url', 'http://lg-head/portal/config.json') handler = ConfigRequestHandler(url) s = rospy.Service( '/portal_config/query', PortalConfig, handler.handle_request ) rospy.spin() if __name__ == '__main__': main() # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Python
0.000002
@@ -29,16 +29,31 @@ t rospy%0A +import urllib2%0A from por @@ -77,16 +77,80 @@ port *%0A%0A +# XXX TODO: return an error if the config file isn't valid JSON%0A %0Aclass C @@ -265,29 +265,73 @@ re -turn '%7B%22foo%22: %22bar%22%7D' +sponse = urllib2.urlopen(self.url)%0A return response.read() %0A%0A @@ -836,9 +836,21 @@ abstop=4 + smartindent %0A
3023600701d64da42534fdc0050c473450e9e5f7
Bump the dart version used on the infra bots to 1.14.1
infra/download_dart_sdk.py
infra/download_dart_sdk.py
#!/usr/bin/python # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Pulls down the current dart sdk to third_party/dart-sdk/. You can manually force this to run again by removing third_party/dart-sdk/STAMP_FILE, which contains the URL of the SDK that was downloaded. Rolling works by updating LINUX_64_SDK to a new URL. """ import os import shutil import subprocess import sys # How to roll the dart sdk: Just change this url! We write this to the stamp # file after we download, and then check the stamp file for differences. SDK_URL_BASE = ('http://gsdview.appspot.com/dart-archive/channels/stable/raw/' '1.13.0/sdk/') LINUX_64_SDK = 'dartsdk-linux-x64-release.zip' MACOS_64_SDK = 'dartsdk-macos-x64-release.zip' # Path constants. (All of these should be absolute paths.) THIS_DIR = os.path.abspath(os.path.dirname(__file__)) DART_SDK_DIR = os.path.join(THIS_DIR, 'dart-sdk') STAMP_FILE = os.path.join(DART_SDK_DIR, 'STAMP_FILE') LIBRARIES_FILE = os.path.join(DART_SDK_DIR,'dart-sdk', 'lib', '_internal', 'libraries.dart') def RunCommand(command, fail_hard=True): """Run command and return success (True) or failure; or if fail_hard is True, exit on failure.""" print 'Running %s' % (str(command)) if subprocess.call(command, shell=False) == 0: return True print 'Failed.' if fail_hard: sys.exit(1) return False def main(): # Only get the SDK if we don't have a stamp for or have an out of date stamp # file. get_sdk = False if sys.platform.startswith('linux'): sdk_url = SDK_URL_BASE + LINUX_64_SDK output_file = os.path.join(DART_SDK_DIR, LINUX_64_SDK) elif sys.platform.startswith('darwin'): sdk_url = SDK_URL_BASE + MACOS_64_SDK output_file = os.path.join(DART_SDK_DIR, MACOS_64_SDK) else: print "Platform not supported" return 1 if not os.path.exists(STAMP_FILE): get_sdk = True else: # Get the contents of the stamp file. with open(STAMP_FILE, "r") as stamp_file: stamp_url = stamp_file.read().replace('\n', '') if stamp_url != sdk_url: get_sdk = True if get_sdk: # Completely remove all traces of the previous SDK. if os.path.exists(DART_SDK_DIR): shutil.rmtree(DART_SDK_DIR) os.mkdir(DART_SDK_DIR) # Download the Linux x64 based Dart SDK. # '-C -': Resume transfer if possible. # '--location': Follow Location: redirects. # '-o': Output file. curl_command = ['curl', '-C', '-', '--location', '-o', output_file, sdk_url] if not RunCommand(curl_command, fail_hard=False): print "Failed to get dart sdk from server." return 1 # Write our stamp file so we don't redownload the sdk. with open(STAMP_FILE, "w") as stamp_file: stamp_file.write(sdk_url) unzip_command = ['unzip', '-o', '-q', output_file, '-d', DART_SDK_DIR] if not RunCommand(unzip_command, fail_hard=False): print "Failed to unzip the dart sdk." return 1 return 0 if __name__ == '__main__': sys.exit(main())
Python
0
@@ -742,11 +742,11 @@ '1.1 -3.0 +4.1 /sdk
cb96065fcf1f31dfbecfbb064c9414ffbc69217f
Remove all relative imports. We have always been at war with relative imports.
forms.py
forms.py
""" GB-specific Form helpers """ import re from django.forms.fields import CharField, Select from django.forms import ValidationError from django.utils.translation import ugettext_lazy as _ class GBPostcodeField(CharField): """ A form field that validates its input is a UK postcode. The regular expression used is sourced from the schema for British Standard BS7666 address types: http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd The value is uppercased and a space added in the correct place, if required. """ default_error_messages = { 'invalid': _(u'Enter a valid postcode.'), } outcode_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])' incode_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}' postcode_regex = re.compile(r'^(GIR 0AA|%s %s)$' % (outcode_pattern, incode_pattern)) space_regex = re.compile(r' *(%s)$' % incode_pattern) def clean(self, value): value = super(GBPostcodeField, self).clean(value) if value == u'': return value postcode = value.upper().strip() # Put a single space before the incode (second part). postcode = self.space_regex.sub(r' \1', postcode) if not self.postcode_regex.search(postcode): raise ValidationError(self.error_messages['invalid']) return postcode class GBCountySelect(Select): """ A Select widget that uses a list of UK Counties/Regions as its choices. """ def __init__(self, attrs=None): from gb_regions import GB_REGION_CHOICES super(GBCountySelect, self).__init__(attrs, choices=GB_REGION_CHOICES) class GBNationSelect(Select): """ A Select widget that uses a list of UK Nations as its choices. """ def __init__(self, attrs=None): from gb_regions import GB_NATIONS_CHOICES super(GBNationSelect, self).__init__(attrs, choices=GB_NATIONS_CHOICES)
Python
0.002027
@@ -31,18 +31,149 @@ %22%22%0A%0A -import re%0A +from __future__ import absolute_import%0A%0Aimport re%0A%0Afrom django.contrib.localflavor.gb.gb_regions import GB_NATIONS_CHOICES, GB_REGION_CHOICES %0Afro @@ -317,16 +317,17 @@ y as _%0A%0A +%0A class GB @@ -1664,57 +1664,8 @@ e):%0A - from gb_regions import GB_REGION_CHOICES%0A @@ -1893,58 +1893,8 @@ e):%0A - from gb_regions import GB_NATIONS_CHOICES%0A
c78c6f7e9cc305b96eb35a5a0c8f7353db5a3ed2
Update _share.py
tago/account/_share.py
tago/account/_share.py
import requests # Used to make HTTP requests import os import json API_TAGO = os.environ.get('TAGO_SERVER') or 'https://api.tago.io' def invite(type, ref_id, data, default_options): data = data if data else {} if ref_id is None or ref_id == '': raise ValueError('ref_id must be set') elif data['email'] is None or data['email'] == '': raise ValueError('email must be set in data') return requests.post('{api_endpoint}/share/{type}/{ref_id}'.format(api_endpoint=API_TAGO,type=type,ref_id=ref_id), headers=default_options, data=json.dumps(data)).json() def edit(type, share_id, data, default_options): data = data if data else {} if share_id is None or share_id == '': raise ValueError('share_id must be set') return requests.put('{api_endpoint}/share/{share_id}'.format(api_endpoint=API_TAGO,share_id=share_id), headers=default_options, data=json.dumps(data)).json() def list(type, ref_id, default_options): if ref_id is None or ref_id == '': raise ValueError('ref_id must be set') return requests.get('{api_endpoint}/share/{type}/{ref_id}'.format(api_endpoint=API_TAGO,type=type, ref_id=ref_id), headers=default_options).json() def remove(type, share_id, default_options): if share_id is None or share_id == '': raise ValueError('share_id must be set') return requests.delete('{api_endpoint}/share/{share_id}'.format(api_endpoint=API_TAGO,share_id=share_id), headers=default_options).json() # Not sure what exports do...
Python
0
@@ -1477,35 +1477,4 @@ n()%0A -%0A# Not sure what exports do...%0A
f2a2f6268e11086ece3c311dd3e93e11672de03b
Comment addition.
Lib/distutils/command/build_py.py
Lib/distutils/command/build_py.py
"""distutils.command.build_py Implements the Distutils 'build_py' command.""" # created 1999/03/08, Greg Ward __rcsid__ = "$Id$" import string, os from distutils.core import Command from distutils.errors import * from distutils.util import mkpath, newer, make_file, copy_file class BuildPy (Command): options = [('dir=', 'd', "directory for platform-shared files"), ] def set_default_options (self): self.dir = None self.modules = None self.package = None def set_final_options (self): self.set_undefined_options ('build', ('libdir', 'dir')) if self.package is None: self.package = '' def run (self): # XXX copy_file by default preserves all stat info -- mode, atime, # and mtime. IMHO this is the right thing to do, but perhaps it # should be an option -- in particular, a site administrator might # want installed files to reflect the time of installation rather # than the last modification time before the installed release. # XXX copy_file does *not* preserve MacOS-specific file metadata. # If this is a problem for building/installing Python modules, then # we'll have to fix copy_file. (And what about installing scripts, # when the time comes for that -- does MacOS use its special # metadata to know that a file is meant to be interpreted by # Python?) self.set_final_options () infiles = [] outfiles = [] missing = [] # Loop over the list of "pure Python" modules, deriving # input and output filenames and checking for missing # input files. # it's ok not to have *any* py files, right? if not self.modules: return # XXX we should allow for wildcards, so eg. the Distutils setup.py # file would just have to say # py_modules = ['distutils.*', 'distutils.command.*'] # without having to list each one explicitly. for m in self.modules: fn = apply (os.path.join, tuple (string.split (m, '.'))) + '.py' if not os.path.exists (fn): missing.append (fn) else: infiles.append (fn) outfiles.append (os.path.join (self.dir, self.package, fn)) # Blow up if any input files were not found. if missing: raise DistutilsFileError, \ "missing files: " + string.join (missing, ' ') # Loop over the list of input files, copying them to their # temporary (build) destination. created = {} for i in range (len (infiles)): outdir = os.path.split (outfiles[i])[0] if not created.get(outdir): self.mkpath (outdir) created[outdir] = 1 self.copy_file (infiles[i], outfiles[i]) # end class BuildPy
Python
0
@@ -639,16 +639,205 @@ 'dir'))%0A + # 'package' is an alias option in Distribution (hmmm, we%0A # really should change to %22pull%22 options from Distribution%0A # rather than %22pushing%22 them out to commands...)%0A
929fbcf6b41feb620c2ddb713b0b239bd01be0f2
Simplify status code check
technic/solder/base.py
technic/solder/base.py
import hashlib import json import os import os.path import requests import requests.exceptions import shutil import zipfile # Provide Python 2 and Python 3 support try: import urlparse except ImportError: # pylint: disable=import-error, no-member, no-name-in-module import urllib.parse urlparse = urllib.parse # pylint: enable=import-error, no-member, no-name-in-module from .exceptions import SolderAPIError class SolderServer(object): USER_CONFIG = os.path.join(os.path.expanduser('~'), '.solderrc') SOLDER_CACHE = os.path.join(os.path.expanduser('~'), '.solder-cache') def __init__(self, solder_url, config_file = None, requests_module = None): self.solder_url = solder_url self._requests_module = requests_module if requests_module else requests config_file = config_file or SolderServer.USER_CONFIG if os.path.exists(config_file): with open(config_file, 'r') as file_handle: config = json.load(file_handle) else: config = {} self.solder_cache = os.path.expanduser( os.path.expandvars( config.get('cache', SolderServer.SOLDER_CACHE) ) ) def verify_api_key(self, api_key): return self._request( '/api/verify/{key}', 'GET', key = api_key, ) def get_mod_info(self, slug): return self._request( '/api/mod/{slug}', 'GET', slug = slug, ) def get_modpack_info(self, slug): return self._request( '/api/modpack/{slug}', 'GET', slug = slug, ) def get_modpack_build_info(self, slug, build): return self._request( '/api/modpack/{slug}/{build}', 'GET', slug = slug, build = build, ) # pylint: disable=too-many-arguments def download_modpack(self, slug, build = None, callback = None, latest = False, directory = None, upgrade = False): if not build: modpack_info = self.get_modpack_info(slug) if latest: build = modpack_info['latest'] else: build = modpack_info['recommended'] if not build: raise SolderAPIError('Could not find a build to use') if not directory: directory = '.' build_info = self.get_modpack_build_info(slug, build) if upgrade: for path in ['bin', 'config', 'mods']: if os.path.exists(os.path.join(directory, path)): shutil.rmtree(os.path.join(directory, path)) for mod in build_info['mods']: self._download_mod(mod, directory, callback = callback) # pylint: disable=too-many-arguments @property def server_info(self): info = self._request( '/api', 'GET', ) return (info['version'], info['stream']) @property def modpacks(self): return self._request('/api/modpack', 'GET')['modpacks'] @property def mods(self): return self._request('/api/mod', 'GET')['mods'] def _request(self, url, method, **kwargs): url_parts = urlparse.urlparse(self.solder_url) url = urlparse.urlunparse( ( url_parts.scheme, url_parts.netloc, url.format(**kwargs), '', '', '', ) ) resp = self._requests_module.request(method, url) if not resp.status_code == 200: raise SolderAPIError('API connection error ({})'.format(resp.status_code)) json_resp = resp.json() if 'error' in json_resp: raise SolderAPIError(json_resp['error']) return json_resp def _download_mod(self, mod_info, directory, callback = None): if not callback: # pylint: disable=unused-argument def skip(status, *args, **kwargs): pass callback = skip # pylint: enable=unused-argument callback('mod.download.start', name = mod_info['name']) url = mod_info['url'] filename = os.path.basename(url) if not os.path.exists(self.solder_cache): os.mkdir(self.solder_cache) file_path = os.path.join(directory, filename) if os.path.exists(os.path.join(self.solder_cache, filename)): callback('mod.download.cache') shutil.copy(os.path.join(self.solder_cache, filename), directory) else: resp = self._requests_module.get(url, stream = True) with open(file_path, 'wb') as file_handle: for chunk in resp.iter_content(chunk_size = 1024): if chunk: file_handle.write(chunk) file_handle.flush() callback('mod.download.verify') md5 = hashlib.md5(open(file_path, 'rb').read()).hexdigest() if md5 != mod_info['md5']: callback('mod.download.verify.error') return shutil.copy(file_path, os.path.join(self.solder_cache, filename)) callback('mod.download.unpack') with zipfile.ZipFile(file_path, 'r') as zip_handle: zip_handle.extractall(directory) callback('mod.download.clean') os.remove(file_path) callback('mod.download.finish')
Python
0.000004
@@ -2952,24 +2952,54 @@ thod, url)%0A%0A +%09%09# pylint: disable=no-member%0A %09%09if not res @@ -3019,11 +3019,25 @@ == -200 +requests.codes.OK :%0A%09%09 @@ -3111,16 +3111,45 @@ s_code)) +%0A%09%09# pylint: enable=no-member %0A%0A%09%09json
bbae716c79307bd477925fc1fe9cdc9df7c1884c
Replace self.nodes[0].p2p with conn
test/functional/p2p_feefilter.py
test/functional/p2p_feefilter.py
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of feefilter messages.""" from decimal import Decimal import time from test_framework.messages import MSG_TX, msg_feefilter from test_framework.mininode import mininode_lock, P2PInterface from test_framework.test_framework import SyscoinTestFramework def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True time.sleep(1) return False class TestP2PConn(P2PInterface): def __init__(self): super().__init__() self.txinvs = [] def on_inv(self, message): for i in message.inv: if (i.type == MSG_TX): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] class FeeFilterTest(SyscoinTestFramework): def set_test_params(self): self.num_nodes = 2 # We lower the various required feerates for this test # to catch a corner-case where feefilter used to slightly undercut # mempool and wallet feerate calculation based on GetFee # rounding down 3 places, leading to stranded transactions. # See issue #16499 self.extra_args = [["-minrelaytxfee=0.00000100", "-mintxfee=0.00000100"]] * self.num_nodes def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] self.nodes[0].add_p2p_connection(TestP2PConn()) # Test that invs are received by test connection for all txs at # feerate of .2 sat/byte node1.settxfee(Decimal("0.00000200")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert allInvsMatch(txids, self.nodes[0].p2p) self.nodes[0].p2p.clear_invs() # Set a filter of .15 sat/byte on test connection self.nodes[0].p2p.send_and_ping(msg_feefilter(150)) # Test that txs are still being received by test connection (paying .15 sat/byte) node1.settxfee(Decimal("0.00000150")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert allInvsMatch(txids, self.nodes[0].p2p) self.nodes[0].p2p.clear_invs() # Change tx fee rate to .1 sat/byte and test they are no longer received # by the test connection node1.settxfee(Decimal("0.00000100")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] self.sync_mempools() # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert allInvsMatch(txids, self.nodes[0].p2p) self.nodes[0].p2p.clear_invs() # Remove fee filter and check that txs are received again self.nodes[0].p2p.send_and_ping(msg_feefilter(0)) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert allInvsMatch(txids, self.nodes[0].p2p) self.nodes[0].p2p.clear_invs() if __name__ == '__main__': FeeFilterTest().main()
Python
0.001081
@@ -1850,32 +1850,39 @@ odes%5B0%5D%0A%0A + conn = self.nodes%5B0%5D.a @@ -2187,52 +2187,26 @@ ds, -self.nodes%5B0%5D.p2p)%0A self.nodes%5B0%5D.p2p +conn)%0A conn .cle @@ -2282,33 +2282,20 @@ -self.nodes%5B0%5D.p2p +conn .send_an @@ -2579,52 +2579,26 @@ ds, -self.nodes%5B0%5D.p2p)%0A self.nodes%5B0%5D.p2p +conn)%0A conn .cle @@ -3550,52 +3550,26 @@ ds, -self.nodes%5B0%5D.p2p)%0A self.nodes%5B0%5D.p2p +conn)%0A conn .cle @@ -3653,33 +3653,20 @@ -self.nodes%5B0%5D.p2p +conn .send_an @@ -3811,52 +3811,26 @@ ds, -self.nodes%5B0%5D.p2p)%0A self.nodes%5B0%5D.p2p +conn)%0A conn .cle
3575415592fbd215de02e139d95ad5780bccadd2
Add greeting method that returns given parameter
hello.py
hello.py
print("Hello")
Python
0.000146
@@ -1,15 +1,85 @@ -print(%22H +%0Adef greeting(msg):%0A print(msg)%0A%0Aif __name__ == %22__main__%22:%0A greeting('h ello -%22 +' )%0A
fe004672d79f74b939e812985639924d605d45c9
Clear Site cache upon SiteConfiguration change.
ecommerce/core/models.py
ecommerce/core/models.py
import logging from analytics import Client as SegmentClient from django.conf import settings from django.contrib.auth.models import AbstractUser from django.core.exceptions import ValidationError from django.db import models from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from jsonfield.fields import JSONField from ecommerce.extensions.payment.exceptions import ProcessorNotFoundError from ecommerce.extensions.payment.helpers import get_processor_class_by_name, get_processor_class log = logging.getLogger(__name__) class SiteConfiguration(models.Model): """Custom Site model for custom sites/microsites. This model will enable the basic theming and payment processor configuration for each custom site. The multi-tenant implementation has one site per partner. """ site = models.OneToOneField('sites.Site', null=False, blank=False) partner = models.ForeignKey('partner.Partner', null=False, blank=False) lms_url_root = models.URLField( verbose_name=_('LMS base url for custom site/microsite'), help_text=_("Root URL of this site's LMS (e.g. https://courses.stage.edx.org)"), null=False, blank=False ) theme_scss_path = models.CharField( verbose_name=_('Path to custom site theme'), help_text=_('Path to scss files of the custom site theme'), max_length=255, null=False, blank=False ) payment_processors = models.CharField( verbose_name=_('Payment processors'), help_text=_("Comma-separated list of processor names: 'cybersource,paypal'"), max_length=255, null=False, blank=False ) oauth_settings = JSONField( verbose_name=_('OAuth settings'), help_text=_('JSON string containing OAuth backend settings.'), null=False, blank=False, default={} ) segment_key = models.CharField( verbose_name=_('Segment key'), help_text=_('Segment write/API key.'), max_length=255, null=True, blank=True ) from_email = models.CharField( verbose_name=_('From email'), help_text=_('Address from which emails are sent.'), max_length=255, null=True, blank=True ) class Meta(object): unique_together = ('site', 'partner') @property def payment_processors_set(self): """ Returns a set of enabled payment processor keys Returns: set[string]: Returns a set of enabled payment processor keys """ return { raw_processor_value.strip() for raw_processor_value in self.payment_processors.split(',') } def _clean_payment_processors(self): """ Validates payment_processors field value Raises: ValidationError: If `payment_processors` field contains invalid/unknown payment_processor names """ value = self.payment_processors.strip() if not value: raise ValidationError('Invalid payment processors field: must not consist only of whitespace characters') processor_names = value.split(',') for name in processor_names: try: get_processor_class_by_name(name.strip()) except ProcessorNotFoundError as exc: log.exception( "Exception validating site configuration for site `%s` - payment processor %s could not be found", self.site.id, name ) raise ValidationError(exc.message) def get_payment_processors(self): """ Returns payment processor classes enabled for the corresponding Site Returns: list[BasePaymentProcessor]: Returns payment processor classes enabled for the corresponding Site """ all_processors = [get_processor_class(path) for path in settings.PAYMENT_PROCESSORS] all_processor_names = {processor.NAME for processor in all_processors} missing_processor_configurations = self.payment_processors_set - all_processor_names if missing_processor_configurations: processor_config_repr = ", ".join(missing_processor_configurations) log.warning( 'Unknown payment processors [%s] are configured for site %s', processor_config_repr, self.site.id ) return [ processor for processor in all_processors if processor.NAME in self.payment_processors_set and processor.is_enabled() ] def get_from_email(self): """ Returns the configured from_email value for the specified site. If no from_email is available we return the base OSCAR_FROM_EMAIL setting Returns: string: Returns sender address for use in customer emails/alerts """ return self.from_email or settings.OSCAR_FROM_EMAIL def clean_fields(self, exclude=None): """ Validates model fields """ if not exclude or 'payment_processors' not in exclude: self._clean_payment_processors() @cached_property def segment_client(self): return SegmentClient(self.segment_key, debug=settings.DEBUG) class User(AbstractUser): """Custom user model for use with OIDC.""" full_name = models.CharField(_('Full Name'), max_length=255, blank=True, null=True) @property def access_token(self): try: return self.social_auth.first().extra_data[u'access_token'] # pylint: disable=no-member except Exception: # pylint: disable=broad-except return None tracking_context = JSONField(blank=True, null=True) class Meta(object): get_latest_by = 'date_joined' db_table = 'ecommerce_user' def get_full_name(self): return self.full_name or super(User, self).get_full_name() class Client(User): pass class BusinessClient(models.Model): """The model for the business client.""" name = models.CharField(_('Name'), unique=True, max_length=255, blank=False, null=False) def __str__(self): return self.name def validate_configuration(): """ Validates all existing SiteConfiguration models """ for config in SiteConfiguration.objects.all(): config.clean_fields()
Python
0
@@ -140,16 +140,61 @@ actUser%0A +from django.contrib.sites.models import Site%0A from dja @@ -5363,16 +5363,208 @@ DEBUG)%0A%0A + def save(self, *args, **kwargs):%0A # Clear Site cache upon SiteConfiguration changed%0A Site.objects.clear_cache()%0A super(SiteConfiguration, self).save(*args, **kwargs)%0A%0A %0Aclass U
f2e8f2ef957a6053345f72889c1048a871988bc0
Add octario library path to the plugin helper
ir-plugin/osp_version_name.py
ir-plugin/osp_version_name.py
#!/usr/bin/env python # Copyright 2017 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import sys from octario.lib.component import Component import logging LOG = logging.getLogger("OctarioLogger") LOG.setLevel(logging.ERROR) def main(component_path): cmpnt = Component(component_path) release = cmpnt.get_rhos_release() name = cmpnt.get_name() if release is not None and name is not None: json_out = { 'plugin': 'iroctario', 'name': name, 'version': release, } print(json.dumps(json_out)) if __name__ == "__main__": """Helper script used by InfraRed-Octario plugin to discover component name and OSP release number. """ if len(sys.argv) != 2: LOG.error("Improper number of arguments, passed %d instead of 1" % int(len(sys.argv)-1)) sys.exit(1) main(sys.argv[1])
Python
0.000002
@@ -667,16 +667,46 @@ port sys +%0Asys.path.append('../octario') %0A%0Afrom o
6565c4852c2a26f385cf9a422a914ee110b25b4b
Remove cruft from activity_WorkflowConflictCheck.py
activity/activity_WorkflowConflictCheck.py
activity/activity_WorkflowConflictCheck.py
import boto.swf import json import random import datetime import calendar import time import activity import boto.ses import provider.swfmeta as swfmetalib """ WorkflowConflictCheck activity """ class activity_WorkflowConflictCheck(activity.activity): def __init__(self, settings, logger, conn = None, token = None, activity_task = None): activity.activity.__init__(self, settings, logger, conn, token, activity_task) self.name = "WorkflowConflictCheck" self.version = "1" self.default_task_heartbeat_timeout = 30 self.default_task_schedule_to_close_timeout = 60*30 self.default_task_schedule_to_start_timeout = 30 self.default_task_start_to_close_timeout= 60*30 self.description = "Check for open workflows to determine logical conflicts, when two workflow types should not run concurrently." def do_activity(self, data = None): """ WorkflowConflictCheck activity, do the work """ if(self.logger): self.logger.info('data: %s' % json.dumps(data, sort_keys=True, indent=4)) is_open = None workflow_id = None workflow_name = None workflow_version = None try: workflow_id = data["data"]["workflow_id"] except KeyError: pass try: workflow_name = data["data"]["workflow_name"] except KeyError: pass try: workflow_version = data["data"]["workflow_version"] except KeyError: pass swfmeta = swfmetalib.SWFMeta(self.settings) swfmeta.connect() is_open = swfmeta.is_workflow_open(workflow_id = workflow_id, workflow_name = workflow_name, workflow_version = workflow_version) # Return logic: if is_open is False, then return True as being no conflict # But, if is_open is True, do not return a value, causing this activity to timeout if is_open is False: return True else: return None def get_email_body(self, time_period, history_text): """ Format the body of the email """ body = "" date_format = '%Y-%m-%dT%H:%M:%S.000Z' datetime_string = time.strftime(date_format, time.gmtime()) body = "A short history of workflow executions\n" body += "As at " + datetime_string + "\n" body += "Time period: " + str(time_period) + " seconds" + "\n" body += "Domain: " + self.settings.domain + "\n" body += history_text body += "\n\nSincerely\n\neLife bot" return body def send_email(self, sender_email, recipient_email, subject, body, format = "text"): """ Using Amazon SES service """ ses_conn = boto.ses.connect_to_region(self.settings.simpledb_region, aws_access_key_id = self.settings.aws_access_key_id, aws_secret_access_key = self.settings.aws_secret_access_key) ses_conn.send_email( source = sender_email, to_addresses = recipient_email, subject = subject, body = body, format = format) def get_workflow_count_by_closestatus(self, seconds): history_text = "" close_status_list = ["COMPLETED", "FAILED", "CANCELED", "TERMINATED", "CONTINUED_AS_NEW", "TIMED_OUT"] swfmeta = swfmetalib.SWFMeta(self.settings) swfmeta.connect() date_format = '%Y-%m-%dT%H:%M:%S.000Z' current_timestamp = calendar.timegm(time.gmtime()) start_latest_date_timestamp = current_timestamp start_oldest_date_timestamp = start_latest_date_timestamp - seconds for close_status in close_status_list: count = swfmeta.get_closed_workflow_execution_count( domain = self.settings.domain, start_oldest_date = start_oldest_date_timestamp, start_latest_date = start_latest_date_timestamp, close_status = close_status ) run_count = None try: run_count = count["count"] except: run_count = None # Concatenate the message history_text = history_text + "\n" + close_status + ": " + str(run_count) return history_text
Python
0
@@ -1885,2147 +1885,4 @@ one%0A -%0A def get_email_body(self, time_period, history_text):%0A %22%22%22%0A Format the body of the email%0A %22%22%22%0A %0A body = %22%22%0A %0A date_format = '%25Y-%25m-%25dT%25H:%25M:%25S.000Z'%0A datetime_string = time.strftime(date_format, time.gmtime())%0A %0A body = %22A short history of workflow executions%5Cn%22%0A body += %22As at %22 + datetime_string + %22%5Cn%22%0A body += %22Time period: %22 + str(time_period) + %22 seconds%22 + %22%5Cn%22%0A body += %22Domain: %22 + self.settings.domain + %22%5Cn%22%0A body += history_text%0A body += %22%5Cn%5CnSincerely%5Cn%5CneLife bot%22%0A %0A return body%0A%0A def send_email(self, sender_email, recipient_email, subject, body, format = %22text%22):%0A %22%22%22%0A Using Amazon SES service%0A %22%22%22%0A %0A ses_conn = boto.ses.connect_to_region(self.settings.simpledb_region, aws_access_key_id = self.settings.aws_access_key_id, aws_secret_access_key = self.settings.aws_secret_access_key)%0A %0A ses_conn.send_email(%0A source = sender_email,%0A to_addresses = recipient_email,%0A subject = subject,%0A body = body,%0A format = format)%0A%0A def get_workflow_count_by_closestatus(self, seconds):%0A %0A history_text = %22%22%0A %0A close_status_list = %5B%22COMPLETED%22, %22FAILED%22, %22CANCELED%22, %22TERMINATED%22, %22CONTINUED_AS_NEW%22, %22TIMED_OUT%22%5D%0A %0A swfmeta = swfmetalib.SWFMeta(self.settings)%0A swfmeta.connect()%0A%0A date_format = '%25Y-%25m-%25dT%25H:%25M:%25S.000Z'%0A current_timestamp = calendar.timegm(time.gmtime())%0A %0A start_latest_date_timestamp = current_timestamp%0A start_oldest_date_timestamp = start_latest_date_timestamp - seconds%0A %0A for close_status in close_status_list:%0A count = swfmeta.get_closed_workflow_execution_count(%0A domain = self.settings.domain,%0A start_oldest_date = start_oldest_date_timestamp,%0A start_latest_date = start_latest_date_timestamp,%0A close_status = close_status%0A )%0A run_count = None%0A try:%0A run_count = count%5B%22count%22%5D%0A except:%0A run_count = None%0A %0A # Concatenate the message%0A history_text = history_text + %22%5Cn%22 + close_status + %22: %22 + str(run_count)%0A %0A return history_text%0A
5a5418a9e5f817c3c3f426f57aeefe800c45cc96
Implement tuples.
jaspyx/visitor/types.py
jaspyx/visitor/types.py
import json from jaspyx.visitor import BaseVisitor class Types(BaseVisitor): def visit_Num(self, node): self.output(json.dumps(node.n)) def visit_Str(self, node): self.output(json.dumps(node.s)) def visit_List(self, node): self.group(node.elts, prefix='[', infix=', ', suffix=']')
Python
0.000004
@@ -314,8 +314,38 @@ ix='%5D')%0A +%0A visit_Tuple = visit_List%0A
c902c135a2e3e7d91d2a57cfa67df1a083f048c6
Add name attribute to linters
jenkins_job_linter/linters.py
jenkins_job_linter/linters.py
# Copyright (C) 2017 Daniel Watkins <daniel@daniel-watkins.co.uk> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A collection of linters for Jenkins job XML.""" import re from configparser import ConfigParser from enum import Enum from typing import Optional, Tuple from xml.etree import ElementTree from stevedore.extension import ExtensionManager class LintResult(Enum): """ The result of a linting check (i.e. pass/fail/skip). The value of each element represents whether or not the result should be considered a success when reducing down to just pass/fail. """ PASS = True FAIL = False SKIP = True class Linter: """A super-class capturing the common linting pattern.""" def __init__(self, tree: ElementTree.ElementTree, config: ConfigParser) -> None: """ Create an instance of a Linter. :param tree: A Jenkins job XML file parsed in to an ElementTree. :param config: The configuration for this linting run. """ self._tree = tree self._config = config def actual_check(self) -> Tuple[LintResult, Optional[str]]: """Perform the actual linting check.""" raise NotImplementedError # pragma: nocover def check(self) -> Tuple[LintResult, Optional[str]]: """Wrap actual_check in nice output.""" return self.actual_check() @property def description(self) -> str: """Output-friendly description of what this Linter does.""" raise NotImplementedError # pragma: nocover class EnsureTimestamps(Linter): """Ensure that a job is configured with timestamp output.""" description = 'checking for timestamps' _xpath = ( './buildWrappers/hudson.plugins.timestamper.TimestamperBuildWrapper') def actual_check(self) -> Tuple[LintResult, Optional[str]]: """Check that the TimestamperBuildWrapper element is present.""" result = LintResult.FAIL if self._tree.find(self._xpath) is not None: result = LintResult.PASS return result, None class ShellBuilderLinter(Linter): """A linter that operates on the shell builders of jobs.""" _xpath = './builders/hudson.tasks.Shell/command' def actual_check(self) -> Tuple[LintResult, Optional[str]]: """ Iterate over the shell builders in a job calling self.shell_check. If any of the self.shell_check calls fail, this returns that result immediately. (Note also that it assumes that there will only be text to return on that single failure.) """ shell_builders = self._tree.findall(self._xpath) if not shell_builders: return LintResult.SKIP, None for shell_builder in shell_builders: shell_script = shell_builder.text result, text = self.shell_check(shell_script) if result == LintResult.FAIL: return result, text return LintResult.PASS, None def shell_check(self, shell_script: Optional[str]) -> Tuple[LintResult, Optional[str]]: """Perform a check for a specific shell builder.""" raise NotImplementedError # pragma: nocover class CheckForEmptyShell(ShellBuilderLinter): """Ensure that shell builders in a job have some content.""" description = 'checking shell builder shell scripts are not empty' def shell_check(self, shell_script: Optional[str]) -> Tuple[LintResult, None]: """Check that a shell script is not empty.""" if shell_script is None: return LintResult.FAIL, None return LintResult.PASS, None class CheckShebang(ShellBuilderLinter): """ Ensure that shell builders in a job have an appropriate shebang. Specifically, ensure that those with a shell shebang call the shell with -eux. Shell builders with no shebang or a non-shell shebang are skipped. """ description = 'checking shebang of shell builders' def shell_check(self, shell_script: Optional[str]) -> Tuple[LintResult, Optional[str]]: """Check a shell script for an appropriate shebang.""" if shell_script is None: return LintResult.SKIP, None first_line = shell_script.splitlines()[0] if not first_line.startswith('#!'): # This will use Jenkins' default return LintResult.SKIP, None if re.match(r'#!/bin/[a-z]*sh', first_line) is None: # This has a non-shell shebang return LintResult.SKIP, None line_parts = first_line.split(' ') if (len(line_parts) < 2 or re.match(r'-[eux]{3}', line_parts[1]) is None): return LintResult.FAIL, 'Shebang is {}'.format(first_line) return LintResult.PASS, None extension_manager = ExtensionManager(namespace='jjl.linters') LINTERS = [ext.plugin for ext in extension_manager]
Python
0.000001
@@ -2071,24 +2071,179 @@ a: nocover%0A%0A + @property%0A def name(self) -%3E str:%0A %22%22%22Name for this linter (used in configuration).%22%22%22%0A raise NotImplementedError # pragma: nocover%0A%0A %0Aclass Ensur @@ -2373,16 +2373,47 @@ stamps'%0A + name = 'ensure_timestamps'%0A _xpa @@ -4149,16 +4149,51 @@ t empty' +%0A name = 'check_for_empty_shell' %0A%0A de @@ -4840,16 +4840,43 @@ uilders' +%0A name = 'check_shebang' %0A%0A de
5cda63163acec59a43c3975f1320b7268dcf337b
Add parameter for log level
devito/parameters.py
devito/parameters.py
"""The parameters dictionary contains global parameter settings.""" __all__ = ['Parameters', 'parameters'] # Be EXTREMELY careful when writing to a Parameters dictionary # Read here for reference: http://wiki.c2.com/?GlobalVariablesAreBad # If any issues related to global state arise, the following class should # be made immutable. It shall only be written to at application startup # and never modified. class Parameters(dict): """ A dictionary-like class to hold global configuration parameters for devito On top of a normal dict, this provides the option to provide callback functions so that any interested module can be informed when the configuration changes. """ def __init__(self, name=None, **kwargs): self._name = name self.update_functions = None for key, value in iteritems(kwargs): self[key] = value def __setitem__(self, key, value): super(Parameters, self).__setitem__(key, value) # If a Parameters dictionary is being added as a child, # ask it to tell us when it is updated if isinstance(value, Parameters): child_update = lambda x: self._updated(*x) value.update_functions.push(child_update) # Tell everyone we've been updated self._updated(key, value) def _updated(self, key, value): """ Call any provided update functions so everyone knows we've been updated """ for f in self.update_functions: f(key, value)
Python
0.000001
@@ -234,16 +234,109 @@ sAreBad%0A +# https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil%0A # If any @@ -1605,20 +1605,80 @@ f(key, value)%0A +%0Aparameters = Parameters()%0Aparameters%5B%22log_level%22%5D = 'info'%0A
57fcbfc8b93dca8ffe2e27fd1004e4ee0b396a65
Add 256 token setting to forgotten test in 18f2f684e82c0e807a80
disk_balance_test.py
disk_balance_test.py
import os import os.path from assertions import assert_almost_equal from dtest import DISABLE_VNODES, Tester from jmxutils import JolokiaAgent, make_mbean, remove_perf_disable_shared_mem from tools import create_c1c2_table, insert_c1c2, new_node, query_c1c2, since @since('3.2') class TestDiskBalance(Tester): """ @jira_ticket CASSANDRA-6696 """ def disk_balance_stress_test(self): cluster = self.cluster cluster.set_datadir_count(3) cluster.set_configuration_options(values={'allocate_tokens_for_keyspace': 'keyspace1'}) cluster.populate(4).start(wait_for_binary_proto=True) node1 = cluster.nodes['node1'] node1.stress(['write', 'n=10k', '-rate', 'threads=100', '-schema', 'replication(factor=2)']) cluster.flush() # make sure the data directories are balanced: for node in cluster.nodelist(): self.assert_balanced(node) def disk_balance_bootstrap_test(self): cluster = self.cluster if not DISABLE_VNODES: cluster.set_configuration_options(values={'num_tokens': 256}) # apparently we have legitimate errors in the log when bootstrapping (see bootstrap_test.py) self.allow_log_errors = True cluster.set_configuration_options(values={'allocate_tokens_for_keyspace': 'keyspace1'}) cluster.populate(4).start(wait_for_binary_proto=True) node1 = cluster.nodes['node1'] node1.stress(['write', 'n=10k', '-rate', 'threads=100', '-schema', 'replication(factor=3)']) cluster.flush() node5 = new_node(cluster) node5.start(wait_for_binary_proto=True) self.assert_balanced(node5) cluster.cleanup() self.assert_balanced(node5) if DISABLE_VNODES: for node in cluster.nodelist(): node.nodetool('relocatesstables') self.assertTrue(len(node5.grep_log("No sstables to RELOCATE for keyspace1.standard1")) > 0) for node in cluster.nodelist(): self.assert_balanced(node) def disk_balance_decommission_test(self): cluster = self.cluster if not DISABLE_VNODES: cluster.set_configuration_options(values={'num_tokens': 256}) cluster.set_configuration_options(values={'allocate_tokens_for_keyspace': 'keyspace1'}) cluster.populate(4).start(wait_for_binary_proto=True) node1 = cluster.nodes['node1'] node4 = cluster.nodes['node4'] node1.stress(['write', 'n=1', '-rate', 'threads=100', '-schema', 'replication(factor=2)']) for node in cluster.nodelist(): node.nodetool('disableautocompaction') node1.stress(['write', 'n=10k', '-rate', 'threads=100', '-schema', 'replication(factor=2)']) cluster.flush() node4.decommission() if DISABLE_VNODES: for node in cluster.nodelist(): node.nodetool('relocatesstables') for node in cluster.nodelist(): self.assert_balanced(node) def blacklisted_directory_test(self): cluster = self.cluster cluster.set_datadir_count(3) cluster.populate(1) [node] = cluster.nodelist() remove_perf_disable_shared_mem(node) cluster.start(wait_for_binary_proto=True) session = self.patient_cql_connection(node) self.create_ks(session, 'ks', 1) create_c1c2_table(self, session) insert_c1c2(session, n=10000) node.flush() for k in xrange(0, 10000): query_c1c2(session, k) node.compact() mbean = make_mbean('db', type='BlacklistedDirectories') with JolokiaAgent(node) as jmx: jmx.execute_method(mbean, 'markUnwritable', [os.path.join(node.get_path(), 'data0')]) for k in xrange(0, 10000): query_c1c2(session, k) node.nodetool('relocatesstables') for k in xrange(0, 10000): query_c1c2(session, k) def alter_replication_factor_test(self): cluster = self.cluster cluster.set_datadir_count(3) cluster.set_configuration_options(values={'allocate_tokens_for_keyspace': 'keyspace1'}) cluster.populate(3).start(wait_for_binary_proto=True) node1 = cluster.nodes['node1'] node1.stress(['write', 'n=1', '-rate', 'threads=100', '-schema', 'replication(factor=1)']) cluster.flush() session = self.patient_cql_connection(node1) session.execute("ALTER KEYSPACE keyspace1 WITH replication = {'class':'SimpleStrategy', 'replication_factor':2}") node1.stress(['write', 'n=100k', '-rate', 'threads=100']) cluster.flush() for node in cluster.nodelist(): self.assert_balanced(node) def assert_balanced(self, node): sums = [] for sstabledir in node.get_sstables_per_data_directory('keyspace1', 'standard1'): sum = 0 for sstable in sstabledir: sum = sum + os.path.getsize(sstable) sums.append(sum) assert_almost_equal(*sums, error=0.2, error_message=node.name)
Python
0.000001
@@ -550,32 +550,137 @@ : 'keyspace1'%7D)%0A + if not DISABLE_VNODES:%0A cluster.set_configuration_options(values=%7B'num_tokens': 256%7D)%0A cluster.
87e1e998c155731c44ca6e9cf1f97831d09f18a0
Make 46elks Alerter Python 3 flavoured
Alerters/fortysixelks.py
Alerters/fortysixelks.py
try: import requests requests_available = True except: requests_available = False from alerter import Alerter class FortySixElksAlerter(Alerter): """Send SMS alerts using the 46elks SMS service. Account required, see https://www.46elks.com/""" def __init__(self, config_options): if not requests_available: print "Requests package is not available, cannot use FortySixElksAlerter." print "Try: pip install -r requirements.txt" return Alerter.__init__(self, config_options) try: username = config_options["username"] password = config_options["password"] target = config_options["target"] except: raise RuntimeError("Required configuration fields missing") if 'sender' in config_options: sender = config_options["sender"] if sender[0] == '+' and sender[1:].isdigit(): # sender is phone number pass elif len(sender) < 3: raise RuntimeError("SMS sender name must be at least 3 chars long") elif len(sender) > 11: print "warning: truncating SMS sender name to 11 chars" sender = sender[:11] else: sender = "SmplMntr" api_host = 'api.46elks.com' if 'api_host' in config_options: api_host = config_options['api_host'] self.username = username self.password = password self.target = target self.sender = sender self.api_host = api_host self.support_catchup = True def send_alert(self, name, monitor): """Send an SMS alert.""" if not monitor.is_urgent(): return type = self.should_alert(monitor) message = "" url = "" (days, hours, minutes, seconds) = self.get_downtime(monitor) if type == "": return elif type == "catchup": (days, hours, minutes, seconds) = self.get_downtime(monitor) message = "catchup: %s failed on %s at %s (%d+%02d:%02d:%02d)\n%s" % ( name, monitor.running_on, self.format_datetime(monitor.first_failure_time()), days, hours, minutes, seconds, monitor.get_result()) if len(message) > 160: print "Warning! Truncating SMS message to 160 chars." message = message[:156] + "..." url = "https://{}/a1/SMS".format(self.api_host) auth = (self.username, self.password) params = { 'from': self.sender, 'to': self.target, 'message': message, } elif type == "failure": (days, hours, minutes, seconds) = self.get_downtime(monitor) message = "%s failed on %s at %s (%d+%02d:%02d:%02d)\n%s" % ( name, monitor.running_on, self.format_datetime(monitor.first_failure_time()), days, hours, minutes, seconds, monitor.get_result()) if len(message) > 160: print "Warning! Truncating SMS message to 160 chars." message = message[:156] + "..." url = "https://{}/a1/SMS".format(self.api_host) auth = (self.username, self.password) params = { 'from': self.sender, 'to': self.target, 'message': message, } else: # we don't handle other types of message pass if url == "": return if not self.dry_run: try: response = requests.post(url, data=params, auth=auth) s = response.json() if s['status'] not in ('created', 'delivered'): print "Unable to send SMS: %s" % s print "URL: %s, PARAMS: %s" % (url, params) self.available = False except Exception as e: print "SMS sending failed" print e print url print params self.available = False else: print "dry_run: would send SMS: %s" % url return
Python
0.998421
@@ -93,16 +93,17 @@ e%0A%0Afrom +. alerter @@ -355,17 +355,17 @@ print - +( %22Request @@ -424,16 +424,17 @@ lerter.%22 +) %0A @@ -443,17 +443,17 @@ print - +( %22Try: pi @@ -482,16 +482,17 @@ nts.txt%22 +) %0A @@ -1179,17 +1179,17 @@ print - +( %22warning @@ -1229,16 +1229,17 @@ 1 chars%22 +) %0A @@ -2408,33 +2408,33 @@ print - +( %22Warning! Trunca @@ -2456,32 +2456,33 @@ e to 160 chars.%22 +) %0A @@ -3215,17 +3215,17 @@ print - +( %22Warning @@ -3263,16 +3263,17 @@ chars.%22 +) %0A @@ -3936,17 +3936,17 @@ print - +( %22Unable @@ -3965,16 +3965,17 @@ %25s%22 %25 s +) %0A @@ -3992,17 +3992,17 @@ print - +( %22URL: %25s @@ -4030,16 +4030,17 @@ params) +) %0A @@ -4131,17 +4131,17 @@ print - +( %22SMS sen @@ -4152,16 +4152,17 @@ failed%22 +) %0A @@ -4175,18 +4175,19 @@ print - e +(e) %0A @@ -4200,20 +4200,21 @@ print - +( url +) %0A @@ -4227,23 +4227,24 @@ print - +( params +) %0A @@ -4306,17 +4306,17 @@ print - +( %22dry_run @@ -4342,16 +4342,17 @@ s%22 %25 url +) %0A
8555fc56b72dc86f266055da4b903cda7986654b
Update utils.py to prevent downcasting
emdp/utils.py
emdp/utils.py
import numpy as np # 1D utilities. def convert_int_rep_to_onehot(state, vector_size): s = np.zeros(vector_size) s[state] = 1 return s def convert_onehot_to_int(state): if type(state) is not np.ndarray: state = np.array(state) return state.argmax().astype(np.int8) # # def xy_to_flatten_state(state, size): # """Flatten state (x,y) into a one hot vector of size""" # idx = self.size * state[0] + state[1] # one_hot = np.zeros(self.size * self.size) # one_hot[idx] = 1 # return one_hot # # def unflatten_state(self, onehot): # onehot = onehot.reshape(self.size, self.size) # x = onehot.argmax(0).max() # y = onehot.argmax(1).max() # return (x, y) # def step(self, action): # """action must be the index of an action""" # # get the vector representing the next state probabilities: # current_state_idx = np.argmax(self.current_state) # next_state_probs = self.P[current_state_idx, action] # # sample the next state # sampled_next_state = np.random.choice(np.arange(self.P.shape[0]), p=next_state_probs) # # observe the reward # reward = self.r[current_state_idx, action] # self.current_state = self.convert_int_rep_to_onehot(sampled_next_state) # # if reward > 0 :print(reward, current_state_idx, action) # return self.current_state, reward, sampled_next_state == self.P.shape[0] - 1, {}
Python
0
@@ -275,22 +275,13 @@ x(). -astype(np.int8 +item( )%0A#%0A
76aa0d680f85298ca66de7bbcd0dbdc2342c9955
Update Vikidia versions
pywikibot/families/vikidia_family.py
pywikibot/families/vikidia_family.py
# -*- coding: utf-8 -*- """Family module for Vikidia.""" from __future__ import absolute_import, unicode_literals __version__ = '$Id$' from pywikibot import family class Family(family.SubdomainFamily): """Family class for Vikidia.""" name = 'vikidia' domain = 'vikidia.org' codes = ['ca', 'en', 'es', 'eu', 'fr', 'it', 'ru', 'scn'] def protocol(self, code): """Return https as the protocol for this family.""" return "https" def ignore_certificate_error(self, code): """Ignore certificate errors.""" return True # has self-signed certificate for a different domain.
Python
0
@@ -305,16 +305,22 @@ = %5B'ca', + 'de', 'en', ' @@ -356,16 +356,114 @@ 'scn'%5D%0A%0A + # Sites we want to edit but not count as real languages%0A test_codes = %5B'central', 'test'%5D%0A%0A def
5d3b2a794cee8f440209636359dc00cff3180bb9
Use comment style variable annotations for python 3.5 support.
aerospike_helpers/expressions/resources.py
aerospike_helpers/expressions/resources.py
''' Resources used by all expressions. ''' from itertools import chain from typing import List, Optional, Tuple, Union, Dict, Any import aerospike from aerospike_helpers import cdt_ctx class _Keys: VALUE_TYPE_KEY = "value_type" BIN_KEY = "bin" RETURN_TYPE_KEY = "return_type" CTX_KEY = "ctx" VALUE_KEY = "val" LIST_POLICY_KEY = "list_policy" MAP_POLICY_KEY = "map_policy" LIST_ORDER_KEY = "list_order" REGEX_OPTIONS_KEY = "regex_options" class _ExprOp: EQ = 1 NE = 2 GT = 3 GE = 4 LT = 5 LE = 6 CMP_REGEX = 7 CMP_GEO = 8 AND = 16 OR = 17 NOT = 18 META_DIGEST_MOD = 64 META_DEVICE_SIZE = 65 META_LAST_UPDATE_TIME = 66 META_VOID_TIME = 67 META_TTL = 68 META_SET_NAME = 69 META_KEY_EXISTS = 70 META_SINCE_UPDATE_TIME = 71 META_IS_TOMBSTONE = 72 REC_KEY = 80 BIN = 81 BIN_TYPE = 82 BIN_EXISTS = 83 CALL = 127 VAL = 128 PK = 129 INT = 130 UINT = 131 FLOAT = 132 BOOL = 133 STR = 134 BYTES = 135 RAWSTR = 136 RTYPE = 137 NIL = 138 # virtual ops _AS_EXP_CODE_CALL_VOP_START = 139 _AS_EXP_CODE_CDT_LIST_CRMOD = 140 _AS_EXP_CODE_CDT_LIST_MOD = 141 _AS_EXP_CODE_CDT_MAP_CRMOD = 142 _AS_EXP_CODE_CDT_MAP_CR = 143 _AS_EXP_CODE_CDT_MAP_MOD = 144 _AS_EXP_CODE_END_OF_VA_ARGS = 150 _TRUE = 151 _FALSE = 152 _AS_EXP_BIT_FLAGS = 153 class ResultType: """ Flags used to indicate expression value_type. """ BOOLEAN = 1 INTEGER = 2 STRING = 3 LIST = 4 MAP = 5 BLOB = 6 FLOAT = 7 GEOJSON = 8 HLL = 9 class _AtomExpr: def _op(self): raise NotImplementedError def compile(self): raise NotImplementedError TypeResultType = Optional[int] TypeFixedEle = Union[int, float, str, bytes, dict] TypeFixed = Optional[Dict[str, TypeFixedEle]] TypeCompiledOp = Tuple[int, TypeResultType, TypeFixed, int] TypeExpression = List[TypeCompiledOp] TypeChild = Union[int, float, str, bytes, _AtomExpr] TypeChildren = Tuple[TypeChild, ...] class _BaseExpr(_AtomExpr): _op: int = 0 _rt: TypeResultType = None _fixed: TypeFixed = None _children: TypeChildren = () def _get_op(self) -> TypeCompiledOp: return (self._op, self._rt, self._fixed, len(self._children)) def _vop(self, v) -> TypeCompiledOp: return ( 0, None, {_Keys.VALUE_KEY: v}, 0, ) def compile(self) -> TypeExpression: expression: TypeExpression = [self._get_op()] work = chain(self._children) while True: try: item = next(work) except StopIteration: break if isinstance(item, _BaseExpr): expression.append(item._get_op()) work = chain(item._children, work) else: # Should be a str, bin, int, float, etc. expression.append(self._vop(item)) return expression class _GenericExpr(_BaseExpr): def __init__(self, op: _ExprOp, rt: TypeResultType, fixed: TypeFixed): self._op = op self._rt = rt self._fixed = fixed
Python
0
@@ -2152,25 +2152,54 @@ _op -: int = 0%0A _rt + = 0%0A # type: int%0A _rt = None%0A # type : Ty @@ -2210,16 +2210,27 @@ sultType +%0A _fixed = None%0A @@ -2233,22 +2233,22 @@ one%0A -_fixed +# type : TypeFi @@ -2246,31 +2246,24 @@ e: TypeFixed - = None %0A _childr @@ -2264,16 +2264,32 @@ children + = ()%0A # type : TypeCh @@ -2294,21 +2294,16 @@ Children - = () %0A%0A de @@ -2622,24 +2622,8 @@ sion -: TypeExpression = %5B @@ -2638,16 +2638,47 @@ t_op()%5D%0A + # type: TypeExpression%0A
f1c4b6c9a4bc5a34c6b63b0b96e170f7d2b7fa17
Move comment for min_conflicts algorithm
ai_graph_color/algorithms/min_conflicts.py
ai_graph_color/algorithms/min_conflicts.py
""" Color a graph using min-conflicts: First generate a random coloring for the graph. Until there are no conflicts in the graph, choose a random node in the graph, and change it to have the color which reduces the number of conflicts in the graph the most. :param colors: the number of colors to color the graph with :type colors: int """ import random params = {} def run(graph, setup, params): num_colors = params['colors'] colors = range(num_colors) setup.logger.debug( 'Trying to color min-conflicts with %s colors', num_colors ) coloring = [random.choice(colors) for _ in graph] setup.logger.debug('Initial coloring: %s', coloring) num_conflicts = num_conflicts_graph(graph, coloring) setup.logger.debug('Initial conflicts: %s', num_conflicts) if setup.counter.increment(): yield num_conflicts while num_conflicts > 0: index = random.randint(0, len(graph) - 1) setup.logger.debug('Selected node: %s', index) initial_conflicts = num_conflicts_node(graph, index, coloring) if setup.counter.increment(): yield num_conflicts initial_color = coloring[index] min_conflicts = initial_conflicts min_conflicts_value = initial_color colors = range(num_colors) colors.remove(initial_color) # don't recheck the same color for color in colors: coloring[index] = color conflicts = num_conflicts_node(graph, index, coloring) if setup.counter.increment(): yield num_conflicts if conflicts < min_conflicts: min_conflicts = conflicts min_conflicts_value = color coloring[index] = min_conflicts_value setup.logger.debug('Updated coloring: %s', coloring) num_conflicts -= initial_conflicts - min_conflicts setup.logger.debug('Updated conflicts: %s', num_conflicts) yield num_conflicts def num_conflicts_graph(graph, coloring): """ Compute the number of conflicting edges on a graph for a given coloring. :param graph: the graph, in adjacency list form :type graph: list[list[int]] :param coloring: the coloring of the graph :type coloring: list[int] :rtype: int :return: the number of conflicting edges for the coloring of the given graph. """ conflicts = 0 for from_index, connections in enumerate(graph): for to_index in connections: if (from_index < to_index and coloring[to_index] == coloring[from_index]): conflicts += 1 return conflicts def num_conflicts_node(graph, index, coloring): """ Compute the number of conflicting edges coming from a particular node on a graph with a particular coloring. :param graph: a graph in adjacency list form :type graph: list[list[int]] :param index: the index of the node in the graph :type index: int :param coloring: the coloring of the graph :type coloring: list[int] :return: the number of conflicting edges coming from the given node for the given coloring """ conflicts = 0 for to_index in graph[index]: if coloring[index] == coloring[to_index]: conflicts += 1 return conflicts
Python
0
@@ -1,12 +1,80 @@ -%22%22%22%0A +import random%0A%0Aparams = %7B%7D%0A%0A%0Adef run(graph, setup, params):%0A %22%22%22%0A Color a @@ -101,16 +101,20 @@ licts:%0A%0A + First ge @@ -153,16 +153,20 @@ graph.%0A + Until th @@ -204,16 +204,20 @@ ph,%0A + + choose a @@ -279,16 +279,20 @@ lor%0A + + which re @@ -345,16 +345,20 @@ most.%0A%0A + :param c @@ -409,16 +409,20 @@ ph with%0A + :type co @@ -435,72 +435,16 @@ int%0A + %22%22%22%0A -%0Aimport random%0A%0Aparams = %7B%7D%0A%0A%0Adef run(graph, setup, params): %0A
7f14a3a1babf102a090a7541038e88337ef14c46
Remove unused import from test
tests/functional/test_customer_account.py
tests/functional/test_customer_account.py
from django.core.urlresolvers import reverse from oscar.test.testcases import WebTestCase from oscar.test.factories import create_order from oscar_support.models import Ticket from oscar_support.defaults import SUPPORT_INITIAL_STATUS from tests import factories class TestACustomer(WebTestCase): is_anonymous = False def setUp(self): super(TestACustomer, self).setUp() self.status = factories.TicketStatusFactory( name=SUPPORT_INITIAL_STATUS ) self.type = factories.TicketTypeFactory() self.subject = "this is the subject line" self.message_text = "this is a new message text" def test_can_create_a_new_ticket(self): page = self.get(reverse('support:customer-ticket-create')) ticket_form = page.forms['create-ticket-form'] ticket_form['type'] = self.type.uuid ticket_form['subject'] = self.subject ticket_form['body'] = self.message_text page = ticket_form.submit() user_tickets = Ticket.objects.filter(requester=self.user) self.assertEquals(user_tickets.count(), 1) ticket = user_tickets[0] self.assertEquals(ticket.status, self.status) self.assertEquals(ticket.type, self.type) self.assertEquals(ticket.subject, self.subject) self.assertEquals(ticket.body, self.message_text) self.assertEquals(ticket.number, '1') self.assertEquals(ticket.subticket_id, 0) self.assertEquals(ticket.relatedorders.count(), 0) def test_can_create_a_ticket_with_related_order(self): page = self.get(reverse('support:customer-ticket-create')) ticket_form = page.forms['create-ticket-form'] ticket_form['type'] = self.type.uuid ticket_form['subject'] = self.subject ticket_form['body'] = self.message_text page = ticket_form.submit() user_tickets = Ticket.objects.filter(requester=self.user) self.assertEquals(user_tickets.count(), 1) ticket = user_tickets[0] self.assertEquals(ticket.status, self.status) self.assertEquals(ticket.type, self.type) self.assertEquals(ticket.subject, self.subject) self.assertEquals(ticket.body, self.message_text) self.assertEquals(ticket.number, '1') self.assertEquals(ticket.subticket_id, 0) def test_can_add_message_to_a_ticket(self): ticket = Ticket.objects.create( requester=self.user, status=self.status, type=self.type, subject='This is the subject line', body="I have a question about something", ) self.assertEquals(ticket.messages.count(), 0) page = self.get( reverse( 'support:customer-ticket-update', kwargs={'pk': ticket.uuid} ) ) self.assertContains(page, ticket.body) message_form = page.forms['add-message-form'] message_form['message_text'] = 'this is some additional message' message_form.submit() ticket = Ticket.objects.get(uuid=ticket.uuid) self.assertEquals(ticket.messages.count(), 1)
Python
0
@@ -87,54 +87,8 @@ Case -%0Afrom oscar.test.factories import create_order %0A%0Afr
df6d39ba6de91c9c67322395a14dffd613507493
print more
shcmd/proc.py
shcmd/proc.py
# -*- coding: utf8 -*- import contextlib import io import logging import subprocess import threading import time from .errors import ShCmdError logger = logging.getLogger(__name__) LINE_CHUNK_SIZE = 1024 def kill_proc(proc, cmd, started_at): """kill proc if started returns True if proc is killed actually """ if proc.returncode is None: proc.kill() class Proc(object): """ Simple Wrapper around the built-in subprocess module use threading.Timer to add timeout option easy interface for get streamed output of stdout """ codec = "utf8" def __init__(self, cmd, cwd, env, timeout): """ :param cmd: the command :param cwd: the command should be running under `cwd` dir :param env: the environment variable :param timeout: the command should return in `timeout` seconds Usage:: >>> p = Proc("ls", "/", timeout=1) >>> p.block() >>> p.ok True >>> type(p.stdout) <class 'str'> """ self._cmd = cmd self._cwd = cwd self._env = env self._timeout = timeout self._return_code = self._stdout = self._stderr = None @property def cmd(self): """the proc's command.""" return self._cmd[:] @property def cwd(self): """the proc's execuation dir.""" return self._cwd @property def env(self): """the proc's environment setting.""" return self._env.copy() @property def timeout(self): """the proc's timeout setting.""" return self._timeout @property def stdout(self): """proc's stdout.""" return self._stdout.decode(self.codec) @property def stderr(self): """proc's stderr.""" return self._stderr.decode(self.codec) @property def return_code(self): """proc's return_code""" return self._return_code @property def content(self): """the output gathered in stdout in bytes format""" return self._stdout @property def ok(self): """`True` if proc's return_code is 0""" return self.return_code == 0 def raise_for_error(self): """raise `ShCmdError` if the proc's return_code is not 0""" if not self.ok: tip = "running {0} @<{1}> error, return code {2}".format( " ".join(self.cmd), self.cwd, self.return_code ) logger.error("{0}\nstdout:{1}\nstderr:{2}\n".format( tip, self.stdout, self.stderr )) raise ShCmdError(tip) @contextlib.contextmanager def _stream(self): """execute subprocess with timeout Usage:: >>> with cmd_proc.run_with_timeout() as cmd_proc: ... stdout, stderr = cmd_proc.communicate() ... >>> assert cmd_proc.proc.return_code == 0, "proc exec failed" """ timer = None try: proc = subprocess.Popen( self.cmd, cwd=self.cwd, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) timer = threading.Timer( self.timeout, kill_proc, [proc, self.cmd, time.time()] ) timer.start() yield proc finally: if timer: timer.cancel() def iter_lines(self): """yields stdout text, line by line.""" remain = "" for data in self.iter_content(LINE_CHUNK_SIZE): print(repr(data).center(50, "x")) line_break_found = data[-1] in (b"\n", b"\r") lines = data.decode(self.codec).splitlines() lines[0] = remain + lines[0] if not line_break_found: remain = lines.pop() for line in lines: yield line if remain: yield remain def iter_content(self, chunk_size=1): """ yields stdout data, chunk by chunk :param chunk_size: size of each chunk (in bytes) """ if self.return_code is not None: stdout = io.BytesIO(self._stdout) data = stdout.read(chunk_size) while data: yield data data = stdout.read(chunk_size) else: data = b'' started_at = time.time() with self._stream() as proc: while proc.poll() is None: chunk = proc.stdout.read(chunk_size) yield chunk data += chunk if proc.returncode == -9: raise subprocess.TimeoutExpired( proc.args, time.time() - started_at ) chunk = proc.stdout.read(chunk_size) while chunk: yield chunk data += chunk chunk = proc.stdout.read(chunk_size) self._return_code = proc.returncode self._stderr = proc.stderr.read() self._stdout = data def block(self): """blocked executation.""" if self._return_code is None: proc = subprocess.Popen( self.cmd, cwd=self.cwd, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) self._stdout, self._stderr = proc.communicate(timeout=self.timeout) self._return_code = proc.returncode
Python
0.000003
@@ -4603,32 +4603,94 @@ ead(chunk_size)%0A + print(%22chunk is %7B0%7D%22.format(repr(chunk)))%0A @@ -5024,32 +5024,104 @@ yield chunk%0A + print(%22end block chunk is %7B0%7D%22.format(repr(chunk)))%0A
abfd8fbd858e79793988c6b29941e3af81085e3a
Fix test_get_zonecode
tests/integration/modules/mac_timezone.py
tests/integration/modules/mac_timezone.py
# -*- coding: utf-8 -*- ''' Integration tests for mac_timezone ''' # Import python libs from __future__ import absolute_import from datetime import datetime # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath, destructiveTest ensure_in_syspath('../../') # Import salt libs import integration import salt.utils USE_NETWORK_TIME = False TIME_SERVER = 'time.apple.com' TIME_ZONE = '' CURRENT_DATE = '' CURRENT_TIME = '' class MacTimezoneModuleTest(integration.ModuleCase): ''' Validate the mac_timezone module ''' def setUp(self): ''' Get current settings ''' if not salt.utils.is_darwin(): self.skipTest('Test only available on Mac OS X') if not salt.utils.which('systemsetup'): self.skipTest('Test requires systemsetup binary') if salt.utils.get_uid(salt.utils.get_user()) != 0: self.skipTest('Test requires root') USE_NETWORK_TIME = self.run_function('timezone.get_using_network_time') TIME_SERVER = self.run_function('timezone.get_time_server') TIME_ZONE = self.run_function('timezone.get_zone') CURRENT_DATE = self.run_function('timezone.get_date') CURRENT_TIME = self.run_function('timezone.get_time') self.run_function('timezone.set_using_network_time', [False]) def tearDown(self): ''' Reset to original settings ''' self.run_function('timezone.set_time_server', [TIME_SERVER]) self.run_function('timezone.set_using_network_time', [USE_NETWORK_TIME]) self.run_function('timezone.set_zone', [TIME_ZONE]) if not USE_NETWORK_TIME: self.run_function('timezone.set_date', [CURRENT_DATE]) self.run_function('timezone.set_time', [CURRENT_TIME]) @destructiveTest def test_get_set_date(self): ''' Test timezone.get_date Test timezone.set_date ''' # Correct Functionality self.assertTrue(self.run_function('timezone.set_date', ['2/20/2011'])) self.assertEqual(self.run_function('timezone.get_date'), '2/20/2011') # Test bad date format self.assertEqual( self.run_function('timezone.set_date', ['13/12/2014']), 'ERROR executing \'timezone.set_date\': ' 'Invalid Date/Time Format: 13/12/2014' ) def test_get_time(self): ''' Test timezone.get_time ''' text_time = self.run_function('timezone.get_time') self.assertNotEqual(text_time, 'Invalid Timestamp') obj_date = datetime.datetime.strptime(text_time, '%H:%M:%S') self.assertIsInstance(obj_date, datetime.date) @destructiveTest def test_set_time(self): ''' Test timezone.set_time ''' # Correct Functionality self.assertTrue(self.run_function('timezone.set_time', ['3:14'])) # Test bad time format self.assertEqual( self.run_function('timezone.set_time', ['3:71']), 'ERROR executing \'timezone.set_time\': ' 'Invalid Date/Time Format: 3:71') @destructiveTest def test_get_set_zone(self): ''' Test timezone.get_zone Test timezone.set_zone ''' # Correct Functionality self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertEqual(self.run_function('timezone.get_zone'), 'Pacific/Wake') # Test bad time zone self.assertEqual( self.run_function('timezone.set_zone', ['spongebob']), 'ERROR executing \'timezone.set_zone\': ' 'Invalid Timezone: spongebob') @destructiveTest def test_get_offset(self): ''' Test timezone.get_offset ''' self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertEqual(self.run_function('timezone.get_offset'), '+1200') self.assertTrue(self.run_function('timezone.set_zone', ['America/Denver'])) self.assertEqual(self.run_function('timezone.get_offset'), '-0600') @destructiveTest def test_get_zonecode(self): ''' Test timezone.get_zonecode ''' self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertEqual(self.run_function('timezone.get_zonecode'), 'WAKT') self.assertTrue(self.run_function('timezone.set_zone', ['America/Denver'])) self.assertEqual(self.run_function('timezone.get_zonecode'), 'MDT') def test_list_zones(self): ''' Test timezone.list_zones ''' ret = self.run_function('timezone.list_zones') self.assertIn('America/Denver', ret) self.assertIn('Asia/Hong_Kong', ret) self.assertIn('Australia/Sydney', ret) self.assertIn('Europe/London', ret) def test_zone_compare(self): ''' Test timezone.zone_compare ''' self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertTrue(self.run_function('timezone.zone_compare', ['Pacific/Wake'])) self.assertFalse(self.run_function('timezone.zone_compare', ['America/Denver'])) @destructiveTest def test_get_set_using_network_time(self): ''' Test timezone.get_using_network_time Test timezone.set_using_network_time ''' self.assertTrue(self.run_function('timezone.set_using_network_time', [True])) self.assertTrue(self.run_function('timezone.get_using_network_time')) self.assertTrue(self.run_function('timezone.set_using_network_time', [False])) self.assertFalse(self.run_function('timezone.get_using_network_time')) @destructiveTest def test_get_set_time_server(self): ''' Test timezone.get_time_server Test timezone.set_time_server ''' self.assertTrue(self.run_function('timezone.set_time_server', ['time.spongebob.com'])) self.assertEqual(self.run_function('timezone.get_time_server'), 'time.spongebob.com') if __name__ == '__main__': from integration import run_tests run_tests(MacTimezoneModuleTest)
Python
0.00007
@@ -125,22 +125,8 @@ ort%0A -from datetime impo @@ -4137,38 +4137,38 @@ %5B'America/ -Denver +Panama '%5D))%0A sel @@ -4230,9 +4230,9 @@ '-0 -6 +5 00') @@ -4658,30 +4658,30 @@ %5B'America/ -Denver +Panama '%5D))%0A
213c400c033c83412127c4988e502e8248bb4b57
Fix timezone test
tests/integration/modules/mac_timezone.py
tests/integration/modules/mac_timezone.py
# -*- coding: utf-8 -*- ''' Integration tests for mac_timezone ''' # Import python libs from __future__ import absolute_import from datetime import datetime # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs import integration import salt.utils USE_NETWORK_TIME = False TIME_SERVER = 'time.apple.com' TIME_ZONE = '' CURRENT_DATE = '' CURRENT_TIME = '' class MacTimezoneModuleTest(integration.ModuleCase): ''' Validate the mac_timezone module ''' def setUp(self): ''' Get current settings ''' if not salt.utils.is_darwin(): self.skipTest('Test only available on Mac OS X') if not salt.utils.which('systemsetup'): self.skipTest('Test requires systemsetup binary') if salt.utils.get_uid(salt.utils.get_user()) != 0: self.skipTest('Test requires root') USE_NETWORK_TIME = self.run_function('timezone.get_using_network_time') TIME_SERVER = self.run_function('timezone.get_time_server') TIME_ZONE = self.run_function('timezone.get_zone') CURRENT_DATE = self.run_function('timezone.get_date') CURRENT_TIME = self.run_function('timezone.get_time') self.run_function('timezone.set_using_network_time', [False]) def tearDown(self): ''' Reset to original settings ''' self.run_function('timezone.set_time_server', [TIME_SERVER]) self.run_function('timezone.set_using_network_time', [USE_NETWORK_TIME]) self.run_function('timezone.set_zone', [TIME_ZONE]) if not USE_NETWORK_TIME: self.run_function('timezone.set_date', [CURRENT_DATE]) self.run_function('timezone.set_time', [CURRENT_TIME]) def test_get_set_date(self): ''' Test timezone.get_date Test timezone.set_date ''' # Correct Functionality self.assertTrue(self.run_function('timezone.set_date', ['2/20/2011'])) self.assertEqual(self.run_function('timezone.get_date'), '2/20/2011') # Test bad date format self.assertEqual( self.run_function('timezone.set_date', ['13/12/2014']), 'ERROR executing \'timezone.set_date\': ' 'Invalid Date/Time Format: 13/12/2014' ) def test_get_set_time(self): ''' Test timezone.get_time Test timezone.set_time ''' # Correct Functionality self.assertTrue(self.run_function('timezone.set_time', ['3:14'])) new_time = self.run_function('timezone.get_time') new_time = datetime.strptime(new_time, '%H:%M:%S').strftime('%H:%M') self.assertEqual(new_time, '03:14') # Test bad time format self.assertEqual( self.run_function('timezone.set_time', ['"3:71"']), 'ERROR executing \'timezone.set_time\': ' 'Invalid Date/Time Format: 3:71' ) def test_get_set_zone(self): ''' Test timezone.get_zone Test timezone.set_zone ''' # Correct Functionality self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertEqual(self.run_function('timezone.get_zone'), 'Pacific/Wake') # Test bad time zone self.assertEqual( self.run_function('timezone.set_zone', ['spongebob']), 'ERROR executing \'timezone.set_time\': ' 'Invalid Timezone: spongebob') def test_get_offset(self): ''' Test timezone.get_offset ''' self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertEqual(self.run_function('timezone.get_offset'), '+1200') def test_get_zonecode(self): ''' Test timezone.get_zonecode ''' self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertEqual(self.run_function('timezone.get_zonecode'), 'WAKT') def test_list_zones(self): ''' Test timezone.list_zones ''' ret = self.run_function('timezone.list_zones') self.assertIn('America/Denver', ret) self.assertIn('Asia/Hong_Kong', ret) self.assertIn('Australia/Sydney', ret) self.assertIn('Europe/London', ret) def test_zone_compare(self): ''' Test timezone.zone_compare ''' self.assertTrue(self.run_function('timezone.set_zone', ['Pacific/Wake'])) self.assertTrue(self.run_function('timezone.zone_compare', ['Pacific/Wake'])) self.assertFalse(self.run_function('timezone.zone_compare', ['America/Denver'])) def test_get_set_using_network_time(self): ''' Test timezone.get_using_network_time Test timezone.set_using_network_time ''' self.assertTrue(self.run_function('timezone.set_using_network_time', [True])) self.assertTrue(self.run_function('timezone.get_using_network_time')) self.assertTrue(self.run_function('timezone.set_using_network_time', [False])) self.assertFalse(self.run_function('timezone.get_using_network_time')) def test_get_set_time_server(self): ''' Test timezone.get_time_server Test timezone.set_time_server ''' self.assertTrue(self.run_function('timezone.set_time_server', ['time.spongebob.com'])) self.assertEqual(self.run_function('timezone.get_time_server'), 'time.spongebob.com') if __name__ == '__main__': from integration import run_tests run_tests(MacTimezoneModuleTest)
Python
0.004105
@@ -3490,35 +3490,35 @@ %5C'timezone.set_ -tim +zon e%5C': '%0A
35e45049e269b46940a812c2f70cafb90439e0d8
use a ruby gem that doesn't have dependencies
tests/integration/modules/gem.py
tests/integration/modules/gem.py
# -*- coding: utf-8 -*- ''' Integration tests for Ruby Gem module ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from salttesting import skipIf from salttesting.helpers import ensure_in_syspath, destructiveTest ensure_in_syspath('../../') # Import salt libs import integration import salt.utils import salt.utils.http GEM = 'tidy' GEM_VER = '1.1.2' OLD_GEM = 'test' OLD_VERSION = '0.2.0' NEW_VERSION = '1.0.0' GEM_LIST = [GEM, OLD_GEM] def check_status(): ''' Check the status of the rubygems source ''' ret = salt.utils.http.query('https://rubygems.org', status=True) return ret['status'] == 200 @destructiveTest @skipIf(not salt.utils.which('gem'), 'Gem is not available') @skipIf(not check_status(), 'External source \'https://rubygems.org\' is not available') class GemModuleTest(integration.ModuleCase): ''' Validate gem module ''' def test_install_uninstall(self): ''' gem.install gem.uninstall ''' # Remove gem if it is already installed if self.run_function('gem.list', [GEM]): self.run_function('gem.uninstall', [GEM]) self.run_function('gem.install', [GEM]) gem_list = self.run_function('gem.list', [GEM]) self.assertIn(GEM, gem_list) self.run_function('gem.uninstall', [GEM]) self.assertFalse(self.run_function('gem.list', [GEM])) def test_install_version(self): ''' gem.install rake version=11.1.2 ''' # Remove gem if it is already installed if self.run_function('gem.list', [GEM]): self.run_function('gem.uninstall', [GEM]) self.run_function('gem.install', [GEM], version=GEM_VER) gem_list = self.run_function('gem.list', [GEM]) self.assertIn(GEM, gem_list) self.assertIn(GEM_VER, gem_list[GEM]) self.run_function('gem.uninstall', [GEM]) self.assertFalse(self.run_function('gem.list', [GEM])) def test_list(self): ''' gem.list ''' self.run_function('gem.install', [' '.join(GEM_LIST)]) all_ret = self.run_function('gem.list') for gem in GEM_LIST: self.assertIn(gem, all_ret) single_ret = self.run_function('gem.list', [GEM]) self.assertIn(GEM, single_ret) self.run_function('gem.uninstall', [' '.join(GEM_LIST)]) def test_list_upgrades(self): ''' gem.list_upgrades ''' # install outdated gem self.run_function('gem.install', [OLD_GEM], version=OLD_VERSION) ret = self.run_function('gem.list_upgrades') self.assertIn(OLD_GEM, ret) self.run_function('gem.uninstall', [OLD_GEM]) def test_sources_add_remove(self): ''' gem.sources_add gem.sources_remove ''' source = 'http://gems.github.com' self.run_function('gem.sources_add', [source]) sources_list = self.run_function('gem.sources_list') self.assertIn(source, sources_list) self.run_function('gem.sources_remove', [source]) sources_list = self.run_function('gem.sources_list') self.assertNotIn(source, sources_list) def test_update(self): ''' gem.update ''' # Remove gem if it is already installed if self.run_function('gem.list', [OLD_GEM]): self.run_function('gem.uninstall', [OLD_GEM]) self.run_function('gem.install', [OLD_GEM], version=OLD_VERSION) gem_list = self.run_function('gem.list', [OLD_GEM]) self.assertEqual({OLD_GEM: [OLD_VERSION]}, gem_list) self.run_function('gem.update', [OLD_GEM]) gem_list = self.run_function('gem.list', [OLD_GEM]) self.assertEqual({OLD_GEM: [NEW_VERSION, OLD_VERSION]}, gem_list) self.run_function('gem.uninstall', [OLD_GEM]) self.assertFalse(self.run_function('gem.list', [OLD_GEM])) def test_update_system(self): ''' gem.update_system ''' ret = self.run_function('gem.update_system') self.assertTrue(ret) if __name__ == '__main__': from integration import run_tests run_tests(GemModuleTest)
Python
0.000001
@@ -401,20 +401,21 @@ _GEM = ' -test +brass '%0AOLD_VE @@ -427,11 +427,11 @@ = ' -0.2 +1.0 .0'%0A @@ -447,19 +447,19 @@ ON = '1. -0.0 +2.1 '%0AGEM_LI
5138db4353edf7414c79ca8e1e42c73b35313b15
Remove various now unused interfaces.
morepath/interfaces.py
morepath/interfaces.py
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod class Interface(object): __meta__ = ABCMeta class IConsumer(Interface): """A consumer consumes steps in a stack to find an object. """ @abstractmethod def __call__(self, obj, stack, lookup): """Returns a boolean meaning that some stack has been consumed, an object and the rest of unconsumed stack """ class IResource(Interface): pass class IResponse(Interface): pass class IResponseFactory(Interface): """When called, a Response instance is returned. """ @abstractmethod def __call__(self): """Returns a Response instance.""" class ITraject(Interface): pass class IInverse(Interface): """Marker interface to hook in inverse component in a traject.""" class IRoot(Interface): """Mark this object as the root. """ class ILookup(Interface): """Mark this model as an model that can change the lookup. """ class IApp(Interface): """An application.""" # XXX fill in details class IModelBase(Interface): """Mark this object as a base of a model. """ class IPath(Interface): """Get the path for a model.""" class ILink(Interface): """Get the hyperlink for a model.""" class IConfigAction(Interface): """A configuration item. """ @abstractmethod def discriminator(self): """Returns an immutable that uniquely identifies this config. Used for configuration conflict detection. """ @abstractmethod def prepare(self, obj): """Prepare action for configuration. obj - the object being registered """ @abstractmethod def perform(self, obj): """Register whatever is being configured. obj - the object being registered """ class ConfigError(Exception): """Raised when configuration is bad """ class ResolveError(Exception): """Raised when path cannot be resolved """ class ModelError(ResolveError): """Raised when a model cannot be resolved """ class ResourceError(ResolveError): """Raised when a resource cannot be resolved """ class TrajectError(Exception): """Raised when path supplied to traject is not allowed. """ class LinkError(Exception): """Raised when a link cannot be made. """
Python
0
@@ -108,16 +108,18 @@ CMeta%0A%0A%0A +# class IC @@ -130,32 +130,34 @@ mer(Interface):%0A +# %22%22%22A consume @@ -203,16 +203,18 @@ object.%0A +# %22%22%22%0A @@ -206,32 +206,34 @@ ect.%0A# %22%22%22%0A%0A +# @abstractmet @@ -228,32 +228,34 @@ @abstractmethod%0A +# def __call__ @@ -282,16 +282,18 @@ ookup):%0A +# @@ -356,16 +356,18 @@ nsumed,%0A +# @@ -413,880 +413,168 @@ ack%0A - %22%22%22%0A%0A%0Aclass IResource(Interface):%0A pass%0A%0A%0Aclass IResponse(Interface):%0A pass%0A%0A%0Aclass IResponseFactory(Interface):%0A %22%22%22When called, a Response instance is returned.%0A %22%22%22%0A @abstractmethod%0A def __call__(self):%0A %22%22%22Returns a Response instance.%22%22%22%0A%0A%0Aclass ITraject(Interface):%0A pass%0A%0A%0Aclass IInverse(Interface):%0A %22%22%22Marker interface to hook in inverse component in a traject.%22%22%22%0A%0A%0Aclass IRoot(Interface):%0A %22%22%22Mark this object as the root.%0A %22%22%22%0A%0A%0Aclass ILookup(Interface):%0A %22%22%22Mark this model as an model that can change the lookup.%0A %22%22%22%0A%0A%0Aclass IApp(Interface):%0A %22%22%22An application.%22%22%22%0A # XXX fill in details%0A%0A%0Aclass IModelBase(Interface):%0A %22%22%22Mark this object as a base of a model.%0A %22%22%22%0A%0A%0Aclass IPath(Interface):%0A %22%22%22Get the path for a model.%22%22%22%0A%0A%0Aclass ILink(Interface):%0A %22%22%22Get the hyperlink for a model.%22%22%22 +# %22%22%22%0A%0A%0Aclass IRoot(Interface):%0A %22%22%22Mark this object as the root.%0A %22%22%22%0A%0Aclass IApp(Interface):%0A %22%22%22An application.%22%22%22%0A # XXX fill in details %0A%0A%0Ac
d7f17d7d8592f016d8c46ac530338e11b366896d
make randomizer standalone
mpf/core/randomizer.py
mpf/core/randomizer.py
from uuid import uuid4 import random class Randomizer(object): def __init__(self, machine, items, memory='player'): self.force_different = True self.force_all = False self.disable_random = False # self.loop - property which sets force_all=True if loop==False self.items = list() self._loop = True self._machine = machine self._uuid = uuid4() self._data = None self._player_memory = True assert(isinstance(items, list) or isinstance(items, tuple)) for i in items: if hasattr(i, '__iter__'): this_item = i[0] this_weight = int(i[1]) else: this_item = i this_weight = 1 self.items.append((this_item, this_weight)) if memory == 'player': self._player_memory = True elif memory == 'machine': self._player_memory = False self._data = dict() self._init_data(self._data) else: raise ValueError("Memory should be 'machine' or 'player") def __iter__(self): return self def __next__(self): if self.disable_random: return self._next_not_random() potential_nexts = list() if self.force_all: potential_nexts = [ x for x in self.items if x[0] not in self.data['items_sent']] elif self.force_different: potential_nexts = [ x for x in self.items if x[0] is not self.data['current_item']] if not potential_nexts: if not self._loop: raise StopIteration self.data['items_sent'] = set() if self.force_different: potential_nexts = [x for x in self.items if x[0] is not ( self.data['current_item'])] else: potential_nexts = [x for x in self.items] self.data['current_item'] = self.pick_weighted_random(potential_nexts) self.data['items_sent'].add(self.data['current_item']) return self.data['current_item'] @property def data(self): if self._player_memory: try: if not self._machine.game.player[self._uuid]: self._machine.game.player[self._uuid] = dict() self._init_data(self._machine.game.player[self._uuid]) except AttributeError: raise AssertionError("Cannot access 'player memory' Randomizer" " as there is no active game or player") return self._machine.game.player[self._uuid] else: return self._data @property def loop(self): return self._loop @loop.setter def loop(self, loop): if loop: self._loop = True else: self._loop = False self.force_all = True def _next_not_random(self): if self.data['current_item_index'] == len(self.items): if not self.loop: raise StopIteration else: self.data['current_item_index'] = 0 self.data['current_item'] = ( self.items[self._data['current_item_index']][0]) self.data['current_item_index'] += 1 return self.data['current_item'] def _init_data(self, data_dict): data_dict['current_item'] = None data_dict['items_sent'] = set() data_dict['current_item_index'] = 0 # only used with disable random def get_current(self): if self.data['current_item']: return self.data['current_item'] else: return self.__next__() def get_next(self): return self.__next__() @staticmethod def pick_weighted_random(items): total_weights = sum([x[1] for x in items]) value = random.randint(1, total_weights) index_value = 0 for item in items: index_value += item[1] if index_value >= value: return item[0] return items[-1][0]
Python
0.000029
@@ -86,39 +86,13 @@ lf, -machine, items, memory='player' +items ):%0A%0A @@ -338,24 +338,17 @@ elf. -_machine = machi +data = No ne%0A @@ -378,69 +378,8 @@ d4() -%0A self._data = None%0A self._player_memory = True %0A%0A @@ -488,29 +488,35 @@ if -hasattr(i, '__iter__' +isinstance(i, (tuple, list) ):%0A @@ -737,163 +737,13 @@ -if memory == 'player':%0A self._player_memory = True%0A elif memory == 'machine':%0A self._player_memory = False%0A%0A self._ +self. data @@ -752,36 +752,32 @@ dict()%0A - self._init_data( @@ -785,101 +785,15 @@ elf. -_ data)%0A%0A - else:%0A raise ValueError(%22Memory should be 'machine' or 'player%22)%0A%0A @@ -1825,592 +1825,8 @@ '%5D%0A%0A - @property%0A def data(self):%0A if self._player_memory:%0A try:%0A if not self._machine.game.player%5Bself._uuid%5D:%0A self._machine.game.player%5Bself._uuid%5D = dict()%0A self._init_data(self._machine.game.player%5Bself._uuid%5D)%0A except AttributeError:%0A raise AssertionError(%22Cannot access 'player memory' Randomizer%22%0A %22 as there is no active game or player%22)%0A%0A return self._machine.game.player%5Bself._uuid%5D%0A%0A else:%0A return self._data%0A%0A @@ -2350,17 +2350,16 @@ ms%5Bself. -_ data%5B'cu
e58686442750afeae70dd3f669070c1342af0bbe
Fix error in qrepeatall()
ControlFlow.py
ControlFlow.py
from BlockLabel import label, endlabel from functools import wraps ## QGL control-flow statements ## def qif(mask, ifSeq, elseSeq=None): if elseSeq: endlabel(elseSeq) # make sure to populate label of elseSeq before using it return [CmpEq(mask), Goto(label(ifSeq))] + elseSeq + [Goto(endlabel(ifSeq))] + ifSeq else: endlabel(ifSeq) return [CmpNeq(mask), Goto(endlabel(ifSeq))] + ifSeq def qwhile(mask, seq): return [CmpNeq(mask), Goto(endlabel(seq))] + seq def qdowhile(mask, seq): return seq + [CmpEq(mask), Goto(label(seq))] def qfunction(func): # caches for sequences and labels seq = {} target = {} @wraps(func) def crfunc(*args): if args not in target: seq[args] = func(*args) target[args] = label(seq[args]) return [Call(target[args])], seq[args] + [Return()] # TODO: update me to only return seq[args] on first call return crfunc def qrepeat(n, seq): if n < 1: return None elif n == 1: return seq else: label(seq) return [LoadRepeat(n)] + seq + [Repeat(label(seq))] # utility to repeat all sequences the same number of times def qrepeatall(n, seqs): for ct in range(len(seqs)): seqs[ct] = qrepeat(seqs[ct]) ## Sequencer primitives ## class ControlInstruction(object): def __init__(self, instruction, target=None, value=None): self.instruction = instruction self.target = target self.value = value self.label = None def __repr__(self): return self.__str__() def __str__(self): labelPart = "{0}: ".format(self.label) if self.label else "" result = labelPart + self.instruction if self.target: result += "(" + str(self.target) + ")" elif self.value: result += "(" + str(self.value) + ")" return result def __eq__(self, other): # ignore label in equality testing mydict = self.__dict__.copy() otherdict = other.__dict__.copy() mydict.pop('label') otherdict.pop('label') return mydict == otherdict def promote(self): return self @property def totLength(self): return 0 @property def length(self): return 0 def Goto(target): return ControlInstruction("GOTO", target=target) def Call(target): return ControlInstruction("CALL", target=target) def Return(): return ControlInstruction("RETURN") def LoadRepeat(n): return ControlInstruction("LOAD", value=n) def Repeat(target): return ControlInstruction("REPEAT", target=target) def Wait(): return ControlInstruction("WAIT") qwait = Wait class ComparisonInstruction(ControlInstruction): def __init__(self, mask, operator): super(ComparisonInstruction, self).__init__("CMP") self.mask = mask self.operator = operator def __str__(self): labelPart = "{0}: ".format(self.label) if self.label else "" return labelPart + "CMP " + self.operator + " " + str(self.mask) def CmpEq(mask): return ComparisonInstruction(mask, "==") def CmpNeq(mask): return ComparisonInstruction(mask, "!=") def CmpLt(mask): return ComparisonInstruction(mask, "<") def CmpGt(mask): return ComparisonInstruction(mask, ">")
Python
0.000009
@@ -1146,16 +1146,19 @@ qrepeat( +n, seqs%5Bct%5D @@ -1158,16 +1158,29 @@ eqs%5Bct%5D) +%0A%09return seqs %0A%0A## Seq
44847ab2843167352a599e7f8bf468c1c0037541
fix crash with EOS switch
mpf/devices/flipper.py
mpf/devices/flipper.py
""" Contains the base class for flippers.""" from mpf.devices.driver import ReconfiguredDriver from mpf.core.system_wide_device import SystemWideDevice class Flipper(SystemWideDevice): """Represents a flipper in a pinball machine. Subclass of Device. Contains several methods for actions that can be performed on this flipper, like :meth:`enable`, :meth:`disable`, etc. Flippers have several options, including player buttons, EOS swtiches, multiple coil options (pulsing, hold coils, etc.) More details: http://missionpinball.com/docs/devices/flippers/ Args: machine: A reference to the machine controller instance. name: A string of the name you'll refer to this flipper object as. """ config_section = 'flippers' collection = 'flippers' class_label = 'flipper' def __init__(self, machine, name): super().__init__(machine, name) self.flipper_switches = [] self.main_coil = None self.hold_coil = None def _initialize(self): self.flipper_switches.append(self.config['activation_switch'].name) self.platform = self.config['main_coil'].platform self.main_coil = ReconfiguredDriver(self.config['main_coil'], self.config) if self.config['hold_coil']: self.hold_coil = ReconfiguredDriver(self.config['hold_coil'], self.config) if self.debug: self.log.debug('Platform Driver: %s', self.platform) def enable(self, **kwargs): """Enables the flipper by writing the necessary hardware rules to the hardware controller. The hardware rules for coils can be kind of complex given all the options, so we've mapped all the options out here. We literally have methods to enable the various rules based on the rule letters here, which we've implemented below. Keeps it easy to understand. :) Note there's a platform feature saved at: self.machine.config['platform']['hw_enable_auto_disable']. If True, it means that the platform hardware rules will automatically disable a coil that has been enabled when the trigger switch is disabled. If False, it means the hardware platform needs its own rule to disable the coil when the switch is disabled. Methods F and G below check for that feature setting and will not be applied to the hardware if it's True. Two coils, using EOS switch to indicate the end of the power stroke: Rule Type Coil Switch Action A. Enable Main Button active D. Enable Hold Button active E. Disable Main EOS active One coil, using EOS switch (not implemented): Rule Type Coil Switch Action A. Enable Main Button active H. PWM Main EOS active Two coils, not using EOS switch: Rule Type Coil Switch Action B. Pulse Main Button active D. Enable Hold Button active One coil, not using EOS switch: Rule Type Coil Switch Action C. Pulse/PWM Main button active Use EOS switch for safety (for platforms that support mutiple switch rules). Note that this rule is the letter "i", not a numeral 1. I. Enable power if button is active and EOS is not active """ del kwargs # todo disable first to clear any old rules? self.log.debug('Enabling flipper with config: %s', self.config) # Apply the proper hardware rules for our config if not self.config['hold_coil']: # single coil self._enable_single_coil_rule() elif not self.config['use_eos']: # two coils, no eos self._enable_main_coil_pulse_rule() self._enable_hold_coil_rule() else: # two coils, cutoff main on EOS self._enable_main_coil_eos_cutoff_rule() self._enable_hold_coil_rule() # todo detect bad EOS and program around it def disable(self, **kwargs): """Disables the flipper. This method makes it so the cabinet flipper buttons no longer control the flippers. Used when no game is active and when the player has tilted. """ del kwargs if self.flipper_switches: self.log.debug("Disabling") for switch in self.flipper_switches: self.platform.clear_hw_rule(switch) def _enable_single_coil_rule(self): self.log.debug('Enabling single coil rule') self.main_coil.set_pulse_on_hit_and_enable_and_release_rule(self.config['activation_switch']) def _enable_main_coil_pulse_rule(self): self.log.debug('Enabling main coil pulse rule') self.main_coil.set_pulse_on_hit_and_release_rule(self.config['activation_switch']) def _enable_hold_coil_rule(self): self.log.debug('Enabling hold coil rule') self.platform.set_hw_rule( sw_name=self.config['activation_switch'].name, sw_activity=1, driver_name=self.config['hold_coil'].name, driver_action='hold', disable_on_release=True, **self.config) def _enable_main_coil_eos_cutoff_rule(self): self.log.debug('Enabling main coil EOS cutoff rule') # TODO: did that ever work? only a disable rule? self.platform.set_hw_rule( sw_name=self.config['eos_switch'], sw_activity=1, driver_name=self.config['main_coil'].name, driver_action='disable', **self.config) def sw_flip(self): """Activates the flipper via software as if the flipper button was pushed. This is needed because the real flipper activations are handled in hardware, so if you want to flip the flippers with the keyboard or OSC interfaces, you have to call this method. Note this method will keep this flipper enabled until you call sw_release(). """ # todo add support for other types of flipper coils # Send the activation switch press to the switch controller self.machine.switch_controller.process_switch( name=self.config['activation_switch'].name, state=1, logical=True) self.config['main_coil'].enable() def sw_release(self): """Deactives the flipper via software as if the flipper button was released. See the documentation for sw_flip() for details. """ # Send the activation switch release to the switch controller self.machine.switch_controller.process_switch( name=self.config['activation_switch'].name, state=0, logical=True) # disable the flipper coil(s) self.config['main_coil'].disable()
Python
0
@@ -5524,16 +5524,21 @@ switch'%5D +.name ,%0A
70ecc48e9fb4d936d9c72d89ccbeec51f42b5252
fix get master ip
docker/k8s_tools.py
docker/k8s_tools.py
#!/bin/env python import os import sys import time import socket from kubernetes import client, config PADDLE_JOB_NAME = os.getenv("PADDLE_JOB_NAME") NAMESPACE = os.getenv("NAMESPACE") PORT = os.getenv("PSERVER_PORT") if os.getenv("KUBERNETES_SERVICE_HOST", None): config.load_incluster_config() else: config.load_kube_config() v1 = client.CoreV1Api() def fetch_pods_info(label_selector): api_response = v1.list_namespaced_pod( namespace=NAMESPACE, pretty=True, label_selector=label_selector) pod_list = [] for item in api_response.items: pod_list.append((item.status.phase, item.status.pod_ip)) return pod_list def wait_pods_running(label_selector, desired): print "label selector: %s, desired: %s" % (label_selector, desired) while True: pod_list = fetch_pods_info(label_selector) running_pod_list = filter(lambda x: x[0] == "Running", pod_list) print "running pod list: ", running_pod_list if len(running_pod_list) == int(desired): return [item[1] for item in running_pod_list] print "sleep for 10 seconds..." time.sleep(10) def fetch_pserver_ips(): label_selector = "paddle-job-pserver=%s" % PADDLE_JOB_NAME pod_list = fetch_pods_info(label_selector) pserver_ips = [item[1] for item in pod_list] return ",".join(pserver_ips) def fetch_master_ip(): label_selector = "paddle-job-master=%s" % PADDLE_JOB_NAME pod_list = fetch_pods_info(label_selector) master_ip = "" if len(pod_list) >=1: master_ip = pod_list[0][1] return master_ip def fetch_trainer_id(): label_selector = "paddle-job=%s" % PADDLE_JOB_NAME pod_list = fetch_pods_info(label_selector) trainer_ips = [item[1] for item in pod_list] trainer_ips.sort() local_ip = socket.gethostbyname(socket.gethostname()) for i in xrange(len(trainer_ips)): if trainer_ips[i] == local_ip: return i return None if __name__ == "__main__": command = sys.argv[1] if command == "fetch_pserver_ips": print fetch_pserver_ips() elif command == "fetch_trainer_id": print fetch_trainer_id() elif command == "fetch_master_ip": print fetch_master_ip() elif command == "wait_pods_running": wait_pods_running(sys.argv[2], sys.argv[3])
Python
0
@@ -1095,18 +1095,17 @@ eep for -10 +5 seconds @@ -1132,10 +1132,9 @@ eep( -10 +5 )%0A%0A%0A @@ -1370,24 +1370,44 @@ aster_ip():%0A + while True:%0A label_se @@ -1452,32 +1452,36 @@ LE_JOB_NAME%0A + + pod_list = fetch @@ -1503,24 +1503,28 @@ l_selector)%0A + master_i @@ -1530,16 +1530,20 @@ ip = %22%22%0A + if l @@ -1560,32 +1560,36 @@ t) %3E=1:%0A + + master_ip = pod_ @@ -1607,24 +1607,76 @@ -return master_ip + if master_ip:%0A return master_ip%0A time.sleep(5) %0A%0Ade
a0791372d7943a785ae55ed31044d0316b53a2ac
Patch release
elephantblog/__init__.py
elephantblog/__init__.py
from __future__ import absolute_import, unicode_literals VERSION = (1, 0, 0) __version__ = '.'.join(map(str, VERSION))
Python
0.000001
@@ -68,17 +68,17 @@ (1, 0, -0 +1 )%0A__vers
34a6ccce1d93843d53efb5985ff5bbb7ea063e31
add force_text a la Django
babel/_compat.py
babel/_compat.py
import sys import array PY2 = sys.version_info[0] == 2 _identity = lambda x: x if not PY2: text_type = str string_types = (str,) integer_types = (int, ) unichr = chr text_to_native = lambda s, enc: s iterkeys = lambda d: iter(d.keys()) itervalues = lambda d: iter(d.values()) iteritems = lambda d: iter(d.items()) from io import StringIO, BytesIO import pickle izip = zip imap = map range_type = range cmp = lambda a, b: (a > b) - (a < b) array_tobytes = array.array.tobytes else: text_type = unicode string_types = (str, unicode) integer_types = (int, long) text_to_native = lambda s, enc: s.encode(enc) unichr = unichr iterkeys = lambda d: d.iterkeys() itervalues = lambda d: d.itervalues() iteritems = lambda d: d.iteritems() from cStringIO import StringIO as BytesIO from StringIO import StringIO import cPickle as pickle from itertools import imap from itertools import izip range_type = xrange cmp = cmp array_tobytes = array.array.tostring number_types = integer_types + (float,) # # Since Python 3.3, a fast decimal implementation is already included in the # standard library. Otherwise use cdecimal when available # if sys.version_info[:2] >= (3, 3): import decimal else: try: import cdecimal as decimal except ImportError: import decimal
Python
0.00049
@@ -108,16 +108,40 @@ e = str%0A + binary_type = bytes%0A stri @@ -158,16 +158,16 @@ (str,)%0A - inte @@ -189,25 +189,8 @@ t, ) -%0A unichr = chr %0A%0A @@ -224,16 +224,33 @@ , enc: s +%0A unichr = chr %0A%0A it @@ -593,16 +593,38 @@ unicode%0A + binary_type = str%0A stri @@ -1129,16 +1129,16 @@ tring%0A%0A%0A - number_t @@ -1171,16 +1171,223 @@ oat,)%0A%0A%0A +def force_text(s, encoding='utf-8', errors='strict'):%0A if isinstance(s, text_type):%0A return s%0A if isinstance(s, binary_type):%0A return s.decode(encoding, errors)%0A return text_type(s)%0A%0A%0A #%0A# Sinc
b65b359402b2f38dad043b1b6d1840f0ef6d8e72
Fix constants
openprocurement/auctions/dgf/constants.py
openprocurement/auctions/dgf/constants.py
from datetime import datetime, timedelta from openprocurement.api.models import TZ, ORA_CODES def read_json(name): import os.path from json import loads curr_dir = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(curr_dir, name) with open(file_path) as lang_file: data = lang_file.read() return loads(data) #document types DOCUMENT_TYPE_OFFLINE = ['x_dgfAssetFamiliarization'] DOCUMENT_TYPE_URL_ONLY = ['virtualDataRoom'] #requiremnt periods MINIMAL_EXPOSITION_PERIOD = timedelta(days=7) MINIMAL_PERIOD_FROM_RECTIFICATION_END = timedelta(days=5) VERIFY_AUCTION_PROTOCOL_TIME = timedelta(days=6) AWARD_PAYMENT_TIME = timedelta(days=20) CONTRACT_SIGNING_TIME = timedelta(days=20) #time constants DGF_ID_REQUIRED_FROM = datetime(2017, 1, 1, tzinfo=TZ) DGF_DECISION_REQUIRED_FROM = datetime(2017, 1, 1, tzinfo=TZ) CLASSIFICATION_PRECISELY_FROM = datetime(2017, 7, 19, tzinfo=TZ) MINIMAL_EXPOSITION_REQUIRED_FROM = datetime(2017, 11, 17, tzinfo=TZ) DGF_ADDRESS_REQUIRED_FROM = datetime(2018, 2, 9, tzinfo=TZ) RECTIFICATION_END_EDITING_AND_VALIDATION_REQUIRED_FROM = datetime(2018, 01, 22, tzinfo=TZ) #codes CAVPS_CODES = read_json('cav_ps.json') CPVS_CODES = read_json('cpvs.json') ORA_CODES[0:0] = ["UA-IPN", "UA-FIN"] NUMBER_OF_BIDS_TO_BE_QUALIFIED = 2 #code units CPV_NON_SPECIFIC_LOCATION_UNITS = ('71', '72', '73', '75', '76', '77', '79', '80', '85', '90', '92', '98') CAV_NON_SPECIFIC_LOCATION_UNITS = ('07', '08')
Python
0.000021
@@ -1130,14 +1130,12 @@ 18, -01, 22 +2, 9 , tz
fbefb3b9d0273e02f5f8f2c708d9c76b57127df0
add provean_read
nsdm/fileparse.py
nsdm/fileparse.py
# -*- coding: utf-8 -*- import vcf import re import glob import os.path import hashlib param = re.compile("LOW|MODIFIER") class Vcf: def __init__(self, data): # 'CHROM', 'POS', 'ID', 'REF', 'ALT', # 'QUAL', 'FILTER', 'INFO', 'FORMAT', # 'start', 'end', 'alleles', 'samples', # '_sample_indexes', 'affected_start', # 'affected_end' # INFO:'AC', 'AF', 'AN', 'BaseQRankSum', # 'ClippingRankSum', 'DP', 'FS', 'MLEAC', # 'MLEAF', 'MQ', 'MQRankSum', 'QD', # 'ReadPosRankSum', 'SNPEFF_AMINO_ACID_CHANGE', # 'SNPEFF_CODON_CHANGE', 'SNPEFF_EFFECT', # 'SNPEFF_EXON_ID', 'SNPEFF_FUNCTIONAL_CLASS', # 'SNPEFF_GENE_BIOTYPE', 'SNPEFF_GENE_NAME', # 'SNPEFF_IMPACT', 'SNPEFF_TRANSCRIPT_ID', 'SOR' self.info = data.INFO self.alt = str(data.ALT[0]) self.ref = data.REF self.pos = str(data.POS) self.annotation = data.INFO.get("SNPEFF_FUNCTIONAL_CLASS", "") self.impact = data.INFO.get("SNPEFF_IMPACT", "") self.gene = data.INFO.get("SNPEFF_GENE_NAME", "") self.feature = data.INFO.get("SNPEFF_TRANSCRIPT_ID", "") vid = (self.alt + self.ref + self.pos + self.annotation + self.impact + self.gene + self.feature) self.sha1 = hashlib.sha1(vid.encode('utf-8')).hexdigest() class Gff: def __init__(self, data): self.start = data[3] self.end = data[4] self.strand = data[6] info = data[8].split(";") self.gene = info[0].split(":")[1] self.description = info[2].split("=")[1].replace("%2C", ",") def vcf_read(filename): """read vcf file. only annotated""" filename = filepath(filename) result = [] fp = open(filename, "r") vcf_r = vcf.Reader(fp) for v in vcf_r: vcfobj = Vcf(v) if vcfobj.impact is "": continue if re.match(param, vcfobj.impact) is None: result.append(vcfobj) fp.close() return result def reference_read(filename): """read reference file""" filename = filepath(filename) fp = open(filename, "r") next(fp) reference = fp.read().strip().replace("\n", "") return reference def vcf_allread(targetdir): result = [] allvariantdir = filepath(targetdir) vcffiles = sorted(glob.glob(allvariantdir + "/*.vcf")) for i in vcffiles: vlist = vcf_read(i) result.append(vlist) return result def gff_read(filename): """read gff file""" filename = filepath(filename) result = dict() fp = open(filename, "r") for i in fp: data = i.split("\t") if i[0] != "#" and data[2] == "gene": gene = data[8].split(";")[0].split(":")[1] result[gene] = Gff(data) fp.close() return result def v_intersect(variant_list): vsum = dict() for g in variant_list: for v in g: vsum[v.sha1] = vsum.get(v.sha1, []) + [v] ret = [] for k, v in vsum.items(): if len(v) == len(variant_list): ret.append(v[0]) return ret def v_union(variant_list, gffdict=None): vsum = dict() if gffdict == None: for g in variant_list: for v in g: if in_cobj(vsum.get(v.gene, []), v) == False: vsum[v.gene] = vsum.get(v.gene, []) + [v] else: for g in variant_list: for v in g: if in_cobj(vsum.get(v.gene, []), v) == False: gff = gffdict[v.gene] v.start = gff.start v.end = gff.end v.strand = gff.strand v.description = gff.description vsum[v.gene] = vsum.get(v.gene, []) + [v] return vsum def in_cobj(listobj, cobj): tf = 0 for i in listobj: if i.sha1 == cobj.sha1: tf += 1 if tf > 0: return True else: return False def bbhdict(f): filename = filepath(f) f = open(filename, "r") ret = dict() for i in f: k, v = i.strip().split("\t")[:2] ret[k] = v return ret def bbh(f, variantdict): result = dict() bdict = bbhdict(f) for key, valuelist in variantdict.items(): homolog = bdict[key] if homolog == "-": continue for v in valuelist: v.homolog = homolog result[homolog] = result.get(homolog, []) + [v] return result def filepath(file): return os.path.abspath(os.path.expanduser(file))
Python
0
@@ -2220,24 +2220,572 @@ reference%0A%0A%0A +def provean_read(filename):%0A f = open(filename, %22r%22)%0A gene = %22%22%0A result = dict()%0A p1 = re.compile(%22%5E# Query%22)%0A p2 = re.compile(%22%5E#%7C%5E%5C%5B%22)%0A for i in f:%0A i = i.strip()%0A if re.match(p1, i) is not None:%0A gene = os.path.basename(i.split(%22:%22).strip()).split(%22.%22)%5B0%5D%0A if re.match(p2, i) is not None:%0A continue%0A scores = i.split()%0A result%5Bgene%5D = result.get(gene, %5B%5D) + %5B%0A %7B%22change%22: scores%5B0%5D,%0A %22provean_score%22:scores%5B1%5D,%0A %7D%5D%0A return result%0A%0A%0A def vcf_allr
8a110323a41635597f8891aa04c51d7784aa0195
Remove commented-out code.
multi_schema/models.py
multi_schema/models.py
from django.conf import settings from django.contrib import auth from django.db import models, connection, transaction from django.utils.translation import ugettext as _ from django.core.validators import RegexValidator from django.forms import ValidationError from model_utils.managers import PassThroughManager from model_utils import ModelTracker import ensure_installation import signals try: User = auth.get_user_model() except: # Was getting an error where auth.models could not be found. import django.contrib.auth.models User = auth.models.User # This is a bit of fancy trickery to stick the property _is_schema_aware # on every model class, returning False, unless it has been explicitly # set to True in the model definition (see base.py for examples). class ClassProperty(property): def __get__(self, cls, owner): return self.fget.__get__(None, owner)() def is_schema_aware(cls): return cls._meta.auto_created and cls._meta.auto_created._is_schema_aware models.Model._is_schema_aware = ClassProperty(classmethod(is_schema_aware)) class SchemaQuerySet(models.query.QuerySet): def bulk_create(self, *args, **kwargs): created = super(SchemaQuerySet, self).bulk_create(*args, **kwargs) for schema in created: schema.create_schema() return created def mass_create(self, *args): self.bulk_create([Schema(name=x, schema=x) for x in args]) class Schema(models.Model): """ The Schema model provides an abstraction for a Postgres schema. It will take care of creating a cloned copy of the template_schema when it is created, and also has the ability to activate and deactivate itself (at the start and end of the request cycle would be a good plan). """ name = models.CharField(max_length=128, unique=True, help_text=_(u'The display name of the schema.')) schema = models.CharField(max_length=36, primary_key=True, unique=True, validators=[RegexValidator( regex='^[a-z][a-z_]*$', message=_(u'May only contain lowercase letters and underscores. Must start with a letter.') )], help_text=_(u'The internal name of the schema. May not be changed after creation.'), ) users = models.ManyToManyField(User, blank=True, null=True, related_name='schemata') objects = PassThroughManager.for_queryset_class(SchemaQuerySet)() tracker = ModelTracker() class Meta: app_label = 'multi_schema' verbose_name_plural = 'schemata' def __unicode__(self): return self.name def save(self, *args, **kwargs): self._meta.get_field_by_name('schema')[0].run_validators(self.schema) if self.tracker.previous('schema') is None or 'force_insert' in kwargs: try: Schema.objects.get(schema=self.schema) except Schema.DoesNotExist: pass else: raise ValidationError('Schema already in use') try: Schema.objects.get(name=self.name) except Schema.DoesNotExist: pass else: raise ValidationError('Schema name already in use') else: if self.tracker.has_changed('schema'): raise ValidationError('May not change schema after creation') self.create_schema() return super(Schema, self).save(*args, **kwargs) def create_schema(self, cursor=None): if not cursor: cursor = connection.cursor() cursor.execute("SELECT schema_name FROM information_schema.schemata WHERE schema_name = %s", [self.schema]) if not cursor.fetchone(): cursor.execute("SELECT clone_schema('__template__', %s);", [self.schema]) transaction.commit_unless_managed() signals.schema_created.send(sender=self, schema=self.schema) def activate(self, cursor=None): signals.schema_pre_activate.send(sender=self, schema=self.schema) (cursor or connection.cursor()).execute('SET search_path TO "%s",public' % self.schema) signals.schema_post_activate.send(sender=self, schema=self.schema) def deactivate(self, cursor=None): signals.schema_pre_activate.send(sender=self, schema=None) (cursor or connection.cursor()).execute('SET search_path TO "$user",public') signals.schema_post_activate.send(sender=self, schema=None) # An in-memory only template schema. template_schema = Schema(name="Template Schema", schema="__template__") # class UserSchema(models.Model): # """ # A relationship between a User and a Schema. A User may be able to # access the data from many schemata, and in that case should be # provided with tools to do so. # # See templates/multi_schema/change_schema.html for an example. # """ # user = models.ForeignKey(User, related_name='schemata') # schema = models.ForeignKey(Schema, related_name='users') # # class Meta: # app_label = 'multi_schema' # # def __unicode__(self): # return u"%s : %s" % (self.user, self.schema)
Python
0
@@ -4627,590 +4627,4 @@ __%22) -%0A%0A# class UserSchema(models.Model):%0A# %22%22%22%0A# A relationship between a User and a Schema. A User may be able to%0A# access the data from many schemata, and in that case should be%0A# provided with tools to do so.%0A# %0A# See templates/multi_schema/change_schema.html for an example.%0A# %22%22%22%0A# user = models.ForeignKey(User, related_name='schemata')%0A# schema = models.ForeignKey(Schema, related_name='users')%0A# %0A# class Meta:%0A# app_label = 'multi_schema'%0A# %0A# def __unicode__(self):%0A# return u%22%25s : %25s%22 %25 (self.user, self.schema)%0A
2fb1c14f9ad0b72f1f059d7e5e233b8001c2b60b
Update auth tests
app/tests/integration/test_twitter_api.py
app/tests/integration/test_twitter_api.py
# -*- coding: utf-8 -*- """ Twitter API test module. """ from unittest import TestCase from lib.twitter_api import authentication class TestAuth(TestCase): def test_generateAppToken(self): auth = authentication._generateAppAccessToken() def test_getTweepyConnection(self): auth = authentication._generateAppAccessToken() api = authentication._getTweepyConnection(auth) def test_getAPIConnection(self): """ Test App Access token. """ api = authentication.getAPIConnection(userFlow=False) def test_getAppOnlyConnection(self): """ Test App-only token. """ api = authentication.getAppOnlyConnection()
Python
0.000003
@@ -45,16 +45,163 @@ module. +%0A%0ADo requests to the Twitter API using configured credentials. NB. These require%0Avalid tokens for a Twitter dev account, plus a network connection. %0A%22%22%22%0Afro @@ -228,16 +228,47 @@ stCase%0A%0A +from lib.config import AppConf%0A from lib @@ -303,16 +303,34 @@ cation%0A%0A +conf = AppConf()%0A%0A %0Aclass T @@ -373,16 +373,22 @@ erateApp +Access Token(se @@ -664,16 +664,21 @@ Test +that App Acce @@ -681,24 +681,62 @@ Access token + can be used to connect to Twitter API .%0A %22%22
65948c9759abe85aee3cda4befc0fca9c49ce069
add get_color function
explorer/rc.py
explorer/rc.py
import re from .catalog import CoaddCatalog, VisitCatalog, ColorCatalog, MultiMatchedCatalog visits = {'cosmos' : {'HSC-G' : "11690..11712:2^29324^29326^29336^29340^29350^29352", 'HSC-R' : "1202..1220:2^23692^23694^23704^23706^23716^23718", 'HSC-I' : "1228..1232:2^1236..1248:2^19658^19660^19662^19680^19682^19684^19694^19696^19698^19708^19710^19712^30482..30504:2", 'HSC-Y' : "274..302:2^306..334:2^342..370:2^1858..1862:2^1868..1882:2^11718..11742:2^22602..22608:2^22626..22632:2^22642..22648:2^22658..22664:2", 'HSC-Z' : "1166..1194:2^17900..17908:2^17926..17934:2^17944..17952:2^17962^28354..28402:2", 'NB0921' : "23038..23056:2^23594..23606:2^24298..24310:2^25810..25816:2"}, 'wide' : {'HSC-G' : "9852^9856^9860^9864^9868^9870^9888^9890^9898^9900^9904^9906^9912^11568^11572^11576^11582^11588^11590^11596^11598", 'HSC-R' : "11442^11446^11450^11470^11476^11478^11506^11508^11532^11534", 'HSC-I' : "7300^7304^7308^7318^7322^7338^7340^7344^7348^7358^7360^7374^7384^7386^19468^19470^19482^19484^19486", 'HSC-Y' : "6478^6482^6486^6496^6498^6522^6524^6528^6532^6544^6546^6568^13152^13154", 'HSC-Z' : "9708^9712^9716^9724^9726^9730^9732^9736^9740^9750^9752^9764^9772^9774^17738^17740^17750^17752^17754"} } visits['wide-8766'] = visits['wide'] visits['wide-8767'] = visits['wide'] def visit_list(visit_string): l = [] for v in visit_string.split('^'): try: l.append([int(v)]) except: m = re.search('(\d+)\.\.(\d+):(\d)', v) l.append(range(int(m.group(1)), int(m.group(2))+1, int(m.group(3)))) return [x for y in l for x in y] def get_visits(field, filt): return visit_list(visits[field][filt]) def field_name(tract): if tract==9813: return 'cosmos' elif tract==8766: return 'wide-8766' elif tract==8767: return 'wide-8767' def get_tractList(field): if field=='cosmos': tractList = [9813] elif field=='wide-8766': tractList = [8766] elif field=='wide-8767': tractList = [8767] return tractList def get_coadd(butler, field, filt, description=None, **kwargs): dataIds = [{'tract':t, 'filter':filt} for t in get_tractList(field)] return CoaddCatalog(butler, dataIds, description=description, **kwargs) def get_matched(butler, field, filt, description=None, visit_description=None, match_registry='rc_match_registry.h5', **kwargs): coadd_cat = get_coadd(butler, field, filt, description=description, **kwargs) visits = get_visits(field, filt) tracts = get_tractList(field) visit_cats = [VisitCatalog(butler, {'tract':t, 'visit':v, 'filter':filt}, name=float('{}.{}'.format(v,i))) for i,t in enumerate(tracts) for v in visits] return MultiMatchedCatalog(coadd_cat, visit_cats, match_registry=match_registry)
Python
0.000003
@@ -3034,8 +3034,223 @@ egistry) +%0A%0Adef get_color(butler, field, filt, description=None, **kwargs):%0A dataIds = %5B%7B'tract':t, 'filter':filt%7D for t in get_tractList(field)%5D%0A return ColorCatalog(butler, dataIds, description=description, **kwargs)%0A
cdfc808383d0c3a0b722a67febb0d41bdd23a12c
Remove craziness
roushagent/plugins/lib/bashscriptrunner.py
roushagent/plugins/lib/bashscriptrunner.py
import os import string import subprocess from threading import Thread from Queue import Queue, Empty def name_mangle(s, prefix=""): # we only support upper case variables and as a convenience convert # - to _, as - is not valid in bash variables. prefix = prefix.upper() r = s.upper().replace("-", "_") # first character must be _ or alphabet if not r[0] == '_' and not (r[0].isalpha() and len(prefix) == 0): r = "".join(["_", r]) # rest of the characters must be alphanumeric or _ valid = string.digits + string.ascii_uppercase + "_" r = "".join([l for l in r if l in valid]) if len(r) >= 1: #valid r, prefix it unless it is already prefixed return r if r.find(prefix) == 0 else prefix + r raise ValueError("Failed to convert %s to valid bash identifier" % s) def posix_escape(s): #The only special character inside of a ' is ', which terminates #the '. We will surround s with single quotes. If we encounter a #single quote inside of s, we need to close our enclosure with ', #escape the single quote in s with "'", then reopen our enclosure #with '. return "'%s'" % (s.replace("'", "'\"'\"'")) def find_script(script, script_path): path = None found = False for path in script_path: filename = os.path.join(path, script) if os.path.exists(filename) and \ os.path.dirname(os.path.realpath(filename)) == \ os.path.realpath(path): found = True break if not found: return None return filename class BashScriptRunner(object): def __init__(self, script_path=["scripts"], environment=None, log=None): self.script_path = script_path self.environment = environment or {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin"} self.log = log def run(self, script, *args): return self.run_env(script, {}, "RCB", *args) def run_env(self, script, environment, prefix, *args): # first pass: no input, return something like the following # { "response": { # "result_code": <result-code-ish> # "result_str": <error-or-success-message> # "result_data": <extended error info or arbitrary data> # } # } env = {} env.update(self.environment) env.update(dict([(name_mangle(k, prefix), v) for k, v in environment.iteritems()])) response = {"response": {}} path = find_script(script, self.script_path) if path is None: response['result_code'] = 127 response['result_str'] = "%s not found in %s" % ( script, ":".join(self.script_path)) response['result_data'] = {"script": script, "output": "", "error": ""} return response to_run = [path] + list(args) #first pass, never use bash to run things c = subprocess.Popen(to_run, stdin=open("/dev/null", "r"), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if self.log is None: response['result_code'] = c.wait() response['result_str'] = os.strerror(c.returncode) response['result_data'] = {"script": path, "output": c.stdout.read(), "error": c.stderr.read()} else: response['result_data'] = {"script": path, "output": "", "error": ""} stdout = Queue() stderr = Queue() t1 = Thread(enqueue_output, args=(c.stdout, stdout)) t2 = Thread(enqueue_output, args=(c.stderr, stderr)) t1.daemon = True t2.daemon = True t1.start() t2.start() while c.poll() is None: for out, name, attr in ((stdout, "output", "INFO"), (stderr, "error", "ERROR")): try: line = out.get(timeout=0.5) getattr(log, attr)(line) response['result_data'][name] += line except Empty: pass response['result_code'] = c.retcode response['result_str'] = os.strerror(c.retcode) def enqueue_output(out, queue): for line in iter(out, queue): queue.put(line) out.close()
Python
0.000015
@@ -3879,30 +3879,24 @@ eue_output, -args=( c.stdout, st @@ -3900,17 +3900,16 @@ stdout) -) %0A @@ -3945,14 +3945,8 @@ ut, -args=( c.st @@ -3958,17 +3958,16 @@ stderr) -) %0A @@ -4643,24 +4643,11 @@ in -iter(out, queue) +out :%0A
6ba94b87e11b994b02457e57d71eab9b80d28167
fix import for django 1.8
tests/notification/test_sites.py
tests/notification/test_sites.py
from mock import patch from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.sites.models import Site from django.test import TestCase, override_settings from django.urls import reverse from callisto.delivery.models import Report from callisto.notification.models import EmailNotification User = get_user_model() class TempSiteID(): ''' with TempSiteID(1): ... ''' def __init__(self, site_id): self.site_id_temp = site_id def __enter__(self): self.site_id_stable = getattr(settings, 'SITE_ID', 1) settings.SITE_ID = self.site_id_temp def __exit__(self, *args): settings.SITE_ID = self.site_id_stable class SiteIDTest(TestCase): def test_on_site_respects_SITE_ID_setting(self): site_1_pages = 3 site_2_pages = site_1_pages + 1 site_2 = Site.objects.create() index = 0 for i in range(site_1_pages): EmailNotification.objects.create(name=index) index += 1 for i in range(site_2_pages): notification = EmailNotification.objects.create(name=index) notification.sites.add(site_2) # site_1 is already added index += 1 self.assertEqual(EmailNotification.objects.on_site().count(), site_1_pages + site_2_pages) with TempSiteID(site_2.id): self.assertEqual(EmailNotification.objects.on_site().count(), site_2_pages) def test_multiple_added_sites_are_reflected_by_on_site(self): site_2 = Site.objects.create() notification = EmailNotification.objects.create() notification.sites.add(site_2) self.assertIn(notification, EmailNotification.objects.on_site()) with TempSiteID(site_2.id): self.assertIn(notification, EmailNotification.objects.on_site()) class SiteRequestTest(TestCase): def setUp(self): super(SiteRequestTest, self).setUp() User.objects.create_user(username='dummy', password='dummy') self.client.login(username='dummy', password='dummy') user = User.objects.get(username='dummy') self.report = Report(owner=user) self.report_key = 'bananabread! is not my key' self.report.encrypt_report('{}', self.report_key) self.report.save() self.submit_url = reverse('test_submit_report', args=[self.report.pk]) @override_settings() @patch('django.http.request.HttpRequest.get_host') def test_can_request_pages_without_site_id_set(self, mock_get_host): mock_get_host.return_value = Site.objects.get(id=settings.SITE_ID).domain del settings.SITE_ID response = self.client.get(self.submit_url) self.assertNotEqual(response.status_code, 404) @override_settings() @patch('django.http.request.HttpRequest.get_host') @patch('callisto.notification.managers.EmailNotificationQuerySet.on_site') def test_site_passed_to_email_notification_manager(self, mock_on_site, mock_get_host): mock_get_host.return_value = Site.objects.get(id=settings.SITE_ID).domain site_id = settings.SITE_ID del settings.SITE_ID self.client.post( self.submit_url, data={ 'name': 'test submitter', 'email': 'test@example.com', 'phone_number': '555-555-1212', 'email_confirmation': 'True', 'key': self.report_key, }, ) mock_on_site.assert_called_with(site_id)
Python
0.000001
@@ -158,47 +158,40 @@ ngo. -test import TestCase, override_settings +core.urlresolvers import reverse %0Afro @@ -203,20 +203,20 @@ ngo. -urls +test import reve @@ -211,23 +211,43 @@ import -reverse +TestCase, override_settings %0A%0Afrom c
0b7b9f95ab2efd16b75dd7d5689ba2329c879b28
fix default
drillsrs/cmd/study.py
drillsrs/cmd/study.py
import argparse import random from datetime import datetime from typing import List from drillsrs.cmd.command_base import CommandBase from drillsrs import db, scheduler, util from drillsrs.cli_args import Mode def _learn_single_card( index: int, num_cards_to_study: int, card: db.Card, mode: Mode) -> None: print('Card #{} ({:.01%} done, {} left)'.format( card.num, index / num_cards_to_study, num_cards_to_study - index)) raw_question = card.question raw_answers = card.answers if mode is Mode.reversed or mode is Mode.mixed and random.random() > 0.5: raw_question, raw_answers = random.choice(raw_answers), [raw_question] question = 'Question: %s' % raw_question if card.tags: question += ' [%s]' % util.format_card_tags(card.tags) util.ask(question) util.ask('Answers: %s' % ', '.join(raw_answers)) print('') card.is_active = True card.due_date = scheduler.next_due_date(card) card.activation_date = datetime.now() class StudyCommand(CommandBase): names = ['study', 'learn'] description = 'begin a study session' def decorate_arg_parser(self, parser: argparse.ArgumentParser) -> None: parser.add_argument( 'deck', nargs='?', help='choose the deck name') parser.add_argument( '-n', type=int, default=10, help='set how many flashcards to study') parser.add_argument( '-m', '--mode', type=Mode.parse, default="direct", choices=list(Mode), help='learning mode. whether to involve reversed direction') def run(self, args: argparse.Namespace) -> None: deck_name: str = args.deck how_many: int = args.n mode: Mode = args.mode with db.session_scope() as session: deck = db.get_deck_by_name(session, deck_name) cards_to_study = scheduler.get_cards_to_study( session, deck, how_many) if not cards_to_study: print('No cards to study.') return print( '%d cards to study. After seeing a card, hit enter.' % len(cards_to_study)) print() num_cards_to_study = len(cards_to_study) for index, card in enumerate(cards_to_study): _learn_single_card(index, num_cards_to_study, card, mode)
Python
0.000004
@@ -57,32 +57,8 @@ ime%0A -from typing import List%0A from @@ -1494,16 +1494,19 @@ ult= -%22 +Mode. direct -%22 ,%0A
f91fc2a8858c243b62d1a9a369d45216fb15f443
Change auth selenium test to use wait_element_become_present
tests/webui/steps/authentication_steps.py
tests/webui/steps/authentication_steps.py
# -*- coding: utf-8 -*- import time from behave import when, then, given from toxicbuild.ui import settings from tests.webui.steps.base_steps import ( # noqa f811 given_logged_in_webui, user_sees_main_main_page_login) # Scenario: Someone try to access a page without being logged. @when('someone tries to access a waterfall url without being logged') def step_impl(context): browser = context.browser base_url = 'http://{}:{}/'.format(settings.TEST_WEB_HOST, settings.TORNADO_PORT) url = base_url + 'waterfall/some-repo' browser.get(url) @then('he sees the login page') # noqa f401 def step_impl(context): browser = context.browser el = browser.find_element_by_id('inputUsername') assert el # Scenario: Do login @given('the user is in the login page') # noqa f401 def step_impl(context): browser = context.browser base_url = 'http://{}:{}/'.format(settings.TEST_WEB_HOST, settings.TORNADO_PORT) url = base_url + 'login' browser.get(url) @when('he inserts "{user_name}" as user name') def user_inserts_username_login(context, user_name): browser = context.browser username_input = browser.find_element_by_id('inputUsername') username_input.send_keys(user_name) @when('inserts "{passwd}" as password') def user_inserts_password_login(context, passwd): browser = context.browser passwd_input = browser.find_element_by_id('inputPassword') passwd_input.send_keys(passwd) @when('clicks in the login button') def user_clicks_login_button(context): browser = context.browser btn = browser.find_element_by_id('btn-login') btn.click() @then('he sees the red warning in the password field') def user_sees_missing_required_field_warning(context): browser = context.browser el = browser.find_element_by_class_name('form-control-error') assert el @then('he sees the invalid credentials message') def user_sees_invalid_credentials_message(context): browser = context.browser el = browser.find_element_by_id('login-error-msg-container') color = el.value_of_css_property('color') time.sleep(0.5) assert color != 'rgb(255, 255, 255)' # Scenario: Do logout @when('he clicks in the logout link') # noqa f401 def step_impl(context): browser = context.browser el = browser.find_element_by_class_name('nav-link') browser.click(el) el = browser.find_elements_by_class_name('dropdown-item-logout')[-1] browser.click(el)
Python
0.000001
@@ -689,32 +689,68 @@ context.browser%0A +%0A def fn():%0A try:%0A el = browser @@ -782,24 +782,142 @@ tUsername')%0A + except Exception:%0A el = None%0A%0A return el%0A%0A el = browser.wait_element_become_present(fn)%0A%0A assert e
9c8bfb78a1e45ab9cb78fc18318b2a39153103db
use the level arg to populate the operations list instead of appending. This allows the operation list to be changed on every iteration and keep a better record
numbers_solver.py
numbers_solver.py
#!/usr/bin/env python numbers = [25, 7, 9, 3, 1, 8] target = 642 # target = 225 def mult(x, y): return x * y def divide(x, y): if(x > y): return x / y else: return y / x def add(x, y): return x + y def sub(x, y): if(x > y): return x - y else: return y - x OPS = { 'x': mult, '/': divide, '+': add, '-': sub } def find_abs_diff(x, y): return abs(x - y) class CalcOperation(object): def __init__(self, num, op=None): """ The op arg is the operation that should be applied to the next value in the chain """ self.num = num self.op = op self.next = None def update(self, op=None, next=None, num=None): if(num): self.num = num if(op): self.op = op if(next): self.next = next def __repr__(self): return '{num} {op} '.format(num=self.num, op=self.op) class NumberSolution(object): def __init__(self, operations, result, target): self.operations = operations self.result = result self.target = target def __repr__(self): if(self.result - self.target == 0): return 'Found A Solution' return 'Only managed to find a result of {result}, this is an error of {error}'.format(result=self.result, error=abs(self.target - self.result)) class NumberGameSolver(object): def __init__(self, numbers, target): self.numbers = sorted(numbers) self.target = target self.best = 0 self.solution = self._solve() print(self.solution) def __repr__(self): return self.solution.__repr__() def _solve(self, operations=[], used=[], current=0, level=0): if not used: used = [False for num in self.numbers] for i, val in enumerate(self.numbers): if used[i]: continue if current > 0: for op, fn in OPS.items(): combo = sorted([current, val], reverse=True) result = fn(combo[0], combo[1]) if find_abs_diff(result, self.target) < find_abs_diff(self.best, self.target): if type(result) is int: self.best = result # print('NEW BEST') # print(self.best) operations.append(CalcOperation(val)) operations[-2].update(op=op, next=operations[-1]) print(self.best) print(operations) self.solution = NumberSolution(operations, self.best, self.target) if self.best == self.target: # print(operations) return self.solution has_solution = self._solve( [obj for obj in operations], [True if used[j] or j == i else False for (j, num) in enumerate(self.numbers)], result, level+1) if has_solution: return has_solution else: operations.append(CalcOperation(val)) has_solution = self._solve( [obj for obj in operations], [True if used[j] or j == i else False for (j, num) in enumerate(self.numbers)], val, level+1) if has_solution: return has_solution solution = NumberGameSolver(numbers, target)
Python
0
@@ -1833,16 +1833,99 @@ numbers%5D +%0A if not operations:%0A operations = %5BNone for num in self.numbers%5D %0A%0A @@ -2205,16 +2205,156 @@ bo%5B1%5D)%0A%0A + operations%5Blevel%5D = CalcOperation(val)%0A operations%5Blevel - 1%5D.update(op=op, next=operations%5Blevel%5D)%0A%0A @@ -2637,243 +2637,8 @@ est) -%0A operations.append(CalcOperation(val))%0A operations%5B-2%5D.update(op=op, next=operations%5B-1%5D)%0A print(self.best)%0A print(operations) %0A%0A @@ -2815,26 +2815,24 @@ - # print(opera @@ -3388,16 +3388,18 @@ ions -.append( +%5Blevel%5D = Calc @@ -3412,17 +3412,16 @@ ion(val) -) %0A
1ab8224372a5f839c8f0f74f3cafe7926905a7ec
Update __init__.py
nupic/__init__.py
nupic/__init__.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import os __version__ = "0.2.4.dev0" NUPIC_ROOT = os.environ.get('NUPIC', os.path.dirname(os.path.realpath(__file__)))
Python
0.000072
@@ -1014,87 +1014,4 @@ v0%22%0A -%0ANUPIC_ROOT = os.environ.get('NUPIC', os.path.dirname(os.path.realpath(__file__)))%0A
39986540e1ad1c4712405e46b988459f2abbf6e9
Update for new python
Communication/testUDP.py
Communication/testUDP.py
# ------------------------------------------------------- import socket, traceback import time host = '' port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) filein = open('saveUDP.txt', 'w') t0 = time.time() while time.time()-t0 < 20: try: message, address = s.recvfrom(9000) print message filein.write('%s\n' % (message)) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() filein.close() # -------------------------------------------------------
Python
0
@@ -99,16 +99,42 @@ st = ''%0A +#host = '192.168.201.251'%0A port = 1 @@ -136,17 +136,16 @@ t = 1234 -5 %0A%0As = so @@ -460,24 +460,39 @@ 00)%0A -%09 + print - +( message -%0A%09 +)%0A file @@ -571,16 +571,17 @@ %0A + raise%0A @@ -594,9 +594,16 @@ pt:%0A -%09 + trac
862c42a8abf0836604f56a9008018f34c405ca13
update version number
f5/__init__.py
f5/__init__.py
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # __version__ = '0.1.5'
Python
0.000002
@@ -593,11 +593,11 @@ = '0.1. -5 +6 '%0A
cd1d576b7c0e1c75b0c890b4a0829a1018dadff6
Load list elements in the correct order
redisdl.py
redisdl.py
#!/usr/bin/env python import json import redis def dumps(host='localhost', port=6379, db=0, pretty=False): r = redis.Redis(host=host, port=port, db=db) kwargs = {} if not pretty: kwargs['separators'] = (',', ':') else: kwargs['indent'] = 2 kwargs['sort_keys'] = True encoder = json.JSONEncoder(**kwargs) table = {} for key, type, value in _reader(r): table[key] = {'type': type, 'value': value} return encoder.encode(table) def dump(fp, host='localhost', port=6379, db=0, pretty=False): if pretty: # hack to avoid implementing pretty printing fp.write(dumps(host=host, port=port, db=db, pretty=pretty)) return r = redis.Redis(host=host, port=port, db=db) kwargs = {} if not pretty: kwargs['separators'] = (',', ':') else: kwargs['indent'] = 2 kwargs['sort_keys'] = True encoder = json.JSONEncoder(**kwargs) fp.write('{') first = True for key, type, value in _reader(r): key = encoder.encode(key) type = encoder.encode(type) value = encoder.encode(value) item = '%s:{"type":%s,"value":%s}' % (key, type, value) if first: first = False else: fp.write(',') fp.write(item) fp.write('}') def _reader(r): for key in r.keys(): type = r.type(key) if type == 'string': value = r.get(key) elif type == 'list': value = r.lrange(key, 0, -1) elif type == 'set': value = list(r.smembers(key)) elif type == 'zset': value = r.zrange(key, 0, -1, False, True) elif type == 'hash': value = r.hgetall(key) else: raise UnknownTypeError("Unknown key type: %s" % type) yield key, type, value def loads(s, host='localhost', port=6379, db=0, empty=False): r = redis.Redis(host=host, port=port, db=db) if empty: for key in r.keys(): r.delete(key) table = json.loads(s) for key in table: item = table[key] type = item['type'] value = item['value'] _writer(r, key, type, value) def load(fp, host='localhost', port=6379, db=0, empty=False): s = fp.read() loads(s, host, port, db, empty) def _writer(r, key, type, value): r.delete(key) if type == 'string': r.set(key, value) elif type == 'list': for element in value: r.lpush(key, element) elif type == 'set': for element in value: r.sadd(key, element) elif type == 'zset': for element, score in value: r.zadd(key, element, score) elif type == 'hash': r.hmset(key, value) else: raise UnknownTypeError("Unknown key type: %s" % type) if __name__ == '__main__': import optparse import os.path import re import sys DUMP = 1 LOAD = 2 def options_to_kwargs(options): args = {} if options.host: args['host'] = options.host if options.port: args['port'] = int(options.port) if options.db: args['db'] = int(options.db) # dump only if hasattr(options, 'pretty') and options.pretty: args['pretty'] = True # load only if hasattr(options, 'empty') and options.empty: args['empty'] = True return args def do_dump(options): if options.output: output = open(options.output, 'w') else: output = sys.stdout kwargs = options_to_kwargs(options) dump(output, **kwargs) if options.output: output.close() def do_load(options, args): if len(args) > 0: input = open(args[0], 'r') else: input = sys.stdin kwargs = options_to_kwargs(options) load(input, **kwargs) if len(args) > 0: input.close() script_name = os.path.basename(sys.argv[0]) if re.search(r'load(?:$|\.)', script_name): action = help = LOAD elif re.search(r'dump(?:$|\.)', script_name): action = help = DUMP else: # default is dump, however if dump is specifically requested # we don't show help text for toggling between dumping and loading action = DUMP help = None if help == LOAD: usage = "Usage: %prog [options] [FILE]" usage += "\n\nLoad data from FILE (which must be a JSON dump previously created" usage += "\nby redisdl) into specified or default redis." usage += "\n\nIf FILE is omitted standard input is read." elif help == DUMP: usage = "Usage: %prog [options]" usage += "\n\nDump data from specified or default redis." usage += "\n\nIf no output file is specified, dump to standard output." else: usage = "Usage: %prog [options]" usage += "\n %prog -l [options] [FILE]" usage += "\n\nDump data from redis or load data into redis." usage += "\n\nIf input or output file is specified, dump to standard output and load" usage += "\nfrom standard input." parser = optparse.OptionParser(usage=usage) parser.add_option('-H', '--host', help='connect to HOST (default localhost)') parser.add_option('-p', '--port', help='connect to PORT (default 6379)') parser.add_option('-s', '--socket', help='connect to SOCKET') if help == DUMP: parser.add_option('-d', '--db', help='dump DATABASE (0-N, default 0)') parser.add_option('-o', '--output', help='write to OUTPUT instead of stdout') parser.add_option('-y', '--pretty', help='Split output on multiple lines and indent it', action='store_true') elif help == LOAD: parser.add_option('-d', '--db', help='load into DATABASE (0-N, default 0)') parser.add_option('-e', '--empty', help='delete all keys in destination db prior to loading') else: parser.add_option('-l', '--load', help='load data into redis (default is to dump data from redis)', action='store_true') parser.add_option('-d', '--db', help='dump or load into DATABASE (0-N, default 0)') parser.add_option('-o', '--output', help='write to OUTPUT instead of stdout (dump mode only)') parser.add_option('-y', '--pretty', help='Split output on multiple lines and indent it (dump mode only)', action='store_true') parser.add_option('-e', '--empty', help='delete all keys in destination db prior to loading (load mode only)', action='store_true') options, args = parser.parse_args() if action == DUMP: if len(args) > 0: parser.print_help() exit(4) do_dump(options) else: if len(args) > 1: parser.print_help() exit(4) do_load(options, args)
Python
0.000002
@@ -2483,17 +2483,17 @@ r. -l +r push(key
5ec3da094bd9d6d1517425b27223ad5da6bfe804
Use run_su in the restart command as well
fabfile/app.py
fabfile/app.py
#:coding=utf8: import pipes from fabric.api import ( env, task, roles, prefix, local as localexec, sudo, run, execute, put, runs_once, settings, ) env.venv_path = '/var/www/venvs/homepage' env.deploy_user = 'supervisord' def run_su(cmd, user=None): # The Google Compute Engine images prompt for a password when running # sudo -u so we sudo to root and then su to the user we want to run the # command as. if user is None: user = env.sudo_user or 'root' if user == env.user: run(cmd) else: # Temporarily disable prefixes and handle them ourselves. # We need to do that so that the prefix takes effect in the # shell where the command is executed rather than the shell # where su is executed. prefixes = list(env.command_prefixes) with settings(command_prefixes=[]): # Support the prefix() context processor. glue = " && " prefix = (glue.join(prefixes) + glue) if prefixes else "" cmd = prefix + cmd # NOTE: Quote the command since it's being run in a shell. cmd = "%s %s" % (env.shell, pipes.quote(prefix + cmd)) # NOTE: Quote again since it's being run under su run('sudo su %s -c %s' % (user, pipes.quote(cmd))) def virtualenv(path=None): run_su('mkdir -p `dirname %(venv_path)s`' % env, user=env.deploy_user) run_su('if [ ! -d %(venv_path)s ];then ' ' virtualenv %(venv_path)s;' 'fi' % env, user=env.deploy_user) return prefix('source %(venv_path)s/bin/activate' % env) @task @roles('appservers') def restart(): """ Restart the application. """ sudo('supervisorctl restart homepage') @task @roles('appservers') def update(): """ Update the application. """ name = localexec("python setup.py --name", capture=True) version = localexec("python setup.py --version", capture=True) localexec("python setup.py sdist") tmp_path = run("mktemp --suffix=.tar.gz") put("dist/%s-%s.tar.gz" % (name, version), tmp_path, mode=0755) with virtualenv(): run_su('pip install %s' % tmp_path, user=env.deploy_user) @task @runs_once @roles('appservers') def migrate_db(): """ Migrate the database. """ with virtualenv(): # NOTE: The app runs as supervisord so # we run the migrate command as that user also. run_su("homepage migrate", user=env.deploy_user) @task @roles('appservers') def deploy(): """ Deploy the latest version of the app """ execute(update) execute(migrate_db) execute(restart)
Python
0
@@ -105,14 +105,8 @@ xec, - sudo, run @@ -1694,20 +1694,22 @@ %22%22%22%0A +run_ su -do ('superv
0614f520aba191d0992bde4f4de227f2c943e20d
tweak settings to remove secretkey and allowed hosts from base
config/settings/base.py
config/settings/base.py
# -*- coding: utf-8 -*- """ Django settings for config project. Generated by 'django-admin startproject' using Django 1.10.6. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ from __future__ import absolute_import, unicode_literals # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) SECRET_KEY = 'test' ALLOWED_HOSTS = ['192.168.1.7', '0.0.0.0', 'localhost', '127.0.0.1', 'a4a78554.ngrok.io'] # Application definition INSTALLED_APPS = [ 'django.contrib.sitemaps', 'wagtail.contrib.wagtailsitemaps', # First party apps 'common', 'member_calendar', 'home', 'bulletins', 'search', # Wagtail apps 'wagtail.wagtailforms', 'wagtail.wagtailredirects', 'wagtail.wagtailembeds', 'wagtail.wagtailsites', 'wagtail.wagtailusers', 'wagtail.wagtailsnippets', 'wagtail.wagtaildocs', 'wagtail.wagtailimages', 'wagtail.wagtailsearch', 'wagtail.wagtailadmin', 'wagtail.wagtailcore', 'wagtail.contrib.wagtailroutablepage', 'modelcluster', 'taggit', # Third party wagtail apps 'wagtailmenus', 'wagtail.contrib.modeladmin', # required for wagtailmenus 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'wagtailmenus.context_processors.wagtailmenus', ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/New_York' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Wagtail settings WAGTAIL_SITE_NAME = "PhillyDSA" # Base URL to use when referring to full URLs within the Wagtail admin backend - # e.g. in notification emails. Don't include '/admin' or a trailing slash BASE_URL = 'http://www.phillydsa.com'
Python
0
@@ -587,120 +587,8 @@ R)%0A%0A -SECRET_KEY = 'test'%0A%0AALLOWED_HOSTS = %5B'192.168.1.7', '0.0.0.0', 'localhost', '127.0.0.1', 'a4a78554.ngrok.io'%5D%0A%0A # Ap
b181ad6d8d54a8e72a5a1838f42746b5d592732f
update documentation and add support for more dictionaries.
index.py
index.py
# Author: Colton Sweeney # Date: August 10, 2017 # Name: TrustRadius Review Scraper # # Lang: Python # Dependencies: BeautifulSoup4 # Requests # # Description: As part of my current workload, I have to create # weekly reports gathered from reviews on TrustRadius. # In order to expedite this process, I decided to create # simple Python bot that scours the TrustRadius page for # all new reviews and then creates detailed reports directly # from the information gathered in those reports. from bs4 import BeautifulSoup import requests # Open up TrustRadius page for Sitefinity url = "https://www.trustradius.com/products/progress-sitefinity/reviews" data = requests.get(url).text soup = BeautifulSoup(data, "html.parser") # Find all review links from main product page query = soup.find_all('a', { 'class' : 'link-to-review-btn' }) # List that holds URLs of individual reviews links = [] # Append all the URLs to the list we created for link in query: links.append('https://www.trustradius.com' + link.get('href')) # Function for returning review sections from review page # return (dictionary): a key-value list of the headings and review text # parameters: link (string): the url for the review def findMaterials(link): # Parse the given link into some Beautiful Soup req = requests.get(link).text review = BeautifulSoup(req, 'html.parser') # Set up list string variables. sectionHeading = [] sectionText = [] # Perform find.contents[] for all of the headings and text # and append them to our functions variables for find in review.find_all('div', {'class': 'description'}): # Recieve review section headings sectionHeading.append(find.contents[0].contents[0].contents[1].contents[0].contents[0].contents[0].contents[0].contents[0].text) sectionHeading.append(find.contents[0].contents[0].contents[1].contents[1].contents[0].contents[0].contents[0].contents[0].text) sectionHeading.append(find.contents[0].contents[0].contents[1].contents[2].contents[0].contents[0].contents[0].contents[0].text) sectionHeading.append(find.contents[0].contents[0].contents[1].contents[3].contents[0].contents[0].contents[0].contents[0].text) sectionHeading.append(find.contents[0].contents[0].contents[1].contents[4].contents[0].contents[0].contents[0].contents[0].text) sectionHeading.append(find.contents[0].contents[0].contents[1].contents[5].contents[0].contents[0].contents[0].contents[0].text) # Recieve review text sectionText.append(find.contents[0].contents[0].contents[1].contents[0].contents[1].contents[0].contents[0].contents[0].text) sectionText.append(find.contents[0].contents[0].contents[1].contents[1].contents[1].contents[0].contents[0].contents[0].text) sectionText.append(find.contents[0].contents[0].contents[1].contents[2].contents[1].contents[0].contents[0].contents[0].text) sectionText.append(find.contents[0].contents[0].contents[1].contents[3].contents[1].contents[0].contents[0].contents[0].text) sectionText.append(find.contents[0].contents[0].contents[1].contents[4].contents[1].contents[0].contents[0].contents[0].text) sectionText.append(find.contents[0].contents[0].contents[1].contents[5].contents[1].contents[0].contents[0].contents[0].text) # Return a dictionary object of headings and text return(dict(zip(sectionHeading, sectionText))) dictionary = findMaterials(links[0]) for x, y in dictionary.items(): print(x,y)
Python
0
@@ -562,16 +562,48 @@ reports. +%0A%0A# import required dependencies %0Afrom bs @@ -1134,16 +1134,57 @@ ref'))%0A%0A +print %22%25d links found.%5Cn%22 %25 len(links)%0A%0A%0A # Functi @@ -3479,24 +3479,25 @@ ts%5B0%5D.text)%0A +%0A # Return @@ -3594,42 +3594,232 @@ ))%0A%0A -dictionary = findMaterials(links%5B0 +%0A# DEBUGGING CODE FOR DEVELOPMENT%0A%0Adict1 = findMaterials(links%5B0%5D)%0Adict2 = findMaterials(links%5B1%5D)%0Adict3 = findMaterials(links%5B2%5D)%0Adict4 = findMaterials(links%5B3%5D)%0Adict5 = findMaterials(links%5B4%5D)%0Adict6 = findMaterials(links%5B5 %5D)%0A%0A @@ -3834,22 +3834,17 @@ in dict -ionary +5 .items() @@ -3857,12 +3857,13 @@ print(x, + y)%0A%0A
db36e08a81d16463d8c76b896593aaeb91c057a0
Refactor into get_check_digit_from_checkable_int method
falcom/luhn.py
falcom/luhn.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. def convert_into_luhn_checkable_int (number): if number: return int(number) else: return None def rotate_digit (digit): if digit > 4: return (digit * 2) - 9 else: return digit * 2 def get_check_digit (number = None): number = convert_into_luhn_checkable_int(number) if number is None: return None return (9 * ((number // 10) + rotate_digit(number % 10))) % 10
Python
0.002407
@@ -176,33 +176,36 @@ s.%0A%0Adef -convert_into_luhn +get_check_digit_from _checkab @@ -229,76 +229,70 @@ -if number:%0A return int(number)%0A%0A else:%0A return None +return (9 * ((number // 10) + rotate_digit(number %25 10))) %25 10 %0A%0Ade @@ -446,34 +446,54 @@ +if number - = convert_into_luhn +:%0A return get_check_digit_from _che @@ -507,37 +507,29 @@ int( +int( number) +) %0A%0A -if number is Non +els e:%0A @@ -551,72 +551,4 @@ one%0A -%0A return (9 * ((number // 10) + rotate_digit(number %25 10))) %25 10%0A
29be4cad4ab90fe5d1fc087f0de2e8a575ced40b
Bump version
nanoservice/version.py
nanoservice/version.py
VERSION = '0.3.0'
Python
0
@@ -8,11 +8,11 @@ = '0.3. -0 +1 '%0A
f66e3e965c00c455608dba994575098e1cd246ae
Update request_tracking_codes.py
samples/request_tracking_codes.py
samples/request_tracking_codes.py
from ..correios.client import Correios from ..correios.models.user import User, Service def get_tracking_codes(service, quantity): olist_user = User('Your Company\'s Name', 'Your Company\'s CNPJ') client = Correios('Your Correio\'s username', 'Your correio\'s password') tracking_codes = client.request_tracking_codes(olist_user, Service.get(service), quantity=quantity) print(tracking_codes) get_tracking_codes('41068', 1) # Request 1 PAC Tracking Code get_tracking_codes('40068', 1) # Request 1 SEDEX Tracking Code
Python
0.000003
@@ -1,24 +1,603 @@ +# Copyright 2017 Adler Medrado%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A%0A from ..correios.client i @@ -984,16 +984,21 @@ codes)%0A%0A + %0A get_trac
aa558384cdefdadc8141736a4168d9d096a3f1b3
Fix loaded apps
config/settings/base.py
config/settings/base.py
""" Django settings for scuole project. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ from __future__ import absolute_import, unicode_literals from os import environ, path import dj_database_url from django.core.exceptions import ImproperlyConfigured ########### # HELPERS # ########### def env(setting, default=None): """ Get the environment setting or return exception """ try: return environ[setting] except KeyError: if default is not None: return default else: error_msg = ('The {} env variable was not found ' 'and no default was set!').format(setting) raise ImproperlyConfigured(error_msg) ###################### # PATH CONFIGURATION # ###################### # This file BASE_FILE = path.abspath(__file__) # Absolute filesystem path to the project directory ROOT_DIR = path.abspath(path.join(path.dirname(BASE_FILE), '..', '..')) # Absolute filesystem path to the Django project's app folder APPS_DIR = path.join(ROOT_DIR, 'scuole') ####################### # DEBUG CONFIGURATION # ####################### DEBUG = False TEMPLATE_DEBUG = DEBUG ##################### # APP CONFIGURATION # ##################### DJANGO_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) THIRD_PARTY_APPS = ( ) LOCAL_APPS = ( 'scuole.regions', 'scuole.states', ) # https://docs.djangoproject.com/en/1.8/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS ############################ # MIDDLEWARE CONFIGURATION # ############################ # https://docs.djangoproject.com/en/1.8/topics/http/middleware/ MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ########################## # TEMPLATE CONFIGURATION # ########################## # https://docs.djangoproject.com/en/1.8/topics/templates/#configuration TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ path.join(APPS_DIR, 'templates'), ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], }, }, ] ########################## # DATABASE CONFIGURATION # ########################## # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': dj_database_url.config(default='postgres://localhost/scuole') } DATABASES['default']['ATOMIC_REQUESTS'] = True ############################# # STATIC FILE CONFIGURATION # ############################# # https://docs.djangoproject.com/en/1.8/ref/settings/#static-root STATIC_ROOT = path.join(APPS_DIR, 'assets') # https://docs.djangoproject.com/en/1.8/ref/settings/#static-url STATIC_URL = '/static/' # https://docs.djangoproject.com/en/1.8/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = ( path.join(APPS_DIR, 'static'), ) # https://docs.djangoproject.com/en/1.8/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) ############################ # MEDIA FILE CONFIGURATION # ############################ # https://docs.djangoproject.com/en/1.8/ref/settings/#media-root MEDIA_ROOT = path.join(APPS_DIR, 'media') # https://docs.djangoproject.com/en/1.8/ref/settings/#media-url MEDIA_URL = '/media/' ##################### # URL CONFIGURATION # ##################### ROOT_URLCONF = 'config.urls' # https://docs.djangoproject.com/en/1.8/ref/settings/#wsgi-application WSGI_APPLICATION = 'config.wsgi.application' ######################### # GENERAL CONFIGURATION # ######################### # https://docs.djangoproject.com/en/1.8/ref/settings/#language-code LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' # https://docs.djangoproject.com/en/1.8/ref/settings/#use-i18n USE_I18N = True # https://docs.djangoproject.com/en/1.8/ref/settings/#use-l10n USE_L10N = True # https://docs.djangoproject.com/en/1.8/ref/settings/#use-tz USE_TZ = True
Python
0.000001
@@ -5337,16 +5337,158 @@ z%0AUSE_TZ = True%0A +%0A#########################%0A# GENERAL CONFIGURATION #%0A#########################%0A%0ADATA_FOLDER = env('DATA_FOLDER', path.join(ROOT_DIR, 'data'))%0A
f3791ea0ed11d46edf9998b80fd1ddd54d7e9b20
Bump to pre-release version 1.0.rc2.
farcy/const.py
farcy/const.py
"""Constants used throughout Farcy.""" import os import re __version__ = '1.0.rc1' VERSION_STR = 'farcy v{0}'.format(__version__) CONFIG_DIR = os.path.expanduser('~/.config/farcy') MD_VERSION_STR = ('[{0}](https://github.com/appfolio/farcy)' .format(VERSION_STR)) FARCY_COMMENT_START = '_{0}_'.format(MD_VERSION_STR) NUMBER_RE = re.compile('(\d+)') APPROVAL_PHRASES = [x.strip() for x in """ Amazing Bravo Excellent Great job Lookin' good Outstanding work Perfect Spectacular Tremendous Well done Wicked awesome Winning Wonderful Wow You are awesome You do not miss a thing """.split('\n') if x.strip()] STATUS_CONTEXT = 'farcy'
Python
0
@@ -74,17 +74,17 @@ '1.0.rc -1 +2 '%0A%0AVERSI
2a6a6703aa63e75b7961d14d09a3472fe321f5de
Use safe json dump when serializing parameters (closes #96)
backslash/api.py
backslash/api.py
import copy import gzip import json import random import time import requests from requests.exceptions import ConnectionError, ReadTimeout from munch import munchify from sentinels import NOTHING from urlobject import URLObject as URL from .__version__ import __version__ as BACKSLASH_CLIENT_VERSION from ._compat import BytesIO, TextIOWrapper, iteritems from .comment import Comment from .error import Error from .exceptions import BackslashClientException, ParamsTooLarge from .session import Session from .suite import Suite from .test import Test from .user import User from .utils import raise_for_status, compute_memory_usage from .warning import Warning _RETRY_STATUS_CODES = frozenset([ requests.codes.bad_gateway, requests.codes.gateway_timeout, ]) _TYPES_BY_TYPENAME = { 'session': Session, 'test': Test, 'error': Error, 'warning': Warning, 'comment': Comment, 'suite': Suite, 'user': User, } _COMPRESS_THRESHOLD = 4 * 1024 _MAX_PARAMS_COMPRESSED_SIZE = 5 * 1024 * 1024 # 5Mb _MAX_PARAMS_UNCOMPRESSED_SIZE = 10 * 1024 * 1024 # 10Mb class API(object): def __init__(self, client, url, runtoken, timeout_seconds=60): super(API, self).__init__() self.client = client self.url = URL(url) self.runtoken = runtoken self.session = requests.Session() self.session.headers.update({ 'X-Backslash-run-token': self.runtoken, 'X-Backslash-client-version': BACKSLASH_CLIENT_VERSION, }) self.call = CallProxy(self) self._cached_info = None self._timeout = timeout_seconds def __del__(self): if self.session is not None: self.session.close() def info(self): """Inspects the remote API and returns information about its capabilities """ if self._cached_info is None: resp = self.session.options(self.url.add_path('api'), timeout=self._timeout) raise_for_status(resp) self._cached_info = munchify(resp.json()) return copy.deepcopy(self._cached_info) def call_function(self, name, params=None): is_compressed, data = self._serialize_params(params) headers = {'Content-type': 'application/json'} if is_compressed: headers['Content-encoding'] = 'gzip' for _ in self._iter_retries(): try: resp = self.session.post( self.url.add_path('api').add_path(name), data=data, headers=headers, timeout=self._timeout) except (ConnectionError, ReadTimeout, ): continue if resp.status_code not in _RETRY_STATUS_CODES: break else: raise BackslashClientException( 'Maximum number of retries exceeded for calling Backslash API') raise_for_status(resp) return self._normalize_return_value(resp) def _iter_retries(self, timeout=30, sleep_range=(3, 10)): start_time = time.time() end_time = start_time + timeout while True: yield if time.time() < end_time: time.sleep(random.randrange(*sleep_range)) def get(self, path, raw=False, params=None): resp = self.session.get(self.url.add_path(path), params=params, timeout=self._timeout) raise_for_status(resp) if raw: return resp.json() else: return self._normalize_return_value(resp) def delete(self, path, params=None): resp = self.session.delete(self.url.add_path(path), params=params, timeout=self._timeout) raise_for_status(resp) return resp def _normalize_return_value(self, response): json_res = response.json() if json_res is None: return None result = json_res.get('result') if result is None: if isinstance(json_res, dict): for key, value in json_res.items(): if isinstance(value, dict) and value.get('type') == key: return self.build_api_object(value) return json_res elif isinstance(result, dict) and 'type' in result: return self.build_api_object(result) return result def build_api_object(self, result): objtype = self._get_objtype(result) if objtype is None: return result return objtype(self.client, result) def _get_objtype(self, json_object): typename = json_object['type'] return _TYPES_BY_TYPENAME.get(typename) def _serialize_params(self, params): if params is None: params = {} returned = {} if compute_memory_usage(params) > _MAX_PARAMS_UNCOMPRESSED_SIZE: raise ParamsTooLarge() for param_name, param_value in iteritems(params): if param_value is NOTHING: continue returned[param_name] = param_value compressed = False returned = json.dumps(returned) if len(returned) > _COMPRESS_THRESHOLD: compressed = True returned = self._compress(returned) if len(returned) > _MAX_PARAMS_COMPRESSED_SIZE: raise ParamsTooLarge() return compressed, returned def _compress(self, data): s = BytesIO() with gzip.GzipFile(fileobj=s, mode='wb') as f: with TextIOWrapper(f) as w: w.write(data) return s.getvalue() class CallProxy(object): def __init__(self, api): super(CallProxy, self).__init__() self._api = api def __getattr__(self, attr): if attr.startswith('_'): raise AttributeError(attr) def new_func(**params): return self._api.call_function(attr, params) new_func.__name__ = attr return new_func
Python
0
@@ -5035,32 +5035,46 @@ n.dumps(returned +, default=repr )%0A if len
035d5feee8ea0691e5777a7b96c362877bcf01ca
Add logging
consumerSQS/consumer.py
consumerSQS/consumer.py
import boto3 import logging from config import config import answer import json import time import librarian def work(message): message = json.loads(message) print(type(message)) print(message) return sendToManager(message) def sendToManager(message): if("entry" in message): um = librarian.User_manager(message["entry"][0]["messaging"][0]["sender"]["id"]) try: um.user_event("MESSAGE",str(message["entry"][0]["messaging"][0]["message"]["text"])) except Exception as e: print(e) um.user_event("MESSAGE",str(message["entry"][0]["messaging"][0]["message"]["attachments"][0]["url"])) return True else: um = librarian.User_manager(int(message["state"])) um.user_event("MESSAGE",str(message["code"])) return True def parrot_work(message): try : msgToSend = "I ear your request :"+str(message["entry"][0]["messaging"][0]["message"]["text"]) idReceiver = message["entry"][0]["messaging"][0]["sender"]["id"] print (idReceiver+":"+msgToSend) answer.send_message(msgToSend,idReceiver) answer.send_message("I will",idReceiver) return True except Exception as e: print(e) return False sqs = boto3.resource('sqs',aws_access_key_id = config["access_key"], aws_secret_access_key=config["secret_access_key"], region_name="us-west-2", endpoint_url="https://sqs.us-west-2.amazonaws.com/731910755973/MessagesYouMus.fifo") while True: queue = sqs.get_queue_by_name(QueueName='MessagesYouMus.fifo') for msg in queue.receive_messages(): try: print("Received ="+str(json.loads(msg.body))) status = work(json.loads(msg.body)) msg.delete() except: pass time.sleep(0.2)
Python
0.000002
@@ -1767,16 +1767,31 @@ except + Exception as e :%0A @@ -1801,11 +1801,15 @@ p -ass +rint(e) %0A
e14b8c6b06c75414f42f730e4c1e1a9208e335b0
correct shebang
fetch/fetch.py
fetch/fetch.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Greedy climate data fetch """ filename = 'wwis.json' indexurl = 'http://worldweather.wmo.int/en/json/full_city_list.txt' baseurl = 'http://worldweather.wmo.int/en/json/{0}_en.xml' guideurl = 'http://worldweather.wmo.int/en/dataguide.html' notice = 'Please note the guidelines at {0}' usage = """{0} <index file> [output file] Data will be downloaded into {1} if no second argument given. The full index file is available for download at {2} You can re-run this script to continue downloading in the case of failures.""" from sys import argv import urllib.request import csv import simplejson as json import time import sys def fetch_entry(id): url = baseurl.format(id) try: f = urllib.request.urlopen(url).read() entry = json.loads(f.decode()) except: return -1 time.sleep(0.1) # don't DoS return entry def nice_entry(entry, country): data = entry['city'] data['country'] = country return data if __name__ == '__main__': if len(argv) < 2: print(usage.format(argv[0], filename, indexurl)) exit(1) print(notice.format(guideurl)) if len(argv) > 2: filename = argv[2] data = {} try: with open(filename, 'r') as f: data = json.load(f) except: pass with open(argv[1], 'r', newline='') as f: reader = csv.reader(f, delimiter=';', quotechar='"') for row in reader: if len(row) < 3: print('?', end='', file=sys.stderr) continue if row[0] == 'Country': continue key = row[2] if key in data: print('✓', end='', file=sys.stderr) continue sys.stderr.flush() entry = fetch_entry(key) if entry == -1: print('⚡', end='', file=sys.stderr) break # bail out, save what we have print('.', end='', file=sys.stderr) data[key] = nice_entry(entry, row[0]) print('', file=sys.stderr) with open(filename, 'w') as f: json.dump(data, f, sort_keys=True, indent='\t')
Python
0.997942
@@ -8,14 +8,19 @@ bin/ +env python +3 %0A# -
47555ef5589ccc07a44d9589c93be4fa193625c7
change qe setting
tests/test_ase_setup/qe_setup.py
tests/test_ase_setup/qe_setup.py
import os from ase.calculators.espresso import Espresso # set up executable label = 'AgI' input_file_name = label+'.pwi' output_file_name = label+'.pwo' no_cpus = 1 npool = 1 pw_loc = os.environ.get('PWSCF_COMMAND') #pw_loc = '/n/home08/xiey/q-e/bin/pw.x' #os.environ['ASE_ESPRESSO_COMMAND'] = 'srun -n {0} --mpi=pmi2 {1} -npool {2} < {3} > {4}'.format(no_cpus, # pw_loc, npool, input_file_name, output_file_name) os.environ['ASE_ESPRESSO_COMMAND'] = '{0} < {1} > {2}'.format(pw_loc, input_file_name, output_file_name) # set up input parameters input_data = {'control': {'prefix': label, 'pseudo_dir': 'test_files/pseudos/', 'outdir': './out', #'verbosity': 'high', 'calculation': 'scf'}, 'system': {'ibrav': 0, 'ecutwfc': 20, # 45, 'ecutrho': 40, # 181, 'smearing': 'gauss', 'degauss': 0.02, 'occupations': 'smearing'}, 'electrons': {'conv_thr': 1.0e-03, #'startingwfc': 'file', 'electron_maxstep': 100, 'mixing_beta': 0.5}} # pseudo-potentials ion_pseudo = {'Ag': 'Ag.pbe-n-kjpaw_psl.1.0.0.UPF', 'I': 'I.pbe-n-kjpaw_psl.1.0.0.UPF'} # create ASE calculator dft_calc = Espresso(pseudopotentials=ion_pseudo, label=label, tstress=True, tprnfor=True, nosym=True, #noinv=True, input_data=input_data, kpts=(1,1,1)) dft_calc.parameters['parallel'] = False
Python
0.000001
@@ -1163,17 +1163,17 @@ : 1.0e-0 -3 +2 ,%0A @@ -1316,17 +1316,17 @@ eta': 0. -5 +7 %7D%7D%0A%0A# ps @@ -1682,44 +1682,4 @@ )) %0A -dft_calc.parameters%5B'parallel'%5D = False%0A
f935f6dceb86b2bf68a7b873f51c44534d626162
fix typo in release notes test
tests/test_make_release_notes.py
tests/test_make_release_notes.py
from datetime import datetime from mock import patch import os from StringIO import StringIO from unittest import TestCase from make_release_notes import ( DEVEL, get_bugs, get_purpose, make_notes, make_resolved_text, make_release_date, main, parse_args, PROPOSED, save_notes, ) from utils import temp_dir class FakeBug(object): def __init__(self, id, title, tags): self.id = id self.title = title self.tags = tags class FakeBugTask(object): def __init__(self, bug): self.bug = bug class MakeReleaseNotes(TestCase): def test_get_purpose(self): self.assertEqual(PROPOSED, get_purpose('1.20.0')) self.assertEqual(DEVEL, get_purpose('1.21-alpha1')) def test_get_bugs(self): tasks = [ FakeBugTask(FakeBug('1', 'one one', ['tech-debt'])), FakeBugTask(FakeBug(2, 'two two', ['ui']))] with patch('make_release_notes.get_lp_bug_tasks', return_value=tasks) as mock: bugs = get_bugs('script', '1.20.1') mock.assert_called_with('script', '1.20.1') self.assertEqual([(2, 'Two two')], bugs) def test_make_resolved_text(self): text = make_resolved_text([('1', 'One'), ('2', 'Long text ' * 10)]) expected = ( ' * One\n' ' Lp 1\n' '\n' ' * Long text Long text Long text Long text Long text Long text ' 'Long\n' ' text Long text Long text Long text\n' ' Lp 2' ) self.assertEqual(expected, text) def test_make_release_date(self): now = datetime.strptime('2015-03-01', '%Y-%m-%d') release_date = make_release_date(now=now) self.assertEqual('Sunday March 08', release_date) def test_make_notes_with_proposed_purpose(self): # Proposed purpose points to the proposed PPA without a warning. text = make_notes('1.20.0', PROPOSED, " * One\n Lp 1") self.assertIn( 'A new proposed stable release of Juju, 1.20.0, is here!', text) self.assertIn( 'https://launchpad.net/~juju/+archive/proposed', text) self.assertIn(' * One\n Lp 1', text) def test_make_notes_with_devel_purpose(self): # Devel purpose points to the devel PPA and a warning is included. text = make_notes('1.21-alpha1', DEVEL, " * One\n Lp 1") self.assertIn( 'A new development release of Juju, 1.21-alpha1, is here!', text) self.assertIn('sudo apt-add-repository ppa/devel', text) self.assertIn( 'https://jujucharms.com/docs/devel/temp-release-notes', text) def test_make_notes_with_notable(self): # The default value of None implies a stable bug fix release. text = make_notes('1.20.1', DEVEL, "* One\n Lp 1", notable=None) self.assertIn( 'This releases addresses stability and performance issues.', text) text = make_notes('1.20.1', DEVEL, "* One\n Lp 1", notable='') # When notable is an empty string, a reminder is added to the text. self.assertIn('[[Add the notable changes here.]]', text) # The notable text is inserted into the document. text = make_notes( '1.20.1', DEVEL, "* One\n Lp 1", notable='New stuff') self.assertIn('New stuff', text) def test_save_notes(self): # The notes are written to file when file_name is not None. with temp_dir() as base: file_name = '{0}/foo.txt'.format(base) save_notes('bar', file_name) self.assertTrue(os.path.exists(file_name)) with open(file_name) as rn: content = rn.read() self.assertEqual('bar', content) # When the file-name is None, the notes are written to stdout. with patch('sys.stdout', new_callable=StringIO) as so_mock: save_notes('bar', None) self.assertEqual('bar\n', so_mock.getvalue()) def test_parse_args(self): # Only the milestone is required. args = parse_args(['foo']) self.assertEqual('foo', args.milestone) self.assertEqual(None, args.file_name) self.assertEqual(None, args.previous) # A file_name can be passed to save the release notes too. args = parse_args(['--file-name', 'bar', 'foo']) # The previous release can be passed for the release notes. args = parse_args(['--previous', 'baz', 'foo']) self.assertEqual('baz', args.previous) def test_main(self): with patch('make_release_notes.get_lp_bug_tasks') as lp_mock: with patch('make_release_notes.save_notes') as save_mock: return_code = main(['script', '--file-name', 'foo', '1.20.0']) self.assertEqual(0, return_code) lp_mock.assert_called_with('script', '1.20.0') text = make_notes('1.20.0', PROPOSED, '') save_mock.assert_called_with(text, 'foo')
Python
0.000009
@@ -2617,16 +2617,21 @@ tory ppa +:juju /devel',
aeca55a5ca5a8b15314cc7bd31a3c89361436318
Add return type check test
tests/test_pandas_integration.py
tests/test_pandas_integration.py
from unittest import TestCase, main import numpy as np import pandas as pd import numpy.testing as npt from nimble import Events class TestAsPandasCondition(TestCase): def setUp(self): conditional_series = pd.Series([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) condition = (conditional_series > 0) self.events = Events(condition, sample_period=1) def test_as_series(self): validation_series = pd.Series([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) test_series = self.events.as_series() test_series.equals(validation_series) def test_as_array(self): validation_array = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) npt.assert_array_equal(validation_array, self.events.as_array()) class TestAsNpArrCondition(TestCase): def setUp(self): conditional_array = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) condition = (conditional_array > 0) self.events = Events(condition, sample_period=1) def test_as_series(self): validation_series = pd.Series([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) test_series = self.events.as_series() test_series.equals(validation_series) def test_as_array(self): validation_array = np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1]) npt.assert_array_equal(validation_array, self.events.as_array()) self.asser if __name__ == '__main__': main()
Python
0.000001
@@ -555,32 +555,99 @@ lidation_series) +%0A self.assertEqual(pd.core.series.Series, type(test_series)) %0A%0A def test_a @@ -808,16 +808,77 @@ rray())%0A + self.assertEqual(np.ndarray, type(validation_array))%0A %0A%0Aclass @@ -1304,16 +1304,83 @@ _series) +%0A self.assertEqual(pd.core.series.Series, type(test_series)) %0A%0A de @@ -1549,17 +1549,16 @@ rray())%0A -%0A @@ -1567,16 +1567,59 @@ lf.asser +tEqual(np.ndarray, type(validation_array))%0A %0A%0Aif __n
d6a2e89736932988650c9244139aae1c1b543a88
Stop skipping tests of secondary reads in Sharded mode.
tests/test_slave_okay_sharded.py
tests/test_slave_okay_sharded.py
# Copyright 2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test PyMongo's SlaveOkay with: - A direct connection to a standalone. - A direct connection to a slave. - A direct connection to a mongos. """ import itertools from pymongo.read_preferences import make_read_preference from pymongo.read_preferences import read_pref_mode_from_name try: from queue import Queue except ImportError: from Queue import Queue from mockupdb import MockupDB, going from pymongo import MongoClient from tests import unittest from tests.operations import operations class TestSlaveOkaySharded(unittest.TestCase): def setup_server(self, wire_version): self.mongos1, self.mongos2 = MockupDB(), MockupDB() # Collect queries to either server in one queue. self.q = Queue() for server in self.mongos1, self.mongos2: server.subscribe(self.q.put) server.run() self.addCleanup(server.stop) server.autoresponds('ismaster', maxWireVersion=wire_version, ismaster=True, msg='isdbgrid') self.mongoses_uri = 'mongodb://%s,%s' % (self.mongos1.address_string, self.mongos2.address_string) def create_slave_ok_sharded_test(mode, operation): def test(self): if mode == 'secondary': raise unittest.SkipTest('PYTHON-868') self.setup_server(operation.wire_version) if operation.op_type == 'always-use-secondary': raise unittest.SkipTest('PYTHON-868') slave_ok = True elif operation.op_type == 'may-use-secondary': slave_ok = mode != 'primary' elif operation.op_type == 'must-use-primary': slave_ok = False else: assert False, 'unrecognized op_type %r' % operation.op_type pref = make_read_preference(read_pref_mode_from_name(mode), tag_sets=None) client = MongoClient(self.mongoses_uri, read_preference=pref) with going(operation.function, client): request = self.q.get(timeout=1) request.reply(operation.reply) if slave_ok: self.assertTrue(request.slave_ok, 'SlaveOkay not set') else: self.assertFalse(request.slave_ok, 'SlaveOkay set') return test def generate_slave_ok_sharded_tests(): modes = 'primary', 'secondary', 'nearest' matrix = itertools.product(modes, operations) for entry in matrix: mode, operation = entry test = create_slave_ok_sharded_test(mode, operation) test_name = 'test_%s_with_mode_%s' % ( operation.name.replace(' ', '_'), mode) test.__name__ = test_name setattr(TestSlaveOkaySharded, test_name, test) generate_slave_ok_sharded_tests() if __name__ == '__main__': unittest.main()
Python
0
@@ -1833,90 +1833,8 @@ f):%0A - if mode == 'secondary':%0A raise unittest.SkipTest('PYTHON-868')%0A @@ -1939,58 +1939,8 @@ y':%0A - raise unittest.SkipTest('PYTHON-868')%0A
bb330514b5a18389c451cf3ba58a72d7711c2ceb
Add unit tests
tests/unit/modules/test_event.py
tests/unit/modules/test_event.py
# -*- coding: utf-8 -*- """ :codeauthor: Rupesh Tare <rupesht@saltstack.com> """ # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt Libs import salt.modules.event as event import salt.utils.event from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch # Import Salt Testing Libs from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase class EventTestCase(TestCase, LoaderModuleMockMixin): """ Test cases for salt.modules.event """ def setup_loader_modules(self): return { event: { "__opts__": { "id": "id", "sock_dir": RUNTIME_VARS.TMP, "transport": "zeromq", } } } def test_fire_master(self): """ Test for Fire an event off up to the master server """ with patch("salt.crypt.SAuth") as salt_crypt_sauth, patch( "salt.transport.client.ReqChannel.factory" ) as salt_transport_channel_factory: preload = { "id": "id", "tag": "tag", "data": "data", "tok": "salt", "cmd": "_minion_event", } with patch.dict( event.__opts__, {"transport": "A", "master_uri": "localhost", "local": False}, ): with patch.object(salt_crypt_sauth, "gen_token", return_value="tok"): with patch.object( salt_transport_channel_factory, "send", return_value=None ): self.assertTrue(event.fire_master("data", "tag", preload)) with patch.dict(event.__opts__, {"transport": "A", "local": False}): with patch.object( salt.utils.event.MinionEvent, "fire_event", side_effect=Exception("foo"), ): self.assertFalse(event.fire_master("data", "tag")) def test_fire(self): """ Test to fire an event on the local minion event bus. Data must be formed as a dict. """ with patch("salt.utils.event") as salt_utils_event: with patch.object(salt_utils_event, "get_event") as mock: mock.fire_event = MagicMock(return_value=True) self.assertTrue(event.fire("data", "tag")) def test_send(self): """ Test for Send an event to the Salt Master """ with patch.object(event, "fire_master", return_value="B"): self.assertEqual(event.send("tag"), "B")
Python
0.000001
@@ -2767,8 +2767,1162 @@ ), %22B%22)%0A +%0A def test_send_use_master_when_local_false(self):%0A %22%22%22%0A Test for Send an event when opts has use_master_when_local and its False%0A %22%22%22%0A patch_master_opts = patch.dict(event.__opts__, %7B%22use_master_when_local%22: False%7D)%0A patch_file_client = patch.dict(event.__opts__, %7B%22file_client%22: %22local%22%7D)%0A with patch.object(event, %22fire%22, return_value=%22B%22) as patch_send:%0A with patch_master_opts, patch_file_client, patch_send:%0A self.assertEqual(event.send(%22tag%22), %22B%22)%0A patch_send.assert_called_once()%0A%0A def test_send_use_master_when_local_true(self):%0A %22%22%22%0A Test for Send an event when opts has use_master_when_local and its True%0A %22%22%22%0A patch_master_opts = patch.dict(event.__opts__, %7B%22use_master_when_local%22: True%7D)%0A patch_file_client = patch.dict(event.__opts__, %7B%22file_client%22: %22local%22%7D)%0A with patch.object(event, %22fire_master%22, return_value=%22B%22) as patch_send:%0A with patch_master_opts, patch_file_client, patch_send:%0A self.assertEqual(event.send(%22tag%22), %22B%22)%0A patch_send.assert_called_once()%0A
42dd21708e9f03850af3359dd0ffed15b6c08e0e
Include redirects in autopatrols
reports.py
reports.py
import mwclient import MySQLdb import datetime from displayTable import * class Reports: def __init__( self, site, db, wiki ): self.db = db self.site = site self.wiki = wiki # Oldest edited articles # Run time on enwiki 5 hours 23 minutes as of 8 Sept 2015 def forgotten_articles( self ): # Make the query cur = self.db.cursor() query = """SELECT p.page_title, p.page_namespace, p.page_is_redirect, p.page_touched, r.editcount FROM page p LEFT JOIN ( SELECT COUNT(*) AS editcount, rev_page FROM revision GROUP BY rev_page ) r ON r.rev_page = p.page_id WHERE page_is_redirect = 0 AND page_namespace = 0 AND p.page_id NOT IN ( SELECT pp_page FROM page_props WHERE pp_propname = 'disambiguation' ) ORDER BY page_touched LIMIT 500""" cur.execute( query ) # Extract the data into a Python nested list content = [] content.append( ['forgotten-articles-title', 'forgotten-articles-last-edited', 'forgotten-articles-editcount'] ) for row in cur.fetchall() : content.append( [ self.linkify(row[0]), datetime.datetime.strptime( row[3],'%Y%m%d%H%M%S'), row[4] ] ) # Format the data as wikitext text = display_report( self.wiki, content, 'forgotten-articles-desc' ) self.publish_report( 'Forgotten articles', text ) # Page count by namespace # Run time on enwiki 4 hours 8 minutes as of 8 Sept 2015 def page_count_by_namespace( self ): cur = self.db.cursor() query = """SELECT page_namespace, COUNT(*) AS total, SUM(page_is_redirect) AS redirect FROM page GROUP BY page_namespace""" cur.execute( query ) content = [] content.append( ['pagecount-namespace', 'pagecount-namespace-name', 'pagecount-total', 'pagecount-redirect', 'pagecount-non-redirect'] ) for row in cur.fetchall(): content.append( [ row[0], '{{subst:ns:' + str( row[0] ) + '}}', row[1], row[2], row[1]-row[2] ]) text = display_report( self.wiki, content , 'pagecount-desc' ) self.publish_report( 'Page count by namespace', text ) # Pages with most revisions def pages_with_most_revisions( self ): cur = self.db.cursor() query = """SELECT COUNT(*) AS revisions, rev_page, p.page_namespace, p.page_title FROM revision r LEFT JOIN ( SELECT page_id, page_title, page_namespace FROM page ) p ON r.rev_page = p.page_id GROUP BY rev_page ORDER BY revisions DESC LIMIT 1000""" cur.execute( query ) content = [] content.append( ['pagerevisions-namespace', 'pagerevisions-title', 'pagerevisions-revisions'] ) for row in cur.fetchall(): content.append( [ row[2], self.linkify( row[3], row[2] ), row[0] ]) text = display_report( self.wiki, content , 'pagerevisions-desc' ) self.publish_report( 'Pages with the most revisions', text ) # Editors eligible for autopatrol privileges def autopatrol_eligibles( self ): cur = self.db.cursor() query = """SELECT COUNT(*) AS creations, rev_user, u.user_name FROM revision r LEFT JOIN ( SELECT user_name, user_id FROM user ) u ON u.user_id = r.rev_user WHERE rev_parent_id = 0 AND rev_page NOT IN ( SELECT pp_page FROM page_props WHERE pp_propname = 'disambiguation' ) AND rev_page IN ( SELECT page_id FROM page WHERE page_namespace = 0 ) AND rev_user NOT IN ( SELECT DISTINCT ug_user FROM user_groups WHERE ug_group IN ('bot', 'autoreviewer', 'bureaucrat', 'sysop') ) GROUP BY rev_user HAVING COUNT(*) > 25 ORDER BY creations DESC LIMIT 500""" cur.execute( query ) content = [] content.append( ['autopatrol-username', 'autopatrol-articles'] ) for row in cur.fetchall(): if row[2] is None: continue content.append( [ self.userify(row[2]), row[0] ] ) text = display_report( self.wiki, content , 'autopatrol-desc' ) self.publish_report( 'Editors eligible for Autopatrol privilege', text ) def talk_pages_by_size( self ): cur = self.db.cursor() query = """SELECT page_namespace, REPLACE( SUBSTRING_INDEX(page_title, '/', 1 ), '_', ' ' ) AS parent, SUM( page_len ) / 1024 / 1024 AS total_size FROM page WHERE page_namespace MOD 2 = 1 GROUP BY page_namespace, parent ORDER BY total_size DESC LIMIT 300""" cur.execute( query ) content = [] content.append( ['tpbs-namespace', 'tpbs-page', 'tpbs-size'] ) for row in cur.fetchall(): content.append( [ row[0], self.linkify( row[1], row[0] ), row[2] ] ) text = display_report( self.wiki, content, 'tpbs-desc' ) self.publish_report( 'Talk pages by size', text ) ''' Publish report on page with given title, with the given content @param title Page title @param content Content to be displayed on page ''' def publish_report( self, title, content ): page = self.site.Pages[ 'Wikipedia:Database reports/' + str( title ) ] page.save( content, summary = 'bot test edit' ) def linkify( self, title, namespace = None ): title = str( title ) title_clean = title.replace( '_', ' ' ) if namespace is None: return '[[' + title_clean + ']]' else: return '[[{{subst:ns:%s}}:%s]]' % (namespace, title_clean) def userify( self, name ): name = str(name) return '[[User:' + name + ' | ' + name + ']]'
Python
0
@@ -3210,16 +3210,40 @@ ace = 0 +OR page_is_redirect = 1 )%0A%09%09%09%09
3405f16f9e687507a1428e3add0326ab0f2130a2
fix bug
apps/user.py
apps/user.py
# coding: utf-8 import uuid, datetime from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from sqlalchemy.orm.state import InstanceState from apps import BaseRequestHandler from apps.models import User, Loud from utils.decorator import authenticated, availabelclient from utils.constants import Fail, Success from utils.imagepp import save_images from utils.sp import sms_send, ret_code2desc from utils.mkthings import generate_password class UserHandler(BaseRequestHandler): @authenticated def get(self, phn): user = User.query.get_by_phone(phn) if user: info = user.user_to_dict(self.current_user) else: info = None self.render_json(info) @availabelclient def post(self, phn): user = User() data = self.get_data() data['avatar'] = 'i/%s.jpg' % data['phone'] user.from_dict(data) info = Fail if user.save(): info = Success self.render_json(info) @authenticated def put(self, phn): ''' The User object can't modify phone ''' user = self.current_user data = self.get_data() user.from_dict(data) self.render_json(user.save() and Success or Fail) @authenticated def delete(self, phn): user = self.current_user data = self.get_data() info = Fail if 'password' in data and user.authenticate(data['password']): self.db.delete(user) # PS: delete all relation data self.db.commit() info = Success # delete user data self.render_json(info) class AuthHandler(BaseRequestHandler): @availabelclient def post(self): new_info = self.get_data() info = Fail if 'phone' in new_info and 'password' in new_info: user = User.query.get_by_phone(new_info['phone']) if user and user.authenticate(new_info['password']): user.token = uuid.uuid5(uuid.NAMESPACE_URL, "%s%s" % (user.phone, datetime.datetime.now())).hex info = user.user_to_dict_by_auth() # must before save user.save() self.render_json(info) class PasswordHandler(BaseRequestHandler): @authenticated def post(self): data = self.get_data() info = Fail if 'new_password' in data and 'old_password' in data: if self.current_user.authenticate(data['old_password']): self.current_user.password = data['new_password']; self.current_user.save() info = Success self.render_json(info) class DelUserHandler(BaseRequestHandler): @authenticated def put(self, phn): user = self.current_user data = self.get_data() info = Fail if 'password' in data and user.authenticate(data['password']): self.db.delete(user) # PS: delete all relation data self.db.commit() info = Success # delete user data self.render_json(info) class UploadHandler(BaseRequestHandler): @availabelclient def post(self): info = Fail if 'photo' in self.request.files: save_images(self.request.files['photo']) info = Success self.render_json(info) class RestPasswordHandler(BaseRequestHandler): @availabelclient def get(self): info = Fail user = User.query.get_by_phone(self.get_argument('p')) if user: new_password = generate_password() sms_send(user.phone, {'name': user.name, 'password': new_password}, 2) user.password = new_password user.save() info = Success return self.render_json(info) class SendCodeHandler(BaseRequestHandler): @availabelclient def get(self): phone = self.get_argument('p') code = self.get_argument('code') user = User.query.get_by_phone(phone) info = Fail if phone and code and not user and: sms_send(phone, {'code': code}, 1) info = Success return self.render_json(info)
Python
0.000001
@@ -4097,20 +4097,16 @@ not user - and :%0A
4680812bcefe32a113547485fae692ee5f6d7a52
Fix typing bugs in loss utils.
enn_acme/losses/utils.py
enn_acme/losses/utils.py
# Copyright 2022 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Helpful functions relating to losses.""" import dataclasses import typing as tp import chex from enn import base as enn_base from enn import losses as enn_losses from enn_acme import base as agent_base import haiku as hk import reverb # Specific types _LossFn = agent_base.LossFn[agent_base.Input, agent_base.Output] _Enn = enn_base.EpistemicNetwork[agent_base.Input, agent_base.Output] def add_l2_weight_decay( loss_fn: _LossFn, scale_fn: tp.Callable[[int], float], # Maps learner_steps --> l2 decay predicate: tp.Optional[enn_losses.PredicateFn] = None, ) -> _LossFn: """Adds l2 weight decay to a given loss function.""" def new_loss( enn: _Enn, params: hk.Params, state: agent_base.LearnerState, batch: reverb.ReplaySample, key: chex.PRNGKey, ) -> tp.Tuple[chex.Array, agent_base.LossMetrics]: loss, metrics = loss_fn(enn, params, state, batch, key) l2_penalty = enn_losses.l2_weights_with_predicate(params, predicate) decay = l2_penalty * scale_fn(state.learner_steps) total_loss = loss + decay metrics['decay'] = decay metrics['raw_loss'] = loss return total_loss, metrics return new_loss @dataclasses.dataclass class CombineLossConfig(tp.Generic[agent_base.Input, agent_base.Output]): loss_fn: _LossFn name: str = 'unnamed' # Name for the loss function weight: float = 1. # Weight to scale the loss by def combine_losses(losses: tp.Sequence[CombineLossConfig]) -> _LossFn: """Combines multiple losses into a single loss.""" def loss_fn( enn: _Enn, params: hk.Params, state: agent_base.LearnerState, batch: reverb.ReplaySample, key: chex.PRNGKey, ) -> tp.Tuple[chex.Array, agent_base.LossMetrics]: combined_loss = 0. combined_metrics = {} for loss_config in losses: loss, metrics = loss_config.loss_fn(enn, params, state, batch, key) combined_metrics[f'{loss_config.name}:loss'] = loss for name, value in metrics.items(): combined_metrics[f'{loss_config.name}:{name}'] = value combined_loss += loss_config.weight * loss return combined_loss, combined_metrics return loss_fn
Python
0.002287
@@ -932,34 +932,45 @@ b%0A%0A%0A -# Specific types%0A_LossFn = +def add_l2_weight_decay(%0A loss_fn: age @@ -1024,126 +1024,8 @@ put%5D -%0A_Enn = enn_base.EpistemicNetwork%5Bagent_base.Input, agent_base.Output%5D%0A%0A%0Adef add_l2_weight_decay(%0A loss_fn: _LossFn ,%0A @@ -1158,31 +1158,78 @@ None,%0A) -%3E -_LossFn +agent_base.LossFn%5Bagent_base.Input, agent_base.Output%5D :%0A %22%22%22Adds @@ -1292,36 +1292,94 @@ oss(%0A enn: -_Enn +enn_base.EpistemicNetwork%5Bagent_base.Input, agent_base.Output%5D ,%0A params: @@ -1976,23 +1976,70 @@ oss_fn: -_LossFn +agent_base.LossFn%5Bagent_base.Input, agent_base.Output%5D %0A name: @@ -2158,16 +2158,21 @@ _losses( +%0A losses: @@ -2204,21 +2204,107 @@ nfig -%5D) -%3E _LossFn +%5Bagent_base.Input, agent_base.Output%5D%5D,%0A) -%3E agent_base.LossFn%5Bagent_base.Input, agent_base.Output%5D :%0A @@ -2385,12 +2385,70 @@ nn: -_Enn +enn_base.EpistemicNetwork%5Bagent_base.Input, agent_base.Output%5D ,%0A @@ -3047,9 +3047,8 @@ loss_fn%0A -%0A
24847fc9842776e08e7acdf08711e9b778bdf47f
fix regacy code
skiski/ski.py
skiski/ski.py
from helper import Typename class VirtualCurry: def __b__(self, x): return self.dot(x) class I(metaclass=Typename("I")): """ the identity operator (lambda x: x)(5) => 5 >>> I(5).b() 5 """ def __init__(self, x): self.x = x def b(self): return self.x @classmethod def __b__(cls, x): if isinstance(cls, type): return cls(x) else: return cls.dot(x) def dot(self, x): y = self.b() return y.__b__(x) def __str__(self): return "(I " + str(self.x) + ") " def __repr__(self): return self.__str__() @classmethod def to_sk(cls): return S(K).dot(K) class K(metaclass=Typename("K")): """ which forms constant functions (lambda x, y)(True, False) => True >>> K(True).dot(False).b() True """ def __init__(self, x): self.x = x def dot(self, y): return K2(self.x, y) def __str__(self): return "(K " + str(self.x) + ") " def __repr__(self): return self.__str__() class K2(metaclass=Typename("K")): def __init__(self, x, y): self.x = x self.y = y def b(self): return self.x def dot(self, z): x = self.b() try: if x.is_class: return x.d(z) else: return x.dot(z) except AttributeError: return x(z) def __repr__(self): return self.__str__() def __str__(self): return "(K " + str(self.x) + " " + str(self.y) + ") " class S(metaclass=Typename("S")): """ a stronger composition operator (lambda x, y, z)(f, g, h) => f(h, g(h)) >>> S(K).dot(K).dot(5).b().b() 5 SII(SII) combinator is infinity loop ;) >>> siisii = S(I).dot(I).dot(S(I).dot(I)) >>> siisii.b().b().b().b() (S I I (I (S I I) ) ) """ def __init__(self, x): self.x = x def dot(self, y): return S2(self.x, y) def b(self): return self def __str__(self): return "(S " + str(self.x) + ") " def __repr__(self): return self.__str__() class S2(VirtualCurry, metaclass=Typename("S")): def __init__(self, x, y): self.x = x self.y = y def dot(self, z): return S3(self.x, self.y, z) def __str__(self): return "(S " + str(self.x) + " " + str(self.y) + ") " def b(self): return self def __repr__(self): return self.__str__() class S3(metaclass=Typename("S")): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def b(self): yz = self.__b__(self.y, self.z) xz = self.__b__(self.x, self.z) return xz.dot(yz) def __str__(self): return "(S " + str(self.x) + " " + str(self.y) + " " + str(self.z) + ") " def __repr__(self): return self.__str__() def _eval_i_(self, x): while isinstance(x, I): x = x.b() return x def __b__(self, x, y): x = self._eval_i_(x) y = self._eval_i_(y) try: if isinstance(x, type): return x(y) else: return x.dot(y) except AttributeError: return x(z) if __name__ == "__main__": import doctest doctest.testmod()
Python
0.000015
@@ -1318,19 +1318,29 @@ if -x.is_class: +isinstance(x, type): %0A @@ -1360,18 +1360,16 @@ return x -.d (z)%0A @@ -1417,63 +1417,8 @@ t(z) -%0A except AttributeError:%0A return x(z) %0A%0A