Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|># For each of step of the output sequence, decide which character should be chosen model.add(TimeDistributed(Dense(INPUT_DIMENSION_SIZE+2))) # model.add(Activation('softmax')) # model.add(Activation('hard_sigmoid')) model.add(Activation('sigmoid')) model.compile(loss='binary_crossen...
history = LossHistory()
Given snippet: <|code_start|>epsilon = 1e-8 ADAM_ = Adam(lr=lr, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon) model.compile(loss='binary_crossentropy', # loss='mse', # optimizer='adam', optimizer=ADAM_, metrics=['accuracy']) print() print(time.strftime('%Y-%m-%...
history = LossHistory()
Based on the snippet: <|code_start|># compile the model model.compile(loss='binary_crossentropy', # loss='mse', # optimizer='adam', optimizer=ADAM_, metrics=['accuracy']) # show the information of the model print() print(time.strftime('%Y-%m-%d %H:%M:%S')) print(...
history = LossHistory()
Based on the snippet: <|code_start|>model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', # loss='mse', optimizer='adam', metrics=['accuracy']) print() print(time.strftime('%Y-%m-%d %H:%M:%S')) print("Model architecture") plot(model, show_shapes=True, to_...
history = LossHistory()
Given the code snippet: <|code_start|>model.add(TimeDistributed(Dense(INPUT_DIMENSION_SIZE))) # model.add(Activation('softmax')) # model.add(Activation('hard_sigmoid')) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', # loss='mse', optimizer='adam', m...
history = LossHistory()
Given the following code snippet before the placeholder: <|code_start|>model.add(TimeDistributed(Dense(INPUT_DIMENSION_SIZE+2))) # model.add(Activation('softmax')) # model.add(Activation('hard_sigmoid')) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', #loss='mse', ...
history = LossHistory()
Using the snippet: <|code_start|># For each of step of the output sequence, decide which character should be chosen model.add(TimeDistributed(Dense(INPUT_DIMENSION_SIZE))) # model.add(Activation('softmax')) # model.add(Activation('hard_sigmoid')) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy...
history = LossHistory()
Predict the next line for this snippet: <|code_start|>model.add(TimeDistributed(Dense(INPUT_DIMENSION_SIZE+1))) model.add(Activation('softmax')) # model.add(Activation('hard_sigmoid')) # model.add(Activation('sigmoid')) model.compile(#loss='binary_crossentropy', # loss='mse', loss='categori...
history = LossHistory()
Given the following code snippet before the placeholder: <|code_start|># model.add(TimeDistributed(Dense(INPUT_DIMENSION_SIZE+2))) # # model.add(Activation('softmax')) # # model.add(Activation('hard_sigmoid')) # model.add(Activation('sigmoid')) print('Compile...') model.compile(loss='binary_crossentropy', ...
history = LossHistory()
Given the following code snippet before the placeholder: <|code_start|># For each of step of the output sequence, decide which character should be chosen model.add(TimeDistributed(Dense(INPUT_DIMENSION_SIZE+2))) # model.add(Activation('softmax')) # model.add(Activation('hard_sigmoid')) model.add(Activation('sigmoid')) ...
history = LossHistory()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/preferencesDialog.ui' # # Created: Sat Jul 25 12:17:10 2015 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! try: ...
self.tabWidget = FingerTabWidget(CanardPreferencesDialog)
Predict the next line for this snippet: <|code_start|> def createURL(self): repository = self.repositoryURLs.currentText() searchTerms = self.searchTerms.text() if self.objectType.isVisible(): objectType = self.objectType.currentText() else: objectType = self....
cache.insertCache(uri=self.currentURI,objType=objectType,obj=etree.tostring(self.items[self.selected]))
Using the snippet: <|code_start|> if node[-1]: params = [s.str for s in node[-1]] params = ", ".join(params) + ", " else: params = "" returns = [s.str for s in node[:-1]] returns = ", ".join(returns) return "%(name)s(" + params + returns + ") ;" def Returns(node): """R...
out += ", " + type_string(child) + "& " + str(child)
Given snippet: <|code_start|>%(3)s }""" return """void %(name)s(%(2)s%(1)s) { %(3)s }""" def Var(node): """Function call as variable Writing a function as if a variable, is equivalent to calling the function without arguments. Property: name (of variable) Examples: >>> print(matlab2cpp.qscript("fu...
return Get(node)
Here is a snippet: <|code_start|> def vec(node): if len(node) != 1: if not len(node): return elif len(node) == 2 and node[1].cls == "Int" and node[1].value == "1": pass else: return <|code_end|> . Write the next line using the current file imports: ...
arg, dim = arma.configure_arg(node[0], 0)
Predict the next line for this snippet: <|code_start|> The RPCServer thread provides an API for external programs to interact with MOM. """ def __init__(self, config, momFuncs): threading.Thread.__init__(self, name="RPCServer") self.setDaemon(True) self.config = config sel...
self.server = UnixXmlRpcServer(unix_port)
Based on the snippet: <|code_start|> self._check_status(response) return response['vmList'][0]['pid'] except vdsmException as e: e.handle_exception() return None def getVmList(self): vmIds = [] try: response = self.vdsm_api.getVMLis...
raise HypervisorInterfaceError(msg)
Using the snippet: <|code_start|># Memory Overcommitment Manager # Copyright (C) 2016 Martin Sivak, Red Hat # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distri...
@memoize(expiration=CACHE_EXPIRATION)
Next line prediction: <|code_start|># Memory Overcommitment Manager # Copyright (C) 2016 Martin Sivak, Red Hat # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is dis...
@memoize(expiration=CACHE_EXPIRATION)
Based on the snippet: <|code_start|> # Parse the data string result = {} for item in data.split(","): parts = item.split(":") result[parts[0]] = int(parts[1]) # Construct the return dict ret = {} for key in self.getFields(): if key in r...
self.collector = HostMemory(None)
Given the code snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fift...
raise HypervisorInterfaceError(msg)
Based on the snippet: <|code_start|> self.logger.error("Guest Manager crashed", exc_info=True) else: self.logger.info("Guest Manager ending") def _spawn_guest_monitors(self, domain_list): """ Get the list of running domains and spawn GuestMonitors for any guests ...
guest = GuestMonitor(self.config, info, self.hypervisor_iface)
Given the code snippet: <|code_start|> self.logger.info("Guest Manager ending") def _spawn_guest_monitors(self, domain_list): """ Get the list of running domains and spawn GuestMonitors for any guests we are not already tracking. The GuestMonitor constructor might block ...
thread = GuestMonitorThread(info, guest)
Based on the snippet: <|code_start|> class PublicTest(BaseTest): def test_public_anon(self): factory = APIRequestFactory() request = factory.get("/") <|code_end|> , predict the immediate next line with the help of imports: from rest_framework.test import APIRequestFactory from .base import BaseTe...
self.assertTrue(Public().is_permitted(request))
Next line prediction: <|code_start|> class PublicTest(BaseTest): def test_public_anon(self): factory = APIRequestFactory() request = factory.get("/") self.assertTrue(Public().is_permitted(request)) def test_public_not_staff(self): user = self.login(is_staff=False) fact...
self.assertFalse(StaffOnly().is_permitted(request))
Given the following code snippet before the placeholder: <|code_start|> logger = logging.getLogger(__name__) order_status_changed = get_class("order.signals", "order_status_changed") @receiver(order_payment_authorized) def send_order_confirmation_message(sender, order, request, **kwargs): <|code_end|> , predict the ...
OrderMessageSender(request).send_order_placed_email(order)
Given the code snippet: <|code_start|> logger = logging.getLogger(__name__) order_status_changed = get_class("order.signals", "order_status_changed") @receiver(order_payment_authorized) def send_order_confirmation_message(sender, order, request, **kwargs): OrderMessageSender(request).send_order_placed_email(orde...
if new_status == ORDER_STATUS_PAYMENT_DECLINED:
Given the code snippet: <|code_start|> ) self.assertPaymentSources( order_resp.data["number"], sources=[ dict( source_name="Cash", reference="", allocated=D("10.00"), debited=D("10.00")...
pre_calculate_total.connect(handle_pre_calculate_total)
Given the following code snippet before the placeholder: <|code_start|> self.assertPaymentSources( order_resp.data["number"], sources=[ dict( source_name="Cash", reference="", allocated=D("10.00"), ...
order_placed.connect(handle_order_placed)
Using the snippet: <|code_start|> order_resp.data["number"], sources=[ dict( source_name="Cash", reference="", allocated=D("10.00"), debited=D("10.00"), ), ], ) ...
order_payment_authorized.connect(handle_order_payment_authorized)
Here is a snippet: <|code_start|> # API should return a new Basket now self.assertNotEqual(self._get_basket_id(), basket_id) def test_voucher_for_order_payment_declined(self): # Login as one user self.login(is_staff=False) # Make a basket basket_id = self._prepare_ba...
_set_order_payment_declined(order, order_resp.wsgi_request)
Predict the next line after this snippet: <|code_start|> self.assertEqual(states_resp.status_code, status.HTTP_200_OK) self.assertEqual(states_resp.data["order_status"], "Pending") self.assertEqual( states_resp.data["payment_method_states"].keys(), set(["pay-later"]) ) ...
"order": OrderTokenField.get_order_token(order),
Based on the snippet: <|code_start|> Order = get_model("order", "Order") Basket = get_model("basket", "Basket") Default = get_class("partner.strategy", "Default") OrderCreator = get_class("order.utils", "OrderCreator") <|code_end|> , predict the immediate next line with the help of imports: from decimal import Decim...
class CheckoutAPITest(BaseTest):
Next line prediction: <|code_start|>Order = get_model("order", "Order") OrderCreator = get_class("order.utils", "OrderCreator") CHECKOUT_ORDER_ID = "api_checkout_pending_order_id" CHECKOUT_PAYMENT_STEPS = "api_checkout_payment_steps" def _session_pickle(obj): pickled = pickle.dumps(obj) base64ed = base64.sta...
order.set_status(ORDER_STATUS_AUTHORIZED)
Continue the code snippet: <|code_start|> pickled = base64.standard_b64decode(base64ed) obj = pickle.loads(pickled) return obj def _update_payment_method_state(request, method_key, state): states = request.session.get(CHECKOUT_PAYMENT_STEPS, {}) states[method_key] = _session_pickle(state) reque...
order.set_status(ORDER_STATUS_PAYMENT_DECLINED)
Given snippet: <|code_start|> order_payment_authorized.send(sender=order, order=order, request=request) def _set_order_payment_declined(order, request): # Set the order status order.set_status(ORDER_STATUS_PAYMENT_DECLINED) voucher_applications = order.voucherapplication_set.all() for voucher_app...
order_payment_declined.send(sender=order, order=order, request=request)
Continue the code snippet: <|code_start|> return utfed def _session_unpickle(utfed): base64ed = utfed.encode("utf8") pickled = base64.standard_b64decode(base64ed) obj = pickle.loads(pickled) return obj def _update_payment_method_state(request, method_key, state): states = request.session.get(...
order_payment_authorized.send(sender=order, order=order, request=request)
Using the snippet: <|code_start|> voucher = voucher_application.voucher parent = getattr(voucher, "parent", None) if parent: parent.num_orders = F("num_orders") - 1 parent.save(update_children=False) voucher.num_orders = F("num_orders") - 1 voucher.save()...
not_complete = [s for k, s in states.items() if s.status != COMPLETE]
Here is a snippet: <|code_start|> voucher_applications = order.voucherapplication_set.all() for voucher_application in voucher_applications: voucher = voucher_application.voucher parent = getattr(voucher, "parent", None) if parent: parent.num_orders = F("num_orders") - 1 ...
declined = [s for k, s in states.items() if s.status == DECLINED]
Given the code snippet: <|code_start|> not_complete = [s for k, s in states.items() if s.status != COMPLETE] if len(not_complete) <= 0: # Authorized the order and consume all the payments _set_order_authorized(order, request) for key, state in states.items(): mark_payment_meth...
if state.status != CONSUMED:
Predict the next line after this snippet: <|code_start|>def clear_payment_method_states(request): request.session[CHECKOUT_PAYMENT_STEPS] = {} request.session.modified = True def clear_consumed_payment_method_states(request): curr_states = list_payment_method_states(request) new_states = {} for ke...
order, request, method_key, Complete(amount, source_id=source_id)
Predict the next line for this snippet: <|code_start|> curr_states = list_payment_method_states(request) new_states = {} for key, state in curr_states.items(): if state.status != CONSUMED: new_states[key] = state clear_payment_method_states(request) for key, state in new_states.it...
order, request, method_key, Declined(amount, source_id=source_id)
Predict the next line for this snippet: <|code_start|> for key, state in new_states.items(): _update_payment_method_state(request, key, state) def update_payment_method_state(order, request, method_key, state): _update_payment_method_state(request, method_key, state) _update_order_status(order, req...
order, request, method_key, Consumed(amount, source_id=source_id)
Based on the snippet: <|code_start|> Country = get_model("address", "Country") class EmailAddressCacheTest(BaseTest): def test_cache(self): <|code_end|> , predict the immediate next line with the help of imports: from oscar.core.loading import get_model from .base import BaseTest from ..cache import ( EmailA...
EmailAddressCache(1).set({"email": "foo1@example.com"})
Predict the next line for this snippet: <|code_start|> Country = get_model("address", "Country") class EmailAddressCacheTest(BaseTest): def test_cache(self): EmailAddressCache(1).set({"email": "foo1@example.com"}) EmailAddressCache(2).set({"email": "foo2@example.com"}) self.assertEqual(Ema...
ShippingAddressCache(1).set(
Predict the next line for this snippet: <|code_start|> class ShippingAddressCacheTest(BaseTest): def test_cache(self): ShippingAddressCache(1).set( { "first_name": "Bart", "last_name": "Simpson", "line1": "123 Evergreen Terrace", "l...
BillingAddressCache(1).set(
Here is a snippet: <|code_start|> class BillingAddressCacheTest(BaseTest): def test_cache(self): BillingAddressCache(1).set( { "first_name": "Lisa", "last_name": "Simpson", "line1": "123 Evergreen Terrace", "line4": "Springfield", ...
ShippingMethodCache(1).set(
Continue the code snippet: <|code_start|> Order = get_model("order", "Order") class GetCardTokenView(generics.GenericAPIView): def post(self, request): amount = Decimal(request.data["amount"]) order_number = request.data["reference_number"] order = get_object_or_404(Order, number=order_num...
new_state = CreditCard().require_authorization_post(order, method_key, amount)
Given the following code snippet before the placeholder: <|code_start|> try: host, port = sock.split(":") port = int(port) if not host: raise bind_param = (host, port) except Exception:...
wrap = lazyload.Wrapper(__name__)
Based on the snippet: <|code_start|> # TODO: might refactor to another file? def mk_msgs_w_ctx(*ctx_ids): """ helper to create a msg with a few contexts """ msg = generate_msg( message_content="test", message_meta=dict(entry1="meta1"), ) ctx_msgs = [] for ctx_id in ct...
CombineCtx([], name="ctx1")
Given snippet: <|code_start|> # TODO: might refactor to another file? def mk_msgs_w_ctx(*ctx_ids): """ helper to create a msg with a few contexts """ msg = generate_msg( message_content="test", message_meta=dict(entry1="meta1"), ) ctx_msgs = [] for ctx_id in ctx_ids:...
with pytest.raises(NodeException):
Given the code snippet: <|code_start|>""" tests for pypeman.contrib.ctx """ # TODO: might refactor to another file? def mk_msgs_w_ctx(*ctx_ids): """ helper to create a msg with a few contexts """ <|code_end|> , generate the next line using the imports in this file: import asyncio import pytest from p...
msg = generate_msg(
Next line prediction: <|code_start|> message_content="test", message_meta=dict(entry1="meta1"), ) ctx_msgs = [] for ctx_id in ctx_ids: meta = dict(entry1="meta_%s" % ctx_id) ctx_msg = generate_msg( message_content={"val_%s" % ctx_id: "data_%s" % ctx_id}, ...
nut.channel = FakeChannel(loop)
Using the snippet: <|code_start|> reverse = True sort_key = order_by[1:] else: reverse = False sort_key = order_by result = [] for value in sorted(self.messages.values(), key=lambda x: x[sort_key], reverse=reverse): resp = dict(value) ...
raise PypemanConfigError('file message store requires a path')
Based on the snippet: <|code_start|>""" Global graph related pypeman functions. On the long run some commands of pypeman.commands might be candidates to be moved into this module """ def load_project(): <|code_end|> , predict the immediate next line with the help of imports: import importlib import sys import ti...
settings.init_settings()
Given the following code snippet before the placeholder: <|code_start|> importlib.import_module(project_module) except ImportError as exc: msg = str(exc) if 'No module' not in msg: print("IMPORT ERROR %s" % project_module) raise if project_module not in msg: ...
channel = channels.all_channels[0]
Given the code snippet: <|code_start|> if project_module not in msg: print("IMPORT ERROR %s" % project_module) raise print("Missing '%s' module !" % project_module) sys.exit(-1) except Exception: traceback.print_exc() raise plugin_manager.init_plugi...
raise PypemanError("couldn't obtain graph's loop")
Given the code snippet: <|code_start|>""" This module contains all persistence related things. """ SENTINEL = object() _backend = None async def get_backend(loop): """ Return the configured backend instance. :param loop: Asyncio loop to use. Passed backend instance. """ global _backend i...
if not settings.PERSISTENCE_BACKEND:
Predict the next line for this snippet: <|code_start|> tst_lock = threading.Lock() # migth refactor to a helper directory @contextmanager def chdir(path=None): """ enter a certain directory for a given test """ if path is None: path = os.path.realpath(os.path.dirname(__file__)) prev_di...
loop = wait_for_loop()
Given the following code snippet before the placeholder: <|code_start|> It can also encourage development of plugins outside of pypeman, that can lateron be merged into to pypeman.contrib.plugins or pypeman.plugins. """ logger = logging.getLogger(__name__) class PluginManager(): def __init__(self): s...
for plugin_name in settings.PLUGINS:
Next line prediction: <|code_start|> :param msg: incoming message :return: modified message after a process call and some treatment """ # TODO : Make sure exceptions are well raised (does not happen if i.e 1/0 here atm) if self.store_input_as: msg.add_context(self.st...
except Dropped:
Next line prediction: <|code_start|> result = await self._handle(msg) return result async def async_run(self, msg): """ Used to overload behaviour like thread Node without rewriting handle process """ result = await self.process(msg) return result def run(self, msg): ...
await (await get_backend(self.channel.loop)).store(self.fullpath(), key, value)
Given the code snippet: <|code_start|> def process(self, msg): content = choose_first_not_none(self.content, msg.payload) subject = choose_first_not_none(self.subject, msg.meta.get('subject'), 'No subject') sender = choose_first_not_none(self.sender, msg.meta.get('sender'), 'pypeman@example....
wrap = lazyload.Wrapper(__name__)
Predict the next line for this snippet: <|code_start|>""" Additional Nodes for working with the context """ class CombineCtx(nodes.BaseNode): """ creates payload dict with combination of different contexts """ def __init__(self, ctx_names, meta_from=None, flatten=False, *args, **kwargs): "...
raise NodeException("must have at least two contexts for combining")
Continue the code snippet: <|code_start|> class PolandSpecProvider(BaseSpecProvider): """Class that provides special data for Poland (pl).""" def __init__(self, seed: Seed = None) -> None: """Initialize attributes.""" super().__init__(locale=Locale.PL, seed=seed) class Meta: """The...
self, birth_date: Optional[DateTime] = None, gender: Optional[Gender] = None
Next line prediction: <|code_start|> __all__ = ["BaseField", "Field", "Schema"] class BaseField: """ BaseField is a class for generating data by the name of the method. Instance of this object takes any string which represents the name of any method of any supported data provider (:class:`~mimesis.G...
self._gen = Generic(locale, seed)
Predict the next line for this snippet: <|code_start|> dict_writer = csv.DictWriter(fp, fieldnames, **kwargs) dict_writer.writeheader() dict_writer.writerows(data) def to_json(self, file_path: str, iterations: int = 100, **kwargs: Any) -> None: """Export a schema as a JSO...
def create(self, iterations: int = 1) -> List[JSON]:
Given the following code snippet before the placeholder: <|code_start|> return result except KeyError: raise FieldError(name) def __str__(self) -> str: return f"{self.__class__.__name__} <{self._gen.locale}>" class Field(BaseField): """Greedy field. The field whcih...
def __init__(self, schema: SchemaType) -> None:
Given the following code snippet before the placeholder: <|code_start|>"""Implements classes for generating data by schema.""" __all__ = ["BaseField", "Field", "Schema"] class BaseField: """ BaseField is a class for generating data by the name of the method. Instance of this object takes any string whi...
seed: Seed = None,
Given snippet: <|code_start|> def validate_pesel(pesel): """Validate PESEL. :param pesel: pesel to validate :return: True if pesel is valid, False otherwise """ pesel_digits = list(map(int, pesel)) args = (9, 7, 3, 1, 9, 7, 3, 1, 9, 7) sum_v = sum(map(lambda x: x[0] * x[1], zip(args, pesel_...
return PolandSpecProvider()
Here is a snippet: <|code_start|> :param enum: Enum object. :return: Value of item. :raises NonEnumerableError: if ``item`` not in ``enum``. """ if item is None: result = get_random_item(enum, self.random) elif item and isinstance(item, enum): resul...
self._data: JSON = {}
Given the following code snippet before the placeholder: <|code_start|> class HelloView(FormView): form_class = HelloWorldForm template_name = 'djam/form.html' def form_valid(self, form): url = self.riff.reverse('hello_finished', slug=form.cleaned_data['name']) ...
class HelloFinishedView(TemplateView):
Given snippet: <|code_start|> class HelloWorldForm(forms.Form): name = forms.SlugField() class ExampleModelForm(GFKForm): <|code_end|> , continue by predicting the next line. Consider current file imports: from djam.forms import GFKField, GFKForm from test_project.example_app.models import ExampleModel import ...
content_object = GFKField(ExampleModel, 'content_object')
Continue the code snippet: <|code_start|> # Heavier security check -- don't allow redirection to a different # host. elif netloc and netloc != self.request.get_host(): redirect_to = self.riff.base_riff.get_default_url() # Okay, security checks complete. Log the user in. ...
class LogoutView(TemplateView):
Given snippet: <|code_start|>from __future__ import unicode_literals class Riff(object): widgets = [] riff_classes = [] display_name = None slug = None namespace = None app_name = None <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls ...
default_redirect_view = DefaultRedirectView
Based on the snippet: <|code_start|> if isinstance(col, basestring): try: value = getattr(obj, col) except AttributeError: value = '' if callable(value): try: value = value() except TypeError: ...
if not hasattr(request, 'user') or not isinstance(riff, Riff):
Here is a snippet: <|code_start|> mod, cls_name = widget.__module__, widget.__class__.__name__ if mod == 'django.forms.widgets' and 'widget' not in kwargs: kwargs['widget'] = getattr(floppyforms, cls_name) rebuild = True return rebuild, kwargs def _post_formfield(self...
field.widget = AddWrapper(field.widget, riff)
Using the snippet: <|code_start|> These are not related to the EOFs computed from the correlation matrix. **Optional argument:** *neofs* Number of EOFs to return. Defaults to all EOFs. If the number of EOFs requested is more than the number that are ...
c = correlation_map(
Based on the snippet: <|code_start|> (option 1). **Returns:** *eofs* An array with the ordered EOFs along the first dimension. **Examples:** All EOFs:: eofs = solver.eofsAsCovariance() The leading EOF:: eof1 = solver.eofsAsCov...
c = covariance_map(pcs, data, ddof=self._ddof)
Continue the code snippet: <|code_start|> pytest.skip('missing dependencies required to test ' 'the {!s} interface'.format(cls.interface)) cls.modify_solution() cls.neofs = cls.solution['eigenvalues'].shape[0] if cls.alternate_weights_arg is not None: ...
eofs *= sign_adjustments(eofs, reofs)
Next line prediction: <|code_start|> pass # Create a mapping from interface name to solver class. solvers = {'standard': eofs.standard.Eof} try: solvers['cdms'] = eofs.cdms.Eof except AttributeError: pass try: solvers['iris'] = eofs.iris.Eof except AttributeError: pass try: solvers['xarray'] ...
cls.solution = reference_solution(cls.interface, cls.weights)
Predict the next line for this snippet: <|code_start|> # Create a mapping from interface name to tools module and solver class. tools = {'standard': eofs.tools.standard} solvers = {'standard': eofs.standard.Eof} try: tools['cdms'] = eofs.tools.cdms solvers['cdms'] = eofs.cdms.Eof except AttributeError: pas...
cls.solution = reference_solution(cls.interface, cls.weights)
Continue the code snippet: <|code_start|> class ToolsTest(EofsTest): """""" interface = None weights = None @classmethod def setup_class(cls): try: cls.solution = reference_solution(cls.interface, cls.weights) except ValueError: pytest.skip('missing dependen...
cov = self._tomasked(cov) * sign_adjustments(eofs, reofs)
Continue the code snippet: <|code_start|># You should have received a copy of the GNU General Public License # along with eofs. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) # noqa try: except ImportError: pass # Create a mapping from interface...
cls.solution = reference_multivariate_solution(cls.interface,
Given the following code snippet before the placeholder: <|code_start|> def setup_class(cls): try: cls.solution = reference_multivariate_solution(cls.interface, cls.weights) except ValueError: pytest.skip('missing depe...
eofs = [e * sign_adjustments(e, r) for e, r in zip(eofs, reofs)]
Predict the next line after this snippet: <|code_start|>from __future__ import (absolute_import, division, print_function) # noqa try: except ImportError: pass # Create a mapping from interface name to solver class. solvers = {'standard': multivariate.standard.MultivariateEof} try: solvers['cdms'] = multi...
cls.solution = reference_multivariate_solution(cls.interface,
Given snippet: <|code_start|> field and there can be any number of PCs. **Arguments:** *pcs* PCs in a `cdms2` variable. *field* Spatial-temporal field in a `cdms2` variable. **Optional arguments:** *ddof* 'Delta degrees of freedom'. The divisor used to normalize ...
cov = standard_covmap(pcs.asma(), field.asma(), ddof=ddof)
Next line prediction: <|code_start|> Given a set of PCs in a `cdms2` variable (e.g., as output from `eofs.cdms.Eof.pcs`) and a spatial-temporal field in a `cdms` variable, one correlation map per PC is computed. The field must have the same temporal dimension as the PCs. Any number of spatial dimen...
cor = standard_cormap(pcs.asma(), field.asma())
Given the following code snippet before the placeholder: <|code_start|> Given a set of PCs in a `cdms2` variable (e.g., as output from `eofs.cdms.Eof.pcs`) and a spatial-temporal field in a `cdms` variable, one correlation map per PC is computed. The field must have the same temporal dimension as the PC...
outdims = covcor_dimensions(pcs.getAxisList(), field.getAxisList())
Here is a snippet: <|code_start|>try: except ImportError: pass # Create a mapping from interface name to solver class. solvers = {'standard': eofs.standard.Eof} try: solvers['cdms'] = eofs.cdms.Eof except AttributeError: pass try: solvers['iris'] = eofs.iris.Eof except AttributeError: pass try: ...
cls.solution = reference_solution(cls.interface, cls.weights)
Continue the code snippet: <|code_start|> class PaginatedList(ListView): template_name = 'showcase/paginated_list.html' model = Task paginate_by = 20 class FormExampleView(FormView): template_name = 'showcase/form.html' <|code_end|> . Use current file imports: from django.views.generic import ListV...
form_class = FormExample
Predict the next line after this snippet: <|code_start|> (forms.MultipleChoiceField( choices=COLOR_CHOICES, widget=forms.CheckboxSelectMultiple() ), "Checkboxes", 'input', { 'name': 'input', 'type': 'checkbox', 'value': 'red' }), (forms.ChoiceField( cho...
output = render_form(TestForm())
Given the code snippet: <|code_start|> choices=COLOR_CHOICES, widget=forms.CheckboxSelectMultiple() ), "Checkboxes", 'input', { 'name': 'input', 'type': 'checkbox', 'value': 'red' }), (forms.ChoiceField( choices=COLOR_CHOICES, widget=forms.RadioSele...
dom = get_dom(output)
Predict the next line for this snippet: <|code_start|> ), "Checkboxes", 'input', { 'name': 'input', 'type': 'checkbox', 'value': 'red' }), (forms.ChoiceField( choices=COLOR_CHOICES, widget=forms.RadioSelect() ), "Radios", 'input', { 'name': 'input', ...
element_has_all_attributes(dom.find(tag), attributes), f"{label} has attributes {str(attributes)}"
Here is a snippet: <|code_start|>#!/usr/bin/env python # vim: set fileencoding=utf-8 : """The Lanshark Daemon serves files, discovery, and search requests""" try: except ImportError: logger = logging.getLogger('lanshark') <|code_end|> . Write the next line using the current file imports: import BaseHTTPServer imp...
socket.getaddrinfo = cached(config.CACHE_TIMEOUT, stats=config.debug)(
Here is a snippet: <|code_start|> LOG_FORMAT = String('%(levelname)s:%(name)s:%(message)s', 'Format of logging output. ' 'See http://docs.python.org/lib/node422.html ' 'for format description') BROADCAST_IP = String("255.255.255.255", ...
DAEMON_IN_GUI = Boolean(True,
Given the code snippet: <|code_start|> player = player + " %s" return player def get_imageviewer(): return sys.platform.startswith("win") and "browser" or select_app( "kuickshow", "display") + " %s" or "browser" def get_openfile(): if sys.platform == "darwin": return "open" ...
PORT = Integer(31337, "Port to use for both UDP and TCP")
Here is a snippet: <|code_start|> except _winreg.error: pass return value player = '"%s"' % get_registry_value('Software\\VideoLAN','VLC') or '' else: player = select_app("gmplayer", "gxine", "totem", "kaffeine", "vlc", "mplayer", "xine"...
LOG_TARGET = String('-',
Here is a snippet: <|code_start|> return "utf-8" return locale.getpreferredencoding() class Config(configuration.Config): LOG_LEVEL = Enum('CRITICAL', ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), 'Sets the verbosity of logging output') LOG_TARGET = Str...
FOLDER_IMAGES = StringList([r"\.?folder\.(png|jpg|gif|img)$",
Given the code snippet: <|code_start|> reg = _winreg.OpenKey(hkey, subkey) value = _winreg.QueryValue(reg, name) _winreg.CloseKey(reg) except _winreg.error: pass return value player = '"%s"' % get_registry...
LOG_LEVEL = Enum('CRITICAL',