text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|> def constructSpace(self, words, maxWidth):
length = len(words)
spaceLength = maxWidth - len(''.join(words))
if length == 1:
return ''.join(words) + ' '*spaceLength
evenSapce,extraSpace = divmod(spaceLength, length-1)
even = ' '*evenSapce
ex... | code_fim | hard | {
"lang": "python",
"repo": "wisesky/LeetCode-Practice",
"path": "/src/68. Text Justification.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wisesky/LeetCode-Practice path: /src/68. Text Justification.py
from typing import List
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
res = []
candidateWords = []
wordslength = 0
for i, word in enumerate(words):
... | code_fim | hard | {
"lang": "python",
"repo": "wisesky/LeetCode-Practice",
"path": "/src/68. Text Justification.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: alok/safe-grid-agents path: /safe_grid_agents/common/agents/value.py
# Value Agents
from . import base
from . import utils
from collections import defaultdict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
# Baseline ag... | code_fim | hard | {
"lang": "python",
"repo": "alok/safe-grid-agents",
"path": "/safe_grid_agents/common/agents/value.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> if len(self.future_eps) > 0:
self.epsilon = self.future_eps.pop(0)
return self.epsilon
def build_Q(self, n_input, n_layers, n_hidden):
first = nn.Sequential(nn.Linear(n_input, n_hidden), nn.ReLU())
hidden = nn.Sequential(*tuple(nn.Sequential(nn.Linear(n_hid... | code_fim | hard | {
"lang": "python",
"repo": "alok/safe-grid-agents",
"path": "/safe_grid_agents/common/agents/value.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>nting_steps=5000 --resume_from_checkpoint="latest" \
--learning_rate=1e-04 --lr_scheduler="constant" --lr_warmup_steps=0 \
--seed=42 --validation_epochs=5 \
--output_dir="ckpts/sd-diffusiondb-canny-v2-model-control-lora" \
--control_lora_config="configs/diffusiondb-canny-v2.json" \
--validation_... | code_fim | hard | {
"lang": "python",
"repo": "HighCWu/ControlLoRA",
"path": "/tasks/train_canny_v2.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: HighCWu/ControlLoRA path: /tasks/train_canny_v2.py
import os
os.chdir(os.path.join(os.path.dirname(__file__), '..'))
validation_prompt = ("1girl, 8 k, unreal engine")
cmd = rf'''accelerate launch --mixed_precision="fp16" train_text_to_image_control_lora.py \
--pretrained_model_name_or_path="... | code_fim | hard | {
"lang": "python",
"repo": "HighCWu/ControlLoRA",
"path": "/tasks/train_canny_v2.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: joe-nano/kitsune path: /kitsune/groups/forms.py
from django import forms
from django.utils.translation import ugettext_lazy as _lazy
from kitsune.groups.models import GroupProfile
from kitsune.sumo.form_fields import MultiUsernameField
from kitsune.users.forms import AvatarForm
<|fim_suffix|> ... | code_fim | medium | {
"lang": "python",
"repo": "joe-nano/kitsune",
"path": "/kitsune/groups/forms.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>class AddUserForm(forms.Form):
"""Form to add members or leaders to group."""
users = MultiUsernameField(
widget=forms.TextInput(attrs={'placeholder': USERS_PLACEHOLDER,
'class': 'user-autocomplete'}))<|fim_prefix|># repo: joe-nano/kitsune path: /kits... | code_fim | hard | {
"lang": "python",
"repo": "joe-nano/kitsune",
"path": "/kitsune/groups/forms.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> logger.info('Starting mark finding')
df['marca']='otros'
for mark in marks:
df['marca']=(df
.apply(lambda row: row['producto'],axis=1)
.apply(lambda product: mark.capitalize() if (product.lower().find(mark)!=-1) else df['marca'][df.index[df[... | code_fim | hard | {
"lang": "python",
"repo": "datacloudgui/prices_load",
"path": "/prices_load.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: datacloudgui/prices_load path: /prices_load.py
import argparse
import logging
logging.basicConfig(level=logging.INFO)
import datetime
import pandas as pd
import numpy as np
logger = logging.getLogger(__name__)
def main(filename_db,filename_t,category,today):
logger.info('Start... | code_fim | hard | {
"lang": "python",
"repo": "datacloudgui/prices_load",
"path": "/prices_load.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # trigger on_exit for those states that are not done yet
self.on_exit(self.userdata,
states=[s for s in self._states if (s.name not in list(self._returned_outcomes.keys()) or
self._returned_outcomes[s.name] is No... | code_fim | hard | {
"lang": "python",
"repo": "team-vigir/flexbe_behavior_engine",
"path": "/flexbe_core/src/flexbe_core/core/concurrency_container.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: team-vigir/flexbe_behavior_engine path: /flexbe_core/src/flexbe_core/core/concurrency_container.py
#!/usr/bin/env python
from flexbe_core.logger import Logger
from flexbe_core.core.user_data import UserData
from flexbe_core.core.event_state import EventState
from flexbe_core.core.priority_contain... | code_fim | hard | {
"lang": "python",
"repo": "team-vigir/flexbe_behavior_engine",
"path": "/flexbe_core/src/flexbe_core/core/concurrency_container.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Coac/tf-detection-example path: /download_model.py
import os
import shutil
import tarfile
import urllib.request
"""
Download a pretrained TF detection model
"""
<|fim_suffix|> tar = tarfile.open(MODEL_FILE)
tar.extractall()
tar.close()
os.remove(MODEL_FILE)
if os.path.exists... | code_fim | hard | {
"lang": "python",
"repo": "Coac/tf-detection-example",
"path": "/download_model.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> tar = tarfile.open(MODEL_FILE)
tar.extractall()
tar.close()
os.remove(MODEL_FILE)
if os.path.exists(DEST_DIR):
shutil.rmtree(DEST_DIR)
os.rename(MODEL, DEST_DIR)
print("Done.")<|fim_prefix|># repo: Coac/tf-detection-example path: /download_model.py
import os
import sh... | code_fim | hard | {
"lang": "python",
"repo": "Coac/tf-detection-example",
"path": "/download_model.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> os.remove(MODEL_FILE)
if os.path.exists(DEST_DIR):
shutil.rmtree(DEST_DIR)
os.rename(MODEL, DEST_DIR)
print("Done.")<|fim_prefix|># repo: Coac/tf-detection-example path: /download_model.py
import os
import shutil
import tarfile
import urllib.request
"""
Download a pretrained TF d... | code_fim | hard | {
"lang": "python",
"repo": "Coac/tf-detection-example",
"path": "/download_model.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: JManou/markdown-fenced-code-tabs path: /markdown_fenced_code_tabs/tab.py
"""
Tab related objects.
Fenced Code Tabs Extension for Python Markdown
This extension generates Bootstrap HTML Tabs for consecutive fenced code blocks
See <https://github.com/yacir/markdown-fenced-code-tabs> for documenta... | code_fim | hard | {
"lang": "python",
"repo": "JManou/markdown-fenced-code-tabs",
"path": "/markdown_fenced_code_tabs/tab.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class TabGroup(object):
GROUP_ID = 'tab-group-{}'
#group-0
TAB_ID = '{}-{}_{}'
#group-0_0-python'
RANDOM_ID_CHAR_LENGTH = 15
def __init__(self, group_id):
self.id = self.GROUP_ID.format(group_id)
self.headers = deque()
self.contents = deque()
... | code_fim | hard | {
"lang": "python",
"repo": "JManou/markdown-fenced-code-tabs",
"path": "/markdown_fenced_code_tabs/tab.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ubdussamad/Subseeker path: /subseeker.py
#!/usr/bin/env python
import os,sys,re,traceback
from utils import *
from comparison_statics import compare
from selection_panel import selection_panel_func
from options_diag import question
from urllib import urlopen
from zipfile import ZipFile
from Strin... | code_fim | hard | {
"lang": "python",
"repo": "ubdussamad/Subseeker",
"path": "/subseeker.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> f = open('/'.join(target.media_path.split('/')[:-1])+'/Sorry, We didn\'t find any Subtitle.txt','w')
f.write(''' We are truely sorry for the inconvinience caused! \n
\n We tried to get the subtitle for your movie/video:
\n %s \n\n But had no Luck! \n Thi... | code_fim | hard | {
"lang": "python",
"repo": "ubdussamad/Subseeker",
"path": "/subseeker.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Charlenator/Amazon-Comprehend path: /reco.py
import boto3
client = boto3.client('comprehend')
ls = []
def sent():
<|fim_suffix|>for ratings in ('POSITIVE', 'NEUTRAL', 'NEGATIVE', 'MIXED'):
print('=============\n{} reviews\n=============\n\n'.format(ratings.lower()))
for reviews in ... | code_fim | hard | {
"lang": "python",
"repo": "Charlenator/Amazon-Comprehend",
"path": "/reco.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
for ratings in ('POSITIVE', 'NEUTRAL', 'NEGATIVE', 'MIXED'):
print('=============\n{} reviews\n=============\n\n'.format(ratings.lower()))
for reviews in range(0,len(ls)):
if ls[reviews]['sentiment'] == ratings:
print(ls[reviews]['text']+'\n')
print('\n\n')<|fim_prefix|># ... | code_fim | hard | {
"lang": "python",
"repo": "Charlenator/Amazon-Comprehend",
"path": "/reco.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ngdeva99/Fulcrum path: /Angle Between Hands of a Clock.py
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
<|fim_suffix|> k = abs(degm-((hour%12)*30)-degh)
if k>180:
return 360-k
return k<|fim_middle|>
... | code_fim | medium | {
"lang": "python",
"repo": "ngdeva99/Fulcrum",
"path": "/Angle Between Hands of a Clock.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def get_image_ids(params: DownloadCommandParameters) -> List[str]:
"""
Gather all the image ids for a specific Dataset.
:param params: The command line parameters.
:return: The ISIC image ids for the dataset requested.
"""
if params.retry:
logger.info(f"Attempting to downl... | code_fim | hard | {
"lang": "python",
"repo": "DavidWalshe93/isic_cli",
"path": "/src/cli/commands/image/download.py",
"mode": "spm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: DavidWalshe93/isic_cli path: /src/cli/commands/image/download.py
"""
Author: David Walshe
Date: 21 February 2021
"""
import logging
from collections import namedtuple
from itertools import chain
from queue import Queue
from typing import List, Union
import os
import json
import urllib ... | code_fim | hard | {
"lang": "python",
"repo": "DavidWalshe93/isic_cli",
"path": "/src/cli/commands/image/download.py",
"mode": "psm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def make_request(api: IsicApi, image_set: list, params: DownloadCommandParameters) -> Union[List[dict], None]:
"""
Make a image download request to the API.
:param api: The reference to tha API object.
:param image_set: The image name to retrieve data on.
:param params: The command l... | code_fim | hard | {
"lang": "python",
"repo": "DavidWalshe93/isic_cli",
"path": "/src/cli/commands/image/download.py",
"mode": "spm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: k-flynn-webdev/daytrack-2 path: /api/api/views.py
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.csrf import ensure_csrf_cookie
from django.contrib.auth import aut... | code_fim | medium | {
"lang": "python",
"repo": "k-flynn-webdev/daytrack-2",
"path": "/api/api/views.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> response = HttpResponse(status=204)
response['HTTP_X_CSRFTOKEN'] = get_token(request)
print(response['HTTP_X_CSRFTOKEN'])
return response<|fim_prefix|># repo: k-flynn-webdev/daytrack-2 path: /api/api/views.py
from rest_framework.authentication import SessionAuthentication, BasicAuthentica... | code_fim | medium | {
"lang": "python",
"repo": "k-flynn-webdev/daytrack-2",
"path": "/api/api/views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if len(table.ids()) < subsampling_depth:
raise ValueError('The subsampling depth exceeds the number of '
'elements on the desired axis. The maximum depth '
'is: %d.' % len(table.ids()))
# the axis is always 'sample' due to the above transp... | code_fim | medium | {
"lang": "python",
"repo": "qiime2/q2-feature-table",
"path": "/q2_feature_table/_subsample.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def subsample(table: biom.Table, subsampling_depth: int,
axis: str) -> biom.Table:
if axis == 'feature':
# we are transposing the table due to biocore/biom-format#759
table = table.transpose()
if len(table.ids()) < subsampling_depth:
raise ValueError('The su... | code_fim | medium | {
"lang": "python",
"repo": "qiime2/q2-feature-table",
"path": "/q2_feature_table/_subsample.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: qiime2/q2-feature-table path: /q2_feature_table/_subsample.py
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2023, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENS... | code_fim | medium | {
"lang": "python",
"repo": "qiime2/q2-feature-table",
"path": "/q2_feature_table/_subsample.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kb3c/anybadge path: /build_examples.py
import anybadge
if __name__ == '__main__':
print("""| Color Name | Hex Code | Example |
| ---------- | -------- | ------- |""")
for color, hex in sorted(anybadge.COLORS.items()):
<|fim_suffix|> anybadge.Badge(label='Color', value=color,... | code_fim | medium | {
"lang": "python",
"repo": "kb3c/anybadge",
"path": "/build_examples.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> print("| {color} | {hex} |  |".format(color=color, hex=hex.upper(), url=url))<|fim_prefix|># repo: kb3c/anybadge path: /build_examples.py
import anybadge
if __name__ == '__main__':
print("""| Color Name | Hex Code | Example |
| ---------- | -------- | ------- |""")
for col... | code_fim | hard | {
"lang": "python",
"repo": "kb3c/anybadge",
"path": "/build_examples.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: aachurin/stark path: /stark/exceptions.py
from typing import Union
from stark.schema import Message, ValidationError, ParseError
__all__ = ("ValidationError", "Message", "ParseError", "NoReverseMatch", "NoCodecAvailable", "ConfigurationError",
"HTTPException", "Found", "BadRequest", ... | code_fim | hard | {
"lang": "python",
"repo": "aachurin/stark",
"path": "/stark/exceptions.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>class Found(HTTPException):
default_status_code = 302
default_detail = "Found"
def __init__(self,
location: str,
detail: Union[str, dict] = None,
status_code: int = None) -> None:
self.location = location
super().__init__(deta... | code_fim | hard | {
"lang": "python",
"repo": "aachurin/stark",
"path": "/stark/exceptions.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __str__(self):
return self.value<|fim_prefix|># repo: StefanoFrazzetto/CrimeDetector path: /Classification/MetricType.py
from enum import Enum
class MetricType(Enum):
ACCURACY = 'Accuracy'
PRECISION = 'Precision'
RECALL = 'Recall'
F05 = 'F0.5'
F1 = 'F1'
F2 = 'F2... | code_fim | medium | {
"lang": "python",
"repo": "StefanoFrazzetto/CrimeDetector",
"path": "/Classification/MetricType.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> MCC = 'Matthews Correlation Coefficient'
CONFUSION_MATRIX = 'Confusion Matrix'
def __str__(self):
return self.value<|fim_prefix|># repo: StefanoFrazzetto/CrimeDetector path: /Classification/MetricType.py
from enum import Enum
class MetricType(Enum):
ACCURACY = 'Accuracy'
PR... | code_fim | medium | {
"lang": "python",
"repo": "StefanoFrazzetto/CrimeDetector",
"path": "/Classification/MetricType.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: StefanoFrazzetto/CrimeDetector path: /Classification/MetricType.py
from enum import Enum
class MetricType(Enum):
<|fim_suffix|> AUC = 'AUC'
FPR = 'FPR'
TPR = 'TPR'
ROC = 'ROC'
THRESHOLDS = 'Thresholds'
MCC = 'Matthews Correlation Coefficient'
CONFUSION_MATRIX = 'Conf... | code_fim | medium | {
"lang": "python",
"repo": "StefanoFrazzetto/CrimeDetector",
"path": "/Classification/MetricType.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> beam_utils.BeamInit()
assert FLAGS.input_file_pattern
assert FLAGS.output_filebase
# Construct pipeline options from argv.
options = beam.options.pipeline_options.PipelineOptions(argv[1:])
reader = beam_utils.GetReader(
'tfrecord',
FLAGS.input_file_pattern,
value_coder=bea... | code_fim | hard | {
"lang": "python",
"repo": "tensorflow/lingvo",
"path": "/lingvo/tasks/car/waymo/tools/generate_waymo_tf.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Construct pipeline options from argv.
options = beam.options.pipeline_options.PipelineOptions(argv[1:])
reader = beam_utils.GetReader(
'tfrecord',
FLAGS.input_file_pattern,
value_coder=beam.coders.ProtoCoder(dataset_pb2.Frame))
writer = beam_utils.GetWriter(
'tfrecord',... | code_fim | medium | {
"lang": "python",
"repo": "tensorflow/lingvo",
"path": "/lingvo/tasks/car/waymo/tools/generate_waymo_tf.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tensorflow/lingvo path: /lingvo/tasks/car/waymo/tools/generate_waymo_tf.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy o... | code_fim | hard | {
"lang": "python",
"repo": "tensorflow/lingvo",
"path": "/lingvo/tasks/car/waymo/tools/generate_waymo_tf.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def set_state(self, high=[], low=[], **kwargs):
if self.activation != 'active':
raise TypeError('Can only set state of an active device. Device '
'is currently "{}"'.format(self.activation))
if 'o' not in self.direction:
raise TypeErr... | code_fim | hard | {
"lang": "python",
"repo": "matham/cplcom",
"path": "/cplcom/moa/device/mcdaq.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: matham/cplcom path: /cplcom/moa/device/mcdaq.py
'''Barst Measurement Computing DAQ Wrapper
==========================================
'''
from functools import partial
from pybarst.mcdaq import MCDAQChannel
from kivy.properties import NumericProperty, ObjectProperty
from moa.threads import Sche... | code_fim | hard | {
"lang": "python",
"repo": "matham/cplcom",
"path": "/cplcom/moa/device/mcdaq.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return self.__precision
@staticmethod
def get_generate_parameter(params: np.ndarray):
parameter = GenerateParameter(params)
return parameter
def get_sample_by_params(self, name: str, params: np.ndarray):
fractions = params[-self.n_components:] / np.sum(params[... | code_fim | hard | {
"lang": "python",
"repo": "smiledway/QGrain",
"path": "/QGrain/artificial/_sample.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: smiledway/QGrain path: /QGrain/artificial/_sample.py
__all__ = ["ComponentParameter",
"GenerateParameter",
"ArtificialComponent",
"ArtificialSample",
"ArtificialDataset"]
import typing
import numpy as np
from QGrain.models.GrainSizeSample import Grain... | code_fim | hard | {
"lang": "python",
"repo": "smiledway/QGrain",
"path": "/QGrain/artificial/_sample.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> assert isinstance(value, str)
self.__name = value
@property
def classes_μm(self) -> np.ndarray:
return self.__classes_μm
@property
def classes_φ(self) -> np.ndarray:
return self.__classes_φ
@property
def distribution(self) -> np.ndarray:
r... | code_fim | hard | {
"lang": "python",
"repo": "smiledway/QGrain",
"path": "/QGrain/artificial/_sample.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Tests for UTC timestamp functions, i.e. functions that do not depend on the behavior
of the flag --use_local_tz_for_unix_timestamp_conversions. Tests added here should
also be run in the custom cluster test test_local_tz_conversion.py to ensure they
have the same behavior when the conv... | code_fim | hard | {
"lang": "python",
"repo": "apache/impala",
"path": "/tests/query_test/test_exprs.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: apache/impala path: /tests/query_test/test_exprs.py
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to... | code_fim | hard | {
"lang": "python",
"repo": "apache/impala",
"path": "/tests/query_test/test_exprs.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: BackupTheBerlios/nanoicq path: /nanoicq/conversation.py
#
# $Id: conversation.py,v 1.1 2006/01/05 14:41:38 lightdruid Exp $
#
from buddy import Buddy
from message import Message
[CONV_UNKNOWN, CONV_IM, CONV_CHAT, CONV_MISC] = range(4)
class History:
<|fim_suffix|> b = Buddy()
m = Mess... | code_fim | hard | {
"lang": "python",
"repo": "BackupTheBerlios/nanoicq",
"path": "/nanoicq/conversation.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> del self._d[n]
def append(self, v):
self._d.append(v)
class Conversation:
def __init__(self, buddy, message):
assert isinstance(buddy, Buddy)
assert isinstance(message, Message)
self._buddy = buddy
self._message = message
def getBuddy(self): ... | code_fim | medium | {
"lang": "python",
"repo": "BackupTheBerlios/nanoicq",
"path": "/nanoicq/conversation.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def getMessage(self): return self._message
def _test():
b = Buddy()
m = Message()
h = History()
h.append(2)
assert h[0] == 2
c = Conversation(b, m)
assert c.getBuddy() == b
assert c.getMessage() == m
if __name__ == '__main__':
_test()
# ---<|fim_prefix|># ... | code_fim | hard | {
"lang": "python",
"repo": "BackupTheBerlios/nanoicq",
"path": "/nanoicq/conversation.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
help = "Nettoyer les demandes obsolètes."
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
def n_days_ago(self, n):
return timezone.now() - timezone.timedelta(days=n)
def handle(self, *args, **options):
organisations_to_delete... | code_fim | hard | {
"lang": "python",
"repo": "neogeo-technologies/idgo",
"path": "/idgo_admin/management/commands/clean_up_actions_out_of_delay.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: neogeo-technologies/idgo path: /idgo_admin/management/commands/clean_up_actions_out_of_delay.py
# Copyright (c) 2017-2021 Neogeo-Technologies.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the Licen... | code_fim | hard | {
"lang": "python",
"repo": "neogeo-technologies/idgo",
"path": "/idgo_admin/management/commands/clean_up_actions_out_of_delay.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> ## Initialize a list to keep track of our position value, a period counter
## to assist in tracking our position relative to the SMA,
## and alpha + beta to represent position sizes in our assets
self.alpha = None
self.beta = None
self.Invested = False
... | code_fim | hard | {
"lang": "python",
"repo": "beemanins-agents/Lean",
"path": "/Algorithm.Python/Alphas/ShareClassMeanReversionAlphaModel.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: beemanins-agents/Lean path: /Algorithm.Python/Alphas/ShareClassMeanReversionAlphaModel.py
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "L... | code_fim | hard | {
"lang": "python",
"repo": "beemanins-agents/Lean",
"path": "/Algorithm.Python/Alphas/ShareClassMeanReversionAlphaModel.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> if not self.Invested:
## Position value greater than SMA indicates that we should 'sell our portfolio' since it will revert back to the mean value
## This means go long 'GOOGL' and go short 'GOOG'
if position_value >= self.sma.Current.Value:
insi... | code_fim | hard | {
"lang": "python",
"repo": "beemanins-agents/Lean",
"path": "/Algorithm.Python/Alphas/ShareClassMeanReversionAlphaModel.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # plt.xlim([0, int(np.max(timeSet))])
if args.auxiliar:
print("Len(Beginnings): ", len(beginings))
for i in beginings:
plt.axvline(x=i, color='g', linestyle='-')
#####horizontal line
# #plt.axhline(y=thr, color='r', linestyle='--', ... | code_fim | hard | {
"lang": "python",
"repo": "DanMartyns/Anomaly_Detection",
"path": "/01_data_conversion/hackrfreadbinfileWithGraphic.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # print(beginings)
max_seconds = len(avgpow)/81
avgpow = avgpow[5:]
maximuns = maximuns[5:]
mean_maximuns = np.mean(maximuns)
print("mean_maximuns:", mean_maximuns)
picos = [x for x in maximuns if x >= 0.95*mean_maximuns ] # all the values higher tha... | code_fim | hard | {
"lang": "python",
"repo": "DanMartyns/Anomaly_Detection",
"path": "/01_data_conversion/hackrfreadbinfileWithGraphic.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: DanMartyns/Anomaly_Detection path: /01_data_conversion/hackrfreadbinfileWithGraphic.py
#!/usr/bin/env python3
import math
import sys
import os
import struct
import subprocess
import threading
import argparse
import time
import pandas as pd
import numpy as np
from bitarray import bitarray
from sys... | code_fim | hard | {
"lang": "python",
"repo": "DanMartyns/Anomaly_Detection",
"path": "/01_data_conversion/hackrfreadbinfileWithGraphic.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Set up the handler chain."""
settings = self.get_settings(prefix='tangled.app.handler.')
# System handler chain
handlers = [settings['exc']]
if self.has_any('static_directory'):
# Only enable static file handler if there's at least one
# l... | code_fim | hard | {
"lang": "python",
"repo": "TangledWeb/tangled.web",
"path": "/tangled/web/app.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: TangledWeb/tangled.web path: /tangled/web/app.py
ngs`).
Extra settings can be passed as keyword args. These settings will
override *all* other settings.
NOTE: If ``settings`` is an :class:`.AppSettings` instance,
extra settings passed here will be ignored; pass them to the
:... | code_fim | hard | {
"lang": "python",
"repo": "TangledWeb/tangled.web",
"path": "/tangled/web/app.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
if not name:
if hasattr(attr, '__name__'):
name = attr.__name__
elif isinstance(attr, property):
name = attr.fget.__name__
if not name:
raise ValueError(
'attribute of type {} requires a name'.f... | code_fim | hard | {
"lang": "python",
"repo": "TangledWeb/tangled.web",
"path": "/tangled/web/app.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Check if all packages to test are already built
built_packages = set([
pkg.name for (path, pkg) in
find_packages(context.package_metadata_path(), warnings=[]).items()])
packages_to_test_names = set(pkg.name for path, pkg in packages_to_test)
if not built_packages.issuper... | code_fim | hard | {
"lang": "python",
"repo": "catkin/catkin_tools",
"path": "/catkin_tools/verbs/catkin_test/test.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: catkin/catkin_tools path: /catkin_tools/verbs/catkin_test/test.py
# 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
#
# U... | code_fim | hard | {
"lang": "python",
"repo": "catkin/catkin_tools",
"path": "/catkin_tools/verbs/catkin_test/test.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Initialize job server
job_server.initialize(
max_jobs=n_jobs,
max_load=None,
gnu_make_enabled=context.use_internal_make_jobserver,
)
try:
# Spin up status output thread
status_thread = ConsoleStatusController(
'test',
['pac... | code_fim | hard | {
"lang": "python",
"repo": "catkin/catkin_tools",
"path": "/catkin_tools/verbs/catkin_test/test.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> @bp.route("/push-callback/<hex_id>", methods=["GET", "POST"])
async def callback(request: Request, hex_id: str) -> sanic.response.HTTPResponse:
topic = request.args.get("hub.topic")
mode = request.args.get("hub.mode")
if mode == "subscribe":
... | code_fim | hard | {
"lang": "python",
"repo": "ShadowJonathan/pywebsub",
"path": "/websub/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ShadowJonathan/pywebsub path: /websub/__init__.py
import asyncio
import datetime
import hashlib
import logging
import os
from dataclasses import dataclass
from functools import partial
from typing import Dict, Callable, Optional, Awaitable
import bs4
import httpx
import sanic
from anyio import c... | code_fim | hard | {
"lang": "python",
"repo": "ShadowJonathan/pywebsub",
"path": "/websub/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Class for language model metrics.
Attributes:
perplexity_per_word: Average perplexity per word of the dataset.
"""
perplexity_per_word: float
def print_metrics(self):
print(f"Perplexity per word : {self.perplexity_per_word: 0.2f}")
def compute_language_mode... | code_fim | medium | {
"lang": "python",
"repo": "appatsekhar/pytext",
"path": "/pytext/metrics/language_model_metrics.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: appatsekhar/pytext path: /pytext/metrics/language_model_metrics.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import math
from typing import NamedTuple
"""
Language model metric utilities.
"""
class LanguageModelMetric(NamedTuple):
"""
... | code_fim | medium | {
"lang": "python",
"repo": "appatsekhar/pytext",
"path": "/pytext/metrics/language_model_metrics.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class LanguageModelMetric(NamedTuple):
"""
Class for language model metrics.
Attributes:
perplexity_per_word: Average perplexity per word of the dataset.
"""
perplexity_per_word: float
def print_metrics(self):
print(f"Perplexity per word : {self.perplexity_per_w... | code_fim | medium | {
"lang": "python",
"repo": "appatsekhar/pytext",
"path": "/pytext/metrics/language_model_metrics.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ScoreUnder/snippets path: /forked.py
# it's forked
import cPickle
import os
import sys
import tempfile
class Fork(object):
def __init__(self):
self._comm_file = tempfile.TemporaryFile(dir="/dev/shm")
self.pid = os.fork()
<|fim_suffix|> def join(self, value):
if se... | code_fim | hard | {
"lang": "python",
"repo": "ScoreUnder/snippets",
"path": "/forked.py",
"mode": "psm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|> return self.pid != 0
def join(self, value):
if self.pid:
os.waitpid(self.pid, 0)
try:
self._comm_file.seek(0)
child_val = cPickle.load(self._comm_file)
self._comm_file.close()
return (value, child_... | code_fim | hard | {
"lang": "python",
"repo": "ScoreUnder/snippets",
"path": "/forked.py",
"mode": "spm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|> if self.pid:
os.waitpid(self.pid, 0)
try:
self._comm_file.seek(0)
child_val = cPickle.load(self._comm_file)
self._comm_file.close()
return (value, child_val)
except EOFError:
return ... | code_fim | hard | {
"lang": "python",
"repo": "ScoreUnder/snippets",
"path": "/forked.py",
"mode": "spm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: NikolayVaklinov10/Interview_Preparation_Kit path: /Miscellaneous/Flipping_bits.py
def flippingBits(n):
<|fim_suffix|> # ^ = bitwise XOR
return n ^ THE_FLIPPING<|fim_middle|> # this number is (2**32)-1
# unsigned integers given which is 32
# 2**32 = 4294967296
# to flip is... | code_fim | medium | {
"lang": "python",
"repo": "NikolayVaklinov10/Interview_Preparation_Kit",
"path": "/Miscellaneous/Flipping_bits.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # ^ = bitwise XOR
return n ^ THE_FLIPPING<|fim_prefix|># repo: NikolayVaklinov10/Interview_Preparation_Kit path: /Miscellaneous/Flipping_bits.py
def flippingBits(n):
<|fim_middle|> # this number is (2**32)-1
# unsigned integers given which is 32
# 2**32 = 4294967296
# to flip is... | code_fim | medium | {
"lang": "python",
"repo": "NikolayVaklinov10/Interview_Preparation_Kit",
"path": "/Miscellaneous/Flipping_bits.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wcmckee/wcmckee path: /kns.py
# coding: utf-8
# Hackathon for Early Childhood Education
#
# kns2014-jogathon
# In[7]:
<|fim_suffix|>
# In[8]:
knsg = requests.get('http://www.kns.ac.nz')
# In[10]:
knsg.text
# In[ ]:<|fim_middle|>import requests
from bs4 import BeautifulSoup
| code_fim | easy | {
"lang": "python",
"repo": "wcmckee/wcmckee",
"path": "/kns.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
# In[10]:
knsg.text
# In[ ]:<|fim_prefix|># repo: wcmckee/wcmckee path: /kns.py
# coding: utf-8
# Hackathon for Early Childhood Education
#
# kns2014-jogathon
# In[7]:
import requests
from bs4 import BeautifulSoup
<|fim_middle|>
# In[8]:
knsg = requests.get('http://www.kns.ac.nz')
| code_fim | easy | {
"lang": "python",
"repo": "wcmckee/wcmckee",
"path": "/kns.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: CortoMaltese3/Mathesis-AdvancedProgrammingWithPython path: /Projects/Week 1/Review excercise/ReviewExcercise_2.py
# Άσκηση 1.4
# βρείτε τη συχνότητα εμφάνισης αλφαβητικών χαρακτήρων που βρίσκονται σε κείμενο
# αρχείου που δίνει ο χρήστης
import re
freq = {}
tonoi = {'ά':'α', 'έ':'ε', 'ή':'η', 'ί... | code_fim | hard | {
"lang": "python",
"repo": "CortoMaltese3/Mathesis-AdvancedProgrammingWithPython",
"path": "/Projects/Week 1/Review excercise/ReviewExcercise_2.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> for letter in tonoi:
txt = txt.lower().replace(letter, tonoi[letter])
alpha = re.findall(r'[ά-ώ]', txt.lower(), re.I) #
for a in alpha:
freq[a] = freq.get(a,0) + 1
total = sum(freq.values())
for ch in sorted(freq.keys()):
print(ch... | code_fim | hard | {
"lang": "python",
"repo": "CortoMaltese3/Mathesis-AdvancedProgrammingWithPython",
"path": "/Projects/Week 1/Review excercise/ReviewExcercise_2.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jwillikers/content-rating path: /capstoneproject/tests/test_models/test_querysets/test_word_queryset.py
from django.test import TestCase
from capstoneproject.models.models.category import Category
from capstoneproject.models.models.word import Word
from capstoneproject.models.models.word_feature ... | code_fim | hard | {
"lang": "python",
"repo": "jwillikers/content-rating",
"path": "/capstoneproject/tests/test_models/test_querysets/test_word_queryset.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> words = list(Word.words.strength(TestWordQuerySet.feature1.strength).strength(TestWordQuerySet.feature2.strength).all())
self.assertIn(TestWordQuerySet.word3, words)
self.assertNotIn(TestWordQuerySet.word1, words)
self.assertNotIn(TestWordQuerySet.word2, words)
self... | code_fim | hard | {
"lang": "python",
"repo": "jwillikers/content-rating",
"path": "/capstoneproject/tests/test_models/test_querysets/test_word_queryset.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kata-ai/wikiner path: /script/entity_filters.py
"""
Filter Automatically Tagged sentence from valid wikipedia entry only
"""
import sys
import json
from urllib.error import HTTPError
from SPARQLWrapper.SPARQLExceptions import QueryBadFormed
from entity_query import generic_query, idsparql, ensp... | code_fim | hard | {
"lang": "python",
"repo": "kata-ai/wikiner",
"path": "/script/entity_filters.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>def get_annotation_type(tag_uri, sparql, get_query: str = GET_TYPE, link_type: bool = False):
annotation_type = set()
tag_result = generic_query(sparql, get_query.replace('[QUERY]', tag_uri))
for rdf_type in tag_result['results']['bindings']:
if link_type:
ret_type = rdf_ty... | code_fim | hard | {
"lang": "python",
"repo": "kata-ai/wikiner",
"path": "/script/entity_filters.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mrbooOoo/PongGame path: /setup.py
import pygame, sys
# General setup
pygame.init()
clock = pygame.time.Clock()
# Setting up the main window
screen_width = 1280
screen_height = 960
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Pong')
# Define the str... | code_fim | medium | {
"lang": "python",
"repo": "mrbooOoo/PongGame",
"path": "/setup.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #Collisions with the bars
if ball.colliderect(player) or ball.colliderect(opponent):
ball_speed_x *= -1
while True:
#Handling input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#Visuals / Drawing the s... | code_fim | hard | {
"lang": "python",
"repo": "mrbooOoo/PongGame",
"path": "/setup.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Read integration information from an HDU list.
Parameters
----------
hdul : fits.HDUList
A list of data HDUs containing "timestream" data.
Returns
-------
None
"""
log.info("Processing scan data:")
tr... | code_fim | medium | {
"lang": "python",
"repo": "SOFIA-USRA/sofia_redux",
"path": "/sofia_redux/scan/custom/example/integration/integration.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: SOFIA-USRA/sofia_redux path: /sofia_redux/scan/custom/example/integration/integration.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy import log
from sofia_redux.scan.integration.integration import Integration
<|fim_suffix|> """
Return a copy of t... | code_fim | hard | {
"lang": "python",
"repo": "SOFIA-USRA/sofia_redux",
"path": "/sofia_redux/scan/custom/example/integration/integration.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>sm.reservedEffect("Effect/Direction6.img/DemonTutorial/Scene2")
sm.sendDelay(1)<|fim_prefix|># repo: Bratah123/v203.4 path: /scripts/field/ds_tuto_home_before.py
# Created by MechAviv
# ID :: [924020010]
# Hidden Street : Scene Change 0
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDire... | code_fim | medium | {
"lang": "python",
"repo": "Bratah123/v203.4",
"path": "/scripts/field/ds_tuto_home_before.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Bratah123/v203.4 path: /scripts/field/ds_tuto_home_before.py
# Created by MechAviv
# ID :: [924020010]
# Hidden Street : Scene Change 0
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.setStandAloneMode(True)
sm.forcedInput(1)
sm.sendDela... | code_fim | easy | {
"lang": "python",
"repo": "Bratah123/v203.4",
"path": "/scripts/field/ds_tuto_home_before.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bharathramh92/shop path: /accounts/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import datetime
class UserExtended(models.Model):
user = models.OneToOneField(User)
profile_picture_url = models.CharField(max_length=2... | code_fim | hard | {
"lang": "python",
"repo": "bharathramh92/shop",
"path": "/accounts/models.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class ForgotPasswordVerification(models.Model):
user = models.ForeignKey(User)
verification_code = models.CharField(max_length=120)
sent_datetime = models.DateTimeField(default=timezone.now)
# true if not expired. Taken care for future time as well(would return false).
def is_not_exp... | code_fim | hard | {
"lang": "python",
"repo": "bharathramh92/shop",
"path": "/accounts/models.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: YingluDeng/CS61A_self_learned path: /lab/lab06/lab06.py
this_file = __file__
def make_adder_inc(a):
"""
>>> adder1 = make_adder_inc(5)
>>> adder2 = make_adder_inc(6)
>>> adder1(2)
7
>>> adder1(2) # 5 + 2 + 1
8
>>> adder1(10) # 5 + 10 + 2
17
>>> [adder1(x)... | code_fim | hard | {
"lang": "python",
"repo": "YingluDeng/CS61A_self_learned",
"path": "/lab/lab06/lab06.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
>>> test_lst = [1, 5, 8, 5, 2, 3]
>>> new_lst = insert_items(test_lst, 5, 7)
>>> new_lst
[1, 5, 7, 8, 5, 7, 2, 3]
>>> large_lst = [1, 4, 8]
>>> large_lst2 = insert_items(large_lst, 4, 4)
>>> large_lst2
[1, 4, 4, 8]
>>> large_lst3 = insert_items(large_lst2, 4, 6)... | code_fim | hard | {
"lang": "python",
"repo": "YingluDeng/CS61A_self_learned",
"path": "/lab/lab06/lab06.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> asteroids = {Coord(3, 2), Coord(3, 3), Coord(3, 1), Coord(4, 3), Coord(2, 4)}
location = Coord(3, 3)
vaporized = vaporize_asteroids(asteroids, location)
assert vaporized == [Coord(3, 2), Coord(4, 3), Coord(2, 4), Coord(3, 1)]<|fim_prefix|># repo: akajuvonen/advent-of-code-2019-python path... | code_fim | hard | {
"lang": "python",
"repo": "akajuvonen/advent-of-code-2019-python",
"path": "/test/test_day10.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: akajuvonen/advent-of-code-2019-python path: /test/test_day10.py
from advent_of_code_2019_python.day10 import find_best_location, Coord, vaporize_asteroids
def test_find_best_location():
<|fim_suffix|> asteroids = {Coord(3, 2), Coord(3, 3), Coord(3, 1), Coord(4, 3), Coord(2, 4)}
location ... | code_fim | hard | {
"lang": "python",
"repo": "akajuvonen/advent-of-code-2019-python",
"path": "/test/test_day10.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>DIGO inválido!')
mostrar = int(input('Verificar CÓDIGO de qual jogador? (999 para parar): '))
print(f' -- LEVANTAMENTO DO JOGADOR {atletas[mostrar]["nome"]}')
for levantamento in range(0, len(atletas[mostrar]["gols"])):
print(f' No jogo {levantamento + 1} fez {atletas[mostrar]... | code_fim | hard | {
"lang": "python",
"repo": "wiliampianco/aulas_python",
"path": "/pacote-download/revisao/dicionarioJogadores.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
print()
print('---' * 15)
for p, i in enumerate(atletas):
print(f'{p:3}', end=' ')
print(f'{str(i["nome"]):<15} {str(i["gols"]):<15} {str(i["total"]):<3}')
print('---' * 15)
while True:
mostrar = int(input('Verificar CÓDIGO de qual jogador? (999 para parar): '))
if mostrar == 999:
... | code_fim | hard | {
"lang": "python",
"repo": "wiliampianco/aulas_python",
"path": "/pacote-download/revisao/dicionarioJogadores.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wiliampianco/aulas_python path: /pacote-download/revisao/dicionarioJogadores.py
atletas = []
jogador = {}
while True:
jogador['nome'] = input('Nome do jogador: ').strip().upper()
partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
gols = []
total = []
for g in... | code_fim | hard | {
"lang": "python",
"repo": "wiliampianco/aulas_python",
"path": "/pacote-download/revisao/dicionarioJogadores.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>@pytest.mark.asyncio
async def test_emailsubmission_set_with_update(account, idmap, email_id, inbox_id, drafts_id):
response1, response2 = await account.emailsubmission_set(
idmap,
create={
"test": {
"identityId": account.id,
"emailId": email... | code_fim | hard | {
"lang": "python",
"repo": "stefan-mrazik/jmap-proxy-python",
"path": "/tests/test_smtpaccount.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: stefan-mrazik/jmap-proxy-python path: /tests/test_smtpaccount.py
import pytest
@pytest.mark.asyncio
async def test_identity_get(account, idmap):
response = await account.identity_get(idmap)
assert response['accountId'] == account.id
assert isinstance(response['notFound'], list)
... | code_fim | hard | {
"lang": "python",
"repo": "stefan-mrazik/jmap-proxy-python",
"path": "/tests/test_smtpaccount.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zhangfaquan/softroboticfish7 path: /fish/pi/ros/catkin_ws/src/depth_control/src/depth_control_node.py
#! /usr/bin/python
import rospy
import numpy as np
from fish_msgs.msg import DepthTestMsg # DepthTestMsg
from fish_msgs.msg import mbedStatusMsg # mbedStatusMsg
from sensor_msgs.msg im... | code_fim | hard | {
"lang": "python",
"repo": "zhangfaquan/softroboticfish7",
"path": "/fish/pi/ros/catkin_ws/src/depth_control/src/depth_control_node.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.