Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> ) # noqa return real_extract def hydrometer_adjustment(sg, temp, units=IMPERIAL_UNITS): """ Adjust the Hydrometer if the temperature deviates from 59degF. :param float sg: Specific Gravity :param float temp: Temperature :param str uni...
if units == SI_UNITS:
Given snippet: <|code_start|> def brix_to_sg(brix): """ Degrees Brix to Specific Gravity :param float brix: Degrees Brix :return: Specific Gravity :rtype: float Source: * http://www.brewersfriend.com/brix-converter/ """ return (brix / (258.6 - ((brix / 258.2) * 227.1))) + 1 def ...
raise SugarException(u"Above 40 degBx this function no longer works")
Given snippet: <|code_start|> 1 + attenuation_coeff ) # noqa return real_extract def hydrometer_adjustment(sg, temp, units=IMPERIAL_UNITS): """ Adjust the Hydrometer if the temperature deviates from 59degF. :param float sg: Specific Gravity :param float temp: Temperature :param st...
validate_units(units)
Using the snippet: <|code_start|> """ Adjust the Hydrometer if the temperature deviates from 59degF. :param float sg: Specific Gravity :param float temp: Temperature :param str units: The units :return: Specific Gravity corrected for temperature :rtype: float :raises SugarException: If t...
temp = celsius_to_fahrenheit(temp)
Given snippet: <|code_start|># -*- coding: utf-8 -*- class TestCliAbv(unittest.TestCase): def setUp(self): self.og = 1.057 self.fg = 1.013 def test_get_abv(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import textwrap import unittest from brew.cl...
abv = get_abv(self.og, self.fg)
Based on the snippet: <|code_start|>#! /usr/bin/env python """ Ray Daniels Designing Great Beers Appendix 2: Course Grind Potential Extract Notes: The chart appears to have been developed with the moisture content set to zero (0.0) and the Brew House Efficiency set to 100% (1.0). This is not typical a...
sg = sg_from_dry_basis(
Here is a snippet: <|code_start|>#! /usr/bin/env python """ Ray Daniels Designing Great Beers Appendix 2: Course Grind Potential Extract Notes: The chart appears to have been developed with the moisture content set to zero (0.0) and the Brew House Efficiency set to 100% (1.0). This is not typical and ...
gu = sg_to_gu(sg)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- __all__ = [u"Yeast"] class Yeast(object): """ A representation of a type of Yeast as added to a Recipe. """ def __init__(self, name, percent_attenuation=0.75): """ :param float percent_attenuation: The percentage the yeast ...
raise YeastException(
Given snippet: <|code_start|> out = u"{0}, percent_attenuation={1}".format(out, self.percent_attenuation) out = u"{0})".format(out) return out def __eq__(self, other): if not isinstance(other, self.__class__): return False if (self.name == other.name) and ( ...
validate_optional_fields(yeast_data, optional_fields)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- __all__ = [u"Yeast"] class Yeast(object): """ A representation of a type of Yeast as added to a Recipe. """ def __init__(self, name, percent_attenuation=0.75): """ :param float percent_attenuation: The p...
self.percent_attenuation = validate_percentage(percent_attenuation)
Given the code snippet: <|code_start|> if self.percent_attenuation: out = u"{0}, percent_attenuation={1}".format(out, self.percent_attenuation) out = u"{0})".format(out) return out def __eq__(self, other): if not isinstance(other, self.__class__): return False...
validate_required_fields(yeast_data, required_fields)
Given snippet: <|code_start|> def alcohol_by_volume_standard(og, fg): """ Alcohol by Volume Standard Calculation :param float og: Original Gravity :param float fg: Final Gravity :return: Alcohol by Volume decimal percentage :rtype: float Most brewing sites use this basic formula: :ma...
return (og - fg) * ABV_CONST / 100.0
Predict the next line after this snippet: <|code_start|> equation, giving Alcohol by Weight. This is then converted to Alcohol by Volume multiplying by the ratio of Final Gravity to Density of Ethanol. The alternate equation reports a higher ABV for higher gravity beers. This equation is just a differe...
return abv * ALCOHOL_SPECIFIC_GRAVITY
Predict the next line for this snippet: <|code_start|> Source: * Formula from Balling: De Clerck, Jean, A Textbook Of Brewing, Chapman & Hall Ltd., 1958 * http://beersmith.com/blog/2010/09/07/apparent-and-real-attenuation-for-beer-brewers-part-1/ * http://beersmith.com/blog/2010/09/14/apparent-and-real-...
real_extract = apparent_extract_to_real_extract(original_extract, apparent_extract)
Given the following code snippet before the placeholder: <|code_start|> :param Recipe recipe: A Recipe object :return: True if recipe matches style, otherwise False :rtype: bool """ if ( self.og_matches(recipe.og) and self.fg_matches(recipe.fg) ...
except ColorException:
Here is a snippet: <|code_start|> :param str style: The style name :param list(float) og: The lower and upper original gravity :param list(float) fg: The lower and upper final gravity :param list(float) abv: The lower and upper alcohol by volume :param list(float) ibu: The lower a...
raise StyleException(u"Must provide value_list for {}".format(name))
Given the code snippet: <|code_start|> return errors def to_dict(self): style_dict = { u"style": self.style, u"category": self.category, u"subcategory": self.subcategory, u"og": self.og, u"fg": self.fg, u"abv": self.abv, ...
validate_required_fields(recipe, required_fields)
Next line prediction: <|code_start|>def main(): recipe = { u"name": u"10 Pound Stout (Extract)", u"start_volume": 4.0, u"final_volume": 5.0, u"grains": [ {u"name": u"Amber Liquid Extract", u"weight": 7.0, u"grain_type": u"lme"}, {u"name": u"Dark Dry Extract",...
loader = JSONDataLoader(data_dir)
Based on the snippet: <|code_start|> recipe = { u"name": u"10 Pound Stout (Extract)", u"start_volume": 4.0, u"final_volume": 5.0, u"grains": [ {u"name": u"Amber Liquid Extract", u"weight": 7.0, u"grain_type": u"lme"}, {u"name": u"Dark Dry Extract", u"weight": ...
beer = parse_recipe(recipe, loader)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- class TestRecipeExtract(unittest.TestCase): def setUp(self): # Define Recipes self.recipe = recipe self.recipe_lme = recipe_lme self.recipe_dme = recipe_dme <|code_end|> using the current file's impor...
self.assertEquals(self.recipe.units, IMPERIAL_UNITS)
Given the code snippet: <|code_start|> return srm * 1.97 def ebc_to_srm(ebc): """ Convert EBC to SRM Color :param float ebc: EBC Color :return: SRM Color :rtype: float """ return ebc / 1.97 def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS): """ C...
final_volume = final_volume * GAL_PER_LITER
Given the code snippet: <|code_start|> u"calculate_srm", u"lovibond_to_srm", u"srm_to_lovibond", u"srm_to_a430", u"ebc_to_a430", ] def srm_to_ebc(srm): """ Convert SRM to EBC Color :param float srm: SRM Color :return: EBC Color :rtype: float """ return srm * 1.97 def ...
def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS):
Next line prediction: <|code_start|> """ return srm * 1.97 def ebc_to_srm(ebc): """ Convert EBC to SRM Color :param float ebc: EBC Color :return: SRM Color :rtype: float """ return ebc / 1.97 def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_UNITS): """...
grain_weight = grain_weight * POUND_PER_KG
Here is a snippet: <|code_start|> :rtype: float """ return srm * 1.97 def ebc_to_srm(ebc): """ Convert EBC to SRM Color :param float ebc: EBC Color :return: SRM Color :rtype: float """ return ebc / 1.97 def calculate_mcu(grain_weight, beer_color, final_volume, units=IMPERIAL_...
if units == SI_UNITS:
Based on the snippet: <|code_start|> Calculate MCU from Grain :param float grain_weight: Grain weight in lbs or kg :param float beer_color: Beer color in deg Lovibond :param float final_volume: Final Volume in gal or liters :param str units: The units Source: * http://beersmith.com/blog/20...
raise ColorException(u"Mosher equation does not work for MCU < 7.0")
Using the snippet: <|code_start|> :return: EBC Color :rtype: float """ return srm * 1.97 def ebc_to_srm(ebc): """ Convert EBC to SRM Color :param float ebc: EBC Color :return: SRM Color :rtype: float """ return ebc / 1.97 def calculate_mcu(grain_weight, beer_color, final_...
validate_units(units)
Here is a snippet: <|code_start|>def main(): print("Enzymatic rests schedule") liquor_to_grist_ratio = 1.5 # qt:lbs grain_weight = 8.0 # lbs water_volume = grain_weight * liquor_to_grist_ratio # qt print("") print("Starting with {} lbs of grain".format(grain_weight)) target_temp = 110...
infusion_volume = mash_infusion(
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- def main(): print("Enzymatic rests schedule") liquor_to_grist_ratio = 1.5 # qt:lbs grain_weight = 8.0 # lbs water_volume = grain_weight * liquor_to_grist_ratio # qt print(""...
sk_temp = strike_temp(
Given snippet: <|code_start|># -*- coding: utf-8 -*- class TestCliTemp(unittest.TestCase): def setUp(self): self.c = 15.6 self.f = 60.1 def test_get_sugar_conversion_fahrenheit(self): out = get_temp_conversion(self.f, None) self.assertEquals(out, self.c) def test_get_sug...
self.parser = get_parser()
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class TestCliTemp(unittest.TestCase): def setUp(self): self.c = 15.6 self.f = 60.1 def test_get_sugar_conversion_fahrenheit(self): <|code_end|> , generate the next line using the imports in this file: import unittest from brew.cl...
out = get_temp_conversion(self.f, None)
Based on the snippet: <|code_start|> expected = {u"celsius": 25.0, u"fahrenheit": None} self.assertEquals(out.__dict__, expected) def test_get_parser_fahrenheit(self): args = [u"-f", u"62.0"] out = self.parser.parse_args(args) expected = {u"celsius": None, u"fahrenheit": 62.0...
self.main = main
Here is a snippet: <|code_start|> :param float grain: Weight of Grain :return: DME Weight :rtype: float """ return malt * 3.0 / 5.0 def specialty_grain_to_liquid_malt_weight(grain): """ Specialty Grain to LME Weight :param float grain: Weight of Specialty Grain :return: LME Weight...
def fine_grind_to_coarse_grind(fine_grind, fc_diff=FC_DIFF_TWO_ROW):
Given snippet: <|code_start|> :param float brew_house_efficiency: The efficiency in decimal form :return: Specific Gravity available from Malt :rtype: float """ # noqa validate_percentage(dbcg) validate_percentage(moisture_content) validate_percentage(moisture_correction) validate_percen...
return basis_percentage * LITERS_OF_WORT_AT_SG
Continue the code snippet: <|code_start|> """ Dry Basis to As-Is Basis Percentage :param float dry_basis: A percentage from the malt bill in decimal form :param float moisture_content: A percentage of moisture content in finished malt in decimal form :return: As-Is Basis :rtype: float """ #...
moisture_correction=MOISTURE_CORRECTION,
Based on the snippet: <|code_start|> def fine_grind_to_coarse_grind(fine_grind, fc_diff=FC_DIFF_TWO_ROW): """ Fine Grind to Coarse Grind Percentage :param float fine_grind: A percentage from the malt bill :param float fc_diff: The F/C difference percentage from the malt bill :return: Coarse Grind ...
def dry_basis_to_as_is_basis(dry_basis, moisture_content=MOISTURE_FINISHED_MALT):
Given snippet: <|code_start|> Ldeg/kg means how many litres of wort with a specific gravity of 1.001 you could produce from a kilogram of the fermentable For example, if you had a kilogram of sucrose, you could make up 386 litres of wort with a specific gravity of 1.001. """ validate_percentage...
return ppg * PPG_TO_HWE_CONVERSION
Based on the snippet: <|code_start|> (dbcg - moisture_content - moisture_correction) * brew_house_efficiency * SUCROSE_PPG ) return gu_to_sg(gu) def plato_from_dry_basis( dbcg, moisture_content=MOISTURE_FINISHED_MALT, moisture_correction=MOISTURE_CORRECTION, brew_house_e...
* SUCROSE_PLATO
Predict the next line for this snippet: <|code_start|> :rtype: float """ # noqa validate_percentage(as_is) validate_percentage(moisture_content) return as_is / (1.0 - moisture_content) def sg_from_dry_basis( dbcg, moisture_content=MOISTURE_FINISHED_MALT, moisture_correction=MOISTURE_CO...
* SUCROSE_PPG
Given the code snippet: <|code_start|> """ Specialty Grain to LME Weight :param float grain: Weight of Specialty Grain :return: LME Weight :rtype: float """ return grain * 0.89 def liquid_malt_to_specialty_grain_weight(malt): """ LME to Specialty Grain Weight :param float grai...
validate_percentage(fine_grind)
Continue the code snippet: <|code_start|> validate_percentage(as_is) validate_percentage(moisture_content) return as_is / (1.0 - moisture_content) def sg_from_dry_basis( dbcg, moisture_content=MOISTURE_FINISHED_MALT, moisture_correction=MOISTURE_CORRECTION, brew_house_efficiency=0.90, ): ...
return gu_to_sg(gu)
Given the code snippet: <|code_start|> html = value['html'] try: pdf = pisa.CreatePDF( StringIO(html.encode('utf-8')), buff, encoding='utf-8' ) except AttributeError: raise SethRendererException(u"Error generating PDF file.") if pd...
writer = UnicodeWriter(buff, encoding='utf-8')
Given the code snippet: <|code_start|> class Model(object): json_included = [] json_excluded = [] __table_args__ = {} def _get_attrs_to_include(self): return self.json_included @declared_attr def manager(cls): # manager is a class that can have some additional methods ...
@classproperty
Given the following code snippet before the placeholder: <|code_start|> class Model(object): json_included = [] json_excluded = [] __table_args__ = {} def _get_attrs_to_include(self): return self.json_included @declared_attr def manager(cls): # manager is a class that can h...
return BaseManager(model_class=cls)
Given the code snippet: <|code_start|> def get(self, **kwargs): return self.not_allowed() def post(self, **kwargs): return self.not_allowed() def put(self, **kwargs): return self.not_allowed() def delete(self, **kwargs): return self.not_allowed() def patch(self, **...
paginate = True
Using the snippet: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- class Handler(object): def __init__(self): super(Handler, self).__init__() self.timestamp = None self.proto = None self.src_ip = None self.dst_ip = None self.sport = None self.dpor...
self.log = Logger("TCP Protocol Handler", "DEBUG")
Using the snippet: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- sys.path.append("../") class Handler: def __init__(self, debug_mode="DEBUG"): <|code_end|> , determine the next line of code. You have imports: import sys import dpkt from ovizart.modules.traffic.log.logger import Logger and context...
self._logger = Logger(log_name="Pcap Handler", log_mode=debug_mode)
Here is a snippet: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- class Handler(object): def __init__(self): super(Handler, self).__init__() self.timestamp = None self.proto = None self.src_ip = None self.dst_ip = None self.sport = None self.dpor...
self.log = Logger("TCP Protocol Handler", "DEBUG")
Continue the code snippet: <|code_start|> class Handler(object): def __init__(self): super(Handler, self).__init__() def get_flow_ips(self, **args): result = self.read_conn_log(args['path'], args['parent_hash_value'], args['user_id']) return result def read_conn_log(self, path, pa...
check = FlowDetails.objects.filter(parent_hash_value=parent_hash_value, user_id=user_id, src_ip=tmp[0], sport=int(tmp[1]),
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- class Handler(object): def __init__(self): super(Handler, self).__init__() <|code_end|> , predict the next line using imports from the current file: from ovizart.modules.traffic.log.logge...
self.log = Logger("Base Protocol Handler", "DEBUG")
Predict the next line after this snippet: <|code_start|> rest_api = Api(api_name='rest') rest_api.register(AppProtocolResource()) rest_api.register(AppProtocolVisualizePacketSizeResource()) <|code_end|> using the current file's imports: from django.conf.urls.defaults import * from django.conf import settings from t...
rest_api.register(AppProtocolVisualizePacketCountResource())
Here is a snippet: <|code_start|> rest_api = Api(api_name='rest') rest_api.register(AppProtocolResource()) rest_api.register(AppProtocolVisualizePacketSizeResource()) rest_api.register(AppProtocolVisualizePacketCountResource()) <|code_end|> . Write the next line using the current file imports: from django.conf.urls....
rest_api.register(AllProtocolsResource())
Next line prediction: <|code_start|> rest_api = Api(api_name='rest') rest_api.register(AppProtocolResource()) rest_api.register(AppProtocolVisualizePacketSizeResource()) rest_api.register(AppProtocolVisualizePacketCountResource()) rest_api.register(AllProtocolsResource()) <|code_end|> . Use current file imports: (fr...
rest_api.register(AllProtocolsByHashResource())
Given snippet: <|code_start|> rest_api = Api(api_name='rest') rest_api.register(AppProtocolResource()) rest_api.register(AppProtocolVisualizePacketSizeResource()) rest_api.register(AppProtocolVisualizePacketCountResource()) rest_api.register(AllProtocolsResource()) rest_api.register(AllProtocolsByHashResource()) <|co...
rest_api.register(AppProtocolResourceByHash())
Here is a snippet: <|code_start|> rest_api = Api(api_name='rest') rest_api.register(AppProtocolResource()) rest_api.register(AppProtocolVisualizePacketSizeResource()) rest_api.register(AppProtocolVisualizePacketCountResource()) rest_api.register(AllProtocolsResource()) rest_api.register(AllProtocolsByHashResource()) ...
rest_api.register(AppProtocolVisualizePacketSizeByHashResource())
Based on the snippet: <|code_start|> rest_api = Api(api_name='rest') rest_api.register(AppProtocolResource()) rest_api.register(AppProtocolVisualizePacketSizeResource()) rest_api.register(AppProtocolVisualizePacketCountResource()) rest_api.register(AllProtocolsResource()) rest_api.register(AllProtocolsByHashResource(...
rest_api.register(AppProtocolVisualizePacketCountByHashResource())
Based on the snippet: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- sys.path.append("../") class Handler: def __init__(self, handler, debug_mode="DEBUG"): self.pcap = handler.get_pcap() self.pcap_handler = handler <|code_end|> , predict the immediate next line with the help of impor...
self._logger = Logger(log_name="Flow Handler", log_mode=debug_mode)
Continue the code snippet: <|code_start|> continue #src_ip = self.ip.src #dst_ip = self.ip.dst # for human readable ip # from socket import inet_ntoa # inet_ntoa(dst_ip) if self.pcap_handler.get_filter_type() == "TCP": ...
random_key = generate_random_name(10)
Predict the next line for this snippet: <|code_start|># Create your views here. def login_user(request): log = Logger("Login form", "DEBUG") form = None logged = False if request.session.has_key('logged_in'): logged = True if logged or request.method == "POST": <|code_end|> with the ...
form = LoginForm(request.POST)
Continue the code snippet: <|code_start|> summary_protocol = protocol summaries = PacketDetails.objects.filter(protocol=proto_dict[protocol]) summary = filter(lambda x: x.timestamp.year == int(date), summaries) paginator = Paginator(summary, 15) # Make sure page request is an int. If not, d...
flows = Flow.objects.all().order_by("-upload_time")
Using the snippet: <|code_start|> context = { 'form': form, 'page_title': 'Login Page' } return render_to_response("main/login.html", context, context_instance=RequestContext(request)) def logout_user(request): if request.session.has_key('uploaded_hash'): ...
summaries = FlowDetails.objects.filter(protocol=protocol)
Given the following code snippet before the placeholder: <|code_start|> context_instance=RequestContext(request)) def logout_user(request): if request.session.has_key('uploaded_hash'): del request.session['uploaded_hash'] if request.session.has_key('uploaded_file_name'): del request....
summaries = PacketDetails.objects.filter(protocol=proto_dict[protocol])
Given snippet: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- #hachoir related imports class Handler: def __init__(self): self.file_path = None self.file_name = None self.stream = None self.data = None <|code_end|> , continue by predicting the next line. Consider curre...
self.log = Logger("File Handler", "DEBUG")
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- #hachoir related imports class Handler: def __init__(self): self.file_path = None self.file_name = None self.stream = None self.data = None self.log = Logger("File Handler"...
new_dir = generate_name_from_timestame()
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python #-*- coding: UTF-8 -*- RESCAN_URL = "https://www.virustotal.com/vtapi/v2/file/rescan" API_KEY = "891c2810d3931fac5af1a2861ac9db18e508a972bb1eaa03d0b43428938d4b93" HOST = "www.virustotal.com" SCAN_URL = "https://www.virustotal.com/vtapi/v2/fi...
self.md5_handler = MD5Handler()
Here is a snippet: <|code_start|> self.file_name_li = [] self.flow = None self.toProcess = dict() self.reportRoot = None self.streamcounter = 0 def get_flow_ips(self, **args): path = args['path'] file_name = args['file_name'] self.reportRoot = path ...
pcap = Pcap.objects.get(id = pcap.id)
Based on the snippet: <|code_start|> self.report_SMTP(f, smtp_details) def process_SMTP(self, aFile): a = False b = False for i in self.toProcess[aFile]['raw']: if a and i.startswith("MAIL FROM"): a = False if b and i == ".": ...
smtp_details = SMTPDetails.objects.create(login_data=self.toProcess[aFile]['logindata'],
Given the following code snippet before the placeholder: <|code_start|> smtp_details = self.process_SMTP(f) self.report_SMTP(f, smtp_details) def process_SMTP(self, aFile): a = False b = False for i in self.toProcess[aFile]['raw']: if a and i.startswith("...
flow_details = FlowDetails.objects.get(src_ip=src_ip, sport=sport, dst_ip=dst_ip, dport=dport)
Next line prediction: <|code_start|>""""ML-ENSEMBLE Testing suite for Layer and Transformer """ def test_fit(): """[Parallel | Layer | Threading | Subset | No Proba | No Prep] test fit""" args = get_layer('fit', 'threading', 'subsemble', False, False) <|code_end|> . Use current file imports: (from mlens.tes...
run_layer(*args)
Based on the snippet: <|code_start|> ... [-1, -2, -3, -4, -5] Warning: this function is experimental and subject to change in a future version of joblib. .. versionadded:: 0.10 """ if isinstance(backend, _basestring): backend = BACKENDS[backend](**backend_params) old_backend_an...
method = get_start_method().strip() or None
Based on the snippet: <|code_start|>"""ML-ENSEMBLE :author: Sebastian Flennerhag :copyright: 2017-2018 :licence: MIT """ from __future__ import division, print_function <|code_end|> , predict the immediate next line with the help of imports: from ..externals.sklearn.base import BaseEstimator, TransformerMixin an...
class Subset(BaseEstimator, TransformerMixin):
Predict the next line for this snippet: <|code_start|>"""ML-ENSEMBLE :author: Sebastian Flennerhag :copyright: 2017-2018 :licence: MIT """ from __future__ import division, print_function <|code_end|> with the help of current file imports: from ..externals.sklearn.base import BaseEstimator, TransformerMixin and ...
class Subset(BaseEstimator, TransformerMixin):
Here is a snippet: <|code_start|>"""ML-Ensemble :author: Sebastian Flennerhag :license: MIT :copyright: 2017-2018 Functions for base computations """ from __future__ import division def load(path, name, raise_on_exception=True): """Utility for loading from cache""" if isinstance(path, str): f = os...
obj = _load(f, raise_on_exception)
Given snippet: <|code_start|> if len(p.shape) == 1: pred[:, col] = p else: pred[:, col:(col + p.shape[1])] = p else: r = n - pred.shape[0] if isinstance(tei[0], tuple): if len(tei) > 1: idx = np.hstack([np.arange(t0 - r, t1 - r) for...
(name, inst_name, exc), MetricWarning)
Continue the code snippet: <|code_start|> # Iterate over flattened parameter collection if isinstance(lpar, (list, set, tuple)): for p1, p2 in zip(lpar, rpar): check_params(p1, p2) # --- param check --- _pass = True if lpar is None or rpar is None: # None parameters are ...
(lpar, rpar), ParameterChangeWarning)
Here is a snippet: <|code_start|>except ImportError: try: # Try get performance counter except ImportError: # Fall back on wall clock ############################################################################### def pickled(name): """Filetype enforcer""" if not name.endswith('.pkl'): name =...
s, lim = get_ivals()
Given the code snippet: <|code_start|>def pickle_save(obj, name): """Utility function for pickling an object""" with open(pickled(name), 'wb') as f: pickle.dump(obj, f) def pickle_load(name): """Utility function for loading pickled object""" with open(pickled(name), 'rb') as f: return ...
raise ParallelProcessingError(
Given the following code snippet before the placeholder: <|code_start|> """Filetype enforcer""" if not name.endswith('.pkl'): name = '.'.join([name, 'pkl']) return name def pickle_save(obj, name): """Utility function for pickling an object""" with open(pickled(name), 'wb') as f: pic...
ParallelProcessingWarning)
Predict the next line for this snippet: <|code_start|> if name not in tmp: # Set up data struct for name tmp[name] = _dict() for k in data_dict.keys(): tmp[name][k] = list() if '%s-m' % k not in data: data['%s-m' % k] = _dic...
"Details: %r" % (k, v, exc), MetricWarning)
Based on the snippet: <|code_start|> if estimator is not None: if isinstance(estimator, six.string_types): estimator_name = estimator.lower() else: estimator_name = estimator.__class__.__name__.lower() estimator_name = "[%s] " % estimator_name else: estima...
LayerSpecificationWarning)
Continue the code snippet: <|code_start|> estimator_name = "" return estimator_name def check_ensemble_build(inst, attr='stack'): """Check that layers have been instantiated.""" if not hasattr(inst, attr): # No layer container. This should not happen! msg = ("No layer class attach...
raise LayerSpecificationError(msg % inst.__class__.__name__)
Next line prediction: <|code_start|> msg = ("Unexpected format of 'preprocessing'. Needs to be " " of type 'None' or 'list' or 'dict'. Got %s .") raise LayerSpecificationError(msg % type(preprocessing)) if not isinstance(estimators, dict): msg = ("Unexpecte...
raise ParallelProcessingError(msg)
Using the snippet: <|code_start|> "estimator cases: %r\npreprocessing cases: %r") raise LayerSpecificationError(msg % (list(estimators), list(preprocessing))) if not all(prep_check): msg = ("Too few preprocessing case...
ParallelProcessingWarning)
Predict the next line for this snippet: <|code_start|> fitted instance with stored sample. """ self.train_shape = X.shape sample_idx = {} for i in range(2): dim_size = min(X.shape[i], self.size) sample_idx[i] = permutation(X.shape[i])[:dim_size] ...
raise NotFittedError("This IdTrain instance is not fitted yet.")
Next line prediction: <|code_start|>"""ML-ENSEMBLE :author: Sebastian Flennerhag :copyright: 2017-2018 :licence: MIT Class for identifying a training set after an estimator has been fitted. Used for determining whether a `predict` or `transform` method should use cross validation to create predictions, or estimators ...
class IdTrain(BaseEstimator):
Given the code snippet: <|code_start|> assert len(cm.cpu) == 2 assert len(cm.rss) == 2 assert len(cm.vms) == 2 def test_cm_exception(): """[Utils] CMLog: test collecting un-monitored returns None.""" if psutil is not None and not __version__.startswith('2.'): cm = utils.CMLog(v...
config.set_ivals(0.1, 0.1)
Continue the code snippet: <|code_start|>try: except ImportError: psutil = None __version__ = sysconfig.get_python_version() # An object to pickle d = {'entry1': 'test', 'entry2': 'also_test'} class Logger(object): """Temporary class redirect print messages to a python object.""" def __init__(self): ...
utils.print_time(t0, message='test', file=logger)
Here is a snippet: <|code_start|> def test_cm_exception(): """[Utils] CMLog: test collecting un-monitored returns None.""" if psutil is not None and not __version__.startswith('2.'): cm = utils.CMLog(verbose=False) with open(os.devnull, 'w') as f, redirect_stdout(f): out = cm.collec...
ParallelProcessingError,
Predict the next line for this snippet: <|code_start|> Parameters ---------- arr : array Returns ------- out : list Examples -------- >>> import numpy as np >>> from mlens.index.base import make_tuple >>> _make_tuple(np.array([0, 1, 2, 5, 6, 8, 9, 10])) [(0, 3), (5, 7),...
class BaseIndex(BaseEstimator):
Continue the code snippet: <|code_start|> list_of_files = [] names = [] # i am not really sure why we need multiline here # is it because start of line char is just matching speakid = re.compile(r'^# %s=(.*)' % re.escape(feature), re.MULTILINE) # if passed a dir, do it for every file if...
if isinstance(dirs_to_do, STRINGTYPE):
Using the snippet: <|code_start|> try: shutil.copytree(pth, newpth) except OSError: shutil.rmtree(newpth) shutil.copytree(pth, newpth) files = get_filepaths(newpth) names = [] metadata = [] for f in files: good_data = [] fo, enc = saferead(f) data ...
if PYTHON_VERSION == 2:
Predict the next line after this snippet: <|code_start|> downloaded_dir = os.path.join(home, 'corenlp') if not os.path.isdir(downloaded_dir): os.makedirs(downloaded_dir) else: poss_zips = glob.glob(os.path.join(downloaded_dir, 'stanford-corenlp-full*.zip')) ...
selection = INPUTFUNC(txt)
Here is a snippet: <|code_start|> print("%s: Couldn't find Tregex in %s." % (thetime, ', '.join(possible_paths))) return False if not query: query = 'NP' # if checking for trees, use the -T option if check_for_trees: options = ['-o', '-T'] ...
if isinstance(corpus, STRINGTYPE):
Next line prediction: <|code_start|> else: start = ' '.join([w for w, p, i in start]) end = ' '.join([w for w, p, i in end]) return ixs[0], start, middle, end def tgrep(parse_string, search): """ Uses tgrep to search a parse tree string :param parse_string: A bracketed ...
mode = 'w' if PYTHON_VERSION == 2 else 'wb'
Next line prediction: <|code_start|> else: filtermode = True elif hasattr(corpus, 'path'): tregex_command.append(corpus.path) if filtermode: tregex_command.append('-filter') if not filtermode: res = subproce...
selection = INPUTFUNC('\n%s: Error parsing Tregex expression "%s".'\
Given the code snippet: <|code_start|> locs = locals() try: get_ipython().getoutput() except TypeError: have_ipython = True except NameError: have_ipython = False try: except ImportError: pass # new ipython error except AttributeError: have_...
if isinstance(denominator, STRINGTYPE) and denominator.lower() == 'self':
Next line prediction: <|code_start|> showing = 'subcorpora' if getattr(self, 'subcorpora', False): sclen = len(self.subcorpora) else: showing = 'files' sclen = len(self.files) show = 'Corpus at %s:\n\nData type: %s\nNumber of %s: %d\n' % ( ...
classname(self), os.path.basename(self.path), len(ssubcorpora))
Continue the code snippet: <|code_start|> can be parsed, and only parsed/tokenised corpora can be interrogated. """ def __init__(self, path, **kwargs): # levels are 'c' for corpus, 's' for subcorpus and 'f' for file. Which # one is determined automatically below, and processed accordingly. ...
elif isinstance(path, STRINGTYPE):
Given the code snippet: <|code_start|> rot=rot) return nplt def copy(self): copied = {} for k, v in self.items(): copied[k] = v return Interrodict(copied) # check what environment we're in tk = checkstack('tkinter') running_python_tex = checkstack...
if isinstance(save, STRINGTYPE):
Given the following code snippet before the placeholder: <|code_start|> unparsed_corpus_path = os.path.abspath(unparsed_corpus_path) # move it into project if fileparse: datapath = project_path else: datapath = join(project_path, 'data') if isdir(datapath): newp = join(d...
check_do_folderise = INPUTFUNC("Your corpus has multiple files, but no subcorpora. "\
Predict the next line for this snippet: <|code_start|> def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] if (parse or tokenise) and coref: # this loop shortens files containing more than 500 lines, # for corenlp memory's sake. maybe user needs a warn...
if PYTHON_VERSION == 2: