Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> User = get_user_model() class SignUp(generics.CreateAPIView): queryset = User.objects.all() <|code_end|> , continue by predicting the next line. Consider current file imports: import base64 from django.contrib.auth import get_user_model, authenticate from django.contrib.auth.tokens import default_token_generator from django.utils.http import urlsafe_base64_decode from rest_framework import viewsets, generics, status, views from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import list_route from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from yak.rest_core.permissions import IsOwnerOrReadOnly from yak.rest_user.permissions import IsAuthenticatedOrCreate from yak.rest_user.serializers import SignUpSerializer, LoginSerializer, PasswordChangeSerializer, UserSerializer, \ PasswordResetSerializer, PasswordSetSerializer from yak.rest_user.utils import reset_password and context: # Path: yak/rest_core/permissions.py # class IsOwnerOrReadOnly(permissions.BasePermission): # """ # Object-level permission to only allow owners of an object to edit it. # Unauthenticated users can still read. # Assumes the model instance has a `user` attribute. # """ # def has_permission(self, request, view): # """ # This is specifically to use PUT for bulk updates, where it appears DRF does not use `has_object_permission` # """ # if request.method in permissions.SAFE_METHODS: # return True # else: # return request.user.is_authenticated # # def has_object_permission(self, request, view, obj): # # Read permissions are allowed to any request, # # so we'll always allow GET, HEAD or OPTIONS requests. # if request.method in permissions.SAFE_METHODS: # return True # # if isinstance(obj, User): # return obj == request.user # else: # return obj.user == request.user # # Path: yak/rest_user/serializers.py # class SignUpSerializer(AuthSerializerMixin, LoginSerializer): # password = serializers.CharField(max_length=128, write_only=True, error_messages={'required': 'Password required'}) # username = serializers.CharField( # error_messages={'required': 'Username required'}, # max_length=30, # validators=[RegexValidator(), UniqueValidator(queryset=User.objects.all(), message="Username taken")]) # email = serializers.EmailField( # allow_blank=True, # allow_null=True, # max_length=75, # required=False, # validators=[UniqueValidator(queryset=User.objects.all(), message="Email address taken")]) # # class Meta(LoginSerializer.Meta): # fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') # # class LoginSerializer(serializers.ModelSerializer): # client_id = serializers.SerializerMethodField() # client_secret = serializers.SerializerMethodField() # # class Meta: # model = User # fields = ('client_id', 'client_secret') # # def get_application(self, obj): # # If we're using version 0.8.0 or higher # if oauth_toolkit_version[0] >= 0 and oauth_toolkit_version[1] >= 8: # return obj.oauth2_provider_application.first() # else: # return obj.oauth2_provider_application.first() # # def get_client_id(self, obj): # return self.get_application(obj).client_id # # def get_client_secret(self, obj): # return self.get_application(obj).client_secret # # class PasswordChangeSerializer(PasswordConfirmSerializer): # old_password = serializers.CharField(required=True, error_messages={'required': 'Old password required'}) # # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) # # class PasswordResetSerializer(serializers.Serializer): # email = serializers.EmailField() # # class PasswordSetSerializer(PasswordConfirmSerializer): # uid = serializers.CharField() # token = serializers.CharField() # # Path: yak/rest_user/utils.py # def reset_password(request, email, subject_template_name='users/password_reset_subject.txt', # rich_template_name='users/password_reset_email_rich.html', # template_name='users/password_reset_email.html'): # """ # Inspired by Django's `PasswordResetForm.save()`. Extracted for reuse. # Allows password reset emails to be sent to users with unusable passwords # """ # from django.core.mail import send_mail # UserModel = get_user_model() # active_users = UserModel._default_manager.filter(email__iexact=email, is_active=True) # for user in active_users: # current_site = get_current_site(request) # site_name = current_site.name # domain = current_site.domain # c = { # 'email': user.email, # 'domain': domain, # 'site_name': site_name, # 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), # 'user': user, # 'token': default_token_generator.make_token(user), # 'protocol': 'http', # Your site can handle its own redirects # } # subject = loader.render_to_string(subject_template_name, c) # # Email subject *must not* contain newlines # subject = ''.join(subject.splitlines()) # email = loader.render_to_string(template_name, c) # html_email = loader.render_to_string(rich_template_name, c) # send_mail(subject, email, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_email) which might include code, classes, or functions. Output only the next line.
serializer_class = SignUpSerializer
Given the following code snippet before the placeholder: <|code_start|> User = get_user_model() class SignUp(generics.CreateAPIView): queryset = User.objects.all() serializer_class = SignUpSerializer permission_classes = (IsAuthenticatedOrCreate,) class Login(generics.ListAPIView): queryset = User.objects.all() <|code_end|> , predict the next line using imports from the current file: import base64 from django.contrib.auth import get_user_model, authenticate from django.contrib.auth.tokens import default_token_generator from django.utils.http import urlsafe_base64_decode from rest_framework import viewsets, generics, status, views from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import list_route from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from yak.rest_core.permissions import IsOwnerOrReadOnly from yak.rest_user.permissions import IsAuthenticatedOrCreate from yak.rest_user.serializers import SignUpSerializer, LoginSerializer, PasswordChangeSerializer, UserSerializer, \ PasswordResetSerializer, PasswordSetSerializer from yak.rest_user.utils import reset_password and context including class names, function names, and sometimes code from other files: # Path: yak/rest_core/permissions.py # class IsOwnerOrReadOnly(permissions.BasePermission): # """ # Object-level permission to only allow owners of an object to edit it. # Unauthenticated users can still read. # Assumes the model instance has a `user` attribute. # """ # def has_permission(self, request, view): # """ # This is specifically to use PUT for bulk updates, where it appears DRF does not use `has_object_permission` # """ # if request.method in permissions.SAFE_METHODS: # return True # else: # return request.user.is_authenticated # # def has_object_permission(self, request, view, obj): # # Read permissions are allowed to any request, # # so we'll always allow GET, HEAD or OPTIONS requests. # if request.method in permissions.SAFE_METHODS: # return True # # if isinstance(obj, User): # return obj == request.user # else: # return obj.user == request.user # # Path: yak/rest_user/serializers.py # class SignUpSerializer(AuthSerializerMixin, LoginSerializer): # password = serializers.CharField(max_length=128, write_only=True, error_messages={'required': 'Password required'}) # username = serializers.CharField( # error_messages={'required': 'Username required'}, # max_length=30, # validators=[RegexValidator(), UniqueValidator(queryset=User.objects.all(), message="Username taken")]) # email = serializers.EmailField( # allow_blank=True, # allow_null=True, # max_length=75, # required=False, # validators=[UniqueValidator(queryset=User.objects.all(), message="Email address taken")]) # # class Meta(LoginSerializer.Meta): # fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') # # class LoginSerializer(serializers.ModelSerializer): # client_id = serializers.SerializerMethodField() # client_secret = serializers.SerializerMethodField() # # class Meta: # model = User # fields = ('client_id', 'client_secret') # # def get_application(self, obj): # # If we're using version 0.8.0 or higher # if oauth_toolkit_version[0] >= 0 and oauth_toolkit_version[1] >= 8: # return obj.oauth2_provider_application.first() # else: # return obj.oauth2_provider_application.first() # # def get_client_id(self, obj): # return self.get_application(obj).client_id # # def get_client_secret(self, obj): # return self.get_application(obj).client_secret # # class PasswordChangeSerializer(PasswordConfirmSerializer): # old_password = serializers.CharField(required=True, error_messages={'required': 'Old password required'}) # # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) # # class PasswordResetSerializer(serializers.Serializer): # email = serializers.EmailField() # # class PasswordSetSerializer(PasswordConfirmSerializer): # uid = serializers.CharField() # token = serializers.CharField() # # Path: yak/rest_user/utils.py # def reset_password(request, email, subject_template_name='users/password_reset_subject.txt', # rich_template_name='users/password_reset_email_rich.html', # template_name='users/password_reset_email.html'): # """ # Inspired by Django's `PasswordResetForm.save()`. Extracted for reuse. # Allows password reset emails to be sent to users with unusable passwords # """ # from django.core.mail import send_mail # UserModel = get_user_model() # active_users = UserModel._default_manager.filter(email__iexact=email, is_active=True) # for user in active_users: # current_site = get_current_site(request) # site_name = current_site.name # domain = current_site.domain # c = { # 'email': user.email, # 'domain': domain, # 'site_name': site_name, # 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), # 'user': user, # 'token': default_token_generator.make_token(user), # 'protocol': 'http', # Your site can handle its own redirects # } # subject = loader.render_to_string(subject_template_name, c) # # Email subject *must not* contain newlines # subject = ''.join(subject.splitlines()) # email = loader.render_to_string(template_name, c) # html_email = loader.render_to_string(rich_template_name, c) # send_mail(subject, email, settings.DEFAULT_FROM_EMAIL, [user.email], html_message=html_email) . Output only the next line.
serializer_class = LoginSerializer
Given the following code snippet before the placeholder: <|code_start|># -*-mode: python; py-indent-offset: 4; indent-tabs-mode: nil; encoding: utf-8-dos; coding: utf-8 -*- """ Publish a message via RabbitMQ to a given chart on a OTMql4Py enabled terminal: {{{ }}} You wont see the return value unless you have already done a: {{{ sub run retval.# }}} The RabbitMQ host and login information is set in the {{{[RabbitMQ]}}} section of the {{{OTCmd2.ini}}} file; see the {{{-c/--config}}} command-line options. """ # pub cmd COMMAND ARG1 ... - publish a Mql command to Mt4, # the command should be a single string, with a space seperating arguments. SDOC = __doc__ LOPTIONS = [make_option("-c", "--chart", dest="sChartId", help="the target chart to publish to (or: ANY ALL NONE)"), ] LCOMMANDS = [] <|code_end|> , predict the next line using imports from the current file: import sys import os import json from optparse import make_option from OpenTrader.doer import Doer from OTMql427.SimpleFormat import sMakeMark and context including class names, function names, and sometimes code from other files: # Path: OpenTrader/doer.py # class Doer(PLogMixin): # """The Doer class has one main method: bexecute # which will execute the options and args given to it # in the do_instance method of the Cmd2 instance. # # It encapsulkates everything tthat is needed to do a # command in the Cmd2 instance. # """ # # def __init__(self, ocmd2, sprefix): # self.ocmd2 = ocmd2 # self.poutput = self.ocmd2.poutput # self.pfeedback = self.ocmd2.pfeedback # self.sprefix = sprefix # # def G(self, gVal=None): # if gVal is not None: # self.ocmd2._G = gVal # self._G = self.ocmd2._G # return self.ocmd2._G # # def vassert_args(self, lArgs, lcommands, imin=1): # assert len(lArgs) >= imin, \ # "ERROR: argument required, one of: " +str(lcommands) # sDo = lArgs[0] # assert sDo in lcommands + ['help'], \ # "ERROR: " +sDo +" choose one of: " +str(lcommands) # # def bis_help(self, lArgs): # sDo = lArgs[0] # # e.g. make help # if sDo != 'help': # return False # if not hasattr(self, 'lCommands'): # lCommands = [] # for sElt in dir(self): # if not sElt.startswith(self.sprefix): continue # sKey = sElt[len(self.sprefix)+1:] # lCommands.append(sKey) # self.lCommands = lCommands # if len(lArgs) == 1: # self.poutput(self.dhelp['']) # # N.B.: subcommands by convention are documented in the module docstring # self.poutput("For help on subcommands type: " +self.sprefix +" help <sub> ") # self.poutput("For help on options type: help " +self.sprefix) # return True # # e.g. make help features # smeth = lArgs[1] # smethod = self.sprefix +'_' + smeth # # FixMe: make a wrapper so this isnt needed? # if smeth not in self.dhelp and hasattr(self, smethod): # omethod = getattr(self, smethod) # if hasattr(omethod, '__doc__'): # self.dhelp[smeth] = omethod.__doc__ # if smeth in self.dhelp: # self.poutput(self.dhelp[smeth]) # self.poutput("For help on options type: help " +self.sprefix) # return True # raise NotImplementedError("Unknown help command for " +sDo +": " \ # +smeth +' not in ' +repr(self.lCommands)) # # def bexecute(self, loptions, dkw): # raise NotImplementedError(self.__class__.__name__) # # def vInfo(self, sMsg): # self.poutput("INFO: " +sMsg) # # def vWarn(self, sMsg): # self.poutput("WARN: " +sMsg) # # def vError(self, sMsg): # self.poutput("ERROR: " +sMsg) . Output only the next line.
class DoPublish(Doer):
Given the code snippet: <|code_start|># -*-mode: python; py-indent-offset: 4; indent-tabs-mode: nil; encoding: utf-8-dos; coding: utf-8 -*- """chart """ SDOC = __doc__ LOPTIONS = [] LCOMMANDS = [] <|code_end|> , generate the next line using the imports in this file: import sys import os from optparse import make_option from OpenTrader.doer import Doer and context (functions, classes, or occasionally code) from other files: # Path: OpenTrader/doer.py # class Doer(PLogMixin): # """The Doer class has one main method: bexecute # which will execute the options and args given to it # in the do_instance method of the Cmd2 instance. # # It encapsulkates everything tthat is needed to do a # command in the Cmd2 instance. # """ # # def __init__(self, ocmd2, sprefix): # self.ocmd2 = ocmd2 # self.poutput = self.ocmd2.poutput # self.pfeedback = self.ocmd2.pfeedback # self.sprefix = sprefix # # def G(self, gVal=None): # if gVal is not None: # self.ocmd2._G = gVal # self._G = self.ocmd2._G # return self.ocmd2._G # # def vassert_args(self, lArgs, lcommands, imin=1): # assert len(lArgs) >= imin, \ # "ERROR: argument required, one of: " +str(lcommands) # sDo = lArgs[0] # assert sDo in lcommands + ['help'], \ # "ERROR: " +sDo +" choose one of: " +str(lcommands) # # def bis_help(self, lArgs): # sDo = lArgs[0] # # e.g. make help # if sDo != 'help': # return False # if not hasattr(self, 'lCommands'): # lCommands = [] # for sElt in dir(self): # if not sElt.startswith(self.sprefix): continue # sKey = sElt[len(self.sprefix)+1:] # lCommands.append(sKey) # self.lCommands = lCommands # if len(lArgs) == 1: # self.poutput(self.dhelp['']) # # N.B.: subcommands by convention are documented in the module docstring # self.poutput("For help on subcommands type: " +self.sprefix +" help <sub> ") # self.poutput("For help on options type: help " +self.sprefix) # return True # # e.g. make help features # smeth = lArgs[1] # smethod = self.sprefix +'_' + smeth # # FixMe: make a wrapper so this isnt needed? # if smeth not in self.dhelp and hasattr(self, smethod): # omethod = getattr(self, smethod) # if hasattr(omethod, '__doc__'): # self.dhelp[smeth] = omethod.__doc__ # if smeth in self.dhelp: # self.poutput(self.dhelp[smeth]) # self.poutput("For help on options type: help " +self.sprefix) # return True # raise NotImplementedError("Unknown help command for " +sDo +": " \ # +smeth +' not in ' +repr(self.lCommands)) # # def bexecute(self, loptions, dkw): # raise NotImplementedError(self.__class__.__name__) # # def vInfo(self, sMsg): # self.poutput("INFO: " +sMsg) # # def vWarn(self, sMsg): # self.poutput("WARN: " +sMsg) # # def vError(self, sMsg): # self.poutput("ERROR: " +sMsg) . Output only the next line.
class DoChart(Doer):
Given the code snippet: <|code_start|> optionParser.set_usage("%s [options] %s" % (func.__name__[3:], arg_desc)) optionParser._func = func def oUpdateOptionParser(instance): if func.__name__.startswith('do_'): sName = func.__name__[3:] if hasattr(instance, 'oConfig') and sName in instance.oConfig: oConfigSection = instance.oConfig[sName] # iterate over optionParser for sKey, gVal in oConfigSection.iteritems(): sOption = '--' +sKey if optionParser.has_option(sOption): oOption = optionParser.get_option(sOption) # FixMe: only if the default is optparse.NO_DEFAULT? if oOption.default is optparse.NO_DEFAULT: # FixMe: does this set the default? oOption.default = gVal # FixMe: how about this? optionParser.defaults[oOption.dest] = oOption.default return optionParser def new_func(instance, arg): try: # makebe return a list and prepend it optionParser = oUpdateOptionParser(instance) opts, newArgList = optionParser.parse_args(arg.split()) # Must find the remaining args in the original argument list, but # mustn't include the command itself #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command: # newArgList = newArgList[1:] <|code_end|> , generate the next line using the imports in this file: import sys import optparse import pyparsing from optparse import OptionParser, make_option from OpenTrader.deps.cmd2plus import remaining_args, ParsedString and context (functions, classes, or occasionally code) from other files: # Path: OpenTrader/deps/cmd2plus.py # def remaining_args(oldArgs, newArgList): # ''' # Preserves the spacing originally in the argument after # the removal of options. # # >>> remaining_args('-f bar bar cow', ['bar', 'cow']) # 'bar cow' # ''' # pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' # matchObj = re.search(pattern, oldArgs) # return oldArgs[matchObj.start():] # # class ParsedString(str): # def full_parsed_statement(self): # new = ParsedString('%s %s' % (self.parsed.command, self.parsed.args)) # new.parsed = self.parsed # new.parser = self.parser # return new # def with_args_replaced(self, newargs): # new = ParsedString(newargs) # new.parsed = self.parsed # new.parser = self.parser # new.parsed['args'] = newargs # new.parsed.statement['args'] = newargs # return new . Output only the next line.
newArgs = remaining_args(arg, newArgList)
Based on the snippet: <|code_start|> optionParser._func = func def oUpdateOptionParser(instance): if func.__name__.startswith('do_'): sName = func.__name__[3:] if hasattr(instance, 'oConfig') and sName in instance.oConfig: oConfigSection = instance.oConfig[sName] # iterate over optionParser for sKey, gVal in oConfigSection.iteritems(): sOption = '--' +sKey if optionParser.has_option(sOption): oOption = optionParser.get_option(sOption) # FixMe: only if the default is optparse.NO_DEFAULT? if oOption.default is optparse.NO_DEFAULT: # FixMe: does this set the default? oOption.default = gVal # FixMe: how about this? optionParser.defaults[oOption.dest] = oOption.default return optionParser def new_func(instance, arg): try: # makebe return a list and prepend it optionParser = oUpdateOptionParser(instance) opts, newArgList = optionParser.parse_args(arg.split()) # Must find the remaining args in the original argument list, but # mustn't include the command itself #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command: # newArgList = newArgList[1:] newArgs = remaining_args(arg, newArgList) <|code_end|> , predict the immediate next line with the help of imports: import sys import optparse import pyparsing from optparse import OptionParser, make_option from OpenTrader.deps.cmd2plus import remaining_args, ParsedString and context (classes, functions, sometimes code) from other files: # Path: OpenTrader/deps/cmd2plus.py # def remaining_args(oldArgs, newArgList): # ''' # Preserves the spacing originally in the argument after # the removal of options. # # >>> remaining_args('-f bar bar cow', ['bar', 'cow']) # 'bar cow' # ''' # pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' # matchObj = re.search(pattern, oldArgs) # return oldArgs[matchObj.start():] # # class ParsedString(str): # def full_parsed_statement(self): # new = ParsedString('%s %s' % (self.parsed.command, self.parsed.args)) # new.parsed = self.parsed # new.parser = self.parser # return new # def with_args_replaced(self, newargs): # new = ParsedString(newargs) # new.parsed = self.parsed # new.parser = self.parser # new.parsed['args'] = newargs # new.parsed.statement['args'] = newargs # return new . Output only the next line.
if isinstance(arg, ParsedString):
Given snippet: <|code_start|># -*-mode: python; py-indent-offset: 4; indent-tabs-mode: nil; encoding: utf-8-dos; coding: utf-8 -*- """Download, resample and convert CSV files into pandas: {{{ csv url PAIRSYMBOL - show a URL where you can download 1 minute Mt HST data csv resample SRAW1MINFILE, SRESAMPLEDCSV, STIMEFRAME - Resample 1 minute CSV data, to a new timeframe and save it as CSV file }}} """ SDOC = __doc__ LOPTIONS = [] LCOMMANDS = [] <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os from optparse import make_option from OpenTrader.doer import Doer from PandasMt4 import vResample1Min and context: # Path: OpenTrader/doer.py # class Doer(PLogMixin): # """The Doer class has one main method: bexecute # which will execute the options and args given to it # in the do_instance method of the Cmd2 instance. # # It encapsulkates everything tthat is needed to do a # command in the Cmd2 instance. # """ # # def __init__(self, ocmd2, sprefix): # self.ocmd2 = ocmd2 # self.poutput = self.ocmd2.poutput # self.pfeedback = self.ocmd2.pfeedback # self.sprefix = sprefix # # def G(self, gVal=None): # if gVal is not None: # self.ocmd2._G = gVal # self._G = self.ocmd2._G # return self.ocmd2._G # # def vassert_args(self, lArgs, lcommands, imin=1): # assert len(lArgs) >= imin, \ # "ERROR: argument required, one of: " +str(lcommands) # sDo = lArgs[0] # assert sDo in lcommands + ['help'], \ # "ERROR: " +sDo +" choose one of: " +str(lcommands) # # def bis_help(self, lArgs): # sDo = lArgs[0] # # e.g. make help # if sDo != 'help': # return False # if not hasattr(self, 'lCommands'): # lCommands = [] # for sElt in dir(self): # if not sElt.startswith(self.sprefix): continue # sKey = sElt[len(self.sprefix)+1:] # lCommands.append(sKey) # self.lCommands = lCommands # if len(lArgs) == 1: # self.poutput(self.dhelp['']) # # N.B.: subcommands by convention are documented in the module docstring # self.poutput("For help on subcommands type: " +self.sprefix +" help <sub> ") # self.poutput("For help on options type: help " +self.sprefix) # return True # # e.g. make help features # smeth = lArgs[1] # smethod = self.sprefix +'_' + smeth # # FixMe: make a wrapper so this isnt needed? # if smeth not in self.dhelp and hasattr(self, smethod): # omethod = getattr(self, smethod) # if hasattr(omethod, '__doc__'): # self.dhelp[smeth] = omethod.__doc__ # if smeth in self.dhelp: # self.poutput(self.dhelp[smeth]) # self.poutput("For help on options type: help " +self.sprefix) # return True # raise NotImplementedError("Unknown help command for " +sDo +": " \ # +smeth +' not in ' +repr(self.lCommands)) # # def bexecute(self, loptions, dkw): # raise NotImplementedError(self.__class__.__name__) # # def vInfo(self, sMsg): # self.poutput("INFO: " +sMsg) # # def vWarn(self, sMsg): # self.poutput("WARN: " +sMsg) # # def vError(self, sMsg): # self.poutput("ERROR: " +sMsg) which might include code, classes, or functions. Output only the next line.
class DoCsv(Doer):
Based on the snippet: <|code_start|> sOut = "" if hasattr(oCtx, 'stdout_capture'): sOut = oCtx.stdout_capture.getvalue().strip() iLen = len(sOut) if sOut and iLen > iLEN_STDOUT: sOut = sOut[iLEN_STDOUT:] iLEN_STDOUT = iLen assert 'Traceback (most recent call last):' not in sOut assert not sOut.startswith('ERR') sErr = "" global iLEN_STDERR if hasattr(oCtx, 'stderr_capture'): sErr = oCtx.stderr_capture.getvalue().strip() iLen = len(sErr) if sErr and iLen > iLEN_STDERR: sOut = sOut[iLEN_STDERR:] iLEN_STDERR = iLen assert 'Traceback (most recent call last):' not in sErr assert not sErr.startswith('ERR') return (sOut, sErr,) @step('Create the OTCmd2 instance') def vTestCreated(oCtx): lCmdLine = [] # get command line arguments from oCtx.config.userdata if oCtx.config.userdata: for sKey, gVal in oCtx.config.userdata.items(): # check the argparser instance lCmdLine += ['--'+sKey, gVal] <|code_end|> , predict the immediate next line with the help of imports: import os import sys import pdb import OpenTrader from OpenTrader import OTCmd2 from support import tools and context (classes, functions, sometimes code) from other files: # Path: OpenTrader/OTCmd2.py # class Mt4Timeout(RuntimeError): # class CmdLineApp(Cmd, PLogMixin): # class TestMyAppCase(Cmd2TestCase): # def __init__(self, oConfig, lArgs): # def G(self, gVal=None): # def vConfigOp(self, lArgs, dConfig): # def eSendOnSpeaker(self, sChartId, sMsgType, sMsg): # def eSendMessage(self, sMsgType, sChartId, sMark, *lArgs): # def gWaitForMessage(self, sMsgType, sChartId, sMark, *lArgs): # def do_csv(self, oArgs, oOpts=None): # def do_chart(self, oArgs, oOpts=None): # def do_subscribe(self, oArgs, oOpts=None): # def do_publish(self, oArgs, oOpts=None): # def do_order(self, oArgs, oOpts=None): # def do_backtest(self, oArgs, oOpts=None): # def do_make(self, oArgs, oOpts=None): # def do_rabbit(self, oArgs, oOpts=None): # def vAtexit(self): # def vNullifyLocalhostProxy(sHost): # def oParseOptions(): # def oParseConfig(sConfigFile): # def oMergeConfig(oConfig, oOptions): # def iMain(lCmdLine): . Output only the next line.
oCtx.userdata['oMain'] = OTCmd2.oMain(lCmdLine)
Using the snippet: <|code_start|># -*-mode: python; py-indent-offset: 4; indent-tabs-mode: nil; encoding: utf-8-dos; coding: utf-8 -*- # should these all be of chart ANY """ Manage orders in an OTMql4AQMp enabled Metatrader: {{{ ord list - list the ticket numbers of current orders. ord info iTicket - list the current order information about iTicket. ord trades - list the details of current orders. ord history - list the details of closed orders. ord close iTicket [fPrice iSlippage] - close an order; Without the fPrice and iSlippage it will be a market order. ord buy|sell sSymbol fVolume [fPrice iSlippage] - send an order to open; Without the fPrice and iSlippage it will be a market order. ord stoploss ord trail ord exposure - total exposure of all orders, worst case scenario }}} """ SDOC = __doc__ LOPTIONS = [] LCOMMANDS = [] <|code_end|> , determine the next line of code. You have imports: import sys import os from optparse import make_option from OpenTrader.doer import Doer from OTMql427.SimpleFormat import sMakeMark and context (class names, function names, or code) available: # Path: OpenTrader/doer.py # class Doer(PLogMixin): # """The Doer class has one main method: bexecute # which will execute the options and args given to it # in the do_instance method of the Cmd2 instance. # # It encapsulkates everything tthat is needed to do a # command in the Cmd2 instance. # """ # # def __init__(self, ocmd2, sprefix): # self.ocmd2 = ocmd2 # self.poutput = self.ocmd2.poutput # self.pfeedback = self.ocmd2.pfeedback # self.sprefix = sprefix # # def G(self, gVal=None): # if gVal is not None: # self.ocmd2._G = gVal # self._G = self.ocmd2._G # return self.ocmd2._G # # def vassert_args(self, lArgs, lcommands, imin=1): # assert len(lArgs) >= imin, \ # "ERROR: argument required, one of: " +str(lcommands) # sDo = lArgs[0] # assert sDo in lcommands + ['help'], \ # "ERROR: " +sDo +" choose one of: " +str(lcommands) # # def bis_help(self, lArgs): # sDo = lArgs[0] # # e.g. make help # if sDo != 'help': # return False # if not hasattr(self, 'lCommands'): # lCommands = [] # for sElt in dir(self): # if not sElt.startswith(self.sprefix): continue # sKey = sElt[len(self.sprefix)+1:] # lCommands.append(sKey) # self.lCommands = lCommands # if len(lArgs) == 1: # self.poutput(self.dhelp['']) # # N.B.: subcommands by convention are documented in the module docstring # self.poutput("For help on subcommands type: " +self.sprefix +" help <sub> ") # self.poutput("For help on options type: help " +self.sprefix) # return True # # e.g. make help features # smeth = lArgs[1] # smethod = self.sprefix +'_' + smeth # # FixMe: make a wrapper so this isnt needed? # if smeth not in self.dhelp and hasattr(self, smethod): # omethod = getattr(self, smethod) # if hasattr(omethod, '__doc__'): # self.dhelp[smeth] = omethod.__doc__ # if smeth in self.dhelp: # self.poutput(self.dhelp[smeth]) # self.poutput("For help on options type: help " +self.sprefix) # return True # raise NotImplementedError("Unknown help command for " +sDo +": " \ # +smeth +' not in ' +repr(self.lCommands)) # # def bexecute(self, loptions, dkw): # raise NotImplementedError(self.__class__.__name__) # # def vInfo(self, sMsg): # self.poutput("INFO: " +sMsg) # # def vWarn(self, sMsg): # self.poutput("WARN: " +sMsg) # # def vError(self, sMsg): # self.poutput("ERROR: " +sMsg) . Output only the next line.
class DoOrder(Doer):
Given snippet: <|code_start|> def __init__(self, sHdfStore="", oFd=sys.stdout): self.oHdfStore = None self.oFd = oFd if sHdfStore: # ugly - active self.oHdfStore = pandas.HDFStore(sHdfStore, mode='w') self.oFd.write("INFO: hdf store" +self.oHdfStore.filename +'\n') self.oRecipe = None self.oChefModule = None def oAddHdfStore(self, sHdfStore): if os.path.isabs(sHdfStore): assert os.path.isdir(os.path.dirname(sHdfStore)), \ "ERROR: directory not found: " +sHdfStore self.oHdfStore = pandas.HDFStore(sHdfStore, mode='w') self.oFd.write("INFO: hdf store: " +self.oHdfStore.filename +'\n') return self.oHdfStore def oRestore(self, sHdfStore): assert os.path.exists(sHdfStore) # FixMe: self.oHdfStore = None return self.oHdfStore # Is this an Omlette method? its generic and the use of self is tangential # It is because it adds components to the HDF fuke, which is the omlette. def dGetFeedFrame(self, sCsvFile, sTimeFrame, sSymbol, sYear): dFeedParams = OrderedDict(sTimeFrame=sTimeFrame, sSymbol=sSymbol, sYear=sYear) # PandasMt4.dDF_OHLC[sKey = sSymbol + sTimeFrame + sYear] <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os import pandas from collections import OrderedDict from OpenTrader.PandasMt4 import oReadMt4Csv and context: # Path: OpenTrader/PandasMt4.py # def oReadMt4Csv(sResampledCsv, sTimeFrame, sSymbol, sYear=""): # global dDF_OHLC # sKey = sSymbol + sTimeFrame + sYear # if sKey not in dDF_OHLC: # print "INFO: reading " + sResampledCsv # dDF_OHLC[sKey] = pandas.read_csv(sResampledCsv, # names=['T', 'O', 'H', 'L', 'C'], # parse_dates={'timestamp': ['T']}, # index_col='timestamp', # dtype={'O': 'float64', # 'H': 'float64', # 'L': 'float64', # 'C': 'float64'}) # return dDF_OHLC[sKey] which might include code, classes, or functions. Output only the next line.
dFeedParams['mFeedOhlc'] = oReadMt4Csv(sCsvFile, **dFeedParams)
Using the snippet: <|code_start|> sub show TOPIC - start seeing TOPIC messages (e.g. tick - not a pattern) sub pprint ?0|1 - seeing TOPIC messages with pretty-printing, with 0 - off, 1 - on, no argument - current value sub thread info - info on the thread listening for messages. sub thread stop - stop a thread listening for messages. sub thread enumerate - enumerate all threads }}} Common RabbitMQ topic patterns are: * {{{#}}} for all messages, * {{{tick.#}}} for ticks, * {{{timer.#}}} for timer events, * {{{retval.#}}} for return values. You can choose as specific chart with syntax like: {{{ tick.oChart.EURGBP.240.93ACD6A2.# }}} The RabbitMQ host and login information is set in the {{{[RabbitMQ]}}} section of the {{{OTCmd2.ini}}} file; see the {{{-c/--config}}} command-line options. """ SDOC = __doc__ LOPTIONS = [] LCOMMANDS = [] <|code_end|> , determine the next line of code. You have imports: import sys import os import threading import traceback import OpenTrader.PikaListenerThread as ListenerThread import OpenTrader.ZmqListenerThread as ListenerThread import zmq from optparse import make_option from OpenTrader.doer import Doer from pika import exceptions and context (class names, function names, or code) available: # Path: OpenTrader/doer.py # class Doer(PLogMixin): # """The Doer class has one main method: bexecute # which will execute the options and args given to it # in the do_instance method of the Cmd2 instance. # # It encapsulkates everything tthat is needed to do a # command in the Cmd2 instance. # """ # # def __init__(self, ocmd2, sprefix): # self.ocmd2 = ocmd2 # self.poutput = self.ocmd2.poutput # self.pfeedback = self.ocmd2.pfeedback # self.sprefix = sprefix # # def G(self, gVal=None): # if gVal is not None: # self.ocmd2._G = gVal # self._G = self.ocmd2._G # return self.ocmd2._G # # def vassert_args(self, lArgs, lcommands, imin=1): # assert len(lArgs) >= imin, \ # "ERROR: argument required, one of: " +str(lcommands) # sDo = lArgs[0] # assert sDo in lcommands + ['help'], \ # "ERROR: " +sDo +" choose one of: " +str(lcommands) # # def bis_help(self, lArgs): # sDo = lArgs[0] # # e.g. make help # if sDo != 'help': # return False # if not hasattr(self, 'lCommands'): # lCommands = [] # for sElt in dir(self): # if not sElt.startswith(self.sprefix): continue # sKey = sElt[len(self.sprefix)+1:] # lCommands.append(sKey) # self.lCommands = lCommands # if len(lArgs) == 1: # self.poutput(self.dhelp['']) # # N.B.: subcommands by convention are documented in the module docstring # self.poutput("For help on subcommands type: " +self.sprefix +" help <sub> ") # self.poutput("For help on options type: help " +self.sprefix) # return True # # e.g. make help features # smeth = lArgs[1] # smethod = self.sprefix +'_' + smeth # # FixMe: make a wrapper so this isnt needed? # if smeth not in self.dhelp and hasattr(self, smethod): # omethod = getattr(self, smethod) # if hasattr(omethod, '__doc__'): # self.dhelp[smeth] = omethod.__doc__ # if smeth in self.dhelp: # self.poutput(self.dhelp[smeth]) # self.poutput("For help on options type: help " +self.sprefix) # return True # raise NotImplementedError("Unknown help command for " +sDo +": " \ # +smeth +' not in ' +repr(self.lCommands)) # # def bexecute(self, loptions, dkw): # raise NotImplementedError(self.__class__.__name__) # # def vInfo(self, sMsg): # self.poutput("INFO: " +sMsg) # # def vWarn(self, sMsg): # self.poutput("WARN: " +sMsg) # # def vError(self, sMsg): # self.poutput("ERROR: " +sMsg) . Output only the next line.
class DoSubscribe(Doer):
Given the following code snippet before the placeholder: <|code_start|> sOldName = oOm.oRecipe.sName else: sOldName = "" oRecipe = oOm.oAddRecipe(sNewRecipe) if sOldName and sOldName != sNewRecipe: #? do we invalidate the current servings if the recipe changed? vClearOven(ocmd2, oValues) return oRecipe def oEnsureChef(ocmd2, oValues, sNewChef=""): oOm = oEnsureOmlette(ocmd2, oValues) if not sNewChef and hasattr(oOm, 'oChefModule') and oOm.oChefModule: return oOm.oChefModule if not sNewChef: # The are set earlier in the call to do_back sNewChef = ocmd2.sChef if hasattr(oOm, 'oChefModule') and oOm.oChefModule and oOm.oChefModule.sChef: sOldName = oOm.oChefModule.sChef else: sOldName = "" oChefModule = oOm.oAddChef(sNewChef) if sOldName and sOldName != sNewChef: #? do we invalidate the current servings if the chef changed? vClearOven(ocmd2, oValues) return oOm.oChefModule def vClearOven(ocmd2, oValues): oOm = oEnsureOmlette(ocmd2, oValues) oOm.oBt = None <|code_end|> , predict the next line using imports from the current file: import sys import os import traceback import glob import yaml import matplotlib import numpy as np import warnings import matplotlib import matplotlib.pylab as pylab from optparse import make_option from pprint import pprint, pformat from OpenTrader.deps import tabview from OpenTrader.OTUtils import sStripCreole, lConfigToList from OpenTrader.doer import Doer from OpenTrader.Omlettes import Omlette from OpenTrader.PandasMt4 import oReadMt4Csv from OpenTrader.PandasMt4 import oReadMt4Csv, oPreprocessOhlc, vResampleFiles from OpenTrader.OTPpnAmgc import vGraphData from OpenTrader.OTBackTest import oPreprocessOhlc from OpenTrader.Omlettes import lKnownRecipes from OpenTrader.Omlettes import lKnownChefs from OpenTrader.OTBackTest import oPyBacktestCook and context including class names, function names, and sometimes code from other files: # Path: OpenTrader/doer.py # class Doer(PLogMixin): # """The Doer class has one main method: bexecute # which will execute the options and args given to it # in the do_instance method of the Cmd2 instance. # # It encapsulkates everything tthat is needed to do a # command in the Cmd2 instance. # """ # # def __init__(self, ocmd2, sprefix): # self.ocmd2 = ocmd2 # self.poutput = self.ocmd2.poutput # self.pfeedback = self.ocmd2.pfeedback # self.sprefix = sprefix # # def G(self, gVal=None): # if gVal is not None: # self.ocmd2._G = gVal # self._G = self.ocmd2._G # return self.ocmd2._G # # def vassert_args(self, lArgs, lcommands, imin=1): # assert len(lArgs) >= imin, \ # "ERROR: argument required, one of: " +str(lcommands) # sDo = lArgs[0] # assert sDo in lcommands + ['help'], \ # "ERROR: " +sDo +" choose one of: " +str(lcommands) # # def bis_help(self, lArgs): # sDo = lArgs[0] # # e.g. make help # if sDo != 'help': # return False # if not hasattr(self, 'lCommands'): # lCommands = [] # for sElt in dir(self): # if not sElt.startswith(self.sprefix): continue # sKey = sElt[len(self.sprefix)+1:] # lCommands.append(sKey) # self.lCommands = lCommands # if len(lArgs) == 1: # self.poutput(self.dhelp['']) # # N.B.: subcommands by convention are documented in the module docstring # self.poutput("For help on subcommands type: " +self.sprefix +" help <sub> ") # self.poutput("For help on options type: help " +self.sprefix) # return True # # e.g. make help features # smeth = lArgs[1] # smethod = self.sprefix +'_' + smeth # # FixMe: make a wrapper so this isnt needed? # if smeth not in self.dhelp and hasattr(self, smethod): # omethod = getattr(self, smethod) # if hasattr(omethod, '__doc__'): # self.dhelp[smeth] = omethod.__doc__ # if smeth in self.dhelp: # self.poutput(self.dhelp[smeth]) # self.poutput("For help on options type: help " +self.sprefix) # return True # raise NotImplementedError("Unknown help command for " +sDo +": " \ # +smeth +' not in ' +repr(self.lCommands)) # # def bexecute(self, loptions, dkw): # raise NotImplementedError(self.__class__.__name__) # # def vInfo(self, sMsg): # self.poutput("INFO: " +sMsg) # # def vWarn(self, sMsg): # self.poutput("WARN: " +sMsg) # # def vError(self, sMsg): # self.poutput("ERROR: " +sMsg) . Output only the next line.
class DoBacktest(Doer):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2003, Taro Ogawa. All Rights Reserved. # Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA from __future__ import division, print_function, unicode_literals GENERIC_DOLLARS = ('dolar', 'dólares') GENERIC_CENTS = ('centavo', 'centavos') CURRENCIES_UNA = ('SLL', 'SEK', 'NOK', 'CZK', 'DKK', 'ISK', 'SKK', 'GBP', 'CYP', 'EGP', 'FKP', 'GIP', 'LBP', 'SDG', 'SHP', 'SSP', 'SYP', 'INR', 'IDR', 'LKR', 'MUR', 'NPR', 'PKR', 'SCR', 'ESP') <|code_end|> with the help of current file imports: import math from .lang_EU import Num2Word_EU and context from other files: # Path: num2words/lang_EU.py # class Num2Word_EU(Num2Word_Base): # CURRENCY_FORMS = { # 'AUD': (GENERIC_DOLLARS, GENERIC_CENTS), # 'CAD': (GENERIC_DOLLARS, GENERIC_CENTS), # # repalced by EUR # 'EEK': (('kroon', 'kroons'), ('sent', 'senti')), # 'EUR': (('euro', 'euro'), GENERIC_CENTS), # 'GBP': (('pound sterling', 'pounds sterling'), ('penny', 'pence')), # # replaced by EUR # 'LTL': (('litas', 'litas'), GENERIC_CENTS), # # replaced by EUR # 'LVL': (('lat', 'lats'), ('santim', 'santims')), # 'USD': (GENERIC_DOLLARS, GENERIC_CENTS), # 'RUB': (('rouble', 'roubles'), ('kopek', 'kopeks')), # 'SEK': (('krona', 'kronor'), ('öre', 'öre')), # 'NOK': (('krone', 'kroner'), ('øre', 'øre')), # 'PLN': (('zloty', 'zlotys', 'zlotu'), ('grosz', 'groszy')), # 'MXN': (('peso', 'pesos'), GENERIC_CENTS), # 'RON': (('leu', 'lei', 'de lei'), ('ban', 'bani', 'de bani')), # 'INR': (('rupee', 'rupees'), ('paisa', 'paise')), # 'HUF': (('forint', 'forint'), ('fillér', 'fillér')) # } # # CURRENCY_ADJECTIVES = { # 'AUD': 'Australian', # 'CAD': 'Canadian', # 'EEK': 'Estonian', # 'USD': 'US', # 'RUB': 'Russian', # 'NOK': 'Norwegian', # 'MXN': 'Mexican', # 'RON': 'Romanian', # 'INR': 'Indian', # 'HUF': 'Hungarian' # } # # GIGA_SUFFIX = "illiard" # MEGA_SUFFIX = "illion" # # def set_high_numwords(self, high): # cap = 3 + 6 * len(high) # # for word, n in zip(high, range(cap, 3, -6)): # if self.GIGA_SUFFIX: # self.cards[10 ** n] = word + self.GIGA_SUFFIX # # if self.MEGA_SUFFIX: # self.cards[10 ** (n - 3)] = word + self.MEGA_SUFFIX # # def gen_high_numwords(self, units, tens, lows): # out = [u + t for t in tens for u in units] # out.reverse() # return out + lows # # def pluralize(self, n, forms): # form = 0 if n == 1 else 1 # return forms[form] # # def setup(self): # lows = ["non", "oct", "sept", "sext", "quint", "quadr", "tr", "b", "m"] # units = ["", "un", "duo", "tre", "quattuor", "quin", "sex", "sept", # "octo", "novem"] # tens = ["dec", "vigint", "trigint", "quadragint", "quinquagint", # "sexagint", "septuagint", "octogint", "nonagint"] # self.high_numwords = ["cent"] + self.gen_high_numwords(units, tens, # lows) , which may contain function names, class names, or code. Output only the next line.
class Num2Word_ES(Num2Word_EU):
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (c) 2003, Taro Ogawa. All Rights Reserved. # Copyright (c) 2013, Savoir-faire Linux inc. All Rights Reserved. # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA from __future__ import division, unicode_literals DOLLAR = ('dólar', 'dólares') CENTS = ('cêntimo', 'cêntimos') <|code_end|> , determine the next line of code. You have imports: import re from .lang_EU import Num2Word_EU and context (class names, function names, or code) available: # Path: num2words/lang_EU.py # class Num2Word_EU(Num2Word_Base): # CURRENCY_FORMS = { # 'AUD': (GENERIC_DOLLARS, GENERIC_CENTS), # 'CAD': (GENERIC_DOLLARS, GENERIC_CENTS), # # repalced by EUR # 'EEK': (('kroon', 'kroons'), ('sent', 'senti')), # 'EUR': (('euro', 'euro'), GENERIC_CENTS), # 'GBP': (('pound sterling', 'pounds sterling'), ('penny', 'pence')), # # replaced by EUR # 'LTL': (('litas', 'litas'), GENERIC_CENTS), # # replaced by EUR # 'LVL': (('lat', 'lats'), ('santim', 'santims')), # 'USD': (GENERIC_DOLLARS, GENERIC_CENTS), # 'RUB': (('rouble', 'roubles'), ('kopek', 'kopeks')), # 'SEK': (('krona', 'kronor'), ('öre', 'öre')), # 'NOK': (('krone', 'kroner'), ('øre', 'øre')), # 'PLN': (('zloty', 'zlotys', 'zlotu'), ('grosz', 'groszy')), # 'MXN': (('peso', 'pesos'), GENERIC_CENTS), # 'RON': (('leu', 'lei', 'de lei'), ('ban', 'bani', 'de bani')), # 'INR': (('rupee', 'rupees'), ('paisa', 'paise')), # 'HUF': (('forint', 'forint'), ('fillér', 'fillér')) # } # # CURRENCY_ADJECTIVES = { # 'AUD': 'Australian', # 'CAD': 'Canadian', # 'EEK': 'Estonian', # 'USD': 'US', # 'RUB': 'Russian', # 'NOK': 'Norwegian', # 'MXN': 'Mexican', # 'RON': 'Romanian', # 'INR': 'Indian', # 'HUF': 'Hungarian' # } # # GIGA_SUFFIX = "illiard" # MEGA_SUFFIX = "illion" # # def set_high_numwords(self, high): # cap = 3 + 6 * len(high) # # for word, n in zip(high, range(cap, 3, -6)): # if self.GIGA_SUFFIX: # self.cards[10 ** n] = word + self.GIGA_SUFFIX # # if self.MEGA_SUFFIX: # self.cards[10 ** (n - 3)] = word + self.MEGA_SUFFIX # # def gen_high_numwords(self, units, tens, lows): # out = [u + t for t in tens for u in units] # out.reverse() # return out + lows # # def pluralize(self, n, forms): # form = 0 if n == 1 else 1 # return forms[form] # # def setup(self): # lows = ["non", "oct", "sept", "sext", "quint", "quadr", "tr", "b", "m"] # units = ["", "un", "duo", "tre", "quattuor", "quin", "sex", "sept", # "octo", "novem"] # tens = ["dec", "vigint", "trigint", "quadragint", "quinquagint", # "sexagint", "septuagint", "octogint", "nonagint"] # self.high_numwords = ["cent"] + self.gen_high_numwords(units, tens, # lows) . Output only the next line.
class Num2Word_PT(Num2Word_EU):
Using the snippet: <|code_start|> post = abs(value - pre) * 10**self.precision if abs(round(post) - post) < 0.01: # We generally floor all values beyond our precision (rather than # rounding), but in cases where we have something like 1.239999999, # which is probably due to python's handling of floats, we actually # want to consider it as 1.24 instead of 1.23 post = int(round(post)) else: post = int(math.floor(post)) return pre, post def to_cardinal_float(self, value): try: float(value) == value except (ValueError, TypeError, AssertionError, AttributeError): raise TypeError(self.errmsg_nonnum % value) pre, post = self.float2tuple(float(value)) post = str(post) post = '0' * (self.precision - len(post)) + post out = [self.to_cardinal(pre)] if self.precision: out.append(self.title(self.pointword)) for i in range(self.precision): curr = int(post[i]) <|code_end|> , determine the next line of code. You have imports: import math from collections import OrderedDict from decimal import Decimal from .compat import to_s from .currency import parse_currency_parts, prefix_currency and context (class names, function names, or code) available: # Path: num2words/compat.py # def to_s(val): # try: # return unicode(val) # except NameError: # return str(val) # # Path: num2words/currency.py # def parse_currency_parts(value, is_int_with_cents=True): # if isinstance(value, int): # if is_int_with_cents: # # assume cents if value is integer # negative = value < 0 # value = abs(value) # integer, cents = divmod(value, 100) # else: # negative = value < 0 # integer, cents = abs(value), 0 # # else: # value = Decimal(value) # value = value.quantize( # Decimal('.01'), # rounding=ROUND_HALF_UP # ) # negative = value < 0 # value = abs(value) # integer, fraction = divmod(value, 1) # integer = int(integer) # cents = int(fraction * 100) # # return integer, cents, negative # # def prefix_currency(prefix, base): # return tuple("%s %s" % (prefix, i) for i in base) . Output only the next line.
out.append(to_s(self.to_cardinal(curr)))
Given the following code snippet before the placeholder: <|code_start|> def pluralize(self, n, forms): """ Should resolve gettext form: http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html """ raise NotImplementedError def _money_verbose(self, number, currency): return self.to_cardinal(number) def _cents_verbose(self, number, currency): return self.to_cardinal(number) def _cents_terse(self, number, currency): return "%02d" % number def to_currency(self, val, currency='EUR', cents=True, separator=',', adjective=False): """ Args: val: Numeric value currency (str): Currency code cents (bool): Verbose cents separator (str): Cent separator adjective (bool): Prefix currency name with adjective Returns: str: Formatted string """ <|code_end|> , predict the next line using imports from the current file: import math from collections import OrderedDict from decimal import Decimal from .compat import to_s from .currency import parse_currency_parts, prefix_currency and context including class names, function names, and sometimes code from other files: # Path: num2words/compat.py # def to_s(val): # try: # return unicode(val) # except NameError: # return str(val) # # Path: num2words/currency.py # def parse_currency_parts(value, is_int_with_cents=True): # if isinstance(value, int): # if is_int_with_cents: # # assume cents if value is integer # negative = value < 0 # value = abs(value) # integer, cents = divmod(value, 100) # else: # negative = value < 0 # integer, cents = abs(value), 0 # # else: # value = Decimal(value) # value = value.quantize( # Decimal('.01'), # rounding=ROUND_HALF_UP # ) # negative = value < 0 # value = abs(value) # integer, fraction = divmod(value, 1) # integer = int(integer) # cents = int(fraction * 100) # # return integer, cents, negative # # def prefix_currency(prefix, base): # return tuple("%s %s" % (prefix, i) for i in base) . Output only the next line.
left, right, is_negative = parse_currency_parts(val)
Given snippet: <|code_start|> def _cents_verbose(self, number, currency): return self.to_cardinal(number) def _cents_terse(self, number, currency): return "%02d" % number def to_currency(self, val, currency='EUR', cents=True, separator=',', adjective=False): """ Args: val: Numeric value currency (str): Currency code cents (bool): Verbose cents separator (str): Cent separator adjective (bool): Prefix currency name with adjective Returns: str: Formatted string """ left, right, is_negative = parse_currency_parts(val) try: cr1, cr2 = self.CURRENCY_FORMS[currency] except KeyError: raise NotImplementedError( 'Currency code "%s" not implemented for "%s"' % (currency, self.__class__.__name__)) if adjective and currency in self.CURRENCY_ADJECTIVES: <|code_end|> , continue by predicting the next line. Consider current file imports: import math from collections import OrderedDict from decimal import Decimal from .compat import to_s from .currency import parse_currency_parts, prefix_currency and context: # Path: num2words/compat.py # def to_s(val): # try: # return unicode(val) # except NameError: # return str(val) # # Path: num2words/currency.py # def parse_currency_parts(value, is_int_with_cents=True): # if isinstance(value, int): # if is_int_with_cents: # # assume cents if value is integer # negative = value < 0 # value = abs(value) # integer, cents = divmod(value, 100) # else: # negative = value < 0 # integer, cents = abs(value), 0 # # else: # value = Decimal(value) # value = value.quantize( # Decimal('.01'), # rounding=ROUND_HALF_UP # ) # negative = value < 0 # value = abs(value) # integer, fraction = divmod(value, 1) # integer = int(integer) # cents = int(fraction * 100) # # return integer, cents, negative # # def prefix_currency(prefix, base): # return tuple("%s %s" % (prefix, i) for i in base) which might include code, classes, or functions. Output only the next line.
cr1 = prefix_currency(self.CURRENCY_ADJECTIVES[currency], cr1)
Given the code snippet: <|code_start|> def __init__(self, *args, **kwargs): super(SparkSGDClassifier, self).__init__(*args, **kwargs) self.average = True # force averaging # workaround to keep the classes parameter unchanged @property def classes_(self): return self._classes_ @classes_.setter def classes_(self, value): pass def fit(self, Z, classes=None): """Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Returns ------- self : object Returns self. """ <|code_end|> , generate the next line using the imports in this file: import numpy as np import scipy.sparse as sp from sklearn.linear_model import SGDClassifier from ..utils.validation import check_rdd from .base import SparkLinearModelMixin and context (functions, classes, or occasionally code) from other files: # Path: splearn/utils/validation.py # def check_rdd(rdd, expected_dtype): # """Wrapper function to check_rdd_dtype. Raises TypeError in case of dtype # mismatch. # # Parameters: # ----------- # rdd: splearn.BlockRDD # The RDD to check # expected_dtype: {type, list of types, tuple of types, dict of types} # Expected type(s). If the RDD is a DictRDD the parameter type is # restricted to dict. # """ # if not check_rdd_dtype(rdd, expected_dtype): # raise TypeError("{0} dtype mismatch.".format(rdd)) # # Path: splearn/linear_model/base.py # class SparkLinearModelMixin(object): # # def __add__(self, other): # """Add method for Linear models with coef and intercept attributes. # # Parameters # ---------- # other : fitted sklearn linear model # Model to add. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # model = copy.deepcopy(self) # model.coef_ += other.coef_ # model.intercept_ += other.intercept_ # return model # # def __radd__(self, other): # """Reverse add method for Linear models. # # Parameters # ---------- # other : fitted sklearn linear model # Model to add. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # return self if other == 0 else self.__add__(other) # # def __div__(self, other): # """Division method for Linear models. Used for averaging. # # Parameters # ---------- # other : integer # Integer to divide with. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # self.coef_ /= other # self.intercept_ /= other # return self # # __truediv__ = __div__ # # def _spark_fit(self, cls, Z, *args, **kwargs): # """Wraps a Scikit-learn Linear model's fit method to use with RDD # input. # # Parameters # ---------- # cls : class object # The sklearn linear model's class to wrap. # Z : TupleRDD or DictRDD # The distributed train data in a DictRDD. # # Returns # ------- # self: the wrapped class # """ # mapper = lambda X_y: super(cls, self).fit( # X_y[0], X_y[1], *args, **kwargs # ) # models = Z.map(mapper) # avg = models.reduce(operator.add) / models.count() # self.__dict__.update(avg.__dict__) # return self # # def _spark_predict(self, cls, X, *args, **kwargs): # """Wraps a Scikit-learn Linear model's predict method to use with RDD # input. # # Parameters # ---------- # cls : class object # The sklearn linear model's class to wrap. # Z : ArrayRDD # The distributed data to predict in a DictRDD. # # Returns # ------- # self: the wrapped class # """ # return X.map(lambda X: super(cls, self).predict(X, *args, **kwargs)) # # def _to_scikit(self, cls): # new = cls() # new.__dict__ = self.__dict__ # return new . Output only the next line.
check_rdd(Z, {'X': (sp.spmatrix, np.ndarray)})
Using the snippet: <|code_start|> class TestSparkLabelEncoder(SplearnTestCase): def test_same_fit_transform(self): Y, Y_rdd = self.make_dense_randint_rdd(low=0, high=10, shape=(1000,)) local = LabelEncoder() <|code_end|> , determine the next line of code. You have imports: from sklearn.preprocessing import LabelEncoder from splearn.preprocessing import SparkLabelEncoder from splearn.utils.testing import SplearnTestCase, assert_array_equal and context (class names, function names, or code) available: # Path: splearn/preprocessing/label.py # class SparkLabelEncoder(LabelEncoder, SparkTransformerMixin, # SparkBroadcasterMixin): # # """Encode labels with value between 0 and n_classes-1. # Read more in the :ref:`User Guide <preprocessing_targets>`. # Attributes # ---------- # classes_ : array of shape (n_class,) # Holds the label for each class. # Examples # -------- # `SparkLabelEncoder` can be used to normalize labels. # >>> from splearn.preprocessing import SparkLabelEncoder # >>> from splearn import BlockRDD # >>> # >>> data = ["paris", "paris", "tokyo", "amsterdam"] # >>> y = BlockRDD(sc.parallelize(data)) # >>> # >>> le = SparkLabelEncoder() # >>> le.fit(y) # >>> le.classes_ # array(['amsterdam', 'paris', 'tokyo'], # dtype='|S9') # >>> # >>> test = ["tokyo", "tokyo", "paris"] # >>> y_test = BlockRDD(sc.parallelize(test)) # >>> # >>> le.transform(y_test).toarray() # array([2, 2, 1]) # >>> # >>> test = [2, 2, 1] # >>> y_test = BlockRDD(sc.parallelize(test)) # >>> # >>> le.inverse_transform(y_test).toarray() # array(['tokyo', 'tokyo', 'paris'], # dtype='|S9') # """ # # __transient__ = ['classes_'] # # def fit(self, y): # """Fit label encoder # Parameters # ---------- # y : ArrayRDD (n_samples,) # Target values. # Returns # ------- # self : returns an instance of self. # """ # # def mapper(y): # y = column_or_1d(y, warn=True) # _check_numpy_unicode_bug(y) # return np.unique(y) # # def reducer(a, b): # return np.unique(np.concatenate((a, b))) # # self.classes_ = y.map(mapper).reduce(reducer) # # return self # # def fit_transform(self, y): # """Fit label encoder and return encoded labels # Parameters # ---------- # y : ArrayRDD [n_samples] # Target values. # Returns # ------- # y : ArrayRDD [n_samples] # """ # return self.fit(y).transform(y) # # def transform(self, y): # """Transform labels to normalized encoding. # Parameters # ---------- # y : ArrayRDD [n_samples] # Target values. # Returns # ------- # y : ArrayRDD [n_samples] # """ # mapper = super(SparkLabelEncoder, self).transform # mapper = self.broadcast(mapper, y.context) # return y.transform(mapper) # # def inverse_transform(self, y): # """Transform labels back to original encoding. # Parameters # ---------- # y : numpy array of shape [n_samples] # Target values. # Returns # ------- # y : ArrayRDD [n_samples] # """ # mapper = super(SparkLabelEncoder, self).inverse_transform # mapper = self.broadcast(mapper, y.context) # return y.transform(mapper) # # Path: splearn/utils/testing.py # def assert_tuple_equal(tpl1, tpl2): # def assert_multiple_tuples_equal(tpls1, tpls2): # def setUp(self): # def tearDown(self): # def make_blobs(self, centers, n_samples, blocks=-1): # def make_regression(self, n_targets, n_samples, blocks=-1): # def make_classification(self, n_classes, n_samples, blocks=-1, # nonnegative=False): # def make_text_rdd(self, blocks=-1): # def make_dense_rdd(self, shape=(1e3, 10), block_size=-1): # def make_dense_randint_rdd(self, low, high=None, shape=(1e3, 10), # block_size=-1): # def make_dense_range_rdd(self, shape=(1e3, 10), block_size=-1): # def make_sparse_rdd(self, shape=(1e3, 10), block_size=-1): # class SplearnTestCase(unittest.TestCase): # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = np.abs(X) # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = ALL_FOOD_DOCS # X = rng.randn(*shape) # X = np.random.randint(low, high, size=shape) # X = np.arange(np.prod(shape)).reshape(shape) # X = sp.rand(shape[0], shape[1], random_state=42, density=0.3) . Output only the next line.
dist = SparkLabelEncoder()
Predict the next line for this snippet: <|code_start|> class TestSparkLabelEncoder(SplearnTestCase): def test_same_fit_transform(self): Y, Y_rdd = self.make_dense_randint_rdd(low=0, high=10, shape=(1000,)) local = LabelEncoder() dist = SparkLabelEncoder() <|code_end|> with the help of current file imports: from sklearn.preprocessing import LabelEncoder from splearn.preprocessing import SparkLabelEncoder from splearn.utils.testing import SplearnTestCase, assert_array_equal and context from other files: # Path: splearn/preprocessing/label.py # class SparkLabelEncoder(LabelEncoder, SparkTransformerMixin, # SparkBroadcasterMixin): # # """Encode labels with value between 0 and n_classes-1. # Read more in the :ref:`User Guide <preprocessing_targets>`. # Attributes # ---------- # classes_ : array of shape (n_class,) # Holds the label for each class. # Examples # -------- # `SparkLabelEncoder` can be used to normalize labels. # >>> from splearn.preprocessing import SparkLabelEncoder # >>> from splearn import BlockRDD # >>> # >>> data = ["paris", "paris", "tokyo", "amsterdam"] # >>> y = BlockRDD(sc.parallelize(data)) # >>> # >>> le = SparkLabelEncoder() # >>> le.fit(y) # >>> le.classes_ # array(['amsterdam', 'paris', 'tokyo'], # dtype='|S9') # >>> # >>> test = ["tokyo", "tokyo", "paris"] # >>> y_test = BlockRDD(sc.parallelize(test)) # >>> # >>> le.transform(y_test).toarray() # array([2, 2, 1]) # >>> # >>> test = [2, 2, 1] # >>> y_test = BlockRDD(sc.parallelize(test)) # >>> # >>> le.inverse_transform(y_test).toarray() # array(['tokyo', 'tokyo', 'paris'], # dtype='|S9') # """ # # __transient__ = ['classes_'] # # def fit(self, y): # """Fit label encoder # Parameters # ---------- # y : ArrayRDD (n_samples,) # Target values. # Returns # ------- # self : returns an instance of self. # """ # # def mapper(y): # y = column_or_1d(y, warn=True) # _check_numpy_unicode_bug(y) # return np.unique(y) # # def reducer(a, b): # return np.unique(np.concatenate((a, b))) # # self.classes_ = y.map(mapper).reduce(reducer) # # return self # # def fit_transform(self, y): # """Fit label encoder and return encoded labels # Parameters # ---------- # y : ArrayRDD [n_samples] # Target values. # Returns # ------- # y : ArrayRDD [n_samples] # """ # return self.fit(y).transform(y) # # def transform(self, y): # """Transform labels to normalized encoding. # Parameters # ---------- # y : ArrayRDD [n_samples] # Target values. # Returns # ------- # y : ArrayRDD [n_samples] # """ # mapper = super(SparkLabelEncoder, self).transform # mapper = self.broadcast(mapper, y.context) # return y.transform(mapper) # # def inverse_transform(self, y): # """Transform labels back to original encoding. # Parameters # ---------- # y : numpy array of shape [n_samples] # Target values. # Returns # ------- # y : ArrayRDD [n_samples] # """ # mapper = super(SparkLabelEncoder, self).inverse_transform # mapper = self.broadcast(mapper, y.context) # return y.transform(mapper) # # Path: splearn/utils/testing.py # def assert_tuple_equal(tpl1, tpl2): # def assert_multiple_tuples_equal(tpls1, tpls2): # def setUp(self): # def tearDown(self): # def make_blobs(self, centers, n_samples, blocks=-1): # def make_regression(self, n_targets, n_samples, blocks=-1): # def make_classification(self, n_classes, n_samples, blocks=-1, # nonnegative=False): # def make_text_rdd(self, blocks=-1): # def make_dense_rdd(self, shape=(1e3, 10), block_size=-1): # def make_dense_randint_rdd(self, low, high=None, shape=(1e3, 10), # block_size=-1): # def make_dense_range_rdd(self, shape=(1e3, 10), block_size=-1): # def make_sparse_rdd(self, shape=(1e3, 10), block_size=-1): # class SplearnTestCase(unittest.TestCase): # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = np.abs(X) # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = ALL_FOOD_DOCS # X = rng.randn(*shape) # X = np.random.randint(low, high, size=shape) # X = np.arange(np.prod(shape)).reshape(shape) # X = sp.rand(shape[0], shape[1], random_state=42, density=0.3) , which may contain function names, class names, or code. Output only the next line.
assert_array_equal(local.fit_transform(Y),
Given the following code snippet before the placeholder: <|code_start|> http://www.csie.ntu.edu.tw/~cjlin/papers/maxent_dual.pdf """ # TODO: REVISIT! # workaround to keep the classes parameter unchanged @property def classes_(self): return self._classes_ @classes_.setter def classes_(self, value): pass def fit(self, Z, classes=None): """Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Returns ------- self : object Returns self. """ <|code_end|> , predict the next line using imports from the current file: import numpy as np import scipy.sparse as sp from sklearn.linear_model import LogisticRegression from ..utils.validation import check_rdd from .base import SparkLinearModelMixin and context including class names, function names, and sometimes code from other files: # Path: splearn/utils/validation.py # def check_rdd(rdd, expected_dtype): # """Wrapper function to check_rdd_dtype. Raises TypeError in case of dtype # mismatch. # # Parameters: # ----------- # rdd: splearn.BlockRDD # The RDD to check # expected_dtype: {type, list of types, tuple of types, dict of types} # Expected type(s). If the RDD is a DictRDD the parameter type is # restricted to dict. # """ # if not check_rdd_dtype(rdd, expected_dtype): # raise TypeError("{0} dtype mismatch.".format(rdd)) # # Path: splearn/linear_model/base.py # class SparkLinearModelMixin(object): # # def __add__(self, other): # """Add method for Linear models with coef and intercept attributes. # # Parameters # ---------- # other : fitted sklearn linear model # Model to add. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # model = copy.deepcopy(self) # model.coef_ += other.coef_ # model.intercept_ += other.intercept_ # return model # # def __radd__(self, other): # """Reverse add method for Linear models. # # Parameters # ---------- # other : fitted sklearn linear model # Model to add. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # return self if other == 0 else self.__add__(other) # # def __div__(self, other): # """Division method for Linear models. Used for averaging. # # Parameters # ---------- # other : integer # Integer to divide with. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # self.coef_ /= other # self.intercept_ /= other # return self # # __truediv__ = __div__ # # def _spark_fit(self, cls, Z, *args, **kwargs): # """Wraps a Scikit-learn Linear model's fit method to use with RDD # input. # # Parameters # ---------- # cls : class object # The sklearn linear model's class to wrap. # Z : TupleRDD or DictRDD # The distributed train data in a DictRDD. # # Returns # ------- # self: the wrapped class # """ # mapper = lambda X_y: super(cls, self).fit( # X_y[0], X_y[1], *args, **kwargs # ) # models = Z.map(mapper) # avg = models.reduce(operator.add) / models.count() # self.__dict__.update(avg.__dict__) # return self # # def _spark_predict(self, cls, X, *args, **kwargs): # """Wraps a Scikit-learn Linear model's predict method to use with RDD # input. # # Parameters # ---------- # cls : class object # The sklearn linear model's class to wrap. # Z : ArrayRDD # The distributed data to predict in a DictRDD. # # Returns # ------- # self: the wrapped class # """ # return X.map(lambda X: super(cls, self).predict(X, *args, **kwargs)) # # def _to_scikit(self, cls): # new = cls() # new.__dict__ = self.__dict__ # return new . Output only the next line.
check_rdd(Z, {'X': (sp.spmatrix, np.ndarray)})
Here is a snippet: <|code_start|> n_jobs : The number of jobs to use for the computation. If -1 all CPUs are used. This will only provide speedup for n_targets > 1 and sufficient large problems. Attributes ---------- coef_ : array, shape (n_features, ) or (n_targets, n_features) Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features. intercept_ : array Independent term in the linear model. """ def fit(self, Z): """ Fit linear model. Parameters ---------- Z : DictRDD with (X, y) values X containing numpy array or sparse matrix - The training data y containing the target values Returns ------- self : returns an instance of self. """ <|code_end|> . Write the next line using the current file imports: import operator import numpy as np import scipy.sparse as sp from sklearn.base import copy from sklearn.linear_model.base import LinearRegression from ..utils.validation import check_rdd and context from other files: # Path: splearn/utils/validation.py # def check_rdd(rdd, expected_dtype): # """Wrapper function to check_rdd_dtype. Raises TypeError in case of dtype # mismatch. # # Parameters: # ----------- # rdd: splearn.BlockRDD # The RDD to check # expected_dtype: {type, list of types, tuple of types, dict of types} # Expected type(s). If the RDD is a DictRDD the parameter type is # restricted to dict. # """ # if not check_rdd_dtype(rdd, expected_dtype): # raise TypeError("{0} dtype mismatch.".format(rdd)) , which may include functions, classes, or code. Output only the next line.
check_rdd(Z, {'X': (sp.spmatrix, np.ndarray)})
Given the code snippet: <|code_start|> class TestLinearRegression(SplearnTestCase): def test_same_coefs(self): X, y, Z = self.make_regression(1, 100000) local = LinearRegression() <|code_end|> , generate the next line using the imports in this file: import numpy as np from sklearn.linear_model import LinearRegression from splearn.linear_model import SparkLinearRegression from splearn.utils.testing import (SplearnTestCase, assert_array_almost_equal, assert_true) from splearn.utils.validation import check_rdd_dtype and context (functions, classes, or occasionally code) from other files: # Path: splearn/linear_model/base.py # class SparkLinearRegression(LinearRegression, SparkLinearModelMixin): # # """Distributed implementation of sklearn's Linear Regression. # # Parameters # ---------- # fit_intercept : boolean, optional # whether to calculate the intercept for this model. If set # to false, no intercept will be used in calculations # (e.g. data is expected to be already centered). # normalize : boolean, optional, default False # If True, the regressors X will be normalized before regression. # copy_X : boolean, optional, default True # If True, X will be copied; else, it may be overwritten. # n_jobs : The number of jobs to use for the computation. # If -1 all CPUs are used. This will only provide speedup for # n_targets > 1 and sufficient large problems. # # Attributes # ---------- # coef_ : array, shape (n_features, ) or (n_targets, n_features) # Estimated coefficients for the linear regression problem. # If multiple targets are passed during the fit (y 2D), this # is a 2D array of shape (n_targets, n_features), while if only # one target is passed, this is a 1D array of length n_features. # intercept_ : array # Independent term in the linear model. # # """ # # def fit(self, Z): # """ # Fit linear model. # # Parameters # ---------- # Z : DictRDD with (X, y) values # X containing numpy array or sparse matrix - The training data # y containing the target values # # Returns # ------- # self : returns an instance of self. # """ # check_rdd(Z, {'X': (sp.spmatrix, np.ndarray)}) # return self._spark_fit(SparkLinearRegression, Z) # # def predict(self, X): # """Distributed method to predict class labels for samples in X. # # Parameters # ---------- # X : ArrayRDD containing {array-like, sparse matrix} # Samples. # # Returns # ------- # C : ArrayRDD # Predicted class label per sample. # """ # check_rdd(X, (sp.spmatrix, np.ndarray)) # return self._spark_predict(SparkLinearRegression, X) # # def to_scikit(self): # return self._to_scikit(LinearRegression) # # Path: splearn/utils/testing.py # def assert_tuple_equal(tpl1, tpl2): # def assert_multiple_tuples_equal(tpls1, tpls2): # def setUp(self): # def tearDown(self): # def make_blobs(self, centers, n_samples, blocks=-1): # def make_regression(self, n_targets, n_samples, blocks=-1): # def make_classification(self, n_classes, n_samples, blocks=-1, # nonnegative=False): # def make_text_rdd(self, blocks=-1): # def make_dense_rdd(self, shape=(1e3, 10), block_size=-1): # def make_dense_randint_rdd(self, low, high=None, shape=(1e3, 10), # block_size=-1): # def make_dense_range_rdd(self, shape=(1e3, 10), block_size=-1): # def make_sparse_rdd(self, shape=(1e3, 10), block_size=-1): # class SplearnTestCase(unittest.TestCase): # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = np.abs(X) # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = ALL_FOOD_DOCS # X = rng.randn(*shape) # X = np.random.randint(low, high, size=shape) # X = np.arange(np.prod(shape)).reshape(shape) # X = sp.rand(shape[0], shape[1], random_state=42, density=0.3) # # Path: splearn/utils/validation.py # def check_rdd_dtype(rdd, expected_dtype): # """Checks if the blocks in the RDD matches the expected types. # # Parameters: # ----------- # rdd: splearn.BlockRDD # The RDD to check # expected_dtype: {type, list of types, tuple of types, dict of types} # Expected type(s). If the RDD is a DictRDD the parameter type is # restricted to dict. # # Returns: # -------- # accept: bool # Returns if the types are matched. # """ # if not isinstance(rdd, BlockRDD): # raise TypeError("Expected {0} for parameter rdd, got {1}." # .format(BlockRDD, type(rdd))) # if isinstance(rdd, DictRDD): # if not isinstance(expected_dtype, dict): # raise TypeError('Expected {0} for parameter ' # 'expected_dtype, got {1}.' # .format(dict, type(expected_dtype))) # accept = True # types = dict(list(zip(rdd.columns, rdd.dtype))) # for key, values in expected_dtype.items(): # if not isinstance(values, (tuple, list)): # values = [values] # accept = accept and types[key] in values # return accept # # if not isinstance(expected_dtype, (tuple, list)): # expected_dtype = [expected_dtype] # # return rdd.dtype in expected_dtype . Output only the next line.
dist = SparkLinearRegression()
Given snippet: <|code_start|> class TestLinearRegression(SplearnTestCase): def test_same_coefs(self): X, y, Z = self.make_regression(1, 100000) local = LinearRegression() dist = SparkLinearRegression() local.fit(X, y) dist.fit(Z) converted = dist.to_scikit() <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from sklearn.linear_model import LinearRegression from splearn.linear_model import SparkLinearRegression from splearn.utils.testing import (SplearnTestCase, assert_array_almost_equal, assert_true) from splearn.utils.validation import check_rdd_dtype and context: # Path: splearn/linear_model/base.py # class SparkLinearRegression(LinearRegression, SparkLinearModelMixin): # # """Distributed implementation of sklearn's Linear Regression. # # Parameters # ---------- # fit_intercept : boolean, optional # whether to calculate the intercept for this model. If set # to false, no intercept will be used in calculations # (e.g. data is expected to be already centered). # normalize : boolean, optional, default False # If True, the regressors X will be normalized before regression. # copy_X : boolean, optional, default True # If True, X will be copied; else, it may be overwritten. # n_jobs : The number of jobs to use for the computation. # If -1 all CPUs are used. This will only provide speedup for # n_targets > 1 and sufficient large problems. # # Attributes # ---------- # coef_ : array, shape (n_features, ) or (n_targets, n_features) # Estimated coefficients for the linear regression problem. # If multiple targets are passed during the fit (y 2D), this # is a 2D array of shape (n_targets, n_features), while if only # one target is passed, this is a 1D array of length n_features. # intercept_ : array # Independent term in the linear model. # # """ # # def fit(self, Z): # """ # Fit linear model. # # Parameters # ---------- # Z : DictRDD with (X, y) values # X containing numpy array or sparse matrix - The training data # y containing the target values # # Returns # ------- # self : returns an instance of self. # """ # check_rdd(Z, {'X': (sp.spmatrix, np.ndarray)}) # return self._spark_fit(SparkLinearRegression, Z) # # def predict(self, X): # """Distributed method to predict class labels for samples in X. # # Parameters # ---------- # X : ArrayRDD containing {array-like, sparse matrix} # Samples. # # Returns # ------- # C : ArrayRDD # Predicted class label per sample. # """ # check_rdd(X, (sp.spmatrix, np.ndarray)) # return self._spark_predict(SparkLinearRegression, X) # # def to_scikit(self): # return self._to_scikit(LinearRegression) # # Path: splearn/utils/testing.py # def assert_tuple_equal(tpl1, tpl2): # def assert_multiple_tuples_equal(tpls1, tpls2): # def setUp(self): # def tearDown(self): # def make_blobs(self, centers, n_samples, blocks=-1): # def make_regression(self, n_targets, n_samples, blocks=-1): # def make_classification(self, n_classes, n_samples, blocks=-1, # nonnegative=False): # def make_text_rdd(self, blocks=-1): # def make_dense_rdd(self, shape=(1e3, 10), block_size=-1): # def make_dense_randint_rdd(self, low, high=None, shape=(1e3, 10), # block_size=-1): # def make_dense_range_rdd(self, shape=(1e3, 10), block_size=-1): # def make_sparse_rdd(self, shape=(1e3, 10), block_size=-1): # class SplearnTestCase(unittest.TestCase): # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = np.abs(X) # Z = DictRDD([X_rdd, y_rdd], columns=('X', 'y'), bsize=blocks) # X = ALL_FOOD_DOCS # X = rng.randn(*shape) # X = np.random.randint(low, high, size=shape) # X = np.arange(np.prod(shape)).reshape(shape) # X = sp.rand(shape[0], shape[1], random_state=42, density=0.3) # # Path: splearn/utils/validation.py # def check_rdd_dtype(rdd, expected_dtype): # """Checks if the blocks in the RDD matches the expected types. # # Parameters: # ----------- # rdd: splearn.BlockRDD # The RDD to check # expected_dtype: {type, list of types, tuple of types, dict of types} # Expected type(s). If the RDD is a DictRDD the parameter type is # restricted to dict. # # Returns: # -------- # accept: bool # Returns if the types are matched. # """ # if not isinstance(rdd, BlockRDD): # raise TypeError("Expected {0} for parameter rdd, got {1}." # .format(BlockRDD, type(rdd))) # if isinstance(rdd, DictRDD): # if not isinstance(expected_dtype, dict): # raise TypeError('Expected {0} for parameter ' # 'expected_dtype, got {1}.' # .format(dict, type(expected_dtype))) # accept = True # types = dict(list(zip(rdd.columns, rdd.dtype))) # for key, values in expected_dtype.items(): # if not isinstance(values, (tuple, list)): # values = [values] # accept = accept and types[key] in values # return accept # # if not isinstance(expected_dtype, (tuple, list)): # expected_dtype = [expected_dtype] # # return rdd.dtype in expected_dtype which might include code, classes, or functions. Output only the next line.
assert_array_almost_equal(local.coef_, dist.coef_)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- class SparkGridSearchCV(GridSearchCV, SparkBaseEstimator): def _fit(self, Z, parameter_iterable): """Actual fitting, performing the search over parameters.""" self.scorer_ = check_scoring(self.estimator, scoring=self.scoring) cv = self.cv <|code_end|> . Write the next line using the current file imports: from collections import Sized from sklearn.base import clone from sklearn.externals.joblib import Parallel, delayed from sklearn.grid_search import GridSearchCV, ParameterGrid, _CVScoreTuple from sklearn.metrics.scorer import check_scoring from splearn.base import SparkBaseEstimator from splearn.cross_validation import _check_cv, _fit_and_score import numpy as np and context from other files: # Path: splearn/base.py # class SparkBaseEstimator(BaseEstimator): # pass # # Path: splearn/cross_validation.py # def _check_cv(cv, Z=None): # # This exists for internal use while indices is being deprecated. # if cv is None: # cv = 3 # if isinstance(cv, numbers.Integral): # n_samples = Z.count() # try: # # scikit-learn version under 0.17 # cv = KFold(n_samples, cv, indices=True) # except: # cv = KFold(n_samples, cv) # if not getattr(cv, "_indices", True): # raise ValueError("Sparse data and lists require indices-based cross" # " validation generator, got: %r", cv) # return cv # # def _fit_and_score(estimator, Z, scorer, train, test, verbose, # parameters, fit_params, return_train_score=False, # return_parameters=False, error_score='raise'): # # if verbose > 1: # if parameters is None: # msg = "no parameters to be set" # else: # msg = '%s' % (', '.join('%s=%s' % (k, v) # for k, v in list(parameters.items()))) # print(("[CV] %s %s" % (msg, (64 - len(msg)) * '.'))) # # fit_params = fit_params if fit_params is not None else {} # # if parameters is not None: # estimator.set_params(**parameters) # # start_time = time.time() # # Z_train = Z[train] # Z_test = Z[test] # # try: # estimator.fit(Z_train, **fit_params) # except Exception as e: # if error_score == 'raise': # raise # elif isinstance(error_score, numbers.Number): # test_score = error_score # if return_train_score: # train_score = error_score # warnings.warn("Classifier fit failed. The score on this train-test" # " partition for these parameters will be set to %f. " # "Details: \n%r" % (error_score, e), FitFailedWarning) # else: # raise ValueError("error_score must be the string 'raise' or a" # " numeric value. (Hint: if using 'raise', please" # " make sure that it has been spelled correctly.)" # ) # else: # test_score = _score(estimator, Z_test, scorer) # if return_train_score: # train_score = _score(estimator, Z_train, scorer) # # scoring_time = time.time() - start_time # # if verbose > 2: # msg += ", score=%f" % test_score # if verbose > 1: # end_msg = "%s -%s" % (msg, logger.short_format_time(scoring_time)) # print(("[CV] %s %s" % ((64 - len(end_msg)) * '.', end_msg))) # # ret = [train_score] if return_train_score else [] # ret.extend([test_score, _num_samples(Z_test), scoring_time]) # if return_parameters: # ret.append(parameters) # return ret , which may include functions, classes, or code. Output only the next line.
cv = _check_cv(cv, Z)
Given snippet: <|code_start|># -*- coding: utf-8 -*- class SparkGridSearchCV(GridSearchCV, SparkBaseEstimator): def _fit(self, Z, parameter_iterable): """Actual fitting, performing the search over parameters.""" self.scorer_ = check_scoring(self.estimator, scoring=self.scoring) cv = self.cv cv = _check_cv(cv, Z) if self.verbose > 0: if isinstance(parameter_iterable, Sized): n_candidates = len(parameter_iterable) print("Fitting {0} folds for each of {1} candidates, totalling" " {2} fits".format(len(cv), n_candidates, n_candidates * len(cv))) base_estimator = clone(self.estimator) pre_dispatch = self.pre_dispatch out = Parallel( n_jobs=self.n_jobs, verbose=self.verbose, pre_dispatch=pre_dispatch, backend="threading" )( <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import Sized from sklearn.base import clone from sklearn.externals.joblib import Parallel, delayed from sklearn.grid_search import GridSearchCV, ParameterGrid, _CVScoreTuple from sklearn.metrics.scorer import check_scoring from splearn.base import SparkBaseEstimator from splearn.cross_validation import _check_cv, _fit_and_score import numpy as np and context: # Path: splearn/base.py # class SparkBaseEstimator(BaseEstimator): # pass # # Path: splearn/cross_validation.py # def _check_cv(cv, Z=None): # # This exists for internal use while indices is being deprecated. # if cv is None: # cv = 3 # if isinstance(cv, numbers.Integral): # n_samples = Z.count() # try: # # scikit-learn version under 0.17 # cv = KFold(n_samples, cv, indices=True) # except: # cv = KFold(n_samples, cv) # if not getattr(cv, "_indices", True): # raise ValueError("Sparse data and lists require indices-based cross" # " validation generator, got: %r", cv) # return cv # # def _fit_and_score(estimator, Z, scorer, train, test, verbose, # parameters, fit_params, return_train_score=False, # return_parameters=False, error_score='raise'): # # if verbose > 1: # if parameters is None: # msg = "no parameters to be set" # else: # msg = '%s' % (', '.join('%s=%s' % (k, v) # for k, v in list(parameters.items()))) # print(("[CV] %s %s" % (msg, (64 - len(msg)) * '.'))) # # fit_params = fit_params if fit_params is not None else {} # # if parameters is not None: # estimator.set_params(**parameters) # # start_time = time.time() # # Z_train = Z[train] # Z_test = Z[test] # # try: # estimator.fit(Z_train, **fit_params) # except Exception as e: # if error_score == 'raise': # raise # elif isinstance(error_score, numbers.Number): # test_score = error_score # if return_train_score: # train_score = error_score # warnings.warn("Classifier fit failed. The score on this train-test" # " partition for these parameters will be set to %f. " # "Details: \n%r" % (error_score, e), FitFailedWarning) # else: # raise ValueError("error_score must be the string 'raise' or a" # " numeric value. (Hint: if using 'raise', please" # " make sure that it has been spelled correctly.)" # ) # else: # test_score = _score(estimator, Z_test, scorer) # if return_train_score: # train_score = _score(estimator, Z_train, scorer) # # scoring_time = time.time() - start_time # # if verbose > 2: # msg += ", score=%f" % test_score # if verbose > 1: # end_msg = "%s -%s" % (msg, logger.short_format_time(scoring_time)) # print(("[CV] %s %s" % ((64 - len(end_msg)) * '.', end_msg))) # # ret = [train_score] if return_train_score else [] # ret.extend([test_score, _num_samples(Z_test), scoring_time]) # if return_parameters: # ret.append(parameters) # return ret which might include code, classes, or functions. Output only the next line.
delayed(_fit_and_score)(clone(base_estimator), Z, self.scorer_,
Given the code snippet: <|code_start|> intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] Constants in decision function. """ # workaround to keep the classes parameter unchanged @property def classes_(self): return self._classes_ @classes_.setter def classes_(self, value): pass def fit(self, Z, classes=None): """Fit the model according to the given training data. Parameters ---------- Z : DictRDD containing (X, y) pairs X - Training vector y - Target labels classes : iterable The set of available classes Returns ------- self : object Returns self. """ <|code_end|> , generate the next line using the imports in this file: import numpy as np import scipy.sparse as sp from sklearn.svm import LinearSVC from splearn.linear_model.base import SparkLinearModelMixin from ..utils.validation import check_rdd and context (functions, classes, or occasionally code) from other files: # Path: splearn/linear_model/base.py # class SparkLinearModelMixin(object): # # def __add__(self, other): # """Add method for Linear models with coef and intercept attributes. # # Parameters # ---------- # other : fitted sklearn linear model # Model to add. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # model = copy.deepcopy(self) # model.coef_ += other.coef_ # model.intercept_ += other.intercept_ # return model # # def __radd__(self, other): # """Reverse add method for Linear models. # # Parameters # ---------- # other : fitted sklearn linear model # Model to add. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # return self if other == 0 else self.__add__(other) # # def __div__(self, other): # """Division method for Linear models. Used for averaging. # # Parameters # ---------- # other : integer # Integer to divide with. # # Returns # ------- # model : Linear model # Model with updated coefficients. # """ # self.coef_ /= other # self.intercept_ /= other # return self # # __truediv__ = __div__ # # def _spark_fit(self, cls, Z, *args, **kwargs): # """Wraps a Scikit-learn Linear model's fit method to use with RDD # input. # # Parameters # ---------- # cls : class object # The sklearn linear model's class to wrap. # Z : TupleRDD or DictRDD # The distributed train data in a DictRDD. # # Returns # ------- # self: the wrapped class # """ # mapper = lambda X_y: super(cls, self).fit( # X_y[0], X_y[1], *args, **kwargs # ) # models = Z.map(mapper) # avg = models.reduce(operator.add) / models.count() # self.__dict__.update(avg.__dict__) # return self # # def _spark_predict(self, cls, X, *args, **kwargs): # """Wraps a Scikit-learn Linear model's predict method to use with RDD # input. # # Parameters # ---------- # cls : class object # The sklearn linear model's class to wrap. # Z : ArrayRDD # The distributed data to predict in a DictRDD. # # Returns # ------- # self: the wrapped class # """ # return X.map(lambda X: super(cls, self).predict(X, *args, **kwargs)) # # def _to_scikit(self, cls): # new = cls() # new.__dict__ = self.__dict__ # return new # # Path: splearn/utils/validation.py # def check_rdd(rdd, expected_dtype): # """Wrapper function to check_rdd_dtype. Raises TypeError in case of dtype # mismatch. # # Parameters: # ----------- # rdd: splearn.BlockRDD # The RDD to check # expected_dtype: {type, list of types, tuple of types, dict of types} # Expected type(s). If the RDD is a DictRDD the parameter type is # restricted to dict. # """ # if not check_rdd_dtype(rdd, expected_dtype): # raise TypeError("{0} dtype mismatch.".format(rdd)) . Output only the next line.
check_rdd(Z, {'X': (sp.spmatrix, np.ndarray)})
Predict the next line for this snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5 = None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> with the help of current file imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) , which may contain function names, class names, or code. Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Predict the next line after this snippet: <|code_start|> idlist = r.content.decode('utf-8').split("\"")[3] ids = [n for n in idlist.split(";") if len(n) > 3] return ids def get_video_id_category_tuples(categoeries, max_num_videos_per_cat=3000): video_id_category_tuples = [] for category in categoeries: ids = get_youtube_ids_of_category(category) if len(ids) > max_num_videos_per_cat: ids = random.sample(ids, max_num_videos_per_cat) video_id_category_tuples.extend([(id, category)for id in ids]) return video_id_category_tuples def remove_downloaded_videos_from_tuple_list(video_id_category_tuples, metadata_dict): if len(metadata_dict) == 0: # no videos downloaded yet return video_id_category_tuples else: download_dict = dict(video_id_category_tuples) for video_name in metadata_dict.keys(): if video_name.replace('.mp4','') in download_dict.keys(): print(video_name.replace('.mp4','')) del download_dict[video_name.replace('.mp4','')] return download_dict.items() def download_youtube_categories(categoeries, destination_directory, metadata_file_name="metadata.json", max_num_videos_per_cat=3000): #prepare data to download video_id_category_tuples = get_video_id_category_tuples(categoeries, max_num_videos_per_cat=max_num_videos_per_cat) success_count, fail_count = 0, 0 <|code_end|> using the current file's imports: import pafy, json, sys, os, os.path, moviepy, imageio import pandas as pd import numpy as np import random import requests import glob from pprint import pprint from collections import defaultdict from io import StringIO from data_prep.activity_net_download import meta_already_downloaded and any relevant context from other files: # Path: data_prep/activity_net_download.py # def meta_already_downloaded(destination_directory, metadata_file_name): # if os.path.isfile(os.path.join(destination_directory, metadata_file_name)): # dump metadata dict already exists # with open(os.path.join(destination_directory, metadata_file_name), 'r') as f: # already_downloaded_dict = json.load(f) # return already_downloaded_dict # else: # return {} . Output only the next line.
metadata_dict = meta_already_downloaded(destination_directory, metadata_file_name)
Predict the next line for this snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> with the help of current file imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) , which may contain function names, class names, or code. Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Given the following code snippet before the placeholder: <|code_start|> return moviepy.video.fx.all.resize(clip_crop, newsize=target_format) def get_activity_net_video_category(taxonomy_list, label): """requires the ucf101 taxonomy tree structure (from json file) and the clip label (e.g. 'Surfing) in order to find the corresponding category (e.g. 'Participating in water sports)''""" return search_list_of_dicts(taxonomy_list, 'nodeName', label)[0]['parentName'] def search_list_of_dicts(list_of_dicts, dict_key, dict_value): """parses through a list of dictionaries in order to return an entire dict entry that matches a given value (dict_value) for a given key (dict_key)""" return [entry for entry in list_of_dicts if entry[dict_key] == dict_value] def get_metadata_dict_entry(subclip_dict_entry, taxonomy_list=None, type='activity_net'): """constructs and returns a dict entry consisting of the following entries (with UCF 101 example values): - label (Scuba diving) - category (Participating in water sports) - video_id (m_ST2LDe5lA_0) - filetype (mp4) - duration (12.627) - mode (training) - url (https://www.youtube.com/watch?v=m_ST2LDe5lA)""" meta_dict_entry = {} assert type in DATASETS assert taxonomy_list or not type=='activity_net' label = subclip_dict_entry['label'] video_path = subclip_dict_entry['path'] duration = subclip_dict_entry['duration'] url = subclip_dict_entry['url'] <|code_end|> , predict the next line using imports from the current file: import math, json, os.path, moviepy, os, multiprocessing, itertools import random, multiprocessing, subprocess, scenedetect import pandas as pd import traceback import shutil from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip from moviepy.editor import * from utils import io_handler from tensorflow.python.platform import gfile from pprint import pprint from joblib import Parallel, delayed and context including class names, function names, and sometimes code from other files: # Path: utils/io_handler.py # def get_subdirectory_files(dir, depth=1): # def files_from_directory(dir_str, file_type): # def file_paths_from_directory(dir_str, file_type): # def get_filename_and_filetype_from_path(path): # def get_metadata_dict_as_bytes(value): # def get_video_id_from_path(path_str, type=None): # def shuffle_files_in_list(paths_list, seed=5): # def shuffle_files_in_list_from_categories(paths_list, categories, metadata_path, type='youtube8m', seed=5): # def create_session_dir(output_dir): #TODO move to utils # def create_subfolder(dir, name): # def store_output_frames_as_frames(output_frames, labels, output_dir): # def store_output_frames_as_gif(output_frames, labels, output_dir): # def bgr_to_rgb(frame): # def write_file_with_append(path, text_to_append): # def write_metainfo(output_dir, model_name, flags): # def store_dataframe(dataframe, output_dir, file_name): # def store_latent_vectors_as_df(output_dir, hidden_representations, labels, metadata, video_file_paths=None, filename=None): # def store_encoder_latent_vector(output_dir, hidden_representations, labels, produce_single_files=True): # def store_plot(output_dir, name1, name2="", name3="", suffix=".png"): # def export_plot_from_pickle(pickle_file_path, plot_options=((64, 64), 15, 15), show=False): # def folder_names_from_dir(directory): # def folder_files_dict(directory): # def video_length(video_path): # def get_class_mapping(mapping_document_path): # def insert_general_classes_to_20bn_dataframe(df, mappings): # def insert_general_class_to_20bn_dataframe(df, mapping_document_path, new_column_string="class_0", class_column="category"): # def remove_rows_from_dataframe(df, to_remove, column="category"): # def replace_char_from_dataframe(df, category, old_character, new_character): # def select_subset_of_df_with_list(df, own_list, column="category"): # def df_col_to_matrix(panda_col): # def convert_frames_to_gif(frames_dir, gif_file_name=None, image_type='.png', fps=15, gif_file_path=None): # def convert_gif_to_frames(gif_file_path): # def frames_to_gif_in_dir_tree(root_dir): # def gif_to_frames_in_dir_tree(root_dir): # def generate_batch_from_dir(path, suffix="*.png"): # def get_meta_info(filename, type=None, meta_dict = None): . Output only the next line.
video_id, filetype = io_handler.get_filename_and_filetype_from_path(video_path)
Using the snippet: <|code_start|> assert current_image.shape == old_shape hsv = np.zeros_like(prev_image) hsv[..., 1] = 255 flow = cv2.calcOpticalFlowFarneback(prev_image_gray, current_image_gray, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags) mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv[..., 0] = ang*180/np.pi/2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) def compute_dense_optical_flow_for_batch(batch, pyr_scale=0.8, levels=15, winsize=5, iterations=10, poly_n=5, poly_sigma=1.5, flags=0): """ Adds an additional (4th) channel containing the result of Farneback optical flow computation to the images in the batch. Since optical flow generally requires motion (i.e. two images), the additional channel of the first image is always zero (black). :param batch: numpy array with shape(1, encoder_length, height, width, num_channels) :param pyr_scale: parameter, specifying the image scale (<1) to build pyramids for each image :param levels: number of pyramid layers including the initial image :param winsize: averaging window size :param iterations: number of iterations the algorithm does at each pyramid level :param poly_n: size of the pixel neighborhood used to find polynomial expansion in each pixel :param poly_sigma: standard deviation of the Gaussian that is used to smooth derivatives used as a basis for the polynomial expansion :param flags: operation flags, see above specification :return: the provided batch with shape (1, encoder_length, height, width, num_channels+1) """ <|code_end|> , determine the next line of code. You have imports: import numpy as np import cv2 as cv2 from settings import FLAGS and context (class names, function names, or code) available: # Path: settings.py # FLAGS = flags.FLAGS . Output only the next line.
assert batch.shape == (1, FLAGS.encoder_length, FLAGS.height, FLAGS.width, 3)
Predict the next line after this snippet: <|code_start|> def encoder_model(frames, sequence_length, initializer, keep_prob_dropout=0.9, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 32, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) conv1 = tf.nn.dropout(conv1, keep_prob_dropout) #LAYER 2: convLSTM1 <|code_end|> using the current file's imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell, conv_lstm_cell_no_input and any relevant context from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) # # def conv_lstm_cell_no_input(state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[state], reuse=reuse): # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 32, initializer, filter_size=5, scope='convlstm1')
Given the following code snippet before the placeholder: <|code_start|> def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4 = None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , predict the next line using imports from the current file: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim import tensorflow.contrib.layers from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context including class names, function names, and sometimes code from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Continue the code snippet: <|code_start|> def encoder_model(frames, sequence_length, initializer, keep_prob_dropout=0.9, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 32, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) conv1 = tf.nn.dropout(conv1, keep_prob_dropout) #LAYER 2: convLSTM1 <|code_end|> . Use current file imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell, conv_lstm_cell_no_input and context (classes, functions, or code) from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) # # def conv_lstm_cell_no_input(state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[state], reuse=reuse): # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 32, initializer, filter_size=5, scope='convlstm1')
Predict the next line after this snippet: <|code_start|> hidden_repr = lstm_state6 return hidden_repr def decoder_model(hidden_repr, sequence_length, initializer, num_channels=3, keep_prob_dropout=0.9, scope='decoder', fc_conv_layer=False): """ Args: hidden_repr: Tensor of latent space representation sequence_length: number of frames that shall be decoded from the hidden_repr num_channels: number of channels for generated frames initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: frame_gen: array of generated frames (Tensors) fc_conv_layer: indicates whether hidden_repr is 1x1xdepth tensor a and fully concolutional layer shall be added """ frame_gen = [] lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state0 = None, None, None, None, None, None assert (not fc_conv_layer) or (hidden_repr.get_shape()[1] == hidden_repr.get_shape()[2] == 1) lstm_state0 = hidden_repr for i in range(sequence_length): reuse = (i > 0) #reuse variables (recurrence) after first time step with tf.variable_scope(scope, reuse=reuse): <|code_end|> using the current file's imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell, conv_lstm_cell_no_input and any relevant context from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) # # def conv_lstm_cell_no_input(state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[state], reuse=reuse): # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden0, lstm_state0 = conv_lstm_cell_no_input(lstm_state0, FC_LSTM_LAYER_SIZE, initializer, filter_size=1,
Based on the snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context (classes, functions, sometimes code) from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Based on the snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 32, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context (classes, functions, sometimes code) from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 32, initializer, filter_size=5, scope='convlstm1')
Given snippet: <|code_start|> PICKLE_FILE_TEST = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/metadata_and_hidden_rep_df_08-14-17_16-17-12_test.pickle' PICKLE_FILE_VALID = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/metadata_and_hidden_rep_df_08-09-17_17-00-24_valid.pickle' def generate_test_labels_csv(valid_df, test_df, dump_path, n_components=100): #train classifier on valid_df <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import pandas as pd import utils.io_handler as io_handler import os, collections, scipy, itertools, multiprocessing, shutil import scipy, pickle, json import sklearn, sklearn.ensemble import csv from datetime import datetime from pprint import pprint from tensorflow.python.platform import flags from data_postp.matching import train_and_dump_classifier from data_postp.similarity_computations import df_col_to_matrix and context: # Path: data_postp/matching.py # def train_and_dump_classifier(df, dump_path=None, class_column="category", classifier=sklearn.linear_model.LogisticRegression(n_jobs=-1), # n_components=500, train_split_ratio=0.8): # # # separate dataframe into test and train split # if train_split_ratio < 1.0: # msk = np.random.rand(len(df)) < train_split_ratio # test_df = df[~msk] # train_df = df[msk] # else: #no testing required -> make test_df dummy # train_df = df.copy() # test_df = df.copy() # # if n_components > 0: # pca = inter_class_pca(df, class_column=class_column, n_components=n_components) # X_train = pca.transform(df_col_to_matrix(train_df['hidden_repr'])) # X_test = pca.transform(df_col_to_matrix(test_df['hidden_repr'])) # # else: # X_train = df_col_to_matrix(train_df['hidden_repr']) # X_test = df_col_to_matrix(test_df['hidden_repr']) # # y_train = np.asarray(list(train_df[class_column])) # y_test = np.asarray(list(test_df[class_column])) # # # #fit model: # print("Training classifier") # classifier.fit(X_train, y_train) # # #calculate accuracy # if train_split_ratio < 1.0: # acc = classifier.score(X_test, y_test) # print("Accuracy:", acc) # top5_acc = top_n_accuracy(classifier, X_test, y_test, n=3) # print("Top5 Accuracy:", top5_acc) # else: # acc, top5_acc = None, None # # #dump classifier # if dump_path: # classifier_dump_path = os.path.join(os.path.dirname(dump_path), 'classifier.pickle') # with open(classifier_dump_path, 'wb') as f: # pickle.dump(classifier, f) # print("Dumped classifier to:", classifier_dump_path) # # return classifier, pca, acc, top5_acc # # Path: data_postp/similarity_computations.py # def df_col_to_matrix(panda_col): # """Converts a pandas dataframe column wherin each element in an ndarray into a 2D Matrix # :return ndarray (2D) # :param panda_col - panda Series wherin each element in an ndarray # """ # panda_col = panda_col.map(lambda x: x.flatten()) # return np.vstack(panda_col) which might include code, classes, or functions. Output only the next line.
classifier, pca, _, _ = train_and_dump_classifier(valid_df, class_column="category",
Here is a snippet: <|code_start|> PICKLE_FILE_TEST = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/metadata_and_hidden_rep_df_08-14-17_16-17-12_test.pickle' PICKLE_FILE_VALID = '/common/homes/students/rothfuss/Documents/selected_trainings/8_20bn_gdl_optical_flow/validate/metadata_and_hidden_rep_df_08-09-17_17-00-24_valid.pickle' def generate_test_labels_csv(valid_df, test_df, dump_path, n_components=100): #train classifier on valid_df classifier, pca, _, _ = train_and_dump_classifier(valid_df, class_column="category", classifier=sklearn.linear_model.LogisticRegression(n_jobs=-1), n_components=n_components, train_split_ratio=0.8) test_df = pd.read_pickle(PICKLE_FILE_TEST) #PCA transform hidden_reps of test_df <|code_end|> . Write the next line using the current file imports: import numpy as np import pandas as pd import utils.io_handler as io_handler import os, collections, scipy, itertools, multiprocessing, shutil import scipy, pickle, json import sklearn, sklearn.ensemble import csv from datetime import datetime from pprint import pprint from tensorflow.python.platform import flags from data_postp.matching import train_and_dump_classifier from data_postp.similarity_computations import df_col_to_matrix and context from other files: # Path: data_postp/matching.py # def train_and_dump_classifier(df, dump_path=None, class_column="category", classifier=sklearn.linear_model.LogisticRegression(n_jobs=-1), # n_components=500, train_split_ratio=0.8): # # # separate dataframe into test and train split # if train_split_ratio < 1.0: # msk = np.random.rand(len(df)) < train_split_ratio # test_df = df[~msk] # train_df = df[msk] # else: #no testing required -> make test_df dummy # train_df = df.copy() # test_df = df.copy() # # if n_components > 0: # pca = inter_class_pca(df, class_column=class_column, n_components=n_components) # X_train = pca.transform(df_col_to_matrix(train_df['hidden_repr'])) # X_test = pca.transform(df_col_to_matrix(test_df['hidden_repr'])) # # else: # X_train = df_col_to_matrix(train_df['hidden_repr']) # X_test = df_col_to_matrix(test_df['hidden_repr']) # # y_train = np.asarray(list(train_df[class_column])) # y_test = np.asarray(list(test_df[class_column])) # # # #fit model: # print("Training classifier") # classifier.fit(X_train, y_train) # # #calculate accuracy # if train_split_ratio < 1.0: # acc = classifier.score(X_test, y_test) # print("Accuracy:", acc) # top5_acc = top_n_accuracy(classifier, X_test, y_test, n=3) # print("Top5 Accuracy:", top5_acc) # else: # acc, top5_acc = None, None # # #dump classifier # if dump_path: # classifier_dump_path = os.path.join(os.path.dirname(dump_path), 'classifier.pickle') # with open(classifier_dump_path, 'wb') as f: # pickle.dump(classifier, f) # print("Dumped classifier to:", classifier_dump_path) # # return classifier, pca, acc, top5_acc # # Path: data_postp/similarity_computations.py # def df_col_to_matrix(panda_col): # """Converts a pandas dataframe column wherin each element in an ndarray into a 2D Matrix # :return ndarray (2D) # :param panda_col - panda Series wherin each element in an ndarray # """ # panda_col = panda_col.map(lambda x: x.flatten()) # return np.vstack(panda_col) , which may include functions, classes, or code. Output only the next line.
transformed_vectors_as_matrix = pca.transform(df_col_to_matrix(test_df['hidden_repr']))
Predict the next line after this snippet: <|code_start|> def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> using the current file's imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell, conv_lstm_cell_no_input and any relevant context from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) # # def conv_lstm_cell_no_input(state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[state], reuse=reuse): # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Here is a snippet: <|code_start|> return hidden_repr def decoder_model(hidden_repr, sequence_length, initializer, num_channels=3, scope='decoder', fc_conv_layer=False): """ Args: hidden_repr: Tensor of latent space representation sequence_length: number of frames that shall be decoded from the hidden_repr num_channels: number of channels for generated frames initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: frame_gen: array of generated frames (Tensors) fc_conv_layer: indicates whether hidden_repr is 1x1xdepth tensor a and fully concolutional layer shall be added """ frame_gen = [] lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state0 = None, None, None, None, None, None assert (not fc_conv_layer) or (hidden_repr.get_shape()[1] == hidden_repr.get_shape()[2] == 1) lstm_state0 = hidden_repr for i in range(sequence_length): reuse = (i > 0) #reuse variables (recurrence) after first time step with tf.variable_scope(scope, reuse=reuse): #Fully Convolutional Layer (1x1xFC_LAYER_SIZE -> 4x4x16) <|code_end|> . Write the next line using the current file imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell, conv_lstm_cell_no_input and context from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) # # def conv_lstm_cell_no_input(state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[state], reuse=reuse): # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) , which may include functions, classes, or code. Output only the next line.
hidden0, lstm_state0 = conv_lstm_cell_no_input(lstm_state0, FC_LSTM_LAYER_SIZE, initializer, filter_size=1,
Using the snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5 = None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , determine the next line of code. You have imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context (class names, function names, or code) available: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Continue the code snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 32, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> . Use current file imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context (classes, functions, or code) from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 32, initializer, filter_size=5, scope='convlstm1')
Continue the code snippet: <|code_start|> """ takes a folder with a gif file, creates sub directory named after the gif file and stores the single frames in it""" assert gif_file_path dir_name = os.path.basename(gif_file_path) new_dir = create_subfolder(os.path.dirname(gif_file_path), os.path.splitext(dir_name)[0]) clip = mpy.VideoFileClip(gif_file_path).to_RGB() clip.write_images_sequence(os.path.join(new_dir, 'generated_clip_frame%03d.png')) def frames_to_gif_in_dir_tree(root_dir): subdirs = get_subdirectory_files(root_dir, depth=2) for subdir in subdirs: convert_frames_to_gif(subdir, 'action', fps=20, image_type='.png') def gif_to_frames_in_dir_tree(root_dir): subdirs = get_subdirectory_files(root_dir, depth=2) for subdir in subdirs: convert_gif_to_frames(subdir) def generate_batch_from_dir(path, suffix="*.png"): ''' :param path: directory path to images :param suffix: regex that specifies the file suffix (e.g. "*.png" or "*.jpg") :return: numpy array with shape (1, encoder_length, height, width, num_channels) ''' assert os.path.isdir(path), str(path) + "doesn't seem to be a valid path" files = file_paths_from_directory(path, suffix) assert files and len(files)>0, 'Could not find an image with suffix %s in %s'%(path, suffix) <|code_end|> . Use current file imports: import os import tensorflow as tf import re import random import datetime as dt import moviepy.editor as mpy import pandas as pd import json import matplotlib import numpy as np import seaborn as sn import glob as glob import cv2 as cv2 from tensorflow.python.platform import gfile from matplotlib import pyplot as plt from moviepy.editor import VideoFileClip from PIL import Image from settings import FLAGS from .video import compute_dense_optical_flow_for_batch and context (classes, functions, or code) from other files: # Path: settings.py # FLAGS = flags.FLAGS # # Path: utils/video.py # def compute_dense_optical_flow_for_batch(batch, pyr_scale=0.8, levels=15, winsize=5, iterations=10, # poly_n=5, poly_sigma=1.5, flags=0): # """ # Adds an additional (4th) channel containing the result of Farneback optical flow computation to the images in the # batch. Since optical flow generally requires motion (i.e. two images), the additional channel of the first # image is always zero (black). # # :param batch: numpy array with shape(1, encoder_length, height, width, num_channels) # :param pyr_scale: parameter, specifying the image scale (<1) to build pyramids for each image # :param levels: number of pyramid layers including the initial image # :param winsize: averaging window size # :param iterations: number of iterations the algorithm does at each pyramid level # :param poly_n: size of the pixel neighborhood used to find polynomial expansion in each pixel # :param poly_sigma: standard deviation of the Gaussian that is used to smooth derivatives used as a basis for the polynomial expansion # :param flags: operation flags, see above specification # :return: the provided batch with shape (1, encoder_length, height, width, num_channels+1) # """ # assert batch.shape == (1, FLAGS.encoder_length, FLAGS.height, FLAGS.width, 3) # num_frames = batch.shape[1] # assert num_frames > 0 # # flow_masks_shape = list(batch.shape) # flow_masks_shape[4] = 1 # flow_masks = np.zeros(flow_masks_shape) # for i in range(num_frames): # # insert the first (black) flow image into new batch (image_prev == image) # if i == 0: # flow_masks[:, i, :, :,0] = np.zeros((1, FLAGS.height, FLAGS.width)) # else: # image_prev = batch[0, i-1, :, :, :3].copy() # image = batch[0, i, :, :, :3].copy() # #frame_flow = compute_dense_optical_flow(image_prev, image, pyr_scale=pyr_scale, levels=levels, winsize=winsize, # # iterations=iterations, poly_n=poly_n, poly_sigma=poly_sigma, flags=flags) # frame_flow = np.zeros((128, 128)) # flow_masks[:,i,:,:,0] = np.expand_dims(frame_flow, axis=0) # # batch = np.concatenate((batch,flow_masks),axis=4) # return batch . Output only the next line.
batch = np.zeros((1, FLAGS.encoder_length, FLAGS.height, FLAGS.width, 3), dtype=np.uint8)
Predict the next line for this snippet: <|code_start|> def gif_to_frames_in_dir_tree(root_dir): subdirs = get_subdirectory_files(root_dir, depth=2) for subdir in subdirs: convert_gif_to_frames(subdir) def generate_batch_from_dir(path, suffix="*.png"): ''' :param path: directory path to images :param suffix: regex that specifies the file suffix (e.g. "*.png" or "*.jpg") :return: numpy array with shape (1, encoder_length, height, width, num_channels) ''' assert os.path.isdir(path), str(path) + "doesn't seem to be a valid path" files = file_paths_from_directory(path, suffix) assert files and len(files)>0, 'Could not find an image with suffix %s in %s'%(path, suffix) batch = np.zeros((1, FLAGS.encoder_length, FLAGS.height, FLAGS.width, 3), dtype=np.uint8) for i, filename in enumerate(files[:FLAGS.encoder_length]): im = Image.open(filename).convert('RGB') if im.size != (FLAGS.height, FLAGS.width): im = im.resize((FLAGS.height, FLAGS.width), Image.ANTIALIAS) print("image " + str(filename) + " has a different shape than expected -> reshape to (%i,%i)"%(FLAGS.height, FLAGS.width)) batch[0, i, :, :, :3] = np.asarray(im, np.uint8) # add dense optical flow channel to batch if FLAGS.num_channels == 4: <|code_end|> with the help of current file imports: import os import tensorflow as tf import re import random import datetime as dt import moviepy.editor as mpy import pandas as pd import json import matplotlib import numpy as np import seaborn as sn import glob as glob import cv2 as cv2 from tensorflow.python.platform import gfile from matplotlib import pyplot as plt from moviepy.editor import VideoFileClip from PIL import Image from settings import FLAGS from .video import compute_dense_optical_flow_for_batch and context from other files: # Path: settings.py # FLAGS = flags.FLAGS # # Path: utils/video.py # def compute_dense_optical_flow_for_batch(batch, pyr_scale=0.8, levels=15, winsize=5, iterations=10, # poly_n=5, poly_sigma=1.5, flags=0): # """ # Adds an additional (4th) channel containing the result of Farneback optical flow computation to the images in the # batch. Since optical flow generally requires motion (i.e. two images), the additional channel of the first # image is always zero (black). # # :param batch: numpy array with shape(1, encoder_length, height, width, num_channels) # :param pyr_scale: parameter, specifying the image scale (<1) to build pyramids for each image # :param levels: number of pyramid layers including the initial image # :param winsize: averaging window size # :param iterations: number of iterations the algorithm does at each pyramid level # :param poly_n: size of the pixel neighborhood used to find polynomial expansion in each pixel # :param poly_sigma: standard deviation of the Gaussian that is used to smooth derivatives used as a basis for the polynomial expansion # :param flags: operation flags, see above specification # :return: the provided batch with shape (1, encoder_length, height, width, num_channels+1) # """ # assert batch.shape == (1, FLAGS.encoder_length, FLAGS.height, FLAGS.width, 3) # num_frames = batch.shape[1] # assert num_frames > 0 # # flow_masks_shape = list(batch.shape) # flow_masks_shape[4] = 1 # flow_masks = np.zeros(flow_masks_shape) # for i in range(num_frames): # # insert the first (black) flow image into new batch (image_prev == image) # if i == 0: # flow_masks[:, i, :, :,0] = np.zeros((1, FLAGS.height, FLAGS.width)) # else: # image_prev = batch[0, i-1, :, :, :3].copy() # image = batch[0, i, :, :, :3].copy() # #frame_flow = compute_dense_optical_flow(image_prev, image, pyr_scale=pyr_scale, levels=levels, winsize=winsize, # # iterations=iterations, poly_n=poly_n, poly_sigma=poly_sigma, flags=flags) # frame_flow = np.zeros((128, 128)) # flow_masks[:,i,:,:,0] = np.expand_dims(frame_flow, axis=0) # # batch = np.concatenate((batch,flow_masks),axis=4) # return batch , which may contain function names, class names, or code. Output only the next line.
batch = compute_dense_optical_flow_for_batch(batch)
Predict the next line after this snippet: <|code_start|> class Model: def __init__(self): self.learning_rate = tf.placeholder_with_default(FLAGS.learning_rate, ()) self.iter_num = tf.placeholder_with_default(FLAGS.num_iterations, ()) self.summaries = [] self.noise_std = tf.placeholder_with_default(FLAGS.noise_std, ()) self.opt = tf.train.AdamOptimizer(self.learning_rate) <|code_end|> using the current file's imports: import tensorflow as tf import math import numpy as np import data_prep.model_input as input from pprint import pprint from settings import FLAGS, model from models import loss_functions and any relevant context from other files: # Path: settings.py # FLAGS = flags.FLAGS # OUT_DIR = '/common/homes/students/rothfuss/Documents/selected_trainings/9_20bn_vae_no_OF/08-06-18_10-21' # DUMP_DIR = "/common/homes/students/rothfuss/Documents/selected_trainings/9_20bn_vae_no_OF/08-06-18_10-21" # TF_RECORDS_DIR = "/localhome/rothfuss/data/20bn-something/tf_records_train" # MODE = 'valid_mode' # VALID_MODE = 'data_frame' #'data_frame gif' # NUM_IMAGES = 15 # NUM_DEPTH = 3 # WIDTH = 128 # HEIGHT = 128 # NUM_THREADS_QUEUERUNNER = 32 # specifies the number of pre-processing threads # PRETRAINED_MODEL = "/common/homes/students/rothfuss/Documents/selected_trainings/9_20bn_vae_no_OF/08-06-18_10-21" # EXCLUDE_FROM_RESTORING = None # FINE_TUNING_WEIGHTS_LIST = None # INPUT_DIR = "" # MEMORY_PATH = "" # LOSS_FUNCTIONS = ['mse', 'gdl', 'mse_gdl', 'vae'] # MODES = ["train_mode", "valid_mode", "feeding_mode"] # VALID_MODES = ['count_trainable_weights', 'vector', 'gif', 'similarity', 'data_frame', 'psnr', 'memory_prep', 'measure_test_time'] # # Path: models/loss_functions.py # def gradient_difference_loss(true, pred, alpha=2.0): # def difference_gradient(image, vertical=True): # def mean_squared_error(true, pred): # def peak_signal_to_noise_ratio(true, pred): # def kl_penalty(mu, sigma): # def decoder_loss(frames_gen, frames_original, loss_fun): # def decoder_psnr(frames_gen, frames_original): # def composite_loss(original_frames, frames_pred, frames_reconst, loss_fun='mse', # encoder_length=5, decoder_future_length=5, # decoder_reconst_length=5, mu_latent=None, sigm_latent=None): . Output only the next line.
self.model_name = model.__file__
Using the snippet: <|code_start|> :param device number for assining queue runner to CPU :param train: boolean that indicates whether train or validation mode :param compute_loss: boolean that specifies whether loss should be computed (for feed mode / production compute_loss might be disabled) :return batch loss (scalar) """ #only dropout in train mode keep_prob_dropout = FLAGS.keep_prob_dopout if train else 1.0 mu = sigma = None, None if FLAGS.loss_function == 'vae': frames_pred, frames_reconst, hidden_repr, mu, sigma = model.composite_model(video_batch, FLAGS.encoder_length, FLAGS.decoder_future_length, FLAGS.decoder_reconst_length, keep_prob_dropout=keep_prob_dropout, noise_std=FLAGS.noise_std, uniform_init=FLAGS.uniform_init, num_channels=FLAGS.num_channels, fc_conv_layer=FLAGS.fc_layer) if use_vae_mu: hidden_repr = mu else: frames_pred, frames_reconst, hidden_repr = model.composite_model(video_batch, FLAGS.encoder_length, FLAGS.decoder_future_length, FLAGS.decoder_reconst_length, keep_prob_dropout=keep_prob_dropout, noise_std=FLAGS.noise_std, uniform_init=FLAGS.uniform_init, num_channels=FLAGS.num_channels, fc_conv_layer=FLAGS.fc_layer) if compute_loss: <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf import math import numpy as np import data_prep.model_input as input from pprint import pprint from settings import FLAGS, model from models import loss_functions and context (class names, function names, or code) available: # Path: settings.py # FLAGS = flags.FLAGS # OUT_DIR = '/common/homes/students/rothfuss/Documents/selected_trainings/9_20bn_vae_no_OF/08-06-18_10-21' # DUMP_DIR = "/common/homes/students/rothfuss/Documents/selected_trainings/9_20bn_vae_no_OF/08-06-18_10-21" # TF_RECORDS_DIR = "/localhome/rothfuss/data/20bn-something/tf_records_train" # MODE = 'valid_mode' # VALID_MODE = 'data_frame' #'data_frame gif' # NUM_IMAGES = 15 # NUM_DEPTH = 3 # WIDTH = 128 # HEIGHT = 128 # NUM_THREADS_QUEUERUNNER = 32 # specifies the number of pre-processing threads # PRETRAINED_MODEL = "/common/homes/students/rothfuss/Documents/selected_trainings/9_20bn_vae_no_OF/08-06-18_10-21" # EXCLUDE_FROM_RESTORING = None # FINE_TUNING_WEIGHTS_LIST = None # INPUT_DIR = "" # MEMORY_PATH = "" # LOSS_FUNCTIONS = ['mse', 'gdl', 'mse_gdl', 'vae'] # MODES = ["train_mode", "valid_mode", "feeding_mode"] # VALID_MODES = ['count_trainable_weights', 'vector', 'gif', 'similarity', 'data_frame', 'psnr', 'memory_prep', 'measure_test_time'] # # Path: models/loss_functions.py # def gradient_difference_loss(true, pred, alpha=2.0): # def difference_gradient(image, vertical=True): # def mean_squared_error(true, pred): # def peak_signal_to_noise_ratio(true, pred): # def kl_penalty(mu, sigma): # def decoder_loss(frames_gen, frames_original, loss_fun): # def decoder_psnr(frames_gen, frames_original): # def composite_loss(original_frames, frames_pred, frames_reconst, loss_fun='mse', # encoder_length=5, decoder_future_length=5, # decoder_reconst_length=5, mu_latent=None, sigm_latent=None): . Output only the next line.
tower_loss = loss_functions.composite_loss(video_batch, frames_pred, frames_reconst, loss_fun=FLAGS.loss_function,
Using the snippet: <|code_start|> self.saver_restore = None self.itr_start = 0 def start_session(self): """Starts a session and initializes all variables. Provides access to session and coordinator""" # Start Session and initialize variables self.status = True init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) self.sess = tf.Session() self.sess.run(init_op) # Start input enqueue threads self.coord = tf.train.Coordinator() self.threads = tf.train.start_queue_runners(sess=self.sess, coord=self.coord) def stop_session(self): """Stops a current session.""" if self.sess and self.coord: self.coord.join(self.threads) self.sess.close() self.status = False def start_saver(self): """Constructs a saver and if pretrained model given, loads the model.""" print('Constructing saver') self.saver = tf.train.Saver(max_to_keep=0) # restore dumped model if provided <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf from settings import FLAGS from utils.helpers import get_iter_from_pretrained_model, remove_items_from_dict and context (class names, function names, or code) available: # Path: settings.py # FLAGS = flags.FLAGS # # Path: utils/helpers.py # def get_iter_from_pretrained_model(checkpoint_file_name): # ''' extracts the iterator count of a dumped checkpoint from the checkpoint file name # :param checkpoint_file_name: name of checkpoint file - must contain a # :return: iterator number # ''' # file_basename = os.path.basename(checkpoint_file_name) # assert re.compile('[A-Za-z0-9]+[-][0-9]+').match(file_basename) # idx = re.findall(r'-\b\d+\b', file_basename)[0][1:] # return int(idx) # # def remove_items_from_dict(string_dict, strings_to_remove): # result_dict = {} # for v_name, v in string_dict.items(): # if not any([(s in v_name) for s in strings_to_remove]): # result_dict[v_name] = v # return result_dict . Output only the next line.
if FLAGS.pretrained_model:
Here is a snippet: <|code_start|> def start_session(self): """Starts a session and initializes all variables. Provides access to session and coordinator""" # Start Session and initialize variables self.status = True init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) self.sess = tf.Session() self.sess.run(init_op) # Start input enqueue threads self.coord = tf.train.Coordinator() self.threads = tf.train.start_queue_runners(sess=self.sess, coord=self.coord) def stop_session(self): """Stops a current session.""" if self.sess and self.coord: self.coord.join(self.threads) self.sess.close() self.status = False def start_saver(self): """Constructs a saver and if pretrained model given, loads the model.""" print('Constructing saver') self.saver = tf.train.Saver(max_to_keep=0) # restore dumped model if provided if FLAGS.pretrained_model: print('Restore model from: ' + str(FLAGS.pretrained_model)) latest_checkpoint = tf.train.latest_checkpoint(FLAGS.pretrained_model) <|code_end|> . Write the next line using the current file imports: import tensorflow as tf from settings import FLAGS from utils.helpers import get_iter_from_pretrained_model, remove_items_from_dict and context from other files: # Path: settings.py # FLAGS = flags.FLAGS # # Path: utils/helpers.py # def get_iter_from_pretrained_model(checkpoint_file_name): # ''' extracts the iterator count of a dumped checkpoint from the checkpoint file name # :param checkpoint_file_name: name of checkpoint file - must contain a # :return: iterator number # ''' # file_basename = os.path.basename(checkpoint_file_name) # assert re.compile('[A-Za-z0-9]+[-][0-9]+').match(file_basename) # idx = re.findall(r'-\b\d+\b', file_basename)[0][1:] # return int(idx) # # def remove_items_from_dict(string_dict, strings_to_remove): # result_dict = {} # for v_name, v in string_dict.items(): # if not any([(s in v_name) for s in strings_to_remove]): # result_dict[v_name] = v # return result_dict , which may include functions, classes, or code. Output only the next line.
self.itr_start = get_iter_from_pretrained_model(latest_checkpoint) + 1
Using the snippet: <|code_start|> self.sess = tf.Session() self.sess.run(init_op) # Start input enqueue threads self.coord = tf.train.Coordinator() self.threads = tf.train.start_queue_runners(sess=self.sess, coord=self.coord) def stop_session(self): """Stops a current session.""" if self.sess and self.coord: self.coord.join(self.threads) self.sess.close() self.status = False def start_saver(self): """Constructs a saver and if pretrained model given, loads the model.""" print('Constructing saver') self.saver = tf.train.Saver(max_to_keep=0) # restore dumped model if provided if FLAGS.pretrained_model: print('Restore model from: ' + str(FLAGS.pretrained_model)) latest_checkpoint = tf.train.latest_checkpoint(FLAGS.pretrained_model) self.itr_start = get_iter_from_pretrained_model(latest_checkpoint) + 1 print('Start with iteration: ' + str(self.itr_start)) if FLAGS.exclude_from_restoring is not None: vars_to_exclude = str(FLAGS.exclude_from_restoring).replace(' ','').split(',') global_vars = dict([(v.name, v) for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="train_model")]) <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf from settings import FLAGS from utils.helpers import get_iter_from_pretrained_model, remove_items_from_dict and context (class names, function names, or code) available: # Path: settings.py # FLAGS = flags.FLAGS # # Path: utils/helpers.py # def get_iter_from_pretrained_model(checkpoint_file_name): # ''' extracts the iterator count of a dumped checkpoint from the checkpoint file name # :param checkpoint_file_name: name of checkpoint file - must contain a # :return: iterator number # ''' # file_basename = os.path.basename(checkpoint_file_name) # assert re.compile('[A-Za-z0-9]+[-][0-9]+').match(file_basename) # idx = re.findall(r'-\b\d+\b', file_basename)[0][1:] # return int(idx) # # def remove_items_from_dict(string_dict, strings_to_remove): # result_dict = {} # for v_name, v in string_dict.items(): # if not any([(s in v_name) for s in strings_to_remove]): # result_dict[v_name] = v # return result_dict . Output only the next line.
global_vars = remove_items_from_dict(global_vars, vars_to_exclude)
Given the code snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 32, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , generate the next line using the imports in this file: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell, conv_lstm_cell_no_input and context (functions, classes, or occasionally code) from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) # # def conv_lstm_cell_no_input(state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[state], reuse=reuse): # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 32, initializer, filter_size=5, scope='convlstm1')
Using the snippet: <|code_start|> hidden_repr = lstm_state6 return hidden_repr def decoder_model(hidden_repr, sequence_length, initializer, num_channels=3, scope='decoder', fc_conv_layer=False): """ Args: hidden_repr: Tensor of latent space representation sequence_length: number of frames that shall be decoded from the hidden_repr num_channels: number of channels for generated frames initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: frame_gen: array of generated frames (Tensors) fc_conv_layer: indicates whether hidden_repr is 1x1xdepth tensor a and fully concolutional layer shall be added """ frame_gen = [] lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state0 = None, None, None, None, None, None assert (not fc_conv_layer) or (hidden_repr.get_shape()[1] == hidden_repr.get_shape()[2] == 1) lstm_state0 = hidden_repr for i in range(sequence_length): reuse = (i > 0) #reuse variables (recurrence) after first time step with tf.variable_scope(scope, reuse=reuse): <|code_end|> , determine the next line of code. You have imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell, conv_lstm_cell_no_input and context (class names, function names, or code) available: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) # # def conv_lstm_cell_no_input(state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[state], reuse=reuse): # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden0, lstm_state0 = conv_lstm_cell_no_input(lstm_state0, FC_LSTM_LAYER_SIZE, initializer, filter_size=1,
Given the code snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , generate the next line using the imports in this file: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context (functions, classes, or occasionally code) from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Using the snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 32, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , determine the next line of code. You have imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context (class names, function names, or code) available: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 32, initializer, filter_size=5, scope='convlstm1')
Using the snippet: <|code_start|>DNA_KERN_SIZE = 5 def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4, lstm_state5, lstm_state6 = None, None, None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> , determine the next line of code. You have imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and context (class names, function names, or code) available: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Here is a snippet: <|code_start|>"""Convert data to TFRecords file format with example protos. An Example is a mostly-normalized data format for storing data for training and inference. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function def read_and_decode(filename_queue): """Creates one image sequence""" reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) image_seq = [] video_id = None <|code_end|> . Write the next line using the current file imports: import os import tensorflow as tf from tensorflow.python.platform import gfile from settings import FLAGS and context from other files: # Path: settings.py # FLAGS = flags.FLAGS , which may include functions, classes, or code. Output only the next line.
for imageCount in range(FLAGS.num_images):
Predict the next line after this snippet: <|code_start|> def encoder_model(frames, sequence_length, initializer, scope='encoder', fc_conv_layer=False): """ Args: frames: 5D array of batch with videos - shape(batch_size, num_frames, frame_width, frame_higth, num_channels) sequence_length: number of frames that shall be encoded scope: tensorflow variable scope name initializer: specifies the initialization type (default: contrib.slim.layers uses Xavier init with uniform data) fc_conv_layer: adds an fc layer at the end of the encoder Returns: hidden4: hidden state of highest ConvLSTM layer fc_conv_layer: indicated whether a Fully Convolutional (8x8x16 -> 1x1x1024) shall be added """ lstm_state1, lstm_state2, lstm_state3, lstm_state4 = None, None, None, None for i in range(sequence_length): frame = frames[:,i,:,:,:] reuse = (i > 0) with tf.variable_scope(scope, reuse=reuse): #LAYER 1: conv1 conv1 = slim.layers.conv2d(frame, 16, [5, 5], stride=2, scope='conv1', normalizer_fn=tf_layers.layer_norm, weights_initializer=initializer, normalizer_params={'scope': 'layer_norm1'}) #LAYER 2: convLSTM1 <|code_end|> using the current file's imports: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim import tensorflow.contrib.layers from tensorflow.contrib.layers.python import layers as tf_layers from models.conv_lstm import basic_conv_lstm_cell and any relevant context from other files: # Path: models/conv_lstm.py # @add_arg_scope # def basic_conv_lstm_cell(inputs, # state, # num_channels, # initializer, # filter_size=5, # forget_bias=1.0, # scope=None, # reuse=None): # """Basic LSTM recurrent network cell, with 2D convolution connctions. # We add forget_bias (default: 1) to the biases of the forget gate in order to # reduce the scale of forgetting in the beginning of the training. # It does not allow cell clipping, a projection layer, and does not # use peep-hole connections: it is the basic baseline. # Args: # inputs: input Tensor, 4D, batch x height x width x channels. # state: state Tensor, 4D, batch x height x width x channels. # num_channels: the number of output channels in the layer. # filter_size: the shape of the each convolution filter. # forget_bias: the initial value of the forget biases. # scope: Optional scope for variable_scope. # reuse: whether or not the layer and the variables should be reused. # Returns: # a tuple of tensors representing output and the new state. # """ # spatial_size = inputs.get_shape()[1:3] # if state is None: # state = init_state(inputs, list(spatial_size) + [2 * num_channels]) # with tf.variable_scope(scope, default_name='BasicConvLstmCell', values=[inputs, state], reuse=reuse): # inputs.get_shape().assert_has_rank(4) # state.get_shape().assert_has_rank(4) # c, h = tf.split(3, 2, state) # inputs_h = tf.concat(3, [inputs, h]) # # Parameters of gates are concatenated into one conv for efficiency. # i_j_f_o = layers.conv2d(inputs_h, # 4 * num_channels, [filter_size, filter_size], # stride=1, # activation_fn=None, # scope='Gates', weights_initializer=initializer) # # # i = input_gate, j = new_input, f = forget_gate, o = output_gate # i, j, f, o = tf.split(3, 4, i_j_f_o) # # new_c = c * tf.sigmoid(f + forget_bias) + tf.sigmoid(i) * tf.tanh(j) # new_h = tf.tanh(new_c) * tf.sigmoid(o) # # return new_h, tf.concat(3, [new_c, new_h]) . Output only the next line.
hidden1, lstm_state1 = basic_conv_lstm_cell(conv1, lstm_state1, 16, initializer, filter_size=5, scope='convlstm1')
Next line prediction: <|code_start|> def create_batch_and_feed(initializer, feeding_model): # TODO """ :param initializer: :param feed_model: :return: """ <|code_end|> . Use current file imports: (import tensorflow as tf import numpy as np from settings import FLAGS from utils.io_handler import generate_batch_from_dir) and context including class names, function names, or small code snippets from other files: # Path: settings.py # FLAGS = flags.FLAGS # # Path: utils/io_handler.py # def generate_batch_from_dir(path, suffix="*.png"): # ''' # :param path: directory path to images # :param suffix: regex that specifies the file suffix (e.g. "*.png" or "*.jpg") # :return: numpy array with shape (1, encoder_length, height, width, num_channels) # ''' # assert os.path.isdir(path), str(path) + "doesn't seem to be a valid path" # # files = file_paths_from_directory(path, suffix) # assert files and len(files)>0, 'Could not find an image with suffix %s in %s'%(path, suffix) # batch = np.zeros((1, FLAGS.encoder_length, FLAGS.height, FLAGS.width, 3), dtype=np.uint8) # # for i, filename in enumerate(files[:FLAGS.encoder_length]): # im = Image.open(filename).convert('RGB') # if im.size != (FLAGS.height, FLAGS.width): # im = im.resize((FLAGS.height, FLAGS.width), Image.ANTIALIAS) # print("image " + str(filename) + " has a different shape than expected -> reshape to (%i,%i)"%(FLAGS.height, FLAGS.width)) # batch[0, i, :, :, :3] = np.asarray(im, np.uint8) # # # # add dense optical flow channel to batch # if FLAGS.num_channels == 4: # batch = compute_dense_optical_flow_for_batch(batch) # # return batch . Output only the next line.
assert FLAGS.pretrained_model
Here is a snippet: <|code_start|> def create_batch_and_feed(initializer, feeding_model): # TODO """ :param initializer: :param feed_model: :return: """ assert FLAGS.pretrained_model <|code_end|> . Write the next line using the current file imports: import tensorflow as tf import numpy as np from settings import FLAGS from utils.io_handler import generate_batch_from_dir and context from other files: # Path: settings.py # FLAGS = flags.FLAGS # # Path: utils/io_handler.py # def generate_batch_from_dir(path, suffix="*.png"): # ''' # :param path: directory path to images # :param suffix: regex that specifies the file suffix (e.g. "*.png" or "*.jpg") # :return: numpy array with shape (1, encoder_length, height, width, num_channels) # ''' # assert os.path.isdir(path), str(path) + "doesn't seem to be a valid path" # # files = file_paths_from_directory(path, suffix) # assert files and len(files)>0, 'Could not find an image with suffix %s in %s'%(path, suffix) # batch = np.zeros((1, FLAGS.encoder_length, FLAGS.height, FLAGS.width, 3), dtype=np.uint8) # # for i, filename in enumerate(files[:FLAGS.encoder_length]): # im = Image.open(filename).convert('RGB') # if im.size != (FLAGS.height, FLAGS.width): # im = im.resize((FLAGS.height, FLAGS.width), Image.ANTIALIAS) # print("image " + str(filename) + " has a different shape than expected -> reshape to (%i,%i)"%(FLAGS.height, FLAGS.width)) # batch[0, i, :, :, :3] = np.asarray(im, np.uint8) # # # # add dense optical flow channel to batch # if FLAGS.num_channels == 4: # batch = compute_dense_optical_flow_for_batch(batch) # # return batch , which may include functions, classes, or code. Output only the next line.
feed_batch = generate_batch_from_dir(FLAGS.feeding_input_dir, suffix='*.jpg')
Continue the code snippet: <|code_start|> psyco.full() except ImportError: # pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" # Follows ASCII order. ASCII58_BYTES = ("123456789" "ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz").encode("ascii") # Therefore, b"1" represents b"\0". ASCII58_ORDS = dict((x, i) for i, x in enumerate(ASCII58_BYTES)) # Really, I don't understand why people use the non-ASCII order, # but if you really like it that much, go ahead. Be my guest. Here # is what you will need: # # Does not follow ASCII order. ALT58_BYTES = ("123456789" "abcdefghijkmnopqrstuvwxyz" "ABCDEFGHJKLMNPQRSTUVWXYZ").encode("ascii") # Therefore, b"1" represents b"\0". ALT58_ORDS = dict((x, i) for i, x in enumerate(ALT58_BYTES)) <|code_end|> . Use current file imports: import psyco from mom import _compat from mom import builtins from mom.codec import _base and context (classes, functions, or code) from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/_base.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True): # def base_decode(encoded, base, base_ords, base_zero, powers): # def base_to_uint(encoded, # base, # ord_lookup_table, # powers): # def uint_to_base256(number, encoded, base_zero): . Output only the next line.
if _compat.HAVE_PYTHON3:
Continue the code snippet: <|code_start|> psyco.full() except ImportError: # pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" # Follows ASCII order. ASCII58_BYTES = ("123456789" "ABCDEFGHJKLMNPQRSTUVWXYZ" "abcdefghijkmnopqrstuvwxyz").encode("ascii") # Therefore, b"1" represents b"\0". ASCII58_ORDS = dict((x, i) for i, x in enumerate(ASCII58_BYTES)) # Really, I don't understand why people use the non-ASCII order, # but if you really like it that much, go ahead. Be my guest. Here # is what you will need: # # Does not follow ASCII order. ALT58_BYTES = ("123456789" "abcdefghijkmnopqrstuvwxyz" "ABCDEFGHJKLMNPQRSTUVWXYZ").encode("ascii") # Therefore, b"1" represents b"\0". ALT58_ORDS = dict((x, i) for i, x in enumerate(ALT58_BYTES)) if _compat.HAVE_PYTHON3: <|code_end|> . Use current file imports: import psyco from mom import _compat from mom import builtins from mom.codec import _base and context (classes, functions, or code) from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/_base.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True): # def base_decode(encoded, base, base_ords, base_zero, powers): # def base_to_uint(encoded, # base, # ord_lookup_table, # powers): # def uint_to_base256(number, encoded, base_zero): . Output only the next line.
ASCII58_BYTES = tuple(builtins.byte(x) for x in ASCII58_BYTES)
Given the code snippet: <|code_start|> if _compat.HAVE_PYTHON3: ASCII58_BYTES = tuple(builtins.byte(x) for x in ASCII58_BYTES) ALT58_BYTES = tuple(builtins.byte(x) for x in ALT58_BYTES) # If you're going to make people type stuff longer than this length # I don't know what to tell you. Beyond this length powers # are computed, so be careful if you care about computation speed. # I think this is a VERY generous range. Decoding bytes fewer than 512 # will use this pre-computed lookup table, and hence, be faster. POW_58 = tuple(58 ** power for power in builtins.range(512)) def b58encode(raw_bytes, base_bytes=ASCII58_BYTES, _padding=True): """ Base58 encodes a sequence of raw bytes. Zero-byte sequences are preserved by default. :param raw_bytes: Raw bytes to encode. :param base_bytes: The character set to use. Defaults to ``ASCII58_BYTES`` that uses natural ASCII order. :param _padding: (Internal) ``True`` (default) to include prefixed zero-byte sequence padding converted to appropriate representation. :returns: Base-58 encoded bytes. """ <|code_end|> , generate the next line using the imports in this file: import psyco from mom import _compat from mom import builtins from mom.codec import _base and context (functions, classes, or occasionally code) from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/_base.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True): # def base_decode(encoded, base, base_ords, base_zero, powers): # def base_to_uint(encoded, # base, # ord_lookup_table, # powers): # def uint_to_base256(number, encoded, base_zero): . Output only the next line.
return _base.base_encode(raw_bytes, 58, base_bytes, base_bytes[0], _padding)
Based on the snippet: <|code_start|># copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # Some tests depend on new div. from __future__ import absolute_import from __future__ import division __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" #TODO inplace long += gmp class Test_integer_init(unittest2.TestCase): def setUp(self): <|code_end|> , predict the immediate next line with the help of imports: import operator import unittest2 from mom import gmp and context (classes, functions, sometimes code) from other files: # Path: mom/gmp.py # def number_to_pybytes(num): # def to_str(raw_bytes_num): # def number_to_pybytes(num): # def to_str(raw_bytes_num): # def __init__(self, init_value=0): # def __del__(self): # def _as_parameter_(self): # def from_param(arg): # def _apply_ret(self, func, ret, op1, op2): # def _apply_2_rets(self, func, ret1, ret2, op1, op2): # def _apply_ret_2_0(self, func, ret, op1): # def _apply_ret_2_1(self, func, op1, op2): # def set(self, value): # def _tobytes(self): # def __str__(self): # def __repr__(self): # def __lt__(self, other): # def __le__(self, other): # def __eq__(self, other): # def __ne__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def __add__(self, other): # def __sub__(self, other): # def __mul__(self, other): # def __divmod__(self, divisor): # def __rdivmod__(self, dividend): # def __div__(self, other): # def __truediv__(self, unused_other): # def __floordiv__(self, other): # def __and__(self, other): # def __mod__(self, other): # def __xor__(self, other): # def __or__(self, other): # def __iadd__(self, other): # def __isub__(self, other): # def __imul__(self, other): # def __imod__(self, other): # def __idiv__(self, other): # def __itruediv__(self, unused_other): # def __ifloordiv__(self, other): # def __iand__(self, other): # def __ixor__(self, other): # def __ior__(self, other): # def __radd__(self, other): # def __rsub__(self, other): # def __rmul__(self, other): # def __rdiv__(self, other): # def __rtruediv__(self, unused_other): # def __rfloordiv__(self, other): # def __rmod__(self, other): # def __abs__(self): # def __neg__(self): # class c_mpz_struct(ctypes.Structure): # class c_gmp_randstate_struct(ctypes.Structure): # class c_mpq_struct(ctypes.Structure): # class c_mpf_struct(ctypes.Structure): # class Integer(object): # RAND_ALGO_DEFAULT = _GMP_randinit_default # RAND_ALGO_MT = _GMP_randinit_mt . Output only the next line.
self.large_gmp = gmp.Integer(4294967300)
Here is a snippet: <|code_start|> sys.path[0:0] = [ os.curdir, ] header = '''\ #/usr/bin/env python # -*- coding: utf-8 -*- # Automatically-generated by dump_primes.py # # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Precomputed prime sieve for faster lookups.""" ''' print(header) <|code_end|> . Write the next line using the current file imports: import sys import os from mom._prime_sieve import make_prime_sieve from pprint import pprint and context from other files: # Path: mom/_prime_sieve.py # def make_prime_sieve(max_n): # def _numpy_primesfrom2to(max_n): # """Input n>=6, Returns a array of primes, 2 <= p < n""" # sieve = np.ones(max_n // 3 + (max_n % 6 == 2), dtype=np.bool) # sieve[0] = False # for i in _compat.range(int(max_n ** 0.5) // 3 + 1): # if sieve[i]: # k = 3 * i + 1 | 1 # sieve[((k * k) // 3)::2 * k] = False # sieve[(k * k + 4 * k - 2 * k * (i & 1)) // 3::2 * k] = False # return np.r_[2, 3, ((3 * np.nonzero(sieve)[0] + 1) | 1)] , which may include functions, classes, or code. Output only the next line.
a = set(make_prime_sieve(9999))
Given snippet: <|code_start|> __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" __all__ = [ "byte", "byte_ord", "bytes", "bytes_leading", "bytes_trailing", "bin", "hex", "integer_byte_length", "integer_byte_size", "integer_bit_length", "is_sequence", "is_unicode", "is_bytes", "is_bytes_or_unicode", "is_integer", "is_even", "is_negative", "is_odd", "is_positive", ] # Integral range <|code_end|> , continue by predicting the next line. Consider current file imports: import psyco import struct from mom import _compat and context: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): which might include code, classes, or functions. Output only the next line.
range = _compat.range
Continue the code snippet: <|code_start|> try: for tup in izip(*iters): yield tup except IndexError: pass def permutations(iterable, r=None): """Return successive `r` length permutations of elements in the `iterable`. If `r` is not specified or is ``None``, then `r` defaults to the length of the `iterable` and all possible full-length permutations are generated. Permutations are emitted in lexicographic sort order. So, if the input `iterable` is sorted, the permutation tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeating value in each permutation. The number of items returned is ``n! / (n - r)!`` when ``0 <= r <= n`` or zero when `r > n`. .. note:: Software and documentation for this function are taken from CPython, :ref:`license details <psf-license>`. """ pool = tuple(iterable) pool_length = len(pool) r = pool_length if r is None else r <|code_end|> . Use current file imports: import itertools from mom import builtins from itertools import izip from itertools import starmap and context (classes, functions, or code) from other files: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): . Output only the next line.
for indices in product(builtins.range(pool_length), repeat=r):
Given snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """:synopsis: Base-36 codec. :module: mom.codec.base36 .. autofunction:: b36encode .. autofunction:: b36decode """ from __future__ import absolute_import # pylint: disable-msg=R0801 try: # pragma: no cover psyco.full() except ImportError: # pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" <|code_end|> , continue by predicting the next line. Consider current file imports: import psyco from mom import _compat from mom import builtins from mom import string from mom.codec import _base and context: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/string.py # ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz" # ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE # DIGITS = "0123456789" # PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""" # PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\ # ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c""" # WHITESPACE = "\t\n\x0b\x0c\r " # # Path: mom/codec/_base.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True): # def base_decode(encoded, base, base_ords, base_zero, powers): # def base_to_uint(encoded, # base, # ord_lookup_table, # powers): # def uint_to_base256(number, encoded, base_zero): which might include code, classes, or functions. Output only the next line.
EMPTY_BYTE = _compat.EMPTY_BYTE
Next line prediction: <|code_start|>""":synopsis: Base-36 codec. :module: mom.codec.base36 .. autofunction:: b36encode .. autofunction:: b36decode """ from __future__ import absolute_import # pylint: disable-msg=R0801 try: # pragma: no cover psyco.full() except ImportError: # pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" EMPTY_BYTE = _compat.EMPTY_BYTE # Follows ASCII order. ASCII36_BYTES = (string.DIGITS + string.ASCII_UPPERCASE).encode("ascii") # Therefore, b"1" represents b"\0". if _compat.HAVE_PYTHON3: <|code_end|> . Use current file imports: ( import psyco from mom import _compat from mom import builtins from mom import string from mom.codec import _base) and context including class names, function names, or small code snippets from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/string.py # ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz" # ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE # DIGITS = "0123456789" # PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""" # PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\ # ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c""" # WHITESPACE = "\t\n\x0b\x0c\r " # # Path: mom/codec/_base.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True): # def base_decode(encoded, base, base_ords, base_zero, powers): # def base_to_uint(encoded, # base, # ord_lookup_table, # powers): # def uint_to_base256(number, encoded, base_zero): . Output only the next line.
ASCII36_BYTES = tuple(builtins.byte(x) for x in ASCII36_BYTES)
Given the following code snippet before the placeholder: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """:synopsis: Base-36 codec. :module: mom.codec.base36 .. autofunction:: b36encode .. autofunction:: b36decode """ from __future__ import absolute_import # pylint: disable-msg=R0801 try: # pragma: no cover psyco.full() except ImportError: # pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" EMPTY_BYTE = _compat.EMPTY_BYTE # Follows ASCII order. <|code_end|> , predict the next line using imports from the current file: import psyco from mom import _compat from mom import builtins from mom import string from mom.codec import _base and context including class names, function names, and sometimes code from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/string.py # ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz" # ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE # DIGITS = "0123456789" # PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""" # PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\ # ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c""" # WHITESPACE = "\t\n\x0b\x0c\r " # # Path: mom/codec/_base.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True): # def base_decode(encoded, base, base_ords, base_zero, powers): # def base_to_uint(encoded, # base, # ord_lookup_table, # powers): # def uint_to_base256(number, encoded, base_zero): . Output only the next line.
ASCII36_BYTES = (string.DIGITS +
Here is a snippet: <|code_start|> __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" EMPTY_BYTE = _compat.EMPTY_BYTE # Follows ASCII order. ASCII36_BYTES = (string.DIGITS + string.ASCII_UPPERCASE).encode("ascii") # Therefore, b"1" represents b"\0". if _compat.HAVE_PYTHON3: ASCII36_BYTES = tuple(builtins.byte(x) for x in ASCII36_BYTES) def b36encode(raw_bytes, base_bytes=ASCII36_BYTES, _padding=True): """ Base-36 encodes a sequence of raw bytes. Zero-byte sequences are preserved by default. :param raw_bytes: Raw bytes to encode. :param base_bytes: The character set to use. Defaults to ``ASCII36_BYTES`` that uses natural ASCII order. :param _padding: (Internal) ``True`` (default) to include prefixed zero-byte sequence padding converted to appropriate representation. :returns: Uppercase (default) base-36 encoded bytes. """ <|code_end|> . Write the next line using the current file imports: import psyco from mom import _compat from mom import builtins from mom import string from mom.codec import _base and context from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/string.py # ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz" # ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE # DIGITS = "0123456789" # PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""" # PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\ # ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c""" # WHITESPACE = "\t\n\x0b\x0c\r " # # Path: mom/codec/_base.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def base_encode(raw_bytes, base, base_bytes, base_zero, padding=True): # def base_decode(encoded, base, base_ords, base_zero, powers): # def base_to_uint(encoded, # base, # ord_lookup_table, # powers): # def uint_to_base256(number, encoded, base_zero): , which may include functions, classes, or code. Output only the next line.
return _base.base_encode(raw_bytes, 36, base_bytes, base_bytes[0], _padding)
Given the following code snippet before the placeholder: <|code_start|> "rfc1924_b85encode(b)", "rfc1924_b85decode(b)", None, "integer_byte_length(n)", "integer_byte_length_word_aligned(n)", "integer_byte_length_shift_counting(n)", None, "integer_bit_length(n)", "integer_bit_length_word_aligned(n)", "integer_bit_length_shift_counting(n)", None, "uint_to_bytes(n)", "uint_to_bytes_simple(n)", "uint_to_bytes_array_based(n)", "uint_to_bytes_pycrypto(n)", "uint_to_bytes_naive(n)", "uint_to_bytes_naive_array_based(n)", None, "bytes_to_uint(b)", "bytes_to_uint_naive(b)", "bytes_to_uint_simple(b)", ] def main(setups, statements): print("Python %s" % sys.version) for setup, statement in zip(setups, statements): if setup is None or statement is None: print("") else: <|code_end|> , predict the next line using imports from the current file: import sys from mom.tests.speed import report and context including class names, function names, and sometimes code from other files: # Path: mom/tests/speed.py # def report(stmt, setup, number=0, verbose=0, precision=3, # repeat=timeit.default_repeat, timer=timeit.default_timer): # sys.stdout.write("%50s -- " % stmt) # t = timeit.Timer(stmt, setup, timer) # if number == 0: # # determine number so that 0.2 <= total time < 2.0 # for i in range(1, 10): # number = 10 ** i # try: # x = t.timeit(number) # except Exception: # t.print_exc() # return 1 # if verbose: # print("%d loops -> %.*g secs" % (number, precision, x)) # if x >= 0.2: # break # try: # r = t.repeat(repeat, number) # except Exception: # t.print_exc() # return 1 # best = min(r) # if verbose: # print("raw times:", " ".join(["%.*g" % (precision, x) for x in r])) # sys.stdout.write("%d loops, " % number) # usec = best * 1e6 / number # if usec < 1000: # print("best of %d: %.*g usec per loop" % (repeat, precision, usec)) # else: # msec = usec / 1000 # if msec < 1000: # print("best of %d: %.*g msec per loop" % (repeat, precision, msec)) # else: # sec = msec / 1000 # print("best of %d: %.*g sec per loop" % (repeat, precision, sec)) . Output only the next line.
report(statement, setup)
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" class Test_match_path_against(unittest2.TestCase): def test_all(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest2 from mom.os import patterns and context: # Path: mom/os/patterns.py # def _string_lower(string): # def match_path_against(pathname, patterns, case_sensitive=True): # def _match_path(pathname, # included_patterns, # excluded_patterns, # case_sensitive=True): # def match_path(pathname, # included_patterns=None, # excluded_patterns=None, # case_sensitive=True): # def filter_paths(pathnames, # included_patterns=None, # excluded_patterns=None, # case_sensitive=True): # def match_any_paths(pathnames, # included_patterns=None, # excluded_patterns=None, # case_sensitive=True): which might include code, classes, or functions. Output only the next line.
self.assertTrue(patterns.match_path_against(
Given the following code snippet before the placeholder: <|code_start|> def _string_lower(string): """ Convenience function to lowercase a string. :param string: The string which will be lower-cased. :returns: Lower-cased copy of string s. """ return string.lower() def match_path_against(pathname, patterns, case_sensitive=True): """ Determines whether the pathname matches any of the given wildcard patterns, optionally ignoring the case of the pathname and patterns. :param pathname: A path name that will be matched against a wildcard pattern. :param patterns: A list of wildcard patterns to match_path the filename against. :param case_sensitive: ``True`` if the matching should be case-sensitive; ``False`` otherwise. :returns: ``True`` if the pattern matches; ``False`` otherwise. """ if case_sensitive: match_func = functools.partial(fnmatch.fnmatchcase, pathname) <|code_end|> , predict the next line using imports from the current file: from itertools import imap as map from mom import functional import fnmatch import functools and context including class names, function names, and sometimes code from other files: # Path: mom/functional.py # def _ifilterfalse(predicate, iterable): # def _complement(item): # def compose(function, *functions): # def _composition(a_func, b_func): # def _wrap(*args, **kwargs): # def _compose(function, *functions): # def _composition(*args_tuple): # def complement(predicate): # def _negate(*args, **kwargs): # def reduce(transform, iterable, *args): # def each(walker, iterable): # def some(predicate, iterable): # def _some1(predicate, iterable): # def _some2(predicate, iterable): # def every(predicate, iterable): # def none(predicate, iterable): # def find(predicate, iterable, start=0): # def leading(predicate, iterable, start=0): # def _leading(predicate, iterable, start=0): # def trailing(predicate, iterable, start=-1): # def tally(predicate, iterable): # def select(predicate, iterable): # def iselect(predicate, iterable): # def reject(predicate, iterable): # def ireject(predicate, iterable): # def partition(predicate, iterable): # def _partitioner(memo, item): # def partition_dict(predicate, dictionary): # def _pred(tup): # def map_dict(transform, dictionary): # def select_dict(predicate, dictionary): # def _pred(tup): # def reject_dict(predicate, dictionary): # def _pred(tup): # def invert_dict(dictionary): # def pluck(dicts, key, *args, **kwargs): # def ipluck(dicts, key, *args, **kwargs): # def _get_value_from_dict(dictionary): # def contains(iterable, item): # def _contains_fallback(iterable, item): # def omits(iterable, item): # def difference(iterable1, iterable2): # def idifference(iterable1, iterable2): # def without(iterable, *values): # def head(iterable): # def tail(iterable): # def itail(iterable): # def nth(iterable, index, default=None): # def last(iterable): # def occurrences(iterable): # def peel(iterable, count=1): # def ipeel(iterable, count=1): # def ichunks(iterable, size, *args, **kwargs): # def chunks(iterable, size, *args, **kwargs): # def truthy(iterable): # def itruthy(iterable): # def falsy(iterable): # def ifalsy(iterable): # def flatten(iterable): # def _flatten(memo, item): # def flatten1(iterable): # def _flatten(memo, item): # def group_consecutive(predicate, iterable): # def flock(predicate, iterable): # def unique(iterable, is_sorted=False): # def _unique(memo, item): # def union(iterable, *iterables): # def intersection(iterable, *iterables): # def _does_other_contain(item): # def take(iterable, amount): # def eat(iterator, amount): # def _get_iter_next(iterator): # def round_robin(*iterables): # def ncycles(iterable, times): # def identity(arg): # def loob(arg): # def always(_): # def never(_): # def constant(c): # def _func(*args, **kwargs): # def nothing(*args, **kwargs): . Output only the next line.
transform = functional.identity
Given snippet: <|code_start|>__all__ = [ "absolute_path", "get_dir_walker", "list_directories", "list_files", "listdir", "parent_dir_path", "real_absolute_path", "walk", ] def get_dir_walker(recursive, topdown=True, followlinks=False): """ Returns a recursive or a non-recursive directory walker. :param recursive: ``True`` produces a recursive walker; ``False`` produces a non-recursive walker. :returns: A walker function. """ if recursive: walker = functools.partial(os.walk, topdown=topdown, followlinks=followlinks) else: def walker(path, topdown=topdown, followlinks=followlinks): """Alternative walker.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import functools import os from mom import builtins and context: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): which might include code, classes, or functions. Output only the next line.
yield builtins.next(os.walk(path,
Based on the snippet: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Alternative implementations of integer module routines that were bench-marked to be slower.""" from __future__ import absolute_import # pylint: disable-msg=R0801 try: # pragma: no cover psyco.full() except ImportError: # pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" <|code_end|> , predict the immediate next line with the help of imports: import psyco import array import struct from mom import _compat from mom import builtins and context (classes, functions, sometimes code) from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): . Output only the next line.
ZERO_BYTE = _compat.ZERO_BYTE
Predict the next line after this snippet: <|code_start|> psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" ZERO_BYTE = _compat.ZERO_BYTE EMPTY_BYTE = _compat.EMPTY_BYTE def uint_to_bytes_naive_array_based(uint, chunk_size=0): """ Converts an integer into bytes. :param uint: Unsigned integer value. :param chunk_size: Chunk size. :returns: Bytes. """ if uint < 0: raise ValueError("Negative numbers cannot be used: %i" % uint) if uint == 0: bytes_count = 1 else: <|code_end|> using the current file's imports: import psyco import array import struct from mom import _compat from mom import builtins and any relevant context from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): . Output only the next line.
bytes_count = builtins.integer_byte_length(uint)
Using the snippet: <|code_start|># Copyright 2009 Facebook. # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """:synopsis: More portable JSON encoding and decoding routines. :module: mom.codec.json .. autofunction:: json_encode .. autofunction:: json_decode """ from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" <|code_end|> , determine the next line of code. You have imports: from mom import _compat from mom import builtins from mom.codec import _json_compat from mom.codec import text and context (class names, function names, or code) available: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/_json_compat.py # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(unused_value): # # Path: mom/codec/text.py # def utf8_encode(unicode_text): # def utf8_decode(utf8_encoded_bytes): # def utf8_encode_if_unicode(obj): # def utf8_decode_if_bytes(obj): # def to_unicode_if_bytes(obj, encoding="utf-8"): # def bytes_to_unicode(raw_bytes, encoding="utf-8"): # def utf8_encode_recursive(obj): # def bytes_to_unicode_recursive(obj, encoding="utf-8"): # def utf8_decode_recursive(obj): # def ascii_encode(obj): # def latin1_encode(obj): . Output only the next line.
if _compat.HAVE_PYTHON3:
Using the snippet: <|code_start|> from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" if _compat.HAVE_PYTHON3: json_dumps = _json_compat.json_dumps else: json_dumps = lambda o: _json_compat.json_dumps(o).decode("utf-8") def json_encode(obj): """ Encodes a Python value into its equivalent JSON string. JSON permits but does not require forward slashes to be escaped. This is useful when json data is emitted in a <script> tag in HTML, as it prevents </script> tags from prematurely terminating the javscript. Some json libraries do this escaping by default, although python's standard library does not, so we do it here. :see: http://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped :param obj: Python value. :returns: JSON string. """ <|code_end|> , determine the next line of code. You have imports: from mom import _compat from mom import builtins from mom.codec import _json_compat from mom.codec import text and context (class names, function names, or code) available: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/_json_compat.py # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(unused_value): # # Path: mom/codec/text.py # def utf8_encode(unicode_text): # def utf8_decode(utf8_encoded_bytes): # def utf8_encode_if_unicode(obj): # def utf8_decode_if_bytes(obj): # def to_unicode_if_bytes(obj, encoding="utf-8"): # def bytes_to_unicode(raw_bytes, encoding="utf-8"): # def utf8_encode_recursive(obj): # def bytes_to_unicode_recursive(obj, encoding="utf-8"): # def utf8_decode_recursive(obj): # def ascii_encode(obj): # def latin1_encode(obj): . Output only the next line.
if builtins.is_bytes(obj):
Given the following code snippet before the placeholder: <|code_start|># Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """:synopsis: More portable JSON encoding and decoding routines. :module: mom.codec.json .. autofunction:: json_encode .. autofunction:: json_decode """ from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" if _compat.HAVE_PYTHON3: <|code_end|> , predict the next line using imports from the current file: from mom import _compat from mom import builtins from mom.codec import _json_compat from mom.codec import text and context including class names, function names, and sometimes code from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/_json_compat.py # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(unused_value): # # Path: mom/codec/text.py # def utf8_encode(unicode_text): # def utf8_decode(utf8_encoded_bytes): # def utf8_encode_if_unicode(obj): # def utf8_decode_if_bytes(obj): # def to_unicode_if_bytes(obj, encoding="utf-8"): # def bytes_to_unicode(raw_bytes, encoding="utf-8"): # def utf8_encode_recursive(obj): # def bytes_to_unicode_recursive(obj, encoding="utf-8"): # def utf8_decode_recursive(obj): # def ascii_encode(obj): # def latin1_encode(obj): . Output only the next line.
json_dumps = _json_compat.json_dumps
Given snippet: <|code_start|> __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" if _compat.HAVE_PYTHON3: json_dumps = _json_compat.json_dumps else: json_dumps = lambda o: _json_compat.json_dumps(o).decode("utf-8") def json_encode(obj): """ Encodes a Python value into its equivalent JSON string. JSON permits but does not require forward slashes to be escaped. This is useful when json data is emitted in a <script> tag in HTML, as it prevents </script> tags from prematurely terminating the javscript. Some json libraries do this escaping by default, although python's standard library does not, so we do it here. :see: http://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped :param obj: Python value. :returns: JSON string. """ if builtins.is_bytes(obj): raise TypeError("Cannot work with bytes.") <|code_end|> , continue by predicting the next line. Consider current file imports: from mom import _compat from mom import builtins from mom.codec import _json_compat from mom.codec import text and context: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/_json_compat.py # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(value): # def json_dumps(value): # def json_loads(unused_value): # # Path: mom/codec/text.py # def utf8_encode(unicode_text): # def utf8_decode(utf8_encoded_bytes): # def utf8_encode_if_unicode(obj): # def utf8_decode_if_bytes(obj): # def to_unicode_if_bytes(obj, encoding="utf-8"): # def bytes_to_unicode(raw_bytes, encoding="utf-8"): # def utf8_encode_recursive(obj): # def bytes_to_unicode_recursive(obj, encoding="utf-8"): # def utf8_decode_recursive(obj): # def ascii_encode(obj): # def latin1_encode(obj): which might include code, classes, or functions. Output only the next line.
return json_dumps(text.utf8_decode_recursive(obj)).replace("</", "<\\/")
Predict the next line after this snippet: <|code_start|> __all__ = [ "ascii_encode", "bytes_to_unicode", "bytes_to_unicode_recursive", "latin1_encode", "to_unicode_if_bytes", "utf8_decode", "utf8_decode_if_bytes", "utf8_decode_recursive", "utf8_encode", "utf8_encode_if_unicode", "utf8_encode_recursive", ] def utf8_encode(unicode_text): """ UTF-8 encodes a Unicode string into bytes; bytes and None are left alone. Work with Unicode strings in your code and encode your Unicode strings into UTF-8 before they leave your system. :param unicode_text: If already a byte string or None, it is returned unchanged. Otherwise it must be a Unicode string and is encoded as UTF-8 bytes. :returns: UTF-8 encoded bytes. """ <|code_end|> using the current file's imports: from mom import builtins and any relevant context from other files: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): . Output only the next line.
if unicode_text is None or builtins.is_bytes(unicode_text):
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import from __future__ import division # pylint: disable-msg=R0801 try: #pragma: no cover psyco.full() except ImportError: #pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" __all__ = [ "b85encode", "b85decode", "rfc1924_b85encode", "rfc1924_b85decode", "ASCII85_PREFIX", "ASCII85_SUFFIX", "ipv6_b85encode", "ipv6_b85decode", ] b = builtins.b <|code_end|> with the help of current file imports: import psyco import array import struct from mom import _compat from mom import builtins from mom import string and context from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/string.py # ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz" # ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE # DIGITS = "0123456789" # PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""" # PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\ # ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c""" # WHITESPACE = "\t\n\x0b\x0c\r " , which may contain function names, class names, or code. Output only the next line.
ZERO_BYTE = _compat.ZERO_BYTE
Using the snippet: <|code_start|> from __future__ import absolute_import from __future__ import division # pylint: disable-msg=R0801 try: #pragma: no cover psyco.full() except ImportError: #pragma: no cover psyco = None # pylint: enable-msg=R0801 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" __all__ = [ "b85encode", "b85decode", "rfc1924_b85encode", "rfc1924_b85decode", "ASCII85_PREFIX", "ASCII85_SUFFIX", "ipv6_b85encode", "ipv6_b85decode", ] <|code_end|> , determine the next line of code. You have imports: import psyco import array import struct from mom import _compat from mom import builtins from mom import string and context (class names, function names, or code) available: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/string.py # ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz" # ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE # DIGITS = "0123456789" # PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""" # PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\ # ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c""" # WHITESPACE = "\t\n\x0b\x0c\r " . Output only the next line.
b = builtins.b
Next line prediction: <|code_start|> ] b = builtins.b ZERO_BYTE = _compat.ZERO_BYTE UINT128_MAX = _compat.UINT128_MAX UINT32_MAX = _compat.UINT32_MAX EMPTY_BYTE = _compat.EMPTY_BYTE EXCLAMATION_CHUNK = b("!!!!!") ZERO_GROUP_CHAR = b("z") # Use this if you want the base85 codec to encode/decode including # ASCII85 prefixes/suffixes. ASCII85_PREFIX = b("<~") ASCII85_SUFFIX = b("~>") # ASCII85 characters. ASCII85_BYTES = array.array("B", [(num + 33) for num in builtins.range(85)]) # I've left this approach in here to warn you to NOT use it. # This results in a massive amount of calls to byte_ord inside # tight loops. Don't use the array. Use the dictionary. It # removes the need to convert to ords at runtime. # ASCII85_ORDS = array.array("B", [255] * 128) # for ordinal, _byte in enumerate(ASCII85_BYTES): # ASCII85_ORDS[_byte] = ordinal # http://tools.ietf.org/html/rfc1924 <|code_end|> . Use current file imports: ( import psyco import array import struct from mom import _compat from mom import builtins from mom import string) and context including class names, function names, or small code snippets from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/string.py # ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz" # ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE # DIGITS = "0123456789" # PUNCTUATION = """!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~""" # PRINTABLE = """0123456789abcdefghijklmnopqrstuvwxyz\ # ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c""" # WHITESPACE = "\t\n\x0b\x0c\r " . Output only the next line.
RFC1924_BYTES = array.array("B", (string.DIGITS +
Using the snippet: <|code_start|> :param num: Integer value. If num is 0, returns 0. If num is negative, its absolute value will be considered. :returns: The number of bytes in the integer. """ return len(_integer_raw_bytes_without_leading(num)) def integer_bit_length_word_aligned(num): """ Number of bits needed to represent a integer excluding any prefix 0 bits. :param num: Integer value. If num is 0, returns 0. Only the absolute value of the number is considered. Therefore, signed integers will be abs(num) before the number's bit length is determined. :returns: Returns the number of bits in the integer. """ # Do not change this to `not num` otherwise a TypeError will not # be raised when `None` is passed in as a value. if num == 0: return 0 if num < 0: num = -num if num > 0x80: raw_bytes = _integer_raw_bytes_without_leading(num) <|code_end|> , determine the next line of code. You have imports: import struct from mom import _compat from mom import builtins and context (class names, function names, or code) available: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): . Output only the next line.
first_byte = builtins.byte_ord(raw_bytes[0])
Using the snippet: <|code_start|># EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """:synopsis: ctypes-based GMP wrapper. :module: mom.gmp :see: http://noahdesu.com/2009/12/14/python-gmp/ .. autoclass:: Integer .. autoclass:: Float .. autoclass:: Rational .. autoclass:: Random """ from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" # pylint: disable-msg=W0212 # pylint: disable-msg=C0103 <|code_end|> , determine the next line of code. You have imports: import ctypes from ctypes import util from mom import _compat and context (class names, function names, or code) available: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): . Output only the next line.
if _compat.HAVE_PYTHON3:
Predict the next line after this snippet: <|code_start|> """:synopsis: MIME-Type Parser. :module: mom.mimeparse This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents -------- .. autofunction:: parse_mime_type .. autofunction:: parse_media_range .. autofunction:: quality .. autofunction:: quality_parsed .. autofunction:: best_match """ __version__ = "0.1.3" __author__ = "Joe Gregorio" __email__ = "joe@bitworking.org" __license__ = "MIT License" __credits__ = "" b = builtins.b <|code_end|> using the current file's imports: from mom import _compat from mom import builtins and any relevant context from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): . Output only the next line.
EMPTY_BYTE = _compat.EMPTY_BYTE
Given the code snippet: <|code_start|># THE SOFTWARE. """:synopsis: MIME-Type Parser. :module: mom.mimeparse This module provides basic functions for handling mime-types. It can handle matching mime-types against a list of media-ranges. See section 14.1 of the HTTP specification [RFC 2616] for a complete explanation. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 Contents -------- .. autofunction:: parse_mime_type .. autofunction:: parse_media_range .. autofunction:: quality .. autofunction:: quality_parsed .. autofunction:: best_match """ __version__ = "0.1.3" __author__ = "Joe Gregorio" __email__ = "joe@bitworking.org" __license__ = "MIT License" __credits__ = "" <|code_end|> , generate the next line using the imports in this file: from mom import _compat from mom import builtins and context (functions, classes, or occasionally code) from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): . Output only the next line.
b = builtins.b
Using the snippet: <|code_start|> def test_ValueError_when_0_bits(self): self.assertRaises(ValueError, random.generate_random_uint_atmost, 0) def test_TypeError_when_invalid_argument(self): self.assertRaises(TypeError, random.generate_random_uint_atmost, None) self.assertRaises(TypeError, random.generate_random_uint_atmost, {}) self.assertRaises(TypeError, random.generate_random_uint_atmost, object) self.assertRaises(TypeError, random.generate_random_uint_atmost, True) self.assertRaises(TypeError, random.generate_random_uint_atmost, "") class Test_generate_random_hex_string(unittest2.TestCase): def test_length(self): default_length = 8 self.assertEqual(len(random.generate_random_hex_string()), default_length, "Length does not match "\ "default expected length of %d." % default_length) self.assertEqual(len(random.generate_random_hex_string(length=10)), 10, "Length does not match expected length.") def test_uniqueness(self): # The likelyhood of recurrence should be tiny if a large enough # length is chosen. self.assertNotEqual(random.generate_random_hex_string(), random.generate_random_hex_string(), "Not unique.") def test_is_string(self): <|code_end|> , determine the next line of code. You have imports: import unittest2 from mom import builtins from mom.codec import integer from mom.security import random and context (class names, function names, or code) available: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/integer.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def bytes_to_uint(raw_bytes): # def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False): # # Path: mom/security/random.py # HEXADECIMAL_DIGITS = string.DIGITS + "abcdef" # DIGITS = string.DIGITS # LOWERCASE_ALPHA = string.ASCII_LOWERCASE # UPPERCASE_ALPHA = string.ASCII_UPPERCASE # LOWERCASE_ALPHANUMERIC = LOWERCASE_ALPHA + string.DIGITS # UPPERCASE_ALPHANUMERIC = UPPERCASE_ALPHA + string.DIGITS # ALPHA = string.ASCII_LETTERS # ALPHANUMERIC = ALPHA + string.DIGITS # ASCII_PRINTABLE = ALPHA + string.DIGITS + string.PUNCTUATION # ALL_PRINTABLE = string.PRINTABLE # PUNCTUATION = string.PUNCTUATION # def generate_random_bits(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_atmost(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_exactly(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_between(low, high, rand_func=generate_random_bytes): # def generate_random_hex_string(length=8, rand_func=generate_random_bytes): # def random_choice(sequence, rand_func=generate_random_bytes): # def random_shuffle(sequence, rand_func=generate_random_bytes): # def generate_random_sequence(length, pool, rand_func=generate_random_bytes): # def generate_random_string(length, pool=ALPHANUMERIC, # rand_func=generate_random_bytes): # def calculate_entropy(length, pool=ALPHANUMERIC): # def generate_random_sequence_strong(entropy, pool, # rand_func=generate_random_bytes): # def generate_random_password(entropy, pool=ASCII_PRINTABLE, # rand_func=generate_random_bytes): . Output only the next line.
self.assertTrue(builtins.is_bytes(random.generate_random_hex_string()),
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" class Test_generate_random_bits(unittest2.TestCase): def test_range(self): for _ in range(999): n_bits = 4 <|code_end|> using the current file's imports: import unittest2 from mom import builtins from mom.codec import integer from mom.security import random and any relevant context from other files: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/integer.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def bytes_to_uint(raw_bytes): # def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False): # # Path: mom/security/random.py # HEXADECIMAL_DIGITS = string.DIGITS + "abcdef" # DIGITS = string.DIGITS # LOWERCASE_ALPHA = string.ASCII_LOWERCASE # UPPERCASE_ALPHA = string.ASCII_UPPERCASE # LOWERCASE_ALPHANUMERIC = LOWERCASE_ALPHA + string.DIGITS # UPPERCASE_ALPHANUMERIC = UPPERCASE_ALPHA + string.DIGITS # ALPHA = string.ASCII_LETTERS # ALPHANUMERIC = ALPHA + string.DIGITS # ASCII_PRINTABLE = ALPHA + string.DIGITS + string.PUNCTUATION # ALL_PRINTABLE = string.PRINTABLE # PUNCTUATION = string.PUNCTUATION # def generate_random_bits(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_atmost(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_exactly(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_between(low, high, rand_func=generate_random_bytes): # def generate_random_hex_string(length=8, rand_func=generate_random_bytes): # def random_choice(sequence, rand_func=generate_random_bytes): # def random_shuffle(sequence, rand_func=generate_random_bytes): # def generate_random_sequence(length, pool, rand_func=generate_random_bytes): # def generate_random_string(length, pool=ALPHANUMERIC, # rand_func=generate_random_bytes): # def calculate_entropy(length, pool=ALPHANUMERIC): # def generate_random_sequence_strong(entropy, pool, # rand_func=generate_random_bytes): # def generate_random_password(entropy, pool=ASCII_PRINTABLE, # rand_func=generate_random_bytes): . Output only the next line.
value = integer.bytes_to_uint(random.generate_random_bits(n_bits))
Based on the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" class Test_generate_random_bits(unittest2.TestCase): def test_range(self): for _ in range(999): n_bits = 4 <|code_end|> , predict the immediate next line with the help of imports: import unittest2 from mom import builtins from mom.codec import integer from mom.security import random and context (classes, functions, sometimes code) from other files: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/integer.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def bytes_to_uint(raw_bytes): # def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False): # # Path: mom/security/random.py # HEXADECIMAL_DIGITS = string.DIGITS + "abcdef" # DIGITS = string.DIGITS # LOWERCASE_ALPHA = string.ASCII_LOWERCASE # UPPERCASE_ALPHA = string.ASCII_UPPERCASE # LOWERCASE_ALPHANUMERIC = LOWERCASE_ALPHA + string.DIGITS # UPPERCASE_ALPHANUMERIC = UPPERCASE_ALPHA + string.DIGITS # ALPHA = string.ASCII_LETTERS # ALPHANUMERIC = ALPHA + string.DIGITS # ASCII_PRINTABLE = ALPHA + string.DIGITS + string.PUNCTUATION # ALL_PRINTABLE = string.PRINTABLE # PUNCTUATION = string.PUNCTUATION # def generate_random_bits(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_atmost(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_exactly(n_bits, rand_func=generate_random_bytes): # def generate_random_uint_between(low, high, rand_func=generate_random_bytes): # def generate_random_hex_string(length=8, rand_func=generate_random_bytes): # def random_choice(sequence, rand_func=generate_random_bytes): # def random_shuffle(sequence, rand_func=generate_random_bytes): # def generate_random_sequence(length, pool, rand_func=generate_random_bytes): # def generate_random_string(length, pool=ALPHANUMERIC, # rand_func=generate_random_bytes): # def calculate_entropy(length, pool=ALPHANUMERIC): # def generate_random_sequence_strong(entropy, pool, # rand_func=generate_random_bytes): # def generate_random_password(entropy, pool=ASCII_PRINTABLE, # rand_func=generate_random_bytes): . Output only the next line.
value = integer.bytes_to_uint(random.generate_random_bits(n_bits))
Given the code snippet: <|code_start|> self.assertRaises(TypeError, functional.leading, lambda w: w > 0, 3) self.assertRaises(TypeError, functional.leading, lambda w: w > 0, True) class Test_trailing(unittest2.TestCase): def test_count(self): self.assertEqual(functional.trailing(lambda w: w > 0, [0, 0, 1]), 1) self.assertEqual(functional.trailing(lambda w: w > 1, [2, 0, 2, 3, 5]), 3) self.assertEqual(functional.trailing(lambda w: ord(w) >= ord("c"), "abalskjd"), 5) self.assertEqual(functional.trailing(lambda w: ord(w) >= ord("c"), "cuddleya"), 0) def test_end(self): self.assertEqual(functional.trailing(lambda w: w == "0", "0001"), 0) self.assertEqual(functional.trailing(lambda w: w == "0", "1000", -1), 3) self.assertEqual(functional.trailing(lambda w: w == "0", "1000", -2), 2) self.assertEqual(functional.trailing(lambda w: w == "0", "1000", 0), 3) self.assertEqual(functional.trailing(lambda w: w == "0", "1000", 1), 2) self.assertEqual(functional.trailing(lambda w: w == "0", "1000", 2), 1) def test_full_count(self): self.assertEqual(functional.trailing((lambda w: w > 0), range(1, 10)), 9) def test_TypeError_when_not_iterable(self): self.assertRaises(TypeError, functional.trailing, lambda w: w > 0, None) self.assertRaises(TypeError, functional.trailing, lambda w: w > 0, 3) self.assertRaises(TypeError, functional.trailing, lambda w: w > 0, True) class Test_select(unittest2.TestCase): def test_select(self): <|code_end|> , generate the next line using the imports in this file: import unittest2 from mom import builtins from mom import functional and context (functions, classes, or occasionally code) from other files: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/functional.py # def _ifilterfalse(predicate, iterable): # def _complement(item): # def compose(function, *functions): # def _composition(a_func, b_func): # def _wrap(*args, **kwargs): # def _compose(function, *functions): # def _composition(*args_tuple): # def complement(predicate): # def _negate(*args, **kwargs): # def reduce(transform, iterable, *args): # def each(walker, iterable): # def some(predicate, iterable): # def _some1(predicate, iterable): # def _some2(predicate, iterable): # def every(predicate, iterable): # def none(predicate, iterable): # def find(predicate, iterable, start=0): # def leading(predicate, iterable, start=0): # def _leading(predicate, iterable, start=0): # def trailing(predicate, iterable, start=-1): # def tally(predicate, iterable): # def select(predicate, iterable): # def iselect(predicate, iterable): # def reject(predicate, iterable): # def ireject(predicate, iterable): # def partition(predicate, iterable): # def _partitioner(memo, item): # def partition_dict(predicate, dictionary): # def _pred(tup): # def map_dict(transform, dictionary): # def select_dict(predicate, dictionary): # def _pred(tup): # def reject_dict(predicate, dictionary): # def _pred(tup): # def invert_dict(dictionary): # def pluck(dicts, key, *args, **kwargs): # def ipluck(dicts, key, *args, **kwargs): # def _get_value_from_dict(dictionary): # def contains(iterable, item): # def _contains_fallback(iterable, item): # def omits(iterable, item): # def difference(iterable1, iterable2): # def idifference(iterable1, iterable2): # def without(iterable, *values): # def head(iterable): # def tail(iterable): # def itail(iterable): # def nth(iterable, index, default=None): # def last(iterable): # def occurrences(iterable): # def peel(iterable, count=1): # def ipeel(iterable, count=1): # def ichunks(iterable, size, *args, **kwargs): # def chunks(iterable, size, *args, **kwargs): # def truthy(iterable): # def itruthy(iterable): # def falsy(iterable): # def ifalsy(iterable): # def flatten(iterable): # def _flatten(memo, item): # def flatten1(iterable): # def _flatten(memo, item): # def group_consecutive(predicate, iterable): # def flock(predicate, iterable): # def unique(iterable, is_sorted=False): # def _unique(memo, item): # def union(iterable, *iterables): # def intersection(iterable, *iterables): # def _does_other_contain(item): # def take(iterable, amount): # def eat(iterator, amount): # def _get_iter_next(iterator): # def round_robin(*iterables): # def ncycles(iterable, times): # def identity(arg): # def loob(arg): # def always(_): # def never(_): # def constant(c): # def _func(*args, **kwargs): # def nothing(*args, **kwargs): . Output only the next line.
self.assertEqual(functional.select(builtins.is_even, [1, 2, 3, 4, 5, 6]), [2, 4, 6])
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" class Test_some(unittest2.TestCase): def test_valid(self): <|code_end|> . Use current file imports: (import unittest2 from mom import builtins from mom import functional) and context including class names, function names, or small code snippets from other files: # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/functional.py # def _ifilterfalse(predicate, iterable): # def _complement(item): # def compose(function, *functions): # def _composition(a_func, b_func): # def _wrap(*args, **kwargs): # def _compose(function, *functions): # def _composition(*args_tuple): # def complement(predicate): # def _negate(*args, **kwargs): # def reduce(transform, iterable, *args): # def each(walker, iterable): # def some(predicate, iterable): # def _some1(predicate, iterable): # def _some2(predicate, iterable): # def every(predicate, iterable): # def none(predicate, iterable): # def find(predicate, iterable, start=0): # def leading(predicate, iterable, start=0): # def _leading(predicate, iterable, start=0): # def trailing(predicate, iterable, start=-1): # def tally(predicate, iterable): # def select(predicate, iterable): # def iselect(predicate, iterable): # def reject(predicate, iterable): # def ireject(predicate, iterable): # def partition(predicate, iterable): # def _partitioner(memo, item): # def partition_dict(predicate, dictionary): # def _pred(tup): # def map_dict(transform, dictionary): # def select_dict(predicate, dictionary): # def _pred(tup): # def reject_dict(predicate, dictionary): # def _pred(tup): # def invert_dict(dictionary): # def pluck(dicts, key, *args, **kwargs): # def ipluck(dicts, key, *args, **kwargs): # def _get_value_from_dict(dictionary): # def contains(iterable, item): # def _contains_fallback(iterable, item): # def omits(iterable, item): # def difference(iterable1, iterable2): # def idifference(iterable1, iterable2): # def without(iterable, *values): # def head(iterable): # def tail(iterable): # def itail(iterable): # def nth(iterable, index, default=None): # def last(iterable): # def occurrences(iterable): # def peel(iterable, count=1): # def ipeel(iterable, count=1): # def ichunks(iterable, size, *args, **kwargs): # def chunks(iterable, size, *args, **kwargs): # def truthy(iterable): # def itruthy(iterable): # def falsy(iterable): # def ifalsy(iterable): # def flatten(iterable): # def _flatten(memo, item): # def flatten1(iterable): # def _flatten(memo, item): # def group_consecutive(predicate, iterable): # def flock(predicate, iterable): # def unique(iterable, is_sorted=False): # def _unique(memo, item): # def union(iterable, *iterables): # def intersection(iterable, *iterables): # def _does_other_contain(item): # def take(iterable, amount): # def eat(iterator, amount): # def _get_iter_next(iterator): # def round_robin(*iterables): # def ncycles(iterable, times): # def identity(arg): # def loob(arg): # def always(_): # def never(_): # def constant(c): # def _func(*args, **kwargs): # def nothing(*args, **kwargs): . Output only the next line.
self.assertTrue(functional.some(lambda w: w > 0, [0, -1, 4, 6]))
Using the snippet: <|code_start|># Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ :module: mom.security.rsa.pycrypto :synopsis: PyCrypto RSA implementation wrapper. .. autoclass:: PrivateKey .. autoclass:: PublicKey """ from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" <|code_end|> , determine the next line of code. You have imports: from Crypto import PublicKey from mom.security.rsa import keys and context (class names, function names, or code) available: # Path: mom/security/rsa/keys.py # ZERO_BYTE = _compat.ZERO_BYTE # SHA1_DIGESTINFO = b("""\ # \x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14""") # SHA1_DIGESTINFO_LEN = len(SHA1_DIGESTINFO) # ZERO_ONE_BYTES = b("\x00\x01") # FF_BYTE = b("\xff") # def pkcs1_v1_5_encode(key_size, data): # def __init__(self, # key_info, # encoded_key, # encoding, # *unused_args, # **unused_kwargs): # def encoded_key(self): # def encoding(self): # def key(self): # def size(self): # def key_info(self): # def sign(self, digest): # def verify(self, digest, signature_bytes): # def pkcs1_v1_5_sign(self, digest): # def pkcs1_v1_5_verify(self, digest, signature_bytes): # def _sign(self, digest): # def _verify(self, digest, signature): # class Key(object): # class PrivateKey(Key): # class PublicKey(Key): . Output only the next line.
class PrivateKey(keys.PrivateKey):
Continue the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" class Test__pure_is_prime(unittest2.TestCase): def test_pure_is_prime_for_sieves(self): for i in [10, 100, 1000, 10000]: <|code_end|> . Use current file imports: import unittest2 from mom import _prime_sieve from mom import math and context (classes, functions, or code) from other files: # Path: mom/_prime_sieve.py # def make_prime_sieve(max_n): # def _numpy_primesfrom2to(max_n): # def make_prime_sieve(max_n): # def _rwh_primes1(max_n): # # Path: mom/math.py # def gcd(num_a, num_b): # def lcm(num_a, num_b): # def inverse_mod(num_a, num_b): # def exact_log2(number): # def _pure_pow_mod(base, power, modulus): # def _pure_is_prime(num, iterations=5, _sieve=prime_sieve.SIEVE): # def generate_random_prime(bits): # def generate_random_safe_prime(bits): . Output only the next line.
sieve = _prime_sieve.make_prime_sieve(i)
Based on the snippet: <|code_start|># Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" class Test__pure_is_prime(unittest2.TestCase): def test_pure_is_prime_for_sieves(self): for i in [10, 100, 1000, 10000]: sieve = _prime_sieve.make_prime_sieve(i) odds = [] for x in sieve: <|code_end|> , predict the immediate next line with the help of imports: import unittest2 from mom import _prime_sieve from mom import math and context (classes, functions, sometimes code) from other files: # Path: mom/_prime_sieve.py # def make_prime_sieve(max_n): # def _numpy_primesfrom2to(max_n): # def make_prime_sieve(max_n): # def _rwh_primes1(max_n): # # Path: mom/math.py # def gcd(num_a, num_b): # def lcm(num_a, num_b): # def inverse_mod(num_a, num_b): # def exact_log2(number): # def _pure_pow_mod(base, power, modulus): # def _pure_is_prime(num, iterations=5, _sieve=prime_sieve.SIEVE): # def generate_random_prime(bits): # def generate_random_safe_prime(bits): . Output only the next line.
if not math._pure_is_prime(x, _sieve=[2, 3]):
Predict the next line for this snippet: <|code_start|># # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ :module: mom.security.rsa.keys :synopsis: Implements abstract classes for keys. """ from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" b = builtins.b <|code_end|> with the help of current file imports: from mom import _compat from mom import builtins from mom.codec import integer and context from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/integer.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def bytes_to_uint(raw_bytes): # def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False): , which may contain function names, class names, or code. Output only the next line.
ZERO_BYTE = _compat.ZERO_BYTE
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com> # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ :module: mom.security.rsa.keys :synopsis: Implements abstract classes for keys. """ from __future__ import absolute_import __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" <|code_end|> using the current file's imports: from mom import _compat from mom import builtins from mom.codec import integer and any relevant context from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/integer.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def bytes_to_uint(raw_bytes): # def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False): . Output only the next line.
b = builtins.b
Given the code snippet: <|code_start|> __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" b = builtins.b ZERO_BYTE = _compat.ZERO_BYTE SHA1_DIGESTINFO = b("""\ \x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14""") SHA1_DIGESTINFO_LEN = len(SHA1_DIGESTINFO) ZERO_ONE_BYTES = b("\x00\x01") FF_BYTE = b("\xff") def pkcs1_v1_5_encode(key_size, data): """ Encodes a key using PKCS1's emsa-pkcs1-v1_5 encoding. :author: Rick Copeland <rcopeland@geek.net> :param key_size: RSA key size. :param data: Data :returns: A blob of data as large as the key's N, using PKCS1's "emsa-pkcs1-v1_5" encoding. """ <|code_end|> , generate the next line using the imports in this file: from mom import _compat from mom import builtins from mom.codec import integer and context (functions, classes, or occasionally code) from other files: # Path: mom/_compat.py # INT_MAX = sys.maxsize # INT_MAX = sys.maxint # INT64_MAX = (1 << 63) - 1 # INT32_MAX = (1 << 31) - 1 # INT16_MAX = (1 << 15) - 1 # UINT128_MAX = (1 << 128) - 1 # 340282366920938463463374607431768211455L # UINT64_MAX = 0xffffffffffffffff # ((1 << 64) - 1) # UINT32_MAX = 0xffffffff # ((1 << 32) - 1) # UINT16_MAX = 0xffff # ((1 << 16) - 1) # UINT8_MAX = 0xff # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # MACHINE_WORD_SIZE = 32 # UINT_MAX = UINT32_MAX # MACHINE_WORD_SIZE = 64 # UINT_MAX = UINT64_MAX # LONG_TYPE = long # LONG_TYPE = int # INT_TYPE = long # INTEGER_TYPES = (int, long) # INT_TYPE = int # INTEGER_TYPES = (int,) # BYTES_TYPE = bytes # BYTES_TYPE = str # UNICODE_TYPE = unicode # BASESTRING_TYPE = basestring # HAVE_PYTHON3 = False # UNICODE_TYPE = str # BASESTRING_TYPE = (str, bytes) # HAVE_PYTHON3 = True # ZERO_BYTE = byte_literal("\x00") # EMPTY_BYTE = byte_literal("") # EQUAL_BYTE = byte_literal("=") # PLUS_BYTE = byte_literal("+") # HYPHEN_BYTE = byte_literal("-") # FORWARD_SLASH_BYTE = byte_literal("/") # UNDERSCORE_BYTE = byte_literal("_") # DIGIT_ZERO_BYTE = byte_literal("0") # HAVE_LITTLE_ENDIAN = bool(struct.pack("h", 1) == "\x01\x00") # def byte_ord(byte_): # def byte_ord(byte_): # def byte_literal(literal): # def byte_literal(literal): # def dict_each(func, iterable): # def dict_each(func, iterable): # def next(iterator, default=throw): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(count): # def generate_random_bytes(_): # def get_word_alignment(num, force_arch=64, # _machine_word_size=MACHINE_WORD_SIZE): # class Throw(object): # # Path: mom/builtins.py # def byte(number): # def bytes_leading(raw_bytes, needle=_compat.ZERO_BYTE): # def bytes_trailing(raw_bytes, needle=_compat.ZERO_BYTE): # def bin(number, prefix="0b"): # def hex(number, prefix="0x"): # def is_sequence(obj): # def is_unicode(obj): # def is_bytes(obj): # def is_bytes_or_unicode(obj): # def is_integer(obj): # def integer_byte_length(number): # def integer_byte_size(number): # def integer_bit_length(number): # def integer_bit_size(number): # def integer_bit_count(number): # def is_even(num): # def is_odd(num): # def is_positive(num): # def is_negative(num): # # Path: mom/codec/integer.py # ZERO_BYTE = _compat.ZERO_BYTE # EMPTY_BYTE = _compat.EMPTY_BYTE # def bytes_to_uint(raw_bytes): # def uint_to_bytes(number, fill_size=0, chunk_size=0, overflow=False): . Output only the next line.
size = len(integer.uint_to_bytes(key_size))