text
stringlengths
4
1.02M
meta
dict
n=int(input()) e=int(input()) edge_u=list() edge_v=list() for i in range(e): x,y=map(int,input().split()) edge_u.append(x) edge_v.append(y) # create empty adjacency lists - one for each node - # with a Python list comprehension adjList = [[] for k in range(n)] for i in range(len(edge_u)): u=edge_u[i] v=edge_v[i] adjList[u].append(v) def dfs(graph, start): visited=[False for k in range(n)] stack=[start] visited[start]=True order=list() while stack: vertex=stack.pop() order.append(vertex) for i in graph[vertex]: if not visited[i]: stack.append(i) visited[i]=True return order print(dfs(adjList,0))
{ "content_hash": "2544fb932d8afca1c3d81c957cd06c50", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 52, "avg_line_length": 21.264705882352942, "alnum_prop": 0.5822959889349931, "repo_name": "saisankargochhayat/algo_quest", "id": "18eaa5a663a5a095a42212867dd81b2909d19862", "size": "736", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Misc/graph-dfs-directed.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "405" }, { "name": "C++", "bytes": "9149" }, { "name": "HTML", "bytes": "1679" }, { "name": "Java", "bytes": "3648" }, { "name": "JavaScript", "bytes": "786" }, { "name": "Python", "bytes": "248621" }, { "name": "Ruby", "bytes": "2761" }, { "name": "Shell", "bytes": "610" } ], "symlink_target": "" }
""" Common webapp related base views. """ from pyramid.httpexceptions import HTTPMethodNotAllowed from pyramid.response import Response HTTP_METHODS = frozenset(["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]) class BaseView(object): """ A base view class supporting route and view configuration based on class attributes. """ _cors_headers = None cors_max_age = 0 # Cache preflight requests, default omit cors_origin = None # Allowed CORS origins, default omit methods = ("GET", "HEAD", "POST") # Supported HTTP methods. renderer = "json" # The name of the renderer to use. route = None # The url path for this view, e.g. `/hello`. @classmethod def configure(cls, config): """ Adds a route and a view with a JSON renderer based on the class route attribute. :param config: The Pyramid main configuration. :type config: :class:`pyramid.config.Configurator` """ path = cls.route name = path.lstrip("/").replace("/", "_") config.add_route(name, path) http_methods = cls.methods config.add_view( cls, route_name=name, renderer=cls.renderer, request_method=http_methods ) unsupported_methods = HTTP_METHODS - set(http_methods) if cls.cors_origin: unsupported_methods = unsupported_methods - set(["OPTIONS"]) config.add_view( cls, attr="options", route_name=name, request_method="OPTIONS" ) cls._cors_headers = {"Access-Control-Allow-Origin": cls.cors_origin} if cls.cors_max_age: cls._cors_headers["Access-Control-Max-Age"] = str(cls.cors_max_age) if unsupported_methods: config.add_view( cls, attr="unsupported", route_name=name, request_method=tuple(unsupported_methods), ) def __init__(self, request): """ Instantiate the view with a request object. """ self.request = request if self._cors_headers: request.response.headers.update(self._cors_headers) def __call__(self): """ Call and execute the view, returning a response. """ raise NotImplementedError() def prepare_exception(self, exc): """Prepare an exception response.""" if isinstance(exc, Response) and self._cors_headers: exc.headers.update(self._cors_headers) return exc def options(self): """ Return a response for HTTP OPTIONS requests. """ # TODO: This does not actually parse the Origin header or # requested method. return Response(headers=self._cors_headers) def unsupported(self): """ Return a method not allowed response. """ raise HTTPMethodNotAllowed()
{ "content_hash": "6a9f79fa25db241dba7784d6fb0568db", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 86, "avg_line_length": 31.56989247311828, "alnum_prop": 0.5888964577656676, "repo_name": "mozilla/ichnaea", "id": "37ff61320ec90710b8c703549b0dd0e3eb1f6603", "size": "2936", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "ichnaea/webapp/view.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "34767" }, { "name": "Cython", "bytes": "16678" }, { "name": "Dockerfile", "bytes": "2819" }, { "name": "HTML", "bytes": "32679" }, { "name": "JavaScript", "bytes": "139102" }, { "name": "Makefile", "bytes": "11673" }, { "name": "Mako", "bytes": "432" }, { "name": "Python", "bytes": "1007139" }, { "name": "Shell", "bytes": "8899" } ], "symlink_target": "" }
import re from typing import Optional, Tuple, cast from .ast import Location from .location import SourceLocation, get_location from .source import Source __all__ = ["print_location", "print_source_location"] def print_location(location: Location) -> str: """Render a helpful description of the location in the GraphQL Source document.""" return print_source_location( location.source, get_location(location.source, location.start) ) _re_newline = re.compile(r"\r\n|[\n\r]") def print_source_location(source: Source, source_location: SourceLocation) -> str: """Render a helpful description of the location in the GraphQL Source document.""" first_line_column_offset = source.location_offset.column - 1 body = "".rjust(first_line_column_offset) + source.body line_index = source_location.line - 1 line_offset = source.location_offset.line - 1 line_num = source_location.line + line_offset column_offset = first_line_column_offset if source_location.line == 1 else 0 column_num = source_location.column + column_offset location_str = f"{source.name}:{line_num}:{column_num}\n" lines = _re_newline.split(body) # works a bit different from splitlines() location_line = lines[line_index] # Special case for minified documents if len(location_line) > 120: sub_line_index, sub_line_column_num = divmod(column_num, 80) sub_lines = [ location_line[i : i + 80] for i in range(0, len(location_line), 80) ] return location_str + print_prefixed_lines( (f"{line_num} |", sub_lines[0]), *[("|", sub_line) for sub_line in sub_lines[1 : sub_line_index + 1]], ("|", "^".rjust(sub_line_column_num)), ( "|", sub_lines[sub_line_index + 1] if sub_line_index < len(sub_lines) - 1 else None, ), ) return location_str + print_prefixed_lines( (f"{line_num - 1} |", lines[line_index - 1] if line_index > 0 else None), (f"{line_num} |", location_line), ("|", "^".rjust(column_num)), ( f"{line_num + 1} |", lines[line_index + 1] if line_index < len(lines) - 1 else None, ), ) def print_prefixed_lines(*lines: Tuple[str, Optional[str]]) -> str: """Print lines specified like this: ("prefix", "string")""" existing_lines = [ cast(Tuple[str, str], line) for line in lines if line[1] is not None ] pad_len = max(len(line[0]) for line in existing_lines) return "\n".join( prefix.rjust(pad_len) + (" " + line if line else "") for prefix, line in existing_lines )
{ "content_hash": "20923a35067a2b8abf06b12fdc371eb7", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 86, "avg_line_length": 35.246753246753244, "alnum_prop": 0.6031687546057479, "repo_name": "graphql-python/graphql-core", "id": "6d13b1e1a070e39f1592be4a69ce1303bdd1123b", "size": "2714", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/graphql/language/print_location.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2235538" } ], "symlink_target": "" }
import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Vandy_Computational_Workshop' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Vandy_Computational_Workshopdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Vandy_Computational_Workshop.tex', u'Vandy_Computational_Workshop Documentation', u"Victor Calderon and Mike Lund", 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'Vandy_Computational_Workshop', u'Vandy_Computational_Workshop Documentation', [u"Victor Calderon and Mike Lund"], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Vandy_Computational_Workshop', u'Vandy_Computational_Workshop Documentation', u"Victor Calderon and Mike Lund", 'Vandy_Computational_Workshop', 'Repository for the Computational Workshop Series Fall 2016-Spring 2017 taught at Vanderbilt University', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote'
{ "content_hash": "9a883bc34fa1a7719cda33d3e70d6c27", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 128, "avg_line_length": 33.21212121212121, "alnum_prop": 0.7005995828988529, "repo_name": "VandyAstroML/Vanderbilt_Computational_Bootcamp", "id": "2254b604d92677ef0440e3bbbb499cac4e4b74b0", "size": "8083", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/conf.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "3664687" }, { "name": "Makefile", "bytes": "1204" }, { "name": "Python", "bytes": "3812" }, { "name": "Shell", "bytes": "1077" }, { "name": "TeX", "bytes": "32843" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user_profile', '0003_auto_20160914_0043'), ] operations = [ migrations.AlterField( model_name='userprofile', name='hireable', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='userprofile', name='is_professional', field=models.BooleanField(default=False), ), ]
{ "content_hash": "361dcbf1bc1c4f42a48f83aafbeceb14", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 53, "avg_line_length": 24.47826086956522, "alnum_prop": 0.5879218472468917, "repo_name": "welliam/imagersite", "id": "c7a5f14a1854e63a3fa93e1f2eb6f1e995c5d467", "size": "636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "user_profile/migrations/0004_auto_20160914_0045.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "767" }, { "name": "HTML", "bytes": "9609" }, { "name": "Python", "bytes": "64285" } ], "symlink_target": "" }
from django.db.transaction import non_atomic_requests from django.utils.translation import ugettext from olympia import amo from olympia.amo.feeds import NonAtomicFeed from olympia.amo.templatetags.jinja_helpers import absolutify, url from olympia.amo.utils import render from olympia.lib.cache import cached from .models import AppVersion def get_versions(order=('application', 'version_int')): def fetch_versions(): apps = amo.APP_USAGE versions = dict((app.id, []) for app in apps) qs = list(AppVersion.objects.order_by(*order) .filter(application__in=versions) .values_list('application', 'version')) for app, version in qs: versions[app].append(version) return apps, versions return cached(fetch_versions, 'getv' + ''.join(order)) @non_atomic_requests def appversions(request): apps, versions = get_versions() return render(request, 'applications/appversions.html', dict(apps=apps, versions=versions)) class AppversionsFeed(NonAtomicFeed): # appversions aren't getting a created date so the sorting is kind of # wanky. I blame fligtar. def title(self): return ugettext(u'Application Versions') def link(self): return absolutify(url('apps.appversions')) def description(self): return ugettext(u'Acceptable versions for all applications on AMO.') def items(self): apps, versions = get_versions(order=('application', '-version_int')) return [(app, version) for app in apps for version in versions[app.id][:3]] return [(app, versions[app.id][:3]) for app in apps] def item_title(self, item): app, version = item return u'%s %s' % (app.pretty, version) item_description = '' def item_link(self): return self.link() def item_guid(self, item): return self.item_link() + '%s:%s' % item
{ "content_hash": "58e8003aa69241d64a31a4ad290ee9cf", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 76, "avg_line_length": 31.580645161290324, "alnum_prop": 0.6527068437180796, "repo_name": "harry-7/addons-server", "id": "029cd469f570f1dcdd7b3cef48fe88a8cff7741b", "size": "1958", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/olympia/applications/views.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "806148" }, { "name": "HTML", "bytes": "673309" }, { "name": "JavaScript", "bytes": "1066531" }, { "name": "Makefile", "bytes": "821" }, { "name": "PLSQL", "bytes": "1074" }, { "name": "PLpgSQL", "bytes": "2381" }, { "name": "Python", "bytes": "4647485" }, { "name": "SQLPL", "bytes": "559" }, { "name": "Shell", "bytes": "9339" }, { "name": "Smarty", "bytes": "1881" } ], "symlink_target": "" }
import smtplib import email def send_email(sender, recipient, subject, body, send=True): message = email.mime.text.MIMEText(body) message[u'Subject'] = subject message[u'From'] = sender message[u'To'] = recipient if send: s = smtplib.SMTP() s.connect() s.sendmail(sender, [recipient], message.as_string()) s.close() return message #TODO: jperla: allow creation of html and mixed emails def create_text_message(sender, recipients, subject, body): message = email.mime.text.MIMEText(body) message[u'Subject'] = subject message[u'From'] = sender #TODO: jperla: allow this to be more complicated: # i.e. tuples of (name,email) message[u'To'] = u', '.join(recipients) return message def sender_and_recipients_from_message(message, bcc=None): bcc = [] if bcc is None else bcc sender = message[u'From'] #TODO: jperla: strip out emails between <> maybe? recipients = [e.strip() for e in message[u'To'].split(u',')] recipients.extend(bcc) return sender, recipients class MailServer(object): def __init__(self): raise NotImplementedError def send_message(self): raise NotImplementedError class LocalMailServer(object): def __init__(self): pass def send_message(self, message, bcc=None): sender, recipients = sender_and_recipients_from_message(message) s = smtplib.SMTP() s.connect() s.sendmail(sender, recipients, message.as_string()) s.close() class TestMailServer(object): def __init__(self): self.sent_email = [] def send_message(self, message, bcc=None): sender, recipients = sender_and_recipients_from_message(message) self.sent_email.append((message, sender, recipients,))
{ "content_hash": "3a362b442e79a6f774719fa7bfba5c23", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 72, "avg_line_length": 27.08955223880597, "alnum_prop": 0.6440771349862259, "repo_name": "jperla/webify", "id": "befe4dd66bb8cf91e0412d14fd7af4484509ffd3", "size": "1815", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webify/email/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "38872" } ], "symlink_target": "" }
''' Implementation of scene controller and scene manipulation tools. ''' import pyglet from editor import rLoader from pyglet.window import mouse, key from pyglet.gl import glPopMatrix, glPushMatrix, \ glScalef, glClearColor, glLineWidth, GL_TRIANGLES, \ glEnable, GL_BLEND, glTranslatef import appEngine.scenegraph as scenegraph from appEngine.scenegraph import SceneGraph ''' BaseTool abstract. base for all scene tools. ''' class BaseTool(object): NAME = "Base" def __init__(self, controller): self.controller = controller def activate(self): return self def deactivate(self): pass def screenToSceneCoords(self, x=0, y=0, point=None): if point != None: x = point[0] - self.controller.graph.focusX y = point[1] - self.controller.graph.focusY x = x / self.controller.scale y = y / self.controller.scale return (x,y) else: x = x - self.controller.graph.focusX y = y - self.controller.graph.focusY x = x / self.controller.scale y = y / self.controller.scale return (x,y) def sceneToScreenCoords(self, x=0, y=0, point=None): if point != None: x = self.controller.graph.focusX + point[0] y = self.controller.graph.focusY + point[1] return (x,y) else: x = self.controller.graph.focusX + x y = self.controller.graph.focusY + y return (x,y) # input event handlers def on_mouse_motion(self, x, y, dx, dy): pass def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): pass def on_mouse_press(self,x, y, button, modifiers): pass def on_mouse_scdfroll(self,x, y, scroll_x, scroll_y): pass def on_mouse_release(self, x, y, button, modifiers): pass def key_press(self, symbol, modifiers): pass def key_release(self, symbol, modifiers): pass ''' PanTool allows user to pan scene using mouse. ''' class PanTool(BaseTool): NAME = "Pan" def __init__(self, controller): super(PanTool, self).__init__(controller) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if self.controller.graph != None: self.controller.graph.moveFocus(dx, dy) ''' PlotLineTool allows user to place a line in the terrain layer. ''' class Point(object): def __init__(self, x, y): self.x = x self.y = y class PlotLineTool(BaseTool): NAME = "Line" def __init__(self, controller): super(PlotLineTool, self).__init__(controller) self.lineStart = (0,0) self.mousePoint = (0,0) self.snapMode = False self.preview = None def doPreview(self, x2, y2): if self.lineStart is None: return if self.preview is not None: self.preview.delete() self.preview = None x1,y1 = self.lineStart x2,y2 = self.screenToSceneCoords(x2,y2) # create vl of line preview batch = self.controller.graph.batch group = self.controller.currentLayer.group curColor = self.controller.currentLayer.curColor self.preview = batch.add(2, pyglet.gl.GL_LINES, group, ('v2f', (x1, y1, x2, y2)), ('c3f', (curColor[0],curColor[1],curColor[2])*2)) def closestPointToMouse(self): lines = self.controller.graph.layers["terrain"].lines mousePos = self.screenToSceneCoords(self.mousePoint[0],self.mousePoint[1]) closestPoint = None points = list() for line in lines: #create list of points points.append(Point(line.x1, line.y1)) points.append(Point(line.x2, line.y2)) for point in points: # calcuate distance between mouse and point xDist = abs(mousePos[0] - point.x) yDist = abs(mousePos[1] - point.y) dist = xDist + yDist if closestPoint == None: closestDist = dist closestPoint = point if dist < closestDist: closestDist = dist closestPoint = point return (closestPoint.x, closestPoint.y) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): self.doPreview(x,y) def on_mouse_press(self, x, y, button, modifiers): if button == mouse.LEFT: if self.snapMode == True: ''' snap mode causes line start to snap to nearest point ''' self.mousePoint = (x,y) self.lineStart = self.closestPointToMouse() else: translatedCoords = self.screenToSceneCoords(x,y) self.lineStart = translatedCoords def on_mouse_release(self, x, y, button, modifiers): if button == mouse.LEFT: terrain = self.controller.graph.layers['terrain'] if self.preview is not None: self.preview.delete() self.preview = None mousePos = self.screenToSceneCoords(x,y) terrain.addLine(self.lineStart[0], self.lineStart[1], mousePos[0], mousePos[1]) self.linePreview = None self.controller.edited = True ''' PlaceItemTool allows user to place aesthetic or object items into correct layer ''' class PlaceItemTool(BaseTool): NAME="PlaceItem" def __init__(self, controller): super(PlaceItemTool, self).__init__(controller) self.selectedName = None self.selectedItem = None self.preview = None self.active = None def activate(self): self.active = True if self.preview is not None: self.preview.visible = True return self def deactivate(self): self.active = False if self.preview is not None: self.preview.visible = False def setSelectedItem(self, path): if path is None: self.selectedName = None self.selectedItem = None self.preview = None return # extracts the file name without extention # f = path[path.rfind("/"):len(path)] f = path.__getslice__(path.rfind("/") + 1, len(path)) self.selectedName = f.__getslice__(0, f.find(".")) self.selectedItem = pyglet.image.load(path) self.preview = pyglet.sprite.Sprite( self.selectedItem, batch=self.controller.graph.batch, group=self.controller.currentLayer.group) if self.active == False: self.preview.visible = False def key_press(self, symbol, modifiers): if self.preview is not None: if modifiers & key.MOD_CTRL: if symbol == key.MINUS: self.preview.scale -= 0.05 elif symbol == key.EQUAL: self.preview.scale += 0.05 elif symbol == key.R: self.preview.rotation += 5 def on_mouse_motion(self, x, y, dx, dy): if self.preview is not None and self.active is True: self.preview.x, self.preview.y = self.screenToSceneCoords(x,y) def on_mouse_release(self, x, y, button, modifiers): if self.preview is not None and self.active is True: mousePos = self.screenToSceneCoords(x,y) self.controller.currentLayer.addItem(self.selectedName, mousePos, self.preview.scale, self.preview.rotation) self.controller.edited = True ''' SelectTool allows user to select an object. ''' class SelectTool(BaseTool): NAME = "Select" def __init__(self, controller, window): super(SelectTool, self).__init__(controller) self.window = window self.selectedItem = None self.highlight = None def on_mouse_motion(self, x, y, dx, dy): self.mousePoint = self.screenToSceneCoords(x, y) if self.controller.currentLayer.isPointOverItem(self.mousePoint, 5) != None: cursor = self.window.get_system_mouse_cursor(self.window.CURSOR_HAND) self.window.set_mouse_cursor(cursor) else: cursor = self.window.get_system_mouse_cursor(self.window.CURSOR_DEFAULT) self.window.set_mouse_cursor(cursor) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): currentLayer = self.controller.currentLayer if currentLayer.name == "terrain": pass else: if self.selectedItem is not None: x = self.selectedItem.x + dx y = self.selectedItem.y + dy self.selectedItem.updatePosition(x=x, y=y) self.controller.edited = True def on_mouse_press(self, x, y, button, modifiers): self.mousePoint = self.screenToSceneCoords(x, y) self.selectedItem = self.controller.currentLayer.isPointOverItem(self.mousePoint, 5) if self.selectedItem is None: return currentLayer = self.controller.currentLayer if currentLayer.name == "terrain": pass else: sprite = self.selectedItem.sprite xy = self.sceneToScreenCoords(sprite.x, sprite.y) x = xy[0] y = xy[1] x2 = x + sprite.width y2 = y + sprite.height self.highlight = self.controller.batch.add(6, GL_TRIANGLES, self.controller.grid.group, ('v2f', (x, y, x2, y, x2, y2, x, y, x2, y2, x, y2)), ('c4f', (1.,1.,1.,0.4)*6)) def on_mouse_release(self, x, y, button, modifiers): if self.highlight is not None: self.highlight.delete() self.highlight = None self.mousePoint = self.screenToSceneCoords(x, y) self.selectedItem = self.controller.currentLayer.isPointOverItem(self.mousePoint, 5) self.window.dispatch_event('on_select_item') ''' class Keys responds to keypresses, notifying an event handler while storing the current state of the keys for querying ''' class Keys(key.KeyStateHandler): def __init__(self, parent): self.parent = parent def on_key_press(self, symbol, modifiers): self.parent.key_press(symbol, modifiers) super(Keys, self).on_key_press(symbol, modifiers) def on_key_release(self, symbol, modifiers): self.parent.key_release(symbol, modifiers) super(Keys, self).on_key_release(symbol, modifiers) class GridGroup(pyglet.graphics.OrderedGroup): def __init__(self, controller): super(GridGroup, self).__init__(8) self.controller = controller self.focusX = 0 self.focusY = 0 def set_state(self): glLineWidth(1) glEnable(GL_BLEND) '''if self.controller.graph is not None: glTranslatef(self.controller.graph.focusX, self.controller.graph.focusY, 0)''' def unset_state(self): '''if self.controller.graph is not None: glTranslatef(-self.controller.graph.focusX, -self.controller.graph.focusY, 0)''' pass class Grid(object): def __init__(self, controller, window): self.visible = False self.snap = False self.hSpacing = 50 self.vSpacing = 50 self.hOffset = 0 self.vOffset = 0 self.batch = pyglet.graphics.Batch() self.group = GridGroup(controller) self.lines = list() self.window = window def update(self): def defLine(x1, y1, x2, y2): self.lines.append(self.batch.add(2, pyglet.gl.GL_LINES, self.group, ('v2i', (x1, y1, x2, y2)), ('c4f', (1.0,1.0,1.0,0.8)*2))) for line in self.lines: line.delete() self.lines = [] if self.visible == True: hCount = self.window.width / self.hSpacing i = 1 while i <= hCount: x = (self.hSpacing * i) + self.hOffset y1 = 0 y2 = self.window.height defLine(x, y1, x, y2) i = i + 1 vCount = self.window.height / self.vSpacing i = 1 while i <= vCount: y = (self.vSpacing * i) + self.vOffset x1 = 0 x2 = self.window.width defLine(x1, y, x2, y) i = i + 1 ''' class SceneController manages editing of the level controller. ''' class Controller(object): def __init__(self, window): self.tools = { "pan" : PanTool(self), "plotline" : PlotLineTool(self), "placeitem" : PlaceItemTool(self), "select" : SelectTool(self, window) } self.window = window self.batch = pyglet.graphics.Batch() self.graph = None self.edited = False self.size = (0,0) self.scale = 1.0 self.keys = Keys(self) self.mouseCoord = (0,0) self.grid = Grid(self, window) self.currentLayer = None self.currentTool = None self.keys = Keys(self) window.push_handlers(self) window.push_handlers(self.keys) def _set_edited(self, edited): self._edited = edited self.window.dispatch_event('on_document_update') def _get_edited(self): return self._edited edited = property(_get_edited, _set_edited) def addLayer(self, name, z_order): self.graph.addAestheticLayer(self, name, z_order) self.edited = True def deleteLayer(self, name): if self.currentLayer.name == name: self.currentLayer = None self.graph.deleteAestheticLayer(name) self.edited = True def renameLayer(self, layer, name): if layer.name == name: return self.graph.layers.delete(layer.name) layer.name = name self.controller.graph.layers.addNamed(layer, layer.name) self.edited = True def changeLayerZOrder(self, layer, value): if layer.group.order == value: return layer.setZOrder(int(values["z_order"])) self.edited = True def changeBackground(self, r, g, b): self.graph.backColour = [r,g,b] self.graph.updateBackground() self.edited = True def setSourcePath(self, path): self.controller.graph.sourcePath = path self.edited = True def setCurrentLayerProperties(self, visible=None, opacity=None): if visible is not None: self.currentLayer.setVisible(visible) self.edited = True if opacity is not None: self.currentLayer.setOpacity(opacity) self.edited = True def newLevel(self, name, width, height): if self.graph is not None: self.graph.unload(False) self.batch = pyglet.graphics.Batch() self.grid.update() self.graph = SceneGraph(name, self.batch, rLoader, self.size, width, height, editorMode=True) self.levelFilename = None self.graph.forceFocus = True self.edited = False def loadLevel(self, filename, window): if self.graph is not None: self.graph.unload(False) self.batch = pyglet.graphics.Batch() self.grid.update() self.graph = SceneGraph.parseMapFile(filename, self.batch, rLoader, self.size, editorMode=True) self.graph.forceFocus = True self.levelFilename = filename window.dispatch_event('on_layer_update') self.edited = False def saveLevelToFile(self, filename): self.graph.saveToFile(filename) self.levelFilename = filename self.edited = False def setActiveLayer(self, name): # sets the reference to the current layer if self.currentTool is not None: if self.currentTool.NAME == "PlaceItem": self.currentTool.preview = None if name == "none": self.currentLayer = None self.currentTool = None return try: self.currentLayer = self.graph.layers[name] except KeyError: print "Set Active Layer Key Error" def setCurrentTool(self, tool): for t in self.tools: self.tools[t].deactivate() # search tool list for name and set # tool with given name to current tool. try: self.currentTool = self.tools[tool].activate() except KeyError: print "Set Current Tool Key Error" def resize(self, width, height): self.size = (width, height) if self.graph: self.graph.viewportWidth = width self.graph.viewportHeight = height def update(self, dt): if self.graph: self.pollPanKeys(dt) self.graph.update(dt) def draw(self): if self.batch is not None: glPushMatrix() glScalef(self.scale, self.scale, 0) self.batch.draw() glPopMatrix() self.grid.batch.draw() ''' input event handlers ''' def pollPanKeys(self, dt): moveRate = dt * 400 if self.keys[key.UP]: self.graph.moveFocus(y=-moveRate) if self.keys[key.DOWN]: self.graph.moveFocus(y=moveRate) if self.keys[key.LEFT]: self.graph.moveFocus(moveRate) if self.keys[key.RIGHT]: self.graph.moveFocus(-moveRate) def key_press(self, symbol, modifiers): if symbol == key.HOME: if self.graph != None: self.graph.setFocus(0,0) return elif modifiers & key.MOD_CTRL and symbol == key._0: self.scale = 1.0 self.window.dispatch_event('on_update_zoom') return elif modifiers & key.MOD_CTRL and symbol == key.MINUS: self.scale = self.scale - 0.1 self.window.dispatch_event('on_update_zoom') return elif modifiers & key.MOD_CTRL and symbol == key.EQUAL: self.scale = self.scale + 0.1 self.window.dispatch_event('on_update_zoom') return elif modifiers & key.MOD_CTRL and symbol == key.S: if self.levelFilename is not None and self.edited is not False: self.graph.saveToFile(filename) if self.currentTool is not None: self.currentTool.key_press(symbol, modifiers) def key_release(self, symbol, modifiers): if self.currentTool is not None: self.currentTool.key_release(symbol, modifiers) def on_mouse_motion(self, x, y, dx, dy): self.mouseCoord = (x,y) if self.currentTool is not None: self.currentTool.on_mouse_motion(x, y, dx, dy) def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): if self.currentTool == None: if self.graph != None: self.graph.moveFocus(dx, dy) if self.currentTool is not None: self.currentTool.on_mouse_drag(x, y, dx, dy, buttons, modifiers) def on_mouse_press(self,x, y, button, modifiers): if self.currentTool is not None: self.currentTool.on_mouse_press(x, y, button , modifiers) def on_mouse_scdfroll(self,x, y, scroll_x, scroll_y): if self.currentTool is not None: self.currentTool.on_mouse_scdfroll(x, y, scroll_x, scroll_y) def on_mouse_release(self, x, y, button, modifiers): if self.currentTool is not None: self.currentTool.on_mouse_release(x, y, button, modifiers)
{ "content_hash": "0de30b932f739eea94a9b93057adc734", "timestamp": "", "source": "github", "line_count": 573, "max_line_length": 120, "avg_line_length": 35.045375218150085, "alnum_prop": 0.5671032319107614, "repo_name": "chrisbiggar/sidescrolltesting", "id": "4aa19d84a0de6471d09dc84882ec23ba39dabae1", "size": "20081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "editor/controller.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "300686" } ], "symlink_target": "" }
import hashlib from distutils.filelist import findall from os.path import relpath, join, basename from zipfile import ZipFile def get_md5(file_path): md5_hash = hashlib.md5() with open(file_path, 'rb') as file_: batch_size = 4096 chunk = file_.read(batch_size) while chunk: md5_hash.update(chunk) chunk = file_.read(batch_size) return hashlib.md5(file_.read()).hexdigest() def zip_dir(path, zip_file_path=None, zip_root=None): zip_file_path = zip_file_path or '{}.zip'.format(path) zip_root = zip_root or basename(path) with ZipFile(zip_file_path, 'w') as zip_file: for file in findall(path): zip_file.write(file, join(zip_root, relpath(file, path)))
{ "content_hash": "a42290dcfe97c6347fb3a8970e9828c1", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 69, "avg_line_length": 30.12, "alnum_prop": 0.6374501992031872, "repo_name": "ahcub/armory", "id": "882e554e62cf8a0201c873e3eec01eec732ab81a", "size": "753", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "os_utils/operations.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "97" }, { "name": "Python", "bytes": "27611" } ], "symlink_target": "" }
from __future__ import print_function import sys import os.path from urllib2 import urlopen INVLIST_URL = 'http://dev.tsadm.local:8000/asb/inv/lst/' SSL_CERT_FILE = os.path.expanduser('~/.asbot.pem') ssl_context = None if INVLIST_URL.startswith('https:'): try: import ssl ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE ssl_context.load_cert_chain(SSL_CERT_FILE) except Exception as e: print(INVLIST_URL, str(e)) if len(sys.argv) >= 2 and sys.argv[1] == '--list': try: print(urlopen(INVLIST_URL, timeout=15, context=ssl_context).read()) except Exception as e: print(INVLIST_URL, str(e)) else: print('{}') sys.exit(0)
{ "content_hash": "da6fc4cfc80fc49ff2da8900bb205637", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 25.9, "alnum_prop": 0.646074646074646, "repo_name": "jctincan/tsadm-ansible", "id": "4268e4d0a005ef77841452a968062a9ee276b3d8", "size": "801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inventory.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "6159" }, { "name": "Python", "bytes": "9549" }, { "name": "Shell", "bytes": "4640" }, { "name": "VimL", "bytes": "41" } ], "symlink_target": "" }
from girder.models.group import Group from girder.utility import mail_utils def sendEmailToGroup(groupName, templateFilename, templateParams, subject=None, asynchronous=True): """ Send a single email with all members of a group as the recipients. :param groupName: The name of the group. :param templateFilename: The name of the Make template file used to format the email. :param templateParams: The parameters with which to render the template. :param subject: The subject line of the email. :param asynchronous: If False, bypass Girder's event system. """ group = Group().findOne({'name': groupName}) if not group: raise Exception(f'Could not load group: {groupName}.') emails = [member['email'] for member in Group().listMembers(group)] if emails: html = mail_utils.renderTemplate(templateFilename, templateParams) if asynchronous: mail_utils.sendMail(subject, html, emails) else: mail_utils.sendMailSync(subject, html, emails)
{ "content_hash": "d3bef3bc2279facb1746176cc478dbff", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 99, "avg_line_length": 41.88, "alnum_prop": 0.6981852913085005, "repo_name": "ImageMarkup/isic-archive", "id": "2860b22603cfedea1fddb62ba94466365885ea7f", "size": "1047", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "isic_archive/utility/mail_utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8936" }, { "name": "Dockerfile", "bytes": "838" }, { "name": "HTML", "bytes": "56481" }, { "name": "JavaScript", "bytes": "3778033" }, { "name": "Jinja", "bytes": "6417" }, { "name": "Mako", "bytes": "76622" }, { "name": "PEG.js", "bytes": "2182" }, { "name": "Pug", "bytes": "51086" }, { "name": "Python", "bytes": "381336" }, { "name": "Shell", "bytes": "30" }, { "name": "Stylus", "bytes": "18670" }, { "name": "TeX", "bytes": "50168" }, { "name": "Vue", "bytes": "70286" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('halfwayapp', '0007_auto_20160224_1908'), ] operations = [ migrations.AlterField( model_name='meeting', name='destination', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='halfwayapp.Address'), ), migrations.AlterField( model_name='meeting', name='participant_two', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Participant_two', to='halfwayapp.Participant'), ), migrations.AlterField( model_name='meeting', name='trip_id', field=models.IntegerField(null=True), ), migrations.AlterField( model_name='participant', name='starting_location', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='halfwayapp.Address'), ), ]
{ "content_hash": "a92892810831368b9e9ee2dc8ef91f76", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 153, "avg_line_length": 33.61764705882353, "alnum_prop": 0.615923009623797, "repo_name": "cszc/meethalfway", "id": "559aa8dd04b6365d4a2c9e8c41f5fef0d7cdec00", "size": "1215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "djangohalfway/halfwayapp/migrations/0008_auto_20160225_2147.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "7663" }, { "name": "Python", "bytes": "34804" } ], "symlink_target": "" }
from __future__ import absolute_import import datetime import getpass import logging import pytz from django.core import mail from sentry.conf import settings from sentry.exceptions import InvalidInterface, InvalidData from sentry.interfaces import Interface from sentry.models import Group, Project from tests.base import TestCase # Configure our test handler logger = logging.getLogger(__name__) class SentryMailTest(TestCase): fixtures = ['tests/fixtures/mail.json'] def setUp(self): settings.ADMINS = ('%s@localhost' % getpass.getuser(),) def test_mail_admins(self): group = Group.objects.get() self.assertEquals(len(mail.outbox), 0) group.mail_admins(fail_silently=False) self.assertEquals(len(mail.outbox), 1) # TODO: needs a new fixture # out = mail.outbox[0] # self.assertTrue('Traceback (most recent call last):' in out.body) # self.assertTrue("COOKIES:{'commenter_name': 'admin'," in out.body, out.body) # self.assertEquals(out.subject, '[Django] Error (EXTERNAL IP): /group/1/') # def test_mail_on_creation(self): # settings.MAIL = True # self.assertEquals(len(mail.outbox), 0) # self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc')) # self.assertEquals(len(mail.outbox), 1) # self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc')) # self.assertEquals(len(mail.outbox), 1) # out = mail.outbox[0] # self.assertTrue('Traceback (most recent call last):' in out.body) # self.assertTrue("<Request" in out.body) # self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500') # def test_mail_on_duplication(self): # settings.MAIL = True # self.assertEquals(len(mail.outbox), 0) # self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc')) # self.assertEquals(len(mail.outbox), 1) # self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc')) # self.assertEquals(len(mail.outbox), 1) # # XXX: why wont this work # # group = Group.objects.update(status=1) # group = Group.objects.all().order_by('-id')[0] # group.status = 1 # group.save() # self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc')) # self.assertEquals(len(mail.outbox), 2) # self.assertRaises(Exception, self.client.get, reverse('sentry-raise-exc')) # self.assertEquals(len(mail.outbox), 2) # out = mail.outbox[1] # self.assertTrue('Traceback (most recent call last):' in out.body) # self.assertTrue("<Request" in out.body) # self.assertEquals(out.subject, '[example.com] [Django] Error (EXTERNAL IP): /trigger-500') def test_url_prefix(self): settings.URL_PREFIX = 'http://example.com' group = Group.objects.get() group.mail_admins(fail_silently=False) self.assertEquals(len(mail.outbox), 1) # out = mail.outbox[0] # self.assertTrue('http://example.com/group/2/' in out.body, out.body) class DummyInterface(Interface): def __init__(self, baz): self.baz = baz class SentryManagerTest(TestCase): def test_invalid_project(self): self.assertRaises(Project.DoesNotExist, Group.objects.from_kwargs, 2, message='foo') def test_invalid_interface_name(self): self.assertRaises(InvalidInterface, Group.objects.from_kwargs, 1, message='foo', data={ 'foo': 'bar', }) def test_invalid_interface_import_path(self): self.assertRaises(InvalidInterface, Group.objects.from_kwargs, 1, message='foo', data={ 'sentry.interfaces.Exception2': 'bar', }) def test_invalid_interface_args(self): self.assertRaises(InvalidData, Group.objects.from_kwargs, 1, message='foo', data={ 'tests.tests.DummyInterface': {'foo': 'bar'} }) def test_missing_required_args(self): self.assertRaises(InvalidData, Group.objects.from_kwargs, 1) def test_valid_only_message(self): event = Group.objects.from_kwargs(1, message='foo') self.assertEquals(event.message, 'foo') self.assertEquals(event.project_id, 1) def test_valid_timestamp_with_tz(self): with self.Settings(USE_TZ=True): date = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) event = Group.objects.from_kwargs(1, message='foo', timestamp=date) self.assertEquals(event.message, 'foo') self.assertEquals(event.project_id, 1) self.assertEquals(event.datetime, date) def test_valid_timestamp_without_tz(self): # TODO: this doesnt error, but it will throw a warning. What should we do? with self.Settings(USE_TZ=True): date = datetime.datetime.utcnow() event = Group.objects.from_kwargs(1, message='foo', timestamp=date) self.assertEquals(event.message, 'foo') self.assertEquals(event.project_id, 1) self.assertEquals(event.datetime, date) def test_legacy_data(self): result = Group.objects.convert_legacy_kwargs({'timestamp': '1234'}) self.assertEquals(result['timestamp'], '1234') result = Group.objects.convert_legacy_kwargs({'message_id': '1234'}) self.assertEquals(result['event_id'], '1234') result = Group.objects.convert_legacy_kwargs({'message': 'hello', 'class_name': 'ValueError'}) self.assertEquals(result['message'], 'ValueError: hello') result = Group.objects.convert_legacy_kwargs({'view': 'foo.bar'}) self.assertEquals(result['culprit'], 'foo.bar') result = Group.objects.convert_legacy_kwargs({'data': { 'url': 'http://foo.com', 'META': { 'REQUEST_METHOD': 'POST', 'QUERY_STRING': 'foo=bar' } }}) self.assertTrue('sentry.interfaces.Http' in result) http = result['sentry.interfaces.Http'] self.assertEquals(http['url'], 'http://foo.com') self.assertEquals(http['query_string'], 'foo=bar') self.assertEquals(http['method'], 'POST') self.assertEquals(http['data'], {}) result = Group.objects.convert_legacy_kwargs({'data': { '__sentry__': { 'exception': ('TypeError', ('hello world', 1, 3, 'foo')), } }}) self.assertTrue('sentry.interfaces.Exception' in result) exc = result['sentry.interfaces.Exception'] self.assertEquals(exc['type'], 'TypeError') self.assertEquals(exc['value'], 'hello world 1 3 foo') result = Group.objects.convert_legacy_kwargs({'data': { '__sentry__': { 'frames': [ { 'filename': 'foo.py', 'function': 'hello_world', 'vars': {}, 'pre_context': ['before i did something'], 'context_line': 'i did something', 'post_context': ['after i did something'], 'lineno': 15, }, ], } }}) self.assertTrue('sentry.interfaces.Stacktrace' in result) stack = result['sentry.interfaces.Stacktrace'] self.assertEquals(len(stack['frames']), 1) frame = stack['frames'][0] self.assertEquals(frame['filename'], 'foo.py') self.assertEquals(frame['function'], 'hello_world') result = Group.objects.convert_legacy_kwargs({'data': { '__sentry__': { 'user': { 'is_authenticated': True, 'id': 1, }, } }}) self.assertTrue('sentry.interfaces.User' in result) user = result['sentry.interfaces.User'] self.assertTrue('is_authenticated' in user) self.assertEquals(user['is_authenticated'], True) self.assertTrue('id' in user) self.assertEquals(user['id'], 1) result = Group.objects.convert_legacy_kwargs({'data': { '__sentry__': { 'template': [ "foo\nbar\nbaz\nbiz\nbin", 5, 3, 'foo.html', ], } }}) self.assertTrue('sentry.interfaces.Template' in result) user = result['sentry.interfaces.Template'] # 'post_context': [(2, 'bar\n'), (3, 'baz\n'), (4, 'biz\n')], 'pre_context': [(0, '')], 'lineno': 1, 'context_line': (1, 'foo\n'), 'filename': 'foo.html'} self.assertTrue('pre_context' in user) self.assertEquals(user['pre_context'], [(0, ''), (1, 'foo\n')]) self.assertTrue('post_context' in user) self.assertEquals(user['post_context'], [(3, 'baz\n'), (4, 'biz\n'), (5, 'bin')]) self.assertTrue('lineno' in user) self.assertEquals(user['lineno'], 2) self.assertTrue('context_line' in user) self.assertEquals(user['context_line'], 'bar\n')
{ "content_hash": "caf75dc5bb077091cd68b00e2a655810", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 162, "avg_line_length": 38.848101265822784, "alnum_prop": 0.5854241338112306, "repo_name": "Kronuz/django-sentry", "id": "5e4f9e052070047e944b88e2bd3be911239b1176", "size": "9232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/tests.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "134924" }, { "name": "JavaScript", "bytes": "77963" }, { "name": "Python", "bytes": "632636" }, { "name": "Shell", "bytes": "4106" } ], "symlink_target": "" }
def biggestValue(values): biggest = values[0] for num in values: if (num > biggest): biggest = num return biggest
{ "content_hash": "6ea768bfc53162ee3c3dca7281cad7be", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 27, "avg_line_length": 21, "alnum_prop": 0.5714285714285714, "repo_name": "crissyg/SCH-PRACTICE", "id": "144e643a9e5192a25d32ba53374613ac753ead78", "size": "147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python Examples/ArrayMethod.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "5292" } ], "symlink_target": "" }
import errno import os def resolve_relative_path(file_name): path = os.path.normpath(os.path.join( os.path.dirname( __import__('rally_runners').__file__), '../', file_name)) if os.path.exists(path): return path def mkdir_tree(path): try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
{ "content_hash": "1cfa7727d93012c837e3c4e3ea908346", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 69, "avg_line_length": 22.3, "alnum_prop": 0.5627802690582959, "repo_name": "shakhat/rally-runners", "id": "53430d632125de03bb8f17b4f24bfd138c77f63c", "size": "1008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rally_runners/utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "30674" } ], "symlink_target": "" }
from baseGate import * from Gate import * import copy #only X,Y,Z,I,H,S,Sd,T,Td,CNOT is allowed import re #delay measure opertor class used in DMif class DMO: def __init__(self,ql,vl): #storage the control-qubit list self.DMOql = ql self.split = SplitGate() self.DMOvl = vl #get the info about the function name and the line number def get_curl_info(self): try: raise Exception except: f = sys.exc_info()[2].tb_frame.f_back return [f.f_code.co_name, f.f_lineno] #set the name of the control qubit gate:if there are 3 qubit in self.DMOql and vl = [1,0,1], #then the full name should be c1-c0-c1-SingleQubitGate. def __fullGName(self,gn:str,vl:list,ql:list): name = "" for i in range(0,len(ql)): name += "c" if len(vl) == 1: j = 0 else: j = i if vl[j] == 0: name += "0" else: name += "1" name += "-" cgn = name[0:len(name)-1] return self.__setFullGName(cgn,gn) #get the full name of the multi-controlled gate def __setFullGName(self,cgn:str,gn:str): return (cgn + "-" + gn) #the "cq" is the control-qubit of the CNOT gate def Operator(self,gateName:str,tq:Qubit,cq = None,angle = None): ql = self.DMOql.copy() vl = self.DMOvl.copy() QASM = "" if cq != None: #CNOT gate call this function. We shoulde convert the format of CNOT ql.append(cq) vl.append(1) fullGName = self.__fullGName(gateName,vl,ql) #CNOT gate if fullGName == "c1-X": return CNOT(ql[0],tq) #the return value is a list consisted of all the control-qubits and the target-qubit if re.match(r'^(c\d-){1}.{1,2}$',fullGName) != None: #split the CU and execute the computation return self.split.CU(fullGName,ql[0],tq,vl,angle,True) else: #split the MCU and execute the computation return self.split.MCU(fullGName,ql,tq,vl,angle,True) def X(self,q:Qubit): gateName = "X" return self.Operator(gateName,q) def Y(self,q:Qubit): gateName = "Y" return self.Operator(gateName,q) def Z(self,q:Qubit): gateName = "Z" return self.Operator(gateName,q) def H(self,q:Qubit): gateName = "H" return self.Operator(gateName,q) def S(self,q:Qubit): gateName = "S" return self.Operator(gateName,q) def Sd(self,q:Qubit): gateName = "Sd" return self.Operator(gateName,q) def T(self,q:Qubit): gateName = "T" return self.Operator(gateName,q) def Td(self,q:Qubit): gateName = "Td" return self.Operator(gateName,q) def CNOT(self,q1:Qubit,q2:Qubit): gateName = "X" return self.Operator(gateName,q2,q1) def Rz(self,phi,q:Qubit): gateName = "Rz" return self.Operator(gateName,q,None,phi) def Ry(self,phi,q:Qubit): gateName = "Ry" return self.Operator(gateName,q,None,phi) #measure operator class used in Mif and Qif class MO(DMO): def __init__(self,ql,vl): self.MOql = ql self.MOvl = vl self.header = "" bitList = self.MO(ql,vl) self.bool = True if len(vl) == 1: for bit in bitList: if bit.value != vl[0]: self.bool = False break else: for j in range(0,len(bitList)): if bitList[j] != vl[j]: self.bool = False break #this kind of measure is used in Mif; #ql means the qubit list need be measured; and the vl stands for the target result of measurement def MO(self,ql:list,vl:list): if len(ql) != len(vl): try: raise CodeError("The element number of Qubit List should be same with Value List!") except CodeError as ce: info = get_curl_info() funName = info[0] line = info[1] writeErrorMsg(ce,funName,line) bitList = [] for q in ql: bitList.append(M(q,False)) #construct the if statement # ifstr = "if (" # for i in range(0,len(ql)): # c = str(ql[i].ids) # tmp = "c[" + c + "]==" + str(vl[i]) # if i != len(ql)-1: # tmp += " && " # ifstr += tmp # ifstr += "){}" ifstr = "" for v in vl: ifstr += "M" + str(v) + "-" self.header = ifstr return bitList def recordGate(self,gate:str,ql:list): circuit = checkEnvironment() maxL = 0 content = gate + " " for i in range(0,len(ql)): length = len(circuit.qubitExecuteList[ql[i]]) maxL = max(length,maxL) content += str(ql[i].ids) if i != len(ql)-1: content += ',' for q in ql: try: while len(circuit.qubitExecuteList[q]) < maxL: circuit.qubitExecuteList[q].append("NULL "+str(q.ids)) circuit.qubitExecuteList[q].append(content) if circuit.withOD: while len(circuit.qubitExecuteListOD[q]) < maxL: circuit.qubitExecuteListOD[q].append("NULL "+str(q.ids)) circuit.qubitExecuteListOD[q].append(content) except KeyError: info = get_curl_info() writeErrorMsg("Qubit: q" + str(q.ids) + " hasn't been stored in circuit.qubitExeucetList!\ " ,info[0],info[1]) # print(circuit.qubitExecuteList) # print(circuit.qubitExecuteListOD) #overwrite the operator method def Operator(self,gateName:str,tq:Qubit,cq = None,angle = None): if cq != None: gateName = "c1-X" fullGName = self.header + gateName #no matter what's self.bool, record the Measure Operator in qubitExecuteList if self.bool: #if the last position of the full gate name is 1, then the gate is executed fullGName += "1" else: #if the last position of the gate name is 0, then the gate isn't executed fullGName += "0" ql = self.MOql.copy() if cq != None: ql.append(cq) ql.append(tq) self.recordGate(fullGName,ql) #execute the operator according to self.bool if gateName == "c1-X": gateName = "CNOT" q = None if self.bool: #execute the gate function in Gate.py if cq == None: exeStr = "q = " + gateName + "(tq,False,True)" else: exeStr = "q = " + gateName + "(cq,tq,False,True)" #print(exeStr) exec(exeStr) else: #don't exeucte the gate pass return q #the single gate operator and the double gate operator were inherited from DMO class #def X #def Y #def Z #def H #def S #def Sd #def T #def Td #def CNOT #def Rz #def Ry #def get_curl_info #delay measure operator class used in Qwhile class QWMO(DMO): def __init__(self,ql,vl,angle): DMO.__init__(ql,vl) self.angle = angle def end(self): for q in ql: Rx(angle,q) if True: return True else: return False
{ "content_hash": "e07ecdf7c356ab9c394fc10ec28104aa", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 98, "avg_line_length": 23.42641509433962, "alnum_prop": 0.6420747422680413, "repo_name": "zhangxin20121923/QuanSim", "id": "d8589ff75492a87f9b50a0b939cf7bb570580207", "size": "6227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "baseClass/DMO.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "111903" } ], "symlink_target": "" }
__author__ = 'Nihar' __project__ = 'QuantAnalysis' import talib import os import numpy as np # DEFINE THRESHOLD FOR SUCCESS success = 75 # HARD CODE PARAMETERS right = 0.03 veryright = 0.05 delta = 30 upperbound = 80 lowerbound = 20 class LongTerm: def analysis(self, filename): # READ PRICES FILE close = np.loadtxt("dow30/" + filename, delimiter=',', skiprows=0, usecols=(5,)) date = np.loadtxt("dow30/" + filename, delimiter=',', dtype='int', skiprows=0, usecols=(0,)) # READ ITERATION COLUMNS ind_duration = np.loadtxt('RSI_MA_LongTerm.csv', delimiter=',', dtype='int', skiprows=1, usecols=(0,)) metric_wait = np.loadtxt('RSI_MA_LongTerm.csv', delimiter=',', dtype='int', skiprows=1, usecols=(1,)) metric_duration = np.loadtxt('RSI_MA_LongTerm.csv', delimiter=',', dtype='int', skiprows=1, usecols=(2,)) # PERFORM TESTS for i in range(len(ind_duration)): for l in range(len(metric_wait)): for j in range(len(metric_duration)): # for k in range(len(right)): percent1 = int((LongTerm().rsi_test(close, date, ind_duration[i], metric_wait[l], metric_duration[j], upperbound, lowerbound, right)) * 100) if (percent1 > success): percent2 = int(LongTerm().rsi_test(close, date, ind_duration[i], metric_wait[l], metric_duration[j], upperbound, lowerbound, veryright) * 100) percent3 = int(percent2 * 100 / percent1) print("\n{6}\nIndicator Duration: {0}, Metric Wait: {2}, Metric Duration: {1}\nRight Percentage: {3}, Very Right Percentage: {4}, Percentage of Very Right within Right: {5}\n".format(ind_duration[i], metric_duration[j], metric_wait[l], percent1, percent2, percent3, filename)) # else: # print("Signal not significantly successful.") def rsi_test(self, p, d, id, mw, md, ub, lb, r): # GENERATE METRIC ma = talib.MA(p, timeperiod=md) # GENERATE INDICATOR (RELATIVE STRENGTH INDEX) rsi = talib.RSI(p, timeperiod=id) # COMPARE RSI TO METRIC oversold = 0 overbought = 0 buy = 0 sell = 0 right = 0 total = 0 for i in range(id, len(rsi)): if (rsi[i] > ub): overbought += 1 total += 1 if (i < len(p)-mw): j = (1-r) * p[i] if (ma[i+mw] <= j): sell += 1 right += 1 # print str(right) + ' ' + str(d[i]) + " SELL" if (rsi[i] < lb): oversold += 1 total += 1 if (i < len(p)-mw): j = (1+r) * p[i] if (ma[i+mw] >= j): buy += 1 right += 1 # print str(right) + ' ' + str(d[i]) + " BUY" # CALCULATE STRENGTH OF INDICATOR if (total >= 15): percent = right / float(total) # print "Good Buy:" + str(buy) + " Good Sell:" + str(sell) + " Total:" + str(total) else: percent = 0 return percent filecount = 0 for root, dirs, files in os.walk('dow30/'): for name in files: if (name == '.DS_Store'): continue LongTerm().analysis(name) filecount += 1 print "\nFinished:", name
{ "content_hash": "9275d33b11c8f3cac066bbad4b1731a6", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 304, "avg_line_length": 38.33695652173913, "alnum_prop": 0.5032605613836121, "repo_name": "niharparikh/Projects", "id": "de28031951bb98bf831f58d6739c1cf58915c4f9", "size": "3527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "QuantAnalysis/src/Trend.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1106" }, { "name": "HTML", "bytes": "4382" }, { "name": "Python", "bytes": "30852" } ], "symlink_target": "" }
from ConfigParser import ParsingError, RawConfigParser from StringIO import StringIO from collections import defaultdict from functools import partial from pkg_resources import resource_filename from genshi.builder import tag from trac.config import Configuration, ConfigSection from trac.core import * from trac.env import IEnvironmentSetupParticipant from trac.perm import PermissionSystem from trac.ticket.api import ITicketActionController, TicketSystem from trac.ticket.model import Resolution from trac.util import get_reporter_id, to_list from trac.util.presentation import separated from trac.util.translation import _, tag_, cleandoc_ from trac.web.chrome import Chrome, add_script, add_script_data from trac.wiki.formatter import system_message from trac.wiki.macros import WikiMacroBase # -- Utilities for the ConfigurableTicketWorkflow def parse_workflow_config(rawactions): """Given a list of options from [ticket-workflow]""" default = { 'oldstates': [], 'newstate': '', 'name': '', 'default': 0, 'operations': [], 'permissions': [] } actions = defaultdict(lambda: default.copy()) for option, value in rawactions: parts = option.split('.') name = parts[0] if len(parts) == 1: # Base name, of the syntax: old,states,here -> newstate try: oldstates, newstate = [x.strip() for x in value.split('->')] except ValueError: continue # Syntax error, a warning will be logged later actions[name]['oldstates'] = to_list(oldstates) actions[name]['newstate'] = newstate else: attribute = parts[1] if attribute == 'default': actions[name][attribute] = int(value) elif attribute in ('operations', 'permissions'): actions[name][attribute] = to_list(value) else: actions[name][attribute] = value for name, attrs in actions.iteritems(): if not attrs.get('name'): attrs['name'] = name return actions def get_workflow_config(config): """Usually passed self.config, this will return the parsed ticket-workflow section. """ raw_actions = list(config.options('ticket-workflow')) actions = parse_workflow_config(raw_actions) return actions def load_workflow_config_snippet(config, filename): """Loads the ticket-workflow section from the given file (expected to be in the 'workflows' tree) into the provided config. """ filename = resource_filename('trac.ticket', 'workflows/%s' % filename) new_config = Configuration(filename) for name, value in new_config.options('ticket-workflow'): config.set('ticket-workflow', name, value) class ConfigurableTicketWorkflow(Component): """Ticket action controller which provides actions according to a workflow defined in trac.ini. The workflow is defined in the `[ticket-workflow]` section of the [wiki:TracIni#ticket-workflow-section trac.ini] configuration file. """ implements(IEnvironmentSetupParticipant, ITicketActionController) ticket_workflow_section = ConfigSection('ticket-workflow', """The workflow for tickets is controlled by plugins. By default, there's only a `ConfigurableTicketWorkflow` component in charge. That component allows the workflow to be configured via this section in the `trac.ini` file. See TracWorkflow for more details. (''since 0.11'')""") def __init__(self, *args, **kwargs): self.actions = self.get_all_actions() self.log.debug('Workflow actions at initialization: %s\n', self.actions) # IEnvironmentSetupParticipant methods def environment_created(self): """When an environment is created, we provide the basic-workflow, unless a ticket-workflow section already exists. """ if 'ticket-workflow' not in self.config.sections(): load_workflow_config_snippet(self.config, 'basic-workflow.ini') self.config.save() self.actions = self.get_all_actions() def environment_needs_upgrade(self, db): """The environment needs an upgrade if there is no [ticket-workflow] section in the config. """ return not list(self.config.options('ticket-workflow')) def upgrade_environment(self, db): """Insert a [ticket-workflow] section using the original-workflow""" load_workflow_config_snippet(self.config, 'original-workflow.ini') self.config.save() self.actions = self.get_all_actions() info_message = """ ==== Upgrade Notice ==== The ticket Workflow is now configurable. Your environment has been upgraded, but configured to use the original workflow. It is recommended that you look at changing this configuration to use basic-workflow. Read TracWorkflow for more information (don't forget to 'wiki upgrade' as well) """ self.log.info(info_message.replace('\n', ' ').replace('==', '')) print info_message # ITicketActionController methods def get_ticket_actions(self, req, ticket): """Returns a list of (weight, action) tuples that are valid for this request and this ticket.""" # Get the list of actions that can be performed # Determine the current status of this ticket. If this ticket is in # the process of being modified, we need to base our information on the # pre-modified state so that we don't try to do two (or more!) steps at # once and get really confused. status = ticket._old.get('status', ticket['status']) or 'new' ticket_perm = req.perm(ticket.resource) allowed_actions = [] for action_name, action_info in self.actions.items(): oldstates = action_info['oldstates'] if oldstates == ['*'] or status in oldstates: # This action is valid in this state. Check permissions. required_perms = action_info['permissions'] if self._is_action_allowed(ticket_perm, required_perms): allowed_actions.append((action_info['default'], action_name)) # Append special `_reset` action if status is invalid. if status not in TicketSystem(self.env).get_all_status() + \ ['new', 'closed']: required_perms = self.actions['_reset'].get('permissions') if self._is_action_allowed(ticket_perm, required_perms): default = self.actions['_reset'].get('default') allowed_actions.append((default, '_reset')) return allowed_actions def _is_action_allowed(self, ticket_perm, required_perms): if not required_perms: return True for permission in required_perms: if permission in ticket_perm: return True return False def get_all_status(self): """Return a list of all states described by the configuration. """ all_status = set() for attributes in self.actions.values(): all_status.update(attributes['oldstates']) all_status.add(attributes['newstate']) all_status.discard('*') all_status.discard('') return all_status def render_ticket_action_control(self, req, ticket, action): self.log.debug('render_ticket_action_control: action "%s"', action) this_action = self.actions[action] status = this_action['newstate'] operations = this_action['operations'] current_owner = ticket._old.get('owner', ticket['owner']) author = get_reporter_id(req, 'author') format_author = partial(Chrome(self.env).format_author, req) formatted_current_owner = format_author(current_owner or _("(none)")) control = [] # default to nothing hints = [] if 'reset_workflow' in operations: control.append(_("from invalid state")) hints.append(_("Current state no longer exists")) if 'del_owner' in operations: hints.append(_("The ticket will be disowned")) if 'set_owner' in operations: id = 'action_%s_reassign_owner' % action if 'set_owner' in this_action: owners = [x.strip() for x in this_action['set_owner'].split(',')] elif self.config.getbool('ticket', 'restrict_owner'): perm = PermissionSystem(self.env) owners = perm.get_users_with_permission('TICKET_MODIFY') owners.sort() else: owners = None if owners is None: owner = req.args.get(id, author) control.append(tag_("to %(owner)s", owner=tag.input(type='text', id=id, name=id, value=owner))) hints.append(_("The owner will be changed from " "%(current_owner)s to the specified user", current_owner=formatted_current_owner)) elif len(owners) == 1: owner = tag.input(type='hidden', id=id, name=id, value=owners[0]) formatted_new_owner = format_author(owners[0]) control.append(tag_("to %(owner)s", owner=tag(formatted_new_owner, owner))) if ticket['owner'] != owners[0]: hints.append(_("The owner will be changed from " "%(current_owner)s to %(selected_owner)s", current_owner=formatted_current_owner, selected_owner=formatted_new_owner)) else: selected_owner = req.args.get(id, req.authname) control.append(tag_("to %(owner)s", owner=tag.select( [tag.option(x, value=x, selected=(x == selected_owner or None)) for x in owners], id=id, name=id))) hints.append(_("The owner will be changed from " "%(current_owner)s to the selected user", current_owner=formatted_current_owner)) elif 'set_owner_to_self' in operations and \ ticket._old.get('owner', ticket['owner']) != author: hints.append(_("The owner will be changed from %(current_owner)s " "to %(authname)s", current_owner=formatted_current_owner, authname=format_author(author))) if 'set_resolution' in operations: if 'set_resolution' in this_action: resolutions = [x.strip() for x in this_action['set_resolution'].split(',')] else: resolutions = [r.name for r in Resolution.select(self.env)] if not resolutions: raise TracError(_("Your workflow attempts to set a resolution " "but none is defined (configuration issue, " "please contact your Trac admin).")) id = 'action_%s_resolve_resolution' % action if len(resolutions) == 1: resolution = tag.input(type='hidden', id=id, name=id, value=resolutions[0]) control.append(tag_("as %(resolution)s", resolution=tag(resolutions[0], resolution))) hints.append(_("The resolution will be set to %(name)s", name=resolutions[0])) else: selected_option = req.args.get(id, TicketSystem(self.env).default_resolution) control.append(tag_("as %(resolution)s", resolution=tag.select( [tag.option(x, value=x, selected=(x == selected_option or None)) for x in resolutions], id=id, name=id))) hints.append(_("The resolution will be set")) if 'del_resolution' in operations: hints.append(_("The resolution will be deleted")) if 'leave_status' in operations: control.append(_("as %(status)s", status= ticket._old.get('status', ticket['status']))) if len(operations) == 1: hints.append(_("The owner will remain %(current_owner)s", current_owner=formatted_current_owner) if current_owner else _("The ticket will remain with no owner")) else: if status != '*': hints.append(_("Next status will be '%(name)s'", name=status)) return (this_action.get('name', action), tag(separated(control, ' ')), '. '.join(hints) + '.' if hints else '') def get_ticket_changes(self, req, ticket, action): this_action = self.actions[action] # Enforce permissions if not self._has_perms_for_action(req, this_action, ticket.resource): # The user does not have any of the listed permissions, so we won't # do anything. return {} updated = {} # Status changes status = this_action['newstate'] if status != '*': updated['status'] = status for operation in this_action['operations']: if operation == 'del_owner': updated['owner'] = '' elif operation == 'set_owner': newowner = req.args.get('action_%s_reassign_owner' % action, this_action.get('set_owner', '').strip()) # If there was already an owner, we get a list, [new, old], # but if there wasn't we just get new. if type(newowner) == list: newowner = newowner[0] updated['owner'] = newowner elif operation == 'set_owner_to_self': updated['owner'] = get_reporter_id(req, 'author') elif operation == 'del_resolution': updated['resolution'] = '' elif operation == 'set_resolution': newresolution = req.args.get('action_%s_resolve_resolution' % \ action, this_action.get('set_resolution', '').strip()) updated['resolution'] = newresolution # reset_workflow is just a no-op here, so we don't look for it. # leave_status is just a no-op here, so we don't look for it. return updated def apply_action_side_effects(self, req, ticket, action): pass def _has_perms_for_action(self, req, action, resource): required_perms = action['permissions'] if required_perms: for permission in required_perms: if permission in req.perm(resource): break else: # The user does not have any of the listed permissions return False return True # Public methods (for other ITicketActionControllers that want to use # our config file and provide an operation for an action) def get_all_actions(self): actions = parse_workflow_config(self.ticket_workflow_section.options()) # Special action that gets enabled if the current status no longer # exists, as no other action can then change its state. (#5307/#11850) if '_reset' not in actions: reset = { 'default': 0, 'name': 'reset', 'newstate': 'new', 'oldstates': [], 'operations': ['reset_workflow'], 'permissions': ['TICKET_ADMIN'] } for key, val in reset.items(): actions['_reset'][key] = val for name, info in actions.iteritems(): if not info['newstate']: self.log.warning("Ticket workflow action '%s' doesn't define " "any transitions", name) return actions def get_actions_by_operation(self, operation): """Return a list of all actions with a given operation (for use in the controller's get_all_status()) """ actions = [(info['default'], action) for action, info in self.actions.items() if operation in info['operations']] return actions def get_actions_by_operation_for_req(self, req, ticket, operation): """Return list of all actions with a given operation that are valid in the given state for the controller's get_ticket_actions(). If state='*' (the default), all actions with the given operation are returned. """ # Be sure to look at the original status. status = ticket._old.get('status', ticket['status']) actions = [(info['default'], action) for action, info in self.actions.items() if operation in info['operations'] and ('*' in info['oldstates'] or status in info['oldstates']) and self._has_perms_for_action(req, info, ticket.resource)] return actions class WorkflowMacro(WikiMacroBase): _domain = 'messages' _description = cleandoc_( """Render a workflow graph. This macro accepts a TracWorkflow configuration and renders the states and transitions as a directed graph. If no parameters are given, the current ticket workflow is rendered. In WikiProcessors mode the `width` and `height` arguments can be specified. (Defaults: `width = 800` and `heigth = 600`) Examples: {{{ [[Workflow()]] [[Workflow(go = here -> there; return = there -> here)]] {{{ #!Workflow width=700 height=700 leave = * -> * leave.operations = leave_status leave.default = 1 accept = new,assigned,accepted,reopened -> accepted accept.permissions = TICKET_MODIFY accept.operations = set_owner_to_self resolve = new,assigned,accepted,reopened -> closed resolve.permissions = TICKET_MODIFY resolve.operations = set_resolution reassign = new,assigned,accepted,reopened -> assigned reassign.permissions = TICKET_MODIFY reassign.operations = set_owner reopen = closed -> reopened reopen.permissions = TICKET_CREATE reopen.operations = del_resolution }}} }}} """) def expand_macro(self, formatter, name, text, args): if not text: raw_actions = self.config.options('ticket-workflow') else: if args is None: text = '\n'.join([line.lstrip() for line in text.split(';')]) if '[ticket-workflow]' not in text: text = '[ticket-workflow]\n' + text parser = RawConfigParser() try: parser.readfp(StringIO(text)) except ParsingError, e: return system_message(_("Error parsing workflow."), unicode(e)) raw_actions = list(parser.items('ticket-workflow')) actions = parse_workflow_config(raw_actions) states = list(set( [state for action in actions.itervalues() for state in action['oldstates']] + [action['newstate'] for action in actions.itervalues()])) action_labels = [attrs.get('name') or name for name, attrs in actions.items()] action_names = actions.keys() edges = [] for name, action in actions.items(): new_index = states.index(action['newstate']) name_index = action_names.index(name) for old_state in action['oldstates']: old_index = states.index(old_state) edges.append((old_index, new_index, name_index)) args = args or {} width = args.get('width', 800) height = args.get('height', 600) graph = {'nodes': states, 'actions': action_labels, 'edges': edges, 'width': width, 'height': height} graph_id = '%012x' % id(graph) req = formatter.req add_script(req, 'common/js/excanvas.js', ie_if='IE') add_script(req, 'common/js/workflow_graph.js') add_script_data(req, {'graph_%s' % graph_id: graph}) return tag( tag.div('', class_='trac-workflow-graph trac-noscript', id='trac-workflow-graph-%s' % graph_id, style="display:inline-block;width:%spx;height:%spx" % (width, height)), tag.noscript( tag.div(_("Enable JavaScript to display the workflow graph."), class_='system-message')))
{ "content_hash": "fe674ae1c9c46f3d622335c76b23b949", "timestamp": "", "source": "github", "line_count": 504, "max_line_length": 79, "avg_line_length": 42.692460317460316, "alnum_prop": 0.5585351117720871, "repo_name": "exocad/exotrac", "id": "f5aca3fc681cde1944db697a6015a9a2a2d588c3", "size": "22159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "trac/ticket/default_workflow.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3268" }, { "name": "CSS", "bytes": "71836" }, { "name": "HTML", "bytes": "344136" }, { "name": "JavaScript", "bytes": "92411" }, { "name": "Makefile", "bytes": "18955" }, { "name": "Python", "bytes": "3486582" }, { "name": "Shell", "bytes": "9573" } ], "symlink_target": "" }
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: win_msg version_added: "2.3" short_description: Sends a message to logged in users on Windows hosts. description: - Wraps the msg.exe command in order to send messages to Windows hosts. options: to: description: - Who to send the message to. Can be a username, sessionname or sessionid. default: '*' display_seconds: description: - How long to wait for receiver to acknowledge message, in seconds. default: 10 wait: description: - Whether to wait for users to respond. Module will only wait for the number of seconds specified in display_seconds or 10 seconds if not specified. However, if I(wait) is true, the message is sent to each logged on user in turn, waiting for the user to either press 'ok' or for the timeout to elapse before moving on to the next user. type: bool default: 'no' msg: description: - The text of the message to be displayed. - The message must be less than 256 characters. default: Hello world! author: - Jon Hawkesworth (@jhawkesworth) notes: - This module must run on a windows host, so ensure your play targets windows hosts, or delegates to a windows host. - Messages are only sent to the local host where the module is run. - The module does not support sending to users listed in a file. - Setting wait to true can result in long run times on systems with many logged in users. ''' EXAMPLES = r''' - name: Warn logged in users of impending upgrade win_msg: display_seconds: 60 msg: Automated upgrade about to start. Please save your work and log off before {{ deployment_start_time }} ''' RETURN = r''' msg: description: Test of the message that was sent. returned: changed type: string sample: Automated upgrade about to start. Please save your work and log off before 22 July 2016 18:00:00 display_seconds: description: Value of display_seconds module parameter. returned: success type: string sample: 10 rc: description: The return code of the API call returned: always type: int sample: 0 runtime_seconds: description: How long the module took to run on the remote windows host. returned: success type: string sample: 22 July 2016 17:45:51 sent_localtime: description: local time from windows host when the message was sent. returned: success type: string sample: 22 July 2016 17:45:51 wait: description: Value of wait module parameter. returned: success type: boolean sample: false '''
{ "content_hash": "ce646e4965df9d6b129a33f2f6096910", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 155, "avg_line_length": 33.55555555555556, "alnum_prop": 0.6902133922001472, "repo_name": "e-gob/plataforma-kioscos-autoatencion", "id": "fa0250994bd600bf4a3a539e8f423bb49136fe8e", "size": "3581", "binary": false, "copies": "34", "ref": "refs/heads/master", "path": "scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/windows/win_msg.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "41110" }, { "name": "C++", "bytes": "3804" }, { "name": "CSS", "bytes": "34823" }, { "name": "CoffeeScript", "bytes": "8521" }, { "name": "HTML", "bytes": "61168" }, { "name": "JavaScript", "bytes": "7206" }, { "name": "Makefile", "bytes": "1347" }, { "name": "PowerShell", "bytes": "584344" }, { "name": "Python", "bytes": "25506593" }, { "name": "Ruby", "bytes": "245726" }, { "name": "Shell", "bytes": "5075" } ], "symlink_target": "" }
import logging LOGGER = logging.getLogger(__name__) from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User import django.contrib.auth.forms as django_auth_forms from django.core.validators import MinLengthValidator from django.contrib.auth import password_validation class NameForm(forms.Form): def __init__(self, *args, **kwargs): super(NameForm, self).__init__(*args, **kwargs) first_name = forms.CharField( label='First name', max_length=100, validators=[ MinLengthValidator(2) ], required = False ) last_name = forms.CharField( label='Last name', max_length=100, validators=[ MinLengthValidator(2) ], required = False ) class EmailForm(forms.Form): def __init__(self, *args, **kwargs): super(EmailForm, self).__init__(*args, **kwargs) email = forms.EmailField( label='Email', max_length=100, required = True ) class AddressForm(forms.Form): def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) street_1 = forms.CharField( label='Street (1)', max_length=100, required = False ) street_2 = forms.CharField( label='Street (2)', max_length=100, required = False ) city = forms.CharField( label='City', max_length=100, required = False ) zipcode = forms.CharField( label='Zip code', max_length=100, required = False ) country = forms.CharField( label='Country', max_length=100, required = False ) class SetPasswordForm(forms.Form): custom_set_password_form_err_msgs = { 'password_mismatch': _("The two password fields didn't match."), } def __init__(self, *args, **kwargs): super(SetPasswordForm, self).__init__(*args, **kwargs) password1 = forms.CharField( label=_('Password'), widget=forms.PasswordInput, required = True ) password2 = forms.CharField( label='Password (confirm)', widget=forms.PasswordInput, required = True ) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.custom_set_password_form_err_msgs['password_mismatch'] ) password_validation.validate_password(password2) # used validators defined in settings.AUTH_PASSWORD_VALIDATORS return password2 class UserMinimalRegistrationForm(NameForm, EmailForm, SetPasswordForm): user_form_err_msgs = { 'unselectable_username': _("This username already exists. Please try another one."), 'unselectable_email': _("This email address is already used by another user. Please try another one."), } def __init__(self, *args, **kwargs): super(UserMinimalRegistrationForm, self).__init__(*args, **kwargs) username = forms.CharField( label='Username', max_length=100, required = True, validators=[ MinLengthValidator(3) ] ) def clean_username(self): username = self.cleaned_data.get("username") if User.objects.filter(username=username).exists(): raise forms.ValidationError(self.user_form_err_msgs['unselectable_username']) return username def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError(self.user_form_err_msgs['unselectable_email']) return email class UserAccountEditionForm(NameForm, EmailForm, AddressForm): user_profile_edit_form_err_msgs = { 'unselectable_email': _("This email address is already used by another user. Please try another one."), } def __init__(self, user, *args, **kwargs): self.user = user super(UserAccountEditionForm, self).__init__(*args, **kwargs) def clean_email(self): email = self.cleaned_data.get('email') username = self.user.username if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError(self.user_profile_edit_form_err_msgs['unselectable_email']) return email class CustomLoginForm(django_auth_forms.AuthenticationForm): def __init__(self, *args, **kwargs): super(CustomLoginForm, self).__init__(*args, **kwargs) class CustomPasswordChangeForm(django_auth_forms.PasswordChangeForm): def __init__(self, *args, **kwargs): super(CustomPasswordChangeForm, self).__init__(*args, **kwargs) self.fields['new_password2'].label = _("New password (confirm)") class CustomPasswordResetForm(django_auth_forms.PasswordResetForm): def __init__(self, *args, **kwargs): super(CustomPasswordResetForm, self).__init__(*args, **kwargs) class CustomChangePasswordForm(django_auth_forms.SetPasswordForm): def __init__(self, *args, **kwargs): super(CustomChangePasswordForm, self).__init__(*args, **kwargs)
{ "content_hash": "7c54f80c1417982f42d0b518d9e24c39", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 111, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6209954751131221, "repo_name": "echodelt/django-auth-skel-project", "id": "ebf4887fd80fc310b965e979d56423173f69effc", "size": "5550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "account/forms.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3829" }, { "name": "HTML", "bytes": "39924" }, { "name": "Python", "bytes": "44127" } ], "symlink_target": "" }
''' import statements. ''' import pyglet pyglet.options['debug_gl'] = False from pyglet_app_line_update_cheetah_with_mmap import PygletApp from pyglet_app_helper import process_sys_argv ''' user config options. ''' # set the 'abs_plugin_ID' to the value you see in Matlab - or provide a value on # the command line. with 'pContinousOpenGL' you also need to append the channel number that you want # to visualize. E.g. '4-131' means: plugin ID 4, channel number 131. abs_plugin_ID = '2-131' # set this variable to zero if you want to generate random data. receive_data_from_matlab = 1 # what is the name of this plugin? must match definition on matlab side. PLUGIN_NAME = 'pContinuousOpenGL' # number of panels that this plugin is displaying. NBR_PANELS = 2 # number of points to render nPoints = 512*100 # how many points should be updated during every 'update()' call? # 'nPoints' must be a multiple of 'nPointsToUpdate', because we don't handle # wrapping around cases. nPointsToUpdate = 512 ''' startup the application. ''' if __name__ == "__main__": # process 'abs_plugin_ID' if given on command line. abs_plugin_ID = process_sys_argv(abs_plugin_ID) # default window height and width of this plugin. # performance decreases (factor of 10!), if WIN_HEIGHT_DEFAULT > 100 and # axes are turned on (SHOW_AXES == True). WIN_HEIGHT_DEFAULT = 1500 WIN_WIDTH_DEFAULT = 1000 # instantiate our application & run setup() method. my_app = PygletApp(width=WIN_WIDTH_DEFAULT, height=WIN_HEIGHT_DEFAULT, abs_plugin_ID=abs_plugin_ID, receive_data_from_matlab=receive_data_from_matlab, resizable=True) # overwrite default values with our custom settings. my_app.PLUGIN_NAME = PLUGIN_NAME my_app.NBR_CHANNELS = NBR_PANELS my_app.nPoints = nPoints my_app.nPointsToUpdate = nPointsToUpdate # don't show the axes - this will slow down rendering. my_app.SHOW_AXES = False my_app.SHOW_HORIZONTAL_LINE = False # finish settings things up. my_app.setup() # run program. pyglet.app.run()
{ "content_hash": "6ca2d1bab55c644cf87bd24374d960bd", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 167, "avg_line_length": 31.359375, "alnum_prop": 0.731938216243149, "repo_name": "StimOMatic/StimOMatic", "id": "703c7099cf52cb58911f269ae9703ddc5544b5ae", "size": "2008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/OpenGLPlotting/pomp/apps/deprecated/10.07.2012/pContinuousOpenGL_new.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "63335" }, { "name": "Matlab", "bytes": "711313" }, { "name": "Objective-C", "bytes": "63058" }, { "name": "Python", "bytes": "292499" } ], "symlink_target": "" }
import random import re from email.headerregistry import Address from typing import List, Sequence from unittest.mock import patch import ldap import orjson from django.conf import settings from django.core import mail from django.test import override_settings from django_auth_ldap.config import LDAPSearch from zerver.lib.actions import do_change_notification_settings, do_change_user_role from zerver.lib.email_notifications import ( enqueue_welcome_emails, fix_emojis, fix_spoilers_in_html, handle_missedmessage_emails, relative_to_full_url, ) from zerver.lib.send_email import FromAddress, send_custom_email from zerver.lib.test_classes import ZulipTestCase from zerver.models import ScheduledEmail, UserProfile, get_realm, get_stream class TestCustomEmails(ZulipTestCase): def test_send_custom_email_argument(self) -> None: hamlet = self.example_user('hamlet') email_subject = 'subject_test' reply_to = 'reply_to_test' from_name = "from_name_test" markdown_template_path = "templates/zerver/emails/email_base_default.source.html" send_custom_email([hamlet], { "markdown_template_path": markdown_template_path, "reply_to": reply_to, "subject": email_subject, "from_name": from_name, }) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.subject, email_subject) self.assertEqual(len(msg.reply_to), 1) self.assertEqual(msg.reply_to[0], reply_to) self.assertNotIn("{% block content %}", msg.body) def test_send_custom_email_headers(self) -> None: hamlet = self.example_user('hamlet') markdown_template_path = "zerver/tests/fixtures/email/custom_emails/email_base_headers_test.source.html" send_custom_email([hamlet], { "markdown_template_path": markdown_template_path, }) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.subject, "Test Subject") self.assertFalse(msg.reply_to) self.assertEqual('Test body', msg.body) def test_send_custom_email_no_argument(self) -> None: hamlet = self.example_user('hamlet') from_name = "from_name_test" email_subject = 'subject_test' markdown_template_path = "zerver/tests/fixtures/email/custom_emails/email_base_headers_no_headers_test.source.html" from zerver.lib.send_email import NoEmailArgumentException self.assertRaises(NoEmailArgumentException, send_custom_email, [hamlet], { "markdown_template_path": markdown_template_path, "from_name": from_name, }) self.assertRaises(NoEmailArgumentException, send_custom_email, [hamlet], { "markdown_template_path": markdown_template_path, "subject": email_subject, }) def test_send_custom_email_doubled_arguments(self) -> None: hamlet = self.example_user('hamlet') from_name = "from_name_test" email_subject = 'subject_test' markdown_template_path = "zerver/tests/fixtures/email/custom_emails/email_base_headers_test.source.html" from zerver.lib.send_email import DoubledEmailArgumentException self.assertRaises(DoubledEmailArgumentException, send_custom_email, [hamlet], { "markdown_template_path": markdown_template_path, "subject": email_subject, }) self.assertRaises(DoubledEmailArgumentException, send_custom_email, [hamlet], { "markdown_template_path": markdown_template_path, "from_name": from_name, }) def test_send_custom_email_admins_only(self) -> None: admin_user = self.example_user('hamlet') do_change_user_role(admin_user, UserProfile.ROLE_REALM_ADMINISTRATOR) non_admin_user = self.example_user('cordelia') markdown_template_path = "zerver/tests/fixtures/email/custom_emails/email_base_headers_test.source.html" send_custom_email([admin_user, non_admin_user], { "markdown_template_path": markdown_template_path, "admins_only": True, }) self.assertEqual(len(mail.outbox), 1) self.assertIn(admin_user.delivery_email, mail.outbox[0].to[0]) class TestFollowupEmails(ZulipTestCase): def test_day1_email_context(self) -> None: hamlet = self.example_user("hamlet") enqueue_welcome_emails(hamlet) scheduled_emails = ScheduledEmail.objects.filter(users=hamlet) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["email"], self.example_email("hamlet")) self.assertEqual(email_data["context"]["is_realm_admin"], False) self.assertEqual(email_data["context"]["getting_started_link"], "https://zulip.com") self.assertNotIn("ldap_username", email_data["context"]) ScheduledEmail.objects.all().delete() iago = self.example_user("iago") enqueue_welcome_emails(iago) scheduled_emails = ScheduledEmail.objects.filter(users=iago) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["email"], self.example_email("iago")) self.assertEqual(email_data["context"]["is_realm_admin"], True) self.assertEqual(email_data["context"]["getting_started_link"], "http://zulip.testserver/help/getting-your-organization-started-with-zulip") self.assertNotIn("ldap_username", email_data["context"]) # See https://zulip.readthedocs.io/en/latest/production/authentication-methods.html#ldap-including-active-directory # for case details. @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend'), # configure email search for email address in the uid attribute: AUTH_LDAP_REVERSE_EMAIL_SEARCH=LDAPSearch("ou=users,dc=zulip,dc=com", ldap.SCOPE_ONELEVEL, "(uid=%(email)s)")) def test_day1_email_ldap_case_a_login_credentials(self) -> None: self.init_default_ldap_database() ldap_user_attr_map = {'full_name': 'cn'} with self.settings(AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map): self.login_with_return("newuser_email_as_uid@zulip.com", self.ldap_password("newuser_email_as_uid@zulip.com")) user = UserProfile.objects.get(delivery_email="newuser_email_as_uid@zulip.com") scheduled_emails = ScheduledEmail.objects.filter(users=user) self.assertEqual(len(scheduled_emails), 2) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["ldap"], True) self.assertEqual(email_data["context"]["ldap_username"], "newuser_email_as_uid@zulip.com") @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_day1_email_ldap_case_b_login_credentials(self) -> None: self.init_default_ldap_database() ldap_user_attr_map = {'full_name': 'cn'} with self.settings( LDAP_APPEND_DOMAIN='zulip.com', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, ): self.login_with_return("newuser@zulip.com", self.ldap_password("newuser")) user = UserProfile.objects.get(delivery_email="newuser@zulip.com") scheduled_emails = ScheduledEmail.objects.filter(users=user) self.assertEqual(len(scheduled_emails), 2) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["ldap"], True) self.assertEqual(email_data["context"]["ldap_username"], "newuser") @override_settings(AUTHENTICATION_BACKENDS=('zproject.backends.ZulipLDAPAuthBackend', 'zproject.backends.ZulipDummyBackend')) def test_day1_email_ldap_case_c_login_credentials(self) -> None: self.init_default_ldap_database() ldap_user_attr_map = {'full_name': 'cn'} with self.settings( LDAP_EMAIL_ATTR='mail', AUTH_LDAP_USER_ATTR_MAP=ldap_user_attr_map, ): self.login_with_return("newuser_with_email", self.ldap_password("newuser_with_email")) user = UserProfile.objects.get(delivery_email="newuser_email@zulip.com") scheduled_emails = ScheduledEmail.objects.filter(users=user) self.assertEqual(len(scheduled_emails), 2) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["context"]["ldap"], True) self.assertEqual(email_data["context"]["ldap_username"], "newuser_with_email") def test_followup_emails_count(self) -> None: hamlet = self.example_user("hamlet") cordelia = self.example_user("cordelia") enqueue_welcome_emails(self.example_user("hamlet")) # Hamlet has account only in Zulip realm so both day1 and day2 emails should be sent scheduled_emails = ScheduledEmail.objects.filter(users=hamlet).order_by( "scheduled_timestamp") self.assertEqual(2, len(scheduled_emails)) self.assertEqual(orjson.loads(scheduled_emails[1].data)["template_prefix"], 'zerver/emails/followup_day2') self.assertEqual(orjson.loads(scheduled_emails[0].data)["template_prefix"], 'zerver/emails/followup_day1') ScheduledEmail.objects.all().delete() enqueue_welcome_emails(cordelia) scheduled_emails = ScheduledEmail.objects.filter(users=cordelia) # Cordelia has account in more than 1 realm so day2 email should not be sent self.assertEqual(len(scheduled_emails), 1) email_data = orjson.loads(scheduled_emails[0].data) self.assertEqual(email_data["template_prefix"], 'zerver/emails/followup_day1') class TestMissedMessages(ZulipTestCase): def normalize_string(self, s: str) -> str: s = s.strip() return re.sub(r'\s+', ' ', s) def _get_tokens(self) -> List[str]: return ['mm' + str(random.getrandbits(32)) for _ in range(30)] def _test_cases(self, msg_id: int, verify_body_include: List[str], email_subject: str, send_as_user: bool, verify_html_body: bool=False, show_message_content: bool=True, verify_body_does_not_include: Sequence[str]=[], trigger: str='') -> None: othello = self.example_user('othello') hamlet = self.example_user('hamlet') tokens = self._get_tokens() with patch('zerver.lib.email_mirror.generate_missed_message_token', side_effect=tokens): handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id, 'trigger': trigger}]) if settings.EMAIL_GATEWAY_PATTERN != "": reply_to_addresses = [settings.EMAIL_GATEWAY_PATTERN % (t,) for t in tokens] reply_to_emails = [str(Address(display_name="Zulip", addr_spec=address)) for address in reply_to_addresses] else: reply_to_emails = ["noreply@testserver"] msg = mail.outbox[0] from_email = str(Address(display_name="Zulip missed messages", addr_spec=FromAddress.NOREPLY)) self.assertEqual(len(mail.outbox), 1) if send_as_user: from_email = f'"{othello.full_name}" <{othello.email}>' self.assertEqual(msg.from_email, from_email) self.assertEqual(msg.subject, email_subject) self.assertEqual(len(msg.reply_to), 1) self.assertIn(msg.reply_to[0], reply_to_emails) if verify_html_body: for text in verify_body_include: self.assertIn(text, self.normalize_string(msg.alternatives[0][0])) else: for text in verify_body_include: self.assertIn(text, self.normalize_string(msg.body)) for text in verify_body_does_not_include: self.assertNotIn(text, self.normalize_string(msg.body)) self.assertEqual(msg.extra_headers["List-Id"], "Zulip Dev <zulip.testserver>") def _realm_name_in_missed_message_email_subject(self, realm_name_in_notifications: bool) -> None: msg_id = self.send_personal_message( self.example_user('othello'), self.example_user('hamlet'), 'Extremely personal message!', ) verify_body_include = ['Extremely personal message!'] email_subject = 'PMs with Othello, the Moor of Venice' if realm_name_in_notifications: email_subject = 'PMs with Othello, the Moor of Venice [Zulip Dev]' self._test_cases(msg_id, verify_body_include, email_subject, False) def _extra_context_in_missed_stream_messages_mention(self, send_as_user: bool, show_message_content: bool=True) -> None: for i in range(0, 11): self.send_stream_message(self.example_user('othello'), "Denmark", content=str(i)) self.send_stream_message( self.example_user('othello'), "Denmark", '11', topic_name='test2') msg_id = self.send_stream_message( self.example_user('othello'), "denmark", '@**King Hamlet**') if show_message_content: verify_body_include = [ "Othello, the Moor of Venice: 1 2 3 4 5 6 7 8 9 10 @**King Hamlet** -- ", "You are receiving this because you were mentioned in Zulip Dev.", ] email_subject = '#Denmark > test' verify_body_does_not_include: List[str] = [] else: # Test in case if message content in missed email message are disabled. verify_body_include = [ "This email does not include message content because you have disabled message ", "http://zulip.testserver/help/pm-mention-alert-notifications ", "View or reply in Zulip", " Manage email preferences: http://zulip.testserver/#settings/notifications", ] email_subject = 'New missed messages' verify_body_does_not_include = ['Denmark > test', 'Othello, the Moor of Venice', '1 2 3 4 5 6 7 8 9 10 @**King Hamlet**', 'private', 'group', 'Reply to this email directly, or view it in Zulip'] self._test_cases(msg_id, verify_body_include, email_subject, send_as_user, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include, trigger='mentioned') def _extra_context_in_missed_stream_messages_wildcard_mention(self, send_as_user: bool, show_message_content: bool=True) -> None: for i in range(1, 6): self.send_stream_message(self.example_user('othello'), "Denmark", content=str(i)) self.send_stream_message( self.example_user('othello'), "Denmark", '11', topic_name='test2') msg_id = self.send_stream_message( self.example_user('othello'), "denmark", '@**all**') if show_message_content: verify_body_include = [ "Othello, the Moor of Venice: 1 2 3 4 5 @**all** -- ", "You are receiving this because you were mentioned in Zulip Dev.", ] email_subject = '#Denmark > test' verify_body_does_not_include: List[str] = [] else: # Test in case if message content in missed email message are disabled. verify_body_include = [ "This email does not include message content because you have disabled message ", "http://zulip.testserver/help/pm-mention-alert-notifications ", "View or reply in Zulip", " Manage email preferences: http://zulip.testserver/#settings/notifications", ] email_subject = 'New missed messages' verify_body_does_not_include = ['Denmark > test', 'Othello, the Moor of Venice', '1 2 3 4 5 @**all**', 'private', 'group', 'Reply to this email directly, or view it in Zulip'] self._test_cases(msg_id, verify_body_include, email_subject, send_as_user, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include, trigger='wildcard_mentioned') def _extra_context_in_missed_stream_messages_email_notify(self, send_as_user: bool) -> None: for i in range(0, 11): self.send_stream_message(self.example_user('othello'), "Denmark", content=str(i)) self.send_stream_message( self.example_user('othello'), "Denmark", '11', topic_name='test2') msg_id = self.send_stream_message( self.example_user('othello'), "denmark", '12') verify_body_include = [ "Othello, the Moor of Venice: 1 2 3 4 5 6 7 8 9 10 12 -- ", "You are receiving this because you have email notifications enabled for this stream.", ] email_subject = '#Denmark > test' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user, trigger='stream_email_notify') def _extra_context_in_missed_stream_messages_mention_two_senders(self, send_as_user: bool) -> None: for i in range(0, 3): self.send_stream_message(self.example_user('cordelia'), "Denmark", str(i)) msg_id = self.send_stream_message( self.example_user('othello'), "Denmark", '@**King Hamlet**') verify_body_include = [ "Cordelia Lear: 0 1 2 Othello, the Moor of Venice: @**King Hamlet** -- ", "You are receiving this because you were mentioned in Zulip Dev.", ] email_subject = '#Denmark > test' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user, trigger='mentioned') def _extra_context_in_personal_missed_stream_messages(self, send_as_user: bool, show_message_content: bool=True, message_content_disabled_by_user: bool=False, message_content_disabled_by_realm: bool=False) -> None: msg_id = self.send_personal_message( self.example_user('othello'), self.example_user('hamlet'), 'Extremely personal message!', ) if show_message_content: verify_body_include = ['Extremely personal message!'] email_subject = 'PMs with Othello, the Moor of Venice' verify_body_does_not_include: List[str] = [] else: if message_content_disabled_by_realm: verify_body_include = [ "This email does not include message content because your organization has disabled", "http://zulip.testserver/help/hide-message-content-in-emails", "View or reply in Zulip", " Manage email preferences: http://zulip.testserver/#settings/notifications", ] elif message_content_disabled_by_user: verify_body_include = [ "This email does not include message content because you have disabled message ", "http://zulip.testserver/help/pm-mention-alert-notifications ", "View or reply in Zulip", " Manage email preferences: http://zulip.testserver/#settings/notifications", ] email_subject = 'New missed messages' verify_body_does_not_include = ['Othello, the Moor of Venice', 'Extremely personal message!', 'mentioned', 'group', 'Reply to this email directly, or view it in Zulip'] self._test_cases(msg_id, verify_body_include, email_subject, send_as_user, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include) def _reply_to_email_in_personal_missed_stream_messages(self, send_as_user: bool) -> None: msg_id = self.send_personal_message( self.example_user('othello'), self.example_user('hamlet'), 'Extremely personal message!', ) verify_body_include = ['Reply to this email directly, or view it in Zulip'] email_subject = 'PMs with Othello, the Moor of Venice' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user) def _reply_warning_in_personal_missed_stream_messages(self, send_as_user: bool) -> None: msg_id = self.send_personal_message( self.example_user('othello'), self.example_user('hamlet'), 'Extremely personal message!', ) verify_body_include = ['Do not reply to this email.'] email_subject = 'PMs with Othello, the Moor of Venice' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user) def _extra_context_in_huddle_missed_stream_messages_two_others(self, send_as_user: bool, show_message_content: bool=True) -> None: msg_id = self.send_huddle_message( self.example_user('othello'), [ self.example_user('hamlet'), self.example_user('iago'), ], 'Group personal message!', ) if show_message_content: verify_body_include = ['Othello, the Moor of Venice: Group personal message! -- Reply'] email_subject = 'Group PMs with Iago and Othello, the Moor of Venice' verify_body_does_not_include: List[str] = [] else: verify_body_include = [ "This email does not include message content because you have disabled message ", "http://zulip.testserver/help/pm-mention-alert-notifications ", "View or reply in Zulip", " Manage email preferences: http://zulip.testserver/#settings/notifications", ] email_subject = 'New missed messages' verify_body_does_not_include = ['Iago', 'Othello, the Moor of Venice Othello, the Moor of Venice', 'Group personal message!', 'mentioned', 'Reply to this email directly, or view it in Zulip'] self._test_cases(msg_id, verify_body_include, email_subject, send_as_user, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include) def _extra_context_in_huddle_missed_stream_messages_three_others(self, send_as_user: bool) -> None: msg_id = self.send_huddle_message( self.example_user('othello'), [ self.example_user('hamlet'), self.example_user('iago'), self.example_user('cordelia'), ], 'Group personal message!', ) verify_body_include = ['Othello, the Moor of Venice: Group personal message! -- Reply'] email_subject = 'Group PMs with Cordelia Lear, Iago, and Othello, the Moor of Venice' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user) def _extra_context_in_huddle_missed_stream_messages_many_others(self, send_as_user: bool) -> None: msg_id = self.send_huddle_message(self.example_user('othello'), [self.example_user('hamlet'), self.example_user('iago'), self.example_user('cordelia'), self.example_user('prospero')], 'Group personal message!') verify_body_include = ['Othello, the Moor of Venice: Group personal message! -- Reply'] email_subject = 'Group PMs with Cordelia Lear, Iago, and 2 others' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user) def _deleted_message_in_missed_stream_messages(self, send_as_user: bool) -> None: msg_id = self.send_stream_message( self.example_user('othello'), "denmark", '@**King Hamlet** to be deleted') hamlet = self.example_user('hamlet') self.login('othello') result = self.client_patch('/json/messages/' + str(msg_id), {'message_id': msg_id, 'content': ' '}) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) def _deleted_message_in_personal_missed_stream_messages(self, send_as_user: bool) -> None: msg_id = self.send_personal_message(self.example_user('othello'), self.example_user('hamlet'), 'Extremely personal message! to be deleted!') hamlet = self.example_user('hamlet') self.login('othello') result = self.client_patch('/json/messages/' + str(msg_id), {'message_id': msg_id, 'content': ' '}) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) def _deleted_message_in_huddle_missed_stream_messages(self, send_as_user: bool) -> None: msg_id = self.send_huddle_message( self.example_user('othello'), [ self.example_user('hamlet'), self.example_user('iago'), ], 'Group personal message!', ) hamlet = self.example_user('hamlet') iago = self.example_user('iago') self.login('othello') result = self.client_patch('/json/messages/' + str(msg_id), {'message_id': msg_id, 'content': ' '}) self.assert_json_success(result) handle_missedmessage_emails(hamlet.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) handle_missedmessage_emails(iago.id, [{'message_id': msg_id}]) self.assertEqual(len(mail.outbox), 0) def test_realm_name_in_notifications(self) -> None: # Test with realm_name_in_notifications for hamlet disabled. self._realm_name_in_missed_message_email_subject(False) # Enable realm_name_in_notifications for hamlet and test again. hamlet = self.example_user('hamlet') hamlet.realm_name_in_notifications = True hamlet.save(update_fields=['realm_name_in_notifications']) # Empty the test outbox mail.outbox = [] self._realm_name_in_missed_message_email_subject(True) def test_message_content_disabled_in_missed_message_notifications(self) -> None: # Test when user disabled message content in email notifications. do_change_notification_settings(self.example_user("hamlet"), "message_content_in_email_notifications", False) self._extra_context_in_missed_stream_messages_mention(False, show_message_content=False) mail.outbox = [] self._extra_context_in_missed_stream_messages_wildcard_mention(False, show_message_content=False) mail.outbox = [] self._extra_context_in_personal_missed_stream_messages(False, show_message_content=False, message_content_disabled_by_user=True) mail.outbox = [] self._extra_context_in_huddle_missed_stream_messages_two_others(False, show_message_content=False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_missed_stream_messages_as_user(self) -> None: self._extra_context_in_missed_stream_messages_mention(True) def test_extra_context_in_missed_stream_messages(self) -> None: self._extra_context_in_missed_stream_messages_mention(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_missed_stream_messages_as_user_wildcard(self) -> None: self._extra_context_in_missed_stream_messages_wildcard_mention(True) def test_extra_context_in_missed_stream_messages_wildcard(self) -> None: self._extra_context_in_missed_stream_messages_wildcard_mention(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_missed_stream_messages_as_user_two_senders(self) -> None: self._extra_context_in_missed_stream_messages_mention_two_senders(True) def test_extra_context_in_missed_stream_messages_two_senders(self) -> None: self._extra_context_in_missed_stream_messages_mention_two_senders(False) def test_reply_to_email_in_personal_missed_stream_messages(self) -> None: self._reply_to_email_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_missed_stream_messages_email_notify_as_user(self) -> None: self._extra_context_in_missed_stream_messages_email_notify(True) def test_extra_context_in_missed_stream_messages_email_notify(self) -> None: self._extra_context_in_missed_stream_messages_email_notify(False) @override_settings(EMAIL_GATEWAY_PATTERN="") def test_reply_warning_in_personal_missed_stream_messages(self) -> None: self._reply_warning_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_personal_missed_stream_messages_as_user(self) -> None: self._extra_context_in_personal_missed_stream_messages(True) def test_extra_context_in_personal_missed_stream_messages(self) -> None: self._extra_context_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_huddle_missed_stream_messages_two_others_as_user(self) -> None: self._extra_context_in_huddle_missed_stream_messages_two_others(True) def test_extra_context_in_huddle_missed_stream_messages_two_others(self) -> None: self._extra_context_in_huddle_missed_stream_messages_two_others(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_huddle_missed_stream_messages_three_others_as_user(self) -> None: self._extra_context_in_huddle_missed_stream_messages_three_others(True) def test_extra_context_in_huddle_missed_stream_messages_three_others(self) -> None: self._extra_context_in_huddle_missed_stream_messages_three_others(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_extra_context_in_huddle_missed_stream_messages_many_others_as_user(self) -> None: self._extra_context_in_huddle_missed_stream_messages_many_others(True) def test_extra_context_in_huddle_missed_stream_messages_many_others(self) -> None: self._extra_context_in_huddle_missed_stream_messages_many_others(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_deleted_message_in_missed_stream_messages_as_user(self) -> None: self._deleted_message_in_missed_stream_messages(True) def test_deleted_message_in_missed_stream_messages(self) -> None: self._deleted_message_in_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_deleted_message_in_personal_missed_stream_messages_as_user(self) -> None: self._deleted_message_in_personal_missed_stream_messages(True) def test_deleted_message_in_personal_missed_stream_messages(self) -> None: self._deleted_message_in_personal_missed_stream_messages(False) @override_settings(SEND_MISSED_MESSAGE_EMAILS_AS_USER=True) def test_deleted_message_in_huddle_missed_stream_messages_as_user(self) -> None: self._deleted_message_in_huddle_missed_stream_messages(True) def test_deleted_message_in_huddle_missed_stream_messages(self) -> None: self._deleted_message_in_huddle_missed_stream_messages(False) def test_realm_message_content_allowed_in_email_notifications(self) -> None: user = self.example_user("hamlet") # When message content is allowed at realm level realm = get_realm("zulip") realm.message_content_allowed_in_email_notifications = True realm.save(update_fields=['message_content_allowed_in_email_notifications']) # Emails have missed message content when message content is enabled by the user do_change_notification_settings(user, "message_content_in_email_notifications", True) mail.outbox = [] self._extra_context_in_personal_missed_stream_messages(False, show_message_content=True) # Emails don't have missed message content when message content is disabled by the user do_change_notification_settings(user, "message_content_in_email_notifications", False) mail.outbox = [] self._extra_context_in_personal_missed_stream_messages(False, show_message_content=False, message_content_disabled_by_user=True) # When message content is not allowed at realm level # Emails don't have missed message irrespective of message content setting of the user realm = get_realm("zulip") realm.message_content_allowed_in_email_notifications = False realm.save(update_fields=['message_content_allowed_in_email_notifications']) do_change_notification_settings(user, "message_content_in_email_notifications", True) mail.outbox = [] self._extra_context_in_personal_missed_stream_messages(False, show_message_content=False, message_content_disabled_by_realm=True) do_change_notification_settings(user, "message_content_in_email_notifications", False) mail.outbox = [] self._extra_context_in_personal_missed_stream_messages(False, show_message_content=False, message_content_disabled_by_user=True, message_content_disabled_by_realm=True) def test_realm_emoji_in_missed_message(self) -> None: realm = get_realm("zulip") msg_id = self.send_personal_message( self.example_user('othello'), self.example_user('hamlet'), 'Extremely personal message with a realm emoji :green_tick:!') realm_emoji_id = realm.get_active_emoji()['green_tick']['id'] realm_emoji_url = f"http://zulip.testserver/user_avatars/{realm.id}/emoji/images/{realm_emoji_id}.png" verify_body_include = [f'<img alt=":green_tick:" src="{realm_emoji_url}" title="green tick" style="height: 20px;">'] email_subject = 'PMs with Othello, the Moor of Venice' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user=False, verify_html_body=True) def test_emojiset_in_missed_message(self) -> None: hamlet = self.example_user('hamlet') hamlet.emojiset = 'twitter' hamlet.save(update_fields=['emojiset']) msg_id = self.send_personal_message( self.example_user('othello'), self.example_user('hamlet'), 'Extremely personal message with a hamburger :hamburger:!') verify_body_include = ['<img alt=":hamburger:" src="http://zulip.testserver/static/generated/emoji/images-twitter-64/1f354.png" title="hamburger" style="height: 20px;">'] email_subject = 'PMs with Othello, the Moor of Venice' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user=False, verify_html_body=True) def test_stream_link_in_missed_message(self) -> None: msg_id = self.send_personal_message( self.example_user('othello'), self.example_user('hamlet'), 'Come and join us in #**Verona**.') stream_id = get_stream('Verona', get_realm('zulip')).id href = f"http://zulip.testserver/#narrow/stream/{stream_id}-Verona" verify_body_include = [f'<a class="stream" data-stream-id="5" href="{href}">#Verona</a'] email_subject = 'PMs with Othello, the Moor of Venice' self._test_cases(msg_id, verify_body_include, email_subject, send_as_user=False, verify_html_body=True) def test_sender_name_in_missed_message(self) -> None: hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_user('iago'), "Denmark", '@**King Hamlet**') msg_id_2 = self.send_stream_message(self.example_user('iago'), "Verona", '* 1\n *2') msg_id_3 = self.send_personal_message(self.example_user('iago'), hamlet, 'Hello') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "mentioned"}, {'message_id': msg_id_2, "trigger": "stream_email_notify"}, {'message_id': msg_id_3}, ]) self.assertIn('Iago: @**King Hamlet**\n\n--\nYou are', mail.outbox[0].body) # If message content starts with <p> tag the sender name is appended inside the <p> tag. self.assertIn('<p><b>Iago</b>: <span class="user-mention"', mail.outbox[0].alternatives[0][0]) self.assertIn('Iago: * 1\n *2\n\n--\nYou are receiving', mail.outbox[1].body) # If message content does not starts with <p> tag sender name is appended before the <p> tag self.assertIn(' <b>Iago</b>: <ul>\n<li>1<br/>\n *2</li>\n</ul>\n', mail.outbox[1].alternatives[0][0]) self.assertEqual('Hello\n\n--\n\nReply', mail.outbox[2].body[:16]) # Sender name is not appended to message for PM missed messages self.assertIn('>\n \n <p>Hello</p>\n', mail.outbox[2].alternatives[0][0]) def test_multiple_missed_personal_messages(self) -> None: hamlet = self.example_user('hamlet') msg_id_1 = self.send_personal_message(self.example_user('othello'), hamlet, 'Personal Message 1') msg_id_2 = self.send_personal_message(self.example_user('iago'), hamlet, 'Personal Message 2') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1}, {'message_id': msg_id_2}, ]) self.assertEqual(len(mail.outbox), 2) email_subject = 'PMs with Othello, the Moor of Venice' self.assertEqual(mail.outbox[0].subject, email_subject) email_subject = 'PMs with Iago' self.assertEqual(mail.outbox[1].subject, email_subject) def test_multiple_stream_messages(self) -> None: hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_user('othello'), "Denmark", 'Message1') msg_id_2 = self.send_stream_message(self.example_user('iago'), "Denmark", 'Message2') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "stream_email_notify"}, {'message_id': msg_id_2, "trigger": "stream_email_notify"}, ]) self.assertEqual(len(mail.outbox), 1) email_subject = '#Denmark > test' self.assertEqual(mail.outbox[0].subject, email_subject) def test_multiple_stream_messages_and_mentions(self) -> None: """Subject should be stream name and topic as usual.""" hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_user('iago'), "Denmark", 'Regular message') msg_id_2 = self.send_stream_message(self.example_user('othello'), "Denmark", '@**King Hamlet**') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "stream_email_notify"}, {'message_id': msg_id_2, "trigger": "mentioned"}, ]) self.assertEqual(len(mail.outbox), 1) email_subject = '#Denmark > test' self.assertEqual(mail.outbox[0].subject, email_subject) def test_message_access_in_emails(self) -> None: # Messages sent to a protected history-private stream shouldn't be # accessible/available in emails before subscribing stream_name = "private_stream" self.make_stream(stream_name, invite_only=True, history_public_to_subscribers=False) user = self.example_user('iago') self.subscribe(user, stream_name) late_subscribed_user = self.example_user('hamlet') self.send_stream_message(user, stream_name, 'Before subscribing') self.subscribe(late_subscribed_user, stream_name) self.send_stream_message(user, stream_name, "After subscribing") mention_msg_id = self.send_stream_message(user, stream_name, '@**King Hamlet**') handle_missedmessage_emails(late_subscribed_user.id, [ {'message_id': mention_msg_id, "trigger": "mentioned"}, ]) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, '#private_stream > test') # email subject email_text = mail.outbox[0].message().as_string() self.assertNotIn('Before subscribing', email_text) self.assertIn('After subscribing', email_text) self.assertIn('@**King Hamlet**', email_text) def test_stream_mentions_multiple_people(self) -> None: """Subject should be stream name and topic as usual.""" hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_user('iago'), "Denmark", '@**King Hamlet**') msg_id_2 = self.send_stream_message(self.example_user('othello'), "Denmark", '@**King Hamlet**') msg_id_3 = self.send_stream_message(self.example_user('cordelia'), "Denmark", 'Regular message') handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "mentioned"}, {'message_id': msg_id_2, "trigger": "mentioned"}, {'message_id': msg_id_3, "trigger": "stream_email_notify"}, ]) self.assertEqual(len(mail.outbox), 1) email_subject = '#Denmark > test' self.assertEqual(mail.outbox[0].subject, email_subject) def test_multiple_stream_messages_different_topics(self) -> None: """Should receive separate emails for each topic within a stream.""" hamlet = self.example_user('hamlet') msg_id_1 = self.send_stream_message(self.example_user('othello'), "Denmark", 'Message1') msg_id_2 = self.send_stream_message(self.example_user('iago'), "Denmark", 'Message2', topic_name="test2") handle_missedmessage_emails(hamlet.id, [ {'message_id': msg_id_1, "trigger": "stream_email_notify"}, {'message_id': msg_id_2, "trigger": "stream_email_notify"}, ]) self.assertEqual(len(mail.outbox), 2) email_subjects = {mail.outbox[0].subject, mail.outbox[1].subject} valid_email_subjects = {'#Denmark > test', '#Denmark > test2'} self.assertEqual(email_subjects, valid_email_subjects) def test_relative_to_full_url(self) -> None: zulip_realm = get_realm("zulip") zephyr_realm = get_realm("zephyr") # Run `relative_to_full_url()` function over test fixtures present in # 'markdown_test_cases.json' and check that it converts all the relative # URLs to absolute URLs. fixtures = orjson.loads(self.fixture_data("markdown_test_cases.json")) test_fixtures = {} for test in fixtures['regular_tests']: test_fixtures[test['name']] = test for test_name in test_fixtures: test_data = test_fixtures[test_name]["expected_output"] output_data = relative_to_full_url("http://example.com", test_data) if re.search(r"""(?<=\=['"])/(?=[^<]+>)""", output_data) is not None: raise AssertionError("Relative URL present in email: " + output_data + "\nFailed test case's name is: " + test_name + "\nIt is present in markdown_test_cases.json") # Specific test cases. # A path similar to our emoji path, but not in a link: test_data = "<p>Check out the file at: '/static/generated/emoji/images/emoji/'</p>" actual_output = relative_to_full_url("http://example.com", test_data) expected_output = "<p>Check out the file at: '/static/generated/emoji/images/emoji/'</p>" self.assertEqual(actual_output, expected_output) # An uploaded file test_data = '<a href="/user_uploads/{realm_id}/1f/some_random_value">/user_uploads/{realm_id}/1f/some_random_value</a>' test_data = test_data.format(realm_id=zephyr_realm.id) actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<a href="http://example.com/user_uploads/{realm_id}/1f/some_random_value">' + \ '/user_uploads/{realm_id}/1f/some_random_value</a>' expected_output = expected_output.format(realm_id=zephyr_realm.id) self.assertEqual(actual_output, expected_output) # A profile picture like syntax, but not actually in an HTML tag test_data = '<p>Set src="/avatar/username@example.com?s=30"</p>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<p>Set src="/avatar/username@example.com?s=30"</p>' self.assertEqual(actual_output, expected_output) # A narrow URL which begins with a '#'. test_data = '<p><a href="#narrow/stream/test/topic/test.20topic/near/142"' + \ 'title="#narrow/stream/test/topic/test.20topic/near/142">Conversation</a></p>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<p><a href="http://example.com/#narrow/stream/test/topic/test.20topic/near/142" ' + \ 'title="http://example.com/#narrow/stream/test/topic/test.20topic/near/142">Conversation</a></p>' self.assertEqual(actual_output, expected_output) # Scrub inline images. test_data = '<p>See this <a href="/user_uploads/{realm_id}/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg" target="_blank" ' + \ 'title="avatar_103.jpeg">avatar_103.jpeg</a>.</p>' + \ '<div class="message_inline_image"><a href="/user_uploads/{realm_id}/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg" ' + \ 'target="_blank" title="avatar_103.jpeg"><img src="/user_uploads/{realm_id}/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg"></a></div>' test_data = test_data.format(realm_id=zulip_realm.id) actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<div><p>See this <a href="http://example.com/user_uploads/{realm_id}/52/fG7GM9e3afz_qsiUcSce2tl_/avatar_103.jpeg" target="_blank" ' + \ 'title="avatar_103.jpeg">avatar_103.jpeg</a>.</p></div>' expected_output = expected_output.format(realm_id=zulip_realm.id) self.assertEqual(actual_output, expected_output) # A message containing only an inline image URL preview, we do # somewhat more extensive surgery. test_data = '<div class="message_inline_image"><a href="https://www.google.com/images/srpr/logo4w.png" ' + \ 'target="_blank" title="https://www.google.com/images/srpr/logo4w.png">' + \ '<img data-src-fullsize="/thumbnail/https%3A//www.google.com/images/srpr/logo4w.png?size=0x0" ' + \ 'src="/thumbnail/https%3A//www.google.com/images/srpr/logo4w.png?size=0x100"></a></div>' actual_output = relative_to_full_url("http://example.com", test_data) expected_output = '<p><a href="https://www.google.com/images/srpr/logo4w.png" ' + \ 'target="_blank" title="https://www.google.com/images/srpr/logo4w.png">' + \ 'https://www.google.com/images/srpr/logo4w.png</a></p>' self.assertEqual(actual_output, expected_output) def test_spoilers_in_html_emails(self) -> None: test_data = "<div class=\"spoiler-block\"><div class=\"spoiler-header\">\n\n<p><a>header</a> text</p>\n</div><div class=\"spoiler-content\" aria-hidden=\"true\">\n\n<p>content</p>\n</div></div>\n\n<p>outside spoiler</p>" actual_output = fix_spoilers_in_html(test_data, 'en') expected_output = "<div><div class=\"spoiler-block\">\n\n<p><a>header</a> text<span> </span><span class=\"spoiler-title\" title=\"Open Zulip to see the spoiler content\">(Open Zulip to see the spoiler content)</span></p>\n</div>\n\n<p>outside spoiler</p></div>" self.assertEqual(actual_output, expected_output) # test against our markdown_test_cases so these features do not get out of sync. fixtures = orjson.loads(self.fixture_data("markdown_test_cases.json")) test_fixtures = {} for test in fixtures['regular_tests']: if 'spoiler' in test['name']: test_fixtures[test['name']] = test for test_name in test_fixtures: test_data = test_fixtures[test_name]["expected_output"] output_data = fix_spoilers_in_html(test_data, 'en') assert('spoiler-header' not in output_data) assert('spoiler-content' not in output_data) assert('spoiler-block' in output_data) assert('spoiler-title' in output_data) def test_spoilers_in_text_emails(self) -> None: content = "@**King Hamlet**\n\n```spoiler header text\nsecret-text\n```" msg_id = self.send_stream_message(self.example_user('othello'), "Denmark", content) verify_body_include = [ "header text", "Open Zulip to see the spoiler content" ] verify_body_does_not_include = ["secret-text"] email_subject = '#Denmark > test' send_as_user = False self._test_cases(msg_id, verify_body_include, email_subject, send_as_user, trigger='mentioned', verify_body_does_not_include=verify_body_does_not_include) def test_fix_emoji(self) -> None: # An emoji. test_data = '<p>See <span aria-label="cloud with lightning and rain" class="emoji emoji-26c8" role="img" title="cloud with lightning and rain">' + \ ':cloud_with_lightning_and_rain:</span>.</p>' actual_output = fix_emojis(test_data, "http://example.com", "google") expected_output = '<p>See <img alt=":cloud_with_lightning_and_rain:" src="http://example.com/static/generated/emoji/images-google-64/26c8.png" ' + \ 'title="cloud with lightning and rain" style="height: 20px;">.</p>' self.assertEqual(actual_output, expected_output)
{ "content_hash": "aa1eab042c4776cb8bfe0fb92e0096dd", "timestamp": "", "source": "github", "line_count": 985, "max_line_length": 269, "avg_line_length": 54.24162436548223, "alnum_prop": 0.5988058695814928, "repo_name": "brainwane/zulip", "id": "f6b8f640277ec2c52a545a040a69f60bba388c25", "size": "53428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zerver/tests/test_email_notifications.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "423578" }, { "name": "Emacs Lisp", "bytes": "158" }, { "name": "HTML", "bytes": "647926" }, { "name": "JavaScript", "bytes": "2886792" }, { "name": "Pascal", "bytes": "1113" }, { "name": "Perl", "bytes": "398747" }, { "name": "Puppet", "bytes": "90558" }, { "name": "Python", "bytes": "6000548" }, { "name": "Ruby", "bytes": "249744" }, { "name": "Shell", "bytes": "110849" }, { "name": "TypeScript", "bytes": "9543" } ], "symlink_target": "" }
""" A StreamHandler that extracts messages from streams """ from __future__ import print_function from collections import defaultdict import sys import traceback from .thrift_message import ThriftMessage class StreamContext(object): def __init__(self): self.bytes = '' class StreamHandler(object): def __init__(self, outqueue, protocol=None, finagle_thrift=False, max_message_size=1024*1000, read_values=False, debug=False): self._contexts_by_streams = defaultdict(StreamContext) self._pop_size = 1024 # TODO: what's a good value here? self._outqueue = outqueue self._protocol = protocol self._finagle_thrift = finagle_thrift self._max_message_size = max_message_size self._debug = debug self._read_values = read_values self._seen_messages = 0 self._recognized_streams = set() # streams from which msgs have been read def __call__(self, *args, **kwargs): self.handler(*args, **kwargs) @property def seen_streams(self): return len(self._contexts_by_streams) @property def recognized_streams(self): return len(self._recognized_streams) @property def unrecognized_streams(self): return self.seen_streams - self.recognized_streams @property def pending_thrift_msgs(self): return len(self._outqueue) @property def seen_thrift_msgs(self): return self._seen_messages def handler(self, stream): context = self._contexts_by_streams[stream] bytes, timestamp = stream.pop_data(self._pop_size) context.bytes += bytes # EMSGSIZE if len(context.bytes) >= self._max_message_size: if self._debug: print('Dropping bytes, dropped size: %d' % len(context.bytes)) context.bytes = '' return # FIXME: a bit of brute force to find the start of a message. # Is there a magic byte/string we can look for? view = memoryview(context.bytes) for idx in range(0, len(context.bytes)): try: data_slice = view[idx:].tobytes() msg, msglen = ThriftMessage.read( data_slice, protocol=self._protocol, finagle_thrift=self._finagle_thrift, read_values=self._read_values) except EOFError: continue except Exception as ex: if self._debug: print('Bad message for stream %s: %s: %s\n(idx=%d) ' '(context size=%d)' % ( stream, ex, traceback.format_exc(), idx, len(context.bytes)), file=sys.stderr ) continue self._recognized_streams.add(stream) self._seen_messages += 1 self._outqueue.append((timestamp, stream.src, stream.dst, msg)) context.bytes = context.bytes[idx + msglen:] break
{ "content_hash": "397275abe6f7a68f62255e1a791a3ed8", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 82, "avg_line_length": 31.854368932038835, "alnum_prop": 0.535202682109113, "repo_name": "shrijeet/thrift-tools", "id": "52694e15de156a63d28edf3880389d6b49e94a23", "size": "3281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "thrift_tools/stream_handler.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "71706" } ], "symlink_target": "" }
import os from shutil import which from threading import Lock from vcstool.executor import USE_COLOR from .vcs_base import VcsClientBase from ..util import rmtree class HgClient(VcsClientBase): type = 'hg' _executable = None _config_color = None _config_color_lock = Lock() @staticmethod def is_repository(path): return os.path.isdir(os.path.join(path, '.hg')) def __init__(self, path): super(HgClient, self).__init__(path) def branch(self, command): self._check_executable() cmd = [HgClient._executable, 'branches' if command.all else 'branch'] self._check_color(cmd) return self._run_command(cmd) def custom(self, command): self._check_executable() cmd = [HgClient._executable] + command.args return self._run_command(cmd) def diff(self, command): self._check_executable() cmd = [HgClient._executable, 'diff'] self._check_color(cmd) if command.context: cmd += ['--unified %d' % command.context] return self._run_command(cmd) def export(self, command): self._check_executable() result_url = self._get_url() if result_url['returncode']: return result_url url = result_url['output'] cmd_id = [HgClient._executable, 'identify', '--id'] result_id = self._run_command(cmd_id) if result_id['returncode']: result_id['output'] = \ 'Could not determine id: ' + result_id['output'] return result_id id_ = result_id['output'] if not command.exact: cmd_branch = [HgClient._executable, 'identify', '--branch'] result_branch = self._run_command(cmd_branch) if result_branch['returncode']: result_branch['output'] = \ 'Could not determine branch: ' + result_branch['output'] return result_branch branch = result_branch['output'] cmd_branch_id = [ HgClient._executable, 'identify', '-r', branch, '--id'] result_branch_id = self._run_command(cmd_branch_id) if result_branch_id['returncode']: result_branch_id['output'] = \ 'Could not determine branch id: ' + \ result_branch_id['output'] return result_branch_id if result_branch_id['output'] == id_: id_ = branch cmd_branch = cmd_branch_id return { 'cmd': '%s && %s' % (result_url['cmd'], ' '.join(cmd_id)), 'cwd': self.path, 'output': '\n'.join([url, id_]), 'returncode': 0, 'export_data': {'url': url, 'version': id_} } def _get_url(self): cmd_url = [HgClient._executable, 'paths', 'default'] result_url = self._run_command(cmd_url) if result_url['returncode']: result_url['output'] = \ 'Could not determine url: ' + result_url['output'] return result_url return result_url def import_(self, command): if not command.url or not command.version: if not command.url and not command.version: value_missing = "'url' and 'version'" elif not command.url: value_missing = "'url'" else: value_missing = "'version'" return { 'cmd': '', 'cwd': self.path, 'output': 'Repository data lacks the %s value' % value_missing, 'returncode': 1 } self._check_executable() if HgClient.is_repository(self.path): # verify that existing repository is the same result_url = self._get_url() if result_url['returncode']: return result_url url = result_url['output'] if url != command.url: if not command.force: return { 'cmd': '', 'cwd': self.path, 'output': 'Path already exists and contains a different ' 'repository', 'returncode': 1 } try: rmtree(self.path) except OSError: os.remove(self.path) not_exist = self._create_path() if not_exist: return not_exist if HgClient.is_repository(self.path): # pull updates for existing repo cmd_pull = [ HgClient._executable, '--noninteractive', 'pull', '--update'] result_pull = self._run_command(cmd_pull, retry=command.retry) if result_pull['returncode']: return result_pull cmd = result_pull['cmd'] output = result_pull['output'] else: cmd_clone = [ HgClient._executable, '--noninteractive', 'clone', command.url, '.'] result_clone = self._run_command(cmd_clone, retry=command.retry) if result_clone['returncode']: result_clone['output'] = \ "Could not clone repository '%s': %s" % \ (command.url, result_clone['output']) return result_clone cmd = result_clone['cmd'] output = result_clone['output'] if command.version: cmd_checkout = [ HgClient._executable, '--noninteractive', 'checkout', command.version] result_checkout = self._run_command(cmd_checkout) if result_checkout['returncode']: result_checkout['output'] = \ "Could not checkout '%s': %s" % \ (command.version, result_checkout['output']) return result_checkout cmd += ' && ' + ' '.join(cmd_checkout) output = '\n'.join([output, result_checkout['output']]) return { 'cmd': cmd, 'cwd': self.path, 'output': output, 'returncode': 0 } def log(self, command): self._check_executable() if command.limit_tag: # check if specific tag exists cmd_log = [ HgClient._executable, 'log', '--rev', 'tag(%s)' % command.limit_tag] result_log = self._run_command(cmd_log) if result_log['returncode']: return { 'cmd': '', 'cwd': self.path, 'output': "Repository lacks the tag '%s'" % command.limit_tag, 'returncode': 1 } # output log since specific tag cmd = [ HgClient._executable, 'log', '--rev', 'sort(tag(%s)::, -rev) and not tag (%s)' % (command.limit_tag, command.limit_tag)] elif command.limit_untagged: # determine distance to nearest tag cmd_log = [ HgClient._executable, 'log', '--rev', '.', '--template', '{latesttagdistance}'] result_log = self._run_command(cmd_log) if result_log['returncode']: return result_log # output log since nearest tag cmd = [ HgClient._executable, 'log', '--limit', result_log['output'], '-b', '.'] else: cmd = [HgClient._executable, 'log'] if command.limit != 0: cmd += ['--limit', '%d' % command.limit] if command.verbose: cmd += ['--verbose'] self._check_color(cmd) return self._run_command(cmd) def pull(self, _command): self._check_executable() cmd = [HgClient._executable, '--noninteractive', 'pull', '--update'] self._check_color(cmd) return self._run_command(cmd) def push(self, _command): self._check_executable() cmd = [HgClient._executable, '--noninteractive', 'push'] return self._run_command(cmd) def remotes(self, _command): self._check_executable() cmd = [HgClient._executable, 'paths'] return self._run_command(cmd) def status(self, command): self._check_executable() cmd = [HgClient._executable, 'status'] self._check_color(cmd) if command.quiet: cmd += ['--untracked-files=no'] return self._run_command(cmd) def validate(self, command): if not command.url: return { 'cmd': '', 'cwd': self.path, 'output': "Repository data lacks the 'url' value", 'returncode': 1 } self._check_executable() cmd_id_repo = [ HgClient._executable, '--noninteractive', 'identify', command.url] result_id_repo = self._run_command( cmd_id_repo, retry=command.retry) if result_id_repo['returncode']: result_id_repo['output'] = \ "Failed to contact remote repository '%s': %s" % \ (command.url, result_id_repo['output']) return result_id_repo if command.version: cmd_id_ver = [ HgClient._executable, '--noninteractive', 'identify', '-r', command.version, command.url] result_id_ver = self._run_command( cmd_id_ver, retry=command.retry) if result_id_ver['returncode']: result_id_ver['output'] = \ 'Specified version not found on remote repository ' + \ "'%s':'%s' : %s" % \ (command.url, command.version, result_id_ver['output']) return result_id_ver cmd = result_id_ver['cmd'] output = "Found hg repository '%s' with changeset '%s'" % \ (command.url, command.version) else: cmd = result_id_repo['cmd'] output = "Found hg repository '%s' with default branch" % \ command.url return { 'cmd': cmd, 'cwd': self.path, 'output': output, 'returncode': None } def _check_color(self, cmd): if not USE_COLOR: return with HgClient._config_color_lock: # check if user uses colorization if HgClient._config_color is None: HgClient._config_color = False # check if config extension is available _cmd = [HgClient._executable, 'config', '--help'] result = self._run_command(_cmd) if result['returncode']: return # check if color extension is available and not disabled _cmd = [HgClient._executable, 'config', 'extensions.color'] result = self._run_command(_cmd) if result['returncode'] or result['output'].startswith('!'): return # check if color mode is not off or not set _cmd = [HgClient._executable, 'config', 'color.mode'] result = self._run_command(_cmd) if not result['returncode'] and result['output'] == 'off': return HgClient._config_color = True # inject arguments to force colorization if HgClient._config_color: cmd[1:1] = '--color', 'always' def _check_executable(self): assert HgClient._executable is not None, \ "Could not find 'hg' executable" if not HgClient._executable: HgClient._executable = which('hg')
{ "content_hash": "480b87bdfb7da66b4de36581d095f8b1", "timestamp": "", "source": "github", "line_count": 333, "max_line_length": 79, "avg_line_length": 35.945945945945944, "alnum_prop": 0.4944026733500418, "repo_name": "dirk-thomas/vcstool", "id": "e0eb3ddc3bdc00171f350eb3fccf6f13560113e9", "size": "11970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vcstool/clients/hg.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "384" }, { "name": "Python", "bytes": "126487" }, { "name": "Shell", "bytes": "814" } ], "symlink_target": "" }
'''Example WordCountTopology''' import sys import heron.api.src.python.api_constants as constants from heron.api.src.python import Grouping, TopologyBuilder from heron.examples.src.python.spout import WordSpout from heron.examples.src.python.bolt import CountBolt # Topology is defined using a topology builder # Refer to multi_stream_topology for defining a topology by subclassing Topology if __name__ == '__main__': if len(sys.argv) != 2: print "Topology's name is not specified" sys.exit(1) builder = TopologyBuilder(name=sys.argv[1]) word_spout = builder.add_spout("word_spout", WordSpout, par=2) count_bolt = builder.add_bolt("count_bolt", CountBolt, par=2, inputs={word_spout: Grouping.fields('word')}, config={constants.TOPOLOGY_TICK_TUPLE_FREQ_SECS: 10}) topology_config = {constants.TOPOLOGY_RELIABILITY_MODE: constants.TopologyReliabilityMode.ATLEAST_ONCE} builder.set_config(topology_config) builder.build_and_submit()
{ "content_hash": "3e5f57ddec58e4289dbb9c2a85812fc8", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 85, "avg_line_length": 38.81481481481482, "alnum_prop": 0.6946564885496184, "repo_name": "streamlio/heron", "id": "0b60b0586aac5c9380bd78c5bcf7619f82fe5464", "size": "1640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "heron/examples/src/python/word_count_topology.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5753" }, { "name": "C++", "bytes": "1314724" }, { "name": "CSS", "bytes": "109095" }, { "name": "HTML", "bytes": "154389" }, { "name": "Java", "bytes": "3505119" }, { "name": "JavaScript", "bytes": "167652" }, { "name": "M4", "bytes": "17941" }, { "name": "Makefile", "bytes": "517" }, { "name": "Objective-C", "bytes": "1929" }, { "name": "Perl", "bytes": "9085" }, { "name": "Protocol Buffer", "bytes": "31644" }, { "name": "Python", "bytes": "1374251" }, { "name": "Ruby", "bytes": "1930" }, { "name": "Scala", "bytes": "4640" }, { "name": "Shell", "bytes": "148606" }, { "name": "Thrift", "bytes": "915" } ], "symlink_target": "" }
from flask import Flask import os import psycopg2 from contextlib import closing from flask import g from flask import render_template from flask import abort from flask import request from flask import url_for from flask import redirect from flask import session import datetime import markdown #import pygments from passlib.hash import pbkdf2_sha256 DB_SCHEMA = """ DROP TABLE IF EXISTS entries; CREATE TABLE entries ( id serial PRIMARY KEY, title VARCHAR (127) NOT NULL, text TEXT NOT NULL, created TIMESTAMP NOT NULL ) """ DB_ENTRY_INSERT = """ INSERT INTO ENTRIES (title, text, created) VALUES (%s, %s, %s) """ DB_ENTRIES_LIST = """ SELECT id, title, text, created FROM entries ORDER BY created DESC """ DB_ENTRY_OVERWRITE = """ UPDATE ENTRIES SET title = %s, text = %s WHERE id = %s """ app = Flask(__name__) app.config['DATABASE'] = os.environ.get( 'DATABASE_URL', 'dbname=learning_journal user=Michelle') app.config['ADMIN_USERNAME'] = os.environ.get( 'ADMIN_USERNAME', 'admin') app.config['ADMIN_PASSWORD'] = os.environ.get( 'ADMIN_PASSWORD', pbkdf2_sha256.encrypt('admin')) app.config['SECRET_KEY'] = os.environ.get( 'FLASK_SECRET_KEY', 'sooperseekritvaluenooneshouldknow') is_edit = False def connect_db(): """Return a connection to the configured database""" return psycopg2.connect(app.config['DATABASE']) def init_db(): """Initializing the database using DB_SCHEMA WARNING: executing this function will drop existing tables. """ with closing(connect_db()) as db: db.cursor().execute(DB_SCHEMA) db.commit() def get_database_connection(): db = getattr(g, 'db', None) if db is None: g.db = db = connect_db() return db @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: if exception and isinstance(exception, psycopg2.Error): # if there was a problem with thte database, rollback any # existing transaction db.rollback() else: # otherwise, commit db.commit() db.close() def write_entry(title, text): if not title or not text: raise ValueError("Title and text required for writing an entry") con = get_database_connection() cur = con.cursor() now = datetime.datetime.utcnow() try: title = unicode(title) text = unicode(text) print type(title), type(text) cur.execute(DB_ENTRY_INSERT, [title, text, now]) except UnicodeDecodeError: abort(500) def rewrite_entry(title, text, id): con = get_database_connection() cur = con.cursor() try: title = unicode(title) text = unicode(text) cur.execute(DB_ENTRY_OVERWRITE, [title, text, id]) except UnicodeDecodeError: abort(500) def get_all_entries(): """return a list of all entries as dicts""" con = get_database_connection() cur = con.cursor() cur.execute(DB_ENTRIES_LIST) keys = (u'id', u'title', u'text', u'created') return [dict(zip(keys, row)) for row in cur.fetchall()] def do_login(username='', passwd=''): if username != app.config['ADMIN_USERNAME']: raise ValueError if not pbkdf2_sha256.verify(passwd, app.config['ADMIN_PASSWORD']): raise ValueError session['logged_in'] = True @app.route('/') def show_entries(): entries = get_all_entries() for entry in entries: entry['text'] = markdown.markdown(entry['text'], extensions=['codehilite']) shebang = u" #!/usr/bin/python\n def main():\n \ return x" shebang_hl = markdown.markdown(shebang, extensions=['codehilite']) shebang2 = u" #!python\n def main():\n \ return x" shebang_wo = markdown.markdown(shebang2, extensions=['codehilite']) colons = u" :::python\n def main():\n \ return x" colons_hl = markdown.markdown(colons, extensions=['codehilite']) return render_template('list_entries.html', entries=entries, shebang_hl=shebang_hl, shebang_wo=shebang_wo, colons_hl=colons_hl) @app.route('/add', methods=['POST']) def add_entry(): try: write_entry(request.form['title'], request.form['text']) except psycopg2.Error: # this will catch any errors generated by the database abort(500) return redirect(url_for('show_entries')) @app.route('/edit/<id>', methods=['GET', 'POST']) def edit_entry(id): entries = get_all_entries() title = u"No Title" text = u"No Text" for entry in entries: if entry['id'] == int(id): title = entry['title'] text = entry['text'] return render_template('list_entries.html', entries=entries, is_edit=True, edit_id=id, edit_title=title, edit_text=text) @app.route('/edit/<id>/submit', methods=['GET', 'POST']) def submit_edit(id): try: rewrite_entry(request.form['title'], request.form['text'], id) except psycopg2.Error: # this will catch any errors generated by the database abort(500) return redirect(url_for('show_entries')) @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': try: do_login(request.form['username'].encode('utf-8'), request.form['password'].encode('utf-8')) except ValueError: error = "Login Failed" else: return redirect(url_for('show_entries')) return render_template('login.html', error=error) @app.route('/logout') def logout(): session.pop('logged_in', None) return redirect(url_for('show_entries')) if __name__ == '__main__': app.run(debug=True)
{ "content_hash": "719187d128714f6a3e44d58ab92a2866", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 78, "avg_line_length": 28.642156862745097, "alnum_prop": 0.6198870443265446, "repo_name": "miracode/learning_journal", "id": "d1cd37b900ebef4bdc28efd44391b64de5b5464f", "size": "5867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "journal.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5540" }, { "name": "Python", "bytes": "13911" } ], "symlink_target": "" }
import argparse import glob import joblib import os from satdetect.ioutil import imgpath2list from satdetect.featextract import WindowExtractor, HOGFeatExtractor from satdetect.detect import BasicTrainSetBuilder, Detector def runDetector(imgpath='', cpath='', decisionThr=0.5, **kwargs): ''' Run pre-trained detector (stored in cpath) on imagery in imgpath Returns -------- None. ''' try: SaveVars = joblib.load(cpath) C = SaveVars['ClassifierObj'] TrainInfo = SaveVars['TrainDataInfo'] except Exception as e: print 'ERROR: Unable to load from file:\n' + cpath raise e imgpathList = imgpath2list(imgpath) DInfo = dict() DInfo['imgpathList'] = imgpathList DInfo['outpath'] = TrainInfo['outpath'] ## Break up satellite image into 25x25 pixel windows WindowExtractor.transform(DInfo) ## Extract HOG feature vector for each window featExtractor = HOGFeatExtractor() featExtractor.transform(DInfo) ## Evaluate the classifier on the training set Detector.runDetector(C, DInfo, decisionThr=decisionThr, **kwargs) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('imgpath', type=str, help='path(s) to load training images from') parser.add_argument('cpath', type=str, help='path where pre-trained classifier dump-file lives') parser.add_argument('--decisionThr', type=float, default=0.5, help='decision threshold for classifier') args = parser.parse_args() runDetector(**args.__dict__)
{ "content_hash": "0b1b458ce44f3433a005ef619f2586eb", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 79, "avg_line_length": 31.019607843137255, "alnum_prop": 0.6845764854614412, "repo_name": "michaelchughes/satdetect", "id": "a085cea95262c746cad14fe26f44156f5a97105a", "size": "1582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "satdetect/RunDetector.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "48341" } ], "symlink_target": "" }
from django.shortcuts import render_to_response, get_object_or_404 from blogpost.models import BlogPost from blogpost.forms import BlogForm from django.http import HttpResponseRedirect def blogList(request): blogs = BlogPost.objects.all() return render_to_response('blogpost/blog_list.html', {'blogs': blogs}) def blogEdit(request, id): id = id blogs = get_object_or_404(BlogPost, id=id) if request.method == "POST": bf = BlogForm(request.POST, instance=blogs) if bf.is_valid(): data = bf.cleaned_data title = data['title'] body = data['body'] if blogs: blogs.title = title blogs.body = body blogs.save() else: blogs = BlogPost(title=blogs.title, body=blogs.body) blogs.save() return HttpResponseRedirect('/blogpost/list/') return render_to_response('blogpost/blog_edit.html', {'bf': BlogForm(instance=blogs)}) def blogWritenew(request): if request.method == "POST": bf = BlogForm(request.POST) if bf.is_valid(): title = bf.cleaned_data['title'] body = bf.cleaned_data['body'] #timestmap = request.POST['timestamp'] blogs = BlogPost.objects.create(title=title, body=body) blogs.save() id = BlogPost.objects.order_by('-timestamp')[0].id return HttpResponseRedirect('/blogpost/showdetail/%s/' % id) else: bf = BlogForm() return render_to_response('blogpost/blog_writenew.html', {'bf': bf}) def blogDelete(request, id): blog = BlogPost.objects.get(id=id) if blog: blog.delete() return HttpResponseRedirect('/blogpost/list') blogs = BlogPost.objects.all() return render_to_response('blogpost/blog_list.html', {'blogs': blogs}) def blogSearch(request): errors = [] if 't' in request.POST and request.POST['t']: t = request.POST['t'] if len(t) == 0: errors.append('Please enter a search term.') elif len(t) >= 20: errors.append('Please enter at most 20 characters.') else: blogs = BlogPost.objects.filter(title__icontains=t).order_by('-timestamp') return render_to_response('blogpost/blog_search_result.html', {'blogs': blogs}) return render_to_response('blogpost/blog_search_result.html', {'errors': errors}) def blogShowDetail(request, id): id = id blog = BlogPost.objects.get(id=id) if blog: return render_to_response('blogpost/blog_show_detail.html', {'blog': blog}) else: blogs = BlogPost.objects.all() render_to_response('blogpost/blog_list.html', {'blogs': blogs})
{ "content_hash": "4dfdba101a875a2ecd2c7bc02696a7a2", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 91, "avg_line_length": 35.294871794871796, "alnum_prop": 0.6077006901561932, "repo_name": "hisuley/sxj", "id": "48f2bf2a61c691ddc37d1bc6857155f81b974fbe", "size": "2753", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blog/blogpost/views.py", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "7449" }, { "name": "Python", "bytes": "26786" } ], "symlink_target": "" }
import unittest import Trace import TraceOperations import BinaryCodec import StringIO testTrace1 = "data/note.bin" testTrace2 = "data/simplecube.bin" class TraceOperationsTest(unittest.TestCase): def loadTrace(self, traceFile): trace = Trace.Trace() reader = BinaryCodec.Reader(trace, open(traceFile, "rb")) reader.load() return trace def assertEqualEventLists(self, events1, events2): for e1, e2 in zip(events1, events2): self.assertEquals(e1.name, e2.name) self.assertEquals(len(e1.values), len(e2.values)) for v1, v2 in zip(e1.values.values(), e2.values.values()): if isinstance(v1, Trace.VoidValue): continue elif isinstance(v1, Trace.Object): for a1, a2 in zip(v1.attrs.values(), v2.attrs.values()): self.assertEquals(a1, a2) else: self.assertEquals(v1, v2) def testExtraction(self): for traceFile in [testTrace1, testTrace2]: trace = self.loadTrace(traceFile) newTrace = TraceOperations.extract(trace, 10, 20) assert len(newTrace.events) == 10 assert newTrace.events[0].time == 0 assert newTrace.events[0].seq == 0 assert newTrace.events[9].seq == 9 self.assertEqualEventLists(newTrace.events, trace.events[10:20]) newTrace.events[0].name = "foo" assert trace.events[0].name != "foo" def testJoining(self): for traceFile in [testTrace1, testTrace2]: trace = self.loadTrace(traceFile) l = len(trace.events) a = TraceOperations.extract(trace, 0, l / 2) b = TraceOperations.extract(trace, l / 2, l) assert len(a.events) + len(b.events) == l newTrace = TraceOperations.join(a, b) self.assertEqualEventLists(newTrace.events, trace.events) for i, event in enumerate(newTrace.events): self.assertEqual(event.seq, i) if __name__ == "__main__": unittest.main()
{ "content_hash": "5462ebc945f02d5a359577beb40aa48f", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 70, "avg_line_length": 31.56923076923077, "alnum_prop": 0.6106237816764133, "repo_name": "skyostil/tracy", "id": "f8b2039a7125658c588d2ed13b7eac2fadf3ebeb", "size": "3155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/analyzer/TraceOperationsTest.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "952865" }, { "name": "C++", "bytes": "165814" }, { "name": "Prolog", "bytes": "554" }, { "name": "Python", "bytes": "1384305" }, { "name": "Shell", "bytes": "4482" } ], "symlink_target": "" }
from __future__ import print_function from __future__ import division import time import random random.seed(67) import numpy as np np.random.seed(67) import matplotlib matplotlib.use('Agg') import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import matplotlib.cm as cm import os sns.set_style('white') sns.set_context('notebook', font_scale=2) def heatmap(data, fig, ax): features = [f for f in list(data) if 'feature' in f] features = data[features] correlation_matrix = features.corr() #fig = plt.figure() #ax = fig.add_subplot(111) cmap = cm.get_cmap('RdBu_r', 30) cax = ax.imshow(correlation_matrix, interpolation='nearest', cmap=cmap) fig.colorbar(cax, ticks=[.75,.8,.85,.90,.95,1]) plt.title('Feature Correlation') # Import Data df_train = pd.read_csv(os.getenv('PREPARED_TRAINING')) df_valid = pd.read_csv(os.getenv('PREPARED_VALIDATING')) df_test = pd.read_csv(os.getenv('PREPARED_TESTING')) feature_cols = list(df_train.columns[:-1]) target_col = df_train.columns[-1] df_valid[feature_cols] = df_valid[feature_cols].astype(float) df_train[target_col] = df_train[target_col].astype(np.int32) df_valid[target_col] = df_valid[target_col].astype(np.int32) # Visualization df_plot = pd.melt(df_valid, 'target', var_name='feature') fig, ax = plt.subplots(figsize=(24, 24)) heatmap(df_valid, fig, ax) fig.savefig(os.path.join(os.getenv('STORING'), 'figure1.png')) fig, ax = plt.subplots(figsize=(24, 12)) sns.violinplot(data=df_plot, x='feature', y='value', split=True, hue='target', scale='area', palette='Set3', cut=0, lw=1, inner='quart') sns.despine(left=True, bottom=True) ax.set_xticklabels(feature_cols, rotation=90); fig.savefig(os.path.join(os.getenv('STORING'), 'figure2.png')) from sklearn.preprocessing import MinMaxScaler, StandardScaler df_valid_std = df_valid.copy() df_valid_std[feature_cols] = StandardScaler().fit_transform(df_valid_std[feature_cols]) df_plot_std = pd.melt(df_valid_std, 'target', var_name='feature') fig, ax = plt.subplots(figsize=(24, 12)) sns.violinplot(data=df_plot_std, x='feature', y='value', split=True, hue='target', scale='area', palette='Set3', cut=0, lw=1, inner='quart') sns.despine(left=True, bottom=True) ax.set_xticklabels(feature_cols, rotation=90) fig.savefig(os.path.join(os.getenv('STORING'), 'figure3.png')) # df_valid_sample = df_valid.sample(n=100) # df_valid_sample_x = pd.DataFrame(df_valid_sample, columns=feature_cols) # df_valid_sample_y = pd.DataFrame(df_valid_sample, columns=[target_col]) # df_valid_sample_y = [(0, 1, 0) if y == 1 else (0, 0, 1) for y in df_valid_sample_y] # # plt.rcParams['axes.labelsize'] = 10 # pd.plotting.scatter_matrix(df_valid_sample_x, figsize=(23, 23), marker='o', hist_kwds={'bins': 10}, s=2, alpha=.8) p = sns.pairplot(df_valid.sample(n=1000), hue='target', vars=feature_cols, size=2) sns.despine(left=True, bottom=True) plt.savefig(os.path.join(os.getenv('STORING'), 'figure4.png')) from sklearn.decomposition import PCA from sklearn.preprocessing import PolynomialFeatures from sklearn.feature_selection import SelectKBest from sklearn.pipeline import make_union, make_pipeline pipeline = make_pipeline( PolynomialFeatures(degree=2), PCA(n_components=2), ) pipeline.fit(df_train[feature_cols].values, df_train[target_col].values) X_pipeline0 = pipeline.transform(df_valid[df_valid[target_col] == 0][feature_cols].values) X_pipeline1 = pipeline.transform(df_valid[df_valid[target_col] == 1][feature_cols].values) import matplotlib.cm as cm fig, ax = plt.subplots(figsize=(24, 24)) ax.scatter(X_pipeline0[:,0], X_pipeline0[:,1], c=cm.Set3(np.zeros_like(X_pipeline0[:,0])), s=24, lw=0, alpha=0.8, marker='o', label='0') ax.scatter(X_pipeline1[:,0], X_pipeline1[:,1], c=cm.Set3(np.ones_like(X_pipeline0[:,0])), s=24, lw=0, alpha=0.8, marker='o', label='1') ax.legend() fig.savefig(os.path.join(os.getenv('STORING'), 'figure5.png')) tsne_data = np.load(os.path.join(os.getenv('STORING'), 'tsne_2d_5p.npz')) fig, ax = plt.subplots(figsize=(25, 25)) plt.scatter(tsne_data['train'][:,0], tsne_data['train'][:,1], c=df_train['target'], cmap='Set3', alpha=0.8, s=4, lw=0) fig.savefig(os.path.join(os.getenv('STORING'), 'figure6.png')) from sklearn.manifold import Isomap from sklearn.pipeline import make_union, make_pipeline isomap = Isomap() isomap.fit(df_train[feature_cols].values[:10000]) isomap_train = isomap.transform(df_train[feature_cols].values) isomap_valid = isomap.transform(df_valid[feature_cols].values) from sklearn.cluster import DBSCAN dbscan = DBSCAN(eps=0.2, min_samples=30) dbscan_train = dbscan.fit_predict(isomap_train) np.unique(dbscan_train) fig, ax = plt.subplots(figsize=(24, 24)) plt.scatter(isomap_train[:,0], isomap_train[:,1], c=dbscan_train, cmap='Set1', alpha=0.8, s=8, marker='.', lw=0) fig.savefig(os.path.join(os.getenv('STORING'), 'figure7.png'))
{ "content_hash": "eef9ff0f65041d480d19abdca747e6cd", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 140, "avg_line_length": 35.36231884057971, "alnum_prop": 0.7102459016393443, "repo_name": "altermarkive/Resurrecting-JimFleming-Numerai", "id": "b1cd759568cb598e5eab62738cc9fbadc6d75a47", "size": "4928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ml-jimfleming--numerai/notebooks/numerai.py", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "58046" }, { "name": "Matlab", "bytes": "4820" }, { "name": "Python", "bytes": "97293" } ], "symlink_target": "" }
import numpy as np import math from sklearn import datasets, neighbors, linear_model digits = datasets.load_digits() X_digits = digits.data y_digits = digits.target np.random.seed(0) indices = np.random.permutation(len(X_digits)) num_samples = len(digits.data) test_set_size = math.floor(.1 * num_samples) print "number of samples: ", num_samples print "test_set_size: " ,test_set_size digits_X_train = X_digits[indices[:-test_set_size]] digits_y_train = y_digits[indices[:-test_set_size]] digits_X_test = X_digits[indices[-test_set_size:]] digits_y_test = y_digits[indices[-test_set_size:]] knn = neighbors.KNeighborsClassifier() knn.fit(digits_X_train, digits_y_train) print "KNN score: " print knn.score(digits_X_test, digits_y_test) logistic = linear_model.LogisticRegression(C=1e5) logistic.fit(digits_X_train, digits_y_train) print "Logistic Regression score: " print logistic.score(digits_X_test, digits_y_test) # """ # ================================ # Digits Classification Exercise # ================================ # A tutorial exercise regarding the use of classification techniques on # the Digits dataset. # This exercise is used in the :ref:`clf_tut` part of the # :ref:`supervised_learning_tut` section of the # :ref:`stat_learn_tut_index`. # """ # print(__doc__) # from sklearn import datasets, neighbors, linear_model # digits = datasets.load_digits() # X_digits = digits.data # y_digits = digits.target # n_samples = len(X_digits) # X_train = X_digits[:.9 * n_samples] # y_train = y_digits[:.9 * n_samples] # X_test = X_digits[.9 * n_samples:] # y_test = y_digits[.9 * n_samples:] # knn = neighbors.KNeighborsClassifier() # logistic = linear_model.LogisticRegression() # print('KNN score: %f' % knn.fit(X_train, y_train).score(X_test, y_test)) # print('LogisticRegression score: %f' # % logistic.fit(X_train, y_train).score(X_test, y_test))
{ "content_hash": "ec870730d6b2b44189a59f48b514b533", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 74, "avg_line_length": 28.984615384615385, "alnum_prop": 0.685244161358811, "repo_name": "pieteradejong/python", "id": "392303fb6b5905b82fdd0d5bfe9bb6f6e393360a", "size": "1884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scikitlearn-ex1.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "11642" } ], "symlink_target": "" }
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def PropertyFilterUpdate(vim, *args, **kwargs): '''The PropertyFilterUpdate data object type contains a list of updates to data visible through a specific filter. Note that if a property changes through multiple filters, then a client receives an update for each filter.''' obj = vim.client.factory.create('ns0:PropertyFilterUpdate') # do some validation checking... if (len(args) + len(kwargs)) < 1: raise IndexError('Expected at least 2 arguments got: %d' % len(args)) required = [ 'filter' ] optional = [ 'missingSet', 'objectSet', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
{ "content_hash": "c74385e9a5df7a89eec5feaa94b5ad3f", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 124, "avg_line_length": 35.411764705882355, "alnum_prop": 0.6254152823920266, "repo_name": "xuru/pyvisdk", "id": "cce246cc7fb67827ecc2feec30d4a018d2ebca65", "size": "1205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pyvisdk/do/property_filter_update.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "369" }, { "name": "Python", "bytes": "3037849" }, { "name": "Shell", "bytes": "4517" } ], "symlink_target": "" }
# -*- coding: utf-8 -*- # Copyright 2012 Google 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. """Additional help about wildcards.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals from gslib.help_provider import HelpProvider _DETAILED_HELP_TEXT = (""" <B>DESCRIPTION</B> gsutil supports URI wildcards. For example, the command: gsutil cp gs://bucket/data/abc* . copies all objects that start with gs://bucket/data/abc followed by any number of characters within that subdirectory. NOTE: Some command shells expand wildcard matches prior to running the gsutil command; however, most shells do not support recursive wildcards (``**``). You can skip command shell wildcard expansion and instead use gsutil's wildcarding support in such shells by single-quoting (on Linux) or double-quoting (on Windows) the argument. For example: gsutil cp 'data/abc**' gs://bucket <B>DIRECTORY BY DIRECTORY VS RECURSIVE WILDCARDS</B> The ``*`` wildcard only matches up to the end of a path within a subdirectory. For example, if your bucket contains objects named gs://bucket/data/abcd, gs://bucket/data/abcdef, and gs://bucket/data/abcxyx, as well as an object in a sub-directory (gs://bucket/data/abc/def) the above gsutil cp command would match the first 3 object names but not the last one. If you want matches to span directory boundaries, use a ``**`` wildcard: gsutil cp gs://bucket/data/abc** . matches all four objects above. Note that gsutil supports the same wildcards for both object and file names. Thus, for example: gsutil cp data/abc* gs://bucket matches all names in the local file system. <B>BUCKET WILDCARDS</B> You can specify wildcards for bucket names within a single project. For example: gsutil ls gs://data*.example.com lists the contents of all buckets whose name starts with ``data`` and ends with ``.example.com`` in the default project. The -p option can be used to specify a project other than the default. For example: gsutil ls -p other-project gs://data*.example.com You can also combine bucket and object name wildcards. For example, this command removes all ``.txt`` files in any of your Google Cloud Storage buckets in the default project: gsutil rm gs://*/**.txt <B>OTHER WILDCARD CHARACTERS</B> In addition to ``*``, you can use these wildcards: ? Matches a single character. For example "gs://bucket/??.txt" only matches objects with two characters followed by .txt. [chars] Match any of the specified characters. For example ``gs://bucket/[aeiou].txt`` matches objects that contain a single vowel character followed by ``.txt``. [char range] Match any of the range of characters. For example ``gs://bucket/[a-m].txt`` matches objects that contain letters a, b, c, ... or m, and end with ``.txt``. You can combine wildcards to provide more powerful matches, for example: gs://bucket/[a-m]??.j*g <B>POTENTIALLY SURPRISING BEHAVIOR WHEN USING WILDCARDS</B> There are a couple of ways that using wildcards can result in surprising behavior: 1. Shells (like bash and zsh) can attempt to expand wildcards before passing the arguments to gsutil. If the wildcard was supposed to refer to a cloud object, this can result in surprising "Not found" errors (e.g., if the shell tries to expand the wildcard ``gs://my-bucket/*`` on the local machine, matching no local files, and failing the command). Note that some shells include additional characters in their wildcard character sets. For example, if you use zsh with the extendedglob option enabled it treats ``#`` as a special character, which conflicts with that character's use in referencing versioned objects (see `Restore noncurrent object versions <https://cloud.google.com/storage/docs/using-versioned-objects#restore>`_ for an example). To avoid these problems, surround the wildcarded expression with single quotes (on Linux) or double quotes (on Windows). 2. Attempting to specify a filename that contains wildcard characters won't work, because gsutil tries to expand the wildcard characters rather than using them as literal characters. For example, running the command: gsutil cp './file[1]' gs://my-bucket causes gsutil to try to match the ``[1]`` part as a wildcard. There's an open issue to support a "raw" mode for gsutil to provide a way to work with file names that contain wildcard characters, but until / unless that support is implemented there's no really good way to use gsutil with such file names. You could use a wildcard to name such files, for example replacing the above command with: gsutil cp './file*1*' gs://my-bucket but that approach may be difficult to use in general. <B>DIFFERENT BEHAVIOR FOR "DOT" FILES IN LOCAL FILE SYSTEM</B> Per standard Unix behavior, the wildcard ``*`` only matches files that don't start with a ``.`` character (to avoid confusion with the ``.`` and ``..`` directories present in all Unix directories). gsutil provides this same behavior when using wildcards over a file system URI, but does not provide this behavior over cloud URIs. For example, the following command copies all objects from gs://bucket1 to gs://bucket2: gsutil cp gs://bucket1/* gs://bucket2 but the following command copies only files that don't start with a ``.`` from the directory ``dir`` to gs://bucket1: gsutil cp dir/* gs://bucket1 <B>EFFICIENCY CONSIDERATION: USING WILDCARDS OVER MANY OBJECTS</B> It is more efficient, faster, and less network traffic-intensive to use wildcards that have a non-wildcard object-name prefix, like: gs://bucket/abc*.txt than it is to use wildcards as the first part of the object name, like: gs://bucket/*abc.txt This is because the request for ``gs://bucket/abc*.txt`` asks the server to send back the subset of results whose object name start with ``abc`` at the bucket root, and then gsutil filters the result list for objects whose name ends with ``.txt``. In contrast, ``gs://bucket/*abc.txt`` asks the server for the complete list of objects in the bucket root, and then filters for those objects whose name ends with ``abc.txt``. This efficiency consideration becomes increasingly noticeable when you use buckets containing thousands or more objects. It is sometimes possible to set up the names of your objects to fit with expected wildcard matching patterns, to take advantage of the efficiency of doing server-side prefix requests. See, for example "gsutil help prod" for a concrete use case example. <B>EFFICIENCY CONSIDERATION: USING MID-PATH WILDCARDS</B> Suppose you have a bucket with these objects: gs://bucket/obj1 gs://bucket/obj2 gs://bucket/obj3 gs://bucket/obj4 gs://bucket/dir1/obj5 gs://bucket/dir2/obj6 If you run the command: gsutil ls gs://bucket/*/obj5 gsutil performs a /-delimited top-level bucket listing and then one bucket listing for each subdirectory, for a total of 3 bucket listings: GET /bucket/?delimiter=/ GET /bucket/?prefix=dir1/obj5&delimiter=/ GET /bucket/?prefix=dir2/obj5&delimiter=/ The more bucket listings your wildcard requires, the slower and more expensive it becomes. The number of bucket listings required grows as: - the number of wildcard components (e.g., "gs://bucket/a??b/c*/*/d" has 3 wildcard components); - the number of subdirectories that match each component; and - the number of results (pagination is implemented using one GET request per 1000 results, specifying markers for each). If you want to use a mid-path wildcard, you might try instead using a recursive wildcard, for example: gsutil ls gs://bucket/**/obj5 This matches more objects than ``gs://bucket/*/obj5`` (since it spans directories), but is implemented using a delimiter-less bucket listing request (which means fewer bucket requests, though it lists the entire bucket and filters locally, so that could require a non-trivial amount of network traffic). """) class CommandOptions(HelpProvider): """Additional help about wildcards.""" # Help specification. See help_provider.py for documentation. help_spec = HelpProvider.HelpSpec( help_name='wildcards', help_name_aliases=['wildcard', '*', '**'], help_type='additional_help', help_one_line_summary='Wildcard Names', help_text=_DETAILED_HELP_TEXT, subcommand_help_text={}, )
{ "content_hash": "9888c65ecf7418f17d9cb8e8553d6522", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 80, "avg_line_length": 38.9957805907173, "alnum_prop": 0.7231118805453365, "repo_name": "catapult-project/catapult", "id": "b92bf8021de029b922170b6a7d31185f0b9c7e2b", "size": "9242", "binary": false, "copies": "9", "ref": "refs/heads/main", "path": "third_party/gsutil/gslib/addlhelp/wildcards.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1324" }, { "name": "C++", "bytes": "46069" }, { "name": "CSS", "bytes": "23376" }, { "name": "Dockerfile", "bytes": "1541" }, { "name": "Go", "bytes": "114396" }, { "name": "HTML", "bytes": "12394298" }, { "name": "JavaScript", "bytes": "1559584" }, { "name": "Makefile", "bytes": "1774" }, { "name": "Python", "bytes": "6778695" }, { "name": "Shell", "bytes": "2288" } ], "symlink_target": "" }
''' Copyright (c) 2012-2017, Agora Games, LLC All rights reserved. https://github.com/agoragames/kairos/blob/master/LICENSE.txt ''' from .exceptions import * from datetime import datetime, timedelta import operator import sys import time import re import warnings import functools if sys.version_info[:2] > (2, 6): from collections import OrderedDict else: from ordereddict import OrderedDict from monthdelta import MonthDelta BACKENDS = {} NUMBER_TIME = re.compile('^[\d]+$') SIMPLE_TIME = re.compile('^([\d]+)([hdwmy])$') SIMPLE_TIMES = { 'h' : 60*60, # hour 'd' : 60*60*24, # day 'w' : 60*60*24*7, # week 'm' : 60*60*24*30, # month(-ish) 'y' : 60*60*24*365, # year(-ish) } GREGORIAN_TIMES = set(['daily', 'weekly', 'monthly', 'yearly']) # Test python3 compatibility try: x = long(1) except NameError: long = int def _resolve_time(value): ''' Resolve the time in seconds of a configuration value. ''' if value is None or isinstance(value,(int,long)): return value if NUMBER_TIME.match(value): return long(value) simple = SIMPLE_TIME.match(value) if SIMPLE_TIME.match(value): multiplier = long( simple.groups()[0] ) constant = SIMPLE_TIMES[ simple.groups()[1] ] return multiplier * constant if value in GREGORIAN_TIMES: return value raise ValueError('Unsupported time format %s'%value) class RelativeTime(object): ''' Functions associated with relative time intervals. ''' def __init__(self, step=1): self._step = step def step_size(self, t0=None, t1=None): ''' Return the time in seconds of a step. If a begin and end timestamp, return the time in seconds between them after adjusting for what buckets they alias to. If t1 and t0 resolve to the same bucket, ''' if t0!=None and t1!=None: tb0 = self.to_bucket( t0 ) tb1 = self.to_bucket( t1, steps=1 ) # NOTE: "end" of second bucket if tb0==tb1: return self._step return self.from_bucket( tb1 ) - self.from_bucket( tb0 ) return self._step def to_bucket(self, timestamp, steps=0): ''' Calculate the bucket from a timestamp, optionally including a step offset. ''' return int( timestamp / self._step ) + steps def from_bucket(self, bucket): ''' Calculate the timestamp given a bucket. ''' return bucket * self._step def buckets(self, start, end): ''' Calculate the buckets within a starting and ending timestamp. ''' start_bucket = self.to_bucket(start) end_bucket = self.to_bucket(end) return range(start_bucket, end_bucket+1) def normalize(self, timestamp, steps=0): ''' Normalize a timestamp according to the interval configuration. Can optionally determine an offset. ''' return self.from_bucket( self.to_bucket(timestamp, steps) ) def ttl(self, steps, relative_time=None): ''' Return the ttl given the number of steps, None if steps is not defined or we're otherwise unable to calculate one. If relative_time is defined, then return a ttl that is the number of seconds from now that the record should be expired. ''' if steps: if relative_time: rtime = self.to_bucket(relative_time) ntime = self.to_bucket(time.time()) # The relative time is beyond our TTL cutoff if (ntime - rtime) > steps: return 0 # The relative time is in "recent" past or future else: return (steps + rtime - ntime) * self._step return steps * self._step return None class GregorianTime(object): ''' Functions associated with gregorian time intervals. ''' # NOTE: strptime weekly has the following bug: # In [10]: datetime.strptime('197001', '%Y%U') # Out[10]: datetime.datetime(1970, 1, 1, 0, 0) # In [11]: datetime.strptime('197002', '%Y%U') # Out[11]: datetime.datetime(1970, 1, 1, 0, 0) FORMATS = { 'daily' : '%Y%m%d', 'weekly' : '%Y%U', 'monthly' : '%Y%m', 'yearly' : '%Y' } def __init__(self, step='daily'): self._step = step def step_size(self, t0, t1=None): ''' Return the time in seconds for each step. Requires that we know a time relative to which we should calculate to account for variable length intervals (e.g. February) ''' tb0 = self.to_bucket( t0 ) if t1: tb1 = self.to_bucket( t1, steps=1 ) # NOTE: "end" of second bucket else: tb1 = self.to_bucket( t0, steps=1 ) # Calculate the difference in days, then multiply by simple scalar days = (self.from_bucket(tb1, native=True) - self.from_bucket(tb0, native=True)).days return days * SIMPLE_TIMES['d'] def to_bucket(self, timestamp, steps=0): ''' Calculate the bucket from a timestamp. ''' dt = datetime.utcfromtimestamp( timestamp ) if steps!=0: if self._step == 'daily': dt = dt + timedelta(days=steps) elif self._step == 'weekly': dt = dt + timedelta(weeks=steps) elif self._step == 'monthly': dt = dt + MonthDelta(steps) elif self._step == 'yearly': year = int(dt.strftime( self.FORMATS[self._step] )) year += steps dt = datetime(year=year, month=1, day=1) return int(dt.strftime( self.FORMATS[self._step] )) def from_bucket(self, bucket, native=False): ''' Calculate the timestamp given a bucket. ''' # NOTE: this is due to a bug somewhere in strptime that does not process # the week number of '%Y%U' correctly. That bug could be very specific to # the combination of python and ubuntu that I was testing. bucket = str(bucket) if self._step == 'weekly': year, week = bucket[:4], bucket[4:] normal = datetime(year=int(year), month=1, day=1) + timedelta(weeks=int(week)) else: normal = datetime.strptime(bucket, self.FORMATS[self._step]) if native: return normal return long(time.mktime( normal.timetuple() )) def buckets(self, start, end): ''' Calculate the buckets within a starting and ending timestamp. ''' rval = [ self.to_bucket(start) ] step = 1 # In theory there's already been a check that end>start # TODO: Not a fan of an unbound while loop here while True: bucket = self.to_bucket(start, step) bucket_time = self.from_bucket( bucket ) if bucket_time >= end: if bucket_time==end: rval.append( bucket ) break rval.append( bucket ) step += 1 return rval def normalize(self, timestamp, steps=0): ''' Normalize a timestamp according to the interval configuration. Optionally can be used to calculate the timestamp N steps away. ''' # So far, the only commonality with RelativeTime return self.from_bucket( self.to_bucket(timestamp, steps) ) def ttl(self, steps, relative_time=None): ''' Return the ttl given the number of steps, None if steps is not defined or we're otherwise unable to calculate one. If relative_time is defined, then return a ttl that is the number of seconds from now that the record should be expired. ''' if steps: # Approximate the ttl based on number of seconds, since it's # "close enough" if relative_time: rtime = self.to_bucket(relative_time) ntime = self.to_bucket(time.time()) # Convert to number of days day_diff = (self.from_bucket(ntime, native=True) - self.from_bucket(rtime, native=True)).days # Convert steps to number of days as well step_diff = (steps*SIMPLE_TIMES[self._step[0]]) / SIMPLE_TIMES['d'] # The relative time is beyond our TTL cutoff if day_diff > step_diff: return 0 # The relative time is in "recent" past or future else: return (step_diff - day_diff) * SIMPLE_TIMES['d'] return steps * SIMPLE_TIMES[ self._step[0] ] return None class TimeseriesMeta(type): ''' Meta class for URL parsing ''' def __call__(cls, client, **kwargs): if isinstance(client, (str,unicode)): for backend in BACKENDS.values(): handle = backend.url_parse(client, **kwargs.pop('client_config',{})) if handle: client = handle break if isinstance(client, (str,unicode)): raise ImportError("Unsupported or unknown client type for %s", client) return type.__call__(cls, client, **kwargs) class Timeseries(object): ''' Base class of all time series. Also acts as a factory to return the correct subclass if "type=" keyword argument supplied. ''' __metaclass__ = TimeseriesMeta def __new__(cls, client, **kwargs): if cls==Timeseries: # load a backend based on the name of the client module client_module = client.__module__.split('.')[0] backend = BACKENDS.get( client_module ) if backend: return backend( client, **kwargs ) raise ImportError("Unsupported or unknown client type %s", client_module) return object.__new__(cls, client, **kwargs) def __init__(self, client, **kwargs): ''' Create a time series using a given redis client and keyword arguments defining the series configuration. Optionally provide a prefix for all keys. If prefix length>0 and it doesn't end with ":", it will be automatically appended. Redis only. The redis client must be API compatible with the Redis instance from the redis package http://pypi.python.org/pypi/redis The supported keyword arguments are: type One of (series, histogram, count). Optional, defaults to "series". series - each interval will append values to a list histogram - each interval will track count of unique values count - each interval will maintain a single counter prefix Optional, is a prefix for all keys in this histogram. If supplied and it doesn't end with ":", it will be automatically appended. Redis only. read_func Optional, is a function applied to all values read back from the database. Without it, values will be strings. Must accept a string value and can return anything. write_func Optional, is a function applied to all values when writing. Can be used for histogram resolution, converting an object into an id, etc. Must accept whatever can be inserted into a timeseries and return an object which can be cast to a string. intervals Required, a dictionary of interval configurations in the form of: { # interval name, used in redis keys and should conform to best practices # and not include ":" minute: { # Required. The number of seconds that the interval will cover step: 60, # Optional. The maximum number of intervals to maintain. If supplied, # will use redis expiration to delete old intervals, else intervals # exist in perpetuity. steps: 240, # Optional. Defines the resolution of the data, i.e. the number of # seconds in which data is assumed to have occurred "at the same time". # So if you're tracking a month long time series, you may only need # resolution down to the day, or resolution=86400. Defaults to same # value as "step". resolution: 60, } } ''' # Process the configuration first so that the backends can use that to # complete their setup. # Prefix is determined by the backend implementation. self._client = client self._read_func = kwargs.get('read_func',None) self._write_func = kwargs.get('write_func',None) self._intervals = kwargs.get('intervals', {}) # Preprocess the intervals for interval,config in self._intervals.items(): # Copy the interval name into the configuration, needed for redis config['interval'] = interval step = config['step'] = _resolve_time( config['step'] ) # Required steps = config.get('steps',None) # Optional resolution = config['resolution'] = _resolve_time( config.get('resolution',config['step']) ) # Optional if step in GREGORIAN_TIMES: interval_calc = GregorianTime(step) else: interval_calc = RelativeTime(step) if resolution in GREGORIAN_TIMES: resolution_calc = GregorianTime(resolution) else: resolution_calc = RelativeTime(resolution) config['i_calc'] = interval_calc config['r_calc'] = resolution_calc config['expire'] = interval_calc.ttl( steps ) config['ttl'] = functools.partial( interval_calc.ttl, steps ) config['coarse'] = (resolution==step) def list(self): ''' List all of the stat names that are stored. ''' raise NotImplementedError() def properties(self, name): ''' Get the properties of a stat. ''' raise NotImplementedError() def expire(self, name): ''' Manually expire data for storage engines that do not support auto expiry. ''' raise NotImplementedError() def bulk_insert(self, inserts, intervals=0, **kwargs): ''' Perform a bulk insert. The format of the inserts must be: { timestamp : { name: [ values ], ... }, ... } If the timestamp should be auto-generated, then "timestamp" should be None. Backends can implement this in any number of ways, the default being to perform a single insert for each value, with no specialized locking, transactions or batching. ''' if None in inserts: inserts[ time.time() ] = inserts.pop(None) if self._write_func: for timestamp,names in inserts.iteritems(): for name,values in names.iteritems(): names[name] = [ self._write_func(v) for v in values ] self._batch_insert(inserts, intervals, **kwargs) def insert(self, name, value, timestamp=None, intervals=0, **kwargs): ''' Insert a value for the timeseries "name". For each interval in the configuration, will insert the value into a bucket for the interval "timestamp". If time is not supplied, will default to time.time(), else it should be a floating point value. If "intervals" is less than 0, inserts the value into timestamps "abs(intervals)" preceeding "timestamp" (i.e. "-1" inserts one extra value). If "intervals" is greater than 0, inserts the value into that many more intervals after "timestamp". The default behavior is to insert for a single timestamp. This supports the public methods of the same name in the subclasses. The value is expected to already be converted. ''' if not timestamp: timestamp = time.time() if isinstance(value, (list,tuple,set)): if self._write_func: value = [ self._write_func(v) for v in value ] return self._batch_insert({timestamp:{name:value}}, intervals, **kwargs) if self._write_func: value = self._write_func(value) # TODO: document acceptable names # TODO: document what types values are supported # TODO: document behavior when time is outside the bounds of TTLed config # TODO: document how the data is stored. # TODO: better abstraction for "intervals" processing rather than in each implementation self._insert( name, value, timestamp, intervals, **kwargs ) def _batch_insert(self, inserts, intervals, **kwargs): ''' Support for batch insert. Default implementation is non-optimized and is a simple loop over values. ''' for timestamp,names in inserts.iteritems(): for name,values in names.iteritems(): for value in values: self._insert( name, value, timestamp, intervals, **kwargs ) def _normalize_timestamps(self, timestamp, intervals, config): ''' Helper for the subclasses to generate a list of timestamps. ''' rval = [timestamp] if intervals<0: while intervals<0: rval.append( config['i_calc'].normalize(timestamp, intervals) ) intervals += 1 elif intervals>0: while intervals>0: rval.append( config['i_calc'].normalize(timestamp, intervals) ) intervals -= 1 return rval def _insert(self, name, value, timestamp, intervals, **kwargs): ''' Support for the insert per type of series. ''' raise NotImplementedError() def delete(self, name): ''' Delete all data in a timeseries. Subclasses are responsible for implementing this. ''' raise NotImplementedError() def delete_all(self): ''' Deletes all data in every timeseries. Default implementation is to walk all of the names and call delete(stat), storage implementations are welcome to optimize this. ''' for name in self.list(): self.delete(name) def iterate(self, name, interval, **kwargs): ''' Returns a generator that iterates over all the intervals and returns data for various timestamps, in the form: ( unix_timestamp, data ) This will check for all timestamp buckets that might exist between the first and last timestamp in a series. Each timestamp bucket will be fetched separately to keep this memory efficient, at the cost of extra trips to the data store. Keyword arguments are the same as get(). ''' config = self._intervals.get(interval) if not config: raise UnknownInterval(interval) properties = self.properties(name)[interval] i_buckets = config['i_calc'].buckets(properties['first'], properties['last']) for i_bucket in i_buckets: data = self.get(name, interval, timestamp=config['i_calc'].from_bucket(i_bucket), **kwargs) for timestamp,row in data.items(): yield (timestamp,row) def get(self, name, interval, **kwargs): ''' Get the set of values for a named timeseries and interval. If timestamp supplied, will fetch data for the period of time in which that timestamp would have fallen, else returns data for "now". If the timeseries resolution was not defined, then returns a simple list of values for the interval, else returns an ordered dict where the keys define the resolution interval and the values are the time series data in that (sub)interval. This allows the user to interpolate sparse data sets. If transform is defined, will utilize one of `[mean, count, min, max, sum]` to process each row of data returned. If the transform is a callable, will pass an array of data to the function. Note that the transform will be run after the data is condensed. If the transform is a list, then each row will return a hash of the form { transform_name_or_func : transformed_data }. If the transform is a hash, then it should be of the form { transform_name : transform_func } and will return the same structure as a list argument. Raises UnknownInterval if `interval` is not one of the configured intervals. TODO: Fix this method doc ''' config = self._intervals.get(interval) if not config: raise UnknownInterval(interval) timestamp = kwargs.get('timestamp', time.time()) fetch = kwargs.get('fetch') process_row = kwargs.get('process_row') or self._process_row condense = kwargs.get('condense', False) join_rows = kwargs.get('join_rows') or self._join transform = kwargs.get('transform') # DEPRECATED handle the deprecated version of condense condense = kwargs.get('condensed',condense) # If name is a list, then join all of results. It is more efficient to # use a single data structure and join "in-line" but that requires a major # refactor of the backends, so trying this solution to start with. At a # minimum we'd have to rebuild the results anyway because of the potential # for sparse data points would result in an out-of-order result. if isinstance(name, (list,tuple,set)): results = [ self._get(x, interval, config, timestamp, fetch=fetch, process_row=process_row) for x in name ] # Even resolution data is "coarse" in that it's not nested rval = self._join_results( results, True, join_rows ) else: rval = self._get( name, interval, config, timestamp, fetch=fetch, process_row=process_row ) # If condensed, collapse the result into a single row. Adjust the step_size # calculation to match. if config['coarse']: step_size = config['i_calc'].step_size(timestamp) else: step_size = config['r_calc'].step_size(timestamp) if condense and not config['coarse']: condense = condense if callable(condense) else self._condense rval = { config['i_calc'].normalize(timestamp) : condense(rval) } step_size = config['i_calc'].step_size(timestamp) if transform: for k,v in rval.items(): rval[k] = self._process_transform(v, transform, step_size) return rval def _get(self, name, interval, config, timestamp, fetch): ''' Support for the insert per type of series. ''' raise NotImplementedError() def series(self, name, interval, **kwargs): ''' Return all the data in a named time series for a given interval. If steps not defined and there are none in the config, defaults to 1. Returns an ordered dict of interval timestamps to a single interval, which matches the return value in get(). If transform is defined, will utilize one of `[mean, count, min, max, sum]` to process each row of data returned. If the transform is a callable, will pass an array of data to the function. Note that the transform will be run after the data is condensed. Raises UnknownInterval if `interval` not configured. ''' config = self._intervals.get(interval) if not config: raise UnknownInterval(interval) start = kwargs.get('start') end = kwargs.get('end') steps = kwargs.get('steps') or config.get('steps',1) fetch = kwargs.get('fetch') process_row = kwargs.get('process_row') or self._process_row condense = kwargs.get('condense', False) join_rows = kwargs.get('join_rows') or self._join collapse = kwargs.get('collapse', False) transform = kwargs.get('transform') # DEPRECATED handle the deprecated version of condense condense = kwargs.get('condensed',condense) # If collapse, also condense if collapse: condense = condense or True # Fugly range determination, all to get ourselves a start and end # timestamp. Adjust steps argument to include the anchoring date. if end is None: if start is None: end = time.time() end_bucket = config['i_calc'].to_bucket( end ) start_bucket = config['i_calc'].to_bucket( end, (-steps+1) ) else: start_bucket = config['i_calc'].to_bucket( start ) end_bucket = config['i_calc'].to_bucket( start, steps-1 ) else: end_bucket = config['i_calc'].to_bucket( end ) if start is None: start_bucket = config['i_calc'].to_bucket( end, (-steps+1) ) else: start_bucket = config['i_calc'].to_bucket( start ) # Now that we have start and end buckets, convert them back to normalized # time stamps and then back to buckets. :) start = config['i_calc'].from_bucket( start_bucket ) end = config['i_calc'].from_bucket( end_bucket ) if start > end: end = start interval_buckets = config['i_calc'].buckets(start, end) # If name is a list, then join all of results. It is more efficient to # use a single data structure and join "in-line" but that requires a major # refactor of the backends, so trying this solution to start with. At a # minimum we'd have to rebuild the results anyway because of the potential # for sparse data points would result in an out-of-order result. if isinstance(name, (list,tuple,set)): results = [ self._series(x, interval, config, interval_buckets, fetch=fetch, process_row=process_row) for x in name ] rval = self._join_results( results, config['coarse'], join_rows ) else: rval = self._series(name, interval, config, interval_buckets, fetch=fetch, process_row=process_row) # If fine-grained, first do the condensed pass so that it's easier to do # the collapse afterwards. Be careful not to run the transform if there's # going to be another pass at condensing the data. if not config['coarse']: if condense: condense = condense if callable(condense) else self._condense for key in rval.iterkeys(): data = condense( rval[key] ) if transform and not collapse: data = self._process_transform(data, transform, config['i_calc'].step_size(key)) rval[key] = data elif transform: for interval,resolutions in rval.items(): for key in resolutions.iterkeys(): resolutions[key] = self._process_transform(resolutions[key], transform, config['r_calc'].step_size(key)) if config['coarse'] or collapse: if collapse: collapse = collapse if callable(collapse) else condense if callable(condense) else self._condense data = collapse(rval) if transform: rval = { rval.keys()[0] : self._process_transform(data, transform, config['i_calc'].step_size(rval.keys()[0], rval.keys()[-1])) } else: rval = { rval.keys()[0] : data } elif transform: for key,data in rval.items(): rval[key] = self._process_transform(data, transform, config['i_calc'].step_size(key)) return rval def _series(self, name, interval, config, buckets, **kws): ''' Subclasses must implement fetching a series. ''' raise NotImplementedError() def _join_results(self, results, coarse, join): ''' Join a list of results. Supports both get and series. ''' rval = OrderedDict() i_keys = set() for res in results: i_keys.update( res.keys() ) for i_key in sorted(i_keys): if coarse: rval[i_key] = join( [res.get(i_key) for res in results] ) else: rval[i_key] = OrderedDict() r_keys = set() for res in results: r_keys.update( res.get(i_key,{}).keys() ) for r_key in sorted(r_keys): rval[i_key][r_key] = join( [res.get(i_key,{}).get(r_key) for res in results] ) return rval def _process_transform(self, data, transform, step_size): ''' Process transforms on the data. ''' if isinstance(transform, (list,tuple,set)): return { t : self._transform(data,t,step_size) for t in transform } elif isinstance(transform, dict): return { tn : self._transform(data,tf,step_size) for tn,tf in transform.items() } return self._transform(data,transform,step_size) def _transform(self, data, transform, step_size): ''' Transform the data. If the transform is not supported by this series, returns the data unaltered. ''' raise NotImplementedError() def _insert(self, handle, key, value): ''' Subclasses must implement inserting a value for a key. ''' raise NotImplementedError() def _process_row(self, data): ''' Subclasses should apply any read function to the data. Will only be called if there is one. ''' raise NotImplementedError() def _condense(self, data): ''' Condense a mapping of timestamps and associated data into a single object/value which will be mapped back to a timestamp that covers all of the data. ''' raise NotImplementedError() def _join(self, rows): ''' Join multiple rows worth of data into a single result. ''' raise NotImplementedError() class Series(Timeseries): ''' Simple time series where all data is stored in a list for each interval. ''' def _type_no_value(self): return [] def _transform(self, data, transform, step_size): ''' Transform the data. If the transform is not supported by this series, returns the data unaltered. ''' if transform=='mean': total = sum( data ) count = len( data ) data = float(total)/float(count) if count>0 else 0 elif transform=='count': data = len( data ) elif transform=='min': data = min( data or [0]) elif transform=='max': data = max( data or [0]) elif transform=='sum': data = sum( data ) elif transform=='rate': data = len( data ) / float(step_size) elif callable(transform): data = transform(data, step_size) return data def _process_row(self, data): if self._read_func: return map(self._read_func, data) return data def _condense(self, data): ''' Condense by adding together all of the lists. ''' if data: return reduce(operator.add, data.values()) return [] def _join(self, rows): ''' Join multiple rows worth of data into a single result. ''' rval = [] for row in rows: if row: rval.extend( row ) return rval class Histogram(Timeseries): ''' Data for each interval is stored in a hash, counting occurrances of the same value within an interval. It is up to the user to determine the precision and distribution of the data points within the histogram. ''' def _type_no_value(self): return {} def _transform(self, data, transform, step_size): ''' Transform the data. If the transform is not supported by this series, returns the data unaltered. ''' if transform=='mean': total = sum( k*v for k,v in data.items() ) count = sum( data.values() ) data = float(total)/float(count) if count>0 else 0 elif transform=='count': data = sum(data.values()) elif transform=='min': data = min(data.keys() or [0]) elif transform=='max': data = max(data.keys() or [0]) elif transform=='sum': data = sum( k*v for k,v in data.items() ) elif transform=='rate': data = { k:v/float(step_size) for k,v in data.items() } elif callable(transform): data = transform(data, step_size) return data def _process_row(self, data): rval = {} for value,count in data.items(): if self._read_func: value = self._read_func(value) rval[ value ] = int(count) return rval def _condense(self, data): ''' Condense by adding together all of the lists. ''' rval = {} for resolution,histogram in data.items(): for value,count in histogram.items(): rval[ value ] = count + rval.get(value,0) return rval def _join(self, rows): ''' Join multiple rows worth of data into a single result. ''' rval = {} for row in rows: if row: for value,count in row.items(): rval[ value ] = count + rval.get(value,0) return rval class Count(Timeseries): ''' Time series that simply increments within each interval. ''' def _type_no_value(self): return 0 def _transform(self, data, transform, step_size): ''' Transform the data. If the transform is not supported by this series, returns the data unaltered. ''' if transform=='rate': data = data / float(step_size) elif callable(transform): data = transform(data, step_size) return data def insert(self, name, value=1, timestamp=None, **kwargs): super(Count,self).insert(name, value, timestamp, **kwargs) def _process_row(self, data): return int(data) if data else 0 def _condense(self, data): ''' Condense by adding together all of the lists. ''' if data: return sum(data.values()) return 0 def _join(self, rows): ''' Join multiple rows worth of data into a single result. ''' rval = 0 for row in rows: if row: rval += row return rval class Gauge(Timeseries): ''' Time series that stores the last value. ''' def _type_no_value(self): # TODO: resolve this disconnect with redis backend return 0 def _transform(self, data, transform, step_size): ''' Transform the data. If the transform is not supported by this series, returns the data unaltered. ''' if callable(transform): data = transform(data, step_size) return data def _process_row(self, data): if self._read_func: return self._read_func(data or '') return data def _condense(self, data): ''' Condense by returning the last real value of the gauge. ''' if data: data = filter(None,data.values()) if data: return data[-1] return None def _join(self, rows): ''' Join multiple rows worth of data into a single result. ''' rval = None for row in rows: if row: rval = row return rval class Set(Timeseries): ''' Time series that manages sets. ''' def _type_no_value(self): return set() def _transform(self, data, transform, step_size): ''' Transform the data. If the transform is not supported by this series, returns the data unaltered. ''' if transform=='mean': total = sum( data ) count = len( data ) data = float(total)/float(count) if count>0 else 0 elif transform=='count': data = len(data) elif transform=='min': data = min(data or [0]) elif transform=='max': data = max(data or [0]) elif transform=='sum': data = sum(data) elif transform=='rate': data = len(data) / float(step_size) elif callable(transform): data = transform(data) return data def _process_row(self, data): if self._read_func: return set( (self._read_func(d) for d in data) ) return data def _condense(self, data): ''' Condense by or-ing all of the sets. ''' if data: return reduce(operator.ior, data.values()) return set() def _join(self, rows): ''' Join multiple rows worth of data into a single result. ''' rval = set() for row in rows: if row: rval |= row return rval # Load the backends after all the timeseries had been defined. try: from .redis_backend import RedisBackend BACKENDS['redis'] = RedisBackend except ImportError as e: warnings.warn('Redis backend not loaded, {}'.format(e)) try: from .mongo_backend import MongoBackend BACKENDS['pymongo'] = MongoBackend except ImportError as e: warnings.warn('Mongo backend not loaded, {}'.format(e)) try: from .sql_backend import SqlBackend BACKENDS['sqlalchemy'] = SqlBackend except ImportError as e: warnings.warn('SQL backend not loaded, {}'.format(e)) try: from .cassandra_backend import CassandraBackend BACKENDS['cql'] = CassandraBackend except ImportError as e: warnings.warn('Cassandra backend not loaded, {}'.format(e))
{ "content_hash": "20c4bd28ef84ebc89f1807d5e2adb859", "timestamp": "", "source": "github", "line_count": 1066, "max_line_length": 139, "avg_line_length": 32.54502814258912, "alnum_prop": 0.6455480932753005, "repo_name": "agoragames/kairos", "id": "4667cc7bbd33b40c382d10b6b0d2038b36a82104", "size": "34693", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "kairos/timeseries.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "195040" } ], "symlink_target": "" }
from __future__ import absolute_import, print_function from sentry import analytics class OrganizationCreatedEvent(analytics.Event): type = "organization.created" attributes = ( analytics.Attribute("id"), analytics.Attribute("name"), analytics.Attribute("slug"), analytics.Attribute("actor_id", required=False), ) analytics.register(OrganizationCreatedEvent)
{ "content_hash": "d2643b25b9501158da5c940ac3338515", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 56, "avg_line_length": 24.058823529411764, "alnum_prop": 0.7017114914425427, "repo_name": "mvaled/sentry", "id": "173b48f6ba29795800326e1c5892fe2d1a36abf3", "size": "409", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/sentry/analytics/events/organization_created.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "226439" }, { "name": "Dockerfile", "bytes": "6431" }, { "name": "HTML", "bytes": "173429" }, { "name": "JavaScript", "bytes": "9314175" }, { "name": "Lua", "bytes": "65885" }, { "name": "Makefile", "bytes": "9225" }, { "name": "Python", "bytes": "50385401" }, { "name": "Ruby", "bytes": "168" }, { "name": "Shell", "bytes": "5685" }, { "name": "TypeScript", "bytes": "773664" } ], "symlink_target": "" }
import copy from dsl_parser import (exceptions, utils, constants) from dsl_parser.interfaces import interfaces_parser from dsl_parser.elements import (node_types as _node_types, plugins as _plugins, relationships as _relationships, operation as _operation, data_types as _data_types, scalable, version as _version) from dsl_parser.framework.requirements import Value, Requirement from dsl_parser.framework.elements import (DictElement, Element, Leaf, Dict, List) class NodeTemplateType(Element): required = True schema = Leaf(type=str) requires = { _node_types.NodeTypes: [Value('node_types')] } def validate(self, node_types): if self.initial_value not in node_types: err_message = ("Could not locate node type: '{0}'; " "existing types: {1}" .format(self.initial_value, node_types.keys())) raise exceptions.DSLParsingLogicException(7, err_message) class NodeTemplateProperties(Element): schema = Leaf(type=dict) requires = { NodeTemplateType: [], _node_types.NodeTypes: [Value('node_types')], _data_types.DataTypes: [Value('data_types')] } def parse(self, node_types, data_types): properties = self.initial_value or {} node_type_name = self.sibling(NodeTemplateType).value node_type = node_types[node_type_name] return utils.merge_schema_and_instance_properties( instance_properties=properties, schema_properties=node_type['properties'], data_types=data_types, undefined_property_error_message=( "'{0}' node '{1}' property is not part of the derived" " type properties schema"), missing_property_error_message=( "'{0}' node does not provide a " "value for mandatory " "'{1}' property which is " "part of its type schema"), node_name=self.ancestor(NodeTemplate).name) class NodeTemplateRelationshipType(Element): required = True schema = Leaf(type=str) requires = { _relationships.Relationships: [Value('relationships')] } def validate(self, relationships): if self.initial_value not in relationships: raise exceptions.DSLParsingLogicException( 26, "A relationship instance under node '{0}' declares an " "undefined relationship type '{1}'" .format(self.ancestor(NodeTemplate).name, self.initial_value)) class NodeTemplateRelationshipTarget(Element): required = True schema = Leaf(type=str) def validate(self): relationship_type = self.sibling(NodeTemplateRelationshipType).name node_name = self.ancestor(NodeTemplate).name node_template_names = self.ancestor(NodeTemplates).initial_value.keys() if self.initial_value not in node_template_names: raise exceptions.DSLParsingLogicException( 25, "A relationship instance under node '{0}' of type '{1}' " "declares an undefined target node '{2}'" .format(node_name, relationship_type, self.initial_value)) if self.initial_value == node_name: raise exceptions.DSLParsingLogicException( 23, "A relationship instance under node '{0}' of type '{1}' " "illegally declares the source node as the target node" .format(node_name, relationship_type)) class NodeTemplateRelationshipProperties(Element): schema = Leaf(type=dict) requires = { NodeTemplateRelationshipType: [], _relationships.Relationships: [Value('relationships')], _data_types.DataTypes: [Value('data_types')] } def parse(self, relationships, data_types): relationship_type_name = self.sibling( NodeTemplateRelationshipType).value properties = self.initial_value or {} return utils.merge_schema_and_instance_properties( instance_properties=properties, schema_properties=relationships[relationship_type_name][ 'properties'], data_types=data_types, undefined_property_error_message=( "'{0}' node relationship '{1}' property is not part of " "the derived relationship type properties schema"), missing_property_error_message=( "'{0}' node relationship does not provide a " "value for mandatory " "'{1}' property which is " 'part of its relationship type schema'), node_name=self.ancestor(NodeTemplate).name) class NodeTemplateInstancesDeploy(Element): required = True schema = Leaf(type=int) def validate(self): if self.initial_value < 0: raise exceptions.DSLParsingFormatException( 1, 'deploy instances must be a non-negative number') class NodeTemplateInstances(DictElement): schema = { 'deploy': NodeTemplateInstancesDeploy } # TODO: Capabilities should be implemented according to TOSCA as generic types class NodeTemplateCapabilitiesScalable(DictElement): schema = { 'properties': scalable.Properties } def parse(self): if self.initial_value is None: return {'properties': scalable.Properties.DEFAULT.copy()} else: return { 'properties': self.child(scalable.Properties).value } def _instances_predicate(source, target): return source.ancestor(NodeTemplate) is target.ancestor(NodeTemplate) class NodeTemplateCapabilities(DictElement): schema = { 'scalable': NodeTemplateCapabilitiesScalable } requires = { _version.ToscaDefinitionsVersion: ['version'], 'inputs': ['validate_version'], NodeTemplateInstancesDeploy: [Value('instances_deploy', required=False, predicate=_instances_predicate)] } def validate(self, version, validate_version, instances_deploy): if validate_version: self.validate_version(version, (1, 3)) if instances_deploy is not None and self.initial_value is not None: raise exceptions.DSLParsingLogicException( exceptions.ERROR_INSTANCES_DEPLOY_AND_CAPABILITIES, "Node '{0}' defines both instances.deploy and " "capabilities.scalable (Note: instances.deploy is deprecated)" .format(self.ancestor(NodeTemplate).name)) def parse(self, instances_deploy, **kwargs): if self.initial_value is None: properties = scalable.Properties.DEFAULT.copy() if instances_deploy is not None: for key in properties: if key not in ['min_instances', 'max_instances']: properties[key] = instances_deploy return { 'scalable': { 'properties': properties } } else: return { 'scalable': self.child(NodeTemplateCapabilitiesScalable).value } def _node_template_relationship_type_predicate(source, target): try: return (source.child(NodeTemplateRelationshipType).initial_value == target.name) except exceptions.DSLParsingElementMatchException: return False class NodeTemplateRelationship(Element): schema = { 'type': NodeTemplateRelationshipType, 'target': NodeTemplateRelationshipTarget, 'properties': NodeTemplateRelationshipProperties, 'source_interfaces': _operation.NodeTemplateInterfaces, 'target_interfaces': _operation.NodeTemplateInterfaces, } requires = { _relationships.Relationship: [ Value('relationship_type', predicate=_node_template_relationship_type_predicate)] } def parse(self, relationship_type): result = self.build_dict_result() for interfaces in [constants.SOURCE_INTERFACES, constants.TARGET_INTERFACES]: result[interfaces] = interfaces_parser. \ merge_relationship_type_and_instance_interfaces( relationship_type_interfaces=relationship_type[interfaces], relationship_instance_interfaces=result[interfaces]) result[constants.TYPE_HIERARCHY] = relationship_type[ constants.TYPE_HIERARCHY] result['target_id'] = result['target'] del result['target'] return result class NodeTemplateRelationships(Element): schema = List(type=NodeTemplateRelationship) provides = ['contained_in'] def validate(self): contained_in_relationships = [] contained_in_targets = [] for relationship in self.children(): relationship_target = relationship.child( NodeTemplateRelationshipTarget).value relationship_type = relationship.child( NodeTemplateRelationshipType).value type_hierarchy = relationship.value[constants.TYPE_HIERARCHY] if constants.CONTAINED_IN_REL_TYPE in type_hierarchy: contained_in_relationships.append(relationship_type) contained_in_targets.append(relationship_target) if len(contained_in_relationships) > 1: ex = exceptions.DSLParsingLogicException( 112, "Node '{0}' has more than one relationship that is " "derived from '{1}' relationship. Found: {2} for targets:" " {3}" .format(self.ancestor(NodeTemplate).name, constants.CONTAINED_IN_REL_TYPE, contained_in_relationships, contained_in_targets)) ex.relationship_types = contained_in_relationships raise ex def parse(self): return [c.value for c in sorted(self.children(), key=lambda child: child.index)] def calculate_provided(self): contained_in_list = [r.child(NodeTemplateRelationshipTarget).value for r in self.children() if constants.CONTAINED_IN_REL_TYPE in r.value[constants.TYPE_HIERARCHY]] contained_in = contained_in_list[0] if contained_in_list else None return { 'contained_in': contained_in } def _node_template_related_nodes_predicate(source, target): if source.name == target.name: return False targets = source.descendants(NodeTemplateRelationshipTarget) relationship_targets = [e.initial_value for e in targets] return target.name in relationship_targets def _node_template_node_type_predicate(source, target): try: return (source.child(NodeTemplateType).initial_value == target.name) except exceptions.DSLParsingElementMatchException: return False class NodeTemplate(Element): schema = { 'type': NodeTemplateType, 'instances': NodeTemplateInstances, 'capabilities': NodeTemplateCapabilities, 'interfaces': _operation.NodeTemplateInterfaces, 'relationships': NodeTemplateRelationships, 'properties': NodeTemplateProperties, } requires = { 'inputs': [Requirement('resource_base', required=False)], 'self': [Value('related_node_templates', predicate=_node_template_related_nodes_predicate, multiple_results=True)], _plugins.Plugins: [Value('plugins')], _node_types.NodeType: [ Value('node_type', predicate=_node_template_node_type_predicate)], _node_types.NodeTypes: ['host_types'] } def parse(self, node_type, host_types, plugins, resource_base, related_node_templates): node = self.build_dict_result() node.update({ 'name': self.name, 'id': self.name, constants.TYPE_HIERARCHY: node_type[constants.TYPE_HIERARCHY] }) node[constants.INTERFACES] = interfaces_parser.\ merge_node_type_and_node_template_interfaces( node_type_interfaces=node_type[constants.INTERFACES], node_template_interfaces=node[constants.INTERFACES]) node['operations'] = _process_operations( partial_error_message="in node '{0}' of type '{1}'" .format(node['id'], node['type']), interfaces=node[constants.INTERFACES], plugins=plugins, error_code=10, resource_base=resource_base) node_name_to_node = dict((node['id'], node) for node in related_node_templates) _post_process_node_relationships(processed_node=node, node_name_to_node=node_name_to_node, plugins=plugins, resource_base=resource_base) contained_in = self.child(NodeTemplateRelationships).provided[ 'contained_in'] if self.child(NodeTemplateType).value in host_types: node['host_id'] = self.name elif contained_in: containing_node = [n for n in related_node_templates if n['name'] == contained_in][0] if 'host_id' in containing_node: node['host_id'] = containing_node['host_id'] return node def _post_process_node_relationships(processed_node, node_name_to_node, plugins, resource_base): for relationship in processed_node[constants.RELATIONSHIPS]: target_node = node_name_to_node[relationship['target_id']] _process_node_relationships_operations( relationship=relationship, interfaces_attribute='source_interfaces', operations_attribute='source_operations', node_for_plugins=processed_node, plugins=plugins, resource_base=resource_base) _process_node_relationships_operations( relationship=relationship, interfaces_attribute='target_interfaces', operations_attribute='target_operations', node_for_plugins=target_node, plugins=plugins, resource_base=resource_base) def _process_operations(partial_error_message, interfaces, plugins, error_code, resource_base): operations = {} for interface_name, interface in interfaces.items(): interface_operations = \ _operation.process_interface_operations( interface=interface, plugins=plugins, error_code=error_code, partial_error_message=( "In interface '{0}' {1}".format(interface_name, partial_error_message)), resource_bases=resource_base) for operation in interface_operations: operation_name = operation.pop('name') if operation_name in operations: # Indicate this implicit operation name needs to be # removed as we can only # support explicit implementation in this case operations[operation_name] = None else: operations[operation_name] = operation operations['{0}.{1}'.format(interface_name, operation_name)] = operation return dict((operation_name, operation) for operation_name, operation in operations.iteritems() if operation is not None) def _process_node_relationships_operations(relationship, interfaces_attribute, operations_attribute, node_for_plugins, plugins, resource_base): partial_error_message = "in relationship of type '{0}' in node '{1}'" \ .format(relationship['type'], node_for_plugins['id']) operations = _process_operations( partial_error_message=partial_error_message, interfaces=relationship[interfaces_attribute], plugins=plugins, error_code=19, resource_base=resource_base) relationship[operations_attribute] = operations class NodeTemplates(Element): required = True schema = Dict(type=NodeTemplate) requires = { _plugins.Plugins: [Value('plugins')], _node_types.NodeTypes: ['host_types'] } provides = [ 'node_template_names', 'deployment_plugins_to_install' ] def parse(self, host_types, plugins): processed_nodes = dict((node.name, node.value) for node in self.children()) _process_nodes_plugins( processed_nodes=processed_nodes, host_types=host_types, plugins=plugins) return processed_nodes.values() def calculate_provided(self, **kwargs): return { 'node_template_names': set(c.name for c in self.children()), 'deployment_plugins_to_install': self._deployment_plugins() } def _deployment_plugins(self): deployment_plugins = {} for node in self.value: for deployment_plugin in \ node[constants.DEPLOYMENT_PLUGINS_TO_INSTALL]: plugin_name = deployment_plugin[constants.PLUGIN_NAME_KEY] deployment_plugins[plugin_name] = deployment_plugin return deployment_plugins.values() def _process_nodes_plugins(processed_nodes, host_types, plugins): # extract node plugins based on node operations # do we really need node.plugins? nodes_operations = dict((name, []) for name in processed_nodes.iterkeys()) for node_name, node in processed_nodes.iteritems(): node_operations = nodes_operations[node_name] node_operations.append(node['operations']) for rel in node['relationships']: node_operations.append(rel['source_operations']) nodes_operations[rel['target_id']].append(rel['target_operations']) for node_name, node in processed_nodes.iteritems(): node[constants.PLUGINS] = _get_plugins_from_operations( operations_lists=nodes_operations[node_name], processed_plugins=plugins) for node in processed_nodes.itervalues(): # set plugins_to_install property for nodes if node['type'] in host_types: plugins_to_install = {} for another_node in processed_nodes.itervalues(): # going over all other nodes, to accumulate plugins # from different nodes whose host is the current node if another_node.get('host_id') == node['id']: # ok to override here since we assume it is the same plugin for plugin in another_node[constants.PLUGINS]: if plugin[constants.PLUGIN_EXECUTOR_KEY] \ == constants.HOST_AGENT: plugins_to_install[plugin['name']] = plugin node[constants.PLUGINS_TO_INSTALL] = plugins_to_install.values() # set deployment_plugins_to_install property for nodes deployment_plugins_to_install = {} for plugin in node[constants.PLUGINS]: if plugin[constants.PLUGIN_EXECUTOR_KEY] \ == constants.CENTRAL_DEPLOYMENT_AGENT: deployment_plugins_to_install[plugin['name']] = plugin node[constants.DEPLOYMENT_PLUGINS_TO_INSTALL] = \ deployment_plugins_to_install.values() _validate_agent_plugins_on_host_nodes(processed_nodes) def _get_plugins_from_operations(operations_lists, processed_plugins): plugins = {} for operations in operations_lists: for operation in operations.values(): plugin_name = operation['plugin'] if not plugin_name: # no-op continue plugin = processed_plugins[plugin_name] operation_executor = operation['executor'] plugin_key = (plugin_name, operation_executor) if plugin_key not in plugins: plugin = copy.deepcopy(plugin) plugin['executor'] = operation_executor plugins[plugin_key] = plugin return plugins.values() def _validate_agent_plugins_on_host_nodes(processed_nodes): for node in processed_nodes.itervalues(): if 'host_id' not in node: for plugin in node[constants.PLUGINS]: if plugin[constants.PLUGIN_EXECUTOR_KEY] \ == constants.HOST_AGENT: raise exceptions.DSLParsingLogicException( 24, "node '{0}' has no relationship which makes it " "contained within a host and it has a " "plugin '{1}' with '{2}' as an executor. " "These types of plugins must be " "installed on a host".format(node['id'], plugin['name'], constants.HOST_AGENT))
{ "content_hash": "6eafc4be33e38f66e330140c1dcafce0", "timestamp": "", "source": "github", "line_count": 573, "max_line_length": 79, "avg_line_length": 39.4694589877836, "alnum_prop": 0.5689777148921118, "repo_name": "cloudify-cosmo/cloudify-dsl-parser", "id": "07a6ed95cf9ec6bbefd9ff923fd7c88ed48df28a", "size": "23260", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dsl_parser/elements/node_templates.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1040" }, { "name": "Python", "bytes": "929968" } ], "symlink_target": "" }
from __future__ import (absolute_import, division, print_function, unicode_literals) from .core import UnitedStates class NewJersey(UnitedStates): """New Jersey""" include_good_friday = True include_election_day_every_year = True
{ "content_hash": "6b8884dfe48fd4689525d04b84be8ac6", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 66, "avg_line_length": 26.9, "alnum_prop": 0.6654275092936803, "repo_name": "sayoun/workalendar", "id": "59cac9e499256d2cc6023989491f376b61837cdf", "size": "293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workalendar/usa/new_jersey.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "1164" }, { "name": "Python", "bytes": "383844" } ], "symlink_target": "" }
import os import re import abc import sys import json import inspect import logging import platform import types import subprocess from argparse import Namespace from pprint import pprint from copy import copy, deepcopy from xml.dom import minidom from xml.dom.minidom import Document from pegasus.platforms import (HostPlatform, TargetPlatform) from pegasus.constants import * from pegasus.models import ( Architecture, Attributes, Compiler, Driver, Factory, Product, ProductType, Language, EnumStringBase, Serializable ) from pegasus.util import Path, get_working_directory UNIVERSAL_VARIABLE = "universal" class Core(object): host_platform = None # the path to where this tool resides install_path = "" # recognized regex patterns for source files (that need compilation) source_patterns = [] # Platforms: all platform classes host_classes = [] # TargetPlatforms target_classes = [] # Compilers compiler_classes = [] # Drivers: all driver classes driver_classes = [] # additional options passed on the commandline for the build file # these are cached in this dictionary for lookup when the file loads again. # Yes, it seems like a pain in the arse...bah. options = {} config = {} supported_architectures = [] @staticmethod def get_source_patterns(): return Core.source_patterns @staticmethod def get_host_platform(): """ Retrieves the host platform; this caches the value in Core.host_platform. """ if Core.host_platform: return Core.host_platform p = platform.platform().lower() if "linux" in p: Core.host_platform = LINUX elif "darwin" in p: Core.host_platform = MACOSX elif "nt" or "windows" in p: Core.host_platform = WINDOWS else: Core.host_platform = "unknown" return Core.host_platform @staticmethod def set_install_path(): # the root path where this tool is installed Core.install_path = os.path.dirname(os.path.realpath(__file__)) @staticmethod def init_logging(args): # use a log file or output to stdout? #logging_filename = 'pegasus.log' if args.quiet else None logging_filename = None logging.basicConfig(level=logging.INFO, filename=logging_filename, filemode='w') logging.info("--------initializing build system---------") @staticmethod def store_options(args, options): for option in options: if hasattr(args, option.safe_name()): Core.options[option.safe_name()] = getattr(args, option.safe_name()) @staticmethod def load_config(filename): configuration_path = os.path.join(Core.install_path, filename) logging.info("Loading configuration from \"%s\"" % configuration_path) handle = open(configuration_path, "rb") config = json.load(handle) handle.close() # store for other callbacks Core.config = config # load enum string classes. for cls in EnumStringBase.__subclasses__(): cls.load_from_config(config) # Source patterns are recognized patterns for files that # need compilation. if config.has_key("source_patterns"): for pattern in config["source_patterns"]: Core.source_patterns.append(".*\.%s$" % pattern) logging.info("-> Loaded %i source patterns." % len(Core.source_patterns)) else: raise Exception("Configuration is missing source patterns!") @staticmethod def startup(): # setup the environment Core.set_install_path() # initialize logging Core.init_logging(None) # load the config file Core.load_config("config.json") Path.set_hostplatform(HostPlatform) Attributes.load_attributes(Core.config) @staticmethod def register_classes(args): logging.info("--------Registering Host Platforms--------") Core.host_classes = Factory.register_subclasses(HostPlatform, os.path.join(Core.install_path, HOST_PLATFORMS_CLASSPATH)) logging.info("-> Registered %i platform(s)---------" % len(Core.host_classes)) # pick the hostplatform that matches this machine HostPlatform.create_platform(Core.host_classes) logging.info("--------Registering Target Platforms--------") Core.target_classes = Factory.register_subclasses(TargetPlatform, os.path.join(Core.install_path, TARGET_PLATFORMS_CLASSPATH)) logging.info("-> Registered %i platform(s)---------" % len(Core.target_classes)) logging.info("--------Registering Compilers--------") Core.compiler_classes = Factory.register_subclasses(Compiler, os.path.join(Core.install_path, COMPILERS_CLASSPATH)) logging.info("-> Registered %i driver(s)---------" % len(Core.compiler_classes)) # instance the target platform TargetPlatform.create(args, Core.target_classes, Core.compiler_classes, HostPlatform.instance) logging.info("--------Registering Drivers--------") Core.driver_classes = Factory.register_subclasses(Driver, os.path.join(Core.install_path, DRIVERS_CLASSPATH)) logging.info("-> Registered %i driver(s)---------" % len(Core.driver_classes)) # pick which driver to use Driver.create_driver_for_platform(args, TargetPlatform.instance, Core.driver_classes) # after classes have been registered and the TargetPlatform, Driver are instanced # load the Attributes config Attributes.load_schema(Core.config, TargetPlatform.instance) if Core.config.has_key("driver_data"): Driver.instance.post_load_driver_schema(Core.config["driver_data"]) logging.info("--------Registering Serializable classes--------") for subclass in Serializable.__subclasses__(): Serializable.register_class(subclass) Core.supported_architectures = [] for architecture in Architecture.enum_keys: if TargetPlatform.compiler.supports_build_architecture(Language.CPP, architecture): Core.supported_architectures.append(architecture) else: logging.info('Does not support arch: {}'.format(architecture)) @staticmethod def preprocess_arguments(args): if getattr(args, "architecture", None): args.architecture = args.architecture.split(",") else: args.architecture = None if getattr(args, "configuration", None): args.configuration = args.configuration.split(",") else: args.configuration = None if getattr(args, "products", None): args.products = args.products.split(",") class XMLBaseNode(object): def __init__(self, document, node_name): self.node = document.createElement(node_name) def set_attributes(self, attributes): for key, value in attributes.iteritems(): self.node.attributes[key] = value
{ "content_hash": "6e31665652209ee824860444a2e9d13b", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 128, "avg_line_length": 28.26222222222222, "alnum_prop": 0.7232269224720868, "repo_name": "apetrone/pegasus", "id": "fa3b788eeadd4354ed7f368ef87778c7f896d77d", "size": "6415", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "296235" } ], "symlink_target": "" }
import os, os.path, sys import json import optparse import random import subprocess import tempfile import time class ScalingTester: def __init__(self, url, object_file, user_file, match_field, filter_fields, method, client_location): self._url = url self._method = method self._object_file = object_file self._user_file = user_file self._match_field = match_field self._filter_fields = self._parseFilterFields(filter_fields) self._client_location = client_location self._object_ids = self._parseObjectIDs() self._options_file = self._generateOptionsFile() self._users = self._parseUsers() def _parseObjectIDs(self): ids_raw = open(self._object_file).read() ids = ids_raw.split('\n') return [id.strip() for id in ids if len(id.strip()) > 0] def _parseUsers(self): users_raw = open(self._user_file).read() return json.loads(users_raw) def _parseFilterFields(self, filter_fields): if not filter_fields: return None return [ff.strip() for ff in filter_fields.split(',')] # Make an options file for querying all objects by ID by field def _generateOptionsFile(self): (fd, filename) = tempfile.mkstemp() os.close(fd) options = {'match' : {self._match_field : self._object_ids}} if self._filter_fields: options['filter'] = self._filter_fields options_data = json.dumps(options) open(filename, 'w').write(options_data) return filename def invoke(self, num_concurrent): (fd, script_filename) = tempfile.mkstemp() os.close(fd) script_file = open(script_filename, 'w') for i in range(num_concurrent): user_index = random.randint(0, len(self._users)-1) user_cert = self._users[user_index]['cert'] user_key = self._users[user_index]['key'] # print "CERT = %s KEY = %s" % (user_cert, user_key) command_template = "time (python %s --key %s --cert %s " + \ "--options_file %s --method %s --url %s 2&>1 > /dev/null) &\n" command = command_template % \ (self._client_location, user_key, user_cert, \ self._options_file, self._method, self._url) script_file.write(command) script_file.close() # print "SC = " + script_filename output = self.run_script(script_filename) real_timing_raw = \ [line for line in output.split('\n') if line.startswith('real')] real_timing = [rt.split('\t')[1] for rt in real_timing_raw] secs = [self.parseTime(rt) for rt in real_timing] mean = 0; for sec in secs: mean = mean + sec mean = mean / num_concurrent print "Mean %s : %s" % (mean, secs) def run_script(self, script_filename): run_script_command = ["/bin/bash", script_filename] proc = subprocess.Popen(run_script_command, stderr=subprocess.PIPE) result = '' chunk = proc.stderr.read() while chunk: result = result + chunk chunk = proc.stderr.read() return result def parseTime(self, time_min_sec): parts = time_min_sec.split('m') min = int(parts[0]) sec = float(parts[1].split('s')[0]) sec = 60*min + sec return sec def parseOptions(args): parser = optparse.OptionParser() parser.add_option("--url", help="URL of service to which to connect", default=None) parser.add_option("--object_file", help="File containing list of object IDs", default=None) parser.add_option("--user_file", help="JSON File containing list {cert, key} dicts", default=None) parser.add_option("--method", help="Name of method to invoke", default='lookup_slices') parser.add_option("--match_field", help="Name of object field to match", default="SLICE_UID") parser.add_option("--filter_fields", help="List of object fields to select", default=None) parser.add_option("--client_location", help="Location of client.py", default = "client.py") parser.add_option("--num_concurrent", help="Number concurrent calls", default=1) parser.add_option("--frequency", help='Time to wait between invocations', default=5) parser.add_option("--num_iterations", help="Total iterations to run", default=10) [opts, args] = parser.parse_args(args) if not opts.url or not opts.object_file or not opts.user_file: print "--url and --object_file and --user_file are required" sys.exit(0) return opts def main(args = sys.argv): opts = parseOptions(args) st = ScalingTester(opts.url, opts.object_file, opts.user_file, \ opts.match_field, opts.filter_fields, \ opts.method, opts.client_location) num_iters = int(opts.num_iterations) for iter in range(num_iters): st.invoke(int(opts.num_concurrent)) if iter < num_iters-1: time.sleep(int(opts.frequency)) if __name__ == "__main__": sys.exit(main())
{ "content_hash": "71edd06a4ac67e803a7b74c8d0be040c", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 80, "avg_line_length": 38.17605633802817, "alnum_prop": 0.5712968087068806, "repo_name": "tcmitchell/geni-ch", "id": "5d9d0def31b6f772a39a2c9a6b0e008785077d1b", "size": "6638", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/chapi_scaling.py", "mode": "33188", "license": "mit", "language": [ { "name": "M4", "bytes": "889" }, { "name": "Makefile", "bytes": "14097" }, { "name": "PLSQL", "bytes": "283" }, { "name": "Python", "bytes": "721711" }, { "name": "Shell", "bytes": "34489" } ], "symlink_target": "" }
import os from smartstart.utilities.plot import plot_summary, \ mean_reward_std_episode, steps_episode, show_plot from smartstart.utilities.utilities import get_data_directory # Get directory where the summaries are saved. Since it is the same folder as # the experimenter we can use the get_data_directory method summary_dir = get_data_directory(__file__) # Define the files list files = [os.path.join(summary_dir, "QLearning_GridWorldMedium"), os.path.join(summary_dir, "SmartStart_QLearning_GridWorldMedium")] legend = ["Q-Learning", "SmartStart Q-Learning"] # We are going to save the plots in img folder output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'img') # Plot average reward and standard deviation per episode # When an output directory is supplied the plots will not be rendered with # a title. The title is used as filename for the plot. plot_summary(files, mean_reward_std_episode, ma_window=5, title="Q-Learning GridWorldMedium Average Reward per Episode", legend=legend, output_dir=output_dir) plot_summary(files, steps_episode, ma_window=5, title="Q-Learning GridWorldMedium Steps per Episode", legend=legend, format=".png", output_dir=output_dir) show_plot()
{ "content_hash": "207cfca8de3fba0087bad8e6b7e464ea", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 77, "avg_line_length": 35.86842105263158, "alnum_prop": 0.6815847395451211, "repo_name": "BartKeulen/smartstart", "id": "06a08292fd2d4b759c08e81fe5f22447ea69da19", "size": "1363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/plotting_example.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "116687" } ], "symlink_target": "" }
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 sys import os from resource_management.libraries.script.script import Script from resource_management.libraries.functions import conf_select from resource_management.libraries.functions import stack_select from resource_management.libraries.functions.stack_features import check_stack_feature from resource_management.libraries.functions import StackFeature from resource_management.libraries.functions.check_process_status import check_process_status from resource_management.core.logger import Logger from resource_management.core import shell from setup_spark import setup_spark from spark_service import spark_service class SparkThriftServer(Script): def install(self, env): import params env.set_params(params) self.install_packages(env) def configure(self, env ,upgrade_type=None): import params env.set_params(params) setup_spark(env, 'server', upgrade_type = upgrade_type, action = 'config') def start(self, env, upgrade_type=None): import params env.set_params(params) self.configure(env) spark_service('sparkthriftserver', upgrade_type=upgrade_type, action='start') def stop(self, env, upgrade_type=None): import params env.set_params(params) spark_service('sparkthriftserver', upgrade_type=upgrade_type, action='stop') def status(self, env): import status_params env.set_params(status_params) check_process_status(status_params.spark_thrift_server_pid_file) def get_component_name(self): return "spark-thriftserver" def pre_upgrade_restart(self, env, upgrade_type=None): import params env.set_params(params) if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version): Logger.info("Executing Spark Thrift Server Stack Upgrade pre-restart") conf_select.select(params.stack_name, "spark", params.version) stack_select.select("spark-thriftserver", params.version) def get_log_folder(self): import params return params.spark_log_dir def get_user(self): import params return params.hive_user if __name__ == "__main__": SparkThriftServer().execute()
{ "content_hash": "1550a14b63d340c6e46990ee5b03aed7", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 93, "avg_line_length": 33.7906976744186, "alnum_prop": 0.7629043358568479, "repo_name": "alexryndin/ambari", "id": "0c82e6fdefd58729bdacdd1192aea67715b34436", "size": "2924", "binary": false, "copies": "1", "ref": "refs/heads/branch-adh-1.5", "path": "ambari-server/src/main/resources/common-services/SPARK/1.2.1/package/scripts/spark_thrift_server.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "44884" }, { "name": "C", "bytes": "331204" }, { "name": "C#", "bytes": "215907" }, { "name": "C++", "bytes": "257" }, { "name": "CSS", "bytes": "786184" }, { "name": "CoffeeScript", "bytes": "8465" }, { "name": "FreeMarker", "bytes": "2654" }, { "name": "Groovy", "bytes": "89958" }, { "name": "HTML", "bytes": "2514774" }, { "name": "Java", "bytes": "29565801" }, { "name": "JavaScript", "bytes": "19033151" }, { "name": "Makefile", "bytes": "11111" }, { "name": "PHP", "bytes": "149648" }, { "name": "PLpgSQL", "bytes": "316489" }, { "name": "PowerShell", "bytes": "2090340" }, { "name": "Python", "bytes": "17215686" }, { "name": "R", "bytes": "3943" }, { "name": "Roff", "bytes": "13935" }, { "name": "Ruby", "bytes": "33764" }, { "name": "SQLPL", "bytes": "4277" }, { "name": "Shell", "bytes": "886011" }, { "name": "Vim script", "bytes": "5813" }, { "name": "sed", "bytes": "2303" } ], "symlink_target": "" }
import re import mechanize from bitcasa import BitcasaClient from casanova.exceptions import LoginError class Client(BitcasaClient): def __init__(self, client_id, client_secret, email, password): super(Client, self).__init__(client_id, client_secret, "http://localhost:2119") self.email = email self.password = password self.browser = mechanize.Browser() self.browser.addheaders = [( "User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36" )] self.browser.set_handle_redirect(True) self.browser.set_handle_referer(True) self.browser.set_handle_robots(False) def login(self): """ Login, authenticate and authorize with Bitcasa. Bitcasa doesn't really support what we are doing. That's the reason for all the workarounds. Workarounds are: - Start up our own local HTTP server for auth callback. - Use `mechanize` so we can pretend to be a real user (even though `mechanize` doesn't execute javascript. We will have a ready to use access token if the flow is successful. """ self.browser.open(self.login_url) self.browser.select_form(nr=0) self.browser["user"] = self.email self.browser["password"] = self.password self.browser.submit() r = self.browser.response() # Bitcasa sends us to a page where we need to give the app permission # to use our account, if we haven't done so before. # We must handle those cases as well. if re.search("oauth2/permission$", r.geturl()): self.browser.select_form(nr=0) self.browser.submit(id="approved") r = self.browser.response() if not re.search(self.redirect_url, r.geturl()): raise LoginError("We hit a dead end! We weren't able to reach the callback page!") # We are certain that we reached the callback endpoint. # Still we need to validate the format of the access token. access_token = r.read() if not re.match("^\w{2}\d_[0-9a-f]{32}", access_token): raise LoginError("Invalid access token!") self.authorization_code = access_token self.authenticate(self.authorization_code)
{ "content_hash": "f18f98d95670d3f8d674c0dab34b0a68", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 134, "avg_line_length": 37.55384615384615, "alnum_prop": 0.6185989348627612, "repo_name": "kristinn/casanova", "id": "da67a32bbf52ee68d111f7bba2e20349db6c4aee", "size": "2441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "casanova/client.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "3074" } ], "symlink_target": "" }
""" Entrypoint module, in case you use `python -mconfigurator`. Why does this file exist, and why __main__? For more info, read: - https://www.python.org/dev/peps/pep-0338/ - https://docs.python.org/2/using/cmdline.html#cmdoption-m - https://docs.python.org/3/using/cmdline.html#cmdoption-m """ import sys from configurator.cli import main if __name__ == "__main__": sys.exit(main())
{ "content_hash": "f83ec4a4a6f22bdf026cea1b18f160bb", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 64, "avg_line_length": 24.5625, "alnum_prop": 0.6921119592875318, "repo_name": "thanos/python-configurator", "id": "2197e67cf12c6b9b57659d560ecd07895994ad3d", "size": "393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/configurator/__main__.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "1598" }, { "name": "HTML", "bytes": "66536" }, { "name": "Python", "bytes": "18494" } ], "symlink_target": "" }
""" remove - remove a device configuration """ from report import Report import sys def main (args, app): for report in Report.FromConfig(app.config): if args.report == report.name: report.remove(app.config) app.config.save( ) print 'removed', report.format_url( ) break
{ "content_hash": "4f9237d55ecb47349fdb9065594bc002", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 46, "avg_line_length": 23.307692307692307, "alnum_prop": 0.6633663366336634, "repo_name": "openaps/openaps", "id": "c7929145f560b7f51c6e40c41eb182325d3643b9", "size": "304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "openaps/reports/remove.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "188" }, { "name": "Python", "bytes": "57732" }, { "name": "Shell", "bytes": "1079" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('place', '0007_auto_20141207_1710'), ] operations = [ migrations.AddField( model_name='place', name='yelp_rating', field=models.FloatField(null=True, blank=True), preserve_default=True, ), ]
{ "content_hash": "fb2bcd1830ac2bd142772870549df1f3", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 59, "avg_line_length": 22.210526315789473, "alnum_prop": 0.5876777251184834, "repo_name": "pizzapanther/Localvore", "id": "41279b54cc0559b5d544b60d268426fed0686a8e", "size": "446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django-app/place/migrations/0008_place_yelp_rating.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "607136" }, { "name": "CoffeeScript", "bytes": "3263" }, { "name": "JavaScript", "bytes": "74606" }, { "name": "Python", "bytes": "38363" }, { "name": "Shell", "bytes": "4789" } ], "symlink_target": "" }
"""Instance API tests. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import mock import jsonschema import six from treadmill import admin from treadmill import exc from treadmill import master from treadmill import yamlwrapper as yaml from treadmill.api import instance def _create_apps(_zkclient, _app_id, app, _count, _created_by): return app class ApiInstanceTest(unittest.TestCase): """treadmill.api.instance tests.""" def setUp(self): self.instance = instance.API() @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.context.ZkContext.conn', mock.Mock()) @mock.patch('treadmill.master.create_apps', mock.Mock()) @mock.patch('treadmill.api.instance._check_required_attributes', mock.Mock()) def test_normalize_run_once(self): """Test missing defaults which cause the app to fail.""" doc = """ services: - command: /bin/sleep 1m name: sleep1m restart: limit: 0 memory: 150M cpu: 10% disk: 100M """ master.create_apps.side_effect = _create_apps new_doc = self.instance.create('proid.app', yaml.load(doc)) # Disable E1126: Sequence index is not an int, slice, or instance # pylint: disable=E1126 self.assertEqual(new_doc['services'][0]['restart']['interval'], 60) self.assertTrue(master.create_apps.called) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.context.ZkContext.conn', mock.Mock()) @mock.patch('treadmill.master.create_apps', mock.Mock()) def test_run_once_small_memory(self): """Testing too small memory definition for container.""" doc = """ services: - command: /bin/sleep 10 name: sleep1m restart: limit: 0 memory: 10M cpu: 10% disk: 100M """ master.create_apps.side_effect = _create_apps with self.assertRaises(exc.TreadmillError): self.instance.create('proid.app', yaml.load(doc)) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.context.ZkContext.conn', mock.Mock()) @mock.patch('treadmill.admin.Application.get', mock.Mock(return_value={ '_id': 'proid.app', 'tickets': ['foo@bar.baz'], 'cpu': '10%', 'memory': '100M', 'disk': '100M', 'endpoints': [{'name': 'http', 'port': 8888}], 'services': [{ 'command': 'python -m SimpleHTTPServer 8888', 'name': 'web_server', 'restart': {'interval': 60, 'limit': 3} }], 'features': [], 'ephemeral_ports': {}, 'passthrough': [], 'args': [], 'environ': [], 'affinity_limits': {} })) @mock.patch('treadmill.master.create_apps') @mock.patch('treadmill.api.instance._check_required_attributes', mock.Mock()) @mock.patch('treadmill.api.instance._set_defaults', mock.Mock()) def test_instance_create_configured(self, create_apps_mock): """Test creating configured instance.""" create_apps_mock.side_effect = _create_apps app = { 'tickets': ['foo@bar.baz'], 'cpu': '10%', 'memory': '100M', 'disk': '100M', 'endpoints': [{'name': 'http', 'port': 8888}], 'services': [{ 'command': 'python -m SimpleHTTPServer 8888', 'name': 'web_server', 'restart': {'interval': 60, 'limit': 3} }], 'features': [], 'ephemeral_ports': {}, 'passthrough': [], 'args': [], 'environ': [], 'affinity_limits': {}, } self.instance.create('proid.app', {}) create_apps_mock.assert_called_once_with( mock.ANY, 'proid.app', app, 1, None ) create_apps_mock.reset_mock() self.instance.create('proid.app', {}, created_by='monitor') create_apps_mock.assert_called_once_with( mock.ANY, 'proid.app', app, 1, 'monitor' ) create_apps_mock.reset_mock() self.instance.create('proid.app', {}, 2, 'foo@BAR.BAZ') create_apps_mock.assert_called_once_with( mock.ANY, 'proid.app', app, 2, 'foo@BAR.BAZ' ) with six.assertRaisesRegex( self, jsonschema.exceptions.ValidationError, "'invalid!' is not valid" ): self.instance.create('proid.app', {}, created_by='invalid!') with six.assertRaisesRegex( self, jsonschema.exceptions.ValidationError, "0 is less than the minimum of 1" ): self.instance.create('proid.app', {}, count=0) with six.assertRaisesRegex( self, jsonschema.exceptions.ValidationError, "1001 is greater than the maximum of 1000" ): self.instance.create('proid.app', {}, count=1001) @mock.patch('treadmill.context.AdminContext.conn', mock.Mock(return_value=admin.Admin(None, None))) @mock.patch('treadmill.context.ZkContext.conn', mock.Mock()) @mock.patch('treadmill.master.delete_apps') def test_instance_delete(self, delete_apps_mock): """Test deleting an instance.""" delete_apps_mock.return_value = None self.instance.delete('proid.app#0000000001') delete_apps_mock.assert_called_once_with( mock.ANY, ['proid.app#0000000001'], None ) delete_apps_mock.reset_mock() self.instance.delete('proid.app#0000000002', deleted_by='monitor') delete_apps_mock.assert_called_once_with( mock.ANY, ['proid.app#0000000002'], 'monitor' ) delete_apps_mock.reset_mock() self.instance.delete('proid.app#0000000003', deleted_by='foo@BAR.BAZ') delete_apps_mock.assert_called_once_with( mock.ANY, ['proid.app#0000000003'], 'foo@BAR.BAZ' ) with six.assertRaisesRegex( self, jsonschema.exceptions.ValidationError, "'invalid!' is not valid" ): self.instance.delete('proid.app#0000000001', deleted_by='invalid!') if __name__ == '__main__': unittest.main()
{ "content_hash": "e77edb329aac8d0524a97ae09f8574ac", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 79, "avg_line_length": 34.15346534653465, "alnum_prop": 0.5538483838237426, "repo_name": "captiosus/treadmill", "id": "9ed42d59ad6aefa203e7e2525a7b717f4e489665", "size": "6899", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/api/instance_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PowerShell", "bytes": "570" }, { "name": "Python", "bytes": "2598791" }, { "name": "Ruby", "bytes": "3712" }, { "name": "Shell", "bytes": "58099" } ], "symlink_target": "" }
import binascii import socket import struct import sys import hashlib UDP_IP = "127.0.0.1" UDP_PORT_client = 5005#different ports because for assignment 4 we want same loop back address for ip UDP_PORT_server=5006 unpacker = struct.Struct('I I 32s')#struct for receiving the packet form server. ACK, SEQ, Checksum. no data! print("UDP target IP:", UDP_IP) print("UDP target port:", UDP_PORT_server) print("\n") """ #---------------------------------------------------------------------------- #ORIGINAL CODE: #Create the Checksum values = (0,0,b'TestData') UDP_Data = struct.Struct('I I 8s') packed_data = UDP_Data.pack(*values) chksum = bytes(hashlib.md5(packed_data).hexdigest(), encoding="UTF-8") #Build the UDP Packet values = (0,0,b'TestData',chksum) #ACK, SEQ, DATA, CHECKSUM UDP_Packet_Data = struct.Struct('I I 8s 32s') UDP_Packet = UDP_Packet_Data.pack(*values) #Send the UDP Packet sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(UDP_Packet, (UDP_IP, UDP_PORT)) #---------------------------------------------------------------------------- """ #function for creating the checksum - MD5 Checksum of packet (32 Bytes) def create_client_checksum(ACK, SEQ, theData): #byteData = theData.encode() byteData = bytes(theData, encoding="UTF-8") values = (ACK,SEQ,byteData) #b casts the data to byte encoding UDP_Data = struct.Struct('I I 8s') packed_data = UDP_Data.pack(*values) chksum = bytes(hashlib.md5(packed_data).hexdigest(), encoding="UTF-8") #utf 8 encoding #return the checksum return chksum; #function for building the UDP packet: #ACK - Indicates if packet is ACK or not. Valid values (1 or 0) #SEQ - Sequence number of packet. Valid values (1 or 0) #DATA - Application Data (8 bytes) #CHKSUM - MD5 Checksum of packet (32 Bytes) def build_UDP_client_packet(ACK, SEQ, theData, chksum): #byteData = theData.encode() byteData = bytes(theData, encoding="UTF-8") values = (ACK,SEQ,byteData,chksum) #ACK, SEQ, DATA, CHECKSUM UDP_Packet_Data = struct.Struct('I I 8s 32s') UDP_Packet = UDP_Packet_Data.pack(*values) #return the packet ready to be sent return UDP_Packet; #Send the UDP Packet def send_packet(UDP_Packet): #send it through the socket sock.sendto(UDP_Packet, (UDP_IP, UDP_PORT)) #---------------------------------------------------------------------------- #Create the socket sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT_client))#bind to itself, attaching ip and port saying RECEIVE HERE """ send the following info: NCC-1701 NCC-1664 NCC-1017 #in order to accomplish this the client must also receive data in form of ACKS from server #because we are useing rdt2.2 #client sends ACK=0 #server sends ACK=1 """ #initializing variables that check before we can send the next packet packet1Success = False packet2Success = False packet3Success = False doneSending = False while doneSending==False: #data 1 clientACK=0 currentSEQ=0 currentData ="NCC-1701" #create checksum currentchecksum = create_client_checksum(clientACK, currentSEQ, currentData) #build packet UDP_Packet_client = build_UDP_client_packet(clientACK, currentSEQ, currentData, currentchecksum) while packet1Success == False: #send the packet print("bouta send packet1") sock.sendto(UDP_Packet_client, (UDP_IP, UDP_PORT_server)) print("we sent dat packet") #receive the UDP packet data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes UDP_Packet = unpacker.unpack(data) print("received from:", addr) print("received message:", UDP_Packet) #Create the Checksum for comparison values = (UDP_Packet[0],UDP_Packet[1]) #ACK SEQ Checksum. UDP_Packet[2] is the checksum packer = struct.Struct('I I') packed_data = packer.pack(*values) chksum = bytes(hashlib.md5(packed_data).hexdigest(), encoding="UTF-8") #Compare Checksums to test for corrupt data if UDP_Packet[2] == chksum and UDP_Packet[1]==currentSEQ: #checksums match and correct sequence print("checksums match and sequences match, packet ok") print("Packet 1 success!!\n") print("Onto the next one\n\n") packet1Success=True else: print("checksums don't match OR wrong sequence\n") print("RETRYING :(") #data 2 currentSEQ=1 currentData ="NCC-1664" #create checksum currentchecksum = create_client_checksum(clientACK, currentSEQ, currentData) #build packet UDP_Packet_client = build_UDP_client_packet(clientACK, currentSEQ, currentData, currentchecksum) while packet2Success == False: #send the packet print("bouta send packet2") sock.sendto(UDP_Packet_client, (UDP_IP, UDP_PORT_server)) print("we sent dat packet") #receive the UDP packet data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes UDP_Packet = unpacker.unpack(data) print("received from:", addr) print("received message:", UDP_Packet) #Create the Checksum for comparison values = (UDP_Packet[0],UDP_Packet[1]) #ACK SEQ Checksum. UDP_Packet[2] is the checksum packer = struct.Struct('I I') packed_data = packer.pack(*values) chksum = bytes(hashlib.md5(packed_data).hexdigest(), encoding="UTF-8") #Compare Checksums to test for corrupt data if UDP_Packet[2] == chksum and UDP_Packet[1]==currentSEQ: #checksums match and correct sequence print("checksums match and sequences match, packet ok") print("Packet 2 success!!\n") print("Onto the next one\n\n") packet2Success=True else: print("checksums don't match OR wrong sequence\n") print("RETRYING :(") #data 3 currentSEQ=0 currentData ="NCC-1017" #create checksum currentchecksum = create_client_checksum(clientACK, currentSEQ, currentData) #build packet UDP_Packet_client = build_UDP_client_packet(clientACK, currentSEQ, currentData, currentchecksum) while packet3Success == False: #send the packet print("bouta send packet3") sock.sendto(UDP_Packet_client, (UDP_IP, UDP_PORT_server)) print("we sent dat packet") #receive the UDP packet data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes UDP_Packet = unpacker.unpack(data) print("received from:", addr) print("received message:", UDP_Packet) #Create the Checksum for comparison values = (UDP_Packet[0],UDP_Packet[1]) #ACK SEQ Checksum. UDP_Packet[2] is the checksum packer = struct.Struct('I I') packed_data = packer.pack(*values) chksum = bytes(hashlib.md5(packed_data).hexdigest(), encoding="UTF-8") #Compare Checksums to test for corrupt data if UDP_Packet[2] == chksum and UDP_Packet[1]==currentSEQ: #checksums match and correct sequence print("checksums match and sequences match, packet ok") print("Packet 3 success!!\n") print("Onto the next one\n\n") packet3Success=True else: print("checksums don't match OR wrong sequence\n") print("RETRYING :(") print("\n") print("We done here") doneSending=True sock.close()#close the socket
{ "content_hash": "2dd3f2e913513eeeea83d1d8030cbbbf", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 109, "avg_line_length": 33.31730769230769, "alnum_prop": 0.6971139971139971, "repo_name": "V-Lam/School-Assignments-and-Labs-2014-2017", "id": "2ed4efbf5da46a28471172be90152c8a87a9792a", "size": "6930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CS 3357 - Python -- (Computer Networks 1)/assignment 3/vlam54_UDP_Client.py", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "49938" }, { "name": "C", "bytes": "44615" }, { "name": "C++", "bytes": "52134" }, { "name": "CSS", "bytes": "38424" }, { "name": "HTML", "bytes": "213355" }, { "name": "Java", "bytes": "491043" }, { "name": "JavaScript", "bytes": "2481" }, { "name": "Makefile", "bytes": "1298" }, { "name": "Prolog", "bytes": "3256" }, { "name": "Python", "bytes": "299476" }, { "name": "Shell", "bytes": "10944" } ], "symlink_target": "" }
import http.server import time import os import pyroute2 import socketserver import threading from functools import partial from pathlib import Path class ThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer): pass class HTTPServer: def __init__(self, path, remote_ip): self.path = path self.port = 8313 self.old_path = None self.httpd = None with pyroute2.IPRoute() as ipr: r = ipr.route('get', dst=remote_ip) for attr in r[0]['attrs']: if attr[0] == 'RTA_PREFSRC': self.ip = attr[1] def get_url(self, filename): path = Path(self.path) / filename assert path.exists() return f"http://{self.ip}:{self.port}/{filename}" def __enter__(self): def start_server(): Handler = http.server.SimpleHTTPRequestHandler self.httpd = ThreadingHTTPServer(("", self.port), Handler) self.httpd.serve_forever() # Kind of annoying, but to work with older pythons where # SimpleHTTPRequestHandler doesn't take a directory parameter but only # serves the current directory: self.old_path = os.getcwd() os.chdir(self.path) self.thread = threading.Thread(target=start_server) self.thread.start() return self def __exit__(self, type, value, exc): if self.httpd is not None: self.httpd.shutdown() self.httpd.server_close() if self.old_path is not None: os.chdir(self.old_path) if __name__ == '__main__': with HTTPServer("/tmp", "127.0.0.1") as server: print("server ip", server.ip) print("server port", server.port) time.sleep(300)
{ "content_hash": "fed4bdee055e1592a0278e6d7095f3f8", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 79, "avg_line_length": 29.966101694915253, "alnum_prop": 0.5978506787330317, "repo_name": "EttusResearch/meta-ettus", "id": "38213f62c594477aca6806ece7694ec195de4770", "size": "1768", "binary": false, "copies": "1", "ref": "refs/heads/zeus", "path": "contrib/test/usrp_emb/usrp_emb/httpd.py", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "484" }, { "name": "BitBake", "bytes": "32590" }, { "name": "BlitzBasic", "bytes": "2285" }, { "name": "C", "bytes": "6558" }, { "name": "C++", "bytes": "2021" }, { "name": "Dockerfile", "bytes": "199" }, { "name": "HTML", "bytes": "9295" }, { "name": "NASL", "bytes": "16939" }, { "name": "PHP", "bytes": "3885" }, { "name": "Pascal", "bytes": "13984" }, { "name": "Python", "bytes": "108965" }, { "name": "Shell", "bytes": "41098" }, { "name": "Tcl", "bytes": "755" } ], "symlink_target": "" }
from .rule_data_source import RuleDataSource class RuleMetricDataSource(RuleDataSource): """A rule metric data source. The discriminator value is always RuleMetricDataSource in this case. :param resource_uri: the resource identifier of the resource the rule monitors. **NOTE**: this property cannot be updated for an existing rule. :type resource_uri: str :param odatatype: Constant filled by server. :type odatatype: str :param metric_name: the name of the metric that defines what the rule monitors. :type metric_name: str """ _validation = { 'odatatype': {'required': True}, } _attribute_map = { 'resource_uri': {'key': 'resourceUri', 'type': 'str'}, 'odatatype': {'key': 'odata\\.type', 'type': 'str'}, 'metric_name': {'key': 'metricName', 'type': 'str'}, } def __init__(self, resource_uri=None, metric_name=None): super(RuleMetricDataSource, self).__init__(resource_uri=resource_uri) self.metric_name = metric_name self.odatatype = 'Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource'
{ "content_hash": "b1d42e24d0b2f9a890df1c11caff6095", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 90, "avg_line_length": 36.483870967741936, "alnum_prop": 0.6569407603890363, "repo_name": "AutorestCI/azure-sdk-for-python", "id": "d18479246de7931d354e2dae6233801800e17744", "size": "1605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-monitor/azure/mgmt/monitor/models/rule_metric_data_source.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "34619070" } ], "symlink_target": "" }
import django.forms as forms from patreon.models import PatreonAppCreds class CredsChoices(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.label def creds_form(user): class CredsForm(forms.Form): account = CredsChoices(queryset=PatreonAppCreds.objects.filter(user=user), empty_label="") return CredsForm
{ "content_hash": "73bf1f11dd80e95f1aec1cacbe52e645", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 98, "avg_line_length": 32.90909090909091, "alnum_prop": 0.7403314917127072, "repo_name": "google/mirandum", "id": "7b3b2ffe4f53c4d81ff966006fb025526c9bf1bf", "size": "362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alerts/patreon/forms.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9472" }, { "name": "Elixir", "bytes": "574" }, { "name": "HTML", "bytes": "122101" }, { "name": "JavaScript", "bytes": "19438" }, { "name": "Jinja", "bytes": "4124" }, { "name": "Python", "bytes": "398732" }, { "name": "Shell", "bytes": "3296" } ], "symlink_target": "" }
from ...subsystem.courses.course import Course import logging from django.core.management.base import BaseCommand logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Running the scraper to populate the courses for the 400 level courses' def handle(self, *args, **options): Course400AndAbove = Course.objects.filter(number__gte=400) listof200leveldeptnum = ["ENGR 201", "ENGR 202", "ENGR 213", "ENGR 233", "ELEC 275", "ENCS 282", "SOEN 228", "SOEN 287", "COMP 232", "COMP 248", "COMP 249"] for C in Course400AndAbove: for P in listof200leveldeptnum: P = P[:4]+P[-3:] prereq = Course.objects.get(pk=P) if prereq not in C.prerequisites.all(): C.prerequisites.add(prereq) print(prereq) print("Finished populating pre-reqs for 400 level courses")
{ "content_hash": "22080d3f50a12cecab8b2d9ffd24ba1c", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 82, "avg_line_length": 34.22222222222222, "alnum_prop": 0.46185064935064934, "repo_name": "foxtrot94/EchelonPlanner", "id": "6d0d612279fdb184e255c4f89e9ca53b7cc054e5", "size": "1232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/management/commands/preRequisites400Level.py", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "7334" }, { "name": "CSS", "bytes": "294499" }, { "name": "HTML", "bytes": "139939" }, { "name": "JavaScript", "bytes": "33582" }, { "name": "Python", "bytes": "273409" }, { "name": "Shell", "bytes": "7334" } ], "symlink_target": "" }
import pylibvw SearchState = pylibvw.SearchState class SearchTask(): def __init__(self, vw, sch, num_actions): self.vw = vw self.sch = sch self.blank_line = self.vw.example("") self.blank_line.finish() self.bogus_example = self.vw.example("1 | x") def __del__(self): self.bogus_example.finish() pass def _run(self, your_own_input_example): pass def _call_vw(self, my_example, isTest, useOracle=False): # run_fn, setup_fn, takedown_fn, isTest): self._output = None self.bogus_example.set_test_only(isTest) def run(): self._output = self._run(my_example) setup = None takedown = None if callable(getattr(self, "_setup", None)): setup = lambda: self._setup(my_example) if callable(getattr(self, "_takedown", None)): takedown = lambda: self._takedown(my_example) self.sch.set_structured_predict_hook(run, setup, takedown) self.sch.set_force_oracle(useOracle) self.vw.learn(self.bogus_example) self.vw.learn(self.blank_line) # this will cause our ._run hook to get called def learn(self, data_iterator): for my_example in data_iterator.__iter__(): self._call_vw(my_example, isTest=False); def get_search_state(self): return self.sch.get_search_state() def example(self, initStringOrDict=None, labelType=pylibvw.vw.lDefault): """TODO""" if self.sch.predict_needs_example(): return self.vw.example(initStringOrDict, labelType) else: return self.vw.example(None, labelType) def predict(self, my_example, useOracle=False): self._call_vw(my_example, isTest=True, useOracle=useOracle); return self._output class vw(pylibvw.vw): """The pyvw.vw object is a (trivial) wrapper around the pylibvw.vw object; you're probably best off using this directly and ignoring the pylibvw.vw structure entirely.""" def __init__(self, argString=None, **kw): """Initialize the vw object. The (optional) argString is the same as the command line arguments you'd use to run vw (eg,"--audit"). you can also use key/value pairs as in: pyvw.vw(audit=True, b=24, k=True, c=True, l2=0.001) or a combination, for instance: pyvw.vw("--audit", b=26)""" def format(key,val): if type(val) is bool and val == False: return '' s = ('-'+key) if len(key) == 1 else ('--'+key) if type(val) is not bool or val != True: s += ' ' + str(val) return s l = [format(k,v) for k,v in kw.iteritems()] if argString is not None: l = [argString] + l #print ' '.join(l) pylibvw.vw.__init__(self,' '.join(l)) self.finished = False def __enter__(self): return self def __exit__(self,typ,value,traceback): self.finish() return typ is None def get_weight(self, index, offset=0): """Given an (integer) index (and an optional offset), return the weight for that position in the (learned) weight vector.""" return pylibvw.vw.get_weight(self, index, offset) def learn(self, ec): """Perform an online update; ec can either be an example object or a string (in which case it is parsed and then learned on).""" #if isinstance(ec, str): # self.learn_string(ec) #else: # if hasattr(ec, 'setup_done') and not ec.setup_done: # ec.setup_example() pylibvw.vw.learn(self, ec) def predict(self, ec): """Perform an prediction; ec can either be an example object or a string (in which case it is parsed and then predicted on).""" #if isinstance(ec, str): # self.predict_string(ec) #else: # if hasattr(ec, 'setup_done') and not ec.setup_done: # ec.setup_example() pylibvw.vw.predict(self, ec) def finish(self): """stop VW by calling finish (and, eg, write weights to disk)""" if not self.finished: pylibvw.vw.finish(self) self.finished = True def example(self, stringOrDict=None, labelType=pylibvw.vw.lDefault): """TODO: document""" return example(self, stringOrDict, labelType) def __del__(self): self.finish() def init_search_task(self, search_task, task_data=None): sch = self.get_search_ptr() def predict(examples, my_tag, oracle, condition=None, allowed=None, learner_id=0): """The basic (via-reduction) prediction mechanism. Several variants are supported through this overloaded function: 'examples' can be a single example (interpreted as non-LDF mode) or a list of examples (interpreted as LDF mode). it can also be a lambda function that returns a single example or list of examples, and in that list, each element can also be a lambda function that returns an example. this is done for lazy example construction (aka speed). 'my_tag' should be an integer id, specifying this prediction 'oracle' can be a single label (or in LDF mode a single array index in 'examples') or a list of such labels if the oracle policy is indecisive; if it is None, then the oracle doesn't care 'condition' should be either: (1) a (tag,char) pair, indicating to condition on the given tag with identifier from the char; or (2) a (tag,len,char) triple, indicating to condition on tag, tag-1, tag-2, ..., tag-len with identifiers char, char+1, char+2, ..., char+len. or it can be a (heterogenous) list of such things. 'allowed' can be None, in which case all actions are allowed; or it can be list of valid actions (in LDF mode, this should be None and you should encode the valid actions in 'examples') 'learner_id' specifies the underlying learner id Returns a single prediction. """ P = sch.get_predictor(my_tag) if sch.is_ldf(): # we need to know how many actions there are, even if we don't know their identities while hasattr(examples, '__call__'): examples = examples() if not isinstance(examples, list): raise TypeError('expected example _list_ in LDF mode for SearchTask.predict()') P.set_input_length(len(examples)) if sch.predict_needs_example(): for n in range(len(examples)): ec = examples[n] while hasattr(ec, '__call__'): ec = ec() # unfold the lambdas if not isinstance(ec, example) and not isinstance(ec, pylibvw.example): raise TypeError('non-example in LDF example list in SearchTask.predict()') if hasattr(ec, 'setup_done') and not ec.setup_done: ec.setup_example() P.set_input_at(n, ec) else: pass # TODO: do we need to set the examples even though they're not used? else: if sch.predict_needs_example(): while hasattr(examples, '__call__'): examples = examples() if hasattr(examples, 'setup_done') and not examples.setup_done: examples.setup_example() P.set_input(examples) else: pass # TODO: do we need to set the examples even though they're not used? # if (isinstance(examples, list) and all([isinstance(ex, example) or isinstance(ex, pylibvw.example) for ex in examples])) or \ # isinstance(examples, example) or isinstance(examples, pylibvw.example): # if isinstance(examples, list): # LDF # P.set_input_length(len(examples)) # for n in range(len(examples)): # P.set_input_at(n, examples[n]) # else: # non-LDF # P.set_input(examples) if True: # TODO: get rid of this if oracle is None: pass elif isinstance(oracle, list): if len(oracle) > 0: P.set_oracles(oracle) elif isinstance(oracle, int): P.set_oracle(oracle) else: raise TypeError('expecting oracle to be a list or an integer') if condition is not None: if not isinstance(condition, list): condition = [condition] for c in condition: if not isinstance(c, tuple): raise TypeError('item ' + str(c) + ' in condition list is malformed') if len(c) == 2 and isinstance(c[0], int) and isinstance(c[1], str) and len(c[1]) == 1: P.add_condition(max(0, c[0]), c[1]) elif len(c) == 3 and isinstance(c[0], int) and isinstance(c[1], int) and isinstance(c[2], str) and len(c[2]) == 1: P.add_condition_range(max(0,c[0]), max(0,c[1]), c[2]) else: raise TypeError('item ' + str(c) + ' in condition list malformed') if allowed is None: pass elif isinstance(allowed, list): P.set_alloweds(allowed) else: raise TypeError('allowed argument wrong type') if learner_id != 0: P.set_learner_id(learner_id) p = P.predict() return p else: raise TypeError("'examples' should be a pyvw example (or a pylibvw example), or a list of said things") sch.predict = predict num_actions = sch.get_num_actions() return search_task(self, sch, num_actions) if task_data is None else search_task(self, sch, num_actions, task_data) class namespace_id(): """The namespace_id class is simply a wrapper to convert between hash spaces referred to by character (eg 'x') versus their index in a particular example. Mostly used internally, you shouldn't really need to touch this.""" def __init__(self, ex, id): """Given an example and an id, construct a namespace_id. The id can either be an integer (in which case we take it to be an index into ex.indices[]) or a string (in which case we take the first character as the namespace id).""" if isinstance(id, int): # you've specified a namespace by index if id < 0 or id >= ex.num_namespaces(): raise Exception('namespace ' + str(id) + ' out of bounds') self.id = id self.ord_ns = ex.namespace(id) self.ns = chr(self.ord_ns) elif isinstance(id, str): # you've specified a namespace by string if len(id) == 0: id = ' ' self.id = None # we don't know and we don't want to do the linear search requered to find it self.ns = id[0] self.ord_ns = ord(self.ns) else: raise Exception("ns_to_characterord failed because id type is unknown: " + str(type(id))) class example_namespace(): """The example_namespace class is a helper class that allows you to extract namespaces from examples and operate at a namespace level rather than an example level. Mainly this is done to enable indexing like ex['x'][0] to get the 0th feature in namespace 'x' in example ex.""" def __init__(self, ex, ns, ns_hash=None): """Construct an example_namespace given an example and a target namespace (ns should be a namespace_id)""" if not isinstance(ns, namespace_id): raise TypeError self.ex = ex self.ns = ns self.ns_hash = None def num_features_in(self): """Return the total number of features in this namespace.""" return self.ex.num_features_in(self.ns) def __getitem__(self, i): """Get the feature/value pair for the ith feature in this namespace.""" f = self.ex.feature(self.ns, i) v = self.ex.feature_weight(self.ns, i) return (f, v) def iter_features(self): """iterate over all feature/value pairs in this namespace.""" for i in range(self.num_features_in()): yield self[i] def push_feature(self, feature, v=1.): """Add an unhashed feature to the current namespace (fails if setup has already run on this example).""" if self.ns_hash is None: self.ns_hash = self.ex.vw.hash_space( self.ns ) self.ex.push_feature(self.ns, feature, v, self.ns_hash) def pop_feature(self): """Remove the top feature from the current namespace; returns True if a feature was removed, returns False if there were no features to pop.""" return self.ex.pop_feature(self.ns) def push_features(self, ns, featureList): """Push a list of features to a given namespace. Each feature in the list can either be an integer (already hashed) or a string (to be hashed) and may be paired with a value or not (if not, the value is assumed to be 1.0). See example.push_features for examples.""" self.ex.push_features(self.ns, featureList) class abstract_label: """An abstract class for a VW label.""" def __init__(self): pass def from_example(self, ex): """grab a label from a given VW example""" raise Exception("from_example not yet implemented") class simple_label(abstract_label): def __init__(self, label=0., weight=1., initial=0., prediction=0.): abstract_label.__init__(self) if isinstance(label, example): self.from_example(label) else: self.label = label self.weight = weight self.initial = initial self.prediction = prediction def from_example(self, ex): self.label = ex.get_simplelabel_label() self.weight = ex.get_simplelabel_weight() self.initial = ex.get_simplelabel_initial() self.prediction = ex.get_simplelabel_prediction() def __str__(self): s = str(self.label) if self.weight != 1.: s += ':' + self.weight return s class multiclass_label(abstract_label): def __init__(self, label=1, weight=1., prediction=1): abstract_label.__init__(self) self.label = label self.weight = weight self.prediction = prediction def from_example(self, ex): self.label = ex.get_multiclass_label() self.weight = ex.get_multiclass_weight() self.prediction = ex.get_multiclass_prediction() def __str__(self): s = str(self.label) if self.weight != 1.: s += ':' + self.weight return s class cost_sensitive_label(abstract_label): class wclass: def __init__(self, label, cost=0., partial_prediction=0., wap_value=0.): self.label = label self.cost = cost self.partial_prediction = partial_prediction self.wap_value = wap_value def __init__(self, costs=[], prediction=0): abstract_label.__init__(self) self.costs = costs self.prediction = prediction def from_example(self, ex): self.prediction = ex.get_costsensitive_prediction() self.costs = [] for i in range(ex.get_costsensitive_num_costs): wc = wclass(ex.get_costsensitive_class(), ex.get_costsensitive_cost(), ex.get_costsensitive_partial_prediction(), ex.get_costsensitive_wap_value()) self.costs.append(wc) def __str__(self): return '[' + ' '.join([str(c.label) + ':' + str(c.cost) for c in self.costs]) class cbandits_label(abstract_label): class wclass: def __init__(self, label, cost=0., partial_prediction=0., probability=0.): self.label = label self.cost = cost self.partial_prediction = partial_prediction self.probability = probability def __init__(self, costs=[], prediction=0): abstract_label.__init__(self) self.costs = costs self.prediction = prediction def from_example(self, ex): self.prediction = ex.get_cbandits_prediction() self.costs = [] for i in range(ex.get_cbandits_num_costs): wc = wclass(ex.get_cbandits_class(), ex.get_cbandits_cost(), ex.get_cbandits_partial_prediction(), ex.get_cbandits_probability()) self.costs.append(wc) def __str__(self): return '[' + ' '.join([str(c.label) + ':' + str(c.cost) for c in self.costs]) class example(pylibvw.example): """The example class is a (non-trivial) wrapper around pylibvw.example. Most of the wrapping is to make the interface easier to use (by making the types safer via namespace_id) and also with added python-specific functionality.""" def __init__(self, vw, initStringOrDict=None, labelType=pylibvw.vw.lDefault): """Construct a new example from vw. If initString is None, you get an "empty" example which you can construct by hand (see, eg, example.push_features). If initString is a string, then this string is parsed as it would be from a VW data file into an example (and "setup_example" is run). if it is a dict, then we add all features in that dictionary. finally, if it's a function, we (repeatedly) execute it fn() until it's not a function any more (for lazy feature computation).""" if initStringOrDict is not None: while hasattr(initStringOrDict, '__call__'): initStringOrDict = initStringOrDict() if initStringOrDict is None: pylibvw.example.__init__(self, vw, labelType) self.setup_done = False elif isinstance(initStringOrDict, str): pylibvw.example.__init__(self, vw, labelType, initStringOrDict) self.setup_done = True elif isinstance(initStringOrDict, dict): pylibvw.example.__init__(self, vw, labelType) self.vw = vw self.stride = vw.get_stride() self.finished = False self.push_feature_dict(vw, initStringOrDict) self.setup_done = False else: raise TypeError('expecting string or dict as argument for example construction') self.vw = vw self.stride = vw.get_stride() self.finished = False self.labelType = labelType def __del__(self): self.finish() def __enter__(self): return self def __exit__(self,typ,value,traceback): self.finish() return typ is None def get_ns(self, id): """Construct a namespace_id from either an integer or string (or, if a namespace_id is fed it, just return it directly).""" if isinstance(id, namespace_id): return id else: return namespace_id(self, id) def __getitem__(self, id): """Get an example_namespace object associated with the given namespace id.""" return example_namespace(self, self.get_ns(id)) def feature(self, ns, i): """Get the i-th hashed feature id in a given namespace (i can range from 0 to self.num_features_in(ns)-1)""" ns = self.get_ns(ns) # guaranteed to be a single character f = pylibvw.example.feature(self, ns.ord_ns, i) if self.setup_done: f = (f - self.get_ft_offset()) / self.stride return f def feature_weight(self, ns, i): """Get the value(weight) associated with a given feature id in a given namespace (i can range from 0 to self.num_features_in(ns)-1)""" return pylibvw.example.feature_weight(self, self.get_ns(ns).ord_ns, i) def set_label_string(self, string): """Give this example a new label, formatted as a string (ala the VW data file format).""" pylibvw.example.set_label_string(self, self.vw, string, self.labelType) def setup_example(self): """If this example hasn't already been setup (ie, quadratic features constructed, etc.), do so.""" if self.setup_done: raise Exception('trying to setup_example on an example that is already setup') self.vw.setup_example(self) self.setup_done = True def unsetup_example(self): """If this example has been setup, reverse that process so you can continue editing the examples.""" if not self.setup_done: raise Exception('trying to unsetup_example that has not yet been setup') self.vw.unsetup_example(self) self.setup_done = False def learn(self): """Learn on this example (and before learning, automatically call setup_example if the example hasn't yet been setup).""" if not self.setup_done: self.setup_example() self.vw.learn(self) def predict(self): """predict on this example (and before predicting, automatically call setup_example if the example hasn't yet been setup).""" if not self.setup_done: self.setup_example() self.vw.predict(self) def sum_feat_sq(self, ns): """Return the total sum feature-value squared for a given namespace.""" return pylibvw.example.sum_feat_sq(self, self.get_ns(ns).ord_ns) def num_features_in(self, ns): """Return the total number of features in a given namespace.""" return pylibvw.example.num_features_in(self, self.get_ns(ns).ord_ns) def get_feature_id(self, ns, feature, ns_hash=None): """Return the hashed feature id for a given feature in a given namespace. feature can either be an integer (already a feature id) or a string, in which case it is hashed. Note that if --hash all is on, then get_feature_id(ns,"5") != get_feature_id(ns, 5). If you've already hashed the namespace, you can optionally provide that value to avoid re-hashing it.""" if isinstance(feature, int): return feature if isinstance(feature, str): if ns_hash is None: ns_hash = self.vw.hash_space( self.get_ns(ns).ns ) return self.vw.hash_feature(feature, ns_hash) raise Exception("cannot extract feature of type: " + str(type(feature))) def push_hashed_feature(self, ns, f, v=1.): """Add a hashed feature to a given namespace.""" if self.setup_done: self.unsetup_example(); pylibvw.example.push_hashed_feature(self, self.get_ns(ns).ord_ns, f, v) def push_feature(self, ns, feature, v=1., ns_hash=None): """Add an unhashed feature to a given namespace.""" f = self.get_feature_id(ns, feature, ns_hash) self.push_hashed_feature(ns, f, v) def pop_feature(self, ns): """Remove the top feature from a given namespace; returns True if a feature was removed, returns False if there were no features to pop.""" if self.setup_done: self.unsetup_example(); return pylibvw.example.pop_feature(self, self.get_ns(ns).ord_ns) def push_namespace(self, ns): """Push a new namespace onto this example. You should only do this if you're sure that this example doesn't already have the given namespace.""" if self.setup_done: self.unsetup_example(); pylibvw.example.push_namespace(self, self.get_ns(ns).ord_ns) def pop_namespace(self): """Remove the top namespace from an example; returns True if a namespace was removed, or False if there were no namespaces left.""" if self.setup_done: self.unsetup_example(); return pylibvw.example.pop_namespace(self) def ensure_namespace_exists(self, ns): """Check to see if a namespace already exists. If it does, do nothing. If it doesn't, add it.""" if self.setup_done: self.unsetup_example(); return pylibvw.example.ensure_namespace_exists(self, self.get_ns(ns).ord_ns) def push_features(self, ns, featureList): """Push a list of features to a given namespace. Each feature in the list can either be an integer (already hashed) or a string (to be hashed) and may be paired with a value or not (if not, the value is assumed to be 1.0). Examples: ex.push_features('x', ['a', 'b']) ex.push_features('y', [('c', 1.), 'd']) space_hash = vw.hash_space( 'x' ) feat_hash = vw.hash_feature( 'a', space_hash ) ex.push_features('x', [feat_hash]) # note: 'x' should match the space_hash! """ ns = self.get_ns(ns) self.ensure_namespace_exists(ns) self.push_feature_list(self.vw, ns.ord_ns, featureList) # much faster just to do it in C++ # ns_hash = self.vw.hash_space( ns.ns ) # for feature in featureList: # if isinstance(feature, int) or isinstance(feature, str): # f = feature # v = 1. # elif isinstance(feature, tuple) and len(feature) == 2 and (isinstance(feature[0], int) or isinstance(feature[0], str)) and (isinstance(feature[1], int) or isinstance(feature[1], float)): # f = feature[0] # v = feature[1] # else: # raise Exception('malformed feature to push of type: ' + str(type(feature))) # self.push_feature(ns, f, v, ns_hash) def finish(self): """Tell VW that you're done with this example and it can recycle it for later use.""" if not self.finished: self.vw.finish_example(self) self.finished = True def iter_features(self): """Iterate over all feature/value pairs in this example (all namespace included).""" for ns_id in range( self.num_namespaces() ): # iterate over every namespace ns = self.get_ns(ns_id) for i in range(self.num_features_in(ns)): f = self.feature(ns, i) v = self.feature_weight(ns, i) yield f,v def get_label(self, label_class=simple_label): """Given a known label class (default is simple_label), get the corresponding label structure for this example.""" return label_class(self) #help(example)
{ "content_hash": "d744e9b7876caf257b6723a2ff73d897", "timestamp": "", "source": "github", "line_count": 630, "max_line_length": 238, "avg_line_length": 42.7984126984127, "alnum_prop": 0.5860252939212995, "repo_name": "hhexiy/vowpal_wabbit", "id": "0d3d26f8858a1cb4095b12df39827f862bbe2474", "size": "26963", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/pyvw.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "2978" }, { "name": "C", "bytes": "9908" }, { "name": "C#", "bytes": "53806" }, { "name": "C++", "bytes": "1090971" }, { "name": "Eagle", "bytes": "99" }, { "name": "HTML", "bytes": "13166" }, { "name": "Java", "bytes": "17304" }, { "name": "Makefile", "bytes": "85180" }, { "name": "Perl", "bytes": "134884" }, { "name": "Python", "bytes": "64843" }, { "name": "R", "bytes": "14865" }, { "name": "Ruby", "bytes": "5219" }, { "name": "Shell", "bytes": "45086" }, { "name": "Tcl", "bytes": "182" } ], "symlink_target": "" }
import sys from PyQt4 import QtGui, QtCore from mainwindowpyqt4 import Ui_MainWindow class MainWindow(QtGui.QMainWindow): ### functions for the buttons to call def pressedOnButton(self): print ("Pressed On!") def pressedOffButton(self): print ("Pressed Off!") def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) ### Hooks to for buttons self.ui.pushButtonOn.clicked.connect(lambda: self.pressedOnButton()) self.ui.pushButtonOff.clicked.connect(lambda: self.pressedOffButton()) # go on setting up your handlers like: # self.ui.okButton.clicked.connect(function_name) # etc... def main(): app = QtGui.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
{ "content_hash": "9d2884b16d1c037347a8bb160c883dec", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 78, "avg_line_length": 27.21212121212121, "alnum_prop": 0.6202672605790646, "repo_name": "shinichiba/YamadaLabSkinFrictionR7", "id": "ccb0bc71879219393292c9ff0b9108ecf453af8a", "size": "898", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mainpyqt4pyuic4.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "14988" } ], "symlink_target": "" }
import factory import factory.fuzzy from zeus import models from zeus.utils import timezone from .base import ModelFactory from .types import GUIDFactory class RepositoryFactory(ModelFactory): id = GUIDFactory() owner_name = factory.Faker("word") name = factory.Faker("word") url = factory.LazyAttribute( lambda o: "git@github.com:%s/%s.git" % (o.owner_name, o.name) ) backend = models.RepositoryBackend.git status = models.RepositoryStatus.active provider = models.RepositoryProvider.github external_id = factory.LazyAttribute(lambda o: "{}/{}".format(o.owner_name, o.name)) public = False date_created = factory.LazyAttribute(lambda o: timezone.now()) class Meta: model = models.Repository class Params: unknown = factory.Trait(backend=models.RepositoryBackend.unknown) github = factory.Trait( backend=models.RepositoryBackend.git, provider=models.RepositoryProvider.github, external_id=factory.LazyAttribute( lambda o: "{}/{}".format(o.owner_name, o.name) ), data=factory.LazyAttribute( lambda o: {"full_name": "{}/{}".format(o.owner_name, o.name)} ), )
{ "content_hash": "143032eefbe291fcd476b834d06b5cc9", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 87, "avg_line_length": 32.282051282051285, "alnum_prop": 0.6441620333598094, "repo_name": "getsentry/zeus", "id": "dddbb8a029ea98ed95361c9ac635b5509a0d90c5", "size": "1259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zeus/factories/repository.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3596" }, { "name": "HTML", "bytes": "13037" }, { "name": "JavaScript", "bytes": "327335" }, { "name": "Makefile", "bytes": "1130" }, { "name": "Mako", "bytes": "494" }, { "name": "Python", "bytes": "822392" }, { "name": "Shell", "bytes": "2564" } ], "symlink_target": "" }
from __future__ import absolute_import import copy import hashlib import re try: reduce except NameError: from functools import reduce from functools import partial from itertools import product from Cython.Utils import cached_function from .Code import UtilityCode, LazyUtilityCode, TempitaUtilityCode from . import StringEncoding from . import Naming from .Errors import error, CannotSpecialize class BaseType(object): # # Base class for all Cython types including pseudo-types. # List of attribute names of any subtypes subtypes = [] _empty_declaration = None _specialization_name = None default_format_spec = None def can_coerce_to_pyobject(self, env): return False def can_coerce_from_pyobject(self, env): return False def can_coerce_to_pystring(self, env, format_spec=None): return False def convert_to_pystring(self, cvalue, code, format_spec=None): raise NotImplementedError("C types that support string formatting must override this method") def cast_code(self, expr_code): return "((%s)%s)" % (self.empty_declaration_code(), expr_code) def empty_declaration_code(self, pyrex=False): if pyrex: return self.declaration_code('', pyrex=True) if self._empty_declaration is None: self._empty_declaration = self.declaration_code('') return self._empty_declaration def specialization_name(self): if self._specialization_name is None: # This is not entirely robust. common_subs = (self.empty_declaration_code() .replace("unsigned ", "unsigned_") .replace("long long", "long_long") .replace(" ", "__")) self._specialization_name = re.sub( '[^a-zA-Z0-9_]', lambda x: '_%x_' % ord(x.group(0)), common_subs) return self._specialization_name def base_declaration_code(self, base_code, entity_code): if entity_code: return "%s %s" % (base_code, entity_code) else: return base_code def __deepcopy__(self, memo): """ Types never need to be copied, if we do copy, Unfortunate Things Will Happen! """ return self def get_fused_types(self, result=None, seen=None, subtypes=None, include_function_return_type=False): subtypes = subtypes or self.subtypes if not subtypes: return None if result is None: result = [] seen = set() for attr in subtypes: list_or_subtype = getattr(self, attr) if list_or_subtype: if isinstance(list_or_subtype, BaseType): list_or_subtype.get_fused_types(result, seen, include_function_return_type=include_function_return_type) else: for subtype in list_or_subtype: subtype.get_fused_types(result, seen, include_function_return_type=include_function_return_type) return result def specialize_fused(self, env): if env.fused_to_specific: return self.specialize(env.fused_to_specific) return self @property def is_fused(self): """ Whether this type or any of its subtypes is a fused type """ # Add this indirection for the is_fused property to allow overriding # get_fused_types in subclasses. return self.get_fused_types() def deduce_template_params(self, actual): """ Deduce any template params in this (argument) type given the actual argument type. https://en.cppreference.com/w/cpp/language/function_template#Template_argument_deduction """ return {} def __lt__(self, other): """ For sorting. The sorting order should correspond to the preference of conversion from Python types. Override to provide something sensible. This is only implemented so that python 3 doesn't trip """ return id(type(self)) < id(type(other)) def py_type_name(self): """ Return the name of the Python type that can coerce to this type. """ def typeof_name(self): """ Return the string with which fused python functions can be indexed. """ if self.is_builtin_type or self.py_type_name() == 'object': index_name = self.py_type_name() else: index_name = str(self) return index_name def check_for_null_code(self, cname): """ Return the code for a NULL-check in case an UnboundLocalError should be raised if an entry of this type is referenced before assignment. Returns None if no check should be performed. """ return None def invalid_value(self): """ Returns the most invalid value an object of this type can assume as a C expression string. Returns None if no such value exists. """ class PyrexType(BaseType): # # Base class for all Cython types # # is_pyobject boolean Is a Python object type # is_extension_type boolean Is a Python extension type # is_final_type boolean Is a final extension type # is_numeric boolean Is a C numeric type # is_int boolean Is a C integer type # is_float boolean Is a C floating point type # is_complex boolean Is a C complex type # is_void boolean Is the C void type # is_array boolean Is a C array type # is_ptr boolean Is a C pointer type # is_null_ptr boolean Is the type of NULL # is_reference boolean Is a C reference type # is_rvalue_reference boolean Is a C++ rvalue reference type # is_const boolean Is a C const type # is_volatile boolean Is a C volatile type # is_cv_qualified boolean Is a C const or volatile type # is_cfunction boolean Is a C function type # is_struct_or_union boolean Is a C struct or union type # is_struct boolean Is a C struct type # is_cpp_class boolean Is a C++ class # is_optional_cpp_class boolean Is a C++ class with variable lifetime handled with std::optional # is_enum boolean Is a C enum type # is_cpp_enum boolean Is a C++ scoped enum type # is_typedef boolean Is a typedef type # is_string boolean Is a C char * type # is_pyunicode_ptr boolean Is a C PyUNICODE * type # is_cpp_string boolean Is a C++ std::string type # python_type_constructor_name string or None non-None if it is a Python type constructor that can be indexed/"templated" # is_unicode_char boolean Is either Py_UCS4 or Py_UNICODE # is_returncode boolean Is used only to signal exceptions # is_error boolean Is the dummy error type # is_buffer boolean Is buffer access type # is_pythran_expr boolean Is Pythran expr # is_numpy_buffer boolean Is Numpy array buffer # has_attributes boolean Has C dot-selectable attributes # needs_cpp_construction boolean Needs C++ constructor and destructor when used in a cdef class # needs_refcounting boolean Needs code to be generated similar to incref/gotref/decref. # Largely used internally. # equivalent_type type A C or Python type that is equivalent to this Python or C type. # default_value string Initial value that can be assigned before first user assignment. # declaration_value string The value statically assigned on declaration (if any). # entry Entry The Entry for this type # # declaration_code(entity_code, # for_display = 0, dll_linkage = None, pyrex = 0) # Returns a code fragment for the declaration of an entity # of this type, given a code fragment for the entity. # * If for_display, this is for reading by a human in an error # message; otherwise it must be valid C code. # * If dll_linkage is not None, it must be 'DL_EXPORT' or # 'DL_IMPORT', and will be added to the base type part of # the declaration. # * If pyrex = 1, this is for use in a 'cdef extern' # statement of a Cython include file. # # assignable_from(src_type) # Tests whether a variable of this type can be # assigned a value of type src_type. # # same_as(other_type) # Tests whether this type represents the same type # as other_type. # # as_argument_type(): # Coerces array and C function types into pointer type for use as # a formal argument type. # is_pyobject = 0 is_unspecified = 0 is_extension_type = 0 is_final_type = 0 is_builtin_type = 0 is_cython_builtin_type = 0 is_numeric = 0 is_int = 0 is_float = 0 is_complex = 0 is_void = 0 is_array = 0 is_ptr = 0 is_null_ptr = 0 is_reference = 0 is_fake_reference = 0 is_rvalue_reference = 0 is_const = 0 is_volatile = 0 is_cv_qualified = 0 is_cfunction = 0 is_struct_or_union = 0 is_cpp_class = 0 is_optional_cpp_class = 0 python_type_constructor_name = None is_cpp_string = 0 is_struct = 0 is_enum = 0 is_cpp_enum = False is_typedef = 0 is_string = 0 is_pyunicode_ptr = 0 is_unicode_char = 0 is_returncode = 0 is_error = 0 is_buffer = 0 is_ctuple = 0 is_memoryviewslice = 0 is_pythran_expr = 0 is_numpy_buffer = 0 has_attributes = 0 needs_cpp_construction = 0 needs_refcounting = 0 equivalent_type = None default_value = "" declaration_value = "" def resolve(self): # If a typedef, returns the base type. return self def specialize(self, values): # Returns the concrete type if this is a fused type, or otherwise the type itself. # May raise Errors.CannotSpecialize on failure return self def literal_code(self, value): # Returns a C code fragment representing a literal # value of this type. return str(value) def __str__(self): return self.declaration_code("", for_display = 1).strip() def same_as(self, other_type, **kwds): return self.same_as_resolved_type(other_type.resolve(), **kwds) def same_as_resolved_type(self, other_type): return self == other_type or other_type is error_type def subtype_of(self, other_type): return self.subtype_of_resolved_type(other_type.resolve()) def subtype_of_resolved_type(self, other_type): return self.same_as(other_type) def assignable_from(self, src_type): return self.assignable_from_resolved_type(src_type.resolve()) def assignable_from_resolved_type(self, src_type): return self.same_as(src_type) def as_argument_type(self): return self def is_complete(self): # A type is incomplete if it is an unsized array, # a struct whose attributes are not defined, etc. return 1 def is_simple_buffer_dtype(self): return (self.is_int or self.is_float or self.is_complex or self.is_pyobject or self.is_extension_type or self.is_ptr) def struct_nesting_depth(self): # Returns the number levels of nested structs. This is # used for constructing a stack for walking the run-time # type information of the struct. return 1 def global_init_code(self, entry, code): # abstract pass def needs_nonecheck(self): return 0 def _assign_from_py_code(self, source_code, result_code, error_pos, code, from_py_function=None, error_condition=None, extra_args=None, special_none_cvalue=None): args = ', ' + ', '.join('%s' % arg for arg in extra_args) if extra_args else '' convert_call = "%s(%s%s)" % ( from_py_function or self.from_py_function, source_code, args, ) if self.is_enum: convert_call = typecast(self, c_long_type, convert_call) if special_none_cvalue: # NOTE: requires 'source_code' to be simple! convert_call = "(__Pyx_Py_IsNone(%s) ? (%s) : (%s))" % ( source_code, special_none_cvalue, convert_call) return '%s = %s; %s' % ( result_code, convert_call, code.error_goto_if(error_condition or self.error_condition(result_code), error_pos)) def _generate_dummy_refcounting(self, code, *ignored_args, **ignored_kwds): if self.needs_refcounting: raise NotImplementedError("Ref-counting operation not yet implemented for type %s" % self) def _generate_dummy_refcounting_assignment(self, code, cname, rhs_cname, *ignored_args, **ignored_kwds): if self.needs_refcounting: raise NotImplementedError("Ref-counting operation not yet implemented for type %s" % self) code.putln("%s = %s" % (cname, rhs_cname)) generate_incref = generate_xincref = generate_decref = generate_xdecref \ = generate_decref_clear = generate_xdecref_clear \ = generate_gotref = generate_xgotref = generate_giveref = generate_xgiveref \ = _generate_dummy_refcounting generate_decref_set = generate_xdecref_set = _generate_dummy_refcounting_assignment def nullcheck_string(self, code, cname): if self.needs_refcounting: raise NotImplementedError("Ref-counting operation not yet implemented for type %s" % self) code.putln("1") def cpp_optional_declaration_code(self, entity_code, dll_linkage=None): # declares an std::optional c++ variable raise NotImplementedError( "cpp_optional_declaration_code only implemented for c++ classes and not type %s" % self) def public_decl(base_code, dll_linkage): if dll_linkage: return "%s(%s)" % (dll_linkage, base_code.replace(',', ' __PYX_COMMA ')) else: return base_code def create_typedef_type(name, base_type, cname, is_external=0, namespace=None): if is_external: if base_type.is_complex or base_type.is_fused: raise ValueError("%s external typedefs not supported" % ( "Fused" if base_type.is_fused else "Complex")) if base_type.is_complex or base_type.is_fused: return base_type return CTypedefType(name, base_type, cname, is_external, namespace) class CTypedefType(BaseType): # # Pseudo-type defined with a ctypedef statement in a # 'cdef extern from' block. # Delegates most attribute lookups to the base type. # (Anything not defined here or in the BaseType is delegated.) # # qualified_name string # typedef_name string # typedef_cname string # typedef_base_type PyrexType # typedef_is_external bool is_typedef = 1 typedef_is_external = 0 to_py_utility_code = None from_py_utility_code = None subtypes = ['typedef_base_type'] def __init__(self, name, base_type, cname, is_external=0, namespace=None): assert not base_type.is_complex self.typedef_name = name self.typedef_cname = cname self.typedef_base_type = base_type self.typedef_is_external = is_external self.typedef_namespace = namespace def invalid_value(self): return self.typedef_base_type.invalid_value() def resolve(self): return self.typedef_base_type.resolve() def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: base_code = self.typedef_name else: base_code = public_decl(self.typedef_cname, dll_linkage) if self.typedef_namespace is not None and not pyrex: base_code = "%s::%s" % (self.typedef_namespace.empty_declaration_code(), base_code) return self.base_declaration_code(base_code, entity_code) def as_argument_type(self): return self def cast_code(self, expr_code): # If self is really an array (rather than pointer), we can't cast. # For example, the gmp mpz_t. if self.typedef_base_type.is_array: base_type = self.typedef_base_type.base_type return CPtrType(base_type).cast_code(expr_code) else: return BaseType.cast_code(self, expr_code) def specialize(self, values): base_type = self.typedef_base_type.specialize(values) namespace = self.typedef_namespace.specialize(values) if self.typedef_namespace else None if base_type is self.typedef_base_type and namespace is self.typedef_namespace: return self else: return create_typedef_type(self.typedef_name, base_type, self.typedef_cname, 0, namespace) def __repr__(self): return "<CTypedefType %s>" % self.typedef_cname def __str__(self): return self.typedef_name def _create_utility_code(self, template_utility_code, template_function_name): type_name = type_identifier(self.typedef_cname) utility_code = template_utility_code.specialize( type = self.typedef_cname, TypeName = type_name) function_name = template_function_name % type_name return utility_code, function_name def create_to_py_utility_code(self, env): if self.typedef_is_external: if not self.to_py_utility_code: base_type = self.typedef_base_type if type(base_type) is CIntType: self.to_py_function = "__Pyx_PyInt_From_" + self.specialization_name() env.use_utility_code(TempitaUtilityCode.load_cached( "CIntToPy", "TypeConversion.c", context={"TYPE": self.empty_declaration_code(), "TO_PY_FUNCTION": self.to_py_function})) return True elif base_type.is_float: pass # XXX implement! elif base_type.is_complex: pass # XXX implement! pass elif base_type.is_cpp_string: cname = "__pyx_convert_PyObject_string_to_py_%s" % type_identifier(self) context = { 'cname': cname, 'type': self.typedef_cname, } from .UtilityCode import CythonUtilityCode env.use_utility_code(CythonUtilityCode.load( "string.to_py", "CppConvert.pyx", context=context)) self.to_py_function = cname return True if self.to_py_utility_code: env.use_utility_code(self.to_py_utility_code) return True # delegation return self.typedef_base_type.create_to_py_utility_code(env) def create_from_py_utility_code(self, env): if self.typedef_is_external: if not self.from_py_utility_code: base_type = self.typedef_base_type if type(base_type) is CIntType: self.from_py_function = "__Pyx_PyInt_As_" + self.specialization_name() env.use_utility_code(TempitaUtilityCode.load_cached( "CIntFromPy", "TypeConversion.c", context={"TYPE": self.empty_declaration_code(), "FROM_PY_FUNCTION": self.from_py_function})) return True elif base_type.is_float: pass # XXX implement! elif base_type.is_complex: pass # XXX implement! elif base_type.is_cpp_string: cname = '__pyx_convert_string_from_py_%s' % type_identifier(self) context = { 'cname': cname, 'type': self.typedef_cname, } from .UtilityCode import CythonUtilityCode env.use_utility_code(CythonUtilityCode.load( "string.from_py", "CppConvert.pyx", context=context)) self.from_py_function = cname return True if self.from_py_utility_code: env.use_utility_code(self.from_py_utility_code) return True # delegation return self.typedef_base_type.create_from_py_utility_code(env) def to_py_call_code(self, source_code, result_code, result_type, to_py_function=None): if to_py_function is None: to_py_function = self.to_py_function return self.typedef_base_type.to_py_call_code( source_code, result_code, result_type, to_py_function) def from_py_call_code(self, source_code, result_code, error_pos, code, from_py_function=None, error_condition=None, special_none_cvalue=None): return self.typedef_base_type.from_py_call_code( source_code, result_code, error_pos, code, from_py_function or self.from_py_function, error_condition or self.error_condition(result_code), special_none_cvalue=special_none_cvalue, ) def overflow_check_binop(self, binop, env, const_rhs=False): env.use_utility_code(UtilityCode.load("Common", "Overflow.c")) type = self.empty_declaration_code() name = self.specialization_name() if binop == "lshift": env.use_utility_code(TempitaUtilityCode.load_cached( "LeftShift", "Overflow.c", context={'TYPE': type, 'NAME': name, 'SIGNED': self.signed})) else: if const_rhs: binop += "_const" _load_overflow_base(env) env.use_utility_code(TempitaUtilityCode.load_cached( "SizeCheck", "Overflow.c", context={'TYPE': type, 'NAME': name})) env.use_utility_code(TempitaUtilityCode.load_cached( "Binop", "Overflow.c", context={'TYPE': type, 'NAME': name, 'BINOP': binop})) return "__Pyx_%s_%s_checking_overflow" % (binop, name) def error_condition(self, result_code): if self.typedef_is_external: if self.exception_value: condition = "(%s == %s)" % ( result_code, self.cast_code(self.exception_value)) if self.exception_check: condition += " && PyErr_Occurred()" return condition # delegation return self.typedef_base_type.error_condition(result_code) def __getattr__(self, name): return getattr(self.typedef_base_type, name) def py_type_name(self): return self.typedef_base_type.py_type_name() def can_coerce_to_pyobject(self, env): return self.typedef_base_type.can_coerce_to_pyobject(env) def can_coerce_from_pyobject(self, env): return self.typedef_base_type.can_coerce_from_pyobject(env) class MemoryViewSliceType(PyrexType): is_memoryviewslice = 1 default_value = "{ 0, 0, { 0 }, { 0 }, { 0 } }" has_attributes = 1 needs_refcounting = 1 # Ideally this would be true and reference counting for # memoryview and pyobject code could be generated in the same way. # However, memoryviews are sufficiently specialized that this doesn't # seem practical. Implement a limited version of it for now scope = None # These are special cased in Defnode from_py_function = None to_py_function = None exception_value = None exception_check = True subtypes = ['dtype'] def __init__(self, base_dtype, axes): """ MemoryViewSliceType(base, axes) Base is the C base type; axes is a list of (access, packing) strings, where access is one of 'full', 'direct' or 'ptr' and packing is one of 'contig', 'strided' or 'follow'. There is one (access, packing) tuple for each dimension. the access specifiers determine whether the array data contains pointers that need to be dereferenced along that axis when retrieving/setting: 'direct' -- No pointers stored in this dimension. 'ptr' -- Pointer stored in this dimension. 'full' -- Check along this dimension, don't assume either. the packing specifiers specify how the array elements are laid-out in memory. 'contig' -- The data is contiguous in memory along this dimension. At most one dimension may be specified as 'contig'. 'strided' -- The data isn't contiguous along this dimension. 'follow' -- Used for C/Fortran contiguous arrays, a 'follow' dimension has its stride automatically computed from extents of the other dimensions to ensure C or Fortran memory layout. C-contiguous memory has 'direct' as the access spec, 'contig' as the *last* axis' packing spec and 'follow' for all other packing specs. Fortran-contiguous memory has 'direct' as the access spec, 'contig' as the *first* axis' packing spec and 'follow' for all other packing specs. """ from . import Buffer, MemoryView self.dtype = base_dtype self.axes = axes self.ndim = len(axes) self.flags = MemoryView.get_buf_flags(self.axes) self.is_c_contig, self.is_f_contig = MemoryView.is_cf_contig(self.axes) assert not (self.is_c_contig and self.is_f_contig) self.mode = MemoryView.get_mode(axes) self.writable_needed = False if not self.dtype.is_fused: self.dtype_name = Buffer.mangle_dtype_name(self.dtype) def __hash__(self): return hash(self.__class__) ^ hash(self.dtype) ^ hash(tuple(self.axes)) def __eq__(self, other): if isinstance(other, BaseType): return self.same_as_resolved_type(other) else: return False def __ne__(self, other): # TODO drop when Python2 is dropped return not (self == other) def same_as_resolved_type(self, other_type): return ((other_type.is_memoryviewslice and #self.writable_needed == other_type.writable_needed and # FIXME: should be only uni-directional self.dtype.same_as(other_type.dtype) and self.axes == other_type.axes) or other_type is error_type) def needs_nonecheck(self): return True def is_complete(self): # incomplete since the underlying struct doesn't have a cython.memoryview object. return 0 def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): # XXX: we put these guards in for now... assert not dll_linkage from . import MemoryView base_code = StringEncoding.EncodedString( str(self) if pyrex or for_display else MemoryView.memviewslice_cname) return self.base_declaration_code( base_code, entity_code) def attributes_known(self): if self.scope is None: from . import Symtab self.scope = scope = Symtab.CClassScope( 'mvs_class_'+self.specialization_suffix(), None, visibility='extern') scope.parent_type = self scope.directives = {} scope.declare_var('_data', c_char_ptr_type, None, cname='data', is_cdef=1) return True def declare_attribute(self, attribute, env, pos): from . import MemoryView, Options scope = self.scope if attribute == 'shape': scope.declare_var('shape', c_array_type(c_py_ssize_t_type, Options.buffer_max_dims), pos, cname='shape', is_cdef=1) elif attribute == 'strides': scope.declare_var('strides', c_array_type(c_py_ssize_t_type, Options.buffer_max_dims), pos, cname='strides', is_cdef=1) elif attribute == 'suboffsets': scope.declare_var('suboffsets', c_array_type(c_py_ssize_t_type, Options.buffer_max_dims), pos, cname='suboffsets', is_cdef=1) elif attribute in ("copy", "copy_fortran"): ndim = len(self.axes) follow_dim = [('direct', 'follow')] contig_dim = [('direct', 'contig')] to_axes_c = follow_dim * (ndim - 1) + contig_dim to_axes_f = contig_dim + follow_dim * (ndim -1) dtype = self.dtype if dtype.is_cv_qualified: dtype = dtype.cv_base_type to_memview_c = MemoryViewSliceType(dtype, to_axes_c) to_memview_f = MemoryViewSliceType(dtype, to_axes_f) for to_memview, cython_name in [(to_memview_c, "copy"), (to_memview_f, "copy_fortran")]: copy_func_type = CFuncType( to_memview, [CFuncTypeArg("memviewslice", self, None)]) copy_cname = MemoryView.copy_c_or_fortran_cname(to_memview) entry = scope.declare_cfunction( cython_name, copy_func_type, pos=pos, defining=1, cname=copy_cname) utility = MemoryView.get_copy_new_utility(pos, self, to_memview) env.use_utility_code(utility) MemoryView.use_cython_array_utility_code(env) elif attribute in ("is_c_contig", "is_f_contig"): # is_c_contig and is_f_contig functions for (c_or_f, cython_name) in (('C', 'is_c_contig'), ('F', 'is_f_contig')): is_contig_name = MemoryView.get_is_contig_func_name(c_or_f, self.ndim) cfunctype = CFuncType( return_type=c_bint_type, args=[CFuncTypeArg("memviewslice", self, None)], exception_value="-1", ) entry = scope.declare_cfunction(cython_name, cfunctype, pos=pos, defining=1, cname=is_contig_name) entry.utility_code_definition = MemoryView.get_is_contig_utility(c_or_f, self.ndim) return True def get_entry(self, node, cname=None, type=None): from . import MemoryView, Symtab if cname is None: assert node.is_simple() or node.is_temp or node.is_elemental cname = node.result() if type is None: type = node.type entry = Symtab.Entry(cname, cname, type, node.pos) return MemoryView.MemoryViewSliceBufferEntry(entry) def conforms_to(self, dst, broadcast=False, copying=False): """ Returns True if src conforms to dst, False otherwise. If conformable, the types are the same, the ndims are equal, and each axis spec is conformable. Any packing/access spec is conformable to itself. 'direct' and 'ptr' are conformable to 'full'. 'contig' and 'follow' are conformable to 'strided'. Any other combo is not conformable. """ from . import MemoryView src = self #if not copying and self.writable_needed and not dst.writable_needed: # return False src_dtype, dst_dtype = src.dtype, dst.dtype # We can add but not remove const/volatile modifiers # (except if we are copying by value, then anything is fine) if not copying: if src_dtype.is_const and not dst_dtype.is_const: return False if src_dtype.is_volatile and not dst_dtype.is_volatile: return False # const/volatile checks are done, remove those qualifiers if src_dtype.is_cv_qualified: src_dtype = src_dtype.cv_base_type if dst_dtype.is_cv_qualified: dst_dtype = dst_dtype.cv_base_type if src_dtype != dst_dtype: return False if src.ndim != dst.ndim: if broadcast: src, dst = MemoryView.broadcast_types(src, dst) else: return False for src_spec, dst_spec in zip(src.axes, dst.axes): src_access, src_packing = src_spec dst_access, dst_packing = dst_spec if src_access != dst_access and dst_access != 'full': return False if src_packing != dst_packing and dst_packing != 'strided' and not copying: return False return True def valid_dtype(self, dtype, i=0): """ Return whether type dtype can be used as the base type of a memoryview slice. We support structs, numeric types and objects """ if dtype.is_complex and dtype.real_type.is_int: return False if dtype.is_struct and dtype.kind == 'struct': for member in dtype.scope.var_entries: if not self.valid_dtype(member.type): return False return True return ( dtype.is_error or # Pointers are not valid (yet) # (dtype.is_ptr and valid_memslice_dtype(dtype.base_type)) or (dtype.is_array and i < 8 and self.valid_dtype(dtype.base_type, i + 1)) or dtype.is_numeric or dtype.is_pyobject or dtype.is_fused or # accept this as it will be replaced by specializations later (dtype.is_typedef and self.valid_dtype(dtype.typedef_base_type)) ) def validate_memslice_dtype(self, pos): if not self.valid_dtype(self.dtype): error(pos, "Invalid base type for memoryview slice: %s" % self.dtype) def assert_direct_dims(self, pos): for access, packing in self.axes: if access != 'direct': error(pos, "All dimensions must be direct") return False return True def transpose(self, pos): if not self.assert_direct_dims(pos): return error_type return MemoryViewSliceType(self.dtype, self.axes[::-1]) def specialization_name(self): return '%s_%s' % ( super(MemoryViewSliceType,self).specialization_name(), self.specialization_suffix()) def specialization_suffix(self): return "%s_%s" % (self.axes_to_name(), self.dtype_name) def can_coerce_to_pyobject(self, env): return True def can_coerce_from_pyobject(self, env): return True def check_for_null_code(self, cname): return cname + '.memview' def create_from_py_utility_code(self, env): from . import MemoryView, Buffer # We don't have 'code', so use a LazyUtilityCode with a callback. def lazy_utility_callback(code): context['dtype_typeinfo'] = Buffer.get_type_information_cname(code, self.dtype) return TempitaUtilityCode.load( "ObjectToMemviewSlice", "MemoryView_C.c", context=context) env.use_utility_code(MemoryView.memviewslice_init_code) env.use_utility_code(LazyUtilityCode(lazy_utility_callback)) if self.is_c_contig: c_or_f_flag = "__Pyx_IS_C_CONTIG" elif self.is_f_contig: c_or_f_flag = "__Pyx_IS_F_CONTIG" else: c_or_f_flag = "0" suffix = self.specialization_suffix() funcname = "__Pyx_PyObject_to_MemoryviewSlice_" + suffix context = dict( MemoryView.context, buf_flag = self.flags, ndim = self.ndim, axes_specs = ', '.join(self.axes_to_code()), dtype_typedecl = self.dtype.empty_declaration_code(), struct_nesting_depth = self.dtype.struct_nesting_depth(), c_or_f_flag = c_or_f_flag, funcname = funcname, ) self.from_py_function = funcname return True def from_py_call_code(self, source_code, result_code, error_pos, code, from_py_function=None, error_condition=None, special_none_cvalue=None): # NOTE: auto-detection of readonly buffers is disabled: # writable = self.writable_needed or not self.dtype.is_const writable = not self.dtype.is_const return self._assign_from_py_code( source_code, result_code, error_pos, code, from_py_function, error_condition, extra_args=['PyBUF_WRITABLE' if writable else '0'], special_none_cvalue=special_none_cvalue, ) def create_to_py_utility_code(self, env): self._dtype_to_py_func, self._dtype_from_py_func = self.dtype_object_conversion_funcs(env) return True def to_py_call_code(self, source_code, result_code, result_type, to_py_function=None): assert self._dtype_to_py_func assert self._dtype_from_py_func to_py_func = "(PyObject *(*)(char *)) " + self._dtype_to_py_func from_py_func = "(int (*)(char *, PyObject *)) " + self._dtype_from_py_func tup = (result_code, source_code, self.ndim, to_py_func, from_py_func, self.dtype.is_pyobject) return "%s = __pyx_memoryview_fromslice(%s, %s, %s, %s, %d);" % tup def dtype_object_conversion_funcs(self, env): get_function = "__pyx_memview_get_%s" % self.dtype_name set_function = "__pyx_memview_set_%s" % self.dtype_name context = dict( get_function = get_function, set_function = set_function, ) if self.dtype.is_pyobject: utility_name = "MemviewObjectToObject" else: self.dtype.create_to_py_utility_code(env) to_py_function = self.dtype.to_py_function from_py_function = None if not self.dtype.is_const: self.dtype.create_from_py_utility_code(env) from_py_function = self.dtype.from_py_function if not (to_py_function or from_py_function): return "NULL", "NULL" if not to_py_function: get_function = "NULL" if not from_py_function: set_function = "NULL" utility_name = "MemviewDtypeToObject" error_condition = (self.dtype.error_condition('value') or 'PyErr_Occurred()') context.update( to_py_function=to_py_function, from_py_function=from_py_function, dtype=self.dtype.empty_declaration_code(), error_condition=error_condition, ) utility = TempitaUtilityCode.load_cached( utility_name, "MemoryView_C.c", context=context) env.use_utility_code(utility) return get_function, set_function def axes_to_code(self): """Return a list of code constants for each axis""" from . import MemoryView d = MemoryView._spec_to_const return ["(%s | %s)" % (d[a], d[p]) for a, p in self.axes] def axes_to_name(self): """Return an abbreviated name for our axes""" from . import MemoryView d = MemoryView._spec_to_abbrev return "".join(["%s%s" % (d[a], d[p]) for a, p in self.axes]) def error_condition(self, result_code): return "!%s.memview" % result_code def __str__(self): from . import MemoryView axes_code_list = [] for idx, (access, packing) in enumerate(self.axes): flag = MemoryView.get_memoryview_flag(access, packing) if flag == "strided": axes_code_list.append(":") else: if flag == 'contiguous': have_follow = [p for a, p in self.axes[idx - 1:idx + 2] if p == 'follow'] if have_follow or self.ndim == 1: flag = '1' axes_code_list.append("::" + flag) if self.dtype.is_pyobject: dtype_name = self.dtype.name else: dtype_name = self.dtype return "%s[%s]" % (dtype_name, ", ".join(axes_code_list)) def specialize(self, values): """This does not validate the base type!!""" dtype = self.dtype.specialize(values) if dtype is not self.dtype: return MemoryViewSliceType(dtype, self.axes) return self def cast_code(self, expr_code): return expr_code # When memoryviews are increfed currently seems heavily special-cased. # Therefore, use our own function for now def generate_incref(self, code, name, **kwds): pass def generate_incref_memoryviewslice(self, code, slice_cname, have_gil): # TODO ideally would be done separately code.putln("__PYX_INC_MEMVIEW(&%s, %d);" % (slice_cname, int(have_gil))) # decref however did look to always apply for memoryview slices # with "have_gil" set to True by default def generate_xdecref(self, code, cname, nanny, have_gil): code.putln("__PYX_XCLEAR_MEMVIEW(&%s, %d);" % (cname, int(have_gil))) def generate_decref(self, code, cname, nanny, have_gil): # Fall back to xdecref since we don't care to have a separate decref version for this. self.generate_xdecref(code, cname, nanny, have_gil) def generate_xdecref_clear(self, code, cname, clear_before_decref, **kwds): self.generate_xdecref(code, cname, **kwds) code.putln("%s.memview = NULL; %s.data = NULL;" % (cname, cname)) def generate_decref_clear(self, code, cname, **kwds): # memoryviews don't currently distinguish between xdecref and decref self.generate_xdecref_clear(code, cname, **kwds) # memoryviews don't participate in giveref/gotref generate_gotref = generate_xgotref = generate_xgiveref = generate_giveref = lambda *args: None class BufferType(BaseType): # # Delegates most attribute lookups to the base type. # (Anything not defined here or in the BaseType is delegated.) # # dtype PyrexType # ndim int # mode str # negative_indices bool # cast bool # is_buffer bool # writable bool is_buffer = 1 writable = True subtypes = ['dtype'] def __init__(self, base, dtype, ndim, mode, negative_indices, cast): self.base = base self.dtype = dtype self.ndim = ndim self.buffer_ptr_type = CPtrType(dtype) self.mode = mode self.negative_indices = negative_indices self.cast = cast self.is_numpy_buffer = self.base.name == "ndarray" def can_coerce_to_pyobject(self,env): return True def can_coerce_from_pyobject(self,env): return True def as_argument_type(self): return self def specialize(self, values): dtype = self.dtype.specialize(values) if dtype is not self.dtype: return BufferType(self.base, dtype, self.ndim, self.mode, self.negative_indices, self.cast) return self def get_entry(self, node): from . import Buffer assert node.is_name return Buffer.BufferEntry(node.entry) def __getattr__(self, name): return getattr(self.base, name) def __repr__(self): return "<BufferType %r>" % self.base def __str__(self): # avoid ', ', as fused functions split the signature string on ', ' cast_str = '' if self.cast: cast_str = ',cast=True' return "%s[%s,ndim=%d%s]" % (self.base, self.dtype, self.ndim, cast_str) def assignable_from(self, other_type): if other_type.is_buffer: return (self.same_as(other_type, compare_base=False) and self.base.assignable_from(other_type.base)) return self.base.assignable_from(other_type) def same_as(self, other_type, compare_base=True): if not other_type.is_buffer: return other_type.same_as(self.base) return (self.dtype.same_as(other_type.dtype) and self.ndim == other_type.ndim and self.mode == other_type.mode and self.cast == other_type.cast and (not compare_base or self.base.same_as(other_type.base))) class PyObjectType(PyrexType): # # Base class for all Python object types (reference-counted). # # buffer_defaults dict or None Default options for bu name = "object" is_pyobject = 1 default_value = "0" declaration_value = "0" buffer_defaults = None is_extern = False is_subclassed = False is_gc_simple = False builtin_trashcan = False # builtin type using trashcan needs_refcounting = True def __str__(self): return "Python object" def __repr__(self): return "<PyObjectType>" def can_coerce_to_pyobject(self, env): return True def can_coerce_from_pyobject(self, env): return True def default_coerced_ctype(self): """The default C type that this Python type coerces to, or None.""" return None def assignable_from(self, src_type): # except for pointers, conversion will be attempted return not src_type.is_ptr or src_type.is_string or src_type.is_pyunicode_ptr def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: base_code = "object" else: base_code = public_decl("PyObject", dll_linkage) entity_code = "*%s" % entity_code return self.base_declaration_code(base_code, entity_code) def as_pyobject(self, cname): if (not self.is_complete()) or self.is_extension_type: return "(PyObject *)" + cname else: return cname def py_type_name(self): return "object" def __lt__(self, other): """ Make sure we sort highest, as instance checking on py_type_name ('object') is always true """ return False def global_init_code(self, entry, code): code.put_init_var_to_py_none(entry, nanny=False) def check_for_null_code(self, cname): return cname def generate_incref(self, code, cname, nanny): if nanny: code.putln("__Pyx_INCREF(%s);" % self.as_pyobject(cname)) else: code.putln("Py_INCREF(%s);" % self.as_pyobject(cname)) def generate_xincref(self, code, cname, nanny): if nanny: code.putln("__Pyx_XINCREF(%s);" % self.as_pyobject(cname)) else: code.putln("Py_XINCREF(%s);" % self.as_pyobject(cname)) def generate_decref(self, code, cname, nanny, have_gil): # have_gil is for the benefit of memoryviewslice - it's ignored here assert have_gil self._generate_decref(code, cname, nanny, null_check=False, clear=False) def generate_xdecref(self, code, cname, nanny, have_gil): # in this (and other) PyObjectType functions, have_gil is being # passed to provide a common interface with MemoryviewSlice. # It's ignored here self._generate_decref(code, cname, nanny, null_check=True, clear=False) def generate_decref_clear(self, code, cname, clear_before_decref, nanny, have_gil): self._generate_decref(code, cname, nanny, null_check=False, clear=True, clear_before_decref=clear_before_decref) def generate_xdecref_clear(self, code, cname, clear_before_decref=False, nanny=True, have_gil=None): self._generate_decref(code, cname, nanny, null_check=True, clear=True, clear_before_decref=clear_before_decref) def generate_gotref(self, code, cname): code.putln("__Pyx_GOTREF(%s);" % self.as_pyobject(cname)) def generate_xgotref(self, code, cname): code.putln("__Pyx_XGOTREF(%s);" % self.as_pyobject(cname)) def generate_giveref(self, code, cname): code.putln("__Pyx_GIVEREF(%s);" % self.as_pyobject(cname)) def generate_xgiveref(self, code, cname): code.putln("__Pyx_XGIVEREF(%s);" % self.as_pyobject(cname)) def generate_decref_set(self, code, cname, rhs_cname): code.putln("__Pyx_DECREF_SET(%s, %s);" % (cname, rhs_cname)) def generate_xdecref_set(self, code, cname, rhs_cname): code.putln("__Pyx_XDECREF_SET(%s, %s);" % (cname, rhs_cname)) def _generate_decref(self, code, cname, nanny, null_check=False, clear=False, clear_before_decref=False): prefix = '__Pyx' if nanny else 'Py' X = 'X' if null_check else '' if clear: if clear_before_decref: if not nanny: X = '' # CPython doesn't have a Py_XCLEAR() code.putln("%s_%sCLEAR(%s);" % (prefix, X, cname)) else: code.putln("%s_%sDECREF(%s); %s = 0;" % ( prefix, X, self.as_pyobject(cname), cname)) else: code.putln("%s_%sDECREF(%s);" % ( prefix, X, self.as_pyobject(cname))) def nullcheck_string(self, cname): return cname builtin_types_that_cannot_create_refcycles = frozenset({ 'object', 'bool', 'int', 'long', 'float', 'complex', 'bytearray', 'bytes', 'unicode', 'str', 'basestring', }) builtin_types_with_trashcan = frozenset({ 'dict', 'list', 'set', 'frozenset', 'tuple', 'type', }) class BuiltinObjectType(PyObjectType): # objstruct_cname string Name of PyObject struct is_builtin_type = 1 has_attributes = 1 base_type = None module_name = '__builtin__' require_exact = 1 # fields that let it look like an extension type vtabslot_cname = None vtabstruct_cname = None vtabptr_cname = None typedef_flag = True is_external = True decl_type = 'PyObject' def __init__(self, name, cname, objstruct_cname=None): self.name = name self.cname = cname self.typeptr_cname = "(&%s)" % cname self.objstruct_cname = objstruct_cname self.is_gc_simple = name in builtin_types_that_cannot_create_refcycles self.builtin_trashcan = name in builtin_types_with_trashcan if name == 'type': # Special case the type type, as many C API calls (and other # libraries) actually expect a PyTypeObject* for type arguments. self.decl_type = objstruct_cname if name == 'Exception': self.require_exact = 0 def set_scope(self, scope): self.scope = scope if scope: scope.parent_type = self def __str__(self): return "%s object" % self.name def __repr__(self): return "<%s>"% self.cname def default_coerced_ctype(self): if self.name in ('bytes', 'bytearray'): return c_char_ptr_type elif self.name == 'bool': return c_bint_type elif self.name == 'float': return c_double_type return None def assignable_from(self, src_type): if isinstance(src_type, BuiltinObjectType): if self.name == 'basestring': return src_type.name in ('str', 'unicode', 'basestring') else: return src_type.name == self.name elif src_type.is_extension_type: # FIXME: This is an ugly special case that we currently # keep supporting. It allows users to specify builtin # types as external extension types, while keeping them # compatible with the real builtin types. We already # generate a warning for it. Big TODO: remove! return (src_type.module_name == '__builtin__' and src_type.name == self.name) else: return True def typeobj_is_available(self): return True def attributes_known(self): return True def subtype_of(self, type): return type.is_pyobject and type.assignable_from(self) def type_check_function(self, exact=True): type_name = self.name if type_name == 'str': type_check = 'PyString_Check' elif type_name == 'basestring': type_check = '__Pyx_PyBaseString_Check' elif type_name == 'Exception': type_check = '__Pyx_PyException_Check' elif type_name == 'bytearray': type_check = 'PyByteArray_Check' elif type_name == 'frozenset': type_check = 'PyFrozenSet_Check' else: type_check = 'Py%s_Check' % type_name.capitalize() if exact and type_name not in ('bool', 'slice', 'Exception'): type_check += 'Exact' return type_check def isinstance_code(self, arg): return '%s(%s)' % (self.type_check_function(exact=False), arg) def type_test_code(self, arg, notnone=False, exact=True): type_check = self.type_check_function(exact=exact) check = 'likely(%s(%s))' % (type_check, arg) if not notnone: check += '||((%s) == Py_None)' % arg if self.name == 'basestring': name = '(PY_MAJOR_VERSION < 3 ? "basestring" : "str")' else: name = '"%s"' % self.name return check + ' || __Pyx_RaiseUnexpectedTypeError(%s, %s)' % (name, arg) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: base_code = self.name else: base_code = public_decl(self.decl_type, dll_linkage) entity_code = "*%s" % entity_code return self.base_declaration_code(base_code, entity_code) def as_pyobject(self, cname): if self.decl_type == 'PyObject': return cname else: return "(PyObject *)" + cname def cast_code(self, expr_code, to_object_struct = False): return "((%s*)%s)" % ( to_object_struct and self.objstruct_cname or self.decl_type, # self.objstruct_cname may be None expr_code) def py_type_name(self): return self.name class PyExtensionType(PyObjectType): # # A Python extension type. # # name string # scope CClassScope Attribute namespace # typedef_flag boolean # base_type PyExtensionType or None # module_name string or None Qualified name of defining module # objstruct_cname string Name of PyObject struct # objtypedef_cname string Name of PyObject struct typedef # typeobj_cname string or None C code fragment referring to type object # typeptr_cname string or None Name of pointer to external type object # vtabslot_cname string Name of C method table member # vtabstruct_cname string Name of C method table struct # vtabptr_cname string Name of pointer to C method table # vtable_cname string Name of C method table definition # early_init boolean Whether to initialize early (as opposed to during module execution). # defered_declarations [thunk] Used to declare class hierarchies in order # is_external boolean Defined in a extern block # check_size 'warn', 'error', 'ignore' What to do if tp_basicsize does not match # dataclass_fields OrderedDict nor None Used for inheriting from dataclasses # multiple_bases boolean Does this class have multiple bases is_extension_type = 1 has_attributes = 1 early_init = 1 objtypedef_cname = None dataclass_fields = None multiple_bases = False def __init__(self, name, typedef_flag, base_type, is_external=0, check_size=None): self.name = name self.scope = None self.typedef_flag = typedef_flag if base_type is not None: base_type.is_subclassed = True self.base_type = base_type self.module_name = None self.objstruct_cname = None self.typeobj_cname = None self.typeptr_cname = None self.vtabslot_cname = None self.vtabstruct_cname = None self.vtabptr_cname = None self.vtable_cname = None self.is_external = is_external self.check_size = check_size or 'warn' self.defered_declarations = [] def set_scope(self, scope): self.scope = scope if scope: scope.parent_type = self def needs_nonecheck(self): return True def subtype_of_resolved_type(self, other_type): if other_type.is_extension_type or other_type.is_builtin_type: return self is other_type or ( self.base_type and self.base_type.subtype_of(other_type)) else: return other_type is py_object_type def typeobj_is_available(self): # Do we have a pointer to the type object? return self.typeptr_cname def typeobj_is_imported(self): # If we don't know the C name of the type object but we do # know which module it's defined in, it will be imported. return self.typeobj_cname is None and self.module_name is not None def assignable_from(self, src_type): if self == src_type: return True if isinstance(src_type, PyExtensionType): if src_type.base_type is not None: return self.assignable_from(src_type.base_type) if isinstance(src_type, BuiltinObjectType): # FIXME: This is an ugly special case that we currently # keep supporting. It allows users to specify builtin # types as external extension types, while keeping them # compatible with the real builtin types. We already # generate a warning for it. Big TODO: remove! return (self.module_name == '__builtin__' and self.name == src_type.name) return False def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0, deref = 0): if pyrex or for_display: base_code = self.name else: if self.typedef_flag: objstruct = self.objstruct_cname else: objstruct = "struct %s" % self.objstruct_cname base_code = public_decl(objstruct, dll_linkage) if deref: assert not entity_code else: entity_code = "*%s" % entity_code return self.base_declaration_code(base_code, entity_code) def type_test_code(self, py_arg, notnone=False): none_check = "((%s) == Py_None)" % py_arg type_check = "likely(__Pyx_TypeTest(%s, %s))" % ( py_arg, self.typeptr_cname) if notnone: return type_check else: return "likely(%s || %s)" % (none_check, type_check) def attributes_known(self): return self.scope is not None def __str__(self): return self.name def __repr__(self): return "<PyExtensionType %s%s>" % (self.scope.class_name, ("", " typedef")[self.typedef_flag]) def py_type_name(self): if not self.module_name: return self.name return "__import__(%r, None, None, ['']).%s" % (self.module_name, self.name) class CType(PyrexType): # # Base class for all C types (non-reference-counted). # # to_py_function string C function for converting to Python object # from_py_function string C function for constructing from Python object # to_py_function = None from_py_function = None exception_value = None exception_check = 1 def create_to_py_utility_code(self, env): return self.to_py_function is not None def create_from_py_utility_code(self, env): return self.from_py_function is not None def can_coerce_to_pyobject(self, env): return self.create_to_py_utility_code(env) def can_coerce_from_pyobject(self, env): return self.create_from_py_utility_code(env) def error_condition(self, result_code): conds = [] if self.is_string or self.is_pyunicode_ptr: conds.append("(!%s)" % result_code) elif self.exception_value is not None: conds.append("(%s == (%s)%s)" % (result_code, self.sign_and_name(), self.exception_value)) if self.exception_check: conds.append("PyErr_Occurred()") if len(conds) > 0: return " && ".join(conds) else: return 0 def to_py_call_code(self, source_code, result_code, result_type, to_py_function=None): func = self.to_py_function if to_py_function is None else to_py_function assert func if self.is_string or self.is_cpp_string: if result_type.is_builtin_type: result_type_name = result_type.name if result_type_name in ('bytes', 'str', 'unicode'): func = func.replace("Object", result_type_name.title(), 1) elif result_type_name == 'bytearray': func = func.replace("Object", "ByteArray", 1) return '%s = %s(%s)' % ( result_code, func, source_code or 'NULL') def from_py_call_code(self, source_code, result_code, error_pos, code, from_py_function=None, error_condition=None, special_none_cvalue=None): return self._assign_from_py_code( source_code, result_code, error_pos, code, from_py_function, error_condition, special_none_cvalue=special_none_cvalue) class PythranExpr(CType): # Pythran object of a given type to_py_function = "__Pyx_pythran_to_python" is_pythran_expr = True writable = True has_attributes = 1 def __init__(self, pythran_type, org_buffer=None): self.org_buffer = org_buffer self.pythran_type = pythran_type self.name = self.pythran_type self.cname = self.pythran_type self.from_py_function = "from_python<%s>" % (self.pythran_type) self.scope = None def declaration_code(self, entity_code, for_display=0, dll_linkage=None, pyrex=0): assert not pyrex return "%s %s" % (self.cname, entity_code) def attributes_known(self): if self.scope is None: from . import Symtab # FIXME: fake C scope, might be better represented by a struct or C++ class scope self.scope = scope = Symtab.CClassScope('', None, visibility="extern") scope.parent_type = self scope.directives = {} scope.declare_var("ndim", c_long_type, pos=None, cname="value", is_cdef=True) scope.declare_cproperty( "shape", c_ptr_type(c_long_type), "__Pyx_PythranShapeAccessor", doc="Pythran array shape", visibility="extern", nogil=True, ) return True def __eq__(self, other): return isinstance(other, PythranExpr) and self.pythran_type == other.pythran_type def __ne__(self, other): return not (isinstance(other, PythranExpr) and self.pythran_type == other.pythran_type) def __hash__(self): return hash(self.pythran_type) class CConstOrVolatileType(BaseType): "A C const or volatile type" subtypes = ['cv_base_type'] is_cv_qualified = 1 def __init__(self, base_type, is_const=0, is_volatile=0): self.cv_base_type = base_type self.is_const = is_const self.is_volatile = is_volatile if base_type.has_attributes and base_type.scope is not None: from .Symtab import CConstOrVolatileScope self.scope = CConstOrVolatileScope(base_type.scope, is_const, is_volatile) def cv_string(self): cvstring = "" if self.is_const: cvstring = "const " + cvstring if self.is_volatile: cvstring = "volatile " + cvstring return cvstring def __repr__(self): return "<CConstOrVolatileType %s%r>" % (self.cv_string(), self.cv_base_type) def __str__(self): return self.declaration_code("", for_display=1) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): cv = self.cv_string() if for_display or pyrex: return cv + self.cv_base_type.declaration_code(entity_code, for_display, dll_linkage, pyrex) else: return self.cv_base_type.declaration_code(cv + entity_code, for_display, dll_linkage, pyrex) def specialize(self, values): base_type = self.cv_base_type.specialize(values) if base_type == self.cv_base_type: return self return CConstOrVolatileType(base_type, self.is_const, self.is_volatile) def deduce_template_params(self, actual): return self.cv_base_type.deduce_template_params(actual) def can_coerce_to_pyobject(self, env): return self.cv_base_type.can_coerce_to_pyobject(env) def can_coerce_from_pyobject(self, env): return self.cv_base_type.can_coerce_from_pyobject(env) def create_to_py_utility_code(self, env): if self.cv_base_type.create_to_py_utility_code(env): self.to_py_function = self.cv_base_type.to_py_function return True def same_as_resolved_type(self, other_type): if other_type.is_cv_qualified: return self.cv_base_type.same_as_resolved_type(other_type.cv_base_type) # Accept cv LHS <- non-cv RHS. return self.cv_base_type.same_as_resolved_type(other_type) def __getattr__(self, name): return getattr(self.cv_base_type, name) def CConstType(base_type): return CConstOrVolatileType(base_type, is_const=1) class FusedType(CType): """ Represents a Fused Type. All it needs to do is keep track of the types it aggregates, as it will be replaced with its specific version wherever needed. See http://wiki.cython.org/enhancements/fusedtypes types [PyrexType] is the list of types to be fused name str the name of the ctypedef """ is_fused = 1 exception_check = 0 def __init__(self, types, name=None): # Use list rather than set to preserve order (list should be short). flattened_types = [] for t in types: if t.is_fused: # recursively merge in subtypes if isinstance(t, FusedType): t_types = t.types else: # handle types that aren't a fused type themselves but contain fused types # for example a C++ template where the template type is fused. t_fused_types = t.get_fused_types() t_types = [] for substitution in product( *[fused_type.types for fused_type in t_fused_types] ): t_types.append( t.specialize( { fused_type: sub for fused_type, sub in zip( t_fused_types, substitution ) } ) ) for subtype in t_types: if subtype not in flattened_types: flattened_types.append(subtype) elif t not in flattened_types: flattened_types.append(t) self.types = flattened_types self.name = name def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: return self.name raise Exception("This may never happen, please report a bug") def __repr__(self): return 'FusedType(name=%r)' % self.name def specialize(self, values): if self in values: return values[self] else: raise CannotSpecialize() def get_fused_types(self, result=None, seen=None, include_function_return_type=False): if result is None: return [self] if self not in seen: result.append(self) seen.add(self) class CVoidType(CType): # # C "void" type # is_void = 1 to_py_function = "__Pyx_void_to_None" def __repr__(self): return "<CVoidType>" def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: base_code = "void" else: base_code = public_decl("void", dll_linkage) return self.base_declaration_code(base_code, entity_code) def is_complete(self): return 0 class InvisibleVoidType(CVoidType): # # For use with C++ constructors and destructors return types. # Acts like void, but does not print out a declaration. # def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: base_code = "[void]" else: base_code = public_decl("", dll_linkage) return self.base_declaration_code(base_code, entity_code) class CNumericType(CType): # # Base class for all C numeric types. # # rank integer Relative size # signed integer 0 = unsigned, 1 = unspecified, 2 = explicitly signed # is_numeric = 1 default_value = "0" has_attributes = True scope = None sign_words = ("unsigned ", "", "signed ") def __init__(self, rank, signed = 1): self.rank = rank if rank > 0 and signed == SIGNED: # Signed is meaningless for anything but char, and complicates # type promotion. signed = 1 self.signed = signed def sign_and_name(self): s = self.sign_words[self.signed] n = rank_to_type_name[self.rank] return s + n def __repr__(self): return "<CNumericType %s>" % self.sign_and_name() def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): type_name = self.sign_and_name() if pyrex or for_display: base_code = type_name.replace('PY_LONG_LONG', 'long long') else: base_code = public_decl(type_name, dll_linkage) base_code = StringEncoding.EncodedString(base_code) return self.base_declaration_code(base_code, entity_code) def attributes_known(self): if self.scope is None: from . import Symtab self.scope = scope = Symtab.CClassScope( '', None, visibility="extern") scope.parent_type = self scope.directives = {} scope.declare_cfunction( "conjugate", CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True), pos=None, defining=1, cname=" ") return True def __lt__(self, other): """Sort based on rank, preferring signed over unsigned""" if other.is_numeric: return self.rank > other.rank and self.signed >= other.signed # Prefer numeric types over others return True def py_type_name(self): if self.rank <= 4: return "(int, long)" return "float" class ForbidUseClass: def __repr__(self): raise RuntimeError() def __str__(self): raise RuntimeError() ForbidUse = ForbidUseClass() class CIntLike(object): """Mixin for shared behaviour of C integers and enums. """ to_py_function = None from_py_function = None to_pyunicode_utility = None default_format_spec = 'd' def can_coerce_to_pyobject(self, env): return True def can_coerce_from_pyobject(self, env): return True def create_to_py_utility_code(self, env): if type(self).to_py_function is None: self.to_py_function = "__Pyx_PyInt_From_" + self.specialization_name() env.use_utility_code(TempitaUtilityCode.load_cached( "CIntToPy", "TypeConversion.c", context={"TYPE": self.empty_declaration_code(), "TO_PY_FUNCTION": self.to_py_function})) return True def create_from_py_utility_code(self, env): if type(self).from_py_function is None: self.from_py_function = "__Pyx_PyInt_As_" + self.specialization_name() env.use_utility_code(TempitaUtilityCode.load_cached( "CIntFromPy", "TypeConversion.c", context={"TYPE": self.empty_declaration_code(), "FROM_PY_FUNCTION": self.from_py_function})) return True @staticmethod def _parse_format(format_spec): padding = ' ' if not format_spec: return ('d', 0, padding) format_type = format_spec[-1] if format_type in ('o', 'd', 'x', 'X'): prefix = format_spec[:-1] elif format_type.isdigit(): format_type = 'd' prefix = format_spec else: return (None, 0, padding) if not prefix: return (format_type, 0, padding) if prefix[0] == '-': prefix = prefix[1:] if prefix and prefix[0] == '0': padding = '0' prefix = prefix.lstrip('0') if prefix.isdigit(): return (format_type, int(prefix), padding) return (None, 0, padding) def can_coerce_to_pystring(self, env, format_spec=None): format_type, width, padding = self._parse_format(format_spec) return format_type is not None and width <= 2**30 def convert_to_pystring(self, cvalue, code, format_spec=None): if self.to_pyunicode_utility is None: utility_code_name = "__Pyx_PyUnicode_From_" + self.specialization_name() to_pyunicode_utility = TempitaUtilityCode.load_cached( "CIntToPyUnicode", "TypeConversion.c", context={"TYPE": self.empty_declaration_code(), "TO_PY_FUNCTION": utility_code_name}) self.to_pyunicode_utility = (utility_code_name, to_pyunicode_utility) else: utility_code_name, to_pyunicode_utility = self.to_pyunicode_utility code.globalstate.use_utility_code(to_pyunicode_utility) format_type, width, padding_char = self._parse_format(format_spec) return "%s(%s, %d, '%s', '%s')" % (utility_code_name, cvalue, width, padding_char, format_type) class CIntType(CIntLike, CNumericType): is_int = 1 typedef_flag = 0 exception_value = -1 def get_to_py_type_conversion(self): if self.rank < list(rank_to_type_name).index('int'): # This assumes sizeof(short) < sizeof(int) return "PyInt_FromLong" else: # Py{Int|Long}_From[Unsigned]Long[Long] Prefix = "Int" SignWord = "" TypeName = "Long" if not self.signed: Prefix = "Long" SignWord = "Unsigned" if self.rank >= list(rank_to_type_name).index('PY_LONG_LONG'): Prefix = "Long" TypeName = "LongLong" return "Py%s_From%s%s" % (Prefix, SignWord, TypeName) def assignable_from_resolved_type(self, src_type): return src_type.is_int or src_type.is_enum or src_type is error_type def invalid_value(self): if rank_to_type_name[int(self.rank)] == 'char': return "'?'" else: # We do not really know the size of the type, so return # a 32-bit literal and rely on casting to final type. It will # be negative for signed ints, which is good. return "0xbad0bad0" def overflow_check_binop(self, binop, env, const_rhs=False): env.use_utility_code(UtilityCode.load("Common", "Overflow.c")) type = self.empty_declaration_code() name = self.specialization_name() if binop == "lshift": env.use_utility_code(TempitaUtilityCode.load_cached( "LeftShift", "Overflow.c", context={'TYPE': type, 'NAME': name, 'SIGNED': self.signed})) else: if const_rhs: binop += "_const" if type in ('int', 'long', 'long long'): env.use_utility_code(TempitaUtilityCode.load_cached( "BaseCaseSigned", "Overflow.c", context={'INT': type, 'NAME': name})) elif type in ('unsigned int', 'unsigned long', 'unsigned long long'): env.use_utility_code(TempitaUtilityCode.load_cached( "BaseCaseUnsigned", "Overflow.c", context={'UINT': type, 'NAME': name})) elif self.rank <= 1: # sizeof(short) < sizeof(int) return "__Pyx_%s_%s_no_overflow" % (binop, name) else: _load_overflow_base(env) env.use_utility_code(TempitaUtilityCode.load_cached( "SizeCheck", "Overflow.c", context={'TYPE': type, 'NAME': name})) env.use_utility_code(TempitaUtilityCode.load_cached( "Binop", "Overflow.c", context={'TYPE': type, 'NAME': name, 'BINOP': binop})) return "__Pyx_%s_%s_checking_overflow" % (binop, name) def _load_overflow_base(env): env.use_utility_code(UtilityCode.load("Common", "Overflow.c")) for type in ('int', 'long', 'long long'): env.use_utility_code(TempitaUtilityCode.load_cached( "BaseCaseSigned", "Overflow.c", context={'INT': type, 'NAME': type.replace(' ', '_')})) for type in ('unsigned int', 'unsigned long', 'unsigned long long'): env.use_utility_code(TempitaUtilityCode.load_cached( "BaseCaseUnsigned", "Overflow.c", context={'UINT': type, 'NAME': type.replace(' ', '_')})) class CAnonEnumType(CIntType): is_enum = 1 def sign_and_name(self): return 'int' class CReturnCodeType(CIntType): to_py_function = "__Pyx_Owned_Py_None" is_returncode = True exception_check = False default_format_spec = '' def can_coerce_to_pystring(self, env, format_spec=None): return not format_spec def convert_to_pystring(self, cvalue, code, format_spec=None): return "__Pyx_NewRef(%s)" % code.globalstate.get_py_string_const(StringEncoding.EncodedString("None")).cname class CBIntType(CIntType): to_py_function = "__Pyx_PyBool_FromLong" from_py_function = "__Pyx_PyObject_IsTrue" exception_check = 1 # for C++ bool default_format_spec = '' def can_coerce_to_pystring(self, env, format_spec=None): return not format_spec or super(CBIntType, self).can_coerce_to_pystring(env, format_spec) def convert_to_pystring(self, cvalue, code, format_spec=None): if format_spec: return super(CBIntType, self).convert_to_pystring(cvalue, code, format_spec) # NOTE: no caching here as the string constant cnames depend on the current module utility_code_name = "__Pyx_PyUnicode_FromBInt_" + self.specialization_name() to_pyunicode_utility = TempitaUtilityCode.load_cached( "CBIntToPyUnicode", "TypeConversion.c", context={ "TRUE_CONST": code.globalstate.get_py_string_const(StringEncoding.EncodedString("True")).cname, "FALSE_CONST": code.globalstate.get_py_string_const(StringEncoding.EncodedString("False")).cname, "TO_PY_FUNCTION": utility_code_name, }) code.globalstate.use_utility_code(to_pyunicode_utility) return "%s(%s)" % (utility_code_name, cvalue) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if for_display: base_code = 'bool' elif pyrex: base_code = 'bint' else: base_code = public_decl('int', dll_linkage) return self.base_declaration_code(base_code, entity_code) def __repr__(self): return "<CNumericType bint>" def __str__(self): return 'bint' def py_type_name(self): return "bool" class CPyUCS4IntType(CIntType): # Py_UCS4 is_unicode_char = True # Py_UCS4 coerces from and to single character unicode strings (or # at most two characters on 16bit Unicode builds), but we also # allow Python integers as input. The value range for Py_UCS4 # is 0..1114111, which is checked when converting from an integer # value. to_py_function = "PyUnicode_FromOrdinal" from_py_function = "__Pyx_PyObject_AsPy_UCS4" def can_coerce_to_pystring(self, env, format_spec=None): return False # does the right thing anyway def create_from_py_utility_code(self, env): env.use_utility_code(UtilityCode.load_cached("ObjectAsUCS4", "TypeConversion.c")) return True def sign_and_name(self): return "Py_UCS4" class CPyUnicodeIntType(CIntType): # Py_UNICODE is_unicode_char = True # Py_UNICODE coerces from and to single character unicode strings, # but we also allow Python integers as input. The value range for # Py_UNICODE is 0..1114111, which is checked when converting from # an integer value. to_py_function = "PyUnicode_FromOrdinal" from_py_function = "__Pyx_PyObject_AsPy_UNICODE" def can_coerce_to_pystring(self, env, format_spec=None): return False # does the right thing anyway def create_from_py_utility_code(self, env): env.use_utility_code(UtilityCode.load_cached("ObjectAsPyUnicode", "TypeConversion.c")) return True def sign_and_name(self): return "Py_UNICODE" class CPyHashTType(CIntType): to_py_function = "__Pyx_PyInt_FromHash_t" from_py_function = "__Pyx_PyInt_AsHash_t" def sign_and_name(self): return "Py_hash_t" class CPySSizeTType(CIntType): to_py_function = "PyInt_FromSsize_t" from_py_function = "__Pyx_PyIndex_AsSsize_t" def sign_and_name(self): return "Py_ssize_t" class CSSizeTType(CIntType): to_py_function = "PyInt_FromSsize_t" from_py_function = "PyInt_AsSsize_t" def sign_and_name(self): return "Py_ssize_t" class CSizeTType(CIntType): to_py_function = "__Pyx_PyInt_FromSize_t" def sign_and_name(self): return "size_t" class CPtrdiffTType(CIntType): def sign_and_name(self): return "ptrdiff_t" class CFloatType(CNumericType): is_float = 1 to_py_function = "PyFloat_FromDouble" from_py_function = "__pyx_PyFloat_AsDouble" exception_value = -1 def __init__(self, rank, math_h_modifier = ''): CNumericType.__init__(self, rank, 1) self.math_h_modifier = math_h_modifier if rank == RANK_FLOAT: self.from_py_function = "__pyx_PyFloat_AsFloat" def assignable_from_resolved_type(self, src_type): return (src_type.is_numeric and not src_type.is_complex) or src_type is error_type def invalid_value(self): return Naming.PYX_NAN class CComplexType(CNumericType): is_complex = 1 to_py_function = "__pyx_PyComplex_FromComplex" has_attributes = 1 scope = None def __init__(self, real_type): while real_type.is_typedef and not real_type.typedef_is_external: real_type = real_type.typedef_base_type self.funcsuffix = "_%s" % real_type.specialization_name() if real_type.is_float: self.math_h_modifier = real_type.math_h_modifier else: self.math_h_modifier = "_UNUSED" self.real_type = real_type CNumericType.__init__(self, real_type.rank + 0.5, real_type.signed) self.binops = {} self.from_parts = "%s_from_parts" % self.specialization_name() self.default_value = "%s(0, 0)" % self.from_parts def __eq__(self, other): if isinstance(self, CComplexType) and isinstance(other, CComplexType): return self.real_type == other.real_type else: return False def __ne__(self, other): if isinstance(self, CComplexType) and isinstance(other, CComplexType): return self.real_type != other.real_type else: return True def __lt__(self, other): if isinstance(self, CComplexType) and isinstance(other, CComplexType): return self.real_type < other.real_type else: # this is arbitrary, but it makes sure we always have # *some* kind of order return False def __hash__(self): return ~hash(self.real_type) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: real_code = self.real_type.declaration_code("", for_display, dll_linkage, pyrex) base_code = "%s complex" % real_code else: base_code = public_decl(self.sign_and_name(), dll_linkage) return self.base_declaration_code(base_code, entity_code) def sign_and_name(self): real_type_name = self.real_type.specialization_name() real_type_name = real_type_name.replace('long__double','long_double') real_type_name = real_type_name.replace('PY_LONG_LONG','long_long') return Naming.type_prefix + real_type_name + "_complex" def assignable_from(self, src_type): # Temporary hack/feature disabling, see #441 if (not src_type.is_complex and src_type.is_numeric and src_type.is_typedef and src_type.typedef_is_external): return False elif src_type.is_pyobject: return True else: return super(CComplexType, self).assignable_from(src_type) def assignable_from_resolved_type(self, src_type): return (src_type.is_complex and self.real_type.assignable_from_resolved_type(src_type.real_type) or src_type.is_numeric and self.real_type.assignable_from_resolved_type(src_type) or src_type is error_type) def attributes_known(self): if self.scope is None: from . import Symtab self.scope = scope = Symtab.CClassScope( '', None, visibility="extern") scope.parent_type = self scope.directives = {} scope.declare_var("real", self.real_type, None, cname="real", is_cdef=True) scope.declare_var("imag", self.real_type, None, cname="imag", is_cdef=True) scope.declare_cfunction( "conjugate", CFuncType(self, [CFuncTypeArg("self", self, None)], nogil=True), pos=None, defining=1, cname="__Pyx_c_conj%s" % self.funcsuffix) return True def _utility_code_context(self): return { 'type': self.empty_declaration_code(), 'type_name': self.specialization_name(), 'real_type': self.real_type.empty_declaration_code(), 'func_suffix': self.funcsuffix, 'm': self.math_h_modifier, 'is_float': int(self.real_type.is_float) } def create_declaration_utility_code(self, env): # This must always be run, because a single CComplexType instance can be shared # across multiple compilations (the one created in the module scope) env.use_utility_code(UtilityCode.load_cached('Header', 'Complex.c')) env.use_utility_code(UtilityCode.load_cached('RealImag', 'Complex.c')) env.use_utility_code(TempitaUtilityCode.load_cached( 'Declarations', 'Complex.c', self._utility_code_context())) env.use_utility_code(TempitaUtilityCode.load_cached( 'Arithmetic', 'Complex.c', self._utility_code_context())) return True def can_coerce_to_pyobject(self, env): return True def can_coerce_from_pyobject(self, env): return True def create_to_py_utility_code(self, env): env.use_utility_code(UtilityCode.load_cached('ToPy', 'Complex.c')) return True def create_from_py_utility_code(self, env): env.use_utility_code(TempitaUtilityCode.load_cached( 'FromPy', 'Complex.c', self._utility_code_context())) self.from_py_function = "__Pyx_PyComplex_As_" + self.specialization_name() return True def lookup_op(self, nargs, op): try: return self.binops[nargs, op] except KeyError: pass try: op_name = complex_ops[nargs, op] self.binops[nargs, op] = func_name = "__Pyx_c_%s%s" % (op_name, self.funcsuffix) return func_name except KeyError: return None def unary_op(self, op): return self.lookup_op(1, op) def binary_op(self, op): return self.lookup_op(2, op) def py_type_name(self): return "complex" def cast_code(self, expr_code): return expr_code complex_ops = { (1, '-'): 'neg', (1, 'zero'): 'is_zero', (2, '+'): 'sum', (2, '-'): 'diff', (2, '*'): 'prod', (2, '/'): 'quot', (2, '**'): 'pow', (2, '=='): 'eq', } class CPyTSSTType(CType): # # PEP-539 "Py_tss_t" type # declaration_value = "Py_tss_NEEDS_INIT" def __repr__(self): return "<Py_tss_t>" def declaration_code(self, entity_code, for_display=0, dll_linkage=None, pyrex=0): if pyrex or for_display: base_code = "Py_tss_t" else: base_code = public_decl("Py_tss_t", dll_linkage) return self.base_declaration_code(base_code, entity_code) class CPointerBaseType(CType): # common base type for pointer/array types # # base_type CType Reference type subtypes = ['base_type'] def __init__(self, base_type): self.base_type = base_type if base_type.is_cv_qualified: base_type = base_type.cv_base_type for char_type in (c_char_type, c_uchar_type, c_schar_type): if base_type.same_as(char_type): self.is_string = 1 break else: if base_type.same_as(c_py_unicode_type): self.is_pyunicode_ptr = 1 if self.is_string and not base_type.is_error: if base_type.signed == 2: self.to_py_function = "__Pyx_PyObject_FromCString" if self.is_ptr: self.from_py_function = "__Pyx_PyObject_As%sSString" elif base_type.signed: self.to_py_function = "__Pyx_PyObject_FromString" if self.is_ptr: self.from_py_function = "__Pyx_PyObject_As%sString" else: self.to_py_function = "__Pyx_PyObject_FromCString" if self.is_ptr: self.from_py_function = "__Pyx_PyObject_As%sUString" if self.is_ptr: self.from_py_function %= '' if self.base_type.is_const else 'Writable' self.exception_value = "NULL" elif self.is_pyunicode_ptr and not base_type.is_error: self.to_py_function = "__Pyx_PyUnicode_FromUnicode" if self.is_ptr: self.from_py_function = "__Pyx_PyUnicode_AsUnicode" self.exception_value = "NULL" def py_type_name(self): if self.is_string: return "bytes" elif self.is_pyunicode_ptr: return "unicode" else: return super(CPointerBaseType, self).py_type_name() def literal_code(self, value): if self.is_string: assert isinstance(value, str) return '"%s"' % StringEncoding.escape_byte_string(value) return str(value) class CArrayType(CPointerBaseType): # base_type CType Element type # size integer or None Number of elements is_array = 1 to_tuple_function = None def __init__(self, base_type, size): super(CArrayType, self).__init__(base_type) self.size = size def __eq__(self, other): if isinstance(other, CType) and other.is_array and self.size == other.size: return self.base_type.same_as(other.base_type) return False def __hash__(self): return hash(self.base_type) + 28 # arbitrarily chosen offset def __repr__(self): return "<CArrayType %s %s>" % (self.size, repr(self.base_type)) def same_as_resolved_type(self, other_type): return ((other_type.is_array and self.base_type.same_as(other_type.base_type)) or other_type is error_type) def assignable_from_resolved_type(self, src_type): # C arrays are assigned by value, either Python containers or C arrays/pointers if src_type.is_pyobject: return True if src_type.is_ptr or src_type.is_array: return self.base_type.assignable_from(src_type.base_type) return False def element_ptr_type(self): return c_ptr_type(self.base_type) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if self.size is not None: dimension_code = self.size else: dimension_code = "" if entity_code.startswith("*"): entity_code = "(%s)" % entity_code return self.base_type.declaration_code( "%s[%s]" % (entity_code, dimension_code), for_display, dll_linkage, pyrex) def as_argument_type(self): return c_ptr_type(self.base_type) def is_complete(self): return self.size is not None def specialize(self, values): base_type = self.base_type.specialize(values) if base_type == self.base_type: return self else: return CArrayType(base_type, self.size) def deduce_template_params(self, actual): if isinstance(actual, CArrayType): return self.base_type.deduce_template_params(actual.base_type) else: return {} def can_coerce_to_pyobject(self, env): return self.base_type.can_coerce_to_pyobject(env) def can_coerce_from_pyobject(self, env): return self.base_type.can_coerce_from_pyobject(env) def create_to_py_utility_code(self, env): if self.to_py_function is not None: return self.to_py_function if not self.base_type.create_to_py_utility_code(env): return False safe_typename = self.base_type.specialization_name() to_py_function = "__Pyx_carray_to_py_%s" % safe_typename to_tuple_function = "__Pyx_carray_to_tuple_%s" % safe_typename from .UtilityCode import CythonUtilityCode context = { 'cname': to_py_function, 'to_tuple_cname': to_tuple_function, 'base_type': self.base_type, } env.use_utility_code(CythonUtilityCode.load( "carray.to_py", "CConvert.pyx", outer_module_scope=env.global_scope(), # need access to types declared in module context=context, compiler_directives=dict(env.global_scope().directives))) self.to_tuple_function = to_tuple_function self.to_py_function = to_py_function return True def to_py_call_code(self, source_code, result_code, result_type, to_py_function=None): func = self.to_py_function if to_py_function is None else to_py_function if self.is_string or self.is_pyunicode_ptr: return '%s = %s(%s)' % ( result_code, func, source_code) target_is_tuple = result_type.is_builtin_type and result_type.name == 'tuple' return '%s = %s(%s, %s)' % ( result_code, self.to_tuple_function if target_is_tuple else func, source_code, self.size) def create_from_py_utility_code(self, env): if self.from_py_function is not None: return self.from_py_function if not self.base_type.create_from_py_utility_code(env): return False from_py_function = "__Pyx_carray_from_py_%s" % self.base_type.specialization_name() from .UtilityCode import CythonUtilityCode context = { 'cname': from_py_function, 'base_type': self.base_type, } env.use_utility_code(CythonUtilityCode.load( "carray.from_py", "CConvert.pyx", outer_module_scope=env.global_scope(), # need access to types declared in module context=context, compiler_directives=dict(env.global_scope().directives))) self.from_py_function = from_py_function return True def from_py_call_code(self, source_code, result_code, error_pos, code, from_py_function=None, error_condition=None, special_none_cvalue=None): assert not error_condition, '%s: %s' % (error_pos, error_condition) assert not special_none_cvalue, '%s: %s' % (error_pos, special_none_cvalue) # not currently supported call_code = "%s(%s, %s, %s)" % ( from_py_function or self.from_py_function, source_code, result_code, self.size) return code.error_goto_if_neg(call_code, error_pos) class CPtrType(CPointerBaseType): # base_type CType Reference type is_ptr = 1 default_value = "0" def __hash__(self): return hash(self.base_type) + 27 # arbitrarily chosen offset def __eq__(self, other): if isinstance(other, CType) and other.is_ptr: return self.base_type.same_as(other.base_type) return False def __ne__(self, other): return not (self == other) def __repr__(self): return "<CPtrType %s>" % repr(self.base_type) def same_as_resolved_type(self, other_type): return ((other_type.is_ptr and self.base_type.same_as(other_type.base_type)) or other_type is error_type) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): #print "CPtrType.declaration_code: pointer to", self.base_type ### return self.base_type.declaration_code( "*%s" % entity_code, for_display, dll_linkage, pyrex) def assignable_from_resolved_type(self, other_type): if other_type is error_type: return 1 if other_type.is_null_ptr: return 1 if self.base_type.is_cv_qualified: self = CPtrType(self.base_type.cv_base_type) if self.base_type.is_cfunction: if other_type.is_ptr: other_type = other_type.base_type.resolve() if other_type.is_cfunction: return self.base_type.pointer_assignable_from_resolved_type(other_type) else: return 0 if (self.base_type.is_cpp_class and other_type.is_ptr and other_type.base_type.is_cpp_class and other_type.base_type.is_subclass(self.base_type)): return 1 if other_type.is_array or other_type.is_ptr: return self.base_type.is_void or self.base_type.same_as(other_type.base_type) return 0 def specialize(self, values): base_type = self.base_type.specialize(values) if base_type == self.base_type: return self else: return CPtrType(base_type) def deduce_template_params(self, actual): if isinstance(actual, CPtrType): return self.base_type.deduce_template_params(actual.base_type) else: return {} def invalid_value(self): return "1" def find_cpp_operation_type(self, operator, operand_type=None): if self.base_type.is_cpp_class: return self.base_type.find_cpp_operation_type(operator, operand_type) return None def get_fused_types(self, result=None, seen=None, include_function_return_type=False): # For function pointers, include the return type - unlike for fused functions themselves, # where the return type cannot be an independent fused type (i.e. is derived or non-fused). return super(CPointerBaseType, self).get_fused_types(result, seen, include_function_return_type=True) class CNullPtrType(CPtrType): is_null_ptr = 1 class CReferenceBaseType(BaseType): is_fake_reference = 0 # Common base type for C reference and C++ rvalue reference types. subtypes = ['ref_base_type'] def __init__(self, base_type): self.ref_base_type = base_type def __repr__(self): return "<%r %s>" % (self.__class__.__name__, self.ref_base_type) def specialize(self, values): base_type = self.ref_base_type.specialize(values) if base_type == self.ref_base_type: return self else: return type(self)(base_type) def deduce_template_params(self, actual): return self.ref_base_type.deduce_template_params(actual) def __getattr__(self, name): return getattr(self.ref_base_type, name) class CReferenceType(CReferenceBaseType): is_reference = 1 def __str__(self): return "%s &" % self.ref_base_type def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): #print "CReferenceType.declaration_code: pointer to", self.base_type ### return self.ref_base_type.declaration_code( "&%s" % entity_code, for_display, dll_linkage, pyrex) class CFakeReferenceType(CReferenceType): is_fake_reference = 1 def __str__(self): return "%s [&]" % self.ref_base_type def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): #print "CReferenceType.declaration_code: pointer to", self.base_type ### return "__Pyx_FakeReference<%s> %s" % (self.ref_base_type.empty_declaration_code(), entity_code) class CppRvalueReferenceType(CReferenceBaseType): is_rvalue_reference = 1 def __str__(self): return "%s &&" % self.ref_base_type def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): return self.ref_base_type.declaration_code( "&&%s" % entity_code, for_display, dll_linkage, pyrex) class CFuncType(CType): # return_type CType # args [CFuncTypeArg] # has_varargs boolean # exception_value string # exception_check boolean True if PyErr_Occurred check needed # calling_convention string Function calling convention # nogil boolean Can be called without gil # with_gil boolean Acquire gil around function body # templates [string] or None # cached_specialized_types [CFuncType] cached specialized versions of the CFuncType if defined in a pxd # from_fused boolean Indicates whether this is a specialized # C function # is_strict_signature boolean function refuses to accept coerced arguments # (used for optimisation overrides) # is_const_method boolean # is_static_method boolean # op_arg_struct CPtrType Pointer to optional argument struct is_cfunction = 1 original_sig = None cached_specialized_types = None from_fused = False is_const_method = False op_arg_struct = None subtypes = ['return_type', 'args'] def __init__(self, return_type, args, has_varargs = 0, exception_value = None, exception_check = 0, calling_convention = "", nogil = 0, with_gil = 0, is_overridable = 0, optional_arg_count = 0, is_const_method = False, is_static_method=False, templates = None, is_strict_signature = False): self.return_type = return_type self.args = args self.has_varargs = has_varargs self.optional_arg_count = optional_arg_count self.exception_value = exception_value self.exception_check = exception_check self.calling_convention = calling_convention self.nogil = nogil self.with_gil = with_gil self.is_overridable = is_overridable self.is_const_method = is_const_method self.is_static_method = is_static_method self.templates = templates self.is_strict_signature = is_strict_signature def __repr__(self): arg_reprs = list(map(repr, self.args)) if self.has_varargs: arg_reprs.append("...") if self.exception_value: except_clause = " %r" % self.exception_value else: except_clause = "" if self.exception_check: except_clause += "?" return "<CFuncType %s %s[%s]%s>" % ( repr(self.return_type), self.calling_convention_prefix(), ",".join(arg_reprs), except_clause) def with_with_gil(self, with_gil): if with_gil == self.with_gil: return self else: return CFuncType( self.return_type, self.args, self.has_varargs, self.exception_value, self.exception_check, self.calling_convention, self.nogil, with_gil, self.is_overridable, self.optional_arg_count, self.is_const_method, self.is_static_method, self.templates, self.is_strict_signature) def calling_convention_prefix(self): cc = self.calling_convention if cc: return cc + " " else: return "" def as_argument_type(self): return c_ptr_type(self) def same_c_signature_as(self, other_type, as_cmethod = 0): return self.same_c_signature_as_resolved_type( other_type.resolve(), as_cmethod) def same_c_signature_as_resolved_type(self, other_type, as_cmethod=False, as_pxd_definition=False, exact_semantics=True): # If 'exact_semantics' is false, allow any equivalent C signatures # if the Cython semantics are compatible, i.e. the same or wider for 'other_type'. #print "CFuncType.same_c_signature_as_resolved_type:", \ # self, other_type, "as_cmethod =", as_cmethod ### if other_type is error_type: return 1 if not other_type.is_cfunction: return 0 if self.is_overridable != other_type.is_overridable: return 0 nargs = len(self.args) if nargs != len(other_type.args): return 0 # When comparing C method signatures, the first argument # is exempt from compatibility checking (the proper check # is performed elsewhere). for i in range(as_cmethod, nargs): if not self.args[i].type.same_as(other_type.args[i].type): return 0 if self.has_varargs != other_type.has_varargs: return 0 if self.optional_arg_count != other_type.optional_arg_count: return 0 if as_pxd_definition: # A narrowing of the return type declared in the pxd is allowed. if not self.return_type.subtype_of_resolved_type(other_type.return_type): return 0 else: if not self.return_type.same_as(other_type.return_type): return 0 if not self.same_calling_convention_as(other_type): return 0 if exact_semantics: if self.exception_check != other_type.exception_check: return 0 if not self._same_exception_value(other_type.exception_value): return 0 elif not self._is_exception_compatible_with(other_type): return 0 return 1 def _same_exception_value(self, other_exc_value): if self.exception_value == other_exc_value: return 1 if self.exception_check != '+': return 0 if not self.exception_value or not other_exc_value: return 0 if self.exception_value.type != other_exc_value.type: return 0 if self.exception_value.entry and other_exc_value.entry: if self.exception_value.entry.cname != other_exc_value.entry.cname: return 0 if self.exception_value.name != other_exc_value.name: return 0 return 1 def compatible_signature_with(self, other_type, as_cmethod = 0): return self.compatible_signature_with_resolved_type(other_type.resolve(), as_cmethod) def compatible_signature_with_resolved_type(self, other_type, as_cmethod): #print "CFuncType.same_c_signature_as_resolved_type:", \ # self, other_type, "as_cmethod =", as_cmethod ### if other_type is error_type: return 1 if not other_type.is_cfunction: return 0 if not self.is_overridable and other_type.is_overridable: return 0 nargs = len(self.args) if nargs - self.optional_arg_count != len(other_type.args) - other_type.optional_arg_count: return 0 if self.optional_arg_count < other_type.optional_arg_count: return 0 # When comparing C method signatures, the first argument # is exempt from compatibility checking (the proper check # is performed elsewhere). for i in range(as_cmethod, len(other_type.args)): if not self.args[i].type.same_as( other_type.args[i].type): return 0 if self.has_varargs != other_type.has_varargs: return 0 if not self.return_type.subtype_of_resolved_type(other_type.return_type): return 0 if not self.same_calling_convention_as(other_type): return 0 if self.nogil != other_type.nogil: return 0 if not self._is_exception_compatible_with(other_type): return 0 self.original_sig = other_type.original_sig or other_type return 1 def _is_exception_compatible_with(self, other_type): # narrower exception checks are ok, but prevent mismatches if self.exception_check == '+' and other_type.exception_check != '+': # must catch C++ exceptions if we raise them return 0 if not other_type.exception_check or other_type.exception_value is not None: # There's no problem if this type doesn't emit exceptions but the other type checks if other_type.exception_check and not (self.exception_check or self.exception_value): return 1 # if other does not *always* check exceptions, self must comply if not self._same_exception_value(other_type.exception_value): return 0 if self.exception_check and self.exception_check != other_type.exception_check: # a redundant exception check doesn't make functions incompatible, but a missing one does return 0 return 1 def narrower_c_signature_than(self, other_type, as_cmethod = 0): return self.narrower_c_signature_than_resolved_type(other_type.resolve(), as_cmethod) def narrower_c_signature_than_resolved_type(self, other_type, as_cmethod): if other_type is error_type: return 1 if not other_type.is_cfunction: return 0 nargs = len(self.args) if nargs != len(other_type.args): return 0 for i in range(as_cmethod, nargs): if not self.args[i].type.subtype_of_resolved_type(other_type.args[i].type): return 0 else: self.args[i].needs_type_test = other_type.args[i].needs_type_test \ or not self.args[i].type.same_as(other_type.args[i].type) if self.has_varargs != other_type.has_varargs: return 0 if self.optional_arg_count != other_type.optional_arg_count: return 0 if not self.return_type.subtype_of_resolved_type(other_type.return_type): return 0 if not self.exception_check and other_type.exception_check: # a redundant exception check doesn't make functions incompatible, but a missing one does return 0 if not self._same_exception_value(other_type.exception_value): return 0 return 1 def same_calling_convention_as(self, other): ## XXX Under discussion ... ## callspec_words = ("__stdcall", "__cdecl", "__fastcall") ## cs1 = self.calling_convention ## cs2 = other.calling_convention ## if (cs1 in callspec_words or ## cs2 in callspec_words): ## return cs1 == cs2 ## else: ## return True sc1 = self.calling_convention == '__stdcall' sc2 = other.calling_convention == '__stdcall' return sc1 == sc2 def same_as_resolved_type(self, other_type, as_cmethod=False): return self.same_c_signature_as_resolved_type(other_type, as_cmethod=as_cmethod) \ and self.nogil == other_type.nogil def pointer_assignable_from_resolved_type(self, rhs_type): # Accept compatible exception/nogil declarations for the RHS. if rhs_type is error_type: return 1 if not rhs_type.is_cfunction: return 0 return rhs_type.same_c_signature_as_resolved_type(self, exact_semantics=False) \ and not (self.nogil and not rhs_type.nogil) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0, with_calling_convention = 1): arg_decl_list = [] for arg in self.args[:len(self.args)-self.optional_arg_count]: arg_decl_list.append( arg.type.declaration_code("", for_display, pyrex = pyrex)) if self.is_overridable: arg_decl_list.append("int %s" % Naming.skip_dispatch_cname) if self.optional_arg_count: arg_decl_list.append(self.op_arg_struct.declaration_code(Naming.optional_args_cname)) if self.has_varargs: arg_decl_list.append("...") arg_decl_code = ", ".join(arg_decl_list) if not arg_decl_code and not pyrex: arg_decl_code = "void" trailer = "" if (pyrex or for_display) and not self.return_type.is_pyobject: if self.exception_value and self.exception_check: trailer = " except? %s" % self.exception_value elif self.exception_value and not self.exception_check: trailer = " except %s" % self.exception_value elif not self.exception_value and not self.exception_check: trailer = " noexcept" elif self.exception_check == '+': trailer = " except +" elif self.exception_check and for_display: # not spelled out by default, unless for human eyes trailer = " except *" if self.nogil: trailer += " nogil" if not with_calling_convention: cc = '' else: cc = self.calling_convention_prefix() if (not entity_code and cc) or entity_code.startswith("*"): entity_code = "(%s%s)" % (cc, entity_code) cc = "" if self.is_const_method: trailer += " const" return self.return_type.declaration_code( "%s%s(%s)%s" % (cc, entity_code, arg_decl_code, trailer), for_display, dll_linkage, pyrex) def function_header_code(self, func_name, arg_code): if self.is_const_method: trailer = " const" else: trailer = "" return "%s%s(%s)%s" % (self.calling_convention_prefix(), func_name, arg_code, trailer) def signature_string(self): s = self.empty_declaration_code() return s def signature_cast_string(self): s = self.declaration_code("(*)", with_calling_convention=False) return '(%s)' % s def specialize(self, values): result = CFuncType(self.return_type.specialize(values), [arg.specialize(values) for arg in self.args], has_varargs = self.has_varargs, exception_value = self.exception_value, exception_check = self.exception_check, calling_convention = self.calling_convention, nogil = self.nogil, with_gil = self.with_gil, is_overridable = self.is_overridable, optional_arg_count = self.optional_arg_count, is_const_method = self.is_const_method, is_static_method = self.is_static_method, templates = self.templates) result.from_fused = self.is_fused return result def opt_arg_cname(self, arg_name): return self.op_arg_struct.base_type.scope.lookup(arg_name).cname # Methods that deal with Fused Types # All but map_with_specific_entries should be called only on functions # with fused types (and not on their corresponding specific versions). def get_all_specialized_permutations(self, fused_types=None): """ Permute all the types. For every specific instance of a fused type, we want all other specific instances of all other fused types. It returns an iterable of two-tuples of the cname that should prefix the cname of the function, and a dict mapping any fused types to their respective specific types. """ assert self.is_fused if fused_types is None: fused_types = self.get_fused_types() return get_all_specialized_permutations(fused_types) def get_all_specialized_function_types(self): """ Get all the specific function types of this one. """ assert self.is_fused if self.entry.fused_cfunction: return [n.type for n in self.entry.fused_cfunction.nodes] elif self.cached_specialized_types is not None: return self.cached_specialized_types result = [] permutations = self.get_all_specialized_permutations() new_cfunc_entries = [] for cname, fused_to_specific in permutations: new_func_type = self.entry.type.specialize(fused_to_specific) if self.optional_arg_count: # Remember, this method is set by CFuncDeclaratorNode self.declare_opt_arg_struct(new_func_type, cname) new_entry = copy.deepcopy(self.entry) new_func_type.specialize_entry(new_entry, cname) new_entry.type = new_func_type new_func_type.entry = new_entry result.append(new_func_type) new_cfunc_entries.append(new_entry) cfunc_entries = self.entry.scope.cfunc_entries try: cindex = cfunc_entries.index(self.entry) except ValueError: cfunc_entries.extend(new_cfunc_entries) else: cfunc_entries[cindex:cindex+1] = new_cfunc_entries self.cached_specialized_types = result return result def get_fused_types(self, result=None, seen=None, subtypes=None, include_function_return_type=False): """Return fused types in the order they appear as parameter types""" return super(CFuncType, self).get_fused_types( result, seen, # for function pointer types, we consider the result type; for plain function # types we don't (because it must be derivable from the arguments) subtypes=self.subtypes if include_function_return_type else ['args']) def specialize_entry(self, entry, cname): assert not self.is_fused specialize_entry(entry, cname) def can_coerce_to_pyobject(self, env): # duplicating the decisions from create_to_py_utility_code() here avoids writing out unused code if self.has_varargs or self.optional_arg_count: return False if self.to_py_function is not None: return self.to_py_function for arg in self.args: if not arg.type.is_pyobject and not arg.type.can_coerce_to_pyobject(env): return False if not self.return_type.is_pyobject and not self.return_type.can_coerce_to_pyobject(env): return False return True def create_to_py_utility_code(self, env): # FIXME: it seems we're trying to coerce in more cases than we should if self.to_py_function is not None: return self.to_py_function if not self.can_coerce_to_pyobject(env): return False from .UtilityCode import CythonUtilityCode # include argument names into the c function name to ensure cname is unique # between functions with identical types but different argument names from .Symtab import punycodify_name def arg_name_part(arg): return "%s%s" % (len(arg.name), punycodify_name(arg.name)) if arg.name else "0" arg_names = [ arg_name_part(arg) for arg in self.args ] arg_names = "_".join(arg_names) safe_typename = type_identifier(self, pyrex=True) to_py_function = "__Pyx_CFunc_%s_to_py_%s" % (safe_typename, arg_names) for arg in self.args: if not arg.type.is_pyobject and not arg.type.create_from_py_utility_code(env): return False if not self.return_type.is_pyobject and not self.return_type.create_to_py_utility_code(env): return False def declared_type(ctype): type_displayname = str(ctype.declaration_code("", for_display=True)) if ctype.is_pyobject: arg_ctype = type_name = type_displayname if ctype.is_builtin_type: arg_ctype = ctype.name elif not ctype.is_extension_type: type_name = 'object' type_displayname = None else: type_displayname = repr(type_displayname) elif ctype is c_bint_type: type_name = arg_ctype = 'bint' else: type_name = arg_ctype = type_displayname if ctype is c_double_type: type_displayname = 'float' else: type_displayname = repr(type_displayname) return type_name, arg_ctype, type_displayname class Arg(object): def __init__(self, arg_name, arg_type): self.name = arg_name self.type = arg_type self.type_cname, self.ctype, self.type_displayname = declared_type(arg_type) if self.return_type.is_void: except_clause = 'except *' elif self.return_type.is_pyobject: except_clause = '' elif self.exception_value: except_clause = ('except? %s' if self.exception_check else 'except %s') % self.exception_value else: except_clause = 'except *' context = { 'cname': to_py_function, 'args': [Arg(arg.name or 'arg%s' % ix, arg.type) for ix, arg in enumerate(self.args)], 'return_type': Arg('return', self.return_type), 'except_clause': except_clause, } # FIXME: directives come from first defining environment and do not adapt for reuse env.use_utility_code(CythonUtilityCode.load( "cfunc.to_py", "CConvert.pyx", outer_module_scope=env.global_scope(), # need access to types declared in module context=context, compiler_directives=dict(env.global_scope().directives))) self.to_py_function = to_py_function return True def specialize_entry(entry, cname): """ Specialize an entry of a copied fused function or method """ entry.is_fused_specialized = True entry.name = get_fused_cname(cname, entry.name) if entry.is_cmethod: entry.cname = entry.name if entry.is_inherited: entry.cname = StringEncoding.EncodedString( "%s.%s" % (Naming.obj_base_cname, entry.cname)) else: entry.cname = get_fused_cname(cname, entry.cname) if entry.func_cname: entry.func_cname = get_fused_cname(cname, entry.func_cname) def get_fused_cname(fused_cname, orig_cname): """ Given the fused cname id and an original cname, return a specialized cname """ assert fused_cname and orig_cname return StringEncoding.EncodedString('%s%s%s' % (Naming.fused_func_prefix, fused_cname, orig_cname)) def unique(somelist): seen = set() result = [] for obj in somelist: if obj not in seen: result.append(obj) seen.add(obj) return result def get_all_specialized_permutations(fused_types): return _get_all_specialized_permutations(unique(fused_types)) def _get_all_specialized_permutations(fused_types, id="", f2s=()): fused_type, = fused_types[0].get_fused_types() result = [] for newid, specific_type in enumerate(fused_type.types): # f2s = dict(f2s, **{ fused_type: specific_type }) f2s = dict(f2s) f2s.update({ fused_type: specific_type }) if id: cname = '%s_%s' % (id, newid) else: cname = str(newid) if len(fused_types) > 1: result.extend(_get_all_specialized_permutations( fused_types[1:], cname, f2s)) else: result.append((cname, f2s)) return result def specialization_signature_string(fused_compound_type, fused_to_specific): """ Return the signature for a specialization of a fused type. e.g. floating[:] -> 'float' or 'double' cdef fused ft: float[:] double[:] ft -> 'float[:]' or 'double[:]' integral func(floating) -> 'int (*func)(float)' or ... """ fused_types = fused_compound_type.get_fused_types() if len(fused_types) == 1: fused_type = fused_types[0] else: fused_type = fused_compound_type return fused_type.specialize(fused_to_specific).typeof_name() def get_specialized_types(type): """ Return a list of specialized types in their declared order. """ assert type.is_fused if isinstance(type, FusedType): result = list(type.types) for specialized_type in result: specialized_type.specialization_string = specialized_type.typeof_name() else: result = [] for cname, f2s in get_all_specialized_permutations(type.get_fused_types()): specialized_type = type.specialize(f2s) specialized_type.specialization_string = ( specialization_signature_string(type, f2s)) result.append(specialized_type) return result class CFuncTypeArg(BaseType): # name string # cname string # type PyrexType # pos source file position # FIXME: is this the right setup? should None be allowed here? not_none = False or_none = False accept_none = True accept_builtin_subtypes = False annotation = None subtypes = ['type'] def __init__(self, name, type, pos, cname=None, annotation=None): self.name = name if cname is not None: self.cname = cname else: self.cname = Naming.var_prefix + name if annotation is not None: self.annotation = annotation self.type = type self.pos = pos self.needs_type_test = False # TODO: should these defaults be set in analyse_types()? def __repr__(self): return "%s:%s" % (self.name, repr(self.type)) def declaration_code(self, for_display = 0): return self.type.declaration_code(self.cname, for_display) def specialize(self, values): return CFuncTypeArg(self.name, self.type.specialize(values), self.pos, self.cname) def is_forwarding_reference(self): if self.type.is_rvalue_reference: if (isinstance(self.type.ref_base_type, TemplatePlaceholderType) and not self.type.ref_base_type.is_cv_qualified): return True return False class ToPyStructUtilityCode(object): requires = None def __init__(self, type, forward_decl, env): self.type = type self.header = "static PyObject* %s(%s)" % (type.to_py_function, type.declaration_code('s')) self.forward_decl = forward_decl self.env = env def __eq__(self, other): return isinstance(other, ToPyStructUtilityCode) and self.header == other.header def __hash__(self): return hash(self.header) def get_tree(self, **kwargs): pass def put_code(self, output): code = output['utility_code_def'] proto = output['utility_code_proto'] code.putln("%s {" % self.header) code.putln("PyObject* res;") code.putln("PyObject* member;") code.putln("res = __Pyx_PyDict_NewPresized(%d); if (unlikely(!res)) return NULL;" % len(self.type.scope.var_entries)) for member in self.type.scope.var_entries: nameconst_cname = code.get_py_string_const(member.name, identifier=True) code.putln("%s; if (unlikely(!member)) goto bad;" % ( member.type.to_py_call_code('s.%s' % member.cname, 'member', member.type))) code.putln("if (unlikely(PyDict_SetItem(res, %s, member) < 0)) goto bad;" % nameconst_cname) code.putln("Py_DECREF(member);") code.putln("return res;") code.putln("bad:") code.putln("Py_XDECREF(member);") code.putln("Py_DECREF(res);") code.putln("return NULL;") code.putln("}") # This is a bit of a hack, we need a forward declaration # due to the way things are ordered in the module... if self.forward_decl: proto.putln(self.type.empty_declaration_code() + ';') proto.putln(self.header + ";") def inject_tree_and_scope_into(self, module_node): pass class CStructOrUnionType(CType): # name string # cname string # kind string "struct" or "union" # scope StructOrUnionScope, or None if incomplete # typedef_flag boolean # packed boolean # entry Entry is_struct_or_union = 1 has_attributes = 1 exception_check = True def __init__(self, name, kind, scope, typedef_flag, cname, packed=False, in_cpp=False): self.name = name self.cname = cname self.kind = kind self.scope = scope self.typedef_flag = typedef_flag self.is_struct = kind == 'struct' self.to_py_function = "%s_to_py_%s" % ( Naming.convert_func_prefix, self.specialization_name()) self.from_py_function = "%s_from_py_%s" % ( Naming.convert_func_prefix, self.specialization_name()) self.exception_check = True self._convert_to_py_code = None self._convert_from_py_code = None self.packed = packed self.needs_cpp_construction = self.is_struct and in_cpp def can_coerce_to_pyobject(self, env): if self._convert_to_py_code is False: return None # tri-state-ish if env.outer_scope is None: return False if self._convert_to_py_code is None: is_union = not self.is_struct unsafe_union_types = set() safe_union_types = set() for member in self.scope.var_entries: member_type = member.type if not member_type.can_coerce_to_pyobject(env): self.to_py_function = None self._convert_to_py_code = False return False if is_union: if member_type.is_ptr or member_type.is_cpp_class: unsafe_union_types.add(member_type) else: safe_union_types.add(member_type) if unsafe_union_types and (safe_union_types or len(unsafe_union_types) > 1): # unsafe mix of safe and unsafe to convert types self.from_py_function = None self._convert_from_py_code = False return False return True def create_to_py_utility_code(self, env): if not self.can_coerce_to_pyobject(env): return False if self._convert_to_py_code is None: for member in self.scope.var_entries: member.type.create_to_py_utility_code(env) forward_decl = self.entry.visibility != 'extern' and not self.typedef_flag self._convert_to_py_code = ToPyStructUtilityCode(self, forward_decl, env) env.use_utility_code(self._convert_to_py_code) return True def can_coerce_from_pyobject(self, env): if env.outer_scope is None or self._convert_from_py_code is False: return False for member in self.scope.var_entries: if not member.type.can_coerce_from_pyobject(env): return False return True def create_from_py_utility_code(self, env): if env.outer_scope is None: return False if self._convert_from_py_code is False: return None # tri-state-ish if self._convert_from_py_code is None: if not self.scope.var_entries: # There are obviously missing fields; don't allow instantiation # where absolutely no content is provided. return False for member in self.scope.var_entries: if not member.type.create_from_py_utility_code(env): self.from_py_function = None self._convert_from_py_code = False return False context = dict( struct_type=self, var_entries=self.scope.var_entries, funcname=self.from_py_function, ) env.use_utility_code(UtilityCode.load_cached("RaiseUnexpectedTypeError", "ObjectHandling.c")) from .UtilityCode import CythonUtilityCode self._convert_from_py_code = CythonUtilityCode.load( "FromPyStructUtility" if self.is_struct else "FromPyUnionUtility", "CConvert.pyx", outer_module_scope=env.global_scope(), # need access to types declared in module context=context) env.use_utility_code(self._convert_from_py_code) return True def __repr__(self): return "<CStructOrUnionType %s %s%s>" % ( self.name, self.cname, ("", " typedef")[self.typedef_flag]) def declaration_code(self, entity_code, for_display=0, dll_linkage=None, pyrex=0): if pyrex or for_display: base_code = self.name else: if self.typedef_flag: base_code = self.cname else: base_code = "%s %s" % (self.kind, self.cname) base_code = public_decl(base_code, dll_linkage) return self.base_declaration_code(base_code, entity_code) def __eq__(self, other): try: return (isinstance(other, CStructOrUnionType) and self.name == other.name) except AttributeError: return False def __lt__(self, other): try: return self.name < other.name except AttributeError: # this is arbitrary, but it makes sure we always have # *some* kind of order return False def __hash__(self): return hash(self.cname) ^ hash(self.kind) def is_complete(self): return self.scope is not None def attributes_known(self): return self.is_complete() def can_be_complex(self): # Does the struct consist of exactly two identical floats? fields = self.scope.var_entries if len(fields) != 2: return False a, b = fields return (a.type.is_float and b.type.is_float and a.type.empty_declaration_code() == b.type.empty_declaration_code()) def struct_nesting_depth(self): child_depths = [x.type.struct_nesting_depth() for x in self.scope.var_entries] return max(child_depths) + 1 def cast_code(self, expr_code): if self.is_struct: return expr_code return super(CStructOrUnionType, self).cast_code(expr_code) cpp_string_conversions = ("std::string",) builtin_cpp_conversions = { # type element template params "std::pair": 2, "std::vector": 1, "std::list": 1, "std::set": 1, "std::unordered_set": 1, "std::map": 2, "std::unordered_map": 2, "std::complex": 1, } class CppClassType(CType): # name string # cname string # scope CppClassScope # templates [string] or None is_cpp_class = 1 has_attributes = 1 needs_cpp_construction = 1 exception_check = True namespace = None # For struct-like declaration. kind = "struct" packed = False typedef_flag = False subtypes = ['templates'] def __init__(self, name, scope, cname, base_classes, templates=None, template_type=None): self.name = name self.cname = cname self.scope = scope self.base_classes = base_classes self.operators = [] self.templates = templates self.template_type = template_type self.num_optional_templates = sum(is_optional_template_param(T) for T in templates or ()) if templates: self.specializations = {tuple(zip(templates, templates)): self} else: self.specializations = {} self.is_cpp_string = cname in cpp_string_conversions def use_conversion_utility(self, from_or_to): pass def maybe_unordered(self): if 'unordered' in self.cname: return 'unordered_' else: return '' def can_coerce_from_pyobject(self, env): if self.cname in builtin_cpp_conversions: template_count = builtin_cpp_conversions[self.cname] for ix, T in enumerate(self.templates or []): if ix >= template_count: break if T.is_pyobject or not T.can_coerce_from_pyobject(env): return False return True elif self.cname in cpp_string_conversions: return True return False def create_from_py_utility_code(self, env): if self.from_py_function is not None: return True if self.cname in builtin_cpp_conversions or self.cname in cpp_string_conversions: X = "XYZABC" tags = [] context = {} for ix, T in enumerate(self.templates or []): if ix >= builtin_cpp_conversions[self.cname]: break if T.is_pyobject or not T.create_from_py_utility_code(env): return False tags.append(T.specialization_name()) context[X[ix]] = T if self.cname in cpp_string_conversions: cls = 'string' tags = type_identifier(self), else: cls = self.cname[5:] cname = '__pyx_convert_%s_from_py_%s' % (cls, '__and_'.join(tags)) context.update({ 'cname': cname, 'maybe_unordered': self.maybe_unordered(), 'type': self.cname, }) # Override directives that should not be inherited from user code. from .UtilityCode import CythonUtilityCode directives = CythonUtilityCode.filter_inherited_directives(env.directives) env.use_utility_code(CythonUtilityCode.load( cls.replace('unordered_', '') + ".from_py", "CppConvert.pyx", context=context, compiler_directives=directives)) self.from_py_function = cname return True def can_coerce_to_pyobject(self, env): if self.cname in builtin_cpp_conversions or self.cname in cpp_string_conversions: for ix, T in enumerate(self.templates or []): if ix >= builtin_cpp_conversions[self.cname]: break if T.is_pyobject or not T.can_coerce_to_pyobject(env): return False return True def create_to_py_utility_code(self, env): if self.to_py_function is not None: return True if self.cname in builtin_cpp_conversions or self.cname in cpp_string_conversions: X = "XYZABC" tags = [] context = {} for ix, T in enumerate(self.templates or []): if ix >= builtin_cpp_conversions[self.cname]: break if not T.create_to_py_utility_code(env): return False tags.append(T.specialization_name()) context[X[ix]] = T if self.cname in cpp_string_conversions: cls = 'string' prefix = 'PyObject_' # gets specialised by explicit type casts in CoerceToPyTypeNode tags = type_identifier(self), else: cls = self.cname[5:] prefix = '' cname = "__pyx_convert_%s%s_to_py_%s" % (prefix, cls, "____".join(tags)) context.update({ 'cname': cname, 'maybe_unordered': self.maybe_unordered(), 'type': self.cname, }) from .UtilityCode import CythonUtilityCode # Override directives that should not be inherited from user code. directives = CythonUtilityCode.filter_inherited_directives(env.directives) env.use_utility_code(CythonUtilityCode.load( cls.replace('unordered_', '') + ".to_py", "CppConvert.pyx", context=context, compiler_directives=directives)) self.to_py_function = cname return True def is_template_type(self): return self.templates is not None and self.template_type is None def get_fused_types(self, result=None, seen=None, include_function_return_type=False): if result is None: result = [] seen = set() if self.namespace: self.namespace.get_fused_types(result, seen) if self.templates: for T in self.templates: T.get_fused_types(result, seen) return result def specialize_here(self, pos, env, template_values=None): if not self.is_template_type(): error(pos, "'%s' type is not a template" % self) return error_type if len(self.templates) - self.num_optional_templates <= len(template_values) < len(self.templates): num_defaults = len(self.templates) - len(template_values) partial_specialization = self.declaration_code('', template_params=template_values) # Most of the time we don't need to declare anything typed to these # default template arguments, but when we do there's no way in C++ # to reference this directly. However, it is common convention to # provide a typedef in the template class that resolves to each # template type. For now, allow the user to specify this name as # the template parameter. # TODO: Allow typedefs in cpp classes and search for it in this # classes scope as a concrete name we could use. template_values = template_values + [ TemplatePlaceholderType( "%s::%s" % (partial_specialization, param.name), True) for param in self.templates[-num_defaults:]] if len(self.templates) != len(template_values): error(pos, "%s templated type receives %d arguments, got %d" % (self.name, len(self.templates), len(template_values))) return error_type has_object_template_param = False for value in template_values: if value.is_pyobject or value.needs_refcounting: has_object_template_param = True type_description = "Python object" if value.is_pyobject else "Reference-counted" error(pos, "%s type '%s' cannot be used as a template argument" % ( type_description, value)) if has_object_template_param: return error_type return self.specialize(dict(zip(self.templates, template_values))) def specialize(self, values): if not self.templates and not self.namespace: return self if self.templates is None: self.templates = [] key = tuple(values.items()) if key in self.specializations: return self.specializations[key] template_values = [t.specialize(values) for t in self.templates] specialized = self.specializations[key] = \ CppClassType(self.name, None, self.cname, [], template_values, template_type=self) # Need to do these *after* self.specializations[key] is set # to avoid infinite recursion on circular references. specialized.base_classes = [b.specialize(values) for b in self.base_classes] if self.namespace is not None: specialized.namespace = self.namespace.specialize(values) specialized.scope = self.scope.specialize(values, specialized) if self.cname == 'std::vector': # vector<bool> is special cased in the C++ standard, and its # accessors do not necessarily return references to the underlying # elements (which may be bit-packed). # http://www.cplusplus.com/reference/vector/vector-bool/ # Here we pretend that the various methods return bool values # (as the actual returned values are coercable to such, and # we don't support call expressions as lvalues). T = values.get(self.templates[0], None) if T and not T.is_fused and T.empty_declaration_code() == 'bool': for bit_ref_returner in ('at', 'back', 'front'): if bit_ref_returner in specialized.scope.entries: specialized.scope.entries[bit_ref_returner].type.return_type = T return specialized def deduce_template_params(self, actual): if actual.is_cv_qualified: actual = actual.cv_base_type if actual.is_reference: actual = actual.ref_base_type if self == actual: return {} elif actual.is_cpp_class: self_template_type = self while getattr(self_template_type, 'template_type', None): self_template_type = self_template_type.template_type def all_bases(cls): yield cls for parent in cls.base_classes: for base in all_bases(parent): yield base for actual_base in all_bases(actual): template_type = actual_base while getattr(template_type, 'template_type', None): template_type = template_type.template_type if (self_template_type.empty_declaration_code() == template_type.empty_declaration_code()): return reduce( merge_template_deductions, [formal_param.deduce_template_params(actual_param) for (formal_param, actual_param) in zip(self.templates, actual_base.templates)], {}) else: return {} def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0, template_params = None): if template_params is None: template_params = self.templates if self.templates: template_strings = [param.declaration_code('', for_display, None, pyrex) for param in template_params if not is_optional_template_param(param) and not param.is_fused] if for_display: brackets = "[%s]" else: brackets = "<%s> " templates = brackets % ",".join(template_strings) else: templates = "" if pyrex or for_display: base_code = "%s%s" % (self.name, templates) else: base_code = "%s%s" % (self.cname, templates) if self.namespace is not None: base_code = "%s::%s" % (self.namespace.empty_declaration_code(), base_code) base_code = public_decl(base_code, dll_linkage) return self.base_declaration_code(base_code, entity_code) def cpp_optional_declaration_code(self, entity_code, dll_linkage=None, template_params=None): return "__Pyx_Optional_Type<%s> %s" % ( self.declaration_code("", False, dll_linkage, False, template_params), entity_code) def is_subclass(self, other_type): if self.same_as_resolved_type(other_type): return 1 for base_class in self.base_classes: if base_class.is_subclass(other_type): return 1 return 0 def subclass_dist(self, super_type): if self.same_as_resolved_type(super_type): return 0 elif not self.base_classes: return float('inf') else: return 1 + min(b.subclass_dist(super_type) for b in self.base_classes) def same_as_resolved_type(self, other_type): if other_type.is_cpp_class: if self == other_type: return 1 # This messy logic is needed due to GH Issue #1852. elif (self.cname == other_type.cname and (self.template_type and other_type.template_type or self.templates or other_type.templates)): if self.templates == other_type.templates: return 1 for t1, t2 in zip(self.templates, other_type.templates): if is_optional_template_param(t1) and is_optional_template_param(t2): break if not t1.same_as_resolved_type(t2): return 0 return 1 return 0 def assignable_from_resolved_type(self, other_type): # TODO: handle operator=(...) here? if other_type is error_type: return True elif other_type.is_cpp_class: return other_type.is_subclass(self) elif other_type.is_string and self.cname in cpp_string_conversions: return True def attributes_known(self): return self.scope is not None def find_cpp_operation_type(self, operator, operand_type=None): operands = [self] if operand_type is not None: operands.append(operand_type) # pos == None => no errors operator_entry = self.scope.lookup_operator_for_types(None, operator, operands) if not operator_entry: return None func_type = operator_entry.type if func_type.is_ptr: func_type = func_type.base_type return func_type.return_type def get_constructor(self, pos): constructor = self.scope.lookup('<init>') if constructor is not None: return constructor # Otherwise: automatically declare no-args default constructor. # Make it "nogil" if the base classes allow it. nogil = True for base in self.base_classes: base_constructor = base.scope.lookup('<init>') if base_constructor and not base_constructor.type.nogil: nogil = False break func_type = CFuncType(self, [], exception_check='+', nogil=nogil) return self.scope.declare_cfunction(u'<init>', func_type, pos) def check_nullary_constructor(self, pos, msg="stack allocated"): constructor = self.scope.lookup(u'<init>') if constructor is not None and best_match([], constructor.all_alternatives()) is None: error(pos, "C++ class must have a nullary constructor to be %s" % msg) def cpp_optional_check_for_null_code(self, cname): # only applies to c++ classes that are being declared as std::optional return "(%s.has_value())" % cname class CppScopedEnumType(CType): # name string # doc string or None # cname string is_cpp_enum = True def __init__(self, name, cname, underlying_type, namespace=None, doc=None): self.name = name self.doc = doc self.cname = cname self.values = [] self.underlying_type = underlying_type self.namespace = namespace def __str__(self): return self.name def declaration_code(self, entity_code, for_display=0, dll_linkage=None, pyrex=0): if pyrex or for_display: type_name = self.name else: if self.namespace: type_name = "%s::%s" % ( self.namespace.empty_declaration_code(), self.cname ) else: type_name = "__PYX_ENUM_CLASS_DECL %s" % self.cname type_name = public_decl(type_name, dll_linkage) return self.base_declaration_code(type_name, entity_code) def create_from_py_utility_code(self, env): if self.from_py_function: return True if self.underlying_type.create_from_py_utility_code(env): self.from_py_function = '(%s)%s' % ( self.cname, self.underlying_type.from_py_function ) return True def create_to_py_utility_code(self, env): if self.to_py_function is not None: return True if self.underlying_type.create_to_py_utility_code(env): # Using a C++11 lambda here, which is fine since # scoped enums are a C++11 feature self.to_py_function = '[](const %s& x){return %s((%s)x);}' % ( self.cname, self.underlying_type.to_py_function, self.underlying_type.empty_declaration_code() ) return True def create_type_wrapper(self, env): from .UtilityCode import CythonUtilityCode rst = CythonUtilityCode.load( "CppScopedEnumType", "CpdefEnums.pyx", context={ "name": self.name, "cname": self.cname.split("::")[-1], "items": tuple(self.values), "underlying_type": self.underlying_type.empty_declaration_code(), "enum_doc": self.doc, }, outer_module_scope=env.global_scope()) env.use_utility_code(rst) class TemplatePlaceholderType(CType): def __init__(self, name, optional=False): self.name = name self.optional = optional def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if entity_code: return self.name + " " + entity_code else: return self.name def specialize(self, values): if self in values: return values[self] else: return self def deduce_template_params(self, actual): return {self: actual} def same_as_resolved_type(self, other_type): if isinstance(other_type, TemplatePlaceholderType): return self.name == other_type.name else: return 0 def __hash__(self): return hash(self.name) def __cmp__(self, other): if isinstance(other, TemplatePlaceholderType): return cmp(self.name, other.name) else: return cmp(type(self), type(other)) def __eq__(self, other): if isinstance(other, TemplatePlaceholderType): return self.name == other.name else: return False def is_optional_template_param(type): return isinstance(type, TemplatePlaceholderType) and type.optional class CEnumType(CIntLike, CType): # name string # doc string or None # cname string or None # typedef_flag boolean # values [string], populated during declaration analysis is_enum = 1 signed = 1 rank = -1 # Ranks below any integer type def __init__(self, name, cname, typedef_flag, namespace=None, doc=None): self.name = name self.doc = doc self.cname = cname self.values = [] self.typedef_flag = typedef_flag self.namespace = namespace self.default_value = "(%s) 0" % self.empty_declaration_code() def __str__(self): return self.name def __repr__(self): return "<CEnumType %s %s%s>" % (self.name, self.cname, ("", " typedef")[self.typedef_flag]) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: base_code = self.name else: if self.namespace: base_code = "%s::%s" % ( self.namespace.empty_declaration_code(), self.cname) elif self.typedef_flag: base_code = self.cname else: base_code = "enum %s" % self.cname base_code = public_decl(base_code, dll_linkage) return self.base_declaration_code(base_code, entity_code) def specialize(self, values): if self.namespace: namespace = self.namespace.specialize(values) if namespace != self.namespace: return CEnumType( self.name, self.cname, self.typedef_flag, namespace) return self def create_type_wrapper(self, env): from .UtilityCode import CythonUtilityCode env.use_utility_code(CythonUtilityCode.load( "EnumType", "CpdefEnums.pyx", context={"name": self.name, "items": tuple(self.values), "enum_doc": self.doc, }, outer_module_scope=env.global_scope())) class CTupleType(CType): # components [PyrexType] is_ctuple = True def __init__(self, cname, components): self.cname = cname self.components = components self.size = len(components) self.to_py_function = "%s_to_py_%s" % (Naming.convert_func_prefix, self.cname) self.from_py_function = "%s_from_py_%s" % (Naming.convert_func_prefix, self.cname) self.exception_check = True self._convert_to_py_code = None self._convert_from_py_code = None def __str__(self): return "(%s)" % ", ".join(str(c) for c in self.components) def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): if pyrex or for_display: return str(self) else: return self.base_declaration_code(self.cname, entity_code) def can_coerce_to_pyobject(self, env): for component in self.components: if not component.can_coerce_to_pyobject(env): return False return True def can_coerce_from_pyobject(self, env): for component in self.components: if not component.can_coerce_from_pyobject(env): return False return True def create_to_py_utility_code(self, env): if self._convert_to_py_code is False: return None # tri-state-ish if self._convert_to_py_code is None: for component in self.components: if not component.create_to_py_utility_code(env): self.to_py_function = None self._convert_to_py_code = False return False context = dict( struct_type_decl=self.empty_declaration_code(), components=self.components, funcname=self.to_py_function, size=len(self.components) ) self._convert_to_py_code = TempitaUtilityCode.load( "ToPyCTupleUtility", "TypeConversion.c", context=context) env.use_utility_code(self._convert_to_py_code) return True def create_from_py_utility_code(self, env): if self._convert_from_py_code is False: return None # tri-state-ish if self._convert_from_py_code is None: for component in self.components: if not component.create_from_py_utility_code(env): self.from_py_function = None self._convert_from_py_code = False return False context = dict( struct_type_decl=self.empty_declaration_code(), components=self.components, funcname=self.from_py_function, size=len(self.components) ) self._convert_from_py_code = TempitaUtilityCode.load( "FromPyCTupleUtility", "TypeConversion.c", context=context) env.use_utility_code(self._convert_from_py_code) return True def cast_code(self, expr_code): return expr_code def c_tuple_type(components): components = tuple(components) cname = Naming.ctuple_type_prefix + type_list_identifier(components) tuple_type = CTupleType(cname, components) return tuple_type class UnspecifiedType(PyrexType): # Used as a placeholder until the type can be determined. is_unspecified = 1 def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): return "<unspecified>" def same_as_resolved_type(self, other_type): return False class ErrorType(PyrexType): # Used to prevent propagation of error messages. is_error = 1 exception_value = "0" exception_check = 0 to_py_function = "dummy" from_py_function = "dummy" def create_to_py_utility_code(self, env): return True def create_from_py_utility_code(self, env): return True def declaration_code(self, entity_code, for_display = 0, dll_linkage = None, pyrex = 0): return "<error>" def same_as_resolved_type(self, other_type): return 1 def error_condition(self, result_code): return "dummy" class PythonTypeConstructor(PyObjectType): """Used to help Cython interpret indexed types from the typing module (or similar) """ modifier_name = None def __init__(self, name, base_type=None): self.python_type_constructor_name = name self.base_type = base_type def specialize_here(self, pos, env, template_values=None): if self.base_type: # for a lot of the typing classes it doesn't really matter what the template is # (i.e. typing.Dict[int] is really just a dict) return self.base_type return self def __repr__(self): if self.base_type: return "%s[%r]" % (self.name, self.base_type) else: return self.name def is_template_type(self): return True class PythonTupleTypeConstructor(PythonTypeConstructor): def specialize_here(self, pos, env, template_values=None): if (template_values and None not in template_values and not any(v.is_pyobject for v in template_values)): entry = env.declare_tuple_type(pos, template_values) if entry: entry.used = True return entry.type return super(PythonTupleTypeConstructor, self).specialize_here(pos, env, template_values) class SpecialPythonTypeConstructor(PythonTypeConstructor): """ For things like ClassVar, Optional, etc, which are not types and disappear during type analysis. """ def __init__(self, name): super(SpecialPythonTypeConstructor, self).__init__(name, base_type=None) self.modifier_name = name def __repr__(self): return self.name def resolve(self): return self def specialize_here(self, pos, env, template_values=None): if len(template_values) != 1: error(pos, "'%s' takes exactly one template argument." % self.name) return error_type if template_values[0] is None: # FIXME: allowing unknown types for now since we don't recognise all Python types. return None # Replace this type with the actual 'template' argument. return template_values[0].resolve() rank_to_type_name = ( "char", # 0 "short", # 1 "int", # 2 "long", # 3 "PY_LONG_LONG", # 4 "float", # 5 "double", # 6 "long double", # 7 ) RANK_INT = rank_to_type_name.index('int') RANK_LONG = rank_to_type_name.index('long') RANK_FLOAT = rank_to_type_name.index('float') UNSIGNED = 0 SIGNED = 2 error_type = ErrorType() unspecified_type = UnspecifiedType() py_object_type = PyObjectType() c_void_type = CVoidType() c_uchar_type = CIntType(0, UNSIGNED) c_ushort_type = CIntType(1, UNSIGNED) c_uint_type = CIntType(2, UNSIGNED) c_ulong_type = CIntType(3, UNSIGNED) c_ulonglong_type = CIntType(4, UNSIGNED) c_char_type = CIntType(0) c_short_type = CIntType(1) c_int_type = CIntType(2) c_long_type = CIntType(3) c_longlong_type = CIntType(4) c_schar_type = CIntType(0, SIGNED) c_sshort_type = CIntType(1, SIGNED) c_sint_type = CIntType(2, SIGNED) c_slong_type = CIntType(3, SIGNED) c_slonglong_type = CIntType(4, SIGNED) c_float_type = CFloatType(5, math_h_modifier='f') c_double_type = CFloatType(6) c_longdouble_type = CFloatType(7, math_h_modifier='l') c_float_complex_type = CComplexType(c_float_type) c_double_complex_type = CComplexType(c_double_type) c_longdouble_complex_type = CComplexType(c_longdouble_type) c_anon_enum_type = CAnonEnumType(-1) c_returncode_type = CReturnCodeType(RANK_INT) c_bint_type = CBIntType(RANK_INT) c_py_unicode_type = CPyUnicodeIntType(RANK_INT-0.5, UNSIGNED) c_py_ucs4_type = CPyUCS4IntType(RANK_LONG-0.5, UNSIGNED) c_py_hash_t_type = CPyHashTType(RANK_LONG+0.5, SIGNED) c_py_ssize_t_type = CPySSizeTType(RANK_LONG+0.5, SIGNED) c_ssize_t_type = CSSizeTType(RANK_LONG+0.5, SIGNED) c_size_t_type = CSizeTType(RANK_LONG+0.5, UNSIGNED) c_ptrdiff_t_type = CPtrdiffTType(RANK_LONG+0.75, SIGNED) c_null_ptr_type = CNullPtrType(c_void_type) c_void_ptr_type = CPtrType(c_void_type) c_void_ptr_ptr_type = CPtrType(c_void_ptr_type) c_char_ptr_type = CPtrType(c_char_type) c_const_char_ptr_type = CPtrType(CConstType(c_char_type)) c_uchar_ptr_type = CPtrType(c_uchar_type) c_const_uchar_ptr_type = CPtrType(CConstType(c_uchar_type)) c_char_ptr_ptr_type = CPtrType(c_char_ptr_type) c_int_ptr_type = CPtrType(c_int_type) c_py_unicode_ptr_type = CPtrType(c_py_unicode_type) c_const_py_unicode_ptr_type = CPtrType(CConstType(c_py_unicode_type)) c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type) c_ssize_t_ptr_type = CPtrType(c_ssize_t_type) c_size_t_ptr_type = CPtrType(c_size_t_type) # GIL state c_gilstate_type = CEnumType("PyGILState_STATE", "PyGILState_STATE", True) c_threadstate_type = CStructOrUnionType("PyThreadState", "struct", None, 1, "PyThreadState") c_threadstate_ptr_type = CPtrType(c_threadstate_type) # PEP-539 "Py_tss_t" type c_pytss_t_type = CPyTSSTType() # the Py_buffer type is defined in Builtin.py c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer") c_py_buffer_ptr_type = CPtrType(c_py_buffer_type) # Not sure whether the unsigned versions and 'long long' should be in there # long long requires C99 and might be slow, and would always get preferred # when specialization happens through calling and not indexing cy_integral_type = FusedType([c_short_type, c_int_type, c_long_type], name="integral") # Omitting long double as it might be slow cy_floating_type = FusedType([c_float_type, c_double_type], name="floating") cy_numeric_type = FusedType([c_short_type, c_int_type, c_long_type, c_float_type, c_double_type, c_float_complex_type, c_double_complex_type], name="numeric") # buffer-related structs c_buf_diminfo_type = CStructOrUnionType("__Pyx_Buf_DimInfo", "struct", None, 1, "__Pyx_Buf_DimInfo") c_pyx_buffer_type = CStructOrUnionType("__Pyx_Buffer", "struct", None, 1, "__Pyx_Buffer") c_pyx_buffer_ptr_type = CPtrType(c_pyx_buffer_type) c_pyx_buffer_nd_type = CStructOrUnionType("__Pyx_LocalBuf_ND", "struct", None, 1, "__Pyx_LocalBuf_ND") cython_memoryview_type = CStructOrUnionType("__pyx_memoryview_obj", "struct", None, 0, "__pyx_memoryview_obj") memoryviewslice_type = CStructOrUnionType("memoryviewslice", "struct", None, 1, "__Pyx_memviewslice") modifiers_and_name_to_type = { #(signed, longness, name) : type (0, 0, "char"): c_uchar_type, (1, 0, "char"): c_char_type, (2, 0, "char"): c_schar_type, (0, -1, "int"): c_ushort_type, (0, 0, "int"): c_uint_type, (0, 1, "int"): c_ulong_type, (0, 2, "int"): c_ulonglong_type, (1, -1, "int"): c_short_type, (1, 0, "int"): c_int_type, (1, 1, "int"): c_long_type, (1, 2, "int"): c_longlong_type, (2, -1, "int"): c_sshort_type, (2, 0, "int"): c_sint_type, (2, 1, "int"): c_slong_type, (2, 2, "int"): c_slonglong_type, (1, 0, "float"): c_float_type, (1, 0, "double"): c_double_type, (1, 1, "double"): c_longdouble_type, (1, 0, "complex"): c_double_complex_type, # C: float, Python: double => Python wins (1, 0, "floatcomplex"): c_float_complex_type, (1, 0, "doublecomplex"): c_double_complex_type, (1, 1, "doublecomplex"): c_longdouble_complex_type, # (1, 0, "void"): c_void_type, (1, 0, "Py_tss_t"): c_pytss_t_type, (1, 0, "bint"): c_bint_type, (0, 0, "Py_UNICODE"): c_py_unicode_type, (0, 0, "Py_UCS4"): c_py_ucs4_type, (2, 0, "Py_hash_t"): c_py_hash_t_type, (2, 0, "Py_ssize_t"): c_py_ssize_t_type, (2, 0, "ssize_t") : c_ssize_t_type, (0, 0, "size_t") : c_size_t_type, (2, 0, "ptrdiff_t") : c_ptrdiff_t_type, (1, 0, "object"): py_object_type, } def is_promotion(src_type, dst_type): # It's hard to find a hard definition of promotion, but empirical # evidence suggests that the below is all that's allowed. if src_type.is_numeric: if dst_type.same_as(c_int_type): unsigned = (not src_type.signed) return (src_type.is_enum or (src_type.is_int and unsigned + src_type.rank < dst_type.rank)) elif dst_type.same_as(c_double_type): return src_type.is_float and src_type.rank <= dst_type.rank return False def best_match(arg_types, functions, pos=None, env=None, args=None): """ Given a list args of arguments and a list of functions, choose one to call which seems to be the "best" fit for this list of arguments. This function is used, e.g., when deciding which overloaded method to dispatch for C++ classes. We first eliminate functions based on arity, and if only one function has the correct arity, we return it. Otherwise, we weight functions based on how much work must be done to convert the arguments, with the following priorities: * identical types or pointers to identical types * promotions * non-Python types That is, we prefer functions where no arguments need converted, and failing that, functions where only promotions are required, and so on. If no function is deemed a good fit, or if two or more functions have the same weight, we return None (as there is no best match). If pos is not None, we also generate an error. """ # TODO: args should be a list of types, not a list of Nodes. actual_nargs = len(arg_types) candidates = [] errors = [] for func in functions: error_mesg = "" func_type = func.type if func_type.is_ptr: func_type = func_type.base_type # Check function type if not func_type.is_cfunction: if not func_type.is_error and pos is not None: error_mesg = "Calling non-function type '%s'" % func_type errors.append((func, error_mesg)) continue # Check no. of args max_nargs = len(func_type.args) min_nargs = max_nargs - func_type.optional_arg_count if actual_nargs < min_nargs or (not func_type.has_varargs and actual_nargs > max_nargs): if max_nargs == min_nargs and not func_type.has_varargs: expectation = max_nargs elif actual_nargs < min_nargs: expectation = "at least %s" % min_nargs else: expectation = "at most %s" % max_nargs error_mesg = "Call with wrong number of arguments (expected %s, got %s)" \ % (expectation, actual_nargs) errors.append((func, error_mesg)) continue if func_type.templates: # For any argument/parameter pair A/P, if P is a forwarding reference, # use lvalue-reference-to-A for deduction in place of A when the # function call argument is an lvalue. See: # https://en.cppreference.com/w/cpp/language/template_argument_deduction#Deduction_from_a_function_call arg_types_for_deduction = list(arg_types) if func.type.is_cfunction and args: for i, formal_arg in enumerate(func.type.args): if formal_arg.is_forwarding_reference(): if args[i].is_lvalue(): arg_types_for_deduction[i] = c_ref_type(arg_types[i]) deductions = reduce( merge_template_deductions, [pattern.type.deduce_template_params(actual) for (pattern, actual) in zip(func_type.args, arg_types_for_deduction)], {}) if deductions is None: errors.append((func, "Unable to deduce type parameters for %s given (%s)" % ( func_type, ', '.join(map(str, arg_types_for_deduction))))) elif len(deductions) < len(func_type.templates): errors.append((func, "Unable to deduce type parameter %s" % ( ", ".join([param.name for param in set(func_type.templates) - set(deductions.keys())])))) else: type_list = [deductions[param] for param in func_type.templates] from .Symtab import Entry specialization = Entry( name = func.name + "[%s]" % ",".join([str(t) for t in type_list]), cname = func.cname + "<%s>" % ",".join([t.empty_declaration_code() for t in type_list]), type = func_type.specialize(deductions), pos = func.pos) candidates.append((specialization, specialization.type)) else: candidates.append((func, func_type)) # Optimize the most common case of no overloading... if len(candidates) == 1: return candidates[0][0] elif len(candidates) == 0: if pos is not None: func, errmsg = errors[0] if len(errors) == 1 or [1 for func, e in errors if e == errmsg]: error(pos, errmsg) else: error(pos, "no suitable method found") return None possibilities = [] bad_types = [] needed_coercions = {} for index, (func, func_type) in enumerate(candidates): score = [0,0,0,0,0,0,0] for i in range(min(actual_nargs, len(func_type.args))): src_type = arg_types[i] dst_type = func_type.args[i].type assignable = dst_type.assignable_from(src_type) # Now take care of unprefixed string literals. So when you call a cdef # function that takes a char *, the coercion will mean that the # type will simply become bytes. We need to do this coercion # manually for overloaded and fused functions if not assignable: c_src_type = None if src_type.is_pyobject: if src_type.is_builtin_type and src_type.name == 'str' and dst_type.resolve().is_string: c_src_type = dst_type.resolve() else: c_src_type = src_type.default_coerced_ctype() elif src_type.is_pythran_expr: c_src_type = src_type.org_buffer if c_src_type is not None: assignable = dst_type.assignable_from(c_src_type) if assignable: src_type = c_src_type needed_coercions[func] = (i, dst_type) if assignable: if src_type == dst_type or dst_type.same_as(src_type): pass # score 0 elif func_type.is_strict_signature: break # exact match requested but not found elif is_promotion(src_type, dst_type): score[2] += 1 elif ((src_type.is_int and dst_type.is_int) or (src_type.is_float and dst_type.is_float)): score[2] += abs(dst_type.rank + (not dst_type.signed) - (src_type.rank + (not src_type.signed))) + 1 elif dst_type.is_ptr and src_type.is_ptr: if dst_type.base_type == c_void_type: score[4] += 1 elif src_type.base_type.is_cpp_class and src_type.base_type.is_subclass(dst_type.base_type): score[6] += src_type.base_type.subclass_dist(dst_type.base_type) else: score[5] += 1 elif not src_type.is_pyobject: score[1] += 1 else: score[0] += 1 else: error_mesg = "Invalid conversion from '%s' to '%s'" % (src_type, dst_type) bad_types.append((func, error_mesg)) break else: possibilities.append((score, index, func)) # so we can sort it if possibilities: possibilities.sort() if len(possibilities) > 1: score1 = possibilities[0][0] score2 = possibilities[1][0] if score1 == score2: if pos is not None: error(pos, "ambiguous overloaded method") return None function = possibilities[0][-1] if function in needed_coercions and env: arg_i, coerce_to_type = needed_coercions[function] args[arg_i] = args[arg_i].coerce_to(coerce_to_type, env) return function if pos is not None: if len(bad_types) == 1: error(pos, bad_types[0][1]) else: error(pos, "no suitable method found") return None def merge_template_deductions(a, b): if a is None or b is None: return None all = a for param, value in b.items(): if param in all: if a[param] != b[param]: return None else: all[param] = value return all def widest_numeric_type(type1, type2): """Given two numeric types, return the narrowest type encompassing both of them. """ if type1.is_reference: type1 = type1.ref_base_type if type2.is_reference: type2 = type2.ref_base_type if type1.is_cv_qualified: type1 = type1.cv_base_type if type2.is_cv_qualified: type2 = type2.cv_base_type if type1 == type2: widest_type = type1 elif type1.is_complex or type2.is_complex: def real_type(ntype): if ntype.is_complex: return ntype.real_type return ntype widest_type = CComplexType( widest_numeric_type( real_type(type1), real_type(type2))) elif type1.is_enum and type2.is_enum: widest_type = c_int_type elif type1.rank < type2.rank: widest_type = type2 elif type1.rank > type2.rank: widest_type = type1 elif type1.signed < type2.signed: widest_type = type1 elif type1.signed > type2.signed: widest_type = type2 elif type1.is_typedef > type2.is_typedef: widest_type = type1 else: widest_type = type2 return widest_type def numeric_type_fits(small_type, large_type): return widest_numeric_type(small_type, large_type) == large_type def independent_spanning_type(type1, type2): # Return a type assignable independently from both type1 and # type2, but do not require any interoperability between the two. # For example, in "True * 2", it is safe to assume an integer # result type (so spanning_type() will do the right thing), # whereas "x = True or 2" must evaluate to a type that can hold # both a boolean value and an integer, so this function works # better. if type1.is_reference ^ type2.is_reference: if type1.is_reference: type1 = type1.ref_base_type else: type2 = type2.ref_base_type resolved_type1 = type1.resolve() resolved_type2 = type2.resolve() if resolved_type1 == resolved_type2: return type1 elif ((resolved_type1 is c_bint_type or resolved_type2 is c_bint_type) and (type1.is_numeric and type2.is_numeric)): # special case: if one of the results is a bint and the other # is another C integer, we must prevent returning a numeric # type so that we do not lose the ability to coerce to a # Python bool if we have to. return py_object_type span_type = _spanning_type(type1, type2) if span_type is None: return error_type return span_type def spanning_type(type1, type2): # Return a type assignable from both type1 and type2, or # py_object_type if no better type is found. Assumes that the # code that calls this will try a coercion afterwards, which will # fail if the types cannot actually coerce to a py_object_type. if type1 == type2: return type1 elif type1 is py_object_type or type2 is py_object_type: return py_object_type elif type1 is c_py_unicode_type or type2 is c_py_unicode_type: # Py_UNICODE behaves more like a string than an int return py_object_type span_type = _spanning_type(type1, type2) if span_type is None: return py_object_type return span_type def _spanning_type(type1, type2): if type1.is_numeric and type2.is_numeric: return widest_numeric_type(type1, type2) elif type1.is_builtin_type and type1.name == 'float' and type2.is_numeric: return widest_numeric_type(c_double_type, type2) elif type2.is_builtin_type and type2.name == 'float' and type1.is_numeric: return widest_numeric_type(type1, c_double_type) elif type1.is_extension_type and type2.is_extension_type: return widest_extension_type(type1, type2) elif type1.is_pyobject or type2.is_pyobject: return py_object_type elif type1.assignable_from(type2): if type1.is_extension_type and type1.typeobj_is_imported(): # external types are unsafe, so we use PyObject instead return py_object_type return type1 elif type2.assignable_from(type1): if type2.is_extension_type and type2.typeobj_is_imported(): # external types are unsafe, so we use PyObject instead return py_object_type return type2 elif type1.is_ptr and type2.is_ptr: if type1.base_type.is_cpp_class and type2.base_type.is_cpp_class: common_base = widest_cpp_type(type1.base_type, type2.base_type) if common_base: return CPtrType(common_base) # incompatible pointers, void* will do as a result return c_void_ptr_type else: return None def widest_extension_type(type1, type2): if type1.typeobj_is_imported() or type2.typeobj_is_imported(): return py_object_type while True: if type1.subtype_of(type2): return type2 elif type2.subtype_of(type1): return type1 type1, type2 = type1.base_type, type2.base_type if type1 is None or type2 is None: return py_object_type def widest_cpp_type(type1, type2): @cached_function def bases(type): all = set() for base in type.base_classes: all.add(base) all.update(bases(base)) return all common_bases = bases(type1).intersection(bases(type2)) common_bases_bases = reduce(set.union, [bases(b) for b in common_bases], set()) candidates = [b for b in common_bases if b not in common_bases_bases] if len(candidates) == 1: return candidates[0] else: # Fall back to void* for now. return None def simple_c_type(signed, longness, name): # Find type descriptor for simple type given name and modifiers. # Returns None if arguments don't make sense. return modifiers_and_name_to_type.get((signed, longness, name)) def parse_basic_type(name): base = None if name.startswith('p_'): base = parse_basic_type(name[2:]) elif name.startswith('p'): base = parse_basic_type(name[1:]) elif name.endswith('*'): base = parse_basic_type(name[:-1]) if base: return CPtrType(base) # basic_type = simple_c_type(1, 0, name) if basic_type: return basic_type # signed = 1 longness = 0 if name == 'Py_UNICODE': signed = 0 elif name == 'Py_UCS4': signed = 0 elif name == 'Py_hash_t': signed = 2 elif name == 'Py_ssize_t': signed = 2 elif name == 'ssize_t': signed = 2 elif name == 'size_t': signed = 0 else: if name.startswith('u'): name = name[1:] signed = 0 elif (name.startswith('s') and not name.startswith('short')): name = name[1:] signed = 2 longness = 0 while name.startswith('short'): name = name.replace('short', '', 1).strip() longness -= 1 while name.startswith('long'): name = name.replace('long', '', 1).strip() longness += 1 if longness != 0 and not name: name = 'int' return simple_c_type(signed, longness, name) def _construct_type_from_base(cls, base_type, *args): if base_type is error_type: return error_type return cls(base_type, *args) def c_array_type(base_type, size): # Construct a C array type. return _construct_type_from_base(CArrayType, base_type, size) def c_ptr_type(base_type): # Construct a C pointer type. if base_type.is_reference: base_type = base_type.ref_base_type return _construct_type_from_base(CPtrType, base_type) def c_ref_type(base_type): # Construct a C reference type return _construct_type_from_base(CReferenceType, base_type) def cpp_rvalue_ref_type(base_type): # Construct a C++ rvalue reference type return _construct_type_from_base(CppRvalueReferenceType, base_type) def c_const_type(base_type): # Construct a C const type. return _construct_type_from_base(CConstType, base_type) def c_const_or_volatile_type(base_type, is_const, is_volatile): # Construct a C const/volatile type. return _construct_type_from_base(CConstOrVolatileType, base_type, is_const, is_volatile) def same_type(type1, type2): return type1.same_as(type2) def assignable_from(type1, type2): return type1.assignable_from(type2) def typecast(to_type, from_type, expr_code): # Return expr_code cast to a C type which can be # assigned to to_type, assuming its existing C type # is from_type. if (to_type is from_type or (not to_type.is_pyobject and assignable_from(to_type, from_type))): return expr_code elif (to_type is py_object_type and from_type and from_type.is_builtin_type and from_type.name != 'type'): # no cast needed, builtins are PyObject* already return expr_code else: #print "typecast: to", to_type, "from", from_type ### return to_type.cast_code(expr_code) def type_list_identifier(types): return cap_length('__and_'.join(type_identifier(type) for type in types)) _special_type_characters = { '__': '__dunder', 'const ': '__const_', ' ': '__space_', '*': '__ptr', '&': '__ref', '&&': '__fwref', '[': '__lArr', ']': '__rArr', '<': '__lAng', '>': '__rAng', '(': '__lParen', ')': '__rParen', ',': '__comma_', '...': '__EL', '::': '__in_', ':': '__D', } _escape_special_type_characters = partial(re.compile( # join substrings in reverse order to put longer matches first, e.g. "::" before ":" " ?(%s) ?" % "|".join(re.escape(s) for s in sorted(_special_type_characters, reverse=True)) ).sub, lambda match: _special_type_characters[match.group(1)]) def type_identifier(type, pyrex=False): decl = type.empty_declaration_code(pyrex=pyrex) return type_identifier_from_declaration(decl) _type_identifier_cache = {} def type_identifier_from_declaration(decl): safe = _type_identifier_cache.get(decl) if safe is None: safe = decl safe = re.sub(' +', ' ', safe) safe = re.sub(' ?([^a-zA-Z0-9_]) ?', r'\1', safe) safe = _escape_special_type_characters(safe) safe = cap_length(re.sub('[^a-zA-Z0-9_]', lambda x: '__%X' % ord(x.group(0)), safe)) _type_identifier_cache[decl] = safe return safe def cap_length(s, max_prefix=63, max_len=1024): if len(s) <= max_prefix: return s hash_prefix = hashlib.sha256(s.encode('ascii')).hexdigest()[:6] return '%s__%s__etc' % (hash_prefix, s[:max_len-17])
{ "content_hash": "cceda328366456238b22b4818db61288", "timestamp": "", "source": "github", "line_count": 5199, "max_line_length": 134, "avg_line_length": 37.387382188882476, "alnum_prop": 0.5796210456998513, "repo_name": "cython/cython", "id": "da30809a37d1f7c52331bb7bec8ab6a31f6407d4", "size": "194415", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Cython/Compiler/PyrexTypes.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1429" }, { "name": "C", "bytes": "786161" }, { "name": "C++", "bytes": "32603" }, { "name": "Cython", "bytes": "3391513" }, { "name": "Emacs Lisp", "bytes": "12379" }, { "name": "Makefile", "bytes": "3184" }, { "name": "PowerShell", "bytes": "4022" }, { "name": "Python", "bytes": "4081204" }, { "name": "Shell", "bytes": "6371" }, { "name": "Smalltalk", "bytes": "618" }, { "name": "Starlark", "bytes": "3341" }, { "name": "sed", "bytes": "807" } ], "symlink_target": "" }
import os from models import Advertisement, Municipality, ObjectType import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sqlalchemy import create_engine from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.linear_model import LassoLarsCV, Ridge, RidgeCV, LassoCV, Lasso, LinearRegression, LogisticRegression from sklearn.naive_bayes import MultinomialNB from sqlalchemy.orm import sessionmaker, defer, load_only, aliased from sqlalchemy.sql import select from sqlalchemy.sql.expression import join from sklearn.feature_extraction.text import CountVectorizer from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import SGDClassifier, SGDRegressor import re import ast import json import nltk import sys from nltk.corpus import stopwords # Import the stop word list from nltk.stem import SnowballStemmer from jupyter import statistics, plot OBJECT_TYPES = {'description': str, 'desc': str, 'groupint': str, 'characteristics': object} import pdb def select_from_database(url=os.environ.get('DATABASE_URL', None)): engine = create_engine(os.environ.get('DATABASE_URL', None)) Session = sessionmaker(bind=engine) session = Session() ot = aliased(ObjectType) ad = aliased(Advertisement) s = select([ad.price_brutto.label('price'), ad.description.label('description'), ad.living_area.label('living_area'), ad.characteristics.label('characteristics'), # ad.additional_data.label('additional_data'), # Not much important stuff some distances ot.grouping.label('grouping'), #Municipality.canton_id.label('canton') # ended.quarter.label('equarter'), ] ).select_from( join(ad, Municipality, isouter=False) .join(ot, ad.object_types_id==ot.id, isouter=False) #.join(ended, Ad.ended_id == ended.id, isouter=False) ).where(ad.build_year >= 1000) return pd.read_sql_query(s, session.bind) def select_from_file(file): return pd.read_csv(file, index_col=0, engine='c', dtype=OBJECT_TYPES) def detect_language(text): """ detect the language by the text where the most stopwords for a language are found """ languages_ratios = {} tokens = nltk.wordpunct_tokenize(text) words_set = set([word.lower() for word in tokens]) for language in ['german', 'french', 'italian']: stopwords_set = set(stopwords.words(language)) languages_ratios[language] = len(words_set.intersection(stopwords_set)) # language "score" return max(languages_ratios, key=languages_ratios.get) def stemm_words(row): language = detect_language(row.description) #letters_only = re.sub("[^a-z0-9üÀâèéàΓͺΓ’]", " ", str(row.desc.lower())) letters_only = row.description.split() stops = set(stopwords.words(language)) meaningful_words = [w for w in letters_only if not w in stops] stemmer = SnowballStemmer(language) stemmed_words = [stemmer.stem(w) for w in meaningful_words] return " ".join(stemmed_words) def category_ads(low, high): def return_func(row): if row.price > high: return 'high' if row.price <= high and row.price > low: return 'normal' return 'budget' return return_func # def to_words(self, desc): # letters_only = re.sub("[^a-zA-Z]", " ", str(desc)) # words = letters_only.lower().split() # stops = set(stopwords.words("german")) # meaningful_words = [w for w in words if not w in stops] # return( " ".join( meaningful_words )) def ape(y_true, y_pred): return np.abs(y_true - y_pred) / y_true def mape(y_true, y_pred): return ape(y_true, y_pred).mean() def mdape(y_true, y_pred): return np.median(ape(y_true, y_pred)) def statistics(y, pred): diff = np.fabs(y - pred) print(" RΒ²-Score: {:10n}".format(metrics.r2_score(y, pred))) print(" MAPE: {:.3%}".format(mape(y, pred))) print(" MdAPE: {:.3%}".format(mdape(y, pred))) print(" Min error: {:10n}".format(np.amin(diff))) print(" Max error: {:10n}".format(np.amax(diff))) print(" Mean absolute error: {:10n}".format(metrics.mean_absolute_error(y, pred))) print("Median absolute error: {:10n}".format(metrics.median_absolute_error(y, pred))) print(" Mean squared error: {:10n}".format(metrics.mean_squared_error(y, pred))) num_elements = len(pred) apes = ape(y, pred) for i in np.arange(5, 100, 5): print("I {}: {}".format(i, len(np.where(apes < i/100)[0])/num_elements)) if __name__ == "__main__": # From database #advertisements = select_from_database(url=os.environ.get('DATABASE_URL', None)) #advertisements.to_csv('description_analyse.csv', header=True, encoding='utf-8') # From file #advertisements = select_from_file('all.csv') #advertisements.drop(['noise_level', 'm_noise_level', 'floor', 'last_renovation_year'], axis=1, inplace=True) #advertisements = advertisements.dropna() # Remove empty entries #advertisements.reindex() # Convert decription to unicode, otherwise NaN is inserted #advertisements['description'] = advertisements['description'].astype('U') #advertisements['desc'] = advertisements.apply(stemm_words, axis=1) #advertisements.to_csv('category_ads.csv', header=True, encoding='utf-8') # From file advertisements = select_from_file('desc_analyse.csv') advertisements['characteristics'] = advertisements['characteristics'].apply(ast.literal_eval) series = [] bath_keys = ['Badezimmer', 'Badewannen', 'WCs', 'Duschen', 'Toiletten'] for index, ad in advertisements.iterrows(): if type(ad['characteristics']) == list: continue bath = {} for key, value in ad['characteristics'].items(): if key in bath_keys: bath[key] = int(value) bath['living_area'] = ad['living_area'] bath['desc'] = ad['desc'] #bath['num_room'] = ad['num_room'] series.append(bath) df = pd.DataFrame(series) df['bath_max'] = df[['Badezimmer', 'Badewannen', 'WCs', 'Duschen', 'Toiletten']].apply(lambda x: np.mean(x), axis=1) sns.lmplot('bath_max', 'living_area', data=df) plt.show() X_desc = df['desc'].astype('U').values y = df['bath_max'].values count_vect = CountVectorizer(analyzer="word", tokenizer=None, preprocessor=None, stop_words=None, max_features=5000) X_train_counts = count_vect.fit_transform(X_desc) tfidf_transformer = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) temp_df = pd.DataFrame(X_train_counts.todense()) temp_df['living_area'] = df['living_area'].values X = temp_df.values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) alpha = 0.006 print("Best alpha: {}".format(alpha)) lassoreg = Lasso(alpha=alpha, normalize=True, max_iter=1e5) lassoreg.fit(X_train, y_train) y_pred = lassoreg.predict(X_test) statistics(y_test, y_pred) plot(y_test, y_pred, show=True, plot_name="lasso") # plt.figure(figsize=(10, 8)) # g = sns.barplot(y=list(chars.keys()), x=list(chars.values())) # g.tick_params(axis='y', labelsize=5) sys.exit(0) for group in [('haus',(700000, 1500000)), ('wohnung', (500000, 1000000))]: ads = pd.DataFrame(advertisements[advertisements['grouping'] == group[0]]) print("Read {} {} data".format(len(ads), group[0])) # sns.distplot(ads['price'], kde=True, bins=300, hist_kws={'alpha': 0.6}) # plt.show() # print(ads.price.describe()) # Make categories low, high ads['category'] = ads.apply(category_ads(group[1][0], group[1][1]), axis=1) X = ads['desc'].astype('U').values y = ads['category'].values X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) count_vect = CountVectorizer(analyzer="word", tokenizer=None, preprocessor=None, stop_words=None, max_features=5000) X_train_counts = count_vect.fit_transform(X_train) tfidf_transformer = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) #clf = RandomForestClassifier(n_estimators = 100) #clf = clf.fit(X_train_tfidf, y_train) for alpha in [1e-12, 1e-11, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 3e-4, 1e-3]: # 3e-3, 0.01, 0.03 ,0.1, 0.3, 1, 3, 10, 30 clf = SGDClassifier(loss="log", penalty='l2', alpha=alpha, n_iter=100, random_state=42).fit(X_train_tfidf, y_train) # clf = MultinomialNB().fit(X_train_tfidf, y_train) X_new_counts = count_vect.transform(X_test) X_new_tfidf = tfidf_transformer.transform(X_new_counts) predicted = clf.predict(X_new_tfidf) # for doc, category in zip(y_test, predicted): # print('%r => %s' % (doc, category)) print("RESULTS for {} with alpha: {}".format(group, alpha)) print(np.mean(predicted == y_test)) print(metrics.classification_report(y_test, predicted)) # words = [] # for i in range(0, len(ds.ads) ): # # If the index is evenly divisible by 1000, print a message # if (i+1)%1000 == 0: # print("Review {} of {}".format(i+1, len(ds.ads))) # words.append(ds.to_words(ds.ads['description'][i])) # ds.ads['desc'] = words # ds.ads.to_csv('description_analyse.csv', header=True, encoding='utf-8')
{ "content_hash": "2bdcd48165232500cc434f03314aa35a", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 135, "avg_line_length": 40.83817427385892, "alnum_prop": 0.6306644990855517, "repo_name": "bhzunami/Immo", "id": "b1860031d25f3489bfe8e95f52a5d6e2fd1f2f35", "size": "9851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "immo/scikit/scripts/data_selection.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4084" }, { "name": "Jupyter Notebook", "bytes": "894963" }, { "name": "PostScript", "bytes": "736084" }, { "name": "Python", "bytes": "235278" }, { "name": "Shell", "bytes": "1283" }, { "name": "TeX", "bytes": "171788" } ], "symlink_target": "" }
''' Load and Preprocess Sample Images Before supplying an image to a pre-trained network in Keras, there are some required preprocessing steps. You will learn more about this in the project; for now, we have implemented this functionality for you in the first code cell of the notebook. We have imported a very small dataset of 8 images and stored the preprocessed image input as img_input. Note that the dimensionality of this array is (8, 224, 224, 3). In this case, each of the 8 images is a 3D tensor, with shape (224, 224, 3). ''' from keras.applications.vgg16 import preprocess_input from keras.preprocessing import image import numpy as np import glob img_paths = glob.glob("images/*.jpg") def path_to_tensor(img_path): # loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(224, 224)) # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3) x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor return np.expand_dims(x, axis=0) def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in img_paths] return np.vstack(list_of_tensors) # calculate the image input. you will learn more about how this works the project! img_input = preprocess_input(paths_to_tensor(img_paths)) print(img_input.shape) #Recall how we import the VGG-16 network (including the final classification layer) that has been pre-trained on ImageNet. from keras.applications.vgg16 import VGG16 model = VGG16() model.summary() model.predict(img_input).shape ''' Import the VGG-16 Model, with the Final Fully-Connected Layers Removed When performing transfer learning, we need to remove the final layers of the network, as they are too specific to the ImageNet database. This is accomplished in the code cell below. ''' model = VGG16(include_top=False) model.summary() ''' Extract Output of Final Max Pooling Layer Now, the network stored in model is a truncated version of the VGG-16 network, where the final three fully-connected layers have been removed. In this case, model.predict returns a 3D array (with dimensions 7Γ—7Γ—5127Γ—7Γ—512 ) corresponding to the final max pooling layer of VGG-16. The dimensionality of the obtained output from passing img_input through the model is (8, 7, 7, 512). The first value of 8 merely denotes that 8 images were passed through the network. ''' print(model.predict(img_input).shape) #This is exactly how we calculate the bottleneck features for your project!
{ "content_hash": "494b37234dd1d32845eddf2ece61bdee", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 122, "avg_line_length": 41.868852459016395, "alnum_prop": 0.7576350822239624, "repo_name": "coolsgupta/machine_learning_nanodegree", "id": "514b9a2ef0d63b3b09cdd7b3f5052ae505c3b623", "size": "2558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Deep_Learning/CNN/transfer learning/transfer_learning_implementation.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "82767" } ], "symlink_target": "" }
from bongo.apps.bongo import models from rest_framework import serializers class AdvertiserSerializer(serializers.ModelSerializer): class Meta: model = models.Advertiser fields = ('id', 'name',)
{ "content_hash": "bb52882de1127c360b1db366c3f9564a", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 27.125, "alnum_prop": 0.7235023041474654, "repo_name": "BowdoinOrient/bongo", "id": "40cc63c31d29f1107cd03da341445fd5eed91fdd", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "bongo/apps/api/serializers/advertiser.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26609" }, { "name": "HTML", "bytes": "20898" }, { "name": "JavaScript", "bytes": "3005" }, { "name": "Python", "bytes": "169382" }, { "name": "Shell", "bytes": "2173" } ], "symlink_target": "" }
from .context import procamcalib import unittest class AdvancedTestSuite(unittest.TestCase): """Advanced test cases.""" def test_thoughts(self): procamcalib.core.hello() if __name__ == '__main__': unittest.main()
{ "content_hash": "11f028ce7a0f5d063a32156596f49001", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 43, "avg_line_length": 17.071428571428573, "alnum_prop": 0.6610878661087866, "repo_name": "I2Cvb/procamcalib", "id": "80812cdc6da57b8798a169d0b4df16aa8e3c48ca", "size": "264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_advanced.py", "mode": "33261", "license": "mit", "language": [ { "name": "Makefile", "bytes": "83" }, { "name": "Python", "bytes": "2190" } ], "symlink_target": "" }
import json import logging import threading import socket import select import uuid import time from plugs import PlugLess, PlugLs from ssh_channel import SSHChannel SESSION_TIMEOUT = 300 BUFF_SIZE = 512 OUT_BUFF_SIZE = 512 # TODO check maximum allowed chunk size for nonblocking write logger = logging.getLogger('%s'%(__name__)) logger.addHandler(logging.NullHandler()) class WebClient(threading.Thread): PL_ACTIVE = True PL_IDLE = False def __init__(self, sock, addr): """ @param sock - client's socket object @param addr - client's addr, used by logger """ threading.Thread.__init__(self) self.name = '['+str(addr)+']: ' self.sock = sock self._buff = '' self._out_buff = [] self._sock_write_fd = [] self._sock_read_fd = [self.sock] self.running = True self._sessions = {} # key: ssh connection uuid; value: list [ssh connection, last timestamp] self._log_sessions = {} # key: logfile uuid; value: list [plug instance, is_active, current_command, conn_id] def recv_from_client(self, data): self._buff = self._buff + str(data) if '\r\n' in self._buff: raw_cmd, self._buff = self._buff.split('\r\n', 1) else: if len(self._buff)>1024: logger.warning(self.name+'Input buffer overrun, longer than 1024 bytes: %s'%self._buff) self._buff = '' return logger.debug(self.name+"some data has arrived: " + raw_cmd) try: req = json.loads(raw_cmd) except (ValueError, TypeError) as e: logger.warning(self.name+"Not a JSON! Ignoring...") return if req.get('cmd', None) == None: logger.warning(self.name+"there is no 'cmd' field! Ignoring...") return cmd = req['cmd'] logger.info(self.name+"cmd = "+cmd) conn_id = req.get('conn_id', None) log_id = req.get('log_id', None) if cmd == 'connect': self._connect(**req) return elif self._is_valid(conn_id=conn_id): if cmd == 'log_open': self._log_open(**req) return elif cmd == 'get_dir': self._get_dir(**req) return elif cmd == 'close': self._disconnect(conn_id) elif self._is_valid(log_id=log_id): if cmd in ['log_page', 'log_next', 'log_prev', 'log_pos', 'log_close']: self._log_cmd(**req) return logger.warning(self.name+"unable to excecute command: " + req['cmd']) def run(self): while self.running: reads,w,x = select.select(self._sock_read_fd, self._sock_write_fd, self._sock_read_fd ,0.5) for read_obj in reads: if read_obj==self.sock: data = self.sock.recv(BUFF_SIZE) if not data: logger.info(self.name+"Client disconnect") self._client_disconnect() return self.recv_from_client(data) else: if read_obj.check_response(): log_id = read_obj.__log_id if self._log_sessions[log_id][1]: self._log_response(log_id) if w: self.send_to_client() for ex_obj in x: if ex_obj==self.sock: logger.error(self.name+ "Client's connection error") self._client_disconnect() return else: logger.error(self.name+ "Log channel error, log_id=%s"%ex_obj.__log_id) self._disconnect_log(ex_obj.__log_id) self._pool_expired() def _pool_expired(self): expired = [] for log_id, (log, status, cmd, conn) in self._log_sessions.iteritems(): if log.channel.exit_status_ready(): logger.warning(self.name+"Log channel has been unexpectedly closed,\ log_id=%s"%log_id) expired.append(log_id) for l in expired: self._disconnect_log(l) expired = [] for conn_id, (conn, prev_time) in self._sessions.iteritems(): if prev_time + SESSION_TIMEOUT < time.time(): logger.warning(self.name+"SSH session has expired,\ conn_id=%s"%conn_id) expired.append(conn_id) for c in expired: self._disconnect(c) def stop(self): self.running = False def _client_disconnect(self): logger.info(self.name+'Terminating') self.running = False self.sock.close() rm_list = self._sessions.keys() for rm_id in rm_list: self._disconnect(rm_id) def _get_dir(self, **kwargs): path = kwargs.get('path', '') conn_id = kwargs['conn_id'] conn = self._touch_conn(conn_id) kwargs['ssh'] = conn try: ls_exec = PlugLs(**kwargs) except Exception as e: logger.warning(self.name+'Unable to run ls: %s'%str(e)) res = {'cmd':kwargs['cmd'], 'res':'error', 'data':str(e)} else: ls_exec.put_request(path) ls_exec.check_response() (out, err) = ls_exec.get_result() if err==[]: ex_res = 'ok' data = out else: ex_res = 'err' data = err res = {'cmd':kwargs['cmd'], 'res':ex_res, 'data':data} self._put_answer_in_queue(res) def _connect(self, **kwargs): host = kwargs.get('host', None) port = kwargs.get('port', 22) user = kwargs.get('user', None) secret = kwargs.get('secret',None) try: ssh_conn = SSHChannel(host=host, port=port, user=user, secret=secret) ssh_conn.connect() except Exception as e: logger.warning('Unable to start ssh session: %s'%str(e)) res = {'cmd':kwargs['cmd'], 'res':'error'} else: conn_id = str(uuid.uuid4()) self._sessions[conn_id] = [ssh_conn, time.time()] logger.info(self.name+'New ssh session was registered, conn_id = %s' % conn_id) res = {'cmd':kwargs['cmd'], 'res':'ok', 'conn_id':conn_id} self._put_answer_in_queue(res) def _log_open(self, **kwargs): conn_id = kwargs['conn_id'] conn = self._touch_conn(conn_id) kwargs['ssh'] = conn log = PlugLess(**kwargs) log_id = str(uuid.uuid4()) log.__log_id = log_id self._log_sessions[log_id] = [log, self.PL_ACTIVE, kwargs['cmd'], conn_id] self._sock_read_fd.append(log) logger.info(self.name+'New log was registered, log_id = %s' % log_id) log.put_request(PlugLess.OPEN) def _log_cmd(self, **kwargs): log_id = kwargs['log_id'] cmd = kwargs['cmd'] log_cmd = None log_arg = None if cmd=='log_page': log_cmd = PlugLess.REDRAW elif cmd=='log_next': log_cmd = PlugLess.FWD elif cmd=='log_prev': log_cmd = PlugLess.BACK elif cmd=='log_pos': log_cmd = PlugLess.POS log_arg = kwargs.get('position', 0) elif cmd=='log_close': self._disconnect_log(log_id) res = {'cmd':cmd, 'res':'ok', 'log_id':log_id} self._put_answer_in_queue(res) return else: return log = self._touch_log(log_id, self.PL_ACTIVE, cmd=cmd) try: if log_cmd: log.put_request(log_cmd, log_arg) except: self._touch_log(log_id) # reset state res = {'cmd': cmd, 'res':'error', 'log_id':log_id} self._put_answer_in_queue(res) def _touch_log(self, log_id, state=PL_IDLE, cmd=None): """ Updates log state and touches associated ssh connection """ log = self._log_sessions[log_id][0] conn_id = self._log_sessions[log_id][3] self._log_sessions[log_id] = [log, state, cmd, conn_id] self._touch_conn(conn_id) return log def _touch_conn(self, conn_id): """ Update timestamp of SSH channel @return ssh channel """ conn = self._sessions[conn_id][0] self._sessions[conn_id] = [conn, time.time()] return conn def _is_valid(self, conn_id=None, log_id=None): if conn_id: return conn_id in self._sessions.keys() if log_id: return log_id in self._log_sessions.keys() return False def _disconnect(self, conn_id): logger.info(self.name+"Going to close conn_id = %s"%conn_id) logs_to_close=[] for k,v in self._log_sessions.iteritems(): if v[3]==conn_id: logs_to_close.append(k) for l in logs_to_close: self._disconnect_log(l) self._sessions[conn_id][0].close() del self._sessions[conn_id] logger.info(self.name+"conn_id = %s is no longer available"%conn_id) def _disconnect_log(self, log_id): logger.info(self.name+"Closing log_id = %s"%log_id) log = self._log_sessions[log_id][0] try: log.close() except: pass if log in self._sock_read_fd: self._sock_read_fd.remove(log) del self._log_sessions[log_id] def _log_response(self, log_id): log_data = self._log_sessions[log_id][0].get_result() logger.info(self.name + 'Log is ready, log_id = %s'%log_id) res = {'cmd': self._log_sessions[log_id][2], 'res':'ok', 'log_id':log_id, 'data':log_data} self._put_answer_in_queue(res) self._touch_log(log_id) def _put_answer_in_queue(self, data): ''' Puts data into output (client's) queue @param data: dict with data ''' logger.info('Going to put answer data in queue') enc = json.dumps(data)+'\r\n' enc_len = len(enc) for pos in range(0, enc_len, OUT_BUFF_SIZE): self._out_buff.append(enc[pos:pos+OUT_BUFF_SIZE]) self._sock_write_fd = [self.sock] def send_to_client(self): if self._out_buff: data = self._out_buff.pop(0) self.sock.send(data) else: self._sock_write_fd = [] def main(): import logging.config logging.config.fileConfig('log.conf') global logger # create logger logger = logging.getLogger('main') host = '127.0.0.1' port = 9999 print 'listening %s:%s'%(host,port) print('press ctrl-c to exit...') backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host,port)) s.listen(backlog) conn_list = [] while 1: try: client, address = s.accept() wc = WebClient(client, address) wc.start() conn_list.append(wc) except: [t.stop() for t in conn_list] break [t.join() for t in conn_list] if __name__=="__main__": main()
{ "content_hash": "e648ff4bf80b1a715bddb8893c59c69b", "timestamp": "", "source": "github", "line_count": 351, "max_line_length": 117, "avg_line_length": 33.49002849002849, "alnum_prop": 0.5039557635048916, "repo_name": "katichev/rt-pager", "id": "515fba094b8e93431239e56f3096d6dd3652f5e4", "size": "11755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web_client.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "44972" }, { "name": "Shell", "bytes": "48" } ], "symlink_target": "" }
_base_ = ['./mask2former_swin-t-p4-w7-224_lsj_8x2_50e_coco-panoptic.py'] pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window12_384.pth' # noqa depths = [2, 2, 18, 2] model = dict( backbone=dict( pretrain_img_size=384, embed_dims=128, depths=depths, num_heads=[4, 8, 16, 32], window_size=12, init_cfg=dict(type='Pretrained', checkpoint=pretrained)), panoptic_head=dict(in_channels=[128, 256, 512, 1024])) # set all layers in backbone to lr_mult=0.1 # set all norm layers, position_embeding, # query_embeding, level_embeding to decay_multi=0.0 backbone_norm_multi = dict(lr_mult=0.1, decay_mult=0.0) backbone_embed_multi = dict(lr_mult=0.1, decay_mult=0.0) embed_multi = dict(lr_mult=1.0, decay_mult=0.0) custom_keys = { 'backbone': dict(lr_mult=0.1, decay_mult=1.0), 'backbone.patch_embed.norm': backbone_norm_multi, 'backbone.norm': backbone_norm_multi, 'absolute_pos_embed': backbone_embed_multi, 'relative_position_bias_table': backbone_embed_multi, 'query_embed': embed_multi, 'query_feat': embed_multi, 'level_embed': embed_multi } custom_keys.update({ f'backbone.stages.{stage_id}.blocks.{block_id}.norm': backbone_norm_multi for stage_id, num_blocks in enumerate(depths) for block_id in range(num_blocks) }) custom_keys.update({ f'backbone.stages.{stage_id}.downsample.norm': backbone_norm_multi for stage_id in range(len(depths) - 1) }) # optimizer optimizer = dict( paramwise_cfg=dict(custom_keys=custom_keys, norm_decay_mult=0.0))
{ "content_hash": "f34bb37122259099c8991928adfb9428", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 124, "avg_line_length": 38.30952380952381, "alnum_prop": 0.6824114356743319, "repo_name": "open-mmlab/mmdetection", "id": "33a805c35eb1aa0adf81b3b69889d3f0a96cf4fa", "size": "1609", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "configs/mask2former/mask2former_swin-b-p4-w12-384_lsj_8x2_50e_coco-panoptic.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2540" }, { "name": "Python", "bytes": "4811377" }, { "name": "Shell", "bytes": "47911" } ], "symlink_target": "" }
# pylint: disable=line-too-long class BaseNumbers: NumberReplaceToken = '@builtin.num' FractionNumberReplaceToken = '@builtin.num.fraction' IntegerRegexDefinition = lambda placeholder, thousandsmark: f'(((?<!\\d+\\s*)-\\s*)|((?<=\\b)(?<!(\\d+\\.|\\d+,))))\\d{{1,3}}({thousandsmark}\\d{{3}})+(?={placeholder})' DoubleRegexDefinition = lambda placeholder, thousandsmark, decimalmark: f'(((?<!\\d+\\s*)-\\s*)|((?<=\\b)(?<!\\d+\\.|\\d+,)))\\d{{1,3}}({thousandsmark}\\d{{3}})+{decimalmark}\\d+(?={placeholder})' PlaceHolderDefault = '\\\\D|\\\\b' # pylint: enable=line-too-long
{ "content_hash": "ddd8c5649aede4af1bdbd0675ee9a283", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 200, "avg_line_length": 67, "alnum_prop": 0.5854063018242123, "repo_name": "matthewshim-ms/Recognizers-Text", "id": "c751eca504d708d6c9862f44276d56fd44e0d3a4", "size": "959", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/libraries/recognizers-number/recognizers_number/resources/base_numbers.py", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "120" }, { "name": "Batchfile", "bytes": "15522" }, { "name": "C#", "bytes": "3462115" }, { "name": "Dockerfile", "bytes": "1358" }, { "name": "HTML", "bytes": "6764" }, { "name": "Java", "bytes": "894664" }, { "name": "JavaScript", "bytes": "1801316" }, { "name": "PowerShell", "bytes": "1418" }, { "name": "Python", "bytes": "1564998" }, { "name": "Shell", "bytes": "229" }, { "name": "TypeScript", "bytes": "1484565" } ], "symlink_target": "" }
import json import os try: from unittest.mock import Mock, patch except ImportError: from mock import Mock, patch try: from StringIO import StringIO except ImportError: from io import StringIO import pytest # Alter path and import modules from sensu_plugin.handler import SensuHandler from sensu_plugin.tests.example_configs import example_check_result from sensu_plugin.tests.example_configs import example_settings # Currently just a single example check result CHECK_RESULT = example_check_result() CHECK_RESULT_DICT = json.loads(CHECK_RESULT) SETTINGS = example_settings() SETTINGS_DICT = json.loads(SETTINGS) def mock_api_settings(): return {'host': "http://api", 'port': 4567, 'user': None, 'password': None} class TestSensuHandler(object): def __init__(self): self.sensu_handler = None def setup(self): ''' Instantiate a fresh SensuHandler before each test. ''' self.sensu_handler = SensuHandler(autorun=False) # noqa @patch.object(SensuHandler, 'get_api_settings', Mock()) @patch('sensu_plugin.handler.get_settings', Mock()) def test_run(self): ''' Tests the run method. ''' # event should be valid json with patch('sensu_plugin.handler.sys.stdin') as mocked_stdin: mocked_stdin.read = lambda: CHECK_RESULT self.sensu_handler.run() assert self.sensu_handler.event == json.loads(CHECK_RESULT) @patch('sys.stdout', new_callable=StringIO) def test_handle(self, out): ''' Tests the handle method. ''' self.sensu_handler.handle() assert out.getvalue() == "ignoring event -- no handler defined.\n" def test_read_stdin(self): ''' Tests the read_stdin method. ''' # read_stdin should read something from stdin with patch('sensu_plugin.handler.sys.stdin') as mocked_stdin: mocked_stdin.read = None with pytest.raises(ValueError): self.sensu_handler.read_stdin() @patch.object(SensuHandler, 'read_stdin', CHECK_RESULT) def test_read_event(self): ''' Tests the read_event method. ''' read_event = self.sensu_handler.read_event # Test with example check assert isinstance(read_event(CHECK_RESULT), dict) # Ensure that the 'client' key is present assert isinstance(read_event(CHECK_RESULT)['client'], dict) # Ensure that the 'check' key is present assert isinstance(read_event(CHECK_RESULT)['check'], dict) # Test with a string (Fail) with pytest.raises(Exception): read_event('astring') @patch.object(SensuHandler, 'filter_disabled', Mock()) @patch.object(SensuHandler, 'filter_silenced', Mock()) @patch.object(SensuHandler, 'filter_dependencies', Mock()) @patch.object(SensuHandler, 'filter_repeated', Mock()) def test_filter(self): ''' Tests the filter method. ''' self.sensu_handler.event = {'check': {}} dfe = 'sensu_plugin.handler.SensuHandler.deprecated_filtering_enabled' dof = ('sensu_plugin.handler.SensuHandler' + '.deprecated_occurrence_filtering') with patch(dfe) as deprecated_filtering_enabled: deprecated_filtering_enabled.return_value = True with patch(dof) as deprecated_occurrence_filtering: deprecated_occurrence_filtering.return_value = True self.sensu_handler.filter() def test_occurrence_filtering(self): # noqa ''' Tests the deprecated_occurrence_filtering method. ''' self.sensu_handler.event = { 'check': { 'enable_deprecated_occurrence_filtering': True } } assert self.sensu_handler.deprecated_occurrence_filtering() self.sensu_handler.event = { 'check': {} } assert not self.sensu_handler.deprecated_occurrence_filtering() @patch.dict(os.environ, {'SENSU_API_URL': "http://api:4567"}) def test_get_api_settings(self): ''' Tests the get_api_settings method. ''' assert self.sensu_handler.get_api_settings() == mock_api_settings() @patch.object(SensuHandler, 'api_request') def test_stash_exists(self, mock_api_request): ''' Tests the stash_exists method. ''' class RequestsMock(object): def __init__(self, ret): self.status_code = ret # Mock stash exists mock_api_request.return_value = RequestsMock(200) assert self.sensu_handler.stash_exists('stash') # Mock stash missing mock_api_request.return_value = RequestsMock(404) assert not self.sensu_handler.stash_exists('stash') @patch('sensu_plugin.handler.requests.post') @patch('sensu_plugin.handler.requests.get') def test_api_request(self, mock_get, mock_post): ''' Tests the api_request method. ''' # No api_settings defined with pytest.raises(AttributeError): self.sensu_handler.api_request('GET', 'foo') for mock_method, method in [(mock_get, 'GET'), (mock_post, 'POST')]: # Should not supply auth self.sensu_handler.api_settings = { 'host': 'http://api', 'port': 4567 } self.sensu_handler.api_request(method, 'foo') mock_method.assert_called_with('http://api:4567/foo', auth=()) # Should still not supply any auth as it requires password too self.sensu_handler.api_settings['user'] = 'mock_user' self.sensu_handler.api_request(method, 'foo') mock_method.assert_called_with('http://api:4567/foo', auth=()) # Should supply auth self.sensu_handler.api_settings['password'] = 'mock_pass' self.sensu_handler.api_request(method, 'foo') mock_method.assert_called_with('http://api:4567/foo', auth=('mock_user', 'mock_pass'))
{ "content_hash": "9cef58af0cfce6d94e19f5db36740afe", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 78, "avg_line_length": 33.18716577540107, "alnum_prop": 0.6040928134063809, "repo_name": "sensu/sensu-plugin-python", "id": "b506fae282d0fb53a6a729e8b124f99892b9f297", "size": "6228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sensu_plugin/tests/test_handler.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "9710" }, { "name": "Shell", "bytes": "350" } ], "symlink_target": "" }
__author__ = 'July' # http://agiliq.com/blog/2013/09/understanding-threads-in-python/ #define a global variable from threading import Thread from threading import Lock some_var = 0 lock = Lock() class IncrementThreadRace(Thread): def run(self): #we want to read a global variable #and then increment it global some_var read_value = some_var print "some_var in %s is %d" % (self.name, read_value) some_var = read_value + 1 print "some_var in %s after increment is %d" % (self.name, some_var) class IncrementThread(Thread): def run(self): #we want to read a global variable #and then increment it global some_var lock.acquire() read_value = some_var print "some_var in %s is %d" % (self.name, read_value) some_var = read_value + 1 print "some_var in %s after increment is %d" % (self.name, some_var) lock.release() def use_increment_threadRace(): threads = [] for i in range(50): t = IncrementThreadRace() threads.append(t) t.start() for t in threads: t.join() print "After 50 modifications, shared_var should have become 50" print "After 50 modifications, shared_var is %d" % (some_var,) def use_increment_thread(): threads = [] for i in range(50): t = IncrementThread() threads.append(t) t.start() for t in threads: t.join() print "After 50 modifications, shared_var should have become 50" print "After 50 modifications, shared_var is %d" % (some_var,) use_increment_threadRace() #use_increment_thread()
{ "content_hash": "c6bb9868a5b329f1f4eb11dd972e57cc", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 76, "avg_line_length": 28.964912280701753, "alnum_prop": 0.6178073894609327, "repo_name": "JulyKikuAkita/PythonPrac", "id": "b0cc8af1a683cc2420e4a0bd338d4b358556ad25", "size": "1651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ThreadPrac/URL_RACE_CONDITION.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "DIGITAL Command Language", "bytes": "191608" }, { "name": "HTML", "bytes": "647778" }, { "name": "Python", "bytes": "5429558" } ], "symlink_target": "" }
"""The Lucene Query DSL parser based on PLY """ # TODO : add reserved chars and escaping, regex # see : https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html # https://lucene.apache.org/core/3_6_0/queryparsersyntax.html import re import ply.lex as lex import ply.yacc as yacc from .tree import * class ParseError(ValueError): """Exception while parsing a lucene statement """ pass reserved = { 'AND': 'AND_OP', 'OR': 'OR_OP', 'NOT': 'NOT', 'TO': 'TO'} # tokens of our grammar tokens = ( ['TERM', 'PHRASE', 'APPROX', 'BOOST', 'MINUS', 'SEPARATOR', 'PLUS', 'COLUMN', 'LPAREN', 'RPAREN', 'LBRACKET', 'RBRACKET'] + # we sort to have a deterministic order, so that gammar signature does not changes sorted(list(reserved.values()))) # text of some simple tokens t_PLUS = r'\+' t_MINUS = r'\-' t_NOT = 'NOT' t_AND_OP = r'AND' t_OR_OP = r'OR' t_COLUMN = r':' t_LPAREN = r'\(' t_RPAREN = r'\)' t_LBRACKET = r'(\[|\{)' t_RBRACKET = r'(\]|\})' # precedence rules precedence = ( ('left', 'OR_OP',), ('left', 'AND_OP'), ('nonassoc', 'MINUS',), ('nonassoc', 'PLUS',), ('nonassoc', 'APPROX'), ('nonassoc', 'BOOST'), ('nonassoc', 'LPAREN', 'RPAREN'), ('nonassoc', 'LBRACKET', 'TO', 'RBRACKET'), ('nonassoc', 'PHRASE'), ('nonassoc', 'TERM'), ) # term # the case of : which is used in date is problematic because it is also a delimiter # lets catch those expressions appart # Note : we must use positive look behind, because regexp engine is eager, # and it's only arrived at : that it will try this rule TIME_RE = r''' (?<=T\d{2}): # look behind for T and two digits: hours \d{2} # minutes (:\d{2})? # seconds ''' # this is a wide catching expression, to also include date math. # Inspired by the original lucene parser: # https://github.com/apache/lucene-solr/blob/master/lucene/queryparser/src/java/org/apache/lucene/queryparser/surround/parser/QueryParser.jj#L189 # We do allow the wildcards operators ('*' and '?') as our parser doesn't deal with them. TERM_RE = r''' (?P<term> # group term [^\s:^~(){{}}[\],"'+\-] # first char is not a space neither some char which have meanings # note: escape of "-" and "]" # and doubling of "{{}}" (because we use format) ([^\s:^~(){{}}[\]] # following chars | # OR {time_re} # a time expression )* ) '''.format(time_re=TIME_RE) # phrase PHRASE_RE = r'(?P<phrase>"[^"]*")' # modifiers after term or phrase APPROX_RE = r'~(?P<degree>[0-9.]+)?' BOOST_RE = r'\^(?P<force>[0-9.]+)?' def t_SEPARATOR(t): r'\s+' pass # discard separators @lex.TOKEN(TERM_RE) def t_TERM(t): # check if it is not a reserved term (an operation) t.type = reserved.get(t.value, 'TERM') # it's not, make it a Word if t.type == 'TERM': m = re.match(TERM_RE, t.value, re.VERBOSE) t.value = Word(m.group("term")) return t @lex.TOKEN(PHRASE_RE) def t_PHRASE(t): m = re.match(PHRASE_RE, t.value) t.value = Phrase(m.group("phrase")) return t @lex.TOKEN(APPROX_RE) def t_APPROX(t): m = re.match(APPROX_RE, t.value) t.value = m.group("degree") return t @lex.TOKEN(BOOST_RE) def t_BOOST(t): m = re.match(BOOST_RE, t.value) t.value = m.group("force") return t # Error handling rule FIXME def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) lexer = lex.lex() def p_expression_or(p): 'expression : expression OR_OP expression' p[0] = create_operation(OrOperation, p[1], p[3]) def p_expression_and(p): '''expression : expression AND_OP expression''' p[0] = create_operation(AndOperation, p[1], p[len(p) - 1]) def p_expression_implicit(p): '''expression : expression expression''' p[0] = create_operation(UnknownOperation, p[1], p[2]) def p_expression_plus(p): '''unary_expression : PLUS unary_expression''' p[0] = Plus(p[2]) def p_expression_minus(p): '''unary_expression : MINUS unary_expression''' p[0] = Prohibit(p[2]) def p_expression_not(p): '''unary_expression : NOT unary_expression''' p[0] = Not(p[2]) def p_expression_unary(p): '''expression : unary_expression''' p[0] = p[1] def p_grouping(p): 'unary_expression : LPAREN expression RPAREN' p[0] = Group(p[2]) # Will p_field_search will transform as FieldGroup if necessary def p_range(p): '''unary_expression : LBRACKET phrase_or_term TO phrase_or_term RBRACKET''' include_low = p[1] == "[" include_high = p[5] == "]" p[0] = Range(p[2], p[4], include_low, include_high) def p_field_search(p): '''unary_expression : TERM COLUMN unary_expression''' if isinstance(p[3], Group): p[3] = group_to_fieldgroup(p[3]) # for field name we take p[1].value for it was captured as a word expression p[0] = SearchField(p[1].value, p[3]) def p_quoting(p): 'unary_expression : PHRASE' p[0] = p[1] def p_proximity(p): '''unary_expression : PHRASE APPROX''' p[0] = Proximity(p[1], p[2]) def p_boosting(p): '''expression : expression BOOST''' p[0] = Boost(p[1], p[2]) def p_terms(p): '''unary_expression : TERM''' p[0] = p[1] def p_fuzzy(p): '''unary_expression : TERM APPROX''' p[0] = Fuzzy(p[1], p[2]) # handling a special case, TO is reserved only in range def p_to_as_term(p): '''unary_expression : TO''' p[0] = Word(p[1]) def p_phrase_or_term(p): '''phrase_or_term : TERM | PHRASE''' p[0] = p[1] # Error rule for syntax errors # TODO :Β should report better def p_error(p): if p is None: p = "(probably at end of input, may be unmatch parenthesis or so)" raise ParseError("Syntax error in input at %r!" % p) parser = yacc.yacc() """This is the parser generated by PLY """
{ "content_hash": "0dd1b85676ef9b626261d0b7cd24d21b", "timestamp": "", "source": "github", "line_count": 254, "max_line_length": 145, "avg_line_length": 23.53937007874016, "alnum_prop": 0.5945810336176618, "repo_name": "adsabs/object_service", "id": "f109e518431174d2d51dec2b208959ef2634c64a", "size": "6004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "object_service/luqum/parser.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "189892" } ], "symlink_target": "" }
"""Make hex structure libraries for all nif versions. Installation ------------ Make sure you have PyFFI installed (see http://pyffi.sourceforge.net). Then, copy makehsl.py to your Hex Workshop structures folder C:\Program Files\BreakPoint Software\Hex Workshop 4.2\Structures and run it. This will create a .hsl file per nif version. Known issues ------------ Hex Workshop libraries cannot properly deal with conditionals, so for serious hacking you probably want to edit the .hsl library as you go, commenting out the parts which are not present in the particular block you are investigating. """ # -------------------------------------------------------------------------- # ***** BEGIN LICENSE BLOCK ***** # # Copyright (c) 2007-2012, NIF File Format Library and Tools. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # * Neither the name of the NIF File Format Library and Tools # project nor the names of its contributors may be used to endorse # or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # ***** END LICENSE BLOCK ***** # -------------------------------------------------------------------------- import sys from types import * from string import maketrans from pyffi.formats.nif import NifFormat from pyffi.object_models.xml.basic import BasicBase def find_templates(): # find all types that are used as a template (excluding the ones # occuring in Ref & its subclass Ptr) templates = set() for cls in NifFormat.xml_struct: for attr in cls._attribute_list: if attr.template != None and attr.template != type(None) and not issubclass(attr.type_, NifFormat.Ref): templates.add(attr.template) return templates transtable = maketrans('?', '_') def sanitize_attrname(s): return s.translate(transtable) def write_hsl(f, ver, templates): # map basic NifFormat types to HWS types and enum byte size hsl_types = { NifFormat.int : ('long', 4), NifFormat.uint : ('ulong', 4), NifFormat.short : ('short', 2), NifFormat.ushort : ('ushort', 2), NifFormat.Flags : ('ushort', None), NifFormat.byte : ('ubyte ', 1), NifFormat.char : ('char', None), NifFormat.float : ('float', None), NifFormat.Ref : ('long', None), NifFormat.Ptr : ('long', None), NifFormat.FileVersion : ('ulong', None), # some stuff we cannot do in hex workshop NifFormat.HeaderString : ('char', None), NifFormat.LineString : ('char', None) } # hack for string (TODO fix this in NifFormat) #NifFormat.string : ('struct string', None) } if ver <= 0x04000002: hsl_types[NifFormat.bool] = ('ulong', 4) else: hsl_types[NifFormat.bool] = ('ubyte ', 1) # write header f.write("""// hex structure library for NIF Format 0x%08X #include "standard-types.hsl" #pragma byteorder(little_endian) #pragma maxarray(65535) """%ver) # write each enum class for cls in NifFormat.xml_enum: write_enum(cls, ver, hsl_types, f) # write each struct class for cls in NifFormat.xml_struct: if cls.__name__[:3] == 'ns ': continue # cheat: skip ns types if not cls._is_template: # write regular class write_struct(cls, ver, hsl_types, f, None) else: # write template classes for template in templates: write_struct(cls, ver, hsl_types, f, template) def write_enum(cls, ver, hsl_types, f): # set enum size f.write('#pragma enumsize(%s)\n' % cls._numbytes) f.write('typedef enum tag' + cls.__name__ + ' {\n') ## list of all non-private attributes gives enum constants #enum_items = [x for x in cls.__dict__.items() if x[0][:2] != '__'] ## sort them by value #enum_items = sorted(enum_items, key=lambda x: x[1]) # and write out all name, value pairs enum_items = list(zip(cls._enumkeys, cls._enumvalues)) for const_name, const_value in enum_items[:-1]: f.write(' ' + const_name + ' = ' + str(const_value) + ',\n') const_name, const_value = enum_items[-1] f.write(' ' + const_name + ' = ' + str(const_value) + '\n') f.write('} ' + cls.__name__ + ';\n\n') def write_struct(cls, ver, hsl_types, f, template): # open the structure if not template: f.write('struct ' + cls.__name__ + ' {\n') else: f.write('struct ' + cls.__name__ + '_' + template.__name__ + ' {\n') #for attrname, typ, default, tmpl, arg, arr1, arr2, cond, ver1, ver2, userver, doc in cls._attribute_list: for attr in cls._attribute_list: # check version if not (ver is None): if (not (attr.ver1 is None)) and ver < attr.ver1: continue if (not (attr.ver2 is None)) and ver > attr.ver2: continue s = ' ' # things that can only be determined at runtime (rt_xxx) rt_type = attr.type_ if attr.type_ != type(None) \ else template rt_template = attr.template if attr.template != type(None) \ else template # get the attribute type name try: s += hsl_types[rt_type][0] except KeyError: if rt_type in NifFormat.xml_enum: s += rt_type.__name__ else: # it's in NifFormat.xml_struct s += 'struct ' + rt_type.__name__ # get the attribute template type name if (not rt_template is None) and (not issubclass(rt_type, NifFormat.Ref)): s += '_' s += rt_template.__name__ # note: basic types are named by their xml name in the template # attribute name s = s.ljust(20) + ' ' + sanitize_attrname(attr.name) # array and conditional arguments arr_str = '' comments = '' if not attr.cond is None: # catch argument passing and double arrays if (str(attr.cond).find('arg') == -1) and (attr.arr2 is None): if attr.cond._op is None or (attr.cond._op == '!=' and attr.cond._right == 0): arr_str += sanitize_attrname(str(attr.cond._left)) else: comments += ' (' + sanitize_attrname(str(attr.cond)) + ')' else: comments += ' (' + sanitize_attrname(str(attr.cond)) + ')' if attr.arr1 is None: pass elif attr.arr2 is None: if str(attr.arr1).find('arg') == -1: # catch argument passing if arr_str: arr_str += ' * ' arr_str += sanitize_attrname(str(attr.arr1._left)) if attr.arr1._op: comments += ' [' + sanitize_attrname(str(attr.arr1)) + ']' else: if arr_str: arr_str += ' * ' arr_str += '1' comments += ' [arg]' else: # TODO catch args here too (so far not used anywhere in nif.xml) if arr_str: arr_str += ' * ' arr_str += sanitize_attrname(str(attr.arr1._left)) + ' * ' + sanitize_attrname(str(attr.arr2._left)) if attr.arr1._op or attr.arr2._op: comments += ' [' + sanitize_attrname(str(attr.arr1)) + ' * ' + sanitize_attrname(str(attr.arr2)) + ']' arr_str = '[' + arr_str + ']' if arr_str else '' comments = ' //' + comments if comments else '' f.write(s + arr_str + ';' + comments + '\n') # close the structure f.write('};\n\n') if __name__ == '__main__': # list all types used as a template templates = find_templates() # write out hex structure library for each nif version for ver_str, ver in list(NifFormat.versions.items()): f = open('nif_' + ver_str.replace('.', '_') + '.hsl', 'w') try: write_hsl(f, ver, templates) finally: f.close()
{ "content_hash": "9281f9256c2da647e5a42a606c6d415f", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 118, "avg_line_length": 40.025862068965516, "alnum_prop": 0.5858281283652811, "repo_name": "griest024/PokyrimTools", "id": "85ca9e46f8e4185b19f812ad5e3d38d45209864e", "size": "9306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pyffi-develop/scripts/nif/nifmakehsl.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1205978" }, { "name": "C++", "bytes": "6318739" }, { "name": "CMake", "bytes": "19319" }, { "name": "CSS", "bytes": "1542" }, { "name": "Groff", "bytes": "2506" }, { "name": "HTML", "bytes": "3154887" }, { "name": "Inno Setup", "bytes": "45620" }, { "name": "Java", "bytes": "129878" }, { "name": "Makefile", "bytes": "18242" }, { "name": "NSIS", "bytes": "29228" }, { "name": "Objective-C", "bytes": "9061" }, { "name": "Python", "bytes": "2406969" }, { "name": "Shell", "bytes": "41141" } ], "symlink_target": "" }
"""Query operators for the file backend.""" import operator import re import six if six.PY3: from functools import reduce def boolean_operator_query(boolean_operator): """Generate boolean operator checking function.""" def _boolean_operator_query(expressions): """Apply boolean operator to expressions.""" def _apply_boolean_operator(query_function, expressions=expressions): """Return if expressions with boolean operator are satisfied.""" compiled_expressions = [compile_query(e) for e in expressions] return reduce( boolean_operator, [e(query_function) for e in compiled_expressions] ) return _apply_boolean_operator return _boolean_operator_query def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expression = compile_query(expression) elif callable(expression): def _filter(index, expression=expression): result = [store_key for value, store_keys in index.get_index().items() if expression(value) for store_key in store_keys] return result compiled_expression = _filter else: compiled_expression = expression def _get(query_function, key=key, expression=compiled_expression): """Get document key and check against expression.""" return query_function(key, expression) return _get def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() returned_keys = expression(index) return [key for key in all_keys if key not in returned_keys] return _not def comparison_operator_query(comparison_operator): """Generate comparison operator checking function.""" def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression return [ store_key for value, store_keys in index.get_index().items() if comparison_operator(value, ev) for store_key in store_keys ] return _apply_comparison_operator return _comparison_operator_query def exists_query(expression): """Check that documents have a key that satisfies expression.""" def _exists(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression if ev: return [ store_key for store_keys in index.get_index().values() for store_key in store_keys ] else: return index.get_undefined_keys() return _exists def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys in index.get_index().items() if (isinstance(value, six.string_types) and re.match(pattern, value)) for store_key in store_keys ] return _regex def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except TypeError: raise AttributeError('$all argument must be an iterable!') hashed_ev = [index.get_hash_for(v) for v in ev] store_keys = set([]) if len(hashed_ev) == 0: return [] store_keys = set(index.get_keys_for(hashed_ev[0])) for value in hashed_ev[1:]: store_keys &= set(index.get_keys_for(value)) return list(store_keys) return _all def elemMatch_query(expression): """Select documents if element in array field matches all conditions.""" def _elemMatch(index, expression=expression): """Raise exception since this operator is not implemented yet.""" raise ValueError( '$elemMatch query is currently not supported by file backend!') return _elemMatch def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except TypeError: raise AttributeError('$in argument must be an iterable!') hashed_ev = [index.get_hash_for(v) for v in ev] store_keys = set() for value in hashed_ev: store_keys |= set(index.get_keys_for(value)) return list(store_keys) return _in def compile_query(query): """Compile each expression in query recursively.""" if isinstance(query, dict): expressions = [] for key, value in query.items(): if key.startswith('$'): if key not in query_funcs: raise AttributeError('Invalid operator: {0}'.format(key)) expressions.append(query_funcs[key](value)) else: expressions.append(filter_query(key, value)) if len(expressions) > 1: return boolean_operator_query(operator.and_)(expressions) else: return ( expressions[0] if len(expressions) else lambda query_function: query_function(None, None) ) else: return query query_funcs = { '$regex': regex_query, '$exists': exists_query, '$and': boolean_operator_query(operator.and_), '$all': all_query, '$elemMatch': elemMatch_query, '$or': boolean_operator_query(operator.or_), '$gte': comparison_operator_query(operator.ge), '$lte': comparison_operator_query(operator.le), '$gt': comparison_operator_query(operator.gt), '$lt': comparison_operator_query(operator.lt), '$ne': comparison_operator_query(operator.ne), '$not': not_query, '$in': in_query, }
{ "content_hash": "fc6d6262ffe0fce4ea7265abceca53eb", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 77, "avg_line_length": 34.13170731707317, "alnum_prop": 0.608546519937116, "repo_name": "cwoebker/blitzdb", "id": "950a65299e4aa9b7b0acdcfb163917b3dfdbdb2a", "size": "6997", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "blitzdb/backends/file/queries.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "317304" } ], "symlink_target": "" }
import torch from pyinn.utils import Stream, load_kernel kernel = """ extern "C" __global__ void swap(float2 *x, int total) { int tx = blockIdx.x * blockDim.x + threadIdx.x; if(tx >= total) return; float2 v = x[tx]; //x[tx] = make_float2(v.y, v.x); x[tx] = make_float2(v.x, -v.y); } """ CUDA_NUM_THREADS = 1024 def GET_BLOCKS(N, K=CUDA_NUM_THREADS): return (N + K - 1) // K def swap(x): assert x.size(-1) == 2 total = x.numel() // 2 with torch.cuda.device_of(x): f = load_kernel('swap', kernel) f(args=[x.data_ptr(), total], block=(CUDA_NUM_THREADS,1,1), grid=(GET_BLOCKS(total),1,1), stream=Stream(ptr=torch.cuda.current_stream().cuda_stream)) def cublas_cdgmm(A, x, out=None): if out is not None: assert out.is_contiguous() and out.size() == A.size() else: out = A.new(A.size()) assert x.dim() == 2 and x.size(-1) == 2 and A.size(-1) == 2 assert A.dim() == 3 assert x.size(0) == A.size(1) or x.size(0) == A.size(0) assert A.type() == x.type() == out.type() assert A.is_contiguous() if not isinstance(A, (torch.cuda.FloatTensor, torch.cuda.DoubleTensor)): raise NotImplementedError else: m, n = A.size(1), A.size(0) if x.size(0) == A.size(1): mode = 'l' elif x.size(0) == A.size(0): mode = 'r' lda, ldc = m, m incx = 1 handle = torch.cuda.current_blas_handle() stream = torch.cuda.current_stream()._as_parameter_ from skcuda import cublas cublas.cublasSetStream(handle, stream) args = [handle, mode, m, n, A.data_ptr(), lda, x.data_ptr(), incx, out.data_ptr(), ldc] if isinstance(A, torch.cuda.FloatTensor): cublas.cublasCdgmm(*args) elif isinstance(A, torch.cuda.DoubleTensor): cublas.cublasZdgmm(*args) return out class CDGMM(torch.autograd.Function): def forward(self, input, x): self.save_for_backward(input, x) return cublas_cdgmm(input, x) def backward(self, grad_output): input, x = self.saved_tensors grad_input = grad_x = None if self.needs_input_grad[0]: grad_output = grad_output.contiguous() swap(x) grad_input = cublas_cdgmm(grad_output.contiguous(), x) swap(x) assert grad_input.size() == input.size() if self.needs_input_grad[1]: raise NotImplementedError # dim = 0 if x.size(0) == input.size(1) else 1 # grad_x = (grad_output * input).sum(dim).squeeze(dim) # assert grad_x.size() == x.size() return grad_input, grad_x def cdgmm(input, x): """Complex multiplication with a diagonal matrix. Does `input.mm(x.diag())` where input and x are complex. Args: input: 3D tensor with last dimension of size 2 x: 2D tensor with last dimension of size 2 """ return CDGMM()(input, x)
{ "content_hash": "25eb6c3ef7dcb40b5fb7460b2da3b818", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 95, "avg_line_length": 29.627450980392158, "alnum_prop": 0.5628722700198544, "repo_name": "szagoruyko/pyinn", "id": "9efb58ef4719aad1e098715804e1aa11a4994151", "size": "3022", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pyinn/cdgmm.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "40667" } ], "symlink_target": "" }
from PIL import Image import numpy as np import matplotlib.pyplot as plt import math from open_image import open_image def max_filter(path, region_size): ''' Values for every pixel equals to the max of all values in the region :param path: path to the image :param region_size: size of the region that will be extracted and its median will be calculated :return: resulting image ''' # initializing image and other helping variables image_array = open_image(path) image_height, image_width = image_array.shape half_size = math.floor(region_size / 2) resulting_img = np.zeros(image_height * image_width).reshape(image_height, image_width) # iterating over the image for i in range(half_size, image_height - half_size): for j in range(half_size, image_width - half_size): # extraction of region of the given size and calculation of its max value region = (image_array[i - half_size:i + half_size + 1, j - half_size:j + half_size + 1]).ravel() resulting_img[i, j] = np.max(region) return resulting_img if __name__ == "__main__": max_img = max_filter('../img/lena_noise.png', 3) plt.imshow(max_img, cmap='gray', interpolation='nearest') plt.show()
{ "content_hash": "67af6ae34d55a28e9f0b8e32a8ead329", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 108, "avg_line_length": 36.628571428571426, "alnum_prop": 0.6575663026521061, "repo_name": "vvvityaaa/PyImgProcess", "id": "5a7ca0faae741af154384e3ee2e108e7fd6fca83", "size": "1282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "filter/max_filter.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3983" }, { "name": "Python", "bytes": "41373" } ], "symlink_target": "" }
import os from process import queueProcess, execCmd from util.data import PackXXTea, RemoveUtf8Bom import util projectdir = util.toolsPath # win32 and android LuaJitBin = os.path.join(projectdir, "bin/win32/luajit.exe") LuaBin = os.path.join(projectdir, "bin/win32/luac.exe") # iOS LuaJitiOSx86Dir = os.path.join(projectdir, "bin/ios/x86/") LuaJitiOSx64Dir = os.path.join(projectdir, "bin/ios/x86_64/") LuaJitiOSx86Bin = os.path.join(projectdir, "bin/ios/x86/luajit") LuaJitiOSx64Bin = os.path.join(projectdir, "bin/ios/x86_64/luajit") class PackLua(): """ PackLua """ def __init__(self, useJit = True, isiOS = False): self.useJit = useJit self.isiOS = isiOS self.JitCompileCMD = "" self.JitCompileCMD2 = "" self.updateCMD(self.useJit, self.isiOS) def updateCMD(self, _useJit = True, _isiOS = False): self.useJit = _useJit self.isiOS = _isiOS if self.useJit: if self.isiOS: self.JitCompileCMD = LuaJitiOSx86Bin + " -b {filename} {filename}.32" self.JitCompileCMD2 = LuaJitiOSx64Bin + " -b {filename} {filename}.64" else: self.JitCompileCMD = LuaJitBin + " -b {filename} {filename}" else: self.JitCompileCMD = LuaBin + " -s -o {filename}c {filename}" def __compileLuaJitiOS(self, absFilePath): os.chdir(LuaJitiOSx86Dir) execCmd(self.JitCompileCMD.format(filename = absFilePath)) os.chdir(LuaJitiOSx64Dir) execCmd(self.JitCompileCMD2.format(filename = absFilePath)) filepath32 = absFilePath+'.32' filepath64 = absFilePath+'.64' if os.path.exists(filepath32) and os.path.exists(filepath64): if os.path.exists(absFilePath): os.remove(absFilePath) return 0 else: if os.path.exists(filepath32): os.remove(filepath32) if os.path.exists(filepath64): os.remove(filepath64) return 1 def __compileLuac(self, absFilePath, relativepath = ''): if PackXXTea.Is(absFilePath): return 0 RemoveUtf8Bom.remove(absFilePath, relativepath) ret = 0 ret = execCmd(self.JitCompileCMD.format(filename = absFilePath)) if os.path.exists(absFilePath + 'c'): ret = PackXXTea.encode(absFilePath + 'c') if os.path.exists(absFilePath): os.remove(absFilePath) os.rename(absFilePath + 'c', absFilePath) else: return 1 return 0 def __compileLua(self, absFilePath, relativepath = ''): ret = 0 if absFilePath.find('LuaScript') != -1 or absFilePath.find('Core') != -1: if absFilePath.find('/ui/') == -1 and absFilePath.find('\\ui\\') == -1: if absFilePath.find('/Scene/') == -1 and absFilePath.find('\\Scene\\') == -1: ret = PackXXTea.encode(absFilePath) return ret def __compileLuaJit(self, absFilePath, relativepath = ''): if self.useJit: if self.isiOS: ret = self.__compileLuaJitiOS(absFilePath) else: ret = execCmd(self.JitCompileCMD.format(filename = absFilePath)) else: return self.__compileLua(absFilePath, relativepath) return ret def compile(self, absFilePath, relativepath = ''): return self.__compileLuaJit(absFilePath, relativepath)
{ "content_hash": "0e86a8554b54cf8811b3d3fab78360db", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 93, "avg_line_length": 34.862385321100916, "alnum_prop": 0.5518421052631579, "repo_name": "lyzardiar/RETools", "id": "0035ef16e4921eefa9908d469b16ebc5cb7895ac", "size": "3825", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PublicTools/bin/tools/PackTool/src/util/lua/PackLua.py", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1347446" }, { "name": "Batchfile", "bytes": "1049" }, { "name": "C", "bytes": "2318643" }, { "name": "C#", "bytes": "17673" }, { "name": "C++", "bytes": "22628" }, { "name": "CMake", "bytes": "45249" }, { "name": "CSS", "bytes": "37269" }, { "name": "Groff", "bytes": "37236" }, { "name": "HTML", "bytes": "708560" }, { "name": "Java", "bytes": "213356" }, { "name": "JavaScript", "bytes": "34594" }, { "name": "Lua", "bytes": "461306" }, { "name": "M4", "bytes": "25935" }, { "name": "Makefile", "bytes": "39650" }, { "name": "Objective-C", "bytes": "747" }, { "name": "PHP", "bytes": "282643" }, { "name": "Python", "bytes": "168568" }, { "name": "Shell", "bytes": "57679" } ], "symlink_target": "" }
from http.server import HTTPServer, BaseHTTPRequestHandler from queue import Queue from threading import Thread, Event import json # Import Tuple type which is used in optional function type annotations. from typing import Tuple import keyprofile class WebServerManager(): """Creates new web server thread.""" def __init__(self): self.exit_event = Event() web_server_settings = ("", 8080) self.settings_queue = Queue() self.web_server_thread = Thread(group=None, target=WebServer, args=(web_server_settings, self.settings_queue, self.exit_event)) self.web_server_thread.start() def close(self): """Close web server. This method will block until web server is closed.""" self.exit_event.set() self.web_server_thread.join() def get_settings_queue(self) -> Queue: return self.settings_queue # Class WebServer inherits HTTPServer class which is from Python standard library. # https://docs.python.org/3/library/http.server.html # Also, note that HTTPServer inherits TCPServer. # https://docs.python.org/3/library/socketserver.html#socketserver.TCPServer class WebServer(HTTPServer): # Type annotations of this constructor are optional. def __init__(self, address_and_port: Tuple [str, int], settings_queue: Queue, exit_event: Event) -> None: # Run constructor from HTTPServer first. Note the RequestHandler class. super().__init__(address_and_port, RequestHandler) # Some object attributes specific to this class. You can modify # them from RequestHandler's methods. self.settings_queue = settings_queue # Check exit event every 0.5 seconds if there is no new TCP connections. self.timeout = 0.5 # TODO: Load saved profiles/settings from file # if file is not found default to keyprofile.settings self.settings = [{}] # keyprofile.setting # Main thread is waiting for profiles/settings so lets send them. self.settings_queue.put_nowait(self.settings) print("web server running") while True: # This method will timeout because exit_event must be checked enough often # to shutdown cleanly. self.handle_request() if exit_event.is_set(): # There was exit event, lets close the web server. break self.server_close() # Save profiles/settings. with open('data.txt', 'w') as outfile: json.dump(self.settings, outfile) print("web server exited") # Python standard library HTTPServer works with request handler system, so lets # make our own request handler. class RequestHandler(BaseHTTPRequestHandler): # By default the HTTP version is 1.0. def do_GET(self) -> None: """Handler for HTTP GET requests.""" # Print some information about the HTTP request. #print("HTTP GET Request, path: " + self.path) #print("client_address: " + str(self.client_address)) #print("request_version: " + self.request_version) #print("headers: " + str(self.headers)) if self.path == "/json.api": message = json.dumps(self.server.settings) message_bytes = message.encode() self.send_utf8_bytes(message_bytes, "text/json") elif self.path == "/heatmap.api": f = open("heatmap_stats.txt", 'r') heatmap_info = f.read() message_bytes = heatmap_info.encode() self.send_utf8_bytes(message_bytes, "text/json") elif self.path == "/": self.send_utf8_file("../frontend/control.html", "text/html") elif self.path == "/styles.css": self.send_utf8_file("../frontend/styles.css", "text/css") elif self.path == "/script.js": self.send_utf8_file("../frontend/script.js", "application/javascript") else: message_bytes = b"<html><body><h1>Hello world</h1></body></html>" self.send_utf8_bytes(message_bytes, "text/html") def do_POST(self) -> None: """Handler for HTTP POST requests.""" #print("HTTP POST Request, path: " + self.path) #print("client_address: " + str(self.client_address)) #print("request_version: " + self.request_version) #print("headers: " + str(self.headers)) content_length = self.headers.get("Content-Length", 0) response = self.rfile.read(int(content_length)) self.server.settings = json.loads(response.decode("utf-8")) # Send new settings to main thread. self.server.settings_queue.put_nowait(self.server.settings) self.send_response(200) self.end_headers() def send_utf8_file(self, file_name: str, mime_type: str) -> None: """Mime type is string like 'text/json'""" file = open(file_name, mode='rb') file_as_bytes = file.read() file.close() self.send_utf8_bytes(file_as_bytes, mime_type) def send_utf8_bytes(self, message_bytes: bytes, mime_type: str) -> None: """Mime type is string like 'text/json'""" # 200 is HTTP status code for successfull request. self.send_response(200) self.send_header("Content-Encoding", "UTF-8") self.send_header("Content-Type", mime_type + "; charset=utf-8") self.end_headers() # Write HTTP message body which is the HTML web page. self.wfile.write(message_bytes) self.wfile.flush()
{ "content_hash": "fc2d9a096ad1d63fe3079f8c37941a70", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 135, "avg_line_length": 37.72108843537415, "alnum_prop": 0.6281334535617673, "repo_name": "miikka-h/Projektikurssi17", "id": "56c9b576c4b07f06a09432d9df383cacb01c81d5", "size": "5545", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pi3/web_server_old.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10821" }, { "name": "HTML", "bytes": "1766" }, { "name": "JavaScript", "bytes": "48810" }, { "name": "Python", "bytes": "94976" }, { "name": "Shell", "bytes": "1895" }, { "name": "TypeScript", "bytes": "17835" } ], "symlink_target": "" }
""" Module :mod:`pyesgf.search.context` =================================== Defines the :class:`SearchContext` class which represents each ESGF search query. """ import os import sys import copy from webob.multidict import MultiDict from .constraints import GeospatialConstraint from .consts import (TYPE_DATASET, TYPE_FILE, TYPE_AGGREGATION, QUERY_KEYWORD_TYPES, DEFAULT_BATCH_SIZE) from .results import ResultSet from .exceptions import EsgfSearchException class SearchContext(object): """Instances of this class represent the state of a current search. It exposes what facets are available to select and the facet counts if they are available. Subclasses of this class can restrict the search options. For instance FileSearchContext, DatasetSerachContext or CMIP5SearchContext SearchContext instances are connected to SearchConnection instances. You normally create SearchContext instances via one of: 1. Calling SearchConnection.new_context() 2. Calling SearchContext.constrain() :ivar constraints: A dictionary of facet constraints currently in effect. ``constraint[facet_name] = [value, value, ...]`` :ivar facets: A string containing a comma-separated list of facets to be returned (for example ``'source_id,ensemble_id'``). If set, this will be used to select which facet counts to include, as returned in the ``facet_counts`` dictionary. Defaults to including all available facets, but with distributed searches (where the SearchConnection instance was created with ``distrib=True``), some results may be missing for server-side reasons when requesting all facets, so a warning message will be issued. This contains further details. :property facet_counts: A dictionary of available hits with each facet value for the search as currently constrained. This property returns a dictionary of dictionaries where ``facet_counts[facet][facet_value] == hit_count`` :property hit_count: The total number of hits available with current constraints. """ DEFAULT_SEARCH_TYPE = NotImplemented def __init__(self, connection, constraints, search_type=None, latest=None, facets=None, fields=None, from_timestamp=None, to_timestamp=None, replica=None, shards=None): """ :param connection: The SearchConnection :param constraints: A dictionary of initial constraints :param search_type: One of TYPE_* constants defining the document type to search for. Overrides SearchContext.DEFAULT_SEARCH_TYPE :param facets: The list of facets for which counts will be retrieved and constraints be validated against. Or None to represent all facets. :param fields: A list of field names to return in search responses :param replica: A boolean defining whether to return master records or replicas, or None to return both. :param latest: A boolean defining whether to return only latest versions or only non-latest versions, or None to return both. :param shards: list of shards to restrict searches to. Should be from the list self.connection.get_shard_list() :param from_timestamp: Date-time string to specify start of search range (e.g. "2000-01-01T00:00:00Z"). :param to_timestamp: Date-time string to specify end of search range (e.g. "2100-12-31T23:59:59Z"). """ self.connection = connection self.__facet_counts = None self.__hit_count = None self._did_facets_star_warning = False if search_type is None: search_type = self.DEFAULT_SEARCH_TYPE # Constraints self.freetext_constraint = None self.facet_constraints = MultiDict() self.temporal_constraint = [from_timestamp, to_timestamp] self.geospatial_constraint = None self._update_constraints(constraints) # Search configuration parameters self.timestamp_range = (from_timestamp, to_timestamp) search_types = [TYPE_DATASET, TYPE_FILE, TYPE_AGGREGATION] if search_type not in search_types: raise EsgfSearchException('search_type must be one of %s' % ','.join(search_types)) self.search_type = search_type self.latest = latest self.facets = facets self.fields = fields self.replica = replica self.shards = shards # ------------------------------------------------------------------------- # Functional search interface # These do not change the constraints on self. def search(self, batch_size=DEFAULT_BATCH_SIZE, ignore_facet_check=False, **constraints): """ Perform the search with current constraints returning a set of results. :batch_size: The number of results to get per HTTP request. :ignore_facet_check: Do not make an extra HTTP request to populate :py:attr:`~facet_counts` and :py:attr:`~hit_count`. :param constraints: Further constraints for this query. Equivalent to calling ``self.constrain(**constraints).search()`` :return: A ResultSet for this query """ if constraints: sc = self.constrain(**constraints) else: sc = self if not ignore_facet_check: sc.__update_counts() return ResultSet(sc, batch_size=batch_size) def constrain(self, **constraints): """ Return a *new* instance with the additional constraints. """ new_sc = copy.deepcopy(self) new_sc._update_constraints(constraints) return new_sc def get_download_script(self, **constraints): """ Download a script for downloading all files in the set of results. :param constraints: Further constraints for this query. Equivalent to calling ``self.constrain(**constraints).get_download_script()`` :return: A string containing the script """ if constraints: sc = self.constrain(**constraints) else: sc = self sc.__update_counts() query_dict = sc._build_query() # !TODO: allow setting limit script = sc.connection.send_wget(query_dict, shards=self.shards) return script @property def facet_counts(self): self.__update_counts() return self.__facet_counts @property def hit_count(self): self.__update_counts() return self.__hit_count def get_facet_options(self): """ Return a dictionary of facet counts filtered to remove all facets that are completely constrained. This method is similar to the property ``facet_counts`` except facet values which are not relevant for further constraining are removed. """ facet_options = {} hits = self.hit_count for facet, counts in list(self.facet_counts.items()): # filter out counts that match total hits counts = dict(items for items in list(counts.items()) if items[1] < hits) if len(counts) > 1: facet_options[facet] = counts return facet_options def __update_counts(self): # If hit_count is set the counts are already retrieved if self.__hit_count is not None: return self.__facet_counts = {} self.__hit_count = None query_dict = self._build_query() if self.facets: query_dict['facets'] = self.facets else: query_dict['facets'] = '*' if self.connection.distrib: self._do_facets_star_warning() response = self.connection.send_search(query_dict, limit=0) for facet, counts in (list(response['facet_counts']['facet_fields'].items())): d = self.__facet_counts[facet] = {} while counts: d[counts.pop()] = counts.pop() self.__hit_count = response['response']['numFound'] def _do_facets_star_warning(self): env_var_name = 'ESGF_PYCLIENT_NO_FACETS_STAR_WARNING' if env_var_name in os.environ: return if not self._did_facets_star_warning: sys.stderr.write(f''' ------------------------------------------------------------------------------- Warning - defaulting to search with facets=* This behavior is kept for backward-compatibility, but ESGF indexes might not successfully perform a distributed search when this option is used, so some results may be missing. For full results, it is recommended to pass a list of facets of interest when instantiating a context object. For example, ctx = conn.new_context(facets='project,experiment_id') Only the facets that you specify will be present in the facets_counts dictionary. This warning is displayed when a distributed search is performed while using the facets=* default, a maximum of once per context object. To suppress this warning, set the environment variable {env_var_name} to any value or explicitly use conn.new_context(facets='*') ------------------------------------------------------------------------------- ''') self._did_facets_star_warning = True # ------------------------------------------------------------------------- # Constraint mutation interface # These functions update the instance in-place. # Use constrain() and search() to generate new contexts with tighter # constraints. def _update_constraints(self, constraints): """ Update the constraints in-place by calling _constrain_*() methods. """ constraints_split = self._split_constraints(constraints) self._constrain_facets(constraints_split['facet']) if 'query' in constraints_split['freetext']: new_freetext = constraints_split['freetext']['query'] self._constrain_freetext(new_freetext) # !TODO: implement temporal and geospatial constraints if 'from_timestamp' in constraints_split['temporal']: self.temporal_constraint[0] = (constraints_split['temporal'] ['from_timestamp']) if 'to_timestamp' in constraints_split['temporal']: self.temporal_constraint[1] = (constraints_split['temporal'] ['to_timestamp']) # self._constrain_geospatial() # reset cached values self.__hit_count = None self.__facet_counts = None def _constrain_facets(self, facet_constraints): for key, values in list(facet_constraints.mixed().items()): current_values = self.facet_constraints.getall(key) if isinstance(values, list): for value in values: if value not in current_values: self.facet_constraints.add(key, value) else: if values not in current_values: self.facet_constraints.add(key, values) def _constrain_freetext(self, query): self.freetext_constraint = query def _constrain_geospatial(self, lat=None, lon=None, bbox=None, location=None, radius=None, polygon=None): self.geospatial_constraint = GeospatialConstraint( lat, lon, bbox, location, radius, polygon) raise NotImplementedError # ------------------------------------------------------------------------- def _split_constraints(self, constraints): """ Divide a constraint dictionary into 4 types of constraints: 1. Freetext query 2. Facet constraints 3. Temporal constraints 4. Geospatial constraints :return: A dictionary of the 4 types of constraint. """ # local import to prevent circular importing from .connection import query_keyword_type constraints_split = dict((kw, MultiDict()) for kw in QUERY_KEYWORD_TYPES) for kw, val in list(constraints.items()): constraint_type = query_keyword_type(kw) constraints_split[constraint_type][kw] = val return constraints_split def _build_query(self): """ Build query string parameters as a dictionary. """ query_dict = MultiDict({"query": self.freetext_constraint, "type": self.search_type, "latest": self.latest, "facets": self.facets, "fields": self.fields, "replica": self.replica}) query_dict.extend(self.facet_constraints) # !TODO: encode datetime start, end = self.temporal_constraint query_dict.update(start=start, end=end) return query_dict class DatasetSearchContext(SearchContext): DEFAULT_SEARCH_TYPE = TYPE_DATASET class FileSearchContext(SearchContext): DEFAULT_SEARCH_TYPE = TYPE_FILE class AggregationSearchContext(SearchContext): DEFAULT_SEARCH_TYPE = TYPE_AGGREGATION
{ "content_hash": "da407163d5158ac53cffb3f0683a48f1", "timestamp": "", "source": "github", "line_count": 363, "max_line_length": 86, "avg_line_length": 37.3168044077135, "alnum_prop": 0.6012845120330725, "repo_name": "ESGF/esgf-pyclient", "id": "5e0cf32306ab84c8c928f71ea9954859a6b9d82d", "size": "13546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pyesgf/search/context.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Jupyter Notebook", "bytes": "20994" }, { "name": "Makefile", "bytes": "2334" }, { "name": "Python", "bytes": "98839" } ], "symlink_target": "" }
''' Given a binary tree, check whether it’s a binary search tree or not. ''' class Node: def __init__(self, val=None): self.left, self.right, self.val = None, None, val INFINITY = float("infinity") NEG_INFINITY = float("-infinity") def isBST(tree, minVal=NEG_INFINITY, maxVal=INFINITY): if tree is None: return True if not minVal <= tree.val <= maxVal: return False return isBST(tree.left, minVal, tree.val) and isBST(tree.right, tree.val, maxVal) # Second Solution: inorder Traversal def isBSTree2(tree,LastNode=NEG_INFINITY): if tree is None: return True if not isBSTree2(tree.left,LastNode): return False if tree.val<LastNode: return False lastNode = tree.val return isBSTree2(tree.right,LastNode)
{ "content_hash": "a6756202be30a1197828baddcb4926be", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 83, "avg_line_length": 24.46875, "alnum_prop": 0.6704980842911877, "repo_name": "jenniferwx/Programming_Practice", "id": "ca087c2bf539df721e4f79e8430ce0bb7441ed39", "size": "785", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ValidBinarySearchTree.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "30716" }, { "name": "Java", "bytes": "1675" }, { "name": "Python", "bytes": "34062" } ], "symlink_target": "" }
from __future__ import unicode_literals, print_function, absolute_import import os def touch(fname): file = open(fname, "w") file.write("Hello World") file.close() def mkdir(path): if not os.path.exists(path): os.makedirs(path) return True return False
{ "content_hash": "92cbbed887fee98097ae8d5737675238", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 72, "avg_line_length": 18.375, "alnum_prop": 0.6428571428571429, "repo_name": "avara1986/ardy", "id": "edef88d34cf6caf27e921a4e81fd5454a548ac26", "size": "326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "69934" }, { "name": "Shell", "bytes": "79" } ], "symlink_target": "" }
import time import datetime import dateutil import stripe import hashlib import re import redis import uuid import mongoengine as mongo from django.db import models from django.db import IntegrityError from django.db.utils import DatabaseError from django.db.models.signals import post_save from django.db.models import Sum, Avg, Count from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.core.mail import EmailMultiAlternatives from django.core.urlresolvers import reverse from django.template.loader import render_to_string from apps.rss_feeds.models import Feed, MStory, MStarredStory from apps.rss_feeds.tasks import SchedulePremiumSetup from apps.feed_import.models import GoogleReaderImporter, OPMLExporter from apps.reader.models import UserSubscription from apps.reader.models import RUserStory from utils import log as logging from utils import json_functions as json from utils.user_functions import generate_secret_token from utils.feed_functions import chunks from vendor.timezones.fields import TimeZoneField from vendor.paypal.standard.ipn.signals import subscription_signup, payment_was_successful, recurring_payment from vendor.paypal.standard.ipn.signals import payment_was_flagged from vendor.paypal.standard.ipn.models import PayPalIPN from vendor.paypalapi.interface import PayPalInterface from vendor.paypalapi.exceptions import PayPalAPIResponseError from zebra.signals import zebra_webhook_customer_subscription_created from zebra.signals import zebra_webhook_charge_succeeded class Profile(models.Model): user = models.OneToOneField(User, unique=True, related_name="profile") is_premium = models.BooleanField(default=False) premium_expire = models.DateTimeField(blank=True, null=True) send_emails = models.BooleanField(default=True) preferences = models.TextField(default="{}") view_settings = models.TextField(default="{}") collapsed_folders = models.TextField(default="[]") feed_pane_size = models.IntegerField(default=242) tutorial_finished = models.BooleanField(default=False) hide_getting_started = models.NullBooleanField(default=False, null=True, blank=True) has_setup_feeds = models.NullBooleanField(default=False, null=True, blank=True) has_found_friends = models.NullBooleanField(default=False, null=True, blank=True) has_trained_intelligence = models.NullBooleanField(default=False, null=True, blank=True) last_seen_on = models.DateTimeField(default=datetime.datetime.now) last_seen_ip = models.CharField(max_length=50, blank=True, null=True) dashboard_date = models.DateTimeField(default=datetime.datetime.now) timezone = TimeZoneField(default="America/New_York") secret_token = models.CharField(max_length=12, blank=True, null=True) stripe_4_digits = models.CharField(max_length=4, blank=True, null=True) stripe_id = models.CharField(max_length=24, blank=True, null=True) def __unicode__(self): return "%s <%s> (Premium: %s)" % (self.user, self.user.email, self.is_premium) @property def unread_cutoff(self, force_premium=False): if self.is_premium or force_premium: return datetime.datetime.utcnow() - datetime.timedelta(days=settings.DAYS_OF_UNREAD) return datetime.datetime.utcnow() - datetime.timedelta(days=settings.DAYS_OF_UNREAD_FREE) @property def unread_cutoff_premium(self): return datetime.datetime.utcnow() - datetime.timedelta(days=settings.DAYS_OF_UNREAD) def canonical(self): return { 'is_premium': self.is_premium, 'premium_expire': int(self.premium_expire.strftime('%s')) if self.premium_expire else 0, 'preferences': json.decode(self.preferences), 'tutorial_finished': self.tutorial_finished, 'hide_getting_started': self.hide_getting_started, 'has_setup_feeds': self.has_setup_feeds, 'has_found_friends': self.has_found_friends, 'has_trained_intelligence': self.has_trained_intelligence, 'dashboard_date': self.dashboard_date } def save(self, *args, **kwargs): if not self.secret_token: self.secret_token = generate_secret_token(self.user.username, 12) try: super(Profile, self).save(*args, **kwargs) except DatabaseError: print " ---> Profile not saved. Table isn't there yet." def delete_user(self, confirm=False, fast=False): if not confirm: print " ---> You must pass confirm=True to delete this user." return logging.user(self.user, "Deleting user: %s / %s" % (self.user.email, self.user.profile.last_seen_ip)) try: self.cancel_premium() except: logging.user(self.user, "~BR~SK~FWError cancelling premium renewal for: %s" % self.user.username) from apps.social.models import MSocialProfile, MSharedStory, MSocialSubscription from apps.social.models import MActivity, MInteraction try: social_profile = MSocialProfile.objects.get(user_id=self.user.pk) logging.user(self.user, "Unfollowing %s followings and %s followers" % (social_profile.following_count, social_profile.follower_count)) for follow in social_profile.following_user_ids: social_profile.unfollow_user(follow) for follower in social_profile.follower_user_ids: follower_profile = MSocialProfile.objects.get(user_id=follower) follower_profile.unfollow_user(self.user.pk) social_profile.delete() except MSocialProfile.DoesNotExist: logging.user(self.user, " ***> No social profile found. S'ok, moving on.") pass shared_stories = MSharedStory.objects.filter(user_id=self.user.pk) logging.user(self.user, "Deleting %s shared stories" % shared_stories.count()) for story in shared_stories: try: if not fast: original_story = MStory.objects.get(story_hash=story.story_hash) original_story.sync_redis() except MStory.DoesNotExist: pass story.delete() subscriptions = MSocialSubscription.objects.filter(subscription_user_id=self.user.pk) logging.user(self.user, "Deleting %s social subscriptions" % subscriptions.count()) subscriptions.delete() interactions = MInteraction.objects.filter(user_id=self.user.pk) logging.user(self.user, "Deleting %s interactions for user." % interactions.count()) interactions.delete() interactions = MInteraction.objects.filter(with_user_id=self.user.pk) logging.user(self.user, "Deleting %s interactions with user." % interactions.count()) interactions.delete() activities = MActivity.objects.filter(user_id=self.user.pk) logging.user(self.user, "Deleting %s activities for user." % activities.count()) activities.delete() activities = MActivity.objects.filter(with_user_id=self.user.pk) logging.user(self.user, "Deleting %s activities with user." % activities.count()) activities.delete() starred_stories = MStarredStory.objects.filter(user_id=self.user.pk) logging.user(self.user, "Deleting %s starred stories." % starred_stories.count()) starred_stories.delete() logging.user(self.user, "Deleting user: %s" % self.user) self.user.delete() def activate_premium(self, never_expire=False): from apps.profile.tasks import EmailNewPremium EmailNewPremium.delay(user_id=self.user.pk) was_premium = self.is_premium self.is_premium = True self.save() self.user.is_active = True self.user.save() # Only auto-enable every feed if a free user is moving to premium subs = UserSubscription.objects.filter(user=self.user) if not was_premium: for sub in subs: if sub.active: continue sub.active = True try: sub.save() except (IntegrityError, Feed.DoesNotExist): pass try: scheduled_feeds = [sub.feed.pk for sub in subs] except Feed.DoesNotExist: scheduled_feeds = [] logging.user(self.user, "~SN~FMTasking the scheduling immediate premium setup of ~SB%s~SN feeds..." % len(scheduled_feeds)) SchedulePremiumSetup.apply_async(kwargs=dict(feed_ids=scheduled_feeds)) UserSubscription.queue_new_feeds(self.user) self.setup_premium_history() if never_expire: self.premium_expire = None self.save() logging.user(self.user, "~BY~SK~FW~SBNEW PREMIUM ACCOUNT! WOOHOO!!! ~FR%s subscriptions~SN!" % (subs.count())) return True def deactivate_premium(self): self.is_premium = False self.save() subs = UserSubscription.objects.filter(user=self.user) for sub in subs: sub.active = False try: sub.save() # Don't bother recalculating feed's subs, as it will do that on next fetch # sub.feed.setup_feed_for_premium_subscribers() except (IntegrityError, Feed.DoesNotExist): pass logging.user(self.user, "~BY~FW~SBBOO! Deactivating premium account: ~FR%s subscriptions~SN!" % (subs.count())) def activate_free(self): if self.user.is_active: return self.user.is_active = True self.user.save() self.send_new_user_queue_email() def setup_premium_history(self, alt_email=None, set_premium_expire=True, force_expiration=False): paypal_payments = [] stripe_payments = [] total_stripe_payments = 0 existing_history = PaymentHistory.objects.filter(user=self.user, payment_provider__in=['paypal', 'stripe']) if existing_history.count(): logging.user(self.user, "~BY~SN~FRDeleting~FW existing history: ~SB%s payments" % existing_history.count()) existing_history.delete() # Record Paypal payments paypal_payments = PayPalIPN.objects.filter(custom=self.user.username, payment_status='Completed', txn_type='subscr_payment') if not paypal_payments.count(): paypal_payments = PayPalIPN.objects.filter(payer_email=self.user.email, payment_status='Completed', txn_type='subscr_payment') if alt_email and not paypal_payments.count(): paypal_payments = PayPalIPN.objects.filter(payer_email=alt_email, payment_status='Completed', txn_type='subscr_payment') if paypal_payments.count(): # Make sure this doesn't happen again, so let's use Paypal's email. self.user.email = alt_email self.user.save() seen_txn_ids = set() for payment in paypal_payments: if payment.txn_id in seen_txn_ids: continue seen_txn_ids.add(payment.txn_id) PaymentHistory.objects.create(user=self.user, payment_date=payment.payment_date, payment_amount=payment.payment_gross, payment_provider='paypal') # Record Stripe payments if self.stripe_id: self.retrieve_stripe_ids() stripe.api_key = settings.STRIPE_SECRET seen_payments = set() for stripe_id_model in self.user.stripe_ids.all(): stripe_id = stripe_id_model.stripe_id stripe_customer = stripe.Customer.retrieve(stripe_id) stripe_payments = stripe.Charge.all(customer=stripe_customer.id).data for payment in stripe_payments: created = datetime.datetime.fromtimestamp(payment.created) if payment.status == 'failed': continue if created in seen_payments: continue seen_payments.add(created) total_stripe_payments += 1 PaymentHistory.objects.get_or_create(user=self.user, payment_date=created, payment_amount=payment.amount / 100.0, payment_provider='stripe') # Calculate payments in last year, then add together payment_history = PaymentHistory.objects.filter(user=self.user) last_year = datetime.datetime.now() - datetime.timedelta(days=364) recent_payments_count = 0 oldest_recent_payment_date = None free_lifetime_premium = False for payment in payment_history: if payment.payment_amount == 0: free_lifetime_premium = True if payment.payment_date > last_year: recent_payments_count += 1 if not oldest_recent_payment_date or payment.payment_date < oldest_recent_payment_date: oldest_recent_payment_date = payment.payment_date if free_lifetime_premium: logging.user(self.user, "~BY~SN~FWFree lifetime premium") self.premium_expire = None self.save() elif oldest_recent_payment_date: new_premium_expire = (oldest_recent_payment_date + datetime.timedelta(days=365*recent_payments_count)) # Only move premium expire forward, never earlier. Also set expiration if not premium. if (force_expiration or (set_premium_expire and not self.premium_expire) or (self.premium_expire and new_premium_expire > self.premium_expire)): self.premium_expire = new_premium_expire self.save() logging.user(self.user, "~BY~SN~FWFound ~SB~FB%s paypal~FW~SN and ~SB~FC%s stripe~FW~SN payments (~SB%s payments expire: ~SN~FB%s~FW)" % ( len(paypal_payments), total_stripe_payments, len(payment_history), self.premium_expire)) if (set_premium_expire and not self.is_premium and (not self.premium_expire or self.premium_expire > datetime.datetime.now())): self.activate_premium() @classmethod def reimport_stripe_history(cls, limit=10, days=7, starting_after=None): stripe.api_key = settings.STRIPE_SECRET week = (datetime.datetime.now() - datetime.timedelta(days=days)).strftime('%s') failed = [] i = 0 while True: logging.debug(" ---> At %s / %s" % (i, starting_after)) i += 1 try: data = stripe.Charge.all(created={'gt': week}, count=limit, starting_after=starting_after) except stripe.APIConnectionError: time.sleep(10) continue charges = data['data'] if not len(charges): logging.debug("At %s (%s), finished" % (i, starting_after)) break starting_after = charges[-1]["id"] customers = [c['customer'] for c in charges if 'customer' in c] for customer in customers: if not customer: print " ***> No customer!" continue try: profile = Profile.objects.get(stripe_id=customer) user = profile.user except Profile.DoesNotExist: logging.debug(" ***> Couldn't find stripe_id=%s" % customer) failed.append(customer) continue except Profile.MultipleObjectsReturned: logging.debug(" ***> Multiple stripe_id=%s" % customer) failed.append(customer) continue try: user.profile.setup_premium_history() except stripe.APIConnectionError: logging.debug(" ***> Failed: %s" % user.username) failed.append(user.username) time.sleep(2) continue return ','.join(failed) def refund_premium(self, partial=False): refunded = False if self.stripe_id: stripe.api_key = settings.STRIPE_SECRET stripe_customer = stripe.Customer.retrieve(self.stripe_id) stripe_payments = stripe.Charge.all(customer=stripe_customer.id).data if partial: stripe_payments[0].refund(amount=1200) refunded = 12 else: stripe_payments[0].refund() self.cancel_premium() refunded = stripe_payments[0].amount/100 logging.user(self.user, "~FRRefunding stripe payment: $%s" % refunded) else: self.cancel_premium() paypal_opts = { 'API_ENVIRONMENT': 'PRODUCTION', 'API_USERNAME': settings.PAYPAL_API_USERNAME, 'API_PASSWORD': settings.PAYPAL_API_PASSWORD, 'API_SIGNATURE': settings.PAYPAL_API_SIGNATURE, 'API_CA_CERTS': False, } paypal = PayPalInterface(**paypal_opts) transactions = PayPalIPN.objects.filter(custom=self.user.username, txn_type='subscr_payment' ).order_by('-payment_date') if not transactions: transactions = PayPalIPN.objects.filter(payer_email=self.user.email, txn_type='subscr_payment' ).order_by('-payment_date') if transactions: transaction = transactions[0] refund = paypal.refund_transaction(transaction.txn_id) try: refunded = int(float(refund.raw['TOTALREFUNDEDAMOUNT'][0])) except KeyError: refunded = int(transaction.payment_gross) logging.user(self.user, "~FRRefunding paypal payment: $%s" % refunded) else: logging.user(self.user, "~FRCouldn't refund paypal payment: not found by username or email") refunded = 0 return refunded def cancel_premium(self): paypal_cancel = self.cancel_premium_paypal() stripe_cancel = self.cancel_premium_stripe() return stripe_cancel or paypal_cancel def cancel_premium_paypal(self, second_most_recent_only=False): transactions = PayPalIPN.objects.filter(custom=self.user.username, txn_type='subscr_signup').order_by('-subscr_date') if not transactions: return paypal_opts = { 'API_ENVIRONMENT': 'PRODUCTION', 'API_USERNAME': settings.PAYPAL_API_USERNAME, 'API_PASSWORD': settings.PAYPAL_API_PASSWORD, 'API_SIGNATURE': settings.PAYPAL_API_SIGNATURE, 'API_CA_CERTS': False, } paypal = PayPalInterface(**paypal_opts) if second_most_recent_only: # Check if user has an active subscription. If so, cancel it because a new one came in. if len(transactions) > 1: transaction = transactions[1] else: return False else: transaction = transactions[0] profileid = transaction.subscr_id try: paypal.manage_recurring_payments_profile_status(profileid=profileid, action='Cancel') except PayPalAPIResponseError: logging.user(self.user, "~FRUser ~SBalready~SN canceled Paypal subscription: %s" % profileid) else: if second_most_recent_only: logging.user(self.user, "~FRCanceling ~BR~FWsecond-oldest~SB~FR Paypal subscription: %s" % profileid) else: logging.user(self.user, "~FRCanceling Paypal subscription: %s" % profileid) return True def cancel_premium_stripe(self): if not self.stripe_id: return stripe.api_key = settings.STRIPE_SECRET stripe_customer = stripe.Customer.retrieve(self.stripe_id) try: stripe_customer.cancel_subscription() except stripe.InvalidRequestError: logging.user(self.user, "~FRFailed to cancel Stripe subscription") logging.user(self.user, "~FRCanceling Stripe subscription") return True def retrieve_stripe_ids(self): if not self.stripe_id: return stripe.api_key = settings.STRIPE_SECRET stripe_customer = stripe.Customer.retrieve(self.stripe_id) stripe_email = stripe_customer.email stripe_ids = set() for email in set([stripe_email, self.user.email]): customers = stripe.Customer.list(email=email) for customer in customers: stripe_ids.add(customer.stripe_id) self.user.stripe_ids.all().delete() for stripe_id in stripe_ids: self.user.stripe_ids.create(stripe_id=stripe_id) @property def latest_paypal_email(self): ipn = PayPalIPN.objects.filter(custom=self.user.username) if not len(ipn): return return ipn[0].payer_email def activate_ios_premium(self, product_identifier, transaction_identifier, amount=36): payments = PaymentHistory.objects.filter(user=self.user, payment_identifier=transaction_identifier, payment_date__gte=datetime.datetime.now()-datetime.timedelta(days=3)) if len(payments): # Already paid logging.user(self.user, "~FG~BBAlready paid iOS premium subscription: $%s~FW" % transaction_identifier) return False PaymentHistory.objects.create(user=self.user, payment_date=datetime.datetime.now(), payment_amount=amount, payment_provider='ios-subscription', payment_identifier=transaction_identifier) self.setup_premium_history() if not self.is_premium: self.activate_premium() logging.user(self.user, "~FG~BBNew iOS premium subscription: $%s~FW" % product_identifier) return True @classmethod def clear_dead_spammers(self, days=30, confirm=False): users = User.objects.filter(date_joined__gte=datetime.datetime.now()-datetime.timedelta(days=days)).order_by('-date_joined') usernames = set() numerics = re.compile(r'[0-9]+') for user in users: opens = UserSubscription.objects.filter(user=user).aggregate(sum=Sum('feed_opens'))['sum'] reads = RUserStory.read_story_count(user.pk) has_numbers = numerics.search(user.username) try: has_profile = user.profile.last_seen_ip except Profile.DoesNotExist: usernames.add(user.username) print " ---> Missing profile: %-20s %-30s %-6s %-6s" % (user.username, user.email, opens, reads) continue if opens is None and not reads and has_numbers: usernames.add(user.username) print " ---> Numerics: %-20s %-30s %-6s %-6s" % (user.username, user.email, opens, reads) elif not has_profile: usernames.add(user.username) print " ---> No IP: %-20s %-30s %-6s %-6s" % (user.username, user.email, opens, reads) if not confirm: return usernames for username in usernames: try: u = User.objects.get(username=username) except User.DoesNotExist: continue u.profile.delete_user(confirm=True) RNewUserQueue.user_count() RNewUserQueue.activate_all() @classmethod def count_feed_subscribers(self, feed_id=None, user_id=None, verbose=True): SUBSCRIBER_EXPIRE = datetime.datetime.now() - datetime.timedelta(days=settings.SUBSCRIBER_EXPIRE) r = redis.Redis(connection_pool=settings.REDIS_FEED_SUB_POOL) entire_feed_counted = False if verbose: feed = Feed.get_by_id(feed_id) logging.debug(" ---> [%-30s] ~SN~FBCounting subscribers for feed:~SB~FM%s~SN~FB user:~SB~FM%s" % (feed.log_title[:30], feed_id, user_id)) if feed_id: feed_ids = [feed_id] elif user_id: feed_ids = [us['feed_id'] for us in UserSubscription.objects.filter(user=user_id, active=True).values('feed_id')] else: assert False, "feed_id or user_id required" if feed_id and not user_id: entire_feed_counted = True for feed_id in feed_ids: total = 0 premium = 0 active = 0 active_premium = 0 key = 's:%s' % feed_id premium_key = 'sp:%s' % feed_id if user_id: active = UserSubscription.objects.get(feed_id=feed_id, user_id=user_id).only('active').active user_ids = dict([(user_id, active)]) else: user_ids = dict([(us.user_id, us.active) for us in UserSubscription.objects.filter(feed_id=feed_id).only('user', 'active')]) profiles = Profile.objects.filter(user_id__in=user_ids.keys()).values('user_id', 'last_seen_on', 'is_premium') feed = Feed.get_by_id(feed_id) if entire_feed_counted: r.delete(key) r.delete(premium_key) for profiles_group in chunks(profiles, 20): pipeline = r.pipeline() for profile in profiles_group: last_seen_on = int(profile['last_seen_on'].strftime('%s')) muted_feed = not bool(user_ids[profile['user_id']]) if muted_feed: last_seen_on = 0 pipeline.zadd(key, profile['user_id'], last_seen_on) total += 1 if profile['is_premium']: pipeline.zadd(premium_key, profile['user_id'], last_seen_on) premium += 1 else: pipeline.zrem(premium_key, profile['user_id']) if profile['last_seen_on'] > SUBSCRIBER_EXPIRE and not muted_feed: active += 1 if profile['is_premium']: active_premium += 1 pipeline.execute() if entire_feed_counted: now = int(datetime.datetime.now().strftime('%s')) r.zadd(key, -1, now) r.expire(key, settings.SUBSCRIBER_EXPIRE*24*60*60) r.zadd(premium_key, -1, now) r.expire(premium_key, settings.SUBSCRIBER_EXPIRE*24*60*60) logging.info(" ---> [%-30s] ~SN~FBCounting subscribers, storing in ~SBredis~SN: ~FMt:~SB~FM%s~SN a:~SB%s~SN p:~SB%s~SN ap:~SB%s" % (feed.log_title[:30], total, active, premium, active_premium)) @classmethod def count_all_feed_subscribers_for_user(self, user): r = redis.Redis(connection_pool=settings.REDIS_FEED_SUB_POOL) if not isinstance(user, User): user = User.objects.get(pk=user) active_feed_ids = [us['feed_id'] for us in UserSubscription.objects.filter(user=user.pk, active=True).values('feed_id')] muted_feed_ids = [us['feed_id'] for us in UserSubscription.objects.filter(user=user.pk, active=False).values('feed_id')] logging.user(user, "~SN~FBRefreshing user last_login_on for ~SB%s~SN/~SB%s subscriptions~SN" % (len(active_feed_ids), len(muted_feed_ids))) for feed_ids in [active_feed_ids, muted_feed_ids]: for feeds_group in chunks(feed_ids, 20): pipeline = r.pipeline() for feed_id in feeds_group: key = 's:%s' % feed_id premium_key = 'sp:%s' % feed_id last_seen_on = int(user.profile.last_seen_on.strftime('%s')) if feed_ids is muted_feed_ids: last_seen_on = 0 pipeline.zadd(key, user.pk, last_seen_on) if user.profile.is_premium: pipeline.zadd(premium_key, user.pk, last_seen_on) else: pipeline.zrem(premium_key, user.pk) pipeline.execute() def import_reader_starred_items(self, count=20): importer = GoogleReaderImporter(self.user) importer.import_starred_items(count=count) def send_new_user_email(self): if not self.user.email or not self.send_emails: return user = self.user text = render_to_string('mail/email_new_account.txt', locals()) html = render_to_string('mail/email_new_account.xhtml', locals()) subject = "Welcome to NewsBlur, %s" % (self.user.username) msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending email for new user: %s" % self.user.email) def send_opml_export_email(self, reason=None, force=False): if not self.user.email: return emails_sent = MSentEmail.objects.filter(receiver_user_id=self.user.pk, email_type='opml_export') day_ago = datetime.datetime.now() - datetime.timedelta(days=1) for email in emails_sent: if email.date_sent > day_ago and not force: logging.user(self.user, "~SN~FMNot sending opml export email, already sent today.") return MSentEmail.record(receiver_user_id=self.user.pk, email_type='opml_export') exporter = OPMLExporter(self.user) opml = exporter.process() params = { 'feed_count': UserSubscription.objects.filter(user=self.user).count(), 'reason': reason, } user = self.user text = render_to_string('mail/email_opml_export.txt', params) html = render_to_string('mail/email_opml_export.xhtml', params) subject = "Backup OPML file of your NewsBlur sites" filename= 'NewsBlur Subscriptions - %s.xml' % datetime.datetime.now().strftime('%Y-%m-%d') msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.attach(filename, opml, 'text/xml') msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending OPML backup email to: %s" % self.user.email) def send_first_share_to_blurblog_email(self, force=False): from apps.social.models import MSocialProfile, MSharedStory if not self.user.email: return params = dict(receiver_user_id=self.user.pk, email_type='first_share') try: MSentEmail.objects.get(**params) if not force: # Return if email already sent return except MSentEmail.DoesNotExist: MSentEmail.objects.create(**params) social_profile = MSocialProfile.objects.get(user_id=self.user.pk) params = { 'shared_stories': MSharedStory.objects.filter(user_id=self.user.pk).count(), 'blurblog_url': social_profile.blurblog_url, 'blurblog_rss': social_profile.blurblog_rss } user = self.user text = render_to_string('mail/email_first_share_to_blurblog.txt', params) html = render_to_string('mail/email_first_share_to_blurblog.xhtml', params) subject = "Your shared stories on NewsBlur are available on your Blurblog" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending first share to blurblog email to: %s" % self.user.email) def send_new_premium_email(self, force=False): # subs = UserSubscription.objects.filter(user=self.user) # message = """Woohoo! # # User: %(user)s # Feeds: %(feeds)s # # Sincerely, # NewsBlur""" % {'user': self.user.username, 'feeds': subs.count()} # mail_admins('New premium account', message, fail_silently=True) if not self.user.email or not self.send_emails: return params = dict(receiver_user_id=self.user.pk, email_type='new_premium') try: MSentEmail.objects.get(**params) if not force: # Return if email already sent return except MSentEmail.DoesNotExist: MSentEmail.objects.create(**params) user = self.user text = render_to_string('mail/email_new_premium.txt', locals()) html = render_to_string('mail/email_new_premium.xhtml', locals()) subject = "Thanks for going premium on NewsBlur!" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending email for new premium: %s" % self.user.email) def send_forgot_password_email(self, email=None): if not self.user.email and not email: print "Please provide an email address." return if not self.user.email and email: self.user.email = email self.user.save() user = self.user text = render_to_string('mail/email_forgot_password.txt', locals()) html = render_to_string('mail/email_forgot_password.xhtml', locals()) subject = "Forgot your password on NewsBlur?" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending email for forgotten password: %s" % self.user.email) def send_new_user_queue_email(self, force=False): if not self.user.email: print "Please provide an email address." return params = dict(receiver_user_id=self.user.pk, email_type='new_user_queue') try: MSentEmail.objects.get(**params) if not force: # Return if email already sent return except MSentEmail.DoesNotExist: MSentEmail.objects.create(**params) user = self.user text = render_to_string('mail/email_new_user_queue.txt', locals()) html = render_to_string('mail/email_new_user_queue.xhtml', locals()) subject = "Your free account is now ready to go on NewsBlur" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending email for new user queue: %s" % self.user.email) def send_upload_opml_finished_email(self, feed_count): if not self.user.email: print "Please provide an email address." return user = self.user text = render_to_string('mail/email_upload_opml_finished.txt', locals()) html = render_to_string('mail/email_upload_opml_finished.xhtml', locals()) subject = "Your OPML upload is complete. Get going with NewsBlur!" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send() logging.user(self.user, "~BB~FM~SBSending email for OPML upload: %s" % self.user.email) def send_import_reader_finished_email(self, feed_count): if not self.user.email: print "Please provide an email address." return user = self.user text = render_to_string('mail/email_import_reader_finished.txt', locals()) html = render_to_string('mail/email_import_reader_finished.xhtml', locals()) subject = "Your Google Reader import is complete. Get going with NewsBlur!" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send() logging.user(self.user, "~BB~FM~SBSending email for Google Reader import: %s" % self.user.email) def send_import_reader_starred_finished_email(self, feed_count, starred_count): if not self.user.email: print "Please provide an email address." return user = self.user text = render_to_string('mail/email_import_reader_starred_finished.txt', locals()) html = render_to_string('mail/email_import_reader_starred_finished.xhtml', locals()) subject = "Your Google Reader starred stories import is complete. Get going with NewsBlur!" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send() logging.user(self.user, "~BB~FM~SBSending email for Google Reader starred stories import: %s" % self.user.email) def send_launch_social_email(self, force=False): if not self.user.email or not self.send_emails: logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, %s: %s" % (self.user.email and 'opt-out: ' or 'blank', self.user.email)) return params = dict(receiver_user_id=self.user.pk, email_type='launch_social') try: MSentEmail.objects.get(**params) if not force: # Return if email already sent logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, sent already: %s" % self.user.email) return except MSentEmail.DoesNotExist: MSentEmail.objects.create(**params) delta = datetime.datetime.now() - self.last_seen_on months_ago = delta.days / 30 user = self.user data = dict(user=user, months_ago=months_ago) text = render_to_string('mail/email_launch_social.txt', data) html = render_to_string('mail/email_launch_social.xhtml', data) subject = "NewsBlur is now a social news reader" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending launch social email for user: %s months, %s" % (months_ago, self.user.email)) def send_launch_turntouch_email(self, force=False): if not self.user.email or not self.send_emails: logging.user(self.user, "~FM~SB~FRNot~FM sending launch TT email for user, %s: %s" % (self.user.email and 'opt-out: ' or 'blank', self.user.email)) return params = dict(receiver_user_id=self.user.pk, email_type='launch_turntouch') try: MSentEmail.objects.get(**params) if not force: # Return if email already sent logging.user(self.user, "~FM~SB~FRNot~FM sending launch social email for user, sent already: %s" % self.user.email) return except MSentEmail.DoesNotExist: MSentEmail.objects.create(**params) delta = datetime.datetime.now() - self.last_seen_on months_ago = delta.days / 30 user = self.user data = dict(user=user, months_ago=months_ago) text = render_to_string('mail/email_launch_turntouch.txt', data) html = render_to_string('mail/email_launch_turntouch.xhtml', data) subject = "Introducing Turn Touch for NewsBlur" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending launch TT email for user: %s months, %s" % (months_ago, self.user.email)) def send_launch_turntouch_end_email(self, force=False): if not self.user.email or not self.send_emails: logging.user(self.user, "~FM~SB~FRNot~FM sending launch TT end email for user, %s: %s" % (self.user.email and 'opt-out: ' or 'blank', self.user.email)) return params = dict(receiver_user_id=self.user.pk, email_type='launch_turntouch_end') try: MSentEmail.objects.get(**params) if not force: # Return if email already sent logging.user(self.user, "~FM~SB~FRNot~FM sending launch TT end email for user, sent already: %s" % self.user.email) return except MSentEmail.DoesNotExist: MSentEmail.objects.create(**params) delta = datetime.datetime.now() - self.last_seen_on months_ago = delta.days / 30 user = self.user data = dict(user=user, months_ago=months_ago) text = render_to_string('mail/email_launch_turntouch_end.txt', data) html = render_to_string('mail/email_launch_turntouch_end.xhtml', data) subject = "Last day to back Turn Touch: NewsBlur's beautiful remote" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) logging.user(self.user, "~BB~FM~SBSending launch TT end email for user: %s months, %s" % (months_ago, self.user.email)) def grace_period_email_sent(self, force=False): emails_sent = MSentEmail.objects.filter(receiver_user_id=self.user.pk, email_type='premium_expire_grace') day_ago = datetime.datetime.now() - datetime.timedelta(days=360) for email in emails_sent: if email.date_sent > day_ago and not force: logging.user(self.user, "~SN~FMNot sending premium expire grace email, already sent before.") return True def send_premium_expire_grace_period_email(self, force=False): if not self.user.email: logging.user(self.user, "~FM~SB~FRNot~FM~SN sending premium expire grace for user: %s" % (self.user)) return if self.grace_period_email_sent(force=force): return if self.premium_expire and self.premium_expire < datetime.datetime.now(): self.premium_expire = datetime.datetime.now() self.save() delta = datetime.datetime.now() - self.last_seen_on months_ago = delta.days / 30 user = self.user data = dict(user=user, months_ago=months_ago) text = render_to_string('mail/email_premium_expire_grace.txt', data) html = render_to_string('mail/email_premium_expire_grace.xhtml', data) subject = "Your premium account on NewsBlur has one more month!" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) MSentEmail.record(receiver_user_id=self.user.pk, email_type='premium_expire_grace') logging.user(self.user, "~BB~FM~SBSending premium expire grace email for user: %s months, %s" % (months_ago, self.user.email)) def send_premium_expire_email(self, force=False): if not self.user.email: logging.user(self.user, "~FM~SB~FRNot~FM sending premium expire for user: %s" % (self.user)) return emails_sent = MSentEmail.objects.filter(receiver_user_id=self.user.pk, email_type='premium_expire') day_ago = datetime.datetime.now() - datetime.timedelta(days=360) for email in emails_sent: if email.date_sent > day_ago and not force: logging.user(self.user, "~FM~SBNot sending premium expire email, already sent before.") return delta = datetime.datetime.now() - self.last_seen_on months_ago = delta.days / 30 user = self.user data = dict(user=user, months_ago=months_ago) text = render_to_string('mail/email_premium_expire.txt', data) html = render_to_string('mail/email_premium_expire.xhtml', data) subject = "Your premium account on NewsBlur has expired" msg = EmailMultiAlternatives(subject, text, from_email='NewsBlur <%s>' % settings.HELLO_EMAIL, to=['%s <%s>' % (user, user.email)]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=True) MSentEmail.record(receiver_user_id=self.user.pk, email_type='premium_expire') logging.user(self.user, "~BB~FM~SBSending premium expire email for user: %s months, %s" % (months_ago, self.user.email)) def autologin_url(self, next=None): return reverse('autologin', kwargs={ 'username': self.user.username, 'secret': self.secret_token }) + ('?' + next + '=1' if next else '') @classmethod def doublecheck_paypal_payments(cls, days=14): payments = PayPalIPN.objects.filter(txn_type='subscr_payment', updated_at__gte=datetime.datetime.now() - datetime.timedelta(days) ).order_by('-created_at') for payment in payments: try: profile = Profile.objects.get(user__username=payment.custom) except Profile.DoesNotExist: logging.debug(" ---> ~FRCouldn't find user: ~SB~FC%s" % payment.custom) continue profile.setup_premium_history() class StripeIds(models.Model): user = models.ForeignKey(User, related_name='stripe_ids') stripe_id = models.CharField(max_length=24, blank=True, null=True) def __unicode__(self): return "%s: %s" % (self.user.username, self.stripe_id) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: Profile.objects.get_or_create(user=instance) post_save.connect(create_profile, sender=User) def paypal_signup(sender, **kwargs): ipn_obj = sender try: user = User.objects.get(username__iexact=ipn_obj.custom) except User.DoesNotExist: user = User.objects.get(email__iexact=ipn_obj.payer_email) logging.user(user, "~BC~SB~FBPaypal subscription signup") try: if not user.email: user.email = ipn_obj.payer_email user.save() except: pass user.profile.activate_premium() user.profile.cancel_premium_stripe() user.profile.cancel_premium_paypal(second_most_recent_only=True) subscription_signup.connect(paypal_signup) def paypal_payment_history_sync(sender, **kwargs): ipn_obj = sender try: user = User.objects.get(username__iexact=ipn_obj.custom) except User.DoesNotExist: user = User.objects.get(email__iexact=ipn_obj.payer_email) logging.user(user, "~BC~SB~FBPaypal subscription payment") try: user.profile.setup_premium_history() except: return {"code": -1, "message": "User doesn't exist."} payment_was_successful.connect(paypal_payment_history_sync) def paypal_payment_was_flagged(sender, **kwargs): ipn_obj = sender try: user = User.objects.get(username__iexact=ipn_obj.custom) except User.DoesNotExist: if ipn_obj.payer_email: user = User.objects.get(email__iexact=ipn_obj.payer_email) try: user.profile.setup_premium_history() logging.user(user, "~BC~SB~FBPaypal subscription payment flagged") except: return {"code": -1, "message": "User doesn't exist."} payment_was_flagged.connect(paypal_payment_was_flagged) def paypal_recurring_payment_history_sync(sender, **kwargs): ipn_obj = sender try: user = User.objects.get(username__iexact=ipn_obj.custom) except User.DoesNotExist: user = User.objects.get(email__iexact=ipn_obj.payer_email) logging.user(user, "~BC~SB~FBPaypal subscription recurring payment") try: user.profile.setup_premium_history() except: return {"code": -1, "message": "User doesn't exist."} recurring_payment.connect(paypal_recurring_payment_history_sync) def stripe_signup(sender, full_json, **kwargs): stripe_id = full_json['data']['object']['customer'] try: profile = Profile.objects.get(stripe_id=stripe_id) logging.user(profile.user, "~BC~SB~FBStripe subscription signup") profile.activate_premium() profile.cancel_premium_paypal() profile.retrieve_stripe_ids() except Profile.DoesNotExist: return {"code": -1, "message": "User doesn't exist."} zebra_webhook_customer_subscription_created.connect(stripe_signup) def stripe_payment_history_sync(sender, full_json, **kwargs): stripe_id = full_json['data']['object']['customer'] try: profile = Profile.objects.get(stripe_id=stripe_id) logging.user(profile.user, "~BC~SB~FBStripe subscription payment") profile.setup_premium_history() except Profile.DoesNotExist: return {"code": -1, "message": "User doesn't exist."} zebra_webhook_charge_succeeded.connect(stripe_payment_history_sync) def change_password(user, old_password, new_password, only_check=False): user_db = authenticate(username=user.username, password=old_password) if user_db is None: blank = blank_authenticate(user.username) if blank and not only_check: user.set_password(new_password or user.username) user.save() if user_db is None: user_db = authenticate(username=user.username, password=user.username) if not user_db: return -1 else: if not only_check: user_db.set_password(new_password) user_db.save() return 1 def blank_authenticate(username, password=""): try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: return if user.password == "!": return user algorithm, salt, hash = user.password.split('$', 2) encoded_blank = hashlib.sha1(salt + password).hexdigest() encoded_username = authenticate(username=username, password=username) if encoded_blank == hash or encoded_username == user: return user # Unfinished class MEmailUnsubscribe(mongo.Document): user_id = mongo.IntField() email_type = mongo.StringField() date = mongo.DateTimeField(default=datetime.datetime.now) EMAIL_TYPE_FOLLOWS = 'follows' EMAIL_TYPE_REPLIES = 'replies' EMAIL_TYOE_PRODUCT = 'product' meta = { 'collection': 'email_unsubscribes', 'allow_inheritance': False, 'indexes': ['user_id', {'fields': ['user_id', 'email_type'], 'unique': True, 'types': False}], } def __unicode__(self): return "%s unsubscribed from %s on %s" % (self.user_id, self.email_type, self.date) @classmethod def user(cls, user_id): unsubs = cls.objects(user_id=user_id) return unsubs @classmethod def unsubscribe(cls, user_id, email_type): cls.objects.create() class MSentEmail(mongo.Document): sending_user_id = mongo.IntField() receiver_user_id = mongo.IntField() email_type = mongo.StringField() date_sent = mongo.DateTimeField(default=datetime.datetime.now) meta = { 'collection': 'sent_emails', 'allow_inheritance': False, 'indexes': ['sending_user_id', 'receiver_user_id', 'email_type'], } def __unicode__(self): return "%s sent %s email to %s" % (self.sending_user_id, self.email_type, self.receiver_user_id) @classmethod def record(cls, email_type, receiver_user_id, sending_user_id=None): cls.objects.create(email_type=email_type, receiver_user_id=receiver_user_id, sending_user_id=sending_user_id) class PaymentHistory(models.Model): user = models.ForeignKey(User, related_name='payments') payment_date = models.DateTimeField() payment_amount = models.IntegerField() payment_provider = models.CharField(max_length=20) payment_identifier = models.CharField(max_length=100, null=True) def __unicode__(self): return "[%s] $%s/%s" % (self.payment_date.strftime("%Y-%m-%d"), self.payment_amount, self.payment_provider) class Meta: ordering = ['-payment_date'] def canonical(self): return { 'payment_date': self.payment_date.strftime('%Y-%m-%d'), 'payment_amount': self.payment_amount, 'payment_provider': self.payment_provider, } @classmethod def report(cls, months=26): output = "" def _counter(start_date, end_date, output, payments=None): if not payments: payments = PaymentHistory.objects.filter(payment_date__gte=start_date, payment_date__lte=end_date) payments = payments.aggregate(avg=Avg('payment_amount'), sum=Sum('payment_amount'), count=Count('user')) output += "%s-%02d-%02d - %s-%02d-%02d:\t$%.2f\t$%-6s\t%-4s\n" % ( start_date.year, start_date.month, start_date.day, end_date.year, end_date.month, end_date.day, round(payments['avg'] if payments['avg'] else 0, 2), payments['sum'] if payments['sum'] else 0, payments['count']) return payments, output output += "\nMonthly Totals:\n" for m in reversed(range(months)): now = datetime.datetime.now() start_date = datetime.datetime(now.year, now.month, 1) - dateutil.relativedelta.relativedelta(months=m) end_time = start_date + datetime.timedelta(days=31) end_date = datetime.datetime(end_time.year, end_time.month, 1) - datetime.timedelta(seconds=1) total, output = _counter(start_date, end_date, output) total = total['sum'] output += "\nMTD Totals:\n" years = datetime.datetime.now().year - 2009 this_mtd_avg = 0 last_mtd_avg = 0 last_mtd_sum = 0 this_mtd_sum = 0 last_mtd_count = 0 this_mtd_count = 0 for y in reversed(range(years)): now = datetime.datetime.now() start_date = datetime.datetime(now.year, now.month, 1) - dateutil.relativedelta.relativedelta(years=y) end_date = now - dateutil.relativedelta.relativedelta(years=y) if end_date > now: end_date = now count, output = _counter(start_date, end_date, output) if end_date.year != now.year: last_mtd_avg = count['avg'] or 0 last_mtd_sum = count['sum'] or 0 last_mtd_count = count['count'] else: this_mtd_avg = count['avg'] or 0 this_mtd_sum = count['sum'] or 0 this_mtd_count = count['count'] output += "\nCurrent Month Totals:\n" years = datetime.datetime.now().year - 2009 last_month_avg = 0 last_month_sum = 0 last_month_count = 0 for y in reversed(range(years)): now = datetime.datetime.now() start_date = datetime.datetime(now.year, now.month, 1) - dateutil.relativedelta.relativedelta(years=y) end_time = start_date + datetime.timedelta(days=31) end_date = datetime.datetime(end_time.year, end_time.month, 1) - datetime.timedelta(seconds=1) if end_date > now: payments = {'avg': this_mtd_avg / (max(1, last_mtd_avg) / float(max(1, last_month_avg))), 'sum': int(round(this_mtd_sum / (max(1, last_mtd_sum) / float(max(1, last_month_sum))))), 'count': int(round(this_mtd_count / (max(1, last_mtd_count) / float(max(1, last_month_count)))))} _, output = _counter(start_date, end_date, output, payments=payments) else: count, output = _counter(start_date, end_date, output) last_month_avg = count['avg'] last_month_sum = count['sum'] last_month_count = count['count'] output += "\nYTD Totals:\n" years = datetime.datetime.now().year - 2009 this_ytd_avg = 0 last_ytd_avg = 0 this_ytd_sum = 0 last_ytd_sum = 0 this_ytd_count = 0 last_ytd_count = 0 for y in reversed(range(years)): now = datetime.datetime.now() start_date = datetime.datetime(now.year, 1, 1) - dateutil.relativedelta.relativedelta(years=y) end_date = now - dateutil.relativedelta.relativedelta(years=y) count, output = _counter(start_date, end_date, output) if end_date.year != now.year: last_ytd_avg = count['avg'] or 0 last_ytd_sum = count['sum'] or 0 last_ytd_count = count['count'] else: this_ytd_avg = count['avg'] or 0 this_ytd_sum = count['sum'] or 0 this_ytd_count = count['count'] output += "\nYearly Totals:\n" years = datetime.datetime.now().year - 2009 last_year_avg = 0 last_year_sum = 0 last_year_count = 0 annual = 0 for y in reversed(range(years)): now = datetime.datetime.now() start_date = datetime.datetime(now.year, 1, 1) - dateutil.relativedelta.relativedelta(years=y) end_date = datetime.datetime(now.year, 1, 1) - dateutil.relativedelta.relativedelta(years=y-1) - datetime.timedelta(seconds=1) if end_date > now: payments = {'avg': this_ytd_avg / (max(1, last_ytd_avg) / float(max(1, last_year_avg))), 'sum': int(round(this_ytd_sum / (max(1, last_ytd_sum) / float(max(1, last_year_sum))))), 'count': int(round(this_ytd_count / (max(1, last_ytd_count) / float(max(1, last_year_count)))))} count, output = _counter(start_date, end_date, output, payments=payments) annual = count['sum'] else: count, output = _counter(start_date, end_date, output) last_year_avg = count['avg'] or 0 last_year_sum = count['sum'] or 0 last_year_count = count['count'] total = cls.objects.all().aggregate(sum=Sum('payment_amount')) output += "\nTotal: $%s\n" % total['sum'] print output return {'annual': annual, 'output': output} class MGiftCode(mongo.Document): gifting_user_id = mongo.IntField() receiving_user_id = mongo.IntField() gift_code = mongo.StringField(max_length=12) duration_days = mongo.IntField() payment_amount = mongo.IntField() created_date = mongo.DateTimeField(default=datetime.datetime.now) meta = { 'collection': 'gift_codes', 'allow_inheritance': False, 'indexes': ['gifting_user_id', 'receiving_user_id', 'created_date'], } def __unicode__(self): return "%s gifted %s on %s: %s (redeemed %s times)" % (self.gifting_user_id, self.receiving_user_id, self.created_date, self.gift_code, self.redeemed) @property def redeemed(self): redeemed_code = MRedeemedCode.objects.filter(gift_code=self.gift_code) return len(redeemed_code) @staticmethod def create_code(gift_code=None): u = unicode(uuid.uuid4()) code = u[:8] + u[9:13] if gift_code: code = gift_code + code[len(gift_code):] return code @classmethod def add(cls, gift_code=None, duration=0, gifting_user_id=None, receiving_user_id=None, payment=0): return cls.objects.create(gift_code=cls.create_code(gift_code), gifting_user_id=gifting_user_id, receiving_user_id=receiving_user_id, duration_days=duration, payment_amount=payment) class MRedeemedCode(mongo.Document): user_id = mongo.IntField() gift_code = mongo.StringField() redeemed_date = mongo.DateTimeField(default=datetime.datetime.now) meta = { 'collection': 'redeemed_codes', 'allow_inheritance': False, 'indexes': ['user_id', 'gift_code', 'redeemed_date'], } def __unicode__(self): return "%s redeemed %s on %s" % (self.user_id, self.gift_code, self.redeemed_date) @classmethod def record(cls, user_id, gift_code): cls.objects.create(user_id=user_id, gift_code=gift_code) @classmethod def redeem(cls, user, gift_code): newsblur_gift_code = MGiftCode.objects.filter(gift_code__iexact=gift_code) if newsblur_gift_code: newsblur_gift_code = newsblur_gift_code[0] PaymentHistory.objects.create(user=user, payment_date=datetime.datetime.now(), payment_amount=newsblur_gift_code.payment_amount, payment_provider='newsblur-gift') else: # Thinkup / Good Web Bundle PaymentHistory.objects.create(user=user, payment_date=datetime.datetime.now(), payment_amount=12, payment_provider='good-web-bundle') cls.record(user.pk, gift_code) user.profile.activate_premium() logging.user(user, "~FG~BBRedeeming gift code: %s~FW" % gift_code) class MCustomStyling(mongo.Document): user_id = mongo.IntField(unique=True) custom_css = mongo.StringField() custom_js = mongo.StringField() updated_date = mongo.DateTimeField(default=datetime.datetime.now) meta = { 'collection': 'custom_styling', 'allow_inheritance': False, 'indexes': ['user_id'], } def __unicode__(self): return "%s custom style %s/%s %s" % (self.user_id, len(self.custom_css) if self.custom_css else "-", len(self.custom_js) if self.custom_js else "-", self.updated_date) def canonical(self): return { 'css': self.custom_css, 'js': self.custom_js, } @classmethod def get_user(cls, user_id): try: styling = cls.objects.get(user_id=user_id) except cls.DoesNotExist: return None return styling @classmethod def save_user(cls, user_id, css, js): styling = cls.get_user(user_id) if not css and not js: if styling: styling.delete() return if not styling: styling = cls.objects.create(user_id=user_id) styling.custom_css = css styling.custom_js = js styling.save() class RNewUserQueue: KEY = "new_user_queue" @classmethod def activate_next(cls): count = cls.user_count() if not count: return user_id = cls.pop_user() try: user = User.objects.get(pk=user_id) except User.DoesNotExist: logging.debug("~FRCan't activate free account, can't find user ~SB%s~SN. ~FB%s still in queue." % (user_id, count-1)) return logging.user(user, "~FBActivating free account (%s / %s). %s still in queue." % (user.email, user.profile.last_seen_ip, (count-1))) user.profile.activate_free() @classmethod def activate_all(cls): count = cls.user_count() if not count: logging.debug("~FBNo users to activate, sleeping...") return for i in range(count): cls.activate_next() @classmethod def add_user(cls, user_id): r = redis.Redis(connection_pool=settings.REDIS_FEED_UPDATE_POOL) now = time.time() r.zadd(cls.KEY, user_id, now) @classmethod def user_count(cls): r = redis.Redis(connection_pool=settings.REDIS_FEED_UPDATE_POOL) count = r.zcard(cls.KEY) return count @classmethod def user_position(cls, user_id): r = redis.Redis(connection_pool=settings.REDIS_FEED_UPDATE_POOL) position = r.zrank(cls.KEY, user_id) if position >= 0: return position + 1 @classmethod def pop_user(cls): r = redis.Redis(connection_pool=settings.REDIS_FEED_UPDATE_POOL) user = r.zrange(cls.KEY, 0, 0)[0] r.zrem(cls.KEY, user) return user
{ "content_hash": "bd81cfe51f5f50e1a74e835a70ff201b", "timestamp": "", "source": "github", "line_count": 1561, "max_line_length": 163, "avg_line_length": 44.63741191543882, "alnum_prop": 0.5680334103531911, "repo_name": "AlphaCluster/NewsBlur", "id": "ea72c1b2c996081e3de135af54e58a58c9f12326", "size": "69679", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/profile/models.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "454" }, { "name": "CSS", "bytes": "720684" }, { "name": "CoffeeScript", "bytes": "9696" }, { "name": "Dockerfile", "bytes": "1331" }, { "name": "HTML", "bytes": "492242" }, { "name": "Java", "bytes": "955691" }, { "name": "JavaScript", "bytes": "1680848" }, { "name": "Objective-C", "bytes": "2591129" }, { "name": "Perl", "bytes": "55598" }, { "name": "Python", "bytes": "2741187" }, { "name": "R", "bytes": "527" }, { "name": "Ruby", "bytes": "870" }, { "name": "Shell", "bytes": "40999" }, { "name": "Swift", "bytes": "3520" } ], "symlink_target": "" }
from atve.application.atveapplication import AtveTestRunner
{ "content_hash": "ae82c044a63c1f5e07aa4279b357d85f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 59, "avg_line_length": 60, "alnum_prop": 0.9, "repo_name": "TE-ToshiakiTanaka/atve", "id": "0959a802db215b2b48a117ea69322ecaf0eb1439", "size": "60", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "atve/application/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "149305" }, { "name": "Shell", "bytes": "1792" } ], "symlink_target": "" }
import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * # Destination settings source_server = "" target_server = "" port = 53 # Build test packet to catch tcp_pkt = Ether() / IP(dst=target_server) / TCP(dport=port) print("Sending test packet...\n----") print(tcp_pkt.summary()) sendp(tcp_pkt)
{ "content_hash": "10142ae695bad67c6dd56598fd8631f7", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 59, "avg_line_length": 22.6, "alnum_prop": 0.7138643067846607, "repo_name": "Aclark2089/Scapy_DDoS", "id": "10a8d93b4459c22335154934021cce6706d432d8", "size": "369", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test_send.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2377" }, { "name": "Shell", "bytes": "189" } ], "symlink_target": "" }
from django.conf.urls import url from django.core.exceptions import ObjectDoesNotExist from django.core.paginator import Paginator, InvalidPage from django.db.models import Count from django.http import Http404 from django.template.loader import render_to_string from tastypie import fields from tastypie.authorization import Authorization from tastypie.constants import ALL_WITH_RELATIONS from tastypie.exceptions import ImmediateHttpResponse from tastypie.fields import ToOneField from tastypie.http import HttpGone, HttpUnauthorized from tastypie.utils import trailing_slash from dss import settings from spa.api.v1.BaseResource import BaseResource from spa.api.v1.CommentResource import CommentResource from spa.api.v1.ActivityResource import ActivityResource from spa.models.mix import Mix from spa.models.show import Show from spa.models.userprofile import UserProfile class MixResource(BaseResource): comments = fields.ToManyField('spa.api.v1.CommentResource.CommentResource', 'comments', null=True, full=True) favourites = fields.ToManyField('spa.api.v1.UserResource.UserResource', 'favourites', related_name='favourites', full=False, null=True) likes = fields.ToManyField('spa.api.v1.UserResource.UserResource', 'likes', related_name='likes', full=False, null=True) genres = fields.ToManyField('spa.api.v1.GenreResource.GenreResource', 'genres', related_name='genres', full=True, null=True) class Meta: queryset = Mix.objects.filter(is_active=True) user = ToOneField('UserResource', 'user') always_return_data = True detail_uri_name = 'slug' excludes = ['is_active', 'waveform-generated'] post_excludes = ['comments'] filtering = {'comments': ALL_WITH_RELATIONS, 'genres': ALL_WITH_RELATIONS, 'favourites': ALL_WITH_RELATIONS, 'likes': ALL_WITH_RELATIONS, 'title': ALL_WITH_RELATIONS, 'slug': ALL_WITH_RELATIONS, } authorization = Authorization() def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/search%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_search'), name="api_get_search"), url(r"^(?P<resource_name>%s)/(?P<id>[\d]+)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), url(r"^(?P<resource_name>%s)/random%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_random'), name="api_dispatch_random"), url(r"^(?P<resource_name>%s)/(?P<slug>[\w\d-]+)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), url(r"^(?P<resource_name>%s)/(?P<slug>\w[\w/-]*)/comments%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_comments'), name="api_get_comments"), url(r"^(?P<resource_name>%s)/(?P<slug>\w[\w/-]*)/activity%s$" % ( self._meta.resource_name, trailing_slash()), self.wrap_view('get_activity'), name="api_get_activity"), ] def dispatch_random(self, request, **kwargs): kwargs['pk'] = \ self._meta.queryset.values_list('pk', flat=True).order_by('?')[0] return self.get_detail(request, **kwargs) def get_comments(self, request, **kwargs): try: basic_bundle = self.build_bundle(request=request) obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() child_resource = CommentResource() return child_resource.get_list(request, mix=obj) def get_activity(self, request, **kwargs): try: basic_bundle = self.build_bundle(request=request) obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs)) except ObjectDoesNotExist: return HttpGone() child_resource = ActivityResource() return child_resource.get_list(request, mix=obj) def obj_create(self, bundle, **kwargs): if 'is_featured' not in bundle.data: bundle.data['is_featured'] = False if 'download_allowed' not in bundle.data: bundle.data['download_allowed'] = False #AAAAAH - STOP BEING LAZY AND REMOVE THIS if settings.DEBUG and bundle.request.user.is_anonymous(): bundle.data['user'] = UserProfile.objects.get(pk=2) else: bundle.data['user'] = bundle.request.user.get_profile() ret = super(MixResource, self).obj_create( bundle, user=bundle.data['user'], uid=bundle.data['upload-hash'], extension=bundle.data['upload-extension']) return ret def obj_update(self, bundle, **kwargs): #don't sync the mix_image, this has to be handled separately bundle.data.pop('mix_image', None) ret = super(MixResource, self).obj_update(bundle, bundle.request) bundle.obj.update_favourite(bundle.request.user, bundle.data['favourited']) bundle.obj.update_liked(bundle.request.user, bundle.data['liked']) return ret def apply_sorting(self, obj_list, options=None): orderby = options.get('order_by', '') if orderby == 'latest': obj_list = obj_list.order_by('-id') elif orderby == 'toprated': obj_list = obj_list.annotate( karma=Count('activity_likes')).order_by('-karma') elif orderby == 'mostplayed': obj_list = obj_list.annotate( karma=Count('activity_plays')).order_by('-karma') elif orderby == 'mostactive': obj_list = obj_list.annotate( karma=Count('comments')).order_by('-karma') elif orderby == 'recommended': obj_list = obj_list.annotate( karma=Count('activity_likes')).order_by('-karma') return obj_list def apply_filters(self, request, applicable_filters): semi_filtered = super(MixResource, self) \ .apply_filters(request, applicable_filters) \ .filter(waveform_generated=True) f_user = request.GET.get('user', None) if request.GET.get('stream'): if request.user.is_anonymous(): raise ImmediateHttpResponse( HttpUnauthorized("Only logged in users have a stream") ) semi_filtered = semi_filtered.filter( user__in=request.user.get_profile().following.all()) if request.GET.get('for_show'): semi_filtered = semi_filtered.filter(show__isnull=True) if f_user is not None: semi_filtered = semi_filtered.filter(user__slug=f_user) elif len(applicable_filters) == 0: semi_filtered = semi_filtered.filter(is_featured=True) return semi_filtered def dehydrate_mix_image(self, bundle): return bundle.obj.get_image_url(size="160x110") def dehydrate(self, bundle): bundle.data['waveform_url'] = bundle.obj.get_waveform_url() bundle.data['audio_src'] = bundle.obj.get_stream_path() bundle.data['user_name'] = bundle.obj.user.get_nice_name() bundle.data['user_profile_url'] = bundle.obj.user.get_absolute_url() bundle.data['user_profile_image'] = \ bundle.obj.user.get_small_profile_image() bundle.data['item_url'] = '/mix/%s' % bundle.obj.slug bundle.data['download_allowed'] = bundle.obj.download_allowed bundle.data['favourite_count'] = bundle.obj.favourites.count() bundle.data['play_count'] = bundle.obj.activity_plays.count() bundle.data['download_count'] = bundle.obj.activity_downloads.count() bundle.data['like_count'] = bundle.obj.activity_likes.count() bundle.data['tooltip'] = render_to_string('inc/player_tooltip.html', {'item': bundle.obj}) bundle.data['comment_count'] = bundle.obj.comments.count() bundle.data['liked'] = bundle.obj.is_liked(bundle.request.user) if bundle.request.user.is_authenticated(): bundle.data['can_edit'] = bundle.request.user.is_staff or \ bundle.obj.user_id == bundle.request.user.get_profile().id else: bundle.data['can_edit'] = False if bundle.request.user.is_authenticated(): bundle.data['favourited'] = bundle.obj.favourites.filter( user=bundle.request.user).count() != 0 else: bundle.data['favourited'] = False return bundle def get_search(self, request, **kwargs): self.method_check(request, allowed=['get']) self.is_authenticated(request) self.throttle_check(request) # Do the query. sqs = Mix.objects.filter(title__icontains=request.GET.get('q', '')) paginator = Paginator(sqs, 20) try: page = paginator.page(int(request.GET.get('page', 1))) except InvalidPage: raise Http404("Sorry, no results on that page.") objects = [] for result in page.object_list: bundle = self.build_bundle(obj=result, request=request) bundle = self.full_dehydrate(bundle) objects.append(bundle) object_list = {'objects': objects, } self.log_throttled_access(request) return self.create_response(request, object_list)
{ "content_hash": "f0fe401dc26bb4417b19381dc7a62c80", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 79, "avg_line_length": 42.717213114754095, "alnum_prop": 0.5747865297898878, "repo_name": "fergalmoran/dss", "id": "e044d277957c47dd765148e890e8010d01f560f3", "size": "10423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spa/api/v1/MixResource.py", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "1335630" }, { "name": "CoffeeScript", "bytes": "91082" }, { "name": "JavaScript", "bytes": "3576558" }, { "name": "Python", "bytes": "1543569" } ], "symlink_target": "" }
#!/usr/bin/python import realog.debug as debug import lutin.tools as tools import os def get_type(): return "LIBRARY" def get_desc(): return "opencv CORE library matrix computation evironement" def get_licence(): return "APAPCHE-2" def get_maintainer(): return ["Maksim Shabunin <maksim.shabunin@itseez.com>"] def get_version(): return [3,1,0] def configure(target, my_module): my_module.add_src_file([ 'opencv/modules/core/src/stl.cpp', 'opencv/modules/core/src/matrix_decomp.cpp', 'opencv/modules/core/src/array.cpp', 'opencv/modules/core/src/matop.cpp', 'opencv/modules/core/src/mathfuncs_core.cpp', 'opencv/modules/core/src/tables.cpp', 'opencv/modules/core/src/matmul.cpp', 'opencv/modules/core/src/copy.cpp', 'opencv/modules/core/src/algorithm.cpp', 'opencv/modules/core/src/cuda_info.cpp', 'opencv/modules/core/src/types.cpp', 'opencv/modules/core/src/umatrix.cpp', 'opencv/modules/core/src/arithm.cpp', 'opencv/modules/core/src/opencl/runtime/opencl_clamdblas.cpp', 'opencv/modules/core/src/opencl/runtime/opencl_clamdfft.cpp', 'opencv/modules/core/src/opencl/runtime/opencl_core.cpp', 'opencv/modules/core/src/split.cpp', 'opencv/modules/core/src/lapack.cpp', 'opencv/modules/core/src/conjugate_gradient.cpp', 'opencv/modules/core/src/system.cpp', 'opencv/modules/core/src/ocl.cpp', 'opencv/modules/core/src/lda.cpp', 'opencv/modules/core/src/out.cpp', 'opencv/modules/core/src/persistence.cpp', 'opencv/modules/core/src/alloc.cpp', 'opencv/modules/core/src/directx.cpp', 'opencv/modules/core/src/stat.cpp', 'opencv/modules/core/src/matrix.cpp', 'opencv/modules/core/src/cuda_host_mem.cpp', 'opencv/modules/core/src/glob.cpp', 'opencv/modules/core/src/mathfuncs.cpp', 'opencv/modules/core/src/convert.cpp', 'opencv/modules/core/src/cuda_gpu_mat.cpp', 'opencv/modules/core/src/downhill_simplex.cpp', 'opencv/modules/core/src/kmeans.cpp', 'opencv/modules/core/src/rand.cpp', 'opencv/modules/core/src/parallel.cpp', 'opencv/modules/core/src/dxt.cpp', 'opencv/modules/core/src/parallel_pthreads.cpp', 'opencv/modules/core/src/va_intel.cpp', 'opencv/modules/core/src/merge.cpp', 'opencv/modules/core/src/command_line_parser.cpp', 'opencv/modules/core/src/datastructs.cpp', 'opencv/modules/core/src/gl_core_3_1.cpp', 'opencv/modules/core/src/opengl.cpp', 'opencv/modules/core/src/pca.cpp', 'opencv/modules/core/src/lpsolver.cpp', 'opencv/modules/core/src/cuda_stream.cpp', ]) my_module.add_flag('c++', [ "-DCVAPI_EXPORTS", "-D__OPENCV_BUILD=1", "-fsigned-char", "-W", "-Wall", "-Werror=return-type", "-Werror=non-virtual-dtor", "-Werror=address", "-Werror=sequence-point", "-Wformat", "-Werror=format-security", "-Wmissing-declarations", "-Winit-self", "-Wpointer-arith", "-Wshadow", "-Wsign-promo", "-Wno-narrowing", "-Wno-delete-non-virtual-dtor", "-fdiagnostics-show-option", "-Wno-long-long", "-fomit-frame-pointer", "-ffunction-sections", "-fvisibility=hidden", "-fvisibility-inlines-hidden", ]) my_module.add_header_file( 'opencv/modules/core/include/*', recursive=True) my_module.add_depend([ 'pthread', 'm', 'z', 'cxx', ]) if "Android" in target.get_type(): my_module.add_depend("SDK") my_module.add_flag('c++', "-DANDROID") my_module.compile_version("C++", 2003) my_module.add_header_file([ 'generated/*' ], destination_path="") # generate dynamic file generate_config_file(my_module) return True def generate_config_file(my_module): #-------------------------------------------------------------------------------------- file_data = "/* Auto generate file with lutin */\n" file_data+= "#pragma once\n" file_data+= "\n" file_data+= "#define HAVE_OPENCV_CALIB3D\n" file_data+= "#define HAVE_OPENCV_CORE\n" file_data+= "#define HAVE_OPENCV_FEATURES2D\n" file_data+= "#define HAVE_OPENCV_FLANN\n" #file_data+= "#define HAVE_OPENCV_HIGHGUI\n" #file_data+= "#define HAVE_OPENCV_IMGCODECS\n" file_data+= "#define HAVE_OPENCV_IMGPROC\n" file_data+= "#define HAVE_OPENCV_ML\n" file_data+= "#define HAVE_OPENCV_OBJDETECT\n" file_data+= "#define HAVE_OPENCV_PHOTO\n" file_data+= "#define HAVE_OPENCV_SHAPE\n" file_data+= "#define HAVE_OPENCV_STITCHING\n" file_data+= "#define HAVE_OPENCV_SUPERRES\n" file_data+= "#define HAVE_OPENCV_VIDEO\n" #file_data+= "#define HAVE_OPENCV_VIDEOIO\n" #file_data+= "#define HAVE_OPENCV_VIDEOSTAB\n" file_data+= "\n" my_module.add_generated_header_file(file_data, "opencv2/opencv_modules.hpp") #-------------------------------------------------------------------------------------- file_data = "/* Auto generate file with lutin */\n" file_data+= "#pragma once\n" file_data+= "// OpenCV compiled as static or dynamic libs\n" file_data+= "#define BUILD_SHARED_LIBS\n" #file_data+= "// Compile for 'real' NVIDIA GPU architectures\n" #file_data+= "#define CUDA_ARCH_BIN ""\n" #file_data+= "// Create PTX or BIN for 1.0 compute capability\n" #file_data+= "#define CUDA_ARCH_BIN_OR_PTX_10\n" #file_data+= "// NVIDIA GPU features are used\n" #file_data+= "#define CUDA_ARCH_FEATURES ""\n" #file_data+= "// Compile for 'virtual' NVIDIA PTX architectures\n" #file_data+= "#define CUDA_ARCH_PTX ""\n" #file_data+= "// AVFoundation video libraries\n" #file_data+= "#define HAVE_AVFOUNDATION\n" #file_data+= "// V4L capturing support\n" #file_data+= "#define HAVE_CAMV4L\n" #file_data+= "// V4L2 capturing support\n" #file_data+= "#define HAVE_CAMV4L2\n" #file_data+= "// Carbon windowing environment\n" #file_data+= "#define HAVE_CARBON\n" #file_data+= "// AMD's Basic Linear Algebra Subprograms Library*/\n" #file_data+= "#define HAVE_CLAMDBLAS\n" #file_data+= "// AMD's OpenCL Fast Fourier Transform Library*/\n" #file_data+= "#define HAVE_CLAMDFFT\n" #file_data+= "// Clp support\n" #file_data+= "#define HAVE_CLP\n" #file_data+= "// Cocoa API\n" #file_data+= "#define HAVE_COCOA\n" #file_data+= "// C=\n" #file_data+= "#define HAVE_CSTRIPES\n" #file_data+= "// NVidia Cuda Basic Linear Algebra Subprograms (BLAS) API*/\n" #file_data+= "#define HAVE_CUBLAS\n" #file_data+= "// NVidia Cuda Runtime API*/\n" #file_data+= "#define HAVE_CUDA\n" #file_data+= "// NVidia Cuda Fast Fourier Transform (FFT) API*/\n" #file_data+= "#define HAVE_CUFFT\n" #file_data+= "// IEEE1394 capturing support\n" #file_data+= "#define HAVE_DC1394\n" #file_data+= "// IEEE1394 capturing support - libdc1394 v2.x\n" #file_data+= "#define HAVE_DC1394_2\n" #file_data+= "// DirectX\n" #file_data+= "#define HAVE_DIRECTX\n" #file_data+= "#define HAVE_DIRECTX_NV12\n" #file_data+= "#define HAVE_D3D11\n" #file_data+= "#define HAVE_D3D10\n" #file_data+= "#define HAVE_D3D9\n" #file_data+= "// DirectShow Video Capture library\n" #file_data+= "#define HAVE_DSHOW\n" #file_data+= "// Eigen Matrix & Linear Algebra Library\n" #file_data+= "#define HAVE_EIGEN\n" #file_data+= "// FFMpeg video library\n" #file_data+= "#define HAVE_FFMPEG\n" #file_data+= "// ffmpeg's libswscale\n" #file_data+= "#define HAVE_FFMPEG_SWSCALE\n" #file_data+= "// ffmpeg in Gentoo\n" #file_data+= "#define HAVE_GENTOO_FFMPEG\n" #file_data+= "// Geospatial Data Abstraction Library\n" #file_data+= "#define HAVE_GDAL\n" #file_data+= "// GStreamer multimedia framework\n" #file_data+= "#define HAVE_GSTREAMER\n" #file_data+= "// GTK+ 2.0 Thread support\n" #file_data+= "#define HAVE_GTHREAD\n" #file_data+= "// GTK+ 2.x toolkit\n" #file_data+= "#define HAVE_GTK\n" #file_data+= "// Define to 1 if you have the <inttypes.h> header file.\n" #file_data+= "#define HAVE_INTTYPES_H\n" #file_data+= "// Intel Perceptual Computing SDK library\n" #file_data+= "#define HAVE_INTELPERC\n" #file_data+= "// Intel Integrated Performance Primitives\n" #file_data+= "#define HAVE_IPP\n" #file_data+= "#define HAVE_IPP_ICV_ONLY\n" #file_data+= "// Intel IPP Async\n" #file_data+= "// #define HAVE_IPP_A\n" #file_data+= "// JPEG-2000 codec\n" #file_data+= "#define HAVE_JASPER\n" #file_data+= "// IJG JPEG codec\n" #file_data+= "#define HAVE_JPEG\n" #file_data+= "// libpng/png.h needs to be included\n" #file_data+= "#define HAVE_LIBPNG_PNG_H\n" #file_data+= "// GDCM DICOM codec\n" #file_data+= "#define HAVE_GDCM\n" #file_data+= "// V4L/V4L2 capturing support via libv4l\n" #file_data+= "#define HAVE_LIBV4L\n" #file_data+= "// Microsoft Media Foundation Capture library\n" #file_data+= "#define HAVE_MSMF\n" #file_data+= "// NVidia Video Decoding API*/\n" #file_data+= "#define HAVE_NVCUVID\n" #file_data+= "// NVidia Video Encoding API*/\n" #file_data+= "#define HAVE_NVCUVENC\n" #file_data+= "// OpenCL Support\n" #file_data+= "#define HAVE_OPENCL\n" #file_data+= "#define HAVE_OPENCL_STATIC\n" #file_data+= "#define HAVE_OPENCL_SVM\n" #file_data+= "// OpenEXR codec\n" #file_data+= "#define HAVE_OPENEXR\n" #file_data+= "// OpenGL support*/\n" #file_data+= "#define HAVE_OPENGL\n" #file_data+= "// OpenNI library\n" #file_data+= "#define HAVE_OPENNI\n" #file_data+= "// OpenNI library\n" #file_data+= "#define HAVE_OPENNI2\n" #file_data+= "// PNG codec\n" #file_data+= "#define HAVE_PNG\n" file_data+= "// Posix threads (pthreads)\n" file_data+= "#define HAVE_PTHREADS\n" file_data+= "// parallel_for with pthreads\n" file_data+= "#define HAVE_PTHREADS_PF\n" #file_data+= "// Qt support\n" #file_data+= "#define HAVE_QT\n" #file_data+= "// Qt OpenGL support\n" #file_data+= "#define HAVE_QT_OPENGL\n" #file_data+= "// QuickTime video libraries\n" #file_data+= "#define HAVE_QUICKTIME\n" #file_data+= "// QTKit video libraries\n" #file_data+= "#define HAVE_QTKIT\n" #file_data+= "// Intel Threading Building Blocks\n" #file_data+= "#define HAVE_TBB\n" #file_data+= "// TIFF codec\n" #file_data+= "#define HAVE_TIFF\n" #file_data+= "// Unicap video capture library\n" #file_data+= "#define HAVE_UNICAP\n" #file_data+= "// Video for Windows support\n" #file_data+= "#define HAVE_VFW\n" #file_data+= "// V4L2 capturing support in videoio.h\n" #file_data+= "#define HAVE_VIDEOIO\n" #file_data+= "// Win32 UI\n" #file_data+= "#define HAVE_WIN32UI\n" #file_data+= "// XIMEA camera support\n" #file_data+= "#define HAVE_XIMEA\n" #file_data+= "// Xine video library\n" #file_data+= "#define HAVE_XINE\n" #file_data+= "// Define if your processor stores words with the most significant byte\n" #file_data+= "// first (like Motorola and SPARC, unlike Intel and VAX).\n" #file_data+= "#define WORDS_BIGENDIAN\n" #file_data+= "// gPhoto2 library\n" #file_data+= "#define HAVE_GPHOTO2\n" #file_data+= "// VA library (libva)\n" #file_data+= "#define HAVE_VA\n" #file_data+= "// Intel VA-API/OpenCL\n" #file_data+= "#define HAVE_VA_INTEL\n" #file_data+= "// Lapack\n" #file_data+= "#define HAVE_LAPACK\n" #file_data+= "// FP16\n" #file_data+= "#define HAVE_FP16\n" #my_module.add_generated_header_file(file_data, "opencv2/cvconfig.h", True) my_module.add_generated_header_file(file_data, "cvconfig.h", True) file_data = "/* Auto generate file with lutin */\n" file_data+= "#pragma once\n" my_module.add_generated_header_file(file_data, "custom_hal.hpp") file_data = "\"generate with lutin build system ...\\n\"" my_module.add_generated_header_file(file_data, "version_string.inc")
{ "content_hash": "e17cf1a83d702e728f604ef144133089", "timestamp": "", "source": "github", "line_count": 300, "max_line_length": 89, "avg_line_length": 38.50333333333333, "alnum_prop": 0.650333304475803, "repo_name": "generic-library/opencv-lutin", "id": "e908c8013a59a811084ff7da860f8669e4d76d65", "size": "11551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lutin_opencv-core.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4180" }, { "name": "C++", "bytes": "8004" }, { "name": "Python", "bytes": "35600" } ], "symlink_target": "" }
import ConfigParser import os config = ConfigParser.ConfigParser() config.read('rapa.cnf') mysql_server = config.get('Mysql', 'server') mysql_port = config.get('Mysql', 'port') mysql_user = config.get('Mysql', 'user') mysql_password = config.get('Mysql', 'password') mysql_database = config.get('Mysql', 'DB') mysql_database_table = config.get('Mysql', 'table') node_latitude = config.get('Node', 'latitude') node_longitude = config.get('Node', 'longitude') node_mac = config.get('Node', 'mac') node_name = config.get('Node', 'name') node_ip = config.get('Node', 'ip') node_port = config.getint('Node', 'port') radius_server = config.get('Radius', 'server') radius_secret = config.get('Radius', 'secret') radius_dictionary = config.get('Radius', 'dictionary') custom_url = config.get('Custom', 'url') custom_nas_port = config.getint('Custom', 'nas_port') custom_nas_port_type = config.getint('Custom', 'nas_port_type') custom_url = config.get('Custom', 'url') custom_wispr_location_id = config.get('Custom', 'wispr_location_id') custom_wispr_location_name = config.get('Custom', 'wispr_location_name') custom_footer_html_message = config.get('Custom', 'footer_html_message') session_session_expiry = config.get('Session', 'session_expiry')
{ "content_hash": "89bf77c301cf1277e80bb39acce71ab2", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 72, "avg_line_length": 37.75757575757576, "alnum_prop": 0.7054574638844302, "repo_name": "giorgioladu/Rapa", "id": "36f5bb1a774ae7c3cd0096507f312d00c8f5da83", "size": "2159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1263" }, { "name": "HTML", "bytes": "112" }, { "name": "JavaScript", "bytes": "220" }, { "name": "Python", "bytes": "28167" } ], "symlink_target": "" }
def create_controller_js(stream, module): """ Creates AngularJS controller from module :param stream: :param module: :return: """ from wutu_compiler.utils import get_implemented_methods from wutu_compiler.core.grammar import Provider, Function, SimpleDeclare stream.write("wutu.controller('{0}Controller', ".format(module.__class__.__name__)) service = Provider("{0}Service".format(module.__class__.__name__)) scope = Provider("$scope") methods = get_implemented_methods(module) entity_name = "{0}_list".format(module.get_entity_name()) params = module.get_identifier() post_params = params + ("data",) put_params = ("data",) scope[entity_name] = service.list() scope.refresh = Function(None, body=[SimpleDeclare(scope[entity_name].compile(), service.list())]) scope["get_{0}".format(module.get_entity_name())] = Function(params, returns=service.get(*params)) scope["create_{0}".format(module.get_entity_name())] = Function(put_params, body=[service.put(*put_params), scope.refresh()]) scope["update_{0}".format(module.get_entity_name())] = Function(post_params, body=[service.post(*post_params), scope.refresh()]) scope["remove_{0}".format(module.get_entity_name())] = Function(params, body=[service.delete(*params), scope.refresh()]) impl = Function([scope.name, service.name], body=scope.assignments) stream.write(impl.compile()) stream.write(");")
{ "content_hash": "439404145be8b4b829344ed25e6879d4", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 132, "avg_line_length": 53.81481481481482, "alnum_prop": 0.6751548520302821, "repo_name": "zaibacu/wutu-compiler", "id": "8711bece4fb191d8a3d17bc215cbd3b764f0c356", "size": "1453", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wutu_compiler/core/controller.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1316" }, { "name": "Python", "bytes": "27389" } ], "symlink_target": "" }
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'BlogPost.post_ptr' db.delete_column('cms_blogpost', 'post_ptr_id') # Adding field 'BlogPost.id' db.add_column('cms_blogpost', 'id', self.gf('django.db.models.fields.AutoField')(default=1, primary_key=True), keep_default=False) # Adding field 'BlogPost.title' db.add_column('cms_blogpost', 'title', self.gf('django.db.models.fields.CharField')(default=1, max_length=255), keep_default=False) # Adding field 'BlogPost.date' db.add_column('cms_blogpost', 'date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now), keep_default=False) # Adding field 'BlogPost.post' db.add_column('cms_blogpost', 'post', self.gf('django.db.models.fields.TextField')(default=1), keep_default=False) def backwards(self, orm): # User chose to not deal with backwards NULL issues for 'BlogPost.post_ptr' raise RuntimeError("Cannot reverse this migration. 'BlogPost.post_ptr' and its values cannot be restored.") # Deleting field 'BlogPost.id' db.delete_column('cms_blogpost', 'id') # Deleting field 'BlogPost.title' db.delete_column('cms_blogpost', 'title') # Deleting field 'BlogPost.date' db.delete_column('cms_blogpost', 'date') # Deleting field 'BlogPost.post' db.delete_column('cms_blogpost', 'post') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'cms.blogpost': { 'Meta': {'ordering': "['-date']", 'object_name': 'BlogPost'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Member']"}), 'date': ('django.db.models.fields.DateTimeField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'post': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'cms.member': { 'Meta': {'object_name': 'Member'}, 'blurb': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'classification': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'group': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'homepage': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}), 'interests': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'profile'", 'to': "orm['auth.User']"}) }, 'cms.news': { 'Meta': {'object_name': 'News'}, 'content': ('django.db.models.fields.TextField', [], {}), 'date': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'max_length': '200'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '100', 'db_index': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'cms.page': { 'Meta': {'object_name': 'Page'}, 'content': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'pub_front_page': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'pub_menu': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '100', 'db_index': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'cms.project': { 'Meta': {'object_name': 'Project'}, 'coordinator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'project'", 'to': "orm['cms.Member']"}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'+'", 'symmetrical': 'False', 'to': "orm['cms.Member']"}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['cms']
{ "content_hash": "004d9b7db4cbaafa6c64638d125b2dff", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 182, "avg_line_length": 62.732824427480914, "alnum_prop": 0.5564614261377464, "repo_name": "ncsu-stars/Stars-CMS", "id": "4f1ff15553a54f42548a24bd9f02ddb9191424ba", "size": "8236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cms/migrations/0010_auto__del_field_blogpost_post_ptr__add_field_blogpost_id__add_field_bl.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "12004" }, { "name": "HTML", "bytes": "60895" }, { "name": "JavaScript", "bytes": "60468" }, { "name": "Python", "bytes": "247430" } ], "symlink_target": "" }
"""Site services for use with a Web Site Process Bus.""" import os import re import signal as _signal import sys import time import threading from cherrypy._cpcompat import basestring, get_daemon, get_thread_ident from cherrypy._cpcompat import ntob, Timer, SetDaemonProperty # _module__file__base is used by Autoreload to make # absolute any filenames retrieved from sys.modules which are not # already absolute paths. This is to work around Python's quirk # of importing the startup script and using a relative filename # for it in sys.modules. # # Autoreload examines sys.modules afresh every time it runs. If an application # changes the current directory by executing os.chdir(), then the next time # Autoreload runs, it will not be able to find any filenames which are # not absolute paths, because the current directory is not the same as when the # module was first imported. Autoreload will then wrongly conclude the file # has "changed", and initiate the shutdown/re-exec sequence. # See ticket #917. # For this workaround to have a decent probability of success, this module # needs to be imported as early as possible, before the app has much chance # to change the working directory. _module__file__base = os.getcwd() class SimplePlugin(object): """Plugin base class which auto-subscribes methods for known channels.""" bus = None """A :class:`Bus <cherrypy.process.wspbus.Bus>`, usually cherrypy.engine. """ def __init__(self, bus): self.bus = bus def subscribe(self): """Register this object as a (multi-channel) listener on the bus.""" for channel in self.bus.listeners: # Subscribe self.start, self.exit, etc. if present. method = getattr(self, channel, None) if method is not None: self.bus.subscribe(channel, method) def unsubscribe(self): """Unregister this object as a listener on the bus.""" for channel in self.bus.listeners: # Unsubscribe self.start, self.exit, etc. if present. method = getattr(self, channel, None) if method is not None: self.bus.unsubscribe(channel, method) class SignalHandler(object): """Register bus channels (and listeners) for system signals. You can modify what signals your application listens for, and what it does when it receives signals, by modifying :attr:`SignalHandler.handlers`, a dict of {signal name: callback} pairs. The default set is:: handlers = {'SIGTERM': self.bus.exit, 'SIGHUP': self.handle_SIGHUP, 'SIGUSR1': self.bus.graceful, } The :func:`SignalHandler.handle_SIGHUP`` method calls :func:`bus.restart()<cherrypy.process.wspbus.Bus.restart>` if the process is daemonized, but :func:`bus.exit()<cherrypy.process.wspbus.Bus.exit>` if the process is attached to a TTY. This is because Unix window managers tend to send SIGHUP to terminal windows when the user closes them. Feel free to add signals which are not available on every platform. The :class:`SignalHandler` will ignore errors raised from attempting to register handlers for unknown signals. """ handlers = {} """A map from signal names (e.g. 'SIGTERM') to handlers (e.g. bus.exit).""" signals = {} """A map from signal numbers to names.""" for k, v in vars(_signal).items(): if k.startswith('SIG') and not k.startswith('SIG_'): signals[v] = k del k, v def __init__(self, bus): self.bus = bus # Set default handlers self.handlers = {'SIGTERM': self.bus.exit, 'SIGHUP': self.handle_SIGHUP, 'SIGUSR1': self.bus.graceful, } if sys.platform[:4] == 'java': del self.handlers['SIGUSR1'] self.handlers['SIGUSR2'] = self.bus.graceful self.bus.log("SIGUSR1 cannot be set on the JVM platform. " "Using SIGUSR2 instead.") self.handlers['SIGINT'] = self._jython_SIGINT_handler self._previous_handlers = {} # used to determine is the process is a daemon in `self._is_daemonized` self._original_pid = os.getpid() def _jython_SIGINT_handler(self, signum=None, frame=None): # See http://bugs.jython.org/issue1313 self.bus.log('Keyboard Interrupt: shutting down bus') self.bus.exit() def _is_daemonized(self): """Return boolean indicating if the current process is running as a daemon. The criteria to determine the `daemon` condition is to verify if the current pid is not the same as the one that got used on the initial construction of the plugin *and* the stdin is not connected to a terminal. The sole validation of the tty is not enough when the plugin is executing inside other process like in a CI tool (Buildbot, Jenkins). """ if (self._original_pid != os.getpid() and not os.isatty(sys.stdin.fileno())): return True else: return False def subscribe(self): """Subscribe self.handlers to signals.""" for sig, func in self.handlers.items(): try: self.set_handler(sig, func) except ValueError: pass def unsubscribe(self): """Unsubscribe self.handlers from signals.""" for signum, handler in self._previous_handlers.items(): signame = self.signals[signum] if handler is None: self.bus.log("Restoring %s handler to SIG_DFL." % signame) handler = _signal.SIG_DFL else: self.bus.log("Restoring %s handler %r." % (signame, handler)) try: our_handler = _signal.signal(signum, handler) if our_handler is None: self.bus.log("Restored old %s handler %r, but our " "handler was not registered." % (signame, handler), level=30) except ValueError: self.bus.log("Unable to restore %s handler %r." % (signame, handler), level=40, traceback=True) def set_handler(self, signal, listener=None): """Subscribe a handler for the given signal (number or name). If the optional 'listener' argument is provided, it will be subscribed as a listener for the given signal's channel. If the given signal name or number is not available on the current platform, ValueError is raised. """ if isinstance(signal, basestring): signum = getattr(_signal, signal, None) if signum is None: raise ValueError("No such signal: %r" % signal) signame = signal else: try: signame = self.signals[signal] except KeyError: raise ValueError("No such signal: %r" % signal) signum = signal prev = _signal.signal(signum, self._handle_signal) self._previous_handlers[signum] = prev if listener is not None: self.bus.log("Listening for %s." % signame) self.bus.subscribe(signame, listener) def _handle_signal(self, signum=None, frame=None): """Python signal handler (self.set_handler subscribes it for you).""" signame = self.signals[signum] self.bus.log("Caught signal %s." % signame) self.bus.publish(signame) def handle_SIGHUP(self): """Restart if daemonized, else exit.""" if self._is_daemonized(): self.bus.log("SIGHUP caught while daemonized. Restarting.") self.bus.restart() else: # not daemonized (may be foreground or background) self.bus.log("SIGHUP caught but not daemonized. Exiting.") self.bus.exit() try: import pwd import grp except ImportError: pwd, grp = None, None class DropPrivileges(SimplePlugin): """Drop privileges. uid/gid arguments not available on Windows. Special thanks to `Gavin Baker <http://antonym.org/2005/12/dropping-privileges-in-python.html>`_ """ def __init__(self, bus, umask=None, uid=None, gid=None): SimplePlugin.__init__(self, bus) self.finalized = False self.uid = uid self.gid = gid self.umask = umask def _get_uid(self): return self._uid def _set_uid(self, val): if val is not None: if pwd is None: self.bus.log("pwd module not available; ignoring uid.", level=30) val = None elif isinstance(val, basestring): val = pwd.getpwnam(val)[2] self._uid = val uid = property(_get_uid, _set_uid, doc="The uid under which to run. Availability: Unix.") def _get_gid(self): return self._gid def _set_gid(self, val): if val is not None: if grp is None: self.bus.log("grp module not available; ignoring gid.", level=30) val = None elif isinstance(val, basestring): val = grp.getgrnam(val)[2] self._gid = val gid = property(_get_gid, _set_gid, doc="The gid under which to run. Availability: Unix.") def _get_umask(self): return self._umask def _set_umask(self, val): if val is not None: try: os.umask except AttributeError: self.bus.log("umask function not available; ignoring umask.", level=30) val = None self._umask = val umask = property( _get_umask, _set_umask, doc="""The default permission mode for newly created files and directories. Usually expressed in octal format, for example, ``0644``. Availability: Unix, Windows. """) def start(self): # uid/gid def current_ids(): """Return the current (uid, gid) if available.""" name, group = None, None if pwd: name = pwd.getpwuid(os.getuid())[0] if grp: group = grp.getgrgid(os.getgid())[0] return name, group if self.finalized: if not (self.uid is None and self.gid is None): self.bus.log('Already running as uid: %r gid: %r' % current_ids()) else: if self.uid is None and self.gid is None: if pwd or grp: self.bus.log('uid/gid not set', level=30) else: self.bus.log('Started as uid: %r gid: %r' % current_ids()) if self.gid is not None: os.setgid(self.gid) os.setgroups([]) if self.uid is not None: os.setuid(self.uid) self.bus.log('Running as uid: %r gid: %r' % current_ids()) # umask if self.finalized: if self.umask is not None: self.bus.log('umask already set to: %03o' % self.umask) else: if self.umask is None: self.bus.log('umask not set', level=30) else: old_umask = os.umask(self.umask) self.bus.log('umask old: %03o, new: %03o' % (old_umask, self.umask)) self.finalized = True # This is slightly higher than the priority for server.start # in order to facilitate the most common use: starting on a low # port (which requires root) and then dropping to another user. start.priority = 77 class Daemonizer(SimplePlugin): """Daemonize the running script. Use this with a Web Site Process Bus via:: Daemonizer(bus).subscribe() When this component finishes, the process is completely decoupled from the parent environment. Please note that when this component is used, the return code from the parent process will still be 0 if a startup error occurs in the forked children. Errors in the initial daemonizing process still return proper exit codes. Therefore, if you use this plugin to daemonize, don't use the return code as an accurate indicator of whether the process fully started. In fact, that return code only indicates if the process succesfully finished the first fork. """ def __init__(self, bus, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): SimplePlugin.__init__(self, bus) self.stdin = stdin self.stdout = stdout self.stderr = stderr self.finalized = False def start(self): if self.finalized: self.bus.log('Already deamonized.') # forking has issues with threads: # http://www.opengroup.org/onlinepubs/000095399/functions/fork.html # "The general problem with making fork() work in a multi-threaded # world is what to do with all of the threads..." # So we check for active threads: if threading.activeCount() != 1: self.bus.log('There are %r active threads. ' 'Daemonizing now may cause strange failures.' % threading.enumerate(), level=30) # See http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 # (or http://www.faqs.org/faqs/unix-faq/programmer/faq/ section 1.7) # and http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 # Finish up with the current stdout/stderr sys.stdout.flush() sys.stderr.flush() # Do first fork. try: pid = os.fork() if pid == 0: # This is the child process. Continue. pass else: # This is the first parent. Exit, now that we've forked. self.bus.log('Forking once.') os._exit(0) except OSError: # Python raises OSError rather than returning negative numbers. exc = sys.exc_info()[1] sys.exit("%s: fork #1 failed: (%d) %s\n" % (sys.argv[0], exc.errno, exc.strerror)) os.setsid() # Do second fork try: pid = os.fork() if pid > 0: self.bus.log('Forking twice.') os._exit(0) # Exit second parent except OSError: exc = sys.exc_info()[1] sys.exit("%s: fork #2 failed: (%d) %s\n" % (sys.argv[0], exc.errno, exc.strerror)) os.chdir("/") os.umask(0) si = open(self.stdin, "r") so = open(self.stdout, "a+") se = open(self.stderr, "a+") # os.dup2(fd, fd2) will close fd2 if necessary, # so we don't explicitly close stdin/out/err. # See http://docs.python.org/lib/os-fd-ops.html os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) self.bus.log('Daemonized to PID: %s' % os.getpid()) self.finalized = True start.priority = 65 class PIDFile(SimplePlugin): """Maintain a PID file via a WSPBus.""" def __init__(self, bus, pidfile): SimplePlugin.__init__(self, bus) self.pidfile = pidfile self.finalized = False def start(self): pid = os.getpid() if self.finalized: self.bus.log('PID %r already written to %r.' % (pid, self.pidfile)) else: open(self.pidfile, "wb").write(ntob("%s\n" % pid, 'utf8')) self.bus.log('PID %r written to %r.' % (pid, self.pidfile)) self.finalized = True start.priority = 70 def exit(self): try: os.remove(self.pidfile) self.bus.log('PID file removed: %r.' % self.pidfile) except (KeyboardInterrupt, SystemExit): raise except: pass class PerpetualTimer(Timer): """A responsive subclass of threading.Timer whose run() method repeats. Use this timer only when you really need a very interruptible timer; this checks its 'finished' condition up to 20 times a second, which can results in pretty high CPU usage """ def __init__(self, *args, **kwargs): "Override parent constructor to allow 'bus' to be provided." self.bus = kwargs.pop('bus', None) super(PerpetualTimer, self).__init__(*args, **kwargs) def run(self): while True: self.finished.wait(self.interval) if self.finished.isSet(): return try: self.function(*self.args, **self.kwargs) except Exception: if self.bus: self.bus.log( "Error in perpetual timer thread function %r." % self.function, level=40, traceback=True) # Quit on first error to avoid massive logs. raise class BackgroundTask(SetDaemonProperty, threading.Thread): """A subclass of threading.Thread whose run() method repeats. Use this class for most repeating tasks. It uses time.sleep() to wait for each interval, which isn't very responsive; that is, even if you call self.cancel(), you'll have to wait until the sleep() call finishes before the thread stops. To compensate, it defaults to being daemonic, which means it won't delay stopping the whole process. """ def __init__(self, interval, function, args=[], kwargs={}, bus=None): threading.Thread.__init__(self) self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.running = False self.bus = bus # default to daemonic self.daemon = True def cancel(self): self.running = False def run(self): self.running = True while self.running: time.sleep(self.interval) if not self.running: return try: self.function(*self.args, **self.kwargs) except Exception: if self.bus: self.bus.log("Error in background task thread function %r." % self.function, level=40, traceback=True) # Quit on first error to avoid massive logs. raise class Monitor(SimplePlugin): """WSPBus listener to periodically run a callback in its own thread.""" callback = None """The function to call at intervals.""" frequency = 60 """The time in seconds between callback runs.""" thread = None """A :class:`BackgroundTask<cherrypy.process.plugins.BackgroundTask>` thread. """ def __init__(self, bus, callback, frequency=60, name=None): SimplePlugin.__init__(self, bus) self.callback = callback self.frequency = frequency self.thread = None self.name = name def start(self): """Start our callback in its own background thread.""" if self.frequency > 0: threadname = self.name or self.__class__.__name__ if self.thread is None: self.thread = BackgroundTask(self.frequency, self.callback, bus=self.bus) self.thread.setName(threadname) self.thread.start() self.bus.log("Started monitor thread %r." % threadname) else: self.bus.log("Monitor thread %r already started." % threadname) start.priority = 70 def stop(self): """Stop our callback's background task thread.""" if self.thread is None: self.bus.log("No thread running for %s." % self.name or self.__class__.__name__) else: if self.thread is not threading.currentThread(): name = self.thread.getName() self.thread.cancel() if not get_daemon(self.thread): self.bus.log("Joining %r" % name) self.thread.join() self.bus.log("Stopped thread %r." % name) self.thread = None def graceful(self): """Stop the callback's background task thread and restart it.""" self.stop() self.start() class Autoreloader(Monitor): """Monitor which re-executes the process when files change. This :ref:`plugin<plugins>` restarts the process (via :func:`os.execv`) if any of the files it monitors change (or is deleted). By default, the autoreloader monitors all imported modules; you can add to the set by adding to ``autoreload.files``:: cherrypy.engine.autoreload.files.add(myFile) If there are imported files you do *not* wish to monitor, you can adjust the ``match`` attribute, a regular expression. For example, to stop monitoring cherrypy itself:: cherrypy.engine.autoreload.match = r'^(?!cherrypy).+' Like all :class:`Monitor<cherrypy.process.plugins.Monitor>` plugins, the autoreload plugin takes a ``frequency`` argument. The default is 1 second; that is, the autoreloader will examine files once each second. """ files = None """The set of files to poll for modifications.""" frequency = 1 """The interval in seconds at which to poll for modified files.""" match = '.*' """A regular expression by which to match filenames.""" def __init__(self, bus, frequency=1, match='.*'): self.mtimes = {} self.files = set() self.match = match Monitor.__init__(self, bus, self.run, frequency) def start(self): """Start our own background task thread for self.run.""" if self.thread is None: self.mtimes = {} Monitor.start(self) start.priority = 70 def sysfiles(self): """Return a Set of sys.modules filenames to monitor.""" files = set() for k, m in list(sys.modules.items()): if re.match(self.match, k): if ( hasattr(m, '__loader__') and hasattr(m.__loader__, 'archive') ): f = m.__loader__.archive else: f = getattr(m, '__file__', None) if f is not None and not os.path.isabs(f): # ensure absolute paths so a os.chdir() in the app # doesn't break me f = os.path.normpath( os.path.join(_module__file__base, f)) files.add(f) return files def run(self): """Reload the process if registered files have been modified.""" for filename in self.sysfiles() | self.files: if filename: if filename.endswith('.pyc'): filename = filename[:-1] oldtime = self.mtimes.get(filename, 0) if oldtime is None: # Module with no .py file. Skip it. continue try: mtime = os.stat(filename).st_mtime except OSError: # Either a module with no .py file, or it's been deleted. mtime = None if filename not in self.mtimes: # If a module has no .py file, this will be None. self.mtimes[filename] = mtime else: if mtime is None or mtime > oldtime: # The file has been deleted or modified. self.bus.log("Restarting because %s changed." % filename) self.thread.cancel() self.bus.log("Stopped thread %r." % self.thread.getName()) self.bus.restart() return class ThreadManager(SimplePlugin): """Manager for HTTP request threads. If you have control over thread creation and destruction, publish to the 'acquire_thread' and 'release_thread' channels (for each thread). This will register/unregister the current thread and publish to 'start_thread' and 'stop_thread' listeners in the bus as needed. If threads are created and destroyed by code you do not control (e.g., Apache), then, at the beginning of every HTTP request, publish to 'acquire_thread' only. You should not publish to 'release_thread' in this case, since you do not know whether the thread will be re-used or not. The bus will call 'stop_thread' listeners for you when it stops. """ threads = None """A map of {thread ident: index number} pairs.""" def __init__(self, bus): self.threads = {} SimplePlugin.__init__(self, bus) self.bus.listeners.setdefault('acquire_thread', set()) self.bus.listeners.setdefault('start_thread', set()) self.bus.listeners.setdefault('release_thread', set()) self.bus.listeners.setdefault('stop_thread', set()) def acquire_thread(self): """Run 'start_thread' listeners for the current thread. If the current thread has already been seen, any 'start_thread' listeners will not be run again. """ thread_ident = get_thread_ident() if thread_ident not in self.threads: # We can't just use get_ident as the thread ID # because some platforms reuse thread ID's. i = len(self.threads) + 1 self.threads[thread_ident] = i self.bus.publish('start_thread', i) def release_thread(self): """Release the current thread and run 'stop_thread' listeners.""" thread_ident = get_thread_ident() i = self.threads.pop(thread_ident, None) if i is not None: self.bus.publish('stop_thread', i) def stop(self): """Release all threads and run all 'stop_thread' listeners.""" for thread_ident, i in self.threads.items(): self.bus.publish('stop_thread', i) self.threads.clear() graceful = stop
{ "content_hash": "6537cd03f3a8715c28b96d031e08ed84", "timestamp": "", "source": "github", "line_count": 740, "max_line_length": 100, "avg_line_length": 36.002702702702706, "alnum_prop": 0.5698896479243301, "repo_name": "CodyKochmann/pi-cluster", "id": "0ec585c0a6e35910d2ebef06456b2b1db1d3d35d", "size": "26642", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "software/src/cherrypy/process/plugins.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17" }, { "name": "HTML", "bytes": "524" }, { "name": "Python", "bytes": "1275353" }, { "name": "Shell", "bytes": "569" } ], "symlink_target": "" }
import re import json import sys pattern = re.compile(r"""\s* # starting whitespaces (?P<distribution>[\d\.\*]{10}?)\s+ # distribution of votes (?P<votes>[\d]*?)\s+ # number of votes (?P<rating>\d0?\.\d?)\s+ # rating ['"]?(?P<title>.+?)['"]?\s* # movie title, optionally quoted \((?P<year>[\d\?]{4}?).*\) # year .*""", re.VERBOSE) # anything else def extract_data(s): try: return pattern.search(s).groups() except AttributeError: print("ERROR while parsing the following line\n" + s) sys.exit(1) return None if len(sys.argv) != 3: print("ERROR\nusage: parse_ratings.py <input file> <output_file>\n" + s) sys.exit(1) stop_line_pattern = "-------------------------------------------------------" start_line_pattern = "New Distribution Votes Rank Title" processing = 0 out_part_num = 0 line_num = 0 out_file = open(sys.argv[2], "w", encoding="utf-8") for line in open(sys.argv[1], "r", encoding="latin-1"): if line.startswith(start_line_pattern): processing += 1 continue if processing<3 or len(line.strip()) == 0: continue if line.startswith(stop_line_pattern): break if "{" in line: continue parsed_data = extract_data(line) to_print = "%s\t%s\t%s\t%s\t%s" % parsed_data print(to_print, file = out_file) line_num += 1 out_file.close() print("exported lines: %d" % line_num)
{ "content_hash": "9ac7d01ceba1e5a5e31e84fe544e6338", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 88, "avg_line_length": 30.72222222222222, "alnum_prop": 0.49065702230259195, "repo_name": "symat/spark-api-comparison", "id": "5a791342e1b0ff8613e29b2f804535353f8c93ff", "size": "1675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/parse_ratings_all.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "8552" }, { "name": "Scala", "bytes": "25674" } ], "symlink_target": "" }
import re import pygame from log import Logerer from colours import * from time import sleep from numpy import add class Background(object): '''class to draw background given a string''' def __init__(self, name, level_string, verbose=True, screen=False): '''class for creating background''' self.name = name self.level_string = level_string self.verbose = verbose self.logger = Logerer() self.log(level_string) self.meta = {} self.blocks = set() self.liquid = set() self.level_lines = [] self.block_width = 0 self.block_height = 0 self.block_matrix = {"h": self.draw_house, "~": self.draw_water, "#": self.draw_path} self.screen = pygame.display.set_mode( (50, 50), pygame.RESIZABLE) if not screen else screen for line in self.level_string.split("\n"): if "=" in line: key, value = line.split("=") self.meta[key] = value if "[" in line and "]" in line: match = re.match(".*\[(.*)\]", line) self.level_lines.append(match.group(1)) self.block_height += 1 if len(match.group(1)) > self.block_width: self.block_width = len(match.group(1)) self.block_vectors = (self.block_width ,self.block_height) self.get_npcs() def dummy(self, *args): pass def log(self, message): '''basic logging method''' if self.verbose: self.logger.log(__name__ + " : " + self.name, message) def listify(self, a_string): return a_string.replace(" ","").split(",") def get_npcs(self): self.npc_names = self.meta.get("npcs", False) if not self.npc_names: self.log("No npcs") self.npcs = False return False self.npc_names = self.listify(self.npc_names) self.npcs = {} for name in self.npc_names: self.npcs[name] = {"position" : self.meta.get(name + ".position", "0, 4")} self.npcs[name]["position"] = self.listify(self.npcs[name]["position"]) self.log(str(self.npcs)) def draw_block_background(self, block_string, x, y): '''takes the block string and the x y coordinates''' self.block_matrix.get(block_string, self.dummy)(x, y) def draw_block_foreground(self, block_string, x, y): '''intended to run and draw foreground elements''' def draw_block_colour(self, x, y, colour, corners=[True, True, True, True]): '''draws a solid background colour at particular co-ordinates''' corners = list(corners) top_left = [x * self.hs, y * self.vs, self.hs/2, self.vs/2] top_right = [x * self.hs + self.hs/2, y * self.vs, self.hs/2 + 1, self.vs/2] bottom_left = [x * self.hs, y * self.vs + self.vs/2, self.hs/2, self.vs/2] bottom_right = [x * self.hs + self.hs/2, y * self.vs + self.vs/2, self.hs/2 + 1, self.vs/2] for corner in (top_left, top_right, bottom_left, bottom_right): c = corners.pop(0) if c: corner = add([1,1,1,1],corner) self.screen.fill(colour, corner) def draw_house(self, x, y): '''draws a house''' for X in x, x + 1: self.blocks.add((X, y)) self.draw_block_colour(x, y, YELLOW, corners=[0,1,0,1]) self.draw_block_colour(x + 1, y, YELLOW, corners=[1,0,1,0]) def draw_water(self, x, y): '''draws water''' left = (x -1, y ) in self.liquid up = (x, y -1) in self.liquid self.liquid.add((x,y)) if left: self.draw_block_colour(x, y, BLUE, corners=[0,0,1,0]) left = True if up: self.draw_block_colour(x, y, BLUE, corners=[0,1,0,0]) up = True if left and up: self.draw_block_colour(x, y, BLUE, corners=[1,0,0,0]) self.draw_block_colour(x, y, BLUE, corners=[0,0,0,1]) def draw_path(self, x, y): '''draws a path''' self.draw_block_colour(x, y, WHITE) def base_grass_biom(self): '''draws a default grass biom''' #self.log("colour green") self.screen.fill(GREEN) def draw_level(self, width, height, biom="grass"): '''sets scalars for other drawing methods and ''' self.scalar = (self.horizontal_scalar, self.vertical_scalar) = ( self.hs, self.vs) = (width / self.block_width, height / self.block_width) y = 0 x = 0 if biom == "grass": self.base_grass_biom() for line in self.level_lines: for block in line: if block is not " ": self.draw_block_background(block, x, y) self.draw_block_foreground(block, x, y) x += 1 y += 1 x = 0 if __name__ == '__main__': pygame.init() level = '''meta=test npcs= Ian, Keith Keith.position=4, 0 [ h ] [ ~ ] [ # ]''' my_background = Background("one", level) while True: my_background.draw_level(50, 50) pygame.display.update()
{ "content_hash": "786b11750c1430370e471ada4e4adf4e", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 99, "avg_line_length": 35.689189189189186, "alnum_prop": 0.5276410450586899, "repo_name": "martyni/rusty_game", "id": "8b79de2fec70715a1198ef56e052f3232065a27d", "size": "5282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rusty_game/background.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "35011" } ], "symlink_target": "" }
class UnitError(Exception): '''Unit Error''' pass class UnitExecutionError(UnitError): '''Unit Execution Error''' pass class UnitOutputError(UnitError): '''Unit Output Error''' pass
{ "content_hash": "07d53d3fe0a73b495f300819d1cf0717", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 36, "avg_line_length": 17.416666666666668, "alnum_prop": 0.6602870813397129, "repo_name": "Harmon758/Harmonbot", "id": "704c7b85c96b1c5bf0084378925e296dcc8b8bf3", "size": "210", "binary": false, "copies": "1", "ref": "refs/heads/rewrite", "path": "units/errors.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "483" }, { "name": "Go", "bytes": "4664" }, { "name": "Python", "bytes": "974320" }, { "name": "mIRC Script", "bytes": "127551" } ], "symlink_target": "" }
from __future__ import annotations from dynaconf import settings print(settings.YAML) print(settings.HOST) print(settings.PORT) # using production values for context with settings.using_env("PRODUCTION"): print(settings.ENVIRONMENT) print(settings.HOST) # back to development env print(settings.get("ENVIRONMENT")) print(settings.HOST) print(settings.WORKS) assertions = { "HOST": "dev_server.com", "PORT": 5000, "ENVIRONMENT": "this is development", "WORKS": "yaml_as_extra_config", } for key, value in assertions.items(): found = settings.get(key) assert found == getattr(settings, key) assert found == value, f"expected: {key}: [{value}] found: [{found}]" assertions = { "HOST": "prod_server.com", "PORT": 5000, "ENVIRONMENT": "this is production", } for key, value in assertions.items(): found = settings.from_env("production").get(key) assert found == getattr(settings.from_env("production"), key) assert found == value, f"expected: {key}: [{value}] found: [{found}]"
{ "content_hash": "a65678ea4c0a7cb0b5fe3762e76f92c6", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 73, "avg_line_length": 23.244444444444444, "alnum_prop": 0.6749521988527725, "repo_name": "rochacbruno/dynaconf", "id": "02bedcf4af428c5a7397a50806ae821e16021565", "size": "1046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example/yaml_example/yaml_as_extra_config/app.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2867" }, { "name": "Makefile", "bytes": "11505" }, { "name": "Python", "bytes": "1438471" }, { "name": "Shell", "bytes": "14740" } ], "symlink_target": "" }
"""Tests for the file entry implementation using the SleuthKit (TSK).""" import unittest from dfvfs.path import os_path_spec from dfvfs.path import qcow_path_spec from dfvfs.path import tsk_path_spec from dfvfs.resolver import context from dfvfs.vfs import tsk_file_entry from dfvfs.vfs import tsk_file_system from tests import test_lib as shared_test_lib @shared_test_lib.skipUnlessHasTestFile([u'Γ­mynd.dd']) class TSKFileEntryTestExt2(shared_test_lib.BaseTestCase): """The unit test for the SleuthKit (TSK) file entry object on ext2.""" def setUp(self): """Sets up the needed objects used throughout the test.""" self._resolver_context = context.Context() test_file = self._GetTestFilePath([u'Γ­mynd.dd']) self._os_path_spec = os_path_spec.OSPathSpec(location=test_file) self._tsk_path_spec = tsk_path_spec.TSKPathSpec( location=u'/', parent=self._os_path_spec) self._file_system = tsk_file_system.TSKFileSystem(self._resolver_context) self._file_system.Open(self._tsk_path_spec) def tearDown(self): """Cleans up the needed objects used throughout the test.""" self._file_system.Close() def testInitialize(self): """Test the __init__ function.""" file_entry = tsk_file_entry.TSKFileEntry( self._resolver_context, self._file_system, self._tsk_path_spec) self.assertIsNotNone(file_entry) def testGetFileEntryByPathSpec(self): """Tests the GetFileEntryByPathSpec function.""" path_spec = tsk_path_spec.TSKPathSpec(inode=15, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) def testGetLinkedFileEntry(self): """Tests the GetLinkedFileEntry function.""" test_location = u'/a_link' path_spec = tsk_path_spec.TSKPathSpec( inode=13, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) linked_file_entry = file_entry.GetLinkedFileEntry() self.assertIsNotNone(linked_file_entry) self.assertEqual(linked_file_entry.name, u'another_file') def testGetParentFileEntry(self): """Tests the GetParentFileEntry function.""" test_location = u'/a_directory/another_file' path_spec = tsk_path_spec.TSKPathSpec( inode=16, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) parent_file_entry = file_entry.GetParentFileEntry() self.assertIsNotNone(parent_file_entry) self.assertEqual(parent_file_entry.name, u'a_directory') def testGetStat(self): """Tests the GetStat function.""" test_location = u'/a_directory/another_file' path_spec = tsk_path_spec.TSKPathSpec( inode=16, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) stat_object = file_entry.GetStat() self.assertIsNotNone(stat_object) self.assertEqual(stat_object.type, stat_object.TYPE_FILE) self.assertEqual(stat_object.size, 22) self.assertEqual(stat_object.mode, 384) self.assertEqual(stat_object.uid, 151107) self.assertEqual(stat_object.gid, 5000) self.assertEqual(stat_object.atime, 1337961563) self.assertEqual(stat_object.atime_nano, None) self.assertEqual(stat_object.ctime, 1337961563) self.assertEqual(stat_object.ctime_nano, None) # EXT2 has no crtime timestamp. with self.assertRaises(AttributeError): _ = stat_object.crtime with self.assertRaises(AttributeError): _ = stat_object.crtime_nano self.assertEqual(stat_object.mtime, 1337961563) self.assertEqual(stat_object.mtime_nano, None) def testIsFunctions(self): """Test the Is? functions.""" test_location = u'/a_directory/another_file' path_spec = tsk_path_spec.TSKPathSpec( inode=16, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertFalse(file_entry.IsRoot()) self.assertFalse(file_entry.IsVirtual()) self.assertTrue(file_entry.IsAllocated()) self.assertFalse(file_entry.IsDevice()) self.assertFalse(file_entry.IsDirectory()) self.assertTrue(file_entry.IsFile()) self.assertFalse(file_entry.IsLink()) self.assertFalse(file_entry.IsPipe()) self.assertFalse(file_entry.IsSocket()) test_location = u'/a_directory' path_spec = tsk_path_spec.TSKPathSpec( inode=12, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertFalse(file_entry.IsRoot()) self.assertFalse(file_entry.IsVirtual()) self.assertTrue(file_entry.IsAllocated()) self.assertFalse(file_entry.IsDevice()) self.assertTrue(file_entry.IsDirectory()) self.assertFalse(file_entry.IsFile()) self.assertFalse(file_entry.IsLink()) self.assertFalse(file_entry.IsPipe()) self.assertFalse(file_entry.IsSocket()) path_spec = tsk_path_spec.TSKPathSpec( location=u'/', parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertTrue(file_entry.IsRoot()) self.assertFalse(file_entry.IsVirtual()) self.assertTrue(file_entry.IsAllocated()) self.assertFalse(file_entry.IsDevice()) self.assertTrue(file_entry.IsDirectory()) self.assertFalse(file_entry.IsFile()) self.assertFalse(file_entry.IsLink()) self.assertFalse(file_entry.IsPipe()) self.assertFalse(file_entry.IsSocket()) def testSubFileEntries(self): """Test the sub file entries iteration functionality.""" path_spec = tsk_path_spec.TSKPathSpec( location=u'/', parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.number_of_sub_file_entries, 5) # Note that passwords.txt~ is currently ignored by dfvfs, since # its directory entry has no pytsk3.TSK_FS_META object. expected_sub_file_entry_names = [ u'a_directory', u'a_link', u'lost+found', u'passwords.txt', u'$OrphanFiles'] sub_file_entry_names = [] for sub_file_entry in file_entry.sub_file_entries: sub_file_entry_names.append(sub_file_entry.name) self.assertEqual( len(sub_file_entry_names), len(expected_sub_file_entry_names)) self.assertEqual( sorted(sub_file_entry_names), sorted(expected_sub_file_entry_names)) def testDataStreams(self): """Test the data streams functionality.""" test_location = u'/a_directory/another_file' path_spec = tsk_path_spec.TSKPathSpec( inode=16, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.number_of_data_streams, 1) data_stream_names = [] for data_stream in file_entry.data_streams: data_stream_names.append(data_stream.name) self.assertEqual(data_stream_names, [u'']) test_location = u'/a_directory' path_spec = tsk_path_spec.TSKPathSpec( inode=12, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.number_of_data_streams, 0) data_stream_names = [] for data_stream in file_entry.data_streams: data_stream_names.append(data_stream.name) self.assertEqual(data_stream_names, []) def testGetDataStream(self): """Tests the GetDataStream function.""" test_location = u'/a_directory/another_file' path_spec = tsk_path_spec.TSKPathSpec( inode=16, location=test_location, parent=self._os_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) data_stream_name = u'' data_stream = file_entry.GetDataStream(data_stream_name) self.assertIsNotNone(data_stream) class TSKFileEntryTestHFS(unittest.TestCase): """The unit test for the SleuthKit (TSK) file entry object on HFS.""" # TODO: implement. @shared_test_lib.skipUnlessHasTestFile([u'vsstest.qcow2']) class TSKFileEntryTestNTFS(shared_test_lib.BaseTestCase): """The unit test for the SleuthKit (TSK) file entry object on NTFS.""" def setUp(self): """Sets up the needed objects used throughout the test.""" self._resolver_context = context.Context() test_file = self._GetTestFilePath([u'vsstest.qcow2']) path_spec = os_path_spec.OSPathSpec(location=test_file) self._qcow_path_spec = qcow_path_spec.QCOWPathSpec(parent=path_spec) self._tsk_path_spec = tsk_path_spec.TSKPathSpec( location=u'\\', parent=self._qcow_path_spec) self._file_system = tsk_file_system.TSKFileSystem(self._resolver_context) self._file_system.Open(self._tsk_path_spec) def tearDown(self): """Cleans up the needed objects used throughout the test.""" self._file_system.Close() def testGetStat(self): """Tests the GetStat function.""" test_location = ( u'\\System Volume Information\\{3808876b-c176-4e48-b7ae-04046e6cc752}') path_spec = tsk_path_spec.TSKPathSpec( inode=38, location=test_location, parent=self._qcow_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) stat_object = file_entry.GetStat() self.assertIsNotNone(stat_object) self.assertEqual(stat_object.type, stat_object.TYPE_FILE) self.assertEqual(stat_object.size, 65536) self.assertEqual(stat_object.mode, 365) self.assertEqual(stat_object.uid, 0) self.assertEqual(stat_object.gid, 0) self.assertEqual(stat_object.atime, 1386052509) self.assertEqual(stat_object.atime_nano, 5023783) self.assertEqual(stat_object.ctime, 1386052509) self.assertEqual(stat_object.ctime_nano, 5179783) self.assertEqual(stat_object.crtime, 1386052509) self.assertEqual(stat_object.crtime_nano, 5023783) self.assertEqual(stat_object.mtime, 1386052509) self.assertEqual(stat_object.mtime_nano, 5179783) def testAttributes(self): """Test the attributes functionality.""" test_location = ( u'\\System Volume Information\\{3808876b-c176-4e48-b7ae-04046e6cc752}') path_spec = tsk_path_spec.TSKPathSpec( inode=38, location=test_location, parent=self._qcow_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.number_of_attributes, 4) def testDataStream(self): """Test the data streams functionality.""" test_location = ( u'\\System Volume Information\\{3808876b-c176-4e48-b7ae-04046e6cc752}') path_spec = tsk_path_spec.TSKPathSpec( inode=38, location=test_location, parent=self._qcow_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.number_of_data_streams, 1) data_stream_names = [] for data_stream in file_entry.data_streams: data_stream_names.append(data_stream.name) self.assertEqual(data_stream_names, [u'']) path_spec = tsk_path_spec.TSKPathSpec( inode=36, location=u'\\System Volume Information', parent=self._qcow_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.number_of_data_streams, 0) data_stream_names = [] for data_stream in file_entry.data_streams: data_stream_names.append(data_stream.name) self.assertEqual(data_stream_names, []) test_location = u'\\$Extend\\$RmMetadata\\$Repair' path_spec = tsk_path_spec.TSKPathSpec( inode=28, location=test_location, parent=self._qcow_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.number_of_data_streams, 2) data_stream_names = [] for data_stream in file_entry.data_streams: data_stream_names.append(data_stream.name) self.assertEqual(sorted(data_stream_names), sorted([u'', u'$Config'])) def testGetDataStream(self): """Test the retrieve data stream functionality.""" test_location = ( u'\\System Volume Information\\{3808876b-c176-4e48-b7ae-04046e6cc752}') path_spec = tsk_path_spec.TSKPathSpec( inode=38, location=test_location, parent=self._qcow_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) data_stream_name = u'' data_stream = file_entry.GetDataStream(data_stream_name) self.assertIsNotNone(data_stream) self.assertEqual(data_stream.name, data_stream_name) data_stream = file_entry.GetDataStream(u'bogus') self.assertIsNone(data_stream) test_location = u'\\$Extend\\$RmMetadata\\$Repair' path_spec = tsk_path_spec.TSKPathSpec( inode=28, location=test_location, parent=self._qcow_path_spec) file_entry = self._file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) data_stream_name = u'$Config' data_stream = file_entry.GetDataStream(data_stream_name) self.assertIsNotNone(data_stream) self.assertEqual(data_stream.name, data_stream_name) if __name__ == '__main__': unittest.main()
{ "content_hash": "4eefa3cfbf256850e9fdcc5db8823613", "timestamp": "", "source": "github", "line_count": 368, "max_line_length": 79, "avg_line_length": 37.27445652173913, "alnum_prop": 0.7103594080338267, "repo_name": "dc3-plaso/dfvfs", "id": "741212fdbfe0741227b8223490bcf8af59184cf9", "size": "13761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/vfs/tsk_file_entry.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "609" }, { "name": "Python", "bytes": "1397977" }, { "name": "Shell", "bytes": "1522" } ], "symlink_target": "" }
"""Pgbouncer check Collects metrics from the pgbouncer database. """ # stdlib import urlparse # 3p import psycopg2 as pg import psycopg2.extras as pgextras # project from checks import AgentCheck, CheckException class ShouldRestartException(Exception): pass class PgBouncer(AgentCheck): """Collects metrics from pgbouncer """ RATE = AgentCheck.rate GAUGE = AgentCheck.gauge DB_NAME = 'pgbouncer' SERVICE_CHECK_NAME = 'pgbouncer.can_connect' STATS_METRICS = { 'descriptors': [ ('database', 'db'), ], 'metrics': [ ('total_requests', ('pgbouncer.stats.requests_per_second', RATE)), # < 1.8 ('total_xact_count', ('pgbouncer.stats.transactions_per_second', RATE)), # >= 1.8 ('total_query_count', ('pgbouncer.stats.queries_per_second', RATE)), # >= 1.8 ('total_received', ('pgbouncer.stats.bytes_received_per_second', RATE)), ('total_sent', ('pgbouncer.stats.bytes_sent_per_second', RATE)), ('total_query_time', ('pgbouncer.stats.total_query_time', RATE)), ('total_xact_time', ('pgbouncer.stats.total_transaction_time', RATE)), # >= 1.8 ('avg_req', ('pgbouncer.stats.avg_req', GAUGE)), # < 1.8 ('avg_xact_count', ('pgbouncer.stats.avg_transaction_count', GAUGE)), # >= 1.8 ('avg_query_count', ('pgbouncer.stats.avg_query_count', GAUGE)), # >= 1.8 ('avg_recv', ('pgbouncer.stats.avg_recv', GAUGE)), ('avg_sent', ('pgbouncer.stats.avg_sent', GAUGE)), ('avg_query', ('pgbouncer.stats.avg_query', GAUGE)), # < 1.8 ('avg_xact_time', ('pgbouncer.stats.avg_transaction_time', GAUGE)), # >= 1.8 ('avg_query_time', ('pgbouncer.stats.avg_query_time', GAUGE)), # >= 1.8 ], 'query': """SHOW STATS""", } POOLS_METRICS = { 'descriptors': [ ('database', 'db'), ('user', 'user'), ], 'metrics': [ ('cl_active', ('pgbouncer.pools.cl_active', GAUGE)), ('cl_waiting', ('pgbouncer.pools.cl_waiting', GAUGE)), ('sv_active', ('pgbouncer.pools.sv_active', GAUGE)), ('sv_idle', ('pgbouncer.pools.sv_idle', GAUGE)), ('sv_used', ('pgbouncer.pools.sv_used', GAUGE)), ('sv_tested', ('pgbouncer.pools.sv_tested', GAUGE)), ('sv_login', ('pgbouncer.pools.sv_login', GAUGE)), ('maxwait', ('pgbouncer.pools.maxwait', GAUGE)), ], 'query': """SHOW POOLS""", } def __init__(self, name, init_config, agentConfig, instances=None): AgentCheck.__init__(self, name, init_config, agentConfig, instances) self.dbs = {} def _get_service_checks_tags(self, host, port, database_url, tags=None): if tags is None: tags = [] if database_url: parsed_url = urlparse.urlparse(database_url) host = parsed_url.hostname port = parsed_url.port service_checks_tags = [ "host:%s" % host, "port:%s" % port, "db:%s" % self.DB_NAME ] service_checks_tags.extend(tags) service_checks_tags = list(set(service_checks_tags)) return service_checks_tags def _collect_stats(self, db, instance_tags): """Query pgbouncer for various metrics """ metric_scope = [self.STATS_METRICS, self.POOLS_METRICS] try: with db.cursor(cursor_factory=pgextras.DictCursor) as cursor: for scope in metric_scope: descriptors = scope['descriptors'] metrics = scope['metrics'] query = scope['query'] try: self.log.debug("Running query: %s", query) cursor.execute(query) rows = cursor.fetchall() except pg.Error: self.log.exception("Not all metrics may be available") else: for row in rows: self.log.debug("Processing row: %r", row) # Skip the "pgbouncer" database if row['database'] == self.DB_NAME: continue tags = list(instance_tags) tags += ["%s:%s" % (tag, row[column]) for (column, tag) in descriptors if column in row] for (column, (name, reporter)) in metrics: if column in row: reporter(self, name, row[column], tags) if not rows: self.log.warning("No results were found for query: %s", query) except pg.Error: self.log.exception("Connection error") raise ShouldRestartException def _get_connect_kwargs(self, host, port, user, password, database_url): """ Get the params to pass to psycopg2.connect() based on passed-in vals from yaml settings file """ if database_url: return {'dsn': database_url} if not host: raise CheckException( "Please specify a PgBouncer host to connect to.") if not user: raise CheckException( "Please specify a user to connect to PgBouncer as.") if host in ('localhost', '127.0.0.1') and password == '': return { # Use ident method 'dsn': "user={} dbname={}".format(user, self.DB_NAME) } if port: return {'host': host, 'user': user, 'password': password, 'database': self.DB_NAME, 'port': port} return {'host': host, 'user': user, 'password': password, 'database': self.DB_NAME} def _get_connection(self, key, host='', port='', user='', password='', database_url='', tags=None, use_cached=True): "Get and memoize connections to instances" if key in self.dbs and use_cached: return self.dbs[key] try: connect_kwargs = self._get_connect_kwargs( host=host, port=port, user=user, password=password, database_url=database_url ) connection = pg.connect(**connect_kwargs) connection.set_isolation_level( pg.extensions.ISOLATION_LEVEL_AUTOCOMMIT) # re-raise the CheckExceptions raised by _get_connect_kwargs() except CheckException: raise except Exception: redacted_url = self._get_redacted_dsn(host, port, user, database_url) message = u'Cannot establish connection to {}'.format(redacted_url) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=self._get_service_checks_tags(host, port, database_url, tags), message=message) raise self.dbs[key] = connection return connection def _get_redacted_dsn(self, host, port, user, database_url): if not database_url: return u'pgbouncer://%s:******@%s:%s/%s' % (user, host, port, self.DB_NAME) parsed_url = urlparse.urlparse(database_url) if parsed_url.password: return database_url.replace(parsed_url.password, '******') return database_url def check(self, instance): host = instance.get('host', '') port = instance.get('port', '') user = instance.get('username', '') password = instance.get('password', '') tags = instance.get('tags', []) database_url = instance.get('database_url') if database_url: key = database_url else: key = '%s:%s' % (host, port) if tags is None: tags = [] else: tags = list(set(tags)) try: db = self._get_connection(key, host, port, user, password, tags=tags, database_url=database_url) self._collect_stats(db, tags) except ShouldRestartException: self.log.info("Resetting the connection") db = self._get_connection(key, host, port, user, password, tags=tags, use_cached=False) self._collect_stats(db, tags) redacted_dsn = self._get_redacted_dsn(host, port, user, database_url) message = u'Established connection to {}'.format(redacted_dsn) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK, tags=self._get_service_checks_tags(host, port, database_url, tags), message=message)
{ "content_hash": "9607ef8f3a9295b60a30f5587a7893e0", "timestamp": "", "source": "github", "line_count": 236, "max_line_length": 116, "avg_line_length": 38.355932203389834, "alnum_prop": 0.5172337604949182, "repo_name": "serverdensity/sd-agent-core-plugins", "id": "13dc69bcac4fce0c909c459788817c86a5beb220", "size": "9159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pgbouncer/check.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Dockerfile", "bytes": "10855" }, { "name": "Erlang", "bytes": "15429" }, { "name": "Go", "bytes": "1471" }, { "name": "PLSQL", "bytes": "27516" }, { "name": "Perl", "bytes": "5845" }, { "name": "Python", "bytes": "1734120" }, { "name": "Roff", "bytes": "488" }, { "name": "Ruby", "bytes": "167975" }, { "name": "Shell", "bytes": "28906" } ], "symlink_target": "" }
"""create report table Revision ID: d2c3abb804 Revises: 210414005a Create Date: 2014-05-25 20:05:53.851881 """ # revision identifiers, used by Alembic. revision = 'd2c3abb804' down_revision = '210414005a' from alembic import context, op import sqlalchemy as sa import bauble.db as db from bauble.model import Report def table_exists(table_name, schema): result = db.engine.execute("select 1 from information_schema.tables where table_name='{}' and table_schema = '{}';".format(table_name, schema)).first() return result is not None def upgrade(): # This migration has to run on a live database and can't be used to # generate sql statements. if context.is_offline_mode(): raise RuntimeError("This migration script cannot be run in offline mode.") # create the report table on all the existing bauble schemas stmt = "select schema_name from information_schema.schemata where schema_name like 'bbl_%%';" for result in db.engine.execute(stmt): schema = result[0] if table_exists('report', schema): continue columns = [c.copy() for c in sa.inspect(Report).columns] print("creating table: {}.report".format(schema)) op.create_table("report", *columns, schema=schema) def downgrade(): if context.is_offline_mode(): raise RuntimeError("This migration script cannot be run in offline mode.") # drop the report table on all the existing bauble schemas stmt = "select schema_name from information_schema.schemata where schema_name like 'bbl_%%';" for result in db.engine.execute(stmt): schema = result[0] if table_exists('report', schema): continue print("dropping table: {}.report".format(schema)) op.drop_table("report", schema=schema)
{ "content_hash": "03362cdfabb182f23a251c60e209d653", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 155, "avg_line_length": 33.370370370370374, "alnum_prop": 0.6842397336293008, "repo_name": "Bauble/bauble.api", "id": "36a2af795fb529b3b449581668e5a4a5c77229ea", "size": "1802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alembic/versions/d2c3abb804_create_report_table.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Emacs Lisp", "bytes": "210" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "300401" }, { "name": "Shell", "bytes": "877" } ], "symlink_target": "" }
import sys import os import tempfile ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__))) CALLBACK_FILE = os.path.join(ROOT, 'callback_notes') CACHED_METHOD_FILE = os.path.join(ROOT, 'cached_method_notes') if not os.path.exists(CACHED_METHOD_FILE): open(CACHED_METHOD_FILE,'w+') def callback_for_method(a, b, c): assert a == 1 assert b == 2 assert c == 3 if os.path.exists(CALLBACK_FILE): with open(CALLBACK_FILE, 'a') as f: f.write('.') else: with open(CALLBACK_FILE, 'w+') as f: f.write('.') return CALLBACK_FILE def method_with_callback(callback, something=None): with open(CACHED_METHOD_FILE, 'a') as f: f.write(".") return callback(1, 2, 3) def method_calling_method(): return method_with_callback(callback_for_method)
{ "content_hash": "9bcd202ee2e040840d8c76a2bef7b264", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 63, "avg_line_length": 25.96875, "alnum_prop": 0.6329723225030084, "repo_name": "buzzfeed/caliendo", "id": "35f48979b7b2380624386483ab8900df134e7867", "size": "831", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/api/callback.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "131139" }, { "name": "Shell", "bytes": "146" } ], "symlink_target": "" }
import pbr.version __version__ = pbr.version.VersionInfo( 'backblast').version_string()
{ "content_hash": "c6a2d6674fed5e1816c3f3179a899a3e", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 38, "avg_line_length": 18.8, "alnum_prop": 0.7021276595744681, "repo_name": "kickstandproject/backblast", "id": "2d2df4ada0b1a2680796bcb1e5f4a9b88f157b18", "size": "665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backblast/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "15456" } ], "symlink_target": "" }
import socket def send_data(sock,data): sock.sendall(data) def receive_data(sock,size = 4096): data = bytes() while size: recv = sock.recv(size) if not recv: raise ConnectionError() data += recv size -= len(recv) return data def nDigit(s,size): s = str(s) if(len(s)<size): s = '0'*(size-len(s))+s return s def send_bytes(sock,data): size = nDigit(len(data),5).encode('utf-8') send_data(sock,size+data) def receive_bytes(sock): size = receive_data(sock,5).decode('utf-8') data = receive_data(sock,int(size)) return data def create_listening_socket(host,port,size): listening_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) listening_socket.bind((host,port)) listening_socket.listen(100) return listening_socket def receive_message(sock): size = receive_data(sock,5).decode('utf-8') msg = receive_data(sock,int(size)).decode('utf-8') return msg def send_message(sock,message): message = message.encode('utf-8') size = nDigit(len(message),5).encode('utf-8') message = size+message send_data(sock,message)
{ "content_hash": "3b3e28b77960f1a9904d60e8f089eee6", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 68, "avg_line_length": 22.956521739130434, "alnum_prop": 0.6998106060606061, "repo_name": "paramsingh/lazycoin", "id": "9721823375d9b48e9b55e928d9fc15df05688fc7", "size": "1056", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "funcs.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "776" }, { "name": "JavaScript", "bytes": "5677" }, { "name": "Python", "bytes": "15782" } ], "symlink_target": "" }
from datetime import timedelta import numpy as np import pytest from pandas.core.dtypes.common import is_integer from pandas import ( DateOffset, Interval, IntervalIndex, Timedelta, Timestamp, date_range, interval_range, timedelta_range) import pandas.util.testing as tm from pandas.tseries.offsets import Day @pytest.fixture(scope='class', params=[None, 'foo']) def name(request): return request.param class TestIntervalRange: @pytest.mark.parametrize('freq, periods', [ (1, 100), (2.5, 40), (5, 20), (25, 4)]) def test_constructor_numeric(self, closed, name, freq, periods): start, end = 0, 100 breaks = np.arange(101, step=freq) expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed) # defined from start/end/freq result = interval_range( start=start, end=end, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # defined from start/periods/freq result = interval_range( start=start, periods=periods, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # defined from end/periods/freq result = interval_range( end=end, periods=periods, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # GH 20976: linspace behavior defined from start/end/periods result = interval_range( start=start, end=end, periods=periods, name=name, closed=closed) tm.assert_index_equal(result, expected) @pytest.mark.parametrize('tz', [None, 'US/Eastern']) @pytest.mark.parametrize('freq, periods', [ ('D', 364), ('2D', 182), ('22D18H', 16), ('M', 11)]) def test_constructor_timestamp(self, closed, name, freq, periods, tz): start, end = Timestamp('20180101', tz=tz), Timestamp('20181231', tz=tz) breaks = date_range(start=start, end=end, freq=freq) expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed) # defined from start/end/freq result = interval_range( start=start, end=end, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # defined from start/periods/freq result = interval_range( start=start, periods=periods, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # defined from end/periods/freq result = interval_range( end=end, periods=periods, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # GH 20976: linspace behavior defined from start/end/periods if not breaks.freq.isAnchored() and tz is None: # matches expected only for non-anchored offsets and tz naive # (anchored/DST transitions cause unequal spacing in expected) result = interval_range(start=start, end=end, periods=periods, name=name, closed=closed) tm.assert_index_equal(result, expected) @pytest.mark.parametrize('freq, periods', [ ('D', 100), ('2D12H', 40), ('5D', 20), ('25D', 4)]) def test_constructor_timedelta(self, closed, name, freq, periods): start, end = Timedelta('0 days'), Timedelta('100 days') breaks = timedelta_range(start=start, end=end, freq=freq) expected = IntervalIndex.from_breaks(breaks, name=name, closed=closed) # defined from start/end/freq result = interval_range( start=start, end=end, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # defined from start/periods/freq result = interval_range( start=start, periods=periods, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # defined from end/periods/freq result = interval_range( end=end, periods=periods, freq=freq, name=name, closed=closed) tm.assert_index_equal(result, expected) # GH 20976: linspace behavior defined from start/end/periods result = interval_range( start=start, end=end, periods=periods, name=name, closed=closed) tm.assert_index_equal(result, expected) @pytest.mark.parametrize('start, end, freq, expected_endpoint', [ (0, 10, 3, 9), (0, 10, 1.5, 9), (0.5, 10, 3, 9.5), (Timedelta('0D'), Timedelta('10D'), '2D4H', Timedelta('8D16H')), (Timestamp('2018-01-01'), Timestamp('2018-02-09'), 'MS', Timestamp('2018-02-01')), (Timestamp('2018-01-01', tz='US/Eastern'), Timestamp('2018-01-20', tz='US/Eastern'), '5D12H', Timestamp('2018-01-17 12:00:00', tz='US/Eastern'))]) def test_early_truncation(self, start, end, freq, expected_endpoint): # index truncates early if freq causes end to be skipped result = interval_range(start=start, end=end, freq=freq) result_endpoint = result.right[-1] assert result_endpoint == expected_endpoint @pytest.mark.parametrize('start, end, freq', [ (0.5, None, None), (None, 4.5, None), (0.5, None, 1.5), (None, 6.5, 1.5)]) def test_no_invalid_float_truncation(self, start, end, freq): # GH 21161 if freq is None: breaks = [0.5, 1.5, 2.5, 3.5, 4.5] else: breaks = [0.5, 2.0, 3.5, 5.0, 6.5] expected = IntervalIndex.from_breaks(breaks) result = interval_range(start=start, end=end, periods=4, freq=freq) tm.assert_index_equal(result, expected) @pytest.mark.parametrize('start, mid, end', [ (Timestamp('2018-03-10', tz='US/Eastern'), Timestamp('2018-03-10 23:30:00', tz='US/Eastern'), Timestamp('2018-03-12', tz='US/Eastern')), (Timestamp('2018-11-03', tz='US/Eastern'), Timestamp('2018-11-04 00:30:00', tz='US/Eastern'), Timestamp('2018-11-05', tz='US/Eastern'))]) def test_linspace_dst_transition(self, start, mid, end): # GH 20976: linspace behavior defined from start/end/periods # accounts for the hour gained/lost during DST transition result = interval_range(start=start, end=end, periods=2) expected = IntervalIndex.from_breaks([start, mid, end]) tm.assert_index_equal(result, expected) @pytest.mark.parametrize('freq', [2, 2.0]) @pytest.mark.parametrize('end', [10, 10.0]) @pytest.mark.parametrize('start', [0, 0.0]) def test_float_subtype(self, start, end, freq): # Has float subtype if any of start/end/freq are float, even if all # resulting endpoints can safely be upcast to integers # defined from start/end/freq index = interval_range(start=start, end=end, freq=freq) result = index.dtype.subtype expected = 'int64' if is_integer(start + end + freq) else 'float64' assert result == expected # defined from start/periods/freq index = interval_range(start=start, periods=5, freq=freq) result = index.dtype.subtype expected = 'int64' if is_integer(start + freq) else 'float64' assert result == expected # defined from end/periods/freq index = interval_range(end=end, periods=5, freq=freq) result = index.dtype.subtype expected = 'int64' if is_integer(end + freq) else 'float64' assert result == expected # GH 20976: linspace behavior defined from start/end/periods index = interval_range(start=start, end=end, periods=5) result = index.dtype.subtype expected = 'int64' if is_integer(start + end) else 'float64' assert result == expected def test_constructor_coverage(self): # float value for periods expected = interval_range(start=0, periods=10) result = interval_range(start=0, periods=10.5) tm.assert_index_equal(result, expected) # equivalent timestamp-like start/end start, end = Timestamp('2017-01-01'), Timestamp('2017-01-15') expected = interval_range(start=start, end=end) result = interval_range(start=start.to_pydatetime(), end=end.to_pydatetime()) tm.assert_index_equal(result, expected) result = interval_range(start=start.asm8, end=end.asm8) tm.assert_index_equal(result, expected) # equivalent freq with timestamp equiv_freq = ['D', Day(), Timedelta(days=1), timedelta(days=1), DateOffset(days=1)] for freq in equiv_freq: result = interval_range(start=start, end=end, freq=freq) tm.assert_index_equal(result, expected) # equivalent timedelta-like start/end start, end = Timedelta(days=1), Timedelta(days=10) expected = interval_range(start=start, end=end) result = interval_range(start=start.to_pytimedelta(), end=end.to_pytimedelta()) tm.assert_index_equal(result, expected) result = interval_range(start=start.asm8, end=end.asm8) tm.assert_index_equal(result, expected) # equivalent freq with timedelta equiv_freq = ['D', Day(), Timedelta(days=1), timedelta(days=1)] for freq in equiv_freq: result = interval_range(start=start, end=end, freq=freq) tm.assert_index_equal(result, expected) def test_errors(self): # not enough params msg = ('Of the four parameters: start, end, periods, and freq, ' 'exactly three must be specified') with pytest.raises(ValueError, match=msg): interval_range(start=0) with pytest.raises(ValueError, match=msg): interval_range(end=5) with pytest.raises(ValueError, match=msg): interval_range(periods=2) with pytest.raises(ValueError, match=msg): interval_range() # too many params with pytest.raises(ValueError, match=msg): interval_range(start=0, end=5, periods=6, freq=1.5) # mixed units msg = 'start, end, freq need to be type compatible' with pytest.raises(TypeError, match=msg): interval_range(start=0, end=Timestamp('20130101'), freq=2) with pytest.raises(TypeError, match=msg): interval_range(start=0, end=Timedelta('1 day'), freq=2) with pytest.raises(TypeError, match=msg): interval_range(start=0, end=10, freq='D') with pytest.raises(TypeError, match=msg): interval_range(start=Timestamp('20130101'), end=10, freq='D') with pytest.raises(TypeError, match=msg): interval_range(start=Timestamp('20130101'), end=Timedelta('1 day'), freq='D') with pytest.raises(TypeError, match=msg): interval_range(start=Timestamp('20130101'), end=Timestamp('20130110'), freq=2) with pytest.raises(TypeError, match=msg): interval_range(start=Timedelta('1 day'), end=10, freq='D') with pytest.raises(TypeError, match=msg): interval_range(start=Timedelta('1 day'), end=Timestamp('20130110'), freq='D') with pytest.raises(TypeError, match=msg): interval_range(start=Timedelta('1 day'), end=Timedelta('10 days'), freq=2) # invalid periods msg = 'periods must be a number, got foo' with pytest.raises(TypeError, match=msg): interval_range(start=0, periods='foo') # invalid start msg = 'start must be numeric or datetime-like, got foo' with pytest.raises(ValueError, match=msg): interval_range(start='foo', periods=10) # invalid end msg = r'end must be numeric or datetime-like, got \(0, 1\]' with pytest.raises(ValueError, match=msg): interval_range(end=Interval(0, 1), periods=10) # invalid freq for datetime-like msg = 'freq must be numeric or convertible to DateOffset, got foo' with pytest.raises(ValueError, match=msg): interval_range(start=0, end=10, freq='foo') with pytest.raises(ValueError, match=msg): interval_range(start=Timestamp('20130101'), periods=10, freq='foo') with pytest.raises(ValueError, match=msg): interval_range(end=Timedelta('1 day'), periods=10, freq='foo') # mixed tz start = Timestamp('2017-01-01', tz='US/Eastern') end = Timestamp('2017-01-07', tz='US/Pacific') msg = 'Start and end cannot both be tz-aware with different timezones' with pytest.raises(TypeError, match=msg): interval_range(start=start, end=end)
{ "content_hash": "c22dcd04c64df88807ae39643fe0cfed", "timestamp": "", "source": "github", "line_count": 314, "max_line_length": 79, "avg_line_length": 40.97133757961783, "alnum_prop": 0.6125145744267392, "repo_name": "cbertinato/pandas", "id": "572fe5fbad1005b8ba7eb67a20f64dd375248d9a", "size": "12865", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pandas/tests/indexes/interval/test_interval_range.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "541" }, { "name": "C", "bytes": "394466" }, { "name": "C++", "bytes": "17248" }, { "name": "HTML", "bytes": "606963" }, { "name": "Makefile", "bytes": "529" }, { "name": "Python", "bytes": "15010333" }, { "name": "Shell", "bytes": "27209" }, { "name": "Smarty", "bytes": "2040" } ], "symlink_target": "" }
import argparse import os import re import shutil import subprocess import sys import tarfile from lib.config import LIBCHROMIUMCONTENT_COMMIT, BASE_URL, TARGET_PLATFORM, \ DIST_ARCH from lib.util import scoped_cwd, rm_rf, get_atom_shell_version, make_zip, \ safe_mkdir, execute, get_chromedriver_version ATOM_SHELL_VERSION = get_atom_shell_version() SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) DIST_DIR = os.path.join(SOURCE_ROOT, 'dist') OUT_DIR = os.path.join(SOURCE_ROOT, 'out', 'Release') NODE_DIR = os.path.join(SOURCE_ROOT, 'vendor', 'node') DIST_HEADERS_NAME = 'node-{0}'.format(ATOM_SHELL_VERSION) DIST_HEADERS_DIR = os.path.join(DIST_DIR, DIST_HEADERS_NAME) SYMBOL_NAME = { 'darwin': 'libchromiumcontent.dylib.dSYM', 'linux': 'libchromiumcontent.so.dbg', 'win32': 'chromiumcontent.dll.pdb', }[TARGET_PLATFORM] TARGET_BINARIES = { 'darwin': [ ], 'win32': [ 'atom.exe', 'chromiumcontent.dll', 'content_shell.pak', 'd3dcompiler_43.dll', 'ffmpegsumo.dll', 'icudtl.dat', 'libEGL.dll', 'libGLESv2.dll', 'msvcp120.dll', 'msvcr120.dll', 'ui_resources_200_percent.pak', 'vccorlib120.dll', 'webkit_resources_200_percent.pak', 'xinput1_3.dll', ], 'linux': [ 'atom', 'content_shell.pak', 'icudtl.dat', 'libchromiumcontent.so', 'libffmpegsumo.so', ], } TARGET_DIRECTORIES = { 'darwin': [ 'Atom.app', ], 'win32': [ 'resources', 'locales', ], 'linux': [ 'resources', 'locales', ], } SYSTEM_LIBRARIES = [ 'libudev.so', 'libgcrypt.so', 'libnotify.so', ] HEADERS_SUFFIX = [ '.h', '.gypi', ] HEADERS_DIRS = [ 'src', 'deps/http_parser', 'deps/zlib', 'deps/uv', 'deps/npm', 'deps/mdb_v8', ] HEADERS_FILES = [ 'common.gypi', 'config.gypi', ] def main(): rm_rf(DIST_DIR) os.makedirs(DIST_DIR) args = parse_args() force_build() download_libchromiumcontent_symbols(args.url) create_symbols() copy_binaries() copy_chromedriver() copy_headers() copy_license() if TARGET_PLATFORM == 'linux': copy_system_libraries() create_version() create_dist_zip() create_chromedriver_zip() create_symbols_zip() create_header_tarball() def parse_args(): parser = argparse.ArgumentParser(description='Create distributions') parser.add_argument('-u', '--url', help='The base URL from which to download ' 'libchromiumcontent (i.e., the URL you passed to ' 'libchromiumcontent\'s script/upload script', default=BASE_URL, required=False) return parser.parse_args() def force_build(): build = os.path.join(SOURCE_ROOT, 'script', 'build.py') execute([sys.executable, build, '-c', 'Release']) def copy_binaries(): for binary in TARGET_BINARIES[TARGET_PLATFORM]: shutil.copy2(os.path.join(OUT_DIR, binary), DIST_DIR) for directory in TARGET_DIRECTORIES[TARGET_PLATFORM]: shutil.copytree(os.path.join(OUT_DIR, directory), os.path.join(DIST_DIR, directory), symlinks=True) def copy_chromedriver(): build = os.path.join(SOURCE_ROOT, 'script', 'build.py') execute([sys.executable, build, '-c', 'Release', '-t', 'copy_chromedriver']) binary = 'chromedriver' if TARGET_PLATFORM == 'win32': binary += '.exe' shutil.copy2(os.path.join(OUT_DIR, binary), DIST_DIR) def copy_headers(): os.mkdir(DIST_HEADERS_DIR) # Copy standard node headers from node. repository. for include_path in HEADERS_DIRS: abs_path = os.path.join(NODE_DIR, include_path) for dirpath, _, filenames in os.walk(abs_path): for filename in filenames: extension = os.path.splitext(filename)[1] if extension not in HEADERS_SUFFIX: continue copy_source_file(os.path.join(dirpath, filename)) for other_file in HEADERS_FILES: copy_source_file(source = os.path.join(NODE_DIR, other_file)) # Copy V8 headers from chromium's repository. src = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor', 'download', 'libchromiumcontent', 'src') for dirpath, _, filenames in os.walk(os.path.join(src, 'v8')): for filename in filenames: extension = os.path.splitext(filename)[1] if extension not in HEADERS_SUFFIX: continue copy_source_file(source=os.path.join(dirpath, filename), start=src, destination=os.path.join(DIST_HEADERS_DIR, 'deps')) def copy_license(): shutil.copy2(os.path.join(SOURCE_ROOT, 'LICENSE'), DIST_DIR) def copy_system_libraries(): ldd = execute(['ldd', os.path.join(OUT_DIR, 'atom')]) lib_re = re.compile('\t(.*) => (.+) \(.*\)$') for line in ldd.splitlines(): m = lib_re.match(line) if not m: continue for i, library in enumerate(SYSTEM_LIBRARIES): real_library = m.group(1) if real_library.startswith(library): shutil.copyfile(m.group(2), os.path.join(DIST_DIR, real_library)) SYSTEM_LIBRARIES[i] = real_library def create_version(): version_path = os.path.join(SOURCE_ROOT, 'dist', 'version') with open(version_path, 'w') as version_file: version_file.write(ATOM_SHELL_VERSION) def download_libchromiumcontent_symbols(url): brightray_dir = os.path.join(SOURCE_ROOT, 'vendor', 'brightray', 'vendor') target_dir = os.path.join(brightray_dir, 'download', 'libchromiumcontent') symbols_path = os.path.join(target_dir, 'Release', SYMBOL_NAME) if os.path.exists(symbols_path): return download = os.path.join(brightray_dir, 'libchromiumcontent', 'script', 'download') subprocess.check_call([sys.executable, download, '-f', '-s', '-c', LIBCHROMIUMCONTENT_COMMIT, url, target_dir]) def create_symbols(): directory = 'Atom-Shell.breakpad.syms' rm_rf(os.path.join(OUT_DIR, directory)) build = os.path.join(SOURCE_ROOT, 'script', 'build.py') subprocess.check_output([sys.executable, build, '-c', 'Release', '-t', 'atom_dump_symbols']) shutil.copytree(os.path.join(OUT_DIR, directory), os.path.join(DIST_DIR, directory), symlinks=True) def create_dist_zip(): dist_name = 'atom-shell-{0}-{1}-{2}.zip'.format(ATOM_SHELL_VERSION, TARGET_PLATFORM, DIST_ARCH) zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name) with scoped_cwd(DIST_DIR): files = TARGET_BINARIES[TARGET_PLATFORM] + ['LICENSE', 'version'] if TARGET_PLATFORM == 'linux': files += SYSTEM_LIBRARIES dirs = TARGET_DIRECTORIES[TARGET_PLATFORM] make_zip(zip_file, files, dirs) def create_chromedriver_zip(): dist_name = 'chromedriver-{0}-{1}-{2}.zip'.format(get_chromedriver_version(), TARGET_PLATFORM, DIST_ARCH) zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name) with scoped_cwd(DIST_DIR): files = ['LICENSE'] if TARGET_PLATFORM == 'win32': files += ['chromedriver.exe'] else: files += ['chromedriver'] make_zip(zip_file, files, []) def create_symbols_zip(): dist_name = 'atom-shell-{0}-{1}-{2}-symbols.zip'.format(ATOM_SHELL_VERSION, TARGET_PLATFORM, DIST_ARCH) zip_file = os.path.join(SOURCE_ROOT, 'dist', dist_name) with scoped_cwd(DIST_DIR): files = ['LICENSE', 'version'] dirs = ['Atom-Shell.breakpad.syms'] make_zip(zip_file, files, dirs) def create_header_tarball(): with scoped_cwd(DIST_DIR): tarball = tarfile.open(name=DIST_HEADERS_DIR + '.tar.gz', mode='w:gz') tarball.add(DIST_HEADERS_NAME) tarball.close() def copy_source_file(source, start=NODE_DIR, destination=DIST_HEADERS_DIR): relative = os.path.relpath(source, start=start) final_destination = os.path.join(destination, relative) safe_mkdir(os.path.dirname(final_destination)) shutil.copy2(source, final_destination) if __name__ == '__main__': sys.exit(main())
{ "content_hash": "7b96de0e7b5af9a1110bedbe4d16fc71", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 79, "avg_line_length": 28.789473684210527, "alnum_prop": 0.6204753199268739, "repo_name": "rprichard/electron", "id": "e623b088c6bd02a6b6b61e21edf9a5caebd1e5e4", "size": "8228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "script/create-dist.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "3255" }, { "name": "C++", "bytes": "950445" }, { "name": "CoffeeScript", "bytes": "136976" }, { "name": "JavaScript", "bytes": "11390" }, { "name": "Objective-C", "bytes": "4716" }, { "name": "Objective-C++", "bytes": "106906" }, { "name": "Python", "bytes": "79992" } ], "symlink_target": "" }
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponseNotAllowed from django.views.generic import simple from vt_manager_kvm.controller.users.forms import * from django.contrib.auth.forms import PasswordChangeForm from vt_manager_kvm.controller.drivers.VTDriver import VTDriver def index(request): if request.user.is_authenticated(): return HttpResponseRedirect('/dashboard') else: return HttpResponseRedirect('/accounts/login') @login_required def change_profile(request): ''' The view function to change profile information for a user or admin. ''' if request.method == "GET": user_form = UserForm(instance=request.user) pass_change_form = PasswordChangeForm(request.user) elif request.method == "POST": user_form = UserForm(request.POST, instance=request.user) valid1 = user_form.is_valid() if (request.POST['old_password']!=""): pass_change_form = PasswordChangeForm(request.user, request.POST) valid2 = pass_change_form.is_valid() else: pass_change_form = PasswordChangeForm(request.user) valid2 = True if (valid1 and valid2): user_form.save() if (request.POST['old_password']!=""): pass_change_form.save() return HttpResponseRedirect("/dashboard") else: return HttpResponseNotAllowed("GET", "POST") if (request.user.is_superuser): return simple.direct_to_template(request, template = 'users/change_profile_admin.html', extra_context = { 'user_form':user_form, 'pass_form':pass_change_form, } ) else: return HttpResponseRedirect('/accounts/login') # return simple.direct_to_template(request, # template = 'users/change_profile_user.html', # extra_context = { # 'user_form':user_form, # 'pass_form':pass_change_form, # } # ) @login_required def dashboard(request): ''' The dashboard view function ''' if (not request.user.is_superuser): return HttpResponseRedirect('/accounts/login') else: #Admin servers = VTDriver.getAllServers() return simple.direct_to_template(request, template = 'dashboard_admin.html', extra_context = { 'user': request.user, 'servers' : servers, }, )
{ "content_hash": "e06bb2143fc9c7aecef7c07a335c4f24", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 69, "avg_line_length": 27.857142857142858, "alnum_prop": 0.6858974358974359, "repo_name": "ict-felix/stack", "id": "1b9c765ae1ac6f5fd4783125796e1b5409734087", "size": "2340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vt_manager_kvm/src/python/vt_manager_kvm/controller/users/urlHandlers.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "337811" }, { "name": "Elixir", "bytes": "17243" }, { "name": "Emacs Lisp", "bytes": "1098" }, { "name": "Groff", "bytes": "1735" }, { "name": "HTML", "bytes": "660363" }, { "name": "Java", "bytes": "18362" }, { "name": "JavaScript", "bytes": "838960" }, { "name": "Makefile", "bytes": "11581" }, { "name": "Perl", "bytes": "5416" }, { "name": "Python", "bytes": "8073455" }, { "name": "Shell", "bytes": "259720" } ], "symlink_target": "" }
import sys import os import generic_run if __name__ == "__main__": if (len(sys.argv) < 8): print("This script is not intended for standalone use - integrate with meld instead.") sys.exit(1) v, r = generic_run.run_cmd_simple(["meld", sys.argv[2], sys.argv[5]]) if not v: print(r) sys.exit(1)
{ "content_hash": "2dec6f67c3e247a5f2740bbf48f7ad6a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 94, "avg_line_length": 25.923076923076923, "alnum_prop": 0.5816023738872403, "repo_name": "mvendra/mvtools", "id": "1f68130bc9efc09bc8ed817ab8f6eef8b93fdbaa", "size": "361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "git/meldiff.py", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "10468" }, { "name": "Python", "bytes": "2654549" }, { "name": "Shell", "bytes": "27094" } ], "symlink_target": "" }
import datetime from .base import Database class InsertVar: """ A late-binding cursor variable that can be passed to Cursor.execute as a parameter, in order to receive the id of the row created by an insert statement. """ types = { 'AutoField': int, 'BigAutoField': int, 'SmallAutoField': int, 'IntegerField': int, 'BigIntegerField': int, 'SmallIntegerField': int, 'PositiveSmallIntegerField': int, 'PositiveIntegerField': int, 'FloatField': Database.NATIVE_FLOAT, 'DateTimeField': Database.TIMESTAMP, 'DateField': Database.Date, 'DecimalField': Database.NUMBER, } def __init__(self, field): internal_type = getattr(field, 'target_field', field).get_internal_type() self.db_type = self.types.get(internal_type, str) def bind_parameter(self, cursor): param = cursor.cursor.var(self.db_type) cursor._insert_id_var = param return param class Oracle_datetime(datetime.datetime): """ A datetime object, with an additional class attribute to tell cx_Oracle to save the microseconds too. """ input_size = Database.TIMESTAMP @classmethod def from_datetime(cls, dt): return Oracle_datetime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, ) class BulkInsertMapper: BLOB = 'TO_BLOB(%s)' CLOB = 'TO_CLOB(%s)' DATE = 'TO_DATE(%s)' INTERVAL = 'CAST(%s as INTERVAL DAY(9) TO SECOND(6))' NUMBER = 'TO_NUMBER(%s)' TIMESTAMP = 'TO_TIMESTAMP(%s)' types = { 'BigIntegerField': NUMBER, 'BinaryField': BLOB, 'BooleanField': NUMBER, 'DateField': DATE, 'DateTimeField': TIMESTAMP, 'DecimalField': NUMBER, 'DurationField': INTERVAL, 'FloatField': NUMBER, 'IntegerField': NUMBER, 'NullBooleanField': NUMBER, 'PositiveIntegerField': NUMBER, 'PositiveSmallIntegerField': NUMBER, 'SmallIntegerField': NUMBER, 'TextField': CLOB, 'TimeField': TIMESTAMP, }
{ "content_hash": "b0242c4fac7625e089e4be53708d072d", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 81, "avg_line_length": 28.355263157894736, "alnum_prop": 0.6046403712296984, "repo_name": "mdworks2016/work_development", "id": "4617886d832761e5ec92ddd5b0d8282097548dab", "size": "2155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Python/20_Third_Certification/venv/lib/python3.7/site-packages/django/db/backends/oracle/utils.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "142" }, { "name": "Kotlin", "bytes": "68744" }, { "name": "Python", "bytes": "1080" } ], "symlink_target": "" }
"""All minimum dependencies for scikit-learn.""" from collections import defaultdict import platform import argparse # scipy and cython should by in sync with pyproject.toml # NumPy version should match oldest-supported-numpy for the minimum supported # Python version. # see: https://github.com/scipy/oldest-supported-numpy/blob/main/setup.cfg if platform.python_implementation() == "PyPy": NUMPY_MIN_VERSION = "1.19.2" else: NUMPY_MIN_VERSION = "1.17.3" SCIPY_MIN_VERSION = "1.3.2" JOBLIB_MIN_VERSION = "1.1.1" THREADPOOLCTL_MIN_VERSION = "2.0.0" PYTEST_MIN_VERSION = "5.3.1" CYTHON_MIN_VERSION = "0.29.24" # 'build' and 'install' is included to have structured metadata for CI. # It will NOT be included in setup's extras_require # The values are (version_spec, comma separated tags) dependent_packages = { "numpy": (NUMPY_MIN_VERSION, "build, install"), "scipy": (SCIPY_MIN_VERSION, "build, install"), "joblib": (JOBLIB_MIN_VERSION, "install"), "threadpoolctl": (THREADPOOLCTL_MIN_VERSION, "install"), "cython": (CYTHON_MIN_VERSION, "build"), "matplotlib": ("3.1.3", "benchmark, docs, examples, tests"), "scikit-image": ("0.16.2", "docs, examples, tests"), "pandas": ("1.0.5", "benchmark, docs, examples, tests"), "seaborn": ("0.9.0", "docs, examples"), "memory_profiler": ("0.57.0", "benchmark, docs"), "pytest": (PYTEST_MIN_VERSION, "tests"), "pytest-cov": ("2.9.0", "tests"), "flake8": ("3.8.2", "tests"), "black": ("22.3.0", "tests"), "mypy": ("0.961", "tests"), "pyamg": ("4.0.0", "tests"), "sphinx": ("4.0.1", "docs"), "sphinx-gallery": ("0.7.0", "docs"), "numpydoc": ("1.2.0", "docs, tests"), "Pillow": ("7.1.2", "docs"), "pooch": ("1.6.0", "docs, examples, tests"), "sphinx-prompt": ("1.3.0", "docs"), "sphinxext-opengraph": ("0.4.2", "docs"), "plotly": ("5.10.0", "docs, examples"), # XXX: Pin conda-lock to the latest released version (needs manual update # from time to time) "conda-lock": ("1.2.1", "maintenance"), } # create inverse mapping for setuptools tag_to_packages: dict = defaultdict(list) for package, (min_version, extras) in dependent_packages.items(): for extra in extras.split(", "): tag_to_packages[extra].append("{}>={}".format(package, min_version)) # Used by CI to get the min dependencies if __name__ == "__main__": parser = argparse.ArgumentParser(description="Get min dependencies for a package") parser.add_argument("package", choices=dependent_packages) args = parser.parse_args() min_version = dependent_packages[args.package][0] print(min_version)
{ "content_hash": "f89f40f13f628ce5df5a8226c037ae40", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 86, "avg_line_length": 36.77777777777778, "alnum_prop": 0.6393504531722054, "repo_name": "scikit-learn/scikit-learn", "id": "6d4183b29eec538c9b8b00a8fbcee793d90d63cc", "size": "2648", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sklearn/_min_dependencies.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "42335" }, { "name": "C++", "bytes": "147316" }, { "name": "Cython", "bytes": "669600" }, { "name": "Makefile", "bytes": "1644" }, { "name": "Python", "bytes": "10545498" }, { "name": "Shell", "bytes": "41551" } ], "symlink_target": "" }
import os from io import BytesIO import glob import math import random import sys import PIL import numpy as np from numpy import argmax, array from sklearn.model_selection import train_test_split from keras.callbacks import Callback, ModelCheckpoint, TensorBoard from keras.models import Model from keras.utils import np_utils from keras.layers import merge, Conv2D, MaxPooling2D, Input, Dense, Dropout, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras import backend as K from captcha.image import ImageCaptcha,WheezyCaptcha # os.environ IS_TH = K.backend() == 'theano' # image_dim_ordering: string, either "tf" or "th". It specifies which dimension # ordering convention Keras will follow. (keras.backend.image_dim_ordering() returns it.) # For 2D data (e.g. image), "tf" assumes (rows, cols, channels) # while "th" assumes (channels, rows, cols). # For 3D data, "tf" assumes (conv_dim1, conv_dim2, conv_dim3, channels) # while "th" assumes (channels, conv_dim1, conv_dim2, conv_dim3). # 20 train samples MBP # 23s th one # 274s th mul(4) # 11s tf one # 44s tf mul(4) # force IS_TH = True # 32s tf one # hang tf mul(4) USE_PLOT = True try: from keras.utils.visualize_util import plot as keras_plot except: USE_PLOT = False USE_PLOT = False plot = keras_plot if USE_PLOT else (lambda model, file_name: model) FONTS = glob.glob('/usr/share/fonts/truetype/dejavu/*.ttf') if True: # development SAMPLE_SIZE = 120 TEST_SAMPLE_RATE = 0.3 NB_BATCH = 10 NB_EPOCH = 10 BATCH_SIZE = 128 else: # production SAMPLE_SIZE = 10000 TEST_SAMPLE_RATE = 0.3 NB_BATCH = 100 NB_EPOCH = 10 BATCH_SIZE = 128 # model.fit_generator( # gen(train_sample_size / NB_BATCH), # steps_per_epoch=NB_BATCH, # epochs=NB_EPOCH, # callbacks=callbacks # ) SHOW_SAMPLE_SIZE = 5 INVALID_DIGIT = -1 DIGIT_COUNT = 4 DIGIT_FORMAT_STR = "%%0%dd" % DIGIT_COUNT CLASS_COUNT = 10 RGB_COLOR_COUNT = 3 POOL_SIZE = (2, 2) # standard width for the whole captcha image IMAGE_STD_WIDTH = 200 # standard height for the whole captcha image IMAGE_STD_HEIGHT = 200 CONV1_NB_FILTERS = IMAGE_STD_HEIGHT / 2 + 2 CONV2_NB_FILTERS = IMAGE_STD_HEIGHT + 2 * 2 OUT_PUT_NAME_FORMAT = 'out_%02d' def generate_image_sets_for_single_digit(nb_sample=SAMPLE_SIZE, single_digit_index=0, fonts=None): captcha = ImageCaptcha(fonts=fonts) if fonts else ImageCaptcha() # print DIGIT_FORMAT_STR labels = [] images = [] for i in range(0, nb_sample): digits = 0 last_digit = INVALID_DIGIT for j in range(0, DIGIT_COUNT): digit = last_digit while digit == last_digit: digit = random.randint(0, 9) last_digit = digit digits = digits * 10 + digit digits_as_str = DIGIT_FORMAT_STR % digits labels.append(digits_as_str) images.append(captcha.generate_image(digits_as_str)) digit_labels = list() for digit_index in range(0, DIGIT_COUNT): digit_labels.append(np.empty(nb_sample, dtype="int8")) shape = (nb_sample, RGB_COLOR_COUNT, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH) if IS_TH else (nb_sample, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH, RGB_COLOR_COUNT) digit_image_data = np.empty(shape, dtype="float32") for index in range(0, nb_sample): img = images[index].resize((IMAGE_STD_WIDTH, IMAGE_STD_HEIGHT), PIL.Image.LANCZOS) # if index < SHOW_SAMPLE_SIZE: # display.display(img) img_arr = np.asarray(img, dtype="float32") / 255.0 if IS_TH: digit_image_data[index, :, :, :] = np.rollaxis(img_arr, 2) else: digit_image_data[index, :, :, :] = img_arr for digit_index in range(0, DIGIT_COUNT): digit_labels[digit_index][index] = labels[index][digit_index] x = digit_image_data y = np_utils.to_categorical(digit_labels[single_digit_index], CLASS_COUNT) return x, y # X, Y_all = digit_image_data, digit_labels[single_digit_index] # x_train, x_test, y_train_as_num, y_test_as_num = train_test_split(X, Y_all, test_size=0.1, random_state=0) # y_train = np_utils.to_categorical(y_train_as_num, CLASS_COUNT) # y_test = y_test_as_num # return (x_train, y_train, x_test, y_test) def generate_image_sets_for_multi_digits(nb_sample=SAMPLE_SIZE, fonts=None): captcha = ImageCaptcha(fonts=fonts) if fonts else ImageCaptcha() # print DIGIT_FORMAT_STR labels = [] images = [] for i in range(0, nb_sample): digits = 0 last_digit = INVALID_DIGIT for j in range(0, DIGIT_COUNT): digit = last_digit while digit == last_digit: digit = random.randint(0, 9) last_digit = digit digits = digits * 10 + digit digits_as_str = DIGIT_FORMAT_STR % digits labels.append(digits_as_str) images.append(captcha.generate_image(digits_as_str)) digit_labels = np.empty((nb_sample, DIGIT_COUNT), dtype="int8") shape = (nb_sample, RGB_COLOR_COUNT, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH) if IS_TH else (nb_sample, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH, RGB_COLOR_COUNT) digit_image_data = np.empty(shape, dtype="float32") for index in range(0, nb_sample): img = images[index].resize((IMAGE_STD_WIDTH, IMAGE_STD_HEIGHT), PIL.Image.LANCZOS) # if index < SHOW_SAMPLE_SIZE: # display.display(img) img_arr = np.asarray(img, dtype="float32") / 255.0 if IS_TH: digit_image_data[index, :, :, :] = np.rollaxis(img_arr, 2) else: digit_image_data[index, :, :, :] = img_arr for digit_index in range(0, DIGIT_COUNT): digit_labels[index][digit_index] = labels[index][digit_index] x, y_as_num = digit_image_data, np.rollaxis(digit_labels, 1) y = { (OUT_PUT_NAME_FORMAT % i ): np_utils.to_categorical(y_as_num[i], CLASS_COUNT) for i in range(0, DIGIT_COUNT) } return x, y # X, Y_all = digit_image_data, digit_labels # x_train, x_test, y_train_as_num, y_test_as_num = train_test_split(X, Y_all, test_size=0.1, random_state=0) # y_train_as_num = np.rollaxis(y_train_as_num, 1) # y_test_as_num = np.rollaxis(y_test_as_num, 1) # # y_train = { (OUT_PUT_NAME_FORMAT % i ): np_utils.to_categorical(y_train_as_num[i], CLASS_COUNT) for i in range(0, DIGIT_COUNT) } # y_test = { (OUT_PUT_NAME_FORMAT % i ): y_test_as_num[i] for i in range(0, DIGIT_COUNT) } # # return (x_train, y_train, x_test, y_test) def create_cnn_layers(): shape = (RGB_COLOR_COUNT, IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH) if IS_TH else (IMAGE_STD_HEIGHT, IMAGE_STD_WIDTH, RGB_COLOR_COUNT) data_format = 'channels_first' if IS_TH else 'channels_last' input_layer = Input(name='input', shape=shape) h = Conv2D(22, (5, 5), activation='relu', data_format=data_format)(input_layer) h = MaxPooling2D(pool_size=POOL_SIZE)(h) h = Conv2D(44, (3, 3), activation='relu', data_format=data_format)(h) h = MaxPooling2D(pool_size=POOL_SIZE)(h) h = Dropout(0.25)(h) last_cnn_layer = Flatten()(h) return (input_layer, last_cnn_layer) def create_single_digit_model(): input_layer, last_cnn_layer = create_cnn_layers() h = Dense(256, activation='relu')(last_cnn_layer) h = Dropout(0.5)(h) output_layer = Dense(CLASS_COUNT, activation='softmax', name='out')(h) model = Model(inputs=input_layer, outputs=output_layer) model.compile( optimizer='adadelta', loss={ 'out': 'categorical_crossentropy', } ) return model def create_multi_digit_model(model_file='', digit_count=DIGIT_COUNT): input_layer, last_cnn_layer = create_cnn_layers() outputs = [] loss = {} for index in range(0, digit_count): h = Dense(256, activation='relu')(last_cnn_layer) h = Dropout(0.5)(h) out_name = OUT_PUT_NAME_FORMAT % index output = Dense(CLASS_COUNT, activation='softmax', name=out_name)(h) loss[out_name] = 'categorical_crossentropy' outputs.append(output) model = Model(inputs=input_layer, outputs=outputs) model.compile( optimizer='adadelta', loss=loss ) return model def print_acc(acc): print 'Single picture test accuracy: %2.2f%%' % (acc * 100) print 'Theoretical accuracy: %2.2f%% ~ %2.2f%%' % ((5*acc-4)*100, pow(acc, 5)*100) def save_model(model, save_model_file): print '... saving to %s' % save_model_file model.save_weights(save_model_file, overwrite=True) BANNER_BAR = '-----------------------------------' BANNER_BAR = 'β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”' def train_single_digit_model(model, index): save_model_file = 'model/model_one_%d.hdf5' % (index + 1) train_sample_size = SAMPLE_SIZE test_sample_size = int(SAMPLE_SIZE * TEST_SAMPLE_RATE) def gen(nb_sample): x, y = generate_image_sets_for_single_digit(nb_sample) while True: yield {'input': x}, {'out': y} class ValidateAcc(Callback): def on_epoch_end(self, epoch, logs={}): print print BANNER_BAR print 'Testing on %d samples...' % test_sample_size x_test, y_test_as_map = gen(test_sample_size).next() y_test = y_test_as_map['out'] y_test_as_num = array([argmax(i) for i in y_test]) r = model.predict(x_test, verbose=0) y_predict_as_num = array([argmax(i) for i in r]) acc = sum(y_predict_as_num == y_test_as_num) / test_sample_size print_acc(acc) print BANNER_BAR check_point = ModelCheckpoint(filepath=save_model_file) validation = ValidateAcc() callbacks = [check_point, validation] if not IS_TH: tb = TensorBoard(log_dir='./logs', histogram_freq=1, write_graph=True, write_images=False) callbacks.append(tb) print 'Training on %d samples...' % (train_sample_size) model.fit_generator( gen(train_sample_size / NB_BATCH), steps_per_epoch=NB_BATCH, epochs=NB_EPOCH, callbacks=callbacks ) save_model(model, save_model_file) def train_multi_digit_model(model, index): save_model_file = 'model/model_mul_%d.hdf5' % (index + 1) train_sample_size = SAMPLE_SIZE test_sample_size = int(SAMPLE_SIZE * TEST_SAMPLE_RATE) def gen(nb_sample): x, y = generate_image_sets_for_multi_digits(nb_sample) while True: yield {'input': x}, y class ValidateAcc(Callback): def on_epoch_end(self, epoch, logs={}): print print BANNER_BAR print 'Testing on %d samples...' % test_sample_size x_test, y_test_as_map = gen(test_sample_size).next() r = model.predict(x_test, verbose=0) # print r # https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html is_predict_correct = np.ones(test_sample_size, dtype="bool") # print r[0] # print r[0][0] # print argmax(r[0][0]) # print array([argmax(j) for j in r[0]]) for i in range(0, DIGIT_COUNT): output_name_i = OUT_PUT_NAME_FORMAT % i # print r[i] y_predict_as_num_i = array([argmax(j) for j in r[i]]) y_test_i = y_test_as_map[output_name_i] y_test_as_num_i = array([argmax(i) for i in y_test_i]) # print y_predict_as_num_i, y_test_as_num_i is_predict_correct_i = y_predict_as_num_i == y_test_as_num_i acc = sum(is_predict_correct_i) / (test_sample_size * 1.0) print '[%s]:' % output_name_i print_acc(acc) is_predict_correct = is_predict_correct & is_predict_correct_i acc_all = sum(is_predict_correct) / (test_sample_size * 1.0) # print y_predict_i, y_test_i, test_sample_size, acc print '[out]:' print_acc(acc_all) print BANNER_BAR check_point = ModelCheckpoint(filepath=save_model_file) # "tmp/mul.weights.{epoch:02d}.hdf5" validation = ValidateAcc() callbacks = [check_point, validation] if not IS_TH: tb = TensorBoard(log_dir='./logs', histogram_freq=1, write_graph=True, write_images=False) callbacks.append(tb) print 'Training on %d samples...' % (train_sample_size) model.fit_generator( gen(train_sample_size / NB_BATCH), steps_per_epoch=NB_BATCH, epochs=NB_EPOCH, callbacks=callbacks ) save_model(model, save_model_file) print sys.argv ARG_MODEL_TYPE = 1 MODEL_TYPE_SINGLE = 'one' MODEL_TYPE_MULTIPLE = 'mul' ARG_MODEL_INDEX = 2 ARG_MODEL_INDEX_MAX = 3 if len(sys.argv) > ARG_MODEL_TYPE: model_type = MODEL_TYPE_MULTIPLE if sys.argv[ARG_MODEL_TYPE] == MODEL_TYPE_MULTIPLE else MODEL_TYPE_SINGLE else: model_type = MODEL_TYPE_SINGLE if len(sys.argv) > ARG_MODEL_INDEX: index = int(sys.argv[ARG_MODEL_INDEX]) else: index = -1 if len(sys.argv) > ARG_MODEL_INDEX_MAX: max = int(sys.argv[ARG_MODEL_INDEX_MAX]) else: max = 1 base_model_file = '' # 'model/model_one_107.hdf5' digit_count = DIGIT_COUNT if model_type == MODEL_TYPE_SINGLE: model = create_single_digit_model() plot(model, 'single_digit_model.png') if index >= 0: model_file = 'model/model_one_%d.hdf5' % index print "Training based on %s" % model_file model.load_weights(model_file) while index < max: train_single_digit_model(model, index) index = index + 1 elif model_type == MODEL_TYPE_MULTIPLE: model = create_multi_digit_model(base_model_file, digit_count) plot(model, '%d_digit_model.png' % digit_count) if index >= 0: model_file = 'model/model_mul_%d.hdf5' % index print "Training based on %s" % model_file model.load_weights(model_file) while index < max: train_multi_digit_model(model, index) index = index + 1 else: pass # for index in range(SHOW_SAMPLE_SIZE): # display.display(labels[index]) # display.display(images[index])
{ "content_hash": "a96b0426b795e5eca736989a1c9aa376", "timestamp": "", "source": "github", "line_count": 413, "max_line_length": 153, "avg_line_length": 34.30992736077482, "alnum_prop": 0.6160197600564573, "repo_name": "utensil/julia-playground", "id": "e5b1aa47473a3ea9ddcb49330e36449d0846ca4b", "size": "14265", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dl/train_captcha.py", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "49" }, { "name": "Jupyter Notebook", "bytes": "8245805" }, { "name": "Python", "bytes": "33235" }, { "name": "Shell", "bytes": "753" } ], "symlink_target": "" }