sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def create_server(self, server): """ Create a server and its storages based on a (locally created) Server object. Populates the given Server instance with the API response. 0.3.0: also supports giving the entire POST body as a dict that is directly serialised into JSON. Refer t...
Create a server and its storages based on a (locally created) Server object. Populates the given Server instance with the API response. 0.3.0: also supports giving the entire POST body as a dict that is directly serialised into JSON. Refer to the REST API documentation for correct format. ...
entailment
def modify_server(self, UUID, **kwargs): """ modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses and Storages are managed by their own add/remove methods. """ body = dict() body['server'] = {} for arg in kwargs: i...
modify_server allows updating the server's updateable_fields. Note: Server's IP-addresses and Storages are managed by their own add/remove methods.
entailment
def get_server_data(self, UUID): """ Return '/server/uuid' data in Python dict. Creates object representations of any IP-address and Storage. """ data = self.get_request('/server/{0}'.format(UUID)) server = data['server'] # Populate subobjects IPAddresse...
Return '/server/uuid' data in Python dict. Creates object representations of any IP-address and Storage.
entailment
def feed(f, limit=25): """ Pull a feed :param f: feed name (eg: csirtgadgetes/correlated) :param limit: return value limit (default 25) :return: Feed dict """ if '/' not in f: raise ValueError('feed name must be formatted like: ' 'csirtgadgets/scanners') ...
Pull a feed :param f: feed name (eg: csirtgadgetes/correlated) :param limit: return value limit (default 25) :return: Feed dict
entailment
def indicator_create(f, i): """ Create an indicator in a feed :param f: feed name (eg: wes/test) :param i: indicator dict (eg: {'indicator': 'example.com', 'tags': ['ssh'], 'description': 'this is a test'}) :return: dict of indicator """ if '/' not in f: raise ValueError('feed na...
Create an indicator in a feed :param f: feed name (eg: wes/test) :param i: indicator dict (eg: {'indicator': 'example.com', 'tags': ['ssh'], 'description': 'this is a test'}) :return: dict of indicator
entailment
def convert_from_file(file): """ Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name. """ if isinstance(file, six_string_types): with open(file, 'rb') as f: return _internal_con...
Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name.
entailment
def _internal_convert(inp): """ Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. """ ''' Converts file in IDX format provided by file-like input into numpy.ndarray and returns it. ''' # Read the "magic number" - 4 bytes. try: mn ...
Converts file in IDX format provided by file-like input into numpy.ndarray and returns it.
entailment
def convert_to_file(file, ndarr): """ Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file name. """ if isinstance(file, six_string_types): with open(file, 'wb') as fp: _internal_write(fp, ndarr) else...
Writes the contents of the numpy.ndarray ndarr to file in IDX format. file is a file-like object (with write() method) or a file name.
entailment
def convert_to_string(ndarr): """ Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it. """ with contextlib.closing(BytesIO()) as bytesio: _internal_write(bytesio, ndarr) return bytesio.getvalue()
Writes the contents of the numpy.ndarray ndarr to bytes in IDX format and returns it.
entailment
def _internal_write(out_stream, arr): """ Writes numpy.ndarray arr to a file-like object (with write() method) in IDX format. """ if arr.size == 0: raise FormatError('Cannot encode empty array.') try: type_byte, struct_lib_type = _DATA_TYPES_NUMPY[str(arr.dtype)] except Key...
Writes numpy.ndarray arr to a file-like object (with write() method) in IDX format.
entailment
def fetch_access_token_by_client_credentials(self): ''' There are three ways to let you start using KKBOX's Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from K...
There are three ways to let you start using KKBOX's Open/Partner API. The first way among them is to generate a client credential to fetch an access token to let KKBOX identify you. It allows you to access public data from KKBOX such as public albums, playlists and so on. Howeve...
entailment
def get_OS_UUID(cls, os): """ Validate Storage OS and its UUID. If the OS is a custom OS UUID, don't validate against templates. """ if os in cls.templates: return cls.templates[os] uuid_regexp = '^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}...
Validate Storage OS and its UUID. If the OS is a custom OS UUID, don't validate against templates.
entailment
def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in parallel in an asynchronous way. ''' result_futures = [self.executor_pool.submit(resp_generator, req, *args, **kwargs) for req in requests] resp = [res_future.re...
Calls the resp_generator for all the requests in parallel in an asynchronous way.
entailment
def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in sequential order. ''' return [resp_generator(request) for request in requests]
Calls the resp_generator for all the requests in sequential order.
entailment
def setup_logging(args): """ Sets up basic logging :param args: ArgParse arguments :return: nothing. sets logger up globally """ loglevel = logging.WARNING if args.verbose: loglevel = logging.INFO if args.debug: loglevel = logging.DEBUG console = logging.StreamHandl...
Sets up basic logging :param args: ArgParse arguments :return: nothing. sets logger up globally
entailment
def get_ip(self, address): """ Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210') """ res = self.get_request('/ip_address/' + address) return IPAddress(cloud_manager=self, **res['ip_address'])
Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210')
entailment
def get_ips(self): """ Get all IPAddress objects from the API. """ res = self.get_request('/ip_address') IPs = IPAddress._create_ip_address_objs(res['ip_addresses'], cloud_manager=self) return IPs
Get all IPAddress objects from the API.
entailment
def attach_ip(self, server, family='IPv4'): """ Attach a new (random) IPAddress to the given server (object or UUID). """ body = { 'ip_address': { 'server': str(server), 'family': family } } res = self.request('POST...
Attach a new (random) IPAddress to the given server (object or UUID).
entailment
def modify_ip(self, ip_addr, ptr_record): """ Modify an IP address' ptr-record (Reverse DNS). Accepts an IPAddress instance (object) or its address (string). """ body = { 'ip_address': { 'ptr_record': ptr_record } } res = ...
Modify an IP address' ptr-record (Reverse DNS). Accepts an IPAddress instance (object) or its address (string).
entailment
def new(self, user, name, description=None): """ Creates a new Feed object :param user: feed username :param name: feed name :param description: feed description :return: dict """ uri = self.client.remote + '/users/{0}/feeds'.format(user) data = ...
Creates a new Feed object :param user: feed username :param name: feed name :param description: feed description :return: dict
entailment
def delete(self, user, name): """ Removes a feed :param user: feed username :param name: feed name :return: true/false """ uri = self.client.remote + '/users/{}/feeds/{}'.format(user, name) resp = self.client.session.delete(uri) return resp.stat...
Removes a feed :param user: feed username :param name: feed name :return: true/false
entailment
def index(self, user): """ Returns a list of Feeds from the API :param user: feed username :return: list Example: ret = feed.index('csirtgadgets') """ uri = self.client.remote + '/users/{0}/feeds'.format(user) return self.client.get(uri)
Returns a list of Feeds from the API :param user: feed username :return: list Example: ret = feed.index('csirtgadgets')
entailment
def show(self, user, name, limit=None, lasttime=None): """ Returns a specific Feed from the API :param user: feed username :param name: feed name :param limit: limit the results :param lasttime: only show >= lasttime :return: dict Example: re...
Returns a specific Feed from the API :param user: feed username :param name: feed name :param limit: limit the results :param lasttime: only show >= lasttime :return: dict Example: ret = feed.show('csirtgadgets', 'port-scanners', limit=5)
entailment
def codenerix(request): ''' Codenerix CONTEXT ''' # Get values DEBUG = getattr(settings, 'DEBUG', False) VERSION = getattr(settings, 'VERSION', _('WARNING: No version set to this code, add VERSION contant to your configuration')) # Set environment return { 'DEBUG': DEBUG, ...
Codenerix CONTEXT
entailment
def build_object(self, obj): """Override django-bakery to skip profiles that raise 404""" try: build_path = self.get_build_path(obj) self.request = self.create_request(build_path) self.request.user = AnonymousUser() self.set_kwargs(obj) self.bu...
Override django-bakery to skip profiles that raise 404
entailment
def make_schedule_row(schedule_day, slot, seen_items): """Create a row for the schedule table.""" row = ScheduleRow(schedule_day, slot) skip = {} expanding = {} all_items = list(slot.scheduleitem_set .select_related('talk', 'page', 'venue') .all()) for ...
Create a row for the schedule table.
entailment
def generate_schedule(today=None): """Helper function which creates an ordered list of schedule days""" # We create a list of slots and schedule items schedule_days = {} seen_items = {} for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'): day = slot.get_day() if ...
Helper function which creates an ordered list of schedule days
entailment
def get_context_data(self, **kwargs): """Allow adding a 'render_description' parameter""" context = super(ScheduleXmlView, self).get_context_data(**kwargs) if self.request.GET.get('render_description', None) == '1': context['render_description'] = True else: conte...
Allow adding a 'render_description' parameter
entailment
def get(self, request): """Create a iCal file from the schedule""" # Heavily inspired by https://djangosnippets.org/snippets/2223/ and # the icalendar documentation calendar = Calendar() site = get_current_site(request) calendar.add('prodid', '-//%s Schedule//%s//' % (sit...
Create a iCal file from the schedule
entailment
def slug(request, url): """Look up a page by url (which is a tree of slugs)""" page = None if url: for slug in url.split('/'): if not slug: continue try: page = Page.objects.get(slug=slug, parent=page) except Page.DoesNotExist: ...
Look up a page by url (which is a tree of slugs)
entailment
def build_object(self, obj): """Override django-bakery to skip pages marked exclude_from_static""" if not obj.exclude_from_static: super(ShowPage, self).build_object(obj)
Override django-bakery to skip pages marked exclude_from_static
entailment
def build_object(self, obj): """Override django-bakery to skip talks that raise 403""" try: super(TalkView, self).build_object(obj) except PermissionDenied: # We cleanup the directory created self.unbuild_object(obj)
Override django-bakery to skip talks that raise 403
entailment
def get_object(self, *args, **kwargs): '''Only talk owners can see talks, unless they've been accepted''' object_ = super(TalkView, self).get_object(*args, **kwargs) if not object_.can_view(self.request.user): raise PermissionDenied return object_
Only talk owners can see talks, unless they've been accepted
entailment
def render_to_response(self, *args, **kwargs): '''Canonicalize the URL if the slug changed''' if self.request.path != self.object.get_absolute_url(): return HttpResponseRedirect(self.object.get_absolute_url()) return super(TalkView, self).render_to_response(*args, **kwargs)
Canonicalize the URL if the slug changed
entailment
def delete(self, request, *args, **kwargs): """Override delete to only withdraw""" talk = self.get_object() talk.status = WITHDRAWN talk.save() revisions.set_user(self.request.user) revisions.set_comment("Talk Withdrawn") return HttpResponseRedirect(self.success_u...
Override delete to only withdraw
entailment
def order_results_by(*fields): """A decorator that applies an ordering to the QuerySet returned by a function. """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kw): result = f(*args, **kw) return result.order_by(*fields) return wrapper ...
A decorator that applies an ordering to the QuerySet returned by a function.
entailment
def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): cache = caches[cache_name] result = cache.get(cache_key) if...
A decorator for caching the result of a function.
entailment
def build_queryset(self): """Override django-bakery's build logic to fake pagination.""" paths = [(os.path.join(self.build_prefix, 'index.html'), {})] self.request = None queryset = self.get_queryset() paginator = self.get_paginator(queryset, self.get_paginate_by(queryset)) ...
Override django-bakery's build logic to fake pagination.
entailment
def get_groups(self, gs=None, processed=[], initial=True): ''' <--------------------------------------- 12 columns ------------------------------------> <--- 6 columns ---> <--- 6 columns ---> ------------------------------------------ -----------...
<--------------------------------------- 12 columns ------------------------------------> <--- 6 columns ---> <--- 6 columns ---> ------------------------------------------ ------------------------------------------ | Info ...
entailment
def site_info(request): '''Expose the site's info to templates''' site = get_current_site(request) context = { 'WAFER_CONFERENCE_NAME': site.name, 'WAFER_CONFERENCE_DOMAIN': site.domain, } return context
Expose the site's info to templates
entailment
def navigation_info(request): '''Expose whether to display the navigation header and footer''' if request.GET.get('wafer_hide_navigation') == "1": nav_class = "wafer-invisible" else: nav_class = "wafer-visible" context = { 'WAFER_NAVIGATION_VISIBILITY': nav_class, } retur...
Expose whether to display the navigation header and footer
entailment
def registration_settings(request): '''Expose selected settings to templates''' context = {} for setting in ( 'WAFER_SSO', 'WAFER_HIDE_LOGIN', 'WAFER_REGISTRATION_OPEN', 'WAFER_REGISTRATION_MODE', 'WAFER_TALKS_OPEN', 'WAFER_VIDEO_LICENS...
Expose selected settings to templates
entailment
def profiles(self): ''' return the rolls this people is related with ''' limit = [] if self.is_admin(): limit.append(_("Administrator")) limit.sort() return limit
return the rolls this people is related with
entailment
def matern_function(Xi, Xj, *args): r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`. The Matern kernel has the following hyperparameters, always referenced in the order listed: = ===== ==================================== 0 sigma prefactor ...
r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`. The Matern kernel has the following hyperparameters, always referenced in the order listed: = ===== ==================================== 0 sigma prefactor 1 nu order of kernel 2 l1 le...
entailment
def _compute_k(self, tau): r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) ...
r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) :math:`k(\tau)` (less the :math...
entailment
def _compute_y(self, tau, return_r2l2=False): r"""Covert tau to :math:`y=2\nu\sum_i(\tau_i^2/l_i^2)`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. return_r2l2 : bool, optional Set to True to return a tu...
r"""Covert tau to :math:`y=2\nu\sum_i(\tau_i^2/l_i^2)`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. return_r2l2 : bool, optional Set to True to return a tuple of (`y`, `r2l2`). Default is False (on...
entailment
def _compute_y_wrapper(self, *args): r"""Convert tau to :math:`y=\sqrt{2\nu\sum_i(\tau_i^2/l_i^2)}`. Takes `tau` as an argument list for compatibility with :py:func:`mpmath.diff`. Parameters ---------- tau[0] : scalar float First element of `tau`. ...
r"""Convert tau to :math:`y=\sqrt{2\nu\sum_i(\tau_i^2/l_i^2)}`. Takes `tau` as an argument list for compatibility with :py:func:`mpmath.diff`. Parameters ---------- tau[0] : scalar float First element of `tau`. tau[1] : And so on... ...
entailment
def _compute_dk_dy(self, y, n): r"""Evaluate the derivative of the outer form of the Matern kernel. Uses the general Leibniz rule to compute the n-th derivative of: .. math:: f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(y^{1/2}) Par...
r"""Evaluate the derivative of the outer form of the Matern kernel. Uses the general Leibniz rule to compute the n-th derivative of: .. math:: f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(y^{1/2}) Parameters ---------- y : :...
entailment
def _compute_dy_dtau(self, tau, b, r2l2): r"""Evaluate the derivative of the inner argument of the Matern kernel. Take the derivative of .. math:: y = 2 \nu \sum_i(\tau_i^2 / l_i^2) Parameters ---------- tau : :py:class:`Mat...
r"""Evaluate the derivative of the inner argument of the Matern kernel. Take the derivative of .. math:: y = 2 \nu \sum_i(\tau_i^2 / l_i^2) Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimen...
entailment
def _compute_dk_dtau_on_partition(self, tau, p): """Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Overrides the version from :py:class:`gptools.kernel.core.ChainRuleKernel` in order to get the correct behavior at the origin. Paramet...
Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Overrides the version from :py:class:`gptools.kernel.core.ChainRuleKernel` in order to get the correct behavior at the origin. Parameters ---------- tau : :py:class:`Matrix`, (`M...
entailment
def add_logging_parser(main_parser): "Build an argparse argument parser to parse the command line." main_parser.set_defaults(setup_logging=set_logging_level) verbosity_group = main_parser.add_mutually_exclusive_group(required=False) verbosity_group.add_argument( '--verbose', '-v', ...
Build an argparse argument parser to parse the command line.
entailment
def set_logging_level(args): "Computes and sets the logging level from the parsed arguments." root_logger = logging.getLogger() level = logging.INFO logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING) if "verbose" in args and args.verbose is not None: logging.getLogger('...
Computes and sets the logging level from the parsed arguments.
entailment
def check_auth(user): ''' Check if the user should or shouldn't be inside the system: - If the user is staff or superuser: LOGIN GRANTED - If the user has a Person and it is not "disabled": LOGIN GRANTED - Elsewhere: LOGIN DENIED ''' # Initialize authentication auth = None person = ...
Check if the user should or shouldn't be inside the system: - If the user is staff or superuser: LOGIN GRANTED - If the user has a Person and it is not "disabled": LOGIN GRANTED - Elsewhere: LOGIN DENIED
entailment
def debug(self, msg): ''' Handle the debugging to a file ''' # If debug is not disabled if self.__debug is not False: # If never was set, try to set it up if self.__debug is None: # Check what do we have inside settings de...
Handle the debugging to a file
entailment
def authenticate(self, *args, **kwargs): ''' Authenticate the user agains LDAP ''' # Get config username = kwargs.get("username", None) password = kwargs.get("password", None) # Check user in Active Directory (authorization == None if can not connect to Active D...
Authenticate the user agains LDAP
entailment
def get_or_create_user(self, username, password): ''' Get or create the given user ''' # Get the groups for this user info = self.get_ad_info(username, password) self.debug("INFO found: {}".format(info)) # Find the user try: user = User.objec...
Get or create the given user
entailment
def synchronize(self, user, info): ''' It tries to do a group synchronization if possible This methods should be redeclared by the developer ''' self.debug("Synchronize!") # Remove all groups from this user user.groups.clear() # For all domains found fo...
It tries to do a group synchronization if possible This methods should be redeclared by the developer
entailment
def set_hyperparams(self, new_params): """Sets the free hyperparameters to the new parameter values in new_params. Parameters ---------- new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),) New parameter values, ordered as dictated ...
Sets the free hyperparameters to the new parameter values in new_params. Parameters ---------- new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),) New parameter values, ordered as dictated by the docstring for the class.
entailment
def _compute_r2l2(self, tau, return_l=False): r"""Compute the anisotropic :math:`r^2/l^2` term for the given `tau`. Here, :math:`\tau=X_i-X_j` is the difference vector. Computes .. math:: \frac{r^2}{l^2} = \sum_i\frac{\tau_i^2}{l_{i}^{2}} Assume...
r"""Compute the anisotropic :math:`r^2/l^2` term for the given `tau`. Here, :math:`\tau=X_i-X_j` is the difference vector. Computes .. math:: \frac{r^2}{l^2} = \sum_i\frac{\tau_i^2}{l_{i}^{2}} Assumes that the length parameters are the last `num_dim` el...
entailment
def enforce_bounds(self, v): """Set `enforce_bounds` for both of the kernels to a new value. """ self._enforce_bounds = v self.k1.enforce_bounds = v self.k2.enforce_bounds = v
Set `enforce_bounds` for both of the kernels to a new value.
entailment
def free_param_bounds(self): """Returns the bounds of the free hyperparameters. Returns ------- free_param_bounds : :py:class:`Array` Array of the bounds of the free parameters, in order. """ return scipy.concatenate((self.k1.free_param_bounds, self.k...
Returns the bounds of the free hyperparameters. Returns ------- free_param_bounds : :py:class:`Array` Array of the bounds of the free parameters, in order.
entailment
def free_param_names(self): """Returns the names of the free hyperparameters. Returns ------- free_param_names : :py:class:`Array` Array of the names of the free parameters, in order. """ return scipy.concatenate((self.k1.free_param_names, self.k2.fre...
Returns the names of the free hyperparameters. Returns ------- free_param_names : :py:class:`Array` Array of the names of the free parameters, in order.
entailment
def set_hyperparams(self, new_params): """Set the (free) hyperparameters. Parameters ---------- new_params : :py:class:`Array` or other Array-like New values of the free parameters. Raises ------ ValueError If the length o...
Set the (free) hyperparameters. Parameters ---------- new_params : :py:class:`Array` or other Array-like New values of the free parameters. Raises ------ ValueError If the length of `new_params` is not consistent with :py:attr:`se...
entailment
def _compute_dk_dtau(self, tau, n): r"""Evaluate :math:`dk/d\tau` at the specified locations with the specified derivatives. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. n : :py:class:`Array`, (`D`,) De...
r"""Evaluate :math:`dk/d\tau` at the specified locations with the specified derivatives. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. n : :py:class:`Array`, (`D`,) Degree of derivative with respect to each dime...
entailment
def _compute_dk_dtau_on_partition(self, tau, p): """Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. p : list of :py:class:`Array` ...
Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. p : list of :py:class:`Array` Each element is a block of the partition representi...
entailment
def _mask_cov_func(self, *args): """Masks the covariance function into a form usable by :py:func:`mpmath.diff`. Parameters ---------- *args : `num_dim` * 2 floats The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`. """ # Have to ...
Masks the covariance function into a form usable by :py:func:`mpmath.diff`. Parameters ---------- *args : `num_dim` * 2 floats The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`.
entailment
def constant(X, n, mu, hyper_deriv=None): """Function implementing a constant mean suitable for use with :py:class:`MeanFunction`. """ if (n == 0).all(): if hyper_deriv is not None: return scipy.ones(X.shape[0]) else: return mu * scipy.ones(X.shape[0]) else: ...
Function implementing a constant mean suitable for use with :py:class:`MeanFunction`.
entailment
def mtanh(alpha, z): """Modified hyperbolic tangent function mtanh(z; alpha). Parameters ---------- alpha : float The core slope of the mtanh. z : float or array The coordinate of the mtanh. """ z = scipy.asarray(z) ez = scipy.exp(z) enz = 1.0 / ez return ((1...
Modified hyperbolic tangent function mtanh(z; alpha). Parameters ---------- alpha : float The core slope of the mtanh. z : float or array The coordinate of the mtanh.
entailment
def mtanh_profile(X, n, x0, delta, alpha, h, b, hyper_deriv=None): """Profile used with the mtanh function to fit profiles, suitable for use with :py:class:`MeanFunction`. Only supports univariate data! Parameters ---------- X : array, (`M`, 1) The points to evaluate at. n : ar...
Profile used with the mtanh function to fit profiles, suitable for use with :py:class:`MeanFunction`. Only supports univariate data! Parameters ---------- X : array, (`M`, 1) The points to evaluate at. n : array, (1,) The order of derivative to compute. Only up to first der...
entailment
def linear(X, n, *args, **kwargs): """Linear mean function of arbitrary dimension, suitable for use with :py:class:`MeanFunction`. The form is :math:`m_0 * X[:, 0] + m_1 * X[:, 1] + \dots + b`. Parameters ---------- X : array, (`M`, `D`) The points to evaluate the model at. n :...
Linear mean function of arbitrary dimension, suitable for use with :py:class:`MeanFunction`. The form is :math:`m_0 * X[:, 0] + m_1 * X[:, 1] + \dots + b`. Parameters ---------- X : array, (`M`, `D`) The points to evaluate the model at. n : array of non-negative int, (`D`) ...
entailment
def update_schedule_items(*args, **kw): """We save all the schedule items associated with this slot, so the last_update time is updated to reflect any changes to the timing of the slots""" slot = kw.pop('instance', None) if not slot: return for item in slot.scheduleitem_set.all(): ...
We save all the schedule items associated with this slot, so the last_update time is updated to reflect any changes to the timing of the slots
entailment
def make_diff(current, revision): """Create the difference between the current revision and a previous version""" the_diff = [] dmp = diff_match_patch() for field in (set(current.field_dict.keys()) | set(revision.field_dict.keys())): # These exclusions really should be configurable if f...
Create the difference between the current revision and a previous version
entailment
def compare_view(self, request, object_id, version_id, extra_context=None): """Actually compare two versions.""" opts = self.model._meta object_id = unquote(object_id) # get_for_object's ordering means this is always the latest revision. # The reversion we want to compare to ...
Actually compare two versions.
entailment
def comparelist_view(self, request, object_id, extra_context=None): """Allow selecting versions to compare.""" opts = self.model._meta object_id = unquote(object_id) current = get_object_or_404(self.model, pk=object_id) # As done by reversion's history_view action_list = ...
Allow selecting versions to compare.
entailment
def grv(struct, position): ''' This function helps to convert date information for showing proper filtering ''' if position == 'year': size = 4 else: size = 2 if (struct[position][2]): rightnow = str(struct[position][0]).zfill(size) else: if position == 'year...
This function helps to convert date information for showing proper filtering
entailment
def _setup(self, request): ''' Entry point for this class, here we decide basic stuff ''' # Get details from self info = model_inspect(self) self._appname = getattr(self, 'appname', info['appname']) self._modelname = getattr(self, 'modelname', info['modelname']) ...
Entry point for this class, here we decide basic stuff
entailment
def get_template_names(self): ''' Build the list of templates related to this user ''' # Get user template template_model = getattr(self, 'template_model', "{0}/{1}_{2}".format(self._appname.lower(), self._modelname.lower(), self.get_template_names_key)) template_model_e...
Build the list of templates related to this user
entailment
def get_context_data(self, **kwargs): ''' Set a base context ''' # Call the base implementation first to get a context context = super(GenBase, self).get_context_data(**kwargs) # Update general context with the stuff we already calculated if hasattr(self, 'html_...
Set a base context
entailment
def dispatch(self, *args, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Get if this class is working as only a base render and List funcionality shouldn't be enabled onlybase = getattr(self, "onlybase", False) # REST not available when only...
Entry point for this class, here we decide basic stuff
entailment
def get_queryset(self, raw_query=False): # Call the base implementation if not self.haystack: queryset = super(GenList, self).get_queryset() else: queryset = SearchQuerySet().models(self.model) # Optional tweak methods Mfields = None MlimitQ = Non...
raise Exception("FOUND: {} -- __foreignkeys: {} -- __columns: {} -- autorules_keys: {} -- \ query_select_related: {} -- query_renamed: {} -- query_optimizer: {} | use_extra: {}| -- \ query: {} -- meta.fields: {} -- fields_related_model: {} -- query_verifier: {}\ -- ??? {} == {}".form...
entailment
def get_context_data(self, **kwargs): ''' Generic list view with validation included and object transfering support ''' # Call the base implementation first to get a context context = super(GenList, self).get_context_data(**kwargs) # Update general context with the stuff...
Generic list view with validation included and object transfering support
entailment
def get_context_json(self, context): ''' Return a base answer for a json answer ''' # Initialize answer answer = {} # Metadata builder answer['meta'] = self.__jcontext_metadata(context) # Filter builder answer['filter'] = self.__jcontext_filter(c...
Return a base answer for a json answer
entailment
def set_context_json(self, jsonquery): ''' Get a json parameter and rebuild the context back to a dictionary (probably kwargs) ''' # Make sure we are getting dicts if type(jsonquery) != dict: raise IOError("set_json_context() method can be called only with dictionari...
Get a json parameter and rebuild the context back to a dictionary (probably kwargs)
entailment
def dispatch(self, request, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Check if this is a webservice request self.json_worker = (bool(getattr(self.request, "authtoken", False))) or (self.json is True) self.__authtoken = (bool(getattr(self...
Entry point for this class, here we decide basic stuff
entailment
def get_form(self, form_class=None): ''' Set form groups to the groups specified in the view if defined ''' formobj = super(GenModify, self).get_form(form_class) # Set requested group to this form selfgroups = getattr(self, "form_groups", None) if selfgroups: ...
Set form groups to the groups specified in the view if defined
entailment
def dispatch(self, request, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Delete method must happen with POST not with GET if request.method == 'POST': # Check if this is a webservice request self.__authtoken = (bool(getattr(...
Entry point for this class, here we decide basic stuff
entailment
def dispatch(self, request, **kwargs): ''' Entry point for this class, here we decide basic stuff ''' # Check if this is a REST query to pusth the answer to responde in JSON if bool(self.request.META.get('HTTP_X_REST', False)): self.json = True # Check if th...
Entry point for this class, here we decide basic stuff
entailment
def get_filled_structure(self, subgroup=None): ''' method in charged of filling an structure containing the object fields values taking into account the 'group' attribute from the corresponding form object, which is necesary to fill the details form as it is configured in the 'gr...
method in charged of filling an structure containing the object fields values taking into account the 'group' attribute from the corresponding form object, which is necesary to fill the details form as it is configured in the 'group' attribute
entailment
def flatatt(attrs): """ Pilfered from `django.forms.utils`: Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. Otherwise, the value ...
Pilfered from `django.forms.utils`: Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. Otherwise, the value is formatted through its own dic...
entailment
def _compute_k(self, tau): r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) ...
r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) :math:`k(\tau)` (less t...
entailment
def _compute_dk_dy(self, y, n): """Evaluate the derivative of the outer form of the RQ kernel. Parameters ---------- y : :py:class:`Array`, (`M`,) `M` inputs to evaluate at. n : non-negative scalar int Order of derivative to compute. ...
Evaluate the derivative of the outer form of the RQ kernel. Parameters ---------- y : :py:class:`Array`, (`M`,) `M` inputs to evaluate at. n : non-negative scalar int Order of derivative to compute. Returns ------- dk_dy :...
entailment
def get_parent(self, directory): """ Given a directory name, return the Page representing it in the menu heirarchy. """ assert settings.PAGE_DIR.startswith('/') assert settings.PAGE_DIR.endswith('/') parents = directory[len(settings.PAGE_DIR):] page = No...
Given a directory name, return the Page representing it in the menu heirarchy.
entailment
def wafer_sso_url(context, sso_method): ''' Return the correct URL to SSO with the given method. ''' request = context.request url = reverse(getattr(views, '%s_login' % sso_method)) if 'next' in request.GET: url += '?' + urlencode({'next': request.GET['next']}) return url
Return the correct URL to SSO with the given method.
entailment
def authorize(args): """ Authorizes Coursera's OAuth2 client for using coursera.org API servers for a specific application """ oauth2_instance = oauth2.build_oauth2(args.app, args) oauth2_instance.build_authorizer() logging.info('Application "%s" authorized!', args.app)
Authorizes Coursera's OAuth2 client for using coursera.org API servers for a specific application
entailment
def check_auth(args): """ Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific application """ oauth2_instance = oauth2.build_oauth2(args.app, args) auth = oauth2_instance.build_authorizer() my_profile_url = ( 'https://api.coursera.org/api/externa...
Checks courseraoauth2client's connectivity to the coursera.org API servers for a specific application
entailment
def display_auth_cache(args): ''' Writes to the screen the state of the authentication cache. (For debugging authentication issues.) BEWARE: DO NOT email the output of this command!!! You must keep the tokens secure. Treat them as passwords. ''' oauth2_instance = oauth2.build_oauth2(args.app, ar...
Writes to the screen the state of the authentication cache. (For debugging authentication issues.) BEWARE: DO NOT email the output of this command!!! You must keep the tokens secure. Treat them as passwords.
entailment
def tanh_warp_arb(X, l1, l2, lw, x0): r"""Warps the `X` coordinate with the tanh model .. math:: l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w} Parameters ---------- X : :py:class:`Array`, (`M`,) or scalar float `M` locations to evaluate length sca...
r"""Warps the `X` coordinate with the tanh model .. math:: l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w} Parameters ---------- X : :py:class:`Array`, (`M`,) or scalar float `M` locations to evaluate length scale at. l1 : positive float Sma...
entailment
def gauss_warp_arb(X, l1, l2, lw, x0): r"""Warps the `X` coordinate with a Gaussian-shaped divot. .. math:: l = l_1 - (l_1 - l_2) \exp\left ( -4\ln 2\frac{(X-x_0)^2}{l_{w}^{2}} \right ) Parameters ---------- X : :py:class:`Array`, (`M`,) or scalar float `M` locatio...
r"""Warps the `X` coordinate with a Gaussian-shaped divot. .. math:: l = l_1 - (l_1 - l_2) \exp\left ( -4\ln 2\frac{(X-x_0)^2}{l_{w}^{2}} \right ) Parameters ---------- X : :py:class:`Array`, (`M`,) or scalar float `M` locations to evaluate length scale at. l1 : po...
entailment
def tanh_warp(x, n, l1, l2, lw, x0): r"""Implements a tanh warping function and its derivative. .. math:: l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w} Parameters ---------- x : float or array of float Locations to evaluate the function at. n ...
r"""Implements a tanh warping function and its derivative. .. math:: l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w} Parameters ---------- x : float or array of float Locations to evaluate the function at. n : int Derivative order to take. U...
entailment
def double_tanh_warp(x, n, lcore, lmid, ledge, la, lb, xa, xb): r"""Implements a sum-of-tanh warping function and its derivative. .. math:: l = a\tanh\frac{x-x_a}{l_a} + b\tanh\frac{x-x_b}{l_b} Parameters ---------- x : float or array of float Locations to evaluate the...
r"""Implements a sum-of-tanh warping function and its derivative. .. math:: l = a\tanh\frac{x-x_a}{l_a} + b\tanh\frac{x-x_b}{l_b} Parameters ---------- x : float or array of float Locations to evaluate the function at. n : int Derivative order to take. Used for...
entailment