Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|> .. versionchanged:: 3.2
Added ``fmt`` and ``datefmt`` arguments.
"""
logging.Formatter.__init__(self, datefmt=datefmt)
self._fmt = fmt
self._colors = {}
if color and _stderr_supports_color():
#... | assert isinstance(message, basestring_type) # guaranteed by logging |
Based on the snippet: <|code_start|> try:
ret = fn(*args, **kwargs)
except:
exc = sys.exc_info()
top = contexts[1]
# If there was exception, try to handle it by going through the exception chain
if top is... | raise_exc_info(exc) |
Predict the next line after this snippet: <|code_start|># ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR... | with handle_exit(append=True): |
Given snippet: <|code_start|># (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ... | SWMR_SYNC.start_read(self.file) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright 2009 Facebook
# Modifications copyright 2016 Meteotest
#
# 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 a... | if PY3: |
Next line prediction: <|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 l... | if not isinstance(value, unicode_type): |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
django.setup()
# pylint: disable=wrong-import-position
def do_build_bulletin(bulletin_id):
if bulletin_id == cavedb.utils.GLOBAL_BULLETIN_ID:
<|code_end|>
, predict the immediate next line with the help of imports:... | write_global_bulletin_files() |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
django.setup()
# pylint: disable=wrong-import-position
def do_build_bulletin(bulletin_id):
if bulletin_id == cavedb.utils.GLOBAL_BULLETIN_ID:
write_global_bulletin_files()
else:
bulletin = caved... | write_bulletin_files(bulletin) |
Next line prediction: <|code_start|>#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
django.setup()
# pylint: disable=wrong-import-position
def do_build_bulletin(bulletin_id):
if bulletin_id == cavedb.utils.GLOBAL_BULLETIN_ID:
write_global_bulletin_files()
else:
bulletin = caved... | run_buildscript(bulletin_id) |
Given the following code snippet before the placeholder: <|code_start|> continue
ret += '<a href="%s/region/%s/map/%s">%s %s</a><br/>\n' % \
(baseurl, region.id, gismap.name, gismap.name, region.region_name)
ret += '<br/>\n'
return... | matches = regex.match(get_request_uri()) |
Given the following code snippet before the placeholder: <|code_start|>
class BulletinRegion(models.Model):
bulletin = models.ForeignKey(Bulletin)
region_name = models.CharField(max_length=64)
map_region_name = models.CharField(max_length=64, blank=True, null=True)
introduction = models.TextField(blank... | .complex_filter({'bulletin__id__in': get_valid_bulletins()})) |
Predict the next line for this snippet: <|code_start|># SPDX-License-Identifier: Apache-2.0
class MapserverMapfile(cavedb.docgen_common.Common):
def __init__(self, bulletin):
cavedb.docgen_common.Common.__init__(self)
self.bulletin = bulletin
self.gis_maps = {}
def gis_map(self, gism... | gis_options['path'] = get_bulletin_mapserver_mapfile(self.bulletin.id, gismap.name) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class TestFileBroker(fake_env.TestFakeFs):
def test_pushpull1(self):
fb = filebroker.FileBroker('bla', create = True)
fb.push_metafile('citekey1', 'abc')
fb.push_bibfile('citekey1', 'cdef')
self.assertEqual(fb.pull_meta... | bib_content = content.read_text_file('testrepo/bib/Page99.bib') |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class TestTag(unittest.TestCase):
def test_parse_tags(self):
self.assertEqual(['+abc', '+def9'], _parse_tag_seq('abc+def9'))
self.assertEqual(['+abc', '-def9'], _parse_tag_seq('abc-def9'))
self.assertEqual(['-abc', '-def9'], _parse_... | _tag_groups(_parse_tag_seq('-war+math+romance'))) |
Here is a snippet: <|code_start|>
from __future__ import unicode_literals
class TestDOIStandardization(unittest.TestCase):
def setUp(self):
# some of these come from
# https://stackoverflow.com/questions/27910/finding-a-doi-in-a-document-or-page
self.crossref_dois = (
'10.231... | sdoi = standardize_doi(doi) |
Here is a snippet: <|code_start|> def push_metadata(self, key, meta):
self.meta = meta
def push_cache(name, entries):
if name != 'metacache':
raise AttributeError
class FakeDataBrokerBib(object):
bib = None
def pull_bibentry(self, key):
return self.bib
def pu... | self.metacache = CacheEntrySet(self.databroker_meta, 'metacache') |
Next line prediction: <|code_start|> def __init__(self, error_msg, bibdata):
"""
:param error_msg: specific message about what went wrong
:param bibdata: the data that was unsuccessfully decoded.
"""
super(Exception, self).__init__(error_msg) # make ... | entry[BP_ENTRYTYPE_KEY] = entry.pop(TYPE_KEY) |
Predict the next line after this snippet: <|code_start|>def read_binary_file(filepath, fail=True):
check_file(filepath, fail=fail)
with _open(filepath, 'rb') as f:
content = f.read()
return content
def remove_file(filepath):
check_file(filepath)
os.remove(filepath)
def write_file(filepat... | parsed = urlparse(path) |
Predict the next line after this snippet: <|code_start|> os.remove(filepath)
def write_file(filepath, data, mode='w'):
"""Write data to file.
Data should be unicode except when binary mode is selected,
in which case data is expected to be binary.
"""
check_directory(os.path.dirname(filepath))
... | conn = HTTPConnection(parsed.netloc) |
Based on the snippet: <|code_start|>
# dealing with formatless content
def content_type(path):
parsed = urlparse(path)
if parsed.scheme in ('http', 'https'):
return 'url'
else:
return 'file'
def url_exists(url):
parsed = urlparse(url)
conn = HTTPConnection(parsed.netloc)
conn.... | response = urlopen(path) |
Given snippet: <|code_start|>from __future__ import unicode_literals
# Citekey stuff
TYPE_KEY = 'ENTRYTYPE'
CONTROL_CHARS = ''.join(map(uchr, list(range(0, 32)) + list(range(127, 160))))
CITEKEY_FORBIDDEN_CHARS = '@\'\\,#}{~%/ ' # '/' is OK for bibtex but forbidden
# here since we transform citekeys into filename... | key = unicodedata.normalize('NFKD', ustr(s)).encode('ascii', 'ignore').decode() |
Given the following code snippet before the placeholder: <|code_start|>
DFT_CONFIG_PATH = os.path.expanduser('~/.pubsrc')
class ConfigurationNotFound(IOError):
def __init__(self, path):
super(ConfigurationNotFound, self).__init__(
"No configuration found at path {}. Maybe you need to initi... | default_conf = configobj.ConfigObj(configspec=configspec) |
Using the snippet: <|code_start|>from __future__ import unicode_literals
def compare_yaml_str(s1, s2):
if s1 == s2:
return True
else:
y1 = yaml.safe_load(s1)
y2 = yaml.safe_load(s2)
return y1 == y2
class TestEnDecode(unittest.TestCase):
def test_decode_emptystring(se... | decoder = endecoder.EnDecoder() |
Given the code snippet: <|code_start|>from __future__ import unicode_literals
def compare_yaml_str(s1, s2):
if s1 == s2:
return True
else:
y1 = yaml.safe_load(s1)
y2 = yaml.safe_load(s2)
return y1 == y2
class TestEnDecode(unittest.TestCase):
def test_decode_emptystri... | self.assertIsInstance(bibraw, ustr) |
Given the code snippet: <|code_start|> return CommandAlias(name, definition, description)
class CommandAlias(Alias):
"""Default kind of alias.
- definition is used as a papers command
- other arguments are passed to the command
"""
def command(self, conf, args):
raw_args = ([ar... | class AliasPlugin(PapersPlugin): |
Given the following code snippet before the placeholder: <|code_start|>
def parser(self, parser):
self.parser = parser
p = parser.add_parser(self.name, help=self.description)
p.add_argument('arguments', nargs=argparse.REMAINDER,
help="arguments to be passed to %s" % se... | execute(raw_args) |
Given the code snippet: <|code_start|>
# code for fake fs
real_os = os
real_os_path = os.path
real_open = open
real_shutil = shutil
real_glob = glob
real_io = io
original_exception_handler = uis.InputUI.handle_exception
# needed to get locale.getpreferredencoding(False) (invoked by pyfakefs)
# t... | real_input = input |
Predict the next line for this snippet: <|code_start|> input() returns 'yes'
input() returns 'no'
input() raises IndexError
"""
class UnexpectedInput(Exception):
pass
def __init__(self, inputs, module_list=tuple()):
self.inputs = list(inputs) or []
self.modu... | content.write_file(path_to_file, self()) |
Given the code snippet: <|code_start|>
# code for fake fs
real_os = os
real_os_path = os.path
real_open = open
real_shutil = shutil
real_glob = glob
real_io = io
<|code_end|>
, generate the next line using the imports in this file:
import sys
import io
import os
import shutil
import glob
import l... | original_exception_handler = uis.InputUI.handle_exception |
Here is a snippet: <|code_start|># coding: utf8
from __future__ import unicode_literals
class APITests(unittest.TestCase):
@mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get)
def test_readme(self, reqget):
apis.doi2bibtex('10.1007/s00422-012-0514-6')
apis.... | self.assertIsInstance(bib, ustr) |
Given snippet: <|code_start|># coding: utf8
from __future__ import unicode_literals
class APITests(unittest.TestCase):
@mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get)
def test_readme(self, reqget):
<|code_end|>
, continue by predicting the next line. Consider current ... | apis.doi2bibtex('10.1007/s00422-012-0514-6') |
Given the code snippet: <|code_start|> bib = apis.get_bibentry_from_api('1312.2021', 'arXiv')
entry = bib[list(bib)[0]]
self.assertEqual(entry['arxiv_doi'], '10.1103/INVALIDDOI.89.084044')
@mock.patch('pubs.apis.requests.get', side_effect=mock_requests.mock_requests_get)
def test_arxiv_g... | self.assertTrue(_is_arxiv_oldstyle(arxiv_id)) |
Given the code snippet: <|code_start|> entry = bib[list(bib)[0]]
self.assertTrue(not 'arxiv_doi' in entry)
self.assertEqual(entry['doi'], '10.1186/s12984-017-0305-3')
self.assertEqual(entry['title'].lower(), 'on neuromechanical approaches for the study of biological and robotic grasp and ... | self.assertEqual(_extract_arxiv_id({'id': "http://arxiv.org/abs/0704.0010v1"}), "0704.0010v1") |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
class TestGenerateCitekey(unittest.TestCase):
def test_fails_on_empty_paper(self):
with self.assertRaises(ValueError):
<|code_end|>
, predict the next line using impor... | bibstruct.generate_citekey(None) |
Continue the code snippet: <|code_start|>
def perf_color():
s = str(list(range(1000)))
for _ in range(5000000):
<|code_end|>
. Use current file imports:
import dotdot
from pubs import color
and context (classes, functions, or code) from other files:
# Path: pubs/color.py
# COLOR_LIST = {'black': '0', 'red':... | color.dye_out(s, 'red') |
Continue the code snippet: <|code_start|> for key in pulled.keys():
self.assertEqual(pulled[key], page99_bibentry['Page99'][key])
self.assertEqual(db.pull_bibentry('citekey1'), page99_bibentry)
def test_existing_data(self):
ende = endecoder.EnDecoder()
page99... | self.assertTrue(content.check_file('testrepo/doc/Page99.pdf', fail=False)) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class TestDataBroker(fake_env.TestFakeFs):
def test_databroker(self):
ende = endecoder.EnDecoder()
page99_metadata = ende.decode_metadata(str_fixtures.metadata_raw0)
page99_bibentry = ende.decode_bibdata(str_fixtures.bib... | for db_class in [databroker.DataBroker, datacache.DataCache]: |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class TestDataBroker(fake_env.TestFakeFs):
def test_databroker(self):
ende = endecoder.EnDecoder()
page99_metadata = ende.decode_metadata(str_fixtures.metadata_raw0)
page99_bibentry = ende.decode_bibdata(str_fixtures.bibtex_r... | for db_class in [databroker.DataBroker, datacache.DataCache]: |
Given the following code snippet before the placeholder: <|code_start|> self.colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
self.gf = GoodnessOfFit()
self.df = self.gf.so.df
# Calculate global maximums
self.gm = {}
for run in self.df.run.unique():
... | plt.savefig(rel_path('./plots/mc/mc.pdf')) |
Predict the next line for this snippet: <|code_start|>"""Functions for calculating the intensity of points in a beam."""
def get_beam_props(model, fwhm):
"""Get beam properties.
Args:
model (str): Which model to use.
fwhm (float): FWHM [frac. deg].
Returns:
beam_size, pixel_scal... | place = paths.models() + f'/beams/{model}.npy' |
Using the snippet: <|code_start|>
def __str__(self):
"""How to print the class."""
# Set up title
f = '{:20.19} {:>10} {:>10} {:>10}\n'
t = f.format(self.name, 'Days', f'{self.object_type.title()}s', '%')
line = '-'*len(t.split('\n')[-2].strip()) + '\n'
t += line
... | return pprint(t, output=False) |
Predict the next line for this snippet: <|code_start|>"""Calculate where null points of an Airy pattern lie."""
STEPSIZE = 1e-6
PLOT = True
x_range = np.arange(0, 50, STEPSIZE)
y_range = 4*(j1(x_range)/x_range)**2
nulls = []
# Find where curve changes direction
ind = np.diff(np.sign(np.diff(y_range)))
x_null = x_ra... | plot_aa_style() |
Next line prediction: <|code_start|>"""Calculate where null points of an Airy pattern lie."""
STEPSIZE = 1e-6
PLOT = True
x_range = np.arange(0, 50, STEPSIZE)
y_range = 4*(j1(x_range)/x_range)**2
nulls = []
# Find where curve changes direction
ind = np.diff(np.sign(np.diff(y_range)))
x_null = x_range[1:-1][ind > 0]... | plt.savefig(rel_path('./plots/null_sidelobes.pdf')) |
Given the code snippet: <|code_start|>EXPECTED = {'parkes-htru': [9, 1549 / 0.551 / 24], # N_frbs, N_days
'wsrt-apertif': [9, 1100/24], # 1100 hours
'askap-fly': [20, 32840 / 8 / 24],
'arecibo-palfa': [1, 24.1],
'guppi': [0.4, 81], # 0.4 is my own assumption
... | exp_min, exp_max = poisson_interval(exp_n, sigma=2) |
Here is a snippet: <|code_start|>
def real_rates(surveys=SURVEYS):
"""Calculate the EXPECTED rates (all scaled to a survey)."""
rates = {}
scale_to = surveys[0]
for surv in surveys:
if surv not in EXPECTED:
continue
# Plot EXPECTED rate
exp_n = EXPECTED[surv][0]
... | plot_aa_style() |
Predict the next line after this snippet: <|code_start|> exp = (exp_n/exp_days) / (scale_n/scale_days)
exp_min *= (1/exp_days) / (scale_n/scale_days)
exp_max *= (1/exp_days) / (scale_n/scale_days)
rates[surv] = (exp, exp_min, exp_max)
return rates
def main():
"""Plot real rate... | plt.savefig(rel_path('./plots/rates_rm.pdf')) |
Using the snippet: <|code_start|>"""Show frbpoppy matches analytical models and predict the event rates."""
REMAKE = True
SIZE = 1e4
SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa')
ELEMENTS = {'analytical': True, 'real': True, 'simple': False, 'complex': True}
ALPHAS = np.around... | plot_aa_style(cols=2) |
Predict the next line after this snippet: <|code_start|> elements = []
for i, surv in enumerate(surveys):
c = cmap(i)
line = Line2D([0], [0], color=c)
label = surv
elements.append((line, label))
# Add gap in legend
elements.append((Line2D([0], [0], color='white'), ''))
... | plt.savefig(rel_path('plots/rates_overview.pdf'), bbox_inches='tight') |
Predict the next line after this snippet: <|code_start|> df.loc[df.frb_name == name, 'rate'] = row.rate
df.loc[df.frb_name == name, 'n_bursts'] = row.n_bursts
df.loc[df.frb_name == name, 'exposure'] = row.exposure
return df
def poisson_interval(k, sigma=1):
"""
Use chi-squared info... | plot_aa_style(cols=1) |
Given the code snippet: <|code_start|> width = db.width
width_err = (db.width_error_lower, db.width_error_upper)
n_bursts = db.n_bursts
rate = db.rate
exposure = db.exposure.to_numpy()
# Calculate error bars
low, high = poisson_interval(n_bursts.to_numpy(), sigma=1)
rate_err = (low/expos... | plt.savefig(rel_path('./plots/rate_w_eff_chime.pdf')) |
Predict the next line after this snippet: <|code_start|> """Calculate the mean and std of a lognormal distribution.
See
https://en.wikipedia.org/wiki/Log-normal_distribution
"""
normal_std = np.sqrt(np.log(1 + (std_x**2/mean_x)**2))
normal_mean = np.log(mean_x**2 / np.sqrt(mean_x**2 + std_x**2))... | xy = hist(data, bin_type='log') |
Using the snippet: <|code_start|>"""Plot corner plots showing best fit for rates.
Linked with the ideas in cube.py -> generating a range of parameters.
TODO: In progress
"""
# # Set parameters needed for generating a rate cube
# GENERATE = False
# PLOT = True
vs = {'alpha': np.linspace(-1, -2, 5)[::-1][1:4],
... | filter = os.path.join(paths.populations(), filename) |
Given the following code snippet before the placeholder: <|code_start|> 'li': np.linspace(-2, 0, 5), # Luminosity function index
'si': np.linspace(-2, 2, 5)} # Spectral index
SURVEYS = ('askap-fly', 'fast-crafts', 'parkes-htru', 'wsrt-apertif', 'arecibo-palfa')
def get_pops(alpha='*', li='*', si='*', sur... | rate_err = poisson_interval(pop.source_rate.det, sigma=1) |
Given the following code snippet before the placeholder: <|code_start|>"""Plot corner plots showing best fit for rates.
Linked with the ideas in cube.py -> generating a range of parameters.
TODO: In progress
"""
# # Set parameters needed for generating a rate cube
# GENERATE = False
# PLOT = True
vs = {'alpha': np... | pops.append(unpickle(path)) |
Next line prediction: <|code_start|> return pops
def make_mesh(x_par, y_par, survey):
v = np.zeros([len(vs[x_par]), len(vs[y_par])])
print(x_par, y_par)
for i, x_val in enumerate(vs[x_par]):
for j, y_val in enumerate(vs[y_par]):
print(x_val, y_val)
pops = get_pops(surve... | plot_aa_style() |
Based on the snippet: <|code_start|> im = axes[2, 1].imshow(make_mesh('li', 'si', survey), **args)
fig.colorbar(im, ax=axes[0, 2])
axes[1, 1].set_title(survey)
axes[2, 0].set_xlabel('alpha')
axes[2, 0].set_ylabel('si')
axes[2, 1].set_xlabel('li')
axes[2, 2].set_xlabel('si')
axes[1, 0].se... | plt.savefig(rel_path(f'./plots/corner_{survey}.pdf')) |
Using the snippet: <|code_start|>"""Compare rate calculations per alpha for the two askap settings."""
REMAKE = False
SIZE = 1e4
SURVEYS = ['parkes-htru', 'askap-fly', 'askap-incoh']
ALPHAS = np.around(np.linspace(-0.2, -2.5, 7), decimals=2)
def main():
"""Get detection rates for surveys."""
complex = compl... | plot_aa_style() |
Using the snippet: <|code_start|> complex = complex_rates(remake=REMAKE,
alphas=ALPHAS,
size=SIZE,
surveys=SURVEYS)
# Plot population event rates
plot_rates(complex)
def plot_rates(rates):
"""Plot detection rates for a... | plt.savefig(rel_path('plots/askap_rates.pdf'), bbox_inches='tight') |
Based on the snippet: <|code_start|> self.downloads = os.path.expanduser("~/Downloads")
self.subfolders = ['data',
'frbcat',
'populations',
'surveys',
'models']
self.config = {s: '' for s... | pprint(f"Creating directory {path}") |
Given the code snippet: <|code_start|> self.beam_pattern = 'perfect'
# Un-used
self.strategy = 'regular' # 'follow-up' not implemented
if self.mount_type == 'transit':
# Transit telescopes can't follow-up
self.strategy = 'regular'
# Set beam properti... | path = os.path.join(paths.surveys(), 'surveys.csv') |
Next line prediction: <|code_start|>
M_BURSTS = 1100
N_DAYS = 50
N_SRCS = int(1e5)
R = 5.7
K = 0.34
def get_probabilities(normalise=False):
"""Get the number of bursts per maximum time.
Args:
normalise (type): Whether to normalise at each maximum time, such that
there's a number of burs... | pprint('Masking days') |
Predict the next line for this snippet: <|code_start|> m_bursts = np.arange(0, M_BURSTS, 1)
xx, yy = np.meshgrid(m_bursts, days)
prob = np.full((len(days), len(m_bursts)), np.nan)
# Mask any frbs over the maximum time
time = td.clustered(r=R, k=K, n_srcs=N_SRCS, n_days=N_DAYS, z=0)
pprint('Mask... | plot_aa_style(cols=2) |
Given the code snippet: <|code_start|>
if normalise:
# Normalise at each maximum time (highest chance becomes one)
prob = prob / np.nanmax(prob, axis=0)
return prob
def plot(prob, show=False):
"""Plot the number of bursts seen over a maximum time."""
plot_aa_style(cols=2)
days = ... | plt.savefig(rel_path('./plots/prob_m_bursts.pdf')) |
Predict the next line for this snippet: <|code_start|>
def plot(*pops, files=[], tns=False, show=True,
mute=True, port=5006, print_command=False):
"""
Plot populations with bokeh. Has to save populations before plotting.
Args:
*pops (Population, optional): Add the populations you would li... | pprint(f'Skipping {pop.name} population as no sources') |
Based on the snippet: <|code_start|> files (list, optional): List of population files to plot.
tns (bool, optional): Whether to plot tns parameters. Defaults to
True
show (bool, optional): Whether to display the plot or not. Mainly used
for debugging purposes. Defaults to ... | out = os.path.join(paths.populations(), file_name) |
Here is a snippet: <|code_start|>"""Check a powerlaw implementation generates the right numbers."""
POWER = -1
SIZE = 1e5
pl = gen_dists.powerlaw(1e35, 1e40, POWER, int(SIZE))
minx = min(pl)
maxx = max(pl)
bins = 10 ** np.linspace(np.log10(minx), np.log10(maxx), 50)
hist, edges = np.histogram(pl, bins=bins)
<|code... | plot_aa_style() |
Continue the code snippet: <|code_start|>
POWER = -1
SIZE = 1e5
pl = gen_dists.powerlaw(1e35, 1e40, POWER, int(SIZE))
minx = min(pl)
maxx = max(pl)
bins = 10 ** np.linspace(np.log10(minx), np.log10(maxx), 50)
hist, edges = np.histogram(pl, bins=bins)
plot_aa_style()
fig = plt.figure()
ax = fig.add_subplot(111)
plt.... | plt.savefig(rel_path('plots/powerlaw.pdf')) |
Next line prediction: <|code_start|>"""Do things with frbcat."""
class TNS(BaseTNS):
"""
Add frbpoppy functionality to Frbcat.
Get the pandas dataframe with Frbcat().df
"""
def __init__(self, frbpoppy=True, **kwargs):
"""Initialize."""
<|code_end|>
. Use current file imports:
(import ... | super(TNS, self).__init__(**kwargs, path=paths.frbcat()) |
Next line prediction: <|code_start|> self.df.at[pmsurv, 'survey'] = 'parkes-pmsurv'
htru = cond('Parkes') & (self.df[c].dt.year > 2008)
htru &= (self.df[c].dt.year < 2015)
self.df.at[htru, 'survey'] = 'parkes-htru'
# This means the default survey for Parkes is superb!
supe... | pop = Population() |
Here is a snippet: <|code_start|> Args:
lat (float): Latitude of observatory in radians.
dec (array): Declination of celestial object in radians.
unit (str): 'deg' or 'rad'
beamsize (float): Beam size in sq. deg
Returns:
float: Fraction of time above horizon in fractional... | plot_aa_style() |
Based on the snippet: <|code_start|> """
if unit == 'deg':
lat = np.deg2rad(lat)
dec = np.deg2rad(dec)
times = np.ones_like(dec)
lim = np.pi/2. - lat
always_visible = dec > lim
never_visible = dec < -lim
sometimes_visible = ((dec > -lim) & (dec < lim))
sm = sometimes_vis... | plt.savefig(rel_path('./plots/transit_times.pdf')) |
Given snippet: <|code_start|>
class NE2001Table:
"""Create/use a NE2001 lookup table for dispersion measure."""
def __init__(self, test=False):
"""Initializing."""
self.test = test
self.set_file_name()
# Setup database
self.db = False
self.step = 0.1
sel... | pprint('Losing all progress in calculations') |
Predict the next line for this snippet: <|code_start|>
# Setup database
self.db = False
self.step = 0.1
self.rounding = 2
# For parallel processes
self.temp_path = None
if self.test:
self.step = 0.1
if os.path.exists(self.file_name):
... | uni_mods = os.path.join(paths.models(), 'universe/') |
Predict the next line after this snippet: <|code_start|> """Match up frbs with surveys."""
# Merge survey names
surf = os.path.join(self.path, 'paper_survey.csv')
self._surveys = pd.read_csv(surf)
cols = ['frb_name', 'pub_description']
self.df = pd.merge(self.df, self._su... | pprint('It seems there are new FRBs!') |
Given the code snippet: <|code_start|>"""Do things with frbcat."""
class Frbcat(PureFrbcat):
"""
Add frbpoppy functionality to Frbcat.
Get the pandas dataframe with Frbcat().df
"""
def __init__(self, frbpoppy=True, repeat_bursts=False, mute=False,
**kwargs):
"""Initial... | super().__init__(self, path=paths.frbcat(), **kwargs) |
Here is a snippet: <|code_start|>
if interrupt and any(no_surveys):
cols = ['pub_description', 'frb_name']
ns_df = self.df[no_surveys].drop_duplicates(subset=cols,
keep='first')
pprint('It seems there are new FRBs!')
... | pop = Population() |
Based on the snippet: <|code_start|>
def test_generate_name():
class SomeTestClass(object):
pass
def some_test_function():
pass
<|code_end|>
, predict the immediate next line with the help of imports:
from tensorprob import utilities
and context (classes, functions, sometimes code) from oth... | assert utilities.generate_name(SomeTestClass) == 'SomeTestClass_1' |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
class Min_Func:
def __init__(self, f, names):
self.f = f
self.func_code = make_func_code(names)
self.func_defaults = None
def __call__(self, *args):
return self.f(args)
<|code_end|>
... | class MigradOptimizer(BaseOptimizer): |
Based on the snippet: <|code_start|> all_kwargs['limit_' + n] = b
if gradient:
def mygrad_func(*x):
out = gradient(x)
return out
else:
mygrad_func = None
def objective_(x):
val = objective(x)
if np.i... | return OptimizationResult( |
Given the following code snippet before the placeholder: <|code_start|> super(ScipyLBFGSBOptimizer, self).__init__(**kwargs)
def minimize_impl(self, objective, gradient, inits, bounds):
if gradient is None:
approx_grad = True
else:
approx_grad = False
self.ni... | ret = OptimizationResult() |
Given the code snippet: <|code_start|> logFull('CeWebUi:index')
if self.user_agent() == 'x':
return 0
try:
srv_ver = open(TWISTER_PATH + '/server/version.txt').read().strip()
except:
srv_ver = '-'
srv_type = self.project.server_init['ce_server_... | int_status = self.project.get_user_info(user, 'status') or STATUS_INVALID |
Given snippet: <|code_start|> """ Initial page """
logFull('CeWebUi:index')
if self.user_agent() == 'x':
return 0
try:
srv_ver = open(TWISTER_PATH + '/server/version.txt').read().strip()
except:
srv_ver = '-'
srv_type = self.project.ser... | rev_dict = dict((v, k) for k, v in EXEC_STATUS.iteritems()) |
Predict the next line after this snippet: <|code_start|>
class SendTest(BaseTest):
def setUp(self):
super(SendTest,self).setUp()
<|code_end|>
using the current file's imports:
from test_base import BaseTest, load_msg
from mock import patch
from smtplib import SMTP
from deliver.send import Sender
and a... | self.sender = Sender(self.config) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class ConverterDigestTest(BaseTest):
'''Tests for the DigestMessage class'''
def setUp(self):
super(ConverterDigestTest,self).setUp()
self.msg = DigestMessage([])
def test_find_text(self):
<|code_end|>
, predict the immediate ne... | self.assertEqual(self.msg._find_text(load_msg('sample5')), u'á') |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class ConverterDigestTest(BaseTest):
'''Tests for the DigestMessage class'''
def setUp(self):
super(ConverterDigestTest,self).setUp()
<|code_end|>
, determine the next line of code. You have imports:
from deliver.tests.test_base import BaseTes... | self.msg = DigestMessage([]) |
Given snippet: <|code_start|># This script creates a Distributor and updates regularly its status,
# until a SIGTERM signal is received. The program is not interrupted
# directly, to avoid inconsistent state. As a config file, it takes
# the config.py file that is in the same directory.
logger = logging.getLogger(__... | distributor = OnlineDistributor(py) |
Using the snippet: <|code_start|>
class ReadTest(BaseTest):
def setUp(self):
super(ReadTest,self).setUp()
<|code_end|>
, determine the next line of code. You have imports:
from test_base import BaseTest
from mock import patch
from poplib import POP3
from deliver.read import Reader
and context (class nam... | self.reader = Reader(self.config) |
Here is a snippet: <|code_start|>
class ConverterDownloadTest(BaseTest):
'''Tests for the DownloadMessage class'''
def setUp(self):
super(ConverterDownloadTest,self).setUp()
def _msg(self, urlopen, url, content):
if isinstance(content, file):
content = content.read()
... | msg = self._msg(urlopen, url, open_data('google.html'))
|
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class ConverterDownloadTest(BaseTest):
'''Tests for the DownloadMessage class'''
def setUp(self):
super(ConverterDownloadTest,self).setUp()
def _msg(self, urlopen, url, content):
if isinstance(content, file):
... | return DownloadMessage(url)
|
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class OfflineDistributeTest(BaseTest):
def setUp(self):
super(OfflineDistributeTest,self).setUp()
<|code_end|>
, determine the next line of code. You have imports:
from test_base import BaseTest, load_msg, get_msg, archive_msg, get_digests
from mo... | self.distributor = OfflineDistributor(self.config) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
class OfflineDistributeTest(BaseTest):
def setUp(self):
super(OfflineDistributeTest,self).setUp()
self.distributor = OfflineDistributor(self.config)
<|code_end|>
. Use current file imports:
from test_base import BaseTest, load_msg,... | self.sender = Mock(spec=Sender) |
Using the snippet: <|code_start|>
curdir = None
def init_d():
global curdir
curdir = os.path.abspath(os.path.curdir)
return Daemon(name='deliver', catch_all_log=curdir, pid_dir=curdir)
def run():
daemon = init_d()
daemon.start()
# Undo some of the changes done by start, otherwise it... | prepare()
|
Predict the next line after this snippet: <|code_start|>
curdir = None
def init_d():
global curdir
curdir = os.path.abspath(os.path.curdir)
return Daemon(name='deliver', catch_all_log=curdir, pid_dir=curdir)
def run():
daemon = init_d()
daemon.start()
# Undo some of the changes done... | loop()
|
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class MemberMgrTest(BaseTest):
def setUp(self):
super(MemberMgrTest,self).setUp()
<|code_end|>
. Use current file imports:
(from test_base import BaseTest
from deliver.members import MemberMgr)
and context including class names, function names... | self.memberMgr = MemberMgr(self.config) |
Predict the next line after this snippet: <|code_start|>
class BaseDBWrapper(object):
def _create_tables(self):
metadata = MetaData()
metadata.bind = self.engine
self.messages = self._create_table('messages', metadata,
Column('id', String(192), ... | mapper(Message, self.messages, properties={ |
Based on the snippet: <|code_start|>
class BaseDBWrapper(object):
def _create_tables(self):
metadata = MetaData()
metadata.bind = self.engine
self.messages = self._create_table('messages', metadata,
Column('id', String(192), index=True, primary_... | 'digests': relationship(Digest, backref='msg') |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class ConverterTest(BaseTest):
'''Tests for the UnicodeMessage class'''
def setUp(self):
super(ConverterTest,self).setUp()
<|code_end|>
. Use current file imports:
(from deliver.tests.test_base import BaseTest, load_msg, load_all_msg)
and c... | self.msg = load_msg('sample3') |
Using the snippet: <|code_start|>
def test_get_payload_empty(self):
self.msg = load_msg('sample6')
self._test_get(u'\n', u'\n')
def test_clean_word_no_replace(self):
self.assertEqual(self.msg._clean_word(u'panic', {}), u'panic')
def test_clean_word_replace(self):
self.asser... | for mail in load_all_msg(): |
Predict the next line after this snippet: <|code_start|>
@register.filter(name="format_links")
@safe
def format_links(value, arg=None):
value = link_regex.sub(r'<a href="\2" target=_new>\1</a>', value)
return value
@register.filter(name="format_autolinks")
@safe
def format_autolinks(value, arg=None):
value = aut... | models.actor_url(match.group(1), 'user', request=request), |
Next line prediction: <|code_start|>
try:
except ImportError:
etree = None
class FixturesTestCase(test.TestCase):
fixtures = ['actors', 'streams', 'contacts', 'streamentries',
'inboxentries', 'subscriptions', 'oauthconsumers',
'invites', 'emails', 'ims', 'activations',
... | xmpp.XmppConnection = test_util.TestXmppConnection |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.