text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_prefix|># repo: achrinza/np-csf02-answers path: /PRG1/Lectures/Week13/FileIODemo.py
import os
f = open("test.txt" "w")
list1 = ["Shoes", "Socks", "Gloves"]
quantity = [10, 5, 32]
<|fim_suffix|>for item in list1:
f.write("{:<10} {:10} {:10}\n".format("S/N", "Items", "Quantity") + "\n")
f.close()<|fim_midd... | code_fim | medium | {
"lang": "python",
"repo": "achrinza/np-csf02-answers",
"path": "/PRG1/Lectures/Week13/FileIODemo.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Grab ini file from adjacent to script only (don't follow symlinks)
configfile = os.path.join(
os.path.dirname(__file__), args.config
)
logger.debug('Parsing configfile: {}'.format(configfile))
config.read(configfile)
logger.debug('Final config:')
logger.debug(config_d... | code_fim | hard | {
"lang": "python",
"repo": "solacelost/libvirt-inventory",
"path": "/libvirt-inventory.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: solacelost/libvirt-inventory path: /libvirt-inventory.py
#!/usr/bin/env python3
"""
libvirt-inventory.py - Libvirt dynamic inventory source for Ansible
A libvirt-managed network pool inventory for very specific use cases and
network layouts.
Copyright (c) 2019 James Harmison
Permission is he... | code_fim | hard | {
"lang": "python",
"repo": "solacelost/libvirt-inventory",
"path": "/libvirt-inventory.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def mac_from_vm(vm: libvirt.virDomain = None) -> str:
"""
Parses the vm's XML to return just the mac address as a string
"""
doc = minidom.parseString(vm.XMLDesc())
interfaces = doc.getElementsByTagName('mac')
return interfaces[0].getAttribute('address')
def leases_to_ip(leases:... | code_fim | hard | {
"lang": "python",
"repo": "solacelost/libvirt-inventory",
"path": "/libvirt-inventory.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: loles/solar-1 path: /solar/test/test_graph_api.py
# Copyright 2015 Mirantis, Inc.
#
# 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.apa... | code_fim | hard | {
"lang": "python",
"repo": "loles/solar-1",
"path": "/solar/test/test_graph_api.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>def test_reset_only_provided(simple_plan):
simple_plan.node['just_fail']['status'] = states.ERROR.name
simple_plan.node['echo_stuff']['status'] = states.SUCCESS.name
graph.reset(simple_plan, [states.ERROR.name])
assert simple_plan.node['just_fail']['status'] == states.PENDING.name
as... | code_fim | hard | {
"lang": "python",
"repo": "loles/solar-1",
"path": "/solar/test/test_graph_api.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: garce1/gcp-datacatalog-python path: /tests_e2e/datacatalog.py
import os
import pytest
import time
import uuid
from google.api_core.exceptions import PermissionDenied
from google.cloud.datacatalog import DataCatalogClient, enums, types
from .bigquery import table
TEST_PROJECT_ID = os.environ['G... | code_fim | hard | {
"lang": "python",
"repo": "garce1/gcp-datacatalog-python",
"path": "/tests_e2e/datacatalog.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> entry = datacatalog_client.lookup_entry(
linked_resource=f'//bigquery.googleapis.com/projects/{table.project}'
f'/datasets/{table.dataset_id}/tables/{table.table_id}')
yield entry
@pytest.fixture
def tag(table_entry, tag_template, scope='function'):
tag = typ... | code_fim | hard | {
"lang": "python",
"repo": "garce1/gcp-datacatalog-python",
"path": "/tests_e2e/datacatalog.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Ranats/gbf-autopilot path: /controller/jsonrpc_methods.py
from .jsonrpc import success, server_error, request_error, JsonRpcException
def element_rect(rect):
return (rect['x'], rect['y'], rect['width'], rect['height'])
def window_rect(rect):
return (0, 0, rect['window']['width'], rect['... | code_fim | hard | {
"lang": "python",
"repo": "Ranats/gbf-autopilot",
"path": "/controller/jsonrpc_methods.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.controller.click(
element_rect(rect),
window_rect(rect),
clicks=clicks
)
return 'OK'
def handle_request(self, json):
req_id = json['id']
method_name = json['method']
try:
method = self.methods.get(met... | code_fim | hard | {
"lang": "python",
"repo": "Ranats/gbf-autopilot",
"path": "/controller/jsonrpc_methods.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tsauerwein/c2cgeoportal path: /c2cgeoportal/tests/functional/test_mapserverproxy.py
<gml:Point srsName="EPSG:21781">
<gml:coordinates>-90.000000,-45.000000</gml:coordinates>
</gml:Point>
</the_geom>
... | code_fim | hard | {
"lang": "python",
"repo": "tsauerwein/c2cgeoportal",
"path": "/c2cgeoportal/tests/functional/test_mapserverproxy.py",
"mode": "psm",
"license": "BSD-2-Clause-Views",
"source": "the-stack-v2"
} |
<|fim_suffix|> response = self._get_feature_is_equal_to(u'foo')
self.assertTrue(response.status_int, 200)
self.assertTrue(unicode(response.body.decode('utf-8')).find(u'foo') > 0)
self.assertTrue(unicode(response.body.decode('utf-8')).find(u'bar') < 0)
self.assertTrue(unicode(respo... | code_fim | hard | {
"lang": "python",
"repo": "tsauerwein/c2cgeoportal",
"path": "/c2cgeoportal/tests/functional/test_mapserverproxy.py",
"mode": "spm",
"license": "BSD-2-Clause-Views",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tsauerwein/c2cgeoportal path: /c2cgeoportal/tests/functional/test_mapserverproxy.py
sion.delete(r)
r = DBSession.query(Role).filter(Role.name == '__test_role3').one()
r.functionalities = []
DBSession.delete(r)
for f in DBSession.query(Functionality).filter(Functio... | code_fim | hard | {
"lang": "python",
"repo": "tsauerwein/c2cgeoportal",
"path": "/c2cgeoportal/tests/functional/test_mapserverproxy.py",
"mode": "psm",
"license": "BSD-2-Clause-Views",
"source": "the-stack-v2"
} |
<|fim_suffix|>for currentFile in os.listdir(sys.argv[1]):
if currentFile.endswith(".fa"):
# CHANGE THIS LINE
working_file = open(sys.argv[1] + "/" + currentFile, "r")
new_file = open(currentFile[0:9] + "_trim_renamed.fa", "w")
for currentLine in working_file:
currentLine ... | code_fim | medium | {
"lang": "python",
"repo": "macmanes-lab/GeosmithiaComparativeGenomics",
"path": "/Scripts4phylogeny/renaming_trimalFiles_TA.py",
"mode": "spm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: macmanes-lab/GeosmithiaComparativeGenomics path: /Scripts4phylogeny/renaming_trimalFiles_TA.py
#!/usr/bin/python3
# A program for
# USAGE: ./renaming_trimalFiles_TA.py PATH_To_Directory_With_Orthofiles
# Author: Taruna Aggarwal
# Affiliation: University of New Hampshire, Durham, NH, USA
# Date: 0... | code_fim | medium | {
"lang": "python",
"repo": "macmanes-lab/GeosmithiaComparativeGenomics",
"path": "/Scripts4phylogeny/renaming_trimalFiles_TA.py",
"mode": "psm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
for currentFile in os.listdir(sys.argv[1]):
if currentFile.endswith(".fa"):
# CHANGE THIS LINE
working_file = open(sys.argv[1] + "/" + currentFile, "r")
new_file = open(currentFile[0:9] + "_trim_renamed.fa", "w")
for currentLine in working_file:
currentLine... | code_fim | medium | {
"lang": "python",
"repo": "macmanes-lab/GeosmithiaComparativeGenomics",
"path": "/Scripts4phylogeny/renaming_trimalFiles_TA.py",
"mode": "spm",
"license": "CC0-1.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> img = generate_image('4521', captcha)
# showMany(data[10:14], data[100:104])
# img = data[132]
img = np.reshape(img, [32, 80, 3])
#print(label[132])
plt.imshow(img)
plt.axis('off')
plt.show()
def showMany(images, images2):
f, a = plt.subplots(2, 4, figsize=(4, 2))
... | code_fim | hard | {
"lang": "python",
"repo": "GuangyanZhang/DeepLearningWithPaddle",
"path": "/OCR/data/generate_data.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # showMany(data[10:14], data[100:104])
# img = data[132]
img = np.reshape(img, [32, 80, 3])
#print(label[132])
plt.imshow(img)
plt.axis('off')
plt.show()
def showMany(images, images2):
f, a = plt.subplots(2, 4, figsize=(4, 2))
plt.axis('off')
for i in range(4):
... | code_fim | hard | {
"lang": "python",
"repo": "GuangyanZhang/DeepLearningWithPaddle",
"path": "/OCR/data/generate_data.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: GuangyanZhang/DeepLearningWithPaddle path: /OCR/data/generate_data.py
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2017 Vic Chan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in t... | code_fim | hard | {
"lang": "python",
"repo": "GuangyanZhang/DeepLearningWithPaddle",
"path": "/OCR/data/generate_data.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def entrance_exam(self):
"""
Checks device life-cycle, Flashboot firmware and Flash state.
:return True if the device is ready for provisioning, otherwise False.
"""
status = False
tool = ProgrammingTool.create(self.PROGRAMMING_TOOL)
if tool.conn... | code_fim | hard | {
"lang": "python",
"repo": "utzig/cysecuretools",
"path": "/cysecuretools/main.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.memory_map = self.target.memory_map
self.register_map = self.target.register_map
self.policy_parser = self.target.policy_parser
self.policy_validator = self.target.policy_validator
self.policy_filter = self.target.policy_filter
# Validate policy file
... | code_fim | hard | {
"lang": "python",
"repo": "utzig/cysecuretools",
"path": "/cysecuretools/main.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: utzig/cysecuretools path: /cysecuretools/main.py
"""
Copyright (c) 2019 Cypress Semiconductor Corporation
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.apach... | code_fim | hard | {
"lang": "python",
"repo": "utzig/cysecuretools",
"path": "/cysecuretools/main.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self, wall.s)
self.x = x*32
self.y = y*32+64
#Initialize
self.rect = pygame.Rect(x*32,y*32+64, 32, 32)<|fim_prefix|># repo: RyunValdez/PokePengo path: /PokePengo/Wall.py
################################... | code_fim | medium | {
"lang": "python",
"repo": "RyunValdez/PokePengo",
"path": "/PokePengo/Wall.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: RyunValdez/PokePengo path: /PokePengo/Wall.py
################################################################################
## PokePengo ##
## Wall Class ##
## ... | code_fim | medium | {
"lang": "python",
"repo": "RyunValdez/PokePengo",
"path": "/PokePengo/Wall.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> s = pygame.sprite.Group()
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self, wall.s)
self.x = x*32
self.y = y*32+64
#Initialize
self.rect = pygame.Rect(x*32,y*32+64, 32, 32)<|fim_prefix|># repo: RyunValdez/PokePengo path: /PokePengo/Wal... | code_fim | medium | {
"lang": "python",
"repo": "RyunValdez/PokePengo",
"path": "/PokePengo/Wall.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> `.____.\\ \\ .' \\
// /\\---\\-' \\
fsc // // \\ \\ \\
DeadAnt (c) 2014, Tim Menzies
Tabu-based ant colony optimizer.
"""))<|fim_prefix|># repo: timm/sbse14 path: /table/settings.py
import sys
sys.dont_write_bytecode = True
from o import ... | code_fim | hard | {
"lang": "python",
"repo": "timm/sbse14",
"path": "/table/settings.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: timm/sbse14 path: /table/settings.py
import sys
sys.dont_write_bytecode = True
from o import *
The = o(cache = o(keep=256,
update=1.1),
cluster=o(using= lambda tbl: tbl.cols.indep),
misc= o(mi<|fim_suffix|> `.____.\\ \\ .' \\
// /... | code_fim | hard | {
"lang": "python",
"repo": "timm/sbse14",
"path": "/table/settings.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rgravina/Pyrope path: /pyrope/tests/test_server.py
import unittest
from pyrope.server import *
from eskimoapps.testing.mock import Mock
<|fim_suffix|> server = PyropeServer()
app = Mock
server.registerApplication(app)
self.assertRaises(ApplicationAlreadyRegisteredE... | code_fim | medium | {
"lang": "python",
"repo": "rgravina/Pyrope",
"path": "/pyrope/tests/test_server.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == '__main__':
unittest.main()<|fim_prefix|># repo: rgravina/Pyrope path: /pyrope/tests/test_server.py
import unittest
from pyrope.server import *
from eskimoapps.testing.mock import Mock
class TestServer(unittest.TestCase):
<|fim_middle|> def testDuplicateRegisterFails(self):
... | code_fim | hard | {
"lang": "python",
"repo": "rgravina/Pyrope",
"path": "/pyrope/tests/test_server.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>t: \t",temp)
print("Degrees Celsius: \t",round(celsius,4))
print("Degrees Kelvin: \t",round(kelvin,4))<|fim_prefix|># repo: rouillonh/challenge-python path: /1.strings/challenge3_rouillonh.py
print("\tWelcome to the Temperature Coonversio App")
#Pedimos el valor de la temperatura en fahrenheit<|fim_middl... | code_fim | hard | {
"lang": "python",
"repo": "rouillonh/challenge-python",
"path": "/1.strings/challenge3_rouillonh.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rouillonh/challenge-python path: /1.strings/challenge3_rouillonh.py
print("\tWelcome to the Temperature Coonversio App")
#Pedimos el valor de la temperatura en fahrenheit<|fim_suffix|>9
kelvin = celsius + 273.15
#Convertimos a celsius e imprimimos los valores
print("\nDegrees Fahrenheit: \t",temp... | code_fim | medium | {
"lang": "python",
"repo": "rouillonh/challenge-python",
"path": "/1.strings/challenge3_rouillonh.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.sampler = Sampler()
self.sampler.start()
result = self.wsgiapp(environ, start_response)
self.sampler.stop()
return result
def render(self, environ, start_response):
verb = environ.get('REQUEST_METHOD', 'GET').strip().upper()
if verb != 'G... | code_fim | hard | {
"lang": "python",
"repo": "schireson/flask-flamegraph",
"path": "/src/flask_flamegraph/wsgi.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.sampler.stop()
return result
def render(self, environ, start_response):
verb = environ.get('REQUEST_METHOD', 'GET').strip().upper()
if verb != 'GET':
response = Response(
'405 Method Not Allowed',
status=405,
... | code_fim | hard | {
"lang": "python",
"repo": "schireson/flask-flamegraph",
"path": "/src/flask_flamegraph/wsgi.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: schireson/flask-flamegraph path: /src/flask_flamegraph/wsgi.py
from werkzeug.wrappers import Response
from flask_flamegraph.sampler import Sampler
class FlaskFlamegraph:
def __init__(self, app=None, path='/__flame__'):
self.wsgiapp = None
self.path = path.rstrip('/')
... | code_fim | hard | {
"lang": "python",
"repo": "schireson/flask-flamegraph",
"path": "/src/flask_flamegraph/wsgi.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Init basics:
assert float_params.name == "my_float"
assert float_params.bounds == (1.5, 2.5)
assert float_params.low == 1.5
assert float_params.high == 2.5
assert float_params.get() == ["my_float", 1.5, 2.5]
# Sampling:
trial = Mock(Tri... | code_fim | hard | {
"lang": "python",
"repo": "vanderschaarlab/temporai",
"path": "/tests/plugins/core/test_params.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: vanderschaarlab/temporai path: /tests/plugins/core/test_params.py
from typing import Any, List
from unittest.mock import MagicMock, Mock
import pytest
from optuna.trial import Trial
from tempor.plugins.core import _params as params
class TestParams:
def test_basic_functionality(self):
... | code_fim | hard | {
"lang": "python",
"repo": "vanderschaarlab/temporai",
"path": "/tests/plugins/core/test_params.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: tbrunetti/decision_tree_classifier path: /data_formatting.py
from collections import deque
import pandas
# imported into build_decision_tree.py
# used to organize and format data into data frame in prep for missing data and decision tree
def format_input(data, rows, cols):
with open(data) as... | code_fim | hard | {
"lang": "python",
"repo": "tbrunetti/decision_tree_classifier",
"path": "/data_formatting.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #store data in dataframe with column labels only, row names are default of pandas numbering
formatted_matrix = pandas.DataFrame(data_values, columns=header)
return formatted_matrix
#in this instance it means row and column names were not supplied by the user
else:
for line in user_i... | code_fim | hard | {
"lang": "python",
"repo": "tbrunetti/decision_tree_classifier",
"path": "/data_formatting.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return formatted_matrix
elif rows == False and cols == True:
header = next(user_input)
header = line.rstrip('\n').split('\t')
# assuming empty tab in beginning where row names are listed
header.pop(0)
for line in user_input:
line = line.rstrip('\n').split('\t')
data_valu... | code_fim | hard | {
"lang": "python",
"repo": "tbrunetti/decision_tree_classifier",
"path": "/data_formatting.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: 2ps/djenga path: /djenga/csv/unicode_csv_writer.py
# encoding: utf-8
import csv
import six
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
class UnicodeCsvWriter:
def __init__(self, f, dialect=csv.excel, **kwds):
<|fim_suffix|> """
wri... | code_fim | medium | {
"lang": "python",
"repo": "2ps/djenga",
"path": "/djenga/csv/unicode_csv_writer.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
writerow(unicode) -> None
This function takes a Unicode string and encodes it to the output.
"""
data = []
basestring_type = six.string_types[0]
for value in row:
if not isinstance(value, basestring_type):
value = '%s'... | code_fim | medium | {
"lang": "python",
"repo": "2ps/djenga",
"path": "/djenga/csv/unicode_csv_writer.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: TevenLeScao/transformer-xl path: /pytorch/optimal_training/conversions.py
import math
import numpy as np
from scipy.optimize import root
day_ratio = 24 * 3600
depth_width_ratio = 128
constants_per_gpu = {
"V100": [2.21527743e+07, 1.18538628e+00, 1.43150104e+00, 1.66015023e+00,
... | code_fim | hard | {
"lang": "python",
"repo": "TevenLeScao/transformer-xl",
"path": "/pytorch/optimal_training/conversions.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> linear_depth = max(1, math.floor(width / depth_width_ratio))
depth = max(linear_depth + 1, math.floor(0.3 * width ** 1.25 / depth_width_ratio))
poly_params = np.array([depth * 7, depth * 8 + 3, 3 - param_number])
roots = np.roots(poly_params)
corresponding_width = int(base * round(max(... | code_fim | hard | {
"lang": "python",
"repo": "TevenLeScao/transformer-xl",
"path": "/pytorch/optimal_training/conversions.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>class EnrollmentSerializer(serializers.ModelSerializer):
class Meta:
model = Enrollment
fields = '__all__'<|fim_prefix|># repo: kvyuan/talentExOP2 path: /backend/dj/main/api/serializer.py
#from datetime import datetime
from rest_framework import serializers
from rest_framework.autht... | code_fim | hard | {
"lang": "python",
"repo": "kvyuan/talentExOP2",
"path": "/backend/dj/main/api/serializer.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: kvyuan/talentExOP2 path: /backend/dj/main/api/serializer.py
#from datetime import datetime
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from main.models import User, Workshop, Enrollment
class TokenSerializer(serializers.ModelSerializer):
class ... | code_fim | hard | {
"lang": "python",
"repo": "kvyuan/talentExOP2",
"path": "/backend/dj/main/api/serializer.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: lunarca/TornadoAppTemplate path: /handlers/__init__.py
# -*- coding: utf-8 -*-
'''
@author: moloch
Copyright 2013
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... | code_fim | hard | {
"lang": "python",
"repo": "lunarca/TornadoAppTemplate",
"path": "/handlers/__init__.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Error Handlers -
(r'/403', ForbiddenHandler),
# Catch all 404 page
(r'(.*)', NotFoundHandler),
],
# Randomly generated secret key
cookie_secret=urandom(32).encode('hex'),
# Request that does not pass @authorized will be
# redirected here
forbidden_url='/403',
... | code_fim | hard | {
"lang": "python",
"repo": "lunarca/TornadoAppTemplate",
"path": "/handlers/__init__.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def closePressed( self ):
self.hide()
def assignWidgets( self ):
self.closeButton.clicked.connect(self.closePressed)<|fim_prefix|># repo: JeffHoogland/qutemtgstats path: /Code/HelpWindow.py
import os
from PySide.QtGui import *
from PySide.QtCore import *
<|fim_middle|>from ui_H... | code_fim | hard | {
"lang": "python",
"repo": "JeffHoogland/qutemtgstats",
"path": "/Code/HelpWindow.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: JeffHoogland/qutemtgstats path: /Code/HelpWindow.py
import os
from PySide.QtGui import *
from PySide.QtCore import *
from ui_Help import Ui_Help
<|fim_suffix|> super(HelpWindow, self).__init__(parent)
self.rent = parent
self.setupUi(self)
self.assignWidgets()
... | code_fim | medium | {
"lang": "python",
"repo": "JeffHoogland/qutemtgstats",
"path": "/Code/HelpWindow.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> with MDC(trace_id=trace_id):
try:
if data_table_uri is None or not data_table_uri.startswith("bq://"):
raise ValidationError(
"Unsupported data table uri. It should looks like bq://projectId.datasetId.tableId"
... | code_fim | hard | {
"lang": "python",
"repo": "upgini/upgini",
"path": "/src/upgini/data_source/data_source_publisher.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> msg = "Data tables successfully activated"
self.logger.info(msg)
print(msg)
except HttpError as e:
if e.status_code == 404:
raise Exception("One of data tables not found")
except Exception:
... | code_fim | hard | {
"lang": "python",
"repo": "upgini/upgini",
"path": "/src/upgini/data_source/data_source_publisher.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: upgini/upgini path: /src/upgini/data_source/data_source_publisher.py
from datetime import datetime
import logging
import time
import uuid
from enum import Enum
from typing import Dict, List, Optional, Union
from upgini.errors import HttpError, ValidationError
from upgini.http import LoggerFactor... | code_fim | hard | {
"lang": "python",
"repo": "upgini/upgini",
"path": "/src/upgini/data_source/data_source_publisher.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: athms/gaze-bias-differences path: /glam/utils.py
#!/usr/bin/python
import numpy as np
import pandas as pd
from scipy.stats import mode
def format_data(df):
"""
Extracts and formats data
from <pandas.DataFrame> to model friendly entities.
"""
subjects = df['subject'].unique(... | code_fim | hard | {
"lang": "python",
"repo": "athms/gaze-bias-differences",
"path": "/glam/utils.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Generate a DataFrame containing parameter estimates
and summary statistics. Each row corresponds to one
participant in one condition.
Parameters:
model: GLAM object
Returns:
DataFrame
"""
from itertools import product
from pymc3 import summary
subject... | code_fim | hard | {
"lang": "python",
"repo": "athms/gaze-bias-differences",
"path": "/glam/utils.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return {
"frame": {"duration": duration, "redraw": True},
"mode": "immediate",
"fromcurrent": True,
"transition": {"duration": duration, "easing": "linear"},
}
# visualization
scatter3d_list = [pc.plotly(0, as_figure=False, max_num_p... | code_fim | hard | {
"lang": "python",
"repo": "chuong98/gradslam",
"path": "/gradslam/utils/plot_update_map.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: chuong98/gradslam path: /gradslam/utils/plot_update_map.py
import numpy as np
import plotly.graph_objects as go
def plotly_map_update_visualization(intermediate_pcs, poses, K, max_points_per_pc=50000, ms_per_frame=50):
"""
Args:
- intermediate_pcs (List[gradslam.Pointclouds]): li... | code_fim | hard | {
"lang": "python",
"repo": "chuong98/gradslam",
"path": "/gradslam/utils/plot_update_map.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rapid7/insightconnect-plugins path: /plugins/abnormal_security/icon_abnormal_security/util/api.py
from insightconnect_plugin_runtime.helper import clean
import requests
from insightconnect_plugin_runtime.exceptions import PluginException
import json
from logging import Logger
from urllib.parse im... | code_fim | hard | {
"lang": "python",
"repo": "rapid7/insightconnect-plugins",
"path": "/plugins/abnormal_security/icon_abnormal_security/util/api.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def manage_threat(self, threat_id: str, action: str) -> dict:
return self.send_request("POST", f"/threats/{threat_id}", payload={"action": action})
def manage_case(self, case_id: str, action: str) -> dict:
results = self.send_request("POST", f"/cases/{case_id}", payload={"action":... | code_fim | hard | {
"lang": "python",
"repo": "rapid7/insightconnect-plugins",
"path": "/plugins/abnormal_security/icon_abnormal_security/util/api.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rechido/PCA-OGD path: /algos/gem.py
import torch
from utils.utils import parameters_to_grad_vector
from algos.common import Memory
import numpy as np
## toolbox for GEM/AGEM methods
def _get_new_gem_m_basis(self, device,optimizer, model,forward):
new_basis = []
... | code_fim | hard | {
"lang": "python",
"repo": "rechido/PCA-OGD",
"path": "/algos/gem.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> trainer.task_memory[trainer.task_count] = Memory()
randind = torch.randperm(len(train_loader.dataset))[:num_sample_per_task] # randomly sample some data
for ind in randind: # save it to the memory
trainer.task_memory[trainer.task_count].append(train_loader.dataset[ind... | code_fim | hard | {
"lang": "python",
"repo": "rechido/PCA-OGD",
"path": "/algos/gem.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hardman/pabook path: /run.py
#coding=utf-8
'''
需要安装的软件:
1. mysql
2. pip
需要安装的python插件
1. PyMySQL
2. beautifulsoup4
3. html5lib
4. lxml
5. pycrypto
'''
'''
#运行
1. 修改Config.sample.py
2. 执行python run.py
'''
from src.utils import Log
<|fim_suffix|> if not os.path.exists("Config.py"):
... | code_fim | hard | {
"lang": "python",
"repo": "hardman/pabook",
"path": "/run.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> Log.D("--test--");
dropAllTables();
sys.exit(0)
# 将Config.sample.py复制出一个Config.py文件
def createConfigFile():
if not os.path.exists("Config.py"):
fd = open("Config.sample.py", "r");
content = fd.read();
fd.close();
wfd = open("Config.py", "w");
wfd.wr... | code_fim | hard | {
"lang": "python",
"repo": "hardman/pabook",
"path": "/run.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>#清空数据库中的表
def dropAllTables():
from src.db import Db
Db.instance.executeSql('''show tables;''');
ret = Db.instance.fetchAll();
for item in ret:
for k, v in item.items():
Db.instance.executeSql('''drop table if exists {};'''.format(v));
Log.D("droping table "... | code_fim | medium | {
"lang": "python",
"repo": "hardman/pabook",
"path": "/run.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>#Labels
Label(master,text="Audio Player | By Joshua .J",font=("Calibri",15),fg="black").grid(sticky="N",row=0,padx=120)
Label(master,text="Select a audio file you would like to play!",font=("Calibri",12),fg="black").grid(sticky="N",row=1)
Label(master,text="Volume",font=("Calibri",12),fg="black").grid(sti... | code_fim | hard | {
"lang": "python",
"repo": "PythonJoshua/AudioPLR",
"path": "/files/main.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: PythonJoshua/AudioPLR path: /files/main.py
from pygame import mixer
from tkinter import Tk
from tkinter import Label
from tkinter import Button
from tkinter import filedialog
current_volume = float(0.5)
#Functions
def play_song():
filename = filedialog.askopenfilename(initialdir="C:/",title... | code_fim | hard | {
"lang": "python",
"repo": "PythonJoshua/AudioPLR",
"path": "/files/main.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: SG-Azar/ABMHC path: /demo.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 07 13:30:00 2020
@author: Alan J.X. Guo
"""
from tqdm import tqdm
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau, EarlyStopping
import scipy.io as ... | code_fim | hard | {
"lang": "python",
"repo": "SG-Azar/ABMHC",
"path": "/demo.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>NUMBER_CLASSES = NB_CLASSES
R = 16
PATCH_SIZE = HALFSIZE * 2 + 1
EPOCHS = 300
BATCH_SIZE = 128
input_c = Input(shape=(PATCH_SIZE,PATCH_SIZE,R))
cc1 = Conv2D(64,3,strides=(1,1),activation='relu')(input_c)
cc2 = Conv2D(32,3,strides=(1,1),activation='relu')(cc1)
cc2 = Conv2D(16,3,strides=(1,1),activation='r... | code_fim | hard | {
"lang": "python",
"repo": "SG-Azar/ABMHC",
"path": "/demo.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> @raises(Exception)
def test_view_individual_module_invalid_code_response(self):
'''
Tests if user will fail to access page for showing module overview
if target module is invalid.
'''
root = self.test_app.get(self.URL_CONTAIN_INVALID_CODE_AY_QUOTA)
... | code_fim | hard | {
"lang": "python",
"repo": "nus-mtp/cs-modify",
"path": "/test/test_view_individual_module.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nus-mtp/cs-modify path: /test/test_view_individual_module.py
'''
test_view_individual_module.py tests the app's view individual mod page
'''
from paste.fixture import TestApp
from nose.tools import assert_equal, raises
from app import APP
from components import session
class TestCode(object)... | code_fim | hard | {
"lang": "python",
"repo": "nus-mtp/cs-modify",
"path": "/test/test_view_individual_module.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Test the hello_world task with fixed inputs and outputs."""
inputs = {
"input_file": workflow_data["test_file"],
"output_filename": "pytest_wdl_readme.md"
}
expected = {
"output_file": workflow_data["test_file"]
}
workflow_runner(
"test_hello_worl... | code_fim | hard | {
"lang": "python",
"repo": "EliLillyCo/pytest-wdl",
"path": "/tests/test_workflow/hello_world/tests/test_hello_world.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: EliLillyCo/pytest-wdl path: /tests/test_workflow/hello_world/tests/test_hello_world.py
#! /usr/bin/env python
"""Test hello_world task"""
import pytest
@pytest.fixture(scope="module")
def project_root_files():
"""
Override the project root for this test since it doesn't follow a
st... | code_fim | medium | {
"lang": "python",
"repo": "EliLillyCo/pytest-wdl",
"path": "/tests/test_workflow/hello_world/tests/test_hello_world.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
@pytest.mark.integration
def test_hello_world(workflow_data, workflow_runner):
"""Test the hello_world task with fixed inputs and outputs."""
inputs = {
"input_file": workflow_data["test_file"],
"output_filename": "pytest_wdl_readme.md"
}
expected = {
"output_file"... | code_fim | medium | {
"lang": "python",
"repo": "EliLillyCo/pytest-wdl",
"path": "/tests/test_workflow/hello_world/tests/test_hello_world.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mutantmonkey/pagerglue path: /pagerglue/methods/xmpp.py
import logging
import sleekxmpp
from pagerglue.methods.base import PageMethod
logger = logging.getLogger(__name__)
class XMPPBackend(sleekxmpp.ClientXMPP):
def __init__(self, jid, password, notify_jids):
super().__init__(jid, ... | code_fim | hard | {
"lang": "python",
"repo": "mutantmonkey/pagerglue",
"path": "/pagerglue/methods/xmpp.py",
"mode": "psm",
"license": "ISC",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __init__(self, config, *args, **kwargs):
if set(('jid', 'password', 'notify')) <= set(config):
self.xmpp_jid = config['jid']
self.xmpp_password = config['password']
self.notify_jids = config['notify']
else:
logger.warning(
... | code_fim | hard | {
"lang": "python",
"repo": "mutantmonkey/pagerglue",
"path": "/pagerglue/methods/xmpp.py",
"mode": "spm",
"license": "ISC",
"source": "the-stack-v2"
} |
<|fim_suffix|>plt.xlabel('$x$')
plt.ylabel('$y$')
plt.legend(loc='best')
plt.grid() # minor
#if using termux
plt.savefig('triangle.pdf')
plt.savefig('triangle.eps')
#subprocess.run(shlex.split("termux−open ../figs/triangle.pdf"))
#else
plt.show()<|fim_prefix|># repo: ravinamani15/Assignments path: /4th_semester/Intro_... | code_fim | hard | {
"lang": "python",
"repo": "ravinamani15/Assignments",
"path": "/4th_semester/Intro_to_AI_and_ML/assignment-1/triangle.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ravinamani15/Assignments path: /4th_semester/Intro_to_AI_and_ML/assignment-1/triangle.py
import numpy as np
import matplotlib.pyplot as plt
A = np.array([-2, -2])
B = np.array([1, 3])
C = np.array([4, -1])
len = 10
<|fim_suffix|>plt.xlabel('$x$')
plt.ylabel('$y$')
plt.legend(loc='best')
plt.gr... | code_fim | hard | {
"lang": "python",
"repo": "ravinamani15/Assignments",
"path": "/4th_semester/Intro_to_AI_and_ML/assignment-1/triangle.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Jimmy-INL/google-research path: /spin_spherical_cnns/layers.py
ed_kernel(self, ell_max, num_channels_in):
# We interpolate along ell to obtain all weights from the learnable weights,
# hence it doesn't make sense to have more parameters than num_ell.
if self.num_filter_params > ell_ma... | code_fim | hard | {
"lang": "python",
"repo": "Jimmy-INL/google-research",
"path": "/spin_spherical_cnns/layers.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Jimmy-INL/google-research path: /spin_spherical_cnns/layers.py
pectral_upsampling,
input_representation, output_representation):
r"""Spin-weighted spherical convolution; spatial input and spectral filters.
This implements a multi-channel version of Eq. (13) in [1], where sphere_set
cor... | code_fim | hard | {
"lang": "python",
"repo": "Jimmy-INL/google-research",
"path": "/spin_spherical_cnns/layers.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> The spin == 0 component does not change phase upon rotation, so any pointwise
nonlinearity works. Here we choose the leaky relu.
Attributes:
spins: (n_spins,) Sequence of int containing the input spins.
epsilon: Small float constant to avoid division by zero.
bias_initializer: initializ... | code_fim | hard | {
"lang": "python",
"repo": "Jimmy-INL/google-research",
"path": "/spin_spherical_cnns/layers.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: idaholab/raven path: /scripts/copy_back_plugins_results.py
#!/usr/bin/env python
# Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 Lic... | code_fim | hard | {
"lang": "python",
"repo": "idaholab/raven",
"path": "/scripts/copy_back_plugins_results.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>import sys, os, shutil
from distutils import dir_util
# get the location of this script
app_path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
plugins_directory = os.path.abspath(os.path.join(app_path, "plugins"))
plugins_test_dir = os.path.abspath(os.path.join(app_path, "tests","pl... | code_fim | hard | {
"lang": "python",
"repo": "idaholab/raven",
"path": "/scripts/copy_back_plugins_results.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: charlesXu86/Bert4tf path: /bert4tf/embeddings.py
# -*- coding: utf-8 -*-
'''
@Author : Xu
@Software: PyCharm
@File : embeddings.py
@Time : 2019-12-11 22:21
@Desc :
'''
from __future__ import absolute_import, division, print_function
<|fim_suffix|>class BertEmbedding... | code_fim | hard | {
"lang": "python",
"repo": "charlesXu86/Bert4tf",
"path": "/bert4tf/embeddings.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>class EmbeddingsProjector(bert4tf.Layer):
class Params(bert4tf.Layer.Params):
hidden_size = 768
embedding_size = None # None for BERT, not None for ALBERT
project_embeddings_with_bias = True # in ALBERT - True for Google, False for brightmart/... | code_fim | medium | {
"lang": "python",
"repo": "charlesXu86/Bert4tf",
"path": "/bert4tf/embeddings.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def test_export(demo_dir):
r = run(f"snakemake exportCounts -c{CORES}", demo_dir)
assert "Finished job 0." in r.stderr
@pytest.mark.trylast
def test_all(demo_dir):
r = run(f"snakemake -c{CORES}", demo_dir)
assert "Finished job 0." in r.stderr<|fim_prefix|># repo: gagneurlab/drop path: /... | code_fim | hard | {
"lang": "python",
"repo": "gagneurlab/drop",
"path": "/tests/pipeline/test_pipeline.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: gagneurlab/drop path: /tests/pipeline/test_pipeline.py
from tests.common import *
def test_dryrun(demo_dir):
r = run("snakemake -n -c1", dir_path=demo_dir)
message = "This was a dry-run (flag -n). The order of jobs does not reflect the order of execution."
assert message in r.stdout... | code_fim | hard | {
"lang": "python",
"repo": "gagneurlab/drop",
"path": "/tests/pipeline/test_pipeline.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ahmet-celik/Selfection path: /selfection/Section.py
class Section(object):
def __init__(self, matched_line):
self.__setfields__(int(matched_line.group("nr")), matched_line.group("name"), matched_line.group("type"),
int(matched_line.group("addr"), 16), int(m... | code_fim | hard | {
"lang": "python",
"repo": "ahmet-celik/Selfection",
"path": "/selfection/Section.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return self.off + (addr - self.addr)
def off2addr(self, off):
return self.addr + (off - self.off)<|fim_prefix|># repo: ahmet-celik/Selfection path: /selfection/Section.py
class Section(object):
def __init__(self, matched_line):
self.__setfields__(int(matched_line.group("... | code_fim | hard | {
"lang": "python",
"repo": "ahmet-celik/Selfection",
"path": "/selfection/Section.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return self.addr <= addr < (self.addr + self.size)
def addr2off(self, addr):
return self.off + (addr - self.addr)
def off2addr(self, off):
return self.addr + (off - self.off)<|fim_prefix|># repo: ahmet-celik/Selfection path: /selfection/Section.py
class Section(object):
... | code_fim | hard | {
"lang": "python",
"repo": "ahmet-celik/Selfection",
"path": "/selfection/Section.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pombreda/python-bizdatetime path: /tests.py
#!/usr/bin/env python
import unittest
from datetime import date
from bizdatetime import Policy, MON, TUE, WED, THU, FRI, SAT, SUN
holidays = (
date(2009, 12, 25), # xmas
date(2009, 12, 28), # boxing day in on
date(2010, 1, 1), #... | code_fim | hard | {
"lang": "python",
"repo": "pombreda/python-bizdatetime",
"path": "/tests.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_positive_addition(self):
self.assertEqual(self.policy.add(date(2011, 3, 3), 1), date(2011, 3, 4))
self.assertEqual(self.policy.add(date(2011, 3, 3), 2), date(2011, 3, 7))
self.assertEqual(self.policy.add(date(2011, 3, 3), 3), date(2011, 3, 8))
self.assertEq... | code_fim | hard | {
"lang": "python",
"repo": "pombreda/python-bizdatetime",
"path": "/tests.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def setUp(self):
self.policy = Policy(weekends=(SAT, SUN), holidays=holidays)
def test_positive_addition(self):
self.assertEqual(self.policy.add(date(2011, 3, 3), 1), date(2011, 3, 4))
self.assertEqual(self.policy.add(date(2011, 3, 3), 2), date(2011, 3, 7))
... | code_fim | hard | {
"lang": "python",
"repo": "pombreda/python-bizdatetime",
"path": "/tests.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mostafaelaraby/Real-DEEL-Dark-Experience path: /real_deel_dark_experience/models/actor_critic.py
"""wrapper for actor critic that takes model name
as input and creates a new network based on the input architecture
with actor as normal forward and critic with a special function
"""
# TODO add au... | code_fim | hard | {
"lang": "python",
"repo": "mostafaelaraby/Real-DEEL-Dark-Experience",
"path": "/real_deel_dark_experience/models/actor_critic.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """takes observation as input and returns actor/ critic
Args:
x (tensor): input tensor
Returns:
tuple: actor output, critic output
"""
x = x.to(self.dummy_param.device)
encoder_output, actor_output = self.get_penultimate(x)
... | code_fim | hard | {
"lang": "python",
"repo": "mostafaelaraby/Real-DEEL-Dark-Experience",
"path": "/real_deel_dark_experience/models/actor_critic.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> Args:
x (tensor): input tensor
Returns:
tuple: actor output, critic output
"""
x = x.to(self.dummy_param.device)
encoder_output, actor_output = self.get_penultimate(x)
critic_output = self.critic_decoder(encoder_output)
... | code_fim | medium | {
"lang": "python",
"repo": "mostafaelaraby/Real-DEEL-Dark-Experience",
"path": "/real_deel_dark_experience/models/actor_critic.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> itr = 0
prev_error = 1000000000
while True:
for itr in range(x_train.shape[0]):
w = w - (alpha*grad_f(w, x_train[itr], y_train[itr]))
new_error = error(w, x_train, y_train)
if prev_error-new_error < epsilion:
return w
... | code_fim | hard | {
"lang": "python",
"repo": "RikilG/Data-Science-Foundations",
"path": "/Optimizers/StocasticGradDesc.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: RikilG/Data-Science-Foundations path: /Optimizers/StocasticGradDesc.py
"""
This module implements stocastic gradient descent
"""
import numpy as np
from tqdm import tqdm
f = None
def grad_f(w: np.array, x: np.array, y: np.array) -> int:
res = (y - f(w, x))
w_grad = -1*res[0]... | code_fim | hard | {
"lang": "python",
"repo": "RikilG/Data-Science-Foundations",
"path": "/Optimizers/StocasticGradDesc.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def write_zoey_json_file(to_dir, data):
global zoey_json_data
zoey_json_data = data
write_json_file(
path_join(to_dir, settings.json_conf_file),
data,
json_dumps={
'indent': 4
}
)
def read_zoey_json_file(to_dir, force=False):
global zoey_json_data
if not force and zoey_json_data is ... | code_fim | medium | {
"lang": "python",
"repo": "charliejuc/zoey",
"path": "/lib/ljson.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: charliejuc/zoey path: /lib/ljson.py
from utils.cjson import write_json_file, read_json_file
import settings, json, sys, os
path_join = os.path.join
zoey_json_data = None
def write_zoey_json_file(to_dir, data):
global zoey_json_data
zoey_json_data = data
<|fim_suffix|> print('[JSONDecodeErr... | code_fim | hard | {
"lang": "python",
"repo": "charliejuc/zoey",
"path": "/lib/ljson.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> try:
zoey_json_data = read_json_file(json_conf_file)
except json.decoder.JSONDecodeError as e:
if os.stat(json_conf_file).st_size != 0:
raise e
print('[JSONDecodeError read_zoey_json_file]', e, file=sys.stderr)
zoey_json_data = {}
except FileNotFoundError:
zoey_json_data = {}
return z... | code_fim | hard | {
"lang": "python",
"repo": "charliejuc/zoey",
"path": "/lib/ljson.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: LucasMoncuit/ucca-parser path: /parser/convert/__init__.py
from .convert import UCCA2tree, to_UCCA
from .trees import InternalParseNode, LeafPars<|fim_suffix|>position
__all__ = (
"UCCA2tree",
"to_UCCA",
"InternalParseNode",
"LeafParseNode",
"InternalTreebankNode",
"LeafT... | code_fim | medium | {
"lang": "python",
"repo": "LucasMoncuit/ucca-parser",
"path": "/parser/convert/__init__.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.