prompt
listlengths
1
1
compression_prompt
listlengths
1
1
target
stringlengths
1.03k
828k
[ { "content": "Here is the snippet:\n```python\n### extends 'class_empty.py'\n### block ClassImports\n# NOTICE: Do not edit anything here, it is generated code\nfrom . import gxapi_cy\nfrom geosoft.gxapi import GXContext, float_ref, int_ref, str_ref\n\n\n### endblock ClassImports\n\n### block Header\n# NOTICE: T...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n### extends 'class_empty.py'\n### block ClassImports\n# NOTICE: Do not edit anything here, it is generated code\nfrom . import gxapi_cy\nfrom geosoft.gxapi import GXContext, float_ref, int_ref, str_ref\n\n\n### endblock ClassImports\n\n### block Hea...
```python ### extends 'class_empty.py' ### block ClassImports # NOTICE: Do not edit anything here, it is generated code from . import gxapi_cy from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref ### endblock ClassImports ### block Header # NOTICE: The code generator will not replace the code in this block ### endblock Header ### block ClassImplementation # NOTICE: Do not edit anything here, it is generated code class GXDOCU(gxapi_cy.WrapDOCU): """ GXDOCU class. Class to work with documents """ def __init__(self, handle=0): super(GXDOCU, self).__init__(GXContext._get_tls_geo(), handle) @classmethod def null(cls): """ A null (undefined) instance of `GXDOCU <geosoft.gxapi.GXDOCU>` :returns: A null `GXDOCU <geosoft.gxapi.GXDOCU>` :rtype: GXDOCU """ return GXDOCU() def is_null(self): """ Check if this is a null (undefined) instance :returns: True if this is a null (undefined) instance, False otherwise. :rtype: bool """ return self._internal_handle() == 0 # Miscellaneous def copy(self, doc_us): """ Copy `GXDOCU <geosoft.gxapi.GXDOCU>` :param doc_us: Source `GXDOCU <geosoft.gxapi.GXDOCU>` :type doc_us: GXDOCU .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ self._copy(doc_us) @classmethod def create(cls): """ Create a document onject :returns: `GXDOCU <geosoft.gxapi.GXDOCU>` Object :rtype: GXDOCU .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = gxapi_cy.WrapDOCU._create(GXContext._get_tls_geo()) return GXDOCU(ret_val) @classmethod def create_s(cls, bf): """ Create from a serialized source :param bf: `GXBF <geosoft.gxapi.GXBF>` from which to read `GXDOCU <geosoft.gxapi.GXDOCU>` :type bf: GXBF :returns: `GXDOCU <geosoft.gxapi.GXDOCU>` Object :rtype: GXDOCU .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = gxapi_cy.WrapDOCU._create_s(GXContext._get_tls_geo(), bf) return GXDOCU(ret_val) def get_file(self, file): """ Get the document and place in a file. :param file: File to which to write document :type file: str .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ self._get_file(file.encode()) def get_file_meta(self, file): """ Get the document and place in a file with metadata. :param file: File to which to write document :type file: str .. versionadded:: 5.1.8 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** If this document is only a URL link, the URL link will be resolved and the document downloaded from the appropriate server using the protocol specified. The document has metadata, and the native document does not support metadata, the metadata will be placed in an associated file "filename.extension.GeosoftMeta" """ self._get_file_meta(file.encode()) def get_meta(self, meta): """ Get the document's meta :param meta: `GXMETA <geosoft.gxapi.GXMETA>` object to fill in with the document's meta :type meta: GXMETA .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ self._get_meta(meta) def doc_name(self, name): """ The document name. :param name: Buffer to fill with document name :type name: str_ref .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ name.value = self._doc_name(name.value.encode()) def file_name(self, name): """ The original document file name. :param name: Buffer to fill with document file name :type name: str_ref .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ name.value = self._file_name(name.value.encode()) def have_meta(self): """ Checks if a document has metadata. :rtype: bool .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = self._have_meta() return ret_val def is_reference(self): """ Is the document only a reference (a URL) ? :returns: 1 - Yes, 0 - No :rtype: int .. versionadded:: 5.1.6 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = self._is_reference() return ret_val def open(self, mode): """ Open a document in the document viewer :param mode: :ref:`DOCU_OPEN` :type mode: int .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** On Windows, the default application for the file extension is used to open the file. """ self._open(mode) def serial(self, bf): """ Serialize `GXDOCU <geosoft.gxapi.GXDOCU>` :param bf: `GXBF <geosoft.gxapi.GXBF>` in which to write object :type bf: GXBF .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ self._serial(bf) def set_file(self, type, name, file): """ Set the document from a file source. :param type: Document type :param name: Document name, if "" file name will be used :param file: Document file, must exist :type type: str :type name: str :type file: str .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** Document types are normally identified by their extension. If you leave the document type blank, the extension of the document file will be used as the document type. To resolve conflicting types, you can define your own unique type by entering your own type "extension" string. The following types are pre-defined (as are any normal Geosoft file types): "htm" HTML "html" HTML "txt" ASCII text file "doc" Word for Windows document "pdf" Adobe PDF "map" Geosoft map file "mmap" Mapinfo map file (real extension "map") "grd" Geosoft grid file "gdb" Geosoft database URL Document Links The document name can be a URL link to the document using one of the supported protocols. The following protocols are supported: http://www.mywebserver.com/MyFile.doc - `GXHTTP <geosoft.gxapi.GXHTTP>` dap://my.dap.server.com/dcs?DatasetName?MyFile.doc - DAP (DAP Document Access) ftp://my.ftp.server.com/Dir1/MyFile.doc - FTP protocol The full file name will be stored but no data will be stored with the `GXDOCU <geosoft.gxapi.GXDOCU>` class and the document can be retrieved using the sGetFile_DOCU method. """ self._set_file(type.encode(), name.encode(), file.encode()) def set_file_meta(self, type, name, file): """ Set the document from a file source with metadata. :param type: Document type extension :param name: Document name, if NULL use file name :param file: Document file or URL :type type: str :type name: str :type file: str .. versionadded:: 5.1.8 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** See `set_file <geosoft.gxapi.GXDOCU.set_file>`. This function is the same as sSetFile_DOCU, plus insures that a `GXMETA <geosoft.gxapi.GXMETA>` exists that includes the "Data" class. If the file has associated metadata, either supported natively in the file, or through an associated file "filename.extension.GeosoftMeta", that metadata will be loaded into the `GXDOCU <geosoft.gxapi.GXDOCU>` meta, and a Data class will be constructed if one does not exist. Also, the Document type Extension is very important in that it specifies the document types that natively have metadata. The ones currently supported are: "map" Geosoft map file "gdb" Geosoft database "grd" Geosoft grid file """ self._set_file_meta(type.encode(), name.encode(), file.encode()) def set_meta(self, meta): """ Set the document's meta :param meta: `GXMETA <geosoft.gxapi.GXMETA>` to add to the document's meta :type meta: GXMETA .. versionadded:: 5.1.1 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ self._set_meta(meta) ### endblock ClassImplementation ### block ClassExtend # NOTICE: The code generator will not replace the code in this block ### endblock ClassExtend ### block Footer # NOTICE: The code generator will not replace the code in this block ### endblock Footer ```
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n```python\nimport sqlite3 # sqlite 3 database\nimport file_check_ex # to check if there is a file\nimport database # creating, editing, deleting the database\nimport intCheck # check that it is an integar\n\n\noption = None # choose what manu o...
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n<|memory_start|>```python\nimport sqlite3 # sqlite 3 database\nimport file_check_ex # to check if there is a file\nimport database # creating, editing, deleting the database\nimport intCheck # check that it is an integar\n\n\noption = None # ch...
```python import sqlite3 # sqlite 3 database import file_check_ex # to check if there is a file import database # creating, editing, deleting the database import intCheck # check that it is an integar option = None # choose what manu option they want sqlite_file = "" # the name of the sqlite3 file option_list = (0, 1, 2, 3) # the menu list option to use with option variable #option_tuple = None # Info from the intCheck held in a tuple. Use var[0] # print opening line print('\nWelcome to the texted based game database of your games') print('\nPlease enter a number to select an option') # user selection of options while option != 0: print('\nExit program = 0 \nNew database = 1\nEdit database = 2 \nDelete database = 3') # remember the sqlit3 file name sqlite_file = sqlite_file #Get user input for menu select option = intCheck.int_check(input('\nEnter number: ')) # get user input and check it is an intager if option in option_list: option = option if option == 1: sqlite_file = database.createDatabase() elif option == 2: database.editDatabase(sqlite_file) elif option == 3: print("\nThis is where you would delete a database, but not yet.") elif option == 0: print("\nThanks for playing") else: print("\nother option") # temp line else: print("\nPlease re-enter a valid number") # add to the columes in the database to make them equel for the game and game expasion so I can use the same gameVaule to input both. ```
[ { "content": "Produce an exact reconstruction of the code:\n```python\nfrom sympy.core import sympify, Lambda, Dummy, Integer, Rational, oo, Float, pi\nfrom sympy.functions import sqrt, exp, erf\nfrom sympy.printing import sstr\nimport random\n\n\nclass Sample(tuple):\n \"\"\"\n Sample([x1, x2, x3, ...]) ...
[ { "content": "Produce an exact reconstruction of the code:\n<|memory_start|>```python\nfrom sympy.core import sympify, Lambda, Dummy, Integer, Rational, oo, Float, pi\nfrom sympy.functions import sqrt, exp, erf\nfrom sympy.printing import sstr\nimport random\n\n\nclass Sample(tuple):\n \"\"\"\n Sample([x1...
```python from sympy.core import sympify, Lambda, Dummy, Integer, Rational, oo, Float, pi from sympy.functions import sqrt, exp, erf from sympy.printing import sstr import random class Sample(tuple): """ Sample([x1, x2, x3, ...]) represents a collection of samples. Sample parameters like mean, variance and stddev can be accessed as properties. The sample will be sorted. """ def __new__(cls, sample): s = tuple.__new__(cls, sorted(sample)) s.mean = mean = sum(s) / Integer(len(s)) s.variance = sum([(x-mean)**2 for x in s]) / Integer(len(s)) s.stddev = sqrt(s.variance) if len(s) % 2: s.median = s[len(s)//2] else: s.median = sum(s[len(s)//2-1:len(s)//2+1]) / Integer(2) return s def __repr__(self): return sstr(self) def __str__(self): return sstr(self) class ContinuousProbability(object): """Base class for continuous probability distributions""" def probability(s, a, b): """Calculate the probability that a random number x generated from the distribution satisfies a <= x <= b """ return s.cdf(b) - s.cdf(a) def random(s, n=None): """ random() -- generate a random number from the distribution. random(n) -- generate a Sample of n random numbers. """ if n is None: return s._random() else: return Sample([s._random() for i in xrange(n)]) def __repr__(self): return sstr(self) def __str__(self): return sstr(self) class Normal(ContinuousProbability): """ Normal(mu, sigma) represents the normal or Gaussian distribution with mean value mu and standard deviation sigma. Example usage: >>> from sympy.statistics import Normal >>> from sympy import oo >>> N = Normal(1, 2) >>> N.mean 1 >>> N.variance 4 >>> N.probability(-oo, 1) # probability on an interval 1/2 >>> N.probability(1, oo) 1/2 >>> N.probability(-oo, oo) 1 >>> N.probability(-1, 3) erf(sqrt(2)/2) >>> _.evalf() 0.682689492137086 """ def __init__(self, mu, sigma): self.mu = sympify(mu) self.sigma = sympify(sigma) mean = property(lambda s: s.mu) median = property(lambda s: s.mu) mode = property(lambda s: s.mu) stddev = property(lambda s: s.sigma) variance = property(lambda s: s.sigma**2) def pdf(s, x): """Return the probability density function as an expression in x""" x = sympify(x) return 1/(s.sigma*sqrt(2*pi)) * exp(-(x-s.mu)**2 / (2*s.sigma**2)) def cdf(s, x): """Return the cumulative density function as an expression in x""" x = sympify(x) return (1+erf((x-s.mu)/(s.sigma*sqrt(2))))/2 def _random(s): return random.gauss(float(s.mu), float(s.sigma)) def confidence(s, p): """Return a symmetric (p*100)% confidence interval. For example, p=0.95 gives a 95% confidence interval. Currently this function only handles numerical values except in the trivial case p=1. Examples usage: # One standard deviation >>> from sympy.statistics import Normal >>> N = Normal(0, 1) >>> N.confidence(0.68) (-0.994457883209753, 0.994457883209753) >>> N.probability(*_).evalf() 0.680000000000000 # Two standard deviations >>> N = Normal(0, 1) >>> N.confidence(0.95) (-1.95996398454005, 1.95996398454005) >>> N.probability(*_).evalf() 0.950000000000000 """ if p == 1: return (-oo, oo) assert p <= 1 # In terms of n*sigma, we have n = sqrt(2)*ierf(p). The inverse # error function is not yet implemented in SymPy but can easily be # computed numerically from sympy.mpmath import mpf, erfinv # calculate y = ierf(p) by solving erf(y) - p = 0 y = erfinv(mpf(p)) t = Float(str(mpf(float(s.sigma)) * mpf(2)**0.5 * y)) mu = s.mu.evalf() return (mu-t, mu+t) @staticmethod def fit(sample): """Create a normal distribution fit to the mean and standard deviation of the given distribution or sample.""" if not hasattr(sample, "stddev"): sample = Sample(sample) return Normal(sample.mean, sample.stddev) class Uniform(ContinuousProbability): """ Uniform(a, b) represents a probability distribution with uniform probability density on the interval [a, b] and zero density everywhere else. """ def __init__(self, a, b): self.a = sympify(a) self.b = sympify(b) mean = property(lambda s: (s.a+s.b)/2) median = property(lambda s: (s.a+s.b)/2) mode = property(lambda s: (s.a+s.b)/2) # arbitrary variance = property(lambda s: (s.b-s.a)**2 / 12) stddev = property(lambda s: sqrt(s.variance)) def pdf(s, x): """Return the probability density function as an expression in x""" x = sympify(x) if not x.is_Number: raise NotImplementedError("SymPy does not yet support" "piecewise functions") if x < s.a or x > s.b: return Rational(0) return 1/(s.b-s.a) def cdf(s, x): """Return the cumulative density function as an expression in x""" x = sympify(x) if not x.is_Number: raise NotImplementedError("SymPy does not yet support" "piecewise functions") if x <= s.a: return Rational(0) if x >= s.b: return Rational(1) return (x-s.a)/(s.b-s.a) def _random(s): return Float(random.uniform(float(s.a), float(s.b))) def confidence(s, p): """Generate a symmetric (p*100)% confidence interval. >>> from sympy import Rational >>> from sympy.statistics import Uniform >>> U = Uniform(1, 2) >>> U.confidence(1) (1, 2) >>> U.confidence(Rational(1,2)) (5/4, 7/4) """ p = sympify(p) assert p <= 1 d = (s.b-s.a)*p / 2 return (s.mean - d, s.mean + d) @staticmethod def fit(sample): """Create a uniform distribution fit to the mean and standard deviation of the given distribution or sample.""" if not hasattr(sample, "stddev"): sample = Sample(sample) m = sample.mean d = sqrt(12*sample.variance)/2 return Uniform(m-d, m+d) class PDF(ContinuousProbability): """ PDF(func, (x, a, b)) represents continuous probability distribution with probability distribution function func(x) on interval (a, b) If func is not normalized so that integrate(func, (x, a, b)) == 1, it can be normalized using PDF.normalize() method Example usage: >>> from sympy import Symbol, exp, oo >>> from sympy.statistics.distributions import PDF >>> from sympy.abc import x >>> a = Symbol('a', positive=True) >>> exponential = PDF(exp(-x/a)/a, (x,0,oo)) >>> exponential.pdf(x) exp(-x/a)/a >>> exponential.cdf(x) 1 - exp(-x/a) >>> exponential.mean a >>> exponential.variance a**2 """ def __init__(self, pdf, var): #XXX maybe add some checking of parameters if isinstance(var, (tuple, list)): self.pdf = Lambda(var[0], pdf) self.domain = tuple(var[1:]) else: self.pdf = Lambda(var, pdf) self.domain = (-oo, oo) self._cdf = None self._mean = None self._variance = None self._stddev = None def normalize(self): """ Normalize the probability distribution function so that integrate(self.pdf(x), (x, a, b)) == 1 Example usage: >>> from sympy import Symbol, exp, oo >>> from sympy.statistics.distributions import PDF >>> from sympy.abc import x >>> a = Symbol('a', positive=True) >>> exponential = PDF(exp(-x/a), (x,0,oo)) >>> exponential.normalize().pdf(x) exp(-x/a)/a """ norm = self.probability(*self.domain) if norm != 1: w = Dummy('w', real=True) return self.__class__(self.pdf(w)/norm, (w, self.domain[0], self.domain[1])) #self._cdf = Lambda(w, (self.cdf(w) - self.cdf(self.domain[0]))/norm) #if self._mean is not None: # self._mean /= norm #if self._variance is not None: # self._variance = (self._variance + (self._mean*norm)**2)/norm - self.mean**2 #if self._stddev is not None: # self._stddev = sqrt(self._variance) else: return self def cdf(self, x): x = sympify(x) if self._cdf is not None: return self._cdf(x) else: from sympy import integrate w = Dummy('w', real=True) self._cdf = integrate(self.pdf(w), w) self._cdf = Lambda(w, self._cdf - self._cdf.subs(w, self.domain[0])) return self._cdf(x) def _get_mean(self): if self._mean is not None: return self._mean else: from sympy import integrate w = Dummy('w', real=True) self._mean = integrate(self.pdf(w)*w,(w,self.domain[0],self.domain[1])) return self._mean def _get_variance(self): if self._variance is not None: return self._variance else: from sympy import integrate, simplify w = Dummy('w', real=True) self._variance = integrate(self.pdf(w)*w**2,(w,self.domain[0],self.domain[1])) - self.mean**2 self._variance = simplify(self._variance) return self._variance def _get_stddev(self): if self._stddev is not None: return self._stddev else: self._stddev = sqrt(self.variance) return self._stddev mean = property(_get_mean) variance = property(_get_variance) stddev = property(_get_stddev) def _random(s): raise NotImplementedError def transform(self,func,var): """Return a probability distribution of random variable func(x) currently only some simple injective functions are supported""" w = Dummy('w', real=True) from sympy import solve inverse = solve(func-w, var) newPdf = S.Zero funcdiff = func.diff(var) #TODO check if x is in domain for x in inverse: # this assignment holds only for x in domain # in general it would require implementing # piecewise defined functions in sympy newPdf += (self.pdf(var)/abs(funcdiff)).subs(var,x) return PDF(newPdf, (w, func.subs(var, self.domain[0]), func.subs(var, self.domain[1]))) ```
[ { "content": "```python\n# Copyright (c) 2013 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apac...
[ { "content": "<|memory_start|>```python\n# Copyright (c) 2013 OpenStack Foundation\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# ...
```python # Copyright (c) 2013 OpenStack Foundation # 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. from oslo_log import log as logging from trove.common import cfg from trove.common.i18n import _ from trove.guestagent.datastore.experimental.postgresql import pgutil from trove.guestagent.db import models LOG = logging.getLogger(__name__) CONF = cfg.CONF class PgSqlAccess(object): """Mixin implementing the user-access API calls.""" def grant_access(self, context, username, hostname, databases): """Give a user permission to use a given database. The username and hostname parameters are strings. The databases parameter is a list of strings representing the names of the databases to grant permission on. """ for database in databases: LOG.info( _("{guest_id}: Granting user ({user}) access to database " "({database}).").format( guest_id=CONF.guest_id, user=username, database=database,) ) pgutil.psql( pgutil.AccessQuery.grant( user=username, database=database, ), timeout=30, ) def revoke_access(self, context, username, hostname, database): """Revoke a user's permission to use a given database. The username and hostname parameters are strings. The database parameter is a string representing the name of the database. """ LOG.info( _("{guest_id}: Revoking user ({user}) access to database" "({database}).").format( guest_id=CONF.guest_id, user=username, database=database,) ) pgutil.psql( pgutil.AccessQuery.revoke( user=username, database=database, ), timeout=30, ) def list_access(self, context, username, hostname): """List database for which the given user as access. Return a list of serialized Postgres databases. """ if self.user_exists(username): return [db.serialize() for db in self._get_databases_for(username)] raise exception.UserNotFound(username) def _get_databases_for(self, username): """Return all Postgres databases accessible by a given user.""" results = pgutil.query( pgutil.AccessQuery.list(user=username), timeout=30, ) return [models.PostgreSQLSchema( row[0].strip(), character_set=row[1], collate=row[2]) for row in results] ```
[ { "content": "Here is the source code:\n```python\n# Written by Shlomi Fish, under the MIT Expat License.\n\nimport unittest\nfrom pysollib.acard import AbstractCard\nfrom pysollib.hint import FreeCellSolver_Hint, PySolHintLayoutImportError\nimport pysollib.stack\n\n\nclass MockItem:\n def __init__(self):\n ...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# Written by Shlomi Fish, under the MIT Expat License.\n\nimport unittest\nfrom pysollib.acard import AbstractCard\nfrom pysollib.hint import FreeCellSolver_Hint, PySolHintLayoutImportError\nimport pysollib.stack\n\n\nclass MockItem:\n def __...
```python # Written by Shlomi Fish, under the MIT Expat License. import unittest from pysollib.acard import AbstractCard from pysollib.hint import FreeCellSolver_Hint, PySolHintLayoutImportError import pysollib.stack class MockItem: def __init__(self): pass def tkraise(self): return def addtag(self, nouse): return class MockCanvas: def __init__(self): self.xmargin = self.ymargin = 50 class MockImages: def __init__(self): self.CARDW = self.CARDH = self.CARD_YOFFSET = 50 class MockOpt: def __init__(self): self.randomize_place = False class MockApp: def __init__(self): self.images = MockImages() self.opt = MockOpt() class MockTalon: def __init__(self, g): self.cards = [ AbstractCard(1000+r*100+s*10, 0, s, r, g) for s in range(4) for r in range(13)] for c in self.cards: c.item = MockItem() class MockGame: def __init__(self): self.app = MockApp() self.talon = MockTalon(self) self.allstacks = [] self.stackmap = {} self.canvas = MockCanvas() self.foundations = [ pysollib.stack.SS_FoundationStack(0, 0, self, s) for s in range(4)] self.rows = [pysollib.stack.AC_RowStack(0, 0, self) for s in range(8)] self.reserves = [ pysollib.stack.AC_RowStack(0, 0, self) for s in range(4)] self.preview = 0 def _empty_override(*args): return True pysollib.stack.MfxCanvasGroup = _empty_override class Mock_S_Game: def __init__(self): self.s = MockGame() def flipMove(self, foo): pass def moveMove(self, cnt, frm, to, frames=0): c = frm.cards.pop() c.face_up = True to.addCard(c) pass class MyTests(unittest.TestCase): def _calc_hint(self, fn): """docstring for _calc_hint""" s_game = Mock_S_Game() h = FreeCellSolver_Hint(s_game, None) fh = open(fn, 'r+b') h.importFileHelper(fh, s_game) return h def _successful_import(self, fn, want_s, blurb): self.assertEqual(self._calc_hint(fn).calcBoardString(), want_s, blurb) def test_import(self): return self._successful_import('tests/unit/data/with-10-for-rank.txt', '''FC: - - - - 4C 2C 9C 8C QS 4S 2H 5H QH 3C AC 3H 4H QD QC 9S 6H 9H 3S KS 3D 5D 2S JC 5C JH 6D AS 2D KD TH TC TD 8D 7H JS KH TS KC 7C AH 5S 6S AD 8H JD 7S 6C 7D 4D 8S 9D ''', 'import worked with "10"s as ranks') def test_import_2(self): return self._successful_import('tests/unit/data/624.board', '''FC: - - - - KC 6H 4C QS 2D 4S AS 4H TH 2S JH 2H 9S AH 3S 6C 9H AD KH QD 7C 3C JS 5H KS TC 9C 8C 4D 9D 7S JC 5D TS KD QC 5C QH 6S 3D 5S JD 8D 6D TD 8H 8S 7H 3H 2C AC 7D ''', 'import worked with Ts') def test_import_utf8_bom(self): return self._successful_import( 'tests/unit/data/624-with-utf8-bom.board', '''FC: - - - - KC 6H 4C QS 2D 4S AS 4H TH 2S JH 2H 9S AH 3S 6C 9H AD KH QD 7C 3C JS 5H KS TC 9C 8C 4D 9D 7S JC 5D TS KD QC 5C QH 6S 3D 5S JD 8D 6D TD 8H 8S 7H 3H 2C AC 7D ''', 'import worked with utf-8 bom') def test_throw_error_on_duplicate_card(self): try: self._calc_hint('tests/unit/data/624-with-dup-card.board') except PySolHintLayoutImportError as err: self.assertEqual(err.msg, "Duplicate cards in input") self.assertEqual(err.cards, ["KC"]) self.assertEqual(err.line_num, 1) self.assertEqual(err.format(), "Duplicate cards in input:\n\nKC") return self.fail("No exception thrown.") def test_throw_error_on_invalid_foundations_line(self): try: self._calc_hint( 'tests/unit/data/624-invalid-foundations-line.board') except PySolHintLayoutImportError as err: self.assertEqual(err.msg, "Invalid Foundations line") self.assertEqual(err.cards, []) self.assertEqual(err.line_num, 1) return self.fail("No exception thrown.") def test_throw_error_on_missing_cards(self): try: self._calc_hint('tests/unit/data/624-missing-cards.board') except PySolHintLayoutImportError as err: self.assertEqual(err.msg, "Missing cards in input") self.assertEqual(err.cards, ["5H"]) return self.fail("No exception thrown.") ```
[ { "content": "Reproduce the code exactly as provided (keep formatting):\n```python\nfrom subprocess import *\nfrom tempfile import TemporaryFile\n\nSHELL = '/bin/bash'\n\nclass Bench:\n workingDir = ''\n test = ''\n name = ''\n script = {}\n expected_result = None\n\n def __init__(self, workin...
[ { "content": "Reproduce the code exactly as provided (keep formatting):\n<|memory_start|>```python\nfrom subprocess import *\nfrom tempfile import TemporaryFile\n\nSHELL = '/bin/bash'\n\nclass Bench:\n workingDir = ''\n test = ''\n name = ''\n script = {}\n expected_result = None\n\n def __ini...
```python from subprocess import * from tempfile import TemporaryFile SHELL = '/bin/bash' class Bench: workingDir = '' test = '' name = '' script = {} expected_result = None def __init__(self, workingDir, test, name, script, expected_result): self.workingDir = workingDir self.test = test self.name = name self.script = script if expected_result: self.expected_result = str(expected_result).strip() def getPrepareCommand(self): if 'compile' in self.script: return self.script['compile'] else: return [ ['cp', '%f', '%o'], ['chmod', '+x', '%o'] ] def getRunCommand(self): if 'run' in self.script: return ['/usr/bin/time', '-f', '%U'] + self.script['run'] else: return ['/usr/bin/time', '-f', '%U', './%o'] def getRunPrintCommand(self): if 'print' in self.script: return self.script['print'] else: return self.getRunCommand() + ['--print'] def getClearCommand(self): files = ['*.out', '*.bin', '%o'] if 'other_files' in self.script: files.extend(self.script['other_files']) return ['rm', '-rf'] + files def getOutputFile(self): if 'output' in self.script: return self.script['output'] else: return self.getBaseName() + '.bin' def getInputFile(self): return self.script['input'] def getBaseName(self): return self.test + '-' + self.name def version(self): return self.executeMultiple(self.script['version']) def prepare(self): return self.executeMultiple(self.getPrepareCommand()) def clear(self): return self.execute(self.getClearCommand()) def run(self): out = self.execute(self.getRunCommand()) if out == False: return { 'success': False, 'error': 'Error executing command!', 'details': '' } try: return { 'success': True, 'time': float(out['err']) } except: return { 'success': False, 'error': 'Error getting the time', 'details': str(out) } def runCheck(self): out = self.execute(self.getRunPrintCommand()) if out == False: return { 'success': False, 'error': 'Failed', 'details': 'Boh..' } if self.expected_result and self.expected_result != out['out'].strip(): return { 'success': False, 'error': 'Wrong answer', 'details': "'%s' != '%s'" % (self.expected_result, out['out'].strip()) } return { 'success': True } def executeMultiple(self, commands): res = '' for command in commands: out = self.execute(command) if not out: return False else: res += out['out'] + out['err'] return res def execute(self, command): try: command = list(map(self.prepareParameter, command)) proc = Popen(command, stdout=PIPE, stderr=PIPE, cwd=self.workingDir) stdout, stderr = proc.communicate() stdout = str(stdout, 'utf-8') stderr = str(stderr, 'utf-8') if proc.returncode != 0: print("Command %s in dir %s failed! (exit-code = %d)" % (str(command), self.workingDir, proc.returncode)) print("STDOUT") print(stdout) print("STDERR") print(stderr) return False return {'out': stdout, 'err': stderr, 'code': proc.returncode} except Exception as e: print(e) return False def prepareParameter(self, param): param = param.replace('%f', self.getInputFile()) param = param.replace('%o', self.getOutputFile()) param = param.replace('%b', self.getBaseName()) param = param.replace('%t', self.test) return param class ScriptBench: workingDir = '' name = '' script = '' expected_result = None def __init__(self, workingDir, name, script, expected_result): self.workingDir = workingDir self.name = name self.script = script if expected_result: self.expected_result = str(expected_result).strip() def version(self): return self.execute('version', 'version.out') def prepare(self): return self.execute('pre_exec') def clear(self): return self.execute('clean') def run(self): out = self.execute('exec', 'time.out') if out == False: return { 'success': False, 'error': 'Error executing command!', 'details': '' } try: return { 'success': True, 'time': float(out) } except: return { 'success': False, 'error': 'Error getting the time', 'details': out } def runCheck(self): out = self.execute('print_exec', 'print.out') if out == False: return { 'success': False, 'error': 'Failed', 'details': 'Boh..' } if self.expected_result and self.expected_result != out.strip(): return { 'success': False, 'error': 'Wrong answer', 'details': "'%s' != '%s'" % (self.expected_result, out.strip()) } return { 'success': True } def execute(self, command, output = None): ret = call([SHELL, self.workingDir + '/' + self.script, command]) if ret != 0: return False if output: return self.readFile(output) return True def readFile(self, file): try: return open(self.workingDir + '/' + file, 'r').read() except: return '## File Not Found ##' ```
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n```python\nfrom typing import Deque, Union, Optional, List\n\nfrom hwt.code import Concat\nfrom hwt.hdl.types.bitsVal import BitsVal\nfrom hwt.hdl.types.struct import HStruct\nfrom hwt.hdl.types.structValBase import StructV...
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n<|memory_start|>```python\nfrom typing import Deque, Union, Optional, List\n\nfrom hwt.code import Concat\nfrom hwt.hdl.types.bitsVal import BitsVal\nfrom hwt.hdl.types.struct import HStruct\nfrom hwt.hdl.types.structValBas...
```python from typing import Deque, Union, Optional, List from hwt.code import Concat from hwt.hdl.types.bitsVal import BitsVal from hwt.hdl.types.struct import HStruct from hwt.hdl.types.structValBase import StructValBase from hwt.hdl.value import HValue from hwt.synthesizer.rtlLevel.constants import NOT_SPECIFIED from hwtLib.peripheral.usb.constants import USB_PID from hwtLib.peripheral.usb.descriptors.bundle import UsbDescriptorBundle, \ UsbNoSuchDescriptor from hwtLib.peripheral.usb.descriptors.cdc import usb_descriptor_functional_header, \ USB_CDC_DESCRIPTOR_SUBTYPE, usb_descriptor_functional_header_t, \ usb_descriptor_functional_call_management_t, \ usb_descriptor_functional_abstract_control_management_t, \ usb_define_descriptor_functional_union_t from hwtLib.peripheral.usb.descriptors.std import usb_descriptor_interface_t, \ USB_DEVICE_CLASS, usb_descriptor_header_t, USB_DESCRIPTOR_TYPE, \ usb_descriptor_configuration_t, usb_descriptor_endpoint_t, \ make_usb_device_request_get_descr, usb_define_descriptor_string, \ usb_descriptor_device_t, usb_descriptor_device_qualifier_t, \ usb_define_descriptor_string0, USB_ENDPOINT_DIR from hwtLib.peripheral.usb.device_request import make_usb_device_request, \ USB_REQUEST_TYPE_RECIPIENT, USB_REQUEST_TYPE_TYPE, \ USB_REQUEST_TYPE_DIRECTION, USB_REQUEST from hwtLib.peripheral.usb.sim.agent_base import UsbAgent, UsbPacketToken, \ UsbPacketData, UsbPacketHandshake from hwtLib.types.ctypes import uint8_t class UsbHostAgent(UsbAgent): """ This agent uses rx and tx queue to comunicate with a USB device. It performs bus enumerations, sets address to a device and downloads the descriptors. Note that the agent is written in a way which allows for easy extension to a driver which can parse the specific descriptors and comunicate with devices further. """ def __init__(self, rx: Deque[Union[UsbPacketToken, UsbPacketHandshake, UsbPacketData]], tx: Deque[Union[UsbPacketToken, UsbPacketHandshake, UsbPacketData]]): super(UsbHostAgent, self).__init__(rx, tx) # the addresses are not asigned yet this dictionary will be filled during device enumeration self.descr = {} self._descriptors_downloaded = False def parse_interface_functional_descriptor(self, interface_descr: StructValBase, data:BitsVal): bInterfaceClass = int(interface_descr.body.bInterfaceClass) if bInterfaceClass == USB_DEVICE_CLASS.CDC_CONTROL: h_t = usb_descriptor_functional_header header = data[h_t.bit_length():]._reinterpret_cast(h_t) sub_t = int(header.bDescriptorSubtype) if sub_t == USB_CDC_DESCRIPTOR_SUBTYPE.HEADER: descr_t = usb_descriptor_functional_header_t elif sub_t == USB_CDC_DESCRIPTOR_SUBTYPE.CALL_MANAGEMENT_FUNCTIONAL: descr_t = usb_descriptor_functional_call_management_t elif sub_t == USB_CDC_DESCRIPTOR_SUBTYPE.ABSTRACT_CONTROL_MANAGEMENT: descr_t = usb_descriptor_functional_abstract_control_management_t elif sub_t == USB_CDC_DESCRIPTOR_SUBTYPE.UNION: slave_cnt = (data._dtype.bit_length() - h_t.bit_length() - 8) // 8 descr_t = usb_define_descriptor_functional_union_t(slave_cnt) assert data._dtype.bit_length() == descr_t.bit_length() return data._reinterpret_cast(descr_t) else: raise NotImplementedError() def parse_configuration_descriptor_bundle(self, data_bytes: List[int]): data = [d if isinstance(d, HValue) else uint8_t.from_py(d) for d in data_bytes] data = Concat(*reversed(data)) offset = 0 end = data._dtype.bit_length() header_width = usb_descriptor_header_t.bit_length() descriptors = [] interface_descr = None while offset < end: header = data[header_width + offset: offset] header = header._reinterpret_cast(usb_descriptor_header_t) descr_typeId = int(header.bDescriptorType) descr_width = int(header.bLength) * 8 try: d = data[descr_width + offset: offset] except IndexError: raise IndexError("The input data is incomplete, the header suggest additional data", offset, descr_width, end) if descr_typeId == USB_DESCRIPTOR_TYPE.CONFIGURATION: t = usb_descriptor_configuration_t assert descr_width == t.bit_length() d = d._reinterpret_cast(t) interface_descr = None elif descr_typeId == USB_DESCRIPTOR_TYPE.INTERFACE: # :note: interface descriptors are class dependent, # the class can be resolved from first interface descriptor # next interface descriptors may be functional descriptors t = usb_descriptor_interface_t assert d._dtype.bit_length() == t.bit_length(), (d._dtype.bit_length(), t.bit_length()) d = d._reinterpret_cast(t) interface_descr = d elif descr_typeId == USB_DESCRIPTOR_TYPE.ENDPOINT: t = usb_descriptor_endpoint_t assert descr_width == t.bit_length() d = d._reinterpret_cast(t) elif descr_typeId == USB_DESCRIPTOR_TYPE.FUNCTIONAL: d = self.parse_interface_functional_descriptor(interface_descr, d) else: raise NotImplementedError(descr_typeId) descriptors.append(d) offset += descr_width return descriptors def get_max_packet_size(self, addr:int, endp: int, direction: USB_ENDPOINT_DIR): ddb: UsbDescriptorBundle = self.descr.get(addr, None) if ddb is None: max_packet_size = 64 else: if endp == 0: d = ddb.get_descriptor(usb_descriptor_device_t, 0)[1] max_packet_size = int(d.body.bMaxPacketSize) else: max_packet_size = None for des in ddb: if des._dtype == usb_descriptor_endpoint_t and \ int(des.body.bEndpointAddress) == endp and \ int(des.body.bEndpointAddressDir) == direction: max_packet_size = int(des.body.wMaxPacketSize) break if max_packet_size is None: raise ValueError("Can not find configuration for endpoint in descriptors", endp, ddb) return max_packet_size def receive_bulk(self, addr: int, endp: int, pid_init: USB_PID, size=NOT_SPECIFIED) -> List[int]: max_packet_size = self.get_max_packet_size(addr, endp, USB_ENDPOINT_DIR.IN) pid = pid_init # start recieveing the data yield from self.send(UsbPacketToken(USB_PID.TOKEN_IN, addr, endp)) # can receive data or STALL if the descriptor is not present d_raw = yield from self.receive(NOT_SPECIFIED) if isinstance(d_raw, UsbPacketData): assert d_raw.pid == pid, (d_raw.pid, pid) # descriptor data yield from self.send_ack() if size is not NOT_SPECIFIED: return d_raw.data # could be actually larger in the case when EP0 is not configured yet if len(d_raw.data) >= max_packet_size: # coud be possibly split into multiple packets # if the first chunk was just of pmax_packet_size and this is the size what we are asking for while True: if pid == USB_PID.DATA_0: pid = USB_PID.DATA_1 elif pid == USB_PID.DATA_1: pid = USB_PID.DATA_0 else: raise NotImplementedError(pid) yield from self.send(UsbPacketToken(USB_PID.TOKEN_IN, addr, endp)) descr_part = yield from self.receive(UsbPacketData) assert descr_part.pid == pid, (d_raw.pid, pid) d_raw.data.extend(descr_part.data) yield from self.send_ack() if len(descr_part.data) < max_packet_size: break return d_raw.data elif isinstance(d_raw, UsbPacketHandshake): # packet which means some error if d_raw.pid == USB_PID.HS_STALL: raise UsbNoSuchDescriptor() elif d_raw.pid == USB_PID.HS_NACK: return None else: raise NotImplementedError() else: raise NotImplementedError() def transmit_bulk(self, addr: int, endp: int, pid_init: USB_PID, data_bytes: List[int]): max_packet_size = self.get_max_packet_size(addr, endp, USB_ENDPOINT_DIR.OUT) pid = pid_init # start sending the data begin = 0 end = len(data_bytes) while True: yield from self.send(UsbPacketToken(USB_PID.TOKEN_OUT, addr, endp)) _end = min(begin + max_packet_size, end) p = UsbPacketData(pid, data_bytes[begin:_end]) yield from self.send(p) yield from self.wait_on_ack() begin = _end if pid == USB_PID.DATA_0: pid = USB_PID.DATA_1 elif pid == USB_PID.DATA_1: pid = USB_PID.DATA_0 else: raise ValueError(pid) if len(p.data) < max_packet_size: break def control_read(self, addr, bmRequestType_type:USB_REQUEST_TYPE_TYPE, bRequest:int, wValue:int, wIndex:int, wLength:int, bmRequestType_recipient:USB_REQUEST_TYPE_RECIPIENT=USB_REQUEST_TYPE_RECIPIENT.DEVICE, bmRequestType_data_transfer_direction:USB_REQUEST_TYPE_DIRECTION=USB_REQUEST_TYPE_DIRECTION.DEV_TO_HOST, ): dev_req = make_usb_device_request( bmRequestType_recipient=bmRequestType_recipient, bmRequestType_type=bmRequestType_type, bmRequestType_data_transfer_direction=bmRequestType_data_transfer_direction, bRequest=bRequest, wValue=wValue, wIndex=wIndex, wLength=wLength) # read the device descriptor # SETUP STAGE, send request for descriptor downloading yield from self.send(UsbPacketToken(USB_PID.TOKEN_SETUP, addr, 0)) yield from self.send(UsbPacketData(USB_PID.DATA_0, dev_req)) yield from self.wait_on_ack() # DATA stage data = yield from self.receive_bulk(addr, 0, USB_PID.DATA_1) # STATUS stage yield from self.transmit_bulk(addr, 0, USB_PID.DATA_1, []) return data def control_write(self, addr:int, ep:int, bmRequestType_type:USB_REQUEST_TYPE_TYPE, bRequest:int, wValue:int, wIndex:int, buff:List[int], bmRequestType_recipient:USB_REQUEST_TYPE_RECIPIENT=USB_REQUEST_TYPE_RECIPIENT.DEVICE, bmRequestType_data_transfer_direction:USB_REQUEST_TYPE_DIRECTION=USB_REQUEST_TYPE_DIRECTION.HOST_TO_DEV, ): p = UsbPacketToken(USB_PID.TOKEN_SETUP, addr, ep) yield from self.send(p) dev_req = make_usb_device_request( bmRequestType_recipient=bmRequestType_recipient, bmRequestType_type=bmRequestType_type, bmRequestType_data_transfer_direction=bmRequestType_data_transfer_direction, bRequest=bRequest, wValue=wValue, wIndex=wIndex, wLength=len(buff)) yield from self.send(UsbPacketData(USB_PID.DATA_0, dev_req)) yield from self.wait_on_ack() if buff: yield from self.transmit_bulk(addr, 0, USB_PID.DATA_1, buff) else: # no data present skiping write pass # STATUS stage data = yield from self.receive_bulk(addr, 0, USB_PID.DATA_1) assert not data, data def download_descriptor(self, addr: int, descriptor_t: Union[HStruct, str], index: int, wIndex:int=0, wLength: Optional[int]=NOT_SPECIFIED): dev_req_get_descr = make_usb_device_request_get_descr( descriptor_t, index, wIndex=wIndex, wLength=wLength) # read the device descriptor # SETUP STAGE, send request for descriptor downloading yield from self.send(UsbPacketToken(USB_PID.TOKEN_SETUP, addr, 0)) yield from self.send(UsbPacketData(USB_PID.DATA_0, dev_req_get_descr)) yield from self.wait_on_ack() # DATA stage descr = yield from self.receive_bulk(addr, 0, USB_PID.DATA_1) # assert len(descr) == int(dev_req_get_descr.wLength), (descriptor_t, wIndex, len(descr), int(dev_req_get_descr.wLength)) if wLength is NOT_SPECIFIED: if descriptor_t is str: char_cnt = (len(descr) - usb_descriptor_header_t.bit_length() // 8) // 2 if index == 0: descriptor_t = usb_define_descriptor_string0(char_cnt) else: descriptor_t = usb_define_descriptor_string(char_cnt) descr = UsbPacketData(USB_PID.DATA_1, descr) descr = descr.unpack(descriptor_t) else: assert len(descr) == int(dev_req_get_descr.wLength), (len(descr), int(dev_req_get_descr.wLength)) assert descriptor_t is usb_descriptor_configuration_t, descriptor_t descr = self.parse_configuration_descriptor_bundle(descr) # STATUS stage yield from self.send(UsbPacketToken(USB_PID.TOKEN_OUT, addr, 0)) yield from self.send(UsbPacketData(USB_PID.DATA_1, [])) yield from self.wait_on_ack() return descr def proc(self): new_addr = len(self.descr) + 1 # init device address yield from self.control_write(0, 0, bmRequestType_type=USB_REQUEST_TYPE_TYPE.STANDARD, bRequest=USB_REQUEST.SET_ADDRESS, wValue=new_addr, wIndex=0, buff=[]) # :note: device address now set, starting download of descriptors dev_descr = yield from self.download_descriptor(new_addr, usb_descriptor_device_t, 0) ddb = self.descr[new_addr] = UsbDescriptorBundle() ddb.append(dev_descr) bNumConfigurations = int(dev_descr.body.bNumConfigurations) assert bNumConfigurations > 0, "Device must have some configuration descriptors" for i in range(bNumConfigurations): # first we have to resolve wTotalLength (the total lenght of configuration bundle) conf_descr = yield from self.download_descriptor(new_addr, usb_descriptor_configuration_t, i) size = int(conf_descr.body.wTotalLength) # now we download all descriptors in configuration bundle conf_descr_bundle = yield from self.download_descriptor( new_addr, usb_descriptor_configuration_t, i, wLength=size) real_size = sum(c._dtype.bit_length() for c in conf_descr_bundle) // 8 assert real_size == size, (real_size, size, conf_descr_bundle) ddb.extend(conf_descr_bundle) while True: try: yield from self.download_descriptor( new_addr, usb_descriptor_device_qualifier_t, 0 ) except UsbNoSuchDescriptor: break raise NotImplementedError("usb_descriptor_device_qualifier") # now read all string descriptors str_descr0 = None for i in range(0, 255): try: str_descr = yield from self.download_descriptor( new_addr, str, i, wIndex=0 if i == 0 else int(str_descr0.body[0]) ) except UsbNoSuchDescriptor: if i == 0: raise UsbNoSuchDescriptor("Need at least string descriptor 0 with language code") else: # other are not required break if i == 0: str_descr0 = str_descr ddb.append(str_descr) self._descriptors_downloaded = True ```
[ { "content": "Provide an exact copy of the source code:\n```python\n# -*- coding: utf-8 -*-\r\nfrom django.utils.translation import ugettext as _\r\nfrom django.db import models\r\n\r\n#adapted from http://www.djangosnippets.org/snippets/494/\r\n#using UN country and 3 char code list from http://unstats.un.org/...
[ { "content": "Provide an exact copy of the source code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\r\nfrom django.utils.translation import ugettext as _\r\nfrom django.db import models\r\n\r\n#adapted from http://www.djangosnippets.org/snippets/494/\r\n#using UN country and 3 char code list from http:/...
```python # -*- coding: utf-8 -*- from django.utils.translation import ugettext as _ from django.db import models #adapted from http://www.djangosnippets.org/snippets/494/ #using UN country and 3 char code list from http://unstats.un.org/unsd/methods/m49/m49alpha.htm #correct as of 17th October 2008 COUNTRIES = ( ('AFG', _('Afghanistan')), ('ALA', _('Aland Islands')), ('ALB', _('Albania')), ('DZA', _('Algeria')), ('ASM', _('American Samoa')), ('AND', _('Andorra')), ('AGO', _('Angola')), ('AIA', _('Anguilla')), ('ATA', _('Antarctica')), ('ATG', _('Antigua and Barbuda')), ('ARG', _('Argentina')), ('ARM', _('Armenia')), ('ABW', _('Aruba')), ('AUS', _('Australia')), ('AUT', _('Austria')), ('AZE', _('Azerbaijan')), ('BHS', _('Bahamas')), ('BHR', _('Bahrain')), ('BGD', _('Bangladesh')), ('BRB', _('Barbados')), ('BLR', _('Belarus')), ('BEL', _('Belgium')), ('BLZ', _('Belize')), ('BEN', _('Benin')), ('BMU', _('Bermuda')), ('BTN', _('Bhutan')), ('BOL', _('Bolivia')), ('BIH', _('Bosnia and Herzegovina')), ('BWA', _('Botswana')), ('BRA', _('Brazil')), ('IOT', _('British Indian Ocean Territory')), ('VGB', _('British Virgin Islands')), ('BRN', _('Brunei Darussalam')), ('BGR', _('Bulgaria')), ('BFA', _('Burkina Faso')), ('BDI', _('Burundi')), ('KHM', _('Cambodia')), ('CMR', _('Cameroon')), ('CAN', _('Canada')), ('CPV', _('Cape Verde')), ('CYM', _('Cayman Islands')), ('CAF', _('Central African Republic')), ('TCD', _('Chad')), ('CIL', _('Channel Islands')), ('CHL', _('Chile')), ('CHN', _('China')), ('HKG', _('China - Hong Kong')), ('MAC', _('China - Macao')), ('CXR', _('Christmas Island')), ('CCK', _('Cocos (Keeling) Islands')), ('COL', _('Colombia')), ('COM', _('Comoros')), ('COG', _('Congo')), ('COK', _('Cook Islands')), ('CRI', _('Costa Rica')), ('CIV', _('Cote d\'Ivoire')), ('HRV', _('Croatia')), ('CUB', _('Cuba')), ('CYP', _('Cyprus')), ('CZE', _('Czech Republic')), ('PRK', _('Democratic People\'s Republic of Korea')), ('COD', _('Democratic Republic of the Congo')), ('DNK', _('Denmark')), ('DJI', _('Djibouti')), ('DMA', _('Dominica')), ('DOM', _('Dominican Republic')), ('ECU', _('Ecuador')), ('EGY', _('Egypt')), ('SLV', _('El Salvador')), ('GNQ', _('Equatorial Guinea')), ('ERI', _('Eritrea')), ('EST', _('Estonia')), ('ETH', _('Ethiopia')), ('FRO', _('Faeroe Islands')), ('FLK', _('Falkland Islands (Malvinas)')), ('FJI', _('Fiji')), ('FIN', _('Finland')), ('FRA', _('France')), ('GUF', _('French Guiana')), ('PYF', _('French Polynesia')), ('ATF', _('French Southern Territories')), ('GAB', _('Gabon')), ('GMB', _('Gambia')), ('GEO', _('Georgia')), ('DEU', _('Germany')), ('GHA', _('Ghana')), ('GIB', _('Gibraltar')), ('GRC', _('Greece')), ('GRL', _('Greenland')), ('GRD', _('Grenada')), ('GLP', _('Guadeloupe')), ('GUM', _('Guam')), ('GTM', _('Guatemala')), ('GGY', _('Guernsey')), ('GIN', _('Guinea')), ('GNB', _('Guinea-Bissau')), ('GUY', _('Guyana')), ('HTI', _('Haiti')), ('VAT', _('Holy See (Vatican City)')), ('HND', _('Honduras')), ('HUN', _('Hungary')), ('ISL', _('Iceland')), ('IND', _('India')), ('IDN', _('Indonesia')), ('IRN', _('Iran')), ('IRQ', _('Iraq')), ('IRL', _('Ireland')), ('IMN', _('Isle of Man')), ('ISR', _('Israel')), ('ITA', _('Italy')), ('JAM', _('Jamaica')), ('JPN', _('Japan')), ('JEY', _('Jersey')), ('JOR', _('Jordan')), ('KAZ', _('Kazakhstan')), ('KEN', _('Kenya')), ('KIR', _('Kiribati')), ('KWT', _('Kuwait')), ('KGZ', _('Kyrgyzstan')), ('LAO', _('Lao People\'s Democratic Republic')), ('LVA', _('Latvia')), ('LBN', _('Lebanon')), ('LSO', _('Lesotho')), ('LBR', _('Liberia')), ('LBY', _('Libyan Arab Jamahiriya')), ('LIE', _('Liechtenstein')), ('LTU', _('Lithuania')), ('LUX', _('Luxembourg')), ('MKD', _('Macedonia')), ('MDG', _('Madagascar')), ('MWI', _('Malawi')), ('MYS', _('Malaysia')), ('MDV', _('Maldives')), ('MLI', _('Mali')), ('MLT', _('Malta')), ('MHL', _('Marshall Islands')), ('MTQ', _('Martinique')), ('MRT', _('Mauritania')), ('MUS', _('Mauritius')), ('MYT', _('Mayotte')), ('MEX', _('Mexico')), ('FSM', _('Micronesia, Federated States of')), ('MCO', _('Monaco')), ('MNG', _('Mongolia')), ('MNE', _('Montenegro')), ('MSR', _('Montserrat')), ('MAR', _('Morocco')), ('MOZ', _('Mozambique')), ('MMR', _('Myanmar')), ('NAM', _('Namibia')), ('NRU', _('Nauru')), ('NPL', _('Nepal')), ('NLD', _('Netherlands')), ('ANT', _('Netherlands Antilles')), ('NCL', _('New Caledonia')), ('NZL', _('New Zealand')), ('NIC', _('Nicaragua')), ('NER', _('Niger')), ('NGA', _('Nigeria')), ('NIU', _('Niue')), ('NFK', _('Norfolk Island')), ('MNP', _('Northern Mariana Islands')), ('NOR', _('Norway')), ('PSE', _('Occupied Palestinian Territory')), ('OMN', _('Oman')), ('PAK', _('Pakistan')), ('PLW', _('Palau')), ('PAN', _('Panama')), ('PNG', _('Papua New Guinea')), ('PRY', _('Paraguay')), ('PER', _('Peru')), ('PHL', _('Philippines')), ('PCN', _('Pitcairn')), ('POL', _('Poland')), ('PRT', _('Portugal')), ('PRI', _('Puerto Rico')), ('QAT', _('Qatar')), ('KOR', _('Republic of Korea')), ('MDA', _('Republic of Moldova')), ('REU', _('Reunion')), ('ROU', _('Romania')), ('RUS', _('Russian Federation')), ('RWA', _('Rwanda')), ('BLM', _('Saint-Barthelemy')), ('SHN', _('Saint Helena')), ('KNA', _('Saint Kitts and Nevis')), ('LCA', _('Saint Lucia')), ('MAF', _('Saint-Martin (French part)')), ('SPM', _('Saint Pierre and Miquelon')), ('VCT', _('Saint Vincent and the Grenadines')), ('WSM', _('Samoa')), ('SMR', _('San Marino')), ('STP', _('Sao Tome and Principe')), ('SAU', _('Saudi Arabia')), ('SEN', _('Senegal')), ('SRB', _('Serbia')), ('SYC', _('Seychelles')), ('SLE', _('Sierra Leone')), ('SGP', _('Singapore')), ('SVK', _('Slovakia')), ('SVN', _('Slovenia')), ('SLB', _('Solomon Islands')), ('SOM', _('Somalia')), ('ZAF', _('South Africa')), ('ESP', _('Spain')), ('LKA', _('Sri Lanka')), ('SDN', _('Sudan')), ('SUR', _('Suriname')), ('SJM', _('Svalbard and Jan Mayen Islands')), ('SWZ', _('Swaziland')), ('SWE', _('Sweden')), ('CHE', _('Switzerland')), ('SYR', _('Syrian Arab Republic')), ('TWN', _('Taiwan')), ('TJK', _('Tajikistan')), ('THA', _('Thailand')), ('TLS', _('Timor-Leste')), ('TGO', _('Togo')), ('TKL', _('Tokelau')), ('TON', _('Tonga')), ('TTO', _('Trinidad and Tobago')), ('TUN', _('Tunisia')), ('TUR', _('Turkey')), ('TKM', _('Turkmenistan')), ('TCA', _('Turks and Caicos Islands')), ('TUV', _('Tuvalu')), ('UGA', _('Uganda')), ('UKR', _('Ukraine')), ('ARE', _('United Arab Emirates')), ('GBR', _('United Kingdom')), ('TZA', _('United Republic of Tanzania')), ('USA', _('United States of America')), ('VIR', _('United States Virgin Islands')), ('URY', _('Uruguay')), ('UZB', _('Uzbekistan')), ('VUT', _('Vanuatu')), ('VEN', _('Venezuela (Bolivarian Republic of)')), ('VNM', _('Viet Nam')), ('WLF', _('Wallis and Futuna Islands')), ('ESH', _('Western Sahara')), ('YEM', _('Yemen')), ('ZMB', _('Zambia')), ('ZWE', _('Zimbabwe')), ) COUNTRY_DICT = { u'Afghanistan': 'AFG', u'Aland Islands': 'ALA', u'Albania': 'ALB', u'Algeria': 'DZA', u'American Samoa': 'ASM', u'Andorra': 'AND', u'Angola': 'AGO', u'Anguilla': 'AIA', u'Antarctica' : 'ATA', u'Antigua and Barbuda': 'ATG', u'Argentina': 'ARG', u'Armenia': 'ARM', u'Aruba': 'ABW', u'Australia': 'AUS', u'Austria': 'AUT', u'Azerbaijan': 'AZE', u'Bahamas': 'BHS', u'Bahrain': 'BHR', u'Bangladesh': 'BGD', u'Barbados': 'BRB', u'Belarus': 'BLR', u'Belgium': 'BEL', u'Belize': 'BLZ', u'Benin': 'BEN', u'Bermuda': 'BMU', u'Bhutan': 'BTN', u'Bolivia': 'BOL', u'Bosnia and Herzegovina': 'BIH', u'Botswana': 'BWA', u'Brazil': 'BRA', u'British Indian Ocean Territory': 'IOT', u'British Virgin Islands': 'VGB', u'Brunei Darussalam': 'BRN', u'Bulgaria': 'BGR', u'Burkina Faso': 'BFA', u'Burundi': 'BDI', u'Cambodia': 'KHM', u'Cameroon': 'CMR', u'Canada': 'CAN', u'Cape Verde': 'CPV', u'Cayman Islands': 'CYM', u'Central African Republic': 'CAF', u'Chad': 'TCD', u'Channel Islands': 'CIL', u'Chile': 'CHL', u'China': 'CHN', u'China - Hong Kong': 'HKG', u'China - Macao': 'MAC', u'Christmas Island': 'CXR', u'Cocos (Keeling) Islands': 'CCK', u'Colombia': 'COL', u'Comoros': 'COM', u'Congo': 'COG', u'Cook Islands': 'COK', u'Costa Rica': 'CRI', u"Cote d'Ivoire": 'CIV', u"Cote D'Ivoire (Ivory Coast)" : 'CIV', u'Croatia': 'HRV', u'Cuba': 'CUB', u'Cyprus': 'CYP', u'Czech Republic': 'CZE', u"Democratic People's Republic of Korea": 'PRK', u'Democratic Republic of the Congo': 'COD', u'Denmark': 'DNK', u'Djibouti': 'DJI', u'Dominica': 'DMA', u'Dominican Republic': 'DOM', u'East Timor': 'TLS', u'Ecuador': 'ECU', u'Egypt': 'EGY', u'El Salvador': 'SLV', u'Equatorial Guinea': 'GNQ', u'Eritrea': 'ERI', u'Estonia': 'EST', u'Ethiopia': 'ETH', u'Faeroe Islands': 'FRO', u'Falkland Islands (Malvinas)': 'FLK', u'Faroe Islands': 'FRO', u'Federated States of Micronesia': 'FSM', u'Fiji': 'FJI', u'Finland': 'FIN', u'France': 'FRA', u'French Guiana': 'GUF', u'French Polynesia': 'PYF', u'French Southern Territories': 'ATF', u'Gabon': 'GAB', u'Gambia': 'GMB', u'Georgia': 'GEO', u'Germany': 'DEU', u'Ghana': 'GHA', u'Gibraltar': 'GIB', u'Greece': 'GRC', u'Greenland': 'GRL', u'Grenada': 'GRD', u'Guadeloupe': 'GLP', u'Guam': 'GUM', u'Guatemala': 'GTM', u'Guernsey': 'GGY', u'Guinea': 'GIN', u'Guinea-Bissau': 'GNB', u'Guyana': 'GUY', u'Haiti': 'HTI', u'Holy See (Vatican City)': 'VAT', u'Honduras': 'HND', u'Hong Kong': 'HKG', u'Hungary': 'HUN', u'Iceland': 'ISL', u'India': 'IND', u'Indonesia': 'IDN', u'Iran': 'IRN', u'Iraq': 'IRQ', u'Ireland': 'IRL', u'Isle of Man': 'IMN', u'Israel': 'ISR', u'Italy': 'ITA', u'Jamaica': 'JAM', u'Japan': 'JPN', u'Jersey': 'JEY', u'Jordan': 'JOR', u'Kazakhstan': 'KAZ', u'Kenya': 'KEN', u'Kiribati': 'KIR', u'Korea': 'KOR', u"Korea (North)": 'PRK', u'Kuwait': 'KWT', u'Kyrgyzstan': 'KGZ', u"Lao People's Democratic Republic": 'LAO', u"Laos": 'LAO', u'Latvia': 'LVA', u'Lebanon': 'LBN', u'Lesotho': 'LSO', u'Liberia': 'LBR', u'Libya': 'LBY', u'Libyan Arab Jamahiriya': 'LBY', u'Liechtenstein': 'LIE', u'Lithuania': 'LTU', u'Luxembourg': 'LUX', u'Macao': 'MAC', u'Macedonia': 'MKD', u'Madagascar': 'MDG', u'Malawi': 'MWI', u'Malaysia': 'MYS', u'Maldives': 'MDV', u'Mali': 'MLI', u'Malta': 'MLT', u'Marshall Islands': 'MHL', u'Martinique': 'MTQ', u'Mauritania': 'MRT', u'Mauritius': 'MUS', u'Mayotte': 'MYT', u'Mexico': 'MEX', u'Micronesia, Federated States of': 'FSM', u'Moldova': 'MDA', u'Monaco': 'MCO', u'Mongolia': 'MNG', u'Montenegro': 'MNE', u'Montserrat': 'MSR', u'Morocco': 'MAR', u'Mozambique': 'MOZ', u'Myanmar': 'MMR', u'Namibia': 'NAM', u'Nauru': 'NRU', u'Nepal': 'NPL', u'Netherlands': 'NLD', u'Netherlands Antilles': 'ANT', u'New Caledonia': 'NCL', u'New Zealand': 'NZL', u'Nicaragua': 'NIC', u'Niger': 'NER', u'Nigeria': 'NGA', u'Niue': 'NIU', u'Norfolk Island': 'NFK', u'Northern Mariana Islands': 'MNP', u'Norway': 'NOR', u'Occupied Palestinian Territory': 'PSE', u'Oman': 'OMN', u'Pakistan': 'PAK', u'Palau': 'PLW', u'Palestinian Territory': 'PSE', u'Panama': 'PAN', u'Papua New Guinea': 'PNG', u'Paraguay': 'PRY', u'Peru': 'PER', u'Philippines': 'PHL', u'Pitcairn': 'PCN', u'Poland': 'POL', u'Portugal': 'PRT', u'Puerto Rico': 'PRI', u'Qatar': 'QAT', u'Republic of Korea': 'KOR', u'Republic of Moldova': 'MDA', u'Reunion': 'REU', u'Romania': 'ROU', u'Russian Federation': 'RUS', u'Rwanda': 'RWA', u'Saint Helena': 'SHN', u'Saint Kitts and Nevis': 'KNA', u'Saint Lucia': 'LCA', u'Saint Pierre and Miquelon': 'SPM', u'Saint Vincent and the Grenadines': 'VCT', u'Saint-Barthelemy': 'BLM', u'Saint-Martin (French part)': 'MAF', u'Samoa': 'WSM', u'San Marino': 'SMR', u'Sao Tome and Principe': 'STP', u'Saudi Arabia': 'SAU', u'Senegal': 'SEN', u'Serbia': 'SRB', u'Seychelles': 'SYC', u'Sierra Leone': 'SLE', u'Singapore': 'SGP', u'Slovak Republic': 'SVK', u'Slovakia': 'SVK', u'Slovenia': 'SVN', u'Solomon Islands': 'SLB', u'Somalia': 'SOM', u'South Africa': 'ZAF', u'Spain': 'ESP', u'Sri Lanka': 'LKA', u'Sudan': 'SDN', u'Suriname': 'SUR', u'Svalbard and Jan Mayen': 'SJM', u'Svalbard and Jan Mayen Islands': 'SJM', u'Swaziland': 'SWZ', u'Sweden': 'SWE', u'Switzerland': 'CHE', u'Syria': 'SYR', u'Syrian Arab Republic': 'SYR', u'Tajikistan': 'TJK', u'Tanzania' : 'TZA', u'Taiwan' : 'TWN', u'Thailand': 'THA', u'Timor-Leste': 'TLS', u'Togo': 'TGO', u'Tokelau': 'TKL', u'Tonga': 'TON', u'Trinidad and Tobago': 'TTO', u'Tunisia': 'TUN', u'Turkey': 'TUR', u'Turkmenistan': 'TKM', u'Turks and Caicos Islands': 'TCA', u'Tuvalu': 'TUV', u'Uganda': 'UGA', u'Ukraine': 'UKR', u'United Arab Emirates': 'ARE', u'United Kingdom': 'GBR', u'United Republic of Tanzania': 'TZA', u'United States Virgin Islands': 'VIR', u'United States': 'USA', u'United States of America': 'USA', u'Uruguay': 'URY', u'Uzbekistan': 'UZB', u'Vanuatu': 'VUT', u'Vatican City State (Holy See)': 'VAT', u'Venezuela': 'VEN', u'Venezuela (Bolivarian Republic of)': 'VEN', u'Viet Nam': 'VNM', u'Vietnam': 'VNM', u'Virgin Islands (British)': 'VGB', u'Virgin Islands (U.S.)': 'VIR', u'Wallis and Futuna': 'WLF', u'Wallis and Futuna Islands': 'WLF', u'Western Sahara': 'ESH', u'Yemen': 'YEM', u'Zambia': 'ZMB', u'Zimbabwe': 'ZWE' } class CountryField(models.CharField): def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 3) kwargs.setdefault('choices', COUNTRIES) super(CountryField, self).__init__(*args, **kwargs) def get_internal_type(self): return "CharField" ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\nfrom django import template\n\nregister = template.Library()\n\n\n@register.filter\ndef get_range(value):\n if value is not None:\n return range(value)\n else:\n return 0\n\n\n@register.filter\ndef absolute(value):\...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\nfrom django import template\n\nregister = template.Library()\n\n\n@register.filter\ndef get_range(value):\n if value is not None:\n return range(value)\n else:\n return 0\n\n\n@register.filter\ndef a...
```python from django import template register = template.Library() @register.filter def get_range(value): if value is not None: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_') # Get dictionary key by string @register.filter def key(d, key_name): if type(d) == list: return d[key_name] else: return d.get(key_name) @register.filter def humanize_number(value): powers = [10 ** x for x in (0, 3, 6, 9, 12)] human_powers = ('', 'K', 'M', 'B', 'T') try: index, hp = next((i, p) for i, p in enumerate(human_powers) if 10 ** 3 > value / powers[i] > 0) return_value = "%.{fraction_point}f".format( fraction_point=1) % (float(value) / powers[index]) return_value = return_value \ if float(return_value) != int(float(return_value)) \ else str(int(float(return_value))) return "%s%s" % (return_value, hp) except (IndexError, StopIteration): return value @register.filter def timedelta(delta): if delta: total_seconds = delta.total_seconds() minutes = int(total_seconds // 60) seconds = total_seconds - minutes * 60 return f'{minutes:02d}:{seconds:2.3f}' else: return '' ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\nimport os\nimport sys\nimport shutil\n\nfrom django_safe_project import safe_settings\n\nPY3 = sys.version_info.major > 2\n\nif PY3:\n basestring = str\n\nclass Template(object):\n \"\"\"Handles copying and modifying the project ...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\nimport os\nimport sys\nimport shutil\n\nfrom django_safe_project import safe_settings\n\nPY3 = sys.version_info.major > 2\n\nif PY3:\n basestring = str\n\nclass Template(object):\n \"\"\"Handles copying and modify...
```python import os import sys import shutil from django_safe_project import safe_settings PY3 = sys.version_info.major > 2 if PY3: basestring = str class Template(object): """Handles copying and modifying the project template. :param source: Source path of the project template :param dest: Destination for modified template """ def __init__(self, **kwargs): self.source = kwargs.get('source') self.dest = kwargs.get('dest') def build_dest(self): """Initiates the copy/modification process. This is not called by the constructor. """ ign = shutil.ignore_patterns('*.pyc') shutil.copytree(self.source, self.dest, ignore=ign) for root, dirs, files in os.walk(self.dest): for name in files: if os.path.splitext(name)[1] != '.py-tpl': continue name = os.path.join(root, name) new_name = '.'.join([os.path.splitext(name)[0], 'py']) os.rename(name, new_name) self.build_local_settings() self.update_settings() self.build_gitignore() def build_local_settings(self): """Generates the local_settings.py module. Uses the contents of safe_settings.py. """ filename = os.path.join(self.dest, 'project_name', 'local_settings.py') lines = [] for attr, val in self.iter_safe_settings(): if 'value' not in val: continue value = self.make_py_string(val['value']) lines.append(' = '.join([attr, value])) with open(filename, 'w') as f: f.write('\n'.join(lines)) def update_settings(self): """Modifies the destination's settings.py module. Adds an import for the generated local_settings.py. All values for 'local_settings' are either replaced via `getattr`. """ filename = os.path.join(self.dest, 'project_name', 'settings.py') with open(filename, 'r') as f: lines = f.read().splitlines() def add_import(): last_import = None for i, line in enumerate(lines): if line.startswith('import'): last_import = i elif last_import is not None: break imp_lines = [ 'import warnings', 'try:', ' import local_settings', 'except ImportError:', ' class local_settings(object):', ] for key, val in self.iter_safe_settings(): if key == 'SECRET_KEY': val = {'value':"'NotSecret'"} elif 'value' not in val: continue imp_lines.append(' %s=%s' % (key,val['value'])) imp_lines.append(" warnings.warn('local_settings module not found. Using unsafe defaults', ImportWarning)") for i, imp_line in enumerate(imp_lines): lines.insert(last_import + i + 1, imp_line) add_import() settings_dict = self.build_settings_dict(lines) local_settings_attrs = [] for attr, val in self.iter_safe_settings(): local_settings_attrs.append(attr) if 'default' in val: df = self.make_py_string(val['default']) value = "getattr(local_settings, '%s', %s)" % (attr, df) else: value = "getattr(local_settings, '%s')" % (attr) if val.get('update_dict'): value = '%s.update(%s)' % (attr, value) lines.append(value) else: d = settings_dict[attr] lines[d['line_num']] = ' = '.join([attr, value]) lines.extend(self.add_custom_settings(local_settings_attrs)) with open(filename, 'w') as f: f.write('\n'.join(lines)) def build_gitignore(self): """Builds a `.gitignore` file to exclude the `local_settings` module. """ filename = os.path.join(self.dest, 'project_name', '.gitignore') if os.path.exists(filename): with open(filename, 'r') as f: lines = f.read().splitlines() else: lines = [] if 'local_settings.py*' in lines: return lines.append('local_settings.py*') with open(filename, 'w') as f: f.write('\n'.join(lines)) def iter_safe_settings(self): for attr in dir(safe_settings): if attr.startswith('_'): continue if not attr.isupper(): continue yield attr, getattr(safe_settings, attr) def make_py_string(self, obj): if isinstance(obj, basestring): return "'%s'" % (obj) return str(obj) def build_settings_dict(self, lines): """Parses the `settings.py` file manually. Generates a `dict` of settings attributes with their corresponding line numbers. """ d = {} bracket_chars = [['{', '[', '('], ['}', ']', ')']] def find_bracket_close(line_num, bracket_char): # The results of this function are not currently used, but may # possibly be in future versions. close_char = bracket_chars[1][bracket_chars[0].index(bracket_char)] num_open = 0 for i, line in enumerate(lines[line_num:]): num_open += line.count(bracket_char) - line.count(close_char) if num_open == 0: return line_num + i def find_next_setting(start_line): for i, line in enumerate(lines[start_line:]): if line.startswith('#'): continue if ' = ' not in line: continue s = line.split(' = ')[0] if not s.isupper(): continue if s in d: continue value = line.split(' = ')[1].rstrip('\n').rstrip(' ') line_num = start_line + i if value[-1] in bracket_chars[0]: last_line = find_bracket_close(line_num, value[-1]) else: last_line = line_num d[s] = {'line_num':line_num, 'last_line':last_line} return last_line return None line_num = 0 while True: line_num = find_next_setting(line_num) if line_num is None: break return d def add_custom_settings(self, ignored_settings): lines = [ '', '# If any settings are added to `local_settings.py` later,', '# import them here.', '_local_settings_attrs = [', ] for s in ignored_settings: lines.append(" '{0}',".format(s)) lines.extend([ ']', 'for attr in dir(local_settings):', ' if attr in _local_settings_attrs:', ' continue', ' if not attr.isupper():', ' continue', ' locals()[attr] = getattr(local_settings, attr)', '', ]) return lines ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\n\"\"\"\nMain group for naruto cli\n\"\"\"\nimport io\nimport logging\nimport os\nimport pathlib\nimport shutil\n\nimport click\n\nfrom naruto import NarutoLayer, LayerNotFound\n\nDEV_LOGGER = logging.getLogger(__name__)\nDEFAULT_NARUTO_HOME = pathlib.Path(os.pat...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\"\"\"\nMain group for naruto cli\n\"\"\"\nimport io\nimport logging\nimport os\nimport pathlib\nimport shutil\n\nimport click\n\nfrom naruto import NarutoLayer, LayerNotFound\n\nDEV_LOGGER = logging.getLogger(__name__)\nDEFAULT_NARUTO_HOME = pat...
```python # -*- coding: utf-8 -*- """ Main group for naruto cli """ import io import logging import os import pathlib import shutil import click from naruto import NarutoLayer, LayerNotFound DEV_LOGGER = logging.getLogger(__name__) DEFAULT_NARUTO_HOME = pathlib.Path(os.path.expanduser('~/.naruto')) DEFAULT_LOG_LEVEL = logging.INFO class CLIContext(object): ''' Context for CLI ''' def __init__(self): self.naruto_home = DEFAULT_NARUTO_HOME cli_context = click.make_pass_decorator(CLIContext, ensure=True) @click.group() @click.option( '--naruto-home', default=str(DEFAULT_NARUTO_HOME), type=click.Path( file_okay=False, dir_okay=True, writable=True, readable=True, resolve_path=True, exists=False), help=( 'Set default config directory used to store and retrieve layers. Default: {}'.format( DEFAULT_NARUTO_HOME))) @click.option( '--verbosity', '-V', help='Set verbosity level explicitly (int or CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET)', default=DEFAULT_LOG_LEVEL, type=str) @cli_context def naruto_cli(ctx, naruto_home, verbosity): ''' CLI for naruto ''' try: verbosity = int(verbosity) except ValueError: #Ints and strings are ok pass logging.basicConfig(level=verbosity) DEV_LOGGER.debug('Set log level to %s', verbosity) ctx.naruto_home = pathlib.Path(naruto_home) DEV_LOGGER.debug('Home path is %r', ctx.naruto_home) class _LayerLookup(click.ParamType): ''' Type which loads naruto dir ''' name = 'NarutoDir' def __init__(self, allow_discovery=True): self._allow_discovery = allow_discovery def convert(self, value, param, local_context): ''' Parse Naruto argument ''' DEV_LOGGER.debug('Trying to find root layer for value %r', value) root_spec, _, layer_spec = value.partition(':') cli_context = local_context.ensure_object(CLIContext) if not root_spec and self._allow_discovery: try: layer = NarutoLayer.find_layer_mounted_at_dest(pathlib.Path(os.getcwd())) except LayerNotFound: self.fail( 'Couldn\'t auto-discover layer. ' 'You must in a directory which is a mounted layer for auto-discovery to work') else: if os.sep in root_spec: naruto_root = pathlib.Path(root_spec) else: naruto_root = cli_context.naruto_home / root_spec try: naruto_root, = tuple(naruto_root.iterdir()) except FileNotFoundError: self.fail('Directory {} does not exist'.format(naruto_root)) except ValueError: self.fail('Unexpected number of folders in {}'.format(naruto_root)) try: layer = NarutoLayer(naruto_root) except LayerNotFound: self.fail('{!s} is not a layer.'.format(naruto_root)) if layer_spec: layer = layer.find_layer(layer_spec) DEV_LOGGER.debug('Parsed layer at %r from cli', layer) return layer @naruto_cli.command() @click.argument('name_or_path') @click.option('--description', help='Add description to new naruto layer') @cli_context def create(ctx, name_or_path, description): ''' Create new NarutoLayer ''' if os.sep in name_or_path: path = pathlib.Path(name_or_path) DEV_LOGGER.info('Creating at raw path %r', path) else: home_naruto_dir = ctx.naruto_home if not home_naruto_dir.is_dir(): home_naruto_dir.mkdir() home_naruto_dir = home_naruto_dir.resolve() path = home_naruto_dir / name_or_path if not path.is_dir(): path.mkdir() # Check nothing nasty from user assert path.parent == home_naruto_dir DEV_LOGGER.info('Creating %r in naruto home %r', home_naruto_dir, name_or_path) if len(tuple(path.iterdir())) != 0: raise Exception('Expected create directory {!s} to be empty'.format(path)) NarutoLayer.create(path, description=description) @naruto_cli.command() @cli_context def list_home_layers(ctx): ''' List layers stored in home directory ''' for path in ctx.naruto_home.iterdir(): click.echo(str(path)) ################################################################################################# ## Commands that modify or inspect existing layers ################################################################################################# def _modification_command(fn): ''' Add common options for modification ''' fn = naruto_cli.command()(fn) layer_lookup_help = ( 'This specifies the layer you want to act upon. ' 'If not specified we will try and discover the layer you have currently mounted.') fn = click.option('-l', '--layer', type=_LayerLookup(), default='', help=layer_lookup_help)(fn) return fn class InfoNodeAdapter(object): ''' Adapt NarutoLayer for info printout ''' def __init__(self, layer): self._layer = layer def output(self, io_stream, level, highlight): io_stream.write('{indent}+-- {highlight}{layer!s}{highlight}\n'.format( indent=' ' * level, layer=self._layer, highlight='!!!!' if self._layer in highlight else '')) for child in self._layer: self.__class__(child).output(io_stream, level + 1, highlight) @_modification_command def info(layer): ''' Get info about a layer ''' io_stream = io.StringIO() InfoNodeAdapter(layer.get_root()).output(io_stream, 0, highlight=(layer,)) click.echo(io_stream.getvalue()) @_modification_command @click.argument('mount_dest') def mount(layer, mount_dest): ''' Mount a layer ''' layer.mount(mount_dest) @_modification_command @click.argument('mount_dest') @click.option('--description', help='Add description to new naruto layer') def branch_and_mount(layer, mount_dest, description): ''' Branch a layer and mount at new dest ''' layer.create_child(description=description).mount(mount_dest) @_modification_command def unmount_all(layer): ''' Unmount all uses of this layer ''' layer.unmount_all() @_modification_command def find_mounts(layer): ''' Find where layer is mounted ''' for branch in layer.find_mounted_branches_iter(): click.echo('{branch.path}={branch.permission} at {branch.mount_point}'.format( branch=branch)) @_modification_command @click.option('--no-prompt', default=False, is_flag=True) def delete(layer, no_prompt): ''' Delete a layer ''' if no_prompt: confirm = click.echo else: confirm = lambda message: click.confirm(message, abort=True) if layer.has_children: click.secho( 'WARNING: This layer has {} direct children and a further {} descendants.'.format( len(layer.children), len(layer.descendants)), fg='red') if layer.mounted: confirm( '{} is currently mounted. Must unmount first. Continue?'.format(layer)) layer.unmount_all() confirm( click.style( 'This will irreversible delete {} and all {} descendants. Continue?'.format( layer, len(layer.descendants)), fg='red')) shutil.rmtree(str(layer.path.resolve())) @_modification_command @click.argument('description', default='') def description(layer, description): ''' Get set layer description ''' if description: layer.description = description else: click.echo(layer.description) @_modification_command @click.argument('tags', nargs=-1) def tags(layer, tags): ''' Get set tags ''' if tags: layer.tags = tags else: click.echo(', '.join(layer.tags)) @_modification_command @click.argument('tags', nargs=-1) def add_tags(layer, tags): ''' Add tag to layer''' layer.tags = layer.tags.union(tags) @_modification_command @click.argument('tags', nargs=-1) def remove_tags(layer, tags): ''' Remove tag from layer''' layer.tags = layer.tags.difference(tags) ```
[ { "content": "Reconstruct the code exactly:\n```python\nimport os\nfrom django.test import TestCase\n\nfrom cyder.base.eav.models import Attribute\nfrom cyder.base.utils import copy_tree, remove_dir_contents\nfrom cyder.base.vcs import GitRepo, GitRepoManager, SanityCheckFailure\n\nfrom cyder.core.ctnr.models i...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\nimport os\nfrom django.test import TestCase\n\nfrom cyder.base.eav.models import Attribute\nfrom cyder.base.utils import copy_tree, remove_dir_contents\nfrom cyder.base.vcs import GitRepo, GitRepoManager, SanityCheckFailure\n\nfrom cyder.co...
```python import os from django.test import TestCase from cyder.base.eav.models import Attribute from cyder.base.utils import copy_tree, remove_dir_contents from cyder.base.vcs import GitRepo, GitRepoManager, SanityCheckFailure from cyder.core.ctnr.models import Ctnr from cyder.core.system.models import System from cyder.cydhcp.build.builder import DHCPBuilder from cyder.cydhcp.interface.dynamic_intr.models import DynamicInterface from cyder.cydhcp.network.models import Network, NetworkAV from cyder.cydhcp.range.models import Range DHCPBUILD = { 'stage_dir': '/tmp/cyder_dhcp_test/stage', 'prod_dir': '/tmp/cyder_dhcp_test/prod', 'lock_file': '/tmp/cyder_dhcp_test.lock', 'pid_file': '/tmp/cyder_dhcp_test.pid', 'target_file': 'dhcpd.conf.data', 'check_file': 'dhcpd.conf', 'line_change_limit': 500, 'line_removal_limit': None, 'stop_file': '/tmp/cyder_dhcp_test.stop', 'stop_file_email_interval': None, # never } PROD_ORIGIN_DIR = '/tmp/cyder_dhcp_test/prod_origin' class DHCPBuildTest(TestCase): fixtures = ['dhcp_build_test.json'] def setUp(self): if not os.path.isdir(DHCPBUILD['stage_dir']): os.makedirs(DHCPBUILD['stage_dir']) if not os.path.isdir(DHCPBUILD['prod_dir']): os.makedirs(DHCPBUILD['prod_dir']) remove_dir_contents(DHCPBUILD['prod_dir']) if not os.path.isdir(PROD_ORIGIN_DIR): os.makedirs(PROD_ORIGIN_DIR) remove_dir_contents(PROD_ORIGIN_DIR) mgr = GitRepoManager(config={ 'user.name': 'test', 'user.email': 'test', }) mgr.init(PROD_ORIGIN_DIR, bare=True) mgr.clone(PROD_ORIGIN_DIR, DHCPBUILD['prod_dir']) self.builder = DHCPBuilder(verbose=False, debug=False, **DHCPBUILD) self.builder.repo.commit_and_push( empty=True, message='Initial commit') copy_tree('cyder/cydhcp/build/tests/files/', DHCPBUILD['stage_dir']) super(DHCPBuildTest, self).setUp() def test_build_and_push(self): """Test that adding data triggers a rebuild""" self.builder.build() self.builder.push(sanity_check=False) rev1 = self.builder.repo.get_revision() self.builder.build() self.builder.push(sanity_check=False) rev2 = self.builder.repo.get_revision() self.assertEqual(rev1, rev2) NetworkAV.objects.create( entity=Network.objects.get(network_str='192.168.0.0/16'), attribute=Attribute.objects.get(attribute_type='o', name='routers'), value='192.168.0.1', ) self.builder.build() self.builder.push(sanity_check=False) rev3 = self.builder.repo.get_revision() self.assertNotEqual(rev2, rev3) def test_sanity_check1(self): """Test that the sanity check fails when too many lines are changed""" self.builder.repo.line_change_limit = 1 self.builder.repo.line_removal_limit = 100 self.builder.build() self.builder.push(sanity_check=False) d = DynamicInterface.objects.create( system=System.objects.get(name='Test_system_5'), mac='ab:cd:ef:ab:cd:ef', range=Range.objects.get(name='Test range 1'), ctnr=Ctnr.objects.get(name='Global'), ) self.builder.build() self.assertRaises( SanityCheckFailure, self.builder.push, sanity_check=True) def test_sanity_check2(self): """Test that the sanity check fails when too many lines are removed""" self.builder.repo.line_change_limit = 100 self.builder.repo.line_removal_limit = 1 self.builder.build() self.builder.push(sanity_check=False) DynamicInterface.objects.filter( mac__in=('010204081020', 'aabbccddeeff')).delete() self.builder.build() self.assertRaises( SanityCheckFailure, self.builder.push, sanity_check=True) def test_sanity_check3(self): """Test that the sanity check succeeds when changes are sane""" self.builder.repo.line_change_limit = 100 self.builder.repo.line_removal_limit = 100 self.builder.build() self.builder.push(sanity_check=False) DynamicInterface.objects.filter( mac__in=('010204081020', 'aabbccddeeff')).delete() d = DynamicInterface.objects.create( system=System.objects.get(name='Test_system_5'), mac='ab:cd:ef:ab:cd:ef', range=Range.objects.get(name='Test range 1'), ctnr=Ctnr.objects.get(name='Global'), ) self.builder.build() self.builder.push(sanity_check=True) ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import with_statement\n\nimport sys\nimport tarfile\n\nfrom .Extractor import ArchiveError, CRCError, Extractor\nfrom .misc import encode, fsjoin\n\n\nclass UnTar(Extractor):\n __name__ = \"UnTar\"\n __type__ = \"extractor\"\n __versio...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import with_statement\n\nimport sys\nimport tarfile\n\nfrom .Extractor import ArchiveError, CRCError, Extractor\nfrom .misc import encode, fsjoin\n\n\nclass UnTar(Extractor):\n __name__ = \"UnTar\"\n __type__ = \"extractor...
```python # -*- coding: utf-8 -*- from __future__ import with_statement import sys import tarfile from .Extractor import ArchiveError, CRCError, Extractor from .misc import encode, fsjoin class UnTar(Extractor): __name__ = "UnTar" __type__ = "extractor" __version__ = "0.05" __status__ = "stable" __description__ = """TAR extractor plugin""" __license__ = "GPLv3" __authors__ = [("Walter Purcaro", "vuolter@gmail.com")] VERSION = "%s.%s.%s" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) @classmethod def isarchive(cls, filename): try: return tarfile.is_tarfile(encode(filename)) except: return False @classmethod def find(cls): return sys.version_info[:2] >= (2, 5) def list(self, password=None): with tarfile.open(self.filename) as t: self.files = [fsjoin(self.dest, _f) for _f in t.getnames()] return self.files def verify(self, password=None): try: t = tarfile.open(self.filename, errorlevel=1) except tarfile.CompressionError, e: raise CRCError(e) except (OSError, tarfile.TarError), e: raise ArchiveError(e) else: t.close() def extract(self, password=None): self.verify(password) try: with tarfile.open(self.filename, errorlevel=2) as t: t.extractall(self.dest) self.files = t.getnames() return self.files except tarfile.ExtractError, e: self.log_warning(e) except tarfile.CompressionError, e: raise CRCError(e) except (OSError, tarfile.TarError), e: raise ArchiveError(e) ```
[ { "content": "Recreate the entire code block with identical formatting:\n```python\n################################################################################\n#\n# expr_examples.py\n#\n################################################################################\n\nfrom boole.core.model import *\n ...
[ { "content": "Recreate the entire code block with identical formatting:\n<|memory_start|>```python\n################################################################################\n#\n# expr_examples.py\n#\n################################################################################\n\nfrom boole.core.mode...
```python ################################################################################ # # expr_examples.py # ################################################################################ from boole.core.model import * ################################################################################ # # Examples # ################################################################################ if __name__ == '__main__': print "Built-in language:" print built_in_language.show() print i, j, k = Int('i j k') x = Const('x', Real) y, z = Real('y, z') p, q, r = Bool('p q r') A = BasicType('A') B = BasicType('B') f = (A >> B)('f') g = Const('g', A * A >> B) a1, a2 = A('a1 a2') print 'Global language:' print global_language.show() print def check(e): print 'Expression:', e try: etype = e.etype() except TypeError as err: print 'Type error:', err else: print 'Type:', etype print check(j) check(i + j) check(x) check(x + i) check(i + rr(4.2)) check(f(a1)) check(f(a1, a2)) check(g(a1)) check(g(a1, a2)) check(ii(42)) check(rr(42)) adder = Abs([i, j], i + j) check(adder) check(adder(i, ii(3))) check(plus) check(x ** ii(2) + ii(3) * x + ii(7)) check(j ** ii(2) + ii(3) * j + ii(7)) check(Sum(x ** ii(2), ii(3) * x, ii(7))) check(Sum(j ** ii(2), ii(3) * j, ii(7))) check((x * rr(3.0) >= ii(17)) & (p | q)) check(x + p) check(p & q) check(And(p,q)) check(And(p, q, r)) check(~And(p, ~q, (r | p))) check(Forall(x, x == x)) check(Forall([x, y], x == y)) check(Exists([x, y], (rr(0) < x) & (x + y < rr(3)))) L = Language() set_default_language(L) m, n, p, q = Int('m n p q') prime = Const('Prime', Int >> Bool) even = Const('Even', Int >> Bool) f = (Int >> Int)('f') People = EnumType('People', ['Alice', 'Bob', 'Cathy']) Alice, Bob, Cathy = People.make_constants() x = People('x') print 'Language L:' print L.show() print check (Forall([f, m, n], f(m) == f(n))) def precond(n): return (ii(2) < n) & even(n) def goldbach(n): return Exists([p,q], (precond(n)) >> (prime(p) & prime(q) & (p + q == n))) Goldbach = Forall(n, goldbach(n)) check(Goldbach) check(Forall(x, (x == Alice) | (x == Bob) | (x == Cathy))) check(Forall(x, (x == Alice) | (x == Bob))) ```
[ { "content": "Here is the source code:\n```python\n# This file is part of the GOsa framework.\n#\n# http://gosa-project.org\n#\n# Copyright:\n# (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de\n#\n# See the LICENSE file in the project's top-level directory for details.\n\nimport dbus\nfrom gosa.common.co...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# This file is part of the GOsa framework.\n#\n# http://gosa-project.org\n#\n# Copyright:\n# (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de\n#\n# See the LICENSE file in the project's top-level directory for details.\n\nimport dbus\nfro...
```python # This file is part of the GOsa framework. # # http://gosa-project.org # # Copyright: # (C) 2016 GONICUS GmbH, Germany, http://www.gonicus.de # # See the LICENSE file in the project's top-level directory for details. import dbus from gosa.common.components.dbus_runner import DBusRunner from logging import getLogger NM_STATE_UNKNOWN = 0 NM_STATE_ASLEEP = 10 NM_STATE_DISCONNECTED = 20 NM_STATE_DISCONNECTING = 30 NM_STATE_CONNECTING = 40 NM_STATE_CONNECTED_LOCAL = 50 NM_STATE_CONNECTED_SITE = 60 NM_STATE_CONNECTED_GLOBAL = 70 class Monitor(object): def __init__(self, callback=None): self.__callback = callback self.log = getLogger(__name__) self.__running = False self.__thread = None self.log.info("Initializing network state monitor") # Initialize DBUS dr = DBusRunner.get_instance() self.__bus = dr.get_system_bus() # Register actions to detect the network state self.__upower_actions() self.__network_actions() # Get current state try: proxy = self.__bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties') version = str(iface.Get("org.freedesktop.NetworkManager", "Version")) if tuple(version.split(".")) < ("0", "9"): self.log.warning("network-manager is too old: defaulting to state 'online'") self.__state = True else: # Register actions to detect the network state self.__upower_actions() self.__network_actions() self.__state = iface.Get("org.freedesktop.NetworkManager", "State") in [NM_STATE_CONNECTED_SITE, NM_STATE_CONNECTED_GLOBAL] except: self.log.warning("no network-manager detected: defaulting to state 'online'") self.__state = True def is_online(self): return self.__state def __upower_actions(self): try: proxy = self.__bus.get_object('org.freedesktop.UPower', '/org/freedesktop/UPower') iface = dbus.Interface(proxy, 'org.freedesktop.UPower') iface.connect_to_signal("Sleeping", self.__upower_sleeping) except: self.log.warning("no UPower detected: will not be able to suspend network") def __network_actions(self): try: proxy = self.__bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, 'org.freedesktop.NetworkManager') iface.connect_to_signal("StateChanged", self.__network_state) except: self.log.warning("no network-manager detected: will not be able to suspend or activate network") def __upower_sleeping(self): self.log.info("network down") self.__state = False if self.__callback: self.__callback(False) def __network_state(self, state): if state in [NM_STATE_CONNECTED_SITE, NM_STATE_CONNECTED_GLOBAL]: if self.__state is False: self.log.info("network up") self.__state = True if self.__callback: self.__callback(True) elif self.__state is True: self.log.info("network down") self.__state = False if self.__callback: self.__callback(False) ```
[ { "content": "Recreate the original code text:\n```python\nfrom lib_openmolar.client.db_orm.client_address import AddressRecord, AddressObjects\n\nfrom lib_openmolar.client.db_orm.client_patient import PatientDB, PatientNotFoundError\nfrom lib_openmolar.client.db_orm.client_address import AddressObjects\nfrom l...
[ { "content": "Recreate the original code text:\n<|memory_start|>```python\nfrom lib_openmolar.client.db_orm.client_address import AddressRecord, AddressObjects\n\nfrom lib_openmolar.client.db_orm.client_patient import PatientDB, PatientNotFoundError\nfrom lib_openmolar.client.db_orm.client_address import Addres...
```python from lib_openmolar.client.db_orm.client_address import AddressRecord, AddressObjects from lib_openmolar.client.db_orm.client_patient import PatientDB, PatientNotFoundError from lib_openmolar.client.db_orm.client_address import AddressObjects from lib_openmolar.client.db_orm.client_telephone import TelephoneDB from lib_openmolar.client.db_orm.client_teeth_present import TeethPresentDB from lib_openmolar.client.db_orm.client_static_fills import StaticFillsDB from lib_openmolar.client.db_orm.client_static_crowns import StaticCrownsDB from lib_openmolar.client.db_orm.client_static_roots import StaticRootsDB from lib_openmolar.client.db_orm.client_static_comments import StaticCommentsDB from lib_openmolar.client.db_orm.client_notes_clinical import NotesClinicalDB from lib_openmolar.client.db_orm.client_notes_clerical import NotesClericalDB from lib_openmolar.client.db_orm.client_memo_clinical import MemoClinicalDB from lib_openmolar.client.db_orm.client_memo_clerical import MemoClericalDB from lib_openmolar.client.db_orm.client_perio_bpe import PerioBpeDB from lib_openmolar.client.db_orm.client_perio_pocketing import PerioPocketingDB from lib_openmolar.client.db_orm.client_contracted_practitioner import ContractedPractitionerDB from lib_openmolar.client.db_orm.notes_model import NotesModel from lib_openmolar.client.db_orm.treatment_model import TreatmentModel from lib_openmolar.client.db_orm.patient_model import PatientModel __all__ = [ 'AddressObjects', 'ContractedPractitionerDB', 'MemoClericalDB', 'MemoClinicalDB', 'NotesClericalDB', 'NotesClinicalDB', 'NotesModel', 'PatientDB', 'PerioBpeDB', 'PerioPocketingDB', 'StaticCommentsDB', 'StaticCrownsDB', 'StaticFillsDB', 'StaticRootsDB', 'TeethPresentDB', 'TelephoneDB', 'TreatmentModel', 'PatientModel'] ```
[ { "content": "Repeat the code precisely as written (spacing intact):\n```python\nfrom dataclasses import dataclass\nfrom datetime import date, datetime, timedelta\nfrom operator import itemgetter\nfrom typing import Dict, List, Optional, Set, Tuple\nfrom pytz import timezone\nimport libarchive.public\nimport lo...
[ { "content": "Repeat the code precisely as written (spacing intact):\n<|memory_start|>```python\nfrom dataclasses import dataclass\nfrom datetime import date, datetime, timedelta\nfrom operator import itemgetter\nfrom typing import Dict, List, Optional, Set, Tuple\nfrom pytz import timezone\nimport libarchive.p...
```python from dataclasses import dataclass from datetime import date, datetime, timedelta from operator import itemgetter from typing import Dict, List, Optional, Set, Tuple from pytz import timezone import libarchive.public import logging import ftplib import json import re import os from .const import DIR_DOWNLOAD, DIR_CONVERTED, FTP_ADDR from .util import ensure_dir_exists """ Module containg code responsible for synchornising feeds with the FTP server. Calculates which feeds need to be converted, gets and decompresses required files. Information about specific feeds is passed around with the FileInfo objects. Main functionality is exposed in the sync_feeds() and append_modtimes() procedures. """ _logger = logging.getLogger("WarsawGTFS.downloader") @dataclass class FileInfo: """Info about a source file""" __slots__ = ("path", "version", "modtime", "start", "end", "is_converted") path: str version: str modtime: str start: date end: date is_converted: bool def read_modtimes() -> Dict[str, str]: """Reads {DIR_CONVERTED}/modtimes.json to determine modtimes of currently converted files. """ modtimes_file = os.path.join(DIR_CONVERTED, "modtimes.json") # File doesn't exist: no known files if not os.path.isfile(modtimes_file): return {} with open(str(modtimes_file), mode="r") as f: return json.load(f) def write_modtimes(x: Dict[str, str]): """Writes new content to the {DIR_CONVERTED}/modtimes.json""" with open(os.path.join(DIR_CONVERTED, "modtimes.json"), "w") as f: json.dump(x, f, indent=2) def append_modtimes(new: FileInfo): """Once a converted feed has been written to {DIR_CONVERTED}, call this function. Adds info about just converted feed to {DIR_CONVERTED}/modtimes.json/ """ c = read_modtimes() c[new.version] = new.modtime write_modtimes(c) def which_versions_ok(required_feeds: List[FileInfo], current_modtimes: Dict[str, str]) -> Set[str]: """Returns a set of versions which don't need to bee re-converted.""" ok_versions: Set[str] = set() for i in required_feeds: curr_modtime = current_modtimes.get(i.version, "") if curr_modtime == i.modtime: ok_versions.add(i.version) return ok_versions def remove_unused_converted(versions_ok: Set[str], curr_modtimes: Dict[str, str]): """Removes outdated and unnecessary feeds from {DIR_CONVERTED}, updates {DIR_CONVERTED}/modtimes.json """ _logger.info("removing unnecessary files from DIR_CONVERTED") # Calculate which files to remove all_files = set(os.listdir(DIR_CONVERTED)) expected_files = {"modtimes.json"} expected_files.update(i + ".zip" for i in versions_ok) unexpected_files = all_files.difference(expected_files) # Schedule removal of unexpected files for f in unexpected_files: os.remove(os.path.join(DIR_CONVERTED, f)) # Remove versions from curr_modtimes new_modtimes = {k: v for k, v in curr_modtimes.items() if k in versions_ok} write_modtimes(new_modtimes) def list_files(ftp: ftplib.FTP, max_files: int = 5, start_date: Optional[date] = None) -> List[FileInfo]: """Lists all files required to create a valid feed. At most {max_files} will be returned (defaults to 5). Required files are evaulated starting from start_date, which defaults to 'today' in Warsaw. """ _logger.info("calculating required files") files = ftp.mlsd() fn_match = re.compile(r"^RA\d{6}\.7z") # Ignore non-schedule files & sort files by date files = sorted( filter(lambda i: fn_match.fullmatch(str(i[0])), files), key=itemgetter(0) ) # User hasn't specified when the feed should be valid: start from 'today' (in Warsaw) if start_date is None: start_date = datetime.now(timezone("Europe/Warsaw")).date() active_files: List[FileInfo] = [] # Check which files should be converted for idx, (file_name, file_meta) in enumerate(files): file_start = datetime.strptime(file_name, "RA%y%m%d.7z").date() # Get last day when file is active (next file - 1 day) try: file_end = datetime.strptime(str(files[idx + 1][0]), "RA%y%m%d.7z").date() file_end -= timedelta(days=1) except IndexError: file_end = date.max # We don't need anything for previous dates if file_end < start_date: continue active_files.append(FileInfo( path=file_name, version=file_name[:-3], modtime=file_meta["modify"], start=file_start, end=file_end, is_converted=False )) # Limit files to max_files active_files = active_files[:max_files] # Last file shouldn't have an end_date active_files[-1].end = date.max return active_files def list_single_file(ftp: ftplib.FTP, for_day: Optional[date] = None) -> FileInfo: """Returns FileInfo about file valid in the given day (or today in Warsaw)""" # Variables from loop file_name = "" file_meta = {} file_start = date.min # List files from FTP files = ftp.mlsd() fn_match = re.compile(r"^RA\d{6}\.7z") # Ignore non-schedule files & sort files by date files = sorted( filter(lambda i: fn_match.fullmatch(str(i[0])), files), key=itemgetter(0) ) # Ensure for_day is not None if for_day is None: for_day = datetime.now(timezone("Europe/Warsaw")).date() # Iterate over files and to get one valid for `for_day` max_idx = len(files) - 1 for idx, (file_name, file_meta) in enumerate(files): file_start = datetime.strptime(file_name, "RA%y%m%d.7z").date() # If user requested file before the very first file - raise an error if idx == 0 and for_day < file_start: raise FileNotFoundError(f"No files for day {for_day.strftime('%Y-%m-%d')}") # Last file always matches if idx != max_idx: next_file_start = datetime.strptime(str(files[idx + 1][0]), "RA%y%m%d.7z").date() # Next file starts past for_day, so current file matches - break out of the loop if next_file_start > for_day: break # guard against no matches if not file_name: raise FileNotFoundError(f"Error matching files for day {for_day.strftime('%Y-%m-%d')}") # file_path, file_start and file_meta now contain info about matched file return FileInfo( path=file_name, version=file_name[:-3], modtime=file_meta["modify"], start=file_start, end=date.max, is_converted=False ) def get_and_decompress(ftp: ftplib.FTP, i: FileInfo): """Requests given file from the FTP server, and decompresses the included TXT file. Provided FileInfo object will be modified as such: - finfo.path points to the decompressed txt file - finfo.is_converted is False """ # Download the 7z file into DIR_DOWNLOAD archive_local_path = os.path.join(DIR_DOWNLOAD, i.path) txt_local_path = os.path.join(DIR_DOWNLOAD, (i.version + ".txt")) _logger.debug(f"Downloading file for version {i.version}") with open(archive_local_path, mode="wb") as f: ftp.retrbinary("RETR " + str(i.path), f.write) # Open the 7z file and decompress the txt file _logger.debug(f"Decompressing file for version {i.version}") with libarchive.public.file_reader(str(archive_local_path)) as arch: # Iterate over each file inside the archive for arch_file in arch: name = arch_file.pathname.upper() # Assert the file inside the archive is the TXT file we're looking for if name != f"{i.version}.TXT": continue # Open the target txt file with open(txt_local_path, mode="wb") as f: # Decompress the TXT file block by block and save it to the reader for block in arch_file.get_blocks(): f.write(block) # only one TXT file should be inside the archive break else: raise FileNotFoundError(f"no schedule file for ver {i.version!r} found inside " f"archive {i.path!r}") # Modify given FileInfo i.path = txt_local_path i.is_converted = False # Remove downloaded archive os.remove(archive_local_path) def mark_as_converted(i: FileInfo): """Modifies given FileInfo object to mark it as already-converted. finfo.is_converted will be Ture, and finfo.path will point to the GTFS .zip. """ i.path = os.path.join(DIR_CONVERTED, (i.version + ".zip")) i.is_converted = True def sync_files(max_files: int = 5, start_date: Optional[date] = None, reparse_all: bool = False) \ -> Tuple[List[FileInfo], bool]: """Manages required source feeds. 1. Lists required source feeds 2. Determines which feeds were already converted. 3. Removes non-required and outdated feeds 4. Downloads new/changed source feeds amd extarcts them. Returns 2 values: 1. List of *all* required feeds 2. Whether any new files were downloaded Please call append_modtimes for each sucessfuly converted file. """ # Ensure DIR_DOWNLOAD and DIR_CONVERTED exist ensure_dir_exists(DIR_DOWNLOAD, clear=True) ensure_dir_exists(DIR_CONVERTED, clear=False) with ftplib.FTP(FTP_ADDR) as ftp: ftp.login() # List source feeds required_feeds = list_files(ftp, max_files, start_date) # Determine which feeeds were already converted if not reparse_all: current_modtimes = read_modtimes() converted_versions = which_versions_ok(required_feeds, current_modtimes) else: current_modtimes = {} converted_versions = set() # Check if new files will be downloaded new_files = sum(1 for i in required_feeds if i.version not in converted_versions) # Clean-up {DIR_CONVERTED} if new_files > 0: _logger.info(f"new files to download&convert: {new_files}") remove_unused_converted(converted_versions, current_modtimes) else: _logger.info("no new files") # Download txt files or mark feeds as converted for i in required_feeds: if i.version in converted_versions: mark_as_converted(i) else: get_and_decompress(ftp, i) return required_feeds, (new_files > 0) def sync_single_file(valid_day: Optional[date] = None) -> FileInfo: """Manages required feed to create schedules for given day. Downloads and decompresses detected required file. Returns the FileInfo object containing data bout the required feed. Call append_modtimes after successfuly converting this feed. """ # Ensure DIR_DOWNLOAD and DIR_CONVERTED exist ensure_dir_exists(DIR_DOWNLOAD, clear=True) with ftplib.FTP(FTP_ADDR) as ftp: ftp.login() # Check which file to download finfo = list_single_file(ftp, valid_day) # Download said file _logger.info(f"Downloading feed for {finfo.version}") get_and_decompress(ftp, finfo) return finfo ```
[ { "content": "Here is the script:\n```python\n#!/usr/bin/env python\n#\n# Kenwood Morse Beacon - turns a Kenwood TS-480 into a heli beacon\n#\n# Copyright (C) 2016 by Mir Rodriguez <mir.rodriguez@greenpeace.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms ...
[ { "content": "Here is the script:\n<|memory_start|>```python\n#!/usr/bin/env python\n#\n# Kenwood Morse Beacon - turns a Kenwood TS-480 into a heli beacon\n#\n# Copyright (C) 2016 by Mir Rodriguez <mir.rodriguez@greenpeace.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it ...
```python #!/usr/bin/env python # # Kenwood Morse Beacon - turns a Kenwood TS-480 into a heli beacon # # Copyright (C) 2016 by Mir Rodriguez <mir.rodriguez@greenpeace.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ MY Esperanza heli beacon Turns the Kenwood TS-480 into a morse code NDB Works with a Bendix King KR87m which goes up to 1799. Kenwood can transmit from 1705 kHz Transmits the ship's call sign in CW in a loop for a defined period Connect the TS-480 to serial port usage: python heli_beacon.py {timer in minutes} Example: python heli_beacon.py 30 by mir - written on the Indian Ocean 2016.04.19 """ from __future__ import print_function import serial import sys import time import os serialport = '/dev/ttyUSB0' serialspeed = 38400 freq = '1711' # Beacon frequency in KHz - remember to tune antenna first! power = '10' # Transmitter Power in W callsign = 'PD6464' ser = serial.Serial(serialport, serialspeed, timeout=1) def stopbeacon(): ser.write('KY' + (' ' * 25) + ';') # Clears morse cache and stops transmitting ser.write('PS9;\n') # Puts transceiver on standby ser.close() def main(argv=None): if argv is None: argv = sys.argv timermins = sys.argv[1] timersecs = float(timermins) * 60 start = time.time() print ('Beacon timer set to ' + str(timersecs) + ' seconds\n') print ('Callsign: ' + callsign + '\n') print ('Turning transceiver on\n') ser.write('PS;') # Checks transceiver power status status = ser.read(4) while status != 'PS1;': # Iterates until transceiver is on ser.write(';;;;PS1;\n') # Tries to turn transceiver on ser.write('PS;') status = ser.read(4) print ('Transceiver is on!\n') time.sleep(2) # Waits for transceiver to boot ser.write('FA0000' + freq + '000;') # sets frequency # s = 'Freq: '+ ser.read(2) + '\n' ser.write('AN1;') # sets antenna # s += 'Antenna: ' + ser.read(2) + '\n' ser.write('EX01300003;') # Sets sidetone volume # s += 'Sidetone:' + ser.read(2) + '\n' ser.write('KS010;') # Sets 10 words per minute #s += 'Speed:' + ser.read(2) + '\n' ser.write('PC0'+power+';') # Sets 10 KW power #s += 'Power:' + ser.read(2) + '\n' ser.write('MD3;') # Sets CW mode #s += 'Mode:' + ser.read(2) + '\n' # print (s) # uncomment these and above for debugging print ('Starting beacon\n') elapsed = int(time.time() - start) current = elapsed status = 'start' while elapsed < timersecs: ser.write('KY;') status = ser.read(4) elapsed = int(time.time() - start) remaining = str(elapsed - int(timersecs)) print ('Timer: ' + remaining, end='s \r') if status == 'KY1;': continue ser.write('KY ' + ((callsign + ' ') * 3) + ' ;') response = ser.read(2) ser.write('KY;') status = ser.read(4) stopbeacon() print ('End beacon') if __name__ == '__main__': try: main() except KeyboardInterrupt: print ('\nInterrupted!') stopbeacon() try: sys.exit(0) except SystemExit: os._exit(0) ```
[ { "content": "Provide an exact copy of the source code:\n```python\n# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '/home/tedlaz/python_work/meta_manager/fmeta_main2.ui'\n#\n# Created by: PyQt4 UI code generator 4.11.4\n#\n# WARNING! All changes made in this file will be lost!\n...
[ { "content": "Provide an exact copy of the source code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file '/home/tedlaz/python_work/meta_manager/fmeta_main2.ui'\n#\n# Created by: PyQt4 UI code generator 4.11.4\n#\n# WARNING! All changes made in this file...
```python # -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/tedlaz/python_work/meta_manager/fmeta_main2.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.tab = QtGui.QTabWidget(self.centralwidget) self.tab.setObjectName(_fromUtf8("tab")) self.tab_tables = QtGui.QWidget() self.tab_tables.setObjectName(_fromUtf8("tab_tables")) self.verticalLayout = QtGui.QVBoxLayout(self.tab_tables) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.tableView = QtGui.QTableView(self.tab_tables) self.tableView.setObjectName(_fromUtf8("tableView")) self.verticalLayout.addWidget(self.tableView) self.tab.addTab(self.tab_tables, _fromUtf8("")) self.tab_queries = QtGui.QWidget() self.tab_queries.setObjectName(_fromUtf8("tab_queries")) self.tab.addTab(self.tab_queries, _fromUtf8("")) self.verticalLayout_2.addWidget(self.tab) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25)) self.menubar.setObjectName(_fromUtf8("menubar")) self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName(_fromUtf8("menuFile")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.actionOpen = QtGui.QAction(MainWindow) self.actionOpen.setObjectName(_fromUtf8("actionOpen")) self.actionNew = QtGui.QAction(MainWindow) self.actionNew.setObjectName(_fromUtf8("actionNew")) self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionNew) self.menubar.addAction(self.menuFile.menuAction()) self.retranslateUi(MainWindow) self.tab.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Meta Manager", None)) self.tab.setTabText(self.tab.indexOf(self.tab_tables), _translate("MainWindow", "Πίνακες", None)) self.tab.setTabText(self.tab.indexOf(self.tab_queries), _translate("MainWindow", "Queries", None)) self.menuFile.setTitle(_translate("MainWindow", "file", None)) self.actionOpen.setText(_translate("MainWindow", "open", None)) self.actionNew.setText(_translate("MainWindow", "New", None)) ```
[ { "content": "Here is a code file:\n```python\nimport socket\nimport sys\nimport RPi.GPIO as gpio\nimport time\n\nHOST = '192.168.0.9' # RC카 라즈베리파이 IP값으로 변경필요\nPORT = 10000\nTIME_OUT = 100\n\n#Motor 1 GPIO Pin\nIC1A = 22\nIC2A = 27\n\n#Motor 2 GPIO Pin\nIC3A = 4\nIC4A = 17\n\ngpio.cleanup()\n\ngpio.setmode(gpio...
[ { "content": "Here is a code file:\n<|memory_start|>```python\nimport socket\nimport sys\nimport RPi.GPIO as gpio\nimport time\n\nHOST = '192.168.0.9' # RC카 라즈베리파이 IP값으로 변경필요\nPORT = 10000\nTIME_OUT = 100\n\n#Motor 1 GPIO Pin\nIC1A = 22\nIC2A = 27\n\n#Motor 2 GPIO Pin\nIC3A = 4\nIC4A = 17\n\ngpio.cleanup()\n\ng...
```python import socket import sys import RPi.GPIO as gpio import time HOST = '192.168.0.9' # RC카 라즈베리파이 IP값으로 변경필요 PORT = 10000 TIME_OUT = 100 #Motor 1 GPIO Pin IC1A = 22 IC2A = 27 #Motor 2 GPIO Pin IC3A = 4 IC4A = 17 gpio.cleanup() gpio.setmode(gpio.BCM) #Motor Pin Setup gpio.setup(IC1A, gpio.OUT) gpio.setup(IC2A, gpio.OUT) gpio.setup(IC3A, gpio.OUT) gpio.setup(IC4A, gpio.OUT) # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = (HOST, PORT) print >>sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) def main(): # Listen for incoming connections sock.listen(1) while True: # Wait for a connection print >>sys.stderr, 'waiting for a connection' connection, client_address = sock.accept() # Timeout connection.settimeout(TIME_OUT) try: print >>sys.stderr, 'connection from', client_address # Receive the data in small chunks and retransmit it while True: data = connection.recv(16) print >>sys.stderr, 'received "%s"' % data if data: pdata = parsing_data(data) print 'Go %s' % pdata else: print >>sys.stderr, 'no more data from', client_address break except socket.timeout: print 'timeout error : "%d" secs' % TIME_OUT connection.close() finally: # Clean up the connection connection.close() def parsing_data(data) : data = data.lower() print 'receive data : %s' % data try: intindex = data.index("rcpi") getStr = data.replace("rcpi","") getStr = getStr.strip() print >>sys.stderr, 'Receive Key : "%s"' % getStr if ( getStr == 'ff' ): print 'Move Forward / "%d" speed' elif ( getStr == 'bb' ): print 'Move Backward / "%d" speed' elif ( getStr == 'll' ): print 'Turn Left' elif ( getStr == 'rr' ): print 'Turn Right' elif ( getStr == 'bf' ): print 'stop For/Backward' elif ( getStr == 'rl' ): print 'stop Left/Right' elif ( getStr == 'ee' ): print 'toggle Motor Enable' elif ( getStr == 'dd' ): print 'toggle Motor Disable' else: print 'unknown commend' return 'u' run_motor(getStr) except ValueError: return 'a' def run_motor(rcvStr): if ( rcvStr == 'rr' ): print 'GPIO Turn Right' gpio.output(IC1A, gpio.LOW) gpio.output(IC2A, gpio.HIGH) elif ( rcvStr == 'll' ): print 'GPIO Turn Left' gpio.output(IC1A, gpio.HIGH) gpio.output(IC2A, gpio.LOW) elif ( rcvStr == 'rl' ): print 'GPIO Front Wheel Zero' gpio.output(IC1A, gpio.LOW) gpio.output(IC2A, gpio.LOW) elif ( rcvStr == 'ff' ): print 'GPIO Forward' gpio.output(IC3A, gpio.LOW) gpio.output(IC4A, gpio.HIGH) elif ( rcvStr == 'bb' ): print 'GPIO Backward' gpio.output(IC3A, gpio.HIGH) gpio.output(IC4A, gpio.LOW) elif ( rcvStr == 'bf' ): print 'GPIO Stop Back Wheel' gpio.output(IC3A, gpio.LOW) gpio.output(IC4A, gpio.LOW) if __name__ == "__main__": main() ```
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n```python\nimport os\nimport sys\n\n\nclass ConfigHelper():\n \"\"\"\n Manage all configuration information for the application\n \"\"\"\n def __init__(self):\n TRUE = \"True\"\n FALSE = \"Fals...
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n<|memory_start|>```python\nimport os\nimport sys\n\n\nclass ConfigHelper():\n \"\"\"\n Manage all configuration information for the application\n \"\"\"\n def __init__(self):\n TRUE = \"True\"\n ...
```python import os import sys class ConfigHelper(): """ Manage all configuration information for the application """ def __init__(self): TRUE = "True" FALSE = "False" ERROR = 1 self.halo_key = os.getenv("HALO_API_KEY") self.halo_secret = os.getenv("HALO_API_SECRET_KEY") # get the results directory and create it if it does not exist scan_results_directory = os.environ["SCAN_RESULTS_DIRECTORY"] = \ "/tmp/scan_results/" path_exists = os.path.exists(scan_results_directory) if not path_exists: try: os.mkdir(scan_results_directory) path_exists = os.path.exists(scan_results_directory) except OSError: pass days_for_scan_age = os.environ["DAYS_FOR_SCAN_AGE"] = "0" days_for_scan_age = int(days_for_scan_age) days_string_is_int_value = isinstance(days_for_scan_age, int) os.environ["HALO_SERVER_GROUP"] = "Git" scan_examples = os.environ["SCAN_EXAMPLES"] = "False" heartbeat_interval = os.environ["HEARTBEAT_INTERVAL"] = "60" heartbeat_interval = int(heartbeat_interval) hi_string_is_int_value = isinstance(heartbeat_interval, int) # for unit tests Travis populates the IP server_ip = "<server_ip>" os.environ["SERVER_IP"] = server_ip unit_tests = os.environ["UNIT_TESTS"] = "no_unit_tests" # NOQA if self.halo_key is None or self.halo_secret is None \ or not os.path.exists(scan_results_directory) or not path_exists \ or days_string_is_int_value == "False" \ or hi_string_is_int_value == "False" \ or scan_examples != TRUE and scan_examples != FALSE: print "Configuration validation failed... exiting...\n" sys.exit(ERROR) ```
[ { "content": "Repeat the code exactly:\n```python\n#!/usr/bin/env python\n\nfrom scheduler.job import *\nfrom scheduler.fcfs import *\nfrom scheduler.sjf import *\nfrom scheduler.srjf import *\nfrom scheduler.priority import *\nfrom scheduler.preemptive_priority import *\nfrom scheduler.round_robin import *\n\n...
[ { "content": "Repeat the code exactly:\n<|memory_start|>```python\n#!/usr/bin/env python\n\nfrom scheduler.job import *\nfrom scheduler.fcfs import *\nfrom scheduler.sjf import *\nfrom scheduler.srjf import *\nfrom scheduler.priority import *\nfrom scheduler.preemptive_priority import *\nfrom scheduler.round_ro...
```python #!/usr/bin/env python from scheduler.job import * from scheduler.fcfs import * from scheduler.sjf import * from scheduler.srjf import * from scheduler.priority import * from scheduler.preemptive_priority import * from scheduler.round_robin import * from PyQt4 import QtCore, QtGui from random import randint import copy import time class JobWidget(QtGui.QLabel): # todo add colors def __init__(self, text=''): QtGui.QLabel.__init__(self, None) self.setText(text) self.setFrameShape(QtGui.QFrame.Box) self.setWordWrap(True) self.setIndent(0) self.setFont(QtGui.QFont("Times", 20))#, QtGui.QFont.Bold)) #self.setScaledContents(True) #def __copy__(self): # #http://stackoverflow.com/questions/1500718/what-is-the-right-way-to-override-the-copy-deepcopy-operations-on-an-object-in-p # newone = type(self)() # newone.__dict__.update(self.__dict__) # return newone # need to be improved or changed # TODO: reimplement this in QGraphics scene and view class JobListWidget(QtGui.QScrollArea): def __init__(self, title='', allowDuplicates = False, spacing = 5): QtGui.QLabel.__init__(self, None) self.widget = QtGui.QWidget() self.titleLbl = QtGui.QLabel(title) self.hbox = QtGui.QHBoxLayout() self.hbox.setSpacing(spacing) self.vbox = QtGui.QVBoxLayout() self.vbox.addWidget(self.titleLbl) self.vbox.addLayout(self.hbox) self.widget.setLayout(self.vbox) self.allowDuplicates = allowDuplicates self.widgets = [] self.hbox.addStretch() # last one self.setWidgetResizable(True) self.setWidget(self.widget) def addWidget(self, widget, sub_text=None): if not self.allowDuplicates and self.hbox.indexOf(widget) != -1: return if self.allowDuplicates: #widget = copy.copy(widget) #widget = copy.deepcopy(widget) widget = JobWidget(widget.text()) if sub_text: widget.setText(widget.text() + '<sub>%s</sub>' % sub_text) self.widgets.append(widget) self.hbox.insertWidget(self.hbox.count() - 1, widget) widget.show() def removeWidget(self, widget): #widget.clearLayout() if self.hbox.indexOf(widget) != -1: self.hbox.removeWidget(widget) def clear(self): # delete error causes some error if called agian # figure it out for widget in self.widgets: try: widget.deleteLater() except: continue class SchedulerWidget(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self, None) self.resize(700, 500) self.setWindowTitle('CPU Scheduling Simulator') self.sch = None self.jobs = [] self.init_ui() def init_ui(self): self.timer = QtCore.QTimer() self.timer.setInterval(1000) # one second self.timer.timeout.connect(self.tick) self.numLbl = QtGui.QLabel('No. of jobs: ') self.jobs_no = QtGui.QSpinBox() self.jobs_no.setValue(5) self.jobs_no.valueChanged[int].connect(lambda v: self.generateJobs()) self.generateBtn = QtGui.QPushButton('&Generate') self.startBtn = QtGui.QPushButton('&Start') self.startBtn.setEnabled(False) self.stopBtn = QtGui.QPushButton('&Stop') self.stopBtn.setEnabled(False) self.pauseBtn = QtGui.QPushButton('&Pause') self.pauseBtn.clicked.connect(self.pauseSimu) self.resumeBtn = QtGui.QPushButton('&Resume') self.resumeBtn.clicked.connect(self.resumeSimu) self.pauseBtn.setEnabled(False) self.resumeBtn.setVisible(False) self.generateBtn.clicked.connect(self.generateJobs) self.startBtn.clicked.connect(self.startSimu) self.stopBtn.clicked.connect(self.stopSimu) self.speedLbl = QtGui.QLabel('Speed: ') self.speedSlider = QtGui.QSlider(QtCore.Qt.Horizontal) self.speedSlider.setMinimum(0) self.speedSlider.setMaximum(10) self.speedSlider.setValue(1) self.speedSlider.valueChanged[int].connect(lambda v: self.timer.setInterval(v*1000)) self.timeLbl = QtGui.QLabel('Time: ') self.controlLayout = QtGui.QHBoxLayout() self.controlLayout.addWidget(self.numLbl) self.controlLayout.addWidget(self.jobs_no) self.controlLayout.addWidget(self.generateBtn) self.controlLayout.addWidget(self.startBtn) self.controlLayout.addWidget(self.stopBtn) self.controlLayout.addWidget(self.pauseBtn) self.controlLayout.addWidget(self.resumeBtn) self.controlLayout.addWidget(self.speedLbl) self.controlLayout.addWidget(self.speedSlider) self.controlLayout.addWidget(self.timeLbl) self.algorithms = [FCFS, SJF, SRJF, Priority, PreemptivePriority, RoundRobin] self.algoLabel = QtGui.QLabel('Algorithm: ') self.comoboAlgo = QtGui.QComboBox() self.comoboAlgo.activated[int].connect(self.algoChoosed) self.timeSliceLabel = QtGui.QLabel('Time Slice: ') self.timeSliceSpin = QtGui.QSpinBox() self.timeSliceSpin.setMinimum(1) self.timeSliceSpin.setValue(1) self.timeSliceLabel.setVisible(False) self.timeSliceSpin.setVisible(False) self.comoboAlgo.setCurrentIndex(0) self.algoChoosed(0) self.comoboAlgo.addItems(['FCFS', 'SJF', 'SRJF', 'Priority', 'Preemptive Priority', 'RoundRobin']) self.algoLayout = QtGui.QHBoxLayout() self.algoLayout.addWidget(self.algoLabel) self.algoLayout.addWidget(self.comoboAlgo) self.algoLayout.addWidget(self.timeSliceLabel) self.algoLayout.addWidget(self.timeSliceSpin) self.algoLayout.addStretch() self.aboutBtn = QtGui.QPushButton('&About') self.aboutBtn.clicked.connect(self.aboutMsg) self.algoLayout.addWidget(self.aboutBtn) # control algo layout self.calgoLayout = QtGui.QVBoxLayout() self.calgoLayout.addLayout(self.controlLayout) self.calgoLayout.addLayout(self.algoLayout) self.calgoLayout.addStretch() self.jobsTable = QtGui.QTableWidget(0, 3) self.generateJobs() # calgoLayout and table self.splitter = QtGui.QSplitter(QtCore.Qt.Vertical) self.calgoWidget = QtGui.QWidget() self.calgoWidget.setLayout(self.calgoLayout) self.splitter.addWidget(self.calgoWidget) self.splitter.addWidget(self.jobsTable) self.new_jobs = JobListWidget('New') self.ready_jobs = JobListWidget('Ready') self.running_jobs = JobListWidget('Running', True, 0) self.terminated_jobs = JobListWidget('Terminated') self.avgTurnaround = QtGui.QLabel('Average Turnaround time: ') self.avgWaiting = QtGui.QLabel('Average Waiting time: ') self.cpuUtilization = QtGui.QLabel('CPU Utilization: ') self.mainLayout = QtGui.QVBoxLayout() self.mainLayout.addWidget(self.splitter) self.mainLayout.addWidget(self.new_jobs) self.mainLayout.addWidget(self.ready_jobs) self.mainLayout.addWidget(self.running_jobs) self.mainLayout.addWidget(self.terminated_jobs) self.mainLayout.addStretch() self.mainLayout.addWidget(self.avgTurnaround) self.mainLayout.addWidget(self.avgWaiting) self.mainLayout.addWidget(self.cpuUtilization) self.setLayout(self.mainLayout) def tick(self): if self.sch: # to get the ready ones #self.sch.get_ready_jobs(self.sch.current_time) self.report_scheduler(self.sch) #time.sleep(0.3) self.timeLbl.setText('Time: %d' % self.sch.current_time) if self.sch.isFinished(): self.stopSimu() self.avgTurnaround.setText('Average Turnaround time: %f' % self.sch.avg_turnaround_time()) self.avgWaiting.setText('Average Waiting time: %f' % self.sch.avg_waiting_time()) self.cpuUtilization.setText('CPU Utilization: %f' % (self.sch.cpu_util() * 100.0) + '%') else: self.sch.tick() def report_scheduler(self, sch): for job in sch.ready: self.add_to_ready(job.widget) if sch.current_job: self.add_to_running(sch.current_job.widget) for job in sch.terminated: self.add_to_terminated(job.widget) #if self.sch.isIdle(): # self.add_to_running(JobWidget(' ')) def add_to_new(self, widget): ### self.new_jobs.addWidget(widget) def add_to_ready(self, widget): self.new_jobs.removeWidget(widget) self.ready_jobs.addWidget(widget) def add_to_running(self, widget): #widget.setText(widget.text() + ) self.ready_jobs.removeWidget(widget) self.running_jobs.addWidget(widget, self.sch.current_time) def add_to_terminated(self, widget): self.terminated_jobs.addWidget(widget) def job_status_changed(self, job, new_status): if new_status == Status.Ready: self.add_to_ready(job.widget) elif new_status == Status.Running: self.add_to_running(job.widget) elif new_status == Status.Terminated: self.add_to_terminated(job.widget) def algoChoosed(self, index): self.algo = self.algorithms[index] if self.algo == RoundRobin: self.timeSliceLabel.setVisible(True) self.timeSliceSpin.setVisible(True) else: self.timeSliceLabel.setVisible(False) self.timeSliceSpin.setVisible(False) def generateJobs(self): self.startBtn.setEnabled(True) n = self.jobs_no.value() if n > 0: self.jobsTable.clear() self.jobsTable.setRowCount(n) for r in range(0, self.jobsTable.rowCount()): self.jobsTable.setItem(r, 0, QtGui.QTableWidgetItem(str(randint(0, n)))) self.jobsTable.setItem(r, 1, QtGui.QTableWidgetItem(str(randint(1, n)))) self.jobsTable.setItem(r, 2, QtGui.QTableWidgetItem(str(randint(0, n)))) self.jobsTable.setVerticalHeaderLabels(['P%d'%p for p in range(1, n+1)]) self.jobsTable.setHorizontalHeaderLabels(['Arrival Time', 'Bursts', 'Priority']) def startSimu(self): self.new_jobs.clear() self.ready_jobs.clear() self.running_jobs.clear() self.terminated_jobs.clear() self.avgTurnaround.setText('Average Turnaround time: ') self.avgWaiting.setText('Average Waiting time: ') self.jobs = [] for r in range(0, self.jobsTable.rowCount()): arrival_time = int(self.jobsTable.item(r, 0).text()) brusts = int(self.jobsTable.item(r, 1).text()) priority = int(self.jobsTable.item(r, 2).text()) job = Job(bursts=brusts, arrival_time=arrival_time, priority=priority, job_id=r+1) widget = JobWidget('P%d' % job.job_id) job.widget = widget self.jobs.append(job) self.add_to_new(job.widget) #self.sch = FCFS(self.jobs) if self.algo == RoundRobin: self.sch = RoundRobin(self.timeSliceSpin.value(), self.jobs) else: self.sch = self.algo(self.jobs) self.stopBtn.setEnabled(True) self.pauseBtn.setEnabled(True) self.startBtn.setEnabled(False) self.timer.start() def stopSimu(self): self.timer.stop() self.stopBtn.setEnabled(False) self.pauseBtn.setEnabled(False) self.startBtn.setEnabled(True) self.resumeBtn.setVisible(False) self.pauseBtn.setVisible(True) def pauseSimu(self): self.timer.stop() self.pauseBtn.setVisible(False) self.resumeBtn.setVisible(True) def resumeSimu(self): self.timer.start() self.pauseBtn.setVisible(True) self.resumeBtn.setVisible(False) def aboutMsg(self): QtGui.QMessageBox.about(self, 'About', 'CPU Scheduling Simulator<br>Operating Systems Project<br>By: Abdelrahman Ghanem') if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) en_eg= QtCore.QLocale(QtCore.QLocale.English, QtCore.QLocale.Egypt) QtCore.QLocale.setDefault(en_eg) mwin = SchedulerWidget() mwin.show() sys.exit(app.exec_()) ```
[ { "content": "```python\nimport os\nimport os.path\nimport sys\n\nfrom fabric import Connection, Config\nfrom click import echo, secho\n\nfrom drift.management import get_ec2_instances\nfrom drift.utils import get_config\n\nEC2_USERNAME = 'ubuntu'\nUWSGI_LOGFILE = \"/var/log/uwsgi/uwsgi.log\"\n\n\ndef get_optio...
[ { "content": "<|memory_start|>```python\nimport os\nimport os.path\nimport sys\n\nfrom fabric import Connection, Config\nfrom click import echo, secho\n\nfrom drift.management import get_ec2_instances\nfrom drift.utils import get_config\n\nEC2_USERNAME = 'ubuntu'\nUWSGI_LOGFILE = \"/var/log/uwsgi/uwsgi.log\"\n\...
```python import os import os.path import sys from fabric import Connection, Config from click import echo, secho from drift.management import get_ec2_instances from drift.utils import get_config EC2_USERNAME = 'ubuntu' UWSGI_LOGFILE = "/var/log/uwsgi/uwsgi.log" def get_options(parser): parser.add_argument( "--ip", help="Deploy to a certain instance instead of across the cluster") parser.add_argument( "--stream", help="Stream live logs from the host (requires the --host argument)", action="store_true") parser.add_argument( "--host", help="Pick a single host to view logs from", default=None) parser.add_argument( "--grep", help="Grep pattern to search for", default=None) def run_command(args): conf = get_config() if not conf.deployable: secho("Deployable '{}' not found in config '{}'.".format( conf.drift_app['name'], conf.domain['domain_name']), fg="red") sys.exit(1) deployable_name = conf.deployable['deployable_name'] tier = conf.tier['tier_name'] region = conf.tier['aws']['region'] ssh_key_name = conf.tier['aws']['ssh_key'] ssh_key_file = os.path.expanduser('~/.ssh/{}.pem'.format(ssh_key_name)) echo() echo("*** VIEWING LOGS FOR SERVICE '{}' / TIER '{}' IN REGION '{}'\n".format(deployable_name, tier, region)) instances = get_ec2_instances(region, tier, deployable_name) if args.host: instances = [i for i in instances if i.private_ip_address == args.host] echo("Gathering logs from '%s' on the following instances:" % UWSGI_LOGFILE) for inst in instances: echo(" %s" % inst.private_ip_address) if args.stream and len(instances) > 1: secho("The --stream argument can only be used on a single host. Please use --host to pick one", fg="red") return for ec2 in instances: ip_address = ec2.private_ip_address echo("*** Logs in {} on {}...".format(UWSGI_LOGFILE, ip_address)) if not args.stream: conf = Config() conf.connect_kwargs.key_filename = ssh_key_file conn = Connection(host=ip_address, user=EC2_USERNAME, config=conf) cmd = "sudo tail {} -n 100".format(UWSGI_LOGFILE) if args.grep: cmd += " | grep {}".format(args.grep) conn.run(cmd) echo() else: import paramiko import select client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) key_path = os.path.expanduser(ssh_key_file) client.connect(ip_address, username=EC2_USERNAME, key_filename=key_path) channel = client.get_transport().open_session() grep_cmd = "" if args.grep: grep_cmd = " | grep --line-buffered {}".format(args.grep) channel.exec_command("sudo tail -f {}{}".format(UWSGI_LOGFILE, grep_cmd)) while True: if channel.exit_status_ready(): break rl, wl, xl = select.select([channel], [], [], 0.0) if len(rl) > 0: sys.stdout.write(channel.recv(1024)) ```
[ { "content": "Here is a code file:\n```python\nimport os\nimport sys\nimport shutil\nimport glob\nfrom os.path import join, realpath, dirname, normpath, normcase\nfrom operator import methodcaller\ntry:\n from urlparse import urlparse\nexcept ImportError:\n from urllib.parse import urlparse\n\nimport clic...
[ { "content": "Here is a code file:\n<|memory_start|>```python\nimport os\nimport sys\nimport shutil\nimport glob\nfrom os.path import join, realpath, dirname, normpath, normcase\nfrom operator import methodcaller\ntry:\n from urlparse import urlparse\nexcept ImportError:\n from urllib.parse import urlpars...
```python import os import sys import shutil import glob from os.path import join, realpath, dirname, normpath, normcase from operator import methodcaller try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import click from pkg_resources import Requirement try: WindowsError except NameError: IS_WIN = False BIN_DIR = 'bin' else: IS_WIN = True BIN_DIR = 'Scripts' FIND_SCRIPTS_SCRIPT = r'''if 1: import os import sys import pkg_resources pkg = sys.argv[1] prefix = sys.argv[2] dist = pkg_resources.get_distribution(pkg) if dist.has_metadata('RECORD'): for line in dist.get_metadata_lines('RECORD'): print(os.path.join(dist.location, line.split(',')[0])) elif dist.has_metadata('installed-files.txt'): for line in dist.get_metadata_lines('installed-files.txt'): print(os.path.join(dist.egg_info, line.split(',')[0])) elif dist.has_metadata('entry_points.txt'): try: from ConfigParser import SafeConfigParser from StringIO import StringIO except ImportError: from configparser import SafeConfigParser from io import StringIO parser = SafeConfigParser() parser.readfp(StringIO( '\n'.join(dist.get_metadata_lines('entry_points.txt')))) if parser.has_section('console_scripts'): for name, _ in parser.items('console_scripts'): print(os.path.join(prefix, name)) ''' # The `click` custom context settings CONTEXT_SETTINGS = dict( help_option_names=['-h', '--help'], ) def normalize_package(value): # Strips the version and normalizes name requirement = Requirement.parse(value) return requirement.project_name.lower() def normalize(path): return normcase(normpath(realpath(path))) def real_readlink(filename): try: target = os.readlink(filename) except (OSError, IOError, AttributeError): return None return normpath(realpath(join(dirname(filename), target))) def statusoutput(argv, **kw): from subprocess import Popen, PIPE p = Popen( argv, stdout=PIPE, stderr=PIPE, **kw) output = p.communicate()[0].strip() if not isinstance(output, str): output = output.decode('utf-8', 'replace') return p.returncode, output def publish_script(src, dst): if IS_WIN: # always copy new exe on windows shutil.copy(src, dst) click.echo(' Copied Executable ' + dst) return True else: old_target = real_readlink(dst) if old_target == src: return True try: os.remove(dst) except OSError: pass try: os.symlink(src, dst) except OSError: pass else: click.echo(' Linked script ' + dst) return True def find_scripts(virtualenv, package): prefix = normalize(join(virtualenv, BIN_DIR, '')) files = statusoutput([ join(prefix, 'python'), '-c', FIND_SCRIPTS_SCRIPT, package, prefix ])[1].splitlines() files = map(normalize, files) files = filter( methodcaller('startswith', prefix), files, ) def valid(filename): return os.path.isfile(filename) and \ IS_WIN or os.access(filename, os.X_OK) result = list(filter(valid, files)) if IS_WIN: for filename in files: globed = glob.glob(filename + '*') result.extend(filter(valid, globed)) return result class UninstallInfo(object): def __init__(self, package, paths=None, installed=True): self.package = package self.paths = paths or [] self.installed = installed def perform(self): for path in self.paths: try: os.remove(path) except OSError: shutil.rmtree(path) class Repo(object): def __init__(self, home, bin_dir): self.home = home self.bin_dir = bin_dir def resolve_package(self, spec, python=None): url = urlparse(spec) if url.netloc == 'file': location = url.path elif url.netloc != '': if not url.fragment.startswith('egg='): raise click.UsageError('When installing from URLs you need ' 'to add an egg at the end. For ' 'instance git+https://.../#egg=Foo') return url.fragment[4:], [spec] elif os.path.isdir(spec): location = spec else: return spec, [spec] error, name = statusoutput( [python or sys.executable, 'setup.py', '--name'], cwd=location) if error: raise click.UsageError('%s does not appear to be a local ' 'Python package.' % spec) return name, [location] def get_package_path(self, package): return join(self.home, normalize_package(package)) def find_installed_executables(self, path): prefix = join(realpath(normpath(path)), '') try: for filename in os.listdir(self.bin_dir): exe = os.path.join(self.bin_dir, filename) target = real_readlink(exe) if target is None: continue if target.startswith(prefix): yield exe except OSError: pass def link_scripts(self, scripts): rv = [] for script in scripts: script_dst = os.path.join( self.bin_dir, os.path.basename(script)) if publish_script(script, script_dst): rv.append((script, script_dst)) return rv def install(self, package, python=None, editable=False): package, install_args = self.resolve_package(package, python) venv_path = self.get_package_path(package) if os.path.isdir(venv_path): click.echo('%s is already installed' % package) return if not os.path.exists(self.bin_dir): os.makedirs(self.bin_dir) from subprocess import Popen def _cleanup(): try: shutil.rmtree(venv_path) except (OSError, IOError): pass return False # Install virtualenv, use the pipsi used python version by default args = ['virtualenv', '-p', python or sys.executable, venv_path] try: if Popen(args).wait() != 0: click.echo('Failed to create virtualenv. Aborting.') return _cleanup() args = [os.path.join(venv_path, BIN_DIR, 'pip'), 'install'] if editable: args.append('--editable') if Popen(args + install_args).wait() != 0: click.echo('Failed to pip install. Aborting.') return _cleanup() except Exception: _cleanup() raise # Find all the scripts scripts = find_scripts(venv_path, package) # And link them linked_scripts = self.link_scripts(scripts) # We did not link any, rollback. if not linked_scripts: click.echo('Did not find any scripts. Uninstalling.') return _cleanup() return True def uninstall(self, package): path = self.get_package_path(package) if not os.path.isdir(path): return UninstallInfo(package, installed=False) paths = [path] paths.extend(self.find_installed_executables(path)) return UninstallInfo(package, paths) def upgrade(self, package, editable=False): package, install_args = self.resolve_package(package) venv_path = self.get_package_path(package) if not os.path.isdir(venv_path): click.echo('%s is not installed' % package) return from subprocess import Popen old_scripts = set(find_scripts(venv_path, package)) args = [os.path.join(venv_path, BIN_DIR, 'pip'), 'install', '--upgrade'] if editable: args.append('--editable') if Popen(args + install_args).wait() != 0: click.echo('Failed to upgrade through pip. Aborting.') return scripts = find_scripts(venv_path, package) linked_scripts = self.link_scripts(scripts) to_delete = old_scripts - set(x[0] for x in linked_scripts) for script_src, script_link in linked_scripts: if script_src in to_delete: try: click.echo(' Removing old script %s' % script_src) os.remove(script_link) except (IOError, OSError): pass def list_everything(self): venvs = {} python = '/Scripts/python.exe' if IS_WIN else '/bin/python' for venv in os.listdir(self.home): venv_path = os.path.join(self.home, venv) if os.path.isdir(venv_path) and \ os.path.isfile(venv_path + python): venvs[venv] = [] def _find_venv(target): for venv in venvs: if target.startswith(join(self.home, venv, '')): return venv for script in os.listdir(self.bin_dir): exe = os.path.join(self.bin_dir, script) target = real_readlink(exe) if target is None: continue venv = _find_venv(target) if venv is not None: venvs[venv].append(script) return sorted(venvs.items()) @click.group(context_settings=CONTEXT_SETTINGS) @click.option( '--home', type=click.Path(),envvar='PIPSI_HOME', default=os.path.expanduser('~/.local/venvs'), help='The folder that contains the virtualenvs.') @click.option( '--bin-dir', type=click.Path(), envvar='PIPSI_BIN_DIR', default=os.path.expanduser('~/.local/bin'), help='The path where the scripts are symlinked to.') @click.version_option( message='%(prog)s, version %(version)s, python ' + str(sys.executable)) @click.pass_context def cli(ctx, home, bin_dir): """pipsi is a tool that uses virtualenv and pip to install shell tools that are separated from each other. """ ctx.obj = Repo(home, bin_dir) @cli.command() @click.argument('package') @click.option('--python', default=None, help='The python interpreter to use.') @click.option('--editable', is_flag=True, help='Enable editable installation. This only works for ' 'locally installed packages.') @click.pass_obj def install(repo, package, python, editable): """Installs scripts from a Python package. Given a package this will install all the scripts and their dependencies of the given Python package into a new virtualenv and symlinks the discovered scripts into BIN_DIR (defaults to ~/.local/bin). """ if repo.install(package, python, editable): click.echo('Done.') else: sys.exit(1) @cli.command() @click.argument('package') @click.option('--editable', is_flag=True, help='Enable editable installation. This only works for ' 'locally installed packages.') @click.pass_obj def upgrade(repo, package, editable): """Upgrades an already installed package.""" if repo.upgrade(package, editable): click.echo('Done.') else: sys.exit(1) @cli.command(short_help='Uninstalls scripts of a package.') @click.argument('package') @click.option('--yes', is_flag=True, help='Skips all prompts.') @click.pass_obj def uninstall(repo, package, yes): """Uninstalls all scripts of a Python package and cleans up the virtualenv. """ uinfo = repo.uninstall(package) if not uinfo.installed: click.echo('%s is not installed' % package) else: click.echo('The following paths will be removed:') for path in uinfo.paths: click.echo(' %s' % click.format_filename(path)) click.echo() if yes or click.confirm('Do you want to uninstall %s?' % package): uinfo.perform() click.echo('Done!') else: click.echo('Aborted!') sys.exit(1) @cli.command('list') @click.pass_obj def list_cmd(repo): """Lists all scripts installed through pipsi.""" click.echo('Packages and scripts installed through pipsi:') for venv, scripts in repo.list_everything(): if not scripts: continue click.echo(' Package "%s":' % venv) for script in scripts: click.echo(' ' + script) if __name__ == '__main__': cli() ```
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n```python\nimport logging\nfrom ..parsers import DictParser\n\nfrom base_scraper import TwittrScrapr\n\nlog = logging.getLogger('scrapers.TimelineScrapr')\n\n\nclass TimelineScrapr(TwittrScrapr):\n def __init__(self, api...
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n<|memory_start|>```python\nimport logging\nfrom ..parsers import DictParser\n\nfrom base_scraper import TwittrScrapr\n\nlog = logging.getLogger('scrapers.TimelineScrapr')\n\n\nclass TimelineScrapr(TwittrScrapr):\n def __...
```python import logging from ..parsers import DictParser from base_scraper import TwittrScrapr log = logging.getLogger('scrapers.TimelineScrapr') class TimelineScrapr(TwittrScrapr): def __init__(self, api_keys, writer): super(TimelineScrapr, self).__init__(api_keys, writer) def _fetch_user_timeline(self, user): finished_pagination = False new_max = None results = [] parser = DictParser() while not finished_pagination: self.check_rate_limit() call_result = self.api.get_user_timeline(screen_name=user, count=200, include_rts=1, trim_user=True, max_id=new_max) if len(call_result) > 0: results.extend([parser.parse(t, user=user) for t in call_result]) new_max = str(int(call_result[-1]['id_str']) - 1) else: finished_pagination = True self.reset_time = self.api.get_lastfunction_header('x-rate-limit-reset') self.calls_remaining = self.api.get_lastfunction_header('x-rate-limit-remaining') return results @TwittrScrapr.error_handler def fetch_user_statuses(self, writer): for user in self.scrape_queue: log.info('Fetching tweets for {}'.format(user)) res = self._fetch_user_timeline(user) log.info('Got {} tweets'.format(len(res))) writer.writerows(res) ```
[ { "content": "Here is the snippet:\n```python\n# This file is part of the Hotwire Shell project API.\n\n# Copyright (C) 2007 Colin Walters <walters@verbum.org>\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy \n# of this software and associated documentation files (the \"Softwar...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n# This file is part of the Hotwire Shell project API.\n\n# Copyright (C) 2007 Colin Walters <walters@verbum.org>\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy \n# of this software and associated documentation file...
```python # This file is part of the Hotwire Shell project API. # Copyright (C) 2007 Colin Walters <walters@verbum.org> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR # THE USE OR OTHER DEALINGS IN THE SOFTWARE. import os,sys,pickle,inspect,locale from io import StringIO from hotwire.fs import FilePath from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema import simplejson class LossyObjectJSONDumper(simplejson.JSONEncoder): def __init__(self, *args, **kwargs): super(LossyObjectJSONDumper, self).__init__(*args, **kwargs) def default(self, o): name_repr = {} for name,member in sorted(inspect.getmembers(o), lambda a,b: locale.strcoll(a[0],b[0])): if name.startswith('_'): continue name_repr[name] = str(type(member)) return self.encode(name_repr) class JsonBuiltin(Builtin): __doc__ = _("""Convert object stream to JSON.""") def __init__(self): super(JsonBuiltin, self).__init__('json', output=str, # 'any' input=InputStreamSchema('any'), idempotent=True, argspec=None) def execute(self, context, args, options=[]): out = StringIO() for o in context.input: simplejson.dump(o, out, indent=2, cls=LossyObjectJSONDumper) # Should support binary streaming for line in StringIO(out.getvalue()): if line.endswith('\n'): yield line[0:-1] else: yield line BuiltinRegistry.getInstance().register_hotwire(JsonBuiltin()) ```
[ { "content": "Replicate the source code:\n```python\nimport subprocess \nimport numpy as np\nimport os\nimport numpy.ma as ma\nimport re\nfrom tempfile import mkstemp, mkdtemp\nimport shutil\nimport scipy.constants\n\n#########################################\n#replace will search through a file for a specific ...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\nimport subprocess \nimport numpy as np\nimport os\nimport numpy.ma as ma\nimport re\nfrom tempfile import mkstemp, mkdtemp\nimport shutil\nimport scipy.constants\n\n#########################################\n#replace will search through a file...
```python import subprocess import numpy as np import os import numpy.ma as ma import re from tempfile import mkstemp, mkdtemp import shutil import scipy.constants ######################################### #replace will search through a file for a specific word an then replace that line def replace(file, pattern, subst): p = re.compile(pattern) #Create temp file fh, abs_path = mkstemp() new_file = open(abs_path,'w') old_file = open(file) for line in old_file: if p.match(line): #using match because for input files only want to replace the currently used variable line = pattern + ' = ' + str(subst) + ', \n' new_file.write(line) #close temp file new_file.close() os.close(fh) old_file.close() os.remove(file) shutil.move(abs_path, file) #routine which call 1d_schrodinger eqn solver and returns #all the levels below zero outputted def run_1d_schrodinger(inputfile_name,outputfile_name,L): home = os.getcwd() replace(inputfile_name, ' L', L) #editing inputfile such that L=L is called subprocess.call(home+"/1d_schrodinger.x < " + inputfile_name, stdout=open(os.devnull, 'w'), shell=True) return() ############################################ lmax = 100 inputfile = 'input_K2.txt' outputfile = 'fort.10' sys = 'kk' #generate to states of the dimer for different n upto nmax for i in range(0,lmax+1): run_1d_schrodinger(inputfile,outputfile,i) # shutil.copyfile(outputfile,sys+'_results_j'+str(i)+'.dat') try: shutil.move(outputfile,sys+'_results_j'+str(i)+'.dat') except IOError: pass ```
[ { "content": "Recreate the entire code block with identical formatting:\n```python\n# -*- coding: utf-8 -*-\n\"\"\"This module defines I/O routines with CASTEP files.\nThe key idea is that all function accept or return atoms objects.\nCASTEP specific parameters will be returned through the <atoms>.calc\nattrib...
[ { "content": "Recreate the entire code block with identical formatting:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\"\"\"This module defines I/O routines with CASTEP files.\nThe key idea is that all function accept or return atoms objects.\nCASTEP specific parameters will be returned through the <ato...
```python # -*- coding: utf-8 -*- """This module defines I/O routines with CASTEP files. The key idea is that all function accept or return atoms objects. CASTEP specific parameters will be returned through the <atoms>.calc attribute. """ from numpy import sqrt, radians, sin, cos, matrix, array, cross, float32, dot import ase from ase.constraints import FixAtoms, FixCartesian from ase.parallel import paropen import os __all__ = [ 'read_castep', 'read_cell', 'read_geom', 'read_param', 'read_seed', 'write_cell', 'write_param', ] def write_cell(filename, atoms, positions_frac=False, castep_cell=None, force_write=False): """This CASTEP export function write minimal information to a .cell file. If the atoms object is a trajectory, it will take the last image. """ if atoms is None: print("Atoms object not initialized") return False if isinstance(atoms, list): if len(atoms) > 1: atoms = atoms[-1] if os.path.isfile(filename) and not force_write: print('ase.io.castep.write_param: Set optional argument') print('force_write=True to overwrite %s.' % filename) return False fd = open(filename, 'w') fd.write('#######################################################\n') fd.write('#CASTEP cell file: %s\n' % filename) fd.write('#Created using the Atomic Simulation Environment (ASE)#\n') fd.write('#######################################################\n\n') fd.write('%BLOCK LATTICE_CART\n') cell = matrix(atoms.get_cell()) for line in atoms.get_cell(): fd.write(' %.10f %.10f %.10f\n' % tuple(line)) fd.write('%ENDBLOCK LATTICE_CART\n\n\n') if positions_frac: keyword = 'POSITIONS_FRAC' positions = array(atoms.get_positions() * cell.I) else: keyword = 'POSITIONS_ABS' positions = atoms.get_positions() if atoms.get_initial_magnetic_moments().any(): pos_block = [('%s %8.6f %8.6f %8.6f SPIN=%4.2f' % (x, y[0], y[1], y[2], m)) for (x, y, m) in zip(atoms.get_chemical_symbols(), positions, atoms.get_initial_magnetic_moments())] else: pos_block = [('%s %8.6f %8.6f %8.6f' % (x, y[0], y[1], y[2])) for (x, y) in zip(atoms.get_chemical_symbols(), positions)] fd.write('%%BLOCK %s\n' % keyword) for line in pos_block: fd.write(' %s\n' % line) fd.write('%%ENDBLOCK %s\n\n' % keyword) # if atoms, has a CASTEP calculator attached, then only # write constraints if really necessary if hasattr(atoms, 'calc')\ and hasattr(atoms.calc, 'param')\ and hasattr(atoms.calc.param, 'task'): task = atoms.calc.param.task if atoms.calc.param.task.value is None: suppress_constraints = True elif task.value.lower() not in [ 'geometryoptimization', 'moleculardynamics', 'transitionstatesearch', 'phonon']: suppress_constraints = True else: suppress_constraints = False else: suppress_constraints = True constraints = atoms.constraints if len(constraints) and not suppress_constraints: fd.write("%BLOCK IONIC_CONSTRAINTS \n") count = 0 for constr in constraints: if not isinstance(constr, FixAtoms)\ and not isinstance(constr, FixCartesian)\ and not suppress_constraints: print('Warning: you have constraints in your atoms, that are') print(' not supported by CASTEP') break if isinstance(constr, FixAtoms): # sorry, for this complicated block # reason is that constraint.index can either # hold booleans or integers and in both cases # it is an numpy array, so no simple comparison works for n, val in enumerate(constr.index): if val.dtype.name.startswith('bool'): if not val: continue symbol = atoms.get_chemical_symbols()[n] nis = atoms.calc._get_number_in_species(n) elif val.dtype.name.startswith('int'): symbol = atoms.get_chemical_symbols()[val] nis = atoms.calc._get_number_in_species(val) else: raise UserWarning('Unrecognized index in' + \ ' constraint %s' % constr) fd.write("%6d %3s %3d 1 0 0 \n" % (count + 1, symbol, nis)) fd.write("%6d %3s %3d 0 1 0 \n" % (count + 2, symbol, nis)) fd.write("%6d %3s %3d 0 0 1 \n" % (count + 3, symbol, nis)) count += 3 elif isinstance(constr, FixCartesian): n = constr.a symbol = atoms.get_chemical_symbols()[n] nis = atoms.calc._get_number_in_species(n) fix_cart = - constr.mask + 1 if fix_cart[0]: count += 1 fd.write("%6d %3s %3d 1 0 0 \n" % (count, symbol, nis)) if fix_cart[1]: count += 1 fd.write("%6d %3s %3d 0 1 0 \n" % (count, symbol, nis)) if fix_cart[2]: count += 1 fd.write("%6d %3s %3d 0 0 1 \n" % (count, symbol, nis)) fd.write("%ENDBLOCK IONIC_CONSTRAINTS \n") if castep_cell is None: if hasattr(atoms, 'calc') and hasattr(atoms.calc, 'cell'): castep_cell = atoms.calc.cell else: fd.close() return True for option in castep_cell._options.values(): if option.value is not None: if option.type == 'Block': fd.write('%%BLOCK %s\n' % option.keyword.upper()) fd.write(option.value) fd.write('\n%%ENDBLOCK %s\n' % option.keyword.upper()) else: fd.write('%s : %s\n' % (option.keyword.upper(), option.value)) fd.close() return True def read_cell(filename, _=None): """Read a .cell file and return an atoms object. Any value found that does not fit the atoms API will be stored in the atoms.calc attribute. """ from ase.calculators.castep import Castep calc = Castep() fileobj = open(filename) lines = fileobj.readlines() fileobj.close() def get_tokens(lines, l): """Tokenizes one line of a *cell file.""" comment_chars = "#!" while l < len(lines): line = lines[l].strip() if len(line) == 0: l += 1 continue elif any([line.startswith(comment_char) for comment_char in comment_chars]): l += 1 continue else: for c in comment_chars: if c in line: icomment = min(line.index(c)) else: icomment = len(line) tokens = line[:icomment].split() return tokens, l + 1 tokens = "" print("read_cell: Warning - get_tokens has not found any more tokens") return tokens, l lat = [] have_lat = False pos = [] spec = [] constraints = [] raw_constraints = {} have_pos = False pos_frac = False l = 0 while l < len(lines): tokens, l = get_tokens(lines, l) if not tokens: continue elif tokens[0].upper() == "%BLOCK": if tokens[1].upper() == "LATTICE_CART" and not have_lat: tokens, l = get_tokens(lines, l) if len(tokens) == 1: print('read_cell: Warning - ignoring unit specifier in') print('%BLOCK LATTICE_CART (assuming Angstrom instead)') tokens, l = get_tokens(lines, l) for _ in range(3): lat_vec = map(float, tokens[0:3]) lat.append(lat_vec) tokens, l = get_tokens(lines, l) if tokens[0].upper() != "%ENDBLOCK": print('read_cell: Warning - ignoring more than three') print('lattice vectors in invalid %BLOCK LATTICE_CART') print('%s ...' % tokens[0].upper()) have_lat = True elif tokens[1].upper() == "LATTICE_ABC" and not have_lat: tokens, l = get_tokens(lines, l) if len(tokens) == 1: print('read_cell: Warning - ignoring unit specifier in') print('%BLOCK LATTICE_ABC (assuming Angstrom instead)') tokens, l = get_tokens(lines, l) a, b, c = map(float, tokens[0:3]) tokens, l = get_tokens(lines, l) alpha, beta, gamma = map(lambda phi: radians(float(phi)), tokens[0:3]) tokens, l = get_tokens(lines, l) if tokens[0].upper() != "%ENDBLOCK": print('read_cell: Warning - ignoring additional lines in') print('invalid %BLOCK LATTICE_ABC') lat_a = [a, 0, 0] lat_b = [b * cos(gamma), b * sin(gamma), 0] lat_c1 = c * cos(beta) lat_c2 = c * (cos(alpha) - cos(beta) * cos(gamma)) / sin(gamma) lat_c3 = sqrt(c * c - lat_c1 * lat_c1 - lat_c2 * lat_c2) lat_c = [lat_c1, lat_c2, lat_c3] lat = [lat_a, lat_b, lat_c] have_lat = True elif tokens[1].upper() == "POSITIONS_ABS" and not have_pos: tokens, l = get_tokens(lines, l) if len(tokens) == 1: print('read_cell: Warning - ignoring unit specifier in') print('%BLOCK POSITIONS_ABS(assuming Angstrom instead)') tokens, l = get_tokens(lines, l) while len(tokens) == 4: spec.append(tokens[0]) pos.append(map(float, tokens[1:4])) tokens, l = get_tokens(lines, l) if tokens[0].upper() != "%ENDBLOCK": print('read_cell: Warning - ignoring invalid lines in') print('%%BLOCK POSITIONS_ABS:\n\t %s' % tokens) have_pos = True elif tokens[1].upper() == "POSITIONS_FRAC" and not have_pos: pos_frac = True tokens, l = get_tokens(lines, l) while len(tokens) == 4: spec.append(tokens[0]) pos.append(map(float, tokens[1:4])) tokens, l = get_tokens(lines, l) if tokens[0].upper() != "%ENDBLOCK": print('read_cell: Warning - ignoring invalid lines') print('%%BLOCK POSITIONS_FRAC:\n\t %s' % tokens) have_pos = True elif tokens[1].upper() == 'SPECIES_POT': tokens, l = get_tokens(lines, l) while tokens and not tokens[0].upper() == '%ENDBLOCK': if len(tokens) == 2: calc.cell.species_pot = tuple(tokens) tokens, l = get_tokens(lines, l) elif tokens[1].upper() == 'IONIC_CONSTRAINTS': while True: if tokens and tokens[0].upper() == '%ENDBLOCK': break tokens, l = get_tokens(lines, l) if not len(tokens) == 6: continue _, species, nic, x, y, z = tokens nic = int(nic) if (species, nic) not in raw_constraints: raw_constraints[(species, nic)] = [] raw_constraints[(species, nic)].append(array( [x, y, z])) else: print('Warning: the keyword %s is not' % tokens[1].upper()) print(' interpreted in cell files') while not tokens[0].upper() == '%ENDBLOCK': tokens, l = get_tokens(lines, l) #raise UserWarning else: key = tokens[0] value = ' '.join(tokens[1:]) try: calc.__setattr__(key, value) except: print("Problem setting calc.cell.%s = %s" % (key, value)) raise if pos_frac: atoms = ase.Atoms( calculator=calc, cell=lat, pbc=True, scaled_positions=pos, symbols=spec, ) else: atoms = ase.Atoms( calculator=calc, cell=lat, pbc=True, positions=pos, symbols=spec, ) fixed_atoms = [] for (species, nic), value in raw_constraints.iteritems(): absolute_nr = atoms.calc._get_absolute_number(species, nic) if len(value) == 3: fixed_atoms.append(absolute_nr) elif len(value) == 2: constraint = ase.constraints.FixedLine(a=absolute_nr, direction=cross(value[0], value[1])) constraints.append(constraint) elif len(value) == 1: constraint = ase.constraints.FixedPlane(a=absolute_nr, direction=array(value[0], dtype=float32)) constraints.append(constraint) else: print('Error: Found %s statements attached to atoms %s' % (len(value), absolute_nr)) constraints.append(ase.constraints.FixAtoms(fixed_atoms)) atoms.set_constraint(constraints) # needs to go here again to have the constraints in # atoms.calc.atoms.constraints as well atoms.calc.atoms = atoms atoms.calc.push_oldstate() return atoms # this actually does not belong here # think how one could join this with # the ase.calculators.castep.Castep.read() # in the future! def read_castep(filename, _=-1): """Reads a .castep file and returns an atoms object. The calculator information will be stored in the calc attribute. If more than one SCF step is found, a list of all steps will be stored in the traj attribute. Note that the index argument has no effect as of now. """ from ase.calculators.singlepoint import SinglePointCalculator fileobj = open(filename) lines = fileobj.readlines() fileobj.close() traj = [] energy_total = None energy_0K = None for i, line in enumerate(lines): if 'NB est. 0K energy' in line: energy_0K = float(line.split()[6]) elif 'Final energy, E' in line: energy_total = float(line.split()[4]) elif 'Unit Cell' in line: cell = [x.split()[0:3] for x in lines[i + 3:i + 6]] cell = array([[float(col) for col in row] for row in cell]) elif 'Cell Contents' in line: geom_starts = i start_found = False for j, jline in enumerate(lines[geom_starts:]): if jline.find('xxxxx') > 0 and start_found: geom_stop = j + geom_starts break if jline.find('xxxx') > 0 and not start_found: geom_start = j + geom_starts + 4 start_found = True species = [line.split()[1] for line in lines[geom_start:geom_stop]] geom = dot(array([[float(col) for col in line.split()[3:6]] for line in lines[geom_start:geom_stop]]), cell) elif 'Writing model to' in line: atoms = ase.Atoms( cell=cell, pbc=True, positions=geom, symbols=''.join(species), ) # take 0K energy where available, else total energy if energy_0K: energy = energy_0K else: energy = energy_total # generate a minimal single-point calculator sp_calc = SinglePointCalculator(atoms=atoms, energy=energy, forces=None, magmoms=None, stress=None, ) atoms.set_calculator(sp_calc) traj.append(atoms) return traj def read_param(filename, calc=None): """Reads a param file. If an Castep object is passed as the second argument, the parameter setings are merged into the existing object and returned. Otherwise a new Castep() calculator instance gets created and returned. Parameters: filename: the .param file. Only opens reading calc: [Optional] calculator object to hang parameters onto """ if calc is None: calc = ase.calculators.castep.Castep(check_castep_version=False) calc.merge_param(filename) return calc def write_param(filename, param, check_checkfile=False, force_write=False, interface_options=None): """Writes a CastepParam object to a CASTEP .param file Parameters: filename: the location of the file to write to. If it exists it will be overwritten without warning. If it doesn't it will be created. param: a CastepParam instance check_checkfile : if set to True, write_param will only write continuation or reuse statement if a restart file exists in the same directory """ if os.path.isfile(filename) and not force_write: print('ase.io.castep.write_param: Set optional argument') print('force_write=True to overwrite %s.' % filename) return False out = paropen(filename, 'w') out.write('#######################################################\n') out.write('#CASTEP param file: %s\n' % filename) out.write('#Created using the Atomic Simulation Environment (ASE)#\n') if interface_options is not None: out.write('# Internal settings of the calculator\n') out.write('# This can be switched off by settings\n') out.write('# calc._export_settings = False\n') out.write('# If stated, this will be automatically processed\n') out.write('# by ase.io.castep.read_seed()\n') for option, value in sorted(interface_options.iteritems()): out.write('# ASE_INTERFACE %s : %s\n' % (option, value)) out.write('#######################################################\n\n') for keyword, opt in sorted(param._options.iteritems()): if opt.type == 'Defined': if opt.value is not None: out.write('%s\n' % (option)) elif opt.value is not None: if keyword in ['continuation', 'reuse'] and check_checkfile: if opt.value == 'default': if not os.path.exists('%s.%s'\ % (os.path.splitext(filename)[0], 'check')): continue elif not os.path.exists(opt.value): continue out.write('%s : %s\n' % (keyword, opt.value)) out.close() def read_geom(filename, _=-1): """Reads a .geom file produced by the CASTEP GeometryOptimization task and returns an atoms object. The information about total free energy and forces of each atom for every relaxation step will be stored for further analysis especially in a single-point calculator. Note that everything in the .geom file is in atomic units, which has been conversed to commonly used unit angstrom(length) and eV (energy). Note that the index argument has no effect as of now. Contribution by Wei-Bing Zhang. Thanks! """ from ase.calculators.singlepoint import SinglePointCalculator fileobj = open(filename) txt = fileobj.readlines() fileobj.close() traj = [] # Source: CODATA2002, used by default # in CASTEP 5.01 # but check with your version in case of error # ase.units is based on CODATA1986/ # here we hard-code from http://physics.nist.gov/cuu/Document/all_2002.pdf Hartree = 27.211384565719481 Bohr = 0.5291772108 print('N.B.: Energy in .geom file is not 0K extrapolated.') for i, line in enumerate(txt): if line.find("<-- E") > 0: start_found = True energy = float(line.split()[0]) * Hartree cell = [x.split()[0:3] for x in txt[i + 1:i + 4]] cell = array([[float(col) * Bohr for col in row] for row in cell]) if line.find('<-- R') > 0 and start_found: start_found = False geom_start = i for i, line in enumerate(txt[geom_start:]): if line.find('<-- F') > 0: geom_stop = i + geom_start break species = [line.split()[0] for line in txt[geom_start:geom_stop]] geom = array([[float(col) * Bohr for col in line.split()[2:5]] for line in txt[geom_start:geom_stop]]) forces = array([[float(col) * Hartree / Bohr for col in line.split()[2:5]] for line in txt[geom_stop:geom_stop + (geom_stop - geom_start)]]) image = ase.Atoms(species, geom, cell=cell, pbc=True) image.set_calculator(SinglePointCalculator(energy, forces, None, None, image)) traj.append(image) return traj def read_seed(seed, new_seed=None, ignore_internal_keys=False): """A wrapper around the CASTEP Calculator in conjunction with read_cell and read_param. Basically this can be used to reuse a previous calculation which results in a triple of cell/param/castep file. The label of the calculation if pre- fixed with cop_of_ and everything else will be recycled as much as possible from the addressed calculation. """ directory = os.path.abspath(os.path.dirname(seed)) seed = os.path.basename(seed) paramfile = os.path.join(directory, '%s.param' % seed) cellfile = os.path.join(directory, '%s.cell' % seed) castepfile = os.path.join(directory, '%s.castep' % seed) atoms = read_cell(cellfile) atoms.calc._directory = directory atoms.calc._rename_existing_dir = False atoms.calc._castep_pp_path = directory atoms.calc.merge_param(paramfile, ignore_internal_keys=ignore_internal_keys) if new_seed is None: atoms.calc._label = 'copy_of_%s' % seed else: atoms.calc._label = str(new_seed) if os.path.isfile(castepfile): # _set_atoms needs to be True here # but we set it right back to False atoms.calc._set_atoms = True atoms.calc.read(castepfile) atoms.calc._set_atoms = False # sync the top-level object with the # one attached to the calculator atoms = atoms.calc.atoms else: print('Corresponding CASTEP not found.') atoms.calc.push_oldstate() return atoms ```
[ { "content": "Return the code unaltered:\n```python\n\"\"\"Helper methods for various modules.\"\"\"\nfrom collections.abc import MutableSet\nfrom itertools import chain\nimport threading\nimport queue\nfrom datetime import datetime\nimport re\nimport enum\nimport socket\nimport random\nimport string\nfrom func...
[ { "content": "Return the code unaltered:\n<|memory_start|>```python\n\"\"\"Helper methods for various modules.\"\"\"\nfrom collections.abc import MutableSet\nfrom itertools import chain\nimport threading\nimport queue\nfrom datetime import datetime\nimport re\nimport enum\nimport socket\nimport random\nimport s...
```python """Helper methods for various modules.""" from collections.abc import MutableSet from itertools import chain import threading import queue from datetime import datetime import re import enum import socket import random import string from functools import wraps from types import MappingProxyType from typing import Any, Sequence from .dt import as_local, utcnow RE_SANITIZE_FILENAME = re.compile(r'(~|\.\.|/|\\)') RE_SANITIZE_PATH = re.compile(r'(~|\.(\.)+)') RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') def sanitize_filename(filename): r"""Sanitize a filename by removing .. / and \\.""" return RE_SANITIZE_FILENAME.sub("", filename) def sanitize_path(path): """Sanitize a path by removing ~ and ..""" return RE_SANITIZE_PATH.sub("", path) def slugify(text: str) -> str: """Slugify a given text.""" text = text.lower().replace(" ", "_") return RE_SLUGIFY.sub("", text) def repr_helper(inp: Any) -> str: """Help creating a more readable string representation of objects.""" if isinstance(inp, (dict, MappingProxyType)): return ", ".join( repr_helper(key)+"="+repr_helper(item) for key, item in inp.items()) elif isinstance(inp, datetime): return as_local(inp).isoformat() else: return str(inp) def convert(value, to_type, default=None): """Convert value to to_type, returns default if fails.""" try: return default if value is None else to_type(value) except (ValueError, TypeError): # If value could not be converted return default def ensure_unique_string(preferred_string: str, current_strings: Sequence[str]) -> str: """Return a string that is not present in current_strings. If preferred string exists will append _2, _3, .. """ test_string = preferred_string current_strings_set = set(current_strings) tries = 1 while test_string in current_strings_set: tries += 1 test_string = "{}_{}".format(preferred_string, tries) return test_string # Taken from: http://stackoverflow.com/a/11735897 def get_local_ip(): """Try to determine the local IP address of the machine.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Use Google Public DNS server to determine own IP sock.connect(('8.8.8.8', 80)) return sock.getsockname()[0] except socket.error: return socket.gethostbyname(socket.gethostname()) finally: sock.close() # Taken from http://stackoverflow.com/a/23728630 def get_random_string(length=10): """Return a random string with letters and digits.""" generator = random.SystemRandom() source_chars = string.ascii_letters + string.digits return ''.join(generator.choice(source_chars) for _ in range(length)) class OrderedEnum(enum.Enum): """Taken from Python 3.4.0 docs.""" # pylint: disable=no-init, too-few-public-methods def __ge__(self, other): """Return the greater than element.""" if self.__class__ is other.__class__: return self.value >= other.value return NotImplemented def __gt__(self, other): """Return the greater element.""" if self.__class__ is other.__class__: return self.value > other.value return NotImplemented def __le__(self, other): """Return the lower than element.""" if self.__class__ is other.__class__: return self.value <= other.value return NotImplemented def __lt__(self, other): """Return the lower element.""" if self.__class__ is other.__class__: return self.value < other.value return NotImplemented class OrderedSet(MutableSet): """Ordered set taken from http://code.activestate.com/recipes/576694/.""" def __init__(self, iterable=None): """Initialize the set.""" self.end = end = [] end += [None, end, end] # sentinel node for doubly linked list self.map = {} # key --> [key, prev, next] if iterable is not None: self |= iterable def __len__(self): """Return the length of the set.""" return len(self.map) def __contains__(self, key): """Check if key is in set.""" return key in self.map def add(self, key): """Add an element to the end of the set.""" if key not in self.map: end = self.end curr = end[1] curr[2] = end[1] = self.map[key] = [key, curr, end] def promote(self, key): """Promote element to beginning of the set, add if not there.""" if key in self.map: self.discard(key) begin = self.end[2] curr = begin[1] curr[2] = begin[1] = self.map[key] = [key, curr, begin] def discard(self, key): """Discard an element from the set.""" if key in self.map: key, prev_item, next_item = self.map.pop(key) prev_item[2] = next_item next_item[1] = prev_item def __iter__(self): """Iteration of the set.""" end = self.end curr = end[2] while curr is not end: yield curr[0] curr = curr[2] def __reversed__(self): """Reverse the ordering.""" end = self.end curr = end[1] while curr is not end: yield curr[0] curr = curr[1] def pop(self, last=True): # pylint: disable=arguments-differ """Pop element of the end of the set. Set last=False to pop from the beginning. """ if not self: raise KeyError('set is empty') key = self.end[1][0] if last else self.end[2][0] self.discard(key) return key def update(self, *args): """Add elements from args to the set.""" for item in chain(*args): self.add(item) def __repr__(self): """Return the representation.""" if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self)) def __eq__(self, other): """Return the comparision.""" if isinstance(other, OrderedSet): return len(self) == len(other) and list(self) == list(other) return set(self) == set(other) class Throttle(object): """A class for throttling the execution of tasks. This method decorator adds a cooldown to a method to prevent it from being called more then 1 time within the timedelta interval `min_time` after it returned its result. Calling a method a second time during the interval will return None. Pass keyword argument `no_throttle=True` to the wrapped method to make the call not throttled. Decorator takes in an optional second timedelta interval to throttle the 'no_throttle' calls. Adds a datetime attribute `last_call` to the method. """ # pylint: disable=too-few-public-methods def __init__(self, min_time, limit_no_throttle=None): """Initialize the throttle.""" self.min_time = min_time self.limit_no_throttle = limit_no_throttle def __call__(self, method): """Caller for the throttle.""" if self.limit_no_throttle is not None: method = Throttle(self.limit_no_throttle)(method) # Different methods that can be passed in: # - a function # - an unbound function on a class # - a method (bound function on a class) # We want to be able to differentiate between function and unbound # methods (which are considered functions). # All methods have the classname in their qualname seperated by a '.' # Functions have a '.' in their qualname if defined inline, but will # be prefixed by '.<locals>.' so we strip that out. is_func = (not hasattr(method, '__self__') and '.' not in method.__qualname__.split('.<locals>.')[-1]) @wraps(method) def wrapper(*args, **kwargs): """Wrapper that allows wrapped to be called only once per min_time. If we cannot acquire the lock, it is running so return None. """ # pylint: disable=protected-access if hasattr(method, '__self__'): host = method.__self__ elif is_func: host = wrapper else: host = args[0] if args else wrapper if not hasattr(host, '_throttle'): host._throttle = {} if id(self) not in host._throttle: host._throttle[id(self)] = [threading.Lock(), None] throttle = host._throttle[id(self)] if not throttle[0].acquire(False): return None # Check if method is never called or no_throttle is given force = not throttle[1] or kwargs.pop('no_throttle', False) try: if force or utcnow() - throttle[1] > self.min_time: result = method(*args, **kwargs) throttle[1] = utcnow() return result else: return None finally: throttle[0].release() return wrapper class ThreadPool(object): """A priority queue-based thread pool.""" # pylint: disable=too-many-instance-attributes def __init__(self, job_handler, worker_count=0, busy_callback=None): """Initialize the pool. job_handler: method to be called from worker thread to handle job worker_count: number of threads to run that handle jobs busy_callback: method to be called when queue gets too big. Parameters: worker_count, list of current_jobs, pending_jobs_count """ self._job_handler = job_handler self._busy_callback = busy_callback self.worker_count = 0 self.busy_warning_limit = 0 self._work_queue = queue.PriorityQueue() self.current_jobs = [] self._lock = threading.RLock() self._quit_task = object() self.running = True for _ in range(worker_count): self.add_worker() def add_worker(self): """Add worker to the thread pool and reset warning limit.""" with self._lock: if not self.running: raise RuntimeError("ThreadPool not running") worker = threading.Thread( target=self._worker, name='ThreadPool Worker {}'.format(self.worker_count)) worker.daemon = True worker.start() self.worker_count += 1 self.busy_warning_limit = self.worker_count * 3 def remove_worker(self): """Remove worker from the thread pool and reset warning limit.""" with self._lock: if not self.running: raise RuntimeError("ThreadPool not running") self._work_queue.put(PriorityQueueItem(0, self._quit_task)) self.worker_count -= 1 self.busy_warning_limit = self.worker_count * 3 def add_job(self, priority, job): """Add a job to the queue.""" with self._lock: if not self.running: raise RuntimeError("ThreadPool not running") self._work_queue.put(PriorityQueueItem(priority, job)) # Check if our queue is getting too big. if self._work_queue.qsize() > self.busy_warning_limit \ and self._busy_callback is not None: # Increase limit we will issue next warning. self.busy_warning_limit *= 2 self._busy_callback( self.worker_count, self.current_jobs, self._work_queue.qsize()) def block_till_done(self): """Block till current work is done.""" self._work_queue.join() def stop(self): """Finish all the jobs and stops all the threads.""" self.block_till_done() with self._lock: if not self.running: return # Tell the workers to quit for _ in range(self.worker_count): self.remove_worker() self.running = False # Wait till all workers have quit self.block_till_done() def _worker(self): """Handle jobs for the thread pool.""" while True: # Get new item from work_queue job = self._work_queue.get().item if job is self._quit_task: self._work_queue.task_done() return # Add to current running jobs job_log = (utcnow(), job) self.current_jobs.append(job_log) # Do the job self._job_handler(job) # Remove from current running job self.current_jobs.remove(job_log) # Tell work_queue the task is done self._work_queue.task_done() class PriorityQueueItem(object): """Holds a priority and a value. Used within PriorityQueue.""" # pylint: disable=too-few-public-methods def __init__(self, priority, item): """Initialize the queue.""" self.priority = priority self.item = item def __lt__(self, other): """Return the ordering.""" return self.priority < other.priority ```
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n```python\n# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# Copyright 2011 Justin Santa Barbara\n# All Rights Reserved.\n#\n# Licensed under the Apache ...
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n<|memory_start|>```python\n# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# Copyright 2011 Justin Santa Barbara\n# All Rights Reserved.\n#\n# Licensed u...
```python # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # 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. """Utilities and helper functions.""" import contextlib import errno import functools import inspect import os import pyclbr import random import re import shutil import socket import sys import tempfile from eventlet import pools import netaddr from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log from oslo_utils import importutils from oslo_utils import timeutils import paramiko import retrying import six from manila.db import api as db_api from manila import exception from manila.i18n import _ CONF = cfg.CONF LOG = log.getLogger(__name__) synchronized = lockutils.synchronized_with_prefix('manila-') def _get_root_helper(): return 'sudo manila-rootwrap %s' % CONF.rootwrap_config def execute(*cmd, **kwargs): """Convenience wrapper around oslo's execute() function.""" if 'run_as_root' in kwargs and 'root_helper' not in kwargs: kwargs['root_helper'] = _get_root_helper() return processutils.execute(*cmd, **kwargs) def trycmd(*args, **kwargs): """Convenience wrapper around oslo's trycmd() function.""" if 'run_as_root' in kwargs and 'root_helper' not in kwargs: kwargs['root_helper'] = _get_root_helper() return processutils.trycmd(*args, **kwargs) class SSHPool(pools.Pool): """A simple eventlet pool to hold ssh connections.""" def __init__(self, ip, port, conn_timeout, login, password=None, privatekey=None, *args, **kwargs): self.ip = ip self.port = port self.login = login self.password = password self.conn_timeout = conn_timeout if conn_timeout else None self.path_to_private_key = privatekey super(SSHPool, self).__init__(*args, **kwargs) def create(self): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) look_for_keys = True if self.path_to_private_key: self.path_to_private_key = os.path.expanduser( self.path_to_private_key) look_for_keys = False elif self.password: look_for_keys = False try: ssh.connect(self.ip, port=self.port, username=self.login, password=self.password, key_filename=self.path_to_private_key, look_for_keys=look_for_keys, timeout=self.conn_timeout) # Paramiko by default sets the socket timeout to 0.1 seconds, # ignoring what we set through the sshclient. This doesn't help for # keeping long lived connections. Hence we have to bypass it, by # overriding it after the transport is initialized. We are setting # the sockettimeout to None and setting a keepalive packet so that, # the server will keep the connection open. All that does is send # a keepalive packet every ssh_conn_timeout seconds. if self.conn_timeout: transport = ssh.get_transport() transport.sock.settimeout(None) transport.set_keepalive(self.conn_timeout) return ssh except Exception as e: msg = _("Check whether private key or password are correctly " "set. Error connecting via ssh: %s") % e LOG.error(msg) raise exception.SSHException(msg) def get(self): """Return an item from the pool, when one is available. This may cause the calling greenthread to block. Check if a connection is active before returning it. For dead connections create and return a new connection. """ if self.free_items: conn = self.free_items.popleft() if conn: if conn.get_transport().is_active(): return conn else: conn.close() return self.create() if self.current_size < self.max_size: created = self.create() self.current_size += 1 return created return self.channel.get() def remove(self, ssh): """Close an ssh client and remove it from free_items.""" ssh.close() ssh = None if ssh in self.free_items: self.free_items.pop(ssh) if self.current_size > 0: self.current_size -= 1 def check_ssh_injection(cmd_list): ssh_injection_pattern = ['`', '$', '|', '||', ';', '&', '&&', '>', '>>', '<'] # Check whether injection attacks exist for arg in cmd_list: arg = arg.strip() # Check for matching quotes on the ends is_quoted = re.match('^(?P<quote>[\'"])(?P<quoted>.*)(?P=quote)$', arg) if is_quoted: # Check for unescaped quotes within the quoted argument quoted = is_quoted.group('quoted') if quoted: if (re.match('[\'"]', quoted) or re.search('[^\\\\][\'"]', quoted)): raise exception.SSHInjectionThreat(command=cmd_list) else: # We only allow spaces within quoted arguments, and that # is the only special character allowed within quotes if len(arg.split()) > 1: raise exception.SSHInjectionThreat(command=cmd_list) # Second, check whether danger character in command. So the shell # special operator must be a single argument. for c in ssh_injection_pattern: if c not in arg: continue result = arg.find(c) if not result == -1: if result == 0 or not arg[result - 1] == '\\': raise exception.SSHInjectionThreat(command=cmd_list) class LazyPluggable(object): """A pluggable backend loaded lazily based on some value.""" def __init__(self, pivot, **backends): self.__backends = backends self.__pivot = pivot self.__backend = None def __get_backend(self): if not self.__backend: backend_name = CONF[self.__pivot] if backend_name not in self.__backends: raise exception.Error(_('Invalid backend: %s') % backend_name) backend = self.__backends[backend_name] if isinstance(backend, tuple): name = backend[0] fromlist = backend[1] else: name = backend fromlist = backend self.__backend = __import__(name, None, None, fromlist) LOG.debug('backend %s', self.__backend) return self.__backend def __getattr__(self, key): backend = self.__get_backend() return getattr(backend, key) def delete_if_exists(pathname): """Delete a file, but ignore file not found error.""" try: os.unlink(pathname) except OSError as e: if e.errno == errno.ENOENT: return else: raise def get_from_path(items, path): """Returns a list of items matching the specified path. Takes an XPath-like expression e.g. prop1/prop2/prop3, and for each item in items, looks up items[prop1][prop2][prop3]. Like XPath, if any of the intermediate results are lists it will treat each list item individually. A 'None' in items or any child expressions will be ignored, this function will not throw because of None (anywhere) in items. The returned list will contain no None values. """ if path is None: raise exception.Error('Invalid mini_xpath') (first_token, sep, remainder) = path.partition('/') if first_token == '': raise exception.Error('Invalid mini_xpath') results = [] if items is None: return results if not isinstance(items, list): # Wrap single objects in a list items = [items] for item in items: if item is None: continue get_method = getattr(item, 'get', None) if get_method is None: continue child = get_method(first_token) if child is None: continue if isinstance(child, list): # Flatten intermediate lists for x in child: results.append(x) else: results.append(child) if not sep: # No more tokens return results else: return get_from_path(results, remainder) def is_ipv6_configured(): """Check if system contain IPv6 capable network interface. :rtype: bool :raises: IOError """ try: fd = open('/proc/net/if_inet6') except IOError as e: if e.errno != errno.ENOENT: raise result = False else: result = bool(fd.read(32)) fd.close() return result def is_eventlet_bug105(): """Check if eventlet support IPv6 addresses. See https://bitbucket.org/eventlet/eventlet/issue/105 :rtype: bool """ try: mod = sys.modules['eventlet.support.greendns'] except KeyError: return False try: connect_data = mod.getaddrinfo('::1', 80) except socket.gaierror: return True fail = [x for x in connect_data if x[0] != socket.AF_INET6] return bool(fail) def monkey_patch(): """Patch decorator. If the Flags.monkey_patch set as True, this function patches a decorator for all functions in specified modules. You can set decorators for each modules using CONF.monkey_patch_modules. The format is "Module path:Decorator function". Example: 'manila.api.ec2.cloud:' \ manila.openstack.common.notifier.api.notify_decorator' Parameters of the decorator is as follows. (See manila.openstack.common.notifier.api.notify_decorator) name - name of the function function - object of the function """ # If CONF.monkey_patch is not True, this function do nothing. if not CONF.monkey_patch: return # Get list of modules and decorators for module_and_decorator in CONF.monkey_patch_modules: module, decorator_name = module_and_decorator.split(':') # import decorator function decorator = importutils.import_class(decorator_name) __import__(module) # Retrieve module information using pyclbr module_data = pyclbr.readmodule_ex(module) for key in module_data.keys(): # set the decorator for the class methods if isinstance(module_data[key], pyclbr.Class): clz = importutils.import_class("%s.%s" % (module, key)) # NOTE(vponomaryov): we need to distinguish class methods types # for py2 and py3, because the concept of 'unbound methods' has # been removed from the python3.x if six.PY3: member_type = inspect.isfunction else: member_type = inspect.ismethod for method, func in inspect.getmembers(clz, member_type): setattr( clz, method, decorator("%s.%s.%s" % (module, key, method), func)) # set the decorator for the function if isinstance(module_data[key], pyclbr.Function): func = importutils.import_class("%s.%s" % (module, key)) setattr(sys.modules[module], key, decorator("%s.%s" % (module, key), func)) def read_cached_file(filename, cache_info, reload_func=None): """Read from a file if it has been modified. :param cache_info: dictionary to hold opaque cache. :param reload_func: optional function to be called with data when file is reloaded due to a modification. :returns: data from file """ mtime = os.path.getmtime(filename) if not cache_info or mtime != cache_info.get('mtime'): with open(filename) as fap: cache_info['data'] = fap.read() cache_info['mtime'] = mtime if reload_func: reload_func(cache_info['data']) return cache_info['data'] def file_open(*args, **kwargs): """Open file see built-in file() documentation for more details Note: The reason this is kept in a separate module is to easily be able to provide a stub module that doesn't alter system state at all (for unit tests) """ return file(*args, **kwargs) def service_is_up(service): """Check whether a service is up based on last heartbeat.""" last_heartbeat = service['updated_at'] or service['created_at'] # Timestamps in DB are UTC. tdelta = timeutils.utcnow() - last_heartbeat elapsed = tdelta.total_seconds() return abs(elapsed) <= CONF.service_down_time def validate_service_host(context, host): service = db_api.service_get_by_host_and_topic(context, host, 'manila-share') if not service_is_up(service): raise exception.ServiceIsDown(service=service['host']) return service def read_file_as_root(file_path): """Secure helper to read file as root.""" try: out, _err = execute('cat', file_path, run_as_root=True) return out except exception.ProcessExecutionError: raise exception.FileNotFound(file_path=file_path) @contextlib.contextmanager def temporary_chown(path, owner_uid=None): """Temporarily chown a path. :params owner_uid: UID of temporary owner (defaults to current user) """ if owner_uid is None: owner_uid = os.getuid() orig_uid = os.stat(path).st_uid if orig_uid != owner_uid: execute('chown', owner_uid, path, run_as_root=True) try: yield finally: if orig_uid != owner_uid: execute('chown', orig_uid, path, run_as_root=True) @contextlib.contextmanager def tempdir(**kwargs): tmpdir = tempfile.mkdtemp(**kwargs) try: yield tmpdir finally: try: shutil.rmtree(tmpdir) except OSError as e: LOG.debug('Could not remove tmpdir: %s', six.text_type(e)) def walk_class_hierarchy(clazz, encountered=None): """Walk class hierarchy, yielding most derived classes first.""" if not encountered: encountered = [] for subclass in clazz.__subclasses__(): if subclass not in encountered: encountered.append(subclass) # drill down to leaves first for subsubclass in walk_class_hierarchy(subclass, encountered): yield subsubclass yield subclass def ensure_tree(path): """Create a directory (and any ancestor directories required) :param path: Directory to create """ try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST: if not os.path.isdir(path): raise else: raise def cidr_to_netmask(cidr): """Convert cidr to netmask.""" try: network = netaddr.IPNetwork(cidr) return str(network.netmask) except netaddr.AddrFormatError: raise exception.InvalidInput(_("Invalid cidr supplied %s") % cidr) def is_valid_ip_address(ip_address, ip_version): if int(ip_version) == 4: return netaddr.valid_ipv4(ip_address) elif int(ip_version) == 6: return netaddr.valid_ipv6(ip_address) else: raise exception.ManilaException( _("Provided improper IP version '%s'.") % ip_version) class IsAMatcher(object): def __init__(self, expected_value=None): self.expected_value = expected_value def __eq__(self, actual_value): return isinstance(actual_value, self.expected_value) class ComparableMixin(object): def _compare(self, other, method): try: return method(self._cmpkey(), other._cmpkey()) except (AttributeError, TypeError): # _cmpkey not implemented, or return different type, # so I can't compare with "other". return NotImplemented def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def __eq__(self, other): return self._compare(other, lambda s, o: s == o) def __ge__(self, other): return self._compare(other, lambda s, o: s >= o) def __gt__(self, other): return self._compare(other, lambda s, o: s > o) def __ne__(self, other): return self._compare(other, lambda s, o: s != o) def retry(exception, interval=1, retries=10, backoff_rate=2, wait_random=False): """A wrapper around retrying library. This decorator allows to log and to check 'retries' input param. Time interval between retries is calculated in the following way: interval * backoff_rate ^ previous_attempt_number :param exception: expected exception type. When wrapped function raises an exception of this type, the function execution is retried. :param interval: param 'interval' is used to calculate time interval between retries: interval * backoff_rate ^ previous_attempt_number :param retries: number of retries. :param backoff_rate: param 'backoff_rate' is used to calculate time interval between retries: interval * backoff_rate ^ previous_attempt_number :param wait_random: boolean value to enable retry with random wait timer. """ def _retry_on_exception(e): return isinstance(e, exception) def _backoff_sleep(previous_attempt_number, delay_since_first_attempt_ms): exp = backoff_rate ** previous_attempt_number wait_for = max(0, interval * exp) if wait_random: wait_val = random.randrange(interval * 1000.0, wait_for * 1000.0) else: wait_val = wait_for * 1000.0 LOG.debug("Sleeping for %s seconds.", (wait_val / 1000.0)) return wait_val def _print_stop(previous_attempt_number, delay_since_first_attempt_ms): delay_since_first_attempt = delay_since_first_attempt_ms / 1000.0 LOG.debug("Failed attempt %s", previous_attempt_number) LOG.debug("Have been at this for %s seconds", delay_since_first_attempt) return previous_attempt_number == retries if retries < 1: raise ValueError(_('Retries must be greater than or ' 'equal to 1 (received: %s).') % retries) def _decorator(f): @six.wraps(f) def _wrapper(*args, **kwargs): r = retrying.Retrying(retry_on_exception=_retry_on_exception, wait_func=_backoff_sleep, stop_func=_print_stop) return r.call(f, *args, **kwargs) return _wrapper return _decorator def require_driver_initialized(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): # we can't do anything if the driver didn't init if not self.driver.initialized: driver_name = self.driver.__class__.__name__ raise exception.DriverNotInitialized(driver=driver_name) return func(self, *args, **kwargs) return wrapper ```
[ { "content": "Return the code exactly, with no changes:\n```python\nfrom __future__ import absolute_import\n\nimport pytest\n\nfrom datetime import datetime, timedelta\n\nfrom sentry.constants import MAX_VERSION_LENGTH, MAX_CULPRIT_LENGTH\nfrom sentry.event_manager import EventManager\n\n\ndef validate_and_norm...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\nfrom __future__ import absolute_import\n\nimport pytest\n\nfrom datetime import datetime, timedelta\n\nfrom sentry.constants import MAX_VERSION_LENGTH, MAX_CULPRIT_LENGTH\nfrom sentry.event_manager import EventManager\n\n\ndef v...
```python from __future__ import absolute_import import pytest from datetime import datetime, timedelta from sentry.constants import MAX_VERSION_LENGTH, MAX_CULPRIT_LENGTH from sentry.event_manager import EventManager def validate_and_normalize(data): manager = EventManager(data) manager.normalize() return manager.get_data() def test_timestamp(): data = validate_and_normalize({"timestamp": "not-a-timestamp"}) assert len(data["errors"]) == 1 now = datetime.utcnow() data = validate_and_normalize({"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ")}) assert "errors" not in data future = now + timedelta(minutes=2) data = validate_and_normalize({"timestamp": future.strftime("%Y-%m-%dT%H:%M:%SZ")}) assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "future_timestamp" past = now - timedelta(days=31) data = validate_and_normalize({"timestamp": past.strftime("%Y-%m-%dT%H:%M:%SZ")}) assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "past_timestamp" def test_empty_event_id(): data = validate_and_normalize({"event_id": ""}) assert len(data["event_id"]) == 32 def test_missing_event_id(): data = validate_and_normalize({}) assert len(data["event_id"]) == 32 def test_invalid_event_id(): data = validate_and_normalize({"event_id": "a" * 33}) assert len(data["event_id"]) == 32 assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "event_id" assert data["errors"][0]["value"] == "a" * 33 data = validate_and_normalize({"event_id": "xyz"}) assert len(data["event_id"]) == 32 assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "event_id" assert data["errors"][0]["value"] == "xyz" def test_unknown_attribute(): data = validate_and_normalize({"message": "foo", "foo": "bar"}) assert data["foo"] is None assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_attribute" assert data["errors"][0]["name"] == "foo" def test_invalid_interface_name(): data = validate_and_normalize({"message": "foo", "foo.baz": "bar"}) assert data["foo.baz"] is None assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_attribute" assert data["errors"][0]["name"] == "foo.baz" def test_invalid_interface_import_path(): data = validate_and_normalize({"message": "foo", "exception2": "bar"}) assert data["exception2"] is None assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_attribute" assert data["errors"][0]["name"] == "exception2" def test_does_expand_list(): data = validate_and_normalize( { "message": "foo", "exception": [{"type": "ValueError", "value": "hello world", "module": "foo.bar"}], } ) assert "exception" in data def test_log_level_as_string(): data = validate_and_normalize({"message": "foo", "level": "error"}) assert data["level"] == "error" def test_log_level_as_int(): data = validate_and_normalize({"message": "foo", "level": 40}) assert data["level"] == "error" def test_invalid_log_level(): data = validate_and_normalize({"message": "foo", "level": "foobar"}) assert data["level"] == "error" assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "level" assert data["errors"][0]["value"] == "foobar" def test_tags_as_string(): data = validate_and_normalize({"message": "foo", "tags": "bar"}) assert data["tags"] == [] def test_tags_with_spaces(): data = validate_and_normalize({"message": "foo", "tags": {"foo bar": "baz bar"}}) assert data["tags"] == [["foo-bar", "baz bar"]] def test_tags_out_of_bounds(): data = validate_and_normalize( {"message": "foo", "tags": {"f" * 33: "value", "foo": "v" * 201, "bar": "value"}} ) assert data["tags"] == [["bar", "value"], None, None] assert len(data["errors"]) == 2 def test_tags_as_invalid_pair(): data = validate_and_normalize( {"message": "foo", "tags": [("foo", "bar"), ("biz", "baz", "boz")]} ) assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "tags.1" assert data["errors"][0]["value"] == ["biz", "baz", "boz"] def test_reserved_tags(): data = validate_and_normalize( {"message": "foo", "tags": [("foo", "bar"), ("release", "abc123")]} ) assert data["tags"] == [["foo", "bar"]] def test_tag_value(): data = validate_and_normalize({"message": "foo", "tags": [("foo", "b\nar"), ("biz", "baz")]}) assert data["tags"] == [["foo", None], ["biz", "baz"]] assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "tags.0.1" assert data["errors"][0]["value"] == "b\nar" def test_extra_as_string(): data = validate_and_normalize({"message": "foo", "extra": "bar"}) assert data["extra"] == {} def test_release_tag_max_len(): release_key = u"sentry:release" release_value = "a" * MAX_VERSION_LENGTH data = validate_and_normalize({"message": "foo", "tags": [[release_key, release_value]]}) assert "errors" not in data assert data["tags"] == [[release_key, release_value]] def test_server_name_too_long(): key = u"server_name" value = "a" * (MAX_CULPRIT_LENGTH + 1) data = validate_and_normalize({key: value}) assert len(dict(data["tags"]).get(key)) == MAX_CULPRIT_LENGTH def test_site_too_long(): key = u"site" value = "a" * (MAX_CULPRIT_LENGTH + 1) data = validate_and_normalize({key: value}) assert len(dict(data["tags"]).get(key)) == MAX_CULPRIT_LENGTH def test_release_too_long(): data = validate_and_normalize({"release": "a" * (MAX_VERSION_LENGTH + 1)}) assert len(data.get("release")) == MAX_VERSION_LENGTH def test_release_as_non_string(): data = validate_and_normalize({"release": 42}) assert data.get("release") == "42" def test_distribution_too_long(): dist_len = 201 data = validate_and_normalize({"release": "a" * 62, "dist": "b" * dist_len}) assert len(data.get("dist")) == dist_len - 1 def test_distribution_bad_char(): data = validate_and_normalize({"release": "a" * 62, "dist": "^%"}) assert not data.get("dist") assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "dist" assert data["errors"][0]["value"] == "^%" def test_distribution_strip(): data = validate_and_normalize({"release": "a" * 62, "dist": " foo "}) assert data.get("dist") == "foo" def test_distribution_as_non_string(): data = validate_and_normalize({"release": "42", "dist": 23}) assert data.get("release") == "42" assert data.get("dist") is None def test_distribution_no_release(): data = validate_and_normalize({"dist": 23}) assert data.get("dist") is None def test_valid_platform(): data = validate_and_normalize({"platform": "python"}) assert data.get("platform") == "python" def test_no_platform(): data = validate_and_normalize({}) assert data.get("platform") == "other" def test_invalid_platform(): data = validate_and_normalize({"platform": "foobar"}) assert data.get("platform") == "other" def test_environment_too_long(): data = validate_and_normalize({"environment": "a" * 65}) assert len(data["environment"]) == 64 def test_environment_invalid(): data = validate_and_normalize({"environment": "a/b"}) assert not data.get("environment") error, = data["errors"] error["type"] == "invalid_data" assert error["name"] == "environment" assert error["value"] == "a/b" def test_environment_as_non_string(): data = validate_and_normalize({"environment": 42}) assert data.get("environment") is None def test_time_spent_too_large(): data = validate_and_normalize({"time_spent": 2147483647 + 1}) assert data.get("time_spent") is None def test_time_spent_invalid(): data = validate_and_normalize({"time_spent": "lol"}) assert not data.get("time_spent") assert len(data["errors"]) == 1 assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "time_spent" assert data["errors"][0]["value"] == "lol" def test_time_spent_non_int(): data = validate_and_normalize({"time_spent": "123"}) assert data["time_spent"] is None def test_fingerprints(): data = validate_and_normalize({"fingerprint": "2012-01-01T10:30:45"}) assert not data.get("fingerprint") assert data["errors"][0]["type"] == "invalid_data" assert data["errors"][0]["name"] == "fingerprint" data = validate_and_normalize({"fingerprint": ["foo", ["bar"]]}) assert data.get("fingerprint") == ["foo"] # With rust, there will be errors emitted data = validate_and_normalize({"fingerprint": ["foo", None, "bar"]}) assert data.get("fingerprint") == ["foo", "bar"] # With rust, there will be errors emitted data = validate_and_normalize({"fingerprint": ["{{default}}", 1, "bar", 4.5, -2.7, True]}) assert data.get("fingerprint") == ["{{default}}", "1", "bar", "4", "-2", "True"] assert "errors" not in data data = validate_and_normalize({"fingerprint": ["{{default}}", 1e100, -1e100, 1e10]}) assert data.get("fingerprint") == ["{{default}}", "10000000000"] assert data["errors"] == [ {"type": "invalid_data", "name": "fingerprint", "value": [1e100, -1e100]} ] data = validate_and_normalize({"fingerprint": []}) assert "fingerprint" not in data assert "errors" not in data data = validate_and_normalize({"fingerprint": [""]}) assert data["fingerprint"] == [""] assert "errors" not in data def test_messages(): # Just 'message': wrap it in interface data = validate_and_normalize({"message": "foo is bar"}) assert data["logentry"] == {"formatted": "foo is bar"} # both 'message' and interface with no 'formatted' value, put 'message' # into 'formatted'. data = validate_and_normalize( {"message": "foo is bar", "logentry": {"message": "something else"}} ) assert data["logentry"] == {"formatted": "something else"} # both 'message' and complete interface, 'message' is discarded data = validate_and_normalize( { "message": "foo is bar", "logentry": {"message": "something else", "formatted": "something else formatted"}, } ) assert "errors" not in data assert data["logentry"] == { "message": "something else", "formatted": "something else formatted", } @pytest.mark.skip(reason="Message behavior that didn't make a lot of sense.") def test_messages_old_behavior(): # both 'message' and complete valid interface but interface has the same # value for both keys so the 'formatted' value is discarded and ends up # being replaced with 'message' data = validate_and_normalize( { "message": "foo is bar", "logentry": {"message": "something else", "formatted": "something else"}, } ) assert "message" not in data assert "errors" not in data assert data["logentry"] == {"message": "something else", "formatted": "foo is bar"} # interface discarded as invalid, replaced by new interface containing # wrapped 'message' data = validate_and_normalize({"message": "foo is bar", "logentry": {"invalid": "invalid"}}) assert "message" not in data assert len(data["errors"]) == 1 assert data["logentry"] == {"message": "foo is bar"} ```
[ { "content": "Here is the code block:\n```python\n# -*- coding: utf-8 -*-\n#########################################################################\n#\n# Copyright (C) 2018 OSGeo\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License a...
[ { "content": "Here is the code block:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n#########################################################################\n#\n# Copyright (C) 2018 OSGeo\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General ...
```python # -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2018 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### import django import fileinput import glob import os import re import shutil import subprocess import signal import sys import time import urllib import urllib2 import zipfile from urlparse import urlparse import yaml from paver.easy import (BuildFailure, call_task, cmdopts, info, needs, options, path, sh, task) from setuptools.command import easy_install try: from paver.path import pushd except ImportError: from paver.easy import pushd from geonode.settings import (on_travis, core_tests, internal_apps_tests, integration_tests, INSTALLED_APPS, GEONODE_CORE_APPS, GEONODE_INTERNAL_APPS, GEONODE_APPS, OGC_SERVER, ASYNC_SIGNALS) _django_11 = django.VERSION[0] == 1 and django.VERSION[1] >= 11 and django.VERSION[2] >= 2 try: from geonode.settings import TEST_RUNNER_KEEPDB, TEST_RUNNER_PARALLEL _keepdb = '-k' if TEST_RUNNER_KEEPDB else '' _parallel = ('--parallel=%s' % TEST_RUNNER_PARALLEL) if TEST_RUNNER_PARALLEL else '' except: _keepdb = '' _parallel = '' assert sys.version_info >= (2, 6), \ SystemError("GeoNode Build requires python 2.6 or better") dev_config = None with open("dev_config.yml", 'r') as f: dev_config = yaml.load(f) def grab(src, dest, name): download = True if not dest.exists(): print('Downloading %s' % name) elif not zipfile.is_zipfile(dest): print('Downloading %s (corrupt file)' % name) else: download = False if download: if str(src).startswith("file://"): src2 = src[7:] if not os.path.exists(src2): print("Source location (%s) does not exist" % str(src2)) else: print("Copying local file from %s" % str(src2)) shutil.copyfile(str(src2), str(dest)) else: # urllib.urlretrieve(str(src), str(dest)) from tqdm import tqdm import requests import math # Streaming, so we can iterate over the response. r = requests.get(str(src), stream=True, timeout=10) # Total size in bytes. total_size = int(r.headers.get('content-length', 0)) print("Requesting %s" % str(src)) block_size = 1024 wrote = 0 with open('output.bin', 'wb') as f: for data in tqdm(r.iter_content(block_size), total=math.ceil(total_size//block_size) , unit='KB', unit_scale=False): wrote = wrote + len(data) f.write(data) print(" total_size [%d] / wrote [%d] " % (total_size, wrote)) if total_size != 0 and wrote != total_size: print("ERROR, something went wrong") else: shutil.move('output.bin', str(dest)) try: # Cleaning up os.remove('output.bin') except OSError: pass @task @cmdopts([ ('geoserver=', 'g', 'The location of the geoserver build (.war file).'), ('jetty=', 'j', 'The location of the Jetty Runner (.jar file).'), ]) def setup_geoserver(options): """Prepare a testing instance of GeoServer.""" # only start if using Geoserver backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.qgis_server' or 'geonode.geoserver' not in INSTALLED_APPS: return download_dir = path('downloaded') if not download_dir.exists(): download_dir.makedirs() geoserver_dir = path('geoserver') geoserver_bin = download_dir / \ os.path.basename(dev_config['GEOSERVER_URL']) jetty_runner = download_dir / \ os.path.basename(dev_config['JETTY_RUNNER_URL']) grab( options.get( 'geoserver', dev_config['GEOSERVER_URL']), geoserver_bin, "geoserver binary") grab( options.get( 'jetty', dev_config['JETTY_RUNNER_URL']), jetty_runner, "jetty runner") if not geoserver_dir.exists(): geoserver_dir.makedirs() webapp_dir = geoserver_dir / 'geoserver' if not webapp_dir: webapp_dir.makedirs() print 'extracting geoserver' z = zipfile.ZipFile(geoserver_bin, "r") z.extractall(webapp_dir) _install_data_dir() @task def setup_qgis_server(options): """Prepare a testing instance of QGIS Server.""" # only start if using QGIS Server backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.geoserver' or 'geonode.qgis_server' not in INSTALLED_APPS: return # QGIS Server testing instance run on top of docker try: sh('scripts/misc/docker_check.sh') except BaseException: info("You need to have docker and docker-compose installed.") return info('Docker and docker-compose were installed.') info('Proceeded to setup QGIS Server.') info('Create QGIS Server related folder.') try: os.makedirs('geonode/qgis_layer') except BaseException: pass try: os.makedirs('geonode/qgis_tiles') except BaseException: pass all_permission = 0o777 os.chmod('geonode/qgis_layer', all_permission) stat = os.stat('geonode/qgis_layer') info('Mode : %o' % stat.st_mode) os.chmod('geonode/qgis_tiles', all_permission) stat = os.stat('geonode/qgis_tiles') info('Mode : %o' % stat.st_mode) info('QGIS Server related folder successfully setup.') def _robust_rmtree(path, logger=None, max_retries=5): """Try to delete paths robustly . Retries several times (with increasing delays) if an OSError occurs. If the final attempt fails, the Exception is propagated to the caller. Taken from https://github.com/hashdist/hashdist/pull/116 """ for i in range(max_retries): try: shutil.rmtree(path) return except OSError as e: if logger: info('Unable to remove path: %s' % path) info('Retrying after %d seconds' % i) time.sleep(i) # Final attempt, pass any Exceptions up to caller. shutil.rmtree(path) def _install_data_dir(): target_data_dir = path('geoserver/data') if target_data_dir.exists(): try: target_data_dir.rmtree() except OSError: _robust_rmtree(target_data_dir, logger=True) original_data_dir = path('geoserver/geoserver/data') justcopy(original_data_dir, target_data_dir) try: config = path( 'geoserver/data/global.xml') with open(config) as f: xml = f.read() m = re.search('proxyBaseUrl>([^<]+)', xml) xml = xml[:m.start(1)] + \ "http://localhost:8080/geoserver" + xml[m.end(1):] with open(config, 'w') as f: f.write(xml) except Exception as e: print(e) try: config = path( 'geoserver/data/security/filter/geonode-oauth2/config.xml') with open(config) as f: xml = f.read() m = re.search('accessTokenUri>([^<]+)', xml) xml = xml[:m.start(1)] + \ "http://localhost:8000/o/token/" + xml[m.end(1):] m = re.search('userAuthorizationUri>([^<]+)', xml) xml = xml[:m.start( 1)] + "http://localhost:8000/o/authorize/" + xml[m.end(1):] m = re.search('redirectUri>([^<]+)', xml) xml = xml[:m.start( 1)] + "http://localhost:8080/geoserver/index.html" + xml[m.end(1):] m = re.search('checkTokenEndpointUrl>([^<]+)', xml) xml = xml[:m.start( 1)] + "http://localhost:8000/api/o/v4/tokeninfo/" + xml[m.end(1):] m = re.search('logoutUri>([^<]+)', xml) xml = xml[:m.start( 1)] + "http://localhost:8000/account/logout/" + xml[m.end(1):] with open(config, 'w') as f: f.write(xml) except Exception as e: print(e) try: config = path( 'geoserver/data/security/role/geonode REST role service/config.xml') with open(config) as f: xml = f.read() m = re.search('baseUrl>([^<]+)', xml) xml = xml[:m.start(1)] + "http://localhost:8000" + xml[m.end(1):] with open(config, 'w') as f: f.write(xml) except Exception as e: print(e) @task def static(options): with pushd('geonode/static'): sh('grunt production') @task @needs([ 'setup_geoserver', 'setup_qgis_server', ]) def setup(options): """Get dependencies and prepare a GeoNode development environment.""" updategeoip(options) info(('GeoNode development environment successfully set up.' 'If you have not set up an administrative account,' ' please do so now. Use "paver start" to start up the server.')) def grab_winfiles(url, dest, packagename): # Add headers headers = {'User-Agent': 'Mozilla 5.10'} request = urllib2.Request(url, None, headers) response = urllib2.urlopen(request) with open(dest, 'wb') as writefile: writefile.write(response.read()) @task def win_install_deps(options): """ Install all Windows Binary automatically This can be removed as wheels become available for these packages """ download_dir = path('downloaded').abspath() if not download_dir.exists(): download_dir.makedirs() win_packages = { # required by transifex-client "Py2exe": dev_config['WINDOWS']['py2exe'], "Nose": dev_config['WINDOWS']['nose'], # the wheel 1.9.4 installs but pycsw wants 1.9.3, which fails to compile # when pycsw bumps their pyproj to 1.9.4 this can be removed. "PyProj": dev_config['WINDOWS']['pyproj'], "lXML": dev_config['WINDOWS']['lxml'] } failed = False for package, url in win_packages.iteritems(): tempfile = download_dir / os.path.basename(url) print "Installing file ... " + tempfile grab_winfiles(url, tempfile, package) try: easy_install.main([tempfile]) except Exception as e: failed = True print "install failed with error: ", e os.remove(tempfile) if failed and sys.maxsize > 2**32: print "64bit architecture is not currently supported" print "try finding the 64 binaries for py2exe, nose, and pyproj" elif failed: print "install failed for py2exe, nose, and/or pyproj" else: print "Windows dependencies now complete. Run pip install -e geonode --use-mirrors" @cmdopts([ ('version=', 'v', 'Legacy GeoNode version of the existing database.') ]) @task def upgradedb(options): """ Add 'fake' data migrations for existing tables from legacy GeoNode versions """ version = options.get('version') if version in ['1.1', '1.2']: sh("python -W ignore manage.py migrate maps 0001 --fake") sh("python -W ignore manage.py migrate avatar 0001 --fake") elif version is None: print "Please specify your GeoNode version" else: print "Upgrades from version %s are not yet supported." % version @task def updategeoip(options): """ Update geoip db """ settings = options.get('settings', '') if settings: settings = 'DJANGO_SETTINGS_MODULE=%s' % settings sh("%s python -W ignore manage.py updategeoip -o" % settings) @task @cmdopts([ ('settings', 's', 'Specify custom DJANGO_SETTINGS_MODULE') ]) def sync(options): """ Run the migrate and migrate management commands to create and migrate a DB """ settings = options.get('settings', '') if settings: settings = 'DJANGO_SETTINGS_MODULE=%s' % settings sh("%s python -W ignore manage.py makemigrations --noinput" % settings) sh("%s python -W ignore manage.py migrate --noinput" % settings) sh("%s python -W ignore manage.py loaddata sample_admin.json" % settings) sh("%s python -W ignore manage.py loaddata geonode/base/fixtures/default_oauth_apps.json" % settings) sh("%s python -W ignore manage.py loaddata geonode/base/fixtures/initial_data.json" % settings) sh("%s python -W ignore manage.py set_all_layers_alternate" % settings) @task def package(options): """ Creates a tarball to use for building the system elsewhere """ import tarfile import geonode version = geonode.get_version() # Use GeoNode's version for the package name. pkgname = 'GeoNode-%s-all' % version # Create the output directory. out_pkg = path(pkgname) out_pkg_tar = path("%s.tar.gz" % pkgname) # Create a distribution in zip format for the geonode python package. dist_dir = path('dist') dist_dir.rmtree() sh('python setup.py sdist --formats=zip') with pushd('package'): # Delete old tar files in that directory for f in glob.glob('GeoNode*.tar.gz'): old_package = path(f) if old_package != out_pkg_tar: old_package.remove() if out_pkg_tar.exists(): info('There is already a package for version %s' % version) return # Clean anything that is in the oupout package tree. out_pkg.rmtree() out_pkg.makedirs() support_folder = path('support') install_file = path('install.sh') # And copy the default files from the package folder. justcopy(support_folder, out_pkg / 'support') justcopy(install_file, out_pkg) geonode_dist = path('..') / 'dist' / 'GeoNode-%s.zip' % version justcopy(geonode_dist, out_pkg) # Create a tar file with all files in the output package folder. tar = tarfile.open(out_pkg_tar, "w:gz") for file in out_pkg.walkfiles(): tar.add(file) # Add the README with the license and important links to documentation. tar.add('README', arcname=('%s/README.rst' % out_pkg)) tar.close() # Remove all the files in the temporary output package directory. out_pkg.rmtree() # Report the info about the new package. info("%s created" % out_pkg_tar.abspath()) @task @needs(['start_geoserver', 'start_qgis_server', 'start_django']) @cmdopts([ ('bind=', 'b', 'Bind server to provided IP address and port number.'), ('java_path=', 'j', 'Full path to java install for Windows'), ('foreground', 'f', 'Do not run in background but in foreground'), ('settings', 's', 'Specify custom DJANGO_SETTINGS_MODULE') ], share_with=['start_django', 'start_geoserver']) def start(): """ Start GeoNode (Django, GeoServer & Client) """ sh('sleep 30') info("GeoNode is now available.") @task def stop_django(): """ Stop the GeoNode Django application """ kill('python', 'celery') kill('python', 'runserver') kill('python', 'runmessaging') @task def stop_geoserver(): """ Stop GeoServer """ # we use docker-compose for integration tests if integration_tests: return # only start if using Geoserver backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.qgis_server' or 'geonode.geoserver' not in INSTALLED_APPS: return kill('java', 'geoserver') # Kill process. try: # proc = subprocess.Popen("ps -ef | grep -i -e '[j]ava\|geoserver' | # awk '{print $2}'", proc = subprocess.Popen( "ps -ef | grep -i -e 'geoserver' | awk '{print $2}'", shell=True, stdout=subprocess.PIPE) for pid in proc.stdout: info('Stopping geoserver (process number %s)' % int(pid)) os.kill(int(pid), signal.SIGKILL) os.kill(int(pid), 9) sh('sleep 30') # Check if the process that we killed is alive. try: os.kill(int(pid), 0) # raise Exception("""wasn't able to kill the process\nHINT:use # signal.SIGKILL or signal.SIGABORT""") except OSError as ex: continue except Exception as e: info(e) @task @cmdopts([ ('qgis_server_port=', 'p', 'The port of the QGIS Server instance.') ]) def stop_qgis_server(): """ Stop QGIS Server Backend. """ # only start if using QGIS Server backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.geoserver' or 'geonode.qgis_server' not in INSTALLED_APPS: return port = options.get('qgis_server_port', '9000') sh( 'docker-compose -f docker-compose-qgis-server.yml down', env={ 'GEONODE_PROJECT_PATH': os.getcwd(), 'QGIS_SERVER_PORT': port }) @task @needs([ 'stop_geoserver', 'stop_qgis_server' ]) def stop(): """ Stop GeoNode """ # windows needs to stop the geoserver first b/c we can't tell which python # is running, so we kill everything info("Stopping GeoNode ...") stop_django() @cmdopts([ ('bind=', 'b', 'Bind server to provided IP address and port number.') ]) @task def start_django(): """ Start the GeoNode Django application """ settings = options.get('settings', '') if settings: settings = 'DJANGO_SETTINGS_MODULE=%s' % settings bind = options.get('bind', '0.0.0.0:8000') foreground = '' if options.get('foreground', False) else '&' sh('%s python -W ignore manage.py runserver %s %s' % (settings, bind, foreground)) if ASYNC_SIGNALS: celery_queues = [ "default", "geonode", "cleanup", "update", "email", # Those queues are directly managed by messages.consumer # "broadcast", # "email.events", # "all.geoserver", # "geoserver.events", # "geoserver.data", # "geoserver.catalog", # "notifications.events", # "geonode.layer.viewer" ] sh('%s celery -A geonode worker -Q %s -B -E -l INFO %s' % (settings, ",".join(celery_queues),foreground)) sh('%s python -W ignore manage.py runmessaging %s' % (settings, foreground)) def start_messaging(): """ Start the GeoNode messaging server """ settings = options.get('settings', '') if settings: settings = 'DJANGO_SETTINGS_MODULE=%s' % settings foreground = '' if options.get('foreground', False) else '&' sh('%s python -W ignore manage.py runmessaging %s' % (settings, foreground)) @cmdopts([ ('java_path=', 'j', 'Full path to java install for Windows') ]) @task def start_geoserver(options): """ Start GeoServer with GeoNode extensions """ # we use docker-compose for integration tests if integration_tests: return # only start if using Geoserver backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.qgis_server' or 'geonode.geoserver' not in INSTALLED_APPS: return GEOSERVER_BASE_URL = OGC_SERVER['default']['LOCATION'] url = GEOSERVER_BASE_URL if urlparse(GEOSERVER_BASE_URL).hostname != 'localhost': print "Warning: OGC_SERVER['default']['LOCATION'] hostname is not equal to 'localhost'" if not GEOSERVER_BASE_URL.endswith('/'): print "Error: OGC_SERVER['default']['LOCATION'] does not end with a '/'" sys.exit(1) download_dir = path('downloaded').abspath() jetty_runner = download_dir / \ os.path.basename(dev_config['JETTY_RUNNER_URL']) data_dir = path('geoserver/data').abspath() geofence_dir = path('geoserver/data/geofence').abspath() web_app = path('geoserver/geoserver').abspath() log_file = path('geoserver/jetty.log').abspath() config = path('scripts/misc/jetty-runner.xml').abspath() jetty_port = urlparse(GEOSERVER_BASE_URL).port import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_free = True try: s.bind(("127.0.0.1", jetty_port)) except socket.error as e: socket_free = False if e.errno == 98: info('Port %s is already in use' % jetty_port) else: info( 'Something else raised the socket.error exception while checking port %s' % jetty_port) print(e) finally: s.close() if socket_free: # @todo - we should not have set workdir to the datadir but a bug in geoserver # prevents geonode security from initializing correctly otherwise with pushd(data_dir): javapath = "java" loggernullpath = os.devnull # checking if our loggernullpath exists and if not, reset it to # something manageable if loggernullpath == "nul": try: open("../../downloaded/null.txt", 'w+').close() except IOError as e: print "Chances are that you have Geoserver currently running. You \ can either stop all servers with paver stop or start only \ the django application with paver start_django." sys.exit(1) loggernullpath = "../../downloaded/null.txt" try: sh(('java -version')) except BaseException: print "Java was not found in your path. Trying some other options: " javapath_opt = None if os.environ.get('JAVA_HOME', None): print "Using the JAVA_HOME environment variable" javapath_opt = os.path.join(os.path.abspath( os.environ['JAVA_HOME']), "bin", "java.exe") elif options.get('java_path'): javapath_opt = options.get('java_path') else: print "Paver cannot find java in the Windows Environment. \ Please provide the --java_path flag with your full path to \ java.exe e.g. --java_path=C:/path/to/java/bin/java.exe" sys.exit(1) # if there are spaces javapath = 'START /B "" "' + javapath_opt + '"' sh(( '%(javapath)s -Xms512m -Xmx2048m -server -XX:+UseConcMarkSweepGC -XX:MaxPermSize=512m' ' -DGEOSERVER_DATA_DIR=%(data_dir)s' ' -Dgeofence.dir=%(geofence_dir)s' # ' -Dgeofence-ovr=geofence-datasource-ovr.properties' # workaround for JAI sealed jar issue and jetty classloader # ' -Dorg.eclipse.jetty.server.webapp.parentLoaderPriority=true' ' -jar %(jetty_runner)s' ' --port %(jetty_port)i' ' --log %(log_file)s' ' %(config)s' ' > %(loggernullpath)s &' % locals() )) info('Starting GeoServer on %s' % url) # wait for GeoServer to start started = waitfor(url) info('The logs are available at %s' % log_file) if not started: # If applications did not start in time we will give the user a chance # to inspect them and stop them manually. info(('GeoServer never started properly or timed out.' 'It may still be running in the background.')) sys.exit(1) @task @cmdopts([ ('qgis_server_port=', 'p', 'The port of the QGIS Server instance.') ]) def start_qgis_server(): """Start QGIS Server instance with GeoNode related plugins.""" # only start if using QGIS Serrver backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.geoserver' or 'geonode.qgis_server' not in INSTALLED_APPS: return info('Starting up QGIS Server...') port = options.get('qgis_server_port', '9000') sh( 'docker-compose -f docker-compose-qgis-server.yml up -d qgis-server', env={ 'GEONODE_PROJECT_PATH': os.getcwd(), 'QGIS_SERVER_PORT': port }) info('QGIS Server is up.') @task def test(options): """ Run GeoNode's Unit Test Suite """ if on_travis: if core_tests: _apps = tuple(GEONODE_CORE_APPS) if internal_apps_tests: _apps = tuple(GEONODE_INTERNAL_APPS) else: _apps = tuple(GEONODE_APPS) sh("%s manage.py test %s.tests --noinput %s %s" % (options.get('prefix'), '.tests '.join(_apps), _keepdb, _parallel)) @task @cmdopts([ ('local=', 'l', 'Set to True if running bdd tests locally') ]) def test_bdd(): """ Run GeoNode's BDD Test Suite """ local = str2bool(options.get('local', 'false')) if local: call_task('reset_hard') call_task('setup') else: call_task('reset') call_task('setup') call_task('sync') sh('sleep 30') info("GeoNode is now available, running the bdd tests now.") sh('py.test') if local: call_task('reset_hard') @task def test_javascript(options): with pushd('geonode/static/geonode'): sh('./run-tests.sh') @task @cmdopts([ ('name=', 'n', 'Run specific tests.'), ('settings', 's', 'Specify custom DJANGO_SETTINGS_MODULE') ]) def test_integration(options): """ Run GeoNode's Integration test suite against the external apps """ _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.geoserver' or 'geonode.qgis_server' not in INSTALLED_APPS: call_task('stop_geoserver') _reset() # Start GeoServer call_task('start_geoserver') else: call_task('stop_qgis_server') _reset() # Start QGis Server call_task('start_qgis_server') sh('sleep 30') name = options.get('name', 'geonode.tests.integration') settings = options.get('settings', '') if not settings and name == 'geonode.upload.tests.integration': if _django_11: sh("cp geonode/upload/tests/test_settings.py geonode/") settings = 'geonode.test_settings' else: settings = 'geonode.upload.tests.test_settings' success = False try: if name == 'geonode.tests.csw': call_task('sync', options={'settings': settings}) call_task('start', options={'settings': settings}) call_task('setup_data', options={'settings': settings}) settings = 'DJANGO_SETTINGS_MODULE=%s' % settings if settings else '' if name == 'geonode.upload.tests.integration': sh("%s python -W ignore manage.py makemigrations --noinput" % settings) sh("%s python -W ignore manage.py migrate --noinput" % settings) sh("%s python -W ignore manage.py loaddata sample_admin.json" % settings) sh("%s python -W ignore manage.py loaddata geonode/base/fixtures/default_oauth_apps.json" % settings) sh("%s python -W ignore manage.py loaddata geonode/base/fixtures/initial_data.json" % settings) call_task('start_geoserver') bind = options.get('bind', '0.0.0.0:8000') foreground = '' if options.get('foreground', False) else '&' sh('%s python -W ignore manage.py runmessaging %s' % (settings, foreground)) sh('%s python -W ignore manage.py runserver %s %s' % (settings, bind, foreground)) sh('sleep 30') settings = 'REUSE_DB=1 %s' % settings live_server_option = '--liveserver=localhost:8000' if _django_11: live_server_option = '' info("GeoNode is now available, running the tests now.") sh(('%s python -W ignore manage.py test %s' ' %s --noinput %s' % (settings, name, _keepdb, live_server_option))) except BuildFailure as e: info('Tests failed! %s' % str(e)) else: success = True finally: # don't use call task here - it won't run since it already has stop() call_task('stop_geoserver') _reset() if not success: sys.exit(1) @task @needs(['start_geoserver', 'start_qgis_server']) @cmdopts([ ('coverage', 'c', 'use this flag to generate coverage during test runs'), ('local=', 'l', 'Set to True if running bdd tests locally') ]) def run_tests(options): """ Executes the entire test suite. """ if options.get('coverage'): prefix = 'coverage run --branch --source=geonode --omit="*/management/*,geonode/contrib/*,*/test*,*/wsgi*,*/middleware*"' else: prefix = 'python' local = options.get('local', 'false') # travis uses default to false if not integration_tests: sh('%s manage.py test geonode.tests.smoke %s %s' % (prefix, _keepdb, _parallel)) call_task('test', options={'prefix': prefix}) else: call_task('test_integration') call_task('test_integration', options={'name': 'geonode.tests.csw'}) # only start if using Geoserver backend _backend = os.environ.get('BACKEND', OGC_SERVER['default']['BACKEND']) if _backend == 'geonode.geoserver' and 'geonode.geoserver' in INSTALLED_APPS: call_task('test_integration', options={'name': 'geonode.upload.tests.integration', 'settings': 'geonode.upload.tests.test_settings'}) call_task('test_bdd', options={'local': local}) sh('flake8 geonode') @task @needs(['stop']) def reset(): """ Reset a development environment (Database, GeoServer & Catalogue) """ _reset() def _reset(): from geonode import settings sh("rm -rf {path}".format( path=os.path.join(settings.PROJECT_ROOT, 'development.db') ) ) sh("rm -rf geonode/development.db") sh("rm -rf geonode/uploaded/*") _install_data_dir() @needs(['reset']) def reset_hard(): """ Reset a development environment (Database, GeoServer & Catalogue) """ sh("git clean -dxf") @task @cmdopts([ ('type=', 't', 'Import specific data type ("vector", "raster", "time")'), ('settings', 's', 'Specify custom DJANGO_SETTINGS_MODULE') ]) def setup_data(): """ Import sample data (from gisdata package) into GeoNode """ import gisdata ctype = options.get('type', None) data_dir = gisdata.GOOD_DATA if ctype in ['vector', 'raster', 'time']: data_dir = os.path.join(gisdata.GOOD_DATA, ctype) settings = options.get('settings', '') if settings: settings = 'DJANGO_SETTINGS_MODULE=%s' % settings sh("%s python -W ignore manage.py importlayers %s -v2" % (settings, data_dir)) @needs(['package']) @cmdopts([ ('key=', 'k', 'The GPG key to sign the package'), ('ppa=', 'p', 'PPA this package should be published to.'), ]) def deb(options): """ Creates debian packages. Example uses: paver deb paver deb -k 12345 paver deb -k 12345 -p geonode/testing """ key = options.get('key', None) ppa = options.get('ppa', None) version, simple_version = versions() info('Creating package for GeoNode version %s' % version) # Get rid of any uncommitted changes to debian/changelog info('Getting rid of any uncommitted changes in debian/changelog') sh('git checkout package/debian/changelog') # Workaround for git-dch bug # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=594580 sh('rm -rf %s/.git' % (os.path.realpath('package'))) sh('ln -s %s %s' % (os.path.realpath('.git'), os.path.realpath('package'))) with pushd('package'): # Install requirements # sh('sudo apt-get -y install debhelper devscripts git-buildpackage') # sh(('git-dch --spawn-editor=snapshot --git-author --new-version=%s' # ' --id-length=6 --ignore-branch --release' % (simple_version))) # In case you publish from Ubuntu Xenial (git-dch is removed from upstream) # use the following line instead: # sh(('gbp dch --spawn-editor=snapshot --git-author --new-version=%s' # ' --id-length=6 --ignore-branch --release' % (simple_version))) distribution = "bionic" # sh(('gbp dch --distribution=%s --force-distribution --spawn-editor=snapshot --git-author --new-version=%s' # ' --id-length=6 --ignore-branch --release' % (distribution, simple_version))) deb_changelog = path('debian') / 'changelog' for idx, line in enumerate(fileinput.input([deb_changelog], inplace=True)): if idx == 0: print "geonode (%s) %s; urgency=high" % (simple_version, distribution), else: print line.replace("urgency=medium", "urgency=high"), # Revert workaround for git-dhc bug sh('rm -rf .git') if key is None and ppa is None: print("A local installable package") sh('debuild -uc -us -A') elif key is None and ppa is not None: print("A sources package, signed by daemon") sh('debuild -S') elif key is not None and ppa is None: print("A signed installable package") sh('debuild -k%s -A' % key) elif key is not None and ppa is not None: print("A signed, source package") sh('debuild -k%s -S' % key) if ppa is not None: sh('dput ppa:%s geonode_%s_source.changes' % (ppa, simple_version)) @task def publish(): if 'GPG_KEY_GEONODE' in os.environ: key = os.environ['GPG_KEY_GEONODE'] else: print "You need to set the GPG_KEY_GEONODE environment variable" return if 'PPA_GEONODE' in os.environ: ppa = os.environ['PPA_GEONODE'] else: ppa = None call_task('deb', options={ 'key': key, 'ppa': ppa, # 'ppa': 'geonode/testing', # 'ppa': 'geonode/unstable', }) version, simple_version = versions() if ppa: sh('git add package/debian/changelog') sh('git commit -m "Updated changelog for version %s"' % version) sh('git tag -f %s' % version) sh('git push origin %s' % version) sh('git tag -f debian/%s' % simple_version) sh('git push origin debian/%s' % simple_version) # sh('git push origin master') sh('python setup.py sdist upload -r pypi') def versions(): import geonode from geonode.version import get_git_changeset raw_version = geonode.__version__ version = geonode.get_version() timestamp = get_git_changeset() major, minor, revision, stage, edition = raw_version branch = 'dev' if stage == 'final': stage = 'thefinal' if stage == 'unstable': tail = '%s%s' % (branch, timestamp) else: tail = '%s%s' % (stage, edition) simple_version = '%s.%s.%s+%s' % (major, minor, revision, tail) return version, simple_version def kill(arg1, arg2): """Stops a proces that contains arg1 and is filtered by arg2 """ from subprocess import Popen, PIPE # Wait until ready t0 = time.time() # Wait no more than these many seconds time_out = 30 running = True while running and time.time() - t0 < time_out: if os.name == 'nt': p = Popen('tasklist | find "%s"' % arg1, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=False) else: p = Popen('ps aux | grep %s' % arg1, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) lines = p.stdout.readlines() running = False for line in lines: # this kills all java.exe and python including self in windows if ('%s' % arg2 in line) or (os.name == 'nt' and '%s' % arg1 in line): running = True # Get pid fields = line.strip().split() info('Stopping %s (process number %s)' % (arg1, fields[1])) if os.name == 'nt': kill = 'taskkill /F /PID "%s"' % fields[1] else: kill = 'kill -9 %s 2> /dev/null' % fields[1] os.system(kill) # Give it a little more time time.sleep(1) else: pass if running: raise Exception('Could not stop %s: ' 'Running processes are\n%s' % (arg1, '\n'.join([l.strip() for l in lines]))) def waitfor(url, timeout=300): started = False for a in xrange(timeout): try: resp = urllib.urlopen(url) except IOError: pass else: if resp.getcode() == 200: started = True break time.sleep(1) return started def _copytree(src, dst, symlinks=False, ignore=None): if not os.path.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) elif os.path.isfile(s): shutil.copy2(s, d) def justcopy(origin, target): if os.path.isdir(origin): shutil.rmtree(target, ignore_errors=True) _copytree(origin, target) elif os.path.isfile(origin): if not os.path.exists(target): os.makedirs(target) shutil.copy(origin, target) def str2bool(v): if v and len(v) > 0: return v.lower() in ("yes", "true", "t", "1") else: return False ```
[ { "content": "Here is a code file:\n```python\n# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-\n# ex: set expandtab softtabstop=4 shiftwidth=4:\n#\n# Copyright (C) 2008-2016,2018 Contributor\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in comp...
[ { "content": "Here is a code file:\n<|memory_start|>```python\n# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-\n# ex: set expandtab softtabstop=4 shiftwidth=4:\n#\n# Copyright (C) 2008-2016,2018 Contributor\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this fil...
```python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008-2016,2018 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from collections import defaultdict from operator import attrgetter from sqlalchemy.orm import joinedload, subqueryload from aquilon.aqdb.model import ( ArchetypeParamDef, ParameterizedPersonality, PersonalityParameter, PersonalityStage, ) from aquilon.aqdb.model.feature import host_features from aquilon.worker.locks import NoLockKey, PlenaryKey from aquilon.worker.templates import ( Plenary, PlenaryCollection, PlenaryParameterized, PlenaryResource, StructurePlenary, ) from aquilon.worker.templates.entitlementutils import flatten_entitlements from aquilon.worker.templates.panutils import ( pan_append, pan_assign, pan_include, pan_include_if_exists, pan_variable, StructureTemplate, ) LOGGER = logging.getLogger(__name__) def get_parameters_by_feature(dbstage, dbfeature): param_def_holder = dbfeature.param_def_holder assert param_def_holder param = dbstage.parameters.get(param_def_holder, None) ret = {} for param_def in param_def_holder.param_definitions: if param: value = param.get_path(param_def.path, compel=False) else: value = None if value is None: value = param_def.parsed_default if value is not None: ret[param_def.path] = value return ret def staged_path(prefix, dbstage, suffix): if dbstage.name == "current": return "%s/%s/%s" % (prefix, dbstage.personality.name, suffix) else: return "%s/%s+%s/%s" % (prefix, dbstage.personality.name, dbstage.name, suffix) class PlenaryParameterizedPersonality(PlenaryParameterized): prefix = "personality" @classmethod def template_name(cls, dbobj): return "{}/{}/{}/{}/config".format( cls.prefix, dbobj.name, dbobj.location.location_type, dbobj.location.name) def body(self, lines): flatten_entitlements(lines, self.dbobj, prefix='/') for resholder in self.dbobj.resholders: if resholder.location != self.dbobj.location: continue lines.append("") for resource in sorted(resholder.resources, key=attrgetter('resource_type', 'name')): res_path = PlenaryResource.template_name(resource) pan_append( lines, '/system/resources/{}'.format(resource.resource_type), StructureTemplate(res_path)) Plenary.handlers[ParameterizedPersonality] = PlenaryParameterizedPersonality class PlenaryPersonality(PlenaryCollection): def __init__(self, dbstage, logger=LOGGER, allow_incomplete=True): super(PlenaryPersonality, self).__init__(logger=logger, allow_incomplete=allow_incomplete) self.append(PlenaryPersonalityBase.get_plenary(dbstage, allow_incomplete=allow_incomplete)) for defholder, dbparam in dbstage.parameters.items(): if not isinstance(defholder, ArchetypeParamDef): continue self.append(PlenaryPersonalityParameter.get_plenary(dbparam, allow_incomplete=allow_incomplete)) @classmethod def query_options(cls, prefix="", load_personality=True): options = [] if load_personality: options.append(joinedload(prefix + 'personality')) return options + [subqueryload(prefix + 'parameters'), subqueryload(prefix + 'features'), subqueryload(prefix + 'grns'), joinedload(prefix + 'features.feature'), joinedload(prefix + 'features.feature.param_def_holder'), subqueryload(prefix + 'features.feature.param_def_holder.param_definitions'), joinedload(prefix + 'features.model')] Plenary.handlers[PersonalityStage] = PlenaryPersonality class PlenaryPersonalityBase(Plenary): prefix = "personality" @classmethod def template_name(cls, dbstage): return staged_path(cls.prefix, dbstage, "config") @classmethod def loadpath(cls, dbstage): return dbstage.personality.archetype.name def body(self, lines): dbpers = self.dbobj.personality if self.dbobj.name == "current": pan_variable(lines, "PERSONALITY", dbpers.name) else: pan_variable(lines, "PERSONALITY", "%s+%s" % (dbpers.name, self.dbobj.name)) pan_assign(lines, "/system/personality/name", dbpers.name) if dbpers.staged: pan_assign(lines, "/system/personality/stage", self.dbobj.name) eon_id_map = defaultdict(set) for grn_rec in self.dbobj.grns: eon_id_map[grn_rec.target].add(grn_rec.grn.eon_id) for target in sorted(eon_id_map): for eon_id in sorted(eon_id_map[target]): pan_append(lines, "/system/eon_id_maps/%s" % target, eon_id) pan_assign(lines, "/system/personality/owner_eon_id", dbpers.owner_eon_id) user_list = sorted(dbusr.name for dbusr in dbpers.root_users) if user_list: pan_assign(lines, "/system/root_users", user_list) ng_list = sorted(ng.name for ng in dbpers.root_netgroups) if ng_list: pan_assign(lines, "/system/root_netgroups", ng_list) pre, post = host_features(self.dbobj) for dbfeature in sorted(frozenset() .union(pre) .union(post) .intersection(self.dbobj.param_features), key=attrgetter('name')): base_path = "/system/" + dbfeature.cfg_path params = get_parameters_by_feature(self.dbobj, dbfeature) for key in sorted(params.keys()): pan_assign(lines, base_path + "/" + key, params[key]) for dbfeature in sorted(pre, key=attrgetter('name')): pan_include(lines, dbfeature.cfg_path + "/config") pan_append(lines, "/metadata/features", dbfeature.cfg_path + "/config") pan_include_if_exists(lines, "personality/config") if dbpers.host_environment.name != 'legacy': pan_assign(lines, "/system/personality/host_environment", dbpers.host_environment, True) if dbpers.config_override: pan_include(lines, "features/personality/config_override/config") for dbfeature in sorted(post, key=attrgetter('name')): pan_include(lines, dbfeature.cfg_path + "/config") pan_append(lines, "/metadata/features", dbfeature.cfg_path + "/config") def get_key(self, exclusive=True): if self.is_deleted(): return NoLockKey(logger=self.logger) else: return PlenaryKey(personality=self.dbobj, logger=self.logger, exclusive=exclusive) class PlenaryPersonalityParameter(StructurePlenary): prefix = "personality" @classmethod def template_name(cls, dbparam): return staged_path(cls.prefix, dbparam.personality_stage, dbparam.param_def_holder.template) @classmethod def loadpath(cls, dbparam): return dbparam.personality_stage.personality.archetype.name def __init__(self, *args, **kwargs): super(PlenaryPersonalityParameter, self).__init__(*args, **kwargs) self.debug_name = "%s/%s" % (self.dbobj.personality_stage.qualified_name, self.dbobj.param_def_holder.template) def body(self, lines): dbparam = self.dbobj param_def_holder = dbparam.param_def_holder for param_def in sorted(param_def_holder.param_definitions, key=attrgetter('path')): value = dbparam.get_path(param_def.path, compel=False) if value is None: value = param_def.parsed_default if value is None: continue # Do a single-level expansion of JSON parameters. This should be # more efficient to compile according to the Pan documentation, and # it also avoids trying to assign a value to an empty path if a # single parameter definition covers the whole template if isinstance(value, dict): for k in sorted(value): v = value[k] if param_def.path: pan_assign(lines, param_def.path + "/" + k, v) else: pan_assign(lines, k, v) else: pan_assign(lines, param_def.path, value) def get_key(self, exclusive=True): if self.is_deleted(): return NoLockKey(logger=self.logger) else: return PlenaryKey(personality=self.dbobj.personality_stage, logger=self.logger, exclusive=exclusive) Plenary.handlers[PersonalityParameter] = PlenaryPersonalityParameter ```
[ { "content": "```python\n\"\"\"\n Priority Queue with Binary Heaps:\n ---------------------------------\n\nIntroduction:\n------------\n A priority queue acts like a queue in that you can dequeue and item by\nremoving it from the front. However, in a priority queue...
[ { "content": "<|memory_start|>```python\n\"\"\"\n Priority Queue with Binary Heaps:\n ---------------------------------\n\nIntroduction:\n------------\n A priority queue acts like a queue in that you can dequeue and item by\nremoving it from the front. However, in ...
```python """ Priority Queue with Binary Heaps: --------------------------------- Introduction: ------------ A priority queue acts like a queue in that you can dequeue and item by removing it from the front. However, in a priority queue the logical order of items inside the queue is determined by their priority. The highest priority items are at the front of the queue and the lowest priority items are at the back. The classic way to implement a priority queue is using a data structure called a binary heap. A binary heap will allow us to both enqueue and dequeue items in O(logn). The binary heap is interesting to study because when we diagram the heap it looks a lot like a tree, but when we implement it we only use a single list as an internal representation. The binary heap has two common variations: the 'min heap,' in which the smallest key is always at the front, and the 'max heap,' in which the largest key is always at the front. In this section, we will implement the min heap. Basic Operations List: --------------------- BinaryHeap(): creates a new, empty binary heap. insert(k): adds a new item to the heap. findMin(): returns the item with the minimum key value, leaving item in the heap. delMin(): returns the item with the minimum key value, removing the item from the list. isEmpty(): returns true if the heap is empty, false otherwise. size(): returns the number of items in the heap. buildHeap(list): builds a new heap from a list of keys. The Structure Property: ----------------------- In order to make our heap work effeciently, we will take advantage of the logarithmic nature of the tree to represent our heap. In order to guarantee logarithmic performance, we must keep our tree balanced. A balanced binary tree has roughly the same number of nodes in the left and right subtrees of the root. In our heap implemention we keep the tree balanced by creating a 'complete binary tree.' A complete binary tree is a tree in which each level has all of its nodes. The exception to this is the bottom of the tree, which we fill in from left to right. Interesting Property: --------------------- Another interesting property of a complete tree is that we can represent it using a single list. We do not need to use nodes and references or even lists of lists. Because the tree is complete, the left child of the parent (at position p) is is the node that is found a position 2p in the list. Similarly, the right child of the parent is at position 2p+1 in the list. The Heap Order Property: ------------------------ The 'heap order property' is as follows: In a heap, for every node x with parent p, the key in p is smaller than or equal to the key in x. Heap Operations: ---------------- We will begin our implemention of a binary heap with the constructor. Since the entire binary heap can be represented by a single list, all the constructor will do is initialize the list and an attribute currentSize to keep track of the current size of the heap. You will notice that an empty binary heap has a single zero as the first element of heapList and that this zero is not used, but is there so that a simple integer can be used in later methods. Insert method: -------------- The next method we will implement in 'insert.' The easiest, and most efficient, way to add an item to a list is to simply append the item to the end of the list. The good news about appending is that it guarantees that we will maintain the complete tree property. The bad news is that we will very likely violate the heap structure property. However, it is possible to write a method that will allow us to regain the heap structure property by comparing the newly added items with its parent. If the newly added item is less than its parent, then we can swap the item with its parent. Notice that when we percolate an item up, we are restoring the heap property between the newly added item and the parent. We are also perserving the heap property for any siblings. delMin method notes: -------------------- Since the heap property requires that the root of the tree be the smallest item in the tree, finding the minimum item is easy. The hard part of delMin is restoring full compliance with the heap structure and heap order properties after the root has been removed. We can restore our heap in two steps. 1. We will restore the root item by taking the last item in the list and moving it to the root position. 2. We will restore the heap order property by pushng the new root node down the tree to its proper position. In order to maintain the heap order property, all we need to do is swap the root with its smallest child less than the root. After the initial swap, we may repeat the swapping process with a node and its children until the node is swapped into a position on the tree where it is already less than both children. The code for percolating a node down the tree is found in the 'percDown' and 'minChild' methods. buildHeap method: ----------------- To finish our discussion of binary heaps, we will look at a method to build an entire heap from a list of keys. If we start with an entire list then we can build the whole heap in O(n) operations. We will start from the middle of the list. Although we start out in the middle of the tree and work our way back towards the root, the percDown method enusres that the largest child is always down the tree. Beacuse it is a complete binary tree, any nodes past the halfway point will be leaves and therefore have no children. """ class BinaryHeap: """ A priority queue acts like a queue in that you can dequeue and item by removing it from the front. However, in a priority queue the logical order of items inside the queue is determined by their priority. The highest priority items are at the front of the queue and the lowest priority items are at the back. """ def __init__(self): """ You will notice that an empty binary heap has a single zero as the first element of heapList and that this zero is not used, but is there so that a simple integer can be used in later methods. """ self.heapList = [0] self.currentSize = 0 def percUp(self, i): """ Compares the newly inserted item with its parent. If the item is less than its parents, then they will be switched. """ while i // 2 > 0: if self.heapList[i] < self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i = i // 2 def insert(self, k): """ Inserts a new item to the binary heap """ self.heapList.append(k) self.currentSize = self.currentSize + 1 self.percUp(self.currentSize) def percDown(self, i): """ Moves the root of the binary heap (or subtree of the heap) down to its proper place in the tree. """ while(i * 2) <= self.currentSize: mc = self.minChild(i) if self.heapList[i] > self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc def minChild(self, i): """ Returns the index of the min Child """ if i * 2 + 1 > self.currentSize: return i*2 else: if self.heapList[i*2] < self.heapList[i*2+1]: return i*2 else: return i*2+1 def delMin(self): """ Returns the smallest item in the Binary Heap """ retval = self.heapList[1] self.heapList[1] = self.heapList[self.currentSize] self.currentSize = self.currentSize - 1 self.heapList.pop() self.percDown(1) return retval def buildHeap(self, alist): """ Builds a Binary Heap from a list """ i = len(alist) // 2 self.currentSize = len(alist) self.heapList = [0] + alist[:] while (i>0): self.percDown(i) i = i - 1 def isEmpty(self): return self.currentSize == 0 if __name__ == "__main__": test = [5,7,3,11] test2 = [9,6,5,2,3] print("Binary heap test 1:\n\n") bh = BinaryHeap() for x in test: bh.insert(x) while not bh.isEmpty(): print(bh.delMin()) print("Binary heap test 2: \n\n") bh2 = BinaryHeap() bh2.buildHeap(test2) while not bh2.isEmpty(): print(bh2.delMin()) ```
[ { "content": "```python\n#Full working with icon working too.\n\n\nfrom distutils.core import setup\nimport py2exe\nimport os\n\nMFCDIR = r\"C:\\Python27\\Lib\\site-packages\\pythonwin\"\nMFCFILES = [\"mfc90.dll\", \"mfc90u.dll\", \"mfcm90.dll\", \"mfcm90u.dll\",\n \"Microsoft.VC90.MFC.manifest\"]\nm...
[ { "content": "<|memory_start|>```python\n#Full working with icon working too.\n\n\nfrom distutils.core import setup\nimport py2exe\nimport os\n\nMFCDIR = r\"C:\\Python27\\Lib\\site-packages\\pythonwin\"\nMFCFILES = [\"mfc90.dll\", \"mfc90u.dll\", \"mfcm90.dll\", \"mfcm90u.dll\",\n \"Microsoft.VC90.MF...
```python #Full working with icon working too. from distutils.core import setup import py2exe import os MFCDIR = r"C:\Python27\Lib\site-packages\pythonwin" MFCFILES = ["mfc90.dll", "mfc90u.dll", "mfcm90.dll", "mfcm90u.dll", "Microsoft.VC90.MFC.manifest"] mfcfiles = map(lambda x: os.path.join(MFCDIR, x), MFCFILES) data_files = mfcfiles #Find details in py2exe\build_exe.py and __init__.py setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "1.0.0", description = "An application to edit multiple files at once", name = "BB Multi File Renamer", data_files = data_files, # targets to build windows = [ { "script":"Main.py", "icon_resources":[(0,"desktop.ico")] } ], options = {"py2exe": { "dll_excludes":["MSVCP90.dll"], "includes" : ["win32ui","win32con","win32print"] } } ) ```
[ { "content": "Write the code verbatim:\n```python\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n=============================================\nManifold Learning methods on a severed sphere\n=============================================\n\nAn application of the different :ref:`manifold` techniques\non a...
[ { "content": "Write the code verbatim:\n<|memory_start|>```python\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n=============================================\nManifold Learning methods on a severed sphere\n=============================================\n\nAn application of the different :ref:`manifold` ...
```python #!/usr/bin/python # -*- coding: utf-8 -*- """ ============================================= Manifold Learning methods on a severed sphere ============================================= An application of the different :ref:`manifold` techniques on a spherical data-set. Here one can see the use of dimensionality reduction in order to gain some intuition regarding the Manifold learning methods. Regarding the dataset, the poles are cut from the sphere, as well as a thin slice down its side. This enables the manifold learning techniques to 'spread it open' whilst projecting it onto two dimensions. For a similiar example, where the methods are applied to the S-curve dataset, see :ref:`example_manifold_plot_compare_methods.py` Note that the purpose of the :ref:`MDS <multidimensional_scaling>` is to find a low-dimensional representation of the data (here 2D) in which the distances respect well the distances in the original high-dimensional space, unlike other manifold-learning algorithms, it does not seeks an isotropic representation of the data in the low-dimensional space. Here the manifold problem matches fairly that of representing a flat map of the Earth, as with `map projection <http://en.wikipedia.org/wiki/Map_projection>`_ """ # Author: Jaques Grobler <jaques.grobler@inria.fr> # License: BSD print __doc__ from time import time import numpy as np import pylab as pl from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from sklearn import manifold from sklearn.utils import check_random_state # Next line to silence pyflakes. Axes3D # Variables for manifold learning. n_neighbors = 10 n_samples = 1000 # Create our sphere. random_state = check_random_state(0) p = random_state.rand(n_samples) * (2 * np.pi - 0.55) t = random_state.rand(n_samples) * np.pi # Sever the poles from the sphere. indices = ((t < (np.pi - (np.pi / 8))) & (t > ((np.pi / 8)))) colors = p[indices] x, y, z = np.sin(t[indices]) * np.cos(p[indices]), \ np.sin(t[indices]) * np.sin(p[indices]), \ np.cos(t[indices]) # Plot our dataset. fig = pl.figure(figsize=(15, 8)) pl.suptitle("Manifold Learning with %i points, %i neighbors" % (1000, n_neighbors), fontsize=14) ax = fig.add_subplot(241, projection='3d') ax.scatter(x, y, z, c=p[indices], cmap=pl.cm.rainbow) try: # compatibility matplotlib < 1.0 ax.view_init(40, -10) except: pass sphere_data = np.array([x, y, z]).T # Perform Locally Linear Embedding Manifold learning methods = ['standard', 'ltsa', 'hessian', 'modified'] labels = ['LLE', 'LTSA', 'Hessian LLE', 'Modified LLE'] for i, method in enumerate(methods): t0 = time() trans_data = manifold\ .LocallyLinearEmbedding(n_neighbors, 2, method=method).fit_transform(sphere_data).T t1 = time() print "%s: %.2g sec" % (methods[i], t1 - t0) ax = fig.add_subplot(242 + i) pl.scatter(trans_data[0], trans_data[1], c=colors, cmap=pl.cm.rainbow) pl.title("%s (%.2g sec)" % (labels[i], t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) pl.axis('tight') # Perform Isomap Manifold learning. t0 = time() trans_data = manifold.Isomap(n_neighbors, n_components=2)\ .fit_transform(sphere_data).T t1 = time() print "%s: %.2g sec" % ('ISO', t1 - t0) ax = fig.add_subplot(246) pl.scatter(trans_data[0], trans_data[1], c=colors, cmap=pl.cm.rainbow) pl.title("%s (%.2g sec)" % ('Isomap', t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) pl.axis('tight') # Perform Multi-dimensional scaling. t0 = time() mds = manifold.MDS(2, max_iter=100, n_init=1) trans_data = mds.fit_transform(sphere_data).T t1 = time() print "MDS: %.2g sec" % (t1 - t0) ax = fig.add_subplot(247) pl.scatter(trans_data[0], trans_data[1], c=colors, cmap=pl.cm.rainbow) pl.title("MDS (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) pl.axis('tight') # Perform Spectral Embedding. t0 = time() se = manifold.SpectralEmbedding(n_components=2, n_neighbors=n_neighbors) trans_data = se.fit_transform(sphere_data).T t1 = time() print "Spectral Embedding: %.2g sec" % (t1 - t0) ax = fig.add_subplot(248) pl.scatter(trans_data[0], trans_data[1], c=colors, cmap=pl.cm.rainbow) pl.title("Spectral Embedding (%.2g sec)" % (t1 - t0)) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) pl.axis('tight') pl.show() ```
[ { "content": "Reconstruct the code exactly:\n```python\n#!/usr/bin/python\n#\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.a...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n#!/usr/bin/python\n#\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# ...
```python #!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from google.cloud import datacatalog datacatalog_client = datacatalog.DataCatalogClient() class CleanupResultsTest(unittest.TestCase): def test_entries_should_not_exist_after_cleanup(self): query = 'system=oracle' scope = datacatalog.SearchCatalogRequest.Scope() scope.include_project_ids.append( os.environ['ORACLE2DC_DATACATALOG_PROJECT_ID']) request = datacatalog.SearchCatalogRequest() request.scope = scope request.query = query request.page_size = 1000 search_results = [ result for result in datacatalog_client.search_catalog(request) ] self.assertEqual(len(search_results), 0) ```
[ { "content": "Here is a code file:\n```python\n# -*- coding: utf-8 -*-\n\n\nfrom django.db import migrations, models\nimport rdrf.models.definition.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rdrf', '0026_auto_20160314_1127'),\n ]\n\n operations = [\n migra...
[ { "content": "Here is a code file:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n\nfrom django.db import migrations, models\nimport rdrf.models.definition.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rdrf', '0026_auto_20160314_1127'),\n ]\n\n operations = ...
```python # -*- coding: utf-8 -*- from django.db import migrations, models import rdrf.models.definition.models class Migration(migrations.Migration): dependencies = [ ('rdrf', '0026_auto_20160314_1127'), ] operations = [ migrations.CreateModel( name='CDEFile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('item', models.FileField(upload_to=rdrf.models.definition.models.file_upload_to, max_length=300)), ('filename', models.CharField(max_length=255)), ('cde', models.ForeignKey(to='rdrf.CommonDataElement', on_delete=models.CASCADE)), ('form', models.ForeignKey(blank=True, to='rdrf.RegistryForm', null=True, on_delete=models.SET_NULL)), ('registry', models.ForeignKey(to='rdrf.Registry', on_delete=models.CASCADE)), ('section', models.ForeignKey(blank=True, to='rdrf.Section', null=True, on_delete=models.SET_NULL)), ], ), ] ```
[ { "content": "Here is some code:\n```python\n### Code for running Hadoop clusters on the model endpoints\n### then using the cumulative summing script to sum the endpoint and area by tcd threshold.\n### Also, sample code for copying results from spot machine to s3 for two endpoints.\n\n### git clone https://git...
[ { "content": "Here is some code:\n<|memory_start|>```python\n### Code for running Hadoop clusters on the model endpoints\n### then using the cumulative summing script to sum the endpoint and area by tcd threshold.\n### Also, sample code for copying results from spot machine to s3 for two endpoints.\n\n### git c...
```python ### Code for running Hadoop clusters on the model endpoints ### then using the cumulative summing script to sum the endpoint and area by tcd threshold. ### Also, sample code for copying results from spot machine to s3 for two endpoints. ### git clone https://github.com/wri/gfw-annual-loss-processing ''' For annual gain rate: python annual_update.py --analysis-type annualGain --points-folder s3://gfw2-data/climate/carbon_model/model_output_tsv/20181116/annualGain_tcd2000/ --output-folder s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/annualGain_tcd2000/20181120/ --polygons-folder s3://gfw2-data/alerts-tsv/country-pages/climate/tsvs/ --iterate-by points python cumsum_hadoop_output.py --input s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/annualGain_tcd2000/20181120/ --no-years --analysis-name annualGain For cumulative gain rate: python annual_update.py --analysis-type cumulGain --points-folder s3://gfw2-data/climate/carbon_model/model_output_tsv/20181116/cumulGain_tcd2000/ --output-folder s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/cumulGain_tcd2000/20181120/ --polygons-folder s3://gfw2-data/alerts-tsv/country-pages/climate/tsvs/ --iterate-by points python cumsum_hadoop_output.py --input s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/cumulGain_tcd2000/20181120/ --no-years --analysis-name cumulGain aws s3 cp /home/ubuntu/gfw-annual-loss-processing/2_Cumulate-Results-and-Create-API-Datasets/processing/XXXXXXXXXXXXXXXXXXXXXXXX/output.csv s3://gfw2-data/climate/carbon_model/model_output_Hadoop/processed/cumulGain_tcd2000/20181121/cumulGain_t_carbon_2001_15.csv For net emissions: python annual_update.py --analysis-type netEmis --points-folder s3://gfw2-data/climate/carbon_model/model_output_tsv/20181116/netEmis_tcd2000/ --output-folder s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/netEmis_tcd2000/20181120/ --polygons-folder s3://gfw2-data/alerts-tsv/country-pages/climate/tsvs/ --iterate-by points python cumsum_hadoop_output.py --input s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/netEmis_tcd2000/20181120/ --no-years --analysis-name netEmis For gross emissions: python annual_update.py --analysis-type grossEmis --points-folder s3://gfw2-data/climate/carbon_model/model_output_tsv/20181119/grossEmis_tcd2000_tcl/ --output-folder s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/grossEmis_tcd2000_tcl/20181120/ --polygons-folder s3://gfw2-data/alerts-tsv/country-pages/climate/tsvs/ --iterate-by points --dryrun python cumsum_hadoop_output.py --input s3://gfw2-data/climate/carbon_model/model_output_Hadoop/raw/grossEmis_tcd2000_tcl/20181120/ --max-year 2015 --analysis-name grossEmis # The cumsum for gross emissions takes a few minutes because there are so many more rows in it (for each year) aws s3 cp /home/ubuntu/gfw-annual-loss-processing/2_Cumulate-Results-and-Create-API-Datasets/processing/357b9433-185e-4c2f-8659-ec613eb58250/output.csv s3://gfw2-data/climate/carbon_model/model_output_Hadoop/processed/grossEmis_tcd2000_tcl/20181121/grossEmis_t_CO2_2001_15.csv ''' ```
[ { "content": "Replicate the source code:\n```python\n#Mohammad Afshar, @mafshar, ma2510@nyu.edu\n\n\"\"\"\nDjango settings for app project.\n\nGenerated by 'django-admin startproject' using Django 1.10.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/settings/\n\nFor t...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\n#Mohammad Afshar, @mafshar, ma2510@nyu.edu\n\n\"\"\"\nDjango settings for app project.\n\nGenerated by 'django-admin startproject' using Django 1.10.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/se...
```python #Mohammad Afshar, @mafshar, ma2510@nyu.edu """ Django settings for app project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'y!2j_m(5$8^b7f_!^yt3gt6c02qwn)h_063a&f&w40mc==_w!d' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'lostnfound.apps.LostnfoundConfig', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # # AUTHENTICATION_BACKENDS = ( # 'backend.email-auth.EmailBackend', # 'django.contrib.auth.backends.ModelBackend', # ) # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases execfile(os.path.join(BASE_DIR, 'db', 'db_settings.py')) # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/New_York' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) #Media PROJ_DIR = BASE_DIR + "/lostnfound" MEDIA_ROOT = PROJ_DIR + STATIC_URL + 'media/' MEDIA_URL = MEDIA_ROOT ```
[ { "content": "Produce an exact reconstruction of the code:\n```python\nimport requests\nimport os\nimport re\nimport time\nfrom selenium import webdriver\nimport multiprocessing\nimport sys\nfrom socket import error as SocketError\nimport errno\nimport argparse\nimport imghdr\nimport uuid\nimport csv\nimport co...
[ { "content": "Produce an exact reconstruction of the code:\n<|memory_start|>```python\nimport requests\nimport os\nimport re\nimport time\nfrom selenium import webdriver\nimport multiprocessing\nimport sys\nfrom socket import error as SocketError\nimport errno\nimport argparse\nimport imghdr\nimport uuid\nimpor...
```python import requests import os import re import time from selenium import webdriver import multiprocessing import sys from socket import error as SocketError import errno import argparse import imghdr import uuid import csv import codecs import platform import downloader # define default chrome download path global default_download_path default_download_path = os.path.join(os.getcwd(), 'download_urls') if not os.path.exists(default_download_path): os.mkdir(default_download_path) global isWindows if re.search('windows', platform.platform(), re.IGNORECASE): isWindows = True else: isWindows = False # use selenium to get the list of URLs def openBrowserRecursively(total, idName, browser): try: for i in range(total): iterator = i * 100 url = r"https://www.google.com/search?q={word}&newwindow=1&biw=300&bih=629&tbm=isch&ijn={times}&start={start}" try: browser.get(url.format(word= idName, start=iterator,times = i)) except SocketError as e: if e.errno != errno.ECONNRESET: raise # raise to reset the connection pass time.sleep(1.5) # 1.5 seconds is the tuned time for HKU service not to be monitored and closed except: if isWindows: os.system("taskkill /im chrome.exe /F") else : os.system("kill " + str(os.getpid())) openBrowserRecursively(total, idName, browser) # basic session setup def setupSession(): session = requests.Session() session.header = { 'User-Agent': "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0","Accept-Encoding": "gzip, deflate, sdch"} return session class GoogleDownloader(): def __init__(self, nameList, root, size, process, browser): assert browser != None, "drive cannot be None!" self.process = process self.browser = browser self.nameList = nameList self.size = size self.root = root # main crawling start def run(self): for i in nameList: self.oneID(i) def oneID(self, name): wordSearch = '' subcategory = name.split(' ') name = name.replace(' ', '_') wordSearch = subcategory[0] if len(subcategory[1:]) >= 1: for pt in subcategory[1:]: wordSearch += "+" + pt print (wordSearch.encode('utf-8')) total = int(self.size / 100) openBrowserRecursively(total, wordSearch, self.browser) # after trigger getting the file list, then the file will be # download but name with f.txt global default_download_path filepath = default_download_path try: for i in range(total): iterator = i * 100 filename = os.path.join("results", name +".txt") newName = name + '_' + str(i) +'.txt' # here is the hardcode part # one may change to his or her own default downloading folder if i == 0: if "f.txt" in os.listdir(filepath): print ("change name to be " , newName.encode('utf-8')) os.rename(os.path.join(filepath,'f.txt'), os.path.join(filepath,newName)) else: fileSpecial = "f (%d).txt" % i if fileSpecial in os.listdir(filepath): print ("change name to be " , newName.encode('utf-8')) os.rename(os.path.join(filepath,fileSpecial), os.path.join(filepath,newName)) else: print ("fail to find the file") except: print("something bad happen, maybe encountering some repeated names") os.remove(os.path.join(filepath, 'f.txt')) return # after rename and locate the url list, then we conduct the final crawling part indexList = [i for i in range(1, 101)] try: folderName = self.makeFolder(name) for i in range(total): newName = name + '_' + str(i) +'.txt' with codecs.open(os.path.join(filepath,newName),'r', encoding="utf-8") as myfile: file1 = myfile.read() results = re.findall(r'"ou":"(.+?)"',file1) self.process.map(_download, zip(results, [folderName] * len(results), indexList[:len(results)])) fileList = os.listdir(folderName) self.dump_imInfo(folderName, sorted(fileList, key=lambda x: int(x.split('.')[0])), results) except IOError: print ("can not find the file called:" , str(newName).encode('utf-8') , "and it may be caused by the bad connection or bad file got from server") def makeFolder(self, fileName): try: if not os.path.exists(os.path.join(self.root, fileName)): os.mkdir(os.path.join(self.root, fileName)) else: print('duplicated root name') except OSError as e: if e.errno != 17: raise else: pass return os.path.join(self.root, fileName) def dump_imInfo(self, folderName, fileList, results): try: with open(os.path.join(folderName, 'imInfo.csv'), 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',') writer.writerow(['img_name', 'uuid', 'url']) for file in fileList: index = int(file.split('.')[0]) writer.writerow([index,str(uuid.uuid4().hex),str(results[index-1])]) except: print('error happens when writing imageInfo, maybe caused by duplicated name') # function to get one image specified with one url def _download(args): url, folderName, index = args session = setupSession() try: # time out is another parameter tuned # fit for the network about 10Mb image = session.get(url, timeout = 5) imageName = str(index) with open(os.path.join(folderName, imageName),'wb') as fout: fout.write(image.content) fileExtension = imghdr.what(os.path.join(folderName, imageName)) if fileExtension is None: os.remove(os.path.join(folderName, imageName)) else: newName = imageName + '.' + str(fileExtension) os.rename(os.path.join(folderName, imageName), os.path.join(folderName, newName)) except Exception as e: print ("failed to download one pages with url of " + str(url)) # basic funciton to get id list def readFile(filename): _list=[] with codecs.open (filename, 'r', encoding='utf-8') as fin: line = fin.readline() while line: _list.append(str(line).rstrip()) line = fin.readline() return _list def arg_parse(): parser = argparse.ArgumentParser(description='Argument Parser for google image downloader') parser.add_argument('--root', help='output file root', default='results', type=str) parser.add_argument('--filename', help='the name of the file which constain the id', default='testlist.txt', type=str) parser.add_argument('--size', help='number of image per id', default=100, type=int) parser.add_argument('--process', help='number of process in parallel', default=100, type=int) args = parser.parse_args() return args if __name__ == '__main__': args = arg_parse() start = time.time() assert args.filename != None, "Name list cannot be None!" # get all id as type of list of str nameList = list(set(readFile(args.filename))) # init processPool and browser driver processPool = multiprocessing.Pool(args.process) # init chrome driver with customized default download path chromeOptions = webdriver.ChromeOptions() preference = {'download.default_directory' : default_download_path, 'download.prompt_for_download': False} chromeOptions.add_experimental_option("prefs",preference) if isWindows: chromedriver = os.path.join(os.getcwd(),'chromedriver.exe') else: chromedriver = os.path.join(os.getcwd(),'chromedriver') browser = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions) # check if the output folder exists or not if not os.path.exists(args.root): os.mkdir(args.root) # construct the downloader instance gdownloader = GoogleDownloader(nameList = nameList, root = args.root, size = args.size, process = processPool, browser = browser) gdownloader.run() # finish running end = time.time() browser.close() print ('task end, time consumed:', end - start, 'seconds') ```
[ { "content": "Here is the snippet:\n```python\n# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'FriendJoinedEmailLog'\n db.c...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding model 'FriendJoinedEmailLo...
```python # -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'FriendJoinedEmailLog' db.create_table('custom_friendjoinedemaillog', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='user_fje', to=orm['auth.User'])), ('user_referred', self.gf('django.db.models.fields.related.ForeignKey')(related_name='user_referred_fje', to=orm['auth.User'])), ('created_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('updated_date', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), )) db.send_create_signal('custom', ['FriendJoinedEmailLog']) # Adding unique constraint on 'FriendJoinedEmailLog', fields ['user', 'user_referred'] db.create_unique('custom_friendjoinedemaillog', ['user_id', 'user_referred_id']) # Adding unique constraint on 'FacebookOGReferredLog', fields ['user', 'user_referred'] db.create_unique('custom_facebookogreferredlog', ['user_id', 'user_referred_id']) def backwards(self, orm): # Removing unique constraint on 'FacebookOGReferredLog', fields ['user', 'user_referred'] db.delete_unique('custom_facebookogreferredlog', ['user_id', 'user_referred_id']) # Removing unique constraint on 'FriendJoinedEmailLog', fields ['user', 'user_referred'] db.delete_unique('custom_friendjoinedemaillog', ['user_id', 'user_referred_id']) # Deleting model 'FriendJoinedEmailLog' db.delete_table('custom_friendjoinedemaillog') 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'}) }, 'custom.facebookogreferredlog': { 'Meta': {'unique_together': "(('user', 'user_referred'),)", 'object_name': 'FacebookOGReferredLog'}, 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'success': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user'", 'to': "orm['auth.User']"}), 'user_referred': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_referred'", 'to': "orm['auth.User']"}) }, 'custom.facebookstatusupdate': { 'Meta': {'object_name': 'FacebookStatusUpdate'}, 'caption': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'end_date': ('django.db.models.fields.DateTimeField', [], {}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'picture': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'custom.facebookstatusupdatelog': { 'Meta': {'unique_together': "(('facebook_status_update', 'user'),)", 'object_name': 'FacebookStatusUpdateLog'}, 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'facebook_status_update': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['custom.FacebookStatusUpdate']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'custom.friendjoinedemaillog': { 'Meta': {'unique_together': "(('user', 'user_referred'),)", 'object_name': 'FriendJoinedEmailLog'}, 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_fje'", 'to': "orm['auth.User']"}), 'user_referred': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_referred_fje'", 'to': "orm['auth.User']"}) }, 'custom.post': { 'Meta': {'object_name': 'Post'}, 'content': ('django.db.models.fields.TextField', [], {}), 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'homepage': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '256'}), 'published_date': ('django.db.models.fields.DateTimeField', [], {}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'custom.profile': { 'Meta': {'object_name': 'Profile'}, 'enable_email_updates': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'enable_facebook_updates': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'enable_twitter_updates': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'followers': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '256', 'blank': 'True'}), 'semaphore_facebook': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'semaphore_twitter': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'social_data_completed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'source_referrer': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}), 'user_referrer': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_referrer'", 'null': 'True', 'to': "orm['auth.User']"}) }, 'custom.twitterautofriendshiplog': { 'Meta': {'object_name': 'TwitterAutoFriendshipLog'}, 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'success': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'custom.twitterstatusupdate': { 'Meta': {'object_name': 'TwitterStatusUpdate'}, 'content': ('django.db.models.fields.TextField', [], {}), 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateTimeField', [], {}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}) }, 'custom.twitterstatusupdatelog': { 'Meta': {'unique_together': "(('twitter_status_update', 'user'),)", 'object_name': 'TwitterStatusUpdateLog'}, 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'twitter_status_update': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['custom.TwitterStatusUpdate']"}), 'updated_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) } } complete_apps = ['custom'] ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the Li...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain ...
```python # coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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. r"""Converts an mrqa dataset file to tf examples. Notes: - this program needs to be run for every mrqa training shard. - this program only outputs the first n top level contexts for every example, where n is set through --max_contexts. - the restriction from --max_contexts is such that the annotated context might not be present in the output examples. --max_contexts=8 leads to about 85% of examples containing the correct context. --max_contexts=48 leads to about 97% of examples containing the correct context. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import random from language.tek_representations import run_mrqa import tensorflow.compat.v1 as tf flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_bool( "is_training", True, "Whether to prepare features for training or for evaluation. Eval features " "don't include gold labels, but include wordpiece to html token maps.") flags.DEFINE_integer( "max_examples", 0, "If positive, stop once these many examples have been converted.") flags.DEFINE_string("split", "train", "Train and dev split to read from and write to.") flags.DEFINE_string("input_data_dir", "", "input_data_dir") flags.DEFINE_string("output_data_dir", "", "output_data_dir") flags.DEFINE_integer("n_shards", 50, "number of shards for this split") def get_examples(input_jsonl_pattern): for input_path in tf.gfile.Glob(input_jsonl_pattern): with tf.gfile.Open(input_path) as input_file: for line in input_file: yield json.loads(line) def get_shard(): return "%05d-of-%05d" % (FLAGS.task_id, FLAGS.n_shards) def main(_): examples_processed = 0 creator_fn = run_mrqa.CreateTFExampleFn(is_training=FLAGS.is_training) instances = [] input_file = os.path.join( FLAGS.input_data_dir, "%s.jsonl-%s" % (FLAGS.split, get_shard())) for example in get_examples(input_file): for instance in creator_fn.process(example): instances.append(instance) if examples_processed % 100 == 0: tf.logging.info("Examples processed: %d", examples_processed) examples_processed += 1 if FLAGS.max_examples > 0 and examples_processed >= FLAGS.max_examples: break random.shuffle(instances) tf.logging.info("Total no: of instances in current shard: %d", len(instances)) rec_output_file = os.path.join(FLAGS.output_data_dir, "%s.tfrecord-%s" % (FLAGS.split, get_shard())) with tf.python_io.TFRecordWriter(rec_output_file) as writer: for instance, _ in instances: writer.write(instance) if not FLAGS.is_training: fea_output_file = os.path.join( FLAGS.output_data_dir, "%s.features.jsonl-%s" % (FLAGS.split, get_shard())) with tf.gfile.Open(fea_output_file, "w") as writer: for _, instance in instances: writer.write(instance) if __name__ == "__main__": flags.mark_flag_as_required("vocab_file") tf.app.run() ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# -*- coding: utf-8 -*-\n# Generated by Django 1.9.3 on 2016-03-10 07:40\nfrom __future__ import unicode_literals\n\nimport django.contrib.auth.models\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.utils...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# Generated by Django 1.9.3 on 2016-03-10 07:40\nfrom __future__ import unicode_literals\n\nimport django.contrib.auth.models\nimport django.core.validators\nfrom django.db import migrations, models\nimp...
```python # -*- coding: utf-8 -*- # Generated by Django 1.9.3 on 2016-03-10 07:40 from __future__ import unicode_literals import django.contrib.auth.models import django.core.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ('bucketlist', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='account', options={'verbose_name': 'user', 'verbose_name_plural': 'users'}, ), migrations.AlterModelManagers( name='account', managers=[ ('objects', django.contrib.auth.models.UserManager()), ], ), migrations.RemoveField( model_name='account', name='is_admin', ), migrations.AddField( model_name='account', name='date_joined', field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined'), ), migrations.AddField( model_name='account', name='first_name', field=models.CharField(blank=True, max_length=30, verbose_name='first name'), ), migrations.AddField( model_name='account', name='groups', field=models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups'), ), migrations.AddField( model_name='account', name='is_active', field=models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active'), ), migrations.AddField( model_name='account', name='is_staff', field=models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status'), ), migrations.AddField( model_name='account', name='is_superuser', field=models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status'), ), migrations.AddField( model_name='account', name='last_name', field=models.CharField(blank=True, max_length=30, verbose_name='last name'), ), migrations.AddField( model_name='account', name='user_permissions', field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'), ), migrations.AlterField( model_name='account', name='email', field=models.EmailField(blank=True, max_length=254, verbose_name='email address'), ), migrations.AlterField( model_name='account', name='tagline', field=models.TextField(max_length=250), ), migrations.AlterField( model_name='account', name='username', field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=30, unique=True, validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.')], verbose_name='username'), ), ] ```
[ { "content": "Reconstruct the code exactly:\n```python\n# -*- coding: utf-8 -*-\nimport pytest\nfrom insert_sort import insert_sort\n\n\ndef test_sorted():\n my_list = list(range(100))\n insert_sort(my_list)\n assert my_list == list(range(100))\n\n\ndef test_reverse():\n my_list = list(range(100))[:...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nimport pytest\nfrom insert_sort import insert_sort\n\n\ndef test_sorted():\n my_list = list(range(100))\n insert_sort(my_list)\n assert my_list == list(range(100))\n\n\ndef test_reverse():\n my_list = li...
```python # -*- coding: utf-8 -*- import pytest from insert_sort import insert_sort def test_sorted(): my_list = list(range(100)) insert_sort(my_list) assert my_list == list(range(100)) def test_reverse(): my_list = list(range(100))[::-1] insert_sort(my_list) assert my_list == list(range(100)) def test_empty(): my_list = [] insert_sort(my_list) assert my_list == [] def test_abc(): my_list = ['a', 'b', 'c', 'd', 'e'] insert_sort(my_list) assert my_list == ['a', 'b', 'c', 'd', 'e'] my_list = ['e', 'd', 'c', 'b', 'a'] insert_sort(my_list) assert my_list == ['a', 'b', 'c', 'd', 'e'] def test_unicode(): my_list = ['π'] insert_sort(my_list) assert my_list == ['\xcf\x80'] def test_duplicate(): my_list = [1, 2, 2, 5, 3] insert_sort(my_list) assert my_list == [1, 2, 2, 3, 5] def test_combo(): my_list = [42, 1, 'a', 500] insert_sort(my_list) assert my_list == [1, 42, 500, 'a'] my_list = [42, '1', 'a', '500'] insert_sort(my_list) assert my_list == [42, '1', '500', 'a'] def test_function(): my_list = [] new_list = [insert_sort(my_list)] assert new_list == [None] def test_non_iterable(): with pytest.raises(TypeError): insert_sort(42) ```
[ { "content": "Produce an exact reconstruction of the code:\n```python\n#!/usr/bin/env python2\n\n##\n# autosign\n# https://github.com/leosartaj/autosign.git\n# \n# copyright (c) 2014 sartaj singh\n# licensed under the mit license.\n##\n\nimport unittest\nimport os, shutil\nimport helper\nfrom autosign.main impo...
[ { "content": "Produce an exact reconstruction of the code:\n<|memory_start|>```python\n#!/usr/bin/env python2\n\n##\n# autosign\n# https://github.com/leosartaj/autosign.git\n# \n# copyright (c) 2014 sartaj singh\n# licensed under the mit license.\n##\n\nimport unittest\nimport os, shutil\nimport helper\nfrom au...
```python #!/usr/bin/env python2 ## # autosign # https://github.com/leosartaj/autosign.git # # copyright (c) 2014 sartaj singh # licensed under the mit license. ## import unittest import os, shutil import helper from autosign.main import removeSign, isSign from autosign.exce import UnsignedError class TestremoveSign(unittest.TestCase): """ tests the removeSign function in main module """ def setUp(self): self.dire = os.path.dirname(__file__) self.signedfile = os.path.join(self.dire, 'testData/toBeSigned.py') self.signed = os.path.join(self.dire, 'testData/test_signedfile.py') shutil.copyfile(self.signedfile, self.signed) self.unsigned = os.path.join(self.dire, 'testData/test_unsignedfile.py') helper.newFile(self.unsigned) helper.readrc(self) def test_remove_from_unsigned_file(self): self.assertRaises(UnsignedError, removeSign, self.unsigned, self.options_py) def test_remove_from_signed_file(self): self.assertTrue(isSign(self.signed, self.options_py)) removeSign(self.signed, self.options_py) self.assertFalse(isSign(self.signed, self.options_py)) def tearDown(self): os.remove(self.unsigned) ```
[ { "content": "```python\nclass InitModule:\n def init(self, viewer):\n raise Exception(\"init has not been implemented.\")\n\n\nclass InteractiveModule:\n def _handle(self, viewer, ch):\n raise Exception(\"_handle has not been implemented.\")\n\n def _handle_help(self, viewer, buf):\n ...
[ { "content": "<|memory_start|>```python\nclass InitModule:\n def init(self, viewer):\n raise Exception(\"init has not been implemented.\")\n\n\nclass InteractiveModule:\n def _handle(self, viewer, ch):\n raise Exception(\"_handle has not been implemented.\")\n\n def _handle_help(self, vie...
```python class InitModule: def init(self, viewer): raise Exception("init has not been implemented.") class InteractiveModule: def _handle(self, viewer, ch): raise Exception("_handle has not been implemented.") def _handle_help(self, viewer, buf): raise Exception("_handle_help has not been implemented.") def _handle_combo(self, viewer, buf): raise Exception("_handle_como has not been implemented.") class LiveModule: def _register_hooks(self, client): raise Exception(self.__class__.__name__ + "._register_hooks has not been implemented.") def _update(self, viewer): raise Exception("_update has not been implemented.") class TextDisplayModule: def _show(self, viewer): raise Exception("_show has not been implemented.") def _hide(self, viewer): raise Exception("_hide has not been implemented.") class VisibleModule: def draw(self): raise Exception("draw has not been implemented.") def up(self): raise Exception("up not been implemented.") def down(self): raise Exception("down not been implemented.") def left(self): raise Exception("left not been implemented.") def right(self): raise Exception("right not been implemented.") class FeatureModule: def add_feature(self): raise Exception("add_feature has not been implemented.") def rm_feature(self): raise Exception("rm_feature has not been implemented.") def get_feature_idx(self): raise Exception("get_feature_idx has not been implemented.") def serialize_features(self): raise Exception("serialize_feautes has not been implemented.") class SavableModule: def save(self): raise Exception("save has not been implemented.") class UserModule: def up(self): raise Exception("up has not been implemented.") def down(self): raise Exception("down has not been implemented.") def left(self): raise Exception("left has not been implemented.") def right(self): raise Exception("right has not been implemented.") def vp_up(self): raise Exception("vp_up has not been implemented.") def vp_down(self): raise Exception("vp_down has not been implemented.") def vp_left(self): raise Exception("vp_left has not been implemented.") def vp_right(self): raise Exception("vp_right has not been implemented.") class NetworkModule: pass class ServerModule(NetworkModule): def update(self): raise Exception("update has not been implemented.") class ClientModule(NetworkModule): def connect(self): raise Exception("update has not been implemented.") def disconnect(self): raise Exception("update has not been implemented.") def update(self): raise Exception("update has not been implemented.") ```
[ { "content": "Return the code unaltered:\n```python\n#!/usr/bin/env python\nimport kalipi\nfrom kalipi import *\n\n\n#############################\n## Local Functions ##\n\n## Local Functions ##\n#############################\n\n\n#############################\n## Buttons ##\n\n#...
[ { "content": "Return the code unaltered:\n<|memory_start|>```python\n#!/usr/bin/env python\nimport kalipi\nfrom kalipi import *\n\n\n#############################\n## Local Functions ##\n\n## Local Functions ##\n#############################\n\n\n#############################\n## Buttons ...
```python #!/usr/bin/env python import kalipi from kalipi import * ############################# ## Local Functions ## ## Local Functions ## ############################# ############################# ## Buttons ## # define all of the buttons label1 = Button(labelPadding * " " + " ", originX, originX, buttonHeight, buttonWidth * 3 + spacing * 2, tron_ora, tron_yel, labelFont) label2 = Button(labelPadding * " " + " ", originX, originY, buttonHeight, buttonWidth * 3 + spacing * 2, tron_ora, tron_yel, labelFont) label3 = Button(labelPadding * " " + " ", originX, originY + buttonHeight + spacing, buttonHeight, buttonWidth * 3 + spacing * 2, tron_ora, tron_yel, labelFont) button7 = Button(labelPadding * " " + " <<<", originX, originY + (buttonHeight * 2) + (spacing * 2), buttonHeight, buttonWidth, tron_ora, tron_yel, labelFont) button9 = Button(labelPadding * " " + " Refresh", originX + (buttonWidth * 2) + (spacing * 2), originY + (buttonHeight * 2) + (spacing * 2), buttonHeight, buttonWidth, tron_ora, tron_yel, labelFont) # Define each button press action def button(number): if number == 7: if button7.disable == 1: return # Previous page pygame.quit() page=os.environ["MENUDIR"] + "menu-pin.py" retPage=kalipi.get_retPage() args = [page, retPage] os.execvp("python", ["python"] + args) sys.exit() if number == 9: if button9.disable == 1: return # Refresh pygame.quit() menu9p() ## Buttons ## ############################# def menu9p(): # Init screen kalipi.screen() # Outer Border kalipi.border(tron_ora) ############################# ## Buttons ## # Buttons and labels # See variables at the top of the document to adjust the menu # First Row # label 1 label1.text=labelPadding * " " + kalipi.get_clock() label1.draw() # Second Row # Button 2 label2.text=labelPadding * " " + kalipi.get_temp() label2.draw() # Third Row # Label 3 label3.text=labelPadding * " " + kalipi.get_volts() label3.draw() # Fourth Row # Button 7 button7.disable = 0 # "1" disables button if button7.disable == 1: button7.draw() else: # Add button launch code here button7.draw() # Button 9 button9.disable = 0 # "1" disables button if button9.disable == 1: button9.draw() else: # Add button launch code here button9.draw() ## Buttons ## ############################# ############################# ## Input loop ## while 1: butNo=kalipi.inputLoop("menu-9p.py") button(butNo) ## Input loop ## ############################# if __name__ == "__main__": menu9p() ```
[ { "content": "Here is the source code:\n```python\nimport numpy as np\nfrom IOHandler import loadMultipart\n\n##### Diff between particle data, data should be stored as x column xp column y column yp\nfirstdata = raw_input('Enter first multipart datafile name:')\nseconddata = raw_input('Enter second multipart d...
[ { "content": "Here is the source code:\n<|memory_start|>```python\nimport numpy as np\nfrom IOHandler import loadMultipart\n\n##### Diff between particle data, data should be stored as x column xp column y column yp\nfirstdata = raw_input('Enter first multipart datafile name:')\nseconddata = raw_input('Enter se...
```python import numpy as np from IOHandler import loadMultipart ##### Diff between particle data, data should be stored as x column xp column y column yp firstdata = raw_input('Enter first multipart datafile name:') seconddata = raw_input('Enter second multipart datafile name:') firstmultipart = loadMultipart(firstdata) secondmultipart = loadMultipart(seconddata) xf = [firstmultipart[i][0][0] for i in xrange(len(firstmultipart))] xpf = [firstmultipart[i][0][1] for i in xrange(len(firstmultipart))] yf = [firstmultipart[i][0][2] for i in xrange(len(firstmultipart))] ypf = [firstmultipart[i][0][3] for i in xrange(len(firstmultipart))] zf = [firstmultipart[i][0][4] for i in xrange(len(firstmultipart))] zpf = [firstmultipart[i][0][5] for i in xrange(len(firstmultipart))] xs = [secondmultipart[i][0][0] for i in xrange(len(secondmultipart))] xps = [secondmultipart[i][0][1] for i in xrange(len(secondmultipart))] ys = [secondmultipart[i][0][2] for i in xrange(len(secondmultipart))] yps = [secondmultipart[i][0][3] for i in xrange(len(secondmultipart))] zs = [secondmultipart[i][0][4] for i in xrange(len(secondmultipart))] zps = [secondmultipart[i][0][5] for i in xrange(len(secondmultipart))] diffx = np.array(xf) - np.array(xs) diffxp = np.array(xpf) - np.array(xps) diffy = np.array(yf) - np.array(ys) diffyp = np.array(ypf) - np.array(yps) diffz = np.array(zf) - np.array(zs) diffzp = np.array(zpf) - np.array(zps) diffx = diffx.astype('float') diffxp = diffxp.astype('float') diffy = diffy.astype('float') diffyp = diffyp.astype('float') diffz = diffz.astype('float') diffzp = diffzp.astype('float') stdx = np.std(diffx) stdxp = np.std(diffxp) stdy = np.std(diffy) stdyp = np.std(diffyp) stdz = np.std(diffz) stdzp = np.std(diffzp) print 'stdx:',stdx print 'stdxp:',stdxp print 'stdy:',stdy print 'stdyp:',stdyp print 'stdz:',stdz print 'stdzp:',stdzp # std for xin,xpin,yin,ypin #print 'Initial beam std (when firstsdata is the init while and not results...)' #print 'stdx:',np.std(firstx) #print 'stdxp:',np.std(firstxp) #print 'stdy:',np.std(firsty) #print 'stdyp:',np.std(firstyp) ## TODO: #1: make the program work by calling something like: python diff.py out.txt out2.txt ```
[ { "content": "Repeat the full code snippet:\n```python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom datetime import datetime\nimport hmac\nimport base64\nimport hashlib\n\nfrom requests import Request\n\nfrom paytrail.settings import BASE_API_URL, PAYTRAIL_AUTH_KEY, PAYTRAIL_ID, PAYTR...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom datetime import datetime\nimport hmac\nimport base64\nimport hashlib\n\nfrom requests import Request\n\nfrom paytrail.settings import BASE_API_URL, PAYTRAIL_AUTH_KEY, PA...
```python # -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime import hmac import base64 import hashlib from requests import Request from paytrail.settings import BASE_API_URL, PAYTRAIL_AUTH_KEY, PAYTRAIL_ID, PAYTRAIL_SECRET class PaytrailConnectAPIRequest(Request): def __init__(self, **kwargs): self.merchant_id = kwargs.pop('merchant_id') self.merchant_secret = kwargs.pop('merchant_secret') super(PaytrailConnectAPIRequest, self).__init__(**kwargs) self.headers['Timestamp'] = self.get_timestamp() self.headers['Content-MD5'] = self.get_content_md5() self.headers['Authorization'] = self.get_authorization_signature() def get_content_md5(self): return hashlib.md5(self.prepare().body).digest().encode('base64').strip() @staticmethod def get_timestamp(): return str(datetime.now().isoformat()) def get_authorization_signature(self): base_signature = '\n'.join([ self.method, self.url, 'PaytrailConnectAPI {merchant_id}'.format(self.merchant_id), self.headers['Timestamp'], self.headers['Authorization'] ]) digest = hmac.new( key=self.merchant_secret, msg=base_signature, digestmod=hashlib.sha256 ).digest() signature = base64.b64encode(digest).decode() return 'PaytrailConnectAPI {merchant_id}:{signature}'.format(self.merchant_id, signature) class BasePaytrailClient(object): URL_MAP = { 'authorization': { 'url': '/connectapi/authorizations', 'method': 'POST' }, 'confirming_authorization': { 'url': '/connectapi/authorizations/{id}/confirmation', 'method': 'POST' }, 'invalidatin_authorization': { 'url': '/authorizations/{id}', 'method': 'POST' } , 'charging': '/connectapi/authorizations/{id}/charges', 'fetching_payment_status': '/connectapi/authorizations/{id}/charges/{id}', 'fetching_delivery_address': ' /connectapi/authorizations/{id}/deliveryAddresses', } def __init__(self, base_url=BASE_API_URL, merchant_id=PAYTRAIL_ID, merchant_secret=PAYTRAIL_SECRET): self.base_url = base_url self.merchant_id = merchant_id self.merchant_secret = merchant_secret def authorize(self, auth_key=PAYTRAIL_AUTH_KEY): pass def confirm_authorization(self): pass test_client = BasePaytrailClient() test_client.authorize() ```
[ { "content": "Here is the snippet:\n```python\n#!/usr/bin/env python\n\n# Copyright 2012 (Alexandre Zani)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apac...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n#!/usr/bin/env python\n\n# Copyright 2012 (Alexandre Zani)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# ...
```python #!/usr/bin/env python # Copyright 2012 (Alexandre Zani) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import phero import unittest class TestRequestProcessor(unittest.TestCase): def setUp(self): self.logic_registry = phero.ServiceRegistry() self.auth_registry = phero.ServiceRegistry() self.registries = [ ('auth', self.auth_registry), ('main', self.logic_registry), ] def simple_auth(ctx, username): return username self.auth_registry.register(simple_auth) def whoami(ctx, all_caps=False): if all_caps: return ctx['auth'].upper() return ctx['auth'] self.logic_registry.register(whoami) def test_basic(self): request = { 'main': { 'service': 'whoami', 'args': { 'all_caps': True } }, 'auth': { 'service': 'simple_auth', 'args': { 'username': 'alex' } } } expected = { 'result': 'ALEX' } actual = phero.process_request(self.registries, request) self.assertEquals(expected, actual) def test_no_args(self): def whoami_simple(ctx): return ctx['auth'] self.logic_registry.register(whoami_simple) request = { 'main': { 'service': 'whoami_simple', }, 'auth': { 'service': 'simple_auth', 'args': { 'username': 'alex' } } } expected = { 'result': 'alex' } actual = phero.process_request(self.registries, request) self.assertEquals(expected, actual) def test_phero_error(self): request = { 'main': { 'service': 'does_not_exist' } } expected = { 'error': 'UnknownService', 'details': { 'service': 'does_not_exist' } } actual = phero.process_request(self.registries, request) self.assertEquals(expected, actual) def test_custom_error(self): class AuthError(phero.PheroError): pass def bad_auth(ctx): raise AuthError(msg='I hate you') self.auth_registry.register(bad_auth) request = { 'auth': { 'service': 'bad_auth' } } expected = { 'error': 'AuthError', 'details': { 'msg': 'I hate you' } } actual = phero.process_request(self.registries, request) self.assertEquals(expected, actual) def test_generic_error(self): def bad_method(ctx): raise KeyError self.logic_registry.register(bad_method) request = { 'main': { 'service': 'bad_method' } } with self.assertRaises(KeyError): phero.process_request(self.registries, request) expected = { 'error': 'GenericInternalError' } actual = phero.process_request(self.registries, request, catch_all=True) self.assertEquals(expected, actual) class TestServiceRegistry(unittest.TestCase): def test_basic(self): def multiply(ctx, a, b): return a * b registry = phero.ServiceRegistry() registry.register(multiply) args = { 'a': 3, 'b': 4 } service_name = 'multiply' ctx = {} expected = 12 actual = registry.process(ctx, service_name, args) self.assertEquals(expected, actual) def test_unknown_service(self): registry = phero.ServiceRegistry() args = { 'a': 3, 'b': 4 } service_name = 'multiply' ctx = {} expected = 12 with self.assertRaises(phero.UnknownService) as cmt: registry.process(ctx, service_name, args) self.assertEquals(cmt.exception.details, { 'service': 'multiply' }) def test_default_service(self): def default(ctx): return "Default Service" registry = phero.ServiceRegistry() registry.register_default(default) ctx = {} expected = "Default Service" actual = registry.process(ctx, None, None) self.assertEquals(expected, actual) def test_default_default_service(self): registry = phero.ServiceRegistry() ctx = {} expected = None actual = registry.process(ctx, None, None) self.assertEquals(expected, actual) class TestService(unittest.TestCase): def test_basic(self): def multiply(ctx, a, b): return a * b multiply_service = phero.Service(multiply) args = { 'a': 3, 'b': 4 } ctx = {} expected = 12 actual = multiply_service(ctx, args) self.assertEquals(expected, actual) def test_missing_required_arg(self): def multiply(ctx, a, b): return a * b multiply_service = phero.Service(multiply) args = { 'a': 3 } ctx = {} with self.assertRaises(phero.MissingRequiredArgument) as cmt: multiply_service(ctx, args) self.assertEquals(cmt.exception.details, { 'arg': 'b' }) def test_unknown_arg(self): def multiply(ctx, a, b): return a * b multiply_service = phero.Service(multiply) args = { 'a': 3, 'b': 4, 'c': 3 } ctx = {} with self.assertRaises(phero.UnknownArgument) as cmt: multiply_service(ctx, args) self.assertEquals(cmt.exception.details, { 'arg': 'c' }) def test_default_arg(self): def multiply(ctx, a, b=2): return a * b multiply_service = phero.Service(multiply) args = { 'a': 3 } ctx = {} expected = 6 actual = multiply_service(ctx, args) self.assertEquals(expected, actual) if __name__ == '__main__': unittest.main() ```
[ { "content": "Here is the code block:\n```python\n# -*- encoding: utf-8 -*-\rfrom __future__ import unicode_literals\r\rimport codecs\rimport datetime\rimport locale\rfrom decimal import Decimal\r\rfrom django.utils import six\rfrom django.utils.functional import Promise\rfrom django.utils.six.moves.urllib.pars...
[ { "content": "Here is the code block:\n<|memory_start|>```python\n# -*- encoding: utf-8 -*-\rfrom __future__ import unicode_literals\r\rimport codecs\rimport datetime\rimport locale\rfrom decimal import Decimal\r\rfrom django.utils import six\rfrom django.utils.functional import Promise\rfrom django.utils.six.m...
```python # -*- encoding: utf-8 -*- from __future__ import unicode_literals import codecs import datetime import locale from decimal import Decimal from django.utils import six from django.utils.functional import Promise from django.utils.six.moves.urllib.parse import quote, unquote if six.PY3: from urllib.parse import unquote_to_bytes class DjangoUnicodeDecodeError(UnicodeDecodeError): def __init__(self, obj, *args): self.obj = obj UnicodeDecodeError.__init__(self, *args) def __str__(self): original = UnicodeDecodeError.__str__(self) return '%s. You passed in %r (%s)' % (original, self.obj, type(self.obj)) # For backwards compatibility. (originally in Django, then added to six 1.9) python_2_unicode_compatible = six.python_2_unicode_compatible def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a text object representing 's' -- unicode on Python 2 and str on Python 3. Treats bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_text(s, encoding, strings_only, errors) _PROTECTED_TYPES = six.integer_types + (type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, _PROTECTED_TYPES) def force_text(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if issubclass(type(s), six.text_type): return s if strings_only and is_protected_type(s): return s try: if not issubclass(type(s), six.string_types): if six.PY3: if isinstance(s, bytes): s = six.text_type(s, encoding, errors) else: s = six.text_type(s) elif hasattr(s, '__unicode__'): s = six.text_type(s) else: s = six.text_type(bytes(s), encoding, errors) else: # Note: We use .decode() here, instead of six.text_type(s, encoding, # errors), so that if s is a SafeBytes, it ends up being a # SafeText at the end. s = s.decode(encoding, errors) except UnicodeDecodeError as e: if not isinstance(s, Exception): raise DjangoUnicodeDecodeError(s, *e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = ' '.join(force_text(arg, encoding, strings_only, errors) for arg in s) return s def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_bytes(s, encoding, strings_only, errors) def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == 'utf-8': return s else: return s.decode('utf-8', errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, six.memoryview): return bytes(s) if isinstance(s, Promise): return six.text_type(s).encode(encoding, errors) if not isinstance(s, six.string_types): try: if six.PY3: return six.text_type(s).encode(encoding) else: return bytes(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return b' '.join(force_bytes(arg, encoding, strings_only, errors) for arg in s) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors) if six.PY3: smart_str = smart_text force_str = force_text else: smart_str = smart_bytes force_str = force_bytes # backwards compatibility for Python 2 smart_unicode = smart_text force_unicode = force_text smart_str.__doc__ = """ Apply smart_text in Python 3 and smart_bytes in Python 2. This is suitable for writing to sys.stdout (for instance). """ force_str.__doc__ = """ Apply force_text in Python 3 and force_bytes in Python 2. """ def iri_to_uri(iri): """ Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from section 3.1 of RFC 3987. However, since we are assuming input is either UTF-8 or unicode already, we can simplify things a little from the full method. Takes an IRI in UTF-8 bytes (e.g. '/I \xe2\x99\xa5 Django/') or unicode (e.g. '/I ♥ Django/') and returns ASCII bytes containing the encoded result (e.g. '/I%20%E2%99%A5%20Django/'). """ # The list of safe characters here is constructed from the "reserved" and # "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986: # reserved = gen-delims / sub-delims # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" # / "*" / "+" / "," / ";" / "=" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # Of the unreserved characters, urllib.quote already considers all but # the ~ safe. # The % character is also added to the list of safe characters here, as the # end of section 3.1 of RFC 3987 specifically mentions that % must not be # converted. if iri is None: return iri return quote(force_bytes(iri), safe=b"/#%[]=:;$&()+,!?*@'~") def uri_to_iri(uri): """ Converts a Uniform Resource Identifier(URI) into an Internationalized Resource Identifier(IRI). This is the algorithm from section 3.2 of RFC 3987. Takes an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and returns unicode containing the encoded result (e.g. '/I \xe2\x99\xa5 Django/'). """ if uri is None: return uri uri = force_bytes(uri) iri = unquote_to_bytes(uri) if six.PY3 else unquote(uri) return repercent_broken_unicode(iri).decode('utf-8') def escape_uri_path(path): """ Escape the unsafe characters from the path portion of a Uniform Resource Identifier (URI). """ # These are the "reserved" and "unreserved" characters specified in # sections 2.2 and 2.3 of RFC 2396: # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," # unreserved = alphanum | mark # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" # The list of safe characters here is constructed subtracting ";", "=", # and "?" according to section 3.3 of RFC 2396. # The reason for not subtracting and escaping "/" is that we are escaping # the entire path, not a path segment. return quote(force_bytes(path), safe=b"/:@&+$,-_.!~*'()") def repercent_broken_unicode(path): """ As per section 3.2 of RFC 3987, step three of converting a URI into an IRI, we need to re-percent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode('utf-8') except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = repercent_broken_unicode( path[:e.start] + force_bytes(repercent) + path[e.end:]) return path def filepath_to_uri(path): """Convert a file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method does not encode the ' character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details. Returns an ASCII string containing the encoded result. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return quote(force_bytes(path).replace(b"\\", b"/"), safe=b"/~!*()'") def get_system_encoding(): """ The encoding of the default system locale but falls back to the given fallback encoding if the encoding is unsupported by python or could not be determined. See tickets #10335 and #5846 """ try: encoding = locale.getdefaultlocale()[1] or 'ascii' codecs.lookup(encoding) except Exception: encoding = 'ascii' return encoding DEFAULT_LOCALE_ENCODING = get_system_encoding() ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n\nimport json\nimport requests\nimport re\nimport random\nimport time\nimport sys\nimport csv\nfrom genericKB import genericHandler\nfrom esHealth import esHealthHandler\nfrom wikiFinder import find...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n\nimport json\nimport requests\nimport re\nimport random\nimport time\nimport sys\nimport csv\nfrom genericKB import genericHandler\nfrom esHealth import esHealthHandler\nfrom wikiFi...
```python #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import json import requests import re import random import time import sys import csv from genericKB import genericHandler from esHealth import esHealthHandler from wikiFinder import findWikiEn #from io import open import codecs #from pttChat import pttHandler #from wikiChat import wikiHandler import os class GenericEnBrain(): listIdx = [('enbasic1',0.8), ('enbot1',2.0)] kb = {} notFoundResList = [] def __init__(self): with open('basickb_en.csv') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in spamreader: if(len(row)>=2): self.kb[row[0].strip()] = row[1].strip() def randomAct(self, actKey): res_act = self.kb[actKey].split(";") return random.choice(res_act) def think(self, msg): response = '' dirtylist = self.kb['dirty_words'].lower().split(";") msg = msg.strip() for dword in dirtylist: dword = dword.strip() if dword in msg: return self.randomAct('dirty_words_res') for cnf in self.listIdx: response = genericHandler(cnf[0], 'fb', msg, min_score=cnf[1]) if response != '': return response if response == '': # Wikifinedr nltk_data_path = os.getcwd()+'/nltk_data' print(nltk_data_path) os.environ['NLTK_DATA'] = nltk_data_path from textblob import TextBlob b = TextBlob(msg.lower()) if len(b.noun_phrases) > 0: toFindInWiki = b.noun_phrases[0] wikiResponse = findWikiEn(toFindInWiki) response = wikiResponse[0:256] + "...<search from wiki>" if response == '': response = self.randomAct('act_no_info') return response genBrain = GenericEnBrain() if __name__ == '__main__': msg = sys.argv[1] print(genBrain.think(msg)) # print(gBrain.think(msg)) # print(fbBrain.think(msg)) ```
[ { "content": "```python\n##############################################################################\n#\n# Copyright (c) 2006 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should...
[ { "content": "<|memory_start|>```python\n##############################################################################\n#\n# Copyright (c) 2006 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy o...
```python ############################################################################## # # Copyright (c) 2006 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Global components support $Id: globalregistry.py 69983 2006-09-05 21:41:15Z ctheune $ """ import types from zope.interface import implements from zope.interface.adapter import AdapterRegistry from zope.deprecation.deprecation import deprecate, deprecated from zope.component.registry import Components from zope.component.interfaces import Invalid, IComponentLookup, IRegistry from zope.component.interfaces import ComponentLookupError from zope.interface.interfaces import ISpecification def GAR(components, registryName): return getattr(components, registryName) class GlobalAdapterRegistry(AdapterRegistry): """A global adapter registry This adapter registry's main purpose is to be picklable in combination with a site manager.""" def __init__(self, parent, name): self.__parent__ = parent self.__name__ = name super(GlobalAdapterRegistry, self).__init__() def __reduce__(self): return GAR, (self.__parent__, self.__name__) ######################################################################## # # BBB 2006/02/28 -- to be removed after 12 months class _IGlobalSiteManager(IComponentLookup, IRegistry): def provideAdapter(required, provided, name, factory, info=''): """Register an adapter factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the adapter - `info`: Provide some info about this particular adapter. """ def subscribe(required, provided, factory, info=''): """Register a subscriber factory :Parameters: - `required`: a sequence of specifications for objects to be adapted. - `provided`: The interface provided by the adapter - `name`: The adapter name - `factory`: The object used to compute the subscriber - `info`: Provide some info about this particular adapter. """ def provideUtility(providedInterface, component, name='', info='', strict=True): """Register a utility If strict is true, then the specified component *must* implement the `providedInterface`. Turning strict off is particularly useful for tests.""" # ######################################################################## class BaseGlobalComponents(Components): implements(_IGlobalSiteManager) def _init_registries(self): self.adapters = GlobalAdapterRegistry(self, 'adapters') self.utilities = GlobalAdapterRegistry(self, 'utilities') def __reduce__(self): # Global site managers are pickled as global objects return self.__name__ #################################################################### # # BBB 2006/02/28 -- to be removed after 12 months @deprecate("The provideAdapter method of the global site manager has been " "deprecated. Use registerAdapter instead.") def provideAdapter(self, required, provided, name, factory, info=''): self.registerAdapter(factory, required, provided, name, info) @deprecate("The subscribe method of the global site manager has been " "deprecated. Use registerHandler or registerSubscriptionAdapter " "instead.") def subscribe(self, required, provided, factory, info=''): if provided is None: self.registerHandler(factory, required, u'', info) else: self.registerSubscriptionAdapter(factory, required, provided, info=info) @deprecate("The provideUtility method of the global site manager has been " "deprecated. Use registerUtility instead.") def provideUtility(self, providedInterface, component, name='', info='', strict=True): if strict and not providedInterface.providedBy(component): raise Invalid("The registered component doesn't provide " "the promised interface.") self.registerUtility(component, providedInterface, name, info) @deprecate("The registrations method of the global site manager has been " "deprecate. Use either registeredAdapters, registeredUtilities, " "or registeredSubscriptionAdapters instead.") def registrations(self): for reg in self.registeredAdapters(): yield reg for reg in self.registeredSubscriptionAdapters(): yield reg for reg in self.registeredHandlers(): yield reg for reg in self.registeredUtilities(): yield reg # #################################################################### base = BaseGlobalComponents('base') from zope.testing.cleanup import addCleanUp addCleanUp(lambda: base.__init__('base')) del addCleanUp globalSiteManager = base def getGlobalSiteManager(): return globalSiteManager # The following APIs provide global registration support for Python code. # We eventually want to deprecate these in favor of using the global # component registry directly. def provideUtility(component, provides=None, name=u''): base.registerUtility(component, provides, name, event=False) def provideAdapter(factory, adapts=None, provides=None, name=''): base.registerAdapter(factory, adapts, provides, name, event=False) def provideSubscriptionAdapter(factory, adapts=None, provides=None): base.registerSubscriptionAdapter(factory, adapts, provides, event=False) def provideHandler(factory, adapts=None): base.registerHandler(factory, adapts, event=False) import zope.component._api # see http://www.zope.org/Collectors/Zope3-dev/674 # Ideally, we will switch to an explicit adapter hook registration. For now, # if you provide an adapter, we want to make sure that the adapter hook is # registered, and that registration depends on code in _api, which itself # depends on code in this module. So, for now, we do another of these nasty # circular import workarounds. See also standalonetests.py, as run by # tests.py in StandaloneTests, for a test that fails without this hack, and # succeeds with it. ```
[ { "content": "Here is the code content:\n```python\nfrom unittest import TestCase\nfrom nose_parameterized import parameterized\nfrom collections import OrderedDict\nimport os\nimport gzip\n\nfrom pandas import (\n Series,\n DataFrame,\n date_range,\n Timestamp,\n read_csv\n)\nfrom pandas.util.te...
[ { "content": "Here is the code content:\n<|memory_start|>```python\nfrom unittest import TestCase\nfrom nose_parameterized import parameterized\nfrom collections import OrderedDict\nimport os\nimport gzip\n\nfrom pandas import (\n Series,\n DataFrame,\n date_range,\n Timestamp,\n read_csv\n)\nfro...
```python from unittest import TestCase from nose_parameterized import parameterized from collections import OrderedDict import os import gzip from pandas import ( Series, DataFrame, date_range, Timestamp, read_csv ) from pandas.util.testing import assert_frame_equal from numpy import ( arange, zeros_like, nan, ) import warnings from pyfolio.utils import (to_utc, to_series, check_intraday, detect_intraday, estimate_intraday) from pyfolio.pos import (get_percent_alloc, extract_pos, get_sector_exposures, get_max_median_position_concentration) class PositionsTestCase(TestCase): dates = date_range(start='2015-01-01', freq='D', periods=20) def test_get_percent_alloc(self): raw_data = arange(15, dtype=float).reshape(5, 3) # Make the first column negative to test absolute magnitudes. raw_data[:, 0] *= -1 frame = DataFrame( raw_data, index=date_range('01-01-2015', freq='D', periods=5), columns=['A', 'B', 'C'] ) result = get_percent_alloc(frame) expected_raw = zeros_like(raw_data) for idx, row in enumerate(raw_data): expected_raw[idx] = row / row.sum() expected = DataFrame( expected_raw, index=frame.index, columns=frame.columns, ) assert_frame_equal(result, expected) def test_extract_pos(self): index_dup = [Timestamp('2015-06-08', tz='UTC'), Timestamp('2015-06-08', tz='UTC'), Timestamp('2015-06-09', tz='UTC'), Timestamp('2015-06-09', tz='UTC')] index = [Timestamp('2015-06-08', tz='UTC'), Timestamp('2015-06-09', tz='UTC')] positions = DataFrame( {'amount': [100., 200., 300., 400.], 'last_sale_price': [10., 20., 30., 40.], 'sid': [1, 2, 1, 2]}, index=index_dup ) cash = Series([100., 200.], index=index) result = extract_pos(positions, cash) expected = DataFrame(OrderedDict([ (1, [100.*10., 300.*30.]), (2, [200.*20., 400.*40.]), ('cash', [100., 200.])]), index=index ) expected.index.name = 'index' assert_frame_equal(result, expected) @parameterized.expand([ (DataFrame([[1.0, 2.0, 3.0, 10.0]]*len(dates), columns=[0, 1, 2, 'cash'], index=dates), {0: 'A', 1: 'B', 2: 'A'}, DataFrame([[4.0, 2.0, 10.0]]*len(dates), columns=['A', 'B', 'cash'], index=dates), False), (DataFrame([[1.0, 2.0, 3.0, 10.0]]*len(dates), columns=[0, 1, 2, 'cash'], index=dates), Series(index=[0, 1, 2], data=['A', 'B', 'A']), DataFrame([[4.0, 2.0, 10.0]]*len(dates), columns=['A', 'B', 'cash'], index=dates), False), (DataFrame([[1.0, 2.0, 3.0, 10.0]]*len(dates), columns=[0, 1, 2, 'cash'], index=dates), {0: 'A', 1: 'B'}, DataFrame([[1.0, 2.0, 10.0]]*len(dates), columns=['A', 'B', 'cash'], index=dates), True) ]) def test_sector_exposure(self, positions, mapping, expected_sector_exposure, warning_expected): """ Tests sector exposure mapping and rollup. """ with warnings.catch_warnings(record=True) as w: result_sector_exposure = get_sector_exposures(positions, mapping) assert_frame_equal(result_sector_exposure, expected_sector_exposure) if warning_expected: self.assertEqual(len(w), 1) else: self.assertEqual(len(w), 0) @parameterized.expand([ (DataFrame([[1.0, 2.0, 3.0, 14.0]]*len(dates), columns=[0, 1, 2, 'cash'], index=dates), DataFrame([[0.15, 0.1, nan, nan]]*len(dates), columns=['max_long', 'median_long', 'median_short', 'max_short'], index=dates)), (DataFrame([[1.0, -2.0, -13.0, 15.0]]*len(dates), columns=[0, 1, 2, 'cash'], index=dates), DataFrame([[1.0, 1.0, -7.5, -13.0]]*len(dates), columns=['max_long', 'median_long', 'median_short', 'max_short'], index=dates)), (DataFrame([[nan, 2.0, nan, 8.0]]*len(dates), columns=[0, 1, 2, 'cash'], index=dates), DataFrame([[0.2, 0.2, nan, nan]]*len(dates), columns=['max_long', 'median_long', 'median_short', 'max_short'], index=dates)) ]) def test_max_median_exposure(self, positions, expected): alloc_summary = get_max_median_position_concentration(positions) assert_frame_equal(expected, alloc_summary) __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) test_returns = read_csv( gzip.open( __location__ + '/test_data/test_returns.csv.gz'), index_col=0, parse_dates=True) test_returns = to_series(to_utc(test_returns)) test_txn = to_utc(read_csv( gzip.open( __location__ + '/test_data/test_txn.csv.gz'), index_col=0, parse_dates=True)) test_pos = to_utc(read_csv( gzip.open(__location__ + '/test_data/test_pos.csv.gz'), index_col=0, parse_dates=True)) @parameterized.expand([ (test_pos, test_txn, False), (test_pos.resample('1W').last(), test_txn, True) ]) def test_detect_intraday(self, positions, transactions, expected): detected = detect_intraday(positions, transactions, threshold=0.25) assert detected == expected @parameterized.expand([ ('infer', test_returns, test_pos, test_txn, test_pos), (False, test_returns, test_pos, test_txn, test_pos) ]) def test_check_intraday(self, estimate, returns, positions, transactions, expected): detected = check_intraday(estimate, returns, positions, transactions) assert_frame_equal(detected, expected) @parameterized.expand([ (test_returns, test_pos, test_txn, (1506, 8)), (test_returns, test_pos.resample('1W').last(), test_txn, (1819, 8)) ]) def test_estimate_intraday(self, returns, positions, transactions, expected): intraday_pos = estimate_intraday(returns, positions, transactions) assert intraday_pos.shape == expected ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom PIL import Image\r\n\r\ndef save_img(sess, tensor, name):\r\n tensor0 = tf.transpose(tensor, perm=[1, 2, 0])\r\n res = sess.run(tensor0)\r\n tensor1 = tens...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom PIL import Image\r\n\r\ndef save_img(sess, tensor, name):\r\n tensor0 = tf.transpose(tensor, perm=[1, 2, 0])\r\n res = sess.run(tensor0)\r\n ...
```python import numpy as np import tensorflow as tf from PIL import Image def save_img(sess, tensor, name): tensor0 = tf.transpose(tensor, perm=[1, 2, 0]) res = sess.run(tensor0) tensor1 = tensor0.eval() im = Image.fromarray(tensor1.astype('uint8')) im.save(name) ''' im = Image.open("example_image_227x227.jpg") im1 = im.resize((300,300)) n0 = np.array(im1) print(n0.shape) np.savetxt("input_0_out0_300_300_3.tensor", n0.flatten(), fmt='%f') ''' n1 = np.loadtxt('input_0_out0_300_300_3.tensor', dtype=np.float32) input0 = n1.reshape((300, 300, 3)) im2 = Image.fromarray(input0.astype('uint8')) im2.save("2.jpg") with tf.Session() as sess: input1 = tf.transpose(input0, perm=[2, 0, 1]) res = sess.run(input1) np.savetxt("input_0_out0_3_300_300.tensor", input1.eval().flatten(), fmt='%f') out_crop = tf.slice(input1, [0, 75, 75], [3, 150, 150]) res = sess.run(out_crop) out_crop0 = out_crop.eval() np.savetxt("out_crop0.tensor", out_crop0.flatten(), fmt='%f') save_img(sess, out_crop0, "3.jpg") out_reverse = tf.reverse(out_crop0, [0]) res = sess.run(out_reverse) out_reverse0 = out_reverse.eval() np.savetxt("out_reverse0.tensor", out_reverse0.flatten(), fmt='%f') save_img(sess, out_reverse0, "4.jpg") mean = [127, 127, 127] scale = 1.0 / 128 out_mean0 = tf.transpose(out_reverse0, perm=[1, 2, 0]) out_mean1 = (out_mean0 - mean) * scale out_mean2 = tf.transpose(out_mean1, perm=[2, 0, 1]) sess.run(out_mean2) np.savetxt("out_mean2.tensor", out_mean2.eval().flatten(), fmt='%f') ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\n\"\"\"\n Author: ikosenn\n\n This is a program to eliminate stale git branches.\n It checks last commits and based on the staleness threshold\n eliminates all stale branches\n\n Another CL function is pr...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\n\"\"\"\n Author: ikosenn\n\n This is a program to eliminate stale git branches.\n It checks last commits and based on the staleness threshold\n eliminates all stale branches\n\n Another C...
```python """ Author: ikosenn This is a program to eliminate stale git branches. It checks last commits and based on the staleness threshold eliminates all stale branches Another CL function is provided to eliminate all available branches. You can also remove all branches that have already been merged to the main branch """ import os from datetime import datetime import click from sarge import capture_stdout import pytz from dateutil.parser import parse DEFAULT_BRANCH = 'master' # helper functions def get_time_difference(time): """ Computes the difference with todays time """ timezone = "Africa/Nairobi" branch_time = parse(time) current_time = datetime.now(pytz.timezone(timezone)) diff_days = (current_time - branch_time) return diff_days.days def cwd(path): os.chdir(path) @click.command() @click.option( '--threshold', '-t', default=10, prompt='What number of days should the threshold be? [10 days]') @click.option( 'branches', '--branch', '-b', default=DEFAULT_BRANCH, prompt='What branches should be excluded? [master]', multiple=True) @click.option( '--path', '-p', prompt='File path to the git repo?', type=click.Path(exists=True)) def fummy(threshold, branches, path): cwd(path) all_branches = capture_stdout('git branch') # remove spaces and any blank spaces temp = all_branches.stdout.text.replace( '*', '').replace(' ', '').split('\n') for branch in temp: if branch and branch not in branches: click.echo('Processing branch: {}'.format(branch)) p = capture_stdout( 'git show {} --format="%cI" --no-patch'.format(branch)) diff_days = get_time_difference(p.stdout.text) if diff_days > threshold: click.echo('Deleting {}'.format(branch)) p = capture_stdout( 'git branch -D {}'.format(branch)) click.echo(p.stdout.text) @click.command() @click.option('--filename', type=click.Path(exists=True)) @click.option('--default', '-d', default=DEFAULT_BRANCH) def kill_merged(default): """ Start by checking out to the master branch and then finding out the branches already merged to master and eliminating the buggage """ # git branch --merged master pass @click.group() def cli(): """ Command Line Interface tools loader for ``fummy`` These utilities help with deleting git branches older than the specified period """ pass cli.add_command(fummy) if __name__ == '__main__': cli() ```
[ { "content": "Repeat the following code:\n```python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and\nSOCKS5. To enable its functionality, either install PySocks or install this\n...
[ { "content": "Repeat the following code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and\nSOCKS5. To enable its functionality, either install PySocks o...
```python # -*- coding: utf-8 -*- """ This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4 - SOCKS4a - SOCKS5 - Usernames and passwords for the SOCKS proxy Known Limitations: - Currently PySocks does not support contacting remote websites via literal IPv6 addresses. Any such connection attempt will fail. You must use a domain name. - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any such connection attempt will fail. """ from __future__ import absolute_import try: import socks except ImportError: import warnings from ..exceptions import DependencyWarning warnings.warn(( 'SOCKS support in urllib3 requires the installation of optional ' 'dependencies: specifically, PySocks. For more information, see ' 'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies' ), DependencyWarning ) raise from socket import error as SocketError, timeout as SocketTimeout from ..connection import ( HTTPConnection, HTTPSConnection ) from ..connectionpool import ( HTTPConnectionPool, HTTPSConnectionPool ) from ..exceptions import ConnectTimeoutError, NewConnectionError from ..poolmanager import PoolManager from ..util.url import parse_url try: import ssl except ImportError: ssl = None class SOCKSConnection(HTTPConnection): """ A plain-text HTTP connection that connects via a SOCKS proxy. """ def __init__(self, *args, **kwargs): self._socks_options = kwargs.pop('_socks_options') super(SOCKSConnection, self).__init__(*args, **kwargs) def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], proxy_rdns=self._socks_options['rdns'], timeout=self.timeout, **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout) ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn # We don't need to duplicate the Verified/Unverified distinction from # urllib3/connection.py here because the HTTPSConnection will already have been # correctly set to either the Verified or Unverified form by that module. This # means the SOCKSHTTPSConnection will automatically be the correct type. class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): pass class SOCKSHTTPConnectionPool(HTTPConnectionPool): ConnectionCls = SOCKSConnection class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): ConnectionCls = SOCKSHTTPSConnection class SOCKSProxyManager(PoolManager): """ A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. """ pool_classes_by_scheme = { 'http': SOCKSHTTPConnectionPool, 'https': SOCKSHTTPSConnectionPool, } def __init__(self, proxy_url, username=None, password=None, num_pools=10, headers=None, **connection_pool_kw): parsed = parse_url(proxy_url) if username is None and password is None and parsed.auth is not None: split = parsed.auth.split(':') if len(split) == 2: username, password = split if parsed.scheme == 'socks5': socks_version = socks.PROXY_TYPE_SOCKS5 rdns = False elif parsed.scheme == 'socks5h': socks_version = socks.PROXY_TYPE_SOCKS5 rdns = True elif parsed.scheme == 'socks4': socks_version = socks.PROXY_TYPE_SOCKS4 rdns = False elif parsed.scheme == 'socks4a': socks_version = socks.PROXY_TYPE_SOCKS4 rdns = True else: raise ValueError( "Unable to determine SOCKS version from %s" % proxy_url ) self.proxy_url = proxy_url socks_options = { 'socks_version': socks_version, 'proxy_host': parsed.host, 'proxy_port': parsed.port, 'username': username, 'password': password, 'rdns': rdns } connection_pool_kw['_socks_options'] = socks_options super(SOCKSProxyManager, self).__init__( num_pools, headers, **connection_pool_kw ) self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme ```
[ { "content": "```python\nimport json\nimport datetime\nimport re\nimport os\nimport psycopg2 as dbapi2\n\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import redirect\nfrom flask import request\nfrom flask.helpers import url_for\n\nclass Dil:\n def __init__(self, name, ulkesi, photo...
[ { "content": "<|memory_start|>```python\nimport json\nimport datetime\nimport re\nimport os\nimport psycopg2 as dbapi2\n\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import redirect\nfrom flask import request\nfrom flask.helpers import url_for\n\nclass Dil:\n def __init__(self, nam...
```python import json import datetime import re import os import psycopg2 as dbapi2 from flask import Flask from flask import render_template from flask import redirect from flask import request from flask.helpers import url_for class Dil: def __init__(self, name, ulkesi, photo, bilenler): self.name = name self.ulkesi = ulkesi self.photo = photo self.bilenler = bilenler def init_diller_db(cursor): query = """DROP TABLE IF EXISTS DIL""" cursor.execute(query) query = """CREATE TABLE DIL ( ID SERIAL PRIMARY KEY, NAME varchar(100) UNIQUE NOT NULL, ULKESI INTEGER NOT NULL REFERENCES LOKASYON(ID) ON DELETE CASCADE ON UPDATE CASCADE, PHOTO varchar(80), BILENLER INTEGER NOT NULL REFERENCES KISILER(ID) ON DELETE CASCADE ON UPDATE CASCADE DEFAULT 1 )""" cursor.execute(query) insert_dil(cursor) def insert_dil(cursor): query = """INSERT INTO DIL (NAME, ULKESI, PHOTO, BILENLER) VALUES ( 'Türkçe', 1, 'türkçe.jpeg', 3 )""" cursor.execute(query) query = """INSERT INTO DIL (NAME, ULKESI, PHOTO, BILENLER) VALUES ( 'İngilizce', 2, 'ingilizce.jpg', 4 )""" cursor.execute(query) query = """INSERT INTO DIL (NAME, ULKESI, PHOTO, BILENLER) VALUES ( 'Fransızca', 3, 'fransızca.jpg', 1 )""" cursor.execute(query) query = """INSERT INTO DIL (NAME, ULKESI, PHOTO, BILENLER) VALUES ( 'İtalyanca', 4, 'italyanca.jpg', 3 )""" cursor.execute(query) query = """INSERT INTO DIL (NAME, ULKESI, PHOTO, BILENLER) VALUES ( 'Almanca', 5, 'almanca.png', 5 )""" cursor.execute(query) def add_dil(cursor, request, dil): query = """INSERT INTO DIL (NAME, ULKESI, PHOTO, BILENLER) VALUES ( %s, %s, %s, %s )""" cursor.execute(query, (dil.name, dil.ulkesi, dil.photo, dil.bilenler)) def delete_diller(cursor, id): query="""DELETE FROM DIL WHERE ID = %s""" cursor.execute(query, id) def update_diller(cursor, id, dil): query=""" UPDATE DIL SET NAME=INITCAP(%s), ULKESI=%s, PHOTO=INITCAP(%s), BILENLER=%s WHERE ID=%s """ cursor.execute(query,(dil.name, dil.ulkesi, dil.photo, dil.bilenler, id)) ```
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n```python\n#!/usr/bin/env python3\n\n# Generate Italic calligraphy SVG images and OpenDocument documents according\n# to the specified parameters.\n#\n# Written in 2014 by Jordan Vaughan\n#\n# To the extent possible under l...
[ { "content": "Replicate the code snippet exactly, without paraphrasing or reformatting:\n<|memory_start|>```python\n#!/usr/bin/env python3\n\n# Generate Italic calligraphy SVG images and OpenDocument documents according\n# to the specified parameters.\n#\n# Written in 2014 by Jordan Vaughan\n#\n# To the extent ...
```python #!/usr/bin/env python3 # Generate Italic calligraphy SVG images and OpenDocument documents according # to the specified parameters. # # Written in 2014 by Jordan Vaughan # # To the extent possible under law, the author(s) have dedicated all copyright # and related and neighboring rights to this software to the public domain # worldwide. This software is distributed without any warranty. # # You should have received a copy of the CC0 Public Domain Dedication along # with this software. If not, see # <http://creativecommons.org/publicdomain/zero/1.0/>. import argparse import csv from decimal import Decimal, InvalidOperation, getcontext import os.path import subprocess import sys default_description_format = "" default_svg_filename_format = "italic-sheet-{nibwidth}mm-5degrees-5-5-5-7.{papersize}.svg" default_fodt_filename_format = "italic-sheets-5degrees-5-5-5-7.{papersize}.fodt" default_title_format = "Italic Calligraphy Practice Sheets ({papersize})" errors = False def error(message): global errors sys.stderr.write(os.path.basename(sys.argv[0]) + ": error: " + message + "\n") errors = True def field_to_decimal(lineno, fieldno, field): try: return Decimal(field) except InvalidOperation as e: error("{0}: field {1} is not a number".format(lineno, fieldno)) return Decimal(0) class Paper(object): def __init__(self, lineno, width, height, margin, name): self.width = field_to_decimal(lineno, 1, width) self.height = field_to_decimal(lineno, 2, height) self.margin = field_to_decimal(lineno, 3, margin) self.name = name if self.width <= 0: error("{0}: width must be positive".format(lineno)) if self.height <= 0: error("{0}: height must be positive".format(lineno)) if self.margin < 0: error("{0}: margin must be positive or zero".format(lineno)) if self.margin > self.width * Decimal(0.5): error("{0}: margin exceeds horizontal page dimensions (i.e., it's too large!)".format(lineno)) if self.margin > self.height * Decimal(0.5): error("{0}: margin exceeds vertical page dimensions (i.e., it's too large!)".format(lineno)) parser = argparse.ArgumentParser(description="Generate SVG images of Italic calligraphy practice sheets and combine them into flat OpenDocument text files. The dimensions and margins of each document's pages are read in tab-separated value (TSV) format from standard input, one page size per line. Each line has four fields: page width in mm, page height in mm, margin in mm, and a nickname for the page type (e.g., letter or a4). This program will generate a set of SVG images and an OpenDocument text file for each page size.") parser.add_argument("-x", "--x-height", type=Decimal, default=Decimal(5), help="""set the x-height (distance between the baseline and the waistline) in nib widths (default is 5)""") parser.add_argument("-c", "--cap-height", type=Decimal, default=Decimal(7), help="""set the cap height in nib widths (default is 7)""") parser.add_argument("-a", "--ascender-height", type=Decimal, default=Decimal(5), help="""set the ascender height in nib widths (default is 5)""") parser.add_argument("-d", "--descender-height", type=Decimal, default=Decimal(5), help="""set the descender height in nib widths (default is 5)""") parser.add_argument("-l", "--pen-ladder", action="store_true", default=False, help="""add a pen ladder to each line""") parser.add_argument("-s", "--slant-angle", type=Decimal, default=Decimal(90), help="""Generate slant guide lines with the specified angle from vertical in degrees, each separated by the box width (-w) (default is 90, which disables slant guide lines)""") parser.add_argument("-w", "--box-width", type=Decimal, default=Decimal(3), help="""set the width of each practice box in nib widths (the distance between slant guide lines; default is 3; has no effect if -s is 90)""") parser.add_argument("-p", "--public-domain-dedication", metavar="AUTHOR", default=None, help="""add a Creative Commons CC0 Public Domain Dedication to the generated image using the specified AUTHOR""") parser.add_argument("-r", "--precision", type=int, default=8, help="""numerical precision in digits (default: 8)""") parser.add_argument("-R", "--resolution", type=int, default=30, help="""SVG pixels per mm (default: 30)""") parser.add_argument("-v", "--verbose", action="store_true", default=False, help="""print processing information on standard error""") parser.add_argument("--baseline-thickness", type=Decimal, default=Decimal('0.25'), help="""the thickness of baselines in mm (default is 0.25)""") parser.add_argument("--waistline-thickness", type=Decimal, default=Decimal('0.1'), help="""the thickness of waistlines in mm (default is 0.1)""") parser.add_argument("--cap-line-thickness", type=Decimal, default=Decimal('0.25'), help="""the thickness of cap lines in mm (default is 0.25)""") parser.add_argument("--cap-line-dash-length", type=Decimal, default=Decimal(0.5), help="""the length of the dashes in cap lines in nib widths (default is 0.5)""") parser.add_argument("--ascender-descender-thickness", type=Decimal, default=Decimal('0.1'), help="""the thickness of ascender and descender lines in mm (default is 0.1)""") parser.add_argument("--slant-line-thickness", type=Decimal, default=Decimal('0.1'), help="""the thickness of slant lines in mm (default is 0.1)""") parser.add_argument("--description-format", default=default_description_format, help="""the format for the description of each OpenDocument text file (the public domain dedication, if any [see -p], is appended to this) (default is blank); use "{{papersize}}" where you'd like the document's paper size to appear""".format(default_description_format)) parser.add_argument("--fodt-filename-format", default=default_fodt_filename_format, help="""set the file name pattern for generated OpenDocument text files (default: {0}); use "{{papersize}}" where you'd like each document's paper size to appear; don't use spaces!""".format(default_fodt_filename_format)) parser.add_argument("--svg-filename-format", default=default_svg_filename_format, help="""set the file name pattern for generated SVG images (default: {0}); use "{{nibwidth}}" and "{{papersize}}" where you'd like each images's pen nib width and paper size to appear; don't use spaces!""".format(default_svg_filename_format)) parser.add_argument("--title-format", default=default_title_format, help="""the format for the title of each OpenDocument text file (default: {}); use "{{papersize}}" where you'd like the document's paper size to appear""".format(default_title_format)) parser.add_argument("nibwidth", type=Decimal, nargs="+", help="""pen nib width in mm""") if __name__ == "__main__": try: args = parser.parse_args() except Exception: error("invalid command line arguments (invalid syntax?)") sys.exit(1) if args.ascender_height <= 0: error("ascender height cannot be zero or negative") if args.descender_height <= 0: error("descender height cannot be zero or negative") if args.x_height <= 0: error("x-height cannot be zero or negative") if args.cap_height <= 0: error("cap height cannot be zero or negative") if args.precision <= 0: error("precision must be positive") if args.slant_angle < 0: error("slant angle cannot be negative") elif args.slant_angle > 90: error("slant angle cannot be greater than 90 degrees") elif args.slant_angle != 90 and args.box_width <= 0: error("box width cannot be zero or negative") if args.resolution <= 0: error("resolution cannot be zero or negative") if args.baseline_thickness <= 0: error("baseline thickness cannot be zero or negative") if args.waistline_thickness <= 0: error("x-height thickness cannot be zero or negative") if args.ascender_descender_thickness <= 0: error("ascender and descender thickness cannot be zero or negative") if args.cap_line_thickness <= 0: error("cap line thickness cannot be zero or negative") if args.slant_line_thickness <= 0: error("slant line thickness cannot be zero or negative") if args.cap_line_dash_length <= 0: error("cap line dash length cannot be zero or negative") def test_format(format, format_name, *args, **kwargs): try: format.format(**kwargs) except KeyError as e: error("{} format string is invalid: it specifies an illegal key {{".format(format_name) + str(e) + """} (try doubling '{' and '}' characters to "{{" and "}}")""") test_format(args.description_format, "OpenDocument description", papersize="a4") test_format(args.svg_filename_format, "SVG file name", nibwidth=2, papersize="a4") test_format(args.fodt_filename_format, "OpenDocument text file name", papersize="a4") test_format(args.title_format, "OpenDocument title", papersize="a4") if any(nw <= 0 for nw in args.nibwidth): error("nib widths must be positive") if errors: sys.exit(1) if not args.nibwidth: sys.exit(0) getcontext().prec = args.precision def verbose(level, msg): if args.verbose: sys.stderr.write("=" + "=" * (level * 2) + " " + msg + "\n") verbose(0, "Reading paper dimensions, margins, and names from standard input") papers = [] try: for lineno, line in enumerate(csv.reader(sys.stdin, delimiter="\t"), start=1): line = list(filter(None, line)) if len(line) is 0: continue elif len(line) < 4: error("{0}: expected at least 4 fields, got {1}".format(lineno, len(line))) else: paper = Paper(lineno, line[0], line[1], line[2], line[3]) papers.append(paper) verbose(1, paper.name + ": {0}mmx{1}mm with {2}mm margins".format(paper.width, paper.height, paper.margin)) except csv.Error as e: error("stdin isn't a tab-delimited file") if errors: sys.exit(2) if not papers: sys.exit(0) verbose(0, "Generating files") for paper in papers: verbose(1, paper.name) imgwidth = paper.width - 2 * paper.margin imgheight = paper.height - 2 * paper.margin svgimages = [] svgerrors = False verbose(2, "SVG images ({}mmx{}mm)".format(imgwidth, imgheight)) for nibwidth in args.nibwidth: svgimage = args.svg_filename_format.format(nibwidth=nibwidth, papersize=paper.name) verbose(3, str(nibwidth) + "mm -- " + svgimage) if subprocess.call("svgitalicsheet.py -n {0} -x {args.x_height} -c {args.cap_height} -a {args.ascender_height} -d {args.descender_height} -s {args.slant_angle} {1}-w {args.box_width} {2}-r {args.precision} --baseline-thickness {args.baseline_thickness} --waistline-thickness {args.waistline_thickness} --cap-line-thickness {args.cap_line_thickness} --cap-line-dash-length {args.cap_line_dash_length} --ascender-descender-thickness {args.ascender_descender_thickness} --slant-line-thickness {args.slant_line_thickness} {3} {4} {5} >{6}".format(nibwidth, "-l " if args.pen_ladder else "", '-p "{}" '.format(args.public_domain_dedication) if args.public_domain_dedication else "", imgwidth, imgheight, args.resolution, svgimage, args=args), shell=True) != 0: error("svgitalicsheet.py failed for paper size {0} and nib width {1}".format(paper.name, nibwidth)) svgerrors = True else: svgimages.append(svgimage) if svgerrors: error("skipping OpenDocument generation for paper size {} due to prior errors".format(paper.name)) else: fodtfile = args.fodt_filename_format.format(papersize=paper.name) verbose(2, "OpenDocument file " + fodtfile) if subprocess.call("""fodtitalicsheets.py {}{} -t "{}" {} {} {} {} >{}""".format('-p "{}" '.format(args.public_domain_dedication) if args.public_domain_dedication else "", '-d "{}" '.format(args.description_format.format(papersize=paper.name)) if args.description_format else "", args.title_format.format(papersize=paper.name), paper.width, paper.height, paper.margin, " ".join(svgimages), fodtfile), shell=True) != 0: error("fodtitalicsheets.py failed for paper size {}".format(paper.name)) if errors: verbose(0, "ERRORS! Exiting...") sys.exit(2) verbose(0, "Done") ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license info...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for...
```python # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .trigger import Trigger class PeriodicTimerEventTrigger(Trigger): """Trigger details. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: The path ID that uniquely identifies the object. :vartype id: str :ivar name: The object name. :vartype name: str :ivar type: The hierarchical type of the object. :vartype type: str :param kind: Required. Constant filled by server. :type kind: str :param source_info: Required. Periodic timer details. :type source_info: ~azure.mgmt.edgegateway.models.PeriodicTimerSourceInfo :param sink_info: Required. Role Sink information. :type sink_info: ~azure.mgmt.edgegateway.models.RoleSinkInfo :param custom_context_tag: A custom context tag typically used to correlate the trigger against its usage. For example, if a periodic timer trigger is intended for certain specific IoT modules in the device, the tag can be the name or the image URL of the module. :type custom_context_tag: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'kind': {'required': True}, 'source_info': {'required': True}, 'sink_info': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'source_info': {'key': 'properties.sourceInfo', 'type': 'PeriodicTimerSourceInfo'}, 'sink_info': {'key': 'properties.sinkInfo', 'type': 'RoleSinkInfo'}, 'custom_context_tag': {'key': 'properties.customContextTag', 'type': 'str'}, } def __init__(self, **kwargs): super(PeriodicTimerEventTrigger, self).__init__(**kwargs) self.source_info = kwargs.get('source_info', None) self.sink_info = kwargs.get('sink_info', None) self.custom_context_tag = kwargs.get('custom_context_tag', None) self.kind = 'PeriodicTimerEvent' ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2014 Osmo Salomaa\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, eit...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2014 Osmo Salomaa\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software...
```python # -*- coding: utf-8 -*- # Copyright (C) 2014 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Standard paths to files.""" import os __all__ = ("CACHE_HOME_DIR", "CONFIG_HOME_DIR", "DATA_DIR", "DATA_HOME_DIR", "LOCALE_DIR") XDG_CACHE_HOME = os.path.expanduser(os.getenv("XDG_CACHE_HOME", "~/.cache")) XDG_CONFIG_HOME = os.path.expanduser(os.getenv("XDG_CONFIG_HOME", "~/.config")) XDG_DATA_HOME = os.path.expanduser(os.getenv("XDG_DATA_HOME", "~/.local/share")) CACHE_HOME_DIR = os.path.join(XDG_CACHE_HOME, "harbour-poor-maps") CONFIG_HOME_DIR = os.path.join(XDG_CONFIG_HOME, "harbour-poor-maps") DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) DATA_HOME_DIR = os.path.join(XDG_DATA_HOME, "harbour-poor-maps") LOCALE_DIR = "/usr/share/harbour-poor-maps/locale" ```
[ { "content": "Here is the source code:\n```python\n# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Co...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license infor...
```python # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class AvailableProvidersList(Model): """List of available countries with details. All required parameters must be populated in order to send to Azure. :param countries: Required. List of available countries. :type countries: list[~azure.mgmt.network.v2017_09_01.models.AvailableProvidersListCountry] """ _validation = { 'countries': {'required': True}, } _attribute_map = { 'countries': {'key': 'countries', 'type': '[AvailableProvidersListCountry]'}, } def __init__(self, **kwargs): super(AvailableProvidersList, self).__init__(**kwargs) self.countries = kwargs.get('countries', None) ```
[ { "content": "Here is the source code:\n```python\n# -*- coding: utf-8 -*-\n\nfrom django.db import models\nfrom .validators import validate_printable\nimport os\n\nclass JobSession(models.Model):\n status = models.CharField(max_length=3000)\n all_status = models.CharField(max_length=48000)\n attachedf...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\nfrom django.db import models\nfrom .validators import validate_printable\nimport os\n\nclass JobSession(models.Model):\n status = models.CharField(max_length=3000)\n all_status = models.CharField(max_length=48000...
```python # -*- coding: utf-8 -*- from django.db import models from .validators import validate_printable import os class JobSession(models.Model): status = models.CharField(max_length=3000) all_status = models.CharField(max_length=48000) attachedfile = models.FileField( upload_to='imprimo', validators=[validate_printable]) printer = models.CharField(max_length=12) completed = models.BooleanField() def __unicode__(self): returnstring = "id: %s, status: %s" % (str(self.id), self.status) if self.attachedfile: returnstring += ", attachedfile: %s" % str(self.attachedfile.name) return returnstring def update_status(self, status): update = JobSession.objects.get(pk=self.pk) self.status = update.status+"\n"+status self.all_status += "\n"+status self.save(update_fields=['status', 'all_status']) def print_status(self): status = self.status self.status = '' if self.completed: self.delete() else: self.save(update_fields=['status']) return status def print_all_status(self): self.status = '' if self.completed: self.deleted() else: self.save(update_fields=['status']) return self.all_status def attachedfilename(self): return os.path.basename(self.attachedfile.name) def filetype(self): self.attachedfile.open() magic_number = self.attachedfile.read(2) self.attachedfile.open() if magic_number == r'%!': return 'ps' else: return 'pdf' ```
[ { "content": "Reproduce the code exactly as provided (keep formatting):\n```python\n#!/usr/bin/env python\nimport sys\nimport os\n# setup.py largely based on\n# http://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/\n# Also see Jeet Sukumaran's DendroPy\n\n##################################...
[ { "content": "Reproduce the code exactly as provided (keep formatting):\n<|memory_start|>```python\n#!/usr/bin/env python\nimport sys\nimport os\n# setup.py largely based on\n# http://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/\n# Also see Jeet Sukumaran's DendroPy\n\n##################...
```python #!/usr/bin/env python import sys import os # setup.py largely based on # http://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ # Also see Jeet Sukumaran's DendroPy ############################################################################### # setuptools/distutils/etc. import and configuration try: import ez_setup try: ez_setup_path = " ('" + os.path.abspath(ez_setup.__file__) + "')" except OSError: ez_setup_path = "" sys.stderr.write("using ez_setup%s\n" % ez_setup_path) ez_setup.use_setuptools() import setuptools try: setuptools_path = " ('" + os.path.abspath(setuptools.__file__) + "')" except OSError: setuptools_path = "" sys.stderr.write("using setuptools%s\n" % setuptools_path) from setuptools import setup, find_packages except ImportError, e: sys.stderr.write("using distutils\n") from distutils.core import setup sys.stderr.write("using canned package list\n") PACKAGES = ['rbg',] EXTRA_KWARGS = {} else: sys.stderr.write("searching for packages\n") PACKAGES = find_packages() EXTRA_KWARGS = dict( install_requires = ['setuptools'], include_package_data=True, #test_suite = "peyotl.test" ) EXTRA_KWARGS["zip_safe"] = True ENTRY_POINTS = {} ############################################################################### # setuptools/distuils command extensions try: from setuptools import Command except ImportError: sys.stderr.write("setuptools.Command could not be imported: setuptools extensions not available\n") else: sys.stderr.write("setuptools command extensions are available\n") command_hook = "distutils.commands" ENTRY_POINTS[command_hook] = [] setup( name='rbg', version='0.0.0a', description='Library for generating Rev language from python', long_description=(open('README.md').read()), url='https://github.com/mtholder/rbg', license='BSD', author='Mark T. Holder', author_email='mtholder', py_modules=['rbg'], entry_points=ENTRY_POINTS, classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Bio-Informatics', ], **EXTRA_KWARGS ) ```
[ { "content": "```python\nimport subprocess\nimport sys\nimport os\nimport win32com.client\nimport time\n\noutlook = None\nnameAliasDict = {}\ncontacts = None\nnumEntries = None\nfile = None\nmail_schema = \"http://schemas.microsoft.com/mapi/proptag/0x800F101F\"\nalias_schema = \"http://schemas.microsoft.com/map...
[ { "content": "<|memory_start|>```python\nimport subprocess\nimport sys\nimport os\nimport win32com.client\nimport time\n\noutlook = None\nnameAliasDict = {}\ncontacts = None\nnumEntries = None\nfile = None\nmail_schema = \"http://schemas.microsoft.com/mapi/proptag/0x800F101F\"\nalias_schema = \"http://schemas.m...
```python import subprocess import sys import os import win32com.client import time outlook = None nameAliasDict = {} contacts = None numEntries = None file = None mail_schema = "http://schemas.microsoft.com/mapi/proptag/0x800F101F" alias_schema = "http://schemas.microsoft.com/mapi/proptag/0x3A00001F" criticalCommit = False svn_path ='https://svn.ali.global/gen7/mk7games/games/red_black_yellow/branches/' temp_svn_path = None lastRevision = None #get the svn revision number for the critical fix, all svn logs are written here def getLastCommitRevision(): svn_revision_file = os.path.expanduser('~/AppData/Local/TortoiseSVN/logfile.txt') revision_num_generated = False revision_list = [] for line in open(svn_revision_file): if revision_num_generated: if 'At revision' in line: revision_num = line.split(':')[-1] revision_list.append(revision_num.strip()) revision_num_generated = False if 'Committing transaction' in line: revision_num_generated = True #print revision_list return revision_list[-1] #check if the last commit was critical or not def isCriticalCommit(): global criticalCommit, svn_path, temp_svn_path, lastRevision cmd = 'svn info > svn_log.txt' p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, stderr = p.communicate() for line in open('svn_log.txt'): if 'URL' in line: svn_path = line.split(' ')[1].strip() break temp_svn_path = svn_path svn_path = svn_path.split('branches')[0].strip() svn_path = svn_path + 'branches' lastRevision = getLastCommitRevision() while True: cmd = 'svn log '+svn_path+' -r '+lastRevision p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, stderr = p.communicate() if 'No such revision' in output: print "Repository not synched yet, retrying in next 10 seconds..." time.sleep(10) elif 'Critical Commit' in output: criticalCommit = True break else: criticalCommit = False break #get a substring between first and last def find_between( s, first, last ): try: start = s.index( first ) + len( first ) end = s.index( last, start+1 ) return s[start:end] except ValueError: return "" #send a mail def send_mail(branchname,recipient , manager): global outlook subject = "[IMPORTANT]Critical Check-in Information" body = "The branch " + branchname+" has got a critical issue checked in at revision: "+lastRevision+" , please have a look at the changes." mail = outlook.CreateItem(0) mail.To = recipient if manager != None : mail.CC = manager mail.Subject = subject mail.Body = body print "Sending mail to the stakeholders" mail.Send() def getMailId(contact) : prop_str = contact.PropertyAccessor.GetProperty(mail_schema) prop = str(prop_str).split(',') mail = find_between(prop[0],'\'','\'').split(':')[-1] return mail #Get the global address list def fillContactList(): global contacts, nameAliasDict, file for i in contacts: # name = i.Name prop_str_alias = i.PropertyAccessor.GetProperty(alias_schema) nameAliasDict[prop_str_alias.lower()] = i file.write(prop_str_alias.encode('utf-8').strip() + "\n") file.close() def init(): global outlook, contacts, numEntries, file outlook = win32com.client.gencache.EnsureDispatch("Outlook.Application") ns = outlook.GetNamespace("MAPI") file = open('mapping.txt', 'w') adrLi = ns.AddressLists.Item("Global Address List") contacts = adrLi.AddressEntries numEntries = adrLi.AddressEntries.Count def getSvnLog(): global temp_svn_path cmd = 'svn log -q '+svn_path+'> svn_log.txt' p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, stderr = p.communicate() authors = set() for line in open('svn_log.txt'): if 'r' in line: authors.add(line.split('|')[1].strip()) author_mail = "" manager_mail = "" for author in sorted(authors): if author.lower() in nameAliasDict: author_mail = author_mail + ';' + getMailId(nameAliasDict[author.lower()]) if nameAliasDict[author.lower()].Manager != None: manager_mail = manager_mail + ';' + getMailId(nameAliasDict[author.lower()].Manager) send_mail(temp_svn_path,"Anshul.Garg@ali.com.au", "Aman.Arora@ali.com.au;Anshul.Garg@ali.com.au") #send_mail(temp_svn_path,author_mail,manager_mail) def removeFile(): os.remove ('svn_log.txt') os.remove ('mapping.txt') isCriticalCommit() if criticalCommit == True: print "critical commit detected \n" init() fillContactList() getSvnLog() removeFile() ```
[ { "content": "```python\nimport os\nfrom setuptools import setup\n\nREADME = open(os.path.join(os.path.dirname(__file__), 'README')).read()\n\nsetup(\n\t\tzip_safe=False,\n\t\tname='django-lavaflow',\n\t\tversion='1.1',\n\t\tpackages=['lavaFlow'],\n\t\tinclude_package_data=True,\t\n\t\tlicense=\"GPL 3\",\n\t\td...
[ { "content": "<|memory_start|>```python\nimport os\nfrom setuptools import setup\n\nREADME = open(os.path.join(os.path.dirname(__file__), 'README')).read()\n\nsetup(\n\t\tzip_safe=False,\n\t\tname='django-lavaflow',\n\t\tversion='1.1',\n\t\tpackages=['lavaFlow'],\n\t\tinclude_package_data=True,\t\n\t\tlicense=\...
```python import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README')).read() setup( zip_safe=False, name='django-lavaflow', version='1.1', packages=['lavaFlow'], include_package_data=True, license="GPL 3", description="LavaFlow creates useful reports on the usage of high performance compute clusters. LavaFlow takes data from the batch scheduling system, monitoring, and other tooling, and creates reports that help administrators, managers, and end users better understand their cluster environment.", long_description=README, url="http://ay60dxg.com/projects/lavaflow/", author="David Irvine", author_email="irvined@gmail.com", scripts=['import/lava-import-gridengine.py','import/lava-import-openlava'], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Programming Language :: Python', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Intended Audience :: Science/Research', 'Intended Audience :: System Administrators', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Information Analysis', ], ) ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2009-2010 CloudSizzle Team\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, includi...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2009-2010 CloudSizzle Team\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# rest...
```python # -*- coding: utf-8 -*- # # Copyright (c) 2009-2010 CloudSizzle Team # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import os import unittest from scrapy.http import Request from cloudsizzle.scrapers.noppa.items import CourseItem, FacultyItem, \ DepartmentItem from cloudsizzle.scrapers.mock import MockResponseFactory from cloudsizzle.scrapers.noppa.spiders.noppa import SPIDER RESPONSE_FACTORY = MockResponseFactory(os.path.dirname(__file__)) class ParseFaculties(unittest.TestCase): def setUp(self): response = RESPONSE_FACTORY.create_response( 'https://noppa.tkk.fi/noppa/kurssit', 'faculty_list.html') items = list(SPIDER.parse_faculty_list(response)) self.faculties = [item for item in items if isinstance(item, FacultyItem)] self.requests = [item for item in items if isinstance(item, Request)] def test_correct_number_of_faculties_scraped(self): self.assertEqual(5, len(self.faculties)) def test_faculty_codes_scraped(self): self.assertEqual(u'eri', self.faculties[0]['code']) self.assertEqual(u'km', self.faculties[-1]['code']) def test_faculty_names_scraped(self): self.assertEqual(u'Other separate courses', self.faculties[0]['name']) self.assertEqual(u'Faculty of Chemistry and Materials Sciences', self.faculties[-1]['name']) def test_requests_to_department_list_pages_generated(self): self.assertTrue(isinstance(self.requests[0], Request)) self.assertEqual('https://noppa.tkk.fi/noppa/kurssit/eri', self.requests[0].url) self.assertTrue(self.faculties[0] is self.requests[0].meta['faculty']) self.assertTrue(isinstance(self.requests[-1], Request)) self.assertEqual('https://noppa.tkk.fi/noppa/kurssit/km', self.requests[-1].url) self.assertTrue(self.faculties[-1] is self.requests[-1].meta['faculty']) class ParseDepartments(unittest.TestCase): def setUp(self): self.faculty = FacultyItem() self.faculty['name'] = 'Faculty of Information and Natural Sciences' response = RESPONSE_FACTORY.create_response( 'https://noppa.tkk.fi/noppa/kurssit/il', 'department_list.html') response.request.meta['faculty'] = self.faculty items = list(SPIDER.parse_department_list(response)) self.departments = [item for item in items if isinstance(item, DepartmentItem)] self.requests = [item for item in items if isinstance(item, Request)] def test_correct_number_of_departments_scraped(self): self.assertEqual(10, len(self.departments)) def test_department_names_scraped(self): self.assertEqual(u'Common courses for the faculty', self.departments[0]['name']) self.assertEqual(u'Language Centre', self.departments[-1]['name']) def test_department_codes_scraped(self): self.assertEqual(u'IL-0', self.departments[0]['code']) self.assertEqual(u'T3090', self.departments[-1]['code']) def test_departments_have_faculty_set(self): self.assertEqual(id(self.faculty), id(self.departments[0]['faculty'])) def test_requests_to_course_list_pages_generated(self): self.assertTrue(isinstance(self.requests[0], Request)) self.assertEqual('https://noppa.tkk.fi/noppa/kurssit/il/il-0', self.requests[0].url) self.assertTrue( self.departments[0] is self.requests[0].meta['department']) self.assertTrue(isinstance(self.requests[-1], Request)) self.assertEqual('https://noppa.tkk.fi/noppa/kurssit/il/t3090', self.requests[-1].url) self.assertTrue( self.departments[-1] is self.requests[-1].meta['department']) class ParseCourses(unittest.TestCase): def setUp(self): self.department = DepartmentItem() self.department['name'] = \ u'Department of Computer Science and Engineering' response = RESPONSE_FACTORY.create_response( 'https://noppa.tkk.fi/noppa/kurssit/il/t3050', 'course_list.html') response.request.meta['department'] = self.department items = list(SPIDER.parse_course_list(response)) self.courses = [item for item in items if isinstance(item, CourseItem)] self.requests = [item for item in items if isinstance(item, Request)] def test_correct_number_of_courses_scraped(self): self.assertEqual(22, len(self.courses)) def test_course_codes_scraped(self): self.assertEqual(u'T-0.7050', self.courses[0]['code']) self.assertEqual(u'T-106.3101', self.courses[-1]['code']) def test_course_names_scraped(self): self.assertEqual( u'Introduction to Postgraduate Studies in Computer Science P', self.courses[0]['name']) self.assertEqual(u'Ohjelmoinnin jatkokurssi T2 (C-kieli)', self.courses[-1]['name']) def test_courses_have_department_set(self): self.assertTrue(self.department is self.courses[0]['department']) def test_crawls_to_next_course_list_page(self): request = self.requests[0] self.assertTrue('linkFwd' in request.url) self.assertTrue(request.meta['department'] is self.department) class ParseCourseOverview(unittest.TestCase): def setUp(self): self.course = CourseItem() self.course['code'] = 'T-76.4115' self.course['name'] = 'Software Development Project I' response = RESPONSE_FACTORY.create_response( 'https://noppa.tkk.fi/noppa/kurssi/t-76.4115/esite', 'course_overview.html') response.request.meta['course'] = self.course self.overview = SPIDER.parse_course_overview(response) def test_course_extent_scraped(self): self.assertEqual(u'5-8', self.overview['extent']) def test_teaching_period_scraped(self): self.assertEqual(u'I-III', self.overview['teaching_period']) def test_learning_outcomes_scraped(self): expected = ( u"You learn to apply in a practical software project computer " u"science and software engineering methods and tools that have " u"been taught on other courses. You learn to evaluate the " u"practical utility of the different methods and tools in various " u"situations. You learn to work as a software developer in a large" u" group.") self.assertEqual(expected, self.overview['learning_outcomes']) def test_course_content_scraped(self): expected = ( u"Studying software engineering tools and practices in the context" u" of a software development project done as a team for a real " u"customer. The project includes project planning, requirements " u"specification, technical design, coding, quality assurance, " u"system delivery and producing documentation related to the " u"previous activities. Course participants generally work in " u"activities related to the technical implementation of the " u"system.") self.assertEqual(expected, self.overview['content']) def test_prerequisites_scraped(self): expected = ( u"T-76.3601 (mandatory), T-76.4602 (recommended), moderate " u"programming skills") self.assertEqual(expected, self.overview['prerequisites']) def test_study_materials_scraped(self): self.assertEqual(u"Instructions for the project work.", self.overview['study_materials']) def test_overview_has_course_reference_set(self): self.assertEqual(id(self.course), id(self.overview['course'])) def suite(): tests_suite = unittest.TestSuite() tests_suite.addTest(unittest.makeSuite(ParseFaculties, 'test')) tests_suite.addTest(unittest.makeSuite(ParseDepartments, 'test')) tests_suite.addTest(unittest.makeSuite(ParseCourses, 'test')) tests_suite.addTest(unittest.makeSuite(ParseCourseOverview, 'test')) return tests_suite if __name__ == '__main__': unittest.main(defaultTest='suite') ```
[ { "content": "Produce an exact reconstruction of the code:\n```python\n# -*- coding: utf-8 -*-\n#\n# period documentation build configuration file, created by\n# sphinx-quickstart on Tue Jul 10 18:37:45 2012.\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# Note that no...
[ { "content": "Produce an exact reconstruction of the code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n#\n# period documentation build configuration file, created by\n# sphinx-quickstart on Tue Jul 10 18:37:45 2012.\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#...
```python # -*- coding: utf-8 -*- # # period documentation build configuration file, created by # sphinx-quickstart on Tue Jul 10 18:37:45 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys #import os sys.path.append("../") from build_scripts.version import get_hg_version # 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 = ['sphinx.ext.autosummary', 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.graphviz', 'sphinx.ext.inheritance_diagram', ] todo_include_todos = True intersphinx_mapping = { 'python': ('http://docs.python.org/2.7', None), } if tags.has('maintenance'): autodoc_default_flags = [] else: autodoc_default_flags = ['members', 'undoc-members', 'private-members'] autosummary_generate = True # 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'period' copyright = u'Link Care Services' # 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 = get_hg_version() # The full version, including alpha/beta/rc tags. release = version # 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 = False # 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 = 'armstrong' # 'linfiniti-sphinx-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 = ['themes'] # 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 html_use_modindex = 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 = 'period' # -- 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', 'period.tex', u'period Documentation', u'LCS', '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', 'period', u'period Documentation', [u'LCS'], 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', 'period', u'period Documentation', u'LCS', 'period', 'One line description of project.', '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": "Write out the code verbatim, preserving indentation and whitespace:\n```python\n# coding=utf-8\n# This file is part of SickRage.\n#\n# URL: https://sick-rage.github.io\n# Git: https://github.com/Sick-Rage/Sick-Rage.git\n#\n# SickRage is free software: you can redistribute it and/or modify\n# it un...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\n# coding=utf-8\n# This file is part of SickRage.\n#\n# URL: https://sick-rage.github.io\n# Git: https://github.com/Sick-Rage/Sick-Rage.git\n#\n# SickRage is free software: you can redistribute it and/or...
```python # coding=utf-8 # This file is part of SickRage. # # URL: https://sick-rage.github.io # Git: https://github.com/Sick-Rage/Sick-Rage.git # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SickRage is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. """ Test history """ from __future__ import print_function, unicode_literals import os import sys import unittest sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib'))) sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))) from sickbeard.common import Quality from sickrage.show.History import History import six class HistoryTests(unittest.TestCase): """ Test history """ def test_get_actions(self): """ Tests whether or not the different kinds of actions an episode can have are returned correctly """ test_cases = { None: [], '': [], 'wrong': [], 'downloaded': Quality.DOWNLOADED, 'Downloaded': Quality.DOWNLOADED, 'snatched': Quality.SNATCHED, 'Snatched': Quality.SNATCHED, } unicode_test_cases = { '': [], 'wrong': [], 'downloaded': Quality.DOWNLOADED, 'Downloaded': Quality.DOWNLOADED, 'snatched': Quality.SNATCHED, 'Snatched': Quality.SNATCHED, } for tests in test_cases, unicode_test_cases: for (action, result) in six.iteritems(tests): self.assertEqual(History._get_actions(action), result) # pylint: disable=protected-access def test_get_limit(self): """ Tests the static get limit method which should return the limit on the amount of elements that should be shown/returned """ test_cases = { None: 0, '': 0, '0': 0, '5': 5, '-5': 0, '1.5': 0, '-1.5': 0, 5: 5, -5: 0, 1.5: 1, -1.5: 0, } unicode_test_cases = { '': 0, '0': 0, '5': 5, '-5': 0, '1.5': 0, '-1.5': 0, } for tests in test_cases, unicode_test_cases: for (action, result) in six.iteritems(tests): self.assertEqual(History._get_limit(action), result) # pylint: disable=protected-access if __name__ == '__main__': print('=====> Testing {0}'.format(__file__)) SUITE = unittest.TestLoader().loadTestsFromTestCase(HistoryTests) unittest.TextTestRunner(verbosity=2).run(SUITE) ```
[ { "content": "Here is the script:\n```python\n\"\"\"\n COPYRIGHT (C) 2014 AFRICASTALKING LTD <www.africastalking.com> #\n \n AFRICAStALKING SMS GATEWAY CLASS IS A FREE SOFTWARE IE. CAN BE MODIFIED AND/OR REDISTRIBUTED \n UNDER THER TERMS OF GNU GENERA...
[ { "content": "Here is the script:\n<|memory_start|>```python\n\"\"\"\n COPYRIGHT (C) 2014 AFRICASTALKING LTD <www.africastalking.com> #\n \n AFRICAStALKING SMS GATEWAY CLASS IS A FREE SOFTWARE IE. CAN BE MODIFIED AND/OR REDISTRIBUTED \n UNDER THER TER...
```python """ COPYRIGHT (C) 2014 AFRICASTALKING LTD <www.africastalking.com> # AFRICAStALKING SMS GATEWAY CLASS IS A FREE SOFTWARE IE. CAN BE MODIFIED AND/OR REDISTRIBUTED UNDER THER TERMS OF GNU GENERAL PUBLIC LICENCES AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION VERSION 3 OR ANY LATER VERSION THE CLASS IS DISTRIBUTED ON 'AS IS' BASIS WITHOUT ANY WARRANTY, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import urllib import urllib2 import json class AfricasTalkingGatewayException(Exception): pass class AfricasTalkingGateway: def __init__(self, username_, apiKey_): self.username = username_ self.apiKey = apiKey_ self.SMSURLString = "https://api.africastalking.com/version1/messaging" self.VoiceURLString = "https://voice.africastalking.com" self.SubscriptionURLString = "https://api.africastalking.com/version1/subscription" self.UserDataURLString = "https://api.africastalking.com/version1/user" self.AirtimeUrlString = "https://api.africastalking.com/version1/airtime" self.headers = {'Accept': 'application/json', 'apikey': apiKey_} self.HTTP_RESPONSE_OK = 200 self.HTTP_RESPONSE_CREATED = 201 # Turn this on if you run into problems. It will print the raw HTTP # response from our server self.Debug = False # Messaging methods def sendMessage(self, to_, message_, from_=None, bulkSMSMode_=1, enqueue_=0, keyword_=None, linkId_=None, retryDurationInHours_=None): if len(to_) == 0 or len(message_) == 0: raise AfricasTalkingGatewayException( "Please provide both to_ and message_ parameters") parameters = {'username': self.username, 'to': to_, 'message': message_, 'bulkSMSMode': bulkSMSMode_} if not from_ is None: parameters["from"] = from_ if enqueue_ > 0: parameters["enqueue"] = enqueue_ if not keyword_ is None: parameters["keyword"] = keyword_ if not linkId_ is None: parameters["linkId"] = linkId_ if not retryDurationInHours_ is None: parameters["retryDurationInHours"] = retryDurationInHours_ response = self.sendRequest(self.SMSURLString, parameters) if self.responseCode == self.HTTP_RESPONSE_CREATED: decoded = json.loads(response) recipients = decoded['SMSMessageData']['Recipients'] if len(recipients) > 0: return recipients raise AfricasTalkingGatewayException( decoded['SMSMessageData']['Message']) raise AfricasTalkingGatewayException(response) def fetchMessages(self, lastReceivedId_=0): url = "%s?username=%s&lastReceivedId=%s" % ( self.SMSURLString, self.username, lastReceivedId_) response = self.sendRequest(url) if self.responseCode == self.HTTP_RESPONSE_OK: decoded = json.loads(response) return decoded['SMSMessageData']['Messages'] raise AfricasTalkingGatewayException(response) # Subscription methods def createSubscription(self, phoneNumber_, shortCode_, keyword_): if len(phoneNumber_) == 0 or len(shortCode_) == 0 or len(keyword_) == 0: raise AfricasTalkingGatewayException( "Please supply phone number, short code and keyword") url = "%s/create" % (self.SubscriptionURLString) parameters = { 'username': self.username, 'phoneNumber': phoneNumber_, 'shortCode': shortCode_, 'keyword': keyword_ } response = self.sendRequest(url, parameters) if self.responseCode == self.HTTP_RESPONSE_CREATED: decoded = json.loads(response) return decoded raise AfricasTalkingGatewayException(response) def deleteSubscription(self, phoneNumber_, shortCode_, keyword_): if len(phoneNumber_) == 0 or len(shortCode_) == 0 or len(keyword_) == 0: raise AfricasTalkingGatewayException( "Please supply phone number, short code and keyword") url = "%s/delete" % (self.SubscriptionURLString) parameters = { 'username': self.username, 'phoneNumber': phoneNumber_, 'shortCode': shortCode_, 'keyword': keyword_ } response = self.sendRequest(url, parameters) if self.responseCode == self.HTTP_RESPONSE_CREATED: decoded = json.loads(response) return decoded raise AfricasTalkingGatewayException(response) def fetchPremiumSubscriptions(self, shortCode_, keyword_, lastReceivedId_=0): if len(shortCode_) == 0 or len(keyword_) == 0: raise AfricasTalkingGatewayException( "Please supply the short code and keyword") url = "%s?username=%s&shortCode=%s&keyword=%s&lastReceivedId=%s" % ( self.SubscriptionURLString, self.username, shortCode_, keyword_, lastReceivedId_) result = self.sendRequest(url) if self.responseCode == self.HTTP_RESPONSE_OK: decoded = json.loads(result) return decoded['responses'] raise AfricasTalkingGatewayException(response) # Voice methods def call(self, from_, to_): parameters = { 'username': self.username, 'from': from_, 'to': to_ } url = "%s/call" % (self.VoiceURLString) response = self.sendRequest(url, parameters) decoded = json.loads(response) if decoded['errorMessage'] == "None": return decoded['entries'] raise AfricasTalkingGatewayException(decoded['errorMessage']) def getNumQueuedCalls(self, phoneNumber_, queueName_=None): parameters = { 'username': self.username, 'phoneNumbers': phoneNumber_ } if queueName_ is not None: parameters['queueName'] = queueName_ url = "%s/queueStatus" % (self.VoiceURLString) response = self.sendRequest(url, parameters) decoded = json.loads(response) if decoded['errorMessage'] == "None": return decoded['entries'] raise AfricasTalkingGatewayException(decoded['ErrorMessage']) def uploadMediaFile(self, urlString_): parameters = { 'username': self.username, 'url': urlString_ } url = "%s/mediaUpload" % (self.VoiceURLString) response = self.sendRequest(url, parameters) decoded = json.loads(response) if decoded['errorMessage'] != "None": raise AfricasTalkingGatewayException(decoded['errorMessage']) # Airtime method def sendAirtime(self, recipients_): parameters = { 'username': self.username, 'recipients': json.dumps(recipients_) } SendAirtimeUrlString = "%s/send" % (self.AirtimeUrlString) response = self.sendRequest(SendAirtimeUrlString, parameters) decoded = json.loads(response) responses = decoded['responses'] if self.responseCode == self.HTTP_RESPONSE_CREATED: if len(responses) > 0: return responses raise AfricasTalkingGatewayException(decoded["errorMessage"]) raise AfricasTalkingGatewayException(response) # Userdata method def getUserData(self): url = "%s?username=%s" % (self.UserDataURLString, self.username) result = self.sendRequest(url) if self.responseCode == self.HTTP_RESPONSE_OK: decoded = json.loads(result) return decoded['UserData'] raise AfricasTalkingGatewayException(response) # HTTP access method def sendRequest(self, urlString, data_=None): try: if data_ is not None: data = urllib.urlencode(data_) request = urllib2.Request( urlString, data, headers=self.headers) else: request = urllib2.Request(urlString, headers=self.headers) response = urllib2.urlopen(request) except Exception as e: raise AfricasTalkingGatewayException(str(e)) else: self.responseCode = response.getcode() response = response.read() if self.Debug: print response return response ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n''' ---------------------------------------------------------------------------------------------------------------- '''\n''' These below are the membership groups and their membership customized replies. Edit this area to expand the b...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n''' ---------------------------------------------------------------------------------------------------------------- '''\n''' These below are the membership groups and their membership customized replies. Edit this area...
```python ''' ---------------------------------------------------------------------------------------------------------------- ''' ''' These below are the membership groups and their membership customized replies. Edit this area to expand the bot. ''' ''' ---------------------------------------------------------------------------------------------------------------- ''' SelenaGomez = ("selena", "gomez") #Will trigger if these two words BOTH are in the title. SelenaGomezReply = """ [Instagram](https://instagram.com/SelenaGomez/)\n [Twitter](https://twitter.com/SelenaGomez)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AlexisRen = ("alexis", "ren") #Every ("firstname", "nickname", "lastname") in the ()'s below must be lower case. AlexisRenReply = """ [Instagram](https://instagram.com/alexisren)\n [Twitter](https://twitter.com/alexisreng)\n [Tumblr](http://alexisreneg.tumblr.com)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ TaylorSwift = ("taylor", "swift") TaylorSwiftReply = """ [Instagram](https://instagram.com/taylorswift)\n [Twitter](https://twitter.com/Taylorswift13)\n [Facebook](https://www.facebook.com/TaylorSwift)\n [Website](http://www.taylorswift.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ McKaylaMaroney = ("mckayla", "maroney") McKaylaMaroneyReply = """ [Instagram](https://instagram.com/McKaylaMaroney)\n [Twitter](https://twitter.com/mckaylamaroney)\n [YouTube Channel](https://www.youtube.com/channel/UC0HJyx19LKRmuHxfiqp9E8w)\n [Keek](https://www.keek.com/profile/McKaylaMaroney)\n [Vine](https://vine.co/u/920773070459904000)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ SarahHyland = ("sarah", "hyland") SarahHylandReply = """ [Instagram](https://instagram.com/therealsarahhyland)\n [Twitter](https://twitter.com/sarah_hyland)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ ArielWinter = ("ariel", "winter") ArielWinterReply = """ [Instagram](https://instagram.com/arielwinter)\n [Twitter](https://twitter.com/arielwinter1)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KarlieKloss = ("karlie", "kloss") KarlieKlossReply = """ [Instagram](https://instagram.com/karliekloss/)\n [Twitter](https://twitter.com/karliekloss/)\n [YouTube](https://www.youtube.com/c/karliekloss)\n [Facebook](https://www.facebook.com/KarlieKloss)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KendallJenner = ("kendall", "jenner") KendallJennerReply = """ [Instagram](https://instagram.com/kendalljenner)\n [Twitter](https://twitter.com/kendalljenner)\n [Kendall + Kylie^TM](https://instagram.com/kendallandkylie/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KylieJenner = ("kylie", "jenner") KylieJennerReply = """ Snapchat: KylizzleMyNizzl [Instagram](https://instagram.com/kyliejenner)\n [Twitter](https://twitter.com/kyliejenner)\n [Kendall + Kylie^TM](https://instagram.com/kendallandkylie/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ ChloeBennet = ("chloe", "bennet") ChloeBennetReply = """ [Instagram](https://instagram.com/chloebennet4/)\n [Twitter](https://twitter.com/ChloeBennet4)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ HayleyAtwell = ("hayley", "atwell") HayleyAtwellReply = """ [Instagram](https://instagram.com/realhayleyatwell)\n [Twitter](https://twitter.com/HayleyAtwell)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AnnaKendrick = ("anna", "kendrick") AnnaKendrickReply = """ [Instagram](https://instagram.com/annakendrick47/)\n [Twitter](https://twitter.com/annakendrick47)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ DaniThorne = ("dani", "thorne") DaniThorneReply = """ [Instagram](https://instagram.com/dani_thorne/)\n [Twitter](https://twitter.com/Dani_Thorne)\n [Tumblr](http://danithornesworld.com/)\n [Youtube](https://www.youtube.com/user/danithornesworld)\n [IMDb](http://www.imdb.com/name/nm2374574/)\n [Facebook](https://www.facebook.com/official.danimthorne)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ BellaThorne = ("bella", "thorne") BellaThorneReply = """ [Instagram](https://instagram.com/bellathorne)\n [Twitter](https://twitter.com/BELLATHORNE)\n [IMDb](http://www.imdb.com/name/nm2254074/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ EmiliaClarke = ("emilia", "clarke") EmiliaClarkeReply = """ [Instagram](https://instagram.com/emilia_clarke/)\n [Twitter](https://twitter.com/Emilia_Clarke)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ JessicaBiel = ("jessica", "biel") JessicaBielReply = """ [Instagram](https://instagram.com/jessicabiel)\n [Twitter](https://twitter.com/JessicaBiel)\n [WhoSay](http://www.whosay.com/jessicabiel)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AshleyBenson = ("ashley", "benson") AshleyBensonReply = """ [Instagram](https://instagram.com/itsashbenzo)\n [Twitter](https://twitter.com/AshBenzo)\n [Website](http://ashleybenson.net/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MelissaBenoist = ("melissa", "benoist") MelissaBenoistReply = """ [Instagram](https://instagram.com/melissabenoist/)\n [Twitter](https://twitter.com/MelissaBenoist)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MilanaVayntrub = ("milana", "vayntrub") MilanaVayntrubReply = """ [Instagram](https://instagram.com/mintmilana)\n [Twitter](https://twitter.com/MintMilana)\n [YouTube: Live Prude Girls](https://www.youtube.com/user/LivePrudeGirls)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ HeidiKlum = ("heidi", "klum") HeidiKlumReply = """ [Instagram](https://instagram.com/HeidiKlum)\n [Twitter](https://twitter.com/heidiklum/)\n [Website](http://www.heidiklum.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ StanaKatic = ("stana", "katic") StanaKaticReply = """ [Instagram](https://instagram.com/drstanakatic)\n [Twitter](https://twitter.com/stana_katic)\n [Website](http://www.stanakatic.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ BlakeLively = ("blake", "lively") BlakeLivelyReply = """ [Instagram](https://instagram.com/blakelively/)\n [Twitter](https://twitter.com/blakelively)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MelissaDebling = ("melissa", "debling") MelissaDeblingReply = """ [Instagram](https://instagram.com/melissadebling/)\n [Twitter](https://www.twitter.com/MelissaDebling)\n [Website](http://melissad.co.uk/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ SarahShahi = ("sarah", "shahi") SarahShahiReply = """ [Instagram](https://instagram.com/theonlysarahshahi/)\n [Twitter](https://twitter.com/onlysarahshahi)\n [WhoSay](http://www.whosay.com/sarahshahi)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ IrinaShayk = ("irina", "shayk") IrinaShaykReply = """ [Instagram](https://github.com/DrewsephA/Celeb_Username_Bot)\n [Twitter](https://twitter.com/theirishayk/)\n [Facebook](https://www.facebook.com/IrinaShayk)\n [Website](http://irinashaykofficial.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MarinaNery = ("marina", "nery") MarinaNeryReply = """ [Instagram](https://instagram.com/marinadnery/)\n [Twitter](https://twitter.com/marinadnery)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ SandraRadav = ("sandra", "radav") SandraRadavReply = """ [Instagram](https://instagram.com/sandraradav)\n [Twitter](https://twitter.com/SandraRadav)\n [YouTube channel](https://www.youtube.com/user/TheLovezumba)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ VanessaHudgens = ("vanessa", "hudgens") VanessaHudgensReply = """ [Instagram](https://instagram.com/vanessahudgens)\n [Twitter](https://twitter.com/vanessahudgens)\n [Tumblr](http://vanessahudgens.tumblr.com/)\n [YouTube channel](https://www.youtube.com/vanessahudgens)\n [Facebook](https://www.facebook.com/VanessaHudgens)\n [Pinterest](https://www.pinterest.com/vanessahudgens/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KellyBrook = ("kelly", "brook") KellyBrookReply = """ [Instagram](https://instagram.com/iamkb)\n [Twitter](https://twitter.com/IAMKELLYBROOK)\n [YouTube channel](https://www.youtube.com/user/kellybrookofficial)\n [Facebook](https://www.facebook.com/kellybrookofficial)\n [Website](http://kellybrook.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MandyMoore = ("mandy", "moore") MandyMooreReply = """ [Instagram](https://instagram.com/mandymooremm/)\n [Twitter](https://twitter.com/TheMandyMoore)\n [Facebook](https://www.facebook.com/mandymooreofficial)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AnnaFaith = ("anna", "faith") AnnaFaithReply = """ Snapchat: AnnaFaithBae \n [Instagram](https://instagram.com/annafaithxoxo/)\n [Twitter](https://twitter.com/TheAnnaFaith)\n [YouTube channel](https://www.youtube.com/channel/UCTcBaZEehmQeydOl1LTM_5Q/)\n ^Frost ^Sisters ^[instagram](https://instagram.com/frostsisters/) ^& ^[twitter](https://twitter.com/frostsisters)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ LexieGrace = ("lexie", "grace") LexieGraceReply = """ [Instagram](https://instagram.com/Lexiegracelove/)\n [Twitter](https://twitter.com/lexiegracelove)\n ^Frost ^Sisters ^[instagram](https://instagram.com/frostsisters/) ^& ^[twitter](https://twitter.com/frostsisters)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ FrostSisters = ("frost", "sisters") FrostSistersReply = """ [Instagram](https://instagram.com/frostsisters/)\n [Twitter](https://twitter.com/frostsisters)\n \n-\n **Anna Faith** \n Snapchat: AnnaFaithBae \n [Instagram](https://instagram.com/annafaithxoxo/)\n [Twitter](https://twitter.com/TheAnnaFaith)\n [YouTube channel](https://www.youtube.com/channel/UCTcBaZEehmQeydOl1LTM_5Q/)\n \n-\n **Lexie Grace**\n [Instagram](https://instagram.com/Lexiegracelove/)\n [Twitter](https://twitter.com/lexiegracelove)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ TaylorHannum = ("taylor", "hannum") TaylorHannumReply = """ [Instagram](https://instagram.com/taylorhannum_)\n [Twitter](https://twitter.com/TaylorHannum)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ CaraDelevingne = ("cara", "delevingne") CaraDelevingneReply = """ [Instagram](https://instagram.com/caradelevingne/)\n [Twitter](https://twitter.com/Caradelevingne)\n [Tumblr](http://iamcaradelevingne.tumblr.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ LenaGercke = ("lena", "gercke") LenaGerckeReply = """ [Instagram](https://instagram.com/lenagercke/)\n [Facebook](https://www.facebook.com/pages/Lena-Gercke/439297919435120)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ JenniferMorrison = ("jen", "jennifer", "jenny", "morrison") JenniferMorrisonReply = """ [Instagram](https://instagram.com/jenmorrisonlive/)\n [Twitter](https://twitter.com/jenmorrisonlive/)\n [Facebook](https://www.facebook.com/JenniferMorrisonOfficial)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MargotRobbie = ("margot", "robbie") MargotRobbieReply = """ [Instagram](https://instagram.com/margotrobbieofficial)\n [Twitter](https://twitter.com/MargotRobbie)\n [Website](http://www.margotrobbie.com.au/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AlyssaArce = ("alyssa", "arce") AlyssaArceReply = """ [Instagram](https://instagram.com/miss_alyssaarce/)\n [Twitter](https://twitter.com/missalyssaarce)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MirandaKerr = ("miranda", "kerr") MirandaKerrReply = """ [Instagram](https://instagram.com/mirandakerr/)\n [Twitter](https://twitter.com/mirandakerr)\n [Facebook](https://www.facebook.com/MirandaKerr)\n [Website](http://www.mirandakerr.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KarlieKloss = ("karlie", "kloss") KarlieKlossReply = """ [Instagram](https://instagram.com/karliekloss/)\n [Twitter](https://twitter.com/karliekloss/)\n [YouTube channel: Klossy](https://www.youtube.com/c/karliekloss)\n [Facebook](https://www.facebook.com/KarlieKloss)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ ElsaHosk = ("elsa", "hosk") ElsaHoskReply = """ [Instagram](https://instagram.com/hoskelsa/)\n [Twitter](https://twitter.com/elsahosk)\n [Facebook](https://www.facebook.com/hoskelsa)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ CandiceSwanepoel = ("candice", "swanepoel") CandiceSwanepoelReply = """ [Instagram](https://instagram.com/angelcandices)\n [Twitter](https://twitter.com/angelcandice/)\n [Facebook](https://www.facebook.com/angelcandices)\n [Website](http://www.candiceswanepoel.com/home.php)\n [Pinterest](https://www.pinterest.com/angelcandice/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MeganFox = ("megan", "fox") MeganFoxReply = """ [Instagram](https://instagram.com/the_native_tiger/)\n [Twitter](https://twitter.com/meganfox)\n [Facebook](https://www.facebook.com/MeganFox)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ IzzyMarshall = ("izzy", "marshall") IzzyMarshallReply = """ [Instagram](https://instagram.com/_izzymarshall/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ ArianaGrande = ("ariana", "grande") ArianaGrandeReply = """ Snapchat: moonlightbae [Instagram](https://instagram.com/arianagrande)\n [Twitter](https://twitter.com/arianagrande)\n [YouTube channel(personal)](https://www.youtube.com/user/osnapitzari)\n [Facebook](https://www.facebook.com/arianagrande)\n [YouTubeVEVO](https://www.youtube.com/user/ArianaGrandeVevo)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ NathalieEmmanuel = ("nathalie", "emmanuel") NathalieEmmanuelReply = """ [Instagram](https://instagram.com/nathalieemmanuel/)\n [Twitter](https://twitter.com/missnemmanuel)\n [Tumblr tag (nsfw)](https://www.tumblr.com/search/nathalie+emmanuel)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ HannahFerguson = ("hannah", "ferguson") HannahFergusonReply = """ [Instagram](https://instagram.com/hannahfergusonofficial/)\n [Twitter](https://twitter.com/thehannahferg)\n [Facebook](https://www.facebook.com/TheHannahFerg)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KateHudson = ("kate", "hudson") KateHudsonReply = """ [Instagram](https://instagram.com/katehudson/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ NinaDobrev = ("nina", "dobrev") NinaDobrevReply = """ [Instagram](https://instagram.com/ninadobrev)\n [Twitter](https://twitter.com/ninadobrev/)\n [Tumblr](https://ninadobrev.tumblr.com/)\n [Facebook](https://www.facebook.com/NinaDobrev)\n [Website/whosay](http://www.ninadobrev.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ DaphneJoy = ("daphne", "joy") DaphneJoyReply = """ Snapchat: DaphneJoyLove \n [Instagram](https://instagram.com/daphnejoy/)\n [Twitter](https://twitter.com/DaphneJoy)\n [Website](http://www.daphnejoy.com/site/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ EmilyRudd = ("emily", "rudd") EmilyRuddReply = """ Snapchat: emilysteaparty \n [Instagram](https://instagram.com/emilysteaparty/)\n [Twitter](https://www.twitter.com/emilysteaparty)\n [Tumblr](https://emilysteaparty.tumblr.com)\n [YouTube channel](https://www.youtube.com/user/emilysteaparty)\n [Facebook](https://www.facebook.com/emilyruddofficial)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ OliviaCulpo = ("olivia", "culpo") OliviaCulpoReply = """ [Instagram](https://instagram.com/oliviaculpo)\n [Twitter](https://twitter.com/oliviaculpo)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ OdetteAnnable = ("odette", "annable") OdetteAnnableReply = """ [Instagram](https://instagram.com/odetteannable)\n [Twitter](https://twitter.com/OdetteAnnable)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ OlgaKurylenko = ("olga", "kurylenko") OlgaKurylenkoReply = """ [Instagram](https://instagram.com/olgakurylenkoofficial/)\n [Twitter](https://twitter.com/OlyaKurylenko)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ BrendaSong = ("brenda", "song") BrendaSongReply = """ /r/BrendaSong \n [Instagram](https://instagram.com/brendasong)\n [Twitter](https://twitter.com/BrendaSong)\n [Facebook](https://www.facebook.com/BrendaSong)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ CarolSeleme = ("carol", "seleme") CarolSelemeReply = """ [Instagram](https://instagram.com/cadeque/)\n [Tumblr](http://moorslorac.tumblr.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AlessandraAmbrosio = ("alessandra", "ambrosio") AlessandraAmbrosioReply = """ [Instagram](https://instagram.com/alessandraambrosio)\n [Twitter](https://twitter.com/angelalessandra)\n [Facebook](https://www.facebook.com/Alessandra)\n [Website](http://www.alessandraambrosio.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AlexSchmidt = ("alex", "schmidt") AlexSchmidtReply = """ [Instagram](https://instagram.com/alxxschmidt/)\n [Tumblr](http://alxxschmidt.tumblr.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ RachelHilbert = ("rachel", "hilbert") RachelHilbertReply = """ Snapchat: rachelhilbert \n [Instagram](https://instagram.com/rachelhilbert/)\n [Twitter](https://twitter.com/rachel_hil)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ DevonWindsor = ("devon", "windsor") DevonWindsorReply = """ [Instagram](https://instagram.com/devwindsor/)\n [Twitter](https://twitter.com/devwindsor/)\n [Facebook](https://www.facebook.com/devwindsor)\n [Website](http://www.devonwindsor.com/home/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ TaylorMarieHill = ("taylor", "marie", "hill") TaylorMarieHillReply = """ Snapchat: taylor_hill \n [Instagram](https://instagram.com/taylor_hill/)\n [Twitter](https://twitter.com/TaylorMarieHill)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KateMara = ("kate", "mara") KateMaraReply = """ [Twitter](https://twitter.com/katemara)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ ChloeGraceMortz = ("chloe", "grace", "mortz") ChloeGraceMortzReply = """ [Instagram](https://instagram.com/ChloeGMoretz)\n [Twitter](https://twitter.com/chloegmoretz)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ CamilleRowe = ("camille", "camilla", "rowe") CamilleRoweReply = """ [Instagram](https://instagram.com/fingermonkey/)\n [Twitter](https://twitter.com/CamilleRowe)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ PeytonList = ("peyton", "list") PeytonListReply = """ [Instagram](https://instagram.com/peytonlist)\n [Twitter](https://twitter.com/peytonlist)\n [Facebook](https://www.facebook.com/peyton.list)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ SammiHanratty = ("sammi", "hanratty") SammiHanrattyReply = """ Snapchat: SammiHanratty1 [Instagram](https://instagram.com/sammihanratty143/)\n [Twitter](https://twitter.com/SammiHanratty1)\n [Facebook](https://www.facebook.com/TheOfficialSammiHanratty)\n [YouTube channel](https://www.youtube.com/channel/UCJkIBX-nVKat9C-1PU7FiZg)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MargotRobbie = ("margot", "robbie") MargotRobbieReply = """ [Instagram](https://instagram.com/margotrobbie/)\n [Twitter](https://twitter.com/MargotRobbie)\n [Whosay](http://www.whosay.com/margotrobbie)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ LaurenCohan = ("lauren", "cohan") LaurenCohanReply = """ [Instagram](https://instagram.com/LaurenCohan)\n [Twitter](https://twitter.com/LaurenCohan)\n [Website](http://laurencohan.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ CamilaCabello = ("camila", "cabello") CamilaCabelloReply = """ [Instagram](https://instagram.com/camila_cabello/)\n [Twitter](https://twitter.com/CamilaCabello97)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ YvonneStrahovski = ("yvonne", "strahovski") YvonneStrahovskiReply = """ [Instagram](https://instagram.com/therealyvonnestrahovski/)\n [Twitter](https://twitter.com/Y_Strahovski/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ OliviaMunn = ("olivia", "munn") OliviaMunnReply = """ [Instagram](https://instagram.com/oliviamunn/)\n [Twitter](https://twitter.com/oliviamunn)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KatharineMcphee - ("katharine", "mcphee") KatharineMcpheeReply = """ [Instagram](https://instagram.com/katharinemcphee/)\n [Twitter](https://twitter.com/KatharineMcPhee)\n [Website](http://www.katharinemcphee.net/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ EmmaRoberts = ("emma", "roberts") EmmaRobertsReply = """ [Instagram](https://instagram.com/emmaroberts/)\n [Twitter](https://twitter.com/robertsemma)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ SalmaHayek = ("salma", "hayek") SalmaHayekReply = """ [Instagram](https://instagram.com/salmahayek/)\n [Twitter](https://twitter.com/salmahayek)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KatyaEliseHenry = ("katya", "elise", "henry") KatyaEliseHenryReply = """ Snapchat: katyahenry \n [Instagram](https://instagram.com/katyaelisehenry/)\n [Twitter](https://twitter.com/katyaelisehenry)\n [Facebook](https://www.facebook.com/katyaehenry)\n [Website](http://www.katyaelisehenry.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ ElizabethGillies = ("elizabeth", "liz", "gillies") ElizabethGilliesReply = """ /r/lizgillies \n [Twitter](https://twitter.com/lizgillies)\n [Facebook](https://www.facebook.com/ElizabethGilliesOfficial/timeline)\n [YouTube channel](https://www.youtube.com/user/LizGilliesOfficial)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ MichelleJenneke = ("michelle", "jenneke") MichelleJennekeReply = """ [Instagram](https://instagram.com/mjenneke93/)\n [Twitter](https://twitter.com/MJenneke93)\n [YouTube channel](https://www.youtube.com/channel/UCOiLtIb9UcXKkulRfMQem1g)\n [Website](http://www.michellejenneke.com.au/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ GwenCox = ("gwen", "cox") GwenCoxReply = """ Snapchat: gw3nnyy [Instagram](https://instagram.com/hologrvphic/)\n [Tumblr](http://hologrvphicx.tumblr.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ DakotaJohnson = ("dakota", "johnson") DakotaJohnsonReply = """ [Instagram](https://instagram.com/dakotajohnson/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ CamillaLuddington = ("camilla", "luddington") CamillaLuddingtonReply = """ [Instagram](https://instagram.com/officialcamillaluddington/)\n [Twitter](https://twitter.com/camilluddington)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ JennaHopkins = ("jenna", "hopkins") JennaHopkinsReply = """ [Instagram](https://instagram.com/jhopkins_/)\n [Twitter](https://twitter.com/_jennahop)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ PriscillaQuintana = ("priscilla", "quintana") PriscillaQuintanaReply = """ [Instagram](https://instagram.com/priscilla_quintana/)\n [Twitter](https://twitter.com/_paq)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ RachaelFinch = ("rachael", "finch") RachaelFinchReply = """ [Instagram](https://instagram.com/rachael_finch/)\n [Twitter](https://twitter.com/RachaelFinch)\n [YouTube channel](https://www.youtube.com/user/rachaelfinch)\n [Facebook](https://www.facebook.com/rachaelfinchfanpage)\n [Website](http://rachaelfinch.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ RachaelTaylor = ("rachael", "taylor") RachaelTaylorReply = """ [Instagram](https://instagram.com/rachaelmaytaylor/)\n [Twitter](https://twitter.com/_Rachael_Taylor)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ ElisabettaCanalis = ("elisabetta", "canalis") ElisabettaCanalisReply = """ [Instagram](https://instagram.com/littlecrumb_)\n [Twitter](https://twitter.com/justelisabetta)\n [Website](http://www.elisabettacanalis.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ SolveigMorkHansen = ("sloveig", "mork", "hansen") SolveigMorkHansenReply = """ [Instagram](https://instagram.com/notsolveig)\n [Twitter](https://twitter.com/mhsolveig)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ AlyssaMilano = ("alyssa", "milano") AlyssaMilanoReply = """ [Instagram](https://instagram.com/milano_Alyssa/)\n [Twitter: personal](https://twitter.com/Alyssa_Milano)\n [Facebook](https://www.facebook.com/AlyssaMilano)\n [Twitter: AlyssaDotCom](https://twitter.com/AlyssaDotCom)\n [Twitter: TouchByAM](https://twitter.com/TouchByAM)\n [Website](http://alyssa.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ FrancoiseBoufhal = ("francoise", "boufhal") FrancoiseBoufhalReply = """ [Instagram](https://instagram.com/francoisebouf/)\n [Twitter](https://twitter.com/francoisebouf)\n [Facebook](https://www.facebook.com/officialfrancoise)\n [YouTube channel](https://www.youtube.com/user/officialfrancoise)\n [Website](http://www.officialfrancoise.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KimberleyGarner = ("kimberley", "garner") KimberleyGarnerReply = """ [Instagram](https://instagram.com/kimberleylondon)\n [Twitter](https://twitter.com/KimberleyLondon)\n [Website](http://www.kimberleylondon.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ CarlyCraig = ("carly", "craig") CarlyCraigReply = """ [Instagram](https://instagram.com/carlyccraig/)\n [Twitter](https://twitter.com/carly_craig)\n [Facebook](https://www.facebook.com/CarlyCraigFB)\n [YouTube channel](https://www.youtube.com/user/carlycraig)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KarolinaKurkova = ("karolina", "kurkova") KarolinaKurkovaReply = """ [Instagram](https://instagram.com/karolinakurkova)\n [Twitter](https://twitter.com/KarolinaKurkova)\n [Facebook](https://www.facebook.com/KarolinaKurkova)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ LindsayHeyser = ("lindsay", "heyser") LindsayHeyserReply = """ [Instagram](https://instagram.com/lheyser/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ RachelHurdWood = ("rachel", "hurdwood") RachelHurdWoodReply = """ [Instagram](https://instagram.com/1rachelhurdwood/)\n [Twitter](https://twitter.com/rachelhurdwood)\n [Facebook](https://www.facebook.com/rachelhurdwood/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ TiannaGregory = ("tianna", "gregory") TiannaGregoryReply = """ Snapchat: TiannaGregory [Instagram](https://instagram.com/_tiannag/)\n [Twitter](https://twitter.com/_TiannaG)\n [Tumblr](http://tnutty.tumblr.com/)\n [Facebook](https://www.facebook.com/pages/Tianna-Gregory/585670294906217)\n [Website](http://www.tiannagregory.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ PaigeSpiranac = ("paige", "spiranac") PaigeSpiranacReply = """ [Instagram](https://instagram.com/_paige.renee/)\n [Twitter](https://twitter.com/PaigeSpiranac)\n [Facebook](https://www.facebook.com/paigereneespiranac)\n [Website](http://paigespiranac.com/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ GeorgiaMayJagger = ("georgia", "may", "jagger") GeorgiaMayJaggerReply = """ [Instagram](https://instagram.com/georgiamayjagger/)\n [Twitter](https://twitter.com/GeorgiaMJagger)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ BrookeBurke = ("brooke", "burke") BrookeBurkeReply = """ [Instagram](https://instagram.com/brookeburke/)\n [Twitter](https://twitter.com/BrookeBurke)\n [Facebook](https://www.facebook.com/pages/Brooke-Burke/261925180496418)\n [WhoSay](http://www.whosay.com/brookeburke)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ SydneyFullerMarr = ("sydney", "fuller", "marr") SydneyFullerMarrReply = """ [Instagram](https://instagram.com/misssydneyfuller/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ -start- JennaJenovich = ("jenna", "jenovich") JennaJenovichReply = """ Snapchat: jennajenovich [Instagram](https://instagram.com/jennajenovich/)\n [Twitter](https://twitter.com/JennaJenovich)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ OliviaJordan = ("olivia", "jordan") OliviaJordanReply = """ [Instagram](https://instagram.com/theoliviajordan/)\n [Twitter - personal](https://twitter.com/theOliviaJordan)\n [Twitter - @MissUSA](https://twitter.com/missusa)\n [Facebook](https://www.facebook.com/theoliviajordan)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ HannahPolites = ("hannah", "polites") HannahPolitesReply = """ [Instagram](https://instagram.com/hannahpolites)\n [Facebook](https://www.facebook.com/hannah.polites)\n [Website](http://hannahpolites.com.au/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ DeniseMilani = ("denise", "milani") DeniseMilaniReply = """ [Instagram](https://instagram.com/denisemilaniofficial/)\n [Facebook](https://instagram.com/denisemilaniofficial/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ KatherineTimokhina = ("catherine", "katherine", "timokhina") KatherineTimokhinaReply = """ [Instagram](https://instagram.com/katrintim93/)\n \n-\n ^| ^v0.1 ^| ^I ^am ^a ^bot, ^accuracy ^not ^guaranteed ^| ^/r/Celeb_Username_Bot ^for ^questions, ^help, ^and ^bug ^reporting. ^| ^[Source](https://github.com/DrewsephA/Celeb_Username_Bot) ^|\n """ celebs = ({SelenaGomez: SelenaGomezReply}, {AlexisRen: AlexisRenReply}, {TaylorSwift: TaylorSwiftReply}, {McKaylaMaroney: McKaylaMaroneyReply},\ {SarahHyland: SarahHylandReply}, {ArielWinter: ArielWinterReply}, {KarlieKloss: KarlieKlossReply}, {KendallJenner: KendallJennerReply},\ {KylieJenner: KylieJennerReply}, {ChloeBennet: ChloeBennetReply}, {HayleyAtwell: HayleyAtwellReply}, {AnnaKendrick: AnnaKendrickReply},\ {DaniThorne: DaniThorneReply}, {BellaThorne: BellaThorneReply}, {EmiliaClarke: EmiliaClarkeReply}, {JessicaBiel: JessicaBielReply},\ {AshleyBenson: AshleyBensonReply}, {MelissaBenoist: MelissaBenoistReply}, {MilanaVayntrub: MilanaVayntrubReply}, {HeidiKlum: HeidiKlumReply},\ {StanaKatic: StanaKaticReply}, {BlakeLively: BlakeLivelyReply}, {MelissaDebling: MelissaDeblingReply}, {SarahShahi: SarahShahiReply},\ {IrinaShayk: IrinaShaykReply}, {MarinaNery: MarinaNeryReply}, {SandraRadav: SandraRadavReply}, {VanessaHudgens: VanessaHudgensReply},\ {KellyBrook: KellyBrookReply}, {MandyMoore: MandyMooreReply}, {AnnaFaith: AnnaFaithReply}, {LexieGrace: LexieGraceReply},\ {FrostSisters: FrostSistersReply}, {TaylorHannum: TaylorHannumReply}, {CaraDelevingne: CaraDelevingneReply}, {LenaGercke: LenaGerckeReply},\ {JenniferMorrison: JenniferMorrisonReply}, {MargotRobbie: MargotRobbieReply}, {AlyssaArce: AlyssaArceReply}, {MirandaKerr: MirandaKerrReply},\ {KarlieKloss: KarlieKlossReply}, {ElsaHosk: ElsaHoskReply}, {CandiceSwanepoel: CandiceSwanepoelReply}, {MeganFox: MeganFoxReply},\ {IzzyMarshall: IzzyMarshallReply}, {ArianaGrande: ArianaGrandeReply}, {NathalieEmmanuel: NathalieEmmanuelReply}, {HannahFerguson: HannahFergusonReply}\ {KateHudson: KateHudsonReply}, {NinaDobrev: NinaDobrevReply}, {DaphneJoy: DaphneJoyReply}, {EmilyRudd: EmilyRuddReply}, {OliviaCulpo: OliviaCulpoReply},\ {OdetteAnnable: OdetteAnnableReply}, {OlgaKurylenko: OlgaKurylenkoReply}, {CarolSeleme: CarolSelemeReply}, {AlessandraAmbrosio: AlessandraAmbrosioReply},\ {AlexSchmidt: AlexSchmidtReply}, {RachelHilbert: RachelHilbertReply}, {DevonWindsor: DevonWindsorReply}, {TaylorMarieHill: TaylorMarieHillReply},\ {KateMara: KateMaraReply}, {ChloeGraceMortz: ChloeGraceMortzReply}, {CamilleRowe: CamilleRoweReply}, {SammiHanratty: SammiHanrattyReply},\ {MargotRobbie: MargotRobbieReply}, {LaurenCohan: LaurenCohanReply}, {CamilaCabello: CamilaCabelloReply}, {YvonneStrahovski: YvonneStrahovskiReply},\ {OliviaMunn: OliviaMunnReply}, {KatharineMcphee: KatharineMcpheeReply}, {EmmaRoberts: EmmaRobertsReply}, {SalmaHayek: SalmaHayekReply},\ {KatyaEliseHenry: KatyaEliseHenryReply}, {ElizabethGillies: ElizabethGilliesReply}, {MichelleJenneke: MichelleJennekeReply}, {GwenCox: GwenCoxReply},\ {DakotaJohnson: DakotaJohnsonReply}, {CamillaLuddington: CamillaLuddingtonReply}, {JennaHopkins: JennaHopkinsReply}, {PriscillaQuintana: PriscillaQuintanaReply},\ {RachaelFinch: RachaelFinchReply}, {RachaelTaylor: RachaelTaylorReply}, {ElisabettaCanalis: ElisabettaCanalisReply}, {SolveigMorkHansen: SolveigMorkHansenReply}\ {AlyssaMilano: AlyssaMilanoReply}, {FrancoiseBoufhal: FrancoiseBoufhalReply}, {KimberleyGarner: KimberleyGarnerReply}, {CarlyCraig: CarlyCraigReply},\ {KarolinaKurkova: KarolinaKurkovaReply}, {LindsayHeyser: LindsayHeyserReply}, {RachelHurdWood: RachelHurdWoodReply}, {TiannaGregory: TiannaGregoryReply},\ {PaigeSpiranac: PaigeSpiranacReply}, {GeorgiaMayJagger: GeorgiaMayJaggerReply}, {BrookeBurke: BrookeBurkeReply}, {SydneyFullerMarr: SydneyFullerMarrReply},\ { {JennaJenovich: JennaJenovichReply}, {OliviaJordan: OliviaJordanReply}, {HannahPolites: HannahPolitesReply}, {DeniseMilani: DeniseMilaniReply}, {KatherineTimokhina: KatherineTimokhinaReply}, #In this string put all+your+target_subreddits: subreddits_string = "celeb_username_bot+Celeb_Bot_Test+DrewsephA" #When the script is ready delete the above two lines and remove the "#" from the line below #subreddits_string = "Celebs+CelebGfys+celebgifs+CelebsWallpaper+goddesses+VSModels+vsangels+Models+PrettyGirls+GirlswithGlasses+GirlswithGreenEyes+GirlswithWetHair+VictoriaSecret+VictoriasSecret+VSfans+WtSSTaDaMiT+starlets+girlsinyogapants+girlsinyogashorts+BeautifulFemales" ''' ---------------------------------------------------------------------------------------------------------------- ''' ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport datetime\ni...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nim...
```python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import datetime import re from elasticsearch_dsl import Search, A, F, Q from elasticsearch.exceptions import NotFoundError from socorro.external import ( BadArgumentError, ) from socorro.external.es.super_search_fields import SuperSearchFields from socorro.lib import datetimeutil from socorro.lib.search_common import SearchBase BAD_INDEX_REGEX = re.compile('\[\[(.*)\] missing\]') class SuperSearch(SearchBase): def __init__(self, *args, **kwargs): self.config = kwargs.get('config') self.es_context = self.config.elasticsearch.elasticsearch_class( self.config.elasticsearch ) self.all_fields = SuperSearchFields(config=self.config).get_fields() # Create a map to associate a field's name in the database to its # exposed name (in the results and facets). self.database_name_to_field_name_map = dict( (x['in_database_name'], x['name']) for x in self.all_fields.values() ) kwargs.update(fields=self.all_fields) super(SuperSearch, self).__init__( *args, **kwargs ) def get_connection(self): with self.es_context() as conn: return conn def generate_list_of_indices(self, from_date, to_date, es_index=None): """Return the list of indices to query to access all the crash reports that were processed between from_date and to_date. The naming pattern for indices in elasticsearch is configurable, it is possible to have an index per day, per week, per month... Parameters: * from_date datetime object * to_date datetime object """ if es_index is None: es_index = self.config.elasticsearch_index indices = [] current_date = from_date while current_date <= to_date: index = current_date.strftime(es_index) # Make sure no index is twice in the list # (for weekly or monthly indices for example) if index not in indices: indices.append(index) current_date += datetime.timedelta(days=1) return indices def get_indices(self, dates): """Return the list of indices to use for given dates. """ start_date = None end_date = None for date in dates: if '>' in date.operator: start_date = date.value if '<' in date.operator: end_date = date.value return self.generate_list_of_indices(start_date, end_date) def format_field_names(self, hit): """Return a hit with each field's database name replaced by its exposed name. """ new_hit = {} for field in hit: new_field = field if '.' in new_field: # Remove the prefix ("processed_crash." or "raw_crash."). new_field = new_field.split('.')[-1] new_field = self.database_name_to_field_name_map.get( new_field, new_field ) new_hit[new_field] = hit[field] return new_hit def format_fields(self, hit): """Return a well formatted document. Elasticsearch returns values as lists when using the `fields` option. This function removes the list when it contains zero or one element. It also calls `format_field_names` to correct all the field names. """ hit = self.format_field_names(hit) for field in hit: if isinstance(hit[field], (list, tuple)): if len(hit[field]) == 0: hit[field] = None elif len(hit[field]) == 1: hit[field] = hit[field][0] return hit def get_field_name(self, value, full=True): try: field_ = self.all_fields[value] except KeyError: raise BadArgumentError( value, msg='Unknown field "%s"' % value ) if not field_['is_returned']: # Returning this field is not allowed. raise BadArgumentError( value, msg='Field "%s" is not allowed to be returned' % value ) field_name = '%s.%s' % ( field_['namespace'], field_['in_database_name'] ) if full and field_['has_full_version']: # If the param has a full version, that means what matters # is the full string, and not its individual terms. field_name += '.full' return field_name def format_aggregations(self, aggregations): """Return aggregations in a form that looks like facets. We used to expose the Elasticsearch facets directly. This is thus needed for backwards compatibility. """ aggs = aggregations.to_dict() for agg in aggs: for i, bucket in enumerate(aggs[agg]['buckets']): sub_aggs = {} for key in bucket: # Go through all sub aggregations. Those are contained in # all the keys that are not 'key' or 'count'. if key in ('key', 'key_as_string', 'doc_count'): continue sub_aggs[key] = [ { # For date data, Elasticsearch exposes a timestamp # in 'key' and a human-friendly string in # 'key_as_string'. We thus check if the later # exists to expose it, and return the normal # 'key' if not. 'term': x.get('key_as_string', x['key']), 'count': x['doc_count'], } for x in bucket[key]['buckets'] ] aggs[agg]['buckets'][i] = { 'term': bucket.get('key_as_string', bucket['key']), 'count': bucket['doc_count'], } if sub_aggs: aggs[agg]['buckets'][i]['facets'] = sub_aggs aggs[agg] = aggs[agg]['buckets'] return aggs def get(self, **kwargs): """Return a list of results and aggregations based on parameters. The list of accepted parameters (with types and default values) is in the database and can be accessed with the super_search_fields service. """ # Filter parameters and raise potential errors. params = self.get_parameters(**kwargs) # Find the indices to use to optimize the elasticsearch query. indices = self.get_indices(params['date']) # Create and configure the search object. search = Search( using=self.get_connection(), index=indices, doc_type=self.config.elasticsearch.elasticsearch_doctype, ) # Create filters. filters = None for field, sub_params in params.items(): sub_filters = None for param in sub_params: if param.name.startswith('_'): # By default, all param values are turned into lists, # even when they have and can have only one value. # For those we know there can only be one value, # so we just extract it from the made-up list. if param.name == '_results_offset': results_from = param.value[0] elif param.name == '_results_number': results_number = param.value[0] elif param.name == '_facets_size': facets_size = param.value[0] elif param.name == '_histogram_interval.date': histogram_interval_date = param.value[0] # Don't use meta parameters in the query. continue field_data = self.all_fields[param.name] name = '%s.%s' % ( field_data['namespace'], field_data['in_database_name'] ) if param.data_type in ('date', 'datetime'): param.value = datetimeutil.date_to_string(param.value) elif param.data_type == 'enum': param.value = [x.lower() for x in param.value] elif param.data_type == 'str' and not param.operator: param.value = [x.lower() for x in param.value] args = {} filter_type = 'term' filter_value = None if not param.operator: # contains one of the terms if len(param.value) == 1: val = param.value[0] if not isinstance(val, basestring) or ( isinstance(val, basestring) and ' ' not in val ): filter_value = val # If the term contains white spaces, we want to perform # a phrase query. Thus we do nothing here and let this # value be handled later. else: filter_type = 'terms' filter_value = param.value elif param.operator == '=': # is exactly if field_data['has_full_version']: name = '%s.full' % name filter_value = param.value elif param.operator == '>': # greater than filter_type = 'range' filter_value = { 'gt': param.value } elif param.operator == '<': # lower than filter_type = 'range' filter_value = { 'lt': param.value } elif param.operator == '>=': # greater than or equal to filter_type = 'range' filter_value = { 'gte': param.value } elif param.operator == '<=': # lower than or equal to filter_type = 'range' filter_value = { 'lte': param.value } elif param.operator == '__null__': # is null filter_type = 'missing' args['field'] = name if filter_value is not None: args[name] = filter_value if args: if param.operator_not: new_filter = ~F(filter_type, **args) else: new_filter = F(filter_type, **args) if sub_filters is None: sub_filters = new_filter elif param.data_type == 'enum': sub_filters |= new_filter else: sub_filters &= new_filter continue # These use a wildcard and thus need to be in a query # instead of a filter. operator_wildcards = { '~': '*%s*', # contains '$': '%s*', # starts with '^': '*%s' # ends with } if param.operator in operator_wildcards: if field_data['has_full_version']: name = '%s.full' % name query_type = 'wildcard' args[name] = ( operator_wildcards[param.operator] % param.value ) elif not param.operator: # This is a phrase that was passed down. query_type = 'simple_query_string' args['query'] = param.value[0] args['fields'] = [name] args['default_operator'] = 'and' if args: query = Q(query_type, **args) if param.operator_not: query = ~query search = search.query(query) else: # If we reach this point, that means the operator is # not supported, and we should raise an error about that. raise NotImplementedError( 'Operator %s is not supported' % param.operator ) if filters is None: filters = sub_filters elif sub_filters is not None: filters &= sub_filters search = search.filter(filters) # Restricting returned fields. fields = [] for param in params['_columns']: for value in param.value: if not value: continue field_name = self.get_field_name(value, full=False) fields.append(field_name) search = search.fields(fields) # Sorting. sort_fields = [] for param in params['_sort']: for value in param.value: if not value: continue # Values starting with a '-' are sorted in descending order. # In order to retrieve the database name of the field, we # must first remove the '-' part and add it back later. # Example: given ['product', '-version'], the results will be # sorted by ascending product and descending version. desc = False if value.startswith('-'): desc = True value = value[1:] field_name = self.get_field_name(value, full=False) if desc: # The underlying library understands that '-' means # sorting in descending order. field_name = '-' + field_name sort_fields.append(field_name) search = search.sort(*sort_fields) # Pagination. results_to = results_from + results_number search = search[results_from:results_to] # Create facets. for param in params['_facets']: for value in param.value: if not value: continue field_name = self.get_field_name(value) search.aggs.bucket( value, 'terms', field=field_name, size=facets_size, ) # Create signature aggregations. if params.get('_aggs.signature'): sig_bucket = A( 'terms', field=self.get_field_name('signature'), size=facets_size, ) for param in params['_aggs.signature']: for value in param.value: if not value: continue field_name = self.get_field_name(value) sig_bucket.bucket( value, 'terms', field=field_name, size=facets_size, ) search.aggs.bucket('signature', sig_bucket) # Create date histograms. if params.get('_histogram.date'): date_bucket = A( 'date_histogram', field=self.get_field_name('date'), interval=histogram_interval_date, ) for param in params['_histogram.date']: for value in param.value: if not value: continue field_name = self.get_field_name(value) val_bucket = A( 'terms', field=field_name, size=facets_size, ) date_bucket.bucket(value, val_bucket) search.aggs.bucket('histogram_date', date_bucket) # Query and compute results. hits = [] if params['_return_query'][0].value[0]: # Return only the JSON query that would be sent to elasticsearch. return { 'query': search.to_dict(), 'indices': indices, } # We call elasticsearch with a computed list of indices, based on # the date range. However, if that list contains indices that do not # exist in elasticsearch, an error will be raised. We thus want to # remove all failing indices until we either have a valid list, or # an empty list in which case we return no result. while True: try: results = search.execute() for hit in results: hits.append(self.format_fields(hit.to_dict())) total = search.count() aggregations = self.format_aggregations(results.aggregations) break # Yay! Results! except NotFoundError, e: missing_index = re.findall(BAD_INDEX_REGEX, e.error)[0] if missing_index in indices: del indices[indices.index(missing_index)] else: # Wait what? An error caused by an index that was not # in the request? That should never happen, but in case # it does, better know it. raise if indices: # Update the list of indices and try again. # Note: we need to first empty the list of indices before # updating it, otherwise the removed indices never get # actually removed. search = search.index().index(*indices) else: # There is no index left in the list, return an empty # result. hits = [] total = 0 aggregations = {} break return { 'hits': hits, 'total': total, 'facets': aggregations, } # For backwards compatibility with the previous elasticsearch module. # All those methods used to live in this file, but have been moved to # the super_search_fields.py file now. Since the configuration of the # middleware expect those to still be here, we bind them for now. def get_fields(self, **kwargs): return SuperSearchFields(config=self.config).get_fields(**kwargs) def create_field(self, **kwargs): return SuperSearchFields(config=self.config).create_field(**kwargs) def update_field(self, **kwargs): return SuperSearchFields(config=self.config).update_field(**kwargs) def delete_field(self, **kwargs): return SuperSearchFields(config=self.config).delete_field(**kwargs) def get_missing_fields(self): return SuperSearchFields(config=self.config).get_missing_fields() ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n#!/usr/bin/env python\n\n\"\"\"\nCreates or regenerates a Makefile with special planex-init comments\n\"\"\"\n\nimport os\nimport logging\n\nMAKEFILE_PATH = \"/usr/share/planex\"\n\n\ndef create_makefile():\n \"\"\" Che...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n#!/usr/bin/env python\n\n\"\"\"\nCreates or regenerates a Makefile with special planex-init comments\n\"\"\"\n\nimport os\nimport logging\n\nMAKEFILE_PATH = \"/usr/share/planex\"\n\n\ndef create_makefile():...
```python #!/usr/bin/env python """ Creates or regenerates a Makefile with special planex-init comments """ import os import logging MAKEFILE_PATH = "/usr/share/planex" def create_makefile(): """ Checks if a Makefile exists with special planex-init comments in it. If not, it creates or regenerates the Makefile while preserving its existing contents. """ name = "Makefile" firstline = "# Start generated by planex-init\n" autogen = "include %s/Makefile.rules\n" % (MAKEFILE_PATH) endline = "# End generated by planex-init\n" if not os.path.exists(name): logging.debug("Creating Makefile") with open(name, 'w') as makefile: makefile.write(firstline) makefile.write(autogen) makefile.write(endline) return with open(name, 'r') as makefile: lines = makefile.readlines() try: start = lines.index(firstline) end = lines.index(endline) lines = lines[:start + 1] + [autogen] + lines[end:] except ValueError: logging.error("Couldn't find planex-init stanza in Makefile") with open(name, 'w') as makefile: makefile.writelines(lines) def main(): """ Main entry point """ logging.basicConfig(format='%(message)s', level=logging.ERROR) create_makefile() if __name__ == "__main__": main() ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\n#!/usr/bin/env python3\n# Copyright (c) 2017 Genome Research Ltd.\n# Author: Alistair Dunham\n# This program is free software: you can redistribute it and/or modify it under\n# the terms of the GNU Gene...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\n#!/usr/bin/env python3\n# Copyright (c) 2017 Genome Research Ltd.\n# Author: Alistair Dunham\n# This program is free software: you can redistribute it and/or modify it under\n# the terms o...
```python #!/usr/bin/env python3 # Copyright (c) 2017 Genome Research Ltd. # Author: Alistair Dunham # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 3 of the License , or (at your option) any later # version. # This program is distributed in the hope that it will be useful , but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # You should have received a copy of the GNU General Public License along with # this program. If not , see <http :// www.gnu.org/licenses/>. ## Script to convert bedtools cluster output of merged breakdancer calls into a feature table ## which has columns for each sample indicating the presence of each deletion import argparse import fileinput import re ## Read arguments parser = argparse.ArgumentParser(description="Transform bedtools cluster output for deletion calls into a feature table of 'genotypes'.") parser.add_argument('tenx',metavar='T',type=str,help="Bed file containing clustered deletion calls") parser.add_argument('--bd','-b',action='store_true',help="Expect BreakDancer formatted IDs. Otherwise expect 10X formatted IDs.") args = parser.parse_args() ## Determine function to use for setting sample ID depending on given source format if args.bd: def getSample(x): """Extract sample from BreakDancer formatted ID tags""" return(re.split("[_.]",x)[-2]) else: def getSample(x): """Extract sample from 10X formatted ID tags""" return(x.split('.')[0]) ## Extract each deletion call and its cluster number dels = [] samples = set() with fileinput.input(args.tenx) as bed: for li in bed: t = li.strip().split() s = getSample(t[3]) n = int(t[4]) samples.add(s) if len(dels) < n: dels.append(set([s])) else: dels[n - 1].add(s) ## Print feature table samples = sorted(list(samples)) print("Deletion",*samples,sep='\t') for n,delSamples in enumerate(dels): ## generate feature string feats = [(1 if i in delSamples else 0) for i in samples] print('_'.join(["del",str(n + 1)]),*feats,sep='\t') ```
[ { "content": "Repeat the code precisely:\n```python\n\"\"\"\n Author: Denis Nutiu <denis.nutiu@gmail.com>\n This file is part of scoreboard-benchmark.\n\n scoreboard-benchmark is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published...
[ { "content": "Repeat the code precisely:\n<|memory_start|>```python\n\"\"\"\n Author: Denis Nutiu <denis.nutiu@gmail.com>\n This file is part of scoreboard-benchmark.\n\n scoreboard-benchmark is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public Lice...
```python """ Author: Denis Nutiu <denis.nutiu@gmail.com> This file is part of scoreboard-benchmark. scoreboard-benchmark is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. scoreboard-benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with scoreboard-benchmark . If not, see <http://www.gnu.org/licenses/>. """ from flask_sqlalchemy import SQLAlchemy import sqlalchemy_utils db = SQLAlchemy() class Result(db.Model): """ The result model will store benchmark results. """ __tablename__ = 'results' id = db.Column(db.Integer, primary_key=True, index=True) name = db.Column(db.String(50)) gpu = db.Column(db.String(256)) cpu = db.Column(db.String(256)) log = db.Column(db.Text) score = db.Column(db.Integer, index=True) ip = db.Column(sqlalchemy_utils.IPAddressType) created = db.Column(db.DateTime(timezone=True), server_default=db.func.now()) # Update time created server time. def __init__(self, name="Anonymous", gpu=None, cpu=None, log=None, ip=None, score=1): self.name = name self.gpu = gpu self.cpu = cpu self.log = log self.score = score self.ip = ip def __repr__(self): return self.gpu __table_args__ = ( db.CheckConstraint(score > 0, name="positive_score_constraint"), {} ) ```
[ { "content": "Repeat the following code:\n```python\n#!/usr/bin/env python\n\n# ptp_fuzz.py - Fuzz a PTP implementation\n# Copyright (C) 2016 Matthias Kruk\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Fr...
[ { "content": "Repeat the following code:\n<|memory_start|>```python\n#!/usr/bin/env python\n\n# ptp_fuzz.py - Fuzz a PTP implementation\n# Copyright (C) 2016 Matthias Kruk\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as publis...
```python #!/usr/bin/env python # ptp_fuzz.py - Fuzz a PTP implementation # Copyright (C) 2016 Matthias Kruk # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import sys def usage(argv0): print("Usage: %s iface dest\n\nArguments:\n iface Outgoing network interface\n dest Destination MAC address\n" % (argv0, )) if __name__ == "__main__": if len(sys.argv) < 3: usage(sys.argv[0]) exit(1) for arg in sys.argv: if arg == "-h" or arg == "--help": usage(sys.argv[0]) exit(1) from scapy.all import * from proto.ptp import * import netifaces eth_addr = netifaces.ifaddresses(sys.argv[1])[netifaces.AF_LINK][0]["addr"] sendp(Ether(src=eth_addr,dst=sys.argv[2])/fuzz(PTP()), loop=1, iface=sys.argv[1]) exit(0) ```
[ { "content": "```python\n#!/usr/bin/env python\n# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai\nfrom __future__ import with_statement\n\n__license__ = 'GPL v3'\n__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'\n__docformat__ = 'restructuredtext en'\n\nfrom PyQt4.Qt import Qt, QAbstractListModel,...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\n# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai\nfrom __future__ import with_statement\n\n__license__ = 'GPL v3'\n__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'\n__docformat__ = 'restructuredtext en'\n\nfrom PyQt4.Qt import Qt, QAb...
```python #!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from PyQt4.Qt import Qt, QAbstractListModel, QVariant, SIGNAL from calibre.gui2.convert.page_setup_ui import Ui_Form from calibre.gui2.convert import Widget from calibre.gui2 import NONE from calibre.customize.ui import input_profiles, output_profiles class ProfileModel(QAbstractListModel): def __init__(self, profiles): QAbstractListModel.__init__(self) self.profiles = list(profiles) def rowCount(self, *args): return len(self.profiles) def data(self, index, role): profile = self.profiles[index.row()] if role == Qt.DisplayRole: return QVariant(profile.name) if role in (Qt.ToolTipRole, Qt.StatusTipRole, Qt.WhatsThisRole): w, h = profile.screen_size if w >= 10000: ss = _('unlimited') else: ss = _('%d x %d pixels') % (w, h) ss = _('Screen size: %s') % ss return QVariant('%s [%s]' % (profile.description, ss)) return NONE class PageSetupWidget(Widget, Ui_Form): TITLE = _('Page Setup') COMMIT_NAME = 'page_setup' def __init__(self, parent, get_option, get_help, db=None, book_id=None): self.__connections = [] Widget.__init__(self, parent, ['margin_top', 'margin_left', 'margin_right', 'margin_bottom', 'input_profile', 'output_profile'] ) self.db, self.book_id = db, book_id self.input_model = ProfileModel(input_profiles()) self.output_model = ProfileModel(output_profiles()) self.opt_input_profile.setModel(self.input_model) self.opt_output_profile.setModel(self.output_model) for g, slot in self.__connections: g.selectionModel().currentChanged.connect(slot) del self.__connections for x in (self.opt_input_profile, self.opt_output_profile): x.setMouseTracking(True) self.connect(x, SIGNAL('entered(QModelIndex)'), self.show_desc) self.initialize_options(get_option, get_help, db, book_id) it = unicode(self.opt_input_profile.toolTip()) self.opt_input_profile.setToolTip('<p>'+it.replace('t.','t.\n<br>')) it = unicode(self.opt_output_profile.toolTip()) self.opt_output_profile.setToolTip('<p>'+it.replace('t.','ce.\n<br>')) def show_desc(self, index): desc = index.model().data(index, Qt.StatusTipRole).toString() self.profile_description.setText(desc) def connect_gui_obj_handler(self, g, slot): if g not in (self.opt_input_profile, self.opt_output_profile): raise NotImplementedError() self.__connections.append((g, slot)) def set_value_handler(self, g, val): if g in (self.opt_input_profile, self.opt_output_profile): g.clearSelection() for idx, p in enumerate(g.model().profiles): if p.short_name == val: break idx = g.model().index(idx) sm = g.selectionModel() g.setCurrentIndex(idx) sm.select(idx, sm.SelectCurrent) return True return False def get_value_handler(self, g): if g in (self.opt_input_profile, self.opt_output_profile): idx = g.currentIndex().row() return g.model().profiles[idx].short_name return Widget.get_value_handler(self, g) ```
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n```python\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport logging\n\nimport bleach\n\nfrom django import http\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core import exception...
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\nimport datetime\nimport logging\n\nimport bleach\n\nfrom django import http\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core ...
```python # -*- coding: utf-8 -*- import datetime import logging import bleach from django import http from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core import exceptions from django.shortcuts import get_object_or_404, redirect, render from .forms import AdminEventForm, EventForm from .models import Event logger = logging.getLogger(__name__) @login_required def events_view(request): """Events homepage. Shows a list of events occurring in the next week, month, and future. """ is_events_admin = request.user.has_admin_permission('events') if request.method == "POST": if "approve" in request.POST and is_events_admin: event_id = request.POST.get('approve') event = get_object_or_404(Event, id=event_id) event.rejected = False event.approved = True event.approved_by = request.user event.save() messages.success(request, "Approved event {}".format(event)) if "reject" in request.POST and is_events_admin: event_id = request.POST.get('reject') event = get_object_or_404(Event, id=event_id) event.approved = False event.rejected = True event.rejected_by = request.user event.save() messages.success(request, "Rejected event {}".format(event)) if is_events_admin and "show_all" in request.GET: viewable_events = (Event.objects.prefetch_related("groups")) else: viewable_events = (Event.objects.visible_to_user(request.user).prefetch_related("groups")) # get date objects for week and month today = datetime.date.today() delta = today - datetime.timedelta(days=today.weekday()) this_week = (delta, delta + datetime.timedelta(days=7)) this_month = (this_week[1], this_week[1] + datetime.timedelta(days=31)) events_categories = [ { "title": "This week", "events": viewable_events.filter(time__gte=this_week[0], time__lt=this_week[1]) }, { "title": "This month", "events": viewable_events.filter(time__gte=this_month[0], time__lt=this_month[1]) }, { "title": "Future", "events": viewable_events.filter(time__gte=this_month[1]) } ] if is_events_admin: unapproved_events = (Event.objects.filter(approved=False, rejected=False).prefetch_related("groups")) events_categories = [{"title": "Awaiting Approval", "events": unapproved_events}] + events_categories if is_events_admin and "show_all" in request.GET: events_categories.append({"title": "Past", "events": viewable_events.filter(time__lt=this_week[0])}) context = { "events": events_categories, "num_events": viewable_events.count(), "is_events_admin": is_events_admin, "events_admin": is_events_admin, "show_attend": True, "show_icon": True } return render(request, "events/home.html", context) @login_required def join_event_view(request, id): """Join event page. If a POST request, actually add or remove the attendance of the current user. Otherwise, display a page with confirmation. id: event id """ event = get_object_or_404(Event, id=id) if request.method == "POST": if not event.show_attending: return redirect("events") if "attending" in request.POST: attending = request.POST.get("attending") attending = (attending == "true") if attending: event.attending.add(request.user) else: event.attending.remove(request.user) return redirect("events") context = {"event": event, "is_events_admin": request.user.has_admin_permission('events')} return render(request, "events/join_event.html", context) @login_required def event_roster_view(request, id): """Show the event roster. Users with hidden eighth period permissions will not be displayed. Users will be able to view all other users, along with a count of the number of hidden users. (Same as 8th roster page.) Admins will see a full roster at the bottom. id: event id """ event = get_object_or_404(Event, id=id) full_roster = list(event.attending.all()) viewable_roster = [] num_hidden_members = 0 for p in full_roster: if p.can_view_eighth: viewable_roster.append(p) else: num_hidden_members += 1 context = { "event": event, "viewable_roster": viewable_roster, "full_roster": full_roster, "num_hidden_members": num_hidden_members, "is_events_admin": request.user.has_admin_permission('events'), } return render(request, "events/roster.html", context) @login_required def add_event_view(request): """Add event page. Currently, there is an approval process for events. If a user is an events administrator, they can create events directly. Otherwise, their event is added in the system but must be approved. """ is_events_admin = request.user.has_admin_permission('events') if not is_events_admin: return redirect("request_event") if request.method == "POST": form = EventForm(data=request.POST, all_groups=request.user.has_admin_permission('groups')) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.description = bleach.linkify(obj.description) # auto-approve if admin obj.approved = True obj.approved_by = request.user messages.success(request, "Because you are an administrator, this event was auto-approved.") obj.created_hook(request) obj.save() return redirect("events") else: messages.error(request, "Error adding event") else: form = EventForm(all_groups=request.user.has_admin_permission('groups')) context = {"form": form, "action": "add", "action_title": "Add" if is_events_admin else "Submit", "is_events_admin": is_events_admin} return render(request, "events/add_modify.html", context) @login_required def request_event_view(request): """Request event page. Currently, there is an approval process for events. If a user is an events administrator, they can create events directly. Otherwise, their event is added in the system but must be approved. """ is_events_admin = False if request.method == "POST": form = EventForm(data=request.POST, all_groups=request.user.has_admin_permission('groups')) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.description = bleach.linkify(obj.description) messages.success(request, "Your event needs to be approved by an administrator. If approved, it should appear on Intranet within 24 hours.") obj.created_hook(request) obj.save() return redirect("events") else: messages.error(request, "Error adding event") else: form = EventForm(all_groups=request.user.has_admin_permission('groups')) context = {"form": form, "action": "add", "action_title": "Submit", "is_events_admin": is_events_admin} return render(request, "events/add_modify.html", context) @login_required def modify_event_view(request, id=None): """Modify event page. You may only modify an event if you were the creator or you are an administrator. id: event id """ event = get_object_or_404(Event, id=id) is_events_admin = request.user.has_admin_permission('events') if not is_events_admin: raise exceptions.PermissionDenied if request.method == "POST": if is_events_admin: form = AdminEventForm(data=request.POST, instance=event, all_groups=request.user.has_admin_permission('groups')) else: form = EventForm(data=request.POST, instance=event, all_groups=request.user.has_admin_permission('groups')) logger.debug(form) if form.is_valid(): obj = form.save() obj.user = request.user # SAFE HTML obj.description = bleach.linkify(obj.description) obj.save() messages.success(request, "Successfully modified event.") # return redirect("events") else: messages.error(request, "Error adding event.") else: if is_events_admin: form = AdminEventForm(instance=event, all_groups=request.user.has_admin_permission('groups')) else: form = EventForm(instance=event, all_groups=request.user.has_admin_permission('groups')) context = {"form": form, "action": "modify", "action_title": "Modify", "id": id, "is_events_admin": is_events_admin} return render(request, "events/add_modify.html", context) @login_required def delete_event_view(request, id): """Delete event page. You may only delete an event if you were the creator or you are an administrator. Confirmation page if not POST. id: event id """ event = get_object_or_404(Event, id=id) if not request.user.has_admin_permission('events'): raise exceptions.PermissionDenied if request.method == "POST": try: event.delete() messages.success(request, "Successfully deleted event.") except Event.DoesNotExist: pass return redirect("events") else: return render(request, "events/delete.html", {"event": event}) @login_required def show_event_view(request): """ Unhide an event that was hidden by the logged-in user. events_hidden in the user model is the related_name for "users_hidden" in the EventUserMap model. """ if request.method == "POST": event_id = request.POST.get("event_id") if event_id: event = Event.objects.get(id=event_id) event.user_map.users_hidden.remove(request.user) event.user_map.save() return http.HttpResponse("Unhidden") return http.Http404() else: return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED") @login_required def hide_event_view(request): """ Hide an event for the logged-in user. events_hidden in the user model is the related_name for "users_hidden" in the EventUserMap model. """ if request.method == "POST": event_id = request.POST.get("event_id") if event_id: event = Event.objects.get(id=event_id) event.user_map.users_hidden.add(request.user) event.user_map.save() return http.HttpResponse("Hidden") return http.Http404() else: return http.HttpResponseNotAllowed(["POST"], "HTTP 405: METHOD NOT ALLOWED") ```
[ { "content": "Here is the code block:\n```python\n# coding=utf-8\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unle...
[ { "content": "Here is the code block:\n<|memory_start|>```python\n# coding=utf-8\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENS...
```python # coding=utf-8 # # 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. """Central place for handling Keystone authorization and service lookup.""" from keystoneauth1 import exceptions as kaexception from keystoneauth1 import loading as kaloading from oslo_log import log as logging import six from ironic.common import exception from ironic.conf import CONF LOG = logging.getLogger(__name__) def ks_exceptions(f): """Wraps keystoneclient functions and centralizes exception handling.""" @six.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except kaexception.EndpointNotFound: service_type = kwargs.get('service_type', 'baremetal') endpoint_type = kwargs.get('endpoint_type', 'internal') raise exception.CatalogNotFound( service_type=service_type, endpoint_type=endpoint_type) except (kaexception.Unauthorized, kaexception.AuthorizationFailure): raise exception.KeystoneUnauthorized() except (kaexception.NoMatchingPlugin, kaexception.MissingRequiredOptions) as e: raise exception.ConfigInvalid(six.text_type(e)) except Exception as e: LOG.exception('Keystone request failed: %(msg)s', {'msg': six.text_type(e)}) raise exception.KeystoneFailure(six.text_type(e)) return wrapper @ks_exceptions def get_session(group, **session_kwargs): """Loads session object from options in a configuration file section. The session_kwargs will be passed directly to keystoneauth1 Session and will override the values loaded from config. Consult keystoneauth1 docs for available options. :param group: name of the config section to load session options from """ return kaloading.load_session_from_conf_options( CONF, group, **session_kwargs) @ks_exceptions def get_auth(group, **auth_kwargs): """Loads auth plugin from options in a configuration file section. The auth_kwargs will be passed directly to keystoneauth1 auth plugin and will override the values loaded from config. Note that the accepted kwargs will depend on auth plugin type as defined by [group]auth_type option. Consult keystoneauth1 docs for available auth plugins and their options. :param group: name of the config section to load auth plugin options from """ try: auth = kaloading.load_auth_from_conf_options(CONF, group, **auth_kwargs) except kaexception.MissingRequiredOptions: LOG.error('Failed to load auth plugin from group %s', group) raise return auth # NOTE(pas-ha) Used by neutronclient and resolving ironic API only # FIXME(pas-ha) remove this while moving to kesytoneauth adapters @ks_exceptions def get_service_url(session, **kwargs): """Find endpoint for given service in keystone catalog. If 'interrace' is provided, fetches service url of this interface. Otherwise, first tries to fetch 'internal' endpoint, and then the 'public' one. :param session: keystoneauth Session object :param kwargs: any other arguments accepted by Session.get_endpoint method """ if 'interface' in kwargs: return session.get_endpoint(**kwargs) try: return session.get_endpoint(interface='internal', **kwargs) except kaexception.EndpointNotFound: return session.get_endpoint(interface='public', **kwargs) ```
[ { "content": "Here is the code content:\n```python\n# Find the sum of all the positive integers which\r\n# cannot be written as the sum of two abundant numbers.\r\n#\r\n# Facts:\r\n# All integers greater than 28123 can be\r\n# written as the sum of two abundant numbers.\r\n# Abundant number = sum of proper divi...
[ { "content": "Here is the code content:\n<|memory_start|>```python\n# Find the sum of all the positive integers which\r\n# cannot be written as the sum of two abundant numbers.\r\n#\r\n# Facts:\r\n# All integers greater than 28123 can be\r\n# written as the sum of two abundant numbers.\r\n# Abundant number = su...
```python # Find the sum of all the positive integers which # cannot be written as the sum of two abundant numbers. # # Facts: # All integers greater than 28123 can be # written as the sum of two abundant numbers. # Abundant number = sum of proper divisors of n exceed n. # # Find all abundant numbers up to and including 28123 # Add all combinations of these and store if not greater then 28123 # Add all integers <= 28123 not in the list to get required sum from myMath import * abundants = list() for n in range(1, 28123 + 1): if sum(int(n).properDivisors()) > n: abundants.append(n) print('stage 1 complete --', 'number of abundants = ', len(abundants)) sums = list() for i, n in enumerate(abundants): for m in abundants[i:]: if n+m <= 28123: sums.append(n+m) sums = sorted(set(sums)) print('stage 2 complete --', 'number of sums of abundants = ', len(sums)) sumsIndeces = [0]*(28123 + 1) for i, n in enumerate(sums): sumsIndeces.pop(n) sumsIndeces.insert(n,1) # places a one at every index that is sum of abundants if i%1000 == 0: print(i) print('stage 3 complete') total = 0 for n in range(len(sumsIndeces)): if sumsIndeces[n] == 0: total += n print('sum = ', total) ```
[ { "content": "```python\n# -*- encoding: utf-8 -*-\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under t...
[ { "content": "<|memory_start|>```python\n# -*- encoding: utf-8 -*-\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this fil...
```python # -*- encoding: utf-8 -*- # # 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. # """ Unit tests for pyspark.sql; additional tests are implemented as doctests in individual modules. """ import os import sys import subprocess import pydoc import shutil import tempfile import pickle import functools import time import datetime import py4j try: import xmlrunner except ImportError: xmlrunner = None if sys.version_info[:2] <= (2, 6): try: import unittest2 as unittest except ImportError: sys.stderr.write('Please install unittest2 to test with Python 2.6 or earlier') sys.exit(1) else: import unittest from pyspark import SparkContext from pyspark.sql import SparkSession, SQLContext, HiveContext, Column, Row from pyspark.sql.types import * from pyspark.sql.types import UserDefinedType, _infer_type from pyspark.tests import ReusedPySparkTestCase, SparkSubmitTests from pyspark.sql.functions import UserDefinedFunction, sha2, lit from pyspark.sql.window import Window from pyspark.sql.utils import AnalysisException, ParseException, IllegalArgumentException class UTCOffsetTimezone(datetime.tzinfo): """ Specifies timezone in UTC offset """ def __init__(self, offset=0): self.ZERO = datetime.timedelta(hours=offset) def utcoffset(self, dt): return self.ZERO def dst(self, dt): return self.ZERO class ExamplePointUDT(UserDefinedType): """ User-defined type (UDT) for ExamplePoint. """ @classmethod def sqlType(self): return ArrayType(DoubleType(), False) @classmethod def module(cls): return 'pyspark.sql.tests' @classmethod def scalaUDT(cls): return 'org.apache.spark.sql.test.ExamplePointUDT' def serialize(self, obj): return [obj.x, obj.y] def deserialize(self, datum): return ExamplePoint(datum[0], datum[1]) class ExamplePoint: """ An example class to demonstrate UDT in Scala, Java, and Python. """ __UDT__ = ExamplePointUDT() def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return "ExamplePoint(%s,%s)" % (self.x, self.y) def __str__(self): return "(%s,%s)" % (self.x, self.y) def __eq__(self, other): return isinstance(other, self.__class__) and \ other.x == self.x and other.y == self.y class PythonOnlyUDT(UserDefinedType): """ User-defined type (UDT) for ExamplePoint. """ @classmethod def sqlType(self): return ArrayType(DoubleType(), False) @classmethod def module(cls): return '__main__' def serialize(self, obj): return [obj.x, obj.y] def deserialize(self, datum): return PythonOnlyPoint(datum[0], datum[1]) @staticmethod def foo(): pass @property def props(self): return {} class PythonOnlyPoint(ExamplePoint): """ An example class to demonstrate UDT in only Python """ __UDT__ = PythonOnlyUDT() class MyObject(object): def __init__(self, key, value): self.key = key self.value = value class DataTypeTests(unittest.TestCase): # regression test for SPARK-6055 def test_data_type_eq(self): lt = LongType() lt2 = pickle.loads(pickle.dumps(LongType())) self.assertEqual(lt, lt2) # regression test for SPARK-7978 def test_decimal_type(self): t1 = DecimalType() t2 = DecimalType(10, 2) self.assertTrue(t2 is not t1) self.assertNotEqual(t1, t2) t3 = DecimalType(8) self.assertNotEqual(t2, t3) # regression test for SPARK-10392 def test_datetype_equal_zero(self): dt = DateType() self.assertEqual(dt.fromInternal(0), datetime.date(1970, 1, 1)) # regression test for SPARK-17035 def test_timestamp_microsecond(self): tst = TimestampType() self.assertEqual(tst.toInternal(datetime.datetime.max) % 1000000, 999999) def test_empty_row(self): row = Row() self.assertEqual(len(row), 0) class SQLTests(ReusedPySparkTestCase): @classmethod def setUpClass(cls): ReusedPySparkTestCase.setUpClass() cls.tempdir = tempfile.NamedTemporaryFile(delete=False) os.unlink(cls.tempdir.name) cls.spark = SparkSession(cls.sc) cls.testData = [Row(key=i, value=str(i)) for i in range(100)] cls.df = cls.spark.createDataFrame(cls.testData) @classmethod def tearDownClass(cls): ReusedPySparkTestCase.tearDownClass() cls.spark.stop() shutil.rmtree(cls.tempdir.name, ignore_errors=True) def test_sqlcontext_reuses_sparksession(self): sqlContext1 = SQLContext(self.sc) sqlContext2 = SQLContext(self.sc) self.assertTrue(sqlContext1.sparkSession is sqlContext2.sparkSession) def test_row_should_be_read_only(self): row = Row(a=1, b=2) self.assertEqual(1, row.a) def foo(): row.a = 3 self.assertRaises(Exception, foo) row2 = self.spark.range(10).first() self.assertEqual(0, row2.id) def foo2(): row2.id = 2 self.assertRaises(Exception, foo2) def test_range(self): self.assertEqual(self.spark.range(1, 1).count(), 0) self.assertEqual(self.spark.range(1, 0, -1).count(), 1) self.assertEqual(self.spark.range(0, 1 << 40, 1 << 39).count(), 2) self.assertEqual(self.spark.range(-2).count(), 0) self.assertEqual(self.spark.range(3).count(), 3) def test_duplicated_column_names(self): df = self.spark.createDataFrame([(1, 2)], ["c", "c"]) row = df.select('*').first() self.assertEqual(1, row[0]) self.assertEqual(2, row[1]) self.assertEqual("Row(c=1, c=2)", str(row)) # Cannot access columns self.assertRaises(AnalysisException, lambda: df.select(df[0]).first()) self.assertRaises(AnalysisException, lambda: df.select(df.c).first()) self.assertRaises(AnalysisException, lambda: df.select(df["c"]).first()) def test_column_name_encoding(self): """Ensure that created columns has `str` type consistently.""" columns = self.spark.createDataFrame([('Alice', 1)], ['name', u'age']).columns self.assertEqual(columns, ['name', 'age']) self.assertTrue(isinstance(columns[0], str)) self.assertTrue(isinstance(columns[1], str)) def test_explode(self): from pyspark.sql.functions import explode d = [Row(a=1, intlist=[1, 2, 3], mapfield={"a": "b"})] rdd = self.sc.parallelize(d) data = self.spark.createDataFrame(rdd) result = data.select(explode(data.intlist).alias("a")).select("a").collect() self.assertEqual(result[0][0], 1) self.assertEqual(result[1][0], 2) self.assertEqual(result[2][0], 3) result = data.select(explode(data.mapfield).alias("a", "b")).select("a", "b").collect() self.assertEqual(result[0][0], "a") self.assertEqual(result[0][1], "b") def test_and_in_expression(self): self.assertEqual(4, self.df.filter((self.df.key <= 10) & (self.df.value <= "2")).count()) self.assertRaises(ValueError, lambda: (self.df.key <= 10) and (self.df.value <= "2")) self.assertEqual(14, self.df.filter((self.df.key <= 3) | (self.df.value < "2")).count()) self.assertRaises(ValueError, lambda: self.df.key <= 3 or self.df.value < "2") self.assertEqual(99, self.df.filter(~(self.df.key == 1)).count()) self.assertRaises(ValueError, lambda: not self.df.key == 1) def test_udf_with_callable(self): d = [Row(number=i, squared=i**2) for i in range(10)] rdd = self.sc.parallelize(d) data = self.spark.createDataFrame(rdd) class PlusFour: def __call__(self, col): if col is not None: return col + 4 call = PlusFour() pudf = UserDefinedFunction(call, LongType()) res = data.select(pudf(data['number']).alias('plus_four')) self.assertEqual(res.agg({'plus_four': 'sum'}).collect()[0][0], 85) def test_udf_with_partial_function(self): d = [Row(number=i, squared=i**2) for i in range(10)] rdd = self.sc.parallelize(d) data = self.spark.createDataFrame(rdd) def some_func(col, param): if col is not None: return col + param pfunc = functools.partial(some_func, param=4) pudf = UserDefinedFunction(pfunc, LongType()) res = data.select(pudf(data['number']).alias('plus_four')) self.assertEqual(res.agg({'plus_four': 'sum'}).collect()[0][0], 85) def test_udf(self): self.spark.catalog.registerFunction("twoArgs", lambda x, y: len(x) + y, IntegerType()) [row] = self.spark.sql("SELECT twoArgs('test', 1)").collect() self.assertEqual(row[0], 5) def test_udf2(self): self.spark.catalog.registerFunction("strlen", lambda string: len(string), IntegerType()) self.spark.createDataFrame(self.sc.parallelize([Row(a="test")]))\ .createOrReplaceTempView("test") [res] = self.spark.sql("SELECT strlen(a) FROM test WHERE strlen(a) > 1").collect() self.assertEqual(4, res[0]) def test_chained_udf(self): self.spark.catalog.registerFunction("double", lambda x: x + x, IntegerType()) [row] = self.spark.sql("SELECT double(1)").collect() self.assertEqual(row[0], 2) [row] = self.spark.sql("SELECT double(double(1))").collect() self.assertEqual(row[0], 4) [row] = self.spark.sql("SELECT double(double(1) + 1)").collect() self.assertEqual(row[0], 6) def test_multiple_udfs(self): self.spark.catalog.registerFunction("double", lambda x: x * 2, IntegerType()) [row] = self.spark.sql("SELECT double(1), double(2)").collect() self.assertEqual(tuple(row), (2, 4)) [row] = self.spark.sql("SELECT double(double(1)), double(double(2) + 2)").collect() self.assertEqual(tuple(row), (4, 12)) self.spark.catalog.registerFunction("add", lambda x, y: x + y, IntegerType()) [row] = self.spark.sql("SELECT double(add(1, 2)), add(double(2), 1)").collect() self.assertEqual(tuple(row), (6, 5)) def test_udf_in_filter_on_top_of_outer_join(self): from pyspark.sql.functions import udf left = self.spark.createDataFrame([Row(a=1)]) right = self.spark.createDataFrame([Row(a=1)]) df = left.join(right, on='a', how='left_outer') df = df.withColumn('b', udf(lambda x: 'x')(df.a)) self.assertEqual(df.filter('b = "x"').collect(), [Row(a=1, b='x')]) def test_udf_in_filter_on_top_of_join(self): # regression test for SPARK-18589 from pyspark.sql.functions import udf left = self.spark.createDataFrame([Row(a=1)]) right = self.spark.createDataFrame([Row(b=1)]) f = udf(lambda a, b: a == b, BooleanType()) df = left.crossJoin(right).filter(f("a", "b")) self.assertEqual(df.collect(), [Row(a=1, b=1)]) def test_udf_without_arguments(self): self.spark.catalog.registerFunction("foo", lambda: "bar") [row] = self.spark.sql("SELECT foo()").collect() self.assertEqual(row[0], "bar") def test_udf_with_array_type(self): d = [Row(l=list(range(3)), d={"key": list(range(5))})] rdd = self.sc.parallelize(d) self.spark.createDataFrame(rdd).createOrReplaceTempView("test") self.spark.catalog.registerFunction("copylist", lambda l: list(l), ArrayType(IntegerType())) self.spark.catalog.registerFunction("maplen", lambda d: len(d), IntegerType()) [(l1, l2)] = self.spark.sql("select copylist(l), maplen(d) from test").collect() self.assertEqual(list(range(3)), l1) self.assertEqual(1, l2) def test_broadcast_in_udf(self): bar = {"a": "aa", "b": "bb", "c": "abc"} foo = self.sc.broadcast(bar) self.spark.catalog.registerFunction("MYUDF", lambda x: foo.value[x] if x else '') [res] = self.spark.sql("SELECT MYUDF('c')").collect() self.assertEqual("abc", res[0]) [res] = self.spark.sql("SELECT MYUDF('')").collect() self.assertEqual("", res[0]) def test_udf_with_filter_function(self): df = self.spark.createDataFrame([(1, "1"), (2, "2"), (1, "2"), (1, "2")], ["key", "value"]) from pyspark.sql.functions import udf, col from pyspark.sql.types import BooleanType my_filter = udf(lambda a: a < 2, BooleanType()) sel = df.select(col("key"), col("value")).filter((my_filter(col("key"))) & (df.value < "2")) self.assertEqual(sel.collect(), [Row(key=1, value='1')]) def test_udf_with_aggregate_function(self): df = self.spark.createDataFrame([(1, "1"), (2, "2"), (1, "2"), (1, "2")], ["key", "value"]) from pyspark.sql.functions import udf, col, sum from pyspark.sql.types import BooleanType my_filter = udf(lambda a: a == 1, BooleanType()) sel = df.select(col("key")).distinct().filter(my_filter(col("key"))) self.assertEqual(sel.collect(), [Row(key=1)]) my_copy = udf(lambda x: x, IntegerType()) my_add = udf(lambda a, b: int(a + b), IntegerType()) my_strlen = udf(lambda x: len(x), IntegerType()) sel = df.groupBy(my_copy(col("key")).alias("k"))\ .agg(sum(my_strlen(col("value"))).alias("s"))\ .select(my_add(col("k"), col("s")).alias("t")) self.assertEqual(sel.collect(), [Row(t=4), Row(t=3)]) def test_udf_in_generate(self): from pyspark.sql.functions import udf, explode df = self.spark.range(5) f = udf(lambda x: list(range(x)), ArrayType(LongType())) row = df.select(explode(f(*df))).groupBy().sum().first() self.assertEqual(row[0], 10) df = self.spark.range(3) res = df.select("id", explode(f(df.id))).collect() self.assertEqual(res[0][0], 1) self.assertEqual(res[0][1], 0) self.assertEqual(res[1][0], 2) self.assertEqual(res[1][1], 0) self.assertEqual(res[2][0], 2) self.assertEqual(res[2][1], 1) range_udf = udf(lambda value: list(range(value - 1, value + 1)), ArrayType(IntegerType())) res = df.select("id", explode(range_udf(df.id))).collect() self.assertEqual(res[0][0], 0) self.assertEqual(res[0][1], -1) self.assertEqual(res[1][0], 0) self.assertEqual(res[1][1], 0) self.assertEqual(res[2][0], 1) self.assertEqual(res[2][1], 0) self.assertEqual(res[3][0], 1) self.assertEqual(res[3][1], 1) def test_udf_with_order_by_and_limit(self): from pyspark.sql.functions import udf my_copy = udf(lambda x: x, IntegerType()) df = self.spark.range(10).orderBy("id") res = df.select(df.id, my_copy(df.id).alias("copy")).limit(1) res.explain(True) self.assertEqual(res.collect(), [Row(id=0, copy=0)]) def test_wholefile_json(self): people1 = self.spark.read.json("python/test_support/sql/people.json") people_array = self.spark.read.json("python/test_support/sql/people_array.json", wholeFile=True) self.assertEqual(people1.collect(), people_array.collect()) def test_wholefile_csv(self): ages_newlines = self.spark.read.csv( "python/test_support/sql/ages_newlines.csv", wholeFile=True) expected = [Row(_c0=u'Joe', _c1=u'20', _c2=u'Hi,\nI am Jeo'), Row(_c0=u'Tom', _c1=u'30', _c2=u'My name is Tom'), Row(_c0=u'Hyukjin', _c1=u'25', _c2=u'I am Hyukjin\n\nI love Spark!')] self.assertEqual(ages_newlines.collect(), expected) def test_ignorewhitespace_csv(self): tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) self.spark.createDataFrame([[" a", "b ", " c "]]).write.csv( tmpPath, ignoreLeadingWhiteSpace=False, ignoreTrailingWhiteSpace=False) expected = [Row(value=u' a,b , c ')] readback = self.spark.read.text(tmpPath) self.assertEqual(readback.collect(), expected) shutil.rmtree(tmpPath) def test_read_multiple_orc_file(self): df = self.spark.read.orc(["python/test_support/sql/orc_partitioned/b=0/c=0", "python/test_support/sql/orc_partitioned/b=1/c=1"]) self.assertEqual(2, df.count()) def test_udf_with_input_file_name(self): from pyspark.sql.functions import udf, input_file_name from pyspark.sql.types import StringType sourceFile = udf(lambda path: path, StringType()) filePath = "python/test_support/sql/people1.json" row = self.spark.read.json(filePath).select(sourceFile(input_file_name())).first() self.assertTrue(row[0].find("people1.json") != -1) def test_udf_with_input_file_name_for_hadooprdd(self): from pyspark.sql.functions import udf, input_file_name from pyspark.sql.types import StringType def filename(path): return path sameText = udf(filename, StringType()) rdd = self.sc.textFile('python/test_support/sql/people.json') df = self.spark.read.json(rdd).select(input_file_name().alias('file')) row = df.select(sameText(df['file'])).first() self.assertTrue(row[0].find("people.json") != -1) rdd2 = self.sc.newAPIHadoopFile( 'python/test_support/sql/people.json', 'org.apache.hadoop.mapreduce.lib.input.TextInputFormat', 'org.apache.hadoop.io.LongWritable', 'org.apache.hadoop.io.Text') df2 = self.spark.read.json(rdd2).select(input_file_name().alias('file')) row2 = df2.select(sameText(df2['file'])).first() self.assertTrue(row2[0].find("people.json") != -1) def test_udf_defers_judf_initalization(self): # This is separate of UDFInitializationTests # to avoid context initialization # when udf is called from pyspark.sql.functions import UserDefinedFunction f = UserDefinedFunction(lambda x: x, StringType()) self.assertIsNone( f._judf_placeholder, "judf should not be initialized before the first call." ) self.assertIsInstance(f("foo"), Column, "UDF call should return a Column.") self.assertIsNotNone( f._judf_placeholder, "judf should be initialized after UDF has been called." ) def test_udf_with_string_return_type(self): from pyspark.sql.functions import UserDefinedFunction add_one = UserDefinedFunction(lambda x: x + 1, "integer") make_pair = UserDefinedFunction(lambda x: (-x, x), "struct<x:integer,y:integer>") make_array = UserDefinedFunction( lambda x: [float(x) for x in range(x, x + 3)], "array<double>") expected = (2, Row(x=-1, y=1), [1.0, 2.0, 3.0]) actual = (self.spark.range(1, 2).toDF("x") .select(add_one("x"), make_pair("x"), make_array("x")) .first()) self.assertTupleEqual(expected, actual) def test_udf_shouldnt_accept_noncallable_object(self): from pyspark.sql.functions import UserDefinedFunction from pyspark.sql.types import StringType non_callable = None self.assertRaises(TypeError, UserDefinedFunction, non_callable, StringType()) def test_udf_with_decorator(self): from pyspark.sql.functions import lit, udf from pyspark.sql.types import IntegerType, DoubleType @udf(IntegerType()) def add_one(x): if x is not None: return x + 1 @udf(returnType=DoubleType()) def add_two(x): if x is not None: return float(x + 2) @udf def to_upper(x): if x is not None: return x.upper() @udf() def to_lower(x): if x is not None: return x.lower() @udf def substr(x, start, end): if x is not None: return x[start:end] @udf("long") def trunc(x): return int(x) @udf(returnType="double") def as_double(x): return float(x) df = ( self.spark .createDataFrame( [(1, "Foo", "foobar", 3.0)], ("one", "Foo", "foobar", "float")) .select( add_one("one"), add_two("one"), to_upper("Foo"), to_lower("Foo"), substr("foobar", lit(0), lit(3)), trunc("float"), as_double("one"))) self.assertListEqual( [tpe for _, tpe in df.dtypes], ["int", "double", "string", "string", "string", "bigint", "double"] ) self.assertListEqual( list(df.first()), [2, 3.0, "FOO", "foo", "foo", 3, 1.0] ) def test_udf_wrapper(self): from pyspark.sql.functions import udf from pyspark.sql.types import IntegerType def f(x): """Identity""" return x return_type = IntegerType() f_ = udf(f, return_type) self.assertTrue(f.__doc__ in f_.__doc__) self.assertEqual(f, f_.func) self.assertEqual(return_type, f_.returnType) def test_basic_functions(self): rdd = self.sc.parallelize(['{"foo":"bar"}', '{"foo":"baz"}']) df = self.spark.read.json(rdd) df.count() df.collect() df.schema # cache and checkpoint self.assertFalse(df.is_cached) df.persist() df.unpersist(True) df.cache() self.assertTrue(df.is_cached) self.assertEqual(2, df.count()) df.createOrReplaceTempView("temp") df = self.spark.sql("select foo from temp") df.count() df.collect() def test_apply_schema_to_row(self): df = self.spark.read.json(self.sc.parallelize(["""{"a":2}"""])) df2 = self.spark.createDataFrame(df.rdd.map(lambda x: x), df.schema) self.assertEqual(df.collect(), df2.collect()) rdd = self.sc.parallelize(range(10)).map(lambda x: Row(a=x)) df3 = self.spark.createDataFrame(rdd, df.schema) self.assertEqual(10, df3.count()) def test_infer_schema_to_local(self): input = [{"a": 1}, {"b": "coffee"}] rdd = self.sc.parallelize(input) df = self.spark.createDataFrame(input) df2 = self.spark.createDataFrame(rdd, samplingRatio=1.0) self.assertEqual(df.schema, df2.schema) rdd = self.sc.parallelize(range(10)).map(lambda x: Row(a=x, b=None)) df3 = self.spark.createDataFrame(rdd, df.schema) self.assertEqual(10, df3.count()) def test_apply_schema_to_dict_and_rows(self): schema = StructType().add("b", StringType()).add("a", IntegerType()) input = [{"a": 1}, {"b": "coffee"}] rdd = self.sc.parallelize(input) for verify in [False, True]: df = self.spark.createDataFrame(input, schema, verifySchema=verify) df2 = self.spark.createDataFrame(rdd, schema, verifySchema=verify) self.assertEqual(df.schema, df2.schema) rdd = self.sc.parallelize(range(10)).map(lambda x: Row(a=x, b=None)) df3 = self.spark.createDataFrame(rdd, schema, verifySchema=verify) self.assertEqual(10, df3.count()) input = [Row(a=x, b=str(x)) for x in range(10)] df4 = self.spark.createDataFrame(input, schema, verifySchema=verify) self.assertEqual(10, df4.count()) def test_create_dataframe_schema_mismatch(self): input = [Row(a=1)] rdd = self.sc.parallelize(range(3)).map(lambda i: Row(a=i)) schema = StructType([StructField("a", IntegerType()), StructField("b", StringType())]) df = self.spark.createDataFrame(rdd, schema) self.assertRaises(Exception, lambda: df.show()) def test_serialize_nested_array_and_map(self): d = [Row(l=[Row(a=1, b='s')], d={"key": Row(c=1.0, d="2")})] rdd = self.sc.parallelize(d) df = self.spark.createDataFrame(rdd) row = df.head() self.assertEqual(1, len(row.l)) self.assertEqual(1, row.l[0].a) self.assertEqual("2", row.d["key"].d) l = df.rdd.map(lambda x: x.l).first() self.assertEqual(1, len(l)) self.assertEqual('s', l[0].b) d = df.rdd.map(lambda x: x.d).first() self.assertEqual(1, len(d)) self.assertEqual(1.0, d["key"].c) row = df.rdd.map(lambda x: x.d["key"]).first() self.assertEqual(1.0, row.c) self.assertEqual("2", row.d) def test_infer_schema(self): d = [Row(l=[], d={}, s=None), Row(l=[Row(a=1, b='s')], d={"key": Row(c=1.0, d="2")}, s="")] rdd = self.sc.parallelize(d) df = self.spark.createDataFrame(rdd) self.assertEqual([], df.rdd.map(lambda r: r.l).first()) self.assertEqual([None, ""], df.rdd.map(lambda r: r.s).collect()) df.createOrReplaceTempView("test") result = self.spark.sql("SELECT l[0].a from test where d['key'].d = '2'") self.assertEqual(1, result.head()[0]) df2 = self.spark.createDataFrame(rdd, samplingRatio=1.0) self.assertEqual(df.schema, df2.schema) self.assertEqual({}, df2.rdd.map(lambda r: r.d).first()) self.assertEqual([None, ""], df2.rdd.map(lambda r: r.s).collect()) df2.createOrReplaceTempView("test2") result = self.spark.sql("SELECT l[0].a from test2 where d['key'].d = '2'") self.assertEqual(1, result.head()[0]) def test_infer_nested_schema(self): NestedRow = Row("f1", "f2") nestedRdd1 = self.sc.parallelize([NestedRow([1, 2], {"row1": 1.0}), NestedRow([2, 3], {"row2": 2.0})]) df = self.spark.createDataFrame(nestedRdd1) self.assertEqual(Row(f1=[1, 2], f2={u'row1': 1.0}), df.collect()[0]) nestedRdd2 = self.sc.parallelize([NestedRow([[1, 2], [2, 3]], [1, 2]), NestedRow([[2, 3], [3, 4]], [2, 3])]) df = self.spark.createDataFrame(nestedRdd2) self.assertEqual(Row(f1=[[1, 2], [2, 3]], f2=[1, 2]), df.collect()[0]) from collections import namedtuple CustomRow = namedtuple('CustomRow', 'field1 field2') rdd = self.sc.parallelize([CustomRow(field1=1, field2="row1"), CustomRow(field1=2, field2="row2"), CustomRow(field1=3, field2="row3")]) df = self.spark.createDataFrame(rdd) self.assertEqual(Row(field1=1, field2=u'row1'), df.first()) def test_create_dataframe_from_objects(self): data = [MyObject(1, "1"), MyObject(2, "2")] df = self.spark.createDataFrame(data) self.assertEqual(df.dtypes, [("key", "bigint"), ("value", "string")]) self.assertEqual(df.first(), Row(key=1, value="1")) def test_select_null_literal(self): df = self.spark.sql("select null as col") self.assertEqual(Row(col=None), df.first()) def test_apply_schema(self): from datetime import date, datetime rdd = self.sc.parallelize([(127, -128, -32768, 32767, 2147483647, 1.0, date(2010, 1, 1), datetime(2010, 1, 1, 1, 1, 1), {"a": 1}, (2,), [1, 2, 3], None)]) schema = StructType([ StructField("byte1", ByteType(), False), StructField("byte2", ByteType(), False), StructField("short1", ShortType(), False), StructField("short2", ShortType(), False), StructField("int1", IntegerType(), False), StructField("float1", FloatType(), False), StructField("date1", DateType(), False), StructField("time1", TimestampType(), False), StructField("map1", MapType(StringType(), IntegerType(), False), False), StructField("struct1", StructType([StructField("b", ShortType(), False)]), False), StructField("list1", ArrayType(ByteType(), False), False), StructField("null1", DoubleType(), True)]) df = self.spark.createDataFrame(rdd, schema) results = df.rdd.map(lambda x: (x.byte1, x.byte2, x.short1, x.short2, x.int1, x.float1, x.date1, x.time1, x.map1["a"], x.struct1.b, x.list1, x.null1)) r = (127, -128, -32768, 32767, 2147483647, 1.0, date(2010, 1, 1), datetime(2010, 1, 1, 1, 1, 1), 1, 2, [1, 2, 3], None) self.assertEqual(r, results.first()) df.createOrReplaceTempView("table2") r = self.spark.sql("SELECT byte1 - 1 AS byte1, byte2 + 1 AS byte2, " + "short1 + 1 AS short1, short2 - 1 AS short2, int1 - 1 AS int1, " + "float1 + 1.5 as float1 FROM table2").first() self.assertEqual((126, -127, -32767, 32766, 2147483646, 2.5), tuple(r)) from pyspark.sql.types import _parse_schema_abstract, _infer_schema_type rdd = self.sc.parallelize([(127, -32768, 1.0, datetime(2010, 1, 1, 1, 1, 1), {"a": 1}, (2,), [1, 2, 3])]) abstract = "byte1 short1 float1 time1 map1{} struct1(b) list1[]" schema = _parse_schema_abstract(abstract) typedSchema = _infer_schema_type(rdd.first(), schema) df = self.spark.createDataFrame(rdd, typedSchema) r = (127, -32768, 1.0, datetime(2010, 1, 1, 1, 1, 1), {"a": 1}, Row(b=2), [1, 2, 3]) self.assertEqual(r, tuple(df.first())) def test_struct_in_map(self): d = [Row(m={Row(i=1): Row(s="")})] df = self.sc.parallelize(d).toDF() k, v = list(df.head().m.items())[0] self.assertEqual(1, k.i) self.assertEqual("", v.s) def test_convert_row_to_dict(self): row = Row(l=[Row(a=1, b='s')], d={"key": Row(c=1.0, d="2")}) self.assertEqual(1, row.asDict()['l'][0].a) df = self.sc.parallelize([row]).toDF() df.createOrReplaceTempView("test") row = self.spark.sql("select l, d from test").head() self.assertEqual(1, row.asDict()["l"][0].a) self.assertEqual(1.0, row.asDict()['d']['key'].c) def test_udt(self): from pyspark.sql.types import _parse_datatype_json_string, _infer_type, _verify_type from pyspark.sql.tests import ExamplePointUDT, ExamplePoint def check_datatype(datatype): pickled = pickle.loads(pickle.dumps(datatype)) assert datatype == pickled scala_datatype = self.spark._jsparkSession.parseDataType(datatype.json()) python_datatype = _parse_datatype_json_string(scala_datatype.json()) assert datatype == python_datatype check_datatype(ExamplePointUDT()) structtype_with_udt = StructType([StructField("label", DoubleType(), False), StructField("point", ExamplePointUDT(), False)]) check_datatype(structtype_with_udt) p = ExamplePoint(1.0, 2.0) self.assertEqual(_infer_type(p), ExamplePointUDT()) _verify_type(ExamplePoint(1.0, 2.0), ExamplePointUDT()) self.assertRaises(ValueError, lambda: _verify_type([1.0, 2.0], ExamplePointUDT())) check_datatype(PythonOnlyUDT()) structtype_with_udt = StructType([StructField("label", DoubleType(), False), StructField("point", PythonOnlyUDT(), False)]) check_datatype(structtype_with_udt) p = PythonOnlyPoint(1.0, 2.0) self.assertEqual(_infer_type(p), PythonOnlyUDT()) _verify_type(PythonOnlyPoint(1.0, 2.0), PythonOnlyUDT()) self.assertRaises(ValueError, lambda: _verify_type([1.0, 2.0], PythonOnlyUDT())) def test_simple_udt_in_df(self): schema = StructType().add("key", LongType()).add("val", PythonOnlyUDT()) df = self.spark.createDataFrame( [(i % 3, PythonOnlyPoint(float(i), float(i))) for i in range(10)], schema=schema) df.show() def test_nested_udt_in_df(self): schema = StructType().add("key", LongType()).add("val", ArrayType(PythonOnlyUDT())) df = self.spark.createDataFrame( [(i % 3, [PythonOnlyPoint(float(i), float(i))]) for i in range(10)], schema=schema) df.collect() schema = StructType().add("key", LongType()).add("val", MapType(LongType(), PythonOnlyUDT())) df = self.spark.createDataFrame( [(i % 3, {i % 3: PythonOnlyPoint(float(i + 1), float(i + 1))}) for i in range(10)], schema=schema) df.collect() def test_complex_nested_udt_in_df(self): from pyspark.sql.functions import udf schema = StructType().add("key", LongType()).add("val", PythonOnlyUDT()) df = self.spark.createDataFrame( [(i % 3, PythonOnlyPoint(float(i), float(i))) for i in range(10)], schema=schema) df.collect() gd = df.groupby("key").agg({"val": "collect_list"}) gd.collect() udf = udf(lambda k, v: [(k, v[0])], ArrayType(df.schema)) gd.select(udf(*gd)).collect() def test_udt_with_none(self): df = self.spark.range(0, 10, 1, 1) def myudf(x): if x > 0: return PythonOnlyPoint(float(x), float(x)) self.spark.catalog.registerFunction("udf", myudf, PythonOnlyUDT()) rows = [r[0] for r in df.selectExpr("udf(id)").take(2)] self.assertEqual(rows, [None, PythonOnlyPoint(1, 1)]) def test_infer_schema_with_udt(self): from pyspark.sql.tests import ExamplePoint, ExamplePointUDT row = Row(label=1.0, point=ExamplePoint(1.0, 2.0)) df = self.spark.createDataFrame([row]) schema = df.schema field = [f for f in schema.fields if f.name == "point"][0] self.assertEqual(type(field.dataType), ExamplePointUDT) df.createOrReplaceTempView("labeled_point") point = self.spark.sql("SELECT point FROM labeled_point").head().point self.assertEqual(point, ExamplePoint(1.0, 2.0)) row = Row(label=1.0, point=PythonOnlyPoint(1.0, 2.0)) df = self.spark.createDataFrame([row]) schema = df.schema field = [f for f in schema.fields if f.name == "point"][0] self.assertEqual(type(field.dataType), PythonOnlyUDT) df.createOrReplaceTempView("labeled_point") point = self.spark.sql("SELECT point FROM labeled_point").head().point self.assertEqual(point, PythonOnlyPoint(1.0, 2.0)) def test_apply_schema_with_udt(self): from pyspark.sql.tests import ExamplePoint, ExamplePointUDT row = (1.0, ExamplePoint(1.0, 2.0)) schema = StructType([StructField("label", DoubleType(), False), StructField("point", ExamplePointUDT(), False)]) df = self.spark.createDataFrame([row], schema) point = df.head().point self.assertEqual(point, ExamplePoint(1.0, 2.0)) row = (1.0, PythonOnlyPoint(1.0, 2.0)) schema = StructType([StructField("label", DoubleType(), False), StructField("point", PythonOnlyUDT(), False)]) df = self.spark.createDataFrame([row], schema) point = df.head().point self.assertEqual(point, PythonOnlyPoint(1.0, 2.0)) def test_udf_with_udt(self): from pyspark.sql.tests import ExamplePoint, ExamplePointUDT row = Row(label=1.0, point=ExamplePoint(1.0, 2.0)) df = self.spark.createDataFrame([row]) self.assertEqual(1.0, df.rdd.map(lambda r: r.point.x).first()) udf = UserDefinedFunction(lambda p: p.y, DoubleType()) self.assertEqual(2.0, df.select(udf(df.point)).first()[0]) udf2 = UserDefinedFunction(lambda p: ExamplePoint(p.x + 1, p.y + 1), ExamplePointUDT()) self.assertEqual(ExamplePoint(2.0, 3.0), df.select(udf2(df.point)).first()[0]) row = Row(label=1.0, point=PythonOnlyPoint(1.0, 2.0)) df = self.spark.createDataFrame([row]) self.assertEqual(1.0, df.rdd.map(lambda r: r.point.x).first()) udf = UserDefinedFunction(lambda p: p.y, DoubleType()) self.assertEqual(2.0, df.select(udf(df.point)).first()[0]) udf2 = UserDefinedFunction(lambda p: PythonOnlyPoint(p.x + 1, p.y + 1), PythonOnlyUDT()) self.assertEqual(PythonOnlyPoint(2.0, 3.0), df.select(udf2(df.point)).first()[0]) def test_parquet_with_udt(self): from pyspark.sql.tests import ExamplePoint, ExamplePointUDT row = Row(label=1.0, point=ExamplePoint(1.0, 2.0)) df0 = self.spark.createDataFrame([row]) output_dir = os.path.join(self.tempdir.name, "labeled_point") df0.write.parquet(output_dir) df1 = self.spark.read.parquet(output_dir) point = df1.head().point self.assertEqual(point, ExamplePoint(1.0, 2.0)) row = Row(label=1.0, point=PythonOnlyPoint(1.0, 2.0)) df0 = self.spark.createDataFrame([row]) df0.write.parquet(output_dir, mode='overwrite') df1 = self.spark.read.parquet(output_dir) point = df1.head().point self.assertEqual(point, PythonOnlyPoint(1.0, 2.0)) def test_union_with_udt(self): from pyspark.sql.tests import ExamplePoint, ExamplePointUDT row1 = (1.0, ExamplePoint(1.0, 2.0)) row2 = (2.0, ExamplePoint(3.0, 4.0)) schema = StructType([StructField("label", DoubleType(), False), StructField("point", ExamplePointUDT(), False)]) df1 = self.spark.createDataFrame([row1], schema) df2 = self.spark.createDataFrame([row2], schema) result = df1.union(df2).orderBy("label").collect() self.assertEqual( result, [ Row(label=1.0, point=ExamplePoint(1.0, 2.0)), Row(label=2.0, point=ExamplePoint(3.0, 4.0)) ] ) def test_column_operators(self): ci = self.df.key cs = self.df.value c = ci == cs self.assertTrue(isinstance((- ci - 1 - 2) % 3 * 2.5 / 3.5, Column)) rcc = (1 + ci), (1 - ci), (1 * ci), (1 / ci), (1 % ci), (1 ** ci), (ci ** 1) self.assertTrue(all(isinstance(c, Column) for c in rcc)) cb = [ci == 5, ci != 0, ci > 3, ci < 4, ci >= 0, ci <= 7] self.assertTrue(all(isinstance(c, Column) for c in cb)) cbool = (ci & ci), (ci | ci), (~ci) self.assertTrue(all(isinstance(c, Column) for c in cbool)) css = cs.contains('a'), cs.like('a'), cs.rlike('a'), cs.asc(), cs.desc(),\ cs.startswith('a'), cs.endswith('a'), ci.eqNullSafe(cs) self.assertTrue(all(isinstance(c, Column) for c in css)) self.assertTrue(isinstance(ci.cast(LongType()), Column)) self.assertRaisesRegexp(ValueError, "Cannot apply 'in' operator against a column", lambda: 1 in cs) def test_column_getitem(self): from pyspark.sql.functions import col self.assertIsInstance(col("foo")[1:3], Column) self.assertIsInstance(col("foo")[0], Column) self.assertIsInstance(col("foo")["bar"], Column) self.assertRaises(ValueError, lambda: col("foo")[0:10:2]) def test_column_select(self): df = self.df self.assertEqual(self.testData, df.select("*").collect()) self.assertEqual(self.testData, df.select(df.key, df.value).collect()) self.assertEqual([Row(value='1')], df.where(df.key == 1).select(df.value).collect()) def test_freqItems(self): vals = [Row(a=1, b=-2.0) if i % 2 == 0 else Row(a=i, b=i * 1.0) for i in range(100)] df = self.sc.parallelize(vals).toDF() items = df.stat.freqItems(("a", "b"), 0.4).collect()[0] self.assertTrue(1 in items[0]) self.assertTrue(-2.0 in items[1]) def test_aggregator(self): df = self.df g = df.groupBy() self.assertEqual([99, 100], sorted(g.agg({'key': 'max', 'value': 'count'}).collect()[0])) self.assertEqual([Row(**{"AVG(key#0)": 49.5})], g.mean().collect()) from pyspark.sql import functions self.assertEqual((0, u'99'), tuple(g.agg(functions.first(df.key), functions.last(df.value)).first())) self.assertTrue(95 < g.agg(functions.approxCountDistinct(df.key)).first()[0]) self.assertEqual(100, g.agg(functions.countDistinct(df.value)).first()[0]) def test_first_last_ignorenulls(self): from pyspark.sql import functions df = self.spark.range(0, 100) df2 = df.select(functions.when(df.id % 3 == 0, None).otherwise(df.id).alias("id")) df3 = df2.select(functions.first(df2.id, False).alias('a'), functions.first(df2.id, True).alias('b'), functions.last(df2.id, False).alias('c'), functions.last(df2.id, True).alias('d')) self.assertEqual([Row(a=None, b=1, c=None, d=98)], df3.collect()) def test_approxQuantile(self): df = self.sc.parallelize([Row(a=i, b=i+10) for i in range(10)]).toDF() aq = df.stat.approxQuantile("a", [0.1, 0.5, 0.9], 0.1) self.assertTrue(isinstance(aq, list)) self.assertEqual(len(aq), 3) self.assertTrue(all(isinstance(q, float) for q in aq)) aqs = df.stat.approxQuantile(["a", "b"], [0.1, 0.5, 0.9], 0.1) self.assertTrue(isinstance(aqs, list)) self.assertEqual(len(aqs), 2) self.assertTrue(isinstance(aqs[0], list)) self.assertEqual(len(aqs[0]), 3) self.assertTrue(all(isinstance(q, float) for q in aqs[0])) self.assertTrue(isinstance(aqs[1], list)) self.assertEqual(len(aqs[1]), 3) self.assertTrue(all(isinstance(q, float) for q in aqs[1])) aqt = df.stat.approxQuantile(("a", "b"), [0.1, 0.5, 0.9], 0.1) self.assertTrue(isinstance(aqt, list)) self.assertEqual(len(aqt), 2) self.assertTrue(isinstance(aqt[0], list)) self.assertEqual(len(aqt[0]), 3) self.assertTrue(all(isinstance(q, float) for q in aqt[0])) self.assertTrue(isinstance(aqt[1], list)) self.assertEqual(len(aqt[1]), 3) self.assertTrue(all(isinstance(q, float) for q in aqt[1])) self.assertRaises(ValueError, lambda: df.stat.approxQuantile(123, [0.1, 0.9], 0.1)) self.assertRaises(ValueError, lambda: df.stat.approxQuantile(("a", 123), [0.1, 0.9], 0.1)) self.assertRaises(ValueError, lambda: df.stat.approxQuantile(["a", 123], [0.1, 0.9], 0.1)) def test_corr(self): import math df = self.sc.parallelize([Row(a=i, b=math.sqrt(i)) for i in range(10)]).toDF() corr = df.stat.corr("a", "b") self.assertTrue(abs(corr - 0.95734012) < 1e-6) def test_cov(self): df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF() cov = df.stat.cov("a", "b") self.assertTrue(abs(cov - 55.0 / 3) < 1e-6) def test_crosstab(self): df = self.sc.parallelize([Row(a=i % 3, b=i % 2) for i in range(1, 7)]).toDF() ct = df.stat.crosstab("a", "b").collect() ct = sorted(ct, key=lambda x: x[0]) for i, row in enumerate(ct): self.assertEqual(row[0], str(i)) self.assertTrue(row[1], 1) self.assertTrue(row[2], 1) def test_math_functions(self): df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF() from pyspark.sql import functions import math def get_values(l): return [j[0] for j in l] def assert_close(a, b): c = get_values(b) diff = [abs(v - c[k]) < 1e-6 for k, v in enumerate(a)] return sum(diff) == len(a) assert_close([math.cos(i) for i in range(10)], df.select(functions.cos(df.a)).collect()) assert_close([math.cos(i) for i in range(10)], df.select(functions.cos("a")).collect()) assert_close([math.sin(i) for i in range(10)], df.select(functions.sin(df.a)).collect()) assert_close([math.sin(i) for i in range(10)], df.select(functions.sin(df['a'])).collect()) assert_close([math.pow(i, 2 * i) for i in range(10)], df.select(functions.pow(df.a, df.b)).collect()) assert_close([math.pow(i, 2) for i in range(10)], df.select(functions.pow(df.a, 2)).collect()) assert_close([math.pow(i, 2) for i in range(10)], df.select(functions.pow(df.a, 2.0)).collect()) assert_close([math.hypot(i, 2 * i) for i in range(10)], df.select(functions.hypot(df.a, df.b)).collect()) def test_rand_functions(self): df = self.df from pyspark.sql import functions rnd = df.select('key', functions.rand()).collect() for row in rnd: assert row[1] >= 0.0 and row[1] <= 1.0, "got: %s" % row[1] rndn = df.select('key', functions.randn(5)).collect() for row in rndn: assert row[1] >= -4.0 and row[1] <= 4.0, "got: %s" % row[1] # If the specified seed is 0, we should use it. # https://issues.apache.org/jira/browse/SPARK-9691 rnd1 = df.select('key', functions.rand(0)).collect() rnd2 = df.select('key', functions.rand(0)).collect() self.assertEqual(sorted(rnd1), sorted(rnd2)) rndn1 = df.select('key', functions.randn(0)).collect() rndn2 = df.select('key', functions.randn(0)).collect() self.assertEqual(sorted(rndn1), sorted(rndn2)) def test_array_contains_function(self): from pyspark.sql.functions import array_contains df = self.spark.createDataFrame([(["1", "2", "3"],), ([],)], ['data']) actual = df.select(array_contains(df.data, 1).alias('b')).collect() # The value argument can be implicitly castable to the element's type of the array. self.assertEqual([Row(b=True), Row(b=False)], actual) def test_between_function(self): df = self.sc.parallelize([ Row(a=1, b=2, c=3), Row(a=2, b=1, c=3), Row(a=4, b=1, c=4)]).toDF() self.assertEqual([Row(a=2, b=1, c=3), Row(a=4, b=1, c=4)], df.filter(df.a.between(df.b, df.c)).collect()) def test_struct_type(self): from pyspark.sql.types import StructType, StringType, StructField struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None) struct2 = StructType([StructField("f1", StringType(), True), StructField("f2", StringType(), True, None)]) self.assertEqual(struct1, struct2) struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None) struct2 = StructType([StructField("f1", StringType(), True)]) self.assertNotEqual(struct1, struct2) struct1 = (StructType().add(StructField("f1", StringType(), True)) .add(StructField("f2", StringType(), True, None))) struct2 = StructType([StructField("f1", StringType(), True), StructField("f2", StringType(), True, None)]) self.assertEqual(struct1, struct2) struct1 = (StructType().add(StructField("f1", StringType(), True)) .add(StructField("f2", StringType(), True, None))) struct2 = StructType([StructField("f1", StringType(), True)]) self.assertNotEqual(struct1, struct2) # Catch exception raised during improper construction with self.assertRaises(ValueError): struct1 = StructType().add("name") struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None) for field in struct1: self.assertIsInstance(field, StructField) struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None) self.assertEqual(len(struct1), 2) struct1 = StructType().add("f1", StringType(), True).add("f2", StringType(), True, None) self.assertIs(struct1["f1"], struct1.fields[0]) self.assertIs(struct1[0], struct1.fields[0]) self.assertEqual(struct1[0:1], StructType(struct1.fields[0:1])) with self.assertRaises(KeyError): not_a_field = struct1["f9"] with self.assertRaises(IndexError): not_a_field = struct1[9] with self.assertRaises(TypeError): not_a_field = struct1[9.9] def test_metadata_null(self): from pyspark.sql.types import StructType, StringType, StructField schema = StructType([StructField("f1", StringType(), True, None), StructField("f2", StringType(), True, {'a': None})]) rdd = self.sc.parallelize([["a", "b"], ["c", "d"]]) self.spark.createDataFrame(rdd, schema) def test_save_and_load(self): df = self.df tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) df.write.json(tmpPath) actual = self.spark.read.json(tmpPath) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) schema = StructType([StructField("value", StringType(), True)]) actual = self.spark.read.json(tmpPath, schema) self.assertEqual(sorted(df.select("value").collect()), sorted(actual.collect())) df.write.json(tmpPath, "overwrite") actual = self.spark.read.json(tmpPath) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) df.write.save(format="json", mode="overwrite", path=tmpPath, noUse="this options will not be used in save.") actual = self.spark.read.load(format="json", path=tmpPath, noUse="this options will not be used in load.") self.assertEqual(sorted(df.collect()), sorted(actual.collect())) defaultDataSourceName = self.spark.conf.get("spark.sql.sources.default", "org.apache.spark.sql.parquet") self.spark.sql("SET spark.sql.sources.default=org.apache.spark.sql.json") actual = self.spark.read.load(path=tmpPath) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) self.spark.sql("SET spark.sql.sources.default=" + defaultDataSourceName) csvpath = os.path.join(tempfile.mkdtemp(), 'data') df.write.option('quote', None).format('csv').save(csvpath) shutil.rmtree(tmpPath) def test_save_and_load_builder(self): df = self.df tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) df.write.json(tmpPath) actual = self.spark.read.json(tmpPath) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) schema = StructType([StructField("value", StringType(), True)]) actual = self.spark.read.json(tmpPath, schema) self.assertEqual(sorted(df.select("value").collect()), sorted(actual.collect())) df.write.mode("overwrite").json(tmpPath) actual = self.spark.read.json(tmpPath) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) df.write.mode("overwrite").options(noUse="this options will not be used in save.")\ .option("noUse", "this option will not be used in save.")\ .format("json").save(path=tmpPath) actual =\ self.spark.read.format("json")\ .load(path=tmpPath, noUse="this options will not be used in load.") self.assertEqual(sorted(df.collect()), sorted(actual.collect())) defaultDataSourceName = self.spark.conf.get("spark.sql.sources.default", "org.apache.spark.sql.parquet") self.spark.sql("SET spark.sql.sources.default=org.apache.spark.sql.json") actual = self.spark.read.load(path=tmpPath) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) self.spark.sql("SET spark.sql.sources.default=" + defaultDataSourceName) shutil.rmtree(tmpPath) def test_stream_trigger(self): df = self.spark.readStream.format('text').load('python/test_support/sql/streaming') # Should take at least one arg try: df.writeStream.trigger() except ValueError: pass # Should not take multiple args try: df.writeStream.trigger(once=True, processingTime='5 seconds') except ValueError: pass # Should take only keyword args try: df.writeStream.trigger('5 seconds') self.fail("Should have thrown an exception") except TypeError: pass def test_stream_read_options(self): schema = StructType([StructField("data", StringType(), False)]) df = self.spark.readStream\ .format('text')\ .option('path', 'python/test_support/sql/streaming')\ .schema(schema)\ .load() self.assertTrue(df.isStreaming) self.assertEqual(df.schema.simpleString(), "struct<data:string>") def test_stream_read_options_overwrite(self): bad_schema = StructType([StructField("test", IntegerType(), False)]) schema = StructType([StructField("data", StringType(), False)]) df = self.spark.readStream.format('csv').option('path', 'python/test_support/sql/fake') \ .schema(bad_schema)\ .load(path='python/test_support/sql/streaming', schema=schema, format='text') self.assertTrue(df.isStreaming) self.assertEqual(df.schema.simpleString(), "struct<data:string>") def test_stream_save_options(self): df = self.spark.readStream.format('text').load('python/test_support/sql/streaming') \ .withColumn('id', lit(1)) for q in self.spark._wrapped.streams.active: q.stop() tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) self.assertTrue(df.isStreaming) out = os.path.join(tmpPath, 'out') chk = os.path.join(tmpPath, 'chk') q = df.writeStream.option('checkpointLocation', chk).queryName('this_query') \ .format('parquet').partitionBy('id').outputMode('append').option('path', out).start() try: self.assertEqual(q.name, 'this_query') self.assertTrue(q.isActive) q.processAllAvailable() output_files = [] for _, _, files in os.walk(out): output_files.extend([f for f in files if not f.startswith('.')]) self.assertTrue(len(output_files) > 0) self.assertTrue(len(os.listdir(chk)) > 0) finally: q.stop() shutil.rmtree(tmpPath) def test_stream_save_options_overwrite(self): df = self.spark.readStream.format('text').load('python/test_support/sql/streaming') for q in self.spark._wrapped.streams.active: q.stop() tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) self.assertTrue(df.isStreaming) out = os.path.join(tmpPath, 'out') chk = os.path.join(tmpPath, 'chk') fake1 = os.path.join(tmpPath, 'fake1') fake2 = os.path.join(tmpPath, 'fake2') q = df.writeStream.option('checkpointLocation', fake1)\ .format('memory').option('path', fake2) \ .queryName('fake_query').outputMode('append') \ .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk) try: self.assertEqual(q.name, 'this_query') self.assertTrue(q.isActive) q.processAllAvailable() output_files = [] for _, _, files in os.walk(out): output_files.extend([f for f in files if not f.startswith('.')]) self.assertTrue(len(output_files) > 0) self.assertTrue(len(os.listdir(chk)) > 0) self.assertFalse(os.path.isdir(fake1)) # should not have been created self.assertFalse(os.path.isdir(fake2)) # should not have been created finally: q.stop() shutil.rmtree(tmpPath) def test_stream_status_and_progress(self): df = self.spark.readStream.format('text').load('python/test_support/sql/streaming') for q in self.spark._wrapped.streams.active: q.stop() tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) self.assertTrue(df.isStreaming) out = os.path.join(tmpPath, 'out') chk = os.path.join(tmpPath, 'chk') def func(x): time.sleep(1) return x from pyspark.sql.functions import col, udf sleep_udf = udf(func) # Use "sleep_udf" to delay the progress update so that we can test `lastProgress` when there # were no updates. q = df.select(sleep_udf(col("value")).alias('value')).writeStream \ .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk) try: # "lastProgress" will return None in most cases. However, as it may be flaky when # Jenkins is very slow, we don't assert it. If there is something wrong, "lastProgress" # may throw error with a high chance and make this test flaky, so we should still be # able to detect broken codes. q.lastProgress q.processAllAvailable() lastProgress = q.lastProgress recentProgress = q.recentProgress status = q.status self.assertEqual(lastProgress['name'], q.name) self.assertEqual(lastProgress['id'], q.id) self.assertTrue(any(p == lastProgress for p in recentProgress)) self.assertTrue( "message" in status and "isDataAvailable" in status and "isTriggerActive" in status) finally: q.stop() shutil.rmtree(tmpPath) def test_stream_await_termination(self): df = self.spark.readStream.format('text').load('python/test_support/sql/streaming') for q in self.spark._wrapped.streams.active: q.stop() tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) self.assertTrue(df.isStreaming) out = os.path.join(tmpPath, 'out') chk = os.path.join(tmpPath, 'chk') q = df.writeStream\ .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk) try: self.assertTrue(q.isActive) try: q.awaitTermination("hello") self.fail("Expected a value exception") except ValueError: pass now = time.time() # test should take at least 2 seconds res = q.awaitTermination(2.6) duration = time.time() - now self.assertTrue(duration >= 2) self.assertFalse(res) finally: q.stop() shutil.rmtree(tmpPath) def test_stream_exception(self): sdf = self.spark.readStream.format('text').load('python/test_support/sql/streaming') sq = sdf.writeStream.format('memory').queryName('query_explain').start() try: sq.processAllAvailable() self.assertEqual(sq.exception(), None) finally: sq.stop() from pyspark.sql.functions import col, udf from pyspark.sql.utils import StreamingQueryException bad_udf = udf(lambda x: 1 / 0) sq = sdf.select(bad_udf(col("value")))\ .writeStream\ .format('memory')\ .queryName('this_query')\ .start() try: # Process some data to fail the query sq.processAllAvailable() self.fail("bad udf should fail the query") except StreamingQueryException as e: # This is expected self.assertTrue("ZeroDivisionError" in e.desc) finally: sq.stop() self.assertTrue(type(sq.exception()) is StreamingQueryException) self.assertTrue("ZeroDivisionError" in sq.exception().desc) def test_query_manager_await_termination(self): df = self.spark.readStream.format('text').load('python/test_support/sql/streaming') for q in self.spark._wrapped.streams.active: q.stop() tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) self.assertTrue(df.isStreaming) out = os.path.join(tmpPath, 'out') chk = os.path.join(tmpPath, 'chk') q = df.writeStream\ .start(path=out, format='parquet', queryName='this_query', checkpointLocation=chk) try: self.assertTrue(q.isActive) try: self.spark._wrapped.streams.awaitAnyTermination("hello") self.fail("Expected a value exception") except ValueError: pass now = time.time() # test should take at least 2 seconds res = self.spark._wrapped.streams.awaitAnyTermination(2.6) duration = time.time() - now self.assertTrue(duration >= 2) self.assertFalse(res) finally: q.stop() shutil.rmtree(tmpPath) def test_help_command(self): # Regression test for SPARK-5464 rdd = self.sc.parallelize(['{"foo":"bar"}', '{"foo":"baz"}']) df = self.spark.read.json(rdd) # render_doc() reproduces the help() exception without printing output pydoc.render_doc(df) pydoc.render_doc(df.foo) pydoc.render_doc(df.take(1)) def test_access_column(self): df = self.df self.assertTrue(isinstance(df.key, Column)) self.assertTrue(isinstance(df['key'], Column)) self.assertTrue(isinstance(df[0], Column)) self.assertRaises(IndexError, lambda: df[2]) self.assertRaises(AnalysisException, lambda: df["bad_key"]) self.assertRaises(TypeError, lambda: df[{}]) def test_column_name_with_non_ascii(self): if sys.version >= '3': columnName = "数量" self.assertTrue(isinstance(columnName, str)) else: columnName = unicode("数量", "utf-8") self.assertTrue(isinstance(columnName, unicode)) schema = StructType([StructField(columnName, LongType(), True)]) df = self.spark.createDataFrame([(1,)], schema) self.assertEqual(schema, df.schema) self.assertEqual("DataFrame[数量: bigint]", str(df)) self.assertEqual([("数量", 'bigint')], df.dtypes) self.assertEqual(1, df.select("数量").first()[0]) self.assertEqual(1, df.select(df["数量"]).first()[0]) def test_access_nested_types(self): df = self.sc.parallelize([Row(l=[1], r=Row(a=1, b="b"), d={"k": "v"})]).toDF() self.assertEqual(1, df.select(df.l[0]).first()[0]) self.assertEqual(1, df.select(df.l.getItem(0)).first()[0]) self.assertEqual(1, df.select(df.r.a).first()[0]) self.assertEqual("b", df.select(df.r.getField("b")).first()[0]) self.assertEqual("v", df.select(df.d["k"]).first()[0]) self.assertEqual("v", df.select(df.d.getItem("k")).first()[0]) def test_field_accessor(self): df = self.sc.parallelize([Row(l=[1], r=Row(a=1, b="b"), d={"k": "v"})]).toDF() self.assertEqual(1, df.select(df.l[0]).first()[0]) self.assertEqual(1, df.select(df.r["a"]).first()[0]) self.assertEqual(1, df.select(df["r.a"]).first()[0]) self.assertEqual("b", df.select(df.r["b"]).first()[0]) self.assertEqual("b", df.select(df["r.b"]).first()[0]) self.assertEqual("v", df.select(df.d["k"]).first()[0]) def test_infer_long_type(self): longrow = [Row(f1='a', f2=100000000000000)] df = self.sc.parallelize(longrow).toDF() self.assertEqual(df.schema.fields[1].dataType, LongType()) # this saving as Parquet caused issues as well. output_dir = os.path.join(self.tempdir.name, "infer_long_type") df.write.parquet(output_dir) df1 = self.spark.read.parquet(output_dir) self.assertEqual('a', df1.first().f1) self.assertEqual(100000000000000, df1.first().f2) self.assertEqual(_infer_type(1), LongType()) self.assertEqual(_infer_type(2**10), LongType()) self.assertEqual(_infer_type(2**20), LongType()) self.assertEqual(_infer_type(2**31 - 1), LongType()) self.assertEqual(_infer_type(2**31), LongType()) self.assertEqual(_infer_type(2**61), LongType()) self.assertEqual(_infer_type(2**71), LongType()) def test_filter_with_datetime(self): time = datetime.datetime(2015, 4, 17, 23, 1, 2, 3000) date = time.date() row = Row(date=date, time=time) df = self.spark.createDataFrame([row]) self.assertEqual(1, df.filter(df.date == date).count()) self.assertEqual(1, df.filter(df.time == time).count()) self.assertEqual(0, df.filter(df.date > date).count()) self.assertEqual(0, df.filter(df.time > time).count()) def test_filter_with_datetime_timezone(self): dt1 = datetime.datetime(2015, 4, 17, 23, 1, 2, 3000, tzinfo=UTCOffsetTimezone(0)) dt2 = datetime.datetime(2015, 4, 17, 23, 1, 2, 3000, tzinfo=UTCOffsetTimezone(1)) row = Row(date=dt1) df = self.spark.createDataFrame([row]) self.assertEqual(0, df.filter(df.date == dt2).count()) self.assertEqual(1, df.filter(df.date > dt2).count()) self.assertEqual(0, df.filter(df.date < dt2).count()) def test_time_with_timezone(self): day = datetime.date.today() now = datetime.datetime.now() ts = time.mktime(now.timetuple()) # class in __main__ is not serializable from pyspark.sql.tests import UTCOffsetTimezone utc = UTCOffsetTimezone() utcnow = datetime.datetime.utcfromtimestamp(ts) # without microseconds # add microseconds to utcnow (keeping year,month,day,hour,minute,second) utcnow = datetime.datetime(*(utcnow.timetuple()[:6] + (now.microsecond, utc))) df = self.spark.createDataFrame([(day, now, utcnow)]) day1, now1, utcnow1 = df.first() self.assertEqual(day1, day) self.assertEqual(now, now1) self.assertEqual(now, utcnow1) # regression test for SPARK-19561 def test_datetime_at_epoch(self): epoch = datetime.datetime.fromtimestamp(0) df = self.spark.createDataFrame([Row(date=epoch)]) first = df.select('date', lit(epoch).alias('lit_date')).first() self.assertEqual(first['date'], epoch) self.assertEqual(first['lit_date'], epoch) def test_decimal(self): from decimal import Decimal schema = StructType([StructField("decimal", DecimalType(10, 5))]) df = self.spark.createDataFrame([(Decimal("3.14159"),)], schema) row = df.select(df.decimal + 1).first() self.assertEqual(row[0], Decimal("4.14159")) tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) df.write.parquet(tmpPath) df2 = self.spark.read.parquet(tmpPath) row = df2.first() self.assertEqual(row[0], Decimal("3.14159")) def test_dropna(self): schema = StructType([ StructField("name", StringType(), True), StructField("age", IntegerType(), True), StructField("height", DoubleType(), True)]) # shouldn't drop a non-null row self.assertEqual(self.spark.createDataFrame( [(u'Alice', 50, 80.1)], schema).dropna().count(), 1) # dropping rows with a single null value self.assertEqual(self.spark.createDataFrame( [(u'Alice', None, 80.1)], schema).dropna().count(), 0) self.assertEqual(self.spark.createDataFrame( [(u'Alice', None, 80.1)], schema).dropna(how='any').count(), 0) # if how = 'all', only drop rows if all values are null self.assertEqual(self.spark.createDataFrame( [(u'Alice', None, 80.1)], schema).dropna(how='all').count(), 1) self.assertEqual(self.spark.createDataFrame( [(None, None, None)], schema).dropna(how='all').count(), 0) # how and subset self.assertEqual(self.spark.createDataFrame( [(u'Alice', 50, None)], schema).dropna(how='any', subset=['name', 'age']).count(), 1) self.assertEqual(self.spark.createDataFrame( [(u'Alice', None, None)], schema).dropna(how='any', subset=['name', 'age']).count(), 0) # threshold self.assertEqual(self.spark.createDataFrame( [(u'Alice', None, 80.1)], schema).dropna(thresh=2).count(), 1) self.assertEqual(self.spark.createDataFrame( [(u'Alice', None, None)], schema).dropna(thresh=2).count(), 0) # threshold and subset self.assertEqual(self.spark.createDataFrame( [(u'Alice', 50, None)], schema).dropna(thresh=2, subset=['name', 'age']).count(), 1) self.assertEqual(self.spark.createDataFrame( [(u'Alice', None, 180.9)], schema).dropna(thresh=2, subset=['name', 'age']).count(), 0) # thresh should take precedence over how self.assertEqual(self.spark.createDataFrame( [(u'Alice', 50, None)], schema).dropna( how='any', thresh=2, subset=['name', 'age']).count(), 1) def test_fillna(self): schema = StructType([ StructField("name", StringType(), True), StructField("age", IntegerType(), True), StructField("height", DoubleType(), True)]) # fillna shouldn't change non-null values row = self.spark.createDataFrame([(u'Alice', 10, 80.1)], schema).fillna(50).first() self.assertEqual(row.age, 10) # fillna with int row = self.spark.createDataFrame([(u'Alice', None, None)], schema).fillna(50).first() self.assertEqual(row.age, 50) self.assertEqual(row.height, 50.0) # fillna with double row = self.spark.createDataFrame([(u'Alice', None, None)], schema).fillna(50.1).first() self.assertEqual(row.age, 50) self.assertEqual(row.height, 50.1) # fillna with string row = self.spark.createDataFrame([(None, None, None)], schema).fillna("hello").first() self.assertEqual(row.name, u"hello") self.assertEqual(row.age, None) # fillna with subset specified for numeric cols row = self.spark.createDataFrame( [(None, None, None)], schema).fillna(50, subset=['name', 'age']).first() self.assertEqual(row.name, None) self.assertEqual(row.age, 50) self.assertEqual(row.height, None) # fillna with subset specified for numeric cols row = self.spark.createDataFrame( [(None, None, None)], schema).fillna("haha", subset=['name', 'age']).first() self.assertEqual(row.name, "haha") self.assertEqual(row.age, None) self.assertEqual(row.height, None) # fillna with dictionary for boolean types row = self.spark.createDataFrame([Row(a=None), Row(a=True)]).fillna({"a": True}).first() self.assertEqual(row.a, True) def test_bitwise_operations(self): from pyspark.sql import functions row = Row(a=170, b=75) df = self.spark.createDataFrame([row]) result = df.select(df.a.bitwiseAND(df.b)).collect()[0].asDict() self.assertEqual(170 & 75, result['(a & b)']) result = df.select(df.a.bitwiseOR(df.b)).collect()[0].asDict() self.assertEqual(170 | 75, result['(a | b)']) result = df.select(df.a.bitwiseXOR(df.b)).collect()[0].asDict() self.assertEqual(170 ^ 75, result['(a ^ b)']) result = df.select(functions.bitwiseNOT(df.b)).collect()[0].asDict() self.assertEqual(~75, result['~b']) def test_expr(self): from pyspark.sql import functions row = Row(a="length string", b=75) df = self.spark.createDataFrame([row]) result = df.select(functions.expr("length(a)")).collect()[0].asDict() self.assertEqual(13, result["length(a)"]) def test_replace(self): schema = StructType([ StructField("name", StringType(), True), StructField("age", IntegerType(), True), StructField("height", DoubleType(), True)]) # replace with int row = self.spark.createDataFrame([(u'Alice', 10, 10.0)], schema).replace(10, 20).first() self.assertEqual(row.age, 20) self.assertEqual(row.height, 20.0) # replace with double row = self.spark.createDataFrame( [(u'Alice', 80, 80.0)], schema).replace(80.0, 82.1).first() self.assertEqual(row.age, 82) self.assertEqual(row.height, 82.1) # replace with string row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace(u'Alice', u'Ann').first() self.assertEqual(row.name, u"Ann") self.assertEqual(row.age, 10) # replace with subset specified by a string of a column name w/ actual change row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace(10, 20, subset='age').first() self.assertEqual(row.age, 20) # replace with subset specified by a string of a column name w/o actual change row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace(10, 20, subset='height').first() self.assertEqual(row.age, 10) # replace with subset specified with one column replaced, another column not in subset # stays unchanged. row = self.spark.createDataFrame( [(u'Alice', 10, 10.0)], schema).replace(10, 20, subset=['name', 'age']).first() self.assertEqual(row.name, u'Alice') self.assertEqual(row.age, 20) self.assertEqual(row.height, 10.0) # replace with subset specified but no column will be replaced row = self.spark.createDataFrame( [(u'Alice', 10, None)], schema).replace(10, 20, subset=['name', 'height']).first() self.assertEqual(row.name, u'Alice') self.assertEqual(row.age, 10) self.assertEqual(row.height, None) # replace with lists row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace([u'Alice'], [u'Ann']).first() self.assertTupleEqual(row, (u'Ann', 10, 80.1)) # replace with dict row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace({10: 11}).first() self.assertTupleEqual(row, (u'Alice', 11, 80.1)) # test backward compatibility with dummy value dummy_value = 1 row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace({'Alice': 'Bob'}, dummy_value).first() self.assertTupleEqual(row, (u'Bob', 10, 80.1)) # test dict with mixed numerics row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace({10: -10, 80.1: 90.5}).first() self.assertTupleEqual(row, (u'Alice', -10, 90.5)) # replace with tuples row = self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace((u'Alice', ), (u'Bob', )).first() self.assertTupleEqual(row, (u'Bob', 10, 80.1)) # replace multiple columns row = self.spark.createDataFrame( [(u'Alice', 10, 80.0)], schema).replace((10, 80.0), (20, 90)).first() self.assertTupleEqual(row, (u'Alice', 20, 90.0)) # test for mixed numerics row = self.spark.createDataFrame( [(u'Alice', 10, 80.0)], schema).replace((10, 80), (20, 90.5)).first() self.assertTupleEqual(row, (u'Alice', 20, 90.5)) row = self.spark.createDataFrame( [(u'Alice', 10, 80.0)], schema).replace({10: 20, 80: 90.5}).first() self.assertTupleEqual(row, (u'Alice', 20, 90.5)) # replace with boolean row = (self .spark.createDataFrame([(u'Alice', 10, 80.0)], schema) .selectExpr("name = 'Bob'", 'age <= 15') .replace(False, True).first()) self.assertTupleEqual(row, (True, True)) # should fail if subset is not list, tuple or None with self.assertRaises(ValueError): self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace({10: 11}, subset=1).first() # should fail if to_replace and value have different length with self.assertRaises(ValueError): self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace(["Alice", "Bob"], ["Eve"]).first() # should fail if when received unexpected type with self.assertRaises(ValueError): from datetime import datetime self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace(datetime.now(), datetime.now()).first() # should fail if provided mixed type replacements with self.assertRaises(ValueError): self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace(["Alice", 10], ["Eve", 20]).first() with self.assertRaises(ValueError): self.spark.createDataFrame( [(u'Alice', 10, 80.1)], schema).replace({u"Alice": u"Bob", 10: 20}).first() def test_capture_analysis_exception(self): self.assertRaises(AnalysisException, lambda: self.spark.sql("select abc")) self.assertRaises(AnalysisException, lambda: self.df.selectExpr("a + b")) def test_capture_parse_exception(self): self.assertRaises(ParseException, lambda: self.spark.sql("abc")) def test_capture_illegalargument_exception(self): self.assertRaisesRegexp(IllegalArgumentException, "Setting negative mapred.reduce.tasks", lambda: self.spark.sql("SET mapred.reduce.tasks=-1")) df = self.spark.createDataFrame([(1, 2)], ["a", "b"]) self.assertRaisesRegexp(IllegalArgumentException, "1024 is not in the permitted values", lambda: df.select(sha2(df.a, 1024)).collect()) try: df.select(sha2(df.a, 1024)).collect() except IllegalArgumentException as e: self.assertRegexpMatches(e.desc, "1024 is not in the permitted values") self.assertRegexpMatches(e.stackTrace, "org.apache.spark.sql.functions") def test_with_column_with_existing_name(self): keys = self.df.withColumn("key", self.df.key).select("key").collect() self.assertEqual([r.key for r in keys], list(range(100))) # regression test for SPARK-10417 def test_column_iterator(self): def foo(): for x in self.df.key: break self.assertRaises(TypeError, foo) # add test for SPARK-10577 (test broadcast join hint) def test_functions_broadcast(self): from pyspark.sql.functions import broadcast df1 = self.spark.createDataFrame([(1, "1"), (2, "2")], ("key", "value")) df2 = self.spark.createDataFrame([(1, "1"), (2, "2")], ("key", "value")) # equijoin - should be converted into broadcast join plan1 = df1.join(broadcast(df2), "key")._jdf.queryExecution().executedPlan() self.assertEqual(1, plan1.toString().count("BroadcastHashJoin")) # no join key -- should not be a broadcast join plan2 = df1.crossJoin(broadcast(df2))._jdf.queryExecution().executedPlan() self.assertEqual(0, plan2.toString().count("BroadcastHashJoin")) # planner should not crash without a join broadcast(df1)._jdf.queryExecution().executedPlan() def test_generic_hints(self): from pyspark.sql import DataFrame df1 = self.spark.range(10e10).toDF("id") df2 = self.spark.range(10e10).toDF("id") self.assertIsInstance(df1.hint("broadcast"), DataFrame) self.assertIsInstance(df1.hint("broadcast", []), DataFrame) # Dummy rules self.assertIsInstance(df1.hint("broadcast", "foo", "bar"), DataFrame) self.assertIsInstance(df1.hint("broadcast", ["foo", "bar"]), DataFrame) plan = df1.join(df2.hint("broadcast"), "id")._jdf.queryExecution().executedPlan() self.assertEqual(1, plan.toString().count("BroadcastHashJoin")) def test_toDF_with_schema_string(self): data = [Row(key=i, value=str(i)) for i in range(100)] rdd = self.sc.parallelize(data, 5) df = rdd.toDF("key: int, value: string") self.assertEqual(df.schema.simpleString(), "struct<key:int,value:string>") self.assertEqual(df.collect(), data) # different but compatible field types can be used. df = rdd.toDF("key: string, value: string") self.assertEqual(df.schema.simpleString(), "struct<key:string,value:string>") self.assertEqual(df.collect(), [Row(key=str(i), value=str(i)) for i in range(100)]) # field names can differ. df = rdd.toDF(" a: int, b: string ") self.assertEqual(df.schema.simpleString(), "struct<a:int,b:string>") self.assertEqual(df.collect(), data) # number of fields must match. self.assertRaisesRegexp(Exception, "Length of object", lambda: rdd.toDF("key: int").collect()) # field types mismatch will cause exception at runtime. self.assertRaisesRegexp(Exception, "FloatType can not accept", lambda: rdd.toDF("key: float, value: string").collect()) # flat schema values will be wrapped into row. df = rdd.map(lambda row: row.key).toDF("int") self.assertEqual(df.schema.simpleString(), "struct<value:int>") self.assertEqual(df.collect(), [Row(key=i) for i in range(100)]) # users can use DataType directly instead of data type string. df = rdd.map(lambda row: row.key).toDF(IntegerType()) self.assertEqual(df.schema.simpleString(), "struct<value:int>") self.assertEqual(df.collect(), [Row(key=i) for i in range(100)]) # Regression test for invalid join methods when on is None, Spark-14761 def test_invalid_join_method(self): df1 = self.spark.createDataFrame([("Alice", 5), ("Bob", 8)], ["name", "age"]) df2 = self.spark.createDataFrame([("Alice", 80), ("Bob", 90)], ["name", "height"]) self.assertRaises(IllegalArgumentException, lambda: df1.join(df2, how="invalid-join-type")) # Cartesian products require cross join syntax def test_require_cross(self): from pyspark.sql.functions import broadcast df1 = self.spark.createDataFrame([(1, "1")], ("key", "value")) df2 = self.spark.createDataFrame([(1, "1")], ("key", "value")) # joins without conditions require cross join syntax self.assertRaises(AnalysisException, lambda: df1.join(df2).collect()) # works with crossJoin self.assertEqual(1, df1.crossJoin(df2).count()) def test_conf(self): spark = self.spark spark.conf.set("bogo", "sipeo") self.assertEqual(spark.conf.get("bogo"), "sipeo") spark.conf.set("bogo", "ta") self.assertEqual(spark.conf.get("bogo"), "ta") self.assertEqual(spark.conf.get("bogo", "not.read"), "ta") self.assertEqual(spark.conf.get("not.set", "ta"), "ta") self.assertRaisesRegexp(Exception, "not.set", lambda: spark.conf.get("not.set")) spark.conf.unset("bogo") self.assertEqual(spark.conf.get("bogo", "colombia"), "colombia") def test_current_database(self): spark = self.spark spark.catalog._reset() self.assertEquals(spark.catalog.currentDatabase(), "default") spark.sql("CREATE DATABASE some_db") spark.catalog.setCurrentDatabase("some_db") self.assertEquals(spark.catalog.currentDatabase(), "some_db") self.assertRaisesRegexp( AnalysisException, "does_not_exist", lambda: spark.catalog.setCurrentDatabase("does_not_exist")) def test_list_databases(self): spark = self.spark spark.catalog._reset() databases = [db.name for db in spark.catalog.listDatabases()] self.assertEquals(databases, ["default"]) spark.sql("CREATE DATABASE some_db") databases = [db.name for db in spark.catalog.listDatabases()] self.assertEquals(sorted(databases), ["default", "some_db"]) def test_list_tables(self): from pyspark.sql.catalog import Table spark = self.spark spark.catalog._reset() spark.sql("CREATE DATABASE some_db") self.assertEquals(spark.catalog.listTables(), []) self.assertEquals(spark.catalog.listTables("some_db"), []) spark.createDataFrame([(1, 1)]).createOrReplaceTempView("temp_tab") spark.sql("CREATE TABLE tab1 (name STRING, age INT) USING parquet") spark.sql("CREATE TABLE some_db.tab2 (name STRING, age INT) USING parquet") tables = sorted(spark.catalog.listTables(), key=lambda t: t.name) tablesDefault = sorted(spark.catalog.listTables("default"), key=lambda t: t.name) tablesSomeDb = sorted(spark.catalog.listTables("some_db"), key=lambda t: t.name) self.assertEquals(tables, tablesDefault) self.assertEquals(len(tables), 2) self.assertEquals(len(tablesSomeDb), 2) self.assertEquals(tables[0], Table( name="tab1", database="default", description=None, tableType="MANAGED", isTemporary=False)) self.assertEquals(tables[1], Table( name="temp_tab", database=None, description=None, tableType="TEMPORARY", isTemporary=True)) self.assertEquals(tablesSomeDb[0], Table( name="tab2", database="some_db", description=None, tableType="MANAGED", isTemporary=False)) self.assertEquals(tablesSomeDb[1], Table( name="temp_tab", database=None, description=None, tableType="TEMPORARY", isTemporary=True)) self.assertRaisesRegexp( AnalysisException, "does_not_exist", lambda: spark.catalog.listTables("does_not_exist")) def test_list_functions(self): from pyspark.sql.catalog import Function spark = self.spark spark.catalog._reset() spark.sql("CREATE DATABASE some_db") functions = dict((f.name, f) for f in spark.catalog.listFunctions()) functionsDefault = dict((f.name, f) for f in spark.catalog.listFunctions("default")) self.assertTrue(len(functions) > 200) self.assertTrue("+" in functions) self.assertTrue("like" in functions) self.assertTrue("month" in functions) self.assertTrue("to_date" in functions) self.assertTrue("to_timestamp" in functions) self.assertTrue("to_unix_timestamp" in functions) self.assertTrue("current_database" in functions) self.assertEquals(functions["+"], Function( name="+", description=None, className="org.apache.spark.sql.catalyst.expressions.Add", isTemporary=True)) self.assertEquals(functions, functionsDefault) spark.catalog.registerFunction("temp_func", lambda x: str(x)) spark.sql("CREATE FUNCTION func1 AS 'org.apache.spark.data.bricks'") spark.sql("CREATE FUNCTION some_db.func2 AS 'org.apache.spark.data.bricks'") newFunctions = dict((f.name, f) for f in spark.catalog.listFunctions()) newFunctionsSomeDb = dict((f.name, f) for f in spark.catalog.listFunctions("some_db")) self.assertTrue(set(functions).issubset(set(newFunctions))) self.assertTrue(set(functions).issubset(set(newFunctionsSomeDb))) self.assertTrue("temp_func" in newFunctions) self.assertTrue("func1" in newFunctions) self.assertTrue("func2" not in newFunctions) self.assertTrue("temp_func" in newFunctionsSomeDb) self.assertTrue("func1" not in newFunctionsSomeDb) self.assertTrue("func2" in newFunctionsSomeDb) self.assertRaisesRegexp( AnalysisException, "does_not_exist", lambda: spark.catalog.listFunctions("does_not_exist")) def test_list_columns(self): from pyspark.sql.catalog import Column spark = self.spark spark.catalog._reset() spark.sql("CREATE DATABASE some_db") spark.sql("CREATE TABLE tab1 (name STRING, age INT) USING parquet") spark.sql("CREATE TABLE some_db.tab2 (nickname STRING, tolerance FLOAT) USING parquet") columns = sorted(spark.catalog.listColumns("tab1"), key=lambda c: c.name) columnsDefault = sorted(spark.catalog.listColumns("tab1", "default"), key=lambda c: c.name) self.assertEquals(columns, columnsDefault) self.assertEquals(len(columns), 2) self.assertEquals(columns[0], Column( name="age", description=None, dataType="int", nullable=True, isPartition=False, isBucket=False)) self.assertEquals(columns[1], Column( name="name", description=None, dataType="string", nullable=True, isPartition=False, isBucket=False)) columns2 = sorted(spark.catalog.listColumns("tab2", "some_db"), key=lambda c: c.name) self.assertEquals(len(columns2), 2) self.assertEquals(columns2[0], Column( name="nickname", description=None, dataType="string", nullable=True, isPartition=False, isBucket=False)) self.assertEquals(columns2[1], Column( name="tolerance", description=None, dataType="float", nullable=True, isPartition=False, isBucket=False)) self.assertRaisesRegexp( AnalysisException, "tab2", lambda: spark.catalog.listColumns("tab2")) self.assertRaisesRegexp( AnalysisException, "does_not_exist", lambda: spark.catalog.listColumns("does_not_exist")) def test_cache(self): spark = self.spark spark.createDataFrame([(2, 2), (3, 3)]).createOrReplaceTempView("tab1") spark.createDataFrame([(2, 2), (3, 3)]).createOrReplaceTempView("tab2") self.assertFalse(spark.catalog.isCached("tab1")) self.assertFalse(spark.catalog.isCached("tab2")) spark.catalog.cacheTable("tab1") self.assertTrue(spark.catalog.isCached("tab1")) self.assertFalse(spark.catalog.isCached("tab2")) spark.catalog.cacheTable("tab2") spark.catalog.uncacheTable("tab1") self.assertFalse(spark.catalog.isCached("tab1")) self.assertTrue(spark.catalog.isCached("tab2")) spark.catalog.clearCache() self.assertFalse(spark.catalog.isCached("tab1")) self.assertFalse(spark.catalog.isCached("tab2")) self.assertRaisesRegexp( AnalysisException, "does_not_exist", lambda: spark.catalog.isCached("does_not_exist")) self.assertRaisesRegexp( AnalysisException, "does_not_exist", lambda: spark.catalog.cacheTable("does_not_exist")) self.assertRaisesRegexp( AnalysisException, "does_not_exist", lambda: spark.catalog.uncacheTable("does_not_exist")) def test_read_text_file_list(self): df = self.spark.read.text(['python/test_support/sql/text-test.txt', 'python/test_support/sql/text-test.txt']) count = df.count() self.assertEquals(count, 4) def test_BinaryType_serialization(self): # Pyrolite version <= 4.9 could not serialize BinaryType with Python3 SPARK-17808 schema = StructType([StructField('mybytes', BinaryType())]) data = [[bytearray(b'here is my data')], [bytearray(b'and here is some more')]] df = self.spark.createDataFrame(data, schema=schema) df.collect() class HiveSparkSubmitTests(SparkSubmitTests): def test_hivecontext(self): # This test checks that HiveContext is using Hive metastore (SPARK-16224). # It sets a metastore url and checks if there is a derby dir created by # Hive metastore. If this derby dir exists, HiveContext is using # Hive metastore. metastore_path = os.path.join(tempfile.mkdtemp(), "spark16224_metastore_db") metastore_URL = "jdbc:derby:;databaseName=" + metastore_path + ";create=true" hive_site_dir = os.path.join(self.programDir, "conf") hive_site_file = self.createTempFile("hive-site.xml", (""" |<configuration> | <property> | <name>javax.jdo.option.ConnectionURL</name> | <value>%s</value> | </property> |</configuration> """ % metastore_URL).lstrip(), "conf") script = self.createTempFile("test.py", """ |import os | |from pyspark.conf import SparkConf |from pyspark.context import SparkContext |from pyspark.sql import HiveContext | |conf = SparkConf() |sc = SparkContext(conf=conf) |hive_context = HiveContext(sc) |print(hive_context.sql("show databases").collect()) """) proc = subprocess.Popen( [self.sparkSubmit, "--master", "local-cluster[1,1,1024]", "--driver-class-path", hive_site_dir, script], stdout=subprocess.PIPE) out, err = proc.communicate() self.assertEqual(0, proc.returncode) self.assertIn("default", out.decode('utf-8')) self.assertTrue(os.path.exists(metastore_path)) class SQLTests2(ReusedPySparkTestCase): @classmethod def setUpClass(cls): ReusedPySparkTestCase.setUpClass() cls.spark = SparkSession(cls.sc) @classmethod def tearDownClass(cls): ReusedPySparkTestCase.tearDownClass() cls.spark.stop() # We can't include this test into SQLTests because we will stop class's SparkContext and cause # other tests failed. def test_sparksession_with_stopped_sparkcontext(self): self.sc.stop() sc = SparkContext('local[4]', self.sc.appName) spark = SparkSession.builder.getOrCreate() df = spark.createDataFrame([(1, 2)], ["c", "c"]) df.collect() class UDFInitializationTests(unittest.TestCase): def tearDown(self): if SparkSession._instantiatedSession is not None: SparkSession._instantiatedSession.stop() if SparkContext._active_spark_context is not None: SparkContext._active_spark_contex.stop() def test_udf_init_shouldnt_initalize_context(self): from pyspark.sql.functions import UserDefinedFunction UserDefinedFunction(lambda x: x, StringType()) self.assertIsNone( SparkContext._active_spark_context, "SparkContext shouldn't be initialized when UserDefinedFunction is created." ) self.assertIsNone( SparkSession._instantiatedSession, "SparkSession shouldn't be initialized when UserDefinedFunction is created." ) class HiveContextSQLTests(ReusedPySparkTestCase): @classmethod def setUpClass(cls): ReusedPySparkTestCase.setUpClass() cls.tempdir = tempfile.NamedTemporaryFile(delete=False) try: cls.sc._jvm.org.apache.hadoop.hive.conf.HiveConf() except py4j.protocol.Py4JError: cls.tearDownClass() raise unittest.SkipTest("Hive is not available") except TypeError: cls.tearDownClass() raise unittest.SkipTest("Hive is not available") os.unlink(cls.tempdir.name) cls.spark = HiveContext._createForTesting(cls.sc) cls.testData = [Row(key=i, value=str(i)) for i in range(100)] cls.df = cls.sc.parallelize(cls.testData).toDF() @classmethod def tearDownClass(cls): ReusedPySparkTestCase.tearDownClass() shutil.rmtree(cls.tempdir.name, ignore_errors=True) def test_save_and_load_table(self): df = self.df tmpPath = tempfile.mkdtemp() shutil.rmtree(tmpPath) df.write.saveAsTable("savedJsonTable", "json", "append", path=tmpPath) actual = self.spark.createExternalTable("externalJsonTable", tmpPath, "json") self.assertEqual(sorted(df.collect()), sorted(self.spark.sql("SELECT * FROM savedJsonTable").collect())) self.assertEqual(sorted(df.collect()), sorted(self.spark.sql("SELECT * FROM externalJsonTable").collect())) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) self.spark.sql("DROP TABLE externalJsonTable") df.write.saveAsTable("savedJsonTable", "json", "overwrite", path=tmpPath) schema = StructType([StructField("value", StringType(), True)]) actual = self.spark.createExternalTable("externalJsonTable", source="json", schema=schema, path=tmpPath, noUse="this options will not be used") self.assertEqual(sorted(df.collect()), sorted(self.spark.sql("SELECT * FROM savedJsonTable").collect())) self.assertEqual(sorted(df.select("value").collect()), sorted(self.spark.sql("SELECT * FROM externalJsonTable").collect())) self.assertEqual(sorted(df.select("value").collect()), sorted(actual.collect())) self.spark.sql("DROP TABLE savedJsonTable") self.spark.sql("DROP TABLE externalJsonTable") defaultDataSourceName = self.spark.getConf("spark.sql.sources.default", "org.apache.spark.sql.parquet") self.spark.sql("SET spark.sql.sources.default=org.apache.spark.sql.json") df.write.saveAsTable("savedJsonTable", path=tmpPath, mode="overwrite") actual = self.spark.createExternalTable("externalJsonTable", path=tmpPath) self.assertEqual(sorted(df.collect()), sorted(self.spark.sql("SELECT * FROM savedJsonTable").collect())) self.assertEqual(sorted(df.collect()), sorted(self.spark.sql("SELECT * FROM externalJsonTable").collect())) self.assertEqual(sorted(df.collect()), sorted(actual.collect())) self.spark.sql("DROP TABLE savedJsonTable") self.spark.sql("DROP TABLE externalJsonTable") self.spark.sql("SET spark.sql.sources.default=" + defaultDataSourceName) shutil.rmtree(tmpPath) def test_window_functions(self): df = self.spark.createDataFrame([(1, "1"), (2, "2"), (1, "2"), (1, "2")], ["key", "value"]) w = Window.partitionBy("value").orderBy("key") from pyspark.sql import functions as F sel = df.select(df.value, df.key, F.max("key").over(w.rowsBetween(0, 1)), F.min("key").over(w.rowsBetween(0, 1)), F.count("key").over(w.rowsBetween(float('-inf'), float('inf'))), F.row_number().over(w), F.rank().over(w), F.dense_rank().over(w), F.ntile(2).over(w)) rs = sorted(sel.collect()) expected = [ ("1", 1, 1, 1, 1, 1, 1, 1, 1), ("2", 1, 1, 1, 3, 1, 1, 1, 1), ("2", 1, 2, 1, 3, 2, 1, 1, 1), ("2", 2, 2, 2, 3, 3, 3, 2, 2) ] for r, ex in zip(rs, expected): self.assertEqual(tuple(r), ex[:len(r)]) def test_window_functions_without_partitionBy(self): df = self.spark.createDataFrame([(1, "1"), (2, "2"), (1, "2"), (1, "2")], ["key", "value"]) w = Window.orderBy("key", df.value) from pyspark.sql import functions as F sel = df.select(df.value, df.key, F.max("key").over(w.rowsBetween(0, 1)), F.min("key").over(w.rowsBetween(0, 1)), F.count("key").over(w.rowsBetween(float('-inf'), float('inf'))), F.row_number().over(w), F.rank().over(w), F.dense_rank().over(w), F.ntile(2).over(w)) rs = sorted(sel.collect()) expected = [ ("1", 1, 1, 1, 4, 1, 1, 1, 1), ("2", 1, 1, 1, 4, 2, 2, 2, 1), ("2", 1, 2, 1, 4, 3, 2, 2, 2), ("2", 2, 2, 2, 4, 4, 4, 3, 2) ] for r, ex in zip(rs, expected): self.assertEqual(tuple(r), ex[:len(r)]) def test_window_functions_cumulative_sum(self): df = self.spark.createDataFrame([("one", 1), ("two", 2)], ["key", "value"]) from pyspark.sql import functions as F # Test cumulative sum sel = df.select( df.key, F.sum(df.value).over(Window.rowsBetween(Window.unboundedPreceding, 0))) rs = sorted(sel.collect()) expected = [("one", 1), ("two", 3)] for r, ex in zip(rs, expected): self.assertEqual(tuple(r), ex[:len(r)]) # Test boundary values less than JVM's Long.MinValue and make sure we don't overflow sel = df.select( df.key, F.sum(df.value).over(Window.rowsBetween(Window.unboundedPreceding - 1, 0))) rs = sorted(sel.collect()) expected = [("one", 1), ("two", 3)] for r, ex in zip(rs, expected): self.assertEqual(tuple(r), ex[:len(r)]) # Test boundary values greater than JVM's Long.MaxValue and make sure we don't overflow frame_end = Window.unboundedFollowing + 1 sel = df.select( df.key, F.sum(df.value).over(Window.rowsBetween(Window.currentRow, frame_end))) rs = sorted(sel.collect()) expected = [("one", 3), ("two", 2)] for r, ex in zip(rs, expected): self.assertEqual(tuple(r), ex[:len(r)]) def test_collect_functions(self): df = self.spark.createDataFrame([(1, "1"), (2, "2"), (1, "2"), (1, "2")], ["key", "value"]) from pyspark.sql import functions self.assertEqual( sorted(df.select(functions.collect_set(df.key).alias('r')).collect()[0].r), [1, 2]) self.assertEqual( sorted(df.select(functions.collect_list(df.key).alias('r')).collect()[0].r), [1, 1, 1, 2]) self.assertEqual( sorted(df.select(functions.collect_set(df.value).alias('r')).collect()[0].r), ["1", "2"]) self.assertEqual( sorted(df.select(functions.collect_list(df.value).alias('r')).collect()[0].r), ["1", "2", "2", "2"]) def test_limit_and_take(self): df = self.spark.range(1, 1000, numPartitions=10) def assert_runs_only_one_job_stage_and_task(job_group_name, f): tracker = self.sc.statusTracker() self.sc.setJobGroup(job_group_name, description="") f() jobs = tracker.getJobIdsForGroup(job_group_name) self.assertEqual(1, len(jobs)) stages = tracker.getJobInfo(jobs[0]).stageIds self.assertEqual(1, len(stages)) self.assertEqual(1, tracker.getStageInfo(stages[0]).numTasks) # Regression test for SPARK-10731: take should delegate to Scala implementation assert_runs_only_one_job_stage_and_task("take", lambda: df.take(1)) # Regression test for SPARK-17514: limit(n).collect() should the perform same as take(n) assert_runs_only_one_job_stage_and_task("collect_limit", lambda: df.limit(1).collect()) def test_datetime_functions(self): from pyspark.sql import functions from datetime import date, datetime df = self.spark.range(1).selectExpr("'2017-01-22' as dateCol") parse_result = df.select(functions.to_date(functions.col("dateCol"))).first() self.assertEquals(date(2017, 1, 22), parse_result['to_date(dateCol)']) @unittest.skipIf(sys.version_info < (3, 3), "Unittest < 3.3 doesn't support mocking") def test_unbounded_frames(self): from unittest.mock import patch from pyspark.sql import functions as F from pyspark.sql import window import importlib df = self.spark.range(0, 3) def rows_frame_match(): return "ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING" in df.select( F.count("*").over(window.Window.rowsBetween(-sys.maxsize, sys.maxsize)) ).columns[0] def range_frame_match(): return "RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING" in df.select( F.count("*").over(window.Window.rangeBetween(-sys.maxsize, sys.maxsize)) ).columns[0] with patch("sys.maxsize", 2 ** 31 - 1): importlib.reload(window) self.assertTrue(rows_frame_match()) self.assertTrue(range_frame_match()) with patch("sys.maxsize", 2 ** 63 - 1): importlib.reload(window) self.assertTrue(rows_frame_match()) self.assertTrue(range_frame_match()) with patch("sys.maxsize", 2 ** 127 - 1): importlib.reload(window) self.assertTrue(rows_frame_match()) self.assertTrue(range_frame_match()) importlib.reload(window) if __name__ == "__main__": from pyspark.sql.tests import * if xmlrunner: unittest.main(testRunner=xmlrunner.XMLTestRunner(output='target/test-reports')) else: unittest.main() ```
[ { "content": "Here is a code snippet:\n```python\nimport unittest\nimport sys\n\nfrom PySide.QtGui import QStandardItemModel, QWidget, QStandardItem\n\nfrom helper import UsesQApplication\n\nclass QStandardItemModelTest(UsesQApplication):\n\n def setUp(self):\n super(QStandardItemModelTest, self).setUp...
[ { "content": "Here is a code snippet:\n<|memory_start|>```python\nimport unittest\nimport sys\n\nfrom PySide.QtGui import QStandardItemModel, QWidget, QStandardItem\n\nfrom helper import UsesQApplication\n\nclass QStandardItemModelTest(UsesQApplication):\n\n def setUp(self):\n super(QStandardItemModelT...
```python import unittest import sys from PySide.QtGui import QStandardItemModel, QWidget, QStandardItem from helper import UsesQApplication class QStandardItemModelTest(UsesQApplication): def setUp(self): super(QStandardItemModelTest, self).setUp() self.window = QWidget() self.model = QStandardItemModel(0, 3, self.window) def tearDown(self): del self.window del self.model super(QStandardItemModelTest, self).tearDown() def testInsertRow(self): # bug #227 self.model.insertRow(0) class QStandardItemModelRef(UsesQApplication): def testRefCount(self): model = QStandardItemModel(5, 5) items = [] for r in range(5): row = [] for c in range(5): row.append(QStandardItem("%d,%d" % (r,c)) ) self.assertEqual(sys.getrefcount(row[c]), 2) model.insertRow(r, row) for c in range(5): ref_after = sys.getrefcount(row[c]) # check if the ref count was incremented after insertRow self.assertEqual(ref_after, 3) items.append(row) row = None for r in range(3): my_row = model.takeRow(0) my_row = None for c in range(5): # only rest 1 reference self.assertEqual(sys.getrefcount(items[r][c]), 2) my_i = model.item(0,0) # ref(my_i) + parent_ref + items list ref self.assertEqual(sys.getrefcount(my_i), 4) model.clear() # ref(my_i) self.assertEqual(sys.getrefcount(my_i), 3) if __name__ == '__main__': unittest.main() ```
[ { "content": "```python\n#!/usr/bin/env python\n# Python 3\n# LinkFinder\n# By Gerben_Javado\n\n# Fix webbrowser bug for MacOS\nimport os\nos.environ[\"BROWSER\"] = \"open\"\n\n# Import libraries\nimport re, sys, glob, html, argparse, jsbeautifier, webbrowser, subprocess, base64, ssl, xml.etree.ElementTree\n\nf...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\n# Python 3\n# LinkFinder\n# By Gerben_Javado\n\n# Fix webbrowser bug for MacOS\nimport os\nos.environ[\"BROWSER\"] = \"open\"\n\n# Import libraries\nimport re, sys, glob, html, argparse, jsbeautifier, webbrowser, subprocess, base64, ssl, xml.etree....
```python #!/usr/bin/env python # Python 3 # LinkFinder # By Gerben_Javado # Fix webbrowser bug for MacOS import os os.environ["BROWSER"] = "open" # Import libraries import re, sys, glob, html, argparse, jsbeautifier, webbrowser, subprocess, base64, ssl, xml.etree.ElementTree from gzip import GzipFile from string import Template try: from StringIO import StringIO readBytesCustom = StringIO except ImportError: from io import BytesIO readBytesCustom = BytesIO try: from urllib.request import Request, urlopen except ImportError: from urllib2 import Request, urlopen # Regex used regex_str = r""" (?:"|') # Start newline delimiter ( ((?:[a-zA-Z]{1,10}://|//) # Match a scheme [a-Z]*1-10 or // [^"'/]{1,}\. # Match a domainname (any character + dot) [a-zA-Z]{2,}[^"']{0,}) # The domainextension and/or path | ((?:/|\.\./|\./) # Start with /,../,./ [^"'><,;| *()(%%$^/\\\[\]] # Next character can't be... [^"'><,;|()]{1,}) # Rest of the characters can't be | ([a-zA-Z0-9_\-/]{1,}/ # Relative endpoint with / [a-zA-Z0-9_\-/]{1,} # Resource name \.(?:[a-zA-Z]{1,4}|action) # Rest + extension (length 1-4 or action) (?:[\?|#][^"|']{0,}|)) # ? or # mark with parameters | ([a-zA-Z0-9_\-/]{1,}/ # REST API (no extension) with / [a-zA-Z0-9_\-/]{3,} # Proper REST endpoints usually have 3+ chars (?:[\?|#][^"|']{0,}|)) # ? or # mark with parameters | ([a-zA-Z0-9_\-]{1,} # filename \.(?:php|asp|aspx|jsp|json| action|html|js|txt|xml) # . + extension (?:[\?|#][^"|']{0,}|)) # ? or # mark with parameters ) (?:"|') # End newline delimiter """ context_delimiter_str = "\n" def parser_error(errmsg): ''' Error Messages ''' print("Usage: python %s [Options] use -h for help" % sys.argv[0]) print("Error: %s" % errmsg) sys.exit() def parser_input(input): ''' Parse Input ''' # Method 1 - URL if input.startswith(('http://', 'https://', 'file://', 'ftp://', 'ftps://')): return [input] # Method 2 - URL Inspector Firefox if input.startswith('view-source:'): return [input[12:]] # Method 3 - Burp file if args.burp: jsfiles = [] items = xml.etree.ElementTree.fromstring(open(args.input, "r").read()) for item in items: jsfiles.append({"js":base64.b64decode(item.find('response').text).decode('utf-8',"replace"), "url":item.find('url').text}) return jsfiles # Method 4 - Folder with a wildcard if "*" in input: paths = glob.glob(os.path.abspath(input)) for index, path in enumerate(paths): paths[index] = "file://%s" % path return (paths if len(paths) > 0 else parser_error('Input with wildcard does \ not match any files.')) # Method 5 - Local file path = "file://%s" % os.path.abspath(input) return [path if os.path.exists(input) else parser_error("file could not \ be found (maybe you forgot to add http/https).")] def send_request(url): ''' Send requests with Requests ''' q = Request(url) q.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36') q.add_header('Accept', 'text/html,\ application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8') q.add_header('Accept-Language', 'en-US,en;q=0.8') q.add_header('Accept-Encoding', 'gzip') q.add_header('Cookie', args.cookies) try: sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) response = urlopen(q, timeout=args.timeout, context=sslcontext) except: sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) response = urlopen(q, timeout=args.timeout, context=sslcontext) if response.info().get('Content-Encoding') == 'gzip': data = GzipFile(fileobj=readBytesCustom(response.read())).read() elif response.info().get('Content-Encoding') == 'deflate': data = response.read().read() else: data = response.read() return data.decode('utf-8', 'replace') def getContext(list_matches, content, include_delimiter=0, context_delimiter_str="\n"): ''' Parse Input list_matches: list of tuple (link, start_index, end_index) content: content to search for the context include_delimiter Set 1 to include delimiter in context ''' items = [] for m in list_matches: match_str = m[0] match_start = m[1] match_end = m[2] context_start_index = match_start context_end_index = match_end delimiter_len = len(context_delimiter_str) content_max_index = len(content) - 1 while content[context_start_index] != context_delimiter_str and context_start_index > 0: context_start_index = context_start_index - 1 while content[context_end_index] != context_delimiter_str and context_end_index < content_max_index: context_end_index = context_end_index + 1 if include_delimiter: context = content[context_start_index: context_end_index] else: context = content[context_start_index + delimiter_len: context_end_index] item = { "link": match_str, "context": context } items.append(item) return items def parser_file(content, regex_str, mode=1, more_regex=None, no_dup=1): ''' Parse Input content: string of content to be searched regex_str: string of regex (The link should be in the group(1)) mode: mode of parsing. Set 1 to include surrounding contexts in the result more_regex: string of regex to filter the result no_dup: remove duplicated link (context is NOT counted) Return the list of ["link": link, "context": context] The context is optional if mode=1 is provided. ''' global context_delimiter_str if mode == 1: # Beautify if len(content) > 1000000: content = content.replace(";",";\r\n").replace(",",",\r\n") else: content = jsbeautifier.beautify(content) regex = re.compile(regex_str, re.VERBOSE) if mode == 1: all_matches = [(m.group(1), m.start(0), m.end(0)) for m in re.finditer(regex, content)] items = getContext(all_matches, content, context_delimiter_str=context_delimiter_str) else: items = [{"link": m.group(1)} for m in re.finditer(regex, content)] if no_dup: # Remove duplication all_links = set() no_dup_items = [] for item in items: if item["link"] not in all_links: all_links.add(item["link"]) no_dup_items.append(item) items = no_dup_items # Match Regex filtered_items = [] for item in items: # Remove other capture groups from regex results if more_regex: if re.search(more_regex, item["link"]): filtered_items.append(item) else: filtered_items.append(item) return filtered_items def cli_output(endpoints): ''' Output to CLI ''' for endpoint in endpoints: print(html.escape(endpoint["link"]).encode( 'ascii', 'ignore').decode('utf8')) def html_save(html): ''' Save as HTML file and open in the browser ''' hide = os.dup(1) os.close(1) os.open(os.devnull, os.O_RDWR) try: s = Template(open('%s/template.html' % sys.path[0], 'r').read()) text_file = open(args.output, "wb") text_file.write(s.substitute(content=html).encode('utf8')) text_file.close() print("URL to access output: file://%s" % os.path.abspath(args.output)) file = "file:///%s" % os.path.abspath(args.output) if sys.platform == 'linux' or sys.platform == 'linux2': subprocess.call(["xdg-open", file]) else: webbrowser.open(file) except Exception as e: print("Output can't be saved in %s \ due to exception: %s" % (args.output, e)) finally: os.dup2(hide, 1) def check_url(url): nopelist = ["node_modules", "jquery.js"] if url[-3:] == ".js": words = url.split("/") for word in words: if word in nopelist: return False if url[:2] == "//": url = "https:" + url if url[:4] != "http": if url[:1] == "/": url = args.input + url else: url = args.input + "/" + url return url else: return False if __name__ == "__main__": # Parse command line parser = argparse.ArgumentParser() parser.add_argument("-d", "--domain", help="Input a domain to recursively parse all javascript located in a page", action="store_true") parser.add_argument("-i", "--input", help="Input a: URL, file or folder. \ For folders a wildcard can be used (e.g. '/*.js').", required="True", action="store") parser.add_argument("-o", "--output", help="Where to save the file, \ including file name. Default: output.html", action="store", default="output.html") parser.add_argument("-r", "--regex", help="RegEx for filtering purposes \ against found endpoint (e.g. ^/api/)", action="store") parser.add_argument("-b", "--burp", help="", action="store_true") parser.add_argument("-c", "--cookies", help="Add cookies for authenticated JS files", action="store", default="") default_timeout = 10 parser.add_argument("-t", "--timeout", help="How many seconds to wait for the server to send data before giving up (default: " + str(default_timeout) + " seconds)", default=default_timeout, type=int, metavar="<seconds>") args = parser.parse_args() if args.input[-1:] == "/": args.input = args.input[:-1] mode = 1 if args.output == "cli": mode = 0 # Convert input to URLs or JS files urls = parser_input(args.input) # Convert URLs to JS output = '' for url in urls: if not args.burp: try: file = send_request(url) except Exception as e: parser_error("invalid input defined or SSL error: %s" % e) else: file = url['js'] url = url['url'] endpoints = parser_file(file, regex_str, mode, args.regex) if args.domain: for endpoint in endpoints: endpoint = html.escape(endpoint["link"]).encode('ascii', 'ignore').decode('utf8') endpoint = check_url(endpoint) if endpoint is False: continue print("Running against: " + endpoint) print("") try: file = send_request(endpoint) new_endpoints = parser_file(file, regex_str, mode, args.regex) if args.output == 'cli': cli_output(new_endpoints) else: output += ''' <h1>File: <a href="%s" target="_blank" rel="nofollow noopener noreferrer">%s</a></h1> ''' % (html.escape(endpoint), html.escape(endpoint)) for endpoint2 in new_endpoints: url = html.escape(endpoint2["link"]) header = "<div><a href='%s' class='text'>%s" % ( html.escape(url), html.escape(url) ) body = "</a><div class='container'>%s</div></div>" % html.escape( endpoint2["context"] ) body = body.replace( html.escape(endpoint2["link"]), "<span style='background-color:yellow'>%s</span>" % html.escape(endpoint2["link"]) ) output += header + body except Exception as e: print("Invalid input defined or SSL error for: " + endpoint) continue if args.output == 'cli': cli_output(endpoints) else: output += ''' <h1>File: <a href="%s" target="_blank" rel="nofollow noopener noreferrer">%s</a></h1> ''' % (html.escape(url), html.escape(url)) for endpoint in endpoints: url = html.escape(endpoint["link"]) header = "<div><a href='%s' class='text'>%s" % ( html.escape(url), html.escape(url) ) body = "</a><div class='container'>%s</div></div>" % html.escape( endpoint["context"] ) body = body.replace( html.escape(endpoint["link"]), "<span style='background-color:yellow'>%s</span>" % html.escape(endpoint["link"]) ) output += header + body if args.output != 'cli': html_save(output) ```
[ { "content": "Repeat the code precisely:\n```python\n#!/usr/bin/env python\n\nfrom .util import Spec\n\n\nclass File(Spec):\n\n STATES = [\n \"directory\", \"file\",\n \"owned_by\",\n \"smaller_than\", \"larger_than\"\n ]\n\n def __init__(self, path):\n self.path = path\n ...
[ { "content": "Repeat the code precisely:\n<|memory_start|>```python\n#!/usr/bin/env python\n\nfrom .util import Spec\n\n\nclass File(Spec):\n\n STATES = [\n \"directory\", \"file\",\n \"owned_by\",\n \"smaller_than\", \"larger_than\"\n ]\n\n def __init__(self, path):\n self....
```python #!/usr/bin/env python from .util import Spec class File(Spec): STATES = [ "directory", "file", "owned_by", "smaller_than", "larger_than" ] def __init__(self, path): self.path = path self.state = {} self.get_state() self.WIN = "File %s is %%s" % self.path def get_state(self): import os import stat import pwd import grp s = os.stat(self.path) self.state = { 'st_mode': s.st_mode, 'st_ino': s.st_ino, 'st_dev': s.st_dev, 'st_nlink': s.st_nlink, 'st_uid': s.st_uid, 'st_gid': s.st_gid, 'st_size': s.st_size, 'user': pwd.getpwuid(s.st_uid)[0], 'group': grp.getgrgid(s.st_gid)[0], 'directory': stat.S_ISDIR(s.st_mode), 'file': stat.S_ISREG(s.st_mode), 'full_mode': oct(stat.S_IMODE(s.st_mode)), 'mode': oct(stat.S_IMODE(s.st_mode))[1:], } def sb_smaller_than(self, size): size_map = { 'k': 1024, 'm': 1024*1024, 'g': 1024*1024*1024 } real_size = self.state['st_size'] size_units = size[-1].lower() size_count = int(size[0:-1]) expected_size = size_count * size_map[size_units] if expected_size > real_size: return True, "File %s is smaller than %s" % (self.path, size) else: return False, "File %s is larger than %s" % (self.path, size) def sb_larger_than(self, size): x, msg = self.sb_smaller_than(size) return x is False, msg def sb_directory(self, *args): if self._make_sure(self.state['directory']): return True return "%s is not a directory" % (self.path) def sb_file(self, *args): if self._make_sure(self.state['file']): return True return "%s is not a file" % (self.path) def sb_owned_by(self, desired_owner): user = None group = None problems = [] if ':' in desired_owner: (user, group) = desired_owner.split(':') else: user = desired_owner if user and self.state['user'] != user: problems.append("owned %s not %s" % (self.state['user'], user)) if group and self.state['group'] != group: problems.append("group %s not %s" % (self.state['group'], group)) if problems: return ' and '.join(problems) return True ```
[ { "content": "```python\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nExamples for Python-nvd3 is a Python wrapper for NVD3 graph library.\nNVD3 is an attempt to build re-usable charts and chart components\nfor d3.js without taking away the power that d3.js gives you.\n\nProject location : https://gith...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nExamples for Python-nvd3 is a Python wrapper for NVD3 graph library.\nNVD3 is an attempt to build re-usable charts and chart components\nfor d3.js without taking away the power that d3.js gives you.\n\nProject locatio...
```python #!/usr/bin/python # -*- coding: utf-8 -*- """ Examples for Python-nvd3 is a Python wrapper for NVD3 graph library. NVD3 is an attempt to build re-usable charts and chart components for d3.js without taking away the power that d3.js gives you. Project location : https://github.com/areski/python-nvd3 """ from nvd3.multiBarChart import MultiBarChart import random #Open File for test output_file = open('test_multiBarChart.html', 'w') type = "multiBarChart" chart = MultiBarChart(name=type, height=350) chart.set_containerheader("\n\n<h2>" + type + "</h2>\n\n") nb_element = 10 xdata = list(range(nb_element)) ydata = [random.randint(1, 10) for i in range(nb_element)] ydata2 = [x * 2 for x in ydata] extra_serie = {"tooltip": {"y_start": "", "y_end": " call"}} chart.add_serie(name="Count", y=ydata, x=xdata, extra=extra_serie) extra_serie = {"tooltip": {"y_start": "", "y_end": " min"}} chart.add_serie(name="Duration", y=ydata2, x=xdata, extra=extra_serie) chart.buildhtml() output_file.write(chart.htmlcontent) #--------------------------------------- #close Html file output_file.close() ```
[ { "content": "Here is the snippet:\n```python\n#!/usr/bin/env python\n# -*- coding:gbk -*-\nimport sys\nimport re\nimport os\nimport time\nimport string\nimport datetime\nimport tushare as ts\nfrom internal.ts_common import *\nfrom decimal import Decimal\n\ntoday = datetime.date.today()\n\n#˵Ã÷show_flag\n#0£º²...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n#!/usr/bin/env python\n# -*- coding:gbk -*-\nimport sys\nimport re\nimport os\nimport time\nimport string\nimport datetime\nimport tushare as ts\nfrom internal.ts_common import *\nfrom decimal import Decimal\n\ntoday = datetime.date.today()\n\n#˵Ã÷...
```python #!/usr/bin/env python # -*- coding:gbk -*- import sys import re import os import time import string import datetime import tushare as ts from internal.ts_common import * from decimal import Decimal today = datetime.date.today() #˵Ã÷show_flag #0£º²»»ñµÃÿһֻµÄÁ÷ͨÅÌ£¬²»»á¼ÆËã»»ÊÖÂÊ #1£º»ñµÃÿһֻµÄÁ÷ͨÅÌ£¬²¢ÇÒ¼ÆËã»»ÊÖÂÊ #2£ºÏÔʾÿһֻ×îеÄÐÂÎÅ£¬µ±ÌìµÄÐÂÎÅÈ«²¿ÏÔʾ£¬µ±ÌìûÓÐÖ»ÏÔʾһÌõnews pindex = len(sys.argv) LOOP_COUNT=0 st_today_base = None while LOOP_COUNT<3: try: st_today_base = ts.get_today_all() except: LOOP_COUNT += 1 time.sleep(0.5) else: break; if st_today_base is None: print "Timeout to get stock basic info" exit(0) st_today = st_today_base.sort_values(['changepercent'], 0, False) #new_st_list = list(st_today[st_today.changepercent>11]['code']) new_st_list = [] for index,row in st_today.iterrows(): code = row[0].encode('gbk') if row['changepercent']>11: new_st_list.append(code) print '' #print new_st_list LOOP_COUNT=0 st_bas = None while LOOP_COUNT<3: try: st_bas = ts.get_stock_basics() except: LOOP_COUNT += 1 time.sleep(0.5) else: break; if st_bas is None: print "Timeout to get stock basic info" exit(0) st_pb_base = st_bas[st_bas.pb!=0] st_pb_base = st_pb_base.sort_values(['timeToMarket'], 0, False) st_index = st_pb_base.index st_bas_list=list(st_index) #st_bas.to_excel("a_stock_base.xlsx") #st_pb_base.to_excel("a_stock_pb_base.xlsx") #print st_pb_base.head(10) st_list = [] for i in range(0, len(new_st_list)): if new_st_list[i] in st_bas_list[0:10]: pass else: st_list.append(new_st_list[i]) st_list.extend(st_bas_list) ''' st_list = st_list[0:60] st_list.append('300175') st_list.append('603558') #st_list=['600828','002819','300611'] #print st_list ''' number = len(st_list) if number<=0: exit(0) today_open = [] stcsItem=statisticsItem() b_get_data = 1 #ZTÒ»´ÎÈ¡³ö base ¸ö #½ØÈ¡list£¬Í¨¹ýÅäÖÃÆðʼλÖà base = 23 loop_ct = number/base if number%base!=0: loop_ct += 1 pd_list = [] for i in range(0, loop_ct): end_idx = min(base*(i+1), number) cur_list = st_list[i*base:end_idx] if len(cur_list)==0: break #print cur_list excecount = 0 stdf = None while excecount<5: try: stdf = ts.get_realtime_quotes(cur_list) except: print "Get except:" time.sleep(0.5) excecount += 1 if excecount<5: continue stdf = None break else: break if stdf is None: print "Get list fail at:", cur_list continue #print stdf yzcx_flag = 0 for index,row in stdf.iterrows(): stockInfo = [] code = cur_list[index] index += 1 name = row[0] pre_close = float(row['pre_close']) price = float(row['price']) #ͨ¹ý»ñµÃKÏßÊý¾Ý£¬ÅжÏÊÇ·ñYZZTÐÂ¹É if b_get_data == 1: #»ñµÃÿֻ¸ö¹ÉÿÌì½»Ò×Êý¾Ý day_info_df = ts.get_k_data(code) #print day_info_df trade_days = len(day_info_df) b_open=0 yzzt_day = 0 if trade_days==1: stcsItem.s_new += 1 yzcx_flag = 1 for tdidx,tdrow in day_info_df.iterrows(): open = tdrow[1] close = tdrow[2] high = tdrow['high'] low = tdrow['low'] if high!=low: if yzzt_day!=0: if (yzzt_day+1)==trade_days: chg_perc = round((price-pre_close)*100/pre_close,2) open_list = [code, name, chg_perc, price, yzzt_day] today_open.append(open_list) b_open = 1 break #µ±ZT´ò¿ª£¬¾Í»ábreak for Ñ­»· yzzt_day += 1 pre_close = close if b_open==0: dt_str=day_info_df.iloc[trade_days-1,0] last_date = datetime.datetime.strptime(dt_str, '%Y-%m-%d').date() cmp_delta = today-last_date if cmp_delta.days==0: stcsItem.s_cx_yzzt += 1 yzcx_flag = 1 #ÈÏΪYZZT²»»á³¬¹ý 33 ¸ö½»Ò×ÈÕ if trade_days>33: b_get_data = 0 stk_type = analyze_status(code, name, row, stcsItem, yzcx_flag, pd_list) #if i>2: # break #if len(pd_list)>0: # df_tdy = pd.DataFrame(pd_list) # df_tdy1 = df_tdy.sort_values([0], 0, False) str_opn = "[%d %d %d %d]" % (stcsItem.s_open_zt,stcsItem.s_close_zt,stcsItem.s_open_T_zt,stcsItem.s_dk_zt) print "%4d-ZT %4d-DT %d-X %d--%s" % (stcsItem.s_zt,stcsItem.s_dt,stcsItem.s_new,stcsItem.s_yzzt, str_opn) print "%4d-CG %4d-FT KD:[%s] %2d-YIN" %(stcsItem.s_zthl,stcsItem.s_dtft,','.join(stcsItem.lst_kd),stcsItem.s_zt_o_gt_c) print "%4d(%4d) ZERO:%4d %4d(%4d)" %(stcsItem.s_open_sz, stcsItem.s_open_dz, stcsItem.s_open_pp, stcsItem.s_open_xd, stcsItem.s_open_dd) print "%4d(%4d) ZERO:%4d %4d(%4d)" %(stcsItem.s_close_sz, stcsItem.s_close_dz, stcsItem.s_close_pp, stcsItem.s_close_xd, stcsItem.s_close_dd) print "4%%:%4d %4d" %(stcsItem.s_high_zf,stcsItem.s_low_df) #print today_open str = '' list = today_open if len(list)>0: print "CXKB:" for i in range(0, len(list)): itm_lst = list[i] if itm_lst[2]>9.9: str1 = "%s(%d, ZT), " % (itm_lst[1], itm_lst[4]) elif itm_lst[2]<-9.9: str1 = "%s(%d, DT), " % (itm_lst[1], itm_lst[4]) else: str1 = "%s(%d, %.2f%%), " % (itm_lst[1], itm_lst[4],itm_lst[2]) str += str1 print str else: print "CXKB:=====" print '' str = '' list = stcsItem.lst_nb if len(list)>0: print "NB:" for i in range(0, len(list)): itm_lst = list[i] str1 = "%s(%.2f%%, %.2f%%), " % (itm_lst[1], itm_lst[2], itm_lst[4]) str += str1 print str else: print "NB:=====" print '' str = '' list = stcsItem.lst_jc if len(list)>0: print "JC:" for i in range(0, len(list)): itm_lst = list[i] str1 = "%s(%.2f%%, %.2f%%), " % (itm_lst[1], itm_lst[2], itm_lst[4]) str += str1 print str else: print "JC:=====" #print '\n'.join(['%s:%s' % item for item in stcsItem.__dict__.items()]) ```
[ { "content": "```python\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------...
[ { "content": "<|memory_start|>```python\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# ----------------...
```python # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import azure.cli.command_modules.backup.custom_help as custom_help from azure.cli.command_modules.backup._client_factory import backup_protected_items_cf, \ protection_containers_cf, protected_items_cf, backup_protected_items_crr_cf, recovery_points_crr_cf from azure.cli.core.util import CLIError from azure.cli.core.azclierror import InvalidArgumentValueError # pylint: disable=import-error fabric_name = "Azure" # pylint: disable=unused-argument # Mapping of workload type workload_type_map = {'MSSQL': 'SQLDataBase', 'SAPHANA': 'SAPHanaDatabase', 'SQLDataBase': 'SQLDataBase', 'SAPHanaDatabase': 'SAPHanaDatabase', 'VM': 'VM', 'AzureFileShare': 'AzureFileShare'} def show_container(cmd, client, name, resource_group_name, vault_name, backup_management_type=None, status="Registered", use_secondary_region=None): container_type = custom_help.validate_and_extract_container_type(name, backup_management_type) if use_secondary_region: if container_type and container_type.lower() == "azurestorage": raise InvalidArgumentValueError( """ --use-secondary-region flag is not supported for container of type AzureStorage. Please either remove the flag or query for any other container type. """) if custom_help.is_native_name(name): return protection_containers_cf(cmd.cli_ctx).get(vault_name, resource_group_name, fabric_name, name) containers = _get_containers(client, container_type, status, resource_group_name, vault_name, name, use_secondary_region) return custom_help.get_none_one_or_many(containers) def list_containers(client, resource_group_name, vault_name, backup_management_type, status="Registered", use_secondary_region=None): return _get_containers(client, backup_management_type, status, resource_group_name, vault_name, use_secondary_region=use_secondary_region) def show_policy(client, resource_group_name, vault_name, name): return client.get(vault_name, resource_group_name, name) def list_policies(client, resource_group_name, vault_name, workload_type=None, backup_management_type=None): workload_type = _check_map(workload_type, workload_type_map) filter_string = custom_help.get_filter_string({ 'backupManagementType': backup_management_type, 'workloadType': workload_type}) policies = client.list(vault_name, resource_group_name, filter_string) return custom_help.get_list_from_paged_response(policies) def show_item(cmd, client, resource_group_name, vault_name, container_name, name, backup_management_type=None, workload_type=None, use_secondary_region=None): container_type = custom_help.validate_and_extract_container_type(container_name, backup_management_type) if use_secondary_region: if container_type and container_type.lower() == "azurestorage": raise InvalidArgumentValueError( """ --use-secondary-region flag is not supported for container of type AzureStorage. Please either remove the flag or query for any other container type. """) else: if custom_help.is_native_name(name) and custom_help.is_native_name(container_name): client = protected_items_cf(cmd.cli_ctx) return client.get(vault_name, resource_group_name, fabric_name, container_name, name) items = list_items(cmd, client, resource_group_name, vault_name, workload_type, container_name, container_type, use_secondary_region) if custom_help.is_native_name(name): filtered_items = [item for item in items if item.name.lower() == name.lower()] else: filtered_items = [item for item in items if item.properties.friendly_name.lower() == name.lower()] return custom_help.get_none_one_or_many(filtered_items) def list_items(cmd, client, resource_group_name, vault_name, workload_type=None, container_name=None, container_type=None, use_secondary_region=None): workload_type = _check_map(workload_type, workload_type_map) filter_string = custom_help.get_filter_string({ 'backupManagementType': container_type, 'itemType': workload_type}) if use_secondary_region: if container_type and container_type.lower() == "azurestorage": raise InvalidArgumentValueError( """ --use-secondary-region flag is not supported for --backup-management-type AzureStorage. Please either remove the flag or query for any other backup-management-type. """) client = backup_protected_items_crr_cf(cmd.cli_ctx) items = client.list(vault_name, resource_group_name, filter_string) paged_items = custom_help.get_list_from_paged_response(items) if container_name: if custom_help.is_native_name(container_name): return [item for item in paged_items if _is_container_name_match(item, container_name)] return [item for item in paged_items if item.properties.container_name.lower().split(';')[-1] == container_name.lower()] return paged_items def show_recovery_point(cmd, client, resource_group_name, vault_name, container_name, item_name, name, workload_type=None, backup_management_type=None, use_secondary_region=None): items_client = backup_protected_items_cf(cmd.cli_ctx) item = show_item(cmd, items_client, resource_group_name, vault_name, container_name, item_name, backup_management_type, workload_type, use_secondary_region) custom_help.validate_item(item) if isinstance(item, list): raise CLIError("Multiple items found. Please give native names instead.") # Get container and item URIs container_uri = custom_help.get_protection_container_uri_from_id(item.id) item_uri = custom_help.get_protected_item_uri_from_id(item.id) container_type = custom_help.validate_and_extract_container_type(container_name, backup_management_type) if use_secondary_region: if container_type and container_type.lower() == "azurestorage": raise InvalidArgumentValueError( """ --use-secondary-region flag is not supported for --backup-management-type AzureStorage. Please either remove the flag or query for any other backup-management-type. """) client = recovery_points_crr_cf(cmd.cli_ctx) recovery_points = client.list(vault_name, resource_group_name, fabric_name, container_uri, item_uri, None) paged_rps = custom_help.get_list_from_paged_response(recovery_points) filtered_rps = [rp for rp in paged_rps if rp.name.lower() == name.lower()] return custom_help.get_none_one_or_many(filtered_rps) return client.get(vault_name, resource_group_name, fabric_name, container_uri, item_uri, name) def delete_policy(client, resource_group_name, vault_name, name): client.delete(vault_name, resource_group_name, name) def new_policy(client, resource_group_name, vault_name, policy, policy_name, container_type, workload_type): workload_type = _check_map(workload_type, workload_type_map) policy_object = custom_help.get_policy_from_json(client, policy) policy_object.properties.backup_management_type = container_type policy_object.properties.workload_type = workload_type return client.create_or_update(vault_name, resource_group_name, policy_name, policy_object) def _get_containers(client, backup_management_type, status, resource_group_name, vault_name, container_name=None, use_secondary_region=None): filter_dict = { 'backupManagementType': backup_management_type, 'status': status } if container_name and not custom_help.is_native_name(container_name): filter_dict['friendlyName'] = container_name filter_string = custom_help.get_filter_string(filter_dict) if use_secondary_region: if backup_management_type.lower() == "azurestorage": raise InvalidArgumentValueError( """ --use-secondary-region flag is not supported for --backup-management-type AzureStorage. Please either remove the flag or query for any other backup-management-type. """) paged_containers = client.list(vault_name, resource_group_name, filter_string) containers = custom_help.get_list_from_paged_response(paged_containers) if container_name and custom_help.is_native_name(container_name): return [container for container in containers if container.name == container_name] return containers def _is_container_name_match(item, container_name): if item.properties.container_name.lower() == container_name.lower(): return True name = ';'.join(container_name.split(';')[1:]) if item.properties.container_name.lower() == name.lower(): return True return False def _check_map(item_type, item_type_map): if item_type is None: return None if item_type_map.get(item_type) is not None: return item_type_map[item_type] error_text = "{} is an invalid argument.".format(item_type) recommendation_text = "{} are the allowed values.".format(str(list(item_type_map.keys()))) az_error = InvalidArgumentValueError(error_text) az_error.set_recommendation(recommendation_text) raise az_error ```
[ { "content": "```python\n#!/usr/bin/python -tt\n\n\"\"\"Junos Interface Troubleshooting library.\"\"\"\n\nimport re\nimport warnings\nimport helpers\n\nfrom napalm import get_network_driver\nfrom jnpr.junos.exception import ConnectRefusedError, ConnectAuthError\n\n# JUNOS MAC table RE\nRE_VLAN = r'\\s+([\\w\\d-...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/python -tt\n\n\"\"\"Junos Interface Troubleshooting library.\"\"\"\n\nimport re\nimport warnings\nimport helpers\n\nfrom napalm import get_network_driver\nfrom jnpr.junos.exception import ConnectRefusedError, ConnectAuthError\n\n# JUNOS MAC table RE\nRE_VLAN =...
```python #!/usr/bin/python -tt """Junos Interface Troubleshooting library.""" import re import warnings import helpers from napalm import get_network_driver from jnpr.junos.exception import ConnectRefusedError, ConnectAuthError # JUNOS MAC table RE RE_VLAN = r'\s+([\w\d-]+)\s+' RE_MAC = r'\s?([*\w\d:]+)\s+' RE_TYPE = r'\s?([\w]+) ' RE_AGE = r'\s+([-\d:]+)' RE_INTERFACE = r'\s+([-.\w\d/]+)' RE_SWITCHING_TABLE = RE_VLAN + RE_MAC + RE_TYPE + RE_AGE + RE_INTERFACE class TroubleshootDevice(object): """Class to help troubleshoot device.""" def __init__(self, asset, loopback, ssh_key, interface_name): self.asset = asset self.loopback = loopback self.ssh_key = ssh_key self.interface_name = interface_name self.mac_address = None self.dhcp_logs = None self.dhcp_error = None self.log_entries = None self.interface = None self.error_message = None self.macs = {} self.lldp = {} def run(self): """Run troubleshooter.""" try: # Connect to asset driver = get_network_driver('junos') device = driver(self.loopback, 'automation', '', optional_args={'key_file': self.ssh_key}) device.open() with warnings.catch_warnings(record=True) as warning: warnings.filterwarnings('ignore') # Check interface cmd = 'show interfaces {0} detail'.format(self.interface_name) show_interface = device.cli([cmd]) self.interface = Interface(show_interface[cmd]) if self.interface.link_state == 'Up': # Get LLDP neighbor cmd = 'show lldp neighbors interface {0}'.format(self.interface_name) lldp_neighbor = device.cli([cmd]) self.lldp = LLDP(lldp_neighbor[cmd]) # Check MAC table cmd = 'show ethernet-switching table interface {0}'.format(self.interface_name) mac_table = device.cli([cmd]) self.macs = MACTable(mac_table[cmd]) # Search DHCP logs if MAC is specified if self.macs: self.mac_address = self.macs.mac_entries[0]['mac'] dhcp_server = helpers.get_dhcp_server(asset=self.asset) self.dhcp_logs, self.dhcp_error = helpers.search_dhcp_log(self.mac_address, dhcp_server) # Check log file cmd = 'show log messages' show_log = device.cli([cmd]) show_log = show_log[cmd] self.log_entries = re.findall(r'\n([\[\]\s\w\d:.-]+{0}[\s\w\d:.-]+)\n'.format(self.interface_name), show_log) device.close() except ConnectAuthError: self.error_message = 'Autentication failed to %s.' % self.loopback except ConnectRefusedError: self.error_message = 'Connection refused to %s.' % self.loopback except ValueError: self.error_message = 'No switch found.' class Interface(object): """Class to represent a JUNOS interface.""" def __init__(self, output): self.output = output self.link_state = '' self.speed = '' self.duplex = '' self.flapped = '' self.auto_neg = '' # Analyze output self.analyze_output() def analyze_output(self): """Anlyze the output from show interfaces X.""" # Link down match = re.search(r'Physical link is ([\w]+)', self.output) if match: self.link_state = match.groups()[0] # Speed match = re.search(r'Speed: ([\w\d]+),', self.output) if match: self.speed = match.groups()[0] # Duplex match = re.search(r'Duplex: ([\w-]+),', self.output) if match: self.duplex = match.groups()[0] # Last flapped match = re.search(r'Last flapped : ([\w\d ():-]+)\n', self.output) if match: self.flapped = match.groups()[0] # Auto negotiation match = re.search(r'Auto-negotiation: ([\w]+),', self.output) if match: self.auto_neg = match.groups()[0] class LLDP(object): """Parse and represent a LLDP neighbor.""" def __init__(self, output): self.output = output self.empty = True self.remote_chassis_id = '' self.remote_port_description = '' self.remote_system = '' # Analyze output self.analyze_output() if self.remote_chassis_id: self.empty = False def analyze_output(self): """Parse JUNOS show lldp neighboir interface X command.""" # Remote chassis ID match = re.search(r'Chassis ID\s+: ([\w\d:-]+)', self.output) if match: self.remote_chassis_id = match.groups()[0] # Remote port description match = re.search(r'Port description\s+: ([\w\d\/:-]+)', self.output) if match: self.remote_port_description = match.groups()[0] # Remote port system match = re.search(r'System name\s+: ([\w\d\/:-]+)', self.output) if match: self.remote_system = match.groups()[0] class MACTable(object): """Parse and save MAC entries from a JUNOS device.""" def __init__(self, output): self.output = output self.mac_entries = [] # Analyze output self.analyze_output() def analyze_output(self): """Parse JUNOS show ethernet-switching interface X command.""" # Remote chassis ID match = re.findall(RE_SWITCHING_TABLE, self.output) for entry in match: if entry[1] != '*': mac_entry = {'vlan': entry[0], 'mac': entry[1], 'type': entry[2], 'age': entry[3], 'interface': entry[4]} self.mac_entries.append(mac_entry) def __str__(self): if self.mac_entries: return self.mac_entries[0]['mac'] return None def main(): """Main.""" pass if __name__ == '__main__': main() ```
[ { "content": "Recreate the entire code block with identical formatting:\n```python\n# ----------------------------------------------------------------------\n# LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator\n# http://lammps.sandia.gov, Sandia National Laboratories\n# Steve Plimpton, sj...
[ { "content": "Recreate the entire code block with identical formatting:\n<|memory_start|>```python\n# ----------------------------------------------------------------------\n# LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator\n# http://lammps.sandia.gov, Sandia National Laboratories\n# St...
```python # ---------------------------------------------------------------------- # LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator # http://lammps.sandia.gov, Sandia National Laboratories # Steve Plimpton, sjplimp@sandia.gov # # Copyright (2003) Sandia Corporation. Under the terms of Contract # DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains # certain rights in this software. This software is distributed under # the GNU General Public License. # # See the README file in the top-level LAMMPS directory. # ------------------------------------------------------------------------- # Python wrappers on LAMMPS library via ctypes # for python3 compatibility from __future__ import print_function # imports for simple LAMMPS python wrapper module "lammps" import sys,traceback,types from ctypes import * from os.path import dirname,abspath,join from inspect import getsourcefile # imports for advanced LAMMPS python wrapper modules "PyLammps" and "IPyLammps" from collections import namedtuple import os import select import re import sys def get_ctypes_int(size): if size == 4: return c_int32 elif size == 8: return c_int64 return c_int class MPIAbortException(Exception): def __init__(self, message): self.message = message def __str__(self): return repr(self.message) class lammps(object): # detect if Python is using version of mpi4py that can pass a communicator has_mpi4py_v2 = False try: from mpi4py import MPI from mpi4py import __version__ as mpi4py_version if mpi4py_version.split('.')[0] == '2': has_mpi4py_v2 = True except: pass # create instance of LAMMPS def __init__(self,name="",cmdargs=None,ptr=None,comm=None): self.comm = comm self.opened = 0 # determine module location modpath = dirname(abspath(getsourcefile(lambda:0))) self.lib = None # if a pointer to a LAMMPS object is handed in, # all symbols should already be available try: if ptr: self.lib = CDLL("",RTLD_GLOBAL) except: self.lib = None # load liblammps.so unless name is given # if name = "g++", load liblammps_g++.so # try loading the LAMMPS shared object from the location # of lammps.py with an absolute path, # so that LD_LIBRARY_PATH does not need to be set for regular install # fall back to loading with a relative path, # typically requires LD_LIBRARY_PATH to be set appropriately if not self.lib: try: if not name: self.lib = CDLL(join(modpath,"liblammps.so"),RTLD_GLOBAL) else: self.lib = CDLL(join(modpath,"liblammps_%s.so" % name), RTLD_GLOBAL) except: if not name: self.lib = CDLL("liblammps.so",RTLD_GLOBAL) else: self.lib = CDLL("liblammps_%s.so" % name,RTLD_GLOBAL) # if no ptr provided, create an instance of LAMMPS # don't know how to pass an MPI communicator from PyPar # but we can pass an MPI communicator from mpi4py v2.0.0 and later # no_mpi call lets LAMMPS use MPI_COMM_WORLD # cargs = array of C strings from args # if ptr, then are embedding Python in LAMMPS input script # ptr is the desired instance of LAMMPS # just convert it to ctypes ptr and store in self.lmp if not ptr: # with mpi4py v2, can pass MPI communicator to LAMMPS # need to adjust for type of MPI communicator object # allow for int (like MPICH) or void* (like OpenMPI) if lammps.has_mpi4py_v2 and comm != None: if lammps.MPI._sizeof(lammps.MPI.Comm) == sizeof(c_int): MPI_Comm = c_int else: MPI_Comm = c_void_p narg = 0 cargs = 0 if cmdargs: cmdargs.insert(0,"lammps.py") narg = len(cmdargs) for i in range(narg): if type(cmdargs[i]) is str: cmdargs[i] = cmdargs[i].encode() cargs = (c_char_p*narg)(*cmdargs) self.lib.lammps_open.argtypes = [c_int, c_char_p*narg, \ MPI_Comm, c_void_p()] else: self.lib.lammps_open.argtypes = [c_int, c_int, \ MPI_Comm, c_void_p()] self.lib.lammps_open.restype = None self.opened = 1 self.lmp = c_void_p() comm_ptr = lammps.MPI._addressof(comm) comm_val = MPI_Comm.from_address(comm_ptr) self.lib.lammps_open(narg,cargs,comm_val,byref(self.lmp)) else: self.opened = 1 if cmdargs: cmdargs.insert(0,"lammps.py") narg = len(cmdargs) for i in range(narg): if type(cmdargs[i]) is str: cmdargs[i] = cmdargs[i].encode() cargs = (c_char_p*narg)(*cmdargs) self.lmp = c_void_p() self.lib.lammps_open_no_mpi(narg,cargs,byref(self.lmp)) else: self.lmp = c_void_p() self.lib.lammps_open_no_mpi(0,None,byref(self.lmp)) # could use just this if LAMMPS lib interface supported it # self.lmp = self.lib.lammps_open_no_mpi(0,None) else: # magic to convert ptr to ctypes ptr if sys.version_info >= (3, 0): # Python 3 (uses PyCapsule API) pythonapi.PyCapsule_GetPointer.restype = c_void_p pythonapi.PyCapsule_GetPointer.argtypes = [py_object, c_char_p] self.lmp = c_void_p(pythonapi.PyCapsule_GetPointer(ptr, None)) else: # Python 2 (uses PyCObject API) pythonapi.PyCObject_AsVoidPtr.restype = c_void_p pythonapi.PyCObject_AsVoidPtr.argtypes = [py_object] self.lmp = c_void_p(pythonapi.PyCObject_AsVoidPtr(ptr)) # optional numpy support (lazy loading) self._numpy = None # set default types self.c_bigint = get_ctypes_int(self.extract_setting("bigint")) self.c_tagint = get_ctypes_int(self.extract_setting("tagint")) self.c_imageint = get_ctypes_int(self.extract_setting("imageint")) def __del__(self): if self.lmp and self.opened: self.lib.lammps_close(self.lmp) self.opened = 0 def close(self): if self.opened: self.lib.lammps_close(self.lmp) self.lmp = None self.opened = 0 def version(self): return self.lib.lammps_version(self.lmp) def file(self,file): if file: file = file.encode() self.lib.lammps_file(self.lmp,file) # send a single command def command(self,cmd): if cmd: cmd = cmd.encode() self.lib.lammps_command(self.lmp,cmd) if self.uses_exceptions and self.lib.lammps_has_error(self.lmp): sb = create_string_buffer(100) error_type = self.lib.lammps_get_last_error_message(self.lmp, sb, 100) error_msg = sb.value.decode().strip() if error_type == 2: raise MPIAbortException(error_msg) raise Exception(error_msg) # send a list of commands def commands_list(self,cmdlist): cmds = [x.encode() for x in cmdlist if type(x) is str] args = (c_char_p * len(cmdlist))(*cmds) self.lib.lammps_commands_list(self.lmp,len(cmdlist),args) # send a string of commands def commands_string(self,multicmd): if type(multicmd) is str: multicmd = multicmd.encode() self.lib.lammps_commands_string(self.lmp,c_char_p(multicmd)) # extract global info def extract_global(self,name,type): if name: name = name.encode() if type == 0: self.lib.lammps_extract_global.restype = POINTER(c_int) elif type == 1: self.lib.lammps_extract_global.restype = POINTER(c_double) else: return None ptr = self.lib.lammps_extract_global(self.lmp,name) return ptr[0] # extract per-atom info def extract_atom(self,name,type): if name: name = name.encode() if type == 0: self.lib.lammps_extract_atom.restype = POINTER(c_int) elif type == 1: self.lib.lammps_extract_atom.restype = POINTER(POINTER(c_int)) elif type == 2: self.lib.lammps_extract_atom.restype = POINTER(c_double) elif type == 3: self.lib.lammps_extract_atom.restype = POINTER(POINTER(c_double)) else: return None ptr = self.lib.lammps_extract_atom(self.lmp,name) return ptr # extract lammps type byte sizes def extract_setting(self, name): if name: name = name.encode() self.lib.lammps_extract_atom.restype = c_int return int(self.lib.lammps_extract_setting(self.lmp,name)) @property def numpy(self): if not self._numpy: import numpy as np class LammpsNumpyWrapper: def __init__(self, lmp): self.lmp = lmp def _ctype_to_numpy_int(self, ctype_int): if ctype_int == c_int32: return np.int32 elif ctype_int == c_int64: return np.int64 return np.intc def extract_atom_iarray(self, name, nelem, dim=1): if name in ['id', 'molecule']: c_int_type = self.lmp.c_tagint elif name in ['image']: c_int_type = self.lmp.c_imageint else: c_int_type = c_int np_int_type = self._ctype_to_numpy_int(c_int_type) if dim == 1: tmp = self.lmp.extract_atom(name, 0) ptr = cast(tmp, POINTER(c_int_type * nelem)) else: tmp = self.lmp.extract_atom(name, 1) ptr = cast(tmp[0], POINTER(c_int_type * nelem * dim)) a = np.frombuffer(ptr.contents, dtype=np_int_type) a.shape = (nelem, dim) return a def extract_atom_darray(self, name, nelem, dim=1): if dim == 1: tmp = self.lmp.extract_atom(name, 2) ptr = cast(tmp, POINTER(c_double * nelem)) else: tmp = self.lmp.extract_atom(name, 3) ptr = cast(tmp[0], POINTER(c_double * nelem * dim)) a = np.frombuffer(ptr.contents) a.shape = (nelem, dim) return a self._numpy = LammpsNumpyWrapper(self) return self._numpy # extract compute info def extract_compute(self,id,style,type): if id: id = id.encode() if type == 0: if style > 0: return None self.lib.lammps_extract_compute.restype = POINTER(c_double) ptr = self.lib.lammps_extract_compute(self.lmp,id,style,type) return ptr[0] if type == 1: self.lib.lammps_extract_compute.restype = POINTER(c_double) ptr = self.lib.lammps_extract_compute(self.lmp,id,style,type) return ptr if type == 2: self.lib.lammps_extract_compute.restype = POINTER(POINTER(c_double)) ptr = self.lib.lammps_extract_compute(self.lmp,id,style,type) return ptr return None # extract fix info # in case of global datum, free memory for 1 double via lammps_free() # double was allocated by library interface function def extract_fix(self,id,style,type,i=0,j=0): if id: id = id.encode() if style == 0: self.lib.lammps_extract_fix.restype = POINTER(c_double) ptr = self.lib.lammps_extract_fix(self.lmp,id,style,type,i,j) result = ptr[0] self.lib.lammps_free(ptr) return result elif (style == 1) or (style == 2): if type == 1: self.lib.lammps_extract_fix.restype = POINTER(c_double) elif type == 2: self.lib.lammps_extract_fix.restype = POINTER(POINTER(c_double)) else: return None ptr = self.lib.lammps_extract_fix(self.lmp,id,style,type,i,j) return ptr else: return None # extract variable info # free memory for 1 double or 1 vector of doubles via lammps_free() # for vector, must copy nlocal returned values to local c_double vector # memory was allocated by library interface function def extract_variable(self,name,group,type): if name: name = name.encode() if group: group = group.encode() if type == 0: self.lib.lammps_extract_variable.restype = POINTER(c_double) ptr = self.lib.lammps_extract_variable(self.lmp,name,group) result = ptr[0] self.lib.lammps_free(ptr) return result if type == 1: self.lib.lammps_extract_global.restype = POINTER(c_int) nlocalptr = self.lib.lammps_extract_global(self.lmp,"nlocal".encode()) nlocal = nlocalptr[0] result = (c_double*nlocal)() self.lib.lammps_extract_variable.restype = POINTER(c_double) ptr = self.lib.lammps_extract_variable(self.lmp,name,group) for i in range(nlocal): result[i] = ptr[i] self.lib.lammps_free(ptr) return result return None # set variable value # value is converted to string # returns 0 for success, -1 if failed def set_variable(self,name,value): if name: name = name.encode() if value: value = str(value).encode() return self.lib.lammps_set_variable(self.lmp,name,value) # return current value of thermo keyword def get_thermo(self,name): if name: name = name.encode() self.lib.lammps_get_thermo.restype = c_double return self.lib.lammps_get_thermo(self.lmp,name) # return total number of atoms in system def get_natoms(self): return self.lib.lammps_get_natoms(self.lmp) # return vector of atom properties gathered across procs, ordered by atom ID # name = atom property recognized by LAMMPS in atom->extract() # type = 0 for integer values, 1 for double values # count = number of per-atom valus, 1 for type or charge, 3 for x or f # returned data is a 1d vector - doc how it is ordered? # NOTE: how could we insure are converting to correct Python type # e.g. for Python list or NumPy, etc # ditto for extact_atom() above def gather_atoms(self,name,type,count): if name: name = name.encode() natoms = self.lib.lammps_get_natoms(self.lmp) if type == 0: data = ((count*natoms)*c_int)() self.lib.lammps_gather_atoms(self.lmp,name,type,count,data) elif type == 1: data = ((count*natoms)*c_double)() self.lib.lammps_gather_atoms(self.lmp,name,type,count,data) else: return None return data # scatter vector of atom properties across procs, ordered by atom ID # name = atom property recognized by LAMMPS in atom->extract() # type = 0 for integer values, 1 for double values # count = number of per-atom valus, 1 for type or charge, 3 for x or f # assume data is of correct type and length, as created by gather_atoms() # NOTE: how could we insure are passing correct type to LAMMPS # e.g. for Python list or NumPy, etc def scatter_atoms(self,name,type,count,data): if name: name = name.encode() self.lib.lammps_scatter_atoms(self.lmp,name,type,count,data) # create N atoms on all procs # N = global number of atoms # id = ID of each atom (optional, can be None) # type = type of each atom (1 to Ntypes) (required) # x = coords of each atom as (N,3) array (required) # v = velocity of each atom as (N,3) array (optional, can be None) # NOTE: how could we insure are passing correct type to LAMMPS # e.g. for Python list or NumPy, etc # ditto for gather_atoms() above def create_atoms(self,n,id,type,x,v,image=None,shrinkexceed=False): if id: id_lmp = (c_int * n)() id_lmp[:] = id else: id_lmp = id if image: image_lmp = (c_int * n)() image_lmp[:] = image else: image_lmp = image type_lmp = (c_int * n)() type_lmp[:] = type self.lib.lammps_create_atoms(self.lmp,n,id_lmp,type_lmp,x,v,image_lmp,shrinkexceed) @property def uses_exceptions(self): """ Return whether the LAMMPS shared library was compiled with C++ exceptions handling enabled """ try: if self.lib.lammps_has_error: return True except(AttributeError): return False # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- # ------------------------------------------------------------------------- ################################################################################ # Alternative Python Wrapper # Written by Richard Berger <richard.berger@temple.edu> ################################################################################ class OutputCapture(object): """ Utility class to capture LAMMPS library output """ def __init__(self): self.stdout_pipe_read, self.stdout_pipe_write = os.pipe() self.stdout_fd = 1 def __enter__(self): self.stdout = os.dup(self.stdout_fd) os.dup2(self.stdout_pipe_write, self.stdout_fd) return self def __exit__(self, type, value, tracebac): os.dup2(self.stdout, self.stdout_fd) os.close(self.stdout) os.close(self.stdout_pipe_read) os.close(self.stdout_pipe_write) # check if we have more to read from the pipe def more_data(self, pipe): r, _, _ = select.select([pipe], [], [], 0) return bool(r) # read the whole pipe def read_pipe(self, pipe): out = "" while self.more_data(pipe): out += os.read(pipe, 1024).decode() return out @property def output(self): return self.read_pipe(self.stdout_pipe_read) class Variable(object): def __init__(self, lammps_wrapper_instance, name, style, definition): self.wrapper = lammps_wrapper_instance self.name = name self.style = style self.definition = definition.split() @property def value(self): if self.style == 'atom': return list(self.wrapper.lmp.extract_variable(self.name, "all", 1)) else: value = self.wrapper.lmp_print('"${%s}"' % self.name).strip() try: return float(value) except ValueError: return value class AtomList(object): def __init__(self, lammps_wrapper_instance): self.lmp = lammps_wrapper_instance self.natoms = self.lmp.system.natoms self.dimensions = self.lmp.system.dimensions def __getitem__(self, index): if self.dimensions == 2: return Atom2D(self.lmp, index + 1) return Atom(self.lmp, index + 1) class Atom(object): def __init__(self, lammps_wrapper_instance, index): self.lmp = lammps_wrapper_instance self.index = index @property def id(self): return int(self.lmp.eval("id[%d]" % self.index)) @property def type(self): return int(self.lmp.eval("type[%d]" % self.index)) @property def mol(self): return self.lmp.eval("mol[%d]" % self.index) @property def mass(self): return self.lmp.eval("mass[%d]" % self.index) @property def position(self): return (self.lmp.eval("x[%d]" % self.index), self.lmp.eval("y[%d]" % self.index), self.lmp.eval("z[%d]" % self.index)) @position.setter def position(self, value): self.lmp.set("atom", self.index, "x", value[0]) self.lmp.set("atom", self.index, "y", value[1]) self.lmp.set("atom", self.index, "z", value[2]) @property def velocity(self): return (self.lmp.eval("vx[%d]" % self.index), self.lmp.eval("vy[%d]" % self.index), self.lmp.eval("vz[%d]" % self.index)) @property def force(self): return (self.lmp.eval("fx[%d]" % self.index), self.lmp.eval("fy[%d]" % self.index), self.lmp.eval("fz[%d]" % self.index)) @property def charge(self): return self.lmp.eval("q[%d]" % self.index) class Atom2D(Atom): def __init__(self, lammps_wrapper_instance, index): super(Atom2D, self).__init__(lammps_wrapper_instance, index) @property def position(self): return (self.lmp.eval("x[%d]" % self.index), self.lmp.eval("y[%d]" % self.index)) @position.setter def position(self, value): self.lmp.set("atom", self.index, "x", value[0]) self.lmp.set("atom", self.index, "y", value[1]) @property def velocity(self): return (self.lmp.eval("vx[%d]" % self.index), self.lmp.eval("vy[%d]" % self.index)) @property def force(self): return (self.lmp.eval("fx[%d]" % self.index), self.lmp.eval("fy[%d]" % self.index)) class variable_set: def __init__(self, name, variable_dict): self._name = name array_pattern = re.compile(r"(?P<arr>.+)\[(?P<index>[0-9]+)\]") for key, value in variable_dict.items(): m = array_pattern.match(key) if m: g = m.groupdict() varname = g['arr'] idx = int(g['index']) if varname not in self.__dict__: self.__dict__[varname] = {} self.__dict__[varname][idx] = value else: self.__dict__[key] = value def __str__(self): return "{}({})".format(self._name, ','.join(["{}={}".format(k, self.__dict__[k]) for k in self.__dict__.keys() if not k.startswith('_')])) def __repr__(self): return self.__str__() def get_thermo_data(output): """ traverse output of runs and extract thermo data columns """ if isinstance(output, str): lines = output.splitlines() else: lines = output runs = [] columns = [] in_run = False current_run = {} for line in lines: if line.startswith("Per MPI rank memory allocation"): in_run = True elif in_run and len(columns) == 0: # first line after memory usage are column names columns = line.split() current_run = {} for col in columns: current_run[col] = [] elif line.startswith("Loop time of "): in_run = False columns = None thermo_data = variable_set('ThermoData', current_run) r = {'thermo' : thermo_data } runs.append(namedtuple('Run', list(r.keys()))(*list(r.values()))) elif in_run and len(columns) > 0: values = [float(x) for x in line.split()] for i, col in enumerate(columns): current_run[col].append(values[i]) return runs class PyLammps(object): """ More Python-like wrapper for LAMMPS (e.g., for iPython) See examples/ipython for usage """ def __init__(self,name="",cmdargs=None,ptr=None,comm=None): if ptr: if isinstance(ptr,PyLammps): self.lmp = ptr.lmp elif isinstance(ptr,lammps): self.lmp = ptr else: self.lmp = lammps(name=name,cmdargs=cmdargs,ptr=ptr,comm=comm) else: self.lmp = lammps(name=name,cmdargs=cmdargs,ptr=None,comm=comm) print("LAMMPS output is captured by PyLammps wrapper") self._cmd_history = [] self.runs = [] def __del__(self): if self.lmp: self.lmp.close() self.lmp = None def close(self): if self.lmp: self.lmp.close() self.lmp = None def version(self): return self.lmp.version() def file(self,file): self.lmp.file(file) def write_script(self,filename): """ Write LAMMPS script file containing all commands executed up until now """ with open(filename, "w") as f: for cmd in self._cmd_history: f.write("%s\n" % cmd) def command(self,cmd): self.lmp.command(cmd) self._cmd_history.append(cmd) def run(self, *args, **kwargs): output = self.__getattr__('run')(*args, **kwargs) self.runs += get_thermo_data(output) return output @property def last_run(self): if len(self.runs) > 0: return self.runs[-1] return None @property def atoms(self): return AtomList(self) @property def system(self): output = self.info("system") d = self._parse_info_system(output) return namedtuple('System', d.keys())(*d.values()) @property def communication(self): output = self.info("communication") d = self._parse_info_communication(output) return namedtuple('Communication', d.keys())(*d.values()) @property def computes(self): output = self.info("computes") return self._parse_element_list(output) @property def dumps(self): output = self.info("dumps") return self._parse_element_list(output) @property def fixes(self): output = self.info("fixes") return self._parse_element_list(output) @property def groups(self): output = self.info("groups") return self._parse_groups(output) @property def variables(self): output = self.info("variables") vars = {} for v in self._parse_element_list(output): vars[v['name']] = Variable(self, v['name'], v['style'], v['def']) return vars def eval(self, expr): value = self.lmp_print('"$(%s)"' % expr).strip() try: return float(value) except ValueError: return value def _split_values(self, line): return [x.strip() for x in line.split(',')] def _get_pair(self, value): return [x.strip() for x in value.split('=')] def _parse_info_system(self, output): lines = output[6:-2] system = {} for line in lines: if line.startswith("Units"): system['units'] = self._get_pair(line)[1] elif line.startswith("Atom style"): system['atom_style'] = self._get_pair(line)[1] elif line.startswith("Atom map"): system['atom_map'] = self._get_pair(line)[1] elif line.startswith("Atoms"): parts = self._split_values(line) system['natoms'] = int(self._get_pair(parts[0])[1]) system['ntypes'] = int(self._get_pair(parts[1])[1]) system['style'] = self._get_pair(parts[2])[1] elif line.startswith("Kspace style"): system['kspace_style'] = self._get_pair(line)[1] elif line.startswith("Dimensions"): system['dimensions'] = int(self._get_pair(line)[1]) elif line.startswith("Orthogonal box"): system['orthogonal_box'] = [float(x) for x in self._get_pair(line)[1].split('x')] elif line.startswith("Boundaries"): system['boundaries'] = self._get_pair(line)[1] elif line.startswith("xlo"): keys, values = [self._split_values(x) for x in self._get_pair(line)] for key, value in zip(keys, values): system[key] = float(value) elif line.startswith("ylo"): keys, values = [self._split_values(x) for x in self._get_pair(line)] for key, value in zip(keys, values): system[key] = float(value) elif line.startswith("zlo"): keys, values = [self._split_values(x) for x in self._get_pair(line)] for key, value in zip(keys, values): system[key] = float(value) elif line.startswith("Molecule type"): system['molecule_type'] = self._get_pair(line)[1] elif line.startswith("Bonds"): parts = self._split_values(line) system['nbonds'] = int(self._get_pair(parts[0])[1]) system['nbondtypes'] = int(self._get_pair(parts[1])[1]) system['bond_style'] = self._get_pair(parts[2])[1] elif line.startswith("Angles"): parts = self._split_values(line) system['nangles'] = int(self._get_pair(parts[0])[1]) system['nangletypes'] = int(self._get_pair(parts[1])[1]) system['angle_style'] = self._get_pair(parts[2])[1] elif line.startswith("Dihedrals"): parts = self._split_values(line) system['ndihedrals'] = int(self._get_pair(parts[0])[1]) system['nangletypes'] = int(self._get_pair(parts[1])[1]) system['dihedral_style'] = self._get_pair(parts[2])[1] elif line.startswith("Impropers"): parts = self._split_values(line) system['nimpropers'] = int(self._get_pair(parts[0])[1]) system['nimpropertypes'] = int(self._get_pair(parts[1])[1]) system['improper_style'] = self._get_pair(parts[2])[1] return system def _parse_info_communication(self, output): lines = output[6:-3] comm = {} for line in lines: if line.startswith("MPI library"): comm['mpi_version'] = line.split(':')[1].strip() elif line.startswith("Comm style"): parts = self._split_values(line) comm['comm_style'] = self._get_pair(parts[0])[1] comm['comm_layout'] = self._get_pair(parts[1])[1] elif line.startswith("Processor grid"): comm['proc_grid'] = [int(x) for x in self._get_pair(line)[1].split('x')] elif line.startswith("Communicate velocities for ghost atoms"): comm['ghost_velocity'] = (self._get_pair(line)[1] == "yes") elif line.startswith("Nprocs"): parts = self._split_values(line) comm['nprocs'] = int(self._get_pair(parts[0])[1]) comm['nthreads'] = int(self._get_pair(parts[1])[1]) return comm def _parse_element_list(self, output): lines = output[6:-3] elements = [] for line in lines: element_info = self._split_values(line.split(':')[1].strip()) element = {'name': element_info[0]} for key, value in [self._get_pair(x) for x in element_info[1:]]: element[key] = value elements.append(element) return elements def _parse_groups(self, output): lines = output[6:-3] groups = [] group_pattern = re.compile(r"(?P<name>.+) \((?P<type>.+)\)") for line in lines: m = group_pattern.match(line.split(':')[1].strip()) group = {'name': m.group('name'), 'type': m.group('type')} groups.append(group) return groups def lmp_print(self, s): """ needed for Python2 compatibility, since print is a reserved keyword """ return self.__getattr__("print")(s) def __dir__(self): return ['angle_coeff', 'angle_style', 'atom_modify', 'atom_style', 'atom_style', 'bond_coeff', 'bond_style', 'boundary', 'change_box', 'communicate', 'compute', 'create_atoms', 'create_box', 'delete_atoms', 'delete_bonds', 'dielectric', 'dihedral_coeff', 'dihedral_style', 'dimension', 'dump', 'fix', 'fix_modify', 'group', 'improper_coeff', 'improper_style', 'include', 'kspace_modify', 'kspace_style', 'lattice', 'mass', 'minimize', 'min_style', 'neighbor', 'neigh_modify', 'newton', 'nthreads', 'pair_coeff', 'pair_modify', 'pair_style', 'processors', 'read', 'read_data', 'read_restart', 'region', 'replicate', 'reset_timestep', 'restart', 'run', 'run_style', 'thermo', 'thermo_modify', 'thermo_style', 'timestep', 'undump', 'unfix', 'units', 'variable', 'velocity', 'write_restart'] def __getattr__(self, name): def handler(*args, **kwargs): cmd_args = [name] + [str(x) for x in args] with OutputCapture() as capture: self.command(' '.join(cmd_args)) output = capture.output if 'verbose' in kwargs and kwargs['verbose']: print(output) lines = output.splitlines() if len(lines) > 1: return lines elif len(lines) == 1: return lines[0] return None return handler class IPyLammps(PyLammps): """ iPython wrapper for LAMMPS which adds embedded graphics capabilities """ def __init__(self,name="",cmdargs=None,ptr=None,comm=None): super(IPyLammps, self).__init__(name=name,cmdargs=cmdargs,ptr=ptr,comm=comm) def image(self, filename="snapshot.png", group="all", color="type", diameter="type", size=None, view=None, center=None, up=None, zoom=1.0): cmd_args = [group, "image", filename, color, diameter] if size: width = size[0] height = size[1] cmd_args += ["size", width, height] if view: theta = view[0] phi = view[1] cmd_args += ["view", theta, phi] if center: flag = center[0] Cx = center[1] Cy = center[2] Cz = center[3] cmd_args += ["center", flag, Cx, Cy, Cz] if up: Ux = up[0] Uy = up[1] Uz = up[2] cmd_args += ["up", Ux, Uy, Uz] if zoom: cmd_args += ["zoom", zoom] cmd_args.append("modify backcolor white") self.write_dump(*cmd_args) from IPython.core.display import Image return Image('snapshot.png') def video(self, filename): from IPython.display import HTML return HTML("<video controls><source src=\"" + filename + "\"></video>") ```
[ { "content": "Here is a code snippet:\n```python\nimport os\nimport re\nfrom functools import wraps\nfrom urlparse import urlparse\nimport math\n\nfrom elasticutils import S\nfrom elasticgit.search import RepoHelper\n\n\ndefault_excluded_paths = ['/health/', '/api/notify/']\n\n\ndef is_excluded_path(path, exclu...
[ { "content": "Here is a code snippet:\n<|memory_start|>```python\nimport os\nimport re\nfrom functools import wraps\nfrom urlparse import urlparse\nimport math\n\nfrom elasticutils import S\nfrom elasticgit.search import RepoHelper\n\n\ndefault_excluded_paths = ['/health/', '/api/notify/']\n\n\ndef is_excluded_...
```python import os import re from functools import wraps from urlparse import urlparse import math from elasticutils import S from elasticgit.search import RepoHelper default_excluded_paths = ['/health/', '/api/notify/'] def is_excluded_path(path, excluded_paths): excl_paths = config_list(excluded_paths) + default_excluded_paths return ( path and any([p for p in excl_paths if path.startswith(p)])) def parse_repo_name(repo_url): pr = urlparse(repo_url) _, _, repo_name_dot_ext = pr.path.rpartition('/') if any([ repo_name_dot_ext.endswith('.git'), repo_name_dot_ext.endswith('.json')]): repo_name, _, _ = repo_name_dot_ext.partition('.') return repo_name return repo_name_dot_ext def is_remote_repo_url(repo_url): return any([ repo_url.startswith('http://'), repo_url.startswith('https://')]) def repo_url(repo_dir, repo_location): # If repo_location is an http URL we leave it as is and # assume it specifies a unicore.distribute repo endpoint. # If repo_location is not an http URL, we assume it specifies # a local repo in repo_dir. if is_remote_repo_url(repo_location): return repo_location return os.path.abspath(os.path.join(repo_dir, repo_location)) def ga_context(context_func): """ A decorator for Cornice views that allows one to set extra parameters for Google Analytics tracking:: @ga_context(lambda context: {'dt': context['category'].title, }) @view_config(route_name='page') def view(request): return { 'category': self.workspace.S(Category).filter(title='foo')[0], } :param func context_func: A function which takes one argument, a context dictionary made available to the template. :returns: A dict containing the extra variables for Google Analytics tracking. """ def decorator(func): @wraps(func) def wrapper(self, *args, **kwargs): context = func(self, *args, **kwargs) self.request.google_analytics.update(context_func(context)) return context return wrapper return decorator def config_list(data): """ A function that takes a string of values separated by newline characters and returns a list of those values :param func context_func: A function which takes one argument, a string of values separated by newline characters :returns: A list containing the values separated by newline characters, stripped of whitespace between the value and newline character """ return filter(None, (x.strip() for x in data.splitlines())) def config_dict(data): """ A function that takes a string of pair values, indicated by '=', separated by newline characters and returns a dict of those value pairs :param func context_func: A function which takes one argument, a string of value pairs with '= between them' separated by newline characters :returns: A dict containing the value pairs separated by newline characters """ lines = config_list(data) return dict(re.split('\s*=\s*', value) for value in lines) class Paginator(object): """ A thing that helps us page through result sets :param iterable results: The iterable of objects to paginate. :param int page: The page number, zero-based. :param int results_per_page: The number of objects in each page. :param int slider_value: The number of page numbers to display, excluding the current page. """ def __init__(self, results, page, results_per_page=10, slider_value=5): self.results = results self.page = page self.results_per_page = results_per_page self.slider_value = slider_value self.buffer_value = self.slider_value / 2 def total_count(self): if isinstance(self.results, S): return self.results.count() return len(self.results) def get_page(self): return self.results[self.page * self.results_per_page: (self.page + 1) * self.results_per_page] def has_next_page(self): return ((self.page + 1) * self.results_per_page) < self.total_count() def has_previous_page(self): return self.page def total_pages(self): return int( math.ceil( float(self.total_count()) / float(self.results_per_page))) def page_numbers(self): if (self.page - self.buffer_value) < 0: return [page_number for page_number in range( 0, min([self.slider_value, self.total_pages()]))] elif (self.page + self.buffer_value) >= self.total_pages(): return [page_number for page_number in range( max((self.total_pages() - self.slider_value), 0), self.total_pages()) ] else: return range(self.page - self.buffer_value, self.page + self.buffer_value + 1) def page_numbers_left(self): page_numbers = self.page_numbers() if not any(page_numbers): return False return page_numbers[:page_numbers.index(self.page)] def page_numbers_right(self): page_numbers = self.page_numbers() if not any(page_numbers): return False return page_numbers[page_numbers.index(self.page) + 1:] def needs_start_ellipsis(self): page_numbers = self.page_numbers() if not any(page_numbers): return False return page_numbers[0] > 1 def needs_end_ellipsis(self): page_numbers = self.page_numbers() if not any(page_numbers): return False return page_numbers[-1] < (self.total_pages() - 2) def show_start(self): page_numbers = self.page_numbers() if not any(page_numbers): return False return page_numbers[0] > 0 def show_end(self): page_numbers = self.page_numbers() if not any(page_numbers): return False return page_numbers[-1] < self.total_pages() - 1 class CachingRepoHelper(RepoHelper): """ A subclass of RepoHelper that caches the repo's active branch name to avoid remote calls to get the repo branch. """ def active_branch_name(self): if not hasattr(self, '_active_branch_name'): self._active_branch_name = super( CachingRepoHelper, self).active_branch_name() return self._active_branch_name ```
[ { "content": "```python\nfrom lib.data.message import Message\nfrom tests.unittest.base_custom import TestCustomField\n\n# Needs to be imported last\nfrom ..custom import query\n\n\nclass TestCustomCommandCustomQuery(TestCustomField):\n def setUp(self):\n super().setUp()\n self.args = self.args...
[ { "content": "<|memory_start|>```python\nfrom lib.data.message import Message\nfrom tests.unittest.base_custom import TestCustomField\n\n# Needs to be imported last\nfrom ..custom import query\n\n\nclass TestCustomCommandCustomQuery(TestCustomField):\n def setUp(self):\n super().setUp()\n self....
```python from lib.data.message import Message from tests.unittest.base_custom import TestCustomField # Needs to be imported last from ..custom import query class TestCustomCommandCustomQuery(TestCustomField): def setUp(self): super().setUp() self.args = self.args._replace(field='query', message=Message('a b c')) async def test(self): self.args = self.args._replace(field='') self.assertIsNone(await query.fieldQuery(self.args)) async def test_query(self): self.assertEqual(await query.fieldQuery(self.args), 'b c') async def test_caps(self): self.args = self.args._replace(field='QUERY') self.assertEqual(await query.fieldQuery(self.args), 'b c') async def test_default(self): self.args = self.args._replace(message=Message(''), prefix='[', suffix=']') self.assertEqual(await query.fieldQuery(self.args), '') async def test_prefix(self): self.args = self.args._replace(prefix='[') self.assertEqual(await query.fieldQuery(self.args), '[b c') async def test_prefix_blank(self): self.args = self.args._replace(prefix='') self.assertEqual(await query.fieldQuery(self.args), 'b c') async def test_suffix(self): self.args = self.args._replace(suffix=']') self.assertEqual(await query.fieldQuery(self.args), 'b c]') async def test_suffix_blank(self): self.args = self.args._replace(suffix='') self.assertEqual(await query.fieldQuery(self.args), 'b c') ```
[ { "content": "Recreate the original code text:\n```python\n# -*- coding: utf-8 -*-\n# Generated by Django 1.9.1 on 2016-05-02 14:13\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.delet...
[ { "content": "Recreate the original code text:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# Generated by Django 1.9.1 on 2016-05-02 14:13\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nimport django.core.validators\nfrom django.db import migrations, models\nimport django...
```python # -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-05-02 14:13 from __future__ import unicode_literals from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion import sharingcars.helpers.User class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ] operations = [ migrations.CreateModel( name='Actor', fields=[ ('user_account', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('subject', models.CharField(max_length=256)), ('comment', models.TextField()), ('rating', models.IntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])), ], ), migrations.CreateModel( name='Folder', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=256)), ], ), migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('subject', models.CharField(max_length=256)), ('body', models.TextField(max_length=256)), ('creationMoment', models.DateTimeField(auto_now_add=True)), ('folder', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='common.Folder')), ], ), migrations.CreateModel( name='Administrator', fields=[ ('actor_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='common.Actor')), ], bases=('common.actor',), ), migrations.CreateModel( name='User', fields=[ ('actor_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='common.Actor')), ('name', models.CharField(max_length=256)), ('surnames', models.CharField(max_length=256)), ('city', models.CharField(max_length=256)), ('birthdate', models.DateField()), ('phone', models.CharField(max_length=256, validators=[django.core.validators.RegexValidator('^\\+?\\d+$')])), ('searchinCar', models.BooleanField(default=False)), ('photo', models.ImageField(default='default', null=True, upload_to=sharingcars.helpers.User.path_generator)), ], bases=('common.actor',), ), migrations.AddField( model_name='message', name='recipient', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipient', to='common.Actor'), ), migrations.AddField( model_name='message', name='sender', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sender', to='common.Actor'), ), migrations.AddField( model_name='folder', name='actor', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='common.Actor'), ), migrations.AddField( model_name='comment', name='evaluated', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='evaluated', to='common.User'), ), migrations.AddField( model_name='comment', name='referrer', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='referrer', to='common.User'), ), ] ```
[ { "content": "Here is some code:\n```python\nimport datetime\nimport logging\nimport re\nimport socket\nimport subprocess\nimport os\n\nfrom django.conf import settings\n\nfrom . import exceptions as dakku_exception\n\nlogger = logging.getLogger(__name__)\n\n\nclass BackupBase(object):\n\n def deletefile(sel...
[ { "content": "Here is some code:\n<|memory_start|>```python\nimport datetime\nimport logging\nimport re\nimport socket\nimport subprocess\nimport os\n\nfrom django.conf import settings\n\nfrom . import exceptions as dakku_exception\n\nlogger = logging.getLogger(__name__)\n\n\nclass BackupBase(object):\n\n de...
```python import datetime import logging import re import socket import subprocess import os from django.conf import settings from . import exceptions as dakku_exception logger = logging.getLogger(__name__) class BackupBase(object): def deletefile(self, date_str): """Given a date in YYYYMMDD check if the file should be deleted or keep""" today = datetime.date.today() date = datetime.date(int(date_str[:4]), int(date_str[4:6]), int(date_str[6:8])) age = today - date if age < datetime.timedelta(weeks=2): if self.verbose: print('keeping < 2 weeks') return False if age < datetime.timedelta(weeks=8) and date.weekday() == 0: if self.verbose: print('keeping monday') return False if date.day == 2: if self.verbose: print('keeping first of the month') return False return True class BackupUtil(object): def __init__(self, router, container_name, dry_run=False, verbose=False): from .mysql import MysqlUtil from .rackspace import RackspaceUtil self.mysql = MysqlUtil(router, verbose) self.rackspace = RackspaceUtil(container_name, verbose, dry_run=dry_run) self.verbose = verbose self.start_time = datetime.datetime.utcnow() if not os.path.exists(settings.BACKUP_DIR): os.mkdir(settings.BACKUP_DIR) def _run_cmd(self, cmd, filepath, ext=None): if self.verbose: print(cmd) subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) if ext is not None: filepath += ext filesize = os.stat(filepath).st_size if filesize == 0: raise dakku_exception.BadFileSize('Bad filesize for "%s"' % (filepath)) return filepath, filesize def tar_directory(self, directory, prefix=None): root, name = os.path.split(directory) name = '%s.%s-%s.tar.bz2' % \ (name, self.start_time.strftime('%Y%m%d_%H%M%S'), socket.gethostname()) if prefix is not None: backup_dir = '%s/%s' % (settings.BACKUP_DIR, prefix) else: backup_dir = settings.BACKUP_DIR if not os.path.exists(backup_dir): os.mkdir(backup_dir) filepath = '%s/%s' % (backup_dir, name) cmd = '/bin/tar cfj %s %s -C %s' % (filepath, directory, root) return self._run_cmd(cmd, filepath) def backup_database(self): dbfile = self.mysql.dump() uploaded = self.rackspace.store(dbfile, 'db') logger.info('Uploaded %s to %s %s' % (dbfile, uploaded.name, uploaded.size)) if self.verbose: print(uploaded.name) os.unlink(dbfile) return uploaded def backup_site(self): filepath, filesize = self.tar_directory(settings.SITE_ROOT, 'site') if self.verbose: print('%s %s' % (filepath, filesize)) uploaded = self.rackspace.store(filepath, 'site') logger.info('Uploaded %s to %s %s' % (filepath, uploaded.name, uploaded.size)) if self.verbose: print(uploaded.name) return uploaded def backup_all(self): self.backup_database() self.backup_site() deletes = self.rackspace.cull() for deleted in deletes: logger.info('Deleted %s' % (deleted.name)) if self.verbose: print('Deleted: %s' % (deleted.name)) deletes = self.cull() for deleted in deletes: logger.info('Deleted %s' % (deleted.name)) if self.verbose: print('Deleted: %s' % (deleted.name)) def restore(self, filename=None, remote=None): self.mysql.dump() self.mysql.drop() self.mysql.create() if remote is not None: filename = self.rackspace.get(remote, settings.BACKUP_DIR) return self.mysql.source(filename) def list(self): for obj in self.rackspace.list(): print('%s %s' % (obj.name, obj.size)) def cull_local(self): culled = [] files = os.listdir(settings.BACKUP_DIR) for filename in files: filepath = '%s/%s/' % (settings.BACKUP_DIR, filename) search = re.search(r'(\d{8})', filename) if search is None: continue if self.deletefile(search.group(0)): if self.verbose: print('Deleting %s' % (filename)) if not self.dry_run: os.unlink(filepath) culled.append(filename) elif self.verbose: print('Keeping %s' % (filename)) return culled def cull(self): self.rackspace.cull() self.cull_local() ```
[ { "content": "```python\nimport logging\nfrom HTMLParser import HTMLParser\nfrom lxml.html.clean import Cleaner\nfrom lxml.etree import XMLSyntaxError\n\nclass HTMLSanitizer:\n\n\n\n @classmethod\n def sanitize_and_parse(cls, data):\n if data is not None:\n sanitized = HTMLSanitizer._san...
[ { "content": "<|memory_start|>```python\nimport logging\nfrom HTMLParser import HTMLParser\nfrom lxml.html.clean import Cleaner\nfrom lxml.etree import XMLSyntaxError\n\nclass HTMLSanitizer:\n\n\n\n @classmethod\n def sanitize_and_parse(cls, data):\n if data is not None:\n sanitized = HT...
```python import logging from HTMLParser import HTMLParser from lxml.html.clean import Cleaner from lxml.etree import XMLSyntaxError class HTMLSanitizer: @classmethod def sanitize_and_parse(cls, data): if data is not None: sanitized = HTMLSanitizer._sanitize(data) parsed = HTMLSanitizer._parse(sanitized) result = parsed.encode("utf-8", "ignore") return result @classmethod def _sanitize(cls, data): cleaner = Cleaner() #by default Cleaner remove all malicious data from string cleaner.style = True #I only add omitting style tags try: result = cleaner.clean_html(data) except XMLSyntaxError as e: logging.error("There was an error with sanitizing data (data length: %d): %s" % (len(data), data)) logging.exception(e) return "" return result @classmethod def _parse(cls, data): parser = ExtendedParser() parser.feed(data) return parser.get_data() class ExtendedParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.reset() self.text = [] def handle_data(self, data): self.text.append(data) def handle_charref(self, name): charref = "&#%s;" % name self.text.append(charref) def get_data(self): r = " ".join(self.text).split(" ") result = [] for word in r: w = word.strip("\n") if len(w) > 0: result.append(w) return " ".join(result) ```
[ { "content": "Produce an exact reconstruction of the code:\n```python\nfrom troposphere import GetAtt, If, Join, Output, Ref\nfrom troposphere import elasticloadbalancing as elb\n\nfrom . import USE_ECS, USE_GOVCLOUD\nfrom .security_groups import load_balancer_security_group\nfrom .template import template\nfro...
[ { "content": "Produce an exact reconstruction of the code:\n<|memory_start|>```python\nfrom troposphere import GetAtt, If, Join, Output, Ref\nfrom troposphere import elasticloadbalancing as elb\n\nfrom . import USE_ECS, USE_GOVCLOUD\nfrom .security_groups import load_balancer_security_group\nfrom .template impo...
```python from troposphere import GetAtt, If, Join, Output, Ref from troposphere import elasticloadbalancing as elb from . import USE_ECS, USE_GOVCLOUD from .security_groups import load_balancer_security_group from .template import template from .utils import ParameterWithDefaults as Parameter from .vpc import public_subnet_a, public_subnet_b # Web worker if USE_ECS: web_worker_port = Ref(template.add_parameter( Parameter( "WebWorkerPort", Description="Web worker container exposed port", Type="Number", Default="8000", ), group="Load Balancer", label="Web Worker Port", )) else: # default to port 80 for EC2 and Elastic Beanstalk options web_worker_port = Ref(template.add_parameter( Parameter( "WebWorkerPort", Description="Default web worker exposed port (non-HTTPS)", Type="Number", Default="80", ), group="Load Balancer", label="Web Worker Port", )) web_worker_protocol = Ref(template.add_parameter( Parameter( "WebWorkerProtocol", Description="Web worker instance protocol", Type="String", Default="HTTP", AllowedValues=["HTTP", "HTTPS"], ), group="Load Balancer", label="Web Worker Protocol", )) # Web worker health check web_worker_health_check_protocol = Ref(template.add_parameter( Parameter( "WebWorkerHealthCheckProtocol", Description="Web worker health check protocol", Type="String", Default="TCP", AllowedValues=["TCP", "HTTP", "HTTPS"], ), group="Load Balancer", label="Health Check: Protocol", )) web_worker_health_check_port = Ref(template.add_parameter( Parameter( "WebWorkerHealthCheckPort", Description="Web worker health check port", Type="Number", Default="80", ), group="Load Balancer", label="Health Check: Port", )) web_worker_health_check = Ref(template.add_parameter( Parameter( "WebWorkerHealthCheck", Description="Web worker health check URL path, e.g., \"/health-check\"; " "required unless WebWorkerHealthCheckProtocol is TCP", Type="String", Default="", ), group="Load Balancer", label="Health Check: URL", )) # Web load balancer listeners = [ elb.Listener( LoadBalancerPort=80, InstanceProtocol=web_worker_protocol, InstancePort=web_worker_port, Protocol='HTTP', ) ] if USE_GOVCLOUD: # configure the default HTTPS listener to pass TCP traffic directly, # since GovCloud doesn't support the Certificate Manager (this can be # modified to enable SSL termination at the load balancer via the AWS # console, if needed) listeners.append(elb.Listener( LoadBalancerPort=443, InstanceProtocol='TCP', InstancePort=443, Protocol='TCP', )) else: from .certificates import application as application_certificate from .certificates import cert_condition listeners.append(If(cert_condition, elb.Listener( LoadBalancerPort=443, InstanceProtocol=web_worker_protocol, InstancePort=web_worker_port, Protocol='HTTPS', SSLCertificateId=application_certificate, ), Ref("AWS::NoValue"))) load_balancer = elb.LoadBalancer( 'LoadBalancer', template=template, Subnets=[ Ref(public_subnet_a), Ref(public_subnet_b), ], SecurityGroups=[Ref(load_balancer_security_group)], Listeners=listeners, HealthCheck=elb.HealthCheck( Target=Join("", [ web_worker_health_check_protocol, ":", web_worker_health_check_port, web_worker_health_check, ]), HealthyThreshold="2", UnhealthyThreshold="2", Interval="100", Timeout="10", ), CrossZone=True, ) template.add_output(Output( "LoadBalancerDNSName", Description="Loadbalancer DNS", Value=GetAtt(load_balancer, "DNSName") )) template.add_output(Output( "LoadBalancerHostedZoneID", Description="Loadbalancer hosted zone", Value=GetAtt(load_balancer, "CanonicalHostedZoneNameID") )) ```
[ { "content": "Repeat the full code snippet:\n```python\n\"\"\"\nevents.py\n\nDefines a simple event handler system similar to that used in C#. Events allow\nmulticast delegates and arbitrary message passing. They use weak references so\nthey don't keep their handlers alive if they are otherwise out of scope.\n...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\n\"\"\"\nevents.py\n\nDefines a simple event handler system similar to that used in C#. Events allow\nmulticast delegates and arbitrary message passing. They use weak references so\nthey don't keep their handlers alive if they are otherwise...
```python """ events.py Defines a simple event handler system similar to that used in C#. Events allow multicast delegates and arbitrary message passing. They use weak references so they don't keep their handlers alive if they are otherwise out of scope. """ import weakref import maya.utils from functools import partial, wraps import inspect class Event(object): """ Simple event handler, similar to the standard c# event pattern. The object raising an event calls this event object as a callable; the object will in turn fire any of the callables it stores in its Handlers list, passing the args and kwargs provided by the original caller. sample usage: test = Event() > def a ( *args, **kwargs ): print "A", args, kwargs > test += a; > test( 'arg1', 'arg2', e="fred" ) A ('arg1', 'arg2') {'e': 'fred', 'event': <Event object at 0x00000000026892E8>} the handlers are stored as weakrefs, so they will not keep their referents alive if those referents exists in no other scope. For example: > x = Event() > def test(*args, **kwargs): > print "hello world" > x += test > x() hello world > test = None > x() a hard reference to a handler can be stored on another object when binding to the event, this can be used for when handlers are defined inside another functions scope. For example: > x = Event() > def test(*args, **kwargs): > print 'hello world' > class Stash(object): > pass > stash = Stash() > x += test, stash > del test > x() hello world > del stash > x() Handlers must exhibit the *args, **kwargs signature. It's the handler's job to decide what to do with them but they will be passed. Events can be given 'metadata' - arguments that are passed in at creation time: x = Event(name = 'test_event') def test (*args, *kwargs): print args, kwargs x() {'name': 'test_event', 'event': <Event object at 0x00000000026892E8>} Metadata added when the Event is first created will be included in every firing of the event. Arguments and keywords can also be associated with a particular firing: x = Event(name = 'test_event') def test (*args, *kwargs): print "args:", args print "kwargs:", kwargs x('hello') args: hello kwargs: {'name': 'test_event', 'event': <Event object at 0x00000000026892E8>} x('world') args: world kwargs: {'name': 'test_event', 'event': <Event object at 0x00000000026892E8>} """ def __init__(self, **data): self._handlers = set() '''Set list of handlers callables. Use a set to avoid multiple calls on one handler''' self.data = data self.data['event'] = self def _add_handler(self, handler): """ Add a handler callable. Raises a ValueError if the argument is not callable """ stash = None if isinstance(handler, tuple): handler, stash = handler if not callable(handler): raise ValueError("%s is not callable", handler) if stash is not None: setattr(stash, '_sh_{}'.format(id(handler)), handler) self._handlers.add(get_weak_reference(handler)) return self def _remove_handler(self, handler): """ Remove a handler. Ignores handlers that are not present. """ stash = None if isinstance(handler, tuple): handler, stash = handler try: delattr(stash, '_sh_{}'.format(id(handler))) except AttributeError: pass wr = get_weak_reference(handler) delenda = [h for h in self._handlers if h == wr] self._handlers = self._handlers.difference(set(delenda)) return self def metadata(self, kwargs): """ returns the me """ md = {} md.update(self.data) md.update(kwargs) return md def _fire(self, *args, **kwargs): """ Call all handlers. Any decayed references will be purged. """ delenda = [] for handler in self._handlers: try: handler(*args, **self.metadata(kwargs)) except DeadReferenceError: delenda.append(handler) self._handlers = self._handlers.difference(set(delenda)) def _handler_count(self): """ Returns the count of the _handlers field """ return len([i for i in self._handlers]) # hook up the instance methods to the base methods # doing it this way allows you to override more neatly # in derived classes __call__ = _fire __len__ = _handler_count __iadd__ = _add_handler __isub__ = _remove_handler def __del__(self): print 'event expired' class MayaEvent(Event): """ Subclass of event that uses Maya.utils.executeDeferred. """ def _fire(self, *args, **kwargs): """ Call all handlers. Any decayed references will be purged. """ delenda = [] for handler in self._handlers: try: maya.utils.executeDeferred(partial(handler, *args, **self.metadata(kwargs))) except DeadReferenceError: delenda.append(handler) self._handlers = self._handlers.difference(set(delenda)) __call__ = _fire class DeadReferenceError(TypeError): """ Raised when a WeakMethodBound or WeakMethodFree tries to fire a method that has been garbage collected. Used by Events to know when to drop dead references """ pass # # create weak references to both bound and unbound methods # # hat tip to Frederic Jolliton on ActiveState class WeakMethodBound(object): """ Encapsulates a weak reference to a bound method on an object. Has a hashable ID so that Events can identify multiple references to the same method and not duplicate them """ __slots__ = ('function', 'referent', 'ID', '_ref_name') def __init__(self, f): self.function = f.im_func self.referent = weakref.ref(f.im_self) self._ref_name = f.im_func.__name__ self.ID = id(f.im_self) ^ id(f.im_func.__name__) def __call__(self, *args, **kwargs): ref = self.referent() if not ref is False and not ref is None: return apply(self.function, (self.referent(),) + args, kwargs) else: raise DeadReferenceError("Reference to the bound method {0} no longer exists".format(self._ref_name)) def __eq__(self, other): if not hasattr(other, 'ID'): return False return self.ID == other.ID def __hash__(self): return self.ID class WeakMethodFree(object): """ Encapsulates a weak reference to an unbound method """ __slots__ = ('function', 'ID', '_ref_name') def __init__(self, f): self.function = weakref.ref(f) self.ID = id(f) self._ref_name = getattr(f, '__name__', "'unnamed'") def __call__(self, *args, **kwargs): if self.function(): return apply(self.function(), args, kwargs) else: raise DeadReferenceError("Reference to unbound method {0} no longer exists".format(self._ref_name)) def __eq__(self, other): if not hasattr(other, 'ID'): return False return self.ID == other.ID def __hash__(self): return self.ID def get_weak_reference(f): """ Returns a WeakMethodFree or a WeakMethodBound for the supplied function, as appropriate """ try: f.im_func except AttributeError: return WeakMethodFree(f) return WeakMethodBound(f) def event_handler(fn): """ decorator for making event handlers out of functions with no arguments """ if inspect.getargspec(fn).varargs and inspect.getargspec(fn).keywords: return fn @wraps(fn) def wrapper(*_, **__): return fn() return wrapper ```
[ { "content": "Write the code verbatim:\n```python\nr\"\"\"JSON (JavaScript Object Notation) <http://json.org> is a subset of\r\nJavaScript syntax (ECMA-262 3rd edition) used as a lightweight data\r\ninterchange format.\r\n\r\n:mod:`simplejson` exposes an API familiar to users of the standard library\r\n:mod:`ma...
[ { "content": "Write the code verbatim:\n<|memory_start|>```python\nr\"\"\"JSON (JavaScript Object Notation) <http://json.org> is a subset of\r\nJavaScript syntax (ECMA-262 3rd edition) used as a lightweight data\r\ninterchange format.\r\n\r\n:mod:`simplejson` exposes an API familiar to users of the standard lib...
```python r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print(json.dumps("\"foo\bar")) "\"foo\bar" >>> print(json.dumps(u'\u1234')) "\u1234" >>> print(json.dumps('\\')) "\\" >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) {"a": 0, "b": 0, "c": 0} >>> from simplejson.compat import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> obj = [1,2,3,{'4': 5, '6': 7}] >>> json.dumps(obj, separators=(',',':'), sort_keys=True) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ')) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from simplejson.compat import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> from decimal import Decimal >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError(repr(o) + " is not JSON serializable") ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 3 (char 2) """ from __future__ import absolute_import __version__ = '3.3.0' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', 'OrderedDict', 'simple_first', ] __author__ = 'Bob Ippolito <bob@redivi.com>' from decimal import Decimal from .scanner import JSONDecodeError from .decoder import JSONDecoder from .encoder import JSONEncoder, JSONEncoderForHTML def _import_OrderedDict(): import collections try: return collections.OrderedDict except AttributeError: from . import ordered_dict return ordered_dict.OrderedDict OrderedDict = _import_OrderedDict() def _import_c_make_encoder(): try: from ._speedups import make_encoder return make_encoder except ImportError: return None _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If *skipkeys* is true then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If *ensure_ascii* is false, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If *check_circular* is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If *allow_nan* is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the original JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). See *ignore_nan* for ECMA-262 compliant behavior. If *indent* is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, *separators* should be an ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most compact JSON representation, you should specify ``(',', ':')`` to eliminate whitespace. *encoding* is the character encoding for str instances, default is UTF-8. *default(obj)* is a function that should return a serializable version of obj or raise ``TypeError``. The default simply raises ``TypeError``. If *use_decimal* is true (default: ``True``) then decimal.Decimal will be natively serialized to JSON with full precision. If *namedtuple_as_object* is true (default: ``True``), :class:`tuple` subclasses with ``_asdict()`` methods will be encoded as JSON objects. If *tuple_as_array* is true (default: ``True``), :class:`tuple` (and subclasses) will be encoded as JSON arrays. If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. Note that this is still a lossy operation that will not round-trip correctly and should be used sparingly. If specified, *item_sort_key* is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. This option takes precedence over *sort_keys*. If *sort_keys* is true (default: ``False``), the output of dictionaries will be sorted by item. If *for_json* is true (default: ``False``), objects with a ``for_json()`` method will use the return value of that method for encoding as JSON instead of the object. If *ignore_nan* is true (default: ``False``), then out of range :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as ``null`` in compliance with the ECMA-262 specification. If true, this will override *allow_nan*. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. NOTE: You should use *default* or *for_json* instead of subclassing whenever possible. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and use_decimal and namedtuple_as_object and tuple_as_array and not bigint_as_string and not item_sort_key and not for_json and not ignore_nan and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is false then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If specified, ``separators`` should be an ``(item_separator, key_separator)`` tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and ``(',', ': ')`` otherwise. To get the most compact JSON representation, you should specify ``(',', ':')`` to eliminate whitespace. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``True``) then decimal.Decimal will be natively serialized to JSON with full precision. If *namedtuple_as_object* is true (default: ``True``), :class:`tuple` subclasses with ``_asdict()`` methods will be encoded as JSON objects. If *tuple_as_array* is true (default: ``True``), :class:`tuple` (and subclasses) will be encoded as JSON arrays. If *bigint_as_string* is true (not the default), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. If specified, *item_sort_key* is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. This option takes precendence over *sort_keys*. If *sort_keys* is true (default: ``False``), the output of dictionaries will be sorted by item. If *for_json* is true (default: ``False``), objects with a ``for_json()`` method will use the return value of that method for encoding as JSON instead of the object. If *ignore_nan* is true (default: ``False``), then out of range :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as ``null`` in compliance with the ECMA-262 specification. If true, this will override *allow_nan*. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing whenever possible. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and use_decimal and namedtuple_as_object and tuple_as_array and not bigint_as_string and not sort_keys and not item_sort_key and not for_json and not ignore_nan and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, for_json=for_json, ignore_nan=ignore_nan, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None, object_pairs_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. NOTE: You should use *object_hook* or *object_pairs_hook* instead of subclassing whenever possible. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, use_decimal=use_decimal, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. NOTE: You should use *object_hook* or *object_pairs_hook* instead of subclassing whenever possible. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not use_decimal and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant if use_decimal: if parse_float is not None: raise TypeError("use_decimal=True implies parse_float=Decimal") kw['parse_float'] = Decimal return cls(encoding=encoding, **kw).decode(s) def _toggle_speedups(enabled): from . import decoder as dec from . import encoder as enc from . import scanner as scan c_make_encoder = _import_c_make_encoder() if enabled: dec.scanstring = dec.c_scanstring or dec.py_scanstring enc.c_make_encoder = c_make_encoder enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or enc.py_encode_basestring_ascii) scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner else: dec.scanstring = dec.py_scanstring enc.c_make_encoder = None enc.encode_basestring_ascii = enc.py_encode_basestring_ascii scan.make_scanner = scan.py_make_scanner dec.make_scanner = scan.make_scanner global _default_decoder _default_decoder = JSONDecoder( encoding=None, object_hook=None, object_pairs_hook=None, ) global _default_encoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, ) def simple_first(kv): """Helper function to pass to item_sort_key to sort simple elements to the top, then container elements. """ return (isinstance(kv[1], (list, dict, tuple)), kv[0]) ```
[ { "content": "Repeat the following code:\n```python\n# -*- coding: utf-8 -*-\n#\n# goo-server api documentation build configuration file, created by\n# sphinx-quickstart on Wed Dec 19 10:15:12 2012.\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# Note that not all poss...
[ { "content": "Repeat the following code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n#\n# goo-server api documentation build configuration file, created by\n# sphinx-quickstart on Wed Dec 19 10:15:12 2012.\n#\n# This file is execfile()d with the current directory set to its containing dir.\n#\n# Note t...
```python # -*- coding: utf-8 -*- # # goo-server api documentation build configuration file, created by # sphinx-quickstart on Wed Dec 19 10:15:12 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # 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 = ['sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinxcontrib.httpdomain'] DOC_SOURCE_PATH = os.path.realpath(os.path.dirname(__file__)) # 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' testlevel = 2 # The master toctree document. master_doc = 'index' # General information about the project. project = u'Goo Documentation' copyright = u'2012, NCC - UNESP' # 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.0' # The full version, including alpha/beta/rc tags. release = '0.1.0' # 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 = [] # 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 = 'bootstrap-home' # 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 = ["../themes/"] # 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 = 'goo-docs' ```
[ { "content": "```python\nimport sys\nimport math\nimport time\nimport random\n\nfrom bzrc import BZRC, Command\n\nclass PigeonAgent(object):\n \n def __init__(self, bzrc, mode, time):\n self.bzrc = bzrc\n self.mode = mode\n self.num_tanks = 1\n self.cur_time = time\n \n ...
[ { "content": "<|memory_start|>```python\nimport sys\nimport math\nimport time\nimport random\n\nfrom bzrc import BZRC, Command\n\nclass PigeonAgent(object):\n \n def __init__(self, bzrc, mode, time):\n self.bzrc = bzrc\n self.mode = mode\n self.num_tanks = 1\n self.cur_time = t...
```python import sys import math import time import random from bzrc import BZRC, Command class PigeonAgent(object): def __init__(self, bzrc, mode, time): self.bzrc = bzrc self.mode = mode self.num_tanks = 1 self.cur_time = time self.const_velocity = .5 self.time_move = self.cur_time self.time_turn = self.cur_time self.move_interval = 2.0 self.turn_interval = 1.0 def behave(self, time): if self.mode == "sit": return elif self.mode == "const": #self.mytanks = self.bzrc.get_mytanks() for i in range(self.num_tanks): self.bzrc.speed(i, self.const_velocity) elif self.mode == "wild": for i in range(self.num_tanks): if (time - self.time_move) > self.move_interval: for i in range(self.num_tanks): speed = self.getRandomSpeed() self.bzrc.speed(i, speed) self.time_move = time if (time - self.time_turn) > self.turn_interval: for i in range(self.num_tanks): angvel = self.getRandomAngvel() self.bzrc.angvel(i, angvel) self.time_turn = time def getRandomAngvel(self): rval = random.random() rval *= self.getDirection() return rval def getDirection(self): threshold = .5 n = random.random() if n <= threshold: direction = -1.0 else: direction = 1.0 return direction def getRandomSpeed(self): rval = random.uniform(0.4, 1.0) return rval def stop(self): for tank in self.bzrc.get_mytanks(): self.bzrc.speed(tank.index, 0) self.bzrc.angvel(tank.index, 0) def main(): # Process CLI arguments. try: execname, host, port, mode = sys.argv except ValueError: execname = sys.argv[0] print >>sys.stderr, '%s: incorrect number of arguments' % execname print >>sys.stderr, 'usage: %s hostname port [sit|const|wild]' % sys.argv[0] sys.exit(-1) bzrc = BZRC(host, int(port)) cur_time = time.time() agent = PigeonAgent(bzrc, mode, cur_time) # Run the agent try: while True: cur_time = time.time() agent.behave(cur_time) except KeyboardInterrupt: print "Exiting due to keyboard interrupt." agent.stop() bzrc.close() if __name__ == '__main__': main() ```