text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|> class Meta:
verbose_name = _('Annotation Tool')
verbose_name_plural = _('Annotation Tools')
unique_together = (('name', 'version'))
ordering = ['name']
def __str__(self):
return '{}@{}'.format(self.name, self.version)<|fim_prefix|># repo: CONABIO-audio/ir... | code_fim | hard | {
"lang": "python",
"repo": "CONABIO-audio/irekua-database",
"path": "/irekua_database/models/annotations/annotation_tools.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: CONABIO-audio/irekua-database path: /irekua_database/models/annotations/annotation_tools.py
from django.db import models
from django.utils.translation import gettext_lazy as _
from irekua_database.models import base
class AnnotationTool(base.IrekuaModelBase):
annotation_type = models.Forei... | code_fim | medium | {
"lang": "python",
"repo": "CONABIO-audio/irekua-database",
"path": "/irekua_database/models/annotations/annotation_tools.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> i_run=0
for runids in runid_list:
runid = runids[0]
acqidlist = runids[1]
calibname = runids[2]
while True:
throw_job = False
for i in range(setup.MAX_PROCESS_THREAD):
if not threads[i].isAlive():
with Logger.Logger(setup.SLOWMONITO... | code_fim | hard | {
"lang": "python",
"repo": "nchikuma/wagasci_software",
"path": "/slowMonitor/autoProcess/auto_dq_history.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nchikuma/wagasci_software path: /slowMonitor/autoProcess/auto_dq_history.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, os, time, subprocess, datetime, math, glob
import threading
sys.path.append("{0}/".format(os.path.abspath(os.path.dirname(__file__))))
import AnaAll
sys.path.appen... | code_fim | hard | {
"lang": "python",
"repo": "nchikuma/wagasci_software",
"path": "/slowMonitor/autoProcess/auto_dq_history.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>def process_loop():
setup = Setup.Setup()
if not os.path.exists(setup.AUTO_RUNID_LIST):
print "No auto procces runid list file: {0}".format(setup.AUTO_RUNID_LIST)
return
while True:
# Read auto process runid list
runid_list = []
acqid_list = []
last_runid = -1
last... | code_fim | hard | {
"lang": "python",
"repo": "nchikuma/wagasci_software",
"path": "/slowMonitor/autoProcess/auto_dq_history.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: shivamraj74/django-shop path: /shop/cascade/catalog.py
from django.contrib.admin import StackedInline
from django.forms import fields, widgets
from django.template.loader import select_template
from django.utils.translation import gettext_lazy as _, gettext
from entangled.forms import EntangledM... | code_fim | hard | {
"lang": "python",
"repo": "shivamraj74/django-shop",
"path": "/shop/cascade/catalog.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class ShopAddToCartPlugin(ShopPluginBase):
name = _("Add Product to Cart")
require_parent = True
form = ShopAddToCartPluginForm
parent_classes = ['BootstrapColumnPlugin']
cache = False
def get_render_template(self, context, instance, placeholder):
templates = []
i... | code_fim | hard | {
"lang": "python",
"repo": "shivamraj74/django-shop",
"path": "/shop/cascade/catalog.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> templates = []
if instance.glossary.get('render_template'):
templates.append(instance.glossary['render_template'])
if context['product'].managed_availability():
template_prefix = 'available-'
else:
template_prefix = ''
templates.e... | code_fim | hard | {
"lang": "python",
"repo": "shivamraj74/django-shop",
"path": "/shop/cascade/catalog.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>def test_power_spectrum_mu():
'''
With this test, power_spectrum_nd and mu_binning are also test.
'''
pp, mm, kk = t2c.power_spectrum_mu(gauss, kbins=kbins, mubins=mubins, box_dims=box_dims)
slope = (np.log10(pp[0,:]*kk**3/2/np.pi**2)[kbins-3]-np.log10(pp[0,:]*kk**3/2/np.pi**2)[3])/(np.log10(kk)[kbi... | code_fim | hard | {
"lang": "python",
"repo": "sambit-giri/tools21cm",
"path": "/tests/test_PowerSpectrum.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sambit-giri/tools21cm path: /tests/test_PowerSpectrum.py
import numpy as np
import tools21cm as t2c
box_dims = 200
dims = [128,128,128]
gauss = np.random.normal(loc=0., scale=1., size=dims)
kbins = 10
mubins = 2
def test_cross_power_spectrum_1d():
'''
With this test, cross_power_spectru... | code_fim | hard | {
"lang": "python",
"repo": "sambit-giri/tools21cm",
"path": "/tests/test_PowerSpectrum.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ivRodriguezCA/symbolicatecrash path: /symbolicatecrash.py
import sys
import getopt
from subprocess import check_output
def error(msg):
if msg != None:
print >>sys.stderr, msg
print >>sys.stderr, "For help use -h"
usage()
def usage():
print >>sys.stderr, "##########"
print >>sys.stderr, "... | code_fim | hard | {
"lang": "python",
"repo": "ivRodriguezCA/symbolicatecrash",
"path": "/symbolicatecrash.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>#####################
# #
# Parse parameters #
# #
#####################
def parse_parameters(opts, rem):
app_name = None
crash_report = None
arch = None
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit(2)
elif opt in ("-n", "--name"):
app_name =... | code_fim | hard | {
"lang": "python",
"repo": "ivRodriguezCA/symbolicatecrash",
"path": "/symbolicatecrash.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> app_name, crash_report, arch = parse_parameters(opts, rem)
if app_name == None or app_name == '' or crash_report == None or crash_report == '' or arch == None or arch == '':
print >>sys.stderr, "Error: Invalid parameters"
usage()
sys.exit(2)
else:
status = check_uuid(app... | code_fim | hard | {
"lang": "python",
"repo": "ivRodriguezCA/symbolicatecrash",
"path": "/symbolicatecrash.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: oauthlib/oauthlib path: /oauthlib/oauth2/rfc6749/clients/__init__.py
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logi<|fim_suffix|>_HEADER, BODY, URI_QUERY, Client
from .legacy_application import LegacyApplicationClient
... | code_fim | medium | {
"lang": "python",
"repo": "oauthlib/oauthlib",
"path": "/oauthlib/oauth2/rfc6749/clients/__init__.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>eApplicationClient
from .service_application import ServiceApplicationClient
from .web_application import WebApplicationClient<|fim_prefix|># repo: oauthlib/oauthlib path: /oauthlib/oauth2/rfc6749/clients/__init__.py
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module... | code_fim | hard | {
"lang": "python",
"repo": "oauthlib/oauthlib",
"path": "/oauthlib/oauth2/rfc6749/clients/__init__.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: glotzerlab/hoomd-blue path: /hoomd/md/dihedral.py
# Copyright (c) 2009-2023 The Regents of the University of Michigan.
# Part of HOOMD-blue, released under the BSD 3-Clause License.
r"""Dihedral forces.
Dihedral force classes apply a force and virial on every particle in the
simulation state co... | code_fim | hard | {
"lang": "python",
"repo": "glotzerlab/hoomd-blue",
"path": "/hoomd/md/dihedral.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> harmonic = dihedral.Periodic()
harmonic.params['A-A-A-A'] = dict(k=3.0, d=-1, n=3, phi0=0)
harmonic.params['A-B-C-D'] = dict(k=100.0, d=1, n=4, phi0=math.pi/2)
"""
_cpp_class_name = "HarmonicDihedralForceCompute"
def __init__(self):
super().__init__()
p... | code_fim | hard | {
"lang": "python",
"repo": "glotzerlab/hoomd-blue",
"path": "/hoomd/md/dihedral.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> atexit.register(handler)
# https://docs.python.org/3/library/atexit.html
# The functions registered via this module are not called when the program
# is killed by a signal not handled by Python, when a Python fatal internal
# error is detected, or when os._exit() is called.
# ... | code_fim | hard | {
"lang": "python",
"repo": "hongyonggan/dbnd",
"path": "/modules/dbnd/src/dbnd/_core/tracking/script_tracking_manager.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hongyonggan/dbnd path: /modules/dbnd/src/dbnd/_core/tracking/script_tracking_manager.py
import atexit
import logging
import os
import sys
import typing
from subprocess import list2cmdline
from typing import Optional
from dbnd._core.configuration import get_dbnd_project_config
from dbnd._core.co... | code_fim | hard | {
"lang": "python",
"repo": "hongyonggan/dbnd",
"path": "/modules/dbnd/src/dbnd/_core/tracking/script_tracking_manager.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: marcoslhc/colorclass path: /tests/test_pad_parse_input.py
"""Test _parse_input()."""
from colorclass import _parse_input
def test_simple():
"""Simple tests."""
assert ('test', 'test') == _parse_input('test')
assert ('\033[1mtest\033[22m', 'test') == _parse_input('{b}test{/b}')
<|f... | code_fim | medium | {
"lang": "python",
"repo": "marcoslhc/colorclass",
"path": "/tests/test_pad_parse_input.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Advanced tests."""
assert ('\033[1m{0}\033[22m', '{0}') == _parse_input('{b}{0}{/b}')
assert ('\033[1;31mTest\033[0m', 'Test') == _parse_input('{b}{red}Test{/all}')
actual = _parse_input('{b}{bgblue}{red}{red}This {red}is {red}a test: {green}{0}{/green}{/red}{/bgblue}{/b}')
expecte... | code_fim | medium | {
"lang": "python",
"repo": "marcoslhc/colorclass",
"path": "/tests/test_pad_parse_input.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> '''CREATE THE PARAMETER PERMUTATIONS
'''
ls = [list(self.p[key]) for key in self.p.keys()]
_pg_out = array(list(product(*ls)))
return _pg_out<|fim_prefix|># repo: matthewcarbone/talos path: /talos/parameters/permutations.py
from numpy import array
from itertools import product
<|fi... | code_fim | easy | {
"lang": "python",
"repo": "matthewcarbone/talos",
"path": "/talos/parameters/permutations.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: matthewcarbone/talos path: /talos/parameters/permutations.py
from numpy import array
from itertools import product
<|fim_suffix|> '''CREATE THE PARAMETER PERMUTATIONS
'''
ls = [list(self.p[key]) for key in self.p.keys()]
_pg_out = array(list(product(*ls)))
return _pg_out<|f... | code_fim | easy | {
"lang": "python",
"repo": "matthewcarbone/talos",
"path": "/talos/parameters/permutations.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> operations = [
migrations.RenameModel(
old_name='AAHeartRate',
new_name='AAWholeDay',
),
migrations.RemoveIndex(
model_name='aawholeday',
name='hrr_aaheart_user_id_4f9bc2_idx',
),
migrations.RemoveIndex(
... | code_fim | medium | {
"lang": "python",
"repo": "wahello/jvb",
"path": "/hrr/migrations/0019_auto_20181226_1100.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
dependencies = [
('hrr', '0018_auto_20181226_0920'),
]
operations = [
migrations.RenameModel(
old_name='AAHeartRate',
new_name='AAWholeDay',
),
migrations.RemoveIndex(
model_name='aawholeday',
name='hrr_aaheart_u... | code_fim | medium | {
"lang": "python",
"repo": "wahello/jvb",
"path": "/hrr/migrations/0019_auto_20181226_1100.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wahello/jvb path: /hrr/migrations/0019_auto_20181226_1100.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-12-26 11:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
<|fim_suffix|> operations = [
... | code_fim | medium | {
"lang": "python",
"repo": "wahello/jvb",
"path": "/hrr/migrations/0019_auto_20181226_1100.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.dbm = None
def test_write_client(self):
self.dbm.createUser(self.test_user_data)
self.dbm.cursor.execute('''SELECT * FROM USERS
WHERE id=%s AND alias=%s AND pass=%s;''', self.test_user_data)
self.assertEqual(self.test_user_data[1:], sel... | code_fim | hard | {
"lang": "python",
"repo": "avlec/tdo",
"path": "/testing/test_DatabaseManager.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: avlec/tdo path: /testing/test_DatabaseManager.py
import binascii
import hashlib
import unittest
from database.DatabaseManager import DatabaseManager
class TestDatabaseManager(unittest.TestCase):
def setUp(self):
self.dbm = DatabaseManager('api', 'password')
hashed_pass = bi... | code_fim | hard | {
"lang": "python",
"repo": "avlec/tdo",
"path": "/testing/test_DatabaseManager.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.dbm.createUser(self.test_user_data)
self.dbm.cursor.execute('''SELECT * FROM USERS
WHERE id=%s AND alias=%s AND pass=%s;''', self.test_user_data)
self.assertEqual(self.test_user_data[1:], self.dbm.cursor.fetchone()[1:])
self.dbm.connection.c... | code_fim | hard | {
"lang": "python",
"repo": "avlec/tdo",
"path": "/testing/test_DatabaseManager.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if line.startswith('#'):
continue
w1, w2, score = line.split(sep)
word1.append(dic.text2word(w1))
word2.append(dic.text2word(w2))
scores.append(float(score))
return WordSim(word1, word2, np.array... | code_fim | hard | {
"lang": "python",
"repo": "jyori112/cython-word2vec",
"path": "/word2vec/evaluation.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> word1.append(dic.text2word(w1))
word2.append(dic.text2word(w2))
scores.append(float(score))
return WordSim(word1, word2, np.array(scores, dtype=np.float32))<|fim_prefix|># repo: jyori112/cython-word2vec path: /word2vec/evaluation.py
import numpy as... | code_fim | hard | {
"lang": "python",
"repo": "jyori112/cython-word2vec",
"path": "/word2vec/evaluation.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jyori112/cython-word2vec path: /word2vec/evaluation.py
import numpy as np
from scipy.stats import spearmanr, pearsonr
class WordSim:
def __init__(self, word1, word2, scores):
self.word1 = word1
self.word2 = word2
self.scores = scores
def evaluate(self, emb, r='sp... | code_fim | hard | {
"lang": "python",
"repo": "jyori112/cython-word2vec",
"path": "/word2vec/evaluation.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_detail_with_valid_id(self):
book = create_book('test', 'test')
self.__get_detail_response(book.id)
self.assertEqual(self.response.context['book'], book)
self.assertEqual(self.response.status_code, 200)
def test_detail_with_invalid_id(self):
self._... | code_fim | medium | {
"lang": "python",
"repo": "vkopio/django-library-manager",
"path": "/library_app/tests/views/test_book_views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> book = create_book('test', 'test')
self.login()
self.__get_detail_response(book.id)
self.assertEqual(self.response.context['book'], book)
self.assertEqual(self.response.context['reservation_queue_position'], 0)
self.assertEqual(self.response.status_code, 20... | code_fim | hard | {
"lang": "python",
"repo": "vkopio/django-library-manager",
"path": "/library_app/tests/views/test_book_views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: vkopio/django-library-manager path: /library_app/tests/views/test_book_views.py
from django.urls import reverse
from library_app.tests.extended_test_case import ExtendedTestCase
from library_app.sample.utilities.factories import create_book
class BookViewTests(ExtendedTestCase):
def test_li... | code_fim | hard | {
"lang": "python",
"repo": "vkopio/django-library-manager",
"path": "/library_app/tests/views/test_book_views.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tylerharper/snooze path: /snooze/transport.py
import urllib
import urllib2
from snooze_exceptions import SnoozeError
class RESTfulRequest(object):
"""
This sends the request out to server and returns the raw response.
No formatting here.
"""
def __init__(self, model):
... | code_fim | hard | {
"lang": "python",
"repo": "tylerharper/snooze",
"path": "/snooze/transport.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if method.upper() == 'POST':
req = urllib2.Request(self.url, self.encoded_args, self.headers)
self.response = urllib2.urlopen(req).read()
elif method.upper() == 'GET':
url = self.url + '?' + self.encoded_args
req = urllib2.Request(self.url, N... | code_fim | hard | {
"lang": "python",
"repo": "tylerharper/snooze",
"path": "/snooze/transport.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: petmir/corpedit path: /model/lockdir.py
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
from time import sleep
from random import randint
# lock categories
RWLOCK = 'rwlock' # exclusive lock
#TODO shared lock: READLOCK = 'readlock'
def lock(filename, lockcat, max_attempts=10, max_wai... | code_fim | hard | {
"lang": "python",
"repo": "petmir/corpedit",
"path": "/model/lockdir.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def pid_filename(filename, lockcat):
'''return the name of the lock pid file for the file'''
return os.path.join(lockdir_name(filename, lockcat), 'pid')
def is_locked(filename, lockcat):
return os.path.isdir(lockdir_name(filename, lockcat))
def pid_of_lock(filename, lockcat):
'''ret... | code_fim | hard | {
"lang": "python",
"repo": "petmir/corpedit",
"path": "/model/lockdir.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: dianna-ai/dianna path: /tests/test_visualization.py
from pathlib import Path
import numpy as np
import pytest
from dianna.visualization import plot_timeseries
def test_plot_timeseries_univariate(tmpdir, random):
"""Test plot univariate time series."""
x = np.linspace(0, 10, 20)
y = ... | code_fim | hard | {
"lang": "python",
"repo": "dianna-ai/dianna",
"path": "/tests/test_visualization.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>def test_plot_timeseries_multivariate(tmpdir, random):
"""Test plot multivariate time series."""
x = np.linspace(start=0, stop=10, num=20)
ys = np.stack((np.sin(x), np.cos(x), np.tan(0.4 * x)))
segments = get_test_segments(data=ys)
output_path = Path(tmpdir) / 'temp_visualization_test_... | code_fim | hard | {
"lang": "python",
"repo": "dianna-ai/dianna",
"path": "/tests/test_visualization.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>exported = list(attributes)
exported.sort()
exported.insert(0, 'key')
export_list = '\n , '.join(exported)
outfile.write(header.format(export_list))
for attr in sorted(list(attributes)):
attr_ = attr.lower().replace('_', '')
if attributes[attr] == 'attr':
outfile.write(attr_declarati... | code_fim | hard | {
"lang": "python",
"repo": "ghcjs/ghcjs-sodium",
"path": "/scripts/gen_html.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>export_list = '\n , '.join(exported)
outfile.write(header.format(export_list))
for attr in sorted(list(attributes)):
attr_ = attr.lower().replace('_', '')
if attributes[attr] == 'attr':
outfile.write(attr_declaration.format(attr_, attr))
elif attributes[attr] == 'boolean':
... | code_fim | hard | {
"lang": "python",
"repo": "ghcjs/ghcjs-sodium",
"path": "/scripts/gen_html.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ghcjs/ghcjs-sodium path: /scripts/gen_html.py
#!/usr/bin/env python
### Elements
outfile = open('src/Alder/Html/Elements.hs', 'w')
html_tags = '''
a abbr address area article aside audio b base bdi bdo big blockquote body br
button canvas caption cite code col colgroup data_ datalist dd del de... | code_fim | hard | {
"lang": "python",
"repo": "ghcjs/ghcjs-sodium",
"path": "/scripts/gen_html.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: desainis/practice-problems path: /two-sum/solution.py
# You are given a list of numbers, and a target number k. Return whether or not there are two numbers in the list that add up to k.
# Example:
# Given [4, 7, 1 , -3, 2] and k = 5,
return true since 4 + 1 = 5.
def two_sum(list, k):
<|fim_suff... | code_fim | easy | {
"lang": "python",
"repo": "desainis/practice-problems",
"path": "/two-sum/solution.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>print two_sum([4,7,1,-3,2], 5)
# True
# Try to do it in a single pass of the list.<|fim_prefix|># repo: desainis/practice-problems path: /two-sum/solution.py
# You are given a list of numbers, and a target number k. Return whether or not there are two numbers in the list that add up to k.
<|fim_middle|... | code_fim | medium | {
"lang": "python",
"repo": "desainis/practice-problems",
"path": "/two-sum/solution.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Fill this in.
print two_sum([4,7,1,-3,2], 5)
# True
# Try to do it in a single pass of the list.<|fim_prefix|># repo: desainis/practice-problems path: /two-sum/solution.py
# You are given a list of numbers, and a target number k. Return whether or not there are two numbers in the list that add up t... | code_fim | easy | {
"lang": "python",
"repo": "desainis/practice-problems",
"path": "/two-sum/solution.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: y3nk0/Multi-label-with-Deep-Learning path: /adios/callbacks.py
"""
Multi-label classification specific callbacks.
"""
import numpy as np
import ipdb
from keras.callbacks import Callback
class HammingLoss(Callback):
<|fim_suffix|> self.datasets = datasets
self.batch_size = batch_s... | code_fim | medium | {
"lang": "python",
"repo": "y3nk0/Multi-label-with-Deep-Learning",
"path": "/adios/callbacks.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if 'train' in self.metrics:
logs['hl'] = self.metrics['train']
if 'valid' in self.metrics:
logs['val_hl'] = self.metrics['valid']
def on_epoch_end(self, epoch, logs={}):
if 'train' in self.metrics:
logs['hl'] = self.metrics['train']
... | code_fim | medium | {
"lang": "python",
"repo": "y3nk0/Multi-label-with-Deep-Learning",
"path": "/adios/callbacks.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>ignore[:0]=[source]
ignore.append(destination)
#tup = tuple(ignore)
#print(ignore)
temp = 0
for i in range(len(ignore)):
if ignore[i] not in dict1:
#print("ignore",ignore[i], count)
dict1[ignore[i]] = count
count = count + 1
temp = count
else:
continu... | code_fim | hard | {
"lang": "python",
"repo": "harsh52/Assignments-competitive_coding",
"path": "/interview_ques_hack/Min_cost_to_reach_dist_juicepay.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: harsh52/Assignments-competitive_coding path: /interview_ques_hack/Min_cost_to_reach_dist_juicepay.py
import sys
INF = sys.maxsize
def minCost(cost):
# dist[i] stores minimum
# cost to reach station i
# from station 0.
dist=[0 for i in range(N)]
for i in range(N):
... | code_fim | hard | {
"lang": "python",
"repo": "harsh52/Assignments-competitive_coding",
"path": "/interview_ques_hack/Min_cost_to_reach_dist_juicepay.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>N = int(input())
ignore = [int(input()) for i in range(N)]
noe = int(input())
edges = [tuple(map(int,input().split())) for i in range(noe)]
source = int(input())
destination = int(input())
'''
print(N)
print(ignore)
print(noe)
print(edges)
print(source)
print(destination)
'''
count = 0
dict1 = {}
graph =... | code_fim | hard | {
"lang": "python",
"repo": "harsh52/Assignments-competitive_coding",
"path": "/interview_ques_hack/Min_cost_to_reach_dist_juicepay.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> obj1_x_sacatter.append(ob_1_x[i])
obj2_x_sacatter.append(ob_2_x[i])
obj3_x_sacatter.append(ob_3_x[i])
obj1_y_sacatter.append(ob_1_y[i])
obj2_y_sacatter.append(ob_2_y[i])
obj3_y_sacatter.append(ob_3_y[i])
ax.scatter(obj1_x_sacatter,obj1_y_sacatter,s=1,alpha=0.7,color='... | code_fim | hard | {
"lang": "python",
"repo": "Ahmed-alkharusi/Interesting-problems-",
"path": "/The three-body problem (RK4)/Cpp version/plot.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
frame = 3
shift_y = 0
shift_x = 0
for j in range(int(len(ob_1_x)/save_every_n_frames)-1):
i = j*save_every_n_frames
fig = plt.figure(figsize=(16,9))
avx = (ob_1_x[i] + ob_2_x[i] + ob_3_x[i])/3
avy = (ob_1_y[i] + ob_2_y[i] + ob_3_y[i])/3
ax = fig.add_subplot(111, autoscale_on=... | code_fim | medium | {
"lang": "python",
"repo": "Ahmed-alkharusi/Interesting-problems-",
"path": "/The three-body problem (RK4)/Cpp version/plot.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Ahmed-alkharusi/Interesting-problems- path: /The three-body problem (RK4)/Cpp version/plot.py
"""
=============================================================================
Solving the three - body problem numerically using the RK4 (Plots)
===============================================... | code_fim | hard | {
"lang": "python",
"repo": "Ahmed-alkharusi/Interesting-problems-",
"path": "/The three-body problem (RK4)/Cpp version/plot.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sonalchandani/dataiku-api-client-python path: /dataikuapi/dss/admin.py
from .future import DSSFuture
class DSSConnection(object):
"""
A connection on the DSS instance
"""
def __init__(self, client, name):
self.client = client
self.name = name
############... | code_fim | hard | {
"lang": "python",
"repo": "sonalchandani/dataiku-api-client-python",
"path": "/dataikuapi/dss/admin.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def user_identity(self):
"""
Make the rule map each DSS user to a UNIX user of the same name
"""
self.raw['type'] = 'IDENTITY'
return self
def user_single(self, dss_user, unix_user, hadoop_user=None):
"""
Make the rule map a given DSS user t... | code_fim | hard | {
"lang": "python",
"repo": "sonalchandani/dataiku-api-client-python",
"path": "/dataikuapi/dss/admin.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>def create_strategy_variant_request(variant_id, strategy, legs):
''' Simple utility to generate a StrategyVariantRequest structure.
Parameters
----------
variant_id : :obj:`int`
Variant ID.
strategy : :obj:`str`, {'CoveredCall', 'MarriedPuts', \
'VerticalCallSpread... | code_fim | hard | {
"lang": "python",
"repo": "clinton0313/questradeapi",
"path": "/questradeapi/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> Parameters
----------
quantity : :obj:`double`
Order quantity.
action : :obj:`str`, {'Buy', 'Sell'}
Order side.
limit_price : :obj:`double`
Limit price.
stop_price : :obj:`double`
Stop price.
order_type : :obj:`str`, {'Market', 'Limit',... | code_fim | hard | {
"lang": "python",
"repo": "clinton0313/questradeapi",
"path": "/questradeapi/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: clinton0313/questradeapi path: /questradeapi/utils.py
from tzlocal import get_localzone
def add_local_tz(date):
''' Add the local time zone to the given date and returns a new date.
Parameters
----------
date : :obj:`datetime`
Date to which to adjust with the loc... | code_fim | hard | {
"lang": "python",
"repo": "clinton0313/questradeapi",
"path": "/questradeapi/utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pyspeckit/pyspeckit path: /pyspeckit/spectrum/models/h2co_mm.py
"""
===========================
Formaldehyde mm-line fitter
===========================
This is a formaldehyde 3_03-2_02 / 3_22-221 and 3_03-2_02/3_21-2_20 fitter.
It is based entirely on RADEX models.
This is the EWR fork of the f... | code_fim | hard | {
"lang": "python",
"repo": "pyspeckit/pyspeckit",
"path": "/pyspeckit/spectrum/models/h2co_mm.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> pass
formaldehyde_mm_fitter = formaldehyde_mm_model(formaldehyde_mm, 3,
parnames=['amp','center','width'],
parlimited=[(False,False),(False,False), (True,False)],
parlimits=[(0,0), (0,0), (0,0)],
shortvarnames=("A","v","\\sigma"), # specify the parameter names (TeX is ... | code_fim | hard | {
"lang": "python",
"repo": "pyspeckit/pyspeckit",
"path": "/pyspeckit/spectrum/models/h2co_mm.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
mdl = formaldehyde_vtau(xarr, Tex=amp*0.01, tau=0.01, xoff_v=xoff_v,
width=width,
return_components=return_components)
if return_components:
mdlpeak = np.abs(mdl).squeeze().sum(axis=0).max()
else:
mdlpeak = np.abs(mdl).max()
if mdlpeak > 0:
... | code_fim | hard | {
"lang": "python",
"repo": "pyspeckit/pyspeckit",
"path": "/pyspeckit/spectrum/models/h2co_mm.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Deepbody-me/matrix-service path: /tests/functional/transformers/validation.py
import unittest
import typing
from matrix.common.aws.redshift_handler import TableName
from matrix.common.constants import BundleType
class TransformerValidator(unittest.TestCase):
def validate(self, actual_rows:... | code_fim | hard | {
"lang": "python",
"repo": "Deepbody-me/matrix-service",
"path": "/tests/functional/transformers/validation.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class ProjectPublicationContributorValidator(TransformerValidator):
def validate(self, actual_rows: typing.Tuple, expected_rows: dict, bundle_type: BundleType):
project_rows = actual_rows[0][1]
self.assertTrue(expected_rows[TableName.PROJECT] in project_rows)
contributor_rows ... | code_fim | hard | {
"lang": "python",
"repo": "Deepbody-me/matrix-service",
"path": "/tests/functional/transformers/validation.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_let_discovery(self):
x = EVar("x").with_type(INT)
spec = ESum([x, x, x, x])
assert retypecheck(spec)
y = EVar("y").with_type(INT)
goal = ELet(ESum([x, x]), ELambda(y, ESum([y, y])))
assert retypecheck(goal)
assert check_discovery(spec=sp... | code_fim | hard | {
"lang": "python",
"repo": "MostAwesomeDude/cozy",
"path": "/tests/synthesis.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: MostAwesomeDude/cozy path: /tests/synthesis.py
import unittest
from cozy.syntax_tools import mk_lambda, pprint, alpha_equivalent
from cozy.target_syntax import *
from cozy.contexts import RootCtx, UnderBinder
from cozy.typecheck import retypecheck
from cozy.evaluation import mkval
from cozy.cost... | code_fim | hard | {
"lang": "python",
"repo": "MostAwesomeDude/cozy",
"path": "/tests/synthesis.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tongni1975/gtfspy path: /gtfspy/routing/test/test_journey_data.py
from unittest import TestCase
import pyximport
from gtfspy.routing.journey_data import JourneyDataManager
from gtfspy.routing.label import LabelTimeWithBoardingsCount
pyximport.install()
import shutil
import os
from gtfspy.impor... | code_fim | hard | {
"lang": "python",
"repo": "tongni1975/gtfspy",
"path": "/gtfspy/routing/test/test_journey_data.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # input some journeys
destination_stop = 1
origin_stop = 2
self.jdm.import_journey_data_for_target_stop(destination_stop,
{origin_stop:
[LabelTimeWithBoardingsCount(... | code_fim | hard | {
"lang": "python",
"repo": "tongni1975/gtfspy",
"path": "/gtfspy/routing/test/test_journey_data.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if 'ylim' in kwargs and kwargs['ylim']:
ax1.set_ylim(kwargs['ylim'][0], kwargs['ylim'][1])
if 'graph_title' in kwargs and kwargs['graph_title']:
ax1.set_title(kwargs['graph_title'])
else:
ax1.set_title("Title")
if 'xlabel' in kwargs and kwargs['xlabel']:
a... | code_fim | hard | {
"lang": "python",
"repo": "toru-ver4/ColorScienceLib",
"path": "/src/plot_utility.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: toru-ver4/ColorScienceLib path: /src/plot_utility.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# 概要
plot補助ツール群
# 参考
* [matplotlibでグラフの文字サイズを大きくする](https://goo.gl/E5fLxD)
* [Customizing matplotlib](http://matplotlib.org/users/customizing.html)
"""
import numpy as np
from cycler import... | code_fim | hard | {
"lang": "python",
"repo": "toru-ver4/ColorScienceLib",
"path": "/src/plot_utility.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ChromeHearts/s3grep path: /boto_stream.py
import io
import botocore.response
class BotoStreamBody(io.RawIOBase):
<|fim_suffix|> sizetoread = len(b)
data = self._body.read(sizetoread)
if data is None:
return 0
sizeread = len(data)
b[:sizeread] ... | code_fim | medium | {
"lang": "python",
"repo": "ChromeHearts/s3grep",
"path": "/boto_stream.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> sizetoread = len(b)
data = self._body.read(sizetoread)
if data is None:
return 0
sizeread = len(data)
b[:sizeread] = data
return sizeread
def readall(self):
return self._body.read()
def readable(self):
return True<|fim_p... | code_fim | easy | {
"lang": "python",
"repo": "ChromeHearts/s3grep",
"path": "/boto_stream.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return self._body.read()
def readable(self):
return True<|fim_prefix|># repo: ChromeHearts/s3grep path: /boto_stream.py
import io
import botocore.response
class BotoStreamBody(io.RawIOBase):
<|fim_middle|> def __init__(self, body: botocore.response.StreamingBody):
self.... | code_fim | hard | {
"lang": "python",
"repo": "ChromeHearts/s3grep",
"path": "/boto_stream.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> peridic_carpool_index = self.commuting_modes_index['periodic_carpool']
carpool_only_index = self.commuting_modes_index['carpool_only']
periodic_carpool_additionality = _meets_additionality(peridic_carpool_index)
carpool_only_additionality = _meets_additionality(carpool_only_index)
if... | code_fim | hard | {
"lang": "python",
"repo": "tavakyan/methodology-contracts",
"path": "/draft-vyper/transportation/additionality_service.v.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def _is_mode_dominant_market(commuting_mode_index: uint256) -> bool:
if _is_largest_market_share(commuting_mode_index) or
_herfindahl_hirschman_index(commuting_mode_index) < self.min_herfindahl_hirschman_index:
return true
return false
def _meets_additionality(commuting_mode_index: u... | code_fim | hard | {
"lang": "python",
"repo": "tavakyan/methodology-contracts",
"path": "/draft-vyper/transportation/additionality_service.v.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tavakyan/methodology-contracts path: /draft-vyper/transportation/additionality_service.v.py
commuting_modes = public(string[])
commuting_market_indices = public(string[uint256])
commuting_modes_market_share = public(decimal[])
def __init__(commuting_modes_market_share: decimal[9]):
# Number... | code_fim | hard | {
"lang": "python",
"repo": "tavakyan/methodology-contracts",
"path": "/draft-vyper/transportation/additionality_service.v.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return self.a // x.a
def __mod__(self, x):
return self.a % x.a
def __pow__(self, x):
return self.a ** x.a
def __str__(self):
return str(self.a)
ob1 = A(30)
ob2 = A(20)
print('Addition =' , ob1 + ob2)
print('Subtraction =' , ob1 - ob2)
prin... | code_fim | hard | {
"lang": "python",
"repo": "krishankansal/PythonPrograms",
"path": "/oops/#042_operator_overloading.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>#print(ob3 - ob4)
# We can't do this
'''Error Message
TypeError: unsupported operand type(s) for +: 'int' and 'str'
'''
#print(ob1 + ob4)<|fim_prefix|># repo: krishankansal/PythonPrograms path: /oops/#042_operator_overloading.py
class A:
def __init__(self, a):
self.a = a
# adding ... | code_fim | hard | {
"lang": "python",
"repo": "krishankansal/PythonPrograms",
"path": "/oops/#042_operator_overloading.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: krishankansal/PythonPrograms path: /oops/#042_operator_overloading.py
class A:
def __init__(self, a):
self.a = a
# adding two objects
# magic method
def __add__(self, x):
<|fim_suffix|>print('Addition =' , ob1 + ob2)
print('Subtraction =' , ob1 - ob2)
print('Mul... | code_fim | hard | {
"lang": "python",
"repo": "krishankansal/PythonPrograms",
"path": "/oops/#042_operator_overloading.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> operations = [
migrations.RenameField(
model_name='questions',
old_name='question_name',
new_name='name',
),
migrations.RenameField(
model_name='questions',
old_name='question_type',
new_name='type',
... | code_fim | medium | {
"lang": "python",
"repo": "morethanmin/Fooorm",
"path": "/core/migrations/0005_auto_20210806_2255.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: morethanmin/Fooorm path: /core/migrations/0005_auto_20210806_2255.py
# Generated by Django 3.2.5 on 2021-08-06 13:55
from django.db import migrations
<|fim_suffix|>
dependencies = [
('core', '0004_auto_20210806_2245'),
]
operations = [
migrations.RenameField(
... | code_fim | medium | {
"lang": "python",
"repo": "morethanmin/Fooorm",
"path": "/core/migrations/0005_auto_20210806_2255.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> newTestInput = np.zeros(testInput.shape, dtype='int')
for n in range(testInput.shape[0]):
newTestInput[n, 0, 0] = testInput[n, 0, 0]
for t in range(1, testInput.shape[1]):
if testInput[n, t, 0] != 0:
word = questionIdict[testInput... | code_fim | hard | {
"lang": "python",
"repo": "standardgalactic/imageqa-public",
"path": "/src/imageqa_visprior.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: standardgalactic/imageqa-public path: /src/imageqa_visprior.py
n range(t + 1, data.shape[0]):
word = questionIdict[data[u, 0] - 1]
lexname = lookupLexname(word)
if (lexname is not None and \
lexname.startswith('noun')) or \
... | code_fim | hard | {
"lang": "python",
"repo": "standardgalactic/imageqa-public",
"path": "/src/imageqa_visprior.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: standardgalactic/imageqa-public path: /src/imageqa_visprior.py
stionIdict):
"""
Locate the object of where questions.
Very naive heuristic: take the noun immediately after "where".
"""
where = questionDict['where']
for t in range(data.shape[0] - 1):
if data[t, 0] =... | code_fim | hard | {
"lang": "python",
"repo": "standardgalactic/imageqa-public",
"path": "/src/imageqa_visprior.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: FelipeDuarteFerreira/hermione path: /hermione/not_implemented_file_text/database.txt
import pandas as pd
from ml.data_source.base import DataSource
class DataBase(DataSource):
def __init__(self):
"""
Constructor.
Parameters
-----------
... | code_fim | hard | {
"lang": "python",
"repo": "FelipeDuarteFerreira/hermione",
"path": "/hermione/not_implemented_file_text/database.txt",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> Returns
-------
pd.DataFrame
Dataframe with data
"""
pass
def open_connection(self, connection):
"""
Opens the connection to the database
Parameters
-----------
connection : string
... | code_fim | hard | {
"lang": "python",
"repo": "FelipeDuarteFerreira/hermione",
"path": "/hermione/not_implemented_file_text/database.txt",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: EricNeid/weatherstation_py path: /weatherstation/misc/utils.py
"""utils for setting locale and getting well formated time"""
import os
import platform
import locale
import time
def read_api_key(path):
"""read api key from given path"""
path = os.path.abspath(path)
if not os.path.ex... | code_fim | hard | {
"lang": "python",
"repo": "EricNeid/weatherstation_py",
"path": "/weatherstation/misc/utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def get_time_human_readable():
"""
returns well formated time string.
for example: Donnerstag, 21:00
"""
return time.strftime("%A, %H:%M")<|fim_prefix|># repo: EricNeid/weatherstation_py path: /weatherstation/misc/utils.py
"""utils for setting locale and getting well formated time"""... | code_fim | hard | {
"lang": "python",
"repo": "EricNeid/weatherstation_py",
"path": "/weatherstation/misc/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: microsoft/pgtoolsservice path: /ossdbtoolsservice/object_explorer/contracts/session_created_notification.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. ... | code_fim | hard | {
"lang": "python",
"repo": "microsoft/pgtoolsservice",
"path": "/ossdbtoolsservice/object_explorer/contracts/session_created_notification.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Parameters to be sent back when an object explorer session is created"""
def __init__(self):
self.error_message: Optional[str] = None
self.success: bool = True
self.session_id: Optional[str] = None
self.root_node: Optional[NodeInfo] = None
SESSION_CREATED_METH... | code_fim | medium | {
"lang": "python",
"repo": "microsoft/pgtoolsservice",
"path": "/ossdbtoolsservice/object_explorer/contracts/session_created_notification.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class SessionCreatedParameters:
"""Parameters to be sent back when an object explorer session is created"""
def __init__(self):
self.error_message: Optional[str] = None
self.success: bool = True
self.session_id: Optional[str] = None
self.root_node: Optional[NodeInf... | code_fim | medium | {
"lang": "python",
"repo": "microsoft/pgtoolsservice",
"path": "/ossdbtoolsservice/object_explorer/contracts/session_created_notification.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Get haversine distance between two points.
Expects points as (latitude, longitude) tuples.
"""
# cHaversine expects points to be given as (latitude, longitude) pairs.
# TODO: Determine if this check for non-null values is necessary.
if point_a a... | code_fim | medium | {
"lang": "python",
"repo": "akegan/encompass",
"path": "/backend/models/distance.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Retrieve a distance matrix."""
return [
[self.measure_between_two_points(point_a, point_b) for point_b in destination_points]
for point_a in source_points
]<|fim_prefix|># repo: akegan/encompass path: /backend/models/distance.py
"""Classes for measuring ... | code_fim | hard | {
"lang": "python",
"repo": "akegan/encompass",
"path": "/backend/models/distance.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: akegan/encompass path: /backend/models/distance.py
"""Classes for measuring distances between points."""
from cHaversine import haversine
from backend.models.base import Measurer
class HaversineDistance(Measurer):
<|fim_suffix|> def measure_between_two_points(self, point_a, point_b):
... | code_fim | medium | {
"lang": "python",
"repo": "akegan/encompass",
"path": "/backend/models/distance.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: vpistis/django-star-ratings path: /tests/test_user_rating_manager.py
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from model_mommy import mommy
from star_ratings.models import Rating, UserRating
from .m... | code_fim | medium | {
"lang": "python",
"repo": "vpistis/django-star-ratings",
"path": "/tests/test_user_rating_manager.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> Rating.objects.rate(foo, 1, user=mommy.make(get_user_model()))
expected = Rating.objects.rate(foo, 1, user=user).user_ratings.get(user=user)
self.assertEqual(
expected,
UserRating.objects.for_instance_by_user(foo, user=user),
)<|fim_prefix|># repo: ... | code_fim | hard | {
"lang": "python",
"repo": "vpistis/django-star-ratings",
"path": "/tests/test_user_rating_manager.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: yaananth/mt-lob path: /queue_imbalance/prepare_data.py
import logging
from lob_data_utils import lob, roc_results
def main(s):
errors = []
print('************************************', s)
try:
df, _ = lob.load_data(str(s), data_dir='data/INDEX/', include_test=False)
... | code_fim | medium | {
"lang": "python",
"repo": "yaananth/mt-lob",
"path": "/queue_imbalance/prepare_data.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> pool = Pool(processes=3)
stocks = list(roc_results.results.keys())
res = [pool.apply_async(main, [s]) for s in stocks]
print([r.get() for r in res])<|fim_prefix|># repo: yaananth/mt-lob path: /queue_imbalance/prepare_data.py
import logging
from lob_data_utils import lob, roc_results
de... | code_fim | medium | {
"lang": "python",
"repo": "yaananth/mt-lob",
"path": "/queue_imbalance/prepare_data.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: JackZhouSz/human_motion_manifold path: /trainer.py
ch.div((input_pos - pos_mean), pos_std)
nm_input_pos = nm_input_pos[:, :, pos_dimTouse]
# Euclidean distance (with joint-wise square root, not MSE!)
nm_input_pos = nm_input_pos.view(nm_input_pos.shape[0], nm_input_pos.sha... | code_fim | hard | {
"lang": "python",
"repo": "JackZhouSz/human_motion_manifold",
"path": "/trainer.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.