Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|> if axis != -1: raise NotImplementedError( 'Only last axis supported for now. Please send a feature request.') # Normalize to array (to support broadcasting). # If inputs are static arguments (not `tf.Tensor`), use numpy arrays for # optimization (factors statically computed). from_ = tuple(_to_array(v) for v in from_) to = tuple(_to_array(v) for v in to) # `a` can be scalar or array of shape=(x.shape[-1],), same for `b` a, b = _linear_interp_factors(*from_, *to) return a * x + b def _linear_interp_factors( old_min: _MinMaxValue, old_max: _MinMaxValue, new_min: _MinMaxValue, new_max: _MinMaxValue, ) -> Tuple[Union[float, np.ndarray], Union[float, np.ndarray]]: """Resolve the `y = a * x + b` equation and returns the factors.""" a = (new_min - new_max) / (old_min - old_max) b = (old_min * new_max - new_min * old_max) / (old_min - old_max) return a, b def random_choice( a: Union[int, TensorLike], *, <|code_end|> , predict the immediate next line with the help of imports: import functools import operator import numpy as np import tensorflow as tf from typing import Sequence, Tuple, Union from sunds.typing import Shape, Tensor, TensorLike # pylint: disable=g-multiple-import and context (classes, functions, sometimes code) from other files: # Path: sunds/typing.py . Output only the next line.
size: Union[None, int, Shape] = None,
Given snippet: <|code_start|> raise ValueError(f'interp input should be float32. Got: {x.dtype}') if axis != -1: raise NotImplementedError( 'Only last axis supported for now. Please send a feature request.') # Normalize to array (to support broadcasting). # If inputs are static arguments (not `tf.Tensor`), use numpy arrays for # optimization (factors statically computed). from_ = tuple(_to_array(v) for v in from_) to = tuple(_to_array(v) for v in to) # `a` can be scalar or array of shape=(x.shape[-1],), same for `b` a, b = _linear_interp_factors(*from_, *to) return a * x + b def _linear_interp_factors( old_min: _MinMaxValue, old_max: _MinMaxValue, new_min: _MinMaxValue, new_max: _MinMaxValue, ) -> Tuple[Union[float, np.ndarray], Union[float, np.ndarray]]: """Resolve the `y = a * x + b` equation and returns the factors.""" a = (new_min - new_max) / (old_min - old_max) b = (old_min * new_max - new_min * old_max) / (old_min - old_max) return a, b def random_choice( <|code_end|> , continue by predicting the next line. Consider current file imports: import functools import operator import numpy as np import tensorflow as tf from typing import Sequence, Tuple, Union from sunds.typing import Shape, Tensor, TensorLike # pylint: disable=g-multiple-import and context: # Path: sunds/typing.py which might include code, classes, or functions. Output only the next line.
a: Union[int, TensorLike],
Here is a snippet: <|code_start|> Args: split: The dataset split to load (e.g. 'train', 'train[80%:]',...) decoders: Optional decoders (e.g. to skip the image decoding) pipeline_kwargs: Additional kwargs to forward to the pipeline function. **kwargs: Kwargs to forward to `tfds.core.DatasetBuilder.as_dataset`. Returns: ds: The dataset """ # Scene understanding datasets have many features. Only a very small subset # are required for a specific task. frame_specs = self.frame_specs if callable(frame_specs): raise ValueError( f'Invalid frame_specs={frame_specs!r}. Did you forgot `@property` ?') if frame_specs is not None: decoders = tfds.decode.PartialDecoding(frame_specs, decoders=decoders) ds = self.frame_builder.as_dataset( split=split, decoders=decoders, **kwargs, ) # Apply eventual post-processing on the dataset. return self.pipeline(ds, **(pipeline_kwargs or {})) @property @abc.abstractmethod <|code_end|> . Write the next line using the current file imports: import abc import copy import tensorflow as tf import tensorflow_datasets as tfds from typing import Any, Dict, Optional from sunds.typing import FeatureSpecsHint, Split, Tree, TreeDict # pylint: disable=g-multiple-import and context from other files: # Path: sunds/typing.py , which may include functions, classes, or code. Output only the next line.
def frame_specs(self) -> Optional[FeatureSpecsHint]:
Based on the snippet: <|code_start|>class FrameTask(Task): """Frame task. Frame task allow to easily create pipelines based on the frame dataset. It requires to define: * `frame_specs`: Which subset of the feature specs to read. * `pipeline`: Which pre-processing to apply to the `tf.data.Dataset` object. ```python ds = sunds.load('nerf_synthetic', split='train', task=sunds.tasks.Nerf()) for ex in ds: ex['rays'] ``` The final pipeline is more or less equivalent to: ```python builder = tfds.builder('nerf_synthetic_frames') ds = builder.as_dataset( decoders=tfds.features.PartialDecoding(task.frame_specs), ) ds = task.pipeline(ds) ``` """ def as_dataset( self, *, <|code_end|> , predict the immediate next line with the help of imports: import abc import copy import tensorflow as tf import tensorflow_datasets as tfds from typing import Any, Dict, Optional from sunds.typing import FeatureSpecsHint, Split, Tree, TreeDict # pylint: disable=g-multiple-import and context (classes, functions, sometimes code) from other files: # Path: sunds/typing.py . Output only the next line.
split: Tree[Split],
Using the snippet: <|code_start|>class FrameTask(Task): """Frame task. Frame task allow to easily create pipelines based on the frame dataset. It requires to define: * `frame_specs`: Which subset of the feature specs to read. * `pipeline`: Which pre-processing to apply to the `tf.data.Dataset` object. ```python ds = sunds.load('nerf_synthetic', split='train', task=sunds.tasks.Nerf()) for ex in ds: ex['rays'] ``` The final pipeline is more or less equivalent to: ```python builder = tfds.builder('nerf_synthetic_frames') ds = builder.as_dataset( decoders=tfds.features.PartialDecoding(task.frame_specs), ) ds = task.pipeline(ds) ``` """ def as_dataset( self, *, <|code_end|> , determine the next line of code. You have imports: import abc import copy import tensorflow as tf import tensorflow_datasets as tfds from typing import Any, Dict, Optional from sunds.typing import FeatureSpecsHint, Split, Tree, TreeDict # pylint: disable=g-multiple-import and context (class names, function names, or code) available: # Path: sunds/typing.py . Output only the next line.
split: Tree[Split],
Given snippet: <|code_start|> """Frame task. Frame task allow to easily create pipelines based on the frame dataset. It requires to define: * `frame_specs`: Which subset of the feature specs to read. * `pipeline`: Which pre-processing to apply to the `tf.data.Dataset` object. ```python ds = sunds.load('nerf_synthetic', split='train', task=sunds.tasks.Nerf()) for ex in ds: ex['rays'] ``` The final pipeline is more or less equivalent to: ```python builder = tfds.builder('nerf_synthetic_frames') ds = builder.as_dataset( decoders=tfds.features.PartialDecoding(task.frame_specs), ) ds = task.pipeline(ds) ``` """ def as_dataset( self, *, split: Tree[Split], <|code_end|> , continue by predicting the next line. Consider current file imports: import abc import copy import tensorflow as tf import tensorflow_datasets as tfds from typing import Any, Dict, Optional from sunds.typing import FeatureSpecsHint, Split, Tree, TreeDict # pylint: disable=g-multiple-import and context: # Path: sunds/typing.py which might include code, classes, or functions. Output only the next line.
decoders: Optional[TreeDict[tfds.decode.Decoder]] = None,
Predict the next line for this snippet: <|code_start|>class _Param(NamedTuple): """`pytest.mark.parametrize` single param.""" value: Any default: Any expected: Any @pytest.mark.parametrize( 'value, default, expected', [ _Param(False, tfds.features.Image(), {}), _Param( value=True, # True: use default default=tfds.features.Image(), expected={'a': tfds.features.Image()}, ), _Param( value=True, default=tf.int32, # Also works with dtype expected={ 'a': tf.int32, }, ), _Param( value=tfds.features.Text(), # Feature give, use it default=tfds.features.Image(), expected={'a': tfds.features.Text()}, ), _Param( value=['cat', 'dog'], # Label to use <|code_end|> with the help of current file imports: from typing import Any, NamedTuple from sunds.core import spec_dict import pytest import tensorflow as tf import tensorflow_datasets as tfds and context from other files: # Path: sunds/core/spec_dict.py # class SpecDict(dict): # def maybe_set( # self, # key: str, # value: Union[FeaturesOrBool, Any], # default: Union[FeaturesOrBool, _Factory] = False, # ) -> None: # def maybe_update( # self, # other: FeaturesOrBool, # default: FeaturesOrBool = False, # ) -> None: # def labeled_image( # labels: LabelArg, # **kwargs: Any, # ) -> tfds.features.LabeledImage: # def _is_features(features: FeatureSpecs) -> bool: , which may contain function names, class names, or code. Output only the next line.
default=spec_dict.labeled_image(shape=(28, 28, 1)),
Next line prediction: <|code_start|> tf.constant([ [0., -2., -2], [2., 2., 2.], [8., -2., 4.], [8., -2., 4.], ]), 'ray_directions': tf.constant([ [0., 0., 23.], [1., 1., 0.], [3., 3., 0.], [0., 0., 0.], ]), } scene_ex = [ { 'scene_name': 'scene_00', 'scene_box': { 'min_corner': np.array([-20, -20, -20], dtype=np.float32), 'max_corner': np.array([20, 20, 20], dtype=np.float32), }, }, { 'scene_name': 'scene_01', 'scene_box': { 'min_corner': np.array([0, -2, -2], dtype=np.float32), 'max_corner': np.array([8, 2, 6], dtype=np.float32), }, }, ] <|code_end|> . Use current file imports: (import contextlib import numpy as np import pytest import sunds import tensorflow as tf import tensorflow_datasets as tfds from sunds.tasks import boundaries_utils from sunds.typing import FeatureSpecsHint) and context including class names, function names, or small code snippets from other files: # Path: sunds/tasks/boundaries_utils.py # class MultiSceneBoundaries: # def __init__(self, scene_boundaries: List[ArrayDict]): # def get_corners(self, scene_name: TensorLike) -> Tuple[tf.Tensor, tf.Tensor]: # # Path: sunds/typing.py . Output only the next line.
scene_boundaries = boundaries_utils.MultiSceneBoundaries(scene_ex)
Using the snippet: <|code_start|> split='train', task=sunds.tasks.Nerf( additional_frame_specs={'timestamp', 'pose'}, additional_camera_specs={'intrinsics'}, yield_mode=yield_mode, ), ) assert 'timestamp' in ds.element_spec assert 'pose' in ds.element_spec if yield_mode == 'dict': assert 'intrinsics' in ds.element_spec['cameras']['default_camera'] else: assert 'intrinsics' in ds.element_spec assert len(ds) # pylint: disable=g-explicit-length-test list(ds) # Pipeline can be executed @pytest.mark.parametrize( 'normalize_rays', [False, True], ids=['nonorm', 'norm']) @pytest.mark.parametrize( 'yield_mode', ['ray', 'image', 'stacked', 'dict'], ) @pytest.mark.parametrize('additional_frame_specs', [{}, {'timestamp'}]) @pytest.mark.parametrize( 'remove_invalid_rays', [False, True], ids=['keep', 'remove']) def test_all_flags( lego_builder: sunds.core.DatasetBuilder, normalize_rays: bool, yield_mode: str, <|code_end|> , determine the next line of code. You have imports: import contextlib import numpy as np import pytest import sunds import tensorflow as tf import tensorflow_datasets as tfds from sunds.tasks import boundaries_utils from sunds.typing import FeatureSpecsHint and context (class names, function names, or code) available: # Path: sunds/tasks/boundaries_utils.py # class MultiSceneBoundaries: # def __init__(self, scene_boundaries: List[ArrayDict]): # def get_corners(self, scene_name: TensorLike) -> Tuple[tf.Tensor, tf.Tensor]: # # Path: sunds/typing.py . Output only the next line.
additional_frame_specs: FeatureSpecsHint,
Based on the snippet: <|code_start|># Copyright 2022 The sunds Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Geometry functions related to 3D rays.""" TensorLike = tf.types.experimental.TensorLike TensorDict = Dict[str, tf.Tensor] def rays_from_image_points(camera: cameras.CameraType, <|code_end|> , predict the immediate next line with the help of imports: from typing import Dict from sunds.core.tf_geometry import cameras from sunds.core.tf_geometry import isometry import tensorflow as tf and context (classes, functions, sometimes code) from other files: # Path: sunds/core/tf_geometry/cameras.py # class AbstractCamera(abc.ABC): # class PinholeCamera(AbstractCamera): # def project(self, points: TensorLike) -> tf.Tensor: # def unproject(self, # points: Optional[TensorLike] = None, # to_rays: bool = True) -> tf.Tensor: # def pixel_centers(self) -> tf.Tensor: # def __post_init__(self): # def from_fov( # cls, # *, # image_width: int, # image_height: int, # horizontal_fov_in_degrees: float, # vertical_fov_in_degrees: Optional[float] = None) -> 'PinholeCamera': # def focal_length_from_fov(image_size, fov_in_degrees): # def from_intrinsics( # cls, # *, # image_size_in_pixels: Tuple[int, int], # focal_length_in_pixels: Tuple[float, float], # principal_point_in_pixels: Optional[Tuple[float, float]] = None, # skew: float = 0.0, # ) -> 'PinholeCamera': # def project(self, points: TensorLike) -> tf.Tensor: # def unproject(self, # points: Optional[TensorLike] = None, # to_rays: bool = True) -> tf.Tensor: # def pixel_centers(self) -> tf.Tensor: # K: TensorLike # pylint: disable=invalid-name # # Path: sunds/core/tf_geometry/isometry.py # class Isometry: # R: TensorLike # pylint: disable=invalid-name # def __post_init__(self): # def from_matrix(cls, matrix: TensorLike) -> 'Isometry': # def matrix3x4(self) -> tf.Tensor: # def matrix4x4(self) -> tf.Tensor: # def inverse(self) -> 'Isometry': # def compose(self, other: 'Isometry') -> 'Isometry': # def transform_points(self, points: TensorLike) -> tf.Tensor: # def __mul__( # self, other: Union['Isometry', # TensorLike]) -> Union['Isometry', tf.Tensor]: . Output only the next line.
world_from_camera: isometry.Isometry,
Here is a snippet: <|code_start|> class MultiSceneBoundaries: """Lookup table across scene boundaries.""" def __init__(self, scene_boundaries: List[ArrayDict]): """Constructor. Args: scene_boundaries: List of scene examples (as numpy arrays). """ # Create the scene_name -> index id mapping scene_name2id = { ex['scene_name']: i for i, ex in enumerate(scene_boundaries) } self._table = tf.lookup.StaticHashTable( tf.lookup.KeyValueTensorInitializer( list(scene_name2id.keys()), list(scene_name2id.values()), ), # Ideally, it would be best if `StaticHashTable` supported not # having a default value, and raised a KeyError instead. default_value=-1, ) # Stack all scenes values together corners = [ex['scene_box'] for ex in scene_boundaries] corners = tf.nest.map_structure(lambda *x: tf.stack(x), *corners) self._corners = corners <|code_end|> . Write the next line using the current file imports: from typing import List, Tuple from sunds.typing import ArrayDict, TensorLike # pylint: disable=g-multiple-import import tensorflow as tf and context from other files: # Path: sunds/typing.py , which may include functions, classes, or code. Output only the next line.
def get_corners(self, scene_name: TensorLike) -> Tuple[tf.Tensor, tf.Tensor]:
Predict the next line for this snippet: <|code_start|># Copyright 2022 The sunds Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test of the scene boundaries.""" def test_scene_boundaries(lego_builder: sunds.core.DatasetBuilder): ds = lego_builder.scene_builder.as_dataset(split='train') scene_boundaries_values = list(tfds.as_numpy(ds)) <|code_end|> with the help of current file imports: import numpy as np import sunds import tensorflow_datasets as tfds from sunds.tasks import boundaries_utils and context from other files: # Path: sunds/tasks/boundaries_utils.py # class MultiSceneBoundaries: # def __init__(self, scene_boundaries: List[ArrayDict]): # def get_corners(self, scene_name: TensorLike) -> Tuple[tf.Tensor, tf.Tensor]: , which may contain function names, class names, or code. Output only the next line.
scene_boundaries = boundaries_utils.MultiSceneBoundaries(
Predict the next line after this snippet: <|code_start|># Copyright 2022 The sunds Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data specification of features of scene understanding datasets.""" def scene_spec( frames: FeatureSpecs, # pylint: disable=redefined-outer-name *, point_cloud: FeaturesOrBool = False, ) -> FeatureSpecs: """Scene spec definitions.""" frames = dict(frames) frames.pop('scene_name') # Clear the scene field <|code_end|> using the current file's imports: from typing import Tuple from sunds.core import spec_dict from sunds.typing import Dim, FeatureSpecs, FeaturesOrBool, LabelOrFeaturesOrBool # pylint: disable=g-multiple-import import tensorflow as tf import tensorflow_datasets as tfds and any relevant context from other files: # Path: sunds/core/spec_dict.py # class SpecDict(dict): # def maybe_set( # self, # key: str, # value: Union[FeaturesOrBool, Any], # default: Union[FeaturesOrBool, _Factory] = False, # ) -> None: # def maybe_update( # self, # other: FeaturesOrBool, # default: FeaturesOrBool = False, # ) -> None: # def labeled_image( # labels: LabelArg, # **kwargs: Any, # ) -> tfds.features.LabeledImage: # def _is_features(features: FeatureSpecs) -> bool: # # Path: sunds/typing.py . Output only the next line.
specs = spec_dict.SpecDict({
Next line prediction: <|code_start|> cameras: A dict[camera_name, sunds.specs.camera_spec()] Returns: A composite `tfds` feature defining the specification of `frame` data. """ return { # A unique name 🔑 that identifies the sequence the frame is from. 'scene_name': tfds.features.Text(), # A unique name 🔑 that identifies this particular frame. 'frame_name': tfds.features.Text(), # Frame pose w.r.t scene: X_{scene} = R * X_{frame} + t. 'pose': pose_spec(), # Frame timestamp ⏰. This is expected to be the timestamp when frame # `pose` was recorded. We expect this timestamp to be relative to the # nominal timestamp of the scene this frame belongs to. 'timestamp': tf.float32, # Camera sensor data. Each frame can have multiple cameras (e.g. stereo # setups, autonomous cars with multiple cameras). See `camera_spec` for # more details about the contents of each camera. 'cameras': cameras, } def camera_spec( *, color_image: FeaturesOrBool = False, category_image: LabelOrFeaturesOrBool = False, instance_image: LabelOrFeaturesOrBool = False, depth_image: FeaturesOrBool = False, camera_rays: FeaturesOrBool = False, <|code_end|> . Use current file imports: (from typing import Tuple from sunds.core import spec_dict from sunds.typing import Dim, FeatureSpecs, FeaturesOrBool, LabelOrFeaturesOrBool # pylint: disable=g-multiple-import import tensorflow as tf import tensorflow_datasets as tfds) and context including class names, function names, or small code snippets from other files: # Path: sunds/core/spec_dict.py # class SpecDict(dict): # def maybe_set( # self, # key: str, # value: Union[FeaturesOrBool, Any], # default: Union[FeaturesOrBool, _Factory] = False, # ) -> None: # def maybe_update( # self, # other: FeaturesOrBool, # default: FeaturesOrBool = False, # ) -> None: # def labeled_image( # labels: LabelArg, # **kwargs: Any, # ) -> tfds.features.LabeledImage: # def _is_features(features: FeatureSpecs) -> bool: # # Path: sunds/typing.py . Output only the next line.
img_shape: Tuple[Dim, Dim] = (None, None),
Predict the next line for this snippet: <|code_start|># Copyright 2022 The sunds Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data specification of features of scene understanding datasets.""" def scene_spec( frames: FeatureSpecs, # pylint: disable=redefined-outer-name *, <|code_end|> with the help of current file imports: from typing import Tuple from sunds.core import spec_dict from sunds.typing import Dim, FeatureSpecs, FeaturesOrBool, LabelOrFeaturesOrBool # pylint: disable=g-multiple-import import tensorflow as tf import tensorflow_datasets as tfds and context from other files: # Path: sunds/core/spec_dict.py # class SpecDict(dict): # def maybe_set( # self, # key: str, # value: Union[FeaturesOrBool, Any], # default: Union[FeaturesOrBool, _Factory] = False, # ) -> None: # def maybe_update( # self, # other: FeaturesOrBool, # default: FeaturesOrBool = False, # ) -> None: # def labeled_image( # labels: LabelArg, # **kwargs: Any, # ) -> tfds.features.LabeledImage: # def _is_features(features: FeatureSpecs) -> bool: # # Path: sunds/typing.py , which may contain function names, class names, or code. Output only the next line.
point_cloud: FeaturesOrBool = False,
Using the snippet: <|code_start|> See `frame_info_spec()` for a lightweight version (without sensor data) of `frame` which is used to store information about all frames in a scene. Args: cameras: A dict[camera_name, sunds.specs.camera_spec()] Returns: A composite `tfds` feature defining the specification of `frame` data. """ return { # A unique name 🔑 that identifies the sequence the frame is from. 'scene_name': tfds.features.Text(), # A unique name 🔑 that identifies this particular frame. 'frame_name': tfds.features.Text(), # Frame pose w.r.t scene: X_{scene} = R * X_{frame} + t. 'pose': pose_spec(), # Frame timestamp ⏰. This is expected to be the timestamp when frame # `pose` was recorded. We expect this timestamp to be relative to the # nominal timestamp of the scene this frame belongs to. 'timestamp': tf.float32, # Camera sensor data. Each frame can have multiple cameras (e.g. stereo # setups, autonomous cars with multiple cameras). See `camera_spec` for # more details about the contents of each camera. 'cameras': cameras, } def camera_spec( *, color_image: FeaturesOrBool = False, <|code_end|> , determine the next line of code. You have imports: from typing import Tuple from sunds.core import spec_dict from sunds.typing import Dim, FeatureSpecs, FeaturesOrBool, LabelOrFeaturesOrBool # pylint: disable=g-multiple-import import tensorflow as tf import tensorflow_datasets as tfds and context (class names, function names, or code) available: # Path: sunds/core/spec_dict.py # class SpecDict(dict): # def maybe_set( # self, # key: str, # value: Union[FeaturesOrBool, Any], # default: Union[FeaturesOrBool, _Factory] = False, # ) -> None: # def maybe_update( # self, # other: FeaturesOrBool, # default: FeaturesOrBool = False, # ) -> None: # def labeled_image( # labels: LabelArg, # **kwargs: Any, # ) -> tfds.features.LabeledImage: # def _is_features(features: FeatureSpecs) -> bool: # # Path: sunds/typing.py . Output only the next line.
category_image: LabelOrFeaturesOrBool = False,
Given the code snippet: <|code_start|> def test_fit_success(): # causal direction: x0 --> x1 --> x3 x0 = np.random.uniform(size=1000) x1 = 2.0 * x0 + np.random.uniform(size=1000) x2 = np.random.uniform(size=1000) x3 = 4.0 * x1 + np.random.uniform(size=1000) X = pd.DataFrame(np.array([x0, x1, x2, x3]).T, columns=['x0', 'x1', 'x2', 'x3']) <|code_end|> , generate the next line using the imports in this file: import numpy as np import pandas as pd from lingam.ica_lingam import ICALiNGAM and context (functions, classes, or occasionally code) from other files: # Path: lingam/ica_lingam.py # class ICALiNGAM(_BaseLiNGAM): # """Implementation of ICA-based LiNGAM Algorithm [1]_ # # References # ---------- # .. [1] S. Shimizu, P. O. Hoyer, A. Hyvärinen, and A. J. Kerminen. # A linear non-gaussian acyclic model for causal discovery. # Journal of Machine Learning Research, 7:2003-2030, 2006. # """ # # def __init__(self, random_state=None, max_iter=1000): # """Construct a ICA-based LiNGAM model. # # Parameters # ---------- # random_state : int, optional (default=None) # ``random_state`` is the seed used by the random number generator. # max_iter : int, optional (default=1000) # The maximum number of iterations of FastICA. # """ # super().__init__(random_state) # self._max_iter = max_iter # # def fit(self, X): # """Fit the model to X. # # Parameters # ---------- # X : array-like, shape (n_samples, n_features) # Training data, where ``n_samples`` is the number of samples # and ``n_features`` is the number of features. # # Returns # ------- # self : object # Returns the instance of self. # """ # X = check_array(X) # # # obtain a unmixing matrix from the given data # ica = FastICA(max_iter=self._max_iter, random_state=self._random_state) # ica.fit(X) # W_ica = ica.components_ # # # obtain a permuted W_ica # _, col_index = linear_sum_assignment(1 / np.abs(W_ica)) # PW_ica = np.zeros_like(W_ica) # PW_ica[col_index] = W_ica # # # obtain a vector to scale # D = np.diag(PW_ica)[:, np.newaxis] # # # estimate an adjacency matrix # W_estimate = PW_ica / D # B_estimate = np.eye(len(W_estimate)) - W_estimate # # causal_order = self._estimate_causal_order(B_estimate) # self._causal_order = causal_order # # return self._estimate_adjacency_matrix(X) # # def _search_causal_order(self, matrix): # """Obtain a causal order from the given matrix strictly. # # Parameters # ---------- # matrix : array-like, shape (n_features, n_samples) # Target matrix. # # Return # ------ # causal_order : array, shape [n_features, ] # A causal order of the given matrix on success, None otherwise. # """ # causal_order = [] # # row_num = matrix.shape[0] # original_index = np.arange(row_num) # # while 0 < len(matrix): # # find a row all of which elements are zero # row_index_list = np.where(np.sum(np.abs(matrix), axis=1) == 0)[0] # if len(row_index_list) == 0: # break # # target_index = row_index_list[0] # # # append i to the end of the list # causal_order.append(original_index[target_index]) # original_index = np.delete(original_index, target_index, axis=0) # # # remove the i-th row and the i-th column from matrix # mask = np.delete(np.arange(len(matrix)), target_index, axis=0) # matrix = matrix[mask][:, mask] # # if len(causal_order) != row_num: # causal_order = None # # return causal_order # # def _estimate_causal_order(self, matrix): # """Obtain a lower triangular from the given matrix approximately. # # Parameters # ---------- # matrix : array-like, shape (n_features, n_samples) # Target matrix. # # Return # ------ # causal_order : array, shape [n_features, ] # A causal order of the given matrix on success, None otherwise. # """ # causal_order = None # # # set the m(m + 1)/2 smallest(in absolute value) elements of the matrix to zero # pos_list = np.argsort(np.abs(matrix), axis=None) # pos_list = np.vstack(np.unravel_index(pos_list, matrix.shape)).T # initial_zero_num = int(matrix.shape[0] * (matrix.shape[0] + 1) / 2) # for i, j in pos_list[:initial_zero_num]: # matrix[i, j] = 0 # # for i, j in pos_list[initial_zero_num:]: # # set the smallest(in absolute value) element to zero # matrix[i, j] = 0 # # causal_order = self._search_causal_order(matrix) # if causal_order is not None: # break # # return causal_order . Output only the next line.
model = ICALiNGAM()
Based on the snippet: <|code_start|>with open('requirements.txt') as f: requirements = f.readlines() requirements = [i.replace('\n', '') for i in requirements] setup( name='Hashmal', version = '0.1.0a', description='Bitcoin transaction script IDE.', url='https://github.com/mazaclub/hashmal', install_requires = requirements, author='Tyler Willis, mazaclub', author_email='kefkius@maza.club', keywords=[ 'bitcoin', 'transaction', 'script', 'ide' ], classifiers=[ 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Topic :: Software Development :: Interpreters' ], scripts=['hashmal'], packages=[ 'hashmal_lib', 'hashmal_lib.core', 'hashmal_lib.plugins', 'hashmal_lib.widgets' ], <|code_end|> , predict the immediate next line with the help of imports: from setuptools import setup from hashmal_lib.gui_utils import hashmal_entry_points and context (classes, functions, sometimes code) from other files: # Path: hashmal_lib/gui_utils.py # def HBox(*widgets): # def floated_buttons(btns, left=False): # def add_shortcuts(items): # def __init__(self, parent=None): # def sizeHint(self): # def __init__(self, satoshis=0): # def known_formats(): # def get_str(self): # def __init__(self, parent=None): # def satoshis(self): # def satoshis(self, value): # def get_satoshis(self): # def set_satoshis(self, amount): # def check_text(self): # def update_format(self): # def on_option_changed(self, key): # def __init__(self, max_value=0xffffffff, parent=None): # def amount(self): # def amount(self, value): # def get_amount(self): # def set_amount(self, amount): # def check_text(self): # def __init__( self, *args ): # def isReadOnly( self ): # def mousePressEvent( self, event ): # def mouseMoveEvent( self, event ): # def mouseReleaseEvent( self, event ): # def keyPressEvent( self, event ): # def setReadOnly( self, state ): # class Separator(QFrame): # class Amount(object): # class OutputAmountEdit(QLineEdit): # class AmountEdit(QLineEdit): # class ReadOnlyCheckBox(QtGui.QCheckBox): . Output only the next line.
entry_points = hashmal_entry_points,
Given the following code snippet before the placeholder: <|code_start|>known_script_formats = ['Human', 'Hex'] class HashmalMain(QMainWindow): # Signals # Emitted when the list of user's layouts changes. layoutsChanged = QtCore.pyqtSignal() def __init__(self, app): super(HashmalMain, self).__init__() self.app = app self.app.setStyleSheet(hashmal_style()) self.changes_saved = True # {Qt.DockWidgetArea: [dock0, dock1, ...], ...} self.dock_orders = defaultdict(list) self.setCorner(QtCore.Qt.BottomRightCorner, QtCore.Qt.RightDockWidgetArea) self.config = Config() self.init_logger() self.config.optionChanged.connect(self.on_option_changed) QtCore.QCoreApplication.setOrganizationName('mazaclub') QtCore.QCoreApplication.setApplicationName('hashmal') self.qt_settings = QtCore.QSettings() active_params = self.config.get_option('chainparams', 'Bitcoin') # True if chainparams needs to be set after plugins load. needs_params_change = False # An exception is thrown if the last-active chainparams preset # only exists due to a plugin that defines it. try: <|code_end|> , predict the next line using imports from the current file: from collections import defaultdict from PyQt4.QtGui import * from PyQt4 import QtCore from hashmal_lib.core import chainparams from config import Config from plugin_handler import PluginHandler from settings_dialog import SettingsDialog from widgets.script import ScriptEditor from help_widgets import QuickTips from gui_utils import script_file_filter, floated_buttons, monospace_font from plugin_manager import PluginManager from plugins import BaseDock from downloader import DownloadController from style import hashmal_style from toolbar import ToolBar import os import time import logging and context including class names, function names, and sometimes code from other files: # Path: hashmal_lib/core/chainparams.py # class ParamsPreset(object): # def __init__(self, **kwargs): # def raw_signature_hash(cls, script, txTo, inIdx, hashtype): # def signature_hash(cls, script, txTo, inIdx, hashtype): # def add_preset(preset): # def remove_preset(preset): # def get_presets(): # def get_tx_fields(): # def set_tx_fields(fields): # def set_tx_serializer(cls): # def get_block_header_fields(): # def set_block_header_fields(fields): # def get_block_fields(): # def set_block_fields(fields): # def get_opcode_overrides(): # def set_opcode_overrides(ops): # def set_opcodes(op_names, ops_by_name, disabled_ops): # def get_script_engine_class(): # def set_script_engine_class(cls): # def set_to_preset(name): # def signature_hash(script, txTo, inIdx, hashtype): # HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' . Output only the next line.
chainparams.set_to_preset(active_params)
Given the following code snippet before the placeholder: <|code_start|> # Singleton instance hashmal_config = None def set_config(c): global hashmal_config hashmal_config = c def get_config(): return hashmal_config class Config(QtCore.QObject): """Wrapper for core.Config. This exists so that widgets can connect to optionChanged if they require themselves to update with a certain option. """ optionChanged = QtCore.pyqtSignal(str, name='optionChanged') def __init__(self, parent=None): super(Config, self).__init__(parent) <|code_end|> , predict the next line using imports from the current file: from PyQt4.QtGui import * from PyQt4 import QtCore from hashmal_lib.core import my_config and context including class names, function names, and sometimes code from other files: # Path: hashmal_lib/core/my_config.py # def config_file_path(): # def __init__(self): # def load(self, filename=None): # def save(self): # def get_option(self, key, default=None): # def set_option(self, key, value, do_save=True): # def byteify(input): # class Config(object): . Output only the next line.
self.conf = my_config.Config()
Based on the snippet: <|code_start|> def make_plugin(): p = Plugin(ChainParams) p.has_gui = False return p class ChainParamsObject(QtCore.QObject): """This class exists so that a signal can be emitted when chainparams presets change.""" paramsPresetsChanged = QtCore.pyqtSignal() class ChainParams(BasePluginUI): """For augmentation purposes, we use this plugin to help with chainparams presets.""" tool_name = 'Chainparams' description = 'Chainparams allows plugins to add chainparams presets for Hashmal to use.' category = Category.Core def __init__(self, *args): super(ChainParams, self).__init__(*args) self.chainparams_object = ChainParamsObject() self.paramsPresetsChanged = self.chainparams_object.paramsPresetsChanged self.augment('chainparams_presets', None, callback=self.on_chainparams_augmented) def add_params_preset(self, preset): try: <|code_end|> , predict the immediate next line with the help of imports: from PyQt4 import QtCore from hashmal_lib.core import chainparams from base import Plugin, BasePluginUI, Category and context (classes, functions, sometimes code) from other files: # Path: hashmal_lib/core/chainparams.py # class ParamsPreset(object): # def __init__(self, **kwargs): # def raw_signature_hash(cls, script, txTo, inIdx, hashtype): # def signature_hash(cls, script, txTo, inIdx, hashtype): # def add_preset(preset): # def remove_preset(preset): # def get_presets(): # def get_tx_fields(): # def set_tx_fields(fields): # def set_tx_serializer(cls): # def get_block_header_fields(): # def set_block_header_fields(fields): # def get_block_fields(): # def set_block_fields(fields): # def get_opcode_overrides(): # def set_opcode_overrides(ops): # def set_opcodes(op_names, ops_by_name, disabled_ops): # def get_script_engine_class(): # def set_script_engine_class(cls): # def set_to_preset(name): # def signature_hash(script, txTo, inIdx, hashtype): # HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' . Output only the next line.
chainparams.add_preset(preset)
Predict the next line after this snippet: <|code_start|> def on_option_changed(self, key): if key == 'enabled_plugins': new_enabled = self.config.get_option('enabled_plugins', default_plugins) # Update view if necessary. if self.enabled_plugins != new_enabled: self.enabled_plugins = new_enabled self.dataChanged.emit(QModelIndex(), QModelIndex()) elif key == 'favorite_plugins': new_favorites = self.config.get_option('favorite_plugins', []) if self.favorite_plugins != new_favorites: self.favorite_plugins = new_favorites self.dataChanged.emit(QModelIndex(), QModelIndex()) class PluginsProxyModel(QSortFilterProxyModel): def __init__(self, parent=None): super(PluginsProxyModel, self).__init__(parent) self.name_filter = QRegExp() self.hide_core_plugins = True def set_name_filter(self, regexp): self.name_filter = regexp self.invalidateFilter() def set_hide_core_plugins(self, do_hide): self.hide_core_plugins = do_hide self.invalidateFilter() def filterAcceptsRow(self, source_row, source_parent): if self.hide_core_plugins: plugin = self.sourceModel().plugin_for_row(source_row) <|code_end|> using the current file's imports: import __builtin__ from PyQt4.QtGui import * from PyQt4.QtCore import * from hashmal_lib.plugins.base import Category from gui_utils import Separator, required_plugins, default_plugins and any relevant context from other files: # Path: hashmal_lib/plugins/base.py # class Category(object): # """Plugin category. # # Use one of the below class attributes for a dock's category attribute # e.g. 'category = Category.Script'. # """ # Core = PluginCategory('Core', 'Core Hashmal functionality implemented as a plugin.') # General = PluginCategory('General', 'General or uncategorized plugin.') # Block = PluginCategory('Blocks', 'Plugin that involves blocks and/or block headers.') # Data = PluginCategory('Data', 'Plugin that retrieves blockchain data.') # Key = PluginCategory('Keys', 'Plugin that involves keys, addresses, etc.') # Script = PluginCategory('Scripts', 'Plugin that involves scripts.') # Tx = PluginCategory('Transactions', 'Plugin that involves transactions.') # # @classmethod # def categories(cls): # category_list = [] # for i in dir(cls): # attr = getattr(cls, i) # if attr.__class__.__name__ == 'PluginCategory': # category_list.append(attr) # return category_list . Output only the next line.
if plugin.ui.category == Category.Core:
Next line prediction: <|code_start|> form.addRow(self.create_filters_box()) form.addRow(self.view) # Controls for adding/removing variables self.new_var_key = QLineEdit() self.new_var_key.setPlaceholderText('Key') self.new_var_key.setWhatsThis('Enter the name to give the new variable here.') self.setFocusProxy(self.new_var_key) self.new_var_value = QLineEdit() self.new_var_value.setPlaceholderText('Value') self.new_var_value.setWhatsThis('Enter the value to give the new variable here.') add_var_btn = QPushButton('&Add') add_var_btn.clicked.connect(self.add_new_var) add_var_hbox = HBox(self.new_var_key, QLabel(':'), self.new_var_value, add_var_btn) self.auto_save_check = QCheckBox('Automatically save') self.auto_save_check.setWhatsThis('If this box is checked, then your stored variables will automatically be saved whenever one is added or deleted.') self.auto_save_check.setChecked(self.auto_save) def change_auto_save(is_checked): is_checked = True if is_checked else False self.auto_save = is_checked self.set_option('auto_save', self.auto_save) self.auto_save_check.stateChanged.connect(change_auto_save) self.save_button = QPushButton('Save') self.save_button.clicked.connect(self.save_variables) self.save_button.setToolTip('Save variables to config file') self.save_button.setWhatsThis('This button will save your stored variables in the Hashmal config file.') form.addRow('Add:', add_var_hbox) <|code_end|> . Use current file imports: (from collections import OrderedDict, namedtuple from PyQt4.QtGui import * from PyQt4 import QtCore from base import BaseDock, Plugin, augmenter from item_types import ItemAction, item_types from hashmal_lib.gui_utils import floated_buttons, HBox from hashmal_lib.core.utils import is_hex) and context including class names, function names, or small code snippets from other files: # Path: hashmal_lib/gui_utils.py # def floated_buttons(btns, left=False): # """Returns a HBoxLayout with buttons floated to the right or left.""" # hbox = QHBoxLayout() # for b in btns: # hbox.addWidget(b) # if left: # hbox.addStretch(1) # else: # hbox.insertStretch(0, 1) # return hbox # # def HBox(*widgets): # """Create an HBoxLayout with the widgets passed.""" # hbox = QHBoxLayout() # for w in widgets: # hbox.addWidget(w) # return hbox # # Path: hashmal_lib/core/utils.py # def is_hex(x): # try: # i = int(x, 16) # return True # except ValueError: # pass # return False . Output only the next line.
form.addRow(floated_buttons([self.auto_save_check, self.save_button]))
Using the snippet: <|code_start|> self.view = QTableView() self.view.setWhatsThis('This table displays the variables you have defined.') self.view.setModel(self.proxy_model) self.view.setSortingEnabled(True) self.view.sortByColumn(0, QtCore.Qt.AscendingOrder) self.view.horizontalHeader().setResizeMode(1, QHeaderView.Stretch) self.view.horizontalHeader().setHighlightSections(False) self.view.verticalHeader().setDefaultSectionSize(22) self.view.verticalHeader().setVisible(False) self.view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.context_menu) self.view.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)) self.view.setSelectionMode(QAbstractItemView.SingleSelection) self.view.setSelectionBehavior(QAbstractItemView.SelectRows) self.view.setAlternatingRowColors(True) form.addRow(self.create_filters_box()) form.addRow(self.view) # Controls for adding/removing variables self.new_var_key = QLineEdit() self.new_var_key.setPlaceholderText('Key') self.new_var_key.setWhatsThis('Enter the name to give the new variable here.') self.setFocusProxy(self.new_var_key) self.new_var_value = QLineEdit() self.new_var_value.setPlaceholderText('Value') self.new_var_value.setWhatsThis('Enter the value to give the new variable here.') add_var_btn = QPushButton('&Add') add_var_btn.clicked.connect(self.add_new_var) <|code_end|> , determine the next line of code. You have imports: from collections import OrderedDict, namedtuple from PyQt4.QtGui import * from PyQt4 import QtCore from base import BaseDock, Plugin, augmenter from item_types import ItemAction, item_types from hashmal_lib.gui_utils import floated_buttons, HBox from hashmal_lib.core.utils import is_hex and context (class names, function names, or code) available: # Path: hashmal_lib/gui_utils.py # def floated_buttons(btns, left=False): # """Returns a HBoxLayout with buttons floated to the right or left.""" # hbox = QHBoxLayout() # for b in btns: # hbox.addWidget(b) # if left: # hbox.addStretch(1) # else: # hbox.insertStretch(0, 1) # return hbox # # def HBox(*widgets): # """Create an HBoxLayout with the widgets passed.""" # hbox = QHBoxLayout() # for w in widgets: # hbox.addWidget(w) # return hbox # # Path: hashmal_lib/core/utils.py # def is_hex(x): # try: # i = int(x, 16) # return True # except ValueError: # pass # return False . Output only the next line.
add_var_hbox = HBox(self.new_var_key, QLabel(':'), self.new_var_value, add_var_btn)
Predict the next line for this snippet: <|code_start|> def make_plugin(): return Plugin(Variables) VariableType = namedtuple('VariableType', ('name', 'classify')) """Variable type. Attributes: name (str): Human-readable name. classify (function): Function returning whether a value has this variable type. """ _var_types = [ VariableType('None', lambda x: False), <|code_end|> with the help of current file imports: from collections import OrderedDict, namedtuple from PyQt4.QtGui import * from PyQt4 import QtCore from base import BaseDock, Plugin, augmenter from item_types import ItemAction, item_types from hashmal_lib.gui_utils import floated_buttons, HBox from hashmal_lib.core.utils import is_hex and context from other files: # Path: hashmal_lib/gui_utils.py # def floated_buttons(btns, left=False): # """Returns a HBoxLayout with buttons floated to the right or left.""" # hbox = QHBoxLayout() # for b in btns: # hbox.addWidget(b) # if left: # hbox.addStretch(1) # else: # hbox.insertStretch(0, 1) # return hbox # # def HBox(*widgets): # """Create an HBoxLayout with the widgets passed.""" # hbox = QHBoxLayout() # for w in widgets: # hbox.addWidget(w) # return hbox # # Path: hashmal_lib/core/utils.py # def is_hex(x): # try: # i = int(x, 16) # return True # except ValueError: # pass # return False , which may contain function names, class names, or code. Output only the next line.
VariableType('Hex', is_hex),
Predict the next line after this snippet: <|code_start|> A module's make_plugin() function should return an instance of this class. """ def __init__(self, ui_class): self.ui_class = ui_class self.ui = None # name is set when the entry point is loaded. self.name = '' # If False, plugin has no dedicated GUI. self.has_gui = True def instantiate_ui(self, plugin_handler): instance = self.ui_class(plugin_handler) self.ui = instance def augmenters(self): return self.ui.augmenters if self.ui else None def get_augmenter(self, hook_name): return getattr(self.ui, hook_name) if self.ui else None class BasePluginUI(object): """Base class for plugin user interfaces.""" tool_name = '' description = '' category = Category.General def __init__(self, handler): self.handler = handler <|code_end|> using the current file's imports: from functools import wraps from collections import namedtuple from PyQt4.QtGui import QDockWidget, QWidget, QVBoxLayout from PyQt4 import QtCore from hashmal_lib import config and any relevant context from other files: # Path: hashmal_lib/config.py # def set_config(c): # def get_config(): # def __init__(self, parent=None): # def get_option(self, key, default=None): # def set_option(self, key, value, do_save=True): # class Config(QtCore.QObject): . Output only the next line.
self.config = config.get_config()
Next line prediction: <|code_start|> class UtilsTest(unittest.TestCase): def test_is_hex(self): hex_tests = ( ('0x0', True), ('0x00', True), ('0', True), ('00', True), ('f', True), ('x', False), ('0x', False), ) for value, expected in hex_tests: <|code_end|> . Use current file imports: (import unittest from hashmal_lib.core import utils) and context including class names, function names, or small code snippets from other files: # Path: hashmal_lib/core/utils.py # def format_hex_string(x, with_prefix=True): # def is_hex(x): # def push_script(x): . Output only the next line.
self.assertEqual(expected, utils.is_hex(value))
Predict the next line for this snippet: <|code_start|> description = '\n'.join([ 'Address Encoder encodes/decodes addresses with version bytes (blockchain identifiers).', 'Addresses are decoded into their 20-byte RIPEMD-160 hashes.' ]) category = Category.Key def __init__(self, handler): super(AddrEncoder, self).__init__(handler) self.widget().setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) def init_data(self): pass @augmenter def item_types(self, arg): return [AddressItem, Hash160Item] @augmenter def item_actions(self, *args): return [ ItemAction(self.tool_name, 'Address', 'Decode', self.decode_item), ItemAction(self.tool_name, 'Hash160', 'Encode', self.encode_item) ] def create_layout(self): form = QFormLayout() form.setRowWrapPolicy(QFormLayout.WrapAllRows) self.address_line = QLineEdit() self.address_line.setWhatsThis('Enter a cryptocurrency address in this field to decode it into its raw format.') <|code_end|> with the help of current file imports: from bitcoin.core import x, b2x from bitcoin.base58 import CBase58Data from PyQt4.QtGui import * from base import BaseDock, Plugin, Category, augmenter from hashmal_lib.gui_utils import monospace_font, Separator from item_types import Item, ItemAction and context from other files: # Path: hashmal_lib/gui_utils.py # def HBox(*widgets): # def floated_buttons(btns, left=False): # def add_shortcuts(items): # def __init__(self, parent=None): # def sizeHint(self): # def __init__(self, satoshis=0): # def known_formats(): # def get_str(self): # def __init__(self, parent=None): # def satoshis(self): # def satoshis(self, value): # def get_satoshis(self): # def set_satoshis(self, amount): # def check_text(self): # def update_format(self): # def on_option_changed(self, key): # def __init__(self, max_value=0xffffffff, parent=None): # def amount(self): # def amount(self, value): # def get_amount(self): # def set_amount(self, amount): # def check_text(self): # def __init__( self, *args ): # def isReadOnly( self ): # def mousePressEvent( self, event ): # def mouseMoveEvent( self, event ): # def mouseReleaseEvent( self, event ): # def keyPressEvent( self, event ): # def setReadOnly( self, state ): # class Separator(QFrame): # class Amount(object): # class OutputAmountEdit(QLineEdit): # class AmountEdit(QLineEdit): # class ReadOnlyCheckBox(QtGui.QCheckBox): , which may contain function names, class names, or code. Output only the next line.
self.address_line.setFont(monospace_font)
Continue the code snippet: <|code_start|> form = QFormLayout() form.setRowWrapPolicy(QFormLayout.WrapAllRows) self.address_line = QLineEdit() self.address_line.setWhatsThis('Enter a cryptocurrency address in this field to decode it into its raw format.') self.address_line.setFont(monospace_font) self.address_line.setPlaceholderText('Enter an address') self.setFocusProxy(self.address_line) self.decode_button = QPushButton('Decode') self.decode_button.clicked.connect(self.decode_address) self.hash_line = QLineEdit() self.hash_line.setWhatsThis('Enter a raw RIPEMD-160 hash in this field to encode it into an address.') self.hash_line.setFont(monospace_font) self.hash_line.setPlaceholderText('Enter a RIPEMD-160 hash') self.addr_version = QSpinBox() self.addr_version.setWhatsThis('The address version determines what character an address will start with, and is used to distinguish addresses for different cryptocurrencies.') self.addr_version.setRange(0, 255) self.encode_button = QPushButton('Encode') self.encode_button.clicked.connect(self.encode_address) addr_box = QHBoxLayout() addr_box.addWidget(self.address_line, stretch=1) addr_box.addWidget(self.decode_button) version_box = QHBoxLayout() version_box.addWidget(QLabel('Address Version:')) version_box.addWidget(self.addr_version) version_box.addWidget(self.encode_button) <|code_end|> . Use current file imports: from bitcoin.core import x, b2x from bitcoin.base58 import CBase58Data from PyQt4.QtGui import * from base import BaseDock, Plugin, Category, augmenter from hashmal_lib.gui_utils import monospace_font, Separator from item_types import Item, ItemAction and context (classes, functions, or code) from other files: # Path: hashmal_lib/gui_utils.py # def HBox(*widgets): # def floated_buttons(btns, left=False): # def add_shortcuts(items): # def __init__(self, parent=None): # def sizeHint(self): # def __init__(self, satoshis=0): # def known_formats(): # def get_str(self): # def __init__(self, parent=None): # def satoshis(self): # def satoshis(self, value): # def get_satoshis(self): # def set_satoshis(self, amount): # def check_text(self): # def update_format(self): # def on_option_changed(self, key): # def __init__(self, max_value=0xffffffff, parent=None): # def amount(self): # def amount(self, value): # def get_amount(self): # def set_amount(self, amount): # def check_text(self): # def __init__( self, *args ): # def isReadOnly( self ): # def mousePressEvent( self, event ): # def mouseMoveEvent( self, event ): # def mouseReleaseEvent( self, event ): # def keyPressEvent( self, event ): # def setReadOnly( self, state ): # class Separator(QFrame): # class Amount(object): # class OutputAmountEdit(QLineEdit): # class AmountEdit(QLineEdit): # class ReadOnlyCheckBox(QtGui.QCheckBox): . Output only the next line.
sep = Separator()
Based on the snippet: <|code_start|> class ChainparamsComboBox(QComboBox): """ComboBox for selecting chainparams presets. Separated from SettingsDialog so it can be used elsewhere. """ paramsChanged = pyqtSignal() def __init__(self, main_window, parent=None): super(ChainparamsComboBox, self).__init__(parent) self.gui = main_window self.config = self.gui.config <|code_end|> , predict the immediate next line with the help of imports: from PyQt4.QtGui import * from PyQt4.QtCore import * from hashmal_lib.core import chainparams from gui_utils import floated_buttons, Amount, monospace_font, Separator import logging and context (classes, functions, sometimes code) from other files: # Path: hashmal_lib/core/chainparams.py # class ParamsPreset(object): # def __init__(self, **kwargs): # def raw_signature_hash(cls, script, txTo, inIdx, hashtype): # def signature_hash(cls, script, txTo, inIdx, hashtype): # def add_preset(preset): # def remove_preset(preset): # def get_presets(): # def get_tx_fields(): # def set_tx_fields(fields): # def set_tx_serializer(cls): # def get_block_header_fields(): # def set_block_header_fields(fields): # def get_block_fields(): # def set_block_fields(fields): # def get_opcode_overrides(): # def set_opcode_overrides(ops): # def set_opcodes(op_names, ops_by_name, disabled_ops): # def get_script_engine_class(): # def set_script_engine_class(cls): # def set_to_preset(name): # def signature_hash(script, txTo, inIdx, hashtype): # HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' . Output only the next line.
preset_names = [i.name for i in chainparams.get_presets()]
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- def test_read_spec(): for api_level in defaults.API_LEVELS: base_path = '/api/{}/{}'.format(settings.API_VERSION, api_level) for ext in ('yaml', 'json'): <|code_end|> , generate the next line using the imports in this file: import os from scalrctl import defaults, settings, utils and context (functions, classes, or occasionally code) from other files: # Path: scalrctl/defaults.py # CONFIG_DIRECTORY = os.path.expanduser(os.environ.get("SCALRCLI_HOME", os.path.join(os.path.expanduser("~"), ".scalr"))) # CONFIG_PATH = os.path.join(CONFIG_DIRECTORY, "%s.yaml" % os.environ.get("SCALRCLI_PROFILE", "default")) # VERSION = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() # API_LEVELS = [ # 'user', # 'account', # 'global', # ] # # Path: scalrctl/settings.py # API_KEY_ID = None # API_SECRET_KEY = None # API_VERSION = "v1beta0" # API_SCHEME = 'https' # API_HOST = 'my.scalr.com' # SIGNATURE_VERSION = 'V1-HMAC-SHA256' # SSL_VERIFY_PEER = True # GLOBAL_SCOPE_API_KEY_ID = None # GLOBAL_SCOPE_API_SECRET_KEY = None # # Path: scalrctl/utils.py # def read_spec(api_level, ext='json'): # def read_routes(): # def read_scheme(): # def read_config(profile=None): # def warning(*messages): # def debug(msg): # def reraise(message): # def draw(event): # def __init__(self): # def __enter__(self): # def __exit__(self, type, value, traceback): # class _spinner(object): . Output only the next line.
spec = utils.read_spec(api_level, ext=ext)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @pytest.fixture(scope="module") def specs(): data = {} <|code_end|> . Write the next line using the current file imports: import json import pytest import requests from scalrctl import defaults, examples and context from other files: # Path: scalrctl/defaults.py # CONFIG_DIRECTORY = os.path.expanduser(os.environ.get("SCALRCLI_HOME", os.path.join(os.path.expanduser("~"), ".scalr"))) # CONFIG_PATH = os.path.join(CONFIG_DIRECTORY, "%s.yaml" % os.environ.get("SCALRCLI_PROFILE", "default")) # VERSION = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() # API_LEVELS = [ # 'user', # 'account', # 'global', # ] # # Path: scalrctl/examples.py # DOCS_HOST = 'https://api-explorer.scalr.com' # EXCLUDES = [ # '/{envId}/farm-roles/{farmRoleId}/servers/', # '/{envId}/servers/', # ] # DEFAULTS = { # 'string': '', # 'boolean': True, # 'integer': 1, # 'number': 1, # 'array': [] # } # def _read_spec(api_level, extension="json"): # def _item_by_ref(spec_data, ref): # def _generate_params(spec_data, schema): # def generate_post_data(spec_data, endpoint): # def get_definition(spec_data, endpoint): # def get_doc_url(api_level, endpoint): # def create_post_example(api_level, endpoint): , which may include functions, classes, or code. Output only the next line.
for api_level in defaults.API_LEVELS:
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- @pytest.fixture(scope="module") def specs(): data = {} for api_level in defaults.API_LEVELS: <|code_end|> , predict the immediate next line with the help of imports: import json import pytest import requests from scalrctl import defaults, examples and context (classes, functions, sometimes code) from other files: # Path: scalrctl/defaults.py # CONFIG_DIRECTORY = os.path.expanduser(os.environ.get("SCALRCLI_HOME", os.path.join(os.path.expanduser("~"), ".scalr"))) # CONFIG_PATH = os.path.join(CONFIG_DIRECTORY, "%s.yaml" % os.environ.get("SCALRCLI_PROFILE", "default")) # VERSION = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() # API_LEVELS = [ # 'user', # 'account', # 'global', # ] # # Path: scalrctl/examples.py # DOCS_HOST = 'https://api-explorer.scalr.com' # EXCLUDES = [ # '/{envId}/farm-roles/{farmRoleId}/servers/', # '/{envId}/servers/', # ] # DEFAULTS = { # 'string': '', # 'boolean': True, # 'integer': 1, # 'number': 1, # 'array': [] # } # def _read_spec(api_level, extension="json"): # def _item_by_ref(spec_data, ref): # def _generate_params(spec_data, schema): # def generate_post_data(spec_data, endpoint): # def get_definition(spec_data, endpoint): # def get_doc_url(api_level, endpoint): # def create_post_example(api_level, endpoint): . Output only the next line.
data[api_level] = json.loads(examples._read_spec(api_level))
Given the following code snippet before the placeholder: <|code_start|> :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: a callback that should be executed after the parameter was matched. This is called as ``fn(ctx, param, value)`` and needs to return the value. Before Click 2.0, the signature was ``(ctx, value)``. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. """ param_type_name = 'parameter' def __init__(self, param_decls=None, type=None, required=False, default=None, callback=None, nargs=None, metavar=None, expose_value=True, is_eager=False, envvar=None): self.name, self.opts, self.secondary_opts = \ self._parse_decls(param_decls or (), expose_value) <|code_end|> , predict the next line using imports from the current file: import os import sys from contextlib import contextmanager from itertools import repeat from functools import update_wrapper from .types import convert_type, IntRange, BOOL from .utils import make_str, make_default_short_help, echo, get_os_args from .exceptions import ClickException, UsageError, BadParameter, Abort, \ MissingParameter from .termui import prompt, confirm from .formatting import HelpFormatter, join_options from .parser import OptionParser, split_opt from .globals import push_context, pop_context from ._compat import PY2, isidentifier, iteritems from ._unicodefun import _check_for_unicode_literals, _verify_python3_env from ._bashcomplete import bashcomplete from warnings import warn from .decorators import command, group and context including class names, function names, and sometimes code from other files: # Path: scalrctl/click/types.py # def convert_type(ty, default=None): # """Converts a callable or python ty into the most appropriate param # ty. # """ # guessed_type = False # if ty is None and default is not None: # if isinstance(default, tuple): # ty = tuple(map(type, default)) # else: # ty = type(default) # guessed_type = True # # if isinstance(ty, tuple): # return Tuple(ty) # if isinstance(ty, ParamType): # return ty # if ty is text_type or ty is str or ty is None: # return STRING # if ty is int: # return INT # # Booleans are only okay if not guessed. This is done because for # # flags the default value is actually a bit of a lie in that it # # indicates which of the flags is the one we want. See get_default() # # for more information. # if ty is bool and not guessed_type: # return BOOL # if ty is float: # return FLOAT # if guessed_type: # return STRING # # # Catch a common mistake # if __debug__: # try: # if issubclass(ty, ParamType): # raise AssertionError('Attempted to use an uninstantiated ' # 'parameter type (%s).' % ty) # except TypeError: # pass # return FuncParamType(ty) # # class IntRange(IntParamType): # """A parameter that works similar to :data:`click.INT` but restricts # the value to fit into a range. The default behavior is to fail if the # value falls outside the range, but it can also be silently clamped # between the two edges. # # See :ref:`ranges` for an example. # """ # name = 'integer range' # # def __init__(self, min=None, max=None, clamp=False): # self.min = min # self.max = max # self.clamp = clamp # # def convert(self, value, param, ctx): # rv = IntParamType.convert(self, value, param, ctx) # if self.clamp: # if self.min is not None and rv < self.min: # return self.min # if self.max is not None and rv > self.max: # return self.max # if self.min is not None and rv < self.min or \ # self.max is not None and rv > self.max: # if self.min is None: # self.fail('%s is bigger than the maximum valid value ' # '%s.' % (rv, self.max), param, ctx) # elif self.max is None: # self.fail('%s is smaller than the minimum valid value ' # '%s.' % (rv, self.min), param, ctx) # else: # self.fail('%s is not in the valid range of %s to %s.' # % (rv, self.min, self.max), param, ctx) # return rv # # def __repr__(self): # return 'IntRange(%r, %r)' % (self.min, self.max) # # BOOL = BoolParamType() . Output only the next line.
self.type = convert_type(type, default)
Predict the next line after this snippet: <|code_start|> else: prompt_text = prompt self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.hide_input = hide_input self.hidden = hidden # Flags if is_flag is None: if flag_value is not None: is_flag = True else: is_flag = bool(self.secondary_opts) if is_flag and default_is_missing: self.default = False if flag_value is None: flag_value = not self.default self.is_flag = is_flag self.flag_value = flag_value if self.is_flag and isinstance(self.flag_value, bool) \ and type is None: self.type = BOOL self.is_bool_flag = True else: self.is_bool_flag = False # Counting self.count = count if count: if type is None: <|code_end|> using the current file's imports: import os import sys from contextlib import contextmanager from itertools import repeat from functools import update_wrapper from .types import convert_type, IntRange, BOOL from .utils import make_str, make_default_short_help, echo, get_os_args from .exceptions import ClickException, UsageError, BadParameter, Abort, \ MissingParameter from .termui import prompt, confirm from .formatting import HelpFormatter, join_options from .parser import OptionParser, split_opt from .globals import push_context, pop_context from ._compat import PY2, isidentifier, iteritems from ._unicodefun import _check_for_unicode_literals, _verify_python3_env from ._bashcomplete import bashcomplete from warnings import warn from .decorators import command, group and any relevant context from other files: # Path: scalrctl/click/types.py # def convert_type(ty, default=None): # """Converts a callable or python ty into the most appropriate param # ty. # """ # guessed_type = False # if ty is None and default is not None: # if isinstance(default, tuple): # ty = tuple(map(type, default)) # else: # ty = type(default) # guessed_type = True # # if isinstance(ty, tuple): # return Tuple(ty) # if isinstance(ty, ParamType): # return ty # if ty is text_type or ty is str or ty is None: # return STRING # if ty is int: # return INT # # Booleans are only okay if not guessed. This is done because for # # flags the default value is actually a bit of a lie in that it # # indicates which of the flags is the one we want. See get_default() # # for more information. # if ty is bool and not guessed_type: # return BOOL # if ty is float: # return FLOAT # if guessed_type: # return STRING # # # Catch a common mistake # if __debug__: # try: # if issubclass(ty, ParamType): # raise AssertionError('Attempted to use an uninstantiated ' # 'parameter type (%s).' % ty) # except TypeError: # pass # return FuncParamType(ty) # # class IntRange(IntParamType): # """A parameter that works similar to :data:`click.INT` but restricts # the value to fit into a range. The default behavior is to fail if the # value falls outside the range, but it can also be silently clamped # between the two edges. # # See :ref:`ranges` for an example. # """ # name = 'integer range' # # def __init__(self, min=None, max=None, clamp=False): # self.min = min # self.max = max # self.clamp = clamp # # def convert(self, value, param, ctx): # rv = IntParamType.convert(self, value, param, ctx) # if self.clamp: # if self.min is not None and rv < self.min: # return self.min # if self.max is not None and rv > self.max: # return self.max # if self.min is not None and rv < self.min or \ # self.max is not None and rv > self.max: # if self.min is None: # self.fail('%s is bigger than the maximum valid value ' # '%s.' % (rv, self.max), param, ctx) # elif self.max is None: # self.fail('%s is smaller than the minimum valid value ' # '%s.' % (rv, self.min), param, ctx) # else: # self.fail('%s is not in the valid range of %s to %s.' # % (rv, self.min, self.max), param, ctx) # return rv # # def __repr__(self): # return 'IntRange(%r, %r)' % (self.min, self.max) # # BOOL = BoolParamType() . Output only the next line.
self.type = IntRange(min=0)
Given the code snippet: <|code_start|> multiple=False, count=False, allow_from_autoenv=True, type=None, help=None, hidden=False, **attrs): default_is_missing = attrs.get('default', _missing) is _missing Parameter.__init__(self, param_decls, type=type, **attrs) if prompt is True: prompt_text = self.name.replace('_', ' ').capitalize() elif prompt is False: prompt_text = None else: prompt_text = prompt self.prompt = prompt_text self.confirmation_prompt = confirmation_prompt self.hide_input = hide_input self.hidden = hidden # Flags if is_flag is None: if flag_value is not None: is_flag = True else: is_flag = bool(self.secondary_opts) if is_flag and default_is_missing: self.default = False if flag_value is None: flag_value = not self.default self.is_flag = is_flag self.flag_value = flag_value if self.is_flag and isinstance(self.flag_value, bool) \ and type is None: <|code_end|> , generate the next line using the imports in this file: import os import sys from contextlib import contextmanager from itertools import repeat from functools import update_wrapper from .types import convert_type, IntRange, BOOL from .utils import make_str, make_default_short_help, echo, get_os_args from .exceptions import ClickException, UsageError, BadParameter, Abort, \ MissingParameter from .termui import prompt, confirm from .formatting import HelpFormatter, join_options from .parser import OptionParser, split_opt from .globals import push_context, pop_context from ._compat import PY2, isidentifier, iteritems from ._unicodefun import _check_for_unicode_literals, _verify_python3_env from ._bashcomplete import bashcomplete from warnings import warn from .decorators import command, group and context (functions, classes, or occasionally code) from other files: # Path: scalrctl/click/types.py # def convert_type(ty, default=None): # """Converts a callable or python ty into the most appropriate param # ty. # """ # guessed_type = False # if ty is None and default is not None: # if isinstance(default, tuple): # ty = tuple(map(type, default)) # else: # ty = type(default) # guessed_type = True # # if isinstance(ty, tuple): # return Tuple(ty) # if isinstance(ty, ParamType): # return ty # if ty is text_type or ty is str or ty is None: # return STRING # if ty is int: # return INT # # Booleans are only okay if not guessed. This is done because for # # flags the default value is actually a bit of a lie in that it # # indicates which of the flags is the one we want. See get_default() # # for more information. # if ty is bool and not guessed_type: # return BOOL # if ty is float: # return FLOAT # if guessed_type: # return STRING # # # Catch a common mistake # if __debug__: # try: # if issubclass(ty, ParamType): # raise AssertionError('Attempted to use an uninstantiated ' # 'parameter type (%s).' % ty) # except TypeError: # pass # return FuncParamType(ty) # # class IntRange(IntParamType): # """A parameter that works similar to :data:`click.INT` but restricts # the value to fit into a range. The default behavior is to fail if the # value falls outside the range, but it can also be silently clamped # between the two edges. # # See :ref:`ranges` for an example. # """ # name = 'integer range' # # def __init__(self, min=None, max=None, clamp=False): # self.min = min # self.max = max # self.clamp = clamp # # def convert(self, value, param, ctx): # rv = IntParamType.convert(self, value, param, ctx) # if self.clamp: # if self.min is not None and rv < self.min: # return self.min # if self.max is not None and rv > self.max: # return self.max # if self.min is not None and rv < self.min or \ # self.max is not None and rv > self.max: # if self.min is None: # self.fail('%s is bigger than the maximum valid value ' # '%s.' % (rv, self.max), param, ctx) # elif self.max is None: # self.fail('%s is smaller than the minimum valid value ' # '%s.' % (rv, self.min), param, ctx) # else: # self.fail('%s is not in the valid range of %s to %s.' # % (rv, self.min, self.max), param, ctx) # return rv # # def __repr__(self): # return 'IntRange(%r, %r)' % (self.min, self.max) # # BOOL = BoolParamType() . Output only the next line.
self.type = BOOL
Given the code snippet: <|code_start|> row.append('') if row: rows.append(row) pagination = response_json.get("pagination", None) pagenum_last, current_pagenum = 1, 1 if pagination: url_last = pagination.get('last', None) if url_last: number = re.search("pageNum=(\d*)", url_last) pagenum_last = number.group(1) if number else 1 url_next = pagination.get('next', None) if url_next: num = re.search("pageNum=(\d*)", url_next) pagenum_next = num.group(1) if num else 1 current_pagenum = int(pagenum_next) - 1 return rows, current_pagenum, pagenum_last def prepare_table(): table = prettytable.PrettyTable() table.align = "l" table.right_padding_width = 4 table.left_padding_width = 1 table.set_style(prettytable.PLAIN_COLUMNS) return table def build_vertical_table(field_names, rows, pre=None, post=None): table = prepare_table() <|code_end|> , generate the next line using the imports in this file: import json import yaml import six import prettytable import re from scalrctl import settings and context (functions, classes, or occasionally code) from other files: # Path: scalrctl/settings.py # API_KEY_ID = None # API_SECRET_KEY = None # API_VERSION = "v1beta0" # API_SCHEME = 'https' # API_HOST = 'my.scalr.com' # SIGNATURE_VERSION = 'V1-HMAC-SHA256' # SSL_VERIFY_PEER = True # GLOBAL_SCOPE_API_KEY_ID = None # GLOBAL_SCOPE_API_SECRET_KEY = None . Output only the next line.
template = '\x1b[1m%s\x1b[0m' if settings.colored_output else "%s"
Here is a snippet: <|code_start|> port (int): port number is_auth (bool): server requires authentication username (str): server auth username password (str): server auth password is_tls (bool): use TLS mode """ msg = MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(message)) part = MIMEBase('application', "octet-stream") part.set_payload(picture.getbuffer()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(filename)) msg.attach(part) smtp = smtplib.SMTP(server, port) if is_tls: smtp.starttls() if is_auth: smtp.login(username, password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.quit() <|code_end|> . Write the next line using the current file imports: import logging import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import formatdate from email import encoders from pathlib import Path from .WorkerTask import WorkerTask and context from other files: # Path: photobooth/worker/WorkerTask.py # class WorkerTask: # # def __init__(self, **kwargs): # # assert not kwargs # # def do(self, picture): # # raise NotImplementedError() , which may include functions, classes, or code. Output only the next line.
class PictureMailer(WorkerTask):
Predict the next line after this snippet: <|code_start|># 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. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. class Receiver(QtCore.QThread): notify = QtCore.pyqtSignal(object) def __init__(self, comm): super().__init__() self._comm = comm def handle(self, state): self.notify.emit(state) def run(self): <|code_end|> using the current file's imports: from PyQt5 import QtCore from ...Threading import Workers and any relevant context from other files: # Path: photobooth/Threading.py # class Workers(IntEnum): # # MASTER = 0 # GUI = 1 # CAMERA = 2 # GPIO = 3 # WORKER = 4 . Output only the next line.
for state in self._comm.iter(Workers.GUI):
Given snippet: <|code_start|> app_name = 'widgets' urlpatterns = [ url(r'^$', MapWidgetListView.as_view(), name="list"), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import url from .views import MapWidgetListView, PointFieldGoogleWidgetView, PointFieldGoogleStaticWidgetView, PointFieldGoogleStaticOverlayWidgetView and context: # Path: tests/testapp/widgets/views.py # class MapWidgetListView(TemplateView): # template_name = "widgets/widget_list.html" # # class PointFieldGoogleWidgetView(FormView): # template_name = "widgets/google_point_widget.html" # form_class = PointFieldCreateForm # success_url = "/" # # class PointFieldGoogleStaticWidgetView(TemplateView): # template_name = "widgets/google_point_static_widget.html" # # class PointFieldGoogleStaticOverlayWidgetView(TemplateView): # template_name = "widgets/google_point_static_overlay_widget.html" which might include code, classes, or functions. Output only the next line.
url(r'^google-point-widget/$', PointFieldGoogleWidgetView.as_view(), name="google-point"),
Given the following code snippet before the placeholder: <|code_start|> app_name = 'widgets' urlpatterns = [ url(r'^$', MapWidgetListView.as_view(), name="list"), url(r'^google-point-widget/$', PointFieldGoogleWidgetView.as_view(), name="google-point"), url(r'^google-point-static-widget/$', <|code_end|> , predict the next line using imports from the current file: from django.conf.urls import url from .views import MapWidgetListView, PointFieldGoogleWidgetView, PointFieldGoogleStaticWidgetView, PointFieldGoogleStaticOverlayWidgetView and context including class names, function names, and sometimes code from other files: # Path: tests/testapp/widgets/views.py # class MapWidgetListView(TemplateView): # template_name = "widgets/widget_list.html" # # class PointFieldGoogleWidgetView(FormView): # template_name = "widgets/google_point_widget.html" # form_class = PointFieldCreateForm # success_url = "/" # # class PointFieldGoogleStaticWidgetView(TemplateView): # template_name = "widgets/google_point_static_widget.html" # # class PointFieldGoogleStaticOverlayWidgetView(TemplateView): # template_name = "widgets/google_point_static_overlay_widget.html" . Output only the next line.
PointFieldGoogleStaticWidgetView.as_view(),
Given snippet: <|code_start|> app_name = 'widgets' urlpatterns = [ url(r'^$', MapWidgetListView.as_view(), name="list"), url(r'^google-point-widget/$', PointFieldGoogleWidgetView.as_view(), name="google-point"), url(r'^google-point-static-widget/$', PointFieldGoogleStaticWidgetView.as_view(), name="google-point-static" ), url(r'^google-point-static-overlay-widget/$', <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import url from .views import MapWidgetListView, PointFieldGoogleWidgetView, PointFieldGoogleStaticWidgetView, PointFieldGoogleStaticOverlayWidgetView and context: # Path: tests/testapp/widgets/views.py # class MapWidgetListView(TemplateView): # template_name = "widgets/widget_list.html" # # class PointFieldGoogleWidgetView(FormView): # template_name = "widgets/google_point_widget.html" # form_class = PointFieldCreateForm # success_url = "/" # # class PointFieldGoogleStaticWidgetView(TemplateView): # template_name = "widgets/google_point_static_widget.html" # # class PointFieldGoogleStaticOverlayWidgetView(TemplateView): # template_name = "widgets/google_point_static_overlay_widget.html" which might include code, classes, or functions. Output only the next line.
PointFieldGoogleStaticOverlayWidgetView.as_view(),
Based on the snippet: <|code_start|> class MapWidgetListView(TemplateView): template_name = "widgets/widget_list.html" class PointFieldGoogleWidgetView(FormView): template_name = "widgets/google_point_widget.html" <|code_end|> , predict the immediate next line with the help of imports: from django.views.generic import TemplateView, FormView from .forms import PointFieldCreateForm and context (classes, functions, sometimes code) from other files: # Path: tests/testapp/widgets/forms.py # class PointFieldCreateForm(forms.ModelForm): # # class Meta: # model = PointField # fields = ("name", "location", "city") # widgets = { # 'location': GooglePointFieldWidget, # 'city': GooglePointFieldWidget, # } . Output only the next line.
form_class = PointFieldCreateForm
Next line prediction: <|code_start|> if not isinstance(mw_settings.GoogleStaticMapMarkerSettings, dict): # pragma: no cover raise TypeError('GoogleStaticMapMarkerSettings must be a dictionary.') return mw_settings.GoogleStaticMapMarkerSettings def get_point_field_params(self, latitude, longitude): marker_point = "%s,%s" % (latitude, longitude) marker_params = ["%s:%s" % (key, value) for key, value in self.marker_settings.items()] marker_params.append(marker_point) marker_url_params = "|".join(marker_params) params = { "center": marker_point, "markers": marker_url_params, } params.update(self.map_settings) return params def get_image_url(self, value): if isinstance(value, Point): longitude, latitude = value.x, value.y params = self.get_point_field_params(latitude, longitude) image_url_template = "%(base_url)s?%(params)s" image_url_data = { "base_url": self.base_url, "params": urlencode(params) } return image_url_template % image_url_data <|code_end|> . Use current file imports: (import json from django import forms from django.contrib.gis.forms import BaseGeometryWidget from django.contrib.gis.geos import Point from django.core.exceptions import ImproperlyConfigured from django.template.loader import render_to_string from django.templatetags.static import static from django.utils.http import urlencode from mapwidgets.constants import STATIC_MAP_PLACEHOLDER_IMAGE from mapwidgets.settings import MapWidgetSettings, mw_settings) and context including class names, function names, or small code snippets from other files: # Path: mapwidgets/constants.py # STATIC_MAP_PLACEHOLDER_IMAGE = "mapwidgets/images/no-map-image.png" # # Path: mapwidgets/settings.py # DEFAULTS = { # "GooglePointFieldWidget": ( # ("mapCenterLocationName", None), # ("mapCenterLocation", TIMEZONE_COORDINATES.get(getattr(django_settings, "TIME_ZONE", "UTC"))), # ("zoom", 6), # ("GooglePlaceAutocompleteOptions", {}), # ("markerFitZoom", 15), # ("streetViewControl", True), # ), # # "MapboxPointFieldWidget": ( # ("mapCenterLocationName", None), # ("mapCenterLocation", TIMEZONE_COORDINATES.get(getattr(django_settings, "TIME_ZONE", "UTC"))), # ("zoom", 6), # ("markerFitZoom", 15), # ("access_token", ""), # ), # # "GoogleStaticMapWidget": ( # ("zoom", 15), # ("size", "480x480"), # ("scale", ""), # ("format", ""), # ("maptype", ""), # ("path", ""), # ("visible", ""), # ("style", ""), # ("language", ""), # ("region", "") # ), # # "GoogleStaticMapMarkerSettings": ( # ("size", "normal"), # ("color", ""), # ("icon", ""), # ), # # "GoogleStaticOverlayMapWidget": ( # ("zoom", 15), # ("size", "480x480"), # ("thumbnail_size", "160x160"), # ("scale", ""), # ("format", ""), # ("maptype", ""), # ("path", ""), # ("visible", ""), # ("style", ""), # ("language", ""), # ("region", "") # ), # "LANGUAGE": "en", # "LIBRARIES": "places", # "MINIFED": not django_settings.DEBUG, # "GOOGLE_MAP_API_SIGNATURE": "", # "GOOGLE_MAP_API_KEY": "", # "MAPBOX_API_KEY": "", # } # class MapWidgetSettings(object): # def __init__(self, app_settings=None, defaults=None): # def app_settings(self): # def __getattr__(self, attr): # def reload_widget_settings(*args, **kwargs): . Output only the next line.
return static(STATIC_MAP_PLACEHOLDER_IMAGE)
Given snippet: <|code_start|> class BasePointFieldMapWidget(BaseGeometryWidget): settings_namespace = None settings = None def __init__(self, *args, **kwargs): attrs = kwargs.get('attrs') self.attrs = {} for key in ('geom_type', 'map_srid', 'map_width', 'map_height', 'display_raw'): if key in kwargs: self.attrs[key] = kwargs.get(key) else: self.attrs[key] = getattr(self, key) if isinstance(attrs, dict): self.attrs.update(attrs) self.custom_settings = False if kwargs.get('settings'): self.settings = kwargs.pop('settings') self.custom_settings = True def map_options(self): if not self.settings: # pragma: no cover raise ImproperlyConfigured('%s requires either a definition of "settings"' % self.__class__.__name__) if not self.settings_namespace: # pragma: no cover raise ImproperlyConfigured('%s requires either a definition of "settings_namespace"' % self.__class__.__name__) if self.custom_settings: <|code_end|> , continue by predicting the next line. Consider current file imports: import json from django import forms from django.contrib.gis.forms import BaseGeometryWidget from django.contrib.gis.geos import Point from django.core.exceptions import ImproperlyConfigured from django.template.loader import render_to_string from django.templatetags.static import static from django.utils.http import urlencode from mapwidgets.constants import STATIC_MAP_PLACEHOLDER_IMAGE from mapwidgets.settings import MapWidgetSettings, mw_settings and context: # Path: mapwidgets/constants.py # STATIC_MAP_PLACEHOLDER_IMAGE = "mapwidgets/images/no-map-image.png" # # Path: mapwidgets/settings.py # DEFAULTS = { # "GooglePointFieldWidget": ( # ("mapCenterLocationName", None), # ("mapCenterLocation", TIMEZONE_COORDINATES.get(getattr(django_settings, "TIME_ZONE", "UTC"))), # ("zoom", 6), # ("GooglePlaceAutocompleteOptions", {}), # ("markerFitZoom", 15), # ("streetViewControl", True), # ), # # "MapboxPointFieldWidget": ( # ("mapCenterLocationName", None), # ("mapCenterLocation", TIMEZONE_COORDINATES.get(getattr(django_settings, "TIME_ZONE", "UTC"))), # ("zoom", 6), # ("markerFitZoom", 15), # ("access_token", ""), # ), # # "GoogleStaticMapWidget": ( # ("zoom", 15), # ("size", "480x480"), # ("scale", ""), # ("format", ""), # ("maptype", ""), # ("path", ""), # ("visible", ""), # ("style", ""), # ("language", ""), # ("region", "") # ), # # "GoogleStaticMapMarkerSettings": ( # ("size", "normal"), # ("color", ""), # ("icon", ""), # ), # # "GoogleStaticOverlayMapWidget": ( # ("zoom", 15), # ("size", "480x480"), # ("thumbnail_size", "160x160"), # ("scale", ""), # ("format", ""), # ("maptype", ""), # ("path", ""), # ("visible", ""), # ("style", ""), # ("language", ""), # ("region", "") # ), # "LANGUAGE": "en", # "LIBRARIES": "places", # "MINIFED": not django_settings.DEBUG, # "GOOGLE_MAP_API_SIGNATURE": "", # "GOOGLE_MAP_API_KEY": "", # "MAPBOX_API_KEY": "", # } # class MapWidgetSettings(object): # def __init__(self, app_settings=None, defaults=None): # def app_settings(self): # def __getattr__(self, attr): # def reload_widget_settings(*args, **kwargs): which might include code, classes, or functions. Output only the next line.
custom_settings = MapWidgetSettings(app_settings=self.settings)
Predict the next line after this snippet: <|code_start|> class StreetInline(admin.TabularInline): model = Street formfield_overrides = { <|code_end|> using the current file's imports: import mapwidgets from django.contrib import admin from django.contrib.gis.db import models from .models import PointField, Street and any relevant context from other files: # Path: tests/testapp/widgets/models.py # class PointField(models.Model): # name = models.CharField(max_length=255) # location = models.PointField(srid=4326) # city = models.PointField(blank=True, null=True, srid=3857) # # def __unicode__(self): # return self.name # # class Street(models.Model): # point = models.ForeignKey(PointField, blank=True, null=True, on_delete=models.SET_NULL) # name = models.CharField(max_length=255) # street = models.PointField(srid=4326) . Output only the next line.
models.PointField: {"widget": mapwidgets.GooglePointFieldWidget}
Given the following code snippet before the placeholder: <|code_start|> class WidgetSettingsTests(TestCase): def test_default_settings_values(self): mw_settings = MapWidgetSettings() with override_settings(MAP_WIDGETS={}): <|code_end|> , predict the next line using imports from the current file: from collections import OrderedDict from django.test import TestCase from django.test.utils import override_settings from mapwidgets.settings import MapWidgetSettings, DEFAULTS and context including class names, function names, and sometimes code from other files: # Path: mapwidgets/settings.py # class MapWidgetSettings(object): # # def __init__(self, app_settings=None, defaults=None): # if app_settings: # if not isinstance(app_settings, (dict, tuple)): # raise TypeError(_("MapWidget settings must be a tuple or dictionary")) # self._app_settings = app_settings # # self.defaults = defaults or DEFAULTS # # @property # def app_settings(self): # if not hasattr(self, '_app_settings'): # app_settings = getattr(django_settings, 'MAP_WIDGETS', {}) # if not isinstance(app_settings, (dict, tuple)): # raise TypeError(_("MapWidget settings must be a tuple or dictionary")) # # self._app_settings = getattr(django_settings, 'MAP_WIDGETS', {}) # return self._app_settings # # def __getattr__(self, attr): # if attr not in self.defaults.keys(): # raise AttributeError("Invalid settings key: '%s'. Please check the settings documentation http://django-map-widgets.readthedocs.io/en/latest/widgets/settings.html" % attr) # # try: # # Check if present attr in user settings # val = self.app_settings[attr] # # # Merge app tuple settings with defaults # if isinstance(val, tuple): # try: # app_bundle = OrderedDict(val) # default_bundle = OrderedDict(self.defaults[attr]) # default_bundle.update(app_bundle) # val = default_bundle # except ValueError: # raise ValueError(_("Invalid %s settings value. Please check the settings documentation http://django-map-widgets.readthedocs.io/en/latest/widgets/settings.html" % attr)) # # # Merge app dict settings with defaults # if isinstance(val, dict): # default_bundle = OrderedDict(self.defaults[attr]) # default_bundle.update(val) # val = default_bundle # # except KeyError: # # Fall back to defaults # val = self.defaults[attr] # if isinstance(val, tuple): # try: # val = OrderedDict(val) # except ValueError: # raise ValueError(_("Invalid %s settings value. Please check the settings documentation http://django-map-widgets.readthedocs.io/en/latest/widgets/settings.html" % attr)) # # # Cache the result # setattr(self, attr, val) # return val # # DEFAULTS = { # "GooglePointFieldWidget": ( # ("mapCenterLocationName", None), # ("mapCenterLocation", TIMEZONE_COORDINATES.get(getattr(django_settings, "TIME_ZONE", "UTC"))), # ("zoom", 6), # ("GooglePlaceAutocompleteOptions", {}), # ("markerFitZoom", 15), # ("streetViewControl", True), # ), # # "MapboxPointFieldWidget": ( # ("mapCenterLocationName", None), # ("mapCenterLocation", TIMEZONE_COORDINATES.get(getattr(django_settings, "TIME_ZONE", "UTC"))), # ("zoom", 6), # ("markerFitZoom", 15), # ("access_token", ""), # ), # # "GoogleStaticMapWidget": ( # ("zoom", 15), # ("size", "480x480"), # ("scale", ""), # ("format", ""), # ("maptype", ""), # ("path", ""), # ("visible", ""), # ("style", ""), # ("language", ""), # ("region", "") # ), # # "GoogleStaticMapMarkerSettings": ( # ("size", "normal"), # ("color", ""), # ("icon", ""), # ), # # "GoogleStaticOverlayMapWidget": ( # ("zoom", 15), # ("size", "480x480"), # ("thumbnail_size", "160x160"), # ("scale", ""), # ("format", ""), # ("maptype", ""), # ("path", ""), # ("visible", ""), # ("style", ""), # ("language", ""), # ("region", "") # ), # "LANGUAGE": "en", # "LIBRARIES": "places", # "MINIFED": not django_settings.DEBUG, # "GOOGLE_MAP_API_SIGNATURE": "", # "GOOGLE_MAP_API_KEY": "", # "MAPBOX_API_KEY": "", # } . Output only the next line.
google_point_widget_default_settings = OrderedDict(DEFAULTS["GooglePointFieldWidget"])
Given the following code snippet before the placeholder: <|code_start|>try: except ImportError: try: except ImportError: GOOGLE_MAP_API_KEY = os.environ.get("TEST_GOOGLE_MAP_API_KEY", test_app_settings.GOOGLE_MAP_API_KEY) DJANGO_DEFAULT_SRID_VALUE = 4326 GOOGLE_MAP_DEFAULT_SRID_VALUE = 4326 class GooglePointWidgetUnitTests(TestCase): def test_widget_with_default_settings(self): """ Test the widget with default settings which is defined in django settings file """ zoom = 15 default_map_center = [51.5073509, -0.12775829999] widget_settings = { "GooglePointFieldWidget": ( ("zoom", zoom), ("mapCenterLocation", default_map_center), ) } with override_settings(MAP_WIDGETS=widget_settings): <|code_end|> , predict the next line using imports from the current file: import os import json from importlib import reload as reload_module from imp import reload as reload_module from urllib.request import urlopen from http.client import HTTPMessage from urllib import urlopen from django.test import TestCase from django.test.utils import override_settings from django.contrib.gis.geos import Point from django.utils.html import escapejs from django.conf import settings as test_app_settings from django import forms as django_forms from mapwidgets import widgets as mw_widgets from .utils import html_escape, get_textarea_html and context including class names, function names, and sometimes code from other files: # Path: mapwidgets/widgets.py # def minify_if_not_debug(asset): # def __init__(self, *args, **kwargs): # def map_options(self): # def media(self): # def render(self, name, value, attrs=None, renderer=None): # def media(self): # def render(self, name, value, attrs=None, renderer=None): # def get_js_widget_data(self, name, element_id): # def render(self, name, value, attrs=None, renderer=None): # def media(self): # def map_settings(self): # pragma: no cover # def marker_settings(self): # pragma: no cover # def get_template(self): # pragma: no cover # def get_image_url(self, value): # pragma: no cover # def get_context_data(self, name, value, attrs): # def render(self, name, value, attrs=None, renderer=None): # def __init__(self, zoom=None, size=None, *args, **kwargs): # def map_settings(self): # def marker_settings(self): # def get_point_field_params(self, latitude, longitude): # def get_image_url(self, value): # def __init__(self, zoom=None, size=None, thumbnail_size=None, *args, **kwargs): # def map_settings(self): # def get_thumbnail_url(self, value): # def get_context_data(self, name, value, attrs): # class BasePointFieldMapWidget(BaseGeometryWidget): # class GooglePointFieldWidget(BasePointFieldMapWidget): # class MapboxPointFieldWidget(BasePointFieldMapWidget): # class PointFieldInlineWidgetMixin(object): # class GooglePointFieldInlineWidget(PointFieldInlineWidgetMixin, GooglePointFieldWidget): # class BaseStaticMapWidget(forms.Widget): # class GoogleStaticMapWidget(BaseStaticMapWidget): # class GoogleStaticOverlayMapWidget(GoogleStaticMapWidget): # class Media: # # Path: tests/testapp/widgets/tests/utils.py # def html_escape(html): # """Return the given HTML with ampersands, quotes and carets encoded.""" # return mark_safe(force_text(html).replace('&', '&amp;') # .replace('<', '&lt;').replace('>', '&gt;') # .replace('"', '&quot;').replace("'", '&#39;') # ) # # def get_textarea_html(html_id, name, point): # point_value = point.wkt if point else '' # return '<textarea id="{html_id}" name="{name}">{point}</textarea>'.format( # html_id=html_id, # name=name, # point=point_value # ) . Output only the next line.
reload_module(mw_widgets)
Given snippet: <|code_start|> def test_widget_with_default_settings(self): """ Test the widget with default settings which is defined in django settings file """ zoom = 13 map_size = "200x200" widget_settings = { "GoogleStaticMapWidget": ( ("zoom", zoom), ("size", map_size), ), "GOOGLE_MAP_API_KEY": GOOGLE_MAP_API_KEY, } with override_settings(MAP_WIDGETS=widget_settings): reload_module(mw_widgets) widget = mw_widgets.GoogleStaticMapWidget() settings = widget.map_settings # test `map_settings` method self.assertEqual(settings.get("zoom"), zoom) self.assertEqual(settings.get("size"), map_size) # test render point = Point(-105.9903, 38.7392) widget_html_elem_id = "id_location" widget_html_elem_name = "location" result = widget.render(name=widget_html_elem_name, value=point, attrs={'id': widget_html_elem_id}) map_image_url = widget.get_image_url(point) self.assertIn(GOOGLE_MAP_API_KEY, map_image_url) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import json from importlib import reload as reload_module from imp import reload as reload_module from urllib.request import urlopen from http.client import HTTPMessage from urllib import urlopen from django.test import TestCase from django.test.utils import override_settings from django.contrib.gis.geos import Point from django.utils.html import escapejs from django.conf import settings as test_app_settings from django import forms as django_forms from mapwidgets import widgets as mw_widgets from .utils import html_escape, get_textarea_html and context: # Path: mapwidgets/widgets.py # def minify_if_not_debug(asset): # def __init__(self, *args, **kwargs): # def map_options(self): # def media(self): # def render(self, name, value, attrs=None, renderer=None): # def media(self): # def render(self, name, value, attrs=None, renderer=None): # def get_js_widget_data(self, name, element_id): # def render(self, name, value, attrs=None, renderer=None): # def media(self): # def map_settings(self): # pragma: no cover # def marker_settings(self): # pragma: no cover # def get_template(self): # pragma: no cover # def get_image_url(self, value): # pragma: no cover # def get_context_data(self, name, value, attrs): # def render(self, name, value, attrs=None, renderer=None): # def __init__(self, zoom=None, size=None, *args, **kwargs): # def map_settings(self): # def marker_settings(self): # def get_point_field_params(self, latitude, longitude): # def get_image_url(self, value): # def __init__(self, zoom=None, size=None, thumbnail_size=None, *args, **kwargs): # def map_settings(self): # def get_thumbnail_url(self, value): # def get_context_data(self, name, value, attrs): # class BasePointFieldMapWidget(BaseGeometryWidget): # class GooglePointFieldWidget(BasePointFieldMapWidget): # class MapboxPointFieldWidget(BasePointFieldMapWidget): # class PointFieldInlineWidgetMixin(object): # class GooglePointFieldInlineWidget(PointFieldInlineWidgetMixin, GooglePointFieldWidget): # class BaseStaticMapWidget(forms.Widget): # class GoogleStaticMapWidget(BaseStaticMapWidget): # class GoogleStaticOverlayMapWidget(GoogleStaticMapWidget): # class Media: # # Path: tests/testapp/widgets/tests/utils.py # def html_escape(html): # """Return the given HTML with ampersands, quotes and carets encoded.""" # return mark_safe(force_text(html).replace('&', '&amp;') # .replace('<', '&lt;').replace('>', '&gt;') # .replace('"', '&quot;').replace("'", '&#39;') # ) # # def get_textarea_html(html_id, name, point): # point_value = point.wkt if point else '' # return '<textarea id="{html_id}" name="{name}">{point}</textarea>'.format( # html_id=html_id, # name=name, # point=point_value # ) which might include code, classes, or functions. Output only the next line.
self.assertIn(html_escape(map_image_url), result)
Given snippet: <|code_start|> Test the widget with default settings which is defined in django settings file """ zoom = 15 default_map_center = [51.5073509, -0.12775829999] widget_settings = { "GooglePointFieldWidget": ( ("zoom", zoom), ("mapCenterLocation", default_map_center), ) } with override_settings(MAP_WIDGETS=widget_settings): reload_module(mw_widgets) widget = mw_widgets.GooglePointFieldWidget() self.assertEqual(hasattr(widget, "settings"), True) self.assertEqual(hasattr(widget, "settings_namespace"), True) self.assertEqual(isinstance(widget.media, django_forms.Media), True) # test `map_options` method options_str = widget.map_options() options = json.loads(options_str) self.assertEqual(options.get("zoom"), zoom) self.assertEqual(options.get("mapCenterLocation"), default_map_center) # test render with Point object value point = Point(-104.9903, 39.7392, srid=DJANGO_DEFAULT_SRID_VALUE) widget_html_elem_id = "id_location" widget_html_elem_name = "location" result = widget.render(name=widget_html_elem_name, value=point, attrs={'id': widget_html_elem_id}) self.assertIn(widget.serialize(point), result) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import json from importlib import reload as reload_module from imp import reload as reload_module from urllib.request import urlopen from http.client import HTTPMessage from urllib import urlopen from django.test import TestCase from django.test.utils import override_settings from django.contrib.gis.geos import Point from django.utils.html import escapejs from django.conf import settings as test_app_settings from django import forms as django_forms from mapwidgets import widgets as mw_widgets from .utils import html_escape, get_textarea_html and context: # Path: mapwidgets/widgets.py # def minify_if_not_debug(asset): # def __init__(self, *args, **kwargs): # def map_options(self): # def media(self): # def render(self, name, value, attrs=None, renderer=None): # def media(self): # def render(self, name, value, attrs=None, renderer=None): # def get_js_widget_data(self, name, element_id): # def render(self, name, value, attrs=None, renderer=None): # def media(self): # def map_settings(self): # pragma: no cover # def marker_settings(self): # pragma: no cover # def get_template(self): # pragma: no cover # def get_image_url(self, value): # pragma: no cover # def get_context_data(self, name, value, attrs): # def render(self, name, value, attrs=None, renderer=None): # def __init__(self, zoom=None, size=None, *args, **kwargs): # def map_settings(self): # def marker_settings(self): # def get_point_field_params(self, latitude, longitude): # def get_image_url(self, value): # def __init__(self, zoom=None, size=None, thumbnail_size=None, *args, **kwargs): # def map_settings(self): # def get_thumbnail_url(self, value): # def get_context_data(self, name, value, attrs): # class BasePointFieldMapWidget(BaseGeometryWidget): # class GooglePointFieldWidget(BasePointFieldMapWidget): # class MapboxPointFieldWidget(BasePointFieldMapWidget): # class PointFieldInlineWidgetMixin(object): # class GooglePointFieldInlineWidget(PointFieldInlineWidgetMixin, GooglePointFieldWidget): # class BaseStaticMapWidget(forms.Widget): # class GoogleStaticMapWidget(BaseStaticMapWidget): # class GoogleStaticOverlayMapWidget(GoogleStaticMapWidget): # class Media: # # Path: tests/testapp/widgets/tests/utils.py # def html_escape(html): # """Return the given HTML with ampersands, quotes and carets encoded.""" # return mark_safe(force_text(html).replace('&', '&amp;') # .replace('<', '&lt;').replace('>', '&gt;') # .replace('"', '&quot;').replace("'", '&#39;') # ) # # def get_textarea_html(html_id, name, point): # point_value = point.wkt if point else '' # return '<textarea id="{html_id}" name="{name}">{point}</textarea>'.format( # html_id=html_id, # name=name, # point=point_value # ) which might include code, classes, or functions. Output only the next line.
self.assertIn(get_textarea_html(widget_html_elem_id, widget_html_elem_name, point), result)
Continue the code snippet: <|code_start|> def api(self): """ Return a list of API specifications to be used by auto-suggest and call tips. """ return [] def start(self): """ Start debugging the current script. """ # Grab the Python file. tab = self.view.current_tab if tab is None: logger.debug("There is no active text editor.") self.stop() return if tab.path is None: # Unsaved file. self.editor.save() if tab.path: # If needed, save the script. if tab.isModified(): self.editor.save_tab_to_file(tab) logger.debug(tab.text()) self.set_buttons(modes=False) envars = self.editor.envars cwd = os.path.dirname(tab.path) self.runner = self.view.add_python3_runner( <|code_end|> . Use current file imports: import logging import os from .base import BaseMode from ..debugger.config import DEBUGGER_PORT from ..debugger.client import Debugger from ..debugger.utils import is_breakpoint_line from ..virtual_environment import venv from PyQt5.QtCore import QTimer and context (classes, functions, or code) from other files: # Path: mu/virtual_environment.py # ENCODING = sys.stdout.encoding if hasattr(sys.stdout, "encoding") else "utf-8" # class VirtualEnvironmentError(Exception): # class VirtualEnvironmentEnsureError(VirtualEnvironmentError): # class VirtualEnvironmentCreateError(VirtualEnvironmentError): # class Process(QObject): # class Pip(object): # class SplashLogHandler(logging.NullHandler): # class VirtualEnvironment(object): # def __init__(self, message): # def compact(text): # def __init__(self): # def _set_up_run(self, **envvars): # def run_blocking(self, command, args, wait_for_s=30.0, **envvars): # def run(self, command, args, **envvars): # def wait(self, wait_for_s=30): # def data(self): # def _started(self): # def _readyRead(self): # def _finished(self): # def __init__(self, pip_executable): # def run( # self, command, *args, wait_for_s=120.0, slots=Process.Slots(), **kwargs # ): # def install(self, packages, slots=Process.Slots(), **kwargs): # def uninstall(self, packages, slots=Process.Slots(), **kwargs): # def freeze(self): # def list(self): # def installed(self): # def __init__(self, emitter): # def emit(self, record): # def handle(self, record): # def __init__(self, dirpath=None): # def __str__(self): # def _generate_dirpath(): # def run_subprocess(self, *args, **kwargs): # def reset_pip(self): # def relocate(self, dirpath): # def run_python(self, *args, slots=Process.Slots()): # def _directory_is_venv(self): # def quarantine_venv(self, reason="FAILED"): # def recreate(self): # def ensure_and_create(self, emitter=None): # def ensure(self): # def ensure_path(self): # def ensure_interpreter(self): # def ensure_interpreter_version(self): # def ensure_key_modules(self): # def ensure_pip(self): # def create(self): # def create_venv(self): # def install_jupyter_kernel(self): # def install_from_zipped_wheels(self, zipped_wheels_filepath): # def install_baseline_packages(self): # def register_baseline_packages(self): # def baseline_packages(self): # def install_user_packages(self, packages, slots=Process.Slots()): # def remove_user_packages(self, packages, slots=Process.Slots()): # def installed_packages(self): . Output only the next line.
venv.interpreter, tab.path, cwd, debugger=True, envars=envars
Continue the code snippet: <|code_start|> "ussl", "ustruct", "utime", "uzlib", "_thread", "btree", "framebuf", "machine", "micropython", "network", "ucryptolib", "uctypes", "pyb", "lcd160cr", } def actions(self): """ Return an ordered list of actions provided by this module. An action is a name (also used to identify the icon) , description, and handler. """ buttons = [ { "name": "serial", "display_name": _("Serial"), "description": _("Open a serial connection to your device."), "handler": self.toggle_repl, "shortcut": "CTRL+Shift+U", }, ] <|code_end|> . Use current file imports: import os import ctypes from subprocess import check_output from mu.modes.base import MicroPythonMode from mu.modes.api import PYBOARD_APIS, SHARED_APIS from mu.interface.panes import CHARTS and context (classes, functions, or code) from other files: # Path: mu/interface/panes.py # CHARTS = True . Output only the next line.
if CHARTS:
Given the following code snippet before the placeholder: <|code_start|> of the new child Python process. If running on Darwin, ensure that the correct encoding for the Python environment is used (Flask stop and complain about a misconfigured Python 3 using an ASCII encoding). """ mock_process = mock.MagicMock() mock_process_class = mock.MagicMock(return_value=mock_process) mock_merge_chans = mock.MagicMock() mock_process_class.MergedChannels = mock_merge_chans mock_environment = mock.MagicMock() mock_environment_class = mock.MagicMock() mock_environment_class.systemEnvironment.return_value = mock_environment interpreter = sys.executable script_filename = "script.py" with mock.patch( "mu.interface.panes.QProcess", mock_process_class ), mock.patch("mu.interface.panes.sys") as mock_sys, mock.patch( "mu.interface.panes.QProcessEnvironment", mock_environment_class ): mock_sys.platform = "darwin" ppp = mu.interface.panes.PythonProcessPane() envars = {"name": "value"} ppp.start_process( interpreter, script_filename, "workspace", interactive=False, envars=envars, ) <|code_end|> , predict the next line using imports from the current file: from PyQt5.QtWidgets import QMessageBox, QLabel, QMenu from PyQt5.QtCore import Qt, QEvent, QPointF, QUrl from PyQt5.QtGui import QTextCursor, QMouseEvent from collections import deque from unittest import mock from mu import i18n from mu.interface.panes import CHARTS from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE import sys import os import signal import pytest import mu import mu.interface.panes and context including class names, function names, and sometimes code from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/panes.py # CHARTS = True # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") . Output only the next line.
expected_encoding = "{}.utf-8".format(i18n.language_code)
Continue the code snippet: <|code_start|> """ Check the correct stylesheet values are being set. """ di = mu.interface.panes.DebugInspector() di.setStyleSheet = mock.MagicMock() di.set_font_size(16) style = di.setStyleSheet.call_args[0][0] assert "font-size: 16pt;" in style assert "font-family: Monospace;" in style def test_DebugInspector_set_zoom(): """ Ensure the expected point size is set from the given "t-shirt" size. """ di = mu.interface.panes.DebugInspector() di.set_font_size = mock.MagicMock() di.set_zoom("xl") expected = mu.interface.panes.PANE_ZOOM_SIZES["xl"] di.set_font_size.assert_called_once_with(expected) def test_DebugInspector_set_theme(): """ Setting the theme shouldn't do anything """ di = mu.interface.panes.DebugInspector() di.set_theme("test") <|code_end|> . Use current file imports: from PyQt5.QtWidgets import QMessageBox, QLabel, QMenu from PyQt5.QtCore import Qt, QEvent, QPointF, QUrl from PyQt5.QtGui import QTextCursor, QMouseEvent from collections import deque from unittest import mock from mu import i18n from mu.interface.panes import CHARTS from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE import sys import os import signal import pytest import mu import mu.interface.panes and context (classes, functions, or code) from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/panes.py # CHARTS = True # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") . Output only the next line.
@pytest.mark.skipif(not CHARTS, reason="QtChart unavailable")
Predict the next line after this snippet: <|code_start|> jw.on_append_text.emit.assert_called_once_with("hello".encode("utf-8")) def test_JupyterREPLPane_set_font_size(): """ Check the new point size is succesfully applied. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_font_size(16) assert jw.font.pointSize() == 16 def test_JupyterREPLPane_set_zoom(): """ Ensure the expected font point size is set from the zoom size. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_font_size = mock.MagicMock() jw.set_zoom("xxl") jw.set_font_size.assert_called_once_with( mu.interface.panes.PANE_ZOOM_SIZES["xxl"] ) def test_JupyterREPLPane_set_theme_day(): """ Make sure the theme is correctly set for day. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_theme("day") <|code_end|> using the current file's imports: from PyQt5.QtWidgets import QMessageBox, QLabel, QMenu from PyQt5.QtCore import Qt, QEvent, QPointF, QUrl from PyQt5.QtGui import QTextCursor, QMouseEvent from collections import deque from unittest import mock from mu import i18n from mu.interface.panes import CHARTS from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE import sys import os import signal import pytest import mu import mu.interface.panes and any relevant context from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/panes.py # CHARTS = True # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") . Output only the next line.
assert jw.style_sheet == DAY_STYLE
Given snippet: <|code_start|> def test_JupyterREPLPane_set_zoom(): """ Ensure the expected font point size is set from the zoom size. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_font_size = mock.MagicMock() jw.set_zoom("xxl") jw.set_font_size.assert_called_once_with( mu.interface.panes.PANE_ZOOM_SIZES["xxl"] ) def test_JupyterREPLPane_set_theme_day(): """ Make sure the theme is correctly set for day. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_theme("day") assert jw.style_sheet == DAY_STYLE assert jw.syntax_style == "default" def test_JupyterREPLPane_set_theme_night(): """ Make sure the theme is correctly set for night. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_theme("night") <|code_end|> , continue by predicting the next line. Consider current file imports: from PyQt5.QtWidgets import QMessageBox, QLabel, QMenu from PyQt5.QtCore import Qt, QEvent, QPointF, QUrl from PyQt5.QtGui import QTextCursor, QMouseEvent from collections import deque from unittest import mock from mu import i18n from mu.interface.panes import CHARTS from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE import sys import os import signal import pytest import mu import mu.interface.panes and context: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/panes.py # CHARTS = True # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") which might include code, classes, or functions. Output only the next line.
assert jw.style_sheet == NIGHT_STYLE
Predict the next line for this snippet: <|code_start|> mu.interface.panes.PANE_ZOOM_SIZES["xxl"] ) def test_JupyterREPLPane_set_theme_day(): """ Make sure the theme is correctly set for day. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_theme("day") assert jw.style_sheet == DAY_STYLE assert jw.syntax_style == "default" def test_JupyterREPLPane_set_theme_night(): """ Make sure the theme is correctly set for night. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_theme("night") assert jw.style_sheet == NIGHT_STYLE assert jw.syntax_style == "monokai" def test_JupyterREPLPane_set_theme_contrast(): """ Make sure the theme is correctly set for high contrast. """ jw = mu.interface.panes.JupyterREPLPane() jw.set_theme("contrast") <|code_end|> with the help of current file imports: from PyQt5.QtWidgets import QMessageBox, QLabel, QMenu from PyQt5.QtCore import Qt, QEvent, QPointF, QUrl from PyQt5.QtGui import QTextCursor, QMouseEvent from collections import deque from unittest import mock from mu import i18n from mu.interface.panes import CHARTS from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE import sys import os import signal import pytest import mu import mu.interface.panes and context from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/panes.py # CHARTS = True # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") , which may contain function names, class names, or code. Output only the next line.
assert jw.style_sheet == CONTRAST_STYLE
Predict the next line for this snippet: <|code_start|> # Valid links links = [] # Iterate over each of the urls attached to the event for url in event.mimeData().urls(): # Check the url is to a local file # (not a webpage for example) if url.isLocalFile(): # Grab a 'real' path from the url path = url.toLocalFile() # Add it to the list of valid links links.append(path) # Did we get any? if len(links) > 0: # Only accept now we actually know we can do # something with the drop event event.accept() for link in links: # Start bubbling an open file request self.open_file.emit(link) # If the event wasn't handled let QsciScintilla have a go if not event.isAccepted(): super().dropEvent(event) def configure(self): """ Set up the editor component. """ # Font information <|code_end|> with the help of current file imports: import keyword import os import re import logging import os.path from collections import defaultdict from PyQt5.Qsci import ( QsciScintilla, QsciLexerPython, QsciLexerHTML, QsciAPIs, QsciLexerCSS, ) from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtWidgets import QApplication from mu.interface.themes import Font, DayTheme from mu.logic import NEWLINE and context from other files: # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # class DayTheme(Theme): # """ # Defines a Python related theme including the various font colours for # syntax highlighting. # # This is a light theme. # """ # # FunctionMethodName = ClassName = Font(color="#0000a0") # UnclosedString = Font(paper="#FFDDDD") # Comment = CommentBlock = Font(color="gray") # Keyword = Font(color="#005050", bold=True) # SingleQuotedString = DoubleQuotedString = Font(color="#800000") # SingleQuotedFString = DoubleQuotedFString = Font(color="#800000") # TripleSingleQuotedString = TripleDoubleQuotedString = Font(color="#060") # TripleSingleQuotedFString = TripleDoubleQuotedFString = Font(color="#060") # Number = Font(color="#00008B") # Decorator = Font(color="#cc6600") # Default = Identifier = Font() # Operator = Font(color="#400040") # HighlightedIdentifier = Font(color="#0000a0") # Paper = QColor("#FEFEF7") # Caret = QColor("#181818") # Margin = QColor("#EEE") # IndicatorError = QColor("red") # IndicatorStyle = QColor("blue") # DebugStyle = QColor("#ffcc33") # IndicatorWordMatch = QColor("lightGrey") # BraceBackground = QColor("lightGrey") # BraceForeground = QColor("blue") # UnmatchedBraceBackground = QColor("#FFDDDD") # UnmatchedBraceForeground = QColor("black") # BreakpointMarker = QColor("#D80000") # # HTML # Tag = Keyword # UnknownTag = Tag # XMLTagEnd = Tag # XMLStart = Tag # XMLEnd = Tag # Attribute = ClassName # UnknownAttribute = Attribute # HTMLNumber = Number # HTMLDoubleQuotedString = DoubleQuotedString # HTMLSingleQuotedString = SingleQuotedString # OtherInTag = Default # HTMLComment = Comment # Entity = Operator # CDATA = Decorator # # CSS # ClassSelector = Tag # PseudoClass = ClassSelector # UnknownPseudoClass = ClassSelector # CSS1Property = ( # CSS2Property # ) = CSS3Property = UnknownProperty = SingleQuotedString # Value = Number # IDSelector = Tag # Important = UnmatchedBraceBackground # AtRule = Decorator # MediaRule = Decorator # Variable = HighlightedIdentifier # # Path: mu/logic.py # NEWLINE = "\n" , which may contain function names, class names, or code. Output only the next line.
font = Font().load()
Using the snippet: <|code_start|> # click handler to ignore clicks on this margin: self.connect_margin. self.setMarginWidth(4, 8) self.setMarginSensitivity(4, True) # Indicators self.setIndicatorDrawUnder(True) for type_ in self.check_indicators: self.indicatorDefine( self.SquiggleIndicator, self.check_indicators[type_]["id"] ) for type_ in self.search_indicators: self.indicatorDefine( self.StraightBoxIndicator, self.search_indicators[type_]["id"] ) self.indicatorDefine(self.FullBoxIndicator, self.DEBUG_INDICATOR) self.setAnnotationDisplay(self.AnnotationBoxed) self.selectionChanged.connect(self.selection_change_listener) self.set_zoom() def connect_margin(self, func): """ Connect clicking the margin to the passed in handler function, via a filtering handler that ignores clicks on margin 4. """ # Margin 4 motivation in self.configure comments. def func_ignoring_margin_4(margin, line, modifiers): if margin != 4: func(margin, line, modifiers) self.marginClicked.connect(func_ignoring_margin_4) <|code_end|> , determine the next line of code. You have imports: import keyword import os import re import logging import os.path from collections import defaultdict from PyQt5.Qsci import ( QsciScintilla, QsciLexerPython, QsciLexerHTML, QsciAPIs, QsciLexerCSS, ) from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtWidgets import QApplication from mu.interface.themes import Font, DayTheme from mu.logic import NEWLINE and context (class names, function names, or code) available: # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # class DayTheme(Theme): # """ # Defines a Python related theme including the various font colours for # syntax highlighting. # # This is a light theme. # """ # # FunctionMethodName = ClassName = Font(color="#0000a0") # UnclosedString = Font(paper="#FFDDDD") # Comment = CommentBlock = Font(color="gray") # Keyword = Font(color="#005050", bold=True) # SingleQuotedString = DoubleQuotedString = Font(color="#800000") # SingleQuotedFString = DoubleQuotedFString = Font(color="#800000") # TripleSingleQuotedString = TripleDoubleQuotedString = Font(color="#060") # TripleSingleQuotedFString = TripleDoubleQuotedFString = Font(color="#060") # Number = Font(color="#00008B") # Decorator = Font(color="#cc6600") # Default = Identifier = Font() # Operator = Font(color="#400040") # HighlightedIdentifier = Font(color="#0000a0") # Paper = QColor("#FEFEF7") # Caret = QColor("#181818") # Margin = QColor("#EEE") # IndicatorError = QColor("red") # IndicatorStyle = QColor("blue") # DebugStyle = QColor("#ffcc33") # IndicatorWordMatch = QColor("lightGrey") # BraceBackground = QColor("lightGrey") # BraceForeground = QColor("blue") # UnmatchedBraceBackground = QColor("#FFDDDD") # UnmatchedBraceForeground = QColor("black") # BreakpointMarker = QColor("#D80000") # # HTML # Tag = Keyword # UnknownTag = Tag # XMLTagEnd = Tag # XMLStart = Tag # XMLEnd = Tag # Attribute = ClassName # UnknownAttribute = Attribute # HTMLNumber = Number # HTMLDoubleQuotedString = DoubleQuotedString # HTMLSingleQuotedString = SingleQuotedString # OtherInTag = Default # HTMLComment = Comment # Entity = Operator # CDATA = Decorator # # CSS # ClassSelector = Tag # PseudoClass = ClassSelector # UnknownPseudoClass = ClassSelector # CSS1Property = ( # CSS2Property # ) = CSS3Property = UnknownProperty = SingleQuotedString # Value = Number # IDSelector = Tag # Important = UnmatchedBraceBackground # AtRule = Decorator # MediaRule = Decorator # Variable = HighlightedIdentifier # # Path: mu/logic.py # NEWLINE = "\n" . Output only the next line.
def set_theme(self, theme=DayTheme):
Given snippet: <|code_start|> else: return None return " ".join(kws) class CssLexer(QsciLexerCSS): """ Fixes problems with comments in CSS. """ def description(self, style): """ Ensures "Comment" is returned when the lexer encounters a comment (this is due to a bug in the base class, for which this is a work around). """ if style == QsciLexerCSS.Comment: return "Comment" return super().description(style) class EditorPane(QsciScintilla): """ Represents the text editor. """ # Signal fired when a script or hex is droped on this editor. open_file = pyqtSignal(str) # Signal fired when a context menu is requested. context_menu = pyqtSignal() <|code_end|> , continue by predicting the next line. Consider current file imports: import keyword import os import re import logging import os.path from collections import defaultdict from PyQt5.Qsci import ( QsciScintilla, QsciLexerPython, QsciLexerHTML, QsciAPIs, QsciLexerCSS, ) from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtWidgets import QApplication from mu.interface.themes import Font, DayTheme from mu.logic import NEWLINE and context: # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # class DayTheme(Theme): # """ # Defines a Python related theme including the various font colours for # syntax highlighting. # # This is a light theme. # """ # # FunctionMethodName = ClassName = Font(color="#0000a0") # UnclosedString = Font(paper="#FFDDDD") # Comment = CommentBlock = Font(color="gray") # Keyword = Font(color="#005050", bold=True) # SingleQuotedString = DoubleQuotedString = Font(color="#800000") # SingleQuotedFString = DoubleQuotedFString = Font(color="#800000") # TripleSingleQuotedString = TripleDoubleQuotedString = Font(color="#060") # TripleSingleQuotedFString = TripleDoubleQuotedFString = Font(color="#060") # Number = Font(color="#00008B") # Decorator = Font(color="#cc6600") # Default = Identifier = Font() # Operator = Font(color="#400040") # HighlightedIdentifier = Font(color="#0000a0") # Paper = QColor("#FEFEF7") # Caret = QColor("#181818") # Margin = QColor("#EEE") # IndicatorError = QColor("red") # IndicatorStyle = QColor("blue") # DebugStyle = QColor("#ffcc33") # IndicatorWordMatch = QColor("lightGrey") # BraceBackground = QColor("lightGrey") # BraceForeground = QColor("blue") # UnmatchedBraceBackground = QColor("#FFDDDD") # UnmatchedBraceForeground = QColor("black") # BreakpointMarker = QColor("#D80000") # # HTML # Tag = Keyword # UnknownTag = Tag # XMLTagEnd = Tag # XMLStart = Tag # XMLEnd = Tag # Attribute = ClassName # UnknownAttribute = Attribute # HTMLNumber = Number # HTMLDoubleQuotedString = DoubleQuotedString # HTMLSingleQuotedString = SingleQuotedString # OtherInTag = Default # HTMLComment = Comment # Entity = Operator # CDATA = Decorator # # CSS # ClassSelector = Tag # PseudoClass = ClassSelector # UnknownPseudoClass = ClassSelector # CSS1Property = ( # CSS2Property # ) = CSS3Property = UnknownProperty = SingleQuotedString # Value = Number # IDSelector = Tag # Important = UnmatchedBraceBackground # AtRule = Decorator # MediaRule = Decorator # Variable = HighlightedIdentifier # # Path: mu/logic.py # NEWLINE = "\n" which might include code, classes, or functions. Output only the next line.
def __init__(self, path, text, newline=NEWLINE):
Based on the snippet: <|code_start|> call_args = mock_shutil.rmtree.call_args_list assert call_args[0][0][0] == os.path.join("foo", "bar") assert call_args[1][0][0] == os.path.join("foo", "bin") pd.end_state.assert_called_once_with() @pytest.mark.skip( reason="Superseded probably by ntoll's previous work on venv" ) def test_PackageDialog_end_state(): """ Ensure the expected end-state is correctly cofigured (for when all tasks relating to third party packages have finished). """ pd = mu.interface.dialogs.PackageDialog() pd.append_data = mock.MagicMock() pd.button_box = mock.MagicMock() pd.end_state() pd.append_data.assert_called_once_with("\nFINISHED") pd.button_box.button().setEnabled.assert_called_once_with(True) @pytest.mark.skip(reason="Superseded probably by virtual environment work") def test_PackageDialog_run_pip(): """ Ensure the expected package to be installed is done so via the expected correct call to "pip" in a new process (as per the recommended way to us "pip"). """ pd = mu.interface.dialogs.PackageDialog() <|code_end|> , predict the immediate next line with the help of imports: import os import pytest import mu.interface.dialogs from PyQt5.QtWidgets import QDialog, QWidget, QDialogButtonBox from unittest import mock from mu import virtual_environment from mu.modes import ( PythonMode, CircuitPythonMode, MicrobitMode, DebugMode, ESPMode, ) from PyQt5.QtCore import QProcess and context (classes, functions, sometimes code) from other files: # Path: mu/virtual_environment.py # ENCODING = sys.stdout.encoding if hasattr(sys.stdout, "encoding") else "utf-8" # class VirtualEnvironmentError(Exception): # class VirtualEnvironmentEnsureError(VirtualEnvironmentError): # class VirtualEnvironmentCreateError(VirtualEnvironmentError): # class Process(QObject): # class Pip(object): # class SplashLogHandler(logging.NullHandler): # class VirtualEnvironment(object): # def __init__(self, message): # def compact(text): # def __init__(self): # def _set_up_run(self, **envvars): # def run_blocking(self, command, args, wait_for_s=30.0, **envvars): # def run(self, command, args, **envvars): # def wait(self, wait_for_s=30): # def data(self): # def _started(self): # def _readyRead(self): # def _finished(self): # def __init__(self, pip_executable): # def run( # self, command, *args, wait_for_s=120.0, slots=Process.Slots(), **kwargs # ): # def install(self, packages, slots=Process.Slots(), **kwargs): # def uninstall(self, packages, slots=Process.Slots(), **kwargs): # def freeze(self): # def list(self): # def installed(self): # def __init__(self, emitter): # def emit(self, record): # def handle(self, record): # def __init__(self, dirpath=None): # def __str__(self): # def _generate_dirpath(): # def run_subprocess(self, *args, **kwargs): # def reset_pip(self): # def relocate(self, dirpath): # def run_python(self, *args, slots=Process.Slots()): # def _directory_is_venv(self): # def quarantine_venv(self, reason="FAILED"): # def recreate(self): # def ensure_and_create(self, emitter=None): # def ensure(self): # def ensure_path(self): # def ensure_interpreter(self): # def ensure_interpreter_version(self): # def ensure_key_modules(self): # def ensure_pip(self): # def create(self): # def create_venv(self): # def install_jupyter_kernel(self): # def install_from_zipped_wheels(self, zipped_wheels_filepath): # def install_baseline_packages(self): # def register_baseline_packages(self): # def baseline_packages(self): # def install_user_packages(self, packages, slots=Process.Slots()): # def remove_user_packages(self, packages, slots=Process.Slots()): # def installed_packages(self): . Output only the next line.
venv = virtual_environment.VirtualEnvironment(".")
Based on the snippet: <|code_start|> If python_args is given, these are passed as arguments to the Python interpreter used to launch the child process. """ self.is_interactive = interactive if not envars: # Envars must be a dict if not passed a value. envars = {} envars = { name: v for (name, v) in envars.items() if name != "PYTHONPATH" } self.script = "" if script_name: self.script = os.path.abspath(os.path.normcase(script_name)) logger.info("Running script: {}".format(self.script)) logger.info("Using interpreter: {}".format(interpreter)) if interactive: logger.info("Running with interactive mode.") if command_args is None: command_args = [] logger.info("Command args: {}".format(command_args)) self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.MergedChannels) # Force buffers to flush immediately. env = QProcessEnvironment.systemEnvironment() env.insert("PYTHONUNBUFFERED", "1") env.insert("PYTHONIOENCODING", "utf-8") if sys.platform == "darwin": # Ensure the correct encoding is set for the environment. If the # following two lines are not set, then Flask will complain about # Python 3 being misconfigured to use ASCII encoding. # See: https://click.palletsprojects.com/en/7.x/python3/ <|code_end|> , predict the immediate next line with the help of imports: import sys import os import re import platform import logging import signal import string import bisect import os.path import codecs from PyQt5.QtCore import ( Qt, QProcess, QProcessEnvironment, pyqtSignal, QTimer, QUrl, ) from collections import deque from PyQt5.QtWidgets import ( QMessageBox, QTextEdit, QFrame, QListWidget, QGridLayout, QLabel, QMenu, QTreeView, ) from PyQt5.QtGui import ( QKeySequence, QTextCursor, QCursor, QPainter, QDesktopServices, QStandardItem, ) from qtconsole.rich_jupyter_widget import RichJupyterWidget from ..i18n import language_code from mu.interface.themes import Font, DEFAULT_FONT_SIZE from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE from PyQt5.QtChart import QChart, QLineSeries, QChartView, QValueAxis and context (classes, functions, sometimes code) from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # DEFAULT_FONT_SIZE = 14 # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") . Output only the next line.
encoding = "{}.utf-8".format(language_code)
Predict the next line for this snippet: <|code_start|> Override base setFocus so the focus happens to the embedded _control within this widget. """ self._control.setFocus() VT100_RETURN = b"\r" VT100_BACKSPACE = b"\b" VT100_DELETE = b"\x1B[\x33\x7E" VT100_UP = b"\x1B[A" VT100_DOWN = b"\x1B[B" VT100_RIGHT = b"\x1B[C" VT100_LEFT = b"\x1B[D" VT100_HOME = b"\x1B[H" VT100_END = b"\x1B[F" class MicroPythonREPLPane(QTextEdit): """ REPL = Read, Evaluate, Print, Loop. This widget represents a REPL client connected to a device running MicroPython. The device MUST be flashed with MicroPython for this to work. """ def __init__(self, connection, theme="day", parent=None): super().__init__(parent) self.connection = connection <|code_end|> with the help of current file imports: import sys import os import re import platform import logging import signal import string import bisect import os.path import codecs from PyQt5.QtCore import ( Qt, QProcess, QProcessEnvironment, pyqtSignal, QTimer, QUrl, ) from collections import deque from PyQt5.QtWidgets import ( QMessageBox, QTextEdit, QFrame, QListWidget, QGridLayout, QLabel, QMenu, QTreeView, ) from PyQt5.QtGui import ( QKeySequence, QTextCursor, QCursor, QPainter, QDesktopServices, QStandardItem, ) from qtconsole.rich_jupyter_widget import RichJupyterWidget from ..i18n import language_code from mu.interface.themes import Font, DEFAULT_FONT_SIZE from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE from PyQt5.QtChart import QChart, QLineSeries, QChartView, QValueAxis and context from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # DEFAULT_FONT_SIZE = 14 # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") , which may contain function names, class names, or code. Output only the next line.
self.setFont(Font().load())
Based on the snippet: <|code_start|> "s": 10, "m": 14, "l": 16, "xl": 18, "xxl": 24, "xxxl": 28, } class JupyterREPLPane(RichJupyterWidget): """ REPL = Read, Evaluate, Print, Loop. Displays a Jupyter iPython session. """ on_append_text = pyqtSignal(bytes) def __init__(self, theme="day", parent=None): super().__init__(parent) self.set_theme(theme) self.console_height = 10 def _append_plain_text(self, text, *args, **kwargs): """ Ensures appended text is emitted as a signal with associated bytes. """ super()._append_plain_text(text, *args, **kwargs) self.on_append_text.emit(text.encode("utf-8")) <|code_end|> , predict the immediate next line with the help of imports: import sys import os import re import platform import logging import signal import string import bisect import os.path import codecs from PyQt5.QtCore import ( Qt, QProcess, QProcessEnvironment, pyqtSignal, QTimer, QUrl, ) from collections import deque from PyQt5.QtWidgets import ( QMessageBox, QTextEdit, QFrame, QListWidget, QGridLayout, QLabel, QMenu, QTreeView, ) from PyQt5.QtGui import ( QKeySequence, QTextCursor, QCursor, QPainter, QDesktopServices, QStandardItem, ) from qtconsole.rich_jupyter_widget import RichJupyterWidget from ..i18n import language_code from mu.interface.themes import Font, DEFAULT_FONT_SIZE from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE from PyQt5.QtChart import QChart, QLineSeries, QChartView, QValueAxis and context (classes, functions, sometimes code) from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # DEFAULT_FONT_SIZE = 14 # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") . Output only the next line.
def set_font_size(self, new_size=DEFAULT_FONT_SIZE):
Continue the code snippet: <|code_start|> Ensures appended text is emitted as a signal with associated bytes. """ super()._append_plain_text(text, *args, **kwargs) self.on_append_text.emit(text.encode("utf-8")) def set_font_size(self, new_size=DEFAULT_FONT_SIZE): """ Sets the font size for all the textual elements in this pane. """ font = self.font font.setPointSize(new_size) self._set_font(font) def set_zoom(self, size): """ Set the current zoom level given the "t-shirt" size. """ self.set_font_size(PANE_ZOOM_SIZES[size]) def set_theme(self, theme): """ Sets the theme / look for the REPL pane. """ if theme == "contrast": self.style_sheet = CONTRAST_STYLE self.syntax_style = "bw" elif theme == "night": self.style_sheet = NIGHT_STYLE self.syntax_style = "monokai" else: <|code_end|> . Use current file imports: import sys import os import re import platform import logging import signal import string import bisect import os.path import codecs from PyQt5.QtCore import ( Qt, QProcess, QProcessEnvironment, pyqtSignal, QTimer, QUrl, ) from collections import deque from PyQt5.QtWidgets import ( QMessageBox, QTextEdit, QFrame, QListWidget, QGridLayout, QLabel, QMenu, QTreeView, ) from PyQt5.QtGui import ( QKeySequence, QTextCursor, QCursor, QPainter, QDesktopServices, QStandardItem, ) from qtconsole.rich_jupyter_widget import RichJupyterWidget from ..i18n import language_code from mu.interface.themes import Font, DEFAULT_FONT_SIZE from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE from PyQt5.QtChart import QChart, QLineSeries, QChartView, QValueAxis and context (classes, functions, or code) from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # DEFAULT_FONT_SIZE = 14 # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") . Output only the next line.
self.style_sheet = DAY_STYLE
Given snippet: <|code_start|> def _append_plain_text(self, text, *args, **kwargs): """ Ensures appended text is emitted as a signal with associated bytes. """ super()._append_plain_text(text, *args, **kwargs) self.on_append_text.emit(text.encode("utf-8")) def set_font_size(self, new_size=DEFAULT_FONT_SIZE): """ Sets the font size for all the textual elements in this pane. """ font = self.font font.setPointSize(new_size) self._set_font(font) def set_zoom(self, size): """ Set the current zoom level given the "t-shirt" size. """ self.set_font_size(PANE_ZOOM_SIZES[size]) def set_theme(self, theme): """ Sets the theme / look for the REPL pane. """ if theme == "contrast": self.style_sheet = CONTRAST_STYLE self.syntax_style = "bw" elif theme == "night": <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import os import re import platform import logging import signal import string import bisect import os.path import codecs from PyQt5.QtCore import ( Qt, QProcess, QProcessEnvironment, pyqtSignal, QTimer, QUrl, ) from collections import deque from PyQt5.QtWidgets import ( QMessageBox, QTextEdit, QFrame, QListWidget, QGridLayout, QLabel, QMenu, QTreeView, ) from PyQt5.QtGui import ( QKeySequence, QTextCursor, QCursor, QPainter, QDesktopServices, QStandardItem, ) from qtconsole.rich_jupyter_widget import RichJupyterWidget from ..i18n import language_code from mu.interface.themes import Font, DEFAULT_FONT_SIZE from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE from PyQt5.QtChart import QChart, QLineSeries, QChartView, QValueAxis and context: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # DEFAULT_FONT_SIZE = 14 # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") which might include code, classes, or functions. Output only the next line.
self.style_sheet = NIGHT_STYLE
Predict the next line for this snippet: <|code_start|> super().__init__(parent) self.set_theme(theme) self.console_height = 10 def _append_plain_text(self, text, *args, **kwargs): """ Ensures appended text is emitted as a signal with associated bytes. """ super()._append_plain_text(text, *args, **kwargs) self.on_append_text.emit(text.encode("utf-8")) def set_font_size(self, new_size=DEFAULT_FONT_SIZE): """ Sets the font size for all the textual elements in this pane. """ font = self.font font.setPointSize(new_size) self._set_font(font) def set_zoom(self, size): """ Set the current zoom level given the "t-shirt" size. """ self.set_font_size(PANE_ZOOM_SIZES[size]) def set_theme(self, theme): """ Sets the theme / look for the REPL pane. """ if theme == "contrast": <|code_end|> with the help of current file imports: import sys import os import re import platform import logging import signal import string import bisect import os.path import codecs from PyQt5.QtCore import ( Qt, QProcess, QProcessEnvironment, pyqtSignal, QTimer, QUrl, ) from collections import deque from PyQt5.QtWidgets import ( QMessageBox, QTextEdit, QFrame, QListWidget, QGridLayout, QLabel, QMenu, QTreeView, ) from PyQt5.QtGui import ( QKeySequence, QTextCursor, QCursor, QPainter, QDesktopServices, QStandardItem, ) from qtconsole.rich_jupyter_widget import RichJupyterWidget from ..i18n import language_code from mu.interface.themes import Font, DEFAULT_FONT_SIZE from mu.interface.themes import DAY_STYLE, NIGHT_STYLE, CONTRAST_STYLE from PyQt5.QtChart import QChart, QLineSeries, QChartView, QValueAxis and context from other files: # Path: mu/i18n.py # def set_language(language_code, localedir=localedir): # # Path: mu/interface/themes.py # class Font: # """ # Utility class that makes it easy to set font related values within the # editor. # """ # # _DATABASE = None # # def __init__( # self, color="#181818", paper="#FEFEF7", bold=False, italic=False # ): # self.color = color # self.paper = paper # self.bold = bold # self.italic = italic # # @classmethod # def get_database(cls): # """ # Create a font database and load the MU builtin fonts into it. # This is a cached classmethod so the font files aren't re-loaded # every time a font is refereced # """ # if cls._DATABASE is None: # cls._DATABASE = QFontDatabase() # for variant in FONT_VARIANTS: # filename = FONT_FILENAME_PATTERN.format(variant=variant) # font_data = load_font_data(filename) # cls._DATABASE.addApplicationFontFromData(font_data) # return cls._DATABASE # # def load(self, size=DEFAULT_FONT_SIZE): # """ # Load the font from the font database, using the correct size and style # """ # return Font.get_database().font(FONT_NAME, self.stylename, size) # # @property # def stylename(self): # """ # Map the bold and italic boolean flags here to a relevant # font style name. # """ # if self.bold: # if self.italic: # return "Semibold Italic" # return "Semibold" # if self.italic: # return "Italic" # return "Regular" # # DEFAULT_FONT_SIZE = 14 # # Path: mu/interface/themes.py # DAY_STYLE = load_stylesheet("day.css") # # NIGHT_STYLE = load_stylesheet("night.css") # # CONTRAST_STYLE = load_stylesheet("contrast.css") , which may contain function names, class names, or code. Output only the next line.
self.style_sheet = CONTRAST_STYLE
Based on the snippet: <|code_start|> "sys", "terminalio", "time", "touchio", "uheap", "usb_cdc", "usb_hid", "usb_midi", "ustack", "vectorio", "watchdog", "wifi", "wiznet", "zlib", } def actions(self): """ Return an ordered list of actions provided by this module. An action is a name (also used to identify the icon) , description, and handler. """ buttons = [ { "name": "serial", "display_name": _("Serial"), "description": _("Open a serial connection to your device."), "handler": self.toggle_repl, "shortcut": "CTRL+Shift+U", } ] <|code_end|> , predict the immediate next line with the help of imports: import os import ctypes import logging from subprocess import check_output from mu.modes.base import MicroPythonMode from mu.modes.api import ADAFRUIT_APIS, SHARED_APIS from mu.interface.panes import CHARTS from mu.logic import Device from adafruit_board_toolkit import circuitpython_serial and context (classes, functions, sometimes code) from other files: # Path: mu/interface/panes.py # CHARTS = True # # Path: mu/logic.py # class Device: # """ # Device object, containing both information about the connected device, # the port it's connected through and the mode it works with. # """ # # def __init__( # self, # vid, # pid, # port, # serial_number, # manufacturer, # long_mode_name, # short_mode_name, # board_name=None, # ): # self.vid = vid # self.pid = pid # self.port = port # self.serial_number = serial_number # self.manufacturer = manufacturer # self.long_mode_name = long_mode_name # self.short_mode_name = short_mode_name # self.board_name = board_name # # @property # def name(self): # """ # Returns the device name. # """ # if self.board_name: # return self.board_name # else: # return _("{} compatible").format(self.long_mode_name) # # def __eq__(self, other): # """ # Equality on devices. Comparison on vid, pid, and serial_number, # and most importantly also matches on which port the device is # connected to. That is, if two identical devices are connected # to separate ports they are considered different. # """ # return ( # isinstance(other, self.__class__) # and self.pid == other.pid # and self.vid == other.vid # and self.port == other.port # and self.serial_number == other.serial_number # ) # # def __ne__(self, other): # """ # Inequality of devices is the negation of equality # """ # return not self.__eq__(other) # # def __lt__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name < other.name # # def __gt__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name > other.name # # def __le__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name <= other.name # # def __ge__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name >= other.name # # def __str__(self): # """ # String representation of devices includes name, port, and VID/PID # """ # s = "{} on {} (VID: 0x{:04X}, PID: 0x{:04X})" # return s.format(self.name, self.port, self.vid, self.pid) # # def __hash__(self): # """ # Hash is the hash of the string representation, includes the same # elements in the hash as in equality testing. # """ # return hash(str(self)) . Output only the next line.
if CHARTS:
Predict the next line for this snippet: <|code_start|> wd = super().workspace_dir() if self.connected: m = _("Could not find an attached CircuitPython device.") info = _( "Python files for CircuitPython devices" " are stored on the device. Therefore, to edit" " these files you need to have the device plugged in." " Until you plug in a device, Mu will use the" " directory found here:\n\n" " {}\n\n...to store your code." ) self.view.show_message(m, info.format(wd)) self.connected = False return wd def compatible_board(self, port): """Use adafruit_board_toolkit to find out whether a board is running CircuitPython. The toolkit sees if the CDC Interface name is appropriate. """ pid = port.productIdentifier() vid = port.vendorIdentifier() manufacturer = port.manufacturer() serial_number = port.serialNumber() port_name = self.port_path(port.portName()) # Find all the CircuitPython REPL comports, # and see if any of their device names match the one passed in. for comport in circuitpython_serial.repl_comports(): if comport.device == port_name: <|code_end|> with the help of current file imports: import os import ctypes import logging from subprocess import check_output from mu.modes.base import MicroPythonMode from mu.modes.api import ADAFRUIT_APIS, SHARED_APIS from mu.interface.panes import CHARTS from mu.logic import Device from adafruit_board_toolkit import circuitpython_serial and context from other files: # Path: mu/interface/panes.py # CHARTS = True # # Path: mu/logic.py # class Device: # """ # Device object, containing both information about the connected device, # the port it's connected through and the mode it works with. # """ # # def __init__( # self, # vid, # pid, # port, # serial_number, # manufacturer, # long_mode_name, # short_mode_name, # board_name=None, # ): # self.vid = vid # self.pid = pid # self.port = port # self.serial_number = serial_number # self.manufacturer = manufacturer # self.long_mode_name = long_mode_name # self.short_mode_name = short_mode_name # self.board_name = board_name # # @property # def name(self): # """ # Returns the device name. # """ # if self.board_name: # return self.board_name # else: # return _("{} compatible").format(self.long_mode_name) # # def __eq__(self, other): # """ # Equality on devices. Comparison on vid, pid, and serial_number, # and most importantly also matches on which port the device is # connected to. That is, if two identical devices are connected # to separate ports they are considered different. # """ # return ( # isinstance(other, self.__class__) # and self.pid == other.pid # and self.vid == other.vid # and self.port == other.port # and self.serial_number == other.serial_number # ) # # def __ne__(self, other): # """ # Inequality of devices is the negation of equality # """ # return not self.__eq__(other) # # def __lt__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name < other.name # # def __gt__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name > other.name # # def __le__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name <= other.name # # def __ge__(self, other): # """ # Alphabetical ordering according to device name # """ # return self.name >= other.name # # def __str__(self): # """ # String representation of devices includes name, port, and VID/PID # """ # s = "{} on {} (VID: 0x{:04X}, PID: 0x{:04X})" # return s.format(self.name, self.port, self.vid, self.pid) # # def __hash__(self): # """ # Hash is the hash of the string representation, includes the same # elements in the hash as in equality testing. # """ # return hash(str(self)) , which may contain function names, class names, or code. Output only the next line.
return Device(
Using the snippet: <|code_start|>#!/usr/bin/env python3 """This is a test program for testing the code out on the host.""" sysname = os.uname().sysname if sysname == 'Linux' or sysname == 'Darwin': port = '/dev/ttyUSB0' try: port = SerialPort(port, 38400) except serial.serialutil.SerialException: print("Unable to open port '{}'".format(port)) sys.exit() elif sysname == 'pyboard': port = UART_Port(6, 38400) else: print("Unrecognized sysname: {}".format(sysname)) sys.exit() <|code_end|> , determine the next line of code. You have imports: import array import os import struct import sys import time import serial from commander_rx import CommanderRx from serial_port import SerialPort from serial_bus import SerialBus from stm_uart_port import UART_Port and context (class names, function names, or code) available: # Path: commander_rx.py # class CommanderRx(object): # """Parses packets from the commmander.""" # # NOT_DONE = 0 # SUCCESS = 1 # CHECKSUM = 2 # # def __init__(self): # self.index = -1 # self.checksum = 0 # self.pkt_bytes = bytearray(7) # self.lookv = 0 # self.lookh = 0 # self.walkv = 0 # self.walkh = 0 # self.button = 0 # self.ext = 0 # # def process_byte(self, byte): # """Runs a single byte through the packet parsing state amchine. # # Returns NOT_DONE if the packet is incomplete. # Returns SUCCESS is the packet was received successfully. # Returns CHECKSUM if a checksum error is detected. # """ # if self.index == -1: # if byte == 0xff: # self.index = 0 # self.checksum = 0 # elif self.index == 0: # if byte != 0xff: # self.checksum += byte # self.pkt_bytes[0] = byte # self.index += 1 # else: # self.checksum += byte # self.pkt_bytes[self.index] = byte # self.index += 1 # if self.index == 7: # packet complete # self.index = -1 # if self.checksum & 0xff != 0xff: # return CommanderRx.CHECKSUM # self.lookv = self.pkt_bytes[0] - 128 # 0 - 255 ==> -128 - 127 # self.lookh = self.pkt_bytes[1] - 128 # self.walkv = self.pkt_bytes[2] - 128 # self.walkh = self.pkt_bytes[3] - 128 # self.button = self.pkt_bytes[4] # self.ext = self.pkt_bytes[5] # return CommanderRx.SUCCESS # return CommanderRx.NOT_DONE . Output only the next line.
crx = CommanderRx()
Given the code snippet: <|code_start|>"""This module provides the Bus class which knows how to talk to Bioloid devices, and the BusError exception which is raised when an error is enountered. """ class BusError(Exception): """Exception which is raised when a non-successful status packet is received.""" def __init__(self, error_code, *args, **kwargs): super(BusError, self).__init__(self, *args, **kwargs) self.error_code = error_code def get_error_code(self): """Retrieves the error code associated with the exception.""" return self.error_code def __str__(self): <|code_end|> , generate the next line using the imports in this file: import pyb from bioloid import packet from bioloid.dump_mem import dump_mem from bioloid.log import log and context (functions, classes, or occasionally code) from other files: # Path: bioloid/packet.py # class Id: # class Command: # class ErrorCode: # class Packet: # BROADCAST = 0xFE # INVALID = 0xFF # PING = 0x01 # Used to obatin a status packet # READ = 0x02 # Read values from the control table # WRITE = 0x03 # Write values to control table # REG_WRITE = 0x04 # Prime values to write when ACTION sent # ACTION = 0x05 # Triggers REG_WRITE # RESET = 0x06 # Changes control values back to factory defaults # SYNC_WRITE = 0x83 # Writes values to many devices # RESERVED = 0x80 # Reserved - set to zero # INSTRUCTION = 0x40 # Undefined instruction # OVERLOAD = 0x20 # Max torque can't control applied load # CHECKSUM = 0x10 # Checksum of instruction packet incorrect # RANGE = 0x08 # Instruction is out of range # OVERHEATING = 0x04 # Internal temperature is too high # ANGLE_LIMIT = 0x02 # Goal position is outside of limit range # INPUT_VOLTAGE = 0x01 # Input voltage out of range # NONE = 0x00 # No Error # NOT_DONE = 0x100 # Special error code used by packet::ProcessChar # TIMEOUT = 0x101 # Indicates that a timeout occurred while waiting # TOO_MUCH_DATA = 0x102 # Packet storage isn't big enough # def __init__(self, dev_id): # def __repr__(self): # def __str__(self): # def get_dev_id(self): # def __init__(self, cmd): # def __repr__(self): # def __str__(self): # def parse(string): # def __init__(self, error_code): # def __repr__(self): # def __str__(self): # def parse(error_str): # def __init__(self, status_packet=False): # def param_byte(self, idx): # def params(self): # def param_len(self): # def error_code(self): # def error_code_str(self): # def process_byte(self, byte): # # Path: bioloid/dump_mem.py # def dump_mem(buf, prefix='', addr=0, line_width=16, show_ascii=True, # show_addr=True, log=print): # """Dumps out a hex/ASCII representation of the given buffer.""" # if line_width < 0: # line_width = 16 # if len(prefix) > 0: # prefix += ':' # if buf is None or len(buf) == 0: # log(prefix + 'No data') # return # buf_len = len(buf) # # Use a memoryview to prevent unnecessary allocations # buf_mv = memoryview(buf) # line_ascii = '' # ascii_offset = 0 # # prefix_bytes = bytes(prefix, 'utf-8') # prefix_len = len(prefix_bytes) # if prefix_len > 0: # prefix_len += 1 # For space between prefix and addr # max_len = prefix_len # if show_addr: # max_len += 6 # hex_offset = max_len # max_len += line_width * 3 - 1 # if show_ascii: # ascii_offset = max_len + 1 # max_len += line_width + 1 # out_line = memoryview(bytearray(max_len)) # if prefix_len > 0: # out_line[0:prefix_len-1] = prefix_bytes # out_line[prefix_len-1:prefix_len] = b' ' # # line_hex = out_line[hex_offset:hex_offset + (line_width * 3)] # if show_ascii: # # space between hex and ascii # out_line[ascii_offset-1:ascii_offset] = b' ' # line_ascii = out_line[ascii_offset:ascii_offset + line_width] # # for offset in range(0, buf_len, line_width): # if show_addr: # out_line[prefix_len:prefix_len + 6] \ # = bytes('{:04x}: '.format(addr), 'ascii') # line_bytes = min(buf_len - offset, line_width) # line_hex[0:(line_bytes * 3)-1] \ # = hexlify(buf_mv[offset:offset+line_bytes]) # out_len = hex_offset + line_bytes * 3 - 1 # if show_ascii: # if line_bytes < line_width: # for i in range(line_bytes * 3 - 1, line_width * 3): # line_hex[i:i+1] = b' ' # line_ascii[0:line_bytes] = buf_mv[offset:offset + line_bytes] # for i in range(line_bytes): # char = line_ascii[i] # if char < 0x20 or char > 0x7e: # line_ascii[i] = ord('.') # out_len = ascii_offset + line_bytes # log(bytes(out_line[0:out_len]).decode('utf-8')) # addr += line_width # # Path: bioloid/log.py # def log(*args): # """Make log call log_fn so that other modules can use: # # from log import log # # and then call log_to_xxx and have the changes take effect. # """ # log_fn(args) . Output only the next line.
return "Rcvd Status: " + str(packet.ErrorCode(self.error_code))
Next line prediction: <|code_start|> def __init__(self, error_code, *args, **kwargs): super(BusError, self).__init__(self, *args, **kwargs) self.error_code = error_code def get_error_code(self): """Retrieves the error code associated with the exception.""" return self.error_code def __str__(self): return "Rcvd Status: " + str(packet.ErrorCode(self.error_code)) class Bus: """The Bus class knows the commands used to talk to bioloid devices.""" SHOW_NONE = 0 SHOW_COMMANDS = (1 << 0) SHOW_PACKETS = (1 << 1) def __init__(self, serial_port, show=SHOW_NONE): self.serial_port = serial_port self.show = show def action(self): """Broadcasts an action packet to all of the devices on the bus. This causes all of the devices to perform their deferred writes at the same time. """ if self.show & Bus.SHOW_COMMANDS: <|code_end|> . Use current file imports: (import pyb from bioloid import packet from bioloid.dump_mem import dump_mem from bioloid.log import log) and context including class names, function names, or small code snippets from other files: # Path: bioloid/packet.py # class Id: # class Command: # class ErrorCode: # class Packet: # BROADCAST = 0xFE # INVALID = 0xFF # PING = 0x01 # Used to obatin a status packet # READ = 0x02 # Read values from the control table # WRITE = 0x03 # Write values to control table # REG_WRITE = 0x04 # Prime values to write when ACTION sent # ACTION = 0x05 # Triggers REG_WRITE # RESET = 0x06 # Changes control values back to factory defaults # SYNC_WRITE = 0x83 # Writes values to many devices # RESERVED = 0x80 # Reserved - set to zero # INSTRUCTION = 0x40 # Undefined instruction # OVERLOAD = 0x20 # Max torque can't control applied load # CHECKSUM = 0x10 # Checksum of instruction packet incorrect # RANGE = 0x08 # Instruction is out of range # OVERHEATING = 0x04 # Internal temperature is too high # ANGLE_LIMIT = 0x02 # Goal position is outside of limit range # INPUT_VOLTAGE = 0x01 # Input voltage out of range # NONE = 0x00 # No Error # NOT_DONE = 0x100 # Special error code used by packet::ProcessChar # TIMEOUT = 0x101 # Indicates that a timeout occurred while waiting # TOO_MUCH_DATA = 0x102 # Packet storage isn't big enough # def __init__(self, dev_id): # def __repr__(self): # def __str__(self): # def get_dev_id(self): # def __init__(self, cmd): # def __repr__(self): # def __str__(self): # def parse(string): # def __init__(self, error_code): # def __repr__(self): # def __str__(self): # def parse(error_str): # def __init__(self, status_packet=False): # def param_byte(self, idx): # def params(self): # def param_len(self): # def error_code(self): # def error_code_str(self): # def process_byte(self, byte): # # Path: bioloid/dump_mem.py # def dump_mem(buf, prefix='', addr=0, line_width=16, show_ascii=True, # show_addr=True, log=print): # """Dumps out a hex/ASCII representation of the given buffer.""" # if line_width < 0: # line_width = 16 # if len(prefix) > 0: # prefix += ':' # if buf is None or len(buf) == 0: # log(prefix + 'No data') # return # buf_len = len(buf) # # Use a memoryview to prevent unnecessary allocations # buf_mv = memoryview(buf) # line_ascii = '' # ascii_offset = 0 # # prefix_bytes = bytes(prefix, 'utf-8') # prefix_len = len(prefix_bytes) # if prefix_len > 0: # prefix_len += 1 # For space between prefix and addr # max_len = prefix_len # if show_addr: # max_len += 6 # hex_offset = max_len # max_len += line_width * 3 - 1 # if show_ascii: # ascii_offset = max_len + 1 # max_len += line_width + 1 # out_line = memoryview(bytearray(max_len)) # if prefix_len > 0: # out_line[0:prefix_len-1] = prefix_bytes # out_line[prefix_len-1:prefix_len] = b' ' # # line_hex = out_line[hex_offset:hex_offset + (line_width * 3)] # if show_ascii: # # space between hex and ascii # out_line[ascii_offset-1:ascii_offset] = b' ' # line_ascii = out_line[ascii_offset:ascii_offset + line_width] # # for offset in range(0, buf_len, line_width): # if show_addr: # out_line[prefix_len:prefix_len + 6] \ # = bytes('{:04x}: '.format(addr), 'ascii') # line_bytes = min(buf_len - offset, line_width) # line_hex[0:(line_bytes * 3)-1] \ # = hexlify(buf_mv[offset:offset+line_bytes]) # out_len = hex_offset + line_bytes * 3 - 1 # if show_ascii: # if line_bytes < line_width: # for i in range(line_bytes * 3 - 1, line_width * 3): # line_hex[i:i+1] = b' ' # line_ascii[0:line_bytes] = buf_mv[offset:offset + line_bytes] # for i in range(line_bytes): # char = line_ascii[i] # if char < 0x20 or char > 0x7e: # line_ascii[i] = ord('.') # out_len = ascii_offset + line_bytes # log(bytes(out_line[0:out_len]).decode('utf-8')) # addr += line_width # # Path: bioloid/log.py # def log(*args): # """Make log call log_fn so that other modules can use: # # from log import log # # and then call log_to_xxx and have the changes take effect. # """ # log_fn(args) . Output only the next line.
log('Broadcasting ACTION')
Given the following code snippet before the placeholder: <|code_start|>"""This module implements the UART_Port class which talks to bioloid devices using a UART on the pyboard. """ class UART_Port: """Implements a port which can send or receive commands with a bioloid device using the pyboard UART class. This particular class takes advantage of some features which are only available on the STM32F4xx processors. """ def __init__(self, uart_num, baud, rx_buf_len=64): <|code_end|> , predict the next line using imports from the current file: import stm from pyb import UART and context including class names, function names, and sometimes code from other files: # Path: pyb.py # class ADC(object): # class Pin(object): # def __init__(self, name): # def read(self): # def __str__(self): # def __init__(self, name): # def init(self, mode, pull): # def value(self, val=None): # def __str__(self): # IN = 'in' # OUT_PP = 'out_pp' # OUT_OD = 'out_od' # PULL_NONE = 'pull_none' # PULL_UP = 'pull_up' # PULL_DOWN = 'pull_down' . Output only the next line.
self.uart = UART(uart_num)
Given snippet: <|code_start|>"""This module implements the UART_Port class which talks to bioloid devices using a UART on the pyboard. """ class UART_GPIO_Port: """Implements a port which can send or receive commands with a bioloid device using the pyboard UART class. This class assumes that there is an active HIGH GPIO line used to indicate transmitting (i.e. connected to something like an external 74AHCT1G126) """ def __init__(self, uart_num, baud, control_pin, rx_buf_len=64): <|code_end|> , continue by predicting the next line. Consider current file imports: import stm from pyb import UART and context: # Path: pyb.py # class ADC(object): # class Pin(object): # def __init__(self, name): # def read(self): # def __str__(self): # def __init__(self, name): # def init(self, mode, pull): # def value(self, val=None): # def __str__(self): # IN = 'in' # OUT_PP = 'out_pp' # OUT_OD = 'out_od' # PULL_NONE = 'pull_none' # PULL_UP = 'pull_up' # PULL_DOWN = 'pull_down' which might include code, classes, or functions. Output only the next line.
self.uart = UART(uart_num)
Using the snippet: <|code_start|>"""This module implements the USB_Port class which allows the pyboard to implement bioloid devices using the pyboard's USB Serial. """ class USB_Port: """Implements a port which can be used to receive bioloid device commands from a host. """ def __init__(self): <|code_end|> , determine the next line of code. You have imports: from pyb import USB_VCP and context (class names, function names, or code) available: # Path: pyb.py # class ADC(object): # class Pin(object): # def __init__(self, name): # def read(self): # def __str__(self): # def __init__(self, name): # def init(self, mode, pull): # def value(self, val=None): # def __str__(self): # IN = 'in' # OUT_PP = 'out_pp' # OUT_OD = 'out_od' # PULL_NONE = 'pull_none' # PULL_UP = 'pull_up' # PULL_DOWN = 'pull_down' . Output only the next line.
self.usb_serial = USB_VCP()
Using the snippet: <|code_start|>#!/usr/bin/env python3 # This file tests the packet parser PREFIX = ' Prefix' class TestDumpMem(unittest.TestCase): def clear_log(self): self.log_lines = [] def log(self, str): self.log_lines.append(str) #print(str) def test_empty_buffer(self): self.clear_log() <|code_end|> , determine the next line of code. You have imports: import unittest import binascii from bioloid.dump_mem import dump_mem and context (class names, function names, or code) available: # Path: bioloid/dump_mem.py # def dump_mem(buf, prefix='', addr=0, line_width=16, show_ascii=True, # show_addr=True, log=print): # """Dumps out a hex/ASCII representation of the given buffer.""" # if line_width < 0: # line_width = 16 # if len(prefix) > 0: # prefix += ':' # if buf is None or len(buf) == 0: # log(prefix + 'No data') # return # buf_len = len(buf) # # Use a memoryview to prevent unnecessary allocations # buf_mv = memoryview(buf) # line_ascii = '' # ascii_offset = 0 # # prefix_bytes = bytes(prefix, 'utf-8') # prefix_len = len(prefix_bytes) # if prefix_len > 0: # prefix_len += 1 # For space between prefix and addr # max_len = prefix_len # if show_addr: # max_len += 6 # hex_offset = max_len # max_len += line_width * 3 - 1 # if show_ascii: # ascii_offset = max_len + 1 # max_len += line_width + 1 # out_line = memoryview(bytearray(max_len)) # if prefix_len > 0: # out_line[0:prefix_len-1] = prefix_bytes # out_line[prefix_len-1:prefix_len] = b' ' # # line_hex = out_line[hex_offset:hex_offset + (line_width * 3)] # if show_ascii: # # space between hex and ascii # out_line[ascii_offset-1:ascii_offset] = b' ' # line_ascii = out_line[ascii_offset:ascii_offset + line_width] # # for offset in range(0, buf_len, line_width): # if show_addr: # out_line[prefix_len:prefix_len + 6] \ # = bytes('{:04x}: '.format(addr), 'ascii') # line_bytes = min(buf_len - offset, line_width) # line_hex[0:(line_bytes * 3)-1] \ # = hexlify(buf_mv[offset:offset+line_bytes]) # out_len = hex_offset + line_bytes * 3 - 1 # if show_ascii: # if line_bytes < line_width: # for i in range(line_bytes * 3 - 1, line_width * 3): # line_hex[i:i+1] = b' ' # line_ascii[0:line_bytes] = buf_mv[offset:offset + line_bytes] # for i in range(line_bytes): # char = line_ascii[i] # if char < 0x20 or char > 0x7e: # line_ascii[i] = ord('.') # out_len = ascii_offset + line_bytes # log(bytes(out_line[0:out_len]).decode('utf-8')) # addr += line_width . Output only the next line.
dump_mem(b'', prefix=PREFIX, log=self.log)
Using the snippet: <|code_start|> context = self._get_context() context.setdefault('media_license', attrs_d) self.push('license', 1) def _end_media_license(self): license_ = self.pop('license') if license_ is not None and license_.strip(): context = self._get_context() context['media_license']['content'] = license_ def _start_media_content(self, attrs_d): context = self._get_context() context.setdefault('media_content', []) context['media_content'].append(attrs_d) def _start_media_thumbnail(self, attrs_d): context = self._get_context() context.setdefault('media_thumbnail', []) self.push('url', 1) # new context['media_thumbnail'].append(attrs_d) def _end_media_thumbnail(self): url = self.pop('url') context = self._get_context() if url is not None and url.strip(): if 'url' not in context['media_thumbnail'][-1]: context['media_thumbnail'][-1]['url'] = url def _start_media_player(self, attrs_d): self.push('media_player', 0) <|code_end|> , determine the next line of code. You have imports: from ..util import FeedParserDict and context (class names, function names, or code) available: # Path: src/bin/syndication_app/feedparser/util.py # class FeedParserDict(dict): # keymap = { # 'channel': 'feed', # 'items': 'entries', # 'guid': 'id', # 'date': 'updated', # 'date_parsed': 'updated_parsed', # 'description': ['summary', 'subtitle'], # 'description_detail': ['summary_detail', 'subtitle_detail'], # 'url': ['href'], # 'modified': 'updated', # 'modified_parsed': 'updated_parsed', # 'issued': 'published', # 'issued_parsed': 'published_parsed', # 'copyright': 'rights', # 'copyright_detail': 'rights_detail', # 'tagline': 'subtitle', # 'tagline_detail': 'subtitle_detail', # } # # def __getitem__(self, key): # """ # :return: A :class:`FeedParserDict`. # """ # # if key == 'category': # try: # return dict.__getitem__(self, 'tags')[0]['term'] # except IndexError: # raise KeyError("object doesn't have key 'category'") # elif key == 'enclosures': # norel = lambda link: FeedParserDict([(name, value) for (name, value) in link.items() if name != 'rel']) # return [ # norel(link) # for link in dict.__getitem__(self, 'links') # if link['rel'] == 'enclosure' # ] # elif key == 'license': # for link in dict.__getitem__(self, 'links'): # if link['rel'] == 'license' and 'href' in link: # return link['href'] # elif key == 'updated': # # Temporarily help developers out by keeping the old # # broken behavior that was reported in issue 310. # # This fix was proposed in issue 328. # if ( # not dict.__contains__(self, 'updated') # and dict.__contains__(self, 'published') # ): # warnings.warn( # "To avoid breaking existing software while " # "fixing issue 310, a temporary mapping has been created " # "from `updated` to `published` if `updated` doesn't " # "exist. This fallback will be removed in a future version " # "of feedparser.", # DeprecationWarning, # ) # return dict.__getitem__(self, 'published') # return dict.__getitem__(self, 'updated') # elif key == 'updated_parsed': # if ( # not dict.__contains__(self, 'updated_parsed') # and dict.__contains__(self, 'published_parsed') # ): # warnings.warn( # "To avoid breaking existing software while " # "fixing issue 310, a temporary mapping has been created " # "from `updated_parsed` to `published_parsed` if " # "`updated_parsed` doesn't exist. This fallback will be " # "removed in a future version of feedparser.", # DeprecationWarning, # ) # return dict.__getitem__(self, 'published_parsed') # return dict.__getitem__(self, 'updated_parsed') # else: # realkey = self.keymap.get(key, key) # if isinstance(realkey, list): # for k in realkey: # if dict.__contains__(self, k): # return dict.__getitem__(self, k) # elif dict.__contains__(self, realkey): # return dict.__getitem__(self, realkey) # return dict.__getitem__(self, key) # # def __contains__(self, key): # if key in ('updated', 'updated_parsed'): # # Temporarily help developers out by keeping the old # # broken behavior that was reported in issue 310. # # This fix was proposed in issue 328. # return dict.__contains__(self, key) # try: # self.__getitem__(key) # except KeyError: # return False # else: # return True # # has_key = __contains__ # # def get(self, key, default=None): # """ # :return: A :class:`FeedParserDict`. # """ # # try: # return self.__getitem__(key) # except KeyError: # return default # # def __setitem__(self, key, value): # key = self.keymap.get(key, key) # if isinstance(key, list): # key = key[0] # return dict.__setitem__(self, key, value) # # def setdefault(self, k, default): # if k not in self: # self[k] = default # return default # return self[k] # # def __getattr__(self, key): # # __getattribute__() is called first; this will be called # # only if an attribute was not already found # try: # return self.__getitem__(key) # except KeyError: # raise AttributeError("object has no attribute '%s'" % key) # # def __hash__(self): # # This is incorrect behavior -- dictionaries shouldn't be hashable. # # Note to self: remove this behavior in the future. # return id(self) . Output only the next line.
self._get_context()['media_player'] = FeedParserDict(attrs_d)
Based on the snippet: <|code_start|> super(_StrictFeedParser, self).__init__() @staticmethod def _normalize_attributes(kv): k = kv[0].lower() v = k in ('rel', 'type') and kv[1].lower() or kv[1] return k, v def startPrefixMapping(self, prefix, uri): if not uri: return # Jython uses '' instead of None; standardize on None prefix = prefix or None self.track_namespace(prefix, uri) if prefix and uri == 'http://www.w3.org/1999/xlink': self.decls['xmlns:' + prefix] = uri def startElementNS(self, name, qname, attrs): namespace, localname = name lowernamespace = str(namespace or '').lower() if lowernamespace.find('backend.userland.com/rss') != -1: # match any backend.userland.com namespace namespace = 'http://backend.userland.com/rss' lowernamespace = namespace if qname and qname.find(':') > 0: givenprefix = qname.split(':')[0] else: givenprefix = None prefix = self._matchnamespaces.get(lowernamespace, givenprefix) if givenprefix and (prefix is None or (prefix == '' and lowernamespace == '')) and givenprefix not in self.namespaces_in_use: <|code_end|> , predict the immediate next line with the help of imports: from ..exceptions import UndeclaredNamespace and context (classes, functions, sometimes code) from other files: # Path: src/bin/syndication_app/feedparser/exceptions.py # class UndeclaredNamespace(Exception): # pass . Output only the next line.
raise UndeclaredNamespace("'%s' is not associated with a namespace" % givenprefix)
Given the following code snippet before the placeholder: <|code_start|># CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import from __future__ import unicode_literals class Namespace(object): supported_namespaces = { # RDF-based namespace 'http://creativecommons.org/ns#license': 'cc', # Old RDF-based namespace 'http://web.resource.org/cc/': 'cc', # RSS-based namespace 'http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html': 'creativecommons', # Old RSS-based namespace 'http://backend.userland.com/creativeCommonsRssModule': 'creativecommons', } def _start_cc_license(self, attrs_d): context = self._get_context() value = self._get_attribute(attrs_d, 'rdf:resource') <|code_end|> , predict the next line using imports from the current file: from ..util import FeedParserDict and context including class names, function names, and sometimes code from other files: # Path: src/bin/syndication_app/feedparser/util.py # class FeedParserDict(dict): # keymap = { # 'channel': 'feed', # 'items': 'entries', # 'guid': 'id', # 'date': 'updated', # 'date_parsed': 'updated_parsed', # 'description': ['summary', 'subtitle'], # 'description_detail': ['summary_detail', 'subtitle_detail'], # 'url': ['href'], # 'modified': 'updated', # 'modified_parsed': 'updated_parsed', # 'issued': 'published', # 'issued_parsed': 'published_parsed', # 'copyright': 'rights', # 'copyright_detail': 'rights_detail', # 'tagline': 'subtitle', # 'tagline_detail': 'subtitle_detail', # } # # def __getitem__(self, key): # """ # :return: A :class:`FeedParserDict`. # """ # # if key == 'category': # try: # return dict.__getitem__(self, 'tags')[0]['term'] # except IndexError: # raise KeyError("object doesn't have key 'category'") # elif key == 'enclosures': # norel = lambda link: FeedParserDict([(name, value) for (name, value) in link.items() if name != 'rel']) # return [ # norel(link) # for link in dict.__getitem__(self, 'links') # if link['rel'] == 'enclosure' # ] # elif key == 'license': # for link in dict.__getitem__(self, 'links'): # if link['rel'] == 'license' and 'href' in link: # return link['href'] # elif key == 'updated': # # Temporarily help developers out by keeping the old # # broken behavior that was reported in issue 310. # # This fix was proposed in issue 328. # if ( # not dict.__contains__(self, 'updated') # and dict.__contains__(self, 'published') # ): # warnings.warn( # "To avoid breaking existing software while " # "fixing issue 310, a temporary mapping has been created " # "from `updated` to `published` if `updated` doesn't " # "exist. This fallback will be removed in a future version " # "of feedparser.", # DeprecationWarning, # ) # return dict.__getitem__(self, 'published') # return dict.__getitem__(self, 'updated') # elif key == 'updated_parsed': # if ( # not dict.__contains__(self, 'updated_parsed') # and dict.__contains__(self, 'published_parsed') # ): # warnings.warn( # "To avoid breaking existing software while " # "fixing issue 310, a temporary mapping has been created " # "from `updated_parsed` to `published_parsed` if " # "`updated_parsed` doesn't exist. This fallback will be " # "removed in a future version of feedparser.", # DeprecationWarning, # ) # return dict.__getitem__(self, 'published_parsed') # return dict.__getitem__(self, 'updated_parsed') # else: # realkey = self.keymap.get(key, key) # if isinstance(realkey, list): # for k in realkey: # if dict.__contains__(self, k): # return dict.__getitem__(self, k) # elif dict.__contains__(self, realkey): # return dict.__getitem__(self, realkey) # return dict.__getitem__(self, key) # # def __contains__(self, key): # if key in ('updated', 'updated_parsed'): # # Temporarily help developers out by keeping the old # # broken behavior that was reported in issue 310. # # This fix was proposed in issue 328. # return dict.__contains__(self, key) # try: # self.__getitem__(key) # except KeyError: # return False # else: # return True # # has_key = __contains__ # # def get(self, key, default=None): # """ # :return: A :class:`FeedParserDict`. # """ # # try: # return self.__getitem__(key) # except KeyError: # return default # # def __setitem__(self, key, value): # key = self.keymap.get(key, key) # if isinstance(key, list): # key = key[0] # return dict.__setitem__(self, key, value) # # def setdefault(self, k, default): # if k not in self: # self[k] = default # return default # return self[k] # # def __getattr__(self, key): # # __getattribute__() is called first; this will be called # # only if an attribute was not already found # try: # return self.__getitem__(key) # except KeyError: # raise AttributeError("object has no attribute '%s'" % key) # # def __hash__(self): # # This is incorrect behavior -- dictionaries shouldn't be hashable. # # Note to self: remove this behavior in the future. # return id(self) . Output only the next line.
attrs_d = FeedParserDict()
Given the following code snippet before the placeholder: <|code_start|> 'szeptember': '09', 'okt\u00f3ber': '10', # f3 in iso-8859-2 'november': '11', 'december': '12', } _hungarian_date_format_re = re.compile(r'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))') def _parse_date_hungarian(date_string): """Parse a string according to a Hungarian 8-bit date format.""" m = _hungarian_date_format_re.match(date_string) if not m or m.group(2) not in _hungarian_months: return None month = _hungarian_months[m.group(2)] day = m.group(3) if len(day) == 1: day = '0' + day hour = m.group(4) if len(hour) == 1: hour = '0' + hour w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \ { 'year': m.group(1), 'month': month, 'day': day, 'hour': hour, 'minute': m.group(5), 'zonediff': m.group(6), } <|code_end|> , predict the next line using imports from the current file: import re from .w3dtf import _parse_date_w3dtf and context including class names, function names, and sometimes code from other files: # Path: src/bin/syndication_app/feedparser/datetimes/w3dtf.py # def _parse_date_w3dtf(datestr): # if not datestr.strip(): # return None # parts = datestr.lower().split('t') # if len(parts) == 1: # # This may be a date only, or may be an MSSQL-style date # parts = parts[0].split() # if len(parts) == 1: # # Treat this as a date only # parts.append('00:00:00z') # elif len(parts) > 2: # return None # date = parts[0].split('-', 2) # if not date or len(date[0]) != 4: # return None # # Ensure that `date` has 3 elements. Using '1' sets the default # # month to January and the default day to the 1st of the month. # date.extend(['1'] * (3 - len(date))) # try: # year, month, day = [int(i) for i in date] # except ValueError: # # `date` may have more than 3 elements or may contain # # non-integer strings. # return None # if parts[1].endswith('z'): # parts[1] = parts[1][:-1] # parts.append('z') # # Append the numeric timezone offset, if any, to parts. # # If this is an MSSQL-style date then parts[2] already contains # # the timezone information, so `append()` will not affect it. # # Add 1 to each value so that if `find()` returns -1 it will be # # treated as False. # loc = parts[1].find('-') + 1 or parts[1].find('+') + 1 or len(parts[1]) + 1 # loc = loc - 1 # parts.append(parts[1][loc:]) # parts[1] = parts[1][:loc] # time = parts[1].split(':', 2) # # Ensure that time has 3 elements. Using '0' means that the # # minutes and seconds, if missing, will default to 0. # time.extend(['0'] * (3 - len(time))) # if parts[2][:1] in ('-', '+'): # try: # tzhour = int(parts[2][1:3]) # tzmin = int(parts[2][4:]) # except ValueError: # return None # if parts[2].startswith('-'): # tzhour = tzhour * -1 # tzmin = tzmin * -1 # else: # tzhour = timezonenames.get(parts[2], 0) # tzmin = 0 # try: # hour, minute, second = [int(float(i)) for i in time] # except ValueError: # return None # # Create the datetime object and timezone delta objects # try: # stamp = datetime.datetime(year, month, day, hour, minute, second) # except ValueError: # return None # delta = datetime.timedelta(0, 0, 0, 0, tzmin, tzhour) # # Return the date and timestamp in a UTC 9-tuple # try: # return (stamp - delta).utctimetuple() # except (OverflowError, ValueError): # # IronPython throws ValueErrors instead of OverflowErrors # return None . Output only the next line.
return _parse_date_w3dtf(w3dtfdate)
Predict the next line for this snippet: <|code_start|> lazy_chardet_encoding, 'utf-8', 'windows-1252', 'iso-8859-2'): if callable(proposed_encoding): proposed_encoding = proposed_encoding(data) if not proposed_encoding: continue if proposed_encoding in tried_encodings: continue tried_encodings.append(proposed_encoding) try: data = data.decode(proposed_encoding) except (UnicodeDecodeError, LookupError): pass else: known_encoding = 1 # Update the encoding in the opening XML processing instruction. new_declaration = '''<?xml version='1.0' encoding='utf-8'?>''' if RE_XML_DECLARATION.search(data): data = RE_XML_DECLARATION.sub(new_declaration, data) else: data = new_declaration + '\n' + data data = data.encode('utf-8') break # if still no luck, give up if not known_encoding: error = CharacterEncodingUnknown( 'document encoding unknown, I tried ' + '%s, %s, utf-8, windows-1252, and iso-8859-2 but nothing worked' % (rfc3023_encoding, xml_encoding)) rfc3023_encoding = '' elif proposed_encoding != rfc3023_encoding: <|code_end|> with the help of current file imports: import cgi import codecs import re import cchardet as chardet import chardet from .exceptions import ( CharacterEncodingOverride, CharacterEncodingUnknown, NonXMLContentType, ) and context from other files: # Path: src/bin/syndication_app/feedparser/exceptions.py # class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): # pass # # class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): # pass # # class NonXMLContentType(ThingsNobodyCaresAboutButMe): # pass , which may contain function names, class names, or code. Output only the next line.
error = CharacterEncodingOverride(
Given snippet: <|code_start|> # determine character encoding known_encoding = 0 tried_encodings = [] # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM for proposed_encoding in (rfc3023_encoding, xml_encoding, bom_encoding, lazy_chardet_encoding, 'utf-8', 'windows-1252', 'iso-8859-2'): if callable(proposed_encoding): proposed_encoding = proposed_encoding(data) if not proposed_encoding: continue if proposed_encoding in tried_encodings: continue tried_encodings.append(proposed_encoding) try: data = data.decode(proposed_encoding) except (UnicodeDecodeError, LookupError): pass else: known_encoding = 1 # Update the encoding in the opening XML processing instruction. new_declaration = '''<?xml version='1.0' encoding='utf-8'?>''' if RE_XML_DECLARATION.search(data): data = RE_XML_DECLARATION.sub(new_declaration, data) else: data = new_declaration + '\n' + data data = data.encode('utf-8') break # if still no luck, give up if not known_encoding: <|code_end|> , continue by predicting the next line. Consider current file imports: import cgi import codecs import re import cchardet as chardet import chardet from .exceptions import ( CharacterEncodingOverride, CharacterEncodingUnknown, NonXMLContentType, ) and context: # Path: src/bin/syndication_app/feedparser/exceptions.py # class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): # pass # # class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): # pass # # class NonXMLContentType(ThingsNobodyCaresAboutButMe): # pass which might include code, classes, or functions. Output only the next line.
error = CharacterEncodingUnknown(
Predict the next line after this snippet: <|code_start|> and http_content_type.endswith('+xml') ) ): acceptable_content_type = 1 rfc3023_encoding = http_encoding or 'us-ascii' elif http_content_type.startswith('text/'): rfc3023_encoding = http_encoding or 'us-ascii' elif http_headers and 'content-type' not in http_headers: rfc3023_encoding = xml_encoding or 'iso-8859-1' else: rfc3023_encoding = xml_encoding or 'utf-8' # gb18030 is a superset of gb2312, so always replace gb2312 # with gb18030 for greater compatibility. if rfc3023_encoding.lower() == 'gb2312': rfc3023_encoding = 'gb18030' if xml_encoding.lower() == 'gb2312': xml_encoding = 'gb18030' # there are four encodings to keep track of: # - http_encoding is the encoding declared in the Content-Type HTTP header # - xml_encoding is the encoding declared in the <?xml declaration # - bom_encoding is the encoding sniffed from the first 4 bytes of the XML data # - rfc3023_encoding is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications error = None if http_headers and (not acceptable_content_type): if 'content-type' in http_headers: msg = '%s is not an XML media type' % http_headers['content-type'] else: msg = 'no Content-type specified' <|code_end|> using the current file's imports: import cgi import codecs import re import cchardet as chardet import chardet from .exceptions import ( CharacterEncodingOverride, CharacterEncodingUnknown, NonXMLContentType, ) and any relevant context from other files: # Path: src/bin/syndication_app/feedparser/exceptions.py # class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): # pass # # class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): # pass # # class NonXMLContentType(ThingsNobodyCaresAboutButMe): # pass . Output only the next line.
error = NonXMLContentType(msg)
Given the following code snippet before the placeholder: <|code_start|> '\u039a\u03c5\u03c1': 'Sun', # caf5f1 in iso-8859-7 '\u0394\u03b5\u03c5': 'Mon', # c4e5f5 in iso-8859-7 '\u03a4\u03c1\u03b9': 'Tue', # d4f1e9 in iso-8859-7 '\u03a4\u03b5\u03c4': 'Wed', # d4e5f4 in iso-8859-7 '\u03a0\u03b5\u03bc': 'Thu', # d0e5ec in iso-8859-7 '\u03a0\u03b1\u03c1': 'Fri', # d0e1f1 in iso-8859-7 '\u03a3\u03b1\u03b2': 'Sat', # d3e1e2 in iso-8859-7 } _greek_date_format_re = re.compile(r'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)') def _parse_date_greek(date_string): """Parse a string according to a Greek 8-bit date format.""" m = _greek_date_format_re.match(date_string) if not m: return wday = _greek_wdays[m.group(1)] month = _greek_months[m.group(3)] rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \ { 'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4), 'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7), 'zonediff': m.group(8), } <|code_end|> , predict the next line using imports from the current file: import re from .rfc822 import _parse_date_rfc822 and context including class names, function names, and sometimes code from other files: # Path: src/bin/syndication_app/feedparser/datetimes/rfc822.py # def _parse_date_rfc822(date): # """Parse RFC 822 dates and times # http://tools.ietf.org/html/rfc822#section-5 # # There are some formatting differences that are accounted for: # 1. Years may be two or four digits. # 2. The month and day can be swapped. # 3. Additional timezone names are supported. # 4. A default time and timezone are assumed if only a date is present. # # :param str date: a date/time string that will be converted to a time tuple # :returns: a UTC time tuple, or None # :rtype: time.struct_time | None # """ # # parts = date.lower().split() # if len(parts) < 5: # # Assume that the time and timezone are missing # parts.extend(('00:00:00', '0000')) # # Remove the day name # if parts[0][:3] in day_names: # parts = parts[1:] # if len(parts) < 5: # # If there are still fewer than five parts, there's not enough # # information to interpret this. # return None # # # Handle the day and month name. # month = months.get(parts[1][:3]) # try: # day = int(parts[0]) # except ValueError: # # Check if the day and month are swapped. # if months.get(parts[0][:3]): # try: # day = int(parts[1]) # except ValueError: # return None # month = months.get(parts[0][:3]) # else: # return None # if not month: # return None # # # Handle the year. # try: # year = int(parts[2]) # except ValueError: # return None # # Normalize two-digit years: # # Anything in the 90's is interpreted as 1990 and on. # # Anything 89 or less is interpreted as 2089 or before. # if len(parts[2]) <= 2: # year += (1900, 2000)[year < 90] # # # Handle the time (default to 00:00:00). # time_parts = parts[3].split(':') # time_parts.extend(('0',) * (3 - len(time_parts))) # try: # (hour, minute, second) = [int(i) for i in time_parts] # except ValueError: # return None # # # Handle the timezone information, if any (default to +0000). # # Strip 'Etc/' from the timezone. # if parts[4].startswith('etc/'): # parts[4] = parts[4][4:] # # Normalize timezones that start with 'gmt': # # GMT-05:00 => -0500 # # GMT => GMT # if parts[4].startswith('gmt'): # parts[4] = ''.join(parts[4][3:].split(':')) or 'gmt' # # Handle timezones like '-0500', '+0500', and 'EST' # if parts[4] and parts[4][0] in ('-', '+'): # try: # timezone_hours = int(parts[4][1:3]) # timezone_minutes = int(parts[4][3:]) # except ValueError: # return None # if parts[4].startswith('-'): # timezone_hours *= -1 # timezone_minutes *= -1 # else: # timezone_hours = timezone_names.get(parts[4], 0) # timezone_minutes = 0 # # # Create the datetime object and timezone delta objects # try: # stamp = datetime.datetime(year, month, day, hour, minute, second) # except ValueError: # return None # delta = datetime.timedelta(0, 0, 0, 0, timezone_minutes, timezone_hours) # # # Return the date and timestamp in a UTC 9-tuple # try: # return (stamp - delta).utctimetuple() # except (OverflowError, ValueError): # # IronPython throws ValueErrors instead of OverflowErrors # return None . Output only the next line.
return _parse_date_rfc822(rfc822date)
Continue the code snippet: <|code_start|> def _end_itunes_subtitle(self): self._end_subtitle() def _start_itunes_summary(self, attrs_d): self._start_summary(attrs_d) def _end_itunes_summary(self): self._end_summary() def _start_itunes_owner(self, attrs_d): self.inpublisher = 1 self.push('publisher', 0) def _end_itunes_owner(self): self.pop('publisher') self.inpublisher = 0 self._sync_author_detail('publisher') def _end_itunes_keywords(self): for term in self.pop('itunes_keywords').split(','): if term.strip(): self._add_tag(term.strip(), 'http://www.itunes.com/', None) def _start_itunes_category(self, attrs_d): self._add_tag(attrs_d.get('text'), 'http://www.itunes.com/', None) self.push('category', 1) def _start_itunes_image(self, attrs_d): self.push('itunes_image', 0) if attrs_d.get('href'): <|code_end|> . Use current file imports: from ..util import FeedParserDict and context (classes, functions, or code) from other files: # Path: src/bin/syndication_app/feedparser/util.py # class FeedParserDict(dict): # keymap = { # 'channel': 'feed', # 'items': 'entries', # 'guid': 'id', # 'date': 'updated', # 'date_parsed': 'updated_parsed', # 'description': ['summary', 'subtitle'], # 'description_detail': ['summary_detail', 'subtitle_detail'], # 'url': ['href'], # 'modified': 'updated', # 'modified_parsed': 'updated_parsed', # 'issued': 'published', # 'issued_parsed': 'published_parsed', # 'copyright': 'rights', # 'copyright_detail': 'rights_detail', # 'tagline': 'subtitle', # 'tagline_detail': 'subtitle_detail', # } # # def __getitem__(self, key): # """ # :return: A :class:`FeedParserDict`. # """ # # if key == 'category': # try: # return dict.__getitem__(self, 'tags')[0]['term'] # except IndexError: # raise KeyError("object doesn't have key 'category'") # elif key == 'enclosures': # norel = lambda link: FeedParserDict([(name, value) for (name, value) in link.items() if name != 'rel']) # return [ # norel(link) # for link in dict.__getitem__(self, 'links') # if link['rel'] == 'enclosure' # ] # elif key == 'license': # for link in dict.__getitem__(self, 'links'): # if link['rel'] == 'license' and 'href' in link: # return link['href'] # elif key == 'updated': # # Temporarily help developers out by keeping the old # # broken behavior that was reported in issue 310. # # This fix was proposed in issue 328. # if ( # not dict.__contains__(self, 'updated') # and dict.__contains__(self, 'published') # ): # warnings.warn( # "To avoid breaking existing software while " # "fixing issue 310, a temporary mapping has been created " # "from `updated` to `published` if `updated` doesn't " # "exist. This fallback will be removed in a future version " # "of feedparser.", # DeprecationWarning, # ) # return dict.__getitem__(self, 'published') # return dict.__getitem__(self, 'updated') # elif key == 'updated_parsed': # if ( # not dict.__contains__(self, 'updated_parsed') # and dict.__contains__(self, 'published_parsed') # ): # warnings.warn( # "To avoid breaking existing software while " # "fixing issue 310, a temporary mapping has been created " # "from `updated_parsed` to `published_parsed` if " # "`updated_parsed` doesn't exist. This fallback will be " # "removed in a future version of feedparser.", # DeprecationWarning, # ) # return dict.__getitem__(self, 'published_parsed') # return dict.__getitem__(self, 'updated_parsed') # else: # realkey = self.keymap.get(key, key) # if isinstance(realkey, list): # for k in realkey: # if dict.__contains__(self, k): # return dict.__getitem__(self, k) # elif dict.__contains__(self, realkey): # return dict.__getitem__(self, realkey) # return dict.__getitem__(self, key) # # def __contains__(self, key): # if key in ('updated', 'updated_parsed'): # # Temporarily help developers out by keeping the old # # broken behavior that was reported in issue 310. # # This fix was proposed in issue 328. # return dict.__contains__(self, key) # try: # self.__getitem__(key) # except KeyError: # return False # else: # return True # # has_key = __contains__ # # def get(self, key, default=None): # """ # :return: A :class:`FeedParserDict`. # """ # # try: # return self.__getitem__(key) # except KeyError: # return default # # def __setitem__(self, key, value): # key = self.keymap.get(key, key) # if isinstance(key, list): # key = key[0] # return dict.__setitem__(self, key, value) # # def setdefault(self, k, default): # if k not in self: # self[k] = default # return default # return self[k] # # def __getattr__(self, key): # # __getattribute__() is called first; this will be called # # only if an attribute was not already found # try: # return self.__getitem__(key) # except KeyError: # raise AttributeError("object has no attribute '%s'" % key) # # def __hash__(self): # # This is incorrect behavior -- dictionaries shouldn't be hashable. # # Note to self: remove this behavior in the future. # return id(self) . Output only the next line.
self._get_context()['image'] = FeedParserDict({'href': attrs_d.get('href')})
Given snippet: <|code_start|> 'sep', 'oct', 'nov', 'dec', ] def _parse_date_asctime(dt): """Parse asctime-style dates. Converts asctime to RFC822-compatible dates and uses the RFC822 parser to do the actual parsing. Supported formats (format is standardized to the first one listed): * {weekday name} {month name} dd hh:mm:ss {+-tz} yyyy * {weekday name} {month name} dd hh:mm:ss yyyy """ parts = dt.split() # Insert a GMT timezone, if needed. if len(parts) == 5: parts.insert(4, '+0000') # Exit if there are not six parts. if len(parts) != 6: return None # Reassemble the parts in an RFC822-compatible order and parse them. <|code_end|> , continue by predicting the next line. Consider current file imports: from .rfc822 import _parse_date_rfc822 and context: # Path: src/bin/syndication_app/feedparser/datetimes/rfc822.py # def _parse_date_rfc822(date): # """Parse RFC 822 dates and times # http://tools.ietf.org/html/rfc822#section-5 # # There are some formatting differences that are accounted for: # 1. Years may be two or four digits. # 2. The month and day can be swapped. # 3. Additional timezone names are supported. # 4. A default time and timezone are assumed if only a date is present. # # :param str date: a date/time string that will be converted to a time tuple # :returns: a UTC time tuple, or None # :rtype: time.struct_time | None # """ # # parts = date.lower().split() # if len(parts) < 5: # # Assume that the time and timezone are missing # parts.extend(('00:00:00', '0000')) # # Remove the day name # if parts[0][:3] in day_names: # parts = parts[1:] # if len(parts) < 5: # # If there are still fewer than five parts, there's not enough # # information to interpret this. # return None # # # Handle the day and month name. # month = months.get(parts[1][:3]) # try: # day = int(parts[0]) # except ValueError: # # Check if the day and month are swapped. # if months.get(parts[0][:3]): # try: # day = int(parts[1]) # except ValueError: # return None # month = months.get(parts[0][:3]) # else: # return None # if not month: # return None # # # Handle the year. # try: # year = int(parts[2]) # except ValueError: # return None # # Normalize two-digit years: # # Anything in the 90's is interpreted as 1990 and on. # # Anything 89 or less is interpreted as 2089 or before. # if len(parts[2]) <= 2: # year += (1900, 2000)[year < 90] # # # Handle the time (default to 00:00:00). # time_parts = parts[3].split(':') # time_parts.extend(('0',) * (3 - len(time_parts))) # try: # (hour, minute, second) = [int(i) for i in time_parts] # except ValueError: # return None # # # Handle the timezone information, if any (default to +0000). # # Strip 'Etc/' from the timezone. # if parts[4].startswith('etc/'): # parts[4] = parts[4][4:] # # Normalize timezones that start with 'gmt': # # GMT-05:00 => -0500 # # GMT => GMT # if parts[4].startswith('gmt'): # parts[4] = ''.join(parts[4][3:].split(':')) or 'gmt' # # Handle timezones like '-0500', '+0500', and 'EST' # if parts[4] and parts[4][0] in ('-', '+'): # try: # timezone_hours = int(parts[4][1:3]) # timezone_minutes = int(parts[4][3:]) # except ValueError: # return None # if parts[4].startswith('-'): # timezone_hours *= -1 # timezone_minutes *= -1 # else: # timezone_hours = timezone_names.get(parts[4], 0) # timezone_minutes = 0 # # # Create the datetime object and timezone delta objects # try: # stamp = datetime.datetime(year, month, day, hour, minute, second) # except ValueError: # return None # delta = datetime.timedelta(0, 0, 0, 0, timezone_minutes, timezone_hours) # # # Return the date and timestamp in a UTC 9-tuple # try: # return (stamp - delta).utctimetuple() # except (OverflowError, ValueError): # # IronPython throws ValueErrors instead of OverflowErrors # return None which might include code, classes, or functions. Output only the next line.
return _parse_date_rfc822(' '.join([
Given the code snippet: <|code_start|>from __future__ import unicode_literals # 8-bit date handling routines written by ytrewq1. _korean_year = '\ub144' # b3e2 in euc-kr _korean_month = '\uc6d4' # bff9 in euc-kr _korean_day = '\uc77c' # c0cf in euc-kr _korean_am = '\uc624\uc804' # bfc0 c0fc in euc-kr _korean_pm = '\uc624\ud6c4' # bfc0 c8c4 in euc-kr _korean_onblog_date_re = re.compile( r'(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % (_korean_year, _korean_month, _korean_day) ) _korean_nate_date_re = re.compile( r'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % (_korean_am, _korean_pm)) def _parse_date_onblog(dateString): """Parse a string according to the OnBlog 8-bit date format""" m = _korean_onblog_date_re.match(dateString) if not m: return w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \ {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\ 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\ 'zonediff': '+09:00'} <|code_end|> , generate the next line using the imports in this file: import re from .w3dtf import _parse_date_w3dtf and context (functions, classes, or occasionally code) from other files: # Path: src/bin/syndication_app/feedparser/datetimes/w3dtf.py # def _parse_date_w3dtf(datestr): # if not datestr.strip(): # return None # parts = datestr.lower().split('t') # if len(parts) == 1: # # This may be a date only, or may be an MSSQL-style date # parts = parts[0].split() # if len(parts) == 1: # # Treat this as a date only # parts.append('00:00:00z') # elif len(parts) > 2: # return None # date = parts[0].split('-', 2) # if not date or len(date[0]) != 4: # return None # # Ensure that `date` has 3 elements. Using '1' sets the default # # month to January and the default day to the 1st of the month. # date.extend(['1'] * (3 - len(date))) # try: # year, month, day = [int(i) for i in date] # except ValueError: # # `date` may have more than 3 elements or may contain # # non-integer strings. # return None # if parts[1].endswith('z'): # parts[1] = parts[1][:-1] # parts.append('z') # # Append the numeric timezone offset, if any, to parts. # # If this is an MSSQL-style date then parts[2] already contains # # the timezone information, so `append()` will not affect it. # # Add 1 to each value so that if `find()` returns -1 it will be # # treated as False. # loc = parts[1].find('-') + 1 or parts[1].find('+') + 1 or len(parts[1]) + 1 # loc = loc - 1 # parts.append(parts[1][loc:]) # parts[1] = parts[1][:loc] # time = parts[1].split(':', 2) # # Ensure that time has 3 elements. Using '0' means that the # # minutes and seconds, if missing, will default to 0. # time.extend(['0'] * (3 - len(time))) # if parts[2][:1] in ('-', '+'): # try: # tzhour = int(parts[2][1:3]) # tzmin = int(parts[2][4:]) # except ValueError: # return None # if parts[2].startswith('-'): # tzhour = tzhour * -1 # tzmin = tzmin * -1 # else: # tzhour = timezonenames.get(parts[2], 0) # tzmin = 0 # try: # hour, minute, second = [int(float(i)) for i in time] # except ValueError: # return None # # Create the datetime object and timezone delta objects # try: # stamp = datetime.datetime(year, month, day, hour, minute, second) # except ValueError: # return None # delta = datetime.timedelta(0, 0, 0, 0, tzmin, tzhour) # # Return the date and timestamp in a UTC 9-tuple # try: # return (stamp - delta).utctimetuple() # except (OverflowError, ValueError): # # IronPython throws ValueErrors instead of OverflowErrors # return None . Output only the next line.
return _parse_date_w3dtf(w3dtfdate)
Using the snippet: <|code_start|># # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. class BaseSubscriber: """The base subscriber class It is recommended that all subscriber implementations subclass and then override the subscription methods (i.e. on_{subsribe_type}() methods). """ VALID_SUBSCRIBER_TYPES = ['queued', 'progress', 'done'] def __new__(cls, *args, **kwargs): cls._validate_subscriber_methods() return super().__new__(cls) @classmethod def _validate_subscriber_methods(cls): for subscriber_type in cls.VALID_SUBSCRIBER_TYPES: subscriber_method = getattr(cls, 'on_' + subscriber_type) if not callable(subscriber_method): raise InvalidSubscriberMethodError( 'Subscriber method %s must be callable.' % subscriber_method ) <|code_end|> , determine the next line of code. You have imports: from s3transfer.compat import accepts_kwargs from s3transfer.exceptions import InvalidSubscriberMethodError and context (class names, function names, or code) available: # Path: s3transfer/compat.py # def accepts_kwargs(func): # return inspect.getfullargspec(func)[2] # # Path: s3transfer/exceptions.py # class InvalidSubscriberMethodError(Exception): # pass . Output only the next line.
if not accepts_kwargs(subscriber_method):
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. class BaseSubscriber: """The base subscriber class It is recommended that all subscriber implementations subclass and then override the subscription methods (i.e. on_{subsribe_type}() methods). """ VALID_SUBSCRIBER_TYPES = ['queued', 'progress', 'done'] def __new__(cls, *args, **kwargs): cls._validate_subscriber_methods() return super().__new__(cls) @classmethod def _validate_subscriber_methods(cls): for subscriber_type in cls.VALID_SUBSCRIBER_TYPES: subscriber_method = getattr(cls, 'on_' + subscriber_type) if not callable(subscriber_method): <|code_end|> using the current file's imports: from s3transfer.compat import accepts_kwargs from s3transfer.exceptions import InvalidSubscriberMethodError and any relevant context from other files: # Path: s3transfer/compat.py # def accepts_kwargs(func): # return inspect.getfullargspec(func)[2] # # Path: s3transfer/exceptions.py # class InvalidSubscriberMethodError(Exception): # pass . Output only the next line.
raise InvalidSubscriberMethodError(
Given the code snippet: <|code_start|># Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. MAX_PARTS = 10000 # The maximum file size you can upload via S3 per request. # See: http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html # and: http://docs.aws.amazon.com/AmazonS3/latest/dev/qfacts.html MAX_SINGLE_UPLOAD_SIZE = 5 * (1024 ** 3) MIN_UPLOAD_CHUNKSIZE = 5 * (1024 ** 2) logger = logging.getLogger(__name__) S3_RETRYABLE_DOWNLOAD_ERRORS = ( socket.timeout, <|code_end|> , generate the next line using the imports in this file: import functools import logging import math import os import random import socket import stat import string import threading from collections import defaultdict from botocore.exceptions import IncompleteReadError, ReadTimeoutError from s3transfer.compat import SOCKET_ERROR, fallocate, rename_file and context (functions, classes, or occasionally code) from other files: # Path: s3transfer/compat.py # SOCKET_ERROR = ConnectionError # # def fallocate(fileobj, size): # if hasattr(os, 'posix_fallocate'): # os.posix_fallocate(fileobj.fileno(), 0, size) # else: # fileobj.truncate(size) # # def rename_file(current_filename, new_filename): # try: # os.remove(new_filename) # except OSError as e: # if not e.errno == errno.ENOENT: # # We only want to a ignore trying to remove # # a file that does not exist. If it fails # # for any other reason we should be propagating # # that exception. # raise # os.rename(current_filename, new_filename) . Output only the next line.
SOCKET_ERROR,
Based on the snippet: <|code_start|> """ # If it does not exist, it must be a new file so it cannot be # a special file. if not os.path.exists(filename): return False mode = os.stat(filename).st_mode # Character special device. if stat.S_ISCHR(mode): return True # Block special device if stat.S_ISBLK(mode): return True # Named pipe / FIFO if stat.S_ISFIFO(mode): return True # Socket. if stat.S_ISSOCK(mode): return True return False def get_temp_filename(self, filename): suffix = os.extsep + random_file_extension() path = os.path.dirname(filename) name = os.path.basename(filename) temp_filename = name[: self._MAX_FILENAME_LEN - len(suffix)] + suffix return os.path.join(path, temp_filename) def allocate(self, filename, size): try: with self.open(filename, 'wb') as f: <|code_end|> , predict the immediate next line with the help of imports: import functools import logging import math import os import random import socket import stat import string import threading from collections import defaultdict from botocore.exceptions import IncompleteReadError, ReadTimeoutError from s3transfer.compat import SOCKET_ERROR, fallocate, rename_file and context (classes, functions, sometimes code) from other files: # Path: s3transfer/compat.py # SOCKET_ERROR = ConnectionError # # def fallocate(fileobj, size): # if hasattr(os, 'posix_fallocate'): # os.posix_fallocate(fileobj.fileno(), 0, size) # else: # fileobj.truncate(size) # # def rename_file(current_filename, new_filename): # try: # os.remove(new_filename) # except OSError as e: # if not e.errno == errno.ENOENT: # # We only want to a ignore trying to remove # # a file that does not exist. If it fails # # for any other reason we should be propagating # # that exception. # raise # os.rename(current_filename, new_filename) . Output only the next line.
fallocate(f, size)
Predict the next line after this snippet: <|code_start|> def open_file_chunk_reader_from_fileobj( self, fileobj, chunk_size, full_file_size, callbacks, close_callbacks=None, ): return ReadFileChunk( fileobj, chunk_size, full_file_size, callbacks=callbacks, enable_callbacks=False, close_callbacks=close_callbacks, ) def open(self, filename, mode): return open(filename, mode) def remove_file(self, filename): """Remove a file, noop if file does not exist.""" # Unlike os.remove, if the file does not exist, # then this method does nothing. try: os.remove(filename) except OSError: pass <|code_end|> using the current file's imports: import functools import logging import math import os import random import socket import stat import string import threading from collections import defaultdict from botocore.exceptions import IncompleteReadError, ReadTimeoutError from s3transfer.compat import SOCKET_ERROR, fallocate, rename_file and any relevant context from other files: # Path: s3transfer/compat.py # SOCKET_ERROR = ConnectionError # # def fallocate(fileobj, size): # if hasattr(os, 'posix_fallocate'): # os.posix_fallocate(fileobj.fileno(), 0, size) # else: # fileobj.truncate(size) # # def rename_file(current_filename, new_filename): # try: # os.remove(new_filename) # except OSError as e: # if not e.errno == errno.ENOENT: # # We only want to a ignore trying to remove # # a file that does not exist. If it fails # # for any other reason we should be propagating # # that exception. # raise # os.rename(current_filename, new_filename) . Output only the next line.
def rename_file(self, current_filename, new_filename):
Given the code snippet: <|code_start|> """ with self._lock: self._exception = None self._result = result self._status = 'success' def set_exception(self, exception, override=False): """Set an exception for the TransferFuture Implies the TransferFuture failed. :param exception: The exception that cause the transfer to fail. :param override: If True, override any existing state. """ with self._lock: if not self.done() or override: self._exception = exception self._status = 'failed' def result(self): """Waits until TransferFuture is done and returns the result If the TransferFuture succeeded, it will return the result. If the TransferFuture failed, it will raise the exception associated to the failure. """ # Doing a wait() with no timeout cannot be interrupted in python2 but # can be interrupted in python3 so we just wait with the largest # possible value integer value, which is on the scale of billions of # years... <|code_end|> , generate the next line using the imports in this file: import copy import logging import sys import threading from collections import namedtuple from concurrent import futures from s3transfer.compat import MAXINT from s3transfer.exceptions import CancelledError, TransferNotDoneError from s3transfer.utils import FunctionContainer, TaskSemaphore and context (functions, classes, or occasionally code) from other files: # Path: s3transfer/compat.py # MAXINT = None # # Path: s3transfer/exceptions.py # class RetriesExceededError(Exception): # class S3UploadFailedError(Exception): # class InvalidSubscriberMethodError(Exception): # class TransferNotDoneError(Exception): # class FatalError(CancelledError): # def __init__(self, last_exception, msg='Max Retries Exceeded'): # # Path: s3transfer/utils.py # class FunctionContainer: # """An object that contains a function and any args or kwargs to call it # # When called the provided function will be called with provided args # and kwargs. # """ # # def __init__(self, func, *args, **kwargs): # self._func = func # self._args = args # self._kwargs = kwargs # # def __repr__(self): # return 'Function: {} with args {} and kwargs {}'.format( # self._func, self._args, self._kwargs # ) # # def __call__(self): # return self._func(*self._args, **self._kwargs) # # class TaskSemaphore: # def __init__(self, count): # """A semaphore for the purpose of limiting the number of tasks # # :param count: The size of semaphore # """ # self._semaphore = threading.Semaphore(count) # # def acquire(self, tag, blocking=True): # """Acquire the semaphore # # :param tag: A tag identifying what is acquiring the semaphore. Note # that this is not really needed to directly use this class but is # needed for API compatibility with the SlidingWindowSemaphore # implementation. # :param block: If True, block until it can be acquired. If False, # do not block and raise an exception if cannot be acquired. # # :returns: A token (can be None) to use when releasing the semaphore # """ # logger.debug("Acquiring %s", tag) # if not self._semaphore.acquire(blocking): # raise NoResourcesAvailable("Cannot acquire tag '%s'" % tag) # # def release(self, tag, acquire_token): # """Release the semaphore # # :param tag: A tag identifying what is releasing the semaphore # :param acquire_token: The token returned from when the semaphore was # acquired. Note that this is not really needed to directly use this # class but is needed for API compatibility with the # SlidingWindowSemaphore implementation. # """ # logger.debug(f"Releasing acquire {tag}/{acquire_token}") # self._semaphore.release() . Output only the next line.
self._done_event.wait(MAXINT)
Next line prediction: <|code_start|> Implies the TransferFuture failed. :param exception: The exception that cause the transfer to fail. :param override: If True, override any existing state. """ with self._lock: if not self.done() or override: self._exception = exception self._status = 'failed' def result(self): """Waits until TransferFuture is done and returns the result If the TransferFuture succeeded, it will return the result. If the TransferFuture failed, it will raise the exception associated to the failure. """ # Doing a wait() with no timeout cannot be interrupted in python2 but # can be interrupted in python3 so we just wait with the largest # possible value integer value, which is on the scale of billions of # years... self._done_event.wait(MAXINT) # Once done waiting, raise an exception if present or return the # final result. if self._exception: raise self._exception return self._result <|code_end|> . Use current file imports: (import copy import logging import sys import threading from collections import namedtuple from concurrent import futures from s3transfer.compat import MAXINT from s3transfer.exceptions import CancelledError, TransferNotDoneError from s3transfer.utils import FunctionContainer, TaskSemaphore) and context including class names, function names, or small code snippets from other files: # Path: s3transfer/compat.py # MAXINT = None # # Path: s3transfer/exceptions.py # class RetriesExceededError(Exception): # class S3UploadFailedError(Exception): # class InvalidSubscriberMethodError(Exception): # class TransferNotDoneError(Exception): # class FatalError(CancelledError): # def __init__(self, last_exception, msg='Max Retries Exceeded'): # # Path: s3transfer/utils.py # class FunctionContainer: # """An object that contains a function and any args or kwargs to call it # # When called the provided function will be called with provided args # and kwargs. # """ # # def __init__(self, func, *args, **kwargs): # self._func = func # self._args = args # self._kwargs = kwargs # # def __repr__(self): # return 'Function: {} with args {} and kwargs {}'.format( # self._func, self._args, self._kwargs # ) # # def __call__(self): # return self._func(*self._args, **self._kwargs) # # class TaskSemaphore: # def __init__(self, count): # """A semaphore for the purpose of limiting the number of tasks # # :param count: The size of semaphore # """ # self._semaphore = threading.Semaphore(count) # # def acquire(self, tag, blocking=True): # """Acquire the semaphore # # :param tag: A tag identifying what is acquiring the semaphore. Note # that this is not really needed to directly use this class but is # needed for API compatibility with the SlidingWindowSemaphore # implementation. # :param block: If True, block until it can be acquired. If False, # do not block and raise an exception if cannot be acquired. # # :returns: A token (can be None) to use when releasing the semaphore # """ # logger.debug("Acquiring %s", tag) # if not self._semaphore.acquire(blocking): # raise NoResourcesAvailable("Cannot acquire tag '%s'" % tag) # # def release(self, tag, acquire_token): # """Release the semaphore # # :param tag: A tag identifying what is releasing the semaphore # :param acquire_token: The token returned from when the semaphore was # acquired. Note that this is not really needed to directly use this # class but is needed for API compatibility with the # SlidingWindowSemaphore implementation. # """ # logger.debug(f"Releasing acquire {tag}/{acquire_token}") # self._semaphore.release() . Output only the next line.
def cancel(self, msg='', exc_type=CancelledError):
Based on the snippet: <|code_start|> if meta is None: self._meta = TransferMeta() self._coordinator = coordinator if coordinator is None: self._coordinator = TransferCoordinator() @property def meta(self): return self._meta def done(self): return self._coordinator.done() def result(self): try: # Usually the result() method blocks until the transfer is done, # however if a KeyboardInterrupt is raised we want want to exit # out of this and propagate the exception. return self._coordinator.result() except KeyboardInterrupt as e: self.cancel() raise e def cancel(self): self._coordinator.cancel() def set_exception(self, exception): """Sets the exception on the future.""" if not self.done(): <|code_end|> , predict the immediate next line with the help of imports: import copy import logging import sys import threading from collections import namedtuple from concurrent import futures from s3transfer.compat import MAXINT from s3transfer.exceptions import CancelledError, TransferNotDoneError from s3transfer.utils import FunctionContainer, TaskSemaphore and context (classes, functions, sometimes code) from other files: # Path: s3transfer/compat.py # MAXINT = None # # Path: s3transfer/exceptions.py # class RetriesExceededError(Exception): # class S3UploadFailedError(Exception): # class InvalidSubscriberMethodError(Exception): # class TransferNotDoneError(Exception): # class FatalError(CancelledError): # def __init__(self, last_exception, msg='Max Retries Exceeded'): # # Path: s3transfer/utils.py # class FunctionContainer: # """An object that contains a function and any args or kwargs to call it # # When called the provided function will be called with provided args # and kwargs. # """ # # def __init__(self, func, *args, **kwargs): # self._func = func # self._args = args # self._kwargs = kwargs # # def __repr__(self): # return 'Function: {} with args {} and kwargs {}'.format( # self._func, self._args, self._kwargs # ) # # def __call__(self): # return self._func(*self._args, **self._kwargs) # # class TaskSemaphore: # def __init__(self, count): # """A semaphore for the purpose of limiting the number of tasks # # :param count: The size of semaphore # """ # self._semaphore = threading.Semaphore(count) # # def acquire(self, tag, blocking=True): # """Acquire the semaphore # # :param tag: A tag identifying what is acquiring the semaphore. Note # that this is not really needed to directly use this class but is # needed for API compatibility with the SlidingWindowSemaphore # implementation. # :param block: If True, block until it can be acquired. If False, # do not block and raise an exception if cannot be acquired. # # :returns: A token (can be None) to use when releasing the semaphore # """ # logger.debug("Acquiring %s", tag) # if not self._semaphore.acquire(blocking): # raise NoResourcesAvailable("Cannot acquire tag '%s'" % tag) # # def release(self, tag, acquire_token): # """Release the semaphore # # :param tag: A tag identifying what is releasing the semaphore # :param acquire_token: The token returned from when the semaphore was # acquired. Note that this is not really needed to directly use this # class but is needed for API compatibility with the # SlidingWindowSemaphore implementation. # """ # logger.debug(f"Releasing acquire {tag}/{acquire_token}") # self._semaphore.release() . Output only the next line.
raise TransferNotDoneError(
Using the snippet: <|code_start|> 'Unable to transition from done state %s to non-done ' 'state %s.' % (self.status, desired_state) ) self._status = desired_state def submit(self, executor, task, tag=None): """Submits a task to a provided executor :type executor: s3transfer.futures.BoundedExecutor :param executor: The executor to submit the callable to :type task: s3transfer.tasks.Task :param task: The task to submit to the executor :type tag: s3transfer.futures.TaskTag :param tag: A tag to associate to the submitted task :rtype: concurrent.futures.Future :returns: A future representing the submitted task """ logger.debug( "Submitting task {} to executor {} for transfer request: {}.".format( task, executor, self.transfer_id ) ) future = executor.submit(task, tag=tag) # Add this created future to the list of associated future just # in case it is needed during cleanups. self.add_associated_future(future) future.add_done_callback( <|code_end|> , determine the next line of code. You have imports: import copy import logging import sys import threading from collections import namedtuple from concurrent import futures from s3transfer.compat import MAXINT from s3transfer.exceptions import CancelledError, TransferNotDoneError from s3transfer.utils import FunctionContainer, TaskSemaphore and context (class names, function names, or code) available: # Path: s3transfer/compat.py # MAXINT = None # # Path: s3transfer/exceptions.py # class RetriesExceededError(Exception): # class S3UploadFailedError(Exception): # class InvalidSubscriberMethodError(Exception): # class TransferNotDoneError(Exception): # class FatalError(CancelledError): # def __init__(self, last_exception, msg='Max Retries Exceeded'): # # Path: s3transfer/utils.py # class FunctionContainer: # """An object that contains a function and any args or kwargs to call it # # When called the provided function will be called with provided args # and kwargs. # """ # # def __init__(self, func, *args, **kwargs): # self._func = func # self._args = args # self._kwargs = kwargs # # def __repr__(self): # return 'Function: {} with args {} and kwargs {}'.format( # self._func, self._args, self._kwargs # ) # # def __call__(self): # return self._func(*self._args, **self._kwargs) # # class TaskSemaphore: # def __init__(self, count): # """A semaphore for the purpose of limiting the number of tasks # # :param count: The size of semaphore # """ # self._semaphore = threading.Semaphore(count) # # def acquire(self, tag, blocking=True): # """Acquire the semaphore # # :param tag: A tag identifying what is acquiring the semaphore. Note # that this is not really needed to directly use this class but is # needed for API compatibility with the SlidingWindowSemaphore # implementation. # :param block: If True, block until it can be acquired. If False, # do not block and raise an exception if cannot be acquired. # # :returns: A token (can be None) to use when releasing the semaphore # """ # logger.debug("Acquiring %s", tag) # if not self._semaphore.acquire(blocking): # raise NoResourcesAvailable("Cannot acquire tag '%s'" % tag) # # def release(self, tag, acquire_token): # """Release the semaphore # # :param tag: A tag identifying what is releasing the semaphore # :param acquire_token: The token returned from when the semaphore was # acquired. Note that this is not really needed to directly use this # class but is needed for API compatibility with the # SlidingWindowSemaphore implementation. # """ # logger.debug(f"Releasing acquire {tag}/{acquire_token}") # self._semaphore.release() . Output only the next line.
FunctionContainer(self.remove_associated_future, future)
Next line prediction: <|code_start|> def __init__( self, max_size, max_num_threads, tag_semaphores=None, executor_cls=None ): """An executor implementation that has a maximum queued up tasks The executor will block if the number of tasks that have been submitted and is currently working on is past its maximum. :params max_size: The maximum number of inflight futures. An inflight future means that the task is either queued up or is currently being executed. A size of None or 0 means that the executor will have no bound in terms of the number of inflight futures. :params max_num_threads: The maximum number of threads the executor uses. :type tag_semaphores: dict :params tag_semaphores: A dictionary where the key is the name of the tag and the value is the semaphore to use when limiting the number of tasks the executor is processing at a time. :type executor_cls: BaseExecutor :param underlying_executor_cls: The executor class that get bounded by this executor. If None is provided, the concurrent.futures.ThreadPoolExecutor class is used. """ self._max_num_threads = max_num_threads if executor_cls is None: executor_cls = self.EXECUTOR_CLS self._executor = executor_cls(max_workers=self._max_num_threads) <|code_end|> . Use current file imports: (import copy import logging import sys import threading from collections import namedtuple from concurrent import futures from s3transfer.compat import MAXINT from s3transfer.exceptions import CancelledError, TransferNotDoneError from s3transfer.utils import FunctionContainer, TaskSemaphore) and context including class names, function names, or small code snippets from other files: # Path: s3transfer/compat.py # MAXINT = None # # Path: s3transfer/exceptions.py # class RetriesExceededError(Exception): # class S3UploadFailedError(Exception): # class InvalidSubscriberMethodError(Exception): # class TransferNotDoneError(Exception): # class FatalError(CancelledError): # def __init__(self, last_exception, msg='Max Retries Exceeded'): # # Path: s3transfer/utils.py # class FunctionContainer: # """An object that contains a function and any args or kwargs to call it # # When called the provided function will be called with provided args # and kwargs. # """ # # def __init__(self, func, *args, **kwargs): # self._func = func # self._args = args # self._kwargs = kwargs # # def __repr__(self): # return 'Function: {} with args {} and kwargs {}'.format( # self._func, self._args, self._kwargs # ) # # def __call__(self): # return self._func(*self._args, **self._kwargs) # # class TaskSemaphore: # def __init__(self, count): # """A semaphore for the purpose of limiting the number of tasks # # :param count: The size of semaphore # """ # self._semaphore = threading.Semaphore(count) # # def acquire(self, tag, blocking=True): # """Acquire the semaphore # # :param tag: A tag identifying what is acquiring the semaphore. Note # that this is not really needed to directly use this class but is # needed for API compatibility with the SlidingWindowSemaphore # implementation. # :param block: If True, block until it can be acquired. If False, # do not block and raise an exception if cannot be acquired. # # :returns: A token (can be None) to use when releasing the semaphore # """ # logger.debug("Acquiring %s", tag) # if not self._semaphore.acquire(blocking): # raise NoResourcesAvailable("Cannot acquire tag '%s'" % tag) # # def release(self, tag, acquire_token): # """Release the semaphore # # :param tag: A tag identifying what is releasing the semaphore # :param acquire_token: The token returned from when the semaphore was # acquired. Note that this is not really needed to directly use this # class but is needed for API compatibility with the # SlidingWindowSemaphore implementation. # """ # logger.debug(f"Releasing acquire {tag}/{acquire_token}") # self._semaphore.release() . Output only the next line.
self._semaphore = TaskSemaphore(max_size)
Using the snippet: <|code_start|> result.append(future.result()) # Otherwise if the pending_value is a future, just wait for it. else: result = pending_value.result() # Add the retrieved value to the kwargs to be sent to the # main() call. kwargs[key] = result return kwargs class SubmissionTask(Task): """A base class for any submission task Submission tasks are the top-level task used to submit a series of tasks to execute a particular transfer. """ def _main(self, transfer_future, **kwargs): """ :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for :param kwargs: Any additional kwargs that you may want to pass to the _submit() method """ try: self._transfer_coordinator.set_status_to_queued() # Before submitting any tasks, run all of the on_queued callbacks <|code_end|> , determine the next line of code. You have imports: import copy import logging from s3transfer.utils import get_callbacks and context (class names, function names, or code) available: # Path: s3transfer/utils.py # def get_callbacks(transfer_future, callback_type): # """Retrieves callbacks from a subscriber # # :type transfer_future: s3transfer.futures.TransferFuture # :param transfer_future: The transfer future the subscriber is associated # to. # # :type callback_type: str # :param callback_type: The type of callback to retrieve from the subscriber. # Valid types include: # * 'queued' # * 'progress' # * 'done' # # :returns: A list of callbacks for the type specified. All callbacks are # preinjected with the transfer future. # """ # callbacks = [] # for subscriber in transfer_future.meta.call_args.subscribers: # callback_name = 'on_' + callback_type # if hasattr(subscriber, callback_name): # callbacks.append( # functools.partial( # getattr(subscriber, callback_name), future=transfer_future # ) # ) # return callbacks . Output only the next line.
on_queued_callbacks = get_callbacks(transfer_future, 'queued')
Given the code snippet: <|code_start|>REVERSE_THRESHOLD = 1500 - STOP_RANGE # left and right thresholds set the limit on when a command will begin # to increse the turn command in the left and right direction respectively LEFT_THRESHOLD = 1500 - STOP_RANGE RIGHT_THRESHOLD = 1500 + STOP_RANGE # RC input below the armed threshold will disarm the rc controller # and it will not respond to any control input # RC input above the armed threshold will arm the rc controller and thus # respond to subsequent commands ARMED_THRESHOLD = 1500 # define the channels for rc input RC_THROTTLE_CHANNEL = 2 RC_TURN_CHANNEL = 0 RC_ARM_CHANNEL = 6 # the debounce range value is used to ignore changes in rc input # that are within the debounce range DEBOUNCE_RANGE = 5 class RCControler(ApplicationSession): """Main entry point for controling the Mothership and AUV """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.armed = False <|code_end|> , generate the next line using the imports in this file: import asyncio import logging import time from autobahn.asyncio.wamp import ApplicationSession from navio.rcinput import RCInput and context (functions, classes, or occasionally code) from other files: # Path: navio/rcinput.py # class RCInput(): # CHANNEL_COUNT = 14 # channels = [] # # def __init__(self): # for i in range(0, self.CHANNEL_COUNT): # try: # f = open("/sys/kernel/rcio/rcin/ch%d" % i, "r") # self.channels.append(f) # except: # print ("Can't open file /sys/kernel/rcio/rcin/ch%d" % i) # # def read(self, ch): # value = self.channels[ch].read() # position = self.channels[ch].seek(0, 0) # return value[:-1] . Output only the next line.
self.rc_input = RCInput()
Predict the next line for this snippet: <|code_start|>PWM_FREQUENCY = 50 # Hz def _calculate_value_in_range(min_val, max_val, percentage): """Get the value within a range based on percentage. Example: A percentage 0.0 maps to min_val A percentage of 1.0 maps to max_val """ value_range = max_val - min_val return min_val + int(percentage * value_range) class Motor: """An interface class to allow simple acces to motor functions""" def __init__(self, name, rc_channel, motor_type=T100): self.name = name self.rc_channel = rc_channel if motor_type == T100: self.pwm_map = T100_PWM_MAP elif motor_type == SERVO: self.pwm_map = SERVO_PWM_MAP else: raise ValueError('Unknown motor_type') self._speed = 0 self.duty_cycle_ms = self.pwm_map['stopped'] / 1000 <|code_end|> with the help of current file imports: import os import logging import time from threading import Thread from navio.pwm import PWM and context from other files: # Path: navio/pwm.py # class PWM: # # def __init__(self, channel): # self.channel = channel # self.channel_path = SYSFS_PWM_PATH_BASE + "pwm{}/".format(self.channel) # self.is_initialized = False # self.is_enabled = False # # def __enter__(self): # self.initialize() # return self # # def __exit__(self, *args): # self.deinitialize() # # def deinitialize(self): # if self.is_enabled: # self.disable() # with open(SYSFS_PWM_UNEXPORT_PATH, "a") as pwm_unexport: # pwm_unexport.write(str(self.channel)) # # def initialize(self): # if not os.path.exists(SYSFS_PWM_PATH_BASE): # raise OSError("rcio_pwm module wasn't loaded") # # if not os.path.exists(self.channel_path): # with open(SYSFS_PWM_EXPORT_PATH, "a") as pwm_export: # pwm_export.write(str(self.channel)) # # self.is_initialized = True # # def enable(self): # with open(self.channel_path + "enable", "w") as pwm_enable: # pwm_enable.write("1") # self.is_enabled = True # # def disable(self): # with open(self.channel_path + "enable", "w") as pwm_enable: # pwm_enable.write("0") # self.is_enabled = False # # def set_period(self, freq): # if not self.is_initialized: # raise RuntimeError("PWM not initialized. Call initialize first") # # period_ns = int(1e9/freq) # with open(self.channel_path + "period", "w") as pwm_period: # pwm_period.write(str(period_ns)) # # def set_duty_cycle(self, period): # if not self.is_initialized: # raise RuntimeError("PWM not initialized. Call initialize first") # # period_ns = int(period*1e6) # with open(self.channel_path + "duty_cycle", "w") as pwm_duty: # pwm_duty.write(str(period_ns)) , which may contain function names, class names, or code. Output only the next line.
self.pwm = PWM(self.rc_channel - 1)