text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|> with redis.Redis().lock(BATCH_LOCK):
StoredHook.objects.create(
target=target_url,
event=hook_event,
user_id=hook_user_id,
payload=hook_payload,
hook_id=hook
)
count = StoredHook.objects.filter(target=target_url).coun... | code_fim | hard | {
"lang": "python",
"repo": "GradConnection/django-rest-hooks-delivery",
"path": "/rest_hooks_delivery/tasks.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: GradConnection/django-rest-hooks-delivery path: /rest_hooks_delivery/tasks.py
# -*- coding: utf-8 -*-
# vim: ft=python:sw=4:ts=4:sts=4:et:
from __future__ import absolute_import
from celery import shared_task
from rest_hooks_delivery.models import StoredHook
from django.conf import settings
fr... | code_fim | hard | {
"lang": "python",
"repo": "GradConnection/django-rest-hooks-delivery",
"path": "/rest_hooks_delivery/tasks.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bellhops/django-crud-filters path: /CRUDFilters/serializers.py
from rest_framework import serializers
<|fim_suffix|> class Meta:
model = None<|fim_middle|>
# Swagger requires us to have serializers for all modelViewSets, even when the
# underlying model is an abstract class and doesn'... | code_fim | hard | {
"lang": "python",
"repo": "bellhops/django-crud-filters",
"path": "/CRUDFilters/serializers.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> class Meta:
model = None<|fim_prefix|># repo: bellhops/django-crud-filters path: /CRUDFilters/serializers.py
from rest_framework import serializers
<|fim_middle|># Swagger requires us to have serializers for all modelViewSets, even when the
# underlying model is an abstract class and doesn'... | code_fim | hard | {
"lang": "python",
"repo": "bellhops/django-crud-filters",
"path": "/CRUDFilters/serializers.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gabestein/muck path: /common/all.py
# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/ by George King.
<|fim_suffix|>from .fs import *
from .io import *
from .subproc import *
from .util import *<|fim_middle|>from functools import singledispatch
| code_fim | easy | {
"lang": "python",
"repo": "gabestein/muck",
"path": "/common/all.py",
"mode": "psm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>from .fs import *
from .io import *
from .subproc import *
from .util import *<|fim_prefix|># repo: gabestein/muck path: /common/all.py
# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/ by George King.
<|fim_middle|>from functools import singledispatch
| code_fim | easy | {
"lang": "python",
"repo": "gabestein/muck",
"path": "/common/all.py",
"mode": "spm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> add_title = ' (penalty = ' + str(penalty) + ')'
# plot results
plot_results(num_iterations=config.num_epochs+1, train_plots=trainer.train_accuracy, test_plots=test_plots, loss_plots=loss_plots, save=True, show=False, path=path, experiment='simple_cnn_ewc_' + str(penalty), title=co... | code_fim | hard | {
"lang": "python",
"repo": "asinugobi/ewc",
"path": "/sequential/mains/simple_cnn_layerwise_ewc.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: asinugobi/ewc path: /sequential/mains/simple_cnn_layerwise_ewc.py
import tensorflow as tf
import numpy as np
import os.path
import sys
sys.path.append('/home/asinugobi/tensorflow-1.5.0/tensorflow_pkg/ewc/sequential')
from data_loader.data_generator import DataGenerator
from data_loader.data_... | code_fim | hard | {
"lang": "python",
"repo": "asinugobi/ewc",
"path": "/sequential/mains/simple_cnn_layerwise_ewc.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>async def test_not_configuring_cast_not_creates_entry(hass):
"""Test that no config will not create an entry."""
with patch(
"homeassistant.components.cast.async_setup_entry", return_value=True
) as mock_setup:
await async_setup_component(hass, cast.DOMAIN, {})
await ha... | code_fim | hard | {
"lang": "python",
"repo": "DerMetzger69/core",
"path": "/tests/components/cast/test_init.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>async def test_zeroconf_setup(hass):
"""Test we can finish a config flow through zeroconf."""
result = await hass.config_entries.flow.async_init(
"cast", context={"source": "zeroconf"}
)
assert result["type"] == "form"
result = await hass.config_entries.flow.async_configure(re... | code_fim | hard | {
"lang": "python",
"repo": "DerMetzger69/core",
"path": "/tests/components/cast/test_init.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: DerMetzger69/core path: /tests/components/cast/test_init.py
"""Tests for the Cast config flow."""
from unittest.mock import ANY, patch
import pytest
from homeassistant import config_entries, data_entry_flow
from homeassistant.components import cast
from homeassistant.setup import async_setup_co... | code_fim | hard | {
"lang": "python",
"repo": "DerMetzger69/core",
"path": "/tests/components/cast/test_init.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mbercx/cage path: /cage/scripts/checkCalc.py
# Encoding UTF-8
import sys
import os
from pymatgen.io import nwchem
from json import JSONDecodeError
"""
Script that checks if a calculation has completed successfully from the ouput
file.
"""
# TODO Add method of extracting data more quickly
<|fi... | code_fim | hard | {
"lang": "python",
"repo": "mbercx/cage",
"path": "/cage/scripts/checkCalc.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>try:
error = False
for data in out.data:
if data['has_error']:
error = True
print('File: ' + os.path.abspath(filename))
if out.data[-1]['task_time'] != 0:
print('Calculation completed in ' + str(out.data[-1]['task_time']) + 's')
else:
print('No timi... | code_fim | hard | {
"lang": "python",
"repo": "mbercx/cage",
"path": "/cage/scripts/checkCalc.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>filename = sys.argv[1]
try:
out = nwchem.NwOutput(filename, fmt='json')
except JSONDecodeError:
try:
out = nwchem.NwOutput(filename)
except:
raise IOError('File not found.')
try:
error = False
for data in out.data:
if data['has_error']:
error = Tru... | code_fim | medium | {
"lang": "python",
"repo": "mbercx/cage",
"path": "/cage/scripts/checkCalc.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: cpinte/RMPCDMD path: /experiments/03-single-janus/rotation_analysis.py
#!/usr/bin/env python
"""
Analyze the rotational motion of a L-shaped colloid.
"""
from __future__ import print_function, division
import numpy as np
import h5py
import argparse
parser = argparse.ArgumentParser()
parser.add_... | code_fim | hard | {
"lang": "python",
"repo": "cpinte/RMPCDMD",
"path": "/experiments/03-single-janus/rotation_analysis.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>v12_inplane = v12 - np.sum(v12*one_z, axis=1).reshape((-1,1))*one_z
off_in = np.sum(v12_inplane*one_z, axis=1)
r12 = pos[:,n_planar-args.arm_width,:] - pos[:,0,:]
dist12 = np.sqrt(np.sum((pos[0,n_planar-args.arm_width,:]-pos[0,0,:])**2))
r12 /= dist12
one_y = np.cross(one_z, r12)
omega_z = np.sum(v12_... | code_fim | hard | {
"lang": "python",
"repo": "cpinte/RMPCDMD",
"path": "/experiments/03-single-janus/rotation_analysis.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: JJediny/Cartoview path: /cartoview/catalog/csw_catalog/views.py
import json
import os.path
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import settings
from cartoview2.catalog.models import Resource
from pycsw import server
CONFIGURATION = {
'ser... | code_fim | hard | {
"lang": "python",
"repo": "JJediny/Cartoview",
"path": "/cartoview/catalog/csw_catalog/views.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>@csrf_exempt
def csw(request):
"""CSW WSGI wrapper"""
# serialize settings.CSW into SafeConfigParser
# object for interaction with pycsw
mdict = dict(settings.CSW, **CONFIGURATION)
# update server.url
server_url = '%s://%s%s' % \
(request.META['wsgi.url_scheme'],
... | code_fim | medium | {
"lang": "python",
"repo": "JJediny/Cartoview",
"path": "/cartoview/catalog/csw_catalog/views.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gjtempleton/matasano_cryptopals path: /set1/challenge_6.py
from .utils import string_to_bits
def break_repeating_key_xor(ciphertext):
return ""
<|fim_suffix|> if len(string2) != len(string1):
raise Exception("Two strings must be the same length")
hanning_distance_score = 0
... | code_fim | medium | {
"lang": "python",
"repo": "gjtempleton/matasano_cryptopals",
"path": "/set1/challenge_6.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if len(string2) != len(string1):
raise Exception("Two strings must be the same length")
hanning_distance_score = 0
i = 0
string1_bits = string_to_bits(string1)
string2_bits = string_to_bits(string2)
print("{} rgikthrrgkghuk {}".format(len(string1_bits), len(string2_bits)... | code_fim | medium | {
"lang": "python",
"repo": "gjtempleton/matasano_cryptopals",
"path": "/set1/challenge_6.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: osoken/sqlite-tensor path: /tests/test_core.py
# -*- coding: utf-8 -*-
import unittest
import sqlite3
import numpy as np
from sqlite_tensor import core
class TensorTester(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test__init__(self):... | code_fim | hard | {
"lang": "python",
"repo": "osoken/sqlite-tensor",
"path": "/tests/test_core.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> t = core.Tensor(np.zeros(3), {'a': 1, 'b': 2})
s = core.Database.deserialize(
core.Database.serialize(t)
)
self.assertTrue(np.all(t.data == s.data))
self.assertTrue(all(
t.attr[k] == s.attr[k] for k in
set(t.attr.keys()).union(s.a... | code_fim | hard | {
"lang": "python",
"repo": "osoken/sqlite-tensor",
"path": "/tests/test_core.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> ppwm=sg.PositionalPWM()
ppwm.set_sigma(sigma)
ppwm.set_mean(mu)
pwm=np.array([[0.0, 0.5, 0.1, 1.0],
[0.0, 0.5, 0.5, 0.0],
[1.0, 0.0, 0.4, 0.0],
[0.0, 0.0, 0.0, 0.0]]);
pwm=np.array([[0.01,0.09,0.1],[0.09,0.01,0.1],[0.85,0.4,0.1],[0.05,0.5,0.7]])
ppwm.set... | code_fim | hard | {
"lang": "python",
"repo": "shogun-toolbox/shogun",
"path": "/examples/undocumented/python/distribution_ppwm.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: shogun-toolbox/shogun path: /examples/undocumented/python/distribution_ppwm.py
#!/usr/bin/env python
import shogun as sg
import numpy as np
from tools.load import LoadMatrix
lm=LoadMatrix()
traindna = lm.load_dna('../data/fm_train_dna.dat')
<|fim_suffix|>def distribution_ppwm (fm_dna=traindna, ... | code_fim | medium | {
"lang": "python",
"repo": "shogun-toolbox/shogun",
"path": "/examples/undocumented/python/distribution_ppwm.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Kanma/WoWCharactersViewer path: /tools/retrieve_raid_loot_tables.py
#! /usr/bin/env python
import httplib
from xml.dom.minidom import parseString
from urlparse import urlparse
import sys
import os
import json
from utils import load_json_file
#------------- ENUMERATIONS -----------------------... | code_fim | hard | {
"lang": "python",
"repo": "Kanma/WoWCharactersViewer",
"path": "/tools/retrieve_raid_loot_tables.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>document = parseString(content)
# Extract the loot tables
boss_list = {}
table_rows = document.getElementsByTagName('tr')
for row in table_rows:
links = row.getElementsByTagName('a')
try:
item_link = filter(lambda x: x.hasAttribute('class') and \
(x... | code_fim | hard | {
"lang": "python",
"repo": "Kanma/WoWCharactersViewer",
"path": "/tools/retrieve_raid_loot_tables.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> document = parseString(english_content)
table_rows = document.getElementsByTagName('tr')
item_slots = {}
for row in table_rows:
links = row.getElementsByTagName('a')
try:
item_link = filter(lambda x: x.hasAttribute('class') and \
... | code_fim | hard | {
"lang": "python",
"repo": "Kanma/WoWCharactersViewer",
"path": "/tools/retrieve_raid_loot_tables.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: RunestoneInteractive/RunestoneServer path: /scripts/loadTimes.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
#
# {address space usage: 359067648 bytes/342MB} {rss usage: 107823104 bytes/102MB} [pid: 11266|app: 0|req: 99163/885977] 64.208.17.170 () {48 ... | code_fim | hard | {
"lang": "python",
"repo": "RunestoneInteractive/RunestoneServer",
"path": "/scripts/loadTimes.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
Base.metadata.create_all(engine)
db = Session()
today = datetime.datetime.now().date()-datetime.timedelta(days=1)
for k in sorted(runtimes,key=lambda x: sum(runtimes[x])/len(runtimes[x] )):
e = LogEntry(endpoint=k,
calls=len(runtimes[k]),
response_average=sum(runti... | code_fim | hard | {
"lang": "python",
"repo": "RunestoneInteractive/RunestoneServer",
"path": "/scripts/loadTimes.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def tokenize(self, x):
tokenizer = TweetTokenizer()
return tokenizer.tokenize(x.lower())
def tokenize_remove_regex(self, x):
listToStr = ' '.join([str(elem) for elem in x])
tokenizer = RegexpTokenizer(r'http|2019|2018|cve|2020| |\.|,|:|;|!|\?|\(|\)|\||\+|\'|"|‘|’|“... | code_fim | medium | {
"lang": "python",
"repo": "alexfrancow/CVE-Search",
"path": "/app/mods/mod_main/textProcessing.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: alexfrancow/CVE-Search path: /app/mods/mod_main/textProcessing.py
# Predict exploit
from joblib import dump, load
import re
import nltk
from nltk.tokenize import RegexpTokenizer, TweetTokenizer
from nltk.stem import WordNetLemmatizer
from nltk.stem import PorterStemmer
from nltk.sentiment.vader i... | code_fim | hard | {
"lang": "python",
"repo": "alexfrancow/CVE-Search",
"path": "/app/mods/mod_main/textProcessing.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> lemmatizer = WordNetLemmatizer()
return ' '.join([lemmatizer.lemmatize(word) for word in x])
def gen_pre(self, x):
dfpre = pd.DataFrame({'Tweet': x}, index=[0])
dfpre['Tweet'] = dfpre['Tweet'].map(self.remove_URL)
dfpre['tokens'] = dfpre['Tweet'].map(self.token... | code_fim | medium | {
"lang": "python",
"repo": "alexfrancow/CVE-Search",
"path": "/app/mods/mod_main/textProcessing.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tmikov/jscomp path: /runtime/deps/gyp/test/mac/objc-arc/test.gyp
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'make_global_settings': [
['CC', '/usr/bin/clang'],
['CXX', '/us... | code_fim | hard | {
"lang": "python",
"repo": "tmikov/jscomp",
"path": "/runtime/deps/gyp/test/mac/objc-arc/test.gyp",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> {
'target_name': 'arc_disabled',
'type': 'static_library',
'sources': [
'c-file.c',
'cc-file.cc',
'm-file-no-arc.m',
'mm-file-no-arc.mm',
],
'xcode_settings': {
'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
'MACOSX_DE... | code_fim | hard | {
"lang": "python",
"repo": "tmikov/jscomp",
"path": "/runtime/deps/gyp/test/mac/objc-arc/test.gyp",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def verify_fixture_loaded_properly(self):
# url = '/api/projects'
# client = APIClient()
# assert client.login(username='test_user', password='test')
# response = client.get(url)
# assert response.data[0]['id'] == 1
# assert response.data[0]['name']... | code_fim | hard | {
"lang": "python",
"repo": "hlngo/openeis",
"path": "/openeis/projects/tests/test_silent_ingest_failure.py",
"mode": "spm",
"license": "BSD-2-Clause-Views",
"source": "the-stack-v2"
} |
<|fim_suffix|> url = '/api/files'
response = self.client.get(url)
assert response.data[0]['name'] == 'test_alpha.csv'
assert response.data[0]['time_zone'] == 'America/Los_Angeles'
@pytest.mark.skipif(True, reason='multi-threading issue possibly. Looking into a better fixture bui... | code_fim | hard | {
"lang": "python",
"repo": "hlngo/openeis",
"path": "/openeis/projects/tests/test_silent_ingest_failure.py",
"mode": "spm",
"license": "BSD-2-Clause-Views",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hlngo/openeis path: /openeis/projects/tests/test_silent_ingest_failure.py
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright (c) 2014, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or witho... | code_fim | hard | {
"lang": "python",
"repo": "hlngo/openeis",
"path": "/openeis/projects/tests/test_silent_ingest_failure.py",
"mode": "psm",
"license": "BSD-2-Clause-Views",
"source": "the-stack-v2"
} |
<|fim_suffix|> maxDelay = 120
continueTrying = True
protocol = SubscriberProtocol
def _Connection(host, port, reconnect, pool_size, db, lazy):
factory = RedisFactory(pool_size, db, lazy)
factory.continueTrying = reconnect
for x in xrange(pool_size):
reactor.connectTCP(host, port, factor... | code_fim | hard | {
"lang": "python",
"repo": "wilatai/cyclone",
"path": "/cyclone/redis/__init__.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: wilatai/cyclone path: /cyclone/redis/__init__.py
# coding: utf-8
# Copyright 2009 Alexandre Fiori
#
# 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.... | code_fim | hard | {
"lang": "python",
"repo": "wilatai/cyclone",
"path": "/cyclone/redis/__init__.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>def _ShardingConnection(hosts, reconnect, pool_size, db, lazy):
err = "please use a list or tuple with host:port"
if not isinstance(hosts, (types.ListType, types.TupleType)):
raise ValueError(err)
connections = []
for item in hosts:
try:
host, port = item.split... | code_fim | hard | {
"lang": "python",
"repo": "wilatai/cyclone",
"path": "/cyclone/redis/__init__.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ibis-project/ibis path: /ibis/common/tests/test_temporal.py
from __future__ import annotations
import itertools
from datetime import date, datetime, time, timedelta, timezone
import dateutil
import pandas as pd
import pytest
import pytz
from packaging.version import parse as vparse
from pytest ... | code_fim | hard | {
"lang": "python",
"repo": "ibis-project/ibis",
"path": "/ibis/common/tests/test_temporal.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>def test_interval_unit_compatibility():
v = CoercedTo(IntervalUnit)
for unit in itertools.chain(DateUnit, TimeUnit):
interval = v.match(unit, {})
assert isinstance(interval, IntervalUnit)
assert unit.value == interval.value
@pytest.mark.parametrize(
("value", "expecte... | code_fim | hard | {
"lang": "python",
"repo": "ibis-project/ibis",
"path": "/ibis/common/tests/test_temporal.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@pytest.mark.parametrize(
("value", "expected"),
[
# datetime object
(datetime(2017, 1, 1), datetime(2017, 1, 1)),
(datetime(2017, 1, 1, 0, 0, 0, 1), datetime(2017, 1, 1, 0, 0, 0, 1)),
(
datetime(2017, 1, 1, 0, 0, 0, 1, tzinfo=timezone.utc),
... | code_fim | hard | {
"lang": "python",
"repo": "ibis-project/ibis",
"path": "/ibis/common/tests/test_temporal.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.h5_raw = USIDataset(h5_raw)
self.h5_sho_guess = USIDataset(h5_sho_guess)
self.h5_sho_fit = USIDataset(h5_sho_fit)
self.h5_loop_guess = USIDataset(h5_loop_guess)
self.h5_loop_fit = USIDataset(h5_loop_fit)
self.h5_spec_vals = h5_spec_vals
self.h5_... | code_fim | hard | {
"lang": "python",
"repo": "Liambcollins/pycroscopy",
"path": "/pycroscopy/io/translators/beps_data_generator.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def calc_loop_coef_mat(self, image_list):
"""
Build the loop coefficient matrix
Parameters
----------
image_list : list of numpy.ndarray
Images that will be used to generate the coefficients
Returns
-------
coef_mat : numpy.... | code_fim | hard | {
"lang": "python",
"repo": "Liambcollins/pycroscopy",
"path": "/pycroscopy/io/translators/beps_data_generator.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Liambcollins/pycroscopy path: /pycroscopy/io/translators/beps_data_generator.py
coef_mat = np.rollaxis(coef_mat, 1, coef_mat.ndim).reshape([coef_mat.shape[0], -1])
self.h5_loop_fit[:] = np.tile(stack_real_to_compound(coef_mat, loop_fit32),
[1... | code_fim | hard | {
"lang": "python",
"repo": "Liambcollins/pycroscopy",
"path": "/pycroscopy/io/translators/beps_data_generator.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_shannon_entropy(self):
self.assertTrue(infotheory.shannon_entropy([1, 1, 1, 1]) == 0.0)
self.assertTrue(infotheory.shannon_entropy([1, 2, 3, 4]) == 2.0)
self.assertTrue(infotheory.shannon_entropy([1, 1, 3, 4]) == 1.5)<|fim_prefix|># repo: dougct/infotheory path: /info... | code_fim | easy | {
"lang": "python",
"repo": "dougct/infotheory",
"path": "/infotheory/tests/test_infotheory.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: dougct/infotheory path: /infotheory/tests/test_infotheory.py
from unittest import TestCase
import infotheory
<|fim_suffix|> def test_shannon_entropy(self):
self.assertTrue(infotheory.shannon_entropy([1, 1, 1, 1]) == 0.0)
self.assertTrue(infotheory.shannon_entropy([1, 2, 3, 4]... | code_fim | easy | {
"lang": "python",
"repo": "dougct/infotheory",
"path": "/infotheory/tests/test_infotheory.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: MatyiFKBT/mcreate path: /tests/test_create.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `create` package."""
<|fim_suffix|>
class TestCreate(unittest.TestCase):
"""Tests for `create` package."""
def setUp(self):
"""Set up test fixtures, if any."""... | code_fim | easy | {
"lang": "python",
"repo": "MatyiFKBT/mcreate",
"path": "/tests/test_create.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixtures, if any."""
assert 2==2
def test_command_line_interface(self):
"""Test the CLI."""
assert(1==1)<|fim_prefix|># repo: MatyiFKBT/mcreate path: /test... | code_fim | medium | {
"lang": "python",
"repo": "MatyiFKBT/mcreate",
"path": "/tests/test_create.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bushitan/history_is_relation path: /vmaig_blog-master/vmaig_comments/models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from blog.models import Story
# Create your models here.
# 用来修改admin中显示的app名称,因为admin app 名称是用 str.title()显示的,所以修改str类的title方法就可以... | code_fim | medium | {
"lang": "python",
"repo": "bushitan/history_is_relation",
"path": "/vmaig_blog-master/vmaig_comments/models.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=u'用户')
story = models.ForeignKey(Story, verbose_name=u'故事')
comment = models.TextField(verbose_name=u'评论内容' ,null=True)
create_time = models.DateTimeField(u'创建时间', auto_now_add=True)
class Meta:
verbose_name_plur... | code_fim | hard | {
"lang": "python",
"repo": "bushitan/history_is_relation",
"path": "/vmaig_blog-master/vmaig_comments/models.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> verbose_name_plural = verbose_name = u'评论_l'
ordering = ['-create_time']
app_label = string_with_title('vmaig_comments', u"历史_评论")<|fim_prefix|># repo: bushitan/history_is_relation path: /vmaig_blog-master/vmaig_comments/models.py
# -*- coding: utf-8 -*-
from django.db import mode... | code_fim | hard | {
"lang": "python",
"repo": "bushitan/history_is_relation",
"path": "/vmaig_blog-master/vmaig_comments/models.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>'
dedent|''
name|'except'
op|'('
name|'TypeError'
op|','
name|'KeyError'
op|')'
op|':'
newline|'\n'
indent|' '
name|'msg'
op|'='
name|'_'
op|'('
string|'"onSharedStorage must be specified."'
op|')'
newline|'\n'
name|'raise'
name|'exc'
op|'.'
name|'HTTPBadRequest'
op|'('
name|'explanation'
op|'=... | code_fim | hard | {
"lang": "python",
"repo": "bopopescu/nova-token",
"path": "/nova/api/openstack/compute/legacy_v2/contrib/evacuate.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: bopopescu/nova-token path: /nova/api/openstack/compute/legacy_v2/contrib/evacuate.py
begin_unit
comment|'# Copyright 2013 OpenStack Foundation'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this fil... | code_fim | hard | {
"lang": "python",
"repo": "bopopescu/nova-token",
"path": "/nova/api/openstack/compute/legacy_v2/contrib/evacuate.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> C_validate: Sequence
S_validate: Sequence<|fim_prefix|># repo: DylanModesitt/neural-cryptography path: /models/steganography/steganography.py
# system
from typing import Sequence
# lib
from dataclasses import dataclass
@dataclass
class SteganographyData:
"""
a group of steganography da... | code_fim | medium | {
"lang": "python",
"repo": "DylanModesitt/neural-cryptography",
"path": "/models/steganography/steganography.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: DylanModesitt/neural-cryptography path: /models/steganography/steganography.py
# system
from typing import Sequence
# lib
from dataclasses import dataclass
@dataclass
class SteganographyData:
<|fim_suffix|> C_validate: Sequence
S_validate: Sequence<|fim_middle|> """
a group of st... | code_fim | hard | {
"lang": "python",
"repo": "DylanModesitt/neural-cryptography",
"path": "/models/steganography/steganography.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: xinyangz/interview path: /api_server/interview/interviewer_views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.conf import settings
import pymongo
from . import permissions
@api_view(['GET'])
def root... | code_fim | medium | {
"lang": "python",
"repo": "xinyangz/interview",
"path": "/api_server/interview/interviewer_views.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> client = pymongo.MongoClient()
db = client[settings.DB_NAME]
token = request.GET.get('token')
cursor = db.users.find({'token': token})
room_cursor = db.rooms.find({'interviewer': cursor[0]['username']})
if room_cursor.count() == 0:
return Response(
{
... | code_fim | hard | {
"lang": "python",
"repo": "xinyangz/interview",
"path": "/api_server/interview/interviewer_views.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: astroseger/dnn-model-services path: /Services/JSON-RPC/Basic_Template/services/__init__.py
registry = {
"basic_service_one": {
"jsonrpc": 7002,
"snetd": 7000,
<|fim_suffix|>onrpc": 7003,
"snetd": 7001,
},
}<|fim_middle|> },
"basic_service_two": {
"js | code_fim | easy | {
"lang": "python",
"repo": "astroseger/dnn-model-services",
"path": "/Services/JSON-RPC/Basic_Template/services/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>onrpc": 7003,
"snetd": 7001,
},
}<|fim_prefix|># repo: astroseger/dnn-model-services path: /Services/JSON-RPC/Basic_Template/services/__init__.py
registry = {
"basic_service_one": {
"jsonrpc": 7002,
"snetd": 7000,
<|fim_middle|> },
"basic_service_two": {
"js | code_fim | easy | {
"lang": "python",
"repo": "astroseger/dnn-model-services",
"path": "/Services/JSON-RPC/Basic_Template/services/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: easyopsapis/easyops-api-python path: /topology_sdk/model/resource_manage/filter_strategy_pb2.pyi
# @generated by generate_proto_mypy_stubs.py. Do not edit!
import sys
from google.protobuf.descriptor import (
Descriptor as google___protobuf___descriptor___Descriptor,
)
from google.protobuf.i... | code_fim | hard | {
"lang": "python",
"repo": "easyopsapis/easyops-api-python",
"path": "/topology_sdk/model/resource_manage/filter_strategy_pb2.pyi",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> else:
@classmethod
def FromString(cls, s: typing___Union[builtin___bytes, builtin___buffer, builtin___unicode]) -> FilterStrategy: ...
def MergeFrom(self, other_msg: google___protobuf___message___Message) -> None: ...
def CopyFrom(self, other_msg: google___protobuf___message___... | code_fim | hard | {
"lang": "python",
"repo": "easyopsapis/easyops-api-python",
"path": "/topology_sdk/model/resource_manage/filter_strategy_pb2.pyi",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> print(event)
method, path, subId = obtainDataFromEvent(event=event, getSubId=True)
if path == '/user' and method == 'GET':
user_data = user_endpoint(subId)
return {
'statusCode': 200,
'body': user_data
}
elif path == '/user/updateProfile' an... | code_fim | medium | {
"lang": "python",
"repo": "kmcquade/CampusQwest-backend",
"path": "/lambdas/src/user_handler.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kmcquade/CampusQwest-backend path: /lambdas/src/user_handler.py
import boto3
import json
from urllib.parse import unquote
from utils.common_functions import obtainDataFromEvent, decimal_default
from utils.dynamodb_functions import get_item, update_profile_selected_avatar, update_profile_selected_... | code_fim | medium | {
"lang": "python",
"repo": "kmcquade/CampusQwest-backend",
"path": "/lambdas/src/user_handler.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if n1 == n2:
col_outer = (0.4, 0.4, 0.4, 0.4)
col_inner = (0.0, 0.0, 0.0, 0.5)
col_circle_inner = (0.2, 0.2, 0.2, 1.0)
draw_rounded_node_border(n1, radius=6, colour=col_outer) # outline
draw_rounded_node_border(n1, radius=5, colour=col_inner) ... | code_fim | hard | {
"lang": "python",
"repo": "RnoB/3DVisualSwarm",
"path": "/src/bpy/3.6/scripts/addons/node_wrangler/utils/draw.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: RnoB/3DVisualSwarm path: /src/bpy/3.6/scripts/addons/node_wrangler/utils/draw.py
# SPDX-License-Identifier: GPL-2.0-or-later
import bpy
import gpu
from gpu_extras.batch import batch_for_shader
from math import cos, sin, pi
from .nodes import get_nodes_links, prefs_line_width, abs_node_location,... | code_fim | hard | {
"lang": "python",
"repo": "RnoB/3DVisualSwarm",
"path": "/src/bpy/3.6/scripts/addons/node_wrangler/utils/draw.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rcannood/single-cell-curation path: /datasets/cao_shendure/scripts/create_ontology_lookup_cell_type.py
# that need to be manually curated
import ontology
import re
import scanpy as sc
import sys
# Read shendure big data
dataset = sc.read('./Survey_of_human_embryonic_development-processed.h5ad'... | code_fim | medium | {
"lang": "python",
"repo": "rcannood/single-cell-curation",
"path": "/datasets/cao_shendure/scripts/create_ontology_lookup_cell_type.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if (i[1] == stripped_cell_type):
final = True
else:
final = False
print(cell_type, stripped_cell_type, *i, final, sep="\t")<|fim_prefix|># repo: rcannood/single-cell-curation path: /datasets/cao_shendure/scripts/create_ontology_lookup_cell_type.py
... | code_fim | medium | {
"lang": "python",
"repo": "rcannood/single-cell-curation",
"path": "/datasets/cao_shendure/scripts/create_ontology_lookup_cell_type.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>print("original_cell_type", "stripped_cell_type", "ontology_term_id", "ontology_term_name", "final", sep="\t")
for cell_type in cell_types:
stripped_cell_type=cell_type.split("-")[1]
stripped_cell_type=re.sub("cells*", "", stripped_cell_type).lower()
suggested_term=ontology.lookup_ca... | code_fim | medium | {
"lang": "python",
"repo": "rcannood/single-cell-curation",
"path": "/datasets/cao_shendure/scripts/create_ontology_lookup_cell_type.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def getLabels(self, r_type, r_name, ep_id):
command = r_type + '/' + r_name + '/xconnect/getLabels/' + ep_id
ls_ = self.get(self._base_url + command)
return self.decode_xml_entry(ls_)
def checkAvailability(self, r_type, r_name):
r_id = self.getResourceId(r_type, r_... | code_fim | hard | {
"lang": "python",
"repo": "Hector-/AMsoil",
"path": "/src/vendor/opennaasrm/commandsmanager.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Hector-/AMsoil path: /src/vendor/opennaasrm/commandsmanager.py
import amsoil.core.pluginmanager as pm
import opennaasexceptions as exceptions_package
import amsoil.core.log
logger = amsoil.core.log.getLogger('opennaasresourcemanager')
config = pm.getService('config')
import requests
import xml.... | code_fim | hard | {
"lang": "python",
"repo": "Hector-/AMsoil",
"path": "/src/vendor/opennaasrm/commandsmanager.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class ResponsesTypesEnum(IntEnum):
SUCCESS = 1<|fim_prefix|># repo: astoliarov/toshokan path: /src/domain/constants.py
# coding: utf-8
from enum import IntEnum
<|fim_middle|>class LinkSourceEnum(IntEnum):
CUSTOM = 1
POCKET = 2
| code_fim | medium | {
"lang": "python",
"repo": "astoliarov/toshokan",
"path": "/src/domain/constants.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: astoliarov/toshokan path: /src/domain/constants.py
# coding: utf-8
from enum import IntEnum
<|fim_suffix|>class ResponsesTypesEnum(IntEnum):
SUCCESS = 1<|fim_middle|>
class LinkSourceEnum(IntEnum):
CUSTOM = 1
POCKET = 2
| code_fim | medium | {
"lang": "python",
"repo": "astoliarov/toshokan",
"path": "/src/domain/constants.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> CUSTOM = 1
POCKET = 2
class ResponsesTypesEnum(IntEnum):
SUCCESS = 1<|fim_prefix|># repo: astoliarov/toshokan path: /src/domain/constants.py
# coding: utf-8
from enum import IntEnum
<|fim_middle|>class LinkSourceEnum(IntEnum):
| code_fim | easy | {
"lang": "python",
"repo": "astoliarov/toshokan",
"path": "/src/domain/constants.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jzx1230/obtainfo path: /tools/magnet.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import json
import argparse
import pymongo
from bson import ObjectId
from pcnile.resource import atom_download_resource, format_online_resource, \
format_netdisk_resource, format_bt, format_ed2k... | code_fim | hard | {
"lang": "python",
"repo": "jzx1230/obtainfo",
"path": "/tools/magnet.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> elif args.target == 'atom':
db = pymongo.Connection().server
count = 0
for d in db.server.find():
downloads = atom_download_resource(d['resource']['download'])
if len(downloads) != len(d['resource']['download']):
count += 1
... | code_fim | hard | {
"lang": "python",
"repo": "jzx1230/obtainfo",
"path": "/tools/magnet.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: UWIT-IAM/iam-idbase path: /tests/conftest.py
import os
from pytest import fixture
from importlib import import_module
<|fim_suffix|>@fixture
def session():
engine = import_module('django.contrib.sessions.backends.signed_cookies')
store = engine.SessionStore()
store['active'] = True ... | code_fim | medium | {
"lang": "python",
"repo": "UWIT-IAM/iam-idbase",
"path": "/tests/conftest.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> engine = import_module('django.contrib.sessions.backends.signed_cookies')
store = engine.SessionStore()
store['active'] = True # set something so we can check if it's cleared.
store.modified = False
return store<|fim_prefix|># repo: UWIT-IAM/iam-idbase path: /tests/conftest.py
import... | code_fim | easy | {
"lang": "python",
"repo": "UWIT-IAM/iam-idbase",
"path": "/tests/conftest.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: SevinaGupta/soil_health_detection path: /flask_project_template-master/main.py
import RPi.GPIO as GPIO
import time, random, math, threading, datetime, locale, os, sys, Adafruit_DHT, urllib, yaml, paramiko, tweepy, requests, alsaaudio
from gtts import gTTS
from gpiozero import CPUTemperature
from ... | code_fim | medium | {
"lang": "python",
"repo": "SevinaGupta/soil_health_detection",
"path": "/flask_project_template-master/main.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># Relay
relay = 17
# Hygro
hygro = 23
hygro_Power = 24
# Led Diods
blue_one_pin = 27
blue_two_pin = 22
blue_three_pin = 5
green_one_pin = 6
green_two_pin = 26
red_one_pin = 25
red_two_pin = 16
blue_on_off_pin = 18
# GPIO Set mode to BCM instead of Board
GPIO.setmode(GPIO.BCM)
# GPIO input output
GPIO.... | code_fim | medium | {
"lang": "python",
"repo": "SevinaGupta/soil_health_detection",
"path": "/flask_project_template-master/main.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Aurora11111/speaker-recognition-pytorch path: /devector.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob
import os
import librosa
import numpy as np
from hparam import hparam as hp
from speech_embedder_net import SpeechEmbedder, GE2ELoss, get_centroids, get_cossim
import torch
impor... | code_fim | hard | {
"lang": "python",
"repo": "Aurora11111/speaker-recognition-pytorch",
"path": "/devector.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> enrollment_embeddings = embedder_net(utterance)
embedding = enrollment_embeddings.detach().numpy()
# if i<train_speaker_num: # save spectrogram as numpy file
# # train_x.append(embedding)
# # trainx_devector = np.concatenate(train_x, axis=0)
#... | code_fim | hard | {
"lang": "python",
"repo": "Aurora11111/speaker-recognition-pytorch",
"path": "/devector.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>def save_testdevector(path):
print(len(path))
utter_min_len = (hp.data.tisv_frame * hp.data.hop + hp.data.window) * hp.data.sr # lower bound of utterance length
speaker_dict = {}
max = 0
min = 10000
for utter_name in path:
audios = glob.glob(utter_name + '/*')
A... | code_fim | hard | {
"lang": "python",
"repo": "Aurora11111/speaker-recognition-pytorch",
"path": "/devector.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> n = N_SIMPLE
if args.thorough:
n = N_THOROUGH
# Run tests in alphabetic order
test_seed(0)
# Run tests using n random seeds
for i in range(0, n):
seed = random.randint(0, 2**32)
test_seed(seed, REPEAT)
print("Tests successful!")
sys.exit(0)<|fim_pr... | code_fim | hard | {
"lang": "python",
"repo": "metallicsoul92/mimiker",
"path": "/run_tests.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> try:
args = parser.parse_args()
except SystemExit:
sys.exit(0)
n = N_SIMPLE
if args.thorough:
n = N_THOROUGH
# Run tests in alphabetic order
test_seed(0)
# Run tests using n random seeds
for i in range(0, n):
seed = random.randint(0, 2**32)... | code_fim | hard | {
"lang": "python",
"repo": "metallicsoul92/mimiker",
"path": "/run_tests.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: metallicsoul92/mimiker path: /run_tests.py
#!/usr/bin/python3
import argparse
import pexpect
import sys
import random
N_SIMPLE = 5
N_THOROUGH = 100
TIMEOUT = 5
RETRIES_MAX = 5
REPEAT = 5
def test_seed(seed, repeat=1, retry=0):
if retry == RETRIES_MAX:
print("Maximum retries reache... | code_fim | hard | {
"lang": "python",
"repo": "metallicsoul92/mimiker",
"path": "/run_tests.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># %%
X, y = mglearn.datasets.make_forge()
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# %%
clf = KNeighborsClassifier(n_neighbors=3)
# %%
clf.fit(X_train, y_train)
# %%
print('Test set predictions: {}'.format(clf.predict(X_train)))
# %%
print('Test set accuracy: {:.2f}'.f... | code_fim | medium | {
"lang": "python",
"repo": "ysko909/intro_to_ml_with_python",
"path": "/2_3_boston.py",
"mode": "spm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ysko909/intro_to_ml_with_python path: /2_3_boston.py
# %% [markdown]
# ## Boston housing
# %%
from sklearn.datasets import load_boston
from sklearn.datasets import load_breast_cancer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from skle... | code_fim | hard | {
"lang": "python",
"repo": "ysko909/intro_to_ml_with_python",
"path": "/2_3_boston.py",
"mode": "psm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|># %%
clf.fit(X_train, y_train)
# %%
print('Test set predictions: {}'.format(clf.predict(X_train)))
# %%
print('Test set accuracy: {:.2f}'.format(clf.score(X_test, y_test)))
# %% [markdown]
# ## Display decision boundary
# %%
fig, axes = plt.subplots(1, 3, figsize=(10, 3))
for n_neighbors, ax in zip([... | code_fim | hard | {
"lang": "python",
"repo": "ysko909/intro_to_ml_with_python",
"path": "/2_3_boston.py",
"mode": "spm",
"license": "WTFPL",
"source": "the-stack-v2"
} |
<|fim_suffix|> y = y
for line in lines:
if wrap:
line = wrap_string(line, wrap)
#TODO y + len(line)?
draw_text(line, x, y, color)
y += 1
def draw_lines_tex(lines, x=0, y=0, color=(0,0,1)):
y = y
for line in lines:
draw_chars_tex(line, x, y, color)
... | code_fim | hard | {
"lang": "python",
"repo": "anokata/pythonPetProjects",
"path": "/modules/ByteFont.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: anokata/pythonPetProjects path: /modules/ByteFont.py
import sys
sys.path.append('../modules')
from PIL import Image
from OpenGL.GL import *
from gl_texture import texture_init, draw_tex_quad
from StringUtil import *
#TODO: background color(draw rect under char)
font_file10x16 = 'font10x16.png'
f... | code_fim | hard | {
"lang": "python",
"repo": "anokata/pythonPetProjects",
"path": "/modules/ByteFont.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # values to predict
X_to_predict = dataset[1].iloc[:, 1:].values
passenger_ids = dataset[1].iloc[:, 0].values
return X_train, y_train, X_to_predict, passenger_ids
if __name__ == "__main__":
preprocessed_data()<|fim_prefix|># repo: danielmarostica/GSClassificationTool path: /modules/... | code_fim | medium | {
"lang": "python",
"repo": "danielmarostica/GSClassificationTool",
"path": "/modules/data_preprocessing.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: danielmarostica/GSClassificationTool path: /modules/data_preprocessing.py
import numpy as np
import pandas as pd
def preprocessed_data():
# importing the dataset
training_set = pd.read_csv('dataset/training_set.csv')
test_set = pd.read_csv('dataset/test_set.csv')
dataset = [trai... | code_fim | hard | {
"lang": "python",
"repo": "danielmarostica/GSClassificationTool",
"path": "/modules/data_preprocessing.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> for data in dataset:
# fill Nan with most common occurence
most_popular_port = data['Embarked'].dropna().mode()[0]
data['Embarked'] = data['Embarked'].fillna(most_popular_port)
# encode Sex
data['Sex'] = data['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
... | code_fim | medium | {
"lang": "python",
"repo": "danielmarostica/GSClassificationTool",
"path": "/modules/data_preprocessing.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Hackathon-EEG-Reader/Main path: /predict.py
import tensorflow as tf
import numpy as np
import pandas as pd
import os
import sys
sys.path.append("./")
from etl import ETL
<|fim_suffix|>from sklearn.metrics import log_loss,accuracy_score,roc_auc_score,plot_roc_curve,confusion_matrix
print('\nlog ... | code_fim | hard | {
"lang": "python",
"repo": "Hackathon-EEG-Reader/Main",
"path": "/predict.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>try :
print('\nroc:')
print(roc_auc_score(y_true=y, y_score=predictions,labels=[0,1]))
except ValueError :
print(np.nan)
print('\naccuracy:')
acc_preds = predictions.copy()
for i in range(len(predictions)) :
if predictions[i] > .5 :
acc_preds[i] = 1
else : acc_preds[i] = 0
prin... | code_fim | hard | {
"lang": "python",
"repo": "Hackathon-EEG-Reader/Main",
"path": "/predict.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: eight04/ptt-article-parser path: /ptt_article_parser/dir.py
# pylint: disable=invalid-name
import datetime
import pathlib
import struct
from . import strip_color
FILE_HEAD = struct.Struct("!33sc14s6s73sc")
def to_str(bytes):
return bytes.partition(b"\0")[0].decode("big5-uao")
class DIR:
<|f... | code_fim | hard | {
"lang": "python",
"repo": "eight04/ptt-article-parser",
"path": "/ptt_article_parser/dir.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> file = pathlib.Path(file)
self.read_file(file.with_name(".DIR"))
if file.name in self.items:
return self.items[file.name].title
return None
def getAuthor(self, file):
file = pathlib.Path(file)
self.read_file(file.with_name(".DIR"))
if file.name in self.items:
return self.items[file.n... | code_fim | medium | {
"lang": "python",
"repo": "eight04/ptt-article-parser",
"path": "/ptt_article_parser/dir.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def read_file(self, file, throw_error=False):
file = pathlib.Path(file).resolve()
if str(file) in self.read_cache:
return
if str(file) in self.read_fail and not throw_error:
return
try:
content = file.read_bytes()
except OSError:
self.read_fail.add(str(file))
if throw_error:
... | code_fim | hard | {
"lang": "python",
"repo": "eight04/ptt-article-parser",
"path": "/ptt_article_parser/dir.py",
"mode": "spm",
"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.