signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def schedule_batch(self, batch: '<STR_LIT>'):
self._require_attached_tasks()<EOL>self._spin.schedule_batch(batch)<EOL>
Schedule many jobs at once. Scheduling jobs in batches allows to enqueue them fast by avoiding round-trips to the broker. :arg batch: :class:`Batch` instance containing jobs to schedule
f339:c1:m10
def schedule(self, task: Schedulable, *args, **kwargs):
at = datetime.now(timezone.utc)<EOL>self.schedule_at(task, at, *args, **kwargs)<EOL>
Add a job to be executed ASAP to the batch. :arg task: the task or its name to execute in the background :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function
f339:c2:m1
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs):
self.jobs_to_create.append((task, at, args, kwargs))<EOL>
Add a job to be executed in the future to the batch. :arg task: the task or its name to execute in the background :arg at: Date at which the job should start. It is advised to pass a timezone aware datetime to lift any ambiguity. However if a timezone naive datetime if given, it will be assumed to contain UTC time. :arg args: args to be passed to the task function :arg kwargs: kwargs to be passed to the task function
f339:c2:m2
def advance_job_status(namespace: str, job: Job, duration: float,<EOL>err: Optional[Exception]):
duration = human_duration(duration)<EOL>if not err:<EOL><INDENT>job.status = JobStatus.SUCCEEDED<EOL>logger.info('<STR_LIT>', job, duration)<EOL>return<EOL><DEDENT>if job.should_retry:<EOL><INDENT>job.status = JobStatus.NOT_SET<EOL>job.retries += <NUM_LIT:1><EOL>if isinstance(err, RetryException) and err.at is not None:<EOL><INDENT>job.at = err.at<EOL><DEDENT>else:<EOL><INDENT>job.at = (datetime.now(timezone.utc) +<EOL>exponential_backoff(job.retries))<EOL><DEDENT>signals.job_schedule_retry.send(namespace, job=job, err=err)<EOL>log_args = (<EOL>job.retries, job.max_retries + <NUM_LIT:1>, job, duration,<EOL>human_duration(<EOL>(job.at - datetime.now(tz=timezone.utc)).total_seconds()<EOL>)<EOL>)<EOL>if isinstance(err, RetryException):<EOL><INDENT>logger.info('<STR_LIT>'<EOL>'<STR_LIT>', *log_args)<EOL><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>'<EOL>'<STR_LIT>', *log_args)<EOL><DEDENT>return<EOL><DEDENT>job.status = JobStatus.FAILED<EOL>signals.job_failed.send(namespace, job=job, err=err)<EOL>logger.error(<EOL>'<STR_LIT>',<EOL>job.max_retries + <NUM_LIT:1>, job.max_retries + <NUM_LIT:1>, job, duration,<EOL>exc_info=err<EOL>)<EOL>
Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals.
f340:m0
def human_duration(duration_seconds: float) -> str:
if duration_seconds < <NUM_LIT>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if duration_seconds < <NUM_LIT:1>:<EOL><INDENT>return '<STR_LIT>'.format(int(duration_seconds * <NUM_LIT:1000>))<EOL><DEDENT>return '<STR_LIT>'.format(int(duration_seconds))<EOL>
Convert a duration in seconds into a human friendly string.
f344:m0
def call_with_retry(func: Callable, exceptions, max_retries: int,<EOL>logger: Logger, *args, **kwargs):
attempt = <NUM_LIT:0><EOL>while True:<EOL><INDENT>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>except exceptions as e:<EOL><INDENT>attempt += <NUM_LIT:1><EOL>if attempt >= max_retries:<EOL><INDENT>raise<EOL><DEDENT>delay = exponential_backoff(attempt, cap=<NUM_LIT>)<EOL>logger.warning('<STR_LIT>', e, delay)<EOL>time.sleep(delay.total_seconds())<EOL><DEDENT><DEDENT>
Call a function and retry it on failure.
f344:m2
def exponential_backoff(attempt: int, cap: int=<NUM_LIT>) -> timedelta:
base = <NUM_LIT:3><EOL>temp = min(base * <NUM_LIT:2> ** attempt, cap)<EOL>return timedelta(seconds=temp / <NUM_LIT:2> + random.randint(<NUM_LIT:0>, temp / <NUM_LIT:2>))<EOL>
Calculate a delay to retry using an exponential backoff algorithm. It is an exponential backoff with random jitter to prevent failures from being retried at the same time. It is a good fit for most applications. :arg attempt: the number of attempts made :arg cap: maximum delay, defaults to 20 minutes
f344:m3
@contextlib.contextmanager<EOL>def handle_sigterm():
original_sigterm_handler = signal.getsignal(signal.SIGTERM)<EOL>signal.signal(signal.SIGTERM, signal.default_int_handler)<EOL>try:<EOL><INDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>signal.signal(signal.SIGTERM, original_sigterm_handler)<EOL><DEDENT>
Handle SIGTERM like a normal SIGINT (KeyboardInterrupt). By default Docker sends a SIGTERM for stopping containers, giving them time to terminate before getting killed. If a process does not catch this signal and does nothing, it just gets killed. Handling SIGTERM like SIGINT allows to gracefully terminate both interactively with ^C and with `docker stop`. This context manager restores the default SIGTERM behavior when exiting.
f344:m4
@property<EOL><INDENT>def available_slots(self) -> int:<DEDENT>
return self._in_queue.available_slots()<EOL>
Number of jobs the :class:`Workers` can accept. It may be racy, but it should not be a problem here as jobs are only submitted by a single thread (the arbiter).
f345:c1:m3
@click.group()<EOL>@click.option('<STR_LIT:-c>', '<STR_LIT>', type=click.File('<STR_LIT:r>'), default="<STR_LIT>", help="<STR_LIT>")<EOL>@click.option('<STR_LIT>', '<STR_LIT>', default=False, is_flag=True, help="<STR_LIT>")<EOL>@click.pass_context<EOL>def cli(ctx, config, quiet):
ctx.obj = {}<EOL>ctx.obj['<STR_LIT>'] = load_config(config.read()) <EOL>ctx.obj['<STR_LIT>'] = quiet<EOL>log(ctx, '<STR_LIT>' + rnd_scotty_quote() + '<STR_LIT>')<EOL>
AWS ECS Docker Deployment Tool
f353:m0
def __init__(self):
self.jobid = os.environ.get('<STR_LIT>', -<NUM_LIT:1>)<EOL>"""<STR_LIT>"""<EOL>self.logname = os.environ.get('<STR_LIT>')<EOL>"""<STR_LIT>"""<EOL>self.jobname = os.environ.get('<STR_LIT>')<EOL>"""<STR_LIT>"""<EOL>self.queue = os.environ.get('<STR_LIT>')<EOL>"""<STR_LIT>"""<EOL>self.fqdn = socket.getfqdn()<EOL>"""<STR_LIT>"""<EOL>self.sitename = os.environ.get('<STR_LIT>')<EOL>"""<STR_LIT>"""<EOL>self.platform = os.environ.get('<STR_LIT>')<EOL>"""<STR_LIT>"""<EOL>
Initialize a new HazelHenFilter :raises: None
f361:c0:m0
def filter(self, record):
record.sitename = self.sitename<EOL>record.platform = self.platform<EOL>record.jobid = self.jobid<EOL>record.submitter = self.logname<EOL>record.jobname = self.jobname<EOL>record.queue = self.queue<EOL>record.fqdn = self.fqdn<EOL>return True<EOL>
Add contextual information to the log record :param record: the log record :type record: :class:`logging.LogRecord` :returns: True, if log should get sent :rtype: :class:`bool` :raises: None
f361:c0:m1
def __init__(self, host, port=<NUM_LIT>, debugging_fields=True,<EOL>extra_fields=True, fqdn=False, localname=None,<EOL>facility=None):
self.debugging_fields = debugging_fields<EOL>self.extra_fields = extra_fields<EOL>self.fqdn = fqdn<EOL>self.localname = localname<EOL>self.facility = facility<EOL>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>logging.handlers.SocketHandler.__init__(self, host, port)<EOL><DEDENT>else:<EOL><INDENT>super(GELFTCPHandler, self).__init__(host, port)<EOL><DEDENT>
Initialize a new GELF TCP Handler :param host: The host of the graylog server. :type host: :class:`str` :param port: The port of the graylog server (default 12201). :type port: :class:`int` :param debugging_fields: Send debug fields if true (the default). :type debugging_fields: :class:`bool` :param extra_fields: Send extra fields on the log record to graylog if true (the default). :type extra_fields: :class:`bool` :param fqdn: Use fully qualified domain name of localhost as source host (socket.getfqdn()). :type fqdn: :class:`str` :param localname: Use specified hostname as source host. :type localname: :class:`str` :param facility: Replace facility with specified value. If specified, record.name will be passed as `logger` parameter. :type facility: :class:`str`
f362:c0:m0
def get_logger(context):
logger = get_qs_logger(log_group='<STR_LIT>', log_file_prefix=context.resource.name)<EOL>logger.setLevel(logging.DEBUG)<EOL>return logger<EOL>
:return: logger according to cloudshell standards.
f366:m0
def get_reservation_ports(session, reservation_id, model_name='<STR_LIT>'):
reservation_ports = []<EOL>reservation = session.GetReservationDetails(reservation_id).ReservationDescription<EOL>for resource in reservation.Resources:<EOL><INDENT>if resource.ResourceModelName == model_name:<EOL><INDENT>reservation_ports.append(resource)<EOL><DEDENT><DEDENT>return reservation_ports<EOL>
Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation
f366:m1
def get_reservation_resources(session, reservation_id, *models):
models_resources = []<EOL>reservation = session.GetReservationDetails(reservation_id).ReservationDescription<EOL>for resource in reservation.Resources:<EOL><INDENT>if resource.ResourceModelName in models:<EOL><INDENT>models_resources.append(resource)<EOL><DEDENT><DEDENT>return models_resources<EOL>
Get all resources of given models in reservation. :param session: CloudShell session :type session: cloudshell.api.cloudshell_api.CloudShellAPISession :param reservation_id: active reservation ID :param models: list of requested models :return: list of all resources of models in reservation
f366:m2
def create_quali_api_instance(context, logger):
if hasattr(context, '<STR_LIT>') and context.reservation:<EOL><INDENT>domain = context.reservation.domain<EOL><DEDENT>elif hasattr(context, '<STR_LIT>') and context.remote_reservation:<EOL><INDENT>domain = context.remote_reservation.domain<EOL><DEDENT>else:<EOL><INDENT>domain = None<EOL><DEDENT>address = context.connectivity.server_address<EOL>token = context.connectivity.admin_auth_token<EOL>if token:<EOL><INDENT>instance = QualiAPIHelper(address, logger, token=token, domain=domain)<EOL><DEDENT>else:<EOL><INDENT>instance = QualiAPIHelper(address, logger, username='<STR_LIT>', password='<STR_LIT>', domain=domain)<EOL><DEDENT>return instance<EOL>
Get needed attributes from context and create instance of QualiApiHelper :param context: :param logger: :return:
f367:m0
def login(self):
uri = '<STR_LIT>'<EOL>if self._token:<EOL><INDENT>json_data = {'<STR_LIT>': self._token, '<STR_LIT>': self._domain}<EOL><DEDENT>else:<EOL><INDENT>json_data = {'<STR_LIT:username>': self._username, '<STR_LIT:password>': self._password, '<STR_LIT>': self._domain}<EOL><DEDENT>result = self.__rest_client.request_put(uri, json_data)<EOL>self.__rest_client.session.headers.update(authorization="<STR_LIT>".format(result.replace('<STR_LIT:">', '<STR_LIT>')))<EOL>
Login :return:
f367:c0:m2
def init(scope):
<EOL>scope['<STR_LIT>'] = py2q<EOL>scope['<STR_LIT>'] = q2py<EOL>QtCore.THREADSAFE_NONE = None<EOL>scope['<STR_LIT>'] = QtCore<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = '<STR_LIT>'<EOL>QtCore.QDate.toPython = lambda x: x.toPyDate()<EOL>QtCore.QDateTime.toPython = lambda x: x.toPyDateTime()<EOL>QtCore.QTime.toPython = lambda x: x.toPyTime()<EOL>QtCore.Signal = Signal<EOL>QtCore.Slot = Slot<EOL>QtCore.Property = QtCore.pyqtProperty<EOL>QtCore.SIGNAL = SIGNAL<EOL>QtCore.__version__ = QtCore.QT_VERSION_STR<EOL>if SIP_VERSION == '<STR_LIT:2>':<EOL><INDENT>QtCore.QStringList = list<EOL>QtCore.QString = unicode<EOL><DEDENT>
Initialize the xqt system with the PyQt4 wrapper for the Qt system. :param scope | <dict>
f375:m3
def init(scope):
<EOL>QtCore.THREADSAFE_NONE = XThreadNone()<EOL>QtGui.QDialog = QDialog<EOL>scope['<STR_LIT>'] = QtCore<EOL>scope['<STR_LIT>'] = QtGui<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = lazy_import('<STR_LIT>')<EOL>scope['<STR_LIT>'] = Uic()<EOL>scope['<STR_LIT>'] = '<STR_LIT>'<EOL>QtCore.QDate.toPyDate = lambda x: x.toPython()<EOL>QtCore.QDateTime.toPyDateTime = lambda x: x.toPython()<EOL>QtCore.QTime.toPyTime = lambda x: x.toPython()<EOL>QtCore.QStringList = list<EOL>QtCore.QString = unicode<EOL>
Initialize the xqt system with the PySide wrapper for the Qt system. :param scope | <dict>
f376:m1
def createAction(self, parent=None, name='<STR_LIT>'):
action = super(UiLoader, self).createAction(parent, name)<EOL>if not action.parent():<EOL><INDENT>action.setParent(self._baseinstance)<EOL><DEDENT>setattr(self._baseinstance, name, action)<EOL>return action<EOL>
Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param parent | <QWidget> || None name | <str>
f376:c1:m1
def createActionGroup(self, parent=None, name='<STR_LIT>'):
actionGroup = super(UiLoader, self).createActionGroup(parent, name)<EOL>if not actionGroup.parent():<EOL><INDENT>actionGroup.setParent(self._baseinstance)<EOL><DEDENT>setattr(self._baseinstance, name, actionGroup)<EOL>return actionGroup<EOL>
Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param parent | <QWidget> || None name | <str>
f376:c1:m2
def createLayout(self, className, parent=None, name='<STR_LIT>'):
layout = super(UiLoader, self).createLayout(className, parent, name)<EOL>setattr(self._baseinstance, name, layout)<EOL>return layout<EOL>
Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param className | <str> parent | <QWidget> || None name | <str>
f376:c1:m3
def createWidget(self, className, parent=None, name='<STR_LIT>'):
className = str(className)<EOL>if className in self.dynamicWidgets:<EOL><INDENT>widget = self.dynamicWidgets[className](parent)<EOL>if parent:<EOL><INDENT>widget.setPalette(parent.palette())<EOL><DEDENT>widget.setObjectName(name)<EOL>if className == '<STR_LIT>':<EOL><INDENT>widget.setUrl(QtCore.QUrl('<STR_LIT>'))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>widget = super(UiLoader, self).createWidget(className, parent, name)<EOL>if parent:<EOL><INDENT>widget.setPalette(parent.palette())<EOL><DEDENT><DEDENT>if parent is None:<EOL><INDENT>return self._baseinstance<EOL><DEDENT>else:<EOL><INDENT>setattr(self._baseinstance, name, widget)<EOL>return widget<EOL><DEDENT>
Overloads the createWidget method to handle the proper base instance information similar to the PyQt4 loading system. :param className | <str> parent | <QWidget> || None name | <str> :return <QWidget>
f376:c1:m4
def loadUi(self, filename, baseinstance=None):
try:<EOL><INDENT>xui = ElementTree.parse(filename)<EOL><DEDENT>except xml.parsers.expat.ExpatError:<EOL><INDENT>log.exception('<STR_LIT>' % filename)<EOL>return None<EOL><DEDENT>loader = UiLoader(baseinstance)<EOL>xcustomwidgets = xui.find('<STR_LIT>')<EOL>if xcustomwidgets is not None:<EOL><INDENT>for xcustom in xcustomwidgets:<EOL><INDENT>header = xcustom.find('<STR_LIT>').text<EOL>clsname = xcustom.find('<STR_LIT:class>').text<EOL>if not header:<EOL><INDENT>continue<EOL><DEDENT>if clsname in loader.dynamicWidgets:<EOL><INDENT>continue<EOL><DEDENT>if '<STR_LIT:/>' in header:<EOL><INDENT>header = '<STR_LIT>' + '<STR_LIT:.>'.join(header.split('<STR_LIT:/>')[:-<NUM_LIT:1>])<EOL><DEDENT>try:<EOL><INDENT>__import__(header)<EOL>module = sys.modules[header]<EOL>cls = getattr(module, clsname)<EOL><DEDENT>except (ImportError, KeyError, AttributeError):<EOL><INDENT>log.error('<STR_LIT>' % (header, clsname))<EOL>continue<EOL><DEDENT>loader.dynamicWidgets[clsname] = cls<EOL>loader.registerCustomWidget(cls)<EOL><DEDENT><DEDENT>ui = loader.load(filename)<EOL>QtCore.QMetaObject.connectSlotsByName(ui)<EOL>return ui<EOL>
Generate a loader to load the filename. :param filename | <str> baseinstance | <QWidget> :return <QWidget> || None
f376:c2:m1
def showEvent(self, event):
super(QDialog, self).showEvent(event)<EOL>if not self._centered:<EOL><INDENT>self._centered = True<EOL>try:<EOL><INDENT>window = self.parent().window()<EOL>center = window.geometry().center()<EOL><DEDENT>except AttributeError:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>self.move(center.x() - self.width() / <NUM_LIT:2>, center.y() - self.height() / <NUM_LIT:2>)<EOL><DEDENT><DEDENT>
Displays this dialog, centering on its parent. :param event | <QtCore.QShowEvent>
f376:c3:m1
@staticmethod<EOL><INDENT>def getOpenFileName(*args):<DEDENT>
result = QtGui.QFileDialog.getOpenFileName(*args)<EOL>if type(result) is not tuple:<EOL><INDENT>return result, bool(result)<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>
Normalizes the getOpenFileName method between the different Qt wrappers. :return (<str> filename, <bool> accepted)
f379:c0:m0
@staticmethod<EOL><INDENT>def getDirectory(*args):<DEDENT>
result = QtGui.QFileDialog.getDirectory(*args)<EOL>if type(result) is not tuple:<EOL><INDENT>return result, bool(result)<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>
Normalizes the getDirectory method between the different Qt wrappers. :return (<str> filename, <bool> accepted)
f379:c0:m1
@staticmethod<EOL><INDENT>def getSaveFileName(*args):<DEDENT>
result = QtGui.QFileDialog.getSaveFileName(*args)<EOL>if type(result) is not tuple:<EOL><INDENT>return result, bool(result)<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>
Normalizes the getSaveFileName method between the different Qt wrappers. :return (<str> filename, <bool> accepted)
f379:c0:m2
def __getattr__(self, key):
mod = self.__load_module__()<EOL>if os.environ.get('<STR_LIT>') == '<STR_LIT:1>':<EOL><INDENT>return getattr(mod, key, object)<EOL><DEDENT>else:<EOL><INDENT>return getattr(mod, key)<EOL><DEDENT>
Retrieves the value from the module wrapped by this instance. :param key | <str> :return <variant>
f380:c0:m1
def __setattr__(self, key, value):
mod = self.__load_module__()<EOL>return setattr(mod, key, value)<EOL>
Sets the value within the module wrapped by this instance to the inputed value. :param key | <str> value | <variant>
f380:c0:m2
def request_method(request):
<EOL>if request.method == '<STR_LIT:POST>' and '<STR_LIT>' in request.POST:<EOL><INDENT>method = request.POST['<STR_LIT>'].upper()<EOL><DEDENT>else:<EOL><INDENT>method = request.method<EOL><DEDENT>return method<EOL>
Returns the effective HTTP method of a request. To support the entire range of HTTP methods from HTML forms (which only support GET and POST), an HTTP method may be emulated by setting a POST parameter named "_method" to the name of the HTTP method to be emulated. Example HTML: <!-- Submits a form using the PUT method --> <form> <input type="text" name="name" value="value" /> <button type="submit" name="_method" value="put">Update</button> </form> Args: request: an HttpRequest Returns: An upper-case string naming the HTTP method (like django.http.HttpRequest.method)
f383:m0
def gen():
for i in range(<NUM_LIT:2>):<EOL><INDENT>test_data = ejson.dumps({'<STR_LIT:name>': '<STR_LIT>', '<STR_LIT:a>': '<STR_LIT:b>'})<EOL>yield {'<STR_LIT:type>': '<STR_LIT:message>', '<STR_LIT:data>': test_data}<EOL><DEDENT>
Generate events for the test_read_events function
f393:m0
def gen_non_message_events():
for i in range(<NUM_LIT:2>):<EOL><INDENT>yield {'<STR_LIT:type>': '<STR_LIT>', '<STR_LIT:data>': ejson.dumps({})}<EOL><DEDENT>
Generate events for the test_read_events_skip_non_messages function
f393:m1
def get_ip(request):
if getsetting('<STR_LIT>'):<EOL><INDENT>return getsetting('<STR_LIT>')<EOL><DEDENT>forwarded_for = request.META.get('<STR_LIT>')<EOL>if not forwarded_for:<EOL><INDENT>return UNKNOWN_IP<EOL><DEDENT>for ip in forwarded_for.split('<STR_LIT:U+002C>'):<EOL><INDENT>ip = ip.strip()<EOL>if not ip.startswith('<STR_LIT>') and not ip == '<STR_LIT:127.0.0.1>':<EOL><INDENT>return ip<EOL><DEDENT><DEDENT>return UNKNOWN_IP<EOL>
Return the IP address inside the HTTP_X_FORWARDED_FOR var inside the `request` object. The return of this function can be overrided by the `LOCAL_GEOLOCATION_IP` variable in the `conf` module. This function will skip local IPs (starting with 10. and equals to 127.0.0.1).
f398:m0
def get_connection(self):
if self.conn:<EOL><INDENT>return self.conn<EOL><DEDENT>redis_configs = getsetting('<STR_LIT>')<EOL>if redis_configs:<EOL><INDENT>config_name = getsetting('<STR_LIT>', '<STR_LIT:default>')<EOL>config = redis_configs[config_name]<EOL>host = config['<STR_LIT>']<EOL>port = config['<STR_LIT>']<EOL>self.conn = redis.StrictRedis(host=host, port=port)<EOL><DEDENT>else:<EOL><INDENT>self.conn = None<EOL><DEDENT>return self.conn<EOL>
Return a valid redis connection based on the following settings * `REDIS_CONNECTIONS` * `EVENTLIB_REDIS_CONFIG_NAME` The first one is a dictionary in the following format: >>> { ... 'server1': {'HOST': 'redis-server-1', 'POST': 9001}, ... 'server2': {'HOST': 'redis-server-2', 'POST': 9002}, ... ] The second one is the name of the entry present in the above dict, like `server1` or `server2`.
f398:c0:m0
@task<EOL>def process_task(name, data):
process(name, data)<EOL>
Thin wrapper to transform `core.process()` in a celery task
f401:m0
def listen_for_events():
import_event_modules()<EOL>conn = redis_connection.get_connection()<EOL>pubsub = conn.pubsub()<EOL>pubsub.subscribe("<STR_LIT>")<EOL>for message in pubsub.listen():<EOL><INDENT>if message['<STR_LIT:type>'] != '<STR_LIT:message>':<EOL><INDENT>continue<EOL><DEDENT>data = loads(message["<STR_LIT:data>"])<EOL>if '<STR_LIT:name>' in data:<EOL><INDENT>event_name = data.pop('<STR_LIT:name>')<EOL>process_external(event_name, data)<EOL><DEDENT><DEDENT>
Pubsub event listener Listen for events in the pubsub bus and calls the process function when somebody comes to play.
f402:m0
def parse_event_name(name):
try:<EOL><INDENT>app, event = name.split('<STR_LIT:.>')<EOL>return '<STR_LIT>'.format(app, EVENTS_MODULE_NAME), event<EOL><DEDENT>except ValueError:<EOL><INDENT>raise InvalidEventNameError(<EOL>(u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>).format(name))<EOL><DEDENT>
Returns the python module and obj given an event name
f403:m0
def find_event(name):
try:<EOL><INDENT>module, klass = parse_event_name(name)<EOL>return getattr(import_module(module), klass)<EOL><DEDENT>except (ImportError, AttributeError):<EOL><INDENT>raise EventNotFoundError(<EOL>('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(name, klass, module)))<EOL><DEDENT>
Actually import the event represented by name Raises the `EventNotFoundError` if it's not possible to find the event class refered by `name`.
f403:m2
def cleanup_handlers(event=None):
if event:<EOL><INDENT>if event in HANDLER_REGISTRY:<EOL><INDENT>del HANDLER_REGISTRY[event]<EOL><DEDENT>if event in EXTERNAL_HANDLER_REGISTRY:<EOL><INDENT>del EXTERNAL_HANDLER_REGISTRY[event]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>HANDLER_REGISTRY.clear()<EOL>EXTERNAL_HANDLER_REGISTRY.clear()<EOL><DEDENT>
Remove handlers of a given `event`. If no event is informed, wipe out all events registered. Be careful!! This function is intended to help when writing tests and for debugging purposes. If you call it, all handlers associated to an event (or to all of them) will be disassociated. Which means that you'll have to reload all modules that teclare handlers. I'm sure you don't want it.
f403:m3
def find_handlers(event_name, registry=HANDLER_REGISTRY):
handlers = []<EOL>if isinstance(event_name, basestring):<EOL><INDENT>matched_events = [event for event in registry.keys()<EOL>if fnmatch.fnmatchcase(event_name, event)]<EOL>for matched_event in matched_events:<EOL><INDENT>handlers.extend(registry.get(matched_event))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>handlers = registry.get(find_event(event_name), [])<EOL><DEDENT>return handlers<EOL>
Small helper to find all handlers associated to a given event If the event can't be found, an empty list will be returned, since this is an internal function and all validation against the event name and its existence was already performed.
f403:m4
def process(event_name, data):
deserialized = loads(data)<EOL>event_cls = find_event(event_name)<EOL>event = event_cls(event_name, deserialized)<EOL>try:<EOL><INDENT>event.clean()<EOL><DEDENT>except ValidationError as exc:<EOL><INDENT>if os.environ.get('<STR_LIT>'):<EOL><INDENT>raise<EOL><DEDENT>else:<EOL><INDENT>logger.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>event_name, data, str(exc)))<EOL>return<EOL><DEDENT><DEDENT>for handler in find_handlers(event_name):<EOL><INDENT>try:<EOL><INDENT>handler(deserialized)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>logger.warning(<EOL>(u'<STR_LIT>'<EOL>u'<STR_LIT>').format(event_name, str(exc)))<EOL>if getsetting('<STR_LIT>'):<EOL><INDENT>raise exc<EOL><DEDENT><DEDENT><DEDENT>event._broadcast()<EOL>
Iterates over the event handler registry and execute each found handler. It takes the event name and its its `data`, passing the return of `ejson.loads(data)` to the found handlers.
f403:m6
def process_external(event_name, data):
for handler in find_external_handlers(event_name):<EOL><INDENT>try:<EOL><INDENT>handler(data)<EOL><DEDENT>except Exception as exc:<EOL><INDENT>logger.warning(<EOL>(u'<STR_LIT>'<EOL>u'<STR_LIT>').format(event_name, str(exc)))<EOL>if getsetting('<STR_LIT>'):<EOL><INDENT>raise exc<EOL><DEDENT><DEDENT><DEDENT>
Iterates over the event handler registry and execute each found handler. It takes the event name and its `data`, passing the return of data to the found handlers.
f403:m7
def get_default_values(data):
request = data.get('<STR_LIT>')<EOL>result = {}<EOL>result['<STR_LIT>'] = datetime.now()<EOL>result['<STR_LIT>'] = request and get_ip(request) or '<STR_LIT>'<EOL>return result<EOL>
Return all default values that an event should have
f403:m8
def filter_data_values(data):
banned = ('<STR_LIT>',)<EOL>return {key: val for key, val in data.items() if not key in banned}<EOL>
Remove special values that log function can take There are some special values, like "request" that the `log()` function can take, but they're not meant to be passed to the celery task neither for the event handlers. This function filter these keys and return another dict without them.
f403:m9
def import_event_modules():
for installed_app in getsetting('<STR_LIT>'):<EOL><INDENT>module_name = u'<STR_LIT>'.format(installed_app, EVENTS_MODULE_NAME)<EOL>try:<EOL><INDENT>import_module(module_name)<EOL><DEDENT>except ImportError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Import all events declared for all currently installed apps This function walks through the list of installed apps and tries to import a module named `EVENTS_MODULE_NAME`.
f403:m10
def getsetting(key, default=None):
return getattr(settings, key, default)<EOL>
Just a thin wrapper to avoid repeating code Also, this makes it easier to find places that are using configuration values and change them if we need in the future.
f405:m0
def generate_settings():
output = CONFIG_TEMPLATE % dict(<EOL>default_key=base64.b64encode(os.urandom(KEY_LENGTH)),<EOL>)<EOL>return output<EOL>
This command is run when ``default_path`` doesn't exist, or ``init`` is run and returns a string representing the default data to put into their settings file.
f406:m0
def _register_handler(event, fun, external=False):
registry = core.HANDLER_REGISTRY<EOL>if external:<EOL><INDENT>registry = core.EXTERNAL_HANDLER_REGISTRY<EOL><DEDENT>if not isinstance(event, basestring):<EOL><INDENT>event = core.parse_event_to_name(event)<EOL><DEDENT>if event in registry:<EOL><INDENT>registry[event].append(fun)<EOL><DEDENT>else:<EOL><INDENT>registry[event] = [fun]<EOL><DEDENT>return fun<EOL>
Register a function to be an event handler
f407:m0
def handler(param):
if isinstance(param, basestring):<EOL><INDENT>return lambda f: _register_handler(param, f)<EOL><DEDENT>else:<EOL><INDENT>core.HANDLER_METHOD_REGISTRY.append(param)<EOL>return param<EOL><DEDENT>
Decorator that associates a handler to an event class This decorator works for both methods and functions. Since it only registers the callable object and returns it without evaluating it. The name param should be informed in a dotted notation and should contain two informations: the django app name and the class name. Just like this: >>> @handler('deal.ActionLog') ... def blah(data): ... sys.stdout.write('I love python!\n') You can also use this same decorator to mark class methods as handlers. Just notice that the class *must* inherit from `BaseEvent`. >>> class MyEvent(BaseEvent) ... @handler('deal.ActionLog') ... def another_blah(data): ... sys.stdout.write('Stuff!\n')
f407:m1
def log(name, data=None):
data = data or {}<EOL>data.update(core.get_default_values(data))<EOL>event_cls = core.find_event(name)<EOL>event = event_cls(name, data)<EOL>event.validate() <EOL>data = core.filter_data_values(data)<EOL>data = ejson.dumps(data) <EOL>if conf.getsetting('<STR_LIT>'):<EOL><INDENT>core.process(name, data)<EOL><DEDENT>else:<EOL><INDENT>tasks.process_task.delay(name, data)<EOL><DEDENT>
Entry point for the event lib that starts the logging process This function uses the `name` param to find the event class that will be processed to log stuff. This name must provide two informations separated by a dot: the app name and the event class name. Like this: >>> name = 'deal.ActionLog' The "ActionLog" is a class declared inside the 'deal.events' module and this function will raise an `EventNotFoundError` error if it's not possible to import the right event class. The `data` param *must* be a dictionary, otherwise a `TypeError` will be rised. All keys *must* be strings and all values *must* be serializable by the `json.dumps` function. If you need to pass any unsupported object, you will have to register a serializer function. Consult the RFC-00003-serialize-registry for more information.
f407:m3
def __init__(self, name, data):
self.name = name<EOL>self.data = data<EOL>
Stores event name and data param as instance attributes
f407:c1:m0
def validate(self):
If you want to validate your data *BEFORE* sending it to the wire, override this method. If something goes wrong, you must raise the `ValidationError` exception.
f407:c1:m1
def clean(self):
This method will be called by the event processor It must be overrided in the class that inherits from `BaseEvent' and raise `ValidationError` exceptions if something is wrong with the data received from the caller.
f407:c1:m2
def validate_keys(self, *keys):
current_keys = set(self.data.keys())<EOL>needed_keys = set(keys)<EOL>if not needed_keys.issubset(current_keys):<EOL><INDENT>raise ValidationError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>'<STR_LIT:U+002CU+0020>'.join(needed_keys.difference(current_keys)))<EOL>)<EOL><DEDENT>return True<EOL>
Validation helper to ensure that keys are present in data This method makes sure that all of keys received here are present in the data received from the caller. It is better to call this method in the `validate()` method of your event. Not in the `clean()` one, since the first will be called locally, making it easier to debug things and find problems.
f407:c1:m3
def broadcast(self, data):
return data<EOL>
Returns all the data that will be passed to the external handlers Override this method and update the `data` dictionary to provide all the data that you want to pass to external handlers.
f407:c1:m5
def parse_requirements():
try:<EOL><INDENT>requirements =map(str.strip, local_file('<STR_LIT>').split('<STR_LIT:\n>'))<EOL><DEDENT>except IOError:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>links = []<EOL>pkgs = []<EOL>for req in requirements:<EOL><INDENT>if not req:<EOL><INDENT>continue<EOL><DEDENT>if '<STR_LIT>' in req or '<STR_LIT>' in req:<EOL><INDENT>links.append(req)<EOL>name, version = re.findall("<STR_LIT>", req)[<NUM_LIT:0>]<EOL>pkgs.append('<STR_LIT>'.format(name, version))<EOL><DEDENT>else:<EOL><INDENT>pkgs.append(req)<EOL><DEDENT><DEDENT>return pkgs, links<EOL>
Rudimentary parser for the `requirements.txt` file We just want to separate regular packages from links to pass them to the `install_requires` and `dependency_links` params of the `setup()` function properly.
f409:m0
def random_rectangle_generator(num, max_side=<NUM_LIT:30>, min_side=<NUM_LIT:8>):
return (random_rectangle(max_side, min_side) for i in range(<NUM_LIT:0>, num))<EOL>
Generate a random rectangle list with dimensions within specified parameters. Arguments: max_dim (number): Max rectangle side length min_side (number): Min rectangle side length max_ratio (number): Returns: Rectangle list
f411:m1
def helper():
for mode in PackingMode:<EOL><INDENT>for bin_algo in PackingBin:<EOL><INDENT>for size, w, h in ('<STR_LIT>', <NUM_LIT:50>, <NUM_LIT:50>), ('<STR_LIT>', <NUM_LIT:5>, <NUM_LIT:5>):<EOL><INDENT>name = '<STR_LIT:_>'.join(('<STR_LIT:test>', mode, bin_algo, size))<EOL>print("""<STR_LIT>""" %<EOL>(name, size.replace('<STR_LIT:_>', '<STR_LIT:U+0020>'), mode, bin_algo, w, h))<EOL>if size == '<STR_LIT>':<EOL><INDENT>print("""<STR_LIT>"""<EOL>self.assertEqual(len(p.rect_list()), <NUM_LIT:0>)<EOL>
create a bunch of tests to copy and paste into TestFactory
f415:m0
def random_rectangle_generator(num, max_side=<NUM_LIT:30>, min_side=<NUM_LIT:8>):
return (random_rectangle(max_side, min_side) for i in range(<NUM_LIT:0>, num))<EOL>
Generate a random rectangle list with dimensions within specified parameters. Arguments: max_dim (number): Max rectangle side length min_side (number): Min rectangle side length max_ratio (number): Returns: Rectangle list
f416:m1
def random_rectangle_generator(num, max_side=<NUM_LIT:30>, min_side=<NUM_LIT:8>):
return (random_rectangle(max_side, min_side) for i in range(<NUM_LIT:0>, num))<EOL>
Generate a random rectangle list with dimensions within specified parameters. Arguments: max_dim (number): Max rectangle side length min_side (number): Min rectangle side length max_ratio (number): Returns: Rectangle list
f417:m1
def float2dec(ft, decimal_digits):
with decimal.localcontext() as ctx:<EOL><INDENT>ctx.rounding = decimal.ROUND_UP<EOL>places = decimal.Decimal(<NUM_LIT:10>)**(-decimal_digits)<EOL>return decimal.Decimal.from_float(float(ft)).quantize(places)<EOL><DEDENT>
Convert float (or int) to Decimal (rounding up) with the requested number of decimal digits. Arguments: ft (float, int): Number to convert decimal (int): Number of digits after decimal point Return: Decimal: Number converted to decima
f421:m0
def newPacker(mode=PackingMode.Offline, <EOL>bin_algo=PackingBin.BBF, <EOL>pack_algo=MaxRectsBssf,<EOL>sort_algo=SORT_AREA, <EOL>rotation=True):
packer_class = None<EOL>if mode == PackingMode.Online:<EOL><INDENT>sort_algo=None<EOL>if bin_algo == PackingBin.BNF:<EOL><INDENT>packer_class = PackerOnlineBNF<EOL><DEDENT>elif bin_algo == PackingBin.BFF:<EOL><INDENT>packer_class = PackerOnlineBFF<EOL><DEDENT>elif bin_algo == PackingBin.BBF:<EOL><INDENT>packer_class = PackerOnlineBBF<EOL><DEDENT>else:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT><DEDENT>elif mode == PackingMode.Offline:<EOL><INDENT>if bin_algo == PackingBin.BNF:<EOL><INDENT>packer_class = PackerBNF<EOL><DEDENT>elif bin_algo == PackingBin.BFF:<EOL><INDENT>packer_class = PackerBFF<EOL><DEDENT>elif bin_algo == PackingBin.BBF:<EOL><INDENT>packer_class = PackerBBF<EOL><DEDENT>elif bin_algo == PackingBin.Global:<EOL><INDENT>packer_class = PackerGlobal<EOL>sort_algo=None<EOL><DEDENT>else:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise AttributeError("<STR_LIT>")<EOL><DEDENT>if sort_algo:<EOL><INDENT>return packer_class(pack_algo=pack_algo, sort_algo=sort_algo, <EOL>rotation=rotation)<EOL><DEDENT>else:<EOL><INDENT>return packer_class(pack_algo=pack_algo, rotation=rotation)<EOL><DEDENT>
Packer factory helper function Arguments: mode (PackingMode): Packing mode Online: Rectangles are packed as soon are they are added Offline: Rectangles aren't packed untils pack() is called bin_algo (PackingBin): Bin selection heuristic pack_algo (PackingAlgorithm): Algorithm used rotation (boolean): Enable or disable rectangle rotation. Returns: Packer: Initialized packer instance.
f421:m1
def __init__(self, pack_algo=MaxRectsBssf, rotation=True):
self._rotation = rotation<EOL>self._pack_algo = pack_algo<EOL>self.reset()<EOL>
Arguments: pack_algo (PackingAlgorithm): What packing algo to use rotation (bool): Enable/Disable rectangle rotation
f421:c4:m0
def __getitem__(self, key):
if not isinstance(key, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>size = len(self) <EOL>if key < <NUM_LIT:0>:<EOL><INDENT>key += size<EOL><DEDENT>if not <NUM_LIT:0> <= key < size:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>if key < len(self._closed_bins):<EOL><INDENT>return self._closed_bins[key]<EOL><DEDENT>else:<EOL><INDENT>return self._open_bins[key-len(self._closed_bins)]<EOL><DEDENT>
Return bin in selected position. (excluding empty bins)
f421:c4:m3
def _new_open_bin(self, width=None, height=None, rid=None):
factories_to_delete = set() <EOL>new_bin = None<EOL>for key, binfac in self._empty_bins.items():<EOL><INDENT>if not binfac.fits_inside(width, height):<EOL><INDENT>continue<EOL><DEDENT>new_bin = binfac.new_bin()<EOL>if new_bin is None:<EOL><INDENT>continue<EOL><DEDENT>self._open_bins.append(new_bin)<EOL>if binfac.is_empty():<EOL><INDENT>factories_to_delete.add(key)<EOL><DEDENT>break<EOL><DEDENT>for f in factories_to_delete:<EOL><INDENT>del self._empty_bins[f]<EOL><DEDENT>return new_bin<EOL>
Extract the next empty bin and append it to open bins Returns: PackingAlgorithm: Initialized empty packing bin. None: No bin big enough for the rectangle was found
f421:c4:m4
def bin_list(self):
return [(b.width, b.height) for b in self]<EOL>
Return a list of the dimmensions of the bins in use, that is closed or open containing at least one rectangle
f421:c4:m7
def _find_best_fit(self, pbin):
fit = ((pbin.fitness(r[<NUM_LIT:0>], r[<NUM_LIT:1>]), k) for k, r in self._sorted_rect.items())<EOL>fit = (f for f in fit if f[<NUM_LIT:0>] is not None)<EOL>try:<EOL><INDENT>_, rect = min(fit, key=self.first_item)<EOL>return rect<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT>
Return best fitness rectangle from rectangles packing _sorted_rect list Arguments: pbin (PackingAlgorithm): Packing bin Returns: key of the rectangle with best fitness
f421:c12:m1
def _new_open_bin(self, remaining_rect):
factories_to_delete = set() <EOL>new_bin = None<EOL>for key, binfac in self._empty_bins.items():<EOL><INDENT>a_rectangle_fits = False<EOL>for _, rect in remaining_rect.items():<EOL><INDENT>if binfac.fits_inside(rect[<NUM_LIT:0>], rect[<NUM_LIT:1>]):<EOL><INDENT>a_rectangle_fits = True<EOL>break<EOL><DEDENT><DEDENT>if not a_rectangle_fits:<EOL><INDENT>factories_to_delete.add(key)<EOL>continue<EOL><DEDENT>new_bin = binfac.new_bin()<EOL>if new_bin is None:<EOL><INDENT>continue<EOL><DEDENT>self._open_bins.append(new_bin)<EOL>if binfac.is_empty():<EOL><INDENT>factories_to_delete.add(key)<EOL><DEDENT>break<EOL><DEDENT>for f in factories_to_delete:<EOL><INDENT>del self._empty_bins[f]<EOL><DEDENT>return new_bin<EOL>
Extract the next bin where at least one of the rectangles in rem Arguments: remaining_rect (dict): rectangles not placed yet Returns: PackingAlgorithm: Initialized empty packing bin. None: No bin big enough for the rectangle was found
f421:c12:m2
def __init__(self, width, height, rot=True, *args, **kwargs):
self._waste_management = False<EOL>self._waste = WasteManager(rot=rot)<EOL>super(Skyline, self).__init__(width, height, rot, merge=False, *args, **kwargs)<EOL>
_skyline is the list used to store all the skyline segments, each one is a list with the format [x, y, width] where x is the x coordinate of the left most point of the segment, y the y coordinate of the segment, and width the length of the segment. The initial segment is allways [0, 0, surface_width] Arguments: width (int, float): height (int, float): rot (bool): Enable or disable rectangle rotation
f422:c0:m0
def _placement_points_generator(self, skyline, width):
skyline_r = skyline[-<NUM_LIT:1>].right<EOL>skyline_l = skyline[<NUM_LIT:0>].left<EOL>ppointsl = (s.left for s in skyline if s.left+width <= skyline_r)<EOL>ppointsr = (s.right-width for s in skyline if s.right-width >= skyline_l)<EOL>return heapq.merge(ppointsl, ppointsr)<EOL>
Returns a generator for the x coordinates of all the placement points on the skyline for a given rectangle. WARNING: In some cases could be duplicated points, but it is faster to compute them twice than to remove them. Arguments: skyline (list): Skyline HSegment list width (int, float): Rectangle width Returns: generator
f422:c0:m1
def _generate_placements(self, width, height):
skyline = self._skyline<EOL>points = collections.deque()<EOL>left_index = right_index = <NUM_LIT:0> <EOL>support_height = skyline[<NUM_LIT:0>].top<EOL>support_index = <NUM_LIT:0> <EOL>placements = self._placement_points_generator(skyline, width)<EOL>for p in placements:<EOL><INDENT>if p+width > skyline[right_index].right:<EOL><INDENT>for right_index in range(right_index+<NUM_LIT:1>, len(skyline)):<EOL><INDENT>if skyline[right_index].top >= support_height:<EOL><INDENT>support_index = right_index<EOL>support_height = skyline[right_index].top<EOL><DEDENT>if p+width <= skyline[right_index].right:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if p >= skyline[left_index].right:<EOL><INDENT>left_index +=<NUM_LIT:1><EOL><DEDENT>if support_index < left_index:<EOL><INDENT>support_index = left_index<EOL>support_height = skyline[left_index].top<EOL>for i in range(left_index, right_index+<NUM_LIT:1>):<EOL><INDENT>if skyline[i].top >= support_height:<EOL><INDENT>support_index = i<EOL>support_height = skyline[i].top<EOL><DEDENT><DEDENT><DEDENT>if support_height+height <= self.height:<EOL><INDENT>points.append((Rectangle(p, support_height, width, height),left_index, right_index))<EOL><DEDENT><DEDENT>return points<EOL>
Generate a list with Arguments: skyline (list): SkylineHSegment list width (number): Returns: tuple (Rectangle, fitness): Rectangle: Rectangle in valid position left_skyline: Index for the skyline under the rectangle left edge. right_skyline: Index for the skyline under the rectangle right edte.
f422:c0:m2
def _merge_skyline(self, skylineq, segment):
if len(skylineq) == <NUM_LIT:0>:<EOL><INDENT>skylineq.append(segment)<EOL>return<EOL><DEDENT>if skylineq[-<NUM_LIT:1>].top == segment.top:<EOL><INDENT>s = skylineq[-<NUM_LIT:1>]<EOL>skylineq[-<NUM_LIT:1>] = HSegment(s.start, s.length+segment.length)<EOL><DEDENT>else:<EOL><INDENT>skylineq.append(segment)<EOL><DEDENT>
Arguments: skylineq (collections.deque): segment (HSegment):
f422:c0:m3
def _add_skyline(self, rect):
skylineq = collections.deque([]) <EOL>for sky in self._skyline:<EOL><INDENT>if sky.right <= rect.left or sky.left >= rect.right:<EOL><INDENT>self._merge_skyline(skylineq, sky)<EOL>continue<EOL><DEDENT>if sky.left < rect.left and sky.right > rect.left:<EOL><INDENT>self._merge_skyline(skylineq, <EOL>HSegment(sky.start, rect.left-sky.left))<EOL>sky = HSegment(P(rect.left, sky.top), sky.right-rect.left)<EOL><DEDENT>if sky.left < rect.right:<EOL><INDENT>if sky.left == rect.left:<EOL><INDENT>self._merge_skyline(skylineq, <EOL>HSegment(P(rect.left, rect.top), rect.width))<EOL><DEDENT>if sky.right > rect.right:<EOL><INDENT>self._merge_skyline(skylineq, <EOL>HSegment(P(rect.right, sky.top), sky.right-rect.right))<EOL>sky = HSegment(sky.start, rect.right-sky.left)<EOL><DEDENT><DEDENT>if sky.left >= rect.left and sky.right <= rect.right:<EOL><INDENT>if self._waste_management and sky.top < rect.bottom:<EOL><INDENT>self._waste.add_waste(sky.left, sky.top, <EOL>sky.length, rect.bottom - sky.top)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._merge_skyline(skylineq, sky)<EOL><DEDENT><DEDENT>self._skyline = list(skylineq)<EOL>
Arguments: seg (Rectangle):
f422:c0:m4
def _select_position(self, width, height):
positions = self._generate_placements(width, height)<EOL>if self.rot and width != height:<EOL><INDENT>positions += self._generate_placements(height, width)<EOL><DEDENT>if not positions:<EOL><INDENT>return None, None<EOL><DEDENT>return min(((p[<NUM_LIT:0>], self._rect_fitness(*p))for p in positions), <EOL>key=operator.itemgetter(<NUM_LIT:1>))<EOL>
Search for the placement with the bes fitness for the rectangle. Returns: tuple (Rectangle, fitness) - Rectangle placed in the fittest position None - Rectangle couldn't be placed
f422:c0:m6
def fitness(self, width, height):
assert(width > <NUM_LIT:0> and height ><NUM_LIT:0>)<EOL>if width > max(self.width, self.height) orheight > max(self.height, self.width):<EOL><INDENT>return None<EOL><DEDENT>if self._waste_management:<EOL><INDENT>if self._waste.fitness(width, height) is not None:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT><DEDENT>rect, fitness = self._select_position(width, height)<EOL>return fitness<EOL>
Search for the best fitness
f422:c0:m7
def add_rect(self, width, height, rid=None):
assert(width > <NUM_LIT:0> and height > <NUM_LIT:0>)<EOL>if width > max(self.width, self.height) orheight > max(self.height, self.width):<EOL><INDENT>return None<EOL><DEDENT>rect = None<EOL>if self._waste_management:<EOL><INDENT>rect = self._waste.add_rect(width, height, rid)<EOL><DEDENT>if not rect:<EOL><INDENT>rect, _ = self._select_position(width, height)<EOL>if rect:<EOL><INDENT>self._add_skyline(rect)<EOL><DEDENT><DEDENT>if rect is None:<EOL><INDENT>return None<EOL><DEDENT>rect.rid = rid<EOL>self.rectangles.append(rect)<EOL>return rect<EOL>
Add new rectangle
f422:c0:m8
def _rect_fitness(self, max_rect, width, height):
if width <= max_rect.width and height <= max_rect.height:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Arguments: max_rect (Rectangle): Destination max_rect width (int, float): Rectangle width height (int, float): Rectangle height Returns: None: Rectangle couldn't be placed into max_rect integer, float: fitness value
f423:c0:m1
def _select_position(self, w, h):
if not self._max_rects:<EOL><INDENT>return None, None<EOL><DEDENT>fitn = ((self._rect_fitness(m, w, h), w, h, m) for m in self._max_rects <EOL>if self._rect_fitness(m, w, h) is not None)<EOL>fitr = ((self._rect_fitness(m, h, w), h, w, m) for m in self._max_rects <EOL>if self._rect_fitness(m, h, w) is not None)<EOL>if not self.rot:<EOL><INDENT>fitr = []<EOL><DEDENT>fit = itertools.chain(fitn, fitr)<EOL>try:<EOL><INDENT>_, w, h, m = min(fit, key=first_item)<EOL><DEDENT>except ValueError:<EOL><INDENT>return None, None<EOL><DEDENT>return Rectangle(m.x, m.y, w, h), m<EOL>
Find max_rect with best fitness for placing a rectangle of dimentsions w*h Arguments: w (int, float): Rectangle width h (int, float): Rectangle height Returns: (rect, max_rect) rect (Rectangle): Placed rectangle or None if was unable. max_rect (Rectangle): Maximal rectangle were rect was placed
f423:c0:m2
def _generate_splits(self, m, r):
new_rects = []<EOL>if r.left > m.left:<EOL><INDENT>new_rects.append(Rectangle(m.left, m.bottom, r.left-m.left, m.height))<EOL><DEDENT>if r.right < m.right:<EOL><INDENT>new_rects.append(Rectangle(r.right, m.bottom, m.right-r.right, m.height))<EOL><DEDENT>if r.top < m.top:<EOL><INDENT>new_rects.append(Rectangle(m.left, r.top, m.width, m.top-r.top))<EOL><DEDENT>if r.bottom > m.bottom:<EOL><INDENT>new_rects.append(Rectangle(m.left, m.bottom, m.width, r.bottom-m.bottom))<EOL><DEDENT>return new_rects<EOL>
When a rectangle is placed inside a maximal rectangle, it stops being one and up to 4 new maximal rectangles may appear depending on the placement. _generate_splits calculates them. Arguments: m (Rectangle): max_rect rectangle r (Rectangle): rectangle placed Returns: list : list containing new maximal rectangles or an empty list
f423:c0:m3
def _split(self, rect):
max_rects = collections.deque()<EOL>for r in self._max_rects:<EOL><INDENT>if r.intersects(rect):<EOL><INDENT>max_rects.extend(self._generate_splits(r, rect))<EOL><DEDENT>else:<EOL><INDENT>max_rects.append(r)<EOL><DEDENT><DEDENT>self._max_rects = list(max_rects)<EOL>
Split all max_rects intersecting the rectangle rect into up to 4 new max_rects. Arguments: rect (Rectangle): Rectangle Returns: split (Rectangle list): List of rectangles resulting from the split
f423:c0:m4
def _remove_duplicates(self):
contained = set()<EOL>for m1, m2 in itertools.combinations(self._max_rects, <NUM_LIT:2>):<EOL><INDENT>if m1.contains(m2):<EOL><INDENT>contained.add(m2)<EOL><DEDENT>elif m2.contains(m1):<EOL><INDENT>contained.add(m1)<EOL><DEDENT><DEDENT>self._max_rects = [m for m in self._max_rects if m not in contained]<EOL>
Remove every maximal rectangle contained by another one.
f423:c0:m5
def fitness(self, width, height):
assert(width > <NUM_LIT:0> and height > <NUM_LIT:0>)<EOL>rect, max_rect = self._select_position(width, height)<EOL>if rect is None:<EOL><INDENT>return None<EOL><DEDENT>return self._rect_fitness(max_rect, rect.width, rect.height)<EOL>
Metric used to rate how much space is wasted if a rectangle is placed. Returns a value greater or equal to zero, the smaller the value the more 'fit' is the rectangle. If the rectangle can't be placed, returns None. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height Returns: int, float: Rectangle fitness None: Rectangle can't be placed
f423:c0:m6
def add_rect(self, width, height, rid=None):
assert(width > <NUM_LIT:0> and height ><NUM_LIT:0>)<EOL>rect, _ = self._select_position(width, height)<EOL>if not rect:<EOL><INDENT>return None<EOL><DEDENT>self._split(rect)<EOL>self._remove_duplicates()<EOL>rect.rid = rid<EOL>self.rectangles.append(rect)<EOL>return rect<EOL>
Add rectangle of widthxheight dimensions. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height rid: Optional rectangle user id Returns: Rectangle: Rectangle with placemente coordinates None: If the rectangle couldn be placed.
f423:c0:m7
def _select_position(self, w, h):
fitn = ((m.y+h, m.x, w, h, m) for m in self._max_rects <EOL>if self._rect_fitness(m, w, h) is not None)<EOL>fitr = ((m.y+w, m.x, h, w, m) for m in self._max_rects <EOL>if self._rect_fitness(m, h, w) is not None)<EOL>if not self.rot:<EOL><INDENT>fitr = []<EOL><DEDENT>fit = itertools.chain(fitn, fitr)<EOL>try:<EOL><INDENT>_, _, w, h, m = min(fit, key=first_item)<EOL><DEDENT>except ValueError:<EOL><INDENT>return None, None<EOL><DEDENT>return Rectangle(m.x, m.y, w, h), m<EOL>
Select the position where the y coordinate of the top of the rectangle is lower, if there are severtal pick the one with the smallest x coordinate
f423:c1:m0
def distance(self, point):
return sqrt((self.x-point.x)**<NUM_LIT:2>+(self.y-point.y)**<NUM_LIT:2>)<EOL>
Calculate distance to another point
f424:c0:m3
def __init__(self, start, end):
assert(isinstance(start, Point) and isinstance(end, Point))<EOL>self.start = start<EOL>self.end = end<EOL>
Arguments: start (Point): Segment start point end (Point): Segment end point
f424:c1:m0
@property<EOL><INDENT>def length_squared(self):<DEDENT>
return self.start.distance_squared(self.end)<EOL>
Faster than length and useful for some comparisons
f424:c1:m3
def __init__(self, start, length):
assert(isinstance(start, Point) and not isinstance(length, Point))<EOL>super(HSegment, self).__init__(start, Point(start.x+length, start.y))<EOL>
Create an Horizontal segment given its left most end point and its length. Arguments: - start (Point): Starting Point - length (number): segment length
f424:c2:m0
def __init__(self, start, length):
assert(isinstance(start, Point) and not isinstance(length, Point))<EOL>super(VSegment, self).__init__(start, Point(start.x, start.y+length))<EOL>
Create a Vertical segment given its bottom most end point and its length. Arguments: - start (Point): Starting Point - length (number): segment length
f424:c3:m0
def __init__(self, x, y, width, height, rid = None):
assert(height >=<NUM_LIT:0> and width >=<NUM_LIT:0>)<EOL>self.width = width<EOL>self.height = height<EOL>self.x = x<EOL>self.y = y<EOL>self.rid = rid<EOL>
Args: x (int, float): y (int, float): width (int, float): height (int, float): rid (int):
f424:c4:m0
@property<EOL><INDENT>def bottom(self):<DEDENT>
return self.y<EOL>
Rectangle bottom edge y coordinate
f424:c4:m1
@property<EOL><INDENT>def top(self):<DEDENT>
return self.y+self.height<EOL>
Rectangle top edge y coordiante
f424:c4:m2
@property<EOL><INDENT>def left(self):<DEDENT>
return self.x<EOL>
Rectangle left ednge x coordinate
f424:c4:m3
@property<EOL><INDENT>def right(self):<DEDENT>
return self.x+self.width<EOL>
Rectangle right edge x coordinate
f424:c4:m4
def __lt__(self, other):
return self.area() < other.area()<EOL>
Compare rectangles by area (used for sorting)
f424:c4:m9
def __eq__(self, other):
if not isinstance(other, self.__class__):<EOL><INDENT>return False<EOL><DEDENT>return (self.width == other.width andself.height == other.height andself.x == other.x andself.y == other.y)<EOL>
Equal rectangles have same area.
f424:c4:m10
def __iter__(self):
yield self.corner_top_l<EOL>yield self.corner_top_r<EOL>yield self.corner_bot_r<EOL>yield self.corner_bot_l<EOL>
Iterate through rectangle corners
f424:c4:m12
def area(self):
return self.width * self.height<EOL>
Rectangle area
f424:c4:m14