Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|> for c_j in range(c_i + 1, n_components):
dist = linkage(dm_i[:, component_labels == c_j])
distance_matrix[c_i, c_j] = dist
distance_matrix[c_j, c_i] = dist
else:
for label in range(n_components):
component_centroids[label] = data[component_labels == label].mean(axis=0)
if scipy.sparse.isspmatrix(component_centroids):
warn(
"Forcing component centroids to dense; if you are running out of "
"memory then consider increasing n_neighbors."
)
component_centroids = component_centroids.toarray()
if metric in SPECIAL_METRICS:
distance_matrix = pairwise_special_metric(
component_centroids,
metric=metric,
kwds=metric_kwds,
)
elif metric in SPARSE_SPECIAL_METRICS:
distance_matrix = pairwise_special_metric(
component_centroids,
metric=SPARSE_SPECIAL_METRICS[metric],
kwds=metric_kwds,
)
else:
if callable(metric) and scipy.sparse.isspmatrix(data):
function_to_name_mapping = {
<|code_end|>
. Write the next line using the current file imports:
from warnings import warn
from sklearn.manifold import SpectralEmbedding
from sklearn.metrics import pairwise_distances
from sklearn.metrics.pairwise import _VALID_METRICS as SKLEARN_PAIRWISE_VALID_METRICS
from umap.distances import pairwise_special_metric, SPECIAL_METRICS
from umap.sparse import SPARSE_SPECIAL_METRICS, sparse_named_distances
import numpy as np
import scipy.sparse
import scipy.sparse.csgraph
and context from other files:
# Path: umap/distances.py
# def pairwise_special_metric(X, Y=None, metric="hellinger", kwds=None):
# if callable(metric):
# if kwds is not None:
# kwd_vals = tuple(kwds.values())
# else:
# kwd_vals = ()
#
# @numba.njit(fastmath=True)
# def _partial_metric(_X, _Y=None):
# return metric(_X, _Y, *kwd_vals)
#
# return pairwise_distances(X, Y, metric=_partial_metric)
# else:
# special_metric_func = named_distances[metric]
# return parallel_special_metric(X, Y, metric=special_metric_func)
#
# SPECIAL_METRICS = (
# "hellinger",
# "ll_dirichlet",
# "symmetric_kl",
# "poincare",
# hellinger,
# ll_dirichlet,
# symmetric_kl,
# poincare,
# )
#
# Path: umap/sparse.py
# def arr_unique(arr):
# def arr_union(ar1, ar2):
# def arr_intersect(ar1, ar2):
# def sparse_sum(ind1, data1, ind2, data2):
# def sparse_diff(ind1, data1, ind2, data2):
# def sparse_mul(ind1, data1, ind2, data2):
# def general_sset_intersection(
# indptr1,
# indices1,
# data1,
# indptr2,
# indices2,
# data2,
# result_row,
# result_col,
# result_val,
# right_complement=False,
# mix_weight=0.5,
# ):
# def general_sset_union(
# indptr1,
# indices1,
# data1,
# indptr2,
# indices2,
# data2,
# result_row,
# result_col,
# result_val,
# ):
# def sparse_euclidean(ind1, data1, ind2, data2):
# def sparse_manhattan(ind1, data1, ind2, data2):
# def sparse_chebyshev(ind1, data1, ind2, data2):
# def sparse_minkowski(ind1, data1, ind2, data2, p=2.0):
# def sparse_hamming(ind1, data1, ind2, data2, n_features):
# def sparse_canberra(ind1, data1, ind2, data2):
# def sparse_bray_curtis(ind1, data1, ind2, data2): # pragma: no cover
# def sparse_jaccard(ind1, data1, ind2, data2):
# def sparse_matching(ind1, data1, ind2, data2, n_features):
# def sparse_dice(ind1, data1, ind2, data2):
# def sparse_kulsinski(ind1, data1, ind2, data2, n_features):
# def sparse_rogers_tanimoto(ind1, data1, ind2, data2, n_features):
# def sparse_russellrao(ind1, data1, ind2, data2, n_features):
# def sparse_sokal_michener(ind1, data1, ind2, data2, n_features):
# def sparse_sokal_sneath(ind1, data1, ind2, data2):
# def sparse_cosine(ind1, data1, ind2, data2):
# def sparse_hellinger(ind1, data1, ind2, data2):
# def sparse_correlation(ind1, data1, ind2, data2, n_features):
# def approx_log_Gamma(x):
# def log_beta(x, y):
# def log_single_beta(x):
# def sparse_ll_dirichlet(ind1, data1, ind2, data2):
# SPARSE_SPECIAL_METRICS = {
# sparse_hellinger: "hellinger",
# sparse_ll_dirichlet: "ll_dirichlet",
# }
, which may include functions, classes, or code. Output only the next line. | sparse_named_distances[k]: k |
Predict the next line for this snippet: <|code_start|> raise ValueError("Could not find embedding attribute of umap_object")
def _get_metric(umap_object):
if hasattr(umap_object, "metric"):
return umap_object.metric
else:
# Assume euclidean if no attribute per cuML.UMAP
return "euclidean"
def _get_metric_kwds(umap_object):
if hasattr(umap_object, "_metric_kwds"):
return umap_object._metric_kwds
else:
# Assume no keywords exist
return {}
def _embed_datashader_in_an_axis(datashader_image, ax):
img_rev = datashader_image.data[::-1]
mpl_img = np.dstack([_blue(img_rev), _green(img_rev), _red(img_rev)])
ax.imshow(mpl_img)
return ax
def _nhood_search(umap_object, nhood_size):
if hasattr(umap_object, "_small_data") and umap_object._small_data:
dmat = sklearn.metrics.pairwise_distances(umap_object._raw_data)
indices = np.argpartition(dmat, nhood_size)[:, :nhood_size]
<|code_end|>
with the help of current file imports:
import numpy as np
import numba
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf
import datashader.bundling as bd
import matplotlib.pyplot as plt
import colorcet
import matplotlib.colors
import matplotlib.cm
import bokeh.plotting as bpl
import bokeh.transform as btr
import holoviews as hv
import holoviews.operation.datashader as hd
import sklearn.decomposition
import sklearn.cluster
import sklearn.neighbors
from warnings import warn
from matplotlib.patches import Patch
from umap.utils import submatrix, average_nn_distance
from bokeh.plotting import show as show_interactive
from bokeh.plotting import output_file, output_notebook
from bokeh.layouts import column
from bokeh.models import CustomJS, TextInput
from matplotlib.pyplot import show as show_static
from warnings import warn
and context from other files:
# Path: umap/utils.py
# @numba.njit(parallel=True)
# def submatrix(dmat, indices_col, n_neighbors):
# """Return a submatrix given an orginal matrix and the indices to keep.
#
# Parameters
# ----------
# dmat: array, shape (n_samples, n_samples)
# Original matrix.
#
# indices_col: array, shape (n_samples, n_neighbors)
# Indices to keep. Each row consists of the indices of the columns.
#
# n_neighbors: int
# Number of neighbors.
#
# Returns
# -------
# submat: array, shape (n_samples, n_neighbors)
# The corresponding submatrix.
# """
# n_samples_transform, n_samples_fit = dmat.shape
# submat = np.zeros((n_samples_transform, n_neighbors), dtype=dmat.dtype)
# for i in numba.prange(n_samples_transform):
# for j in numba.prange(n_neighbors):
# submat[i, j] = dmat[i, indices_col[i, j]]
# return submat
#
# def average_nn_distance(dist_matrix):
# """Calculate the average distance to each points nearest neighbors.
#
# Parameters
# ----------
# dist_matrix: a csr_matrix
# A distance matrix (usually umap_model.graph_)
#
# Returns
# -------
# An array with the average distance to each points nearest neighbors
#
# """
# (row_idx, col_idx, val) = scipy.sparse.find(dist_matrix)
#
# # Count/sum is done per row
# count_non_zero_elems = np.bincount(row_idx)
# sum_non_zero_elems = np.bincount(row_idx, weights=val)
# averages = sum_non_zero_elems / count_non_zero_elems
#
# if any(np.isnan(averages)):
# warn(
# "Embedding contains disconnected vertices which will be ignored."
# "Use umap.utils.disconnected_vertices() to identify them."
# )
#
# return averages
, which may contain function names, class names, or code. Output only the next line. | dmat_shortened = submatrix(dmat, indices, nhood_size) |
Given snippet: <|code_start|> point_plot,
aggregator=ds.count(),
cmap=plt.get_cmap(cmap),
width=width,
height=height,
)
return plot
def nearest_neighbour_distribution(umap_object, bins=25, ax=None):
"""Create a histogram of the average distance to each points
nearest neighbors.
Parameters
----------
umap_object: trained UMAP object
A trained UMAP object that has an embedding.
bins: int (optional, default 25)
Number of bins to put the points into
ax: matlotlib axis (optional, default None)
A matplotlib axis to plot to, or, if None, a new
axis will be created and returned.
Returns
-------
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import numba
import pandas as pd
import datashader as ds
import datashader.transfer_functions as tf
import datashader.bundling as bd
import matplotlib.pyplot as plt
import colorcet
import matplotlib.colors
import matplotlib.cm
import bokeh.plotting as bpl
import bokeh.transform as btr
import holoviews as hv
import holoviews.operation.datashader as hd
import sklearn.decomposition
import sklearn.cluster
import sklearn.neighbors
from warnings import warn
from matplotlib.patches import Patch
from umap.utils import submatrix, average_nn_distance
from bokeh.plotting import show as show_interactive
from bokeh.plotting import output_file, output_notebook
from bokeh.layouts import column
from bokeh.models import CustomJS, TextInput
from matplotlib.pyplot import show as show_static
from warnings import warn
and context:
# Path: umap/utils.py
# @numba.njit(parallel=True)
# def submatrix(dmat, indices_col, n_neighbors):
# """Return a submatrix given an orginal matrix and the indices to keep.
#
# Parameters
# ----------
# dmat: array, shape (n_samples, n_samples)
# Original matrix.
#
# indices_col: array, shape (n_samples, n_neighbors)
# Indices to keep. Each row consists of the indices of the columns.
#
# n_neighbors: int
# Number of neighbors.
#
# Returns
# -------
# submat: array, shape (n_samples, n_neighbors)
# The corresponding submatrix.
# """
# n_samples_transform, n_samples_fit = dmat.shape
# submat = np.zeros((n_samples_transform, n_neighbors), dtype=dmat.dtype)
# for i in numba.prange(n_samples_transform):
# for j in numba.prange(n_neighbors):
# submat[i, j] = dmat[i, indices_col[i, j]]
# return submat
#
# def average_nn_distance(dist_matrix):
# """Calculate the average distance to each points nearest neighbors.
#
# Parameters
# ----------
# dist_matrix: a csr_matrix
# A distance matrix (usually umap_model.graph_)
#
# Returns
# -------
# An array with the average distance to each points nearest neighbors
#
# """
# (row_idx, col_idx, val) = scipy.sparse.find(dist_matrix)
#
# # Count/sum is done per row
# count_non_zero_elems = np.bincount(row_idx)
# sum_non_zero_elems = np.bincount(row_idx, weights=val)
# averages = sum_non_zero_elems / count_non_zero_elems
#
# if any(np.isnan(averages)):
# warn(
# "Embedding contains disconnected vertices which will be ignored."
# "Use umap.utils.disconnected_vertices() to identify them."
# )
#
# return averages
which might include code, classes, or functions. Output only the next line. | nn_distances = average_nn_distance(umap_object.graph_) |
Given the code snippet: <|code_start|> for j in range(max_k):
rank = 0
while indices_source[rank] != indices_embedded[i, j]:
rank += 1
for k in range(j + 1, max_k + 1):
if rank > k:
trustworthiness[k] += rank - k
for k in range(1, max_k + 1):
trustworthiness[k] = 1.0 - trustworthiness[k] * (
2.0 / (n_samples * k * (2.0 * n_samples - 3.0 * k - 1.0))
)
trustworthiness[0] = 1.0
return trustworthiness
return trustworthiness_vector_lowmem
def trustworthiness_vector(
source, embedding, max_k, metric="euclidean"
): # pragma: no cover
tree = KDTree(embedding, metric=metric)
indices_embedded = tree.query(embedding, k=max_k, return_distance=False)
# Drop the actual point itself
indices_embedded = indices_embedded[:, 1:]
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import numba
from sklearn.neighbors import KDTree
from umap.distances import named_distances
and context (functions, classes, or occasionally code) from other files:
# Path: umap/distances.py
# def sign(a):
# def euclidean(x, y):
# def euclidean_grad(x, y):
# def standardised_euclidean(x, y, sigma=_mock_ones):
# def standardised_euclidean_grad(x, y, sigma=_mock_ones):
# def manhattan(x, y):
# def manhattan_grad(x, y):
# def chebyshev(x, y):
# def chebyshev_grad(x, y):
# def minkowski(x, y, p=2):
# def minkowski_grad(x, y, p=2):
# def poincare(u, v):
# def hyperboloid_grad(x, y):
# def weighted_minkowski(x, y, w=_mock_ones, p=2):
# def weighted_minkowski_grad(x, y, w=_mock_ones, p=2):
# def mahalanobis(x, y, vinv=_mock_identity):
# def mahalanobis_grad(x, y, vinv=_mock_identity):
# def hamming(x, y):
# def canberra(x, y):
# def canberra_grad(x, y):
# def bray_curtis(x, y):
# def bray_curtis_grad(x, y):
# def jaccard(x, y):
# def matching(x, y):
# def dice(x, y):
# def kulsinski(x, y):
# def rogers_tanimoto(x, y):
# def russellrao(x, y):
# def sokal_michener(x, y):
# def sokal_sneath(x, y):
# def haversine(x, y):
# def haversine_grad(x, y):
# def yule(x, y):
# def cosine(x, y):
# def cosine_grad(x, y):
# def correlation(x, y):
# def hellinger(x, y):
# def hellinger_grad(x, y):
# def approx_log_Gamma(x):
# def log_beta(x, y):
# def log_single_beta(x):
# def ll_dirichlet(data1, data2):
# def symmetric_kl(x, y, z=1e-11): # pragma: no cover
# def symmetric_kl_grad(x, y, z=1e-11): # pragma: no cover
# def correlation_grad(x, y):
# def sinkhorn_distance(
# x, y, M=_mock_identity, cost=_mock_cost, maxiter=64
# ): # pragma: no cover
# def spherical_gaussian_energy_grad(x, y): # pragma: no cover
# def diagonal_gaussian_energy_grad(x, y): # pragma: no cover
# def gaussian_energy_grad(x, y): # pragma: no cover
# def spherical_gaussian_grad(x, y): # pragma: no cover
# def get_discrete_params(data, metric):
# def categorical_distance(x, y):
# def hierarchical_categorical_distance(x, y, cat_hierarchy=[{}]):
# def ordinal_distance(x, y, support_size=1.0):
# def count_distance(x, y, poisson_lambda=1.0, normalisation=1.0):
# def levenshtein(x, y, normalisation=1.0, max_distance=20):
# def parallel_special_metric(X, Y=None, metric=hellinger):
# def chunked_parallel_special_metric(X, Y=None, metric=hellinger, chunk_size=16):
# def pairwise_special_metric(X, Y=None, metric="hellinger", kwds=None):
# def _partial_metric(_X, _Y=None):
# B = s * t
# B = 1.0 + 1e-8
# DISCRETE_METRICS = (
# "categorical",
# "hierarchical_categorical",
# "ordinal",
# "count",
# "string",
# )
# SPECIAL_METRICS = (
# "hellinger",
# "ll_dirichlet",
# "symmetric_kl",
# "poincare",
# hellinger,
# ll_dirichlet,
# symmetric_kl,
# poincare,
# )
. Output only the next line. | dist = named_distances[metric] |
Next line prediction: <|code_start|>
benchmark_only = pytest.mark.skipif(
"BENCHARM_TEST" not in os.environ, reason="Benchmark tests skipped"
)
# Constants for benchmark
WARMUP_ROUNDS = 5
ITERATIONS = 10
ROUNDS = 10
# --------
# Fixtures
# --------
@pytest.fixture(scope="function")
def stashed_previous_impl_for_regression_test():
@numba.njit(parallel=True, nogil=True)
def stashed_chunked_parallel_special_metric(
<|code_end|>
. Use current file imports:
(import pytest
import numba
import os
import numpy as np
from numpy.testing import assert_array_equal
from umap import distances as dist)
and context including class names, function names, or small code snippets from other files:
# Path: umap/distances.py
# def sign(a):
# def euclidean(x, y):
# def euclidean_grad(x, y):
# def standardised_euclidean(x, y, sigma=_mock_ones):
# def standardised_euclidean_grad(x, y, sigma=_mock_ones):
# def manhattan(x, y):
# def manhattan_grad(x, y):
# def chebyshev(x, y):
# def chebyshev_grad(x, y):
# def minkowski(x, y, p=2):
# def minkowski_grad(x, y, p=2):
# def poincare(u, v):
# def hyperboloid_grad(x, y):
# def weighted_minkowski(x, y, w=_mock_ones, p=2):
# def weighted_minkowski_grad(x, y, w=_mock_ones, p=2):
# def mahalanobis(x, y, vinv=_mock_identity):
# def mahalanobis_grad(x, y, vinv=_mock_identity):
# def hamming(x, y):
# def canberra(x, y):
# def canberra_grad(x, y):
# def bray_curtis(x, y):
# def bray_curtis_grad(x, y):
# def jaccard(x, y):
# def matching(x, y):
# def dice(x, y):
# def kulsinski(x, y):
# def rogers_tanimoto(x, y):
# def russellrao(x, y):
# def sokal_michener(x, y):
# def sokal_sneath(x, y):
# def haversine(x, y):
# def haversine_grad(x, y):
# def yule(x, y):
# def cosine(x, y):
# def cosine_grad(x, y):
# def correlation(x, y):
# def hellinger(x, y):
# def hellinger_grad(x, y):
# def approx_log_Gamma(x):
# def log_beta(x, y):
# def log_single_beta(x):
# def ll_dirichlet(data1, data2):
# def symmetric_kl(x, y, z=1e-11): # pragma: no cover
# def symmetric_kl_grad(x, y, z=1e-11): # pragma: no cover
# def correlation_grad(x, y):
# def sinkhorn_distance(
# x, y, M=_mock_identity, cost=_mock_cost, maxiter=64
# ): # pragma: no cover
# def spherical_gaussian_energy_grad(x, y): # pragma: no cover
# def diagonal_gaussian_energy_grad(x, y): # pragma: no cover
# def gaussian_energy_grad(x, y): # pragma: no cover
# def spherical_gaussian_grad(x, y): # pragma: no cover
# def get_discrete_params(data, metric):
# def categorical_distance(x, y):
# def hierarchical_categorical_distance(x, y, cat_hierarchy=[{}]):
# def ordinal_distance(x, y, support_size=1.0):
# def count_distance(x, y, poisson_lambda=1.0, normalisation=1.0):
# def levenshtein(x, y, normalisation=1.0, max_distance=20):
# def parallel_special_metric(X, Y=None, metric=hellinger):
# def chunked_parallel_special_metric(X, Y=None, metric=hellinger, chunk_size=16):
# def pairwise_special_metric(X, Y=None, metric="hellinger", kwds=None):
# def _partial_metric(_X, _Y=None):
# B = s * t
# B = 1.0 + 1e-8
# DISCRETE_METRICS = (
# "categorical",
# "hierarchical_categorical",
# "ordinal",
# "count",
# "string",
# )
# SPECIAL_METRICS = (
# "hellinger",
# "ll_dirichlet",
# "symmetric_kl",
# "poincare",
# hellinger,
# ll_dirichlet,
# symmetric_kl,
# poincare,
# )
. Output only the next line. | X, Y=None, metric=dist.named_distances["hellinger"], chunk_size=16 |
Given the following code snippet before the placeholder: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('simple', 'gru', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - with attention mechanism
out_file = 'result/simple/gru/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, predict the next line using imports from the current file:
import os
import sys
from models import gru_simple
from helpers import checkpoint
and context including class names, function names, and sometimes code from other files:
# Path: models/gru_simple.py
# class GruSimple(Simple):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | gru_net = gru_simple.GruSimple(review_summary_file, checkpointer, attention=True) |
Predict the next line for this snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedSimple', 'lstm', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_simple/lstm/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
with the help of current file imports:
import os
import sys
from models import lstm_stacked_simple
from helpers import checkpoint
and context from other files:
# Path: models/lstm_stacked_simple.py
# class LstmStackedSimple(StackedSimple):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
, which may contain function names, class names, or code. Output only the next line. | lstm_net = lstm_stacked_simple.LstmStackedSimple(review_summary_file, checkpointer, num_layers=2) |
Based on the snippet: <|code_start|>
# download the data from https://snap.stanford.edu/data/web-FineFoods.html and save as raw_data/food_raw.txt.
# The provided food_raw.txt is a placeholder. Also make sure that extracted_data directory exists.
# python extracter_script.py raw_data/finefoods.txt extracted_data/review_summary.csv
args = sys.argv
inputfile = args[1]
outputfile = args[2]
num_reviews = 200000
<|code_end|>
, predict the immediate next line with the help of imports:
from helpers.extracter import Spider
import sys
and context (classes, functions, sometimes code) from other files:
# Path: helpers/extracter.py
# class Spider:
# def __init__(self,num_reviews):
# """
# Simple Spider to crawl the JSON script dataset and load reviews and summary
#
# :param num_reviews: Number of (review, summary) samples to be extracted
# """
# self.num_reviews = num_reviews
# self.raw_data_file = None
# self.df = None
#
# def crawl_for_reviews_and_summary(self, input_file):
# """
# Crawl the input dataset
#
# :param input_file: The location of the file containing the txt file dataset
# :return: None
# """
# self.raw_data_file = input_file
# self.df = pd.DataFrame()
# self.df['Review'] = self.__crawl_review()
# self.df['Summary'] = self.__crawl_summary()
#
# def __crawl_review(self):
# """
# Crawl review
#
# :return: review [numpy array]
# """
# review_list = []
# print 'Crawling Reviews....'
# num_lines = 0
# with open(self.raw_data_file) as infile:
# for line in infile:
# if line.startswith('review/text'):
# if num_lines >= self.num_reviews:
# break
# num_lines += 1
# _,review = line.split('/text: ')
# review_list.append(review)
#
# return np.array(review_list)
#
# def __crawl_summary(self):
# """
# Crawl summary
#
# :return: summary [numpy array]
# """
# summary_list = []
# print 'Crawling Summary....'
# num_lines = 0
# with open(self.raw_data_file) as infile:
# for line in infile:
# if line.startswith('review/summary'):
# if num_lines >= self.num_reviews:
# break
# num_lines += 1
# _,summary = line.split('/summary: ')
# summary_list.append(summary)
#
# return np.array(summary_list)
#
# def save_review_summary_frame(self, output_file):
# """
# save (review, summary) pair in CSV file
#
# :param output_file: The location where CSV file is to be saved.
# :return: None
# """
# self.df.to_csv(output_file, index=False)
. Output only the next line. | spider = Spider(num_reviews) |
Predict the next line for this snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('simple', 'lstm', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using LSTM cell - with attention mechanism
out_file = 'result/simple/lstm/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
with the help of current file imports:
import os
import sys
from models import lstm_simple
from helpers import checkpoint
and context from other files:
# Path: models/lstm_simple.py
# class LstmSimple(Simple):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
, which may contain function names, class names, or code. Output only the next line. | lstm_net = lstm_simple.LstmSimple(review_summary_file, checkpointer, attention=True) |
Continue the code snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('bidirectional', 'lstm', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/bidirectional/lstm/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
. Use current file imports:
import os
import sys
from models import lstm_bidirectional
from helpers import checkpoint
and context (classes, functions, or code) from other files:
# Path: models/lstm_bidirectional.py
# class LstmBidirectional(Bidirectional):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | lstm_net = lstm_bidirectional.LstmBidirectional(review_summary_file, checkpointer, attention=True) |
Predict the next line for this snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('bidirectional', 'gru', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/bidirectional/gru/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
with the help of current file imports:
import os
import sys
from models import gru_bidirectional
from helpers import checkpoint
and context from other files:
# Path: models/gru_bidirectional.py
# class GruBidirectional(Bidirectional):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
, which may contain function names, class names, or code. Output only the next line. | gru_net = gru_bidirectional.GruBidirectional(review_summary_file, checkpointer) |
Here is a snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedBidirectional', 'gru', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_bidirectional/gru/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
from models import gru_stacked_bidirectional
from helpers import checkpoint
and context from other files:
# Path: models/gru_stacked_bidirectional.py
# class GruStackedBidirectional(StackedBidirectional):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
, which may include functions, classes, or code. Output only the next line. | gru_net = gru_stacked_bidirectional.GruStackedBidirectional(review_summary_file, checkpointer, num_layers=2) |
Predict the next line for this snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedSimple', 'gru', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_simple/gru/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
with the help of current file imports:
import os
import sys
from models import gru_stacked_simple
from helpers import checkpoint
and context from other files:
# Path: models/gru_stacked_simple.py
# class GruStackedSimple(StackedSimple):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
, which may contain function names, class names, or code. Output only the next line. | gru_net = gru_stacked_simple.GruStackedSimple(review_summary_file, checkpointer, num_layers=2) |
Using the snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedBidirectional', 'lstm', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_bidirectional/lstm/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, determine the next line of code. You have imports:
import os
import sys
from models import lstm_stacked_bidirectional
from helpers import checkpoint
and context (class names, function names, or code) available:
# Path: models/lstm_stacked_bidirectional.py
# class LstmStackedBidirectional(StackedBidirectional):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | lstm_net = lstm_stacked_bidirectional.LstmStackedBidirectional(review_summary_file, |
Based on the snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedBidirectional', 'lstm', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_bidirectional/lstm/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
from models import lstm_stacked_bidirectional
from helpers import checkpoint
and context (classes, functions, sometimes code) from other files:
# Path: models/lstm_stacked_bidirectional.py
# class LstmStackedBidirectional(StackedBidirectional):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | lstm_net = lstm_stacked_bidirectional.LstmStackedBidirectional(review_summary_file, checkpointer, num_layers=2) |
Predict the next line after this snippet: <|code_start|> self.num_hypothesis * self.steps_per_prediction,
self.steps_per_prediction)
for hypothesis in self.hypotheses.T:
bleu_1,bleu_2, bleu_3, bleu_4, rouge = self.__evaluate_one_ref_hypothesis_pair(self.reference,hypothesis)
self.bleu_1.append(bleu_1)
self.bleu_2.append(bleu_2)
self.bleu_3.append(bleu_3)
self.bleu_4.append(bleu_4)
self.rouge.append(rouge)
def __evaluate_one_ref_hypothesis_pair(self, refs, hyps):
"""
:param refs:
:param hyps:
:return:
"""
# Dump the data into the corresponding files
for index,pair in enumerate(zip(refs,hyps)):
file_ref_nm = self.reference_store_loc + '/ref' + str(index) + '.txt'
file_hyp_nm = self.hypothesis_store_loc + '/gen' + str(index) + '.txt'
ref_file = open(file_ref_nm,'w')
hyp_file = open(file_hyp_nm,'w')
ref_file.write(str(pair[0]))
if pair[1] != 'nan':
hyp_file.write(str(pair[1]))
else:
hyp_file.write('')
# Call the tester function to get the evaluations
<|code_end|>
using the current file's imports:
import pandas as pd
from metrics import tester
and any relevant context from other files:
# Path: metrics/tester.py
# def load_textfiles(references, hypothesis):
# def score(ref, hypo):
# def main():
# BLEU_1 = 0.
# BLEU_2 = 0.
# BLEU_3 = 0.
# BLEU_4 = 0.
# ROUGE_L = 0.
# BLEU_1 = BLEU_1/num_files
# BLEU_2 = BLEU_2/num_files
# BLEU_3 = BLEU_3/num_files
# BLEU_4 = BLEU_4/num_files
# ROUGE_L = ROUGE_L/num_files
. Output only the next line. | return tester.main() |
Based on the snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('bidirectional', 'gru', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/bidirectional/gru/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
from models import gru_bidirectional
from helpers import checkpoint
and context (classes, functions, sometimes code) from other files:
# Path: models/gru_bidirectional.py
# class GruBidirectional(Bidirectional):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | gru_net = gru_bidirectional.GruBidirectional(review_summary_file, checkpointer, attention=True) |
Given snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('bidirectional', 'lstm', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/bidirectional/lstm/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import sys
from models import lstm_bidirectional
from helpers import checkpoint
and context:
# Path: models/lstm_bidirectional.py
# class LstmBidirectional(Bidirectional):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
which might include code, classes, or functions. Output only the next line. | lstm_net = lstm_bidirectional.LstmBidirectional(review_summary_file, checkpointer) |
Based on the snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('simple', 'gru', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/simple/gru/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
from models import gru_simple
from helpers import checkpoint
and context (classes, functions, sometimes code) from other files:
# Path: models/gru_simple.py
# class GruSimple(Simple):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | gru_net = gru_simple.GruSimple(review_summary_file, checkpointer) |
Given the code snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('simple', 'lstm', 'noAttention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using LSTM cell - without attention mechanism
out_file = 'result/simple/lstm/no_attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
from models import lstm_simple
from helpers import checkpoint
and context (functions, classes, or occasionally code) from other files:
# Path: models/lstm_simple.py
# class LstmSimple(Simple):
# def __init__(self, review_summary_file, checkpointer, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | lstm_net = lstm_simple.LstmSimple(review_summary_file, checkpointer) |
Here is a snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedBidirectional', 'gru', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_bidirectional/gru/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
. Write the next line using the current file imports:
import os
import sys
from models import gru_stacked_bidirectional
from helpers import checkpoint
and context from other files:
# Path: models/gru_stacked_bidirectional.py
# class GruStackedBidirectional(StackedBidirectional):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
, which may include functions, classes, or code. Output only the next line. | gru_net = gru_stacked_bidirectional.GruStackedBidirectional(review_summary_file, checkpointer, |
Given the code snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedSimple', 'lstm', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_simple/lstm/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
from models import lstm_stacked_simple
from helpers import checkpoint
and context (functions, classes, or occasionally code) from other files:
# Path: models/lstm_stacked_simple.py
# class LstmStackedSimple(StackedSimple):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
. Output only the next line. | lstm_net = lstm_stacked_simple.LstmStackedSimple(review_summary_file, checkpointer, attention=True, num_layers=2) |
Predict the next line for this snippet: <|code_start|>sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..'))
# Get the review summary file
review_summary_file = 'extracted_data/review_summary.csv'
# Initialize Checkpointer to ensure checkpointing
checkpointer = checkpoint.Checkpointer('stackedSimple', 'gru', 'Attention')
checkpointer.steps_per_checkpoint(1000)
checkpointer.steps_per_prediction(1000)
# Do using GRU cell - without attention mechanism
out_file = 'result/stacked_simple/gru/attention.csv'
checkpointer.set_result_location(out_file)
<|code_end|>
with the help of current file imports:
import os
import sys
from models import gru_stacked_simple
from helpers import checkpoint
and context from other files:
# Path: models/gru_stacked_simple.py
# class GruStackedSimple(StackedSimple):
# def __init__(self, review_summary_file, checkpointer, num_layers, attention=False):
# def get_cell(self):
#
# Path: helpers/checkpoint.py
# class Checkpointer:
# def __init__(self, model_nm, cell_nm, attention_type):
# def steps_per_checkpoint(self, num_steps):
# def get_checkpoint_steps(self):
# def steps_per_prediction(self, num_steps):
# def get_prediction_checkpoint_steps(self):
# def get_checkpoint_location(self):
# def get_last_checkpoint(self):
# def __get_id(self, ckpt_file):
# def delete_previous_checkpoints(self, num_previous=5):
# def get_save_address(self):
# def is_checkpointed(self):
# def get_data_file_location(self):
# def get_mapper_file_location(self):
# def get_mapper_folder_location(self):
# def get_step_file(self):
# def is_mapper_checkpointed(self):
# def is_output_file_present(self):
# def set_result_location(self, outfile):
# def get_result_location(self):
, which may contain function names, class names, or code. Output only the next line. | gru_net = gru_stacked_simple.GruStackedSimple(review_summary_file, checkpointer,attention=True, num_layers=2) |
Given snippet: <|code_start|>## Copyright (c) 2003 Henk Punt
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell 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 WARRANTY 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
HORIZONTAL = 1
VERTICAL = 2
class Splitter(Window):
_window_style_ = WS_CHILD | WS_VISIBLE
_window_style_ex_ = 0
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from venster.windows import *
from venster.wtl import *
from venster import gdi
and context:
# Path: venster/gdi.py
# class BITMAP(Structure):
# class LOGFONT(Structure):
# class LOGBRUSH(Structure):
# class ENUMLOGFONTEX(Structure):
# class BITMAPINFOHEADER(Structure):
# class RGBQUAD(Structure):
# class BITMAPINFO(Structure):
# class BITMAPFILEHEADER(Structure):
# class Bitmap(WindowsObject):
# class SolidBrush(WindowsObject):
# class Pen(WindowsObject):
# class Font(WindowsObject):
# LF_FACESIZE = 32
# MONO_FONT = 8
# OBJ_FONT = 6
# ANSI_FIXED_FONT = 11
# ANSI_VAR_FONT = 12
# DEVICE_DEFAULT_FONT= 14
# DEFAULT_GUI_FONT= 17
# OEM_FIXED_FONT= 10
# SYSTEM_FONT= 13
# SYSTEM_FIXED_FONT= 16
# ANSI_CHARSET = 0
# DEFAULT_CHARSET = 1
# SYMBOL_CHARSET = 2
# SHIFTJIS_CHARSET = 128
# HANGEUL_CHARSET = 129
# HANGUL_CHARSET = 129
# GB2312_CHARSET = 134
# CHINESEBIG5_CHARSET = 136
# OEM_CHARSET = 255
# FIXED_PITCH = 1
# CLR_NONE = 0xffffffff
# HS_BDIAGONAL =3
# HS_CROSS =4
# HS_DIAGCROSS =5
# HS_FDIAGONAL =2
# HS_HORIZONTAL =0
# HS_VERTICAL =1
# PATINVERT = 0x5A0049
# OUT_DEFAULT_PRECIS = 0
# CLIP_DEFAULT_PRECIS = 0
# DEFAULT_QUALITY = 0
# DEFAULT_PITCH = 0
# FF_DONTCARE = (0<<4)
# FF_MODERN = (3<<4)
# PS_GEOMETRIC= 65536
# PS_COSMETIC = 0
# PS_ALTERNATE = 8
# PS_SOLID = 0
# PS_DASH = 1
# PS_DOT= 2
# PS_DASHDOT = 3
# PS_DASHDOTDOT = 4
# PS_NULL = 5
# PS_USERSTYLE = 7
# PS_INSIDEFRAME= 6
# PS_ENDCAP_ROUND = 0
# PS_ENDCAP_SQUARE= 256
# PS_ENDCAP_FLAT= 512
# PS_JOIN_BEVEL = 4096
# PS_JOIN_MITER = 8192
# PS_JOIN_ROUND = 0
# PS_STYLE_MASK = 15
# PS_ENDCAP_MASK= 3840
# PS_TYPE_MASK = 983040
# BS_SOLID = 0
# BS_NULL = 1
# BS_HOLLOW = 1
# BS_HATCHED = 2
# BS_PATTERN = 3
# BS_INDEXED = 4
# BS_DIBPATTERN = 5
# BS_DIBPATTERNPT = 6
# BS_PATTERN8X8 = 7
# BS_DIBPATTERN8X8 = 8
# BI_RGB =0
# BI_RLE8 =1
# BI_RLE4 =2
# BI_BITFIELDS =3
# BI_JPEG =4
# BI_PNG =5
# DIB_RGB_COLORS = 0
# DIB_PAL_COLORS = 1
# def __init__(self, path):
# def getWidth(self):
# def getHeight(self):
# def __init__(self, colorRef):
# def Create(cls, fnPenStyle = PS_SOLID, nWidth = 1, crColor = 0x00000000):
# def CreateEx(cls, dwPenStyle = PS_COSMETIC | PS_SOLID, dwWidth = 1, lbStyle = BS_SOLID,
# lbColor = 0x00000000, lbHatch = 0,
# dwStyleCount = 0, lpStyle = 0):
# def __init__(self, **kwargs):
which might include code, classes, or functions. Output only the next line. | _window_background_ = gdi.GetSysColorBrush(COLOR_BTNFACE) |
Given the code snippet: <|code_start|>
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell 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 WARRANTY 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
WM_USER_TASKBAR = WM_USER + 1
#this message is send when explorer restarts after a crash:
WM_TASKBAR_CREATED = RegisterWindowMessage("TaskbarCreated")
class TrayIcon(Window):
_window_style_ = WS_OVERLAPPEDWINDOW #removed the WS_VISIBLE flag, this creates a hidden window
<|code_end|>
, generate the next line using the imports in this file:
from venster.windows import *
from venster.wtl import *
from venster.shell import *
from venster.lib import form
from venster.lib import menu
and context (functions, classes, or occasionally code) from other files:
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
#
# Path: venster/lib/menu.py
# def EvalItem(item, parent):
# def EvalPopupMenu(item, managed = False):
# def EvalMenu(item, managed = False):
. Output only the next line. | _tray_icon_menu_ = [(MF_STRING, "*Open", form.ID_OPEN), |
Next line prediction: <|code_start|> Shell_NotifyIcon(NIM_DELETE, byref(ntfIconData))
def WndProc(self, hWnd, nMsg, wParam, lParam):
#the shell icon will send notification messages to the hidden window
#the message is the one given by the uCallbackMessage field when the icon was
#added to the tray.
#the lParam contains the original msg (WM_MOUSEMOVE etc). we intercept
#it here, and turn it into a normal msg and use normal wtl processing to handle the msg
if nMsg == WM_USER_TASKBAR:
nMsg = lParam
lParam = 0
wParam = 0
return Window.WndProc(self, hWnd, nMsg, wParam, lParam)
else:
return Window.WndProc(self, hWnd, nMsg, wParam, lParam)
def OnTaskbarCreated(self, event):
#after an Explorer crash, this event will be received
#when explorer restarts. Then we re-add the tray icon...
self.AddTrayIcon()
msg_handler(WM_TASKBAR_CREATED)(OnTaskbarCreated)
def TrackPopupMenu(self):
#To display a context menu for a notification icon, the
#current window must be the foreground window before the
#application calls TrackPopupMenu or TrackPopupMenuEx. Otherwise,
#the menu will not disappear when the user clicks outside of the
#menu or the window that created the menu (if it is visible).
self.SetForegroundWindow()
<|code_end|>
. Use current file imports:
(from venster.windows import *
from venster.wtl import *
from venster.shell import *
from venster.lib import form
from venster.lib import menu)
and context including class names, function names, or small code snippets from other files:
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
#
# Path: venster/lib/menu.py
# def EvalItem(item, parent):
# def EvalPopupMenu(item, managed = False):
# def EvalMenu(item, managed = False):
. Output only the next line. | trayMenu = menu.EvalPopupMenu(self._tray_icon_menu_, managed = True) |
Given the code snippet: <|code_start|>
event.handled = False
msg_handler(WM_PAINT)(OnPaint)
def OnWindowPosChanging(self, event):
event.handled = False
msg_handler(WM_WINDOWPOSCHANGED)(OnWindowPosChanging)
def OnSize(self, event):
#width = self.clientRect.width
ShowScrollBar(self.handle, SB_HORZ, False)
self.SetRedraw(0)
for i in range(len(columnDefs) - 1):
#self.SetColumnWidth(i, width / len(columnDefs))
self.SetColumnWidth(i, -2)
self.SetColumnWidth(len(columnDefs) - 1, -2)
self.SetRedraw(1)
event.handled = False
msg_handler(WM_SIZE)(OnSize)
def OnColumnClick(self, event):
nmlv = NMLISTVIEW.from_address(int(event.lParam))
print "column clicked!", nmlv.iSubItem
ntf_handler(LVN_COLUMNCLICK)(OnColumnClick)
<|code_end|>
, generate the next line using the imports in this file:
from venster.windows import *
from venster.wtl import *
from venster.comctl import *
from venster.lib import list
from venster.lib import form
from ctypes import *
and context (functions, classes, or occasionally code) from other files:
# Path: venster/lib/list.py
# class List(ListView):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def InsertColumns(self, colDefs):
# def SetColumns(self, colDefs):
# def InsertRow(self, i, row, lParam = 0):
# def SetRow(self, i, row):
# def SelectAll(self):
# def InvertSelection(self):
#
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
. Output only the next line. | class MyForm(form.Form): |
Using the snippet: <|code_start|>## WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
class FlashWindow(atl.AxWindow):
def __init__(self, *args, **kwargs):
atl.AxWindow.__init__(self, "ShockwaveFlash.ShockwaveFlash", *args, **kwargs)
pUnk = self.GetControl()
#get the Flash interface of the control
pFlash = wrap(pUnk) # XXX replace 'wrap' with 'GetBestInterface'
#receive events
self.flashEvents = GetEvents(pFlash, self)
#start the flash movie
pFlash.LoadMovie(0, os.getcwd() + os.sep + "cow.swf")
pFlash.Play()
def _IShockwaveFlashEvents_OnReadyStateChange(self, this, state):
# flash event handler
print "OnReadyStateChange: ", state
def dispose(self):
#disconnect connectionpoint
del self.flashEvents
atl.AxWindow.dispose(self)
<|code_end|>
, determine the next line of code. You have imports:
from venster.windows import *
from venster.wtl import *
from venster import atl
from venster.lib import form
from ctypes import *
from comtypes.client import GetEvents, wrap
import os
and context (class names, function names, or code) available:
# Path: venster/atl.py
# class AxWindow(wtl.Window):
# def __init__(self, ctrlId, *args, **kwargs):
# def GetControl(self):
#
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
. Output only the next line. | class MyForm(form.Form): |
Predict the next line for this snippet: <|code_start|>## distribute, sublicense, and/or sell 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 WARRANTY 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
def createTestChild(parent):
lst = list.List(parent = parent, orExStyle = WS_EX_CLIENTEDGE)
lst.InsertColumns([("blaat", 100), ("col2", 150)])
for i in range(20):
lst.InsertRow(i, ["blaat %d" % i, "blaat col2 %d" % i])
return lst
class MyForm(form.Form):
_window_title_ = "Splitter Window Test"
def OnCreate(self, event):
<|code_end|>
with the help of current file imports:
from venster.windows import *
from venster.wtl import *
from venster.lib import splitter
from venster.lib import form
from venster.lib import list
and context from other files:
# Path: venster/lib/splitter.py
# HORIZONTAL = 1
# VERTICAL = 2
# class Splitter(Window):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def Add(self, index, ctrl):
# def OnSize(self, event):
# def Layout(self, cx, cy):
# def OnLeftButtonDown(self, event):
# def IsOverSplitter(self, x, y):
# def OnLeftButtonUp(self, event):
# def Clamp(self, x, y):
# def OnMouseMove(self, event):
# def PatBlt(self, oldPos, newPos, eraseOld):
# def OnSetCursor(self, event):
# def OnCaptureChanged(self, event):
#
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
#
# Path: venster/lib/list.py
# class List(ListView):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def InsertColumns(self, colDefs):
# def SetColumns(self, colDefs):
# def InsertRow(self, i, row, lParam = 0):
# def SetRow(self, i, row):
# def SelectAll(self):
# def InvertSelection(self):
, which may contain function names, class names, or code. Output only the next line. | aSplitter1 = splitter.Splitter(parent = self, |
Based on the snippet: <|code_start|>## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell 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 WARRANTY 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
def createTestChild(parent):
lst = list.List(parent = parent, orExStyle = WS_EX_CLIENTEDGE)
lst.InsertColumns([("blaat", 100), ("col2", 150)])
for i in range(20):
lst.InsertRow(i, ["blaat %d" % i, "blaat col2 %d" % i])
return lst
<|code_end|>
, predict the immediate next line with the help of imports:
from venster.windows import *
from venster.wtl import *
from venster.lib import splitter
from venster.lib import form
from venster.lib import list
and context (classes, functions, sometimes code) from other files:
# Path: venster/lib/splitter.py
# HORIZONTAL = 1
# VERTICAL = 2
# class Splitter(Window):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def Add(self, index, ctrl):
# def OnSize(self, event):
# def Layout(self, cx, cy):
# def OnLeftButtonDown(self, event):
# def IsOverSplitter(self, x, y):
# def OnLeftButtonUp(self, event):
# def Clamp(self, x, y):
# def OnMouseMove(self, event):
# def PatBlt(self, oldPos, newPos, eraseOld):
# def OnSetCursor(self, event):
# def OnCaptureChanged(self, event):
#
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
#
# Path: venster/lib/list.py
# class List(ListView):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def InsertColumns(self, colDefs):
# def SetColumns(self, colDefs):
# def InsertRow(self, i, row, lParam = 0):
# def SetRow(self, i, row):
# def SelectAll(self):
# def InvertSelection(self):
. Output only the next line. | class MyForm(form.Form): |
Based on the snippet: <|code_start|>## Copyright (c) 2003 Henk Punt
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell 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 WARRANTY 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
class Static(Window):
_window_class_ = 'static'
_window_style_ = WS_CHILD | WS_VISIBLE
<|code_end|>
, predict the immediate next line with the help of imports:
from venster.windows import *
from venster.wtl import *
from venster.atl import *
from venster.lib import form
and context (classes, functions, sometimes code) from other files:
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
. Output only the next line. | class MyForm(form.Form): |
Predict the next line for this snippet: <|code_start|>## Copyright (c) 2003 Henk Punt
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell 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 WARRANTY 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
class MyForm(form.Form):
_window_title_ = "ATL ActiveX control test"
def OnCreate(self, event):
#instantiates Windows Media Player by ProgId
<|code_end|>
with the help of current file imports:
from venster import atl
from venster import wtl
from venster.lib import form
and context from other files:
# Path: venster/atl.py
# class AxWindow(wtl.Window):
# def __init__(self, ctrlId, *args, **kwargs):
# def GetControl(self):
#
# Path: venster/wtl.py
# class DecoratedWindow(wtl_core.Window):
# class EventDecorator(wtl_core.Event):
# class Icon(wtl_core.WindowsObject):
# class MenuBase(object):
# class Menu(MenuBase, wtl_core.WindowsObject):
# class PopupMenu(MenuBase, wtl_core.WindowsObject):
# def PostMessage(self, nMsg, wParam = 0, lParam = 0):
# def SendMessage(self, nMsg, wParam = 0, lParam = 0):
# def GetClientRect(self):
# def SetWindowPos(self, hWndInsertAfter, x, y, cx, cy, uFlags):
# def GetWindowRect(self):
# def ChildWindowFromPoint(self, point):
# def ScreenToClient(self, point):
# def ClientToScreen(self, point):
# def SetRedraw(self, bRedraw):
# def SetFont(self, hFont, bRedraw):
# def SetWindowText(self, txt):
# def SetText(self, txt):
# def GetText(self):
# def MoveWindow(self, x, y, nWidth, nHeight, bRepaint):
# def GetParent(self):
# def GetMenu(self):
# def CenterWindow(self, parent = None):
# def SetFocus(self):
# def ShowWindow(self, cmdShow = SW_SHOWNORMAL):
# def IsWindowVisible(self):
# def IsIconic(self):
# def GetClassLong(self, index):
# def SetClassLong(self, index, dwNewLong):
# def UpdateWindow(self):
# def SetCapture(self):
# def Invalidate(self, bErase = TRUE):
# def InvalidateRect(self, rc, bErase = TRUE):
# def GetDCEx(self, hrgnClip, flags):
# def GetDC(self):
# def ReleaseDC(self, hdc):
# def BeginPaint(self, paintStruct):
# def EndPaint(self, paintStruct):
# def DestroyWindow(self):
# def CloseWindow(self):
# def SetForegroundWindow(self):
# def EnumChildWindows(self):
# def enumChildProc(hWnd, lParam):
# def SetTimer(self, id, elapse, timerProc = NULL):
# def LockWindowUpdate(self, fLock):
# def KillTimer(self, id):
# def GetCursorPos():
# def getSize(self):
# def getPosition(self):
# def getClientPosition(self):
# def __init__(self, path):
# def AppendMenu(self, flags, idNewItem, lpNewItem):
# def EnableMenuItem(self, uIDEnableItem, uEnable):
# def GetSubMenu(self, id):
# def GetItemCount(self):
# def SetMenuDefaultItem(self, uItem, fByPos = False):
# def __len__(self):
# def __init__(self, hWnd = None, **kwargs):
# def __init__(self, *args, **kwargs):
# def TrackPopupMenuEx(self, fuFlags, x, y, hwnd, lptpm = NULL):
# def Track(self, hwnd, fuFlags = TPM_LEFTBUTTON):
#
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
, which may contain function names, class names, or code. Output only the next line. | aControl = atl.AxWindow("WMPlayer.OCX", parent = self) |
Continue the code snippet: <|code_start|>## Permission is hereby granted, free of charge, to any person obtaining
## a copy of this software and associated documentation files (the
## "Software"), to deal in the Software without restriction, including
## without limitation the rights to use, copy, modify, merge, publish,
## distribute, sublicense, and/or sell 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 WARRANTY 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
class MyForm(form.Form):
_window_title_ = "ATL ActiveX control test"
def OnCreate(self, event):
#instantiates Windows Media Player by ProgId
aControl = atl.AxWindow("WMPlayer.OCX", parent = self)
self.controls[form.CTRL_VIEW] = aControl
if __name__ == '__main__':
mainForm = MyForm()
<|code_end|>
. Use current file imports:
from venster import atl
from venster import wtl
from venster.lib import form
and context (classes, functions, or code) from other files:
# Path: venster/atl.py
# class AxWindow(wtl.Window):
# def __init__(self, ctrlId, *args, **kwargs):
# def GetControl(self):
#
# Path: venster/wtl.py
# class DecoratedWindow(wtl_core.Window):
# class EventDecorator(wtl_core.Event):
# class Icon(wtl_core.WindowsObject):
# class MenuBase(object):
# class Menu(MenuBase, wtl_core.WindowsObject):
# class PopupMenu(MenuBase, wtl_core.WindowsObject):
# def PostMessage(self, nMsg, wParam = 0, lParam = 0):
# def SendMessage(self, nMsg, wParam = 0, lParam = 0):
# def GetClientRect(self):
# def SetWindowPos(self, hWndInsertAfter, x, y, cx, cy, uFlags):
# def GetWindowRect(self):
# def ChildWindowFromPoint(self, point):
# def ScreenToClient(self, point):
# def ClientToScreen(self, point):
# def SetRedraw(self, bRedraw):
# def SetFont(self, hFont, bRedraw):
# def SetWindowText(self, txt):
# def SetText(self, txt):
# def GetText(self):
# def MoveWindow(self, x, y, nWidth, nHeight, bRepaint):
# def GetParent(self):
# def GetMenu(self):
# def CenterWindow(self, parent = None):
# def SetFocus(self):
# def ShowWindow(self, cmdShow = SW_SHOWNORMAL):
# def IsWindowVisible(self):
# def IsIconic(self):
# def GetClassLong(self, index):
# def SetClassLong(self, index, dwNewLong):
# def UpdateWindow(self):
# def SetCapture(self):
# def Invalidate(self, bErase = TRUE):
# def InvalidateRect(self, rc, bErase = TRUE):
# def GetDCEx(self, hrgnClip, flags):
# def GetDC(self):
# def ReleaseDC(self, hdc):
# def BeginPaint(self, paintStruct):
# def EndPaint(self, paintStruct):
# def DestroyWindow(self):
# def CloseWindow(self):
# def SetForegroundWindow(self):
# def EnumChildWindows(self):
# def enumChildProc(hWnd, lParam):
# def SetTimer(self, id, elapse, timerProc = NULL):
# def LockWindowUpdate(self, fLock):
# def KillTimer(self, id):
# def GetCursorPos():
# def getSize(self):
# def getPosition(self):
# def getClientPosition(self):
# def __init__(self, path):
# def AppendMenu(self, flags, idNewItem, lpNewItem):
# def EnableMenuItem(self, uIDEnableItem, uEnable):
# def GetSubMenu(self, id):
# def GetItemCount(self):
# def SetMenuDefaultItem(self, uItem, fByPos = False):
# def __len__(self):
# def __init__(self, hWnd = None, **kwargs):
# def __init__(self, *args, **kwargs):
# def TrackPopupMenuEx(self, fuFlags, x, y, hwnd, lptpm = NULL):
# def Track(self, hwnd, fuFlags = TPM_LEFTBUTTON):
#
# Path: venster/lib/form.py
# EXIT_NONE = 0
# EXIT_ONDESTROY = 1 #exit app on destroy of form
# EXIT_ONLASTDESTROY = 2 #exit app on destroy of last form
# ID_NEW = 5001
# ID_OPEN = 5002
# ID_EXIT = 5003
# ID_SAVE = 5004
# ID_SAVEAS = 5005
# ID_CLOSE = 5006
# ID_UNDO = 5101
# ID_REDO = 5102
# ID_COPY = 5103
# ID_PASTE = 5104
# ID_CUT = 5105
# ID_SELECTALL = 5106
# ID_CLEAR = 5107
# ID_HELP_CONTENTS = 5201
# ID_ABOUT = 5202
# CTRL_VIEW = "form_CtrlView"
# CTRL_STATUSBAR = "form_CtrlStatusBar"
# CTRL_COOLBAR = "form_CtrlCoolbar"
# class Controls(dict):
# class Form(Window):
# class CmdUIUpdateEvent(object):
# class CMD_UI_UPDATE(object):
# def Add(self, *args):
# def dispose(self):
# def __getattr__(self, key):
# def __init__(self, *args, **kwargs):
# def dispose(self):
# def CreateAccels(self):
# def PreTranslateMessage(self, msg):
# def OnMenuSelect(self, event):
# def __init__(self):
# def Enable(self, fEnable):
# def OnInitMenuPopup(self, event):
# def DoLayout(self, cx, cy):
# def OnDestroy(self, event):
# def OnSize(self, event):
# def OnCreate(self, event):
# def OnExitCmd(self, event):
# def OnCloseCmd(self, event):
# def OnClose(self, event):
# def __init__(self, id, handler):
# def __install__(self, msgMap):
# def __call__(self, receiver, event):
. Output only the next line. | application = wtl.Application() |
Predict the next line for this snippet: <|code_start|> 'https_proxy': 'http://10.1.0.23/',
'ftp_proxy': 'http://10.1.0.23/',
'BROWSER': 'firefox',
'EDITOR': 'gedit',
'SHELL': '/bin/bash',
'PAGER': 'less'
}
authNeedUser = True
authNeedPass = True
def __init__(self, request, client_address, server, vfs, session):
self.vfs = vfs
self.session = session
with self.vfs.open('/etc/motd') as motd:
Commands.WELCOME = motd.read()
self.working_dir = '/'
self.total_file_size = 0
self.update_total_file_size(self.working_dir)
TelnetHandler.__init__(self, request, client_address, server)
@command('ls')
def command_ls(self, params):
if '-l' in params:
self.writeline('total ' + str(self.total_file_size)) # report a fake random file size
file_names = self.vfs.listdir(self.working_dir)
for fname in file_names:
abspath = self.vfs.getsyspath(self.working_dir + '/' + fname)
<|code_end|>
with the help of current file imports:
import argparse
import os
import logging
import sys
import socket
import traceback
import gevent
from datetime import timedelta
from gevent.util import wrap_errors
from fs.errors import ResourceNotFoundError
from fs.path import dirname
from fs.utils import isdir
from telnetsrv.green import TelnetHandler
from telnetsrv.telnetsrvlib import TelnetHandlerBase
from telnetsrv.telnetsrvlib import command
from beeswarm.drones.honeypot.helpers.common import path_to_ls
and context from other files:
# Path: beeswarm/drones/honeypot/helpers/common.py
# def path_to_ls(fn):
# """ Converts an absolute path to an entry resembling the output of
# the ls command on most UNIX systems."""
# st = os.stat(fn)
# full_mode = 'rwxrwxrwx'
# mode = ''
# file_time = ''
# d = ''
# for i in range(9):
# # Incrementally builds up the 9 character string, using characters from the
# # fullmode (defined above) and mode bits from the stat() system call.
# mode += ((st.st_mode >> (8 - i)) & 1) and full_mode[i] or '-'
# d = (os.path.isdir(fn)) and 'd' or '-'
# file_time = time.strftime(' %b %d %H:%M ', time.gmtime(st.st_mtime))
# list_format = '{0}{1} 1 ftp ftp {2}\t{3}{4}'.format(d, mode, str(st.st_size), file_time, os.path.basename(fn))
# return list_format
, which may contain function names, class names, or code. Output only the next line. | self.writeline(path_to_ls(abspath)) |
Continue the code snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Aniket Panse <contact@aniketpanse.in> grants Johnny Vestergaard <jkv@unixcluster.dk>
# a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# copyright license to reproduce, prepare derivative works of, publicly
# display, publicly perform, sublicense, relicense, and distribute [the] Contributions
# and such derivative works.
class VNCDecoder(object):
def __init__(self, challenge, response, passwd_list):
self.challenge = challenge
self.response = response
self.passwd_list = passwd_list
def decode(self):
for password in self.passwd_list:
password = password.strip('\n')
key = (password + '\0' * 8)[:8]
<|code_end|>
. Use current file imports:
from beeswarm.shared.vnc.des import RFBDes
and context (classes, functions, or code) from other files:
# Path: beeswarm/shared/vnc/des.py
# class RFBDes(pyDes.des):
# def setKey(self, key):
# """RFB protocol for authentication requires client to encrypt
# challenge sent by server with password using DES method. However,
# bits in each byte of the password are put in reverse order before
# using it as encryption key."""
# newkey = []
# for ki in range(len(key)):
# bsrc = ord(key[ki])
# btgt = 0
# for i in range(8):
# if bsrc & (1 << i):
# btgt |= 1 << 7 - i
# newkey.append(chr(btgt))
# super(RFBDes, self).setKey(newkey)
. Output only the next line. | encryptor = RFBDes(key) |
Based on the snippet: <|code_start|># This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
class BeeHTTPSHandler(BeeHTTPHandler):
"""
This class doesn't do anything about HTTPS, the difference is in the way the
HTML body is sent. We need smaller chunks for HTTPS apparently.
"""
def send_html(self, filename):
with self.vfs.open(filename) as f:
while True:
chunk = f.read(1024)
if not chunk:
break
self.request.send(chunk)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from beeswarm.drones.honeypot.capabilities.http import Http, BeeHTTPHandler
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
and context (classes, functions, sometimes code) from other files:
# Path: beeswarm/drones/honeypot/capabilities/http.py
# class Http(HandlerBase):
# HandlerClass = BeeHTTPHandler
#
# def __init__(self, options, workdir):
# super(Http, self).__init__(options, workdir)
# self._options = options
#
# def handle_session(self, gsocket, address):
# session = self.create_session(address)
# try:
# # The third argument ensures that the BeeHTTPHandler will access
# # only the data in vfs/var/www
# self.HandlerClass(gsocket, address, self.vfsystem.opendir('/var/www'), None, httpsession=session,
# options=self._options, users=self.users)
# except socket.error as err:
# logger.debug('Unexpected end of http session: {0}, errno: {1}. ({2})'.format(err, err.errno, session.id))
# finally:
# self.close_session(session)
#
# class BeeHTTPHandler(BaseHTTPRequestHandler):
# def __init__(self, request, client_address, vfs, server, httpsession, options, users):
#
# self.vfs = vfs
# self.users = users
# self.current_user = None # This is set if a login attempt is successful
#
# # Had to call parent initializer later, because the methods used
# # in BaseHTTPRequestHandler.__init__() call handle_one_request()
# # which calls the do_* methods here. If _banner, _session and _options
# # are not set, we get a bunch of errors (Undefined reference blah blah)
#
# self._options = options
# if 'banner' in self._options:
# self._banner = self._options['banner']
# else:
# self._banner = 'Microsoft-IIS/5.0'
# self._session = httpsession
# BaseHTTPRequestHandler.__init__(self, request, client_address, server)
# self._session.end_session()
#
# def do_HEAD(self):
# self.send_response(200)
# self.send_header('Content-type', 'text/html')
# self.end_headers()
#
# def do_AUTHHEAD(self):
# self.send_response(401)
# self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
# self.send_header('Content-type', 'text/html')
# self.end_headers()
#
# def do_GET(self):
# if self.headers.getheader('Authorization') is None:
# self.do_AUTHHEAD()
# self.send_html('please_auth.html')
# else:
# hdr = self.headers.getheader('Authorization')
# _, enc_uname_pwd = hdr.split(' ')
# dec_uname_pwd = base64.b64decode(enc_uname_pwd)
# uname, pwd = dec_uname_pwd.split(':')
# if not self._session.try_auth('plaintext', username=uname, password=pwd):
# self.do_AUTHHEAD()
# self.send_html('please_auth.html')
# else:
# self.do_HEAD()
# self.send_html('index.html')
# self.request.close()
#
# def send_html(self, filename):
#
# file_ = self.vfs.open(filename)
# send_whole_file(self.request.fileno(), file_.fileno())
# file_.close()
#
# def version_string(self):
# return self._banner
#
# # Disable logging provided by BaseHTTPServer
# def log_message(self, format_, *args):
# pass
#
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
. Output only the next line. | class https(Http, HandlerBase): |
Given the code snippet: <|code_start|># This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
class BeeHTTPSHandler(BeeHTTPHandler):
"""
This class doesn't do anything about HTTPS, the difference is in the way the
HTML body is sent. We need smaller chunks for HTTPS apparently.
"""
def send_html(self, filename):
with self.vfs.open(filename) as f:
while True:
chunk = f.read(1024)
if not chunk:
break
self.request.send(chunk)
<|code_end|>
, generate the next line using the imports in this file:
import logging
from beeswarm.drones.honeypot.capabilities.http import Http, BeeHTTPHandler
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
and context (functions, classes, or occasionally code) from other files:
# Path: beeswarm/drones/honeypot/capabilities/http.py
# class Http(HandlerBase):
# HandlerClass = BeeHTTPHandler
#
# def __init__(self, options, workdir):
# super(Http, self).__init__(options, workdir)
# self._options = options
#
# def handle_session(self, gsocket, address):
# session = self.create_session(address)
# try:
# # The third argument ensures that the BeeHTTPHandler will access
# # only the data in vfs/var/www
# self.HandlerClass(gsocket, address, self.vfsystem.opendir('/var/www'), None, httpsession=session,
# options=self._options, users=self.users)
# except socket.error as err:
# logger.debug('Unexpected end of http session: {0}, errno: {1}. ({2})'.format(err, err.errno, session.id))
# finally:
# self.close_session(session)
#
# class BeeHTTPHandler(BaseHTTPRequestHandler):
# def __init__(self, request, client_address, vfs, server, httpsession, options, users):
#
# self.vfs = vfs
# self.users = users
# self.current_user = None # This is set if a login attempt is successful
#
# # Had to call parent initializer later, because the methods used
# # in BaseHTTPRequestHandler.__init__() call handle_one_request()
# # which calls the do_* methods here. If _banner, _session and _options
# # are not set, we get a bunch of errors (Undefined reference blah blah)
#
# self._options = options
# if 'banner' in self._options:
# self._banner = self._options['banner']
# else:
# self._banner = 'Microsoft-IIS/5.0'
# self._session = httpsession
# BaseHTTPRequestHandler.__init__(self, request, client_address, server)
# self._session.end_session()
#
# def do_HEAD(self):
# self.send_response(200)
# self.send_header('Content-type', 'text/html')
# self.end_headers()
#
# def do_AUTHHEAD(self):
# self.send_response(401)
# self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
# self.send_header('Content-type', 'text/html')
# self.end_headers()
#
# def do_GET(self):
# if self.headers.getheader('Authorization') is None:
# self.do_AUTHHEAD()
# self.send_html('please_auth.html')
# else:
# hdr = self.headers.getheader('Authorization')
# _, enc_uname_pwd = hdr.split(' ')
# dec_uname_pwd = base64.b64decode(enc_uname_pwd)
# uname, pwd = dec_uname_pwd.split(':')
# if not self._session.try_auth('plaintext', username=uname, password=pwd):
# self.do_AUTHHEAD()
# self.send_html('please_auth.html')
# else:
# self.do_HEAD()
# self.send_html('index.html')
# self.request.close()
#
# def send_html(self, filename):
#
# file_ = self.vfs.open(filename)
# send_whole_file(self.request.fileno(), file_.fileno())
# file_.close()
#
# def version_string(self):
# return self._banner
#
# # Disable logging provided by BaseHTTPServer
# def log_message(self, format_, *args):
# pass
#
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
. Output only the next line. | class https(Http, HandlerBase): |
Based on the snippet: <|code_start|>
config_actor_socket = None
database_actor_socket = None
config_request_lock = gevent.lock.RLock()
database_request_lock = gevent.lock.RLock()
admin_passwd_file = 'admin_passwd_hash'
def connect_sockets():
global config_actor_socket, database_actor_socket
if config_actor_socket is not None:
config_actor_socket.disconnect(SocketNames.CONFIG_COMMANDS.value)
if database_actor_socket is not None:
database_actor_socket.disconnect(SocketNames.DATABASE_REQUESTS.value)
context = beeswarm.shared.zmq_context
config_actor_socket = context.socket(zmq.REQ)
database_actor_socket = context.socket(zmq.REQ)
config_actor_socket.connect(SocketNames.CONFIG_COMMANDS.value)
database_actor_socket.connect(SocketNames.DATABASE_REQUESTS.value)
connect_sockets()
def send_zmq_request_socket(socket, _request):
socket.send(_request)
result = socket.recv()
status, data = result.split(' ', 1)
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import logging
import random
import string
import ast
import gevent
import gevent.lock
import os
import uuid
import zmq.green as zmq
import beeswarm
from flask import Flask, render_template, redirect, flash, Response, abort
from flask.ext.login import LoginManager, login_user, current_user, login_required, logout_user, UserMixin
from werkzeug.security import check_password_hash
from werkzeug.security import generate_password_hash
from wtforms import HiddenField
from flask import request
from forms import HoneypotConfigurationForm, ClientConfigurationForm, LoginForm, SettingsForm
from beeswarm.shared.message_enum import Messages
from beeswarm.shared.socket_enum import SocketNames
and context (classes, functions, sometimes code) from other files:
# Path: beeswarm/shared/message_enum.py
# class Messages(Enum):
# STOP = 'STOP'
# START = 'START'
# CONFIG = 'CONFIG'
# # dump of all configuration elements known to the sender
# CONFIG_FULL = 'CONFIG_FULL'
# # mapping between clients, honeypots, capabilities and bait users
# CONFIG_ARCHITECTURE = 'CONFIG_ARCHITECTURE'
# BROADCAST = 'BROADCAST'
#
# OK = 'OK'
# FAIL = 'FAIL'
# # KEY DRONE_ID DRONE_PRIVATE_KEY
# KEY = 'KEY'
# # CERT DRONE_ID DRONE_CERT
# CERT = 'CERT'
#
# # All data on an entire session, this also indicates session end.
# SESSION_HONEYPOT = 'SESSION_HONEYPOT'
# # Network connect to a honeypot, data format is as in SESSION_HONEYPOT, but not all fields has data.
# SESSION_PART_HONEYPOT_SESSION_START = 'SESSION_PART_HONEYPOT_SESSION_START'
# # Authentication attempt, format is as in self.login_attempts list SESSION_HONEYPOT
# SESSION_PART_HONEYPOT_AUTH = 'SESSION_PART_HONEYPOT_AUTH'
# SESSION_CLIENT = 'SESSION_CLIENT'
#
# SET_CONFIG_ITEM = 'SET'
# GET_CONFIG_ITEM = 'GET'
# GET_ZMQ_KEYS = 'GET_ZMQ_KEYS'
# DELETE_ZMQ_KEYS = 'DELETE_ZMQ_KEYS'
# PING = 'PING'
# PONG = 'PING'
# IP = 'IP'
#
# DRONE_WANT_CONFIG = 'DRONE_WANT_CONFIG'
# DRONE_CONFIG = 'DRONE_CONFIG'
# # ID USERNAME PASSWORD
# BAIT_USER_ADD = 'BAIT_USER_ADD'
# BAIT_USER_DELETE = 'BAIT_USER_DELETE'
# GET_BAIT_USERS = 'GET_BAIT_USERS'
# DRONE_DELETE = 'DRONE_DELETE'
# DRONE_ADD = 'DRONE_ADD'
#
# # Session was deleted because it was matched with an existing session
# # This happens when a bait session is matched with a honeypot session.
# # ID_OF_DELETED_SESSION ID_OF_THE_MERGED_SESSION
# DELETED_DUE_TO_MERGE = "DELETED_DUE_TO_MERGE"
#
# # A classified session is transmitted
# # Parameters is data in json.
# SESSION = "SESSION"
#
# # Database requests
# GET_DB_STATS = 'GET_DB_STATS'
# # TODO: Following three should have to/from params to facilitate pagination
# GET_SESSIONS_ALL = 'GET_SESSIONS_ALL'
# GET_SESSIONS_BAIT = 'GET_SESSIONS_BAIT'
# GET_SESSIONS_ATTACKS = 'GET_SESSIONS_ATTACKS'
#
# # Param: session id
# GET_SESSION_TRANSCRIPT = 'GET_SESSION_TRANSCRIPT'
# # Param: session id
# GET_SESSION_CREDENTIALS = 'GET_SESSION_CREDENTIALS'
# # Param dronetype
# GET_DRONE_LIST = 'GET_DRONE_LIST'
# # Param: clientId config
# CONFIG_DRONE = 'CONFIG_DRONE'
#
# # Param: clientId config
# PING_ALL_DRONES = 'PING_ALL_DRONES'
#
# Path: beeswarm/shared/socket_enum.py
# class SocketNames(Enum):
# #### Sockets used on server ####
# # All data received from drones will be published on this socket
# DRONE_DATA = 'inproc://droneData'
# # After sessions has been classified they will get retransmitted on this socket.
# # TODO: Does not actually happen yet
# PROCESSED_SESSIONS = 'inproc://processedSessionPublisher'
# # Request / Reply to config actor
# CONFIG_COMMANDS = 'inproc://configCommands'
# # Data sent on this socket will be retransmitted to the correct drone, the data must be prefixed with
# # the id of the drone.
# DRONE_COMMANDS = 'inproc://droneCommands'
#
#
# # Requests to and from the databsae
# DATABASE_REQUESTS = 'inproc://databaseRequests'
#
# #### Sockets used on drones ####
# # Drone commands received from the server will be retransmitted on this socket.
# SERVER_COMMANDS = 'inproc://serverCommands'
# # All messages transmitted on this socket will get retransmitted to the server
# SERVER_RELAY = 'inproc://serverRelay'
. Output only the next line. | if status != Messages.OK.value: |
Here is a snippet: <|code_start|> return isinstance(field, HiddenField)
app = Flask(__name__)
app.config['DEBUG'] = False
app.config['WTF_CSRF_ENABLED'] = True
app.config['SECRET_KEY'] = ''.join(random.choice(string.lowercase) for x in range(random.randint(16, 32)))
app.jinja_env.filters['bootstrap_is_hidden_field'] = is_hidden_field_filter
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
logger = logging.getLogger(__name__)
first_cfg_received = gevent.event.Event()
# keys used for adding new drones to the system
drone_keys = []
config_actor_socket = None
database_actor_socket = None
config_request_lock = gevent.lock.RLock()
database_request_lock = gevent.lock.RLock()
admin_passwd_file = 'admin_passwd_hash'
def connect_sockets():
global config_actor_socket, database_actor_socket
if config_actor_socket is not None:
<|code_end|>
. Write the next line using the current file imports:
import json
import logging
import random
import string
import ast
import gevent
import gevent.lock
import os
import uuid
import zmq.green as zmq
import beeswarm
from flask import Flask, render_template, redirect, flash, Response, abort
from flask.ext.login import LoginManager, login_user, current_user, login_required, logout_user, UserMixin
from werkzeug.security import check_password_hash
from werkzeug.security import generate_password_hash
from wtforms import HiddenField
from flask import request
from forms import HoneypotConfigurationForm, ClientConfigurationForm, LoginForm, SettingsForm
from beeswarm.shared.message_enum import Messages
from beeswarm.shared.socket_enum import SocketNames
and context from other files:
# Path: beeswarm/shared/message_enum.py
# class Messages(Enum):
# STOP = 'STOP'
# START = 'START'
# CONFIG = 'CONFIG'
# # dump of all configuration elements known to the sender
# CONFIG_FULL = 'CONFIG_FULL'
# # mapping between clients, honeypots, capabilities and bait users
# CONFIG_ARCHITECTURE = 'CONFIG_ARCHITECTURE'
# BROADCAST = 'BROADCAST'
#
# OK = 'OK'
# FAIL = 'FAIL'
# # KEY DRONE_ID DRONE_PRIVATE_KEY
# KEY = 'KEY'
# # CERT DRONE_ID DRONE_CERT
# CERT = 'CERT'
#
# # All data on an entire session, this also indicates session end.
# SESSION_HONEYPOT = 'SESSION_HONEYPOT'
# # Network connect to a honeypot, data format is as in SESSION_HONEYPOT, but not all fields has data.
# SESSION_PART_HONEYPOT_SESSION_START = 'SESSION_PART_HONEYPOT_SESSION_START'
# # Authentication attempt, format is as in self.login_attempts list SESSION_HONEYPOT
# SESSION_PART_HONEYPOT_AUTH = 'SESSION_PART_HONEYPOT_AUTH'
# SESSION_CLIENT = 'SESSION_CLIENT'
#
# SET_CONFIG_ITEM = 'SET'
# GET_CONFIG_ITEM = 'GET'
# GET_ZMQ_KEYS = 'GET_ZMQ_KEYS'
# DELETE_ZMQ_KEYS = 'DELETE_ZMQ_KEYS'
# PING = 'PING'
# PONG = 'PING'
# IP = 'IP'
#
# DRONE_WANT_CONFIG = 'DRONE_WANT_CONFIG'
# DRONE_CONFIG = 'DRONE_CONFIG'
# # ID USERNAME PASSWORD
# BAIT_USER_ADD = 'BAIT_USER_ADD'
# BAIT_USER_DELETE = 'BAIT_USER_DELETE'
# GET_BAIT_USERS = 'GET_BAIT_USERS'
# DRONE_DELETE = 'DRONE_DELETE'
# DRONE_ADD = 'DRONE_ADD'
#
# # Session was deleted because it was matched with an existing session
# # This happens when a bait session is matched with a honeypot session.
# # ID_OF_DELETED_SESSION ID_OF_THE_MERGED_SESSION
# DELETED_DUE_TO_MERGE = "DELETED_DUE_TO_MERGE"
#
# # A classified session is transmitted
# # Parameters is data in json.
# SESSION = "SESSION"
#
# # Database requests
# GET_DB_STATS = 'GET_DB_STATS'
# # TODO: Following three should have to/from params to facilitate pagination
# GET_SESSIONS_ALL = 'GET_SESSIONS_ALL'
# GET_SESSIONS_BAIT = 'GET_SESSIONS_BAIT'
# GET_SESSIONS_ATTACKS = 'GET_SESSIONS_ATTACKS'
#
# # Param: session id
# GET_SESSION_TRANSCRIPT = 'GET_SESSION_TRANSCRIPT'
# # Param: session id
# GET_SESSION_CREDENTIALS = 'GET_SESSION_CREDENTIALS'
# # Param dronetype
# GET_DRONE_LIST = 'GET_DRONE_LIST'
# # Param: clientId config
# CONFIG_DRONE = 'CONFIG_DRONE'
#
# # Param: clientId config
# PING_ALL_DRONES = 'PING_ALL_DRONES'
#
# Path: beeswarm/shared/socket_enum.py
# class SocketNames(Enum):
# #### Sockets used on server ####
# # All data received from drones will be published on this socket
# DRONE_DATA = 'inproc://droneData'
# # After sessions has been classified they will get retransmitted on this socket.
# # TODO: Does not actually happen yet
# PROCESSED_SESSIONS = 'inproc://processedSessionPublisher'
# # Request / Reply to config actor
# CONFIG_COMMANDS = 'inproc://configCommands'
# # Data sent on this socket will be retransmitted to the correct drone, the data must be prefixed with
# # the id of the drone.
# DRONE_COMMANDS = 'inproc://droneCommands'
#
#
# # Requests to and from the databsae
# DATABASE_REQUESTS = 'inproc://databaseRequests'
#
# #### Sockets used on drones ####
# # Drone commands received from the server will be retransmitted on this socket.
# SERVER_COMMANDS = 'inproc://serverCommands'
# # All messages transmitted on this socket will get retransmitted to the server
# SERVER_RELAY = 'inproc://serverRelay'
, which may include functions, classes, or code. Output only the next line. | config_actor_socket.disconnect(SocketNames.CONFIG_COMMANDS.value) |
Next line prediction: <|code_start|> self.respond('550 The system cannot find the file specified.')
def do_TYPE(self, arg):
self.transfer_mode = arg
self.respond('200 Transfer type set to:' + self.transfer_mode)
def getcmd(self):
return self.conn.recv(512)
def start_data_conn(self):
if self.mode == 'PASV':
self.client_sock, (self.cli_ip, self.cli_port) = self.serv_sock.accept()
else:
self.client_sock = socket.socket()
self.client_sock.connect((self.cli_ip, self.cli_port))
def stop_data_conn(self):
self.client_sock.close()
if self.mode == 'PASV':
self.serv_sock.close()
def respond(self, msg):
msg += TERMINATOR
self.session.transcript_outgoing(msg)
self.conn.send(msg)
def stop(self):
self.session.end_session()
<|code_end|>
. Use current file imports:
(import logging
import os
from gevent import socket
from fs.path import dirname
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
from beeswarm.drones.honeypot.helpers.common import send_whole_file, path_to_ls)
and context including class names, function names, or small code snippets from other files:
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
#
# Path: beeswarm/drones/honeypot/helpers/common.py
# def send_whole_file(sock_fd, file_fd):
# offset = 0
# while True:
# sent = sendfile(sock_fd, file_fd, offset, 65536)
# if sent == 0:
# break
# offset += sent
#
# def path_to_ls(fn):
# """ Converts an absolute path to an entry resembling the output of
# the ls command on most UNIX systems."""
# st = os.stat(fn)
# full_mode = 'rwxrwxrwx'
# mode = ''
# file_time = ''
# d = ''
# for i in range(9):
# # Incrementally builds up the 9 character string, using characters from the
# # fullmode (defined above) and mode bits from the stat() system call.
# mode += ((st.st_mode >> (8 - i)) & 1) and full_mode[i] or '-'
# d = (os.path.isdir(fn)) and 'd' or '-'
# file_time = time.strftime(' %b %d %H:%M ', time.gmtime(st.st_mtime))
# list_format = '{0}{1} 1 ftp ftp {2}\t{3}{4}'.format(d, mode, str(st.st_size), file_time, os.path.basename(fn))
# return list_format
. Output only the next line. | class ftp(HandlerBase): |
Next line prediction: <|code_start|>
def do_PWD(self, arg):
self.respond('257 "%s"' % self.working_dir)
def do_PASV(self, arg):
self.mode = 'PASV'
self.serv_sock = socket.socket()
self.serv_sock.bind((self.local_ip, 0))
self.serv_sock.listen(1)
ip, port = self.serv_sock.getsockname()
self.respond('227 Entering Passive Mode (%s,%u,%u).' % (','.join(ip.split('.')),
port >> 8 & 0xFF, port & 0xFF))
def do_NOOP(self, arg):
self.respond('200 Command Successful.')
def do_SYST(self, arg):
self.respond('215 %s' % self.syst_type)
def do_QUIT(self, arg):
self.respond('221 Bye.')
self.serve_flag = False
self.stop()
def do_RETR(self, arg):
filename = os.path.join(self.working_dir, arg)
if self.vfs.isfile(filename):
self.respond('150 Initiating transfer.')
self.start_data_conn()
file_ = self.vfs.open(filename)
<|code_end|>
. Use current file imports:
(import logging
import os
from gevent import socket
from fs.path import dirname
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
from beeswarm.drones.honeypot.helpers.common import send_whole_file, path_to_ls)
and context including class names, function names, or small code snippets from other files:
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
#
# Path: beeswarm/drones/honeypot/helpers/common.py
# def send_whole_file(sock_fd, file_fd):
# offset = 0
# while True:
# sent = sendfile(sock_fd, file_fd, offset, 65536)
# if sent == 0:
# break
# offset += sent
#
# def path_to_ls(fn):
# """ Converts an absolute path to an entry resembling the output of
# the ls command on most UNIX systems."""
# st = os.stat(fn)
# full_mode = 'rwxrwxrwx'
# mode = ''
# file_time = ''
# d = ''
# for i in range(9):
# # Incrementally builds up the 9 character string, using characters from the
# # fullmode (defined above) and mode bits from the stat() system call.
# mode += ((st.st_mode >> (8 - i)) & 1) and full_mode[i] or '-'
# d = (os.path.isdir(fn)) and 'd' or '-'
# file_time = time.strftime(' %b %d %H:%M ', time.gmtime(st.st_mtime))
# list_format = '{0}{1} 1 ftp ftp {2}\t{3}{4}'.format(d, mode, str(st.st_size), file_time, os.path.basename(fn))
# return list_format
. Output only the next line. | send_whole_file(self.client_sock.fileno(), file_.fileno()) |
Here is a snippet: <|code_start|> self.respond('230 Login Successful.')
else:
self.authenticated = False
self.respond('530 Authentication Failed.')
if self.session.get_number_of_login_attempts() >= self.max_logins:
self.stop()
def do_PORT(self, arg):
if self.mode == 'PASV':
self.client_sock.close()
self.mode = 'PORT'
try:
portlist = arg.split(',')
except ValueError:
self.respond('501 Bad syntax for PORT.')
return
if len(portlist) != 6:
self.respond('501 Bad syntax for PORT.')
return
self.cli_ip = '.'.join(portlist[:4])
self.cli_port = (int(portlist[4]) << 8) + int(portlist[5])
self.respond('200 PORT Command Successful')
def do_LIST(self, arg):
self.respond('150 Listing Files.')
self.start_data_conn()
file_names = self.vfs.listdir(self.working_dir)
for fname in file_names:
abspath = self.vfs.getsyspath(self.working_dir + '/' + fname)
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
from gevent import socket
from fs.path import dirname
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
from beeswarm.drones.honeypot.helpers.common import send_whole_file, path_to_ls
and context from other files:
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
#
# Path: beeswarm/drones/honeypot/helpers/common.py
# def send_whole_file(sock_fd, file_fd):
# offset = 0
# while True:
# sent = sendfile(sock_fd, file_fd, offset, 65536)
# if sent == 0:
# break
# offset += sent
#
# def path_to_ls(fn):
# """ Converts an absolute path to an entry resembling the output of
# the ls command on most UNIX systems."""
# st = os.stat(fn)
# full_mode = 'rwxrwxrwx'
# mode = ''
# file_time = ''
# d = ''
# for i in range(9):
# # Incrementally builds up the 9 character string, using characters from the
# # fullmode (defined above) and mode bits from the stat() system call.
# mode += ((st.st_mode >> (8 - i)) & 1) and full_mode[i] or '-'
# d = (os.path.isdir(fn)) and 'd' or '-'
# file_time = time.strftime(' %b %d %H:%M ', time.gmtime(st.st_mtime))
# list_format = '{0}{1} 1 ftp ftp {2}\t{3}{4}'.format(d, mode, str(st.st_size), file_time, os.path.basename(fn))
# return list_format
, which may include functions, classes, or code. Output only the next line. | self.client_sock.send(path_to_ls(abspath) + '\r\n') |
Predict the next line after this snippet: <|code_start|># and such derivative works.
gevent.monkey.patch_all()
class DispatcherTests(unittest.TestCase):
def setUp(self):
self.work_dir = tempfile.mkdtemp()
self.test_config_file = os.path.join(os.path.dirname(__file__), 'clientcfg.json.test')
def tearDown(self):
if os.path.isdir(self.work_dir):
shutil.rmtree(self.work_dir)
def test_dispatcher(self):
options = {
'enabled': True,
'server': '127.0.0.1',
'active_range': '00:00 - 23:59',
'sleep_interval': '1',
'activation_probability': '1',
'username': 'test',
'password': 'test',
'port': 8080}
<|code_end|>
using the current file's imports:
import shutil
import time
import tempfile
import os
import gevent
import gevent.monkey
import unittest
from gevent.greenlet import Greenlet
from mock import Mock
from beeswarm.drones.client.models.dispatcher import BaitDispatcher
and any relevant context from other files:
# Path: beeswarm/drones/client/models/dispatcher.py
# class BaitDispatcher(Greenlet):
# """ Dispatches capabilities in a realistic fashion (with respect to timings) """
#
# def __init__(self, bait_type, bait_options):
# Greenlet.__init__(self)
# self.options = bait_options
# self.enabled = False
# self.bait_type = bait_type
# self.run_flag = True
# # my_ip and sessions should be moved from here
# self.bait_session_running = False
# self.start_time = None
# self.end_time = None
# try:
# self.set_active_interval()
# except (ValueError, AttributeError, KeyError, IndexError) as err:
# logger.debug('Caught exception: {0} ({1})'.format(err, str(type(err))))
#
# self.activation_probability = self.options['activation_probability']
# self.sleep_interval = float(self.options['sleep_interval'])
#
# def set_active_interval(self):
# interval_string = self.options['active_range']
# begin, end = interval_string.split('-')
# begin = begin.strip()
# end = end.strip()
# begin_hours, begin_min = begin.split(':')
# end_hours, end_min = end.split(':')
# self.start_time = datetime.time(int(begin_hours), int(begin_min))
# self.end_time = datetime.time(int(end_hours), int(end_min))
#
# def _run(self):
# # TODO: This could be done better and more clearly, something along the lines of :
# # 1. spawn_later(second_until_start_of_range, GOTO 2)
# # 2. Role the die and check probability
# # 2.1 Inside probability spawn bait session, after end of session GOTO 3
# # 2.2 If not inside probability GOTO 3
# # 3. If sleep_interval + time_now IS INSIDE timerange: spawn_later(sleep_interval)
# # ELSE GOTO 1
# while self.run_flag:
# while not self.time_in_range():
# gevent.sleep(5)
# while self.time_in_range():
# if self.activation_probability >= random.random() and not self.bait_session_running:
# if not self.options['server']:
# logging.debug('Discarding bait session because the honeypot has not announced '
# 'the ip address yet')
# else:
# self.bait_session_running = True
# # TODO: sessions whould be moved from here, too many has knowledge of the sessions list
# bait = self.bait_type(self.options)
# greenlet = gevent.spawn(bait.start)
# greenlet.link(self._on_bait_session_ended)
# else:
# logging.debug('Not spawing {0} because a bait session of this type is '
# 'already running.'.format(self.bait_type))
# logging.debug('Scheduling next {0} bait session in {1} second.'
# .format(self.bait_type, self.sleep_interval))
# gevent.sleep(self.sleep_interval)
#
# def _on_bait_session_ended(self, greenlet):
# self.bait_session_running = False
#
# if greenlet.exception is not None:
# logger.warning('Bait session of type {0} stopped with unhandled '
# 'error: {1}'.format(self.bait_type, greenlet.exception))
#
#
# def time_in_range(self):
# """Return true if current time is in the active range"""
# curr = datetime.datetime.now().time()
# if self.start_time <= self.end_time:
# return self.start_time <= curr <= self.end_time
# else:
# return self.start_time <= curr or curr <= self.end_time
. Output only the next line. | dispatcher = BaitDispatcher(Mock(), options) |
Given the code snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class ClientBase(object):
""" Base class for Bees. This should only be used after sub-classing. """
def __init__(self, options):
"""
Initializes common values.
:param sessions: A dict which is updated every time a new session is created.
:param options: A dict containing the options entry for this bait
"""
self.options = options
self.sessions = {}
def create_session(self, server_host, server_port, honeypot_id):
"""
Creates a new session.
:param server_host: IP address of the server
:param server_port: Server port
:return: A new `BaitSession` object.
"""
protocol = self.__class__.__name__.lower()
<|code_end|>
, generate the next line using the imports in this file:
from beeswarm.drones.client.models.session import BaitSession
and context (functions, classes, or occasionally code) from other files:
# Path: beeswarm/drones/client/models/session.py
# class BaitSession(BaseSession):
# client_id = ''
#
# def __init__(self, protocol, destination_ip, destination_port, honeypot_id):
# super(BaitSession, self).__init__(protocol, destination_ip=destination_ip,
# destination_port=destination_port)
#
# assert BaitSession.client_id
#
# self.client_id = BaitSession.client_id
# self.honeypot_id = honeypot_id
#
# self.did_connect = False
# self.did_login = False
# self.alldone = False
# self.did_complete = False
# self.protocol_data = {}
#
# def to_dict(self):
# return vars(self)
#
# def end_session(self):
# super(BaitSession, self).end_session(Messages.SESSION_CLIENT.value)
. Output only the next line. | session = BaitSession(protocol, server_host, server_port, honeypot_id) |
Next line prediction: <|code_start|> def handle(self):
self.request.send(RFB_VERSION)
client_version = self.request.recv(1024)
if client_version == RFB_VERSION:
self.security_handshake()
else:
self.finish()
def security_handshake(self):
self.request.send(SUPPORTED_AUTH_METHODS)
sec_method = self.request.recv(1024)
if sec_method == VNC_AUTH:
self.do_vnc_authentication()
else:
self.finish()
def do_vnc_authentication(self):
challenge = get_random_challenge()
self.request.send(challenge)
client_response_ = self.request.recv(1024)
# This could result in an ugly log file, since the des_challenge is just an array of 4 bytes
self.session.try_auth('des_challenge', challenge=challenge, response=client_response_)
if self.session.authenticated:
self.request.send(AUTH_SUCCESSFUL)
else:
self.request.send(AUTH_FAILED)
self.finish()
<|code_end|>
. Use current file imports:
(import socket
import random
import logging
import SocketServer
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
from beeswarm.shared.vnc_constants import *)
and context including class names, function names, or small code snippets from other files:
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
. Output only the next line. | class Vnc(HandlerBase): |
Here is a snippet: <|code_start|> data.append(text)
self.__data = NEWLINE.join(data)
status = self.__server.process_message(
self.__peer,
self.__mailfrom,
self.__rcpttos,
self.__data
)
self.__rcpttos = []
self.__mailfrom = None
self.__state = self.COMMAND
self.set_terminator('\r\n')
if not status:
self.push('250 Ok')
else:
self.push(status)
class DummySMTPServer(object):
def __init__(self, mail_vfs):
self.mail_vfs = mail_vfs
self.mboxpath = self.mail_vfs.getsyspath('mailbox')
def process_message(self, peer, mailfrom, rcpttos, data):
logging.info('Got new mail, peer ({}), from ({}), to ({})'.format(peer, mailfrom, rcpttos))
if self.mboxpath is not None:
mbox = mailbox.mbox(self.mboxpath, create=True)
mbox.add(data)
<|code_end|>
. Write the next line using the current file imports:
import base64
import logging
import time
import random
import smtpd
import asyncore
import asynchat
import mailbox
from smtpd import NEWLINE, EMPTYSTRING
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
and context from other files:
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
, which may include functions, classes, or code. Output only the next line. | class smtp(HandlerBase): |
Given snippet: <|code_start|># Copyright (C) 2016 Johnny Vestergaard <jkv@unixcluster.dk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class TimeTests(unittest.TestCase):
def test_isoFormatToDateTime(self):
no_microseconds = datetime(2016, 11, 12, 11, 47, 20, 0)
no_microseconds_isoformat = no_microseconds.isoformat()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import unittest
from datetime import datetime
from beeswarm.shared.misc.time import isoformatToDatetime
and context:
# Path: beeswarm/shared/misc/time.py
# def isoformatToDatetime(timestamp):
# if '.' in timestamp:
# return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f')
# else:
# return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
which might include code, classes, or functions. Output only the next line. | self.assertEquals(isoformatToDatetime(no_microseconds_isoformat), no_microseconds) |
Continue the code snippet: <|code_start|>#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
class BaseLogger(Greenlet):
def __init__(self, options):
Greenlet.__init__(self)
self.enabled = True
self.options = options
def _run(self):
context = beeswarm.shared.zmq_context
processed_sessions_socket = context.socket(zmq.SUB)
<|code_end|>
. Use current file imports:
import logging
import zmq.green as zmq
import beeswarm
from gevent import Greenlet
from beeswarm.shared.socket_enum import SocketNames
and context (classes, functions, or code) from other files:
# Path: beeswarm/shared/socket_enum.py
# class SocketNames(Enum):
# #### Sockets used on server ####
# # All data received from drones will be published on this socket
# DRONE_DATA = 'inproc://droneData'
# # After sessions has been classified they will get retransmitted on this socket.
# # TODO: Does not actually happen yet
# PROCESSED_SESSIONS = 'inproc://processedSessionPublisher'
# # Request / Reply to config actor
# CONFIG_COMMANDS = 'inproc://configCommands'
# # Data sent on this socket will be retransmitted to the correct drone, the data must be prefixed with
# # the id of the drone.
# DRONE_COMMANDS = 'inproc://droneCommands'
#
#
# # Requests to and from the databsae
# DATABASE_REQUESTS = 'inproc://databaseRequests'
#
# #### Sockets used on drones ####
# # Drone commands received from the server will be retransmitted on this socket.
# SERVER_COMMANDS = 'inproc://serverCommands'
# # All messages transmitted on this socket will get retransmitted to the server
# SERVER_RELAY = 'inproc://serverRelay'
. Output only the next line. | processed_sessions_socket.connect(SocketNames.PROCESSED_SESSIONS.value) |
Continue the code snippet: <|code_start|>
context = beeswarm.shared.zmq_context
self.config_commands = context.socket(zmq.REP)
self.enabled = True
def stop(self):
self.enabled = False
if self.config_commands:
self.config_commands.close()
def _run(self):
self.config_commands.bind(SocketNames.CONFIG_COMMANDS.value)
poller = zmq.Poller()
poller.register(self.config_commands, zmq.POLLIN)
while self.enabled:
socks = dict(poller.poll(500))
if self.config_commands in socks and socks[self.config_commands] == zmq.POLLIN:
self._handle_commands()
def _handle_commands(self):
msg = self.config_commands.recv()
if ' ' in msg:
cmd, data = msg.split(' ', 1)
else:
cmd = msg
logger.debug('Received command: {0}'.format(cmd))
<|code_end|>
. Use current file imports:
import json
import logging
import os
import tempfile
import shutil
import zmq.green as zmq
import beeswarm
from gevent import Greenlet
from zmq.auth.certs import create_certificates
from beeswarm.shared.message_enum import Messages
from beeswarm.shared.socket_enum import SocketNames
and context (classes, functions, or code) from other files:
# Path: beeswarm/shared/message_enum.py
# class Messages(Enum):
# STOP = 'STOP'
# START = 'START'
# CONFIG = 'CONFIG'
# # dump of all configuration elements known to the sender
# CONFIG_FULL = 'CONFIG_FULL'
# # mapping between clients, honeypots, capabilities and bait users
# CONFIG_ARCHITECTURE = 'CONFIG_ARCHITECTURE'
# BROADCAST = 'BROADCAST'
#
# OK = 'OK'
# FAIL = 'FAIL'
# # KEY DRONE_ID DRONE_PRIVATE_KEY
# KEY = 'KEY'
# # CERT DRONE_ID DRONE_CERT
# CERT = 'CERT'
#
# # All data on an entire session, this also indicates session end.
# SESSION_HONEYPOT = 'SESSION_HONEYPOT'
# # Network connect to a honeypot, data format is as in SESSION_HONEYPOT, but not all fields has data.
# SESSION_PART_HONEYPOT_SESSION_START = 'SESSION_PART_HONEYPOT_SESSION_START'
# # Authentication attempt, format is as in self.login_attempts list SESSION_HONEYPOT
# SESSION_PART_HONEYPOT_AUTH = 'SESSION_PART_HONEYPOT_AUTH'
# SESSION_CLIENT = 'SESSION_CLIENT'
#
# SET_CONFIG_ITEM = 'SET'
# GET_CONFIG_ITEM = 'GET'
# GET_ZMQ_KEYS = 'GET_ZMQ_KEYS'
# DELETE_ZMQ_KEYS = 'DELETE_ZMQ_KEYS'
# PING = 'PING'
# PONG = 'PING'
# IP = 'IP'
#
# DRONE_WANT_CONFIG = 'DRONE_WANT_CONFIG'
# DRONE_CONFIG = 'DRONE_CONFIG'
# # ID USERNAME PASSWORD
# BAIT_USER_ADD = 'BAIT_USER_ADD'
# BAIT_USER_DELETE = 'BAIT_USER_DELETE'
# GET_BAIT_USERS = 'GET_BAIT_USERS'
# DRONE_DELETE = 'DRONE_DELETE'
# DRONE_ADD = 'DRONE_ADD'
#
# # Session was deleted because it was matched with an existing session
# # This happens when a bait session is matched with a honeypot session.
# # ID_OF_DELETED_SESSION ID_OF_THE_MERGED_SESSION
# DELETED_DUE_TO_MERGE = "DELETED_DUE_TO_MERGE"
#
# # A classified session is transmitted
# # Parameters is data in json.
# SESSION = "SESSION"
#
# # Database requests
# GET_DB_STATS = 'GET_DB_STATS'
# # TODO: Following three should have to/from params to facilitate pagination
# GET_SESSIONS_ALL = 'GET_SESSIONS_ALL'
# GET_SESSIONS_BAIT = 'GET_SESSIONS_BAIT'
# GET_SESSIONS_ATTACKS = 'GET_SESSIONS_ATTACKS'
#
# # Param: session id
# GET_SESSION_TRANSCRIPT = 'GET_SESSION_TRANSCRIPT'
# # Param: session id
# GET_SESSION_CREDENTIALS = 'GET_SESSION_CREDENTIALS'
# # Param dronetype
# GET_DRONE_LIST = 'GET_DRONE_LIST'
# # Param: clientId config
# CONFIG_DRONE = 'CONFIG_DRONE'
#
# # Param: clientId config
# PING_ALL_DRONES = 'PING_ALL_DRONES'
#
# Path: beeswarm/shared/socket_enum.py
# class SocketNames(Enum):
# #### Sockets used on server ####
# # All data received from drones will be published on this socket
# DRONE_DATA = 'inproc://droneData'
# # After sessions has been classified they will get retransmitted on this socket.
# # TODO: Does not actually happen yet
# PROCESSED_SESSIONS = 'inproc://processedSessionPublisher'
# # Request / Reply to config actor
# CONFIG_COMMANDS = 'inproc://configCommands'
# # Data sent on this socket will be retransmitted to the correct drone, the data must be prefixed with
# # the id of the drone.
# DRONE_COMMANDS = 'inproc://droneCommands'
#
#
# # Requests to and from the databsae
# DATABASE_REQUESTS = 'inproc://databaseRequests'
#
# #### Sockets used on drones ####
# # Drone commands received from the server will be retransmitted on this socket.
# SERVER_COMMANDS = 'inproc://serverCommands'
# # All messages transmitted on this socket will get retransmitted to the server
# SERVER_RELAY = 'inproc://serverRelay'
. Output only the next line. | if cmd == Messages.SET_CONFIG_ITEM.value: |
Based on the snippet: <|code_start|># along with this program. If not, see <http://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
class ConfigActor(Greenlet):
def __init__(self, config_file, work_dir):
Greenlet.__init__(self)
self.config_file = os.path.join(work_dir, config_file)
if not os.path.exists(self.config_file):
self.config = {}
self._save_config_file()
self.config = json.load(open(self.config_file, 'r'))
self.work_dir = work_dir
context = beeswarm.shared.zmq_context
self.config_commands = context.socket(zmq.REP)
self.enabled = True
def stop(self):
self.enabled = False
if self.config_commands:
self.config_commands.close()
def _run(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import logging
import os
import tempfile
import shutil
import zmq.green as zmq
import beeswarm
from gevent import Greenlet
from zmq.auth.certs import create_certificates
from beeswarm.shared.message_enum import Messages
from beeswarm.shared.socket_enum import SocketNames
and context (classes, functions, sometimes code) from other files:
# Path: beeswarm/shared/message_enum.py
# class Messages(Enum):
# STOP = 'STOP'
# START = 'START'
# CONFIG = 'CONFIG'
# # dump of all configuration elements known to the sender
# CONFIG_FULL = 'CONFIG_FULL'
# # mapping between clients, honeypots, capabilities and bait users
# CONFIG_ARCHITECTURE = 'CONFIG_ARCHITECTURE'
# BROADCAST = 'BROADCAST'
#
# OK = 'OK'
# FAIL = 'FAIL'
# # KEY DRONE_ID DRONE_PRIVATE_KEY
# KEY = 'KEY'
# # CERT DRONE_ID DRONE_CERT
# CERT = 'CERT'
#
# # All data on an entire session, this also indicates session end.
# SESSION_HONEYPOT = 'SESSION_HONEYPOT'
# # Network connect to a honeypot, data format is as in SESSION_HONEYPOT, but not all fields has data.
# SESSION_PART_HONEYPOT_SESSION_START = 'SESSION_PART_HONEYPOT_SESSION_START'
# # Authentication attempt, format is as in self.login_attempts list SESSION_HONEYPOT
# SESSION_PART_HONEYPOT_AUTH = 'SESSION_PART_HONEYPOT_AUTH'
# SESSION_CLIENT = 'SESSION_CLIENT'
#
# SET_CONFIG_ITEM = 'SET'
# GET_CONFIG_ITEM = 'GET'
# GET_ZMQ_KEYS = 'GET_ZMQ_KEYS'
# DELETE_ZMQ_KEYS = 'DELETE_ZMQ_KEYS'
# PING = 'PING'
# PONG = 'PING'
# IP = 'IP'
#
# DRONE_WANT_CONFIG = 'DRONE_WANT_CONFIG'
# DRONE_CONFIG = 'DRONE_CONFIG'
# # ID USERNAME PASSWORD
# BAIT_USER_ADD = 'BAIT_USER_ADD'
# BAIT_USER_DELETE = 'BAIT_USER_DELETE'
# GET_BAIT_USERS = 'GET_BAIT_USERS'
# DRONE_DELETE = 'DRONE_DELETE'
# DRONE_ADD = 'DRONE_ADD'
#
# # Session was deleted because it was matched with an existing session
# # This happens when a bait session is matched with a honeypot session.
# # ID_OF_DELETED_SESSION ID_OF_THE_MERGED_SESSION
# DELETED_DUE_TO_MERGE = "DELETED_DUE_TO_MERGE"
#
# # A classified session is transmitted
# # Parameters is data in json.
# SESSION = "SESSION"
#
# # Database requests
# GET_DB_STATS = 'GET_DB_STATS'
# # TODO: Following three should have to/from params to facilitate pagination
# GET_SESSIONS_ALL = 'GET_SESSIONS_ALL'
# GET_SESSIONS_BAIT = 'GET_SESSIONS_BAIT'
# GET_SESSIONS_ATTACKS = 'GET_SESSIONS_ATTACKS'
#
# # Param: session id
# GET_SESSION_TRANSCRIPT = 'GET_SESSION_TRANSCRIPT'
# # Param: session id
# GET_SESSION_CREDENTIALS = 'GET_SESSION_CREDENTIALS'
# # Param dronetype
# GET_DRONE_LIST = 'GET_DRONE_LIST'
# # Param: clientId config
# CONFIG_DRONE = 'CONFIG_DRONE'
#
# # Param: clientId config
# PING_ALL_DRONES = 'PING_ALL_DRONES'
#
# Path: beeswarm/shared/socket_enum.py
# class SocketNames(Enum):
# #### Sockets used on server ####
# # All data received from drones will be published on this socket
# DRONE_DATA = 'inproc://droneData'
# # After sessions has been classified they will get retransmitted on this socket.
# # TODO: Does not actually happen yet
# PROCESSED_SESSIONS = 'inproc://processedSessionPublisher'
# # Request / Reply to config actor
# CONFIG_COMMANDS = 'inproc://configCommands'
# # Data sent on this socket will be retransmitted to the correct drone, the data must be prefixed with
# # the id of the drone.
# DRONE_COMMANDS = 'inproc://droneCommands'
#
#
# # Requests to and from the databsae
# DATABASE_REQUESTS = 'inproc://databaseRequests'
#
# #### Sockets used on drones ####
# # Drone commands received from the server will be retransmitted on this socket.
# SERVER_COMMANDS = 'inproc://serverCommands'
# # All messages transmitted on this socket will get retransmitted to the server
# SERVER_RELAY = 'inproc://serverRelay'
. Output only the next line. | self.config_commands.bind(SocketNames.CONFIG_COMMANDS.value) |
Based on the snippet: <|code_start|># This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Aniket Panse <contact@aniketpanse.in> grants Johnny Vestergaard <jkv@unixcluster.dk>
# a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
# copyright license to reproduce, prepare derivative works of, publicly
# display, publicly perform, sublicense, relicense, and distribute [the] Contributions
# and such derivative works.
class VncDecoderTests(unittest.TestCase):
def test_combinations(self):
"""Tests different combinations of challenge/response pairs and checks if
we can find the right password.
"""
passwords = ['1q2w3e4r', 'asdf', '1234', 'beeswarm', 'random']
# Real password is 1234
challenge = '\x1f\x9c+\t\x14\x03\xfaj\xde\x97p\xe9e\xca\x08\xff'
response = '\xe7\xe2\xe2\xa8\x89T\x87\x8d\xf01\x96\x10\xfe\xb9\xc5\xbb'
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from beeswarm.shared.vnc.decoder import VNCDecoder
and context (classes, functions, sometimes code) from other files:
# Path: beeswarm/shared/vnc/decoder.py
# class VNCDecoder(object):
# def __init__(self, challenge, response, passwd_list):
# self.challenge = challenge
# self.response = response
# self.passwd_list = passwd_list
#
# def decode(self):
# for password in self.passwd_list:
# password = password.strip('\n')
# key = (password + '\0' * 8)[:8]
# encryptor = RFBDes(key)
# resp = encryptor.encrypt(self.challenge)
# if resp == self.response:
# return key
. Output only the next line. | decoder = VNCDecoder(challenge, response, passwords) |
Given snippet: <|code_start|># You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
logger = logging.getLogger(__name__)
class BaseSession(object):
socket = None
socketLock = BoundedSemaphore(1)
def __init__(self, protocol, source_ip=None, source_port=None, destination_ip=None, destination_port=None):
self.id = uuid.uuid4()
self.source_ip = source_ip
self.source_port = source_port
self.protocol = protocol
self.destination_ip = destination_ip
self.destination_port = destination_port
self.timestamp = datetime.utcnow()
self.login_attempts = []
self.transcript = []
self.session_ended = False
with BaseSession.socketLock:
if BaseSession.socket is None:
context = beeswarm.shared.zmq_context
BaseSession.socket = context.socket(zmq.PUSH)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import uuid
import logging
import json
import zmq.green as zmq
import beeswarm
from datetime import datetime
from gevent.lock import BoundedSemaphore
from beeswarm.shared.socket_enum import SocketNames
from beeswarm.shared.message_enum import Messages
and context:
# Path: beeswarm/shared/socket_enum.py
# class SocketNames(Enum):
# #### Sockets used on server ####
# # All data received from drones will be published on this socket
# DRONE_DATA = 'inproc://droneData'
# # After sessions has been classified they will get retransmitted on this socket.
# # TODO: Does not actually happen yet
# PROCESSED_SESSIONS = 'inproc://processedSessionPublisher'
# # Request / Reply to config actor
# CONFIG_COMMANDS = 'inproc://configCommands'
# # Data sent on this socket will be retransmitted to the correct drone, the data must be prefixed with
# # the id of the drone.
# DRONE_COMMANDS = 'inproc://droneCommands'
#
#
# # Requests to and from the databsae
# DATABASE_REQUESTS = 'inproc://databaseRequests'
#
# #### Sockets used on drones ####
# # Drone commands received from the server will be retransmitted on this socket.
# SERVER_COMMANDS = 'inproc://serverCommands'
# # All messages transmitted on this socket will get retransmitted to the server
# SERVER_RELAY = 'inproc://serverRelay'
#
# Path: beeswarm/shared/message_enum.py
# class Messages(Enum):
# STOP = 'STOP'
# START = 'START'
# CONFIG = 'CONFIG'
# # dump of all configuration elements known to the sender
# CONFIG_FULL = 'CONFIG_FULL'
# # mapping between clients, honeypots, capabilities and bait users
# CONFIG_ARCHITECTURE = 'CONFIG_ARCHITECTURE'
# BROADCAST = 'BROADCAST'
#
# OK = 'OK'
# FAIL = 'FAIL'
# # KEY DRONE_ID DRONE_PRIVATE_KEY
# KEY = 'KEY'
# # CERT DRONE_ID DRONE_CERT
# CERT = 'CERT'
#
# # All data on an entire session, this also indicates session end.
# SESSION_HONEYPOT = 'SESSION_HONEYPOT'
# # Network connect to a honeypot, data format is as in SESSION_HONEYPOT, but not all fields has data.
# SESSION_PART_HONEYPOT_SESSION_START = 'SESSION_PART_HONEYPOT_SESSION_START'
# # Authentication attempt, format is as in self.login_attempts list SESSION_HONEYPOT
# SESSION_PART_HONEYPOT_AUTH = 'SESSION_PART_HONEYPOT_AUTH'
# SESSION_CLIENT = 'SESSION_CLIENT'
#
# SET_CONFIG_ITEM = 'SET'
# GET_CONFIG_ITEM = 'GET'
# GET_ZMQ_KEYS = 'GET_ZMQ_KEYS'
# DELETE_ZMQ_KEYS = 'DELETE_ZMQ_KEYS'
# PING = 'PING'
# PONG = 'PING'
# IP = 'IP'
#
# DRONE_WANT_CONFIG = 'DRONE_WANT_CONFIG'
# DRONE_CONFIG = 'DRONE_CONFIG'
# # ID USERNAME PASSWORD
# BAIT_USER_ADD = 'BAIT_USER_ADD'
# BAIT_USER_DELETE = 'BAIT_USER_DELETE'
# GET_BAIT_USERS = 'GET_BAIT_USERS'
# DRONE_DELETE = 'DRONE_DELETE'
# DRONE_ADD = 'DRONE_ADD'
#
# # Session was deleted because it was matched with an existing session
# # This happens when a bait session is matched with a honeypot session.
# # ID_OF_DELETED_SESSION ID_OF_THE_MERGED_SESSION
# DELETED_DUE_TO_MERGE = "DELETED_DUE_TO_MERGE"
#
# # A classified session is transmitted
# # Parameters is data in json.
# SESSION = "SESSION"
#
# # Database requests
# GET_DB_STATS = 'GET_DB_STATS'
# # TODO: Following three should have to/from params to facilitate pagination
# GET_SESSIONS_ALL = 'GET_SESSIONS_ALL'
# GET_SESSIONS_BAIT = 'GET_SESSIONS_BAIT'
# GET_SESSIONS_ATTACKS = 'GET_SESSIONS_ATTACKS'
#
# # Param: session id
# GET_SESSION_TRANSCRIPT = 'GET_SESSION_TRANSCRIPT'
# # Param: session id
# GET_SESSION_CREDENTIALS = 'GET_SESSION_CREDENTIALS'
# # Param dronetype
# GET_DRONE_LIST = 'GET_DRONE_LIST'
# # Param: clientId config
# CONFIG_DRONE = 'CONFIG_DRONE'
#
# # Param: clientId config
# PING_ALL_DRONES = 'PING_ALL_DRONES'
which might include code, classes, or functions. Output only the next line. | BaseSession.socket.connect(SocketNames.SERVER_RELAY.value) |
Using the snippet: <|code_start|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# these will go when database actor is finished
DB_Session = None
engine = None
logger = logging.getLogger(__name__)
def setup_db(connection_string):
"""
Sets up the database schema and adds defaults.
:param connection_string: Database URL. e.g: sqlite:///filename.db
This is usually taken from the config file.
"""
global DB_Session, engine
new_database = False
<|code_end|>
, determine the next line of code. You have imports:
import os
import json
import logging
import sys
import beeswarm.server.db
import entities
from beeswarm.shared.helpers import database_exists
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from entities import Classification
from entities import BaitUser
and context (class names, function names, or code) available:
# Path: beeswarm/shared/helpers.py
# def database_exists(url):
# """Check if a database exists.
#
# :param url: A SQLAlchemy engine URL.
#
# Performs backend-specific testing to quickly determine if a database
# exists on the server. ::
#
# database_exists('postgres://postgres@localhost/name') #=> False
# create_database('postgres://postgres@localhost/name')
# database_exists('postgres://postgres@localhost/name') #=> True
#
# Supports checking against a constructed URL as well. ::
#
# engine = create_engine('postgres://postgres@localhost/name')
# database_exists(engine.url) #=> False
# create_database(engine.url)
# database_exists(engine.url) #=> True
#
# """
#
# url = copy(make_url(url))
# database = url.database
# if url.drivername.startswith('postgresql'):
# url.database = 'template1'
# else:
# url.database = None
#
# engine = sa.create_engine(url)
#
# if engine.dialect.name == 'postgresql':
# text = "SELECT 1 FROM pg_database WHERE datname='%s'" % database
# return bool(engine.execute(text).scalar())
#
# elif engine.dialect.name == 'mysql':
# text = ("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "
# "WHERE SCHEMA_NAME = '%s'" % database)
# return bool(engine.execute(text).scalar())
#
# elif engine.dialect.name == 'sqlite':
# return database == ':memory:' or os.path.exists(database)
#
# else:
# text = 'SELECT 1'
# try:
# url.database = database
# engine = sa.create_engine(url)
# engine.execute(text)
# return True
#
# except (ProgrammingError, OperationalError):
# return False
. Output only the next line. | if connection_string == 'sqlite://' or not database_exists(connection_string): |
Given the following code snippet before the placeholder: <|code_start|> server_host = self.options['server']
server_port = self.options['port']
honeypot_id = self.options['honeypot_id']
session = self.create_session(server_host, server_port, honeypot_id)
self.sessions[session.id] = session
logger.debug(
'Sending {0} bait session to {1}:{2}. (bait id: {3})'.format('vnc', server_host, server_port, session.id))
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client_socket.connect((server_host, int(server_port)))
session.source_port = client_socket.getsockname()[1]
except socket.error as e:
logger.debug('Caught exception: {0} ({1})'.format(e, str(type(e))))
else:
session.did_connect = True
protocol_version = client_socket.recv(1024)
client_socket.send(RFB_VERSION)
supported_auth_methods = client_socket.recv(1024)
# \x02 implies that VNC authentication method is to be used
# Refer to http://tools.ietf.org/html/rfc6143#section-7.1.2 for more info.
if '\x02' in supported_auth_methods:
client_socket.send(VNC_AUTH)
challenge = client_socket.recv(1024)
# password limit for vnc in 8 chars
aligned_password = (password + '\0' * 8)[:8]
<|code_end|>
, predict the next line using imports from the current file:
import logging
import socket
from beeswarm.drones.client.baits.clientbase import ClientBase
from beeswarm.shared.vnc_constants import *
from beeswarm.shared.misc.rfbes import RFBDes
and context including class names, function names, and sometimes code from other files:
# Path: beeswarm/drones/client/baits/clientbase.py
# class ClientBase(object):
# """ Base class for Bees. This should only be used after sub-classing. """
#
# def __init__(self, options):
# """
# Initializes common values.
# :param sessions: A dict which is updated every time a new session is created.
# :param options: A dict containing the options entry for this bait
# """
# self.options = options
# self.sessions = {}
#
# def create_session(self, server_host, server_port, honeypot_id):
# """
# Creates a new session.
#
# :param server_host: IP address of the server
# :param server_port: Server port
# :return: A new `BaitSession` object.
# """
# protocol = self.__class__.__name__.lower()
# session = BaitSession(protocol, server_host, server_port, honeypot_id)
# self.sessions[session.id] = session
# return session
#
# def close_session(self, session):
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session]
# else:
# assert False
#
# Path: beeswarm/shared/misc/rfbes.py
# class RFBDes(pyDes.des):
# def setKey(self, key):
# """RFB protocol for authentication requires client to encrypt
# challenge sent by server with password using DES method. However,
# bits in each byte of the password are put in reverse order before
# using it as encryption key."""
# newkey = []
# for ki in range(len(key)):
# bsrc = ord(key[ki])
# btgt = 0
# for i in range(8):
# if bsrc & (1 << i):
# btgt = btgt | (1 << 7 - i)
# newkey.append(chr(btgt))
# super(RFBDes, self).setKey(newkey)
. Output only the next line. | des = RFBDes(aligned_password) |
Given the code snippet: <|code_start|> "# directory, in the .curve subdirectory.\n",
"\n",
"metadata\n",
"curve\n",
" public-key = \"LeZkQ^HXijnRahQkp$&nxpu6Hh>7YHBOzbz[iJg^\"\n"
],
"zmq_own_private": [
"# **** Generated on 2015-01-13 21:02:44.933568 by pyzmq ****\n",
"# ZeroMQ CURVE **Secret** Certificate\n",
"# DO NOT PROVIDE THIS FILE TO OTHER USERS nor change its permissions.\n",
"\n",
"metadata\n",
"curve\n",
" public-key = \"LeZkQ^HXijnRahQkp$&nxpu6Hh>7YHBOzbz[iJg^\"\n",
" secret-key = \"B{(o5Hpx{[D3}>f*O{NZ(}.e3o5Xh+eO9-fmt0tb\"\n"
],
"zmq_server_public": [
"# **** Generated on 2015-01-13 20:59:19.308358 by pyzmq ****\n",
"# ZeroMQ CURVE Public Certificate\n",
"# Exchange securely, or use a secure mechanism to verify the contents\n",
"# of this file after exchange. Store public certificates in your home\n",
"# directory, in the .curve subdirectory.\n",
"\n",
"metadata\n",
"curve\n",
" public-key = \"^xk>t(V(bj70]=zl.uX=)#@kYwlgjitkfrVo!I+=\"\n"
]
}
}
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import tempfile
import shutil
import os
from beeswarm.drones.client.client import Client
and context (functions, classes, or occasionally code) from other files:
# Path: beeswarm/drones/client/client.py
# class Client(object):
# def __init__(self, work_dir, config):
#
# """
# Main class which runs Beeswarm in Client mode.
#
# :param work_dir: Working directory (usually the current working directory)
# :param config_arg: Beeswarm configuration dictionary.
# """
# self.run_flag = True
# self.config = config
#
# # write ZMQ keys to files - as expected by pyzmq
# extract_keys(work_dir, config)
#
# BaitSession.client_id = self.config['general']['id']
#
# if self.config['general']['fetch_ip']:
# self.my_ip = urllib2.urlopen('http://api-sth01.exip.org/?call=ip').read()
# logger.info('Fetched {0} as my external ip.'.format(self.my_ip))
# else:
# self.my_ip = get_most_likely_ip()
#
# self.dispatcher_greenlets = []
#
# def start(self):
# """
# Starts sending client bait to the configured Honeypot.
# """
# logger.info('Starting client.')
#
# self.dispatcher_greenlets = []
#
# for _, entry in self.config['baits'].items():
# for b in clientbase.ClientBase.__subclasses__():
# bait_name = b.__name__.lower()
# # if the bait has a entry in the config we consider the bait enabled
# if bait_name in entry:
# bait_options = entry[bait_name]
# dispatcher = BaitDispatcher(b, bait_options)
# dispatcher.start()
# self.dispatcher_greenlets.append(dispatcher)
# logger.info('Adding {0} bait'.format(bait_name))
# logger.debug('Bait added with options: {0}'.format(bait_options))
#
# gevent.joinall(self.dispatcher_greenlets)
#
# def stop(self):
# """
# Stop sending bait sessions.
# """
# for g in self.dispatcher_greenlets:
# g.kill()
# logger.info('All clients stopped')
. Output only the next line. | client = Client(self.tmp_dir, config) |
Predict the next line after this snippet: <|code_start|> if self.headers.getheader('Authorization') is None:
self.do_AUTHHEAD()
self.send_html('please_auth.html')
else:
hdr = self.headers.getheader('Authorization')
_, enc_uname_pwd = hdr.split(' ')
dec_uname_pwd = base64.b64decode(enc_uname_pwd)
uname, pwd = dec_uname_pwd.split(':')
if not self._session.try_auth('plaintext', username=uname, password=pwd):
self.do_AUTHHEAD()
self.send_html('please_auth.html')
else:
self.do_HEAD()
self.send_html('index.html')
self.request.close()
def send_html(self, filename):
file_ = self.vfs.open(filename)
send_whole_file(self.request.fileno(), file_.fileno())
file_.close()
def version_string(self):
return self._banner
# Disable logging provided by BaseHTTPServer
def log_message(self, format_, *args):
pass
<|code_end|>
using the current file's imports:
import base64
import socket
import logging
from BaseHTTPServer import BaseHTTPRequestHandler
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
from beeswarm.drones.honeypot.helpers.common import send_whole_file
and any relevant context from other files:
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
#
# Path: beeswarm/drones/honeypot/helpers/common.py
# def send_whole_file(sock_fd, file_fd):
# offset = 0
# while True:
# sent = sendfile(sock_fd, file_fd, offset, 65536)
# if sent == 0:
# break
# offset += sent
. Output only the next line. | class Http(HandlerBase): |
Given snippet: <|code_start|> self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_AUTHHEAD(self):
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
if self.headers.getheader('Authorization') is None:
self.do_AUTHHEAD()
self.send_html('please_auth.html')
else:
hdr = self.headers.getheader('Authorization')
_, enc_uname_pwd = hdr.split(' ')
dec_uname_pwd = base64.b64decode(enc_uname_pwd)
uname, pwd = dec_uname_pwd.split(':')
if not self._session.try_auth('plaintext', username=uname, password=pwd):
self.do_AUTHHEAD()
self.send_html('please_auth.html')
else:
self.do_HEAD()
self.send_html('index.html')
self.request.close()
def send_html(self, filename):
file_ = self.vfs.open(filename)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import base64
import socket
import logging
from BaseHTTPServer import BaseHTTPRequestHandler
from beeswarm.drones.honeypot.capabilities.handlerbase import HandlerBase
from beeswarm.drones.honeypot.helpers.common import send_whole_file
and context:
# Path: beeswarm/drones/honeypot/capabilities/handlerbase.py
# class HandlerBase(object):
# def __init__(self, options, workdir):
# """
# Base class that all capabilities must inherit from.
#
# :param sessions: a dictionary of Session objects.
# :param options: a dictionary of configuration options.
# :param workdir: the directory which contains files for this
# particular instance of Beeswarm
# """
# self.options = options
# self.sessions = {}
# if 'users' in options:
# self.users = options['users']
# else:
# self.users = {}
# # virtual file system shared by all capabilities
# self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# # service port
# self.port = int(options['port'])
#
# def create_session(self, address):
# protocol = self.__class__.__name__.lower()
# session = Session(address[0], address[1], protocol, self.users)
# self.sessions[session.id] = session
# session.destination_port = self.port
# logger.debug(
# 'Accepted {0} session on port {1} from {2}:{3}. ({4})'.format(protocol, self.port, address[0],
# address[1], str(session.id)))
# logger.debug('Size of session list for {0}: {1}'.format(protocol, len(self.sessions)))
# return session
#
# def close_session(self, session):
# logger.debug('Closing sessions')
# session.end_session()
# if session.id in self.sessions:
# del self.sessions[session.id]
# else:
# assert False
#
# def handle_session(self, socket, address):
# raise Exception('Do no call base class!')
#
# Path: beeswarm/drones/honeypot/helpers/common.py
# def send_whole_file(sock_fd, file_fd):
# offset = 0
# while True:
# sent = sendfile(sock_fd, file_fd, offset, 65536)
# if sent == 0:
# break
# offset += sent
which might include code, classes, or functions. Output only the next line. | send_whole_file(self.request.fileno(), file_.fileno()) |
Based on the snippet: <|code_start|>
def extract_keys(work_dir, config):
# dump keys used for secure communication with beeswarm server
# safe to rm since we have everything we need in the config
cert_path = os.path.join(work_dir, 'certificates')
shutil.rmtree(cert_path, True)
public_keys = os.path.join(cert_path, 'public_keys')
private_keys = os.path.join(cert_path, 'private_keys')
for _path in [cert_path, public_keys, private_keys]:
if not os.path.isdir(_path):
os.mkdir(_path)
with open(os.path.join(public_keys, 'server.key'), 'w') as key_file:
key_file.writelines(config['beeswarm_server']['zmq_server_public'])
with open(os.path.join(public_keys, 'client.key'), 'w') as key_file:
key_file.writelines(config['beeswarm_server']['zmq_own_public'])
with open(os.path.join(private_keys, 'client.key'), 'w') as key_file:
key_file.writelines(config['beeswarm_server']['zmq_own_private'])
def extract_config_from_api(config_url, config_file):
# meh, MiTM problem here... Acceptable? Workaround?
# maybe print fingerprint on the web ui and let user verify manually?
try:
req = requests.get(config_url, verify=False)
except Exception as ex:
logger.error('Error while extracting config: {0}'.format(ex))
return None
if req.status_code == 200:
<|code_end|>
, predict the immediate next line with the help of imports:
import urlparse
import os
import pwd
import grp
import platform
import logging
import json
import shutil
import sys
import sqlalchemy as sa
import netifaces
import zmq.green as zmq
import gevent
import requests
import beeswarm
import beeswarm.shared
from OpenSSL import crypto
from Crypto.PublicKey import RSA
from sqlalchemy.exc import ProgrammingError, OperationalError
from sqlalchemy.engine.url import make_url
from copy import copy
from beeswarm.shared.asciify import asciify
from beeswarm.shared.message_enum import Messages
and context (classes, functions, sometimes code) from other files:
# Path: beeswarm/shared/asciify.py
# def asciify(data):
# if isinstance(data, list):
# return _asciify_list(data)
# elif isinstance(data, dict):
# return _asciify_dict(data)
# elif isinstance(data, unicode):
# data = _remove_accents(data)
# return data.encode('utf-8')
# elif isinstance(data, str):
# return data
# else:
# raise TypeError('Input must be dict, list, str or unicode')
#
# Path: beeswarm/shared/message_enum.py
# class Messages(Enum):
# STOP = 'STOP'
# START = 'START'
# CONFIG = 'CONFIG'
# # dump of all configuration elements known to the sender
# CONFIG_FULL = 'CONFIG_FULL'
# # mapping between clients, honeypots, capabilities and bait users
# CONFIG_ARCHITECTURE = 'CONFIG_ARCHITECTURE'
# BROADCAST = 'BROADCAST'
#
# OK = 'OK'
# FAIL = 'FAIL'
# # KEY DRONE_ID DRONE_PRIVATE_KEY
# KEY = 'KEY'
# # CERT DRONE_ID DRONE_CERT
# CERT = 'CERT'
#
# # All data on an entire session, this also indicates session end.
# SESSION_HONEYPOT = 'SESSION_HONEYPOT'
# # Network connect to a honeypot, data format is as in SESSION_HONEYPOT, but not all fields has data.
# SESSION_PART_HONEYPOT_SESSION_START = 'SESSION_PART_HONEYPOT_SESSION_START'
# # Authentication attempt, format is as in self.login_attempts list SESSION_HONEYPOT
# SESSION_PART_HONEYPOT_AUTH = 'SESSION_PART_HONEYPOT_AUTH'
# SESSION_CLIENT = 'SESSION_CLIENT'
#
# SET_CONFIG_ITEM = 'SET'
# GET_CONFIG_ITEM = 'GET'
# GET_ZMQ_KEYS = 'GET_ZMQ_KEYS'
# DELETE_ZMQ_KEYS = 'DELETE_ZMQ_KEYS'
# PING = 'PING'
# PONG = 'PING'
# IP = 'IP'
#
# DRONE_WANT_CONFIG = 'DRONE_WANT_CONFIG'
# DRONE_CONFIG = 'DRONE_CONFIG'
# # ID USERNAME PASSWORD
# BAIT_USER_ADD = 'BAIT_USER_ADD'
# BAIT_USER_DELETE = 'BAIT_USER_DELETE'
# GET_BAIT_USERS = 'GET_BAIT_USERS'
# DRONE_DELETE = 'DRONE_DELETE'
# DRONE_ADD = 'DRONE_ADD'
#
# # Session was deleted because it was matched with an existing session
# # This happens when a bait session is matched with a honeypot session.
# # ID_OF_DELETED_SESSION ID_OF_THE_MERGED_SESSION
# DELETED_DUE_TO_MERGE = "DELETED_DUE_TO_MERGE"
#
# # A classified session is transmitted
# # Parameters is data in json.
# SESSION = "SESSION"
#
# # Database requests
# GET_DB_STATS = 'GET_DB_STATS'
# # TODO: Following three should have to/from params to facilitate pagination
# GET_SESSIONS_ALL = 'GET_SESSIONS_ALL'
# GET_SESSIONS_BAIT = 'GET_SESSIONS_BAIT'
# GET_SESSIONS_ATTACKS = 'GET_SESSIONS_ATTACKS'
#
# # Param: session id
# GET_SESSION_TRANSCRIPT = 'GET_SESSION_TRANSCRIPT'
# # Param: session id
# GET_SESSION_CREDENTIALS = 'GET_SESSION_CREDENTIALS'
# # Param dronetype
# GET_DRONE_LIST = 'GET_DRONE_LIST'
# # Param: clientId config
# CONFIG_DRONE = 'CONFIG_DRONE'
#
# # Param: clientId config
# PING_ALL_DRONES = 'PING_ALL_DRONES'
. Output only the next line. | config = json.loads(req.text, object_hook=asciify) |
Next line prediction: <|code_start|>
default_ip = '127.0.0.1'
logger.warning('Count not detect likely IP, returning {0}'.format(default_ip))
return '127.0.0.1'
def update_config_file(configfile, options):
config = get_config_dict(configfile)
with open(configfile, 'r+') as config_file:
for k, v in options.items():
config[k] = v
config_file.seek(0)
config_file.truncate(0)
config_file.write(json.dumps(config, indent=4))
def get_config_dict(configfile):
config = json.load(open(configfile, 'r'))
return config
# for occasional req/resp
def send_zmq_request(actor_url, request):
context = beeswarm.shared.zmq_context
socket = context.socket(zmq.REQ)
socket.connect(actor_url)
socket.send(request)
gevent.sleep()
result = socket.recv()
<|code_end|>
. Use current file imports:
(import urlparse
import os
import pwd
import grp
import platform
import logging
import json
import shutil
import sys
import sqlalchemy as sa
import netifaces
import zmq.green as zmq
import gevent
import requests
import beeswarm
import beeswarm.shared
from OpenSSL import crypto
from Crypto.PublicKey import RSA
from sqlalchemy.exc import ProgrammingError, OperationalError
from sqlalchemy.engine.url import make_url
from copy import copy
from beeswarm.shared.asciify import asciify
from beeswarm.shared.message_enum import Messages)
and context including class names, function names, or small code snippets from other files:
# Path: beeswarm/shared/asciify.py
# def asciify(data):
# if isinstance(data, list):
# return _asciify_list(data)
# elif isinstance(data, dict):
# return _asciify_dict(data)
# elif isinstance(data, unicode):
# data = _remove_accents(data)
# return data.encode('utf-8')
# elif isinstance(data, str):
# return data
# else:
# raise TypeError('Input must be dict, list, str or unicode')
#
# Path: beeswarm/shared/message_enum.py
# class Messages(Enum):
# STOP = 'STOP'
# START = 'START'
# CONFIG = 'CONFIG'
# # dump of all configuration elements known to the sender
# CONFIG_FULL = 'CONFIG_FULL'
# # mapping between clients, honeypots, capabilities and bait users
# CONFIG_ARCHITECTURE = 'CONFIG_ARCHITECTURE'
# BROADCAST = 'BROADCAST'
#
# OK = 'OK'
# FAIL = 'FAIL'
# # KEY DRONE_ID DRONE_PRIVATE_KEY
# KEY = 'KEY'
# # CERT DRONE_ID DRONE_CERT
# CERT = 'CERT'
#
# # All data on an entire session, this also indicates session end.
# SESSION_HONEYPOT = 'SESSION_HONEYPOT'
# # Network connect to a honeypot, data format is as in SESSION_HONEYPOT, but not all fields has data.
# SESSION_PART_HONEYPOT_SESSION_START = 'SESSION_PART_HONEYPOT_SESSION_START'
# # Authentication attempt, format is as in self.login_attempts list SESSION_HONEYPOT
# SESSION_PART_HONEYPOT_AUTH = 'SESSION_PART_HONEYPOT_AUTH'
# SESSION_CLIENT = 'SESSION_CLIENT'
#
# SET_CONFIG_ITEM = 'SET'
# GET_CONFIG_ITEM = 'GET'
# GET_ZMQ_KEYS = 'GET_ZMQ_KEYS'
# DELETE_ZMQ_KEYS = 'DELETE_ZMQ_KEYS'
# PING = 'PING'
# PONG = 'PING'
# IP = 'IP'
#
# DRONE_WANT_CONFIG = 'DRONE_WANT_CONFIG'
# DRONE_CONFIG = 'DRONE_CONFIG'
# # ID USERNAME PASSWORD
# BAIT_USER_ADD = 'BAIT_USER_ADD'
# BAIT_USER_DELETE = 'BAIT_USER_DELETE'
# GET_BAIT_USERS = 'GET_BAIT_USERS'
# DRONE_DELETE = 'DRONE_DELETE'
# DRONE_ADD = 'DRONE_ADD'
#
# # Session was deleted because it was matched with an existing session
# # This happens when a bait session is matched with a honeypot session.
# # ID_OF_DELETED_SESSION ID_OF_THE_MERGED_SESSION
# DELETED_DUE_TO_MERGE = "DELETED_DUE_TO_MERGE"
#
# # A classified session is transmitted
# # Parameters is data in json.
# SESSION = "SESSION"
#
# # Database requests
# GET_DB_STATS = 'GET_DB_STATS'
# # TODO: Following three should have to/from params to facilitate pagination
# GET_SESSIONS_ALL = 'GET_SESSIONS_ALL'
# GET_SESSIONS_BAIT = 'GET_SESSIONS_BAIT'
# GET_SESSIONS_ATTACKS = 'GET_SESSIONS_ATTACKS'
#
# # Param: session id
# GET_SESSION_TRANSCRIPT = 'GET_SESSION_TRANSCRIPT'
# # Param: session id
# GET_SESSION_CREDENTIALS = 'GET_SESSION_CREDENTIALS'
# # Param dronetype
# GET_DRONE_LIST = 'GET_DRONE_LIST'
# # Param: clientId config
# CONFIG_DRONE = 'CONFIG_DRONE'
#
# # Param: clientId config
# PING_ALL_DRONES = 'PING_ALL_DRONES'
. Output only the next line. | if result.split(' ', 1)[0] != Messages.OK.value: |
Predict the next line after this snippet: <|code_start|>
logger = logging.getLogger(__name__)
class HandlerBase(object):
def __init__(self, options, workdir):
"""
Base class that all capabilities must inherit from.
:param sessions: a dictionary of Session objects.
:param options: a dictionary of configuration options.
:param workdir: the directory which contains files for this
particular instance of Beeswarm
"""
self.options = options
self.sessions = {}
if 'users' in options:
self.users = options['users']
else:
self.users = {}
# virtual file system shared by all capabilities
self.vfsystem = OSFS(os.path.join(workdir, 'data/vfs'))
# service port
self.port = int(options['port'])
def create_session(self, address):
protocol = self.__class__.__name__.lower()
<|code_end|>
using the current file's imports:
import os
import logging
from fs.osfs import OSFS
from beeswarm.drones.honeypot.models.session import Session
and any relevant context from other files:
# Path: beeswarm/drones/honeypot/models/session.py
# class Session(BaseSession):
# authenticator = None
# default_timeout = 25
# honeypot_id = None
#
# def __init__(self, source_ip, source_port, protocol, users, destination_port=None, destination_ip=None):
#
# super(Session, self).__init__(protocol, source_ip, source_port, destination_ip, destination_port)
#
# self.connected = True
# self.authenticated = False
# self.honeypot_id = Session.honeypot_id
# self.users = users
#
# # for session specific volatile data (will not get logged)
# self.vdata = {}
# self.last_activity = datetime.utcnow()
#
# self.send_log(Messages.SESSION_PART_HONEYPOT_SESSION_START.value, self.to_dict())
#
# def activity(self):
# self.last_activity = datetime.utcnow()
#
# def is_connected(self):
# return self.connected
#
# def try_auth(self, _type, **kwargs):
# authenticated = False
# if _type == 'plaintext':
# if kwargs.get('username') in self.users:
# if self.users[kwargs.get('username')] == kwargs.get('password'):
# authenticated = True
#
# elif _type == 'cram_md5':
# def encode_cram_md5(challenge, user, password):
# response = user + ' ' + hmac.HMAC(password, challenge).hexdigest()
# return response
#
# if kwargs.get('username') in self.users:
# uname = kwargs.get('username')
# digest = kwargs.get('digest')
# s_pass = self.users[uname]
# challenge = kwargs.get('challenge')
# ideal_response = encode_cram_md5(challenge, uname, s_pass)
# _, ideal_digest = ideal_response.split()
# if ideal_digest == digest:
# authenticated = True
# elif _type == 'des_challenge':
# challenge = kwargs.get('challenge')
# response = kwargs.get('response')
# for valid_password in self.users.values():
# aligned_password = (valid_password + '\0' * 8)[:8]
# des = RFBDes(aligned_password)
# expected_response = des.encrypt(challenge)
# if response == expected_response:
# authenticated = True
# kwargs['password'] = aligned_password
# break
# else:
# assert False
#
# if authenticated:
# self.authenticated = True
# self.add_auth_attempt(_type, True, **kwargs)
# else:
# self.add_auth_attempt(_type, False, **kwargs)
#
# if _type == 'des_challenge':
# kwargs['challenge'] = kwargs.get('challenge').encode('hex')
# kwargs['response'] = kwargs.get('response').encode('hex')
#
# self.send_log(Messages.SESSION_PART_HONEYPOT_AUTH.value, self.login_attempts[-1])
# logger.debug('{0} authentication attempt from {1}:{2}. Credentials: {3}'.format(self.protocol, self.source_ip,
# self.source_port,
# json.dumps(kwargs)))
# return authenticated
#
# def end_session(self):
# super(Session, self).end_session(Messages.SESSION_HONEYPOT.value)
. Output only the next line. | session = Session(address[0], address[1], protocol, self.users) |
Based on the snippet: <|code_start|># along with PyTask. If not, see <http://www.gnu.org/licenses/>.
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
'"Nishanth Amuluru" <nishanth@fossee.in>',
]
# This import is not used anywhere else, but is very important to register
# the user registered signal receiver. So please don't remove it. Although
# it against style to put any imports in the end of the file, this is
# intentional so that this import may not be removed accidentally when
# cleaning up other unused imports.
# Although this import is not directly used in this module, but it is
# imported here so that it executes the code which connects the
# user_registered signal sent by the django-registration app. Also, to
# avoid cyclic imports, there is no better place than here.
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'pytask.views.home_page', name='home_page'),
(r'^admin/', include(admin.site.urls)),
url(r'^accounts/register/$', register,
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
from registration.views import register
from pytask.profile.forms import CustomRegistrationForm
import pytask.profile.regbackend
and context (classes, functions, sometimes code) from other files:
# Path: pytask/profile/forms.py
# class CustomRegistrationForm(RegistrationFormUniqueEmail):
# """Used instead of RegistrationForm used by default django-registration
# backend, this adds aboutme, dob, gender, address, phonenum to the default
# django-registration RegistrationForm"""
#
# # overriding only this field from the parent Form Class since we
# # don't like the restriction imposed by the registration app on username
# # GMail has more or less set the standard for user names
# username = forms.CharField(
# max_length=30, widget=forms.TextInput(attrs=attrs_dict),
# label=ugettext('Username'), help_text='Username can contain alphabet, '
# 'numbers or special characters underscore (_) and (.)')
#
# full_name = forms.CharField(required=True, max_length=50,
# label="Name as on your bank account",
# help_text="Any DD/Cheque will be issued on \
# this name")
#
# aboutme = forms.CharField(required=True, widget=forms.Textarea,
# max_length=1000, label=u"About Me",
# help_text="A write up about yourself to aid the\
# reviewer in judging your eligibility for a task.\
# It can have your educational background, CGPA,\
# field of interests etc.,"
# )
#
#
# dob = forms.DateField(help_text = "yyyy-mm-dd", required=True,
# label=u'Date of Birth')
#
# gender = forms.ChoiceField(choices = GENDER_CHOICES,
# required=True, label=u'Gender')
#
# address = forms.CharField(
# required=True, max_length=200, widget=forms.Textarea,
# help_text="This information will be used while sending DD/Cheque")
#
# phonenum = forms.CharField(required=True, max_length=10,
# label="Phone Number")
#
# def clean_username(self):
# """Add additional cleaner for username than the parent class
# supplied cleaner.
# """
#
# username = self.cleaned_data['username']
#
# # None of the regular expression works better than this custom
# # username check.
# if not re.match(r'^\w+', username):
# raise forms.ValidationError(
# ugettext('Username can start only with an alphabet or a number'))
# elif not re.search(r'\w+$', username):
# raise forms.ValidationError(
# ugettext('Username can end only with an alphabet or a number'))
# elif re.search(r'\.\.+', username):
# raise forms.ValidationError(
# ugettext('Username cannot not have consecutive periods(.)'))
#
# return super(CustomRegistrationForm, self).clean_username()
#
# def clean_aboutme(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['aboutme']
# if not data.strip():
# raise forms.ValidationError("Please write something about\
# yourself")
#
# return data
#
# def clean_address(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['address']
# if not data.strip():
# raise forms.ValidationError("Please enter an address")
#
# return data
#
# def clean_phonenum(self):
# """ should be of 10 digits """
#
# data = self.cleaned_data['phonenum']
#
# if (not data.strip()) or \
# (data.strip("1234567890")) or \
# (len(data)!= 10):
# raise forms.ValidationError("This is not a valid phone number")
#
# return data
#
#
# def save(self, profile_callback=None):
#
# new_user = RegistrationProfile.objects.create_inactive_user(
# username=self.cleaned_data['username'],
# password=self.cleaned_data['password1'],
# email=self.cleaned_data['email'])
#
# new_profile = Profile(user=new_user,
# aboutme=self.cleaned_data['aboutme'],
# dob=self.cleaned_data['dob'],
# gender=self.cleaned_data['gender'],
# address=self.cleaned_data['address'],
# phonenum=self.cleaned_data['phonenum'],
# )
# new_profile.save()
#
# return new_user
. Output only the next line. | {'form_class': CustomRegistrationForm, |
Continue the code snippet: <|code_start|># This file is part of PyTask.
#
# PyTask is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyTask 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
'"Nishanth Amuluru" <nishanth@fossee.in>',
]
def user_created(sender, user, request, **kwargs):
data = request.POST.copy()
data.update({
"user": user.id,
})
<|code_end|>
. Use current file imports:
from pytask.profile.forms import CreateProfileForm
from registration.signals import user_registered
and context (classes, functions, or code) from other files:
# Path: pytask/profile/forms.py
# class CreateProfileForm(forms.ModelForm):
#
# class Meta:
# model = Profile
# exclude = ['pynts', 'role']
. Output only the next line. | form = CreateProfileForm(data) |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
#
# Copyright 2011 Authors of PyTask.
#
# This file is part of PyTask.
#
# PyTask is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyTask 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
__authors__ = [
'"Nishanth Amuluru" <nishanth@fossee.in>',
]
<|code_end|>
using the current file's imports:
from django.contrib import admin
from pytask.profile.models import Profile
and any relevant context from other files:
# Path: pytask/profile/models.py
# class Profile(models.Model):
# full_name = models.CharField(
# max_length=50, verbose_name="Name as on bank account",
# help_text="Any DD/Cheque will be issued on this name")
#
# user = models.ForeignKey(User, unique = True)
#
# role = models.CharField(max_length=255,
# choices=ROLES_CHOICES,
# default=u"Contributor")
#
# pynts = models.PositiveSmallIntegerField(default=0)
#
# aboutme = models.TextField(
# blank = True,
# help_text="This information will be used to judge the eligibility "
# "for any task")
#
# dob = models.DateField(verbose_name=u"Date of Birth",
# help_text="YYYY-MM-DD")
#
# gender = models.CharField(verbose_name=u'Gender',
# max_length=24, choices=GENDER_CHOICES)
#
# address = models.TextField(
# blank=False, help_text="This information will be used to send "
# "any DDs/Cheques.")
#
# phonenum = models.CharField(max_length = 15, blank = True,
# verbose_name = u"Phone Number")
#
# def __unicode__(self):
# return unicode(self.user.username)
. Output only the next line. | admin.site.register(Profile) |
Given snippet: <|code_start|> # branches/departments
branch_name = os.extsep.join(file_name.split(os.extsep)[:-1])
textbooks = []
for line in csv_obj:
if len(line) == 2 and line[0]:
sep = ' by '
else:
sep = ''
textbooks.append({
'title': sep.join(line),
'desc': '(To be filled in by the Coordinator or the T/A.)',
'tags_field': ', '. join(['Textbook', branch_name, line[1]]),
'pynts': 10,
'status': 'Open',
})
return textbooks
def seed_db(data):
"""Seeds the database when the data is passed as the argument
Args:
data: A dictionary containing the data to be seeded into the
task model.
"""
for task in data:
task.update(STATIC_DATA)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import csv
import datetime
import os
import sys
from django.contrib.auth.models import User
from pytask.taskapp.models import Task
and context:
# Path: pytask/taskapp/models.py
# class Task(models.Model):
#
# parent = models.ForeignKey('self', blank=True, null=True,
# related_name="children_tasks")
#
# title = models.CharField(
# max_length=1024, verbose_name=u"Title",
# help_text=u"Keep it simple and below 100 chars.")
#
# desc = models.TextField(verbose_name=u"Description")
#
# status = models.CharField(max_length=255,
# choices=TASK_STATUS_CHOICES,
# default="Unpublished")
#
# tags_field = TagField(
# verbose_name=u"Tags", help_text=u"Give tags separated by commas. "
# "The allowed characters are all alphabet, numbers, underscore(_), "
# "period(.), forward slash(/), dash(-), ampersand(&), single quote(') "
# " and space.")
#
# pynts = models.PositiveSmallIntegerField(
# help_text=u"Number of Pynts a user gets on completing the task")
#
# created_by = models.ForeignKey(User,
# related_name="created_tasks")
#
# approved_by = models.ForeignKey(User, blank=True, null=True,
# related_name="approved_tasks")
#
# reviewers = models.ManyToManyField(User, blank=True, null=True,
# related_name="reviewing_tasks")
#
# claimed_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="claimed_tasks")
#
# selected_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="selected_tasks")
#
# creation_datetime = models.DateTimeField(auto_now_add=True)
#
# approval_datetime = models.DateTimeField(blank=True, null=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.title)
which might include code, classes, or functions. Output only the next line. | task_obj = Task(**task) |
Continue the code snippet: <|code_start|>
if (request.user == profile_user or access_user_role == 'Administrator'
or request.user.is_superuser):
# context variable all is used to indicate that the currently
# logged in user has access to all the sensitive information.
# context variable medium indicates that the currently logged
# in user has access to medium sensitive information.
context['all'] = True
context['medium'] = True
elif access_user_role == 'Coordinator':
context['medium'] = True
return shortcuts.render_to_response(
template_name, RequestContext(request, context))
@login_required
def edit_profile(request):
""" Make only a few fields editable.
"""
user = request.user
profile = user.get_profile()
context = {"user": user,
"profile": profile,
}
context.update(csrf(request))
if request.method == "POST":
<|code_end|>
. Use current file imports:
from urllib2 import urlparse
from django import http
from django import shortcuts
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import loader
from django.template import RequestContext
from django.utils import simplejson as json
from pytask.profile.forms import EditProfileForm
from pytask.profile.utils import get_notification
from pytask.profile.utils import get_user
and context (classes, functions, or code) from other files:
# Path: pytask/profile/forms.py
# class EditProfileForm(forms.ModelForm):
#
# class Meta:
# model = Profile
# fields = ['full_name', 'aboutme', 'gender', 'dob', 'address', 'phonenum']
#
# def clean_aboutme(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['aboutme']
# if not data.strip():
# raise forms.ValidationError("Please write something about\
# yourself")
#
# return data
#
# def clean_address(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['address']
# if not data.strip():
# raise forms.ValidationError("Please enter an address")
#
# return data
#
# def clean_phonenum(self):
# """ should be of 10 digits """
#
# data = self.cleaned_data['phonenum']
#
# if (not data.strip()) or \
# (data.strip("1234567890")) or \
# (len(data)!= 10):
# raise forms.ValidationError("This is not a valid phone number")
#
# return data
#
# Path: pytask/profile/utils.py
# def get_notification(nid, user):
# """ if notification exists, and belongs to the current user, return it.
# else return None.
# """
#
# user_notifications = user.notification_sent_to.filter(is_deleted=False).order_by('sent_date')
# current_notifications = user_notifications.filter(pk=nid)
# if user_notifications:
# current_notification = current_notifications[0]
#
# try:
# newer_notification = current_notification.get_next_by_sent_date(sent_to=user, is_deleted=False)
# newest_notification = user_notifications.reverse()[0]
# if newest_notification == newer_notification:
# newest_notification = None
# except Notification.DoesNotExist:
# newest_notification, newer_notification = None, None
#
# try:
# older_notification = current_notification.get_previous_by_sent_date(sent_to=user, is_deleted=False)
# oldest_notification = user_notifications[0]
# if oldest_notification == older_notification:
# oldest_notification = None
# except:
# oldest_notification, older_notification = None, None
#
# return newest_notification, newer_notification, current_notification, older_notification, oldest_notification
#
# else:
# return None, None, None, None, None
#
# Path: pytask/profile/utils.py
# def get_user(uid):
#
# user = shortcuts.get_object_or_404(User, pk=uid)
#
# if user.is_active:
# return user
# else:
# raise Http404
. Output only the next line. | form = EditProfileForm(request.POST, instance=profile) |
Continue the code snippet: <|code_start|> else:
form = EditProfileForm(instance=profile)
context.update({"form":form})
return shortcuts.render_to_response(
"profile/edit.html", RequestContext(request, context))
@login_required
def browse_notifications(request):
""" get the list of notifications that are not deleted and display in
datetime order."""
user = request.user
active_notifications = user.notification_sent_to.filter(
is_deleted=False).order_by('-sent_date')
context = {'user':user,
'notifications':active_notifications,
}
return shortcuts.render_to_response('profile/browse_notifications.html',
RequestContext(request, context))
@login_required
def view_notification(request, notification_id):
""" get the notification depending on nid.
Display it.
"""
user = request.user
<|code_end|>
. Use current file imports:
from urllib2 import urlparse
from django import http
from django import shortcuts
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import loader
from django.template import RequestContext
from django.utils import simplejson as json
from pytask.profile.forms import EditProfileForm
from pytask.profile.utils import get_notification
from pytask.profile.utils import get_user
and context (classes, functions, or code) from other files:
# Path: pytask/profile/forms.py
# class EditProfileForm(forms.ModelForm):
#
# class Meta:
# model = Profile
# fields = ['full_name', 'aboutme', 'gender', 'dob', 'address', 'phonenum']
#
# def clean_aboutme(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['aboutme']
# if not data.strip():
# raise forms.ValidationError("Please write something about\
# yourself")
#
# return data
#
# def clean_address(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['address']
# if not data.strip():
# raise forms.ValidationError("Please enter an address")
#
# return data
#
# def clean_phonenum(self):
# """ should be of 10 digits """
#
# data = self.cleaned_data['phonenum']
#
# if (not data.strip()) or \
# (data.strip("1234567890")) or \
# (len(data)!= 10):
# raise forms.ValidationError("This is not a valid phone number")
#
# return data
#
# Path: pytask/profile/utils.py
# def get_notification(nid, user):
# """ if notification exists, and belongs to the current user, return it.
# else return None.
# """
#
# user_notifications = user.notification_sent_to.filter(is_deleted=False).order_by('sent_date')
# current_notifications = user_notifications.filter(pk=nid)
# if user_notifications:
# current_notification = current_notifications[0]
#
# try:
# newer_notification = current_notification.get_next_by_sent_date(sent_to=user, is_deleted=False)
# newest_notification = user_notifications.reverse()[0]
# if newest_notification == newer_notification:
# newest_notification = None
# except Notification.DoesNotExist:
# newest_notification, newer_notification = None, None
#
# try:
# older_notification = current_notification.get_previous_by_sent_date(sent_to=user, is_deleted=False)
# oldest_notification = user_notifications[0]
# if oldest_notification == older_notification:
# oldest_notification = None
# except:
# oldest_notification, older_notification = None, None
#
# return newest_notification, newer_notification, current_notification, older_notification, oldest_notification
#
# else:
# return None, None, None, None, None
#
# Path: pytask/profile/utils.py
# def get_user(uid):
#
# user = shortcuts.get_object_or_404(User, pk=uid)
#
# if user.is_active:
# return user
# else:
# raise Http404
. Output only the next line. | newest, newer, notification, older, oldest = get_notification( |
Continue the code snippet: <|code_start|>@login_required
def unread_notification(request, notification_id):
""" check if the user owns the notification and delete it.
"""
user = request.user
newest, newer, notification, older, oldest = get_notification(
notification_id, user)
if not notification:
raise http.Http404
notification.is_read = False
notification.save()
if older:
redirect_url = reverse('view_notification',
kwargs={'notification_id': older.id})
else:
redirect_url = reverse('browse_notifications')
return shortcuts.redirect(redirect_url)
@login_required
def view_user(request, uid):
user = request.user
profile = user.get_profile()
<|code_end|>
. Use current file imports:
from urllib2 import urlparse
from django import http
from django import shortcuts
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import loader
from django.template import RequestContext
from django.utils import simplejson as json
from pytask.profile.forms import EditProfileForm
from pytask.profile.utils import get_notification
from pytask.profile.utils import get_user
and context (classes, functions, or code) from other files:
# Path: pytask/profile/forms.py
# class EditProfileForm(forms.ModelForm):
#
# class Meta:
# model = Profile
# fields = ['full_name', 'aboutme', 'gender', 'dob', 'address', 'phonenum']
#
# def clean_aboutme(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['aboutme']
# if not data.strip():
# raise forms.ValidationError("Please write something about\
# yourself")
#
# return data
#
# def clean_address(self):
# """ Empty not allowed """
#
# data = self.cleaned_data['address']
# if not data.strip():
# raise forms.ValidationError("Please enter an address")
#
# return data
#
# def clean_phonenum(self):
# """ should be of 10 digits """
#
# data = self.cleaned_data['phonenum']
#
# if (not data.strip()) or \
# (data.strip("1234567890")) or \
# (len(data)!= 10):
# raise forms.ValidationError("This is not a valid phone number")
#
# return data
#
# Path: pytask/profile/utils.py
# def get_notification(nid, user):
# """ if notification exists, and belongs to the current user, return it.
# else return None.
# """
#
# user_notifications = user.notification_sent_to.filter(is_deleted=False).order_by('sent_date')
# current_notifications = user_notifications.filter(pk=nid)
# if user_notifications:
# current_notification = current_notifications[0]
#
# try:
# newer_notification = current_notification.get_next_by_sent_date(sent_to=user, is_deleted=False)
# newest_notification = user_notifications.reverse()[0]
# if newest_notification == newer_notification:
# newest_notification = None
# except Notification.DoesNotExist:
# newest_notification, newer_notification = None, None
#
# try:
# older_notification = current_notification.get_previous_by_sent_date(sent_to=user, is_deleted=False)
# oldest_notification = user_notifications[0]
# if oldest_notification == older_notification:
# oldest_notification = None
# except:
# oldest_notification, older_notification = None, None
#
# return newest_notification, newer_notification, current_notification, older_notification, oldest_notification
#
# else:
# return None, None, None, None, None
#
# Path: pytask/profile/utils.py
# def get_user(uid):
#
# user = shortcuts.get_object_or_404(User, pk=uid)
#
# if user.is_active:
# return user
# else:
# raise Http404
. Output only the next line. | viewing_user = get_user(uid) |
Predict the next line for this snippet: <|code_start|>class CustomRegistrationForm(RegistrationFormUniqueEmail):
"""Used instead of RegistrationForm used by default django-registration
backend, this adds aboutme, dob, gender, address, phonenum to the default
django-registration RegistrationForm"""
# overriding only this field from the parent Form Class since we
# don't like the restriction imposed by the registration app on username
# GMail has more or less set the standard for user names
username = forms.CharField(
max_length=30, widget=forms.TextInput(attrs=attrs_dict),
label=ugettext('Username'), help_text='Username can contain alphabet, '
'numbers or special characters underscore (_) and (.)')
full_name = forms.CharField(required=True, max_length=50,
label="Name as on your bank account",
help_text="Any DD/Cheque will be issued on \
this name")
aboutme = forms.CharField(required=True, widget=forms.Textarea,
max_length=1000, label=u"About Me",
help_text="A write up about yourself to aid the\
reviewer in judging your eligibility for a task.\
It can have your educational background, CGPA,\
field of interests etc.,"
)
dob = forms.DateField(help_text = "yyyy-mm-dd", required=True,
label=u'Date of Birth')
<|code_end|>
with the help of current file imports:
import re
from django import forms
from django.utils.translation import ugettext
from registration.forms import RegistrationFormUniqueEmail
from registration.forms import attrs_dict
from registration.models import RegistrationProfile
from pytask.profile.models import GENDER_CHOICES, Profile
and context from other files:
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
#
# class Profile(models.Model):
# full_name = models.CharField(
# max_length=50, verbose_name="Name as on bank account",
# help_text="Any DD/Cheque will be issued on this name")
#
# user = models.ForeignKey(User, unique = True)
#
# role = models.CharField(max_length=255,
# choices=ROLES_CHOICES,
# default=u"Contributor")
#
# pynts = models.PositiveSmallIntegerField(default=0)
#
# aboutme = models.TextField(
# blank = True,
# help_text="This information will be used to judge the eligibility "
# "for any task")
#
# dob = models.DateField(verbose_name=u"Date of Birth",
# help_text="YYYY-MM-DD")
#
# gender = models.CharField(verbose_name=u'Gender',
# max_length=24, choices=GENDER_CHOICES)
#
# address = models.TextField(
# blank=False, help_text="This information will be used to send "
# "any DDs/Cheques.")
#
# phonenum = models.CharField(max_length = 15, blank = True,
# verbose_name = u"Phone Number")
#
# def __unicode__(self):
# return unicode(self.user.username)
, which may contain function names, class names, or code. Output only the next line. | gender = forms.ChoiceField(choices = GENDER_CHOICES, |
Given the following code snippet before the placeholder: <|code_start|>
def clean_address(self):
""" Empty not allowed """
data = self.cleaned_data['address']
if not data.strip():
raise forms.ValidationError("Please enter an address")
return data
def clean_phonenum(self):
""" should be of 10 digits """
data = self.cleaned_data['phonenum']
if (not data.strip()) or \
(data.strip("1234567890")) or \
(len(data)!= 10):
raise forms.ValidationError("This is not a valid phone number")
return data
def save(self, profile_callback=None):
new_user = RegistrationProfile.objects.create_inactive_user(
username=self.cleaned_data['username'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'])
<|code_end|>
, predict the next line using imports from the current file:
import re
from django import forms
from django.utils.translation import ugettext
from registration.forms import RegistrationFormUniqueEmail
from registration.forms import attrs_dict
from registration.models import RegistrationProfile
from pytask.profile.models import GENDER_CHOICES, Profile
and context including class names, function names, and sometimes code from other files:
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
#
# class Profile(models.Model):
# full_name = models.CharField(
# max_length=50, verbose_name="Name as on bank account",
# help_text="Any DD/Cheque will be issued on this name")
#
# user = models.ForeignKey(User, unique = True)
#
# role = models.CharField(max_length=255,
# choices=ROLES_CHOICES,
# default=u"Contributor")
#
# pynts = models.PositiveSmallIntegerField(default=0)
#
# aboutme = models.TextField(
# blank = True,
# help_text="This information will be used to judge the eligibility "
# "for any task")
#
# dob = models.DateField(verbose_name=u"Date of Birth",
# help_text="YYYY-MM-DD")
#
# gender = models.CharField(verbose_name=u'Gender',
# max_length=24, choices=GENDER_CHOICES)
#
# address = models.TextField(
# blank=False, help_text="This information will be used to send "
# "any DDs/Cheques.")
#
# phonenum = models.CharField(max_length = 15, blank = True,
# verbose_name = u"Phone Number")
#
# def __unicode__(self):
# return unicode(self.user.username)
. Output only the next line. | new_profile = Profile(user=new_user, |
Given the following code snippet before the placeholder: <|code_start|>
__authors__ = [
'"Nishanth Amuluru" <nishanth@fossee.in>',
]
def seed_db():
""" a method to seed the database with random data """
for i in range(21,1,-1):
username = 'user'+str(i)
email = username+'@example.com'
password = '123456'
full_name = "User "+str(i)
dob = datetime.now()
gender = "M"
aboutme = "I am User"+str(i)
address = "I live in street"+str(i)
phonenum = "1234567890"
new_user = User.objects.create_user(username=username,
email=email,
password=password)
<|code_end|>
, predict the next line using imports from the current file:
import sys
from datetime import datetime
from django.core.management.base import NoArgsCommand
from django.contrib.auth.models import User
from pytask.profile.models import Profile, Notification
from pytask.utils import make_key
and context including class names, function names, and sometimes code from other files:
# Path: pytask/profile/models.py
# class Profile(models.Model):
# full_name = models.CharField(
# max_length=50, verbose_name="Name as on bank account",
# help_text="Any DD/Cheque will be issued on this name")
#
# user = models.ForeignKey(User, unique = True)
#
# role = models.CharField(max_length=255,
# choices=ROLES_CHOICES,
# default=u"Contributor")
#
# pynts = models.PositiveSmallIntegerField(default=0)
#
# aboutme = models.TextField(
# blank = True,
# help_text="This information will be used to judge the eligibility "
# "for any task")
#
# dob = models.DateField(verbose_name=u"Date of Birth",
# help_text="YYYY-MM-DD")
#
# gender = models.CharField(verbose_name=u'Gender',
# max_length=24, choices=GENDER_CHOICES)
#
# address = models.TextField(
# blank=False, help_text="This information will be used to send "
# "any DDs/Cheques.")
#
# phonenum = models.CharField(max_length = 15, blank = True,
# verbose_name = u"Phone Number")
#
# def __unicode__(self):
# return unicode(self.user.username)
#
# class Notification(models.Model):
# """ A model to hold notifications.
# All these are sent by the site to users.
# Hence there is no sent_from option.
# """
#
# sent_to = models.ForeignKey(User,
# related_name = "%(class)s_sent_to",
# blank = False)
#
# subject = models.CharField(max_length=100, blank=True)
#
# message = models.TextField()
#
# sent_date = models.DateTimeField()
#
# is_read = models.BooleanField(default = False)
#
# is_deleted = models.BooleanField(default = False)
. Output only the next line. | new_profile = Profile() |
Given the code snippet: <|code_start|> full_name = "User "+str(i)
dob = datetime.now()
gender = "M"
aboutme = "I am User"+str(i)
address = "I live in street"+str(i)
phonenum = "1234567890"
new_user = User.objects.create_user(username=username,
email=email,
password=password)
new_profile = Profile()
new_profile.user = new_user
new_profile.full_name = full_name
new_profile.dob = dob
new_profile.aboutme = aboutme
new_profile.gender = gender
new_profile.address = address
new_profile.phonenum = phonenum
if i%2 == 0:
new_profile.rights = "CT"
elif i%3 == 0:
new_profile.rights = "CR"
new_profile.save()
new_user.is_superuser = True
new_user.is_staff = True
new_user.save()
for i in range(10):
<|code_end|>
, generate the next line using the imports in this file:
import sys
from datetime import datetime
from django.core.management.base import NoArgsCommand
from django.contrib.auth.models import User
from pytask.profile.models import Profile, Notification
from pytask.utils import make_key
and context (functions, classes, or occasionally code) from other files:
# Path: pytask/profile/models.py
# class Profile(models.Model):
# full_name = models.CharField(
# max_length=50, verbose_name="Name as on bank account",
# help_text="Any DD/Cheque will be issued on this name")
#
# user = models.ForeignKey(User, unique = True)
#
# role = models.CharField(max_length=255,
# choices=ROLES_CHOICES,
# default=u"Contributor")
#
# pynts = models.PositiveSmallIntegerField(default=0)
#
# aboutme = models.TextField(
# blank = True,
# help_text="This information will be used to judge the eligibility "
# "for any task")
#
# dob = models.DateField(verbose_name=u"Date of Birth",
# help_text="YYYY-MM-DD")
#
# gender = models.CharField(verbose_name=u'Gender',
# max_length=24, choices=GENDER_CHOICES)
#
# address = models.TextField(
# blank=False, help_text="This information will be used to send "
# "any DDs/Cheques.")
#
# phonenum = models.CharField(max_length = 15, blank = True,
# verbose_name = u"Phone Number")
#
# def __unicode__(self):
# return unicode(self.user.username)
#
# class Notification(models.Model):
# """ A model to hold notifications.
# All these are sent by the site to users.
# Hence there is no sent_from option.
# """
#
# sent_to = models.ForeignKey(User,
# related_name = "%(class)s_sent_to",
# blank = False)
#
# subject = models.CharField(max_length=100, blank=True)
#
# message = models.TextField()
#
# sent_date = models.DateTimeField()
#
# is_read = models.BooleanField(default = False)
#
# is_deleted = models.BooleanField(default = False)
. Output only the next line. | Notification(sent_to=new_user, sent_date=datetime.now(), |
Using the snippet: <|code_start|># under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyTask 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
"""Module containing the context processors for taskapp.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
]
def configuration(request):
"""Context processor that puts all the necessary configuration
related variables to every RequestContext'ed template.
"""
return {
<|code_end|>
, determine the next line of code. You have imports:
from pytask.helpers import configuration as config_settings
and context (class names, function names, or code) available:
# Path: pytask/helpers/configuration.py
# TASK_CLAIM_ENABLED = False
. Output only the next line. | 'TASK_CLAIM_ENABLED': config_settings.TASK_CLAIM_ENABLED, |
Based on the snippet: <|code_start|># (at your option) any later version.
#
# PyTask 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
"""Module containing the middleware that processes exceptions for PyTask.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
]
class ExceptionMiddleware(object):
"""Middleware definition that processes exceptions raised in PyTaskViews.
"""
def process_exception(self, request, exception):
"""Process the exception raised.
"""
<|code_end|>
, predict the immediate next line with the help of imports:
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from pytask.helpers.exceptions import PyTaskException
from pytask.helpers.exceptions import UnauthorizedAccess
and context (classes, functions, sometimes code) from other files:
# Path: pytask/helpers/exceptions.py
# class PyTaskException(Exception):
# """Base exception class to be used through out PyTask
# """
#
# def __init__(self, message=None, **response_args):
# """Constructor specifying the exception specific attributes.
# """
#
# if not message:
# message = DEFAULT_ERROR_MESSAGE
#
# self.message = message
# self.response_args = response_args
#
# super(PyTaskException, self).__init__()
#
# Path: pytask/helpers/exceptions.py
# class UnauthorizedAccess(PyTaskException):
# """Exception that is raised when some one tries to access a view
# without the right priviliges.
# """
#
# def __init__(self, message=None, **response_args):
# """Constructor specifying the exception specific attributes
# """
#
# if not message:
# message = DEFAULT_LOGIN_MESSAGE
#
# response_args['status'] = 401
#
# super(UnauthorizedAccess, self).__init__(message, **response_args)
. Output only the next line. | if (isinstance(exception, PyTaskException) or |
Predict the next line after this snippet: <|code_start|>#
# PyTask 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
"""Module containing the middleware that processes exceptions for PyTask.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
]
class ExceptionMiddleware(object):
"""Middleware definition that processes exceptions raised in PyTaskViews.
"""
def process_exception(self, request, exception):
"""Process the exception raised.
"""
if (isinstance(exception, PyTaskException) or
<|code_end|>
using the current file's imports:
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from pytask.helpers.exceptions import PyTaskException
from pytask.helpers.exceptions import UnauthorizedAccess
and any relevant context from other files:
# Path: pytask/helpers/exceptions.py
# class PyTaskException(Exception):
# """Base exception class to be used through out PyTask
# """
#
# def __init__(self, message=None, **response_args):
# """Constructor specifying the exception specific attributes.
# """
#
# if not message:
# message = DEFAULT_ERROR_MESSAGE
#
# self.message = message
# self.response_args = response_args
#
# super(PyTaskException, self).__init__()
#
# Path: pytask/helpers/exceptions.py
# class UnauthorizedAccess(PyTaskException):
# """Exception that is raised when some one tries to access a view
# without the right priviliges.
# """
#
# def __init__(self, message=None, **response_args):
# """Constructor specifying the exception specific attributes
# """
#
# if not message:
# message = DEFAULT_LOGIN_MESSAGE
#
# response_args['status'] = 401
#
# super(UnauthorizedAccess, self).__init__(message, **response_args)
. Output only the next line. | isinstance(exception, UnauthorizedAccess)): |
Given the following code snippet before the placeholder: <|code_start|># PyTask is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyTask 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 General Public License
# for more details.
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
"""Helper script that contains many utilities.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@gmail.com>',
]
def remove_textbook_from_chapter():
"""Removes the tag Textbook from Chapter.
"""
<|code_end|>
, predict the next line using imports from the current file:
from tagging.managers import TaggedItem
from pytask.taskapp.models import Task
and context including class names, function names, and sometimes code from other files:
# Path: pytask/taskapp/models.py
# class Task(models.Model):
#
# parent = models.ForeignKey('self', blank=True, null=True,
# related_name="children_tasks")
#
# title = models.CharField(
# max_length=1024, verbose_name=u"Title",
# help_text=u"Keep it simple and below 100 chars.")
#
# desc = models.TextField(verbose_name=u"Description")
#
# status = models.CharField(max_length=255,
# choices=TASK_STATUS_CHOICES,
# default="Unpublished")
#
# tags_field = TagField(
# verbose_name=u"Tags", help_text=u"Give tags separated by commas. "
# "The allowed characters are all alphabet, numbers, underscore(_), "
# "period(.), forward slash(/), dash(-), ampersand(&), single quote(') "
# " and space.")
#
# pynts = models.PositiveSmallIntegerField(
# help_text=u"Number of Pynts a user gets on completing the task")
#
# created_by = models.ForeignKey(User,
# related_name="created_tasks")
#
# approved_by = models.ForeignKey(User, blank=True, null=True,
# related_name="approved_tasks")
#
# reviewers = models.ManyToManyField(User, blank=True, null=True,
# related_name="reviewing_tasks")
#
# claimed_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="claimed_tasks")
#
# selected_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="selected_tasks")
#
# creation_datetime = models.DateTimeField(auto_now_add=True)
#
# approval_datetime = models.DateTimeField(blank=True, null=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.title)
. Output only the next line. | tasks = TaggedItem.objects.get_by_model(Task, 'Chapter') |
Given the code snippet: <|code_start|># Copyright 2011 Authors of PyTask.
#
# This file is part of PyTask.
#
# PyTask is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyTask 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
'"Nishanth Amuluru" <nishanth@fossee.in>',
]
class CreateTaskForm(forms.ModelForm):
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
import re
from django import forms
from pytask.taskapp.models import Task
from pytask.taskapp.models import TaskClaim
from pytask.taskapp.models import TaskComment
from pytask.taskapp.models import WorkReport
and context (functions, classes, or occasionally code) from other files:
# Path: pytask/taskapp/models.py
# class Task(models.Model):
#
# parent = models.ForeignKey('self', blank=True, null=True,
# related_name="children_tasks")
#
# title = models.CharField(
# max_length=1024, verbose_name=u"Title",
# help_text=u"Keep it simple and below 100 chars.")
#
# desc = models.TextField(verbose_name=u"Description")
#
# status = models.CharField(max_length=255,
# choices=TASK_STATUS_CHOICES,
# default="Unpublished")
#
# tags_field = TagField(
# verbose_name=u"Tags", help_text=u"Give tags separated by commas. "
# "The allowed characters are all alphabet, numbers, underscore(_), "
# "period(.), forward slash(/), dash(-), ampersand(&), single quote(') "
# " and space.")
#
# pynts = models.PositiveSmallIntegerField(
# help_text=u"Number of Pynts a user gets on completing the task")
#
# created_by = models.ForeignKey(User,
# related_name="created_tasks")
#
# approved_by = models.ForeignKey(User, blank=True, null=True,
# related_name="approved_tasks")
#
# reviewers = models.ManyToManyField(User, blank=True, null=True,
# related_name="reviewing_tasks")
#
# claimed_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="claimed_tasks")
#
# selected_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="selected_tasks")
#
# creation_datetime = models.DateTimeField(auto_now_add=True)
#
# approval_datetime = models.DateTimeField(blank=True, null=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.title)
#
# Path: pytask/taskapp/models.py
# class TaskClaim(models.Model):
#
# task = models.ForeignKey('Task', related_name="claims")
#
# claimed_by = models.ForeignKey(User,
# related_name="claimed_claims")
# proposal = models.TextField()
#
# claim_datetime = models.DateTimeField(auto_now_add=True)
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class TaskComment(models.Model):
#
# task = models.ForeignKey('Task', related_name="comments")
#
# data = models.TextField(verbose_name='Comment')
#
# commented_by = models.ForeignKey(User,
# related_name="commented_taskcomments")
#
# deleted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="deleted_taskcomments")
#
# comment_datetime = models.DateTimeField(auto_now_add=True)
#
# is_deleted = models.BooleanField(default=False)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class WorkReport(models.Model):
#
# task = models.ForeignKey(Task, related_name="reports")
#
# submitted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="submitted_reports")
#
# approved_by = models.ForeignKey(User, null=True, blank=True,
# related_name="approved_reports")
#
# data = models.TextField(verbose_name="Report")
#
# summary = models.CharField(max_length=1024, verbose_name="Summary",
# help_text="A one line summary")
#
# attachment = models.FileField(upload_to=UPLOADS_DIR)
#
# revision = models.PositiveIntegerField(default=0)
#
# submitted_at = models.DateTimeField(auto_now_add=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
. Output only the next line. | model = Task |
Predict the next line for this snippet: <|code_start|> def clean_tags_field(self):
"""Clean the tags field to contain only allowed characters.
"""
tags_field = self.cleaned_data.get('tags_field', '')
if tags_field and not re.match(r'[\w,\-&./\'\" ]+', tags_field):
raise forms.ValidationError("Contains unallowed characters. "
"Allowed characters are all alphabet, numbers, underscore(_), "
"period(.), forward slash(/), dash(-), ampersand(&), single "
"quote(') and space.")
return tags_field
class TaskCommentForm(forms.ModelForm):
class Meta:
model = TaskComment
fields = ['data']
def clean_data(self):
data = self.cleaned_data['data'].strip()
if not data:
raise forms.ValidationError("Please add some content")
return data
class ClaimTaskForm(forms.ModelForm):
class Meta:
<|code_end|>
with the help of current file imports:
import re
from django import forms
from pytask.taskapp.models import Task
from pytask.taskapp.models import TaskClaim
from pytask.taskapp.models import TaskComment
from pytask.taskapp.models import WorkReport
and context from other files:
# Path: pytask/taskapp/models.py
# class Task(models.Model):
#
# parent = models.ForeignKey('self', blank=True, null=True,
# related_name="children_tasks")
#
# title = models.CharField(
# max_length=1024, verbose_name=u"Title",
# help_text=u"Keep it simple and below 100 chars.")
#
# desc = models.TextField(verbose_name=u"Description")
#
# status = models.CharField(max_length=255,
# choices=TASK_STATUS_CHOICES,
# default="Unpublished")
#
# tags_field = TagField(
# verbose_name=u"Tags", help_text=u"Give tags separated by commas. "
# "The allowed characters are all alphabet, numbers, underscore(_), "
# "period(.), forward slash(/), dash(-), ampersand(&), single quote(') "
# " and space.")
#
# pynts = models.PositiveSmallIntegerField(
# help_text=u"Number of Pynts a user gets on completing the task")
#
# created_by = models.ForeignKey(User,
# related_name="created_tasks")
#
# approved_by = models.ForeignKey(User, blank=True, null=True,
# related_name="approved_tasks")
#
# reviewers = models.ManyToManyField(User, blank=True, null=True,
# related_name="reviewing_tasks")
#
# claimed_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="claimed_tasks")
#
# selected_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="selected_tasks")
#
# creation_datetime = models.DateTimeField(auto_now_add=True)
#
# approval_datetime = models.DateTimeField(blank=True, null=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.title)
#
# Path: pytask/taskapp/models.py
# class TaskClaim(models.Model):
#
# task = models.ForeignKey('Task', related_name="claims")
#
# claimed_by = models.ForeignKey(User,
# related_name="claimed_claims")
# proposal = models.TextField()
#
# claim_datetime = models.DateTimeField(auto_now_add=True)
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class TaskComment(models.Model):
#
# task = models.ForeignKey('Task', related_name="comments")
#
# data = models.TextField(verbose_name='Comment')
#
# commented_by = models.ForeignKey(User,
# related_name="commented_taskcomments")
#
# deleted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="deleted_taskcomments")
#
# comment_datetime = models.DateTimeField(auto_now_add=True)
#
# is_deleted = models.BooleanField(default=False)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class WorkReport(models.Model):
#
# task = models.ForeignKey(Task, related_name="reports")
#
# submitted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="submitted_reports")
#
# approved_by = models.ForeignKey(User, null=True, blank=True,
# related_name="approved_reports")
#
# data = models.TextField(verbose_name="Report")
#
# summary = models.CharField(max_length=1024, verbose_name="Summary",
# help_text="A one line summary")
#
# attachment = models.FileField(upload_to=UPLOADS_DIR)
#
# revision = models.PositiveIntegerField(default=0)
#
# submitted_at = models.DateTimeField(auto_now_add=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
, which may contain function names, class names, or code. Output only the next line. | model = TaskClaim |
Continue the code snippet: <|code_start|>
return data
def clean_title(self):
data = self.cleaned_data['title'].strip()
try:
prev_task = Task.objects.exclude(status="DL").get(title__iexact=data)
if prev_task.id != self.instance.id:
raise forms.ValidationError("Another task with same title exists")
else:
return data
except Task.DoesNotExist:
return data
def clean_tags_field(self):
"""Clean the tags field to contain only allowed characters.
"""
tags_field = self.cleaned_data.get('tags_field', '')
if tags_field and not re.match(r'[\w,\-&./\'\" ]+', tags_field):
raise forms.ValidationError("Contains unallowed characters. "
"Allowed characters are all alphabet, numbers, underscore(_), "
"period(.), forward slash(/), dash(-), ampersand(&), single "
"quote(') and space.")
return tags_field
class TaskCommentForm(forms.ModelForm):
class Meta:
<|code_end|>
. Use current file imports:
import re
from django import forms
from pytask.taskapp.models import Task
from pytask.taskapp.models import TaskClaim
from pytask.taskapp.models import TaskComment
from pytask.taskapp.models import WorkReport
and context (classes, functions, or code) from other files:
# Path: pytask/taskapp/models.py
# class Task(models.Model):
#
# parent = models.ForeignKey('self', blank=True, null=True,
# related_name="children_tasks")
#
# title = models.CharField(
# max_length=1024, verbose_name=u"Title",
# help_text=u"Keep it simple and below 100 chars.")
#
# desc = models.TextField(verbose_name=u"Description")
#
# status = models.CharField(max_length=255,
# choices=TASK_STATUS_CHOICES,
# default="Unpublished")
#
# tags_field = TagField(
# verbose_name=u"Tags", help_text=u"Give tags separated by commas. "
# "The allowed characters are all alphabet, numbers, underscore(_), "
# "period(.), forward slash(/), dash(-), ampersand(&), single quote(') "
# " and space.")
#
# pynts = models.PositiveSmallIntegerField(
# help_text=u"Number of Pynts a user gets on completing the task")
#
# created_by = models.ForeignKey(User,
# related_name="created_tasks")
#
# approved_by = models.ForeignKey(User, blank=True, null=True,
# related_name="approved_tasks")
#
# reviewers = models.ManyToManyField(User, blank=True, null=True,
# related_name="reviewing_tasks")
#
# claimed_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="claimed_tasks")
#
# selected_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="selected_tasks")
#
# creation_datetime = models.DateTimeField(auto_now_add=True)
#
# approval_datetime = models.DateTimeField(blank=True, null=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.title)
#
# Path: pytask/taskapp/models.py
# class TaskClaim(models.Model):
#
# task = models.ForeignKey('Task', related_name="claims")
#
# claimed_by = models.ForeignKey(User,
# related_name="claimed_claims")
# proposal = models.TextField()
#
# claim_datetime = models.DateTimeField(auto_now_add=True)
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class TaskComment(models.Model):
#
# task = models.ForeignKey('Task', related_name="comments")
#
# data = models.TextField(verbose_name='Comment')
#
# commented_by = models.ForeignKey(User,
# related_name="commented_taskcomments")
#
# deleted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="deleted_taskcomments")
#
# comment_datetime = models.DateTimeField(auto_now_add=True)
#
# is_deleted = models.BooleanField(default=False)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class WorkReport(models.Model):
#
# task = models.ForeignKey(Task, related_name="reports")
#
# submitted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="submitted_reports")
#
# approved_by = models.ForeignKey(User, null=True, blank=True,
# related_name="approved_reports")
#
# data = models.TextField(verbose_name="Report")
#
# summary = models.CharField(max_length=1024, verbose_name="Summary",
# help_text="A one line summary")
#
# attachment = models.FileField(upload_to=UPLOADS_DIR)
#
# revision = models.PositiveIntegerField(default=0)
#
# submitted_at = models.DateTimeField(auto_now_add=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
. Output only the next line. | model = TaskComment |
Given the following code snippet before the placeholder: <|code_start|> """ if is_plain is true, it means the task has no subs/deps.
so we also give a radio button to choose between subs and dependencies.
else we only give choices.
"""
class myForm(forms.Form):
if is_plain:
type_choices = [('S','Subtasks'),('D','Dependencies')]
type = forms.ChoiceField(type_choices, widget=forms.RadioSelect)
task = forms.ChoiceField(choices=task_choices)
return myForm()
def AssignPyntForm(choices, instance=None):
class myForm(forms.Form):
user = forms.ChoiceField(choices=choices, required=True)
pynts = forms.IntegerField(min_value=0, required=True, help_text="Choose wisely since it cannot be undone.")
return myForm(instance) if instance else myForm()
def RemoveUserForm(choices, instance=None):
class myForm(forms.Form):
user = forms.ChoiceField(choices=choices, required=True)
reason = forms.CharField(min_length=1, required=True)
return myForm(instance) if instance else myForm()
class WorkReportForm(forms.ModelForm):
class Meta:
<|code_end|>
, predict the next line using imports from the current file:
import re
from django import forms
from pytask.taskapp.models import Task
from pytask.taskapp.models import TaskClaim
from pytask.taskapp.models import TaskComment
from pytask.taskapp.models import WorkReport
and context including class names, function names, and sometimes code from other files:
# Path: pytask/taskapp/models.py
# class Task(models.Model):
#
# parent = models.ForeignKey('self', blank=True, null=True,
# related_name="children_tasks")
#
# title = models.CharField(
# max_length=1024, verbose_name=u"Title",
# help_text=u"Keep it simple and below 100 chars.")
#
# desc = models.TextField(verbose_name=u"Description")
#
# status = models.CharField(max_length=255,
# choices=TASK_STATUS_CHOICES,
# default="Unpublished")
#
# tags_field = TagField(
# verbose_name=u"Tags", help_text=u"Give tags separated by commas. "
# "The allowed characters are all alphabet, numbers, underscore(_), "
# "period(.), forward slash(/), dash(-), ampersand(&), single quote(') "
# " and space.")
#
# pynts = models.PositiveSmallIntegerField(
# help_text=u"Number of Pynts a user gets on completing the task")
#
# created_by = models.ForeignKey(User,
# related_name="created_tasks")
#
# approved_by = models.ForeignKey(User, blank=True, null=True,
# related_name="approved_tasks")
#
# reviewers = models.ManyToManyField(User, blank=True, null=True,
# related_name="reviewing_tasks")
#
# claimed_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="claimed_tasks")
#
# selected_users = models.ManyToManyField(User, blank=True, null=True,
# related_name="selected_tasks")
#
# creation_datetime = models.DateTimeField(auto_now_add=True)
#
# approval_datetime = models.DateTimeField(blank=True, null=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.title)
#
# Path: pytask/taskapp/models.py
# class TaskClaim(models.Model):
#
# task = models.ForeignKey('Task', related_name="claims")
#
# claimed_by = models.ForeignKey(User,
# related_name="claimed_claims")
# proposal = models.TextField()
#
# claim_datetime = models.DateTimeField(auto_now_add=True)
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class TaskComment(models.Model):
#
# task = models.ForeignKey('Task', related_name="comments")
#
# data = models.TextField(verbose_name='Comment')
#
# commented_by = models.ForeignKey(User,
# related_name="commented_taskcomments")
#
# deleted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="deleted_taskcomments")
#
# comment_datetime = models.DateTimeField(auto_now_add=True)
#
# is_deleted = models.BooleanField(default=False)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
#
# def __unicode__(self):
# return unicode(self.task.title)
#
# Path: pytask/taskapp/models.py
# class WorkReport(models.Model):
#
# task = models.ForeignKey(Task, related_name="reports")
#
# submitted_by = models.ForeignKey(User, null=True, blank=True,
# related_name="submitted_reports")
#
# approved_by = models.ForeignKey(User, null=True, blank=True,
# related_name="approved_reports")
#
# data = models.TextField(verbose_name="Report")
#
# summary = models.CharField(max_length=1024, verbose_name="Summary",
# help_text="A one line summary")
#
# attachment = models.FileField(upload_to=UPLOADS_DIR)
#
# revision = models.PositiveIntegerField(default=0)
#
# submitted_at = models.DateTimeField(auto_now_add=True)
#
# last_modified = models.DateTimeField(auto_now=True,
# default=datetime.now())
. Output only the next line. | model = WorkReport |
Using the snippet: <|code_start|> 'task/view.html', RequestContext(request, context))
else:
form = taskapp_forms.TaskCommentForm()
context['form'] = form
return shortcuts.render_to_response(
'task/view.html', RequestContext(request, context))
@login_required
def edit_task(request, task_id, **kwargs):
""" only creator gets to edit the task and that too only before it gets
approved.
"""
user = request.user
profile = user.get_profile()
task_url = kwargs.get(
'task_url', reverse('view_task', kwargs={'task_id': task_id}))
task = shortcuts.get_object_or_404(taskapp_models.Task, pk=task_id)
is_creator = True if user == task.created_by else False
if ((is_creator or profile.role != profile_models.ROLES_CHOICES[3][0])
and task.status in [taskapp_models.TASK_STATUS_CHOICES[0][0],
taskapp_models.TASK_STATUS_CHOICES[1][0]]):
can_edit = True
else:
can_edit = False
if not can_edit:
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime
from django import shortcuts
from django import http
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.utils import simplejson as json
from django.utils.translation import ugettext
from tagging.models import Tag
from tagging.models import TaggedItem
from pytask.helpers import exceptions
from pytask.views import show_msg
from pytask.profile import models as profile_models
from pytask.taskapp import forms as taskapp_forms
from pytask.taskapp import models as taskapp_models
and context (class names, function names, or code) available:
# Path: pytask/helpers/exceptions.py
# DEFAULT_ERROR_MESSAGE = ugettext(
# "There was some error in your request.")
# DEFAULT_LOGIN_MESSAGE = ugettext(
# "You have to login to view this page.")
# class PyTaskException(Exception):
# class UnauthorizedAccess(PyTaskException):
# def __init__(self, message=None, **response_args):
# def __init__(self, message=None, **response_args):
#
# Path: pytask/views.py
# def show_msg(user, message, redirect_url=None, url_desc=None):
# """ simply redirect to homepage """
#
# context = {
# 'user': user,
# 'message': message,
# 'redirect_url': redirect_url,
# 'url_desc': url_desc
# }
#
# return render_to_response('show_msg.html', context)
#
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
# ROLES_CHOICES = (
# ("Administrator", "Administrator"),
# ("Coordinator", "Coordinator"),
# ("Mentor", "Mentor"),
# ("Contributor", "Contributor"),
# )
# ROLE_CHOICES = (
# ("Administrator", "Request sent by Administrator \
# to a user at lower level, asking him to act as a administrator"),
# ("Coordinator", "Request sent by Coordinator \
# to a user at lower level, asking him to act as a coordinator"),
# )
# class Profile(models.Model):
# class Notification(models.Model):
# class RoleRequest(models.Model):
# def __unicode__(self):
#
# Path: pytask/taskapp/forms.py
# class CreateTaskForm(forms.ModelForm):
# class Meta:
# class EditTaskForm(forms.ModelForm):
# class Meta:
# class TaskCommentForm(forms.ModelForm):
# class Meta:
# class ClaimTaskForm(forms.ModelForm):
# class Meta:
# class myform(forms.Form):
# class CreateTextbookForm(forms.ModelForm):
# class Meta:
# class CreateChapterForm(forms.ModelForm):
# class Meta:
# class EditTextbookForm(forms.ModelForm):
# class Meta:
# class myForm(forms.Form):
# class myForm(forms.Form):
# class myForm(forms.Form):
# class WorkReportForm(forms.ModelForm):
# class Meta:
# def clean_title(self):
# def clean_desc(self):
# def clean_tags_field(self):
# def clean_desc(self):
# def clean_title(self):
# def clean_tags_field(self):
# def clean_data(self):
# def clean_proposal(self):
# def ChoiceForm(choices, data=None, label="choice"):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def AddTaskForm(task_choices, is_plain=False):
# def AssignPyntForm(choices, instance=None):
# def RemoveUserForm(choices, instance=None):
#
# Path: pytask/taskapp/models.py
# TASK_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("Locked", "Locked"),
# ("Working", "Working"),
# ("Closed", "Closed"),
# ("Deleted", "Deleted"),
# ("Completed", "Completed"))
# TB_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("All tasks have users selected", "All tasks have users selected"),
# ("Completed", "Completed"))
# UPLOADS_DIR = "/pytask/static/uploads"
# class Task(models.Model):
# class TaskComment(models.Model):
# class TaskClaim(models.Model):
# class WorkReport(models.Model):
# class ReportComment(models.Model):
# class PyntRequest(models.Model):
# class TextBook(models.Model):
# def __unicode__(self):
# def __unicode__(self):
# def __unicode__(self):
. Output only the next line. | raise exceptions.UnauthorizedAccess(NO_EDIT_RIGHT) |
Predict the next line for this snippet: <|code_start|> }
context.update(csrf(request))
can_create_task = False if (
profile.role == profile_models.ROLES_CHOICES[3][0]) else True
if can_create_task:
if request.method == "POST":
form = taskapp_forms.CreateTaskForm(request.POST)
if form.is_valid():
data = form.cleaned_data.copy()
data.update({"created_by": user,
"creation_datetime": datetime.now(),
})
task = taskapp_models.Task(**data)
task.save()
task_url = reverse('view_task', kwargs={'task_id': task.id})
return shortcuts.redirect(task_url)
else:
context.update({'form':form})
return shortcuts.render_to_response(
'task/edit.html', RequestContext(request, context))
else:
form = taskapp_forms.CreateTaskForm()
context.update({'form': form})
return shortcuts.render_to_response(
'task/edit.html', RequestContext(request, context))
else:
<|code_end|>
with the help of current file imports:
from datetime import datetime
from django import shortcuts
from django import http
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.utils import simplejson as json
from django.utils.translation import ugettext
from tagging.models import Tag
from tagging.models import TaggedItem
from pytask.helpers import exceptions
from pytask.views import show_msg
from pytask.profile import models as profile_models
from pytask.taskapp import forms as taskapp_forms
from pytask.taskapp import models as taskapp_models
and context from other files:
# Path: pytask/helpers/exceptions.py
# DEFAULT_ERROR_MESSAGE = ugettext(
# "There was some error in your request.")
# DEFAULT_LOGIN_MESSAGE = ugettext(
# "You have to login to view this page.")
# class PyTaskException(Exception):
# class UnauthorizedAccess(PyTaskException):
# def __init__(self, message=None, **response_args):
# def __init__(self, message=None, **response_args):
#
# Path: pytask/views.py
# def show_msg(user, message, redirect_url=None, url_desc=None):
# """ simply redirect to homepage """
#
# context = {
# 'user': user,
# 'message': message,
# 'redirect_url': redirect_url,
# 'url_desc': url_desc
# }
#
# return render_to_response('show_msg.html', context)
#
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
# ROLES_CHOICES = (
# ("Administrator", "Administrator"),
# ("Coordinator", "Coordinator"),
# ("Mentor", "Mentor"),
# ("Contributor", "Contributor"),
# )
# ROLE_CHOICES = (
# ("Administrator", "Request sent by Administrator \
# to a user at lower level, asking him to act as a administrator"),
# ("Coordinator", "Request sent by Coordinator \
# to a user at lower level, asking him to act as a coordinator"),
# )
# class Profile(models.Model):
# class Notification(models.Model):
# class RoleRequest(models.Model):
# def __unicode__(self):
#
# Path: pytask/taskapp/forms.py
# class CreateTaskForm(forms.ModelForm):
# class Meta:
# class EditTaskForm(forms.ModelForm):
# class Meta:
# class TaskCommentForm(forms.ModelForm):
# class Meta:
# class ClaimTaskForm(forms.ModelForm):
# class Meta:
# class myform(forms.Form):
# class CreateTextbookForm(forms.ModelForm):
# class Meta:
# class CreateChapterForm(forms.ModelForm):
# class Meta:
# class EditTextbookForm(forms.ModelForm):
# class Meta:
# class myForm(forms.Form):
# class myForm(forms.Form):
# class myForm(forms.Form):
# class WorkReportForm(forms.ModelForm):
# class Meta:
# def clean_title(self):
# def clean_desc(self):
# def clean_tags_field(self):
# def clean_desc(self):
# def clean_title(self):
# def clean_tags_field(self):
# def clean_data(self):
# def clean_proposal(self):
# def ChoiceForm(choices, data=None, label="choice"):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def AddTaskForm(task_choices, is_plain=False):
# def AssignPyntForm(choices, instance=None):
# def RemoveUserForm(choices, instance=None):
#
# Path: pytask/taskapp/models.py
# TASK_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("Locked", "Locked"),
# ("Working", "Working"),
# ("Closed", "Closed"),
# ("Deleted", "Deleted"),
# ("Completed", "Completed"))
# TB_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("All tasks have users selected", "All tasks have users selected"),
# ("Completed", "Completed"))
# UPLOADS_DIR = "/pytask/static/uploads"
# class Task(models.Model):
# class TaskComment(models.Model):
# class TaskClaim(models.Model):
# class WorkReport(models.Model):
# class ReportComment(models.Model):
# class PyntRequest(models.Model):
# class TextBook(models.Model):
# def __unicode__(self):
# def __unicode__(self):
# def __unicode__(self):
, which may contain function names, class names, or code. Output only the next line. | return show_msg(user, 'You are not authorised to create a task.') |
Continue the code snippet: <|code_start|>
DONT_CLAIM_TASK_MSG = ugettext(
"Please don't submit any claims for the tasks until you get an email "
"to start claiming tasks. Please be warned that the task claim work-"
"flow may change. So all the claims submitted before the workshop may "
"not be valid.")
NO_EDIT_RIGHT = ugettext(
"You are not authorized to edit this page.")
NO_MOD_REVIEWERS_RIGHT = ugettext(
"You are not authorized to moderate reviewers.")
NO_SELECT_USER = ugettext(
"You are not authorized to approve task claims.")
@login_required
def create_task(request):
user = request.user
profile = user.get_profile()
context = {"user": user,
"profile": profile,
}
context.update(csrf(request))
can_create_task = False if (
<|code_end|>
. Use current file imports:
from datetime import datetime
from django import shortcuts
from django import http
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.utils import simplejson as json
from django.utils.translation import ugettext
from tagging.models import Tag
from tagging.models import TaggedItem
from pytask.helpers import exceptions
from pytask.views import show_msg
from pytask.profile import models as profile_models
from pytask.taskapp import forms as taskapp_forms
from pytask.taskapp import models as taskapp_models
and context (classes, functions, or code) from other files:
# Path: pytask/helpers/exceptions.py
# DEFAULT_ERROR_MESSAGE = ugettext(
# "There was some error in your request.")
# DEFAULT_LOGIN_MESSAGE = ugettext(
# "You have to login to view this page.")
# class PyTaskException(Exception):
# class UnauthorizedAccess(PyTaskException):
# def __init__(self, message=None, **response_args):
# def __init__(self, message=None, **response_args):
#
# Path: pytask/views.py
# def show_msg(user, message, redirect_url=None, url_desc=None):
# """ simply redirect to homepage """
#
# context = {
# 'user': user,
# 'message': message,
# 'redirect_url': redirect_url,
# 'url_desc': url_desc
# }
#
# return render_to_response('show_msg.html', context)
#
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
# ROLES_CHOICES = (
# ("Administrator", "Administrator"),
# ("Coordinator", "Coordinator"),
# ("Mentor", "Mentor"),
# ("Contributor", "Contributor"),
# )
# ROLE_CHOICES = (
# ("Administrator", "Request sent by Administrator \
# to a user at lower level, asking him to act as a administrator"),
# ("Coordinator", "Request sent by Coordinator \
# to a user at lower level, asking him to act as a coordinator"),
# )
# class Profile(models.Model):
# class Notification(models.Model):
# class RoleRequest(models.Model):
# def __unicode__(self):
#
# Path: pytask/taskapp/forms.py
# class CreateTaskForm(forms.ModelForm):
# class Meta:
# class EditTaskForm(forms.ModelForm):
# class Meta:
# class TaskCommentForm(forms.ModelForm):
# class Meta:
# class ClaimTaskForm(forms.ModelForm):
# class Meta:
# class myform(forms.Form):
# class CreateTextbookForm(forms.ModelForm):
# class Meta:
# class CreateChapterForm(forms.ModelForm):
# class Meta:
# class EditTextbookForm(forms.ModelForm):
# class Meta:
# class myForm(forms.Form):
# class myForm(forms.Form):
# class myForm(forms.Form):
# class WorkReportForm(forms.ModelForm):
# class Meta:
# def clean_title(self):
# def clean_desc(self):
# def clean_tags_field(self):
# def clean_desc(self):
# def clean_title(self):
# def clean_tags_field(self):
# def clean_data(self):
# def clean_proposal(self):
# def ChoiceForm(choices, data=None, label="choice"):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def AddTaskForm(task_choices, is_plain=False):
# def AssignPyntForm(choices, instance=None):
# def RemoveUserForm(choices, instance=None):
#
# Path: pytask/taskapp/models.py
# TASK_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("Locked", "Locked"),
# ("Working", "Working"),
# ("Closed", "Closed"),
# ("Deleted", "Deleted"),
# ("Completed", "Completed"))
# TB_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("All tasks have users selected", "All tasks have users selected"),
# ("Completed", "Completed"))
# UPLOADS_DIR = "/pytask/static/uploads"
# class Task(models.Model):
# class TaskComment(models.Model):
# class TaskClaim(models.Model):
# class WorkReport(models.Model):
# class ReportComment(models.Model):
# class PyntRequest(models.Model):
# class TextBook(models.Model):
# def __unicode__(self):
# def __unicode__(self):
# def __unicode__(self):
. Output only the next line. | profile.role == profile_models.ROLES_CHOICES[3][0]) else True |
Continue the code snippet: <|code_start|> "to start claiming tasks. Please be warned that the task claim work-"
"flow may change. So all the claims submitted before the workshop may "
"not be valid.")
NO_EDIT_RIGHT = ugettext(
"You are not authorized to edit this page.")
NO_MOD_REVIEWERS_RIGHT = ugettext(
"You are not authorized to moderate reviewers.")
NO_SELECT_USER = ugettext(
"You are not authorized to approve task claims.")
@login_required
def create_task(request):
user = request.user
profile = user.get_profile()
context = {"user": user,
"profile": profile,
}
context.update(csrf(request))
can_create_task = False if (
profile.role == profile_models.ROLES_CHOICES[3][0]) else True
if can_create_task:
if request.method == "POST":
<|code_end|>
. Use current file imports:
from datetime import datetime
from django import shortcuts
from django import http
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.utils import simplejson as json
from django.utils.translation import ugettext
from tagging.models import Tag
from tagging.models import TaggedItem
from pytask.helpers import exceptions
from pytask.views import show_msg
from pytask.profile import models as profile_models
from pytask.taskapp import forms as taskapp_forms
from pytask.taskapp import models as taskapp_models
and context (classes, functions, or code) from other files:
# Path: pytask/helpers/exceptions.py
# DEFAULT_ERROR_MESSAGE = ugettext(
# "There was some error in your request.")
# DEFAULT_LOGIN_MESSAGE = ugettext(
# "You have to login to view this page.")
# class PyTaskException(Exception):
# class UnauthorizedAccess(PyTaskException):
# def __init__(self, message=None, **response_args):
# def __init__(self, message=None, **response_args):
#
# Path: pytask/views.py
# def show_msg(user, message, redirect_url=None, url_desc=None):
# """ simply redirect to homepage """
#
# context = {
# 'user': user,
# 'message': message,
# 'redirect_url': redirect_url,
# 'url_desc': url_desc
# }
#
# return render_to_response('show_msg.html', context)
#
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
# ROLES_CHOICES = (
# ("Administrator", "Administrator"),
# ("Coordinator", "Coordinator"),
# ("Mentor", "Mentor"),
# ("Contributor", "Contributor"),
# )
# ROLE_CHOICES = (
# ("Administrator", "Request sent by Administrator \
# to a user at lower level, asking him to act as a administrator"),
# ("Coordinator", "Request sent by Coordinator \
# to a user at lower level, asking him to act as a coordinator"),
# )
# class Profile(models.Model):
# class Notification(models.Model):
# class RoleRequest(models.Model):
# def __unicode__(self):
#
# Path: pytask/taskapp/forms.py
# class CreateTaskForm(forms.ModelForm):
# class Meta:
# class EditTaskForm(forms.ModelForm):
# class Meta:
# class TaskCommentForm(forms.ModelForm):
# class Meta:
# class ClaimTaskForm(forms.ModelForm):
# class Meta:
# class myform(forms.Form):
# class CreateTextbookForm(forms.ModelForm):
# class Meta:
# class CreateChapterForm(forms.ModelForm):
# class Meta:
# class EditTextbookForm(forms.ModelForm):
# class Meta:
# class myForm(forms.Form):
# class myForm(forms.Form):
# class myForm(forms.Form):
# class WorkReportForm(forms.ModelForm):
# class Meta:
# def clean_title(self):
# def clean_desc(self):
# def clean_tags_field(self):
# def clean_desc(self):
# def clean_title(self):
# def clean_tags_field(self):
# def clean_data(self):
# def clean_proposal(self):
# def ChoiceForm(choices, data=None, label="choice"):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def AddTaskForm(task_choices, is_plain=False):
# def AssignPyntForm(choices, instance=None):
# def RemoveUserForm(choices, instance=None):
#
# Path: pytask/taskapp/models.py
# TASK_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("Locked", "Locked"),
# ("Working", "Working"),
# ("Closed", "Closed"),
# ("Deleted", "Deleted"),
# ("Completed", "Completed"))
# TB_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("All tasks have users selected", "All tasks have users selected"),
# ("Completed", "Completed"))
# UPLOADS_DIR = "/pytask/static/uploads"
# class Task(models.Model):
# class TaskComment(models.Model):
# class TaskClaim(models.Model):
# class WorkReport(models.Model):
# class ReportComment(models.Model):
# class PyntRequest(models.Model):
# class TextBook(models.Model):
# def __unicode__(self):
# def __unicode__(self):
# def __unicode__(self):
. Output only the next line. | form = taskapp_forms.CreateTaskForm(request.POST) |
Continue the code snippet: <|code_start|>NO_MOD_REVIEWERS_RIGHT = ugettext(
"You are not authorized to moderate reviewers.")
NO_SELECT_USER = ugettext(
"You are not authorized to approve task claims.")
@login_required
def create_task(request):
user = request.user
profile = user.get_profile()
context = {"user": user,
"profile": profile,
}
context.update(csrf(request))
can_create_task = False if (
profile.role == profile_models.ROLES_CHOICES[3][0]) else True
if can_create_task:
if request.method == "POST":
form = taskapp_forms.CreateTaskForm(request.POST)
if form.is_valid():
data = form.cleaned_data.copy()
data.update({"created_by": user,
"creation_datetime": datetime.now(),
})
<|code_end|>
. Use current file imports:
from datetime import datetime
from django import shortcuts
from django import http
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.utils import simplejson as json
from django.utils.translation import ugettext
from tagging.models import Tag
from tagging.models import TaggedItem
from pytask.helpers import exceptions
from pytask.views import show_msg
from pytask.profile import models as profile_models
from pytask.taskapp import forms as taskapp_forms
from pytask.taskapp import models as taskapp_models
and context (classes, functions, or code) from other files:
# Path: pytask/helpers/exceptions.py
# DEFAULT_ERROR_MESSAGE = ugettext(
# "There was some error in your request.")
# DEFAULT_LOGIN_MESSAGE = ugettext(
# "You have to login to view this page.")
# class PyTaskException(Exception):
# class UnauthorizedAccess(PyTaskException):
# def __init__(self, message=None, **response_args):
# def __init__(self, message=None, **response_args):
#
# Path: pytask/views.py
# def show_msg(user, message, redirect_url=None, url_desc=None):
# """ simply redirect to homepage """
#
# context = {
# 'user': user,
# 'message': message,
# 'redirect_url': redirect_url,
# 'url_desc': url_desc
# }
#
# return render_to_response('show_msg.html', context)
#
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
# ROLES_CHOICES = (
# ("Administrator", "Administrator"),
# ("Coordinator", "Coordinator"),
# ("Mentor", "Mentor"),
# ("Contributor", "Contributor"),
# )
# ROLE_CHOICES = (
# ("Administrator", "Request sent by Administrator \
# to a user at lower level, asking him to act as a administrator"),
# ("Coordinator", "Request sent by Coordinator \
# to a user at lower level, asking him to act as a coordinator"),
# )
# class Profile(models.Model):
# class Notification(models.Model):
# class RoleRequest(models.Model):
# def __unicode__(self):
#
# Path: pytask/taskapp/forms.py
# class CreateTaskForm(forms.ModelForm):
# class Meta:
# class EditTaskForm(forms.ModelForm):
# class Meta:
# class TaskCommentForm(forms.ModelForm):
# class Meta:
# class ClaimTaskForm(forms.ModelForm):
# class Meta:
# class myform(forms.Form):
# class CreateTextbookForm(forms.ModelForm):
# class Meta:
# class CreateChapterForm(forms.ModelForm):
# class Meta:
# class EditTextbookForm(forms.ModelForm):
# class Meta:
# class myForm(forms.Form):
# class myForm(forms.Form):
# class myForm(forms.Form):
# class WorkReportForm(forms.ModelForm):
# class Meta:
# def clean_title(self):
# def clean_desc(self):
# def clean_tags_field(self):
# def clean_desc(self):
# def clean_title(self):
# def clean_tags_field(self):
# def clean_data(self):
# def clean_proposal(self):
# def ChoiceForm(choices, data=None, label="choice"):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def clean_tags_field(self):
# def AddTaskForm(task_choices, is_plain=False):
# def AssignPyntForm(choices, instance=None):
# def RemoveUserForm(choices, instance=None):
#
# Path: pytask/taskapp/models.py
# TASK_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("Locked", "Locked"),
# ("Working", "Working"),
# ("Closed", "Closed"),
# ("Deleted", "Deleted"),
# ("Completed", "Completed"))
# TB_STATUS_CHOICES = (
# ("Unpublished", "Unpublished"),
# ("Open", "Open"),
# ("All tasks have users selected", "All tasks have users selected"),
# ("Completed", "Completed"))
# UPLOADS_DIR = "/pytask/static/uploads"
# class Task(models.Model):
# class TaskComment(models.Model):
# class TaskClaim(models.Model):
# class WorkReport(models.Model):
# class ReportComment(models.Model):
# class PyntRequest(models.Model):
# class TextBook(models.Model):
# def __unicode__(self):
# def __unicode__(self):
# def __unicode__(self):
. Output only the next line. | task = taskapp_models.Task(**data) |
Here is a snippet: <|code_start|># PyTask 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyTask. If not, see <http://www.gnu.org/licenses/>.
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
]
def get_notification(nid, user):
""" if notification exists, and belongs to the current user, return it.
else return None.
"""
user_notifications = user.notification_sent_to.filter(is_deleted=False).order_by('sent_date')
current_notifications = user_notifications.filter(pk=nid)
if user_notifications:
current_notification = current_notifications[0]
try:
newer_notification = current_notification.get_next_by_sent_date(sent_to=user, is_deleted=False)
newest_notification = user_notifications.reverse()[0]
if newest_notification == newer_notification:
newest_notification = None
<|code_end|>
. Write the next line using the current file imports:
from django import shortcuts
from django.http import Http404
from django.contrib.auth.models import User
from pytask.profile.models import Notification
and context from other files:
# Path: pytask/profile/models.py
# class Notification(models.Model):
# """ A model to hold notifications.
# All these are sent by the site to users.
# Hence there is no sent_from option.
# """
#
# sent_to = models.ForeignKey(User,
# related_name = "%(class)s_sent_to",
# blank = False)
#
# subject = models.CharField(max_length=100, blank=True)
#
# message = models.TextField()
#
# sent_date = models.DateTimeField()
#
# is_read = models.BooleanField(default = False)
#
# is_deleted = models.BooleanField(default = False)
, which may include functions, classes, or code. Output only the next line. | except Notification.DoesNotExist: |
Given the code snippet: <|code_start|>
def show_msg(user, message, redirect_url=None, url_desc=None):
""" simply redirect to homepage """
context = {
'user': user,
'message': message,
'redirect_url': redirect_url,
'url_desc': url_desc
}
return render_to_response('show_msg.html', context)
def home_page(request):
""" get the user and display info about the project if not logged in.
if logged in, display info of their tasks.
"""
user = request.user
if not user.is_authenticated():
return render_to_response("index.html", RequestContext(request, {}))
profile = user.get_profile()
claimed_tasks = user.claimed_tasks.all()
selected_tasks = user.selected_tasks.all()
reviewing_tasks = user.reviewing_tasks.all()
unpublished_tasks = user.created_tasks.filter(status="UP").all()
<|code_end|>
, generate the next line using the imports in this file:
from django.shortcuts import render_to_response
from django.template import RequestContext
from pytask.profile import models as profile_models
and context (functions, classes, or occasionally code) from other files:
# Path: pytask/profile/models.py
# GENDER_CHOICES = (
# ('Male', 'Male'),
# ('Female', 'Female'),
# )
# ROLES_CHOICES = (
# ("Administrator", "Administrator"),
# ("Coordinator", "Coordinator"),
# ("Mentor", "Mentor"),
# ("Contributor", "Contributor"),
# )
# ROLE_CHOICES = (
# ("Administrator", "Request sent by Administrator \
# to a user at lower level, asking him to act as a administrator"),
# ("Coordinator", "Request sent by Coordinator \
# to a user at lower level, asking him to act as a coordinator"),
# )
# class Profile(models.Model):
# class Notification(models.Model):
# class RoleRequest(models.Model):
# def __unicode__(self):
. Output only the next line. | can_create_task = True if profile.role != profile_models.ROLES_CHOICES[3][0] else False |
Given the following code snippet before the placeholder: <|code_start|> if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
params.append(init_params(options))
# load model parameters and set theano shared variables
tparams = []
for i in xrange(len(params)):
params[i] = load_params(models[i], params[i])
tparams.append(init_tparams(params[i]))
# word index
use_noise = theano.shared(numpy.float32(0.))
f_inits = []
f_nexts = []
for i in xrange(len(tparams)):
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context including class names, function names, and sometimes code from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | f_init, f_next = build_sampler(tparams[i], options, trng, use_noise) |
Predict the next line for this snippet: <|code_start|> next_state_chars[i] = numpy.array(hyp_states_char)
next_state_words[i] = numpy.array(hyp_states_word)
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
<|code_end|>
with the help of current file imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
, which may contain function names, class names, or code. Output only the next line. | params.append(init_params(options)) |
Given the following code snippet before the placeholder: <|code_start|> if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
params.append(init_params(options))
# load model parameters and set theano shared variables
tparams = []
for i in xrange(len(params)):
params[i] = load_params(models[i], params[i])
tparams.append(init_tparams(params[i]))
# word index
use_noise = theano.shared(numpy.float32(0.))
f_inits = []
f_nexts = []
for i in xrange(len(tparams)):
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context including class names, function names, and sometimes code from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | f_init, f_next = build_sampler(tparams[i], options, trng, use_noise) |
Continue the code snippet: <|code_start|> next_bound_chars[i] = numpy.array(hyp_bounds_char)
next_bound_words[i] = numpy.array(hyp_bounds_word)
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
<|code_end|>
. Use current file imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context (classes, functions, or code) from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | params.append(init_params(options)) |
Using the snippet: <|code_start|> if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
params.append(init_params(options))
# load model parameters and set theano shared variables
tparams = []
for i in xrange(len(params)):
params[i] = load_params(models[i], params[i])
tparams.append(init_tparams(params[i]))
# word index
use_noise = theano.shared(numpy.float32(0.))
f_inits = []
f_nexts = []
for i in xrange(len(tparams)):
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context (class names, function names, or code) available:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | f_init, f_next = build_sampler(tparams[i], options, trng, use_noise) |
Given the code snippet: <|code_start|> next_state_chars[i] = numpy.array(hyp_states_char)
next_state_words[i] = numpy.array(hyp_states_word)
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
<|code_end|>
, generate the next line using the imports in this file:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context (functions, classes, or occasionally code) from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | params.append(init_params(options)) |
Next line prediction: <|code_start|> if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
params.append(init_params(options))
# load model parameters and set theano shared variables
tparams = []
for i in xrange(len(params)):
params[i] = load_params(models[i], params[i])
tparams.append(init_tparams(params[i]))
# word index
use_noise = theano.shared(numpy.float32(0.))
f_inits = []
f_nexts = []
for i in xrange(len(tparams)):
<|code_end|>
. Use current file imports:
(import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams)
and context including class names, function names, or small code snippets from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | f_init, f_next = build_sampler(tparams[i], options, trng, use_noise) |
Next line prediction: <|code_start|> next_state_chars[i] = numpy.array(hyp_states_char)
next_state_words[i] = numpy.array(hyp_states_word)
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
<|code_end|>
. Use current file imports:
(import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams)
and context including class names, function names, or small code snippets from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | params.append(init_params(options)) |
Here is a snippet: <|code_start|> if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
params.append(init_params(options))
# load model parameters and set theano shared variables
tparams = []
for i in xrange(len(params)):
params[i] = load_params(models[i], params[i])
tparams.append(init_tparams(params[i]))
# word index
use_noise = theano.shared(numpy.float32(0.))
f_inits = []
f_nexts = []
for i in xrange(len(tparams)):
<|code_end|>
. Write the next line using the current file imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
, which may include functions, classes, or code. Output only the next line. | f_init, f_next = build_sampler(tparams[i], options, trng, use_noise) |
Using the snippet: <|code_start|> next_bound_chars[i] = numpy.array(hyp_bounds_char)
next_bound_words[i] = numpy.array(hyp_bounds_word)
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
<|code_end|>
, determine the next line of code. You have imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context (class names, function names, or code) available:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | params.append(init_params(options)) |
Based on the snippet: <|code_start|> if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
params.append(init_params(options))
# load model parameters and set theano shared variables
tparams = []
for i in xrange(len(params)):
params[i] = load_params(models[i], params[i])
tparams.append(init_tparams(params[i]))
# word index
use_noise = theano.shared(numpy.float32(0.))
f_inits = []
f_nexts = []
for i in xrange(len(tparams)):
<|code_end|>
, predict the immediate next line with the help of imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context (classes, functions, sometimes code) from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | f_init, f_next = build_sampler(tparams[i], options, trng, use_noise) |
Given the following code snippet before the placeholder: <|code_start|> next_bound_chars[i] = numpy.array(hyp_bounds_char)
next_bound_words[i] = numpy.array(hyp_bounds_word)
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
<|code_end|>
, predict the next line using imports from the current file:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context including class names, function names, and sometimes code from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | params.append(init_params(options)) |
Continue the code snippet: <|code_start|> if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
params.append(init_params(options))
# load model parameters and set theano shared variables
tparams = []
for i in xrange(len(params)):
params[i] = load_params(models[i], params[i])
tparams.append(init_tparams(params[i]))
# word index
use_noise = theano.shared(numpy.float32(0.))
f_inits = []
f_nexts = []
for i in xrange(len(tparams)):
<|code_end|>
. Use current file imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and context (classes, functions, or code) from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | f_init, f_next = build_sampler(tparams[i], options, trng, use_noise) |
Predict the next line after this snippet: <|code_start|> next_bound_chars[i] = numpy.array(hyp_bounds_char)
next_bound_words[i] = numpy.array(hyp_bounds_word)
hyp_scores = numpy.array(hyp_scores)
live_k = new_live_k
if new_live_k < 1:
break
if dead_k >= k:
break
next_w = numpy.array([w[-1] for w in hyp_samples])
if not stochastic:
# dump every remaining one
if live_k > 0:
for idx in xrange(live_k):
sample.append(hyp_samples[idx])
sample_score.append(hyp_scores[idx])
return sample, sample_score
def translate_model(queue, rqueue, pid, models, options, k, normalize):
trng = RandomStreams(1234)
# allocate model parameters
params = []
for i in xrange(len(models)):
<|code_end|>
using the current file's imports:
import argparse
import numpy
import cPickle as pkl
from nmt import (build_sampler, init_params)
from mixer import *
from multiprocessing import Process, Queue
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
and any relevant context from other files:
# Path: nmt.py
# def prepare_data(seqs_x, seqs_y, maxlen=None, maxlen_trg=None,
# n_words_src=30000, n_words=30000):
# def pred_probs(f_log_probs, prepare_data, options, iterator, verbose=True, verboseFreq=None):
# def train(
# dim_word=100,
# dim_word_src=200,
# enc_dim=1000,
# dec_dim=1000, # the number of LSTM units
# patience=-1, # early stopping patience
# max_epochs=5000,
# finish_after=-1, # finish after this many updates
# decay_c=0., # L2 regularization penalty
# alpha_c=0., # alignment regularization
# clip_c=-1., # gradient clipping threshold
# lrate=0.01, # learning rate
# n_words_src=100000, # source vocabulary size
# n_words=100000, # target vocabulary size
# maxlen=100, # maximum length of the description
# maxlen_trg=None, # maximum length of the description
# maxlen_sample=1000,
# optimizer='rmsprop',
# batch_size=16,
# valid_batch_size=16,
# sort_size=20,
# save_path=None,
# save_file_name='model',
# save_best_models=0,
# dispFreq=100,
# validFreq=100,
# saveFreq=1000, # save the parameters after every saveFreq updates
# sampleFreq=-1,
# verboseFreq=10000,
# datasets=[
# 'data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok'],
# valid_datasets=['../data/dev/newstest2011.en.tok',
# '../data/dev/newstest2011.fr.tok'],
# dictionaries=[
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.en.tok.pkl',
# '/data/lisatmp3/chokyun/europarl/europarl-v7.fr-en.fr.tok.pkl'],
# source_word_level=0,
# target_word_level=0,
# use_dropout=False,
# re_load=False,
# re_load_old_setting=False,
# uidx=None,
# eidx=None,
# cidx=None,
# layers=None,
# save_every_saveFreq=0,
# save_burn_in=20000,
# use_bpe=0,
# init_params=None,
# build_model=None,
# build_sampler=None,
# gen_sample=None,
# **kwargs
# ):
. Output only the next line. | params.append(init_params(options)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.