index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
6,400 | 5aa55a96e414ad6b3ceebbcbd71c23a1fd69f0d1 | from .FactorWarData import Get_FactorWar_Data | [
"from .FactorWarData import Get_FactorWar_Data",
"from .FactorWarData import Get_FactorWar_Data\n",
"<import token>\n"
] | false |
6,401 | 4ef6002480fcaa514f41227978bae76f6e02c22d | name = input("Enter your name: ")
print("Hi buddy! Today we will play a game " + name + "!")
print("Are you ready?")
question = input("Are you ready ? Yes or no: ")
print(name + " we are starting!")
liste1 = ['My neighbor ', 'My girlfriend ', 'My boyfriend ', 'My dog ']
num = input("Enter a number: ")
... | [
"name = input(\"Enter your name: \")\r\nprint(\"Hi buddy! Today we will play a game \" + name + \"!\")\r\n\r\nprint(\"Are you ready?\")\r\n\r\nquestion = input(\"Are you ready ? Yes or no: \")\r\nprint(name + \" we are starting!\")\r\n\r\n\r\nliste1 = ['My neighbor ', 'My girlfriend ', 'My boyfriend ', 'My dog ']\r... | false |
6,402 | 1861c394fb02643d2e6ac8362f3340f512ef6d72 | import gc
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import cv2
import torch
from torch.utils.data import DataLoader
from torch import optim
from torch.optim import lr_scheduler
from dataset.car_dataset import CarDataset
from nn.netw... | [
"import gc\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom tqdm import tqdm\r\nimport cv2 \r\n\r\nimport torch\r\nfrom torch.utils.data import DataLoader\r\nfrom torch import optim\r\nfrom torch.optim import lr_scheduler\r\n\r\nfrom dataset.car_dataset im... | false |
6,403 | 16e5a44cb4fbe71eaa9c1f5b00505578de0d2cea | from django.contrib import admin
# Register your models here.
from .models import HuyenQuan
admin.site.register(HuyenQuan)
| [
"from django.contrib import admin\n\n# Register your models here.\nfrom .models import HuyenQuan\n\nadmin.site.register(HuyenQuan)\n",
"from django.contrib import admin\nfrom .models import HuyenQuan\nadmin.site.register(HuyenQuan)\n",
"<import token>\nadmin.site.register(HuyenQuan)\n",
"<import token>\n<code... | false |
6,404 | 74b1cdcb1aaf6cde7e8ce3eeb73cd82689719b00 | # apport hook for oem-config; adds log file
import os.path
def add_info(report):
if os.path.exists('/var/log/oem-config.log'):
report['OemConfigLog'] = ('/var/log/oem-config.log',)
| [
"# apport hook for oem-config; adds log file\n\nimport os.path\n\ndef add_info(report):\n if os.path.exists('/var/log/oem-config.log'):\n report['OemConfigLog'] = ('/var/log/oem-config.log',)\n",
"import os.path\n\n\ndef add_info(report):\n if os.path.exists('/var/log/oem-config.log'):\n repor... | false |
6,405 | 751d2a07b97d080988c54511ca13a97a969e06bd | import pygame
import numpy as np
import random
from enum import Enum
from .config import *
class Actions(Enum):
FORWARD = 0
RIGHT = 1
LEFT = 2
BACK = 3
class MazeEnv():
''' TODO '''
def __init__(self, GW, GH, SW, SH):
global GRID_WIDTH, GRID_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT, BOX_WID... | [
"import pygame\nimport numpy as np\nimport random\nfrom enum import Enum\nfrom .config import *\n\nclass Actions(Enum):\n FORWARD = 0\n RIGHT = 1\n LEFT = 2\n BACK = 3\n\nclass MazeEnv():\n ''' TODO '''\n def __init__(self, GW, GH, SW, SH):\n global GRID_WIDTH, GRID_HEIGHT, SCREEN_WIDTH, SC... | false |
6,406 | dd9574ea08beb9bc5f1413afd63c751fd42cba67 | #!/usr/bin/env python3
from pexpect import pxssh
import time
s = pxssh.pxssh()
ip = "" #replace ip address
username= "" #replace username
password= "" #replace password
s.login (ip, username, password)
print ("SSH session login successful")
s.sendline ('application stop')
s.prompt() # match the prompt
print("S... | [
"#!/usr/bin/env python3\n\nfrom pexpect import pxssh\nimport time\ns = pxssh.pxssh()\nip = \"\" #replace ip address\nusername= \"\" #replace username\npassword= \"\" #replace password\ns.login (ip, username, password)\nprint (\"SSH session login successful\")\ns.sendline ('application stop')\ns.prompt() # m... | false |
6,407 | ab69f4d6afb96d86381bcf507d7810980446c6ea | import msvcrt
import random
import os
def clear():
''' It clears the screen.'''
os.system('cls')
def InitMatrix():
''' It initializes the matrix as a board game.'''
m = [[0 for i in range(4)] for j in range(4)]
for i in range(2):
x = random.randint(0, 3)
y = random... | [
"import msvcrt\r\nimport random\r\nimport os\r\n\r\ndef clear():\r\n ''' It clears the screen.'''\r\n\r\n os.system('cls')\r\n\r\ndef InitMatrix():\r\n ''' It initializes the matrix as a board game.'''\r\n\r\n m = [[0 for i in range(4)] for j in range(4)]\r\n for i in range(2):\r\n x = random.... | false |
6,408 | 09b14705a6905470058b5eecc6dd0bb214975c66 | """IDQ Importer Exporter
This script defines Import and Export functions through which it can communicate with
a Informatica Model Repository.
It also provides some related functions, such as:
- Create IDQ folder
- Check in IDQ components
Parts by Laurens Verhoeven
Parts by Jac. Beekers
@Version: 20190... | [
"\"\"\"IDQ Importer Exporter\n\nThis script defines Import and Export functions through which it can communicate with\na Informatica Model Repository.\n\nIt also provides some related functions, such as:\n\t- Create IDQ folder\n\t- Check in IDQ components\n\n Parts by Laurens Verhoeven\n Parts by Jac. Beekers... | false |
6,409 | dfd5915428dc8f15fb61c5d81f22dfecfe29af15 | from django.urls import reverse
from django.utils.translation import get_language
from drf_dynamic_fields import DynamicFieldsMixin
from geotrek.api.v2.serializers import AttachmentSerializer
from mapentity.serializers import MapentityGeojsonModelSerializer
from rest_framework import serializers as rest_serializers
fro... | [
"from django.urls import reverse\nfrom django.utils.translation import get_language\nfrom drf_dynamic_fields import DynamicFieldsMixin\nfrom geotrek.api.v2.serializers import AttachmentSerializer\nfrom mapentity.serializers import MapentityGeojsonModelSerializer\nfrom rest_framework import serializers as rest_seria... | false |
6,410 | 03943e146c0d64cfe888073e3a7534b6615b023f | import sys
from pcaspy import SimpleServer, Driver
import time
from datetime import datetime
import thread
import subprocess
import argparse
#import socket
#import json
import pdb
class myDriver(Driver):
def __init__(self):
super(myDriver, self).__init__()
def printDb(prefix):
global pvdb
print... | [
"import sys\n\nfrom pcaspy import SimpleServer, Driver\nimport time\nfrom datetime import datetime\nimport thread\nimport subprocess\nimport argparse\n#import socket\n#import json\nimport pdb\n\nclass myDriver(Driver):\n def __init__(self):\n super(myDriver, self).__init__()\n\n\ndef printDb(prefix):\n ... | true |
6,411 | cd9d10a3ee3956762d88e76a951023dd77023942 | from Get2Gether.api_routes.schedule import schedule_router
from Get2Gether.api_routes.auth import auth_router
from Get2Gether.api_routes.event import event_router
| [
"from Get2Gether.api_routes.schedule import schedule_router\nfrom Get2Gether.api_routes.auth import auth_router\nfrom Get2Gether.api_routes.event import event_router\n",
"<import token>\n"
] | false |
6,412 | c234031fa6d43c19515e27c5b12f8e8338f24a1c | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head:
return head
fh = List... | [
"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param head, a ListNode\n # @return a ListNode\n def insertionSortList(self, head):\n if not head:\n return head\n \... | false |
6,413 | d46cda5354640e1c87432d39a2e949d6db034edc | # Generated by Django 3.2 on 2021-04-21 13:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rate', '0003_auto_20210421_1316'),
]
operations = [
migrations.AlterField(
model_name='song',
name='overall_rating',
... | [
"# Generated by Django 3.2 on 2021-04-21 13:21\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rate', '0003_auto_20210421_1316'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='song',\n name=... | false |
6,414 | 28091b7251f980f3f63abdb03140edd0d789be8f | name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
x = list()
for line in handle:
line.split() ## unnesssecary
if line.startswith("From "):
x.append(line[line.find(" ")+1:line.find(" ",line.find(" ")+1)])
counts = dict()
for name in x:
if name not in co... | [
"name = raw_input(\"Enter file:\")\nif len(name) < 1 : name = \"mbox-short.txt\"\nhandle = open(name)\nx = list()\nfor line in handle:\n line.split() ## unnesssecary\n if line.startswith(\"From \"):\n x.append(line[line.find(\" \")+1:line.find(\" \",line.find(\" \")+1)])\n\n\n\ncounts = dict()\nfor nam... | true |
6,415 | d60a2d4c819f701e8e439b8839415aa2838df185 | # https://www.acmicpc.net/problem/3584
import sys, collections
input = sys.stdin.readline
N = int(input())
for _ in range(N):
n = int(input())
arr = collections.defaultdict(list)
parent = [i for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().split())
arr[a].append(b)
... | [
"# https://www.acmicpc.net/problem/3584\nimport sys, collections\ninput = sys.stdin.readline\nN = int(input())\nfor _ in range(N):\n n = int(input())\n arr = collections.defaultdict(list)\n parent = [i for i in range(n + 1)]\n for i in range(n - 1):\n a, b = map(int, input().split())\n arr... | false |
6,416 | e2e3b63deba20cd87fdfca81a9f67fa24891a1e0 | '''
Copyright (c) 2011 Jacob K. Schoen (jacob.schoen@gmail.com)
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
the Software without restriction, including without limitation the rights to
use, copy, modify,... | [
"'''\nCopyright (c) 2011 Jacob K. Schoen (jacob.schoen@gmail.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in \nthe Software without restriction, including without limitation the rights to \nuse, ... | false |
6,417 | 43b519d7db2e46a0bf9317eddac1f5cf6b7b79e3 | import pandas as pd
import json
import spacy
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF
nlp = spacy.load('en_core_web_sm')
list_data = []
list_data_only_reviews = []
list_data_reviewerid = []
result = []
l = []
for line in open('Automotive_5.json', 'r'):
li... | [
"import pandas as pd\nimport json\nimport spacy\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.decomposition import NMF\n\n\n\nnlp = spacy.load('en_core_web_sm')\nlist_data = []\nlist_data_only_reviews = []\nlist_data_reviewerid = []\nresult = []\nl = []\n\nfor line in open('Automotive_5... | false |
6,418 | 760daa908ca92e7fb1393bdf28fee086dc1648ef | from collections import Counter
# Complete the isValid function below.
def isValid(s):
if not s:
return True
x = Counter(s)
print(x)
first_c = x.pop(s[0])
cnt = 0
for k, c in x.items():
if c != first_c:
if first_c == 1:
cnt += 1
firs... | [
"from collections import Counter\n\n\n# Complete the isValid function below.\ndef isValid(s):\n if not s:\n return True\n\n x = Counter(s)\n print(x)\n first_c = x.pop(s[0])\n cnt = 0\n for k, c in x.items():\n if c != first_c:\n if first_c == 1:\n cnt += 1\... | false |
6,419 | 61ff5fae02d18d51595e8050d97244574e7d8af1 | from setuptools import setup
setup(
name='nodepool_harness',
version='0.1dev',
description='Nodepool harness',
packages=['nodepool_harness', 'statsd', 'apscheduler'],
install_requires=["PyYAML", "python-novaclient", "paramiko", "sqlalchemy"],
entry_points = {
'console_scripts': [
... | [
"from setuptools import setup\n\n\nsetup(\n name='nodepool_harness',\n version='0.1dev',\n description='Nodepool harness',\n packages=['nodepool_harness', 'statsd', 'apscheduler'],\n install_requires=[\"PyYAML\", \"python-novaclient\", \"paramiko\", \"sqlalchemy\"],\n entry_points = {\n 'co... | false |
6,420 | aacd5d671090c3305a53d62c3c6c25d4c033f42d | # Spelling bee NYT puzzle solver
with open('words.txt') as words_fh:
# Converts strips and lowercases lexicon (space seperated txt file)
# Use set to remove duplicates (decasing)
lexicon = set(list(map(lambda x: x.strip().lower(), words_fh.readlines())))
# NOTE: Could add a CLI to allow users to input... | [
"# Spelling bee NYT puzzle solver\r\n\r\nwith open('words.txt') as words_fh:\r\n # Converts strips and lowercases lexicon (space seperated txt file)\r\n # Use set to remove duplicates (decasing)\r\n\tlexicon = set(list(map(lambda x: x.strip().lower(), words_fh.readlines())))\r\n\r\n# NOTE: Could add a CLI to ... | false |
6,421 | 9290294b5df081ef0cae5450a9ea3baef789c041 | from .models import Owner, Vehicle
from rest_framework import viewsets, permissions
from .serializers import OwnerSerializer, VehicleSerializer
class OwnerViewSet(viewsets.ModelViewSet):
queryset = Owner.objects.all().order_by('id')
serializer_class = OwnerSerializer
permission_classes = [permissions.IsAu... | [
"from .models import Owner, Vehicle\nfrom rest_framework import viewsets, permissions\nfrom .serializers import OwnerSerializer, VehicleSerializer\n\n\nclass OwnerViewSet(viewsets.ModelViewSet):\n queryset = Owner.objects.all().order_by('id')\n serializer_class = OwnerSerializer\n permission_classes = [per... | false |
6,422 | c796123fbbf3adcde59779a104dcafb30a673a79 | from elements import Node, Bar, Material, Group, Load
from pprint import pprint
# query
# next((e for e in result['coordinates']['nodes'] if e.n == int(el[0])), None)
class Reader():
def read(self, filePath):
"""
Reads text file with nodes and returns the result dict with all objects
and their nested p... | [
"from elements import Node, Bar, Material, Group, Load\nfrom pprint import pprint\n\n# query\n# next((e for e in result['coordinates']['nodes'] if e.n == int(el[0])), None)\n\nclass Reader():\n def read(self, filePath):\n \"\"\"\n Reads text file with nodes and returns the result dict with all objects\n ... | false |
6,423 | 775ac823f6784510fa919b08ee4150eb500710c4 | # coding: utf-8
"""
CityPay POS API
CityPay Point of Sale API for payment with card present devices including EMV readers and contactless POS readers. The API is available from https://github.com/citypay/citypay-pos-api The API makes it simple to add EMV and contactless card acceptance to iOS, Android, Tabl... | [
"# coding: utf-8\n\n\"\"\"\n CityPay POS API\n\n CityPay Point of Sale API for payment with card present devices including EMV readers and contactless POS readers. The API is available from https://github.com/citypay/citypay-pos-api The API makes it simple to add EMV and contactless card acceptance to iOS, ... | true |
6,424 | a8d52d81ef6538e9cb8a0a9cab7cd0a778454c8e | import json
from constants import *
from coattention_layer import *
from prepare_generator import *
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import LearningRateScheduler, ModelCheckpoint, Early... | [
"import json\r\nfrom constants import *\r\nfrom coattention_layer import *\r\nfrom prepare_generator import *\r\nfrom tensorflow.keras.layers import Input\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom tensorflow.keras.callbacks import LearningRateScheduler, Mod... | false |
6,425 | 015b06d7f08f9de60a46d8428820333621732c53 | import os
def log(text, level=2, outFile='log.txt'):
text = str(text)
if level == 0:
return True
if level == 3:
with open(outFile, 'a') as logger:
logger.write(text)
logger.close()
print(text)
return True
if level == 2:
... | [
"import os\r\n\r\n\r\ndef log(text, level=2, outFile='log.txt'):\r\n text = str(text)\r\n if level == 0:\r\n return True\r\n\r\n if level == 3:\r\n with open(outFile, 'a') as logger:\r\n logger.write(text)\r\n logger.close()\r\n print(text)\r\n return True\... | false |
6,426 | 629649abe9d855122a5db6d61a20735ceb89c5cf | from pathlib import Path
import eyed3
import csv
import sys
import filetype
import os
pathFile = Path('C:\\Users\\JORGE\\Music\\Vicente Garcia - Te Soñé (Lyric Video)(MP3_160K).mp3')
audiofile = eyed3.load(pathFile)
with open('loveMusic.csv', 'w', newline='') as csvFile:
fieldsName = ['nameFile', 'tittle', 'art... | [
"from pathlib import Path\nimport eyed3\nimport csv\nimport sys\nimport filetype\nimport os\n\npathFile = Path('C:\\\\Users\\\\JORGE\\\\Music\\\\Vicente Garcia - Te Soñé (Lyric Video)(MP3_160K).mp3')\n\naudiofile = eyed3.load(pathFile)\n\nwith open('loveMusic.csv', 'w', newline='') as csvFile:\n fieldsName = ['... | false |
6,427 | 935853a4afdb50a4652e14913d0cdb251a84ea14 | from typing import Sized
import pygame
import time
from pygame.locals import *
import random
SIZE = 20
BACKGROUND = (45, 34, 44)
W = 800
H = 400
SCREEN = (W, H)
class Snake:
def __init__(self, parent_screen, length):
self.parent_screen = parent_screen
self.length = length
self.snake = pyg... | [
"from typing import Sized\nimport pygame\nimport time\nfrom pygame.locals import *\nimport random\n\nSIZE = 20\nBACKGROUND = (45, 34, 44)\nW = 800\nH = 400\nSCREEN = (W, H)\n\n\nclass Snake:\n def __init__(self, parent_screen, length):\n self.parent_screen = parent_screen\n self.length = length\n ... | false |
6,428 | 39abda1dd8b35889405db1b3971917d2a34180e3 | #Matthew Shrago
#implementation of bisection search.
import math
low = 0
high = 100
ans = int((high + low)/2)
print "Please think of a number between 0 and 100!"
while ans != 'c':
#print high, low
print "Is your secret number " + str(ans) + "?",
number = raw_input("Enter 'h' to indicate the guess is too hi... | [
"#Matthew Shrago\n#implementation of bisection search.\nimport math\nlow = 0\nhigh = 100\nans = int((high + low)/2)\n\nprint \"Please think of a number between 0 and 100!\"\nwhile ans != 'c':\n #print high, low\n print \"Is your secret number \" + str(ans) + \"?\",\n number = raw_input(\"Enter 'h' to indic... | true |
6,429 | 819607d89035413fc2800e9f16222619a74a5d64 | from functools import wraps
import maya.cmds as mc
import maya.mel as mel
import pymel.core as pm
from PySide2 import QtCore, QtGui, QtWidgets
import adb_core.Class__multi_skin as ms
import adbrower
from CollDict import pysideColorDic as pyQtDic
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
import a... | [
"from functools import wraps\n\nimport maya.cmds as mc\nimport maya.mel as mel\nimport pymel.core as pm\nfrom PySide2 import QtCore, QtGui, QtWidgets\n\nimport adb_core.Class__multi_skin as ms\nimport adbrower\nfrom CollDict import pysideColorDic as pyQtDic\nfrom maya.app.general.mayaMixin import MayaQWidgetDockabl... | false |
6,430 | 9761070a75b043f6cc9e6134e09810b215ccd0c0 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 可写函数说明
def sum(arg1, arg2):
# 返回2个参数的和."
total = arg1 + arg2
print "函数内 : ", total
return total;
# 调用sum函数
total = sum(10, 20);
def nop():
pass
a = nop(); | [
"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# 可写函数说明\ndef sum(arg1, arg2):\n # 返回2个参数的和.\"\n total = arg1 + arg2\n print \"函数内 : \", total\n return total;\n\n\n# 调用sum函数\ntotal = sum(10, 20);\n\ndef nop():\n pass\n\na = nop();"
] | true |
6,431 | 150603004a4b194a7c08f1f23e37c613aa3b883a | import Utility
import copy
class Ratio_Execution_Time:
utility = None
def __init__(self):
self.utility = Utility.Utility()
print("Successfully Found Ration Corrssponding to Execution Time")
def calculatePercentage(self,B,total,strr):
E = {}
for i in B:
... | [
"import Utility\nimport copy\n\nclass Ratio_Execution_Time:\n utility = None\n\n def __init__(self):\n\n self.utility = Utility.Utility() \n print(\"Successfully Found Ration Corrssponding to Execution Time\")\n\n def calculatePercentage(self,B,total,strr):\n \n E = {}\n\n ... | false |
6,432 | aeb986360c6990f9375f2552cbdeef595af815b4 | import numpy as np
np.random.seed(1)
class MonteCarloGameDriver():
def __init__(self):
self.default_moves = np.array(['w','a','s','d'])
self.probability_distribution = np.array([.25,.25,.25,.25])
def run_game(self, simulation_size=20):
from game import GameLayout
from copy ... | [
"import numpy as np\nnp.random.seed(1)\n\nclass MonteCarloGameDriver(): \n def __init__(self):\n self.default_moves = np.array(['w','a','s','d'])\n self.probability_distribution = np.array([.25,.25,.25,.25])\n\n def run_game(self, simulation_size=20):\n from game import GameLayout\n ... | false |
6,433 | 347bfb2d8809b55046f698620a690099cc83fb56 | import sys
import vector
import matrix
def convert_arg_to_list(arg):
try:
return [float(elem) for elem in arg]
except:
sys.exit("Invalid content inside {}".format(arg))
if __name__ == "__main__":
try:
vector1 = sys.argv[1].split(' ')
vector2 = sys.argv[2].split(' ')
exc... | [
"import sys\nimport vector\nimport matrix\n\ndef convert_arg_to_list(arg):\n try:\n return [float(elem) for elem in arg]\n except:\n sys.exit(\"Invalid content inside {}\".format(arg))\n\nif __name__ == \"__main__\":\n try:\n vector1 = sys.argv[1].split(' ')\n vector2 = sys.argv... | false |
6,434 | 7b047ba110732d1b0a749bcbbaa9b55306ca2071 | # --- Do not remove these libs ---
from freqtrade.strategy.interface import IStrategy
from typing import Dict, List
from functools import reduce
from pandas import DataFrame
# --------------------------------
import datetime
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
import numpy... | [
"# --- Do not remove these libs ---\nfrom freqtrade.strategy.interface import IStrategy\nfrom typing import Dict, List\nfrom functools import reduce\nfrom pandas import DataFrame\n# --------------------------------\n\nimport datetime\nimport talib.abstract as ta\nimport freqtrade.vendor.qtpylib.indicators as qtpyli... | false |
6,435 | 326b2dcbef339aeb196bef23debad75fa079b121 | import string
import pandas as pd
import nltk
from nltk import word_tokenize
from nltk.stem import SnowballStemmer
from nltk.tokenize import WordPunctTokenizer
import json
from sklearn.model_selection import train_test_split
from keras.preprocessing.text import Tokenizer
import pickle
import re
import nlpaug.augmenter.... | [
"import string\nimport pandas as pd\nimport nltk\nfrom nltk import word_tokenize\nfrom nltk.stem import SnowballStemmer\nfrom nltk.tokenize import WordPunctTokenizer\nimport json\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing.text import Tokenizer\nimport pickle\nimport re\nimport n... | false |
6,436 | b2944a95dbe25057155aaf6198a97d85b3bb620b | from typing import Dict, Tuple
import torch
from tqdm import tqdm
import schnetpack.properties as structure
from schnetpack.data import AtomsLoader
__all__ = ["calculate_stats"]
def calculate_stats(
dataloader: AtomsLoader,
divide_by_atoms: Dict[str, bool],
atomref: Dict[str, torch.Tensor] = None,
) ->... | [
"from typing import Dict, Tuple\n\nimport torch\nfrom tqdm import tqdm\n\nimport schnetpack.properties as structure\nfrom schnetpack.data import AtomsLoader\n\n__all__ = [\"calculate_stats\"]\n\n\ndef calculate_stats(\n dataloader: AtomsLoader,\n divide_by_atoms: Dict[str, bool],\n atomref: Dict[str, torch... | false |
6,437 | b7d7b6c070f237f9ab59f3367417ecf2672fbaaf | """
Copyright (c) 2017- Sinergise and contributors
For the full list of contributors, see the CREDITS file in the root directory of this source tree.
This source code is licensed under the MIT license, see the LICENSE file in the root directory of this source tree.
"""
import numpy as np
import pytest
from numpy.test... | [
"\"\"\"\nCopyright (c) 2017- Sinergise and contributors\nFor the full list of contributors, see the CREDITS file in the root directory of this source tree.\n\nThis source code is licensed under the MIT license, see the LICENSE file in the root directory of this source tree.\n\"\"\"\n\nimport numpy as np\nimport pyt... | false |
6,438 | 66474b8cdca9a4aa48b8dc710d161a3a16495aed | import numpy as np
count = 0 # счетчик попыток
number = np.random.randint(1, 101) # загадали число
print("Загадано число от 1 до 100")
def game_core_v3(number):
'''Сначала устанавливаем любое random число, а потом уменьшаем или увеличиваем его в зависимости от того, больше оно или меньше нужного.
Функция... | [
"import numpy as np\n\ncount = 0 # счетчик попыток\nnumber = np.random.randint(1, 101) # загадали число\nprint(\"Загадано число от 1 до 100\")\n\ndef game_core_v3(number):\n '''Сначала устанавливаем любое random число, а потом уменьшаем или увеличиваем его в зависимости от того, больше оно или меньше нужного.\... | false |
6,439 | 5a9e0b220d2c94aea7e3d67338771cf48c3aec8f | import os
import io
import yaml
from collections import OrderedDict
from rich.console import Console
from malwarebazaar.platform import get_config_path, get_config_dir
class Config(OrderedDict):
instance = None
def __init__(self):
ec = Console(stderr=True, style="bold red")
Config.ensure_pa... | [
"import os\nimport io\nimport yaml\nfrom collections import OrderedDict\n\nfrom rich.console import Console\n\nfrom malwarebazaar.platform import get_config_path, get_config_dir\n\n\nclass Config(OrderedDict):\n instance = None\n\n def __init__(self):\n ec = Console(stderr=True, style=\"bold red\")\n ... | false |
6,440 | c955057d7f8d5289898ecb96a290f5a7d241b787 | import pandas as pd
import matplotlib.pyplot as plt
import math
import seaborn as sns
import numpy as np
suv_data=pd.read_csv("F:/Development/Machine Learning/suv-data/suv_data.csv")
print(suv_data.head(10))
print("the no of passengers in the list is"+str(len(suv_data.index)))
sns.countplot(x="Purchased",data=suv_data... | [
"import pandas as pd\nimport matplotlib.pyplot as plt \nimport math\nimport seaborn as sns\nimport numpy as np\nsuv_data=pd.read_csv(\"F:/Development/Machine Learning/suv-data/suv_data.csv\")\nprint(suv_data.head(10))\nprint(\"the no of passengers in the list is\"+str(len(suv_data.index)))\nsns.countplot(x=\"Purcha... | false |
6,441 | 983473129bfd56138a615e0f5bdb1353e9c6d8af | import abc
import numpy as np
import ray
from tqdm.autonotebook import tqdm
from src.algorithm.info_theory.it_estimator import (CachingEstimator,
MPCachingEstimator)
from src.algorithm.utils import differ, independent_roll, union
class FeatureSelector(metaclass=ab... | [
"import abc\n\nimport numpy as np\nimport ray\nfrom tqdm.autonotebook import tqdm\n\nfrom src.algorithm.info_theory.it_estimator import (CachingEstimator,\n MPCachingEstimator)\nfrom src.algorithm.utils import differ, independent_roll, union\n\n\nclass FeatureSelec... | false |
6,442 | 8b9336113f64a88eeabe6e45021938fac9efd1c6 | class Vehicle(object):
count_list = []
def __init__(self, registration_number):
self.registration_number = registration_number
Vehicle.count_list.append(self)
Vehicle.count = len(Vehicle.count_list) | [
"class Vehicle(object):\n\n count_list = []\n \n def __init__(self, registration_number):\n self.registration_number = registration_number\n Vehicle.count_list.append(self)\n Vehicle.count = len(Vehicle.count_list)",
"class Vehicle(object):\n count_list = []\n\n def __init__(se... | false |
6,443 | 23d4619527b5fce7fed0b0a66d834e26bb984129 | import hive
from ..bind import Instantiator as _Instantiator
from ..event import bind_info as event_bind_info
bind_infos = (event_bind_info,)
def build_scene_instantiator(i, ex, args, meta_args):
bind_bases = tuple((b_i.environment_hive for b_i in bind_infos if b_i.is_enabled(meta_args)))
# Update bind env... | [
"import hive\n\nfrom ..bind import Instantiator as _Instantiator\nfrom ..event import bind_info as event_bind_info\n\nbind_infos = (event_bind_info,)\n\n\ndef build_scene_instantiator(i, ex, args, meta_args):\n bind_bases = tuple((b_i.environment_hive for b_i in bind_infos if b_i.is_enabled(meta_args)))\n\n #... | false |
6,444 | 61135a10adefd6ba8ffd63e997fa91ce9c78de06 | from setuptools import setup
setup(name = "dragonfab",
version = "1.3.0",
description = "Fabric support",
author = "Joel Pitt",
author_email = "joel@joelpitt.com",
url = "https://github.com/ferrouswheel/dragonfab",
install_requires = ['fabric', 'pip>=1.4', 'wheel'],
packages = ['dragonfab']... | [
"from setuptools import setup\n\nsetup(name = \"dragonfab\",\n version = \"1.3.0\",\n description = \"Fabric support\",\n author = \"Joel Pitt\",\n author_email = \"joel@joelpitt.com\",\n url = \"https://github.com/ferrouswheel/dragonfab\",\n install_requires = ['fabric', 'pip>=1.4', 'wheel'],\n ... | false |
6,445 | 3cca7408eb88f91f295c581c29d3d1e95298f337 | r""" 测试dispatch
>>> from url_router.map import Map
>>> from url_router.rule import Rule
>>> m = Map([
... Rule('/', endpoint='index'),
... Rule('/foo', endpoint='foo'),
... Rule('/bar/', endpoint='bar'),
... Rule('/any/<name>', endpoint='any'),
... Rule('/string/<string:name>', endpoint='string'),
... | [
"r\"\"\" 测试dispatch\n\n>>> from url_router.map import Map\n>>> from url_router.rule import Rule\n>>> m = Map([\n... Rule('/', endpoint='index'),\n... Rule('/foo', endpoint='foo'),\n... Rule('/bar/', endpoint='bar'),\n... Rule('/any/<name>', endpoint='any'),\n... Rule('/string/<string:name>', end... | false |
6,446 | 47025a30d79341ff0819fe87638e35960a5fc87d | from typing import Union
from django.db.models import Q, Value
from django.db.models.functions import Lower, Replace, Trim
from .normalization import (
normalize_doi,
normalize_funkcja_autora,
normalize_grupa_pracownicza,
normalize_isbn,
normalize_kod_dyscypliny,
normalize_nazwa_dyscypliny,
... | [
"from typing import Union\n\nfrom django.db.models import Q, Value\nfrom django.db.models.functions import Lower, Replace, Trim\n\nfrom .normalization import (\n normalize_doi,\n normalize_funkcja_autora,\n normalize_grupa_pracownicza,\n normalize_isbn,\n normalize_kod_dyscypliny,\n normalize_nazw... | false |
6,447 | bd06030ace665a0686c894a863e5c779b6d0931c | # -*- coding: utf-8 -*-
"""Chatbot learning
학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다.
"""
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers, losses, metrics
from tensorflow.keras import preprocessing
import numpy as np
import pa... | [
"# -*- coding: utf-8 -*-\n\"\"\"Chatbot learning\n학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다.\n\"\"\"\n\n\n\nfrom tensorflow.keras import models\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import optimizers, losses, metrics\nfrom tensorflow.keras import preprocessing\n\nimpor... | false |
6,448 | 2500c3562819e4e85ce3cbc30e0ddf1b8437e0a2 | from django.contrib import admin
from lesson.models import ProgrammingEnvironment, Language, Lesson, LessonHint
# list_display - Show these fields for each model on the Admin site
# search_fields - Allow searching in these fields
# Register models for the Admin site
class ProgrammingEnvironmentAdmin(admin.ModelAdmin)... | [
"from django.contrib import admin\nfrom lesson.models import ProgrammingEnvironment, Language, Lesson, LessonHint\n\n# list_display - Show these fields for each model on the Admin site\n# search_fields - Allow searching in these fields\n\n# Register models for the Admin site\nclass ProgrammingEnvironmentAdmin(admin... | false |
6,449 | 9a54ff8e7e8d6d46860cb6173f03c52655b30f43 | TheBeatles = ['John', 'Paul', 'George', 'Ringo']
Wings = ['Paul']
for Beatle in TheBeatles:
if Beatle in Wings:
continue
print Beatle
| [
"TheBeatles = ['John', 'Paul', 'George', 'Ringo']\nWings = ['Paul']\n\nfor Beatle in TheBeatles:\n\t\tif Beatle in Wings:\n\t\t\t\tcontinue\n\t\tprint Beatle\n\n"
] | true |
6,450 | 8c8b5c1ff749a8563788b8d5be5332e273275be3 | # Standard library
# Third party library
# Local library
from warehouse.server import run_server
from warehouse.server.config import log
if __name__ == "__main__":
log.initialize_logs()
run_server()
| [
"# Standard library\n# Third party library\n# Local library\nfrom warehouse.server import run_server\nfrom warehouse.server.config import log\n\n\nif __name__ == \"__main__\":\n log.initialize_logs()\n run_server()\n",
"from warehouse.server import run_server\nfrom warehouse.server.config import log\nif __n... | false |
6,451 | 64cf6b03fb68be8a23c6e87c8d68d0a42db0eb54 | #!/usr/bin/env python3
# coding=utf-8
# title :paramiko_sftp.py
# description :
# author :JackieTsui
# organization :pytoday.org
# date :1/16/18 9:22 PM
# email :jackietsui72@gmail.com
# notes :
# ==================================================
# Import the module n... | [
"#!/usr/bin/env python3\n# coding=utf-8\n# title :paramiko_sftp.py\n# description :\n# author :JackieTsui\n# organization :pytoday.org\n# date :1/16/18 9:22 PM\n# email :jackietsui72@gmail.com\n# notes :\n# ==================================================\n\n# Imp... | false |
6,452 | 1aca1cf11d64374d0e0786e74c16567a4c5a1dec | class Queue:
def __init__(self):
self.head = None
self.tail = None
class Node:
def __init__(self, data):
self.data = data
self.next = None
def isEmpty(self):
return self.head is None
def peek(self):
return self.head.data if self.head i... | [
"class Queue:\n def __init__(self):\n self.head = None\n self.tail = None\n \n class Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n def isEmpty(self):\n return self.head is None\n def peek(self):\n return self.head.da... | false |
6,453 | 7626202d1e3ec7321addbb028be2275b882efda2 | """
Unit Tests for endpoints.py
"""
import unittest
import os # pylint: disable=unused-import
from mock import patch, call
from github_approval_checker.utils import util # pylint: disable=unused-import
from github_approval_checker.utils.github_handler import GithubHandler # pylint: disable=unused-import
from github... | [
"\"\"\"\nUnit Tests for endpoints.py\n\"\"\"\n\nimport unittest\nimport os # pylint: disable=unused-import\nfrom mock import patch, call\nfrom github_approval_checker.utils import util # pylint: disable=unused-import\nfrom github_approval_checker.utils.github_handler import GithubHandler # pylint: disable=unused... | false |
6,454 | 66fe0a3b84773ee1d4f91d8fde60f1fc5b3d7e4c | import pickle
import numpy as np
import torch
import time
import torchvision
import matplotlib
import matplotlib.pyplot as plt
def load_cifar_data(data_files):
data = []
labels = []
for file in data_files:
with open(file, 'rb') as fo:
data_dict = pickle.load(fo, encoding='bytes')
... | [
"import pickle\nimport numpy as np\nimport torch\nimport time\nimport torchvision\nimport matplotlib\nimport matplotlib.pyplot as plt\n\ndef load_cifar_data(data_files):\n data = []\n labels = []\n for file in data_files:\n with open(file, 'rb') as fo:\n data_dict = pickle.load(fo, encodi... | false |
6,455 | d78fd8ebf9ef55700a25a9ce96d9094f1bfa564e | def main():
piso = largura * comprimento
volume_sala = largura * comprimento * altura
area = 2 * altura * largura + 2 * altura * comprimento
print(piso)
print(volume_sala)
print(area)
altura = float(input(""))
largura = float(input(""))
comprimento = float(input(""))
if __name__ == '__main__':... | [
"def main():\n piso = largura * comprimento\n volume_sala = largura * comprimento * altura\n area = 2 * altura * largura + 2 * altura * comprimento\n print(piso)\n print(volume_sala)\n print(area)\n\naltura = float(input(\"\"))\nlargura = float(input(\"\"))\ncomprimento = float(input(\"\"))\n\nif ... | false |
6,456 | 42c9e5039e2d5f784bf6405ea8bcaf7d6973ddcb | from mayan.apps.testing.tests.base import BaseTestCase
from .mixins import AssetTestMixin
class AssetModelTestCase(
AssetTestMixin, BaseTestCase
):
def test_asset_get_absolute_url_method(self):
self._create_test_asset()
self.test_asset.get_absolute_url()
| [
"from mayan.apps.testing.tests.base import BaseTestCase\n\nfrom .mixins import AssetTestMixin\n\n\nclass AssetModelTestCase(\n AssetTestMixin, BaseTestCase\n):\n def test_asset_get_absolute_url_method(self):\n self._create_test_asset()\n\n self.test_asset.get_absolute_url()\n",
"from mayan.app... | false |
6,457 | 2420c835ff91c1269cb16fca2e60e191e1e8ce13 | #!/usr/bin/env python
#-*- coding : utf-8 -*-
import string
import keyword
alphas = string.letters + '_'
nums = string.digits
keywords = keyword.kwlist
checklst = alphas + nums
print 'Welcome to the Identifier Checker v1.0'
myInput = raw_input('Identifier to test? ')
if myInput in keywords:
print 'Okay as a keywor... | [
"#!/usr/bin/env python\n#-*- coding : utf-8 -*-\n\nimport string\nimport keyword\n\nalphas = string.letters + '_'\nnums = string.digits\nkeywords = keyword.kwlist\nchecklst = alphas + nums\n\nprint 'Welcome to the Identifier Checker v1.0'\nmyInput = raw_input('Identifier to test? ')\n\nif myInput in keywords:\n\tpr... | true |
6,458 | a245cb1f232b152edf40b6399686c6811c522d99 | # common methods to delete data from list
fruits = ['orange', ' apple', 'pear', 'banana', 'kiwi']
#pop method
# fruits.pop(1)
# del
# del fruits[1]
# remove
# fruits.remove('banana')
# append, extend, insert
# pop, remove, del
print(fruits)
| [
"# common methods to delete data from list\r\nfruits = ['orange', ' apple', 'pear', 'banana', 'kiwi']\r\n#pop method\r\n# fruits.pop(1)\r\n\r\n\r\n# del\r\n# del fruits[1]\r\n\r\n# remove\r\n\r\n# fruits.remove('banana')\r\n\r\n# append, extend, insert\r\n# pop, remove, del\r\n\r\nprint(fruits)\r\n\r\n\r\n",
"fru... | false |
6,459 | 42d2be7544d2afb9580841422ae35e1a5621df52 | import abc
import math
import random
from typing import Union, Tuple
import numpy as np
from scipy import stats
from . import Rectangle, Line, Point, Shape
__all__ = ['get_critical_angle', 'Paddle', 'Ball', 'Snell', 'Canvas']
EPSILON = 1e-7
def get_critical_angle(s0: float, s1: float) -> Union[float, None]:
"... | [
"import abc\nimport math\nimport random\nfrom typing import Union, Tuple\n\nimport numpy as np\nfrom scipy import stats\n\nfrom . import Rectangle, Line, Point, Shape\n\n__all__ = ['get_critical_angle', 'Paddle', 'Ball', 'Snell', 'Canvas']\n\nEPSILON = 1e-7\n\n\ndef get_critical_angle(s0: float, s1: float) -> Union... | false |
6,460 | 79141679bb2839de9d4a25b6c6c285905dddbb0d | #!/usr/bin/python
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
setup(
name="isc-dhcpd-parser",
version="0.1",
description="Parser for isc-dhcp config files (dhcpd.conf)",
author="Pavel Podkorytov",
author_email="pod.pavel@gmail.com",
classifiers=[
... | [
"#!/usr/bin/python\n\n# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n\nsetup(\n name=\"isc-dhcpd-parser\",\n version=\"0.1\",\n description=\"Parser for isc-dhcp config files (dhcpd.conf)\",\n author=\"Pavel Podkorytov\",\n author_email=\"pod.pavel@gmail.com\"... | false |
6,461 | 536a67935527eb99bc0424613c9b931401db0b06 | from rest_framework import serializers
from .models import Twit, Comment, Message
from django.contrib.auth.models import User
class TwitSerializer(serializers.ModelSerializer):
class Meta:
model = Twit
fields = '__all__'
class CommentSerializer(serializers.ModelSerializer):
class Meta:
... | [
"from rest_framework import serializers\nfrom .models import Twit, Comment, Message\nfrom django.contrib.auth.models import User\n\nclass TwitSerializer(serializers.ModelSerializer):\n class Meta:\n model = Twit\n fields = '__all__'\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n cl... | false |
6,462 | 397686964acbf640a5463a3a7095d85832545d9e | import re
def detectPeriod(data):
numWord = "[0-9,一二三四五六七八九十兩半]"
hourWord = "小時鐘頭"
minWord = "分鐘"
secWord = "秒鐘"
timePat = "["+numWord+"]+點?\.?["+numWord+"]*個?半?["+hourWord+"]*半?又?["+numWord+"]*["+minWord+"]*又?["+numWord+"]*["+secWord+"]*"
def main():
detectPeriod("我要去游泳一個小時")
if _... | [
"import re\n\n\ndef detectPeriod(data):\n \n numWord = \"[0-9,一二三四五六七八九十兩半]\"\n hourWord = \"小時鐘頭\"\n minWord = \"分鐘\"\n secWord = \"秒鐘\"\n\n\n timePat = \"[\"+numWord+\"]+點?\\.?[\"+numWord+\"]*個?半?[\"+hourWord+\"]*半?又?[\"+numWord+\"]*[\"+minWord+\"]*又?[\"+numWord+\"]*[\"+secWord+\"]*\"\n\n\n\n\nd... | false |
6,463 | 658532e1b81b025b8295bbf468dc01ecf12b922a | from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.stem import SnowballStemmer
import pandas as pd
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.tex... | [
"from nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem import SnowballStemmer\nimport pandas as pd\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_ex... | false |
6,464 | 501ca508df5d72b0190b933f07c4bd505d7090c0 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from contextlib import contextmanager
import yaml
from omegaconf import OmegaConf
class CrypTenConfig:
... | [
"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport os\nfrom contextlib import contextmanager\n\nimport yaml\nfrom omegaconf import OmegaConf\n\n\nclas... | false |
6,465 | 78615f6b020e2547e5d9a08d8b4c414184106bb3 | import pandas as pd
import time
from datetime import datetime
from sklearn import metrics
from sklearn import cross_validation
from sklearn.multiclass import OneVsRestClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.naive_bayes import MultinomialNB,BernoulliNB,GaussianNB
... | [
"import pandas as pd\r\nimport time\r\nfrom datetime import datetime\r\nfrom sklearn import metrics\r\nfrom sklearn import cross_validation\r\nfrom sklearn.multiclass import OneVsRestClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\r\nfrom sklearn.naive_bayes import MultinomialNB,Berno... | true |
6,466 | 6ea651e27620d0f26f7364e6d9d57e733b158d77 | import iris
import numpy as np
import matplotlib.pyplot as plt
import glob
import iris.analysis.cartography
import iris.coord_categorisation
import iris.analysis
import time
def my_callback(cube, field, filename):
cube.remove_coord('forecast_reference_time')
cube.remove_coord('forecast_period')
... | [
"import iris\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nimport iris.analysis.cartography\nimport iris.coord_categorisation\nimport iris.analysis\nimport time\n\ndef my_callback(cube, field, filename):\n cube.remove_coord('forecast_reference_time')\n cube.remove_coord('forecast_... | true |
6,467 | 60c862accbb9cda40ed4c45491f643f065e2868a | #!/usr/bin/env python
import os
from distutils.core import setup, Extension
import distutils.util
setup (name = 'pybanery',
version= '1.0',
description='Python interface for Kanbanery',
author = 'Pablo Lluch',
author_email = 'pablo.lluch@gmail.com',
py_modules = ['pybanery'],
... | [
"#!/usr/bin/env python\n\nimport os\nfrom distutils.core import setup, Extension\nimport distutils.util\n\nsetup (name = 'pybanery',\n version= '1.0',\n description='Python interface for Kanbanery',\n author = 'Pablo Lluch',\n author_email = 'pablo.lluch@gmail.com',\n py_modules = ['py... | false |
6,468 | 807b20f4912ab89bf73966961536a4cd4367f851 | # Generated by Django 3.0.1 on 2020-03-20 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('page', '0004_auto_20200320_1521'),
]
operations = [
migrations.AddField(
model_name='menu',
name='level',
... | [
"# Generated by Django 3.0.1 on 2020-03-20 09:59\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('page', '0004_auto_20200320_1521'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='menu',\n name=... | false |
6,469 | a0349abb3a56ff4bc1700dbf0fa5a1fc2e3453ce | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class FlaskConfig(object):
SECRET_KEY = os.environ.get('FLASK_SECRET_KEY') or 'TuLAsWbcoKr5YhDE'
BOOTSTRAP_SERVE_LOCAL = os.environ.get('FLASK_BOOTSTRAP_SERVE_LOCAL') or True
APPLICATION_ROOT = os.environ.get('FLASK_APPLICATION_ROOT') or ''
... | [
"import os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nclass FlaskConfig(object):\n SECRET_KEY = os.environ.get('FLASK_SECRET_KEY') or 'TuLAsWbcoKr5YhDE'\n BOOTSTRAP_SERVE_LOCAL = os.environ.get('FLASK_BOOTSTRAP_SERVE_LOCAL') or True\n APPLICATION_ROOT = os.environ.get('FLASK_APPLICATION_ROO... | false |
6,470 | cdaceb2d8804e08f0b35b9b65f2d06695efad002 | # Generated by Django 3.1.7 on 2021-03-28 01:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('details', '0002_auto_20210310_1421'),
]
operations = [
migrations.AlterModelOptions(
name='detail',
options={'get_latest_by'... | [
"# Generated by Django 3.1.7 on 2021-03-28 01:03\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('details', '0002_auto_20210310_1421'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='detail',\n optio... | false |
6,471 | dc934f8db4e0c1113e1398b051b58369d909fff8 | from collections import deque
class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
def board2str(board: List[List[int]]) -> str:
return ''.join([str(board[i][j]) for i in range(2) for j in range(3)])
start = board2str(board)
bfs = deque([(start, 0)])
... | [
"from collections import deque\n\n\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n def board2str(board: List[List[int]]) -> str:\n return ''.join([str(board[i][j]) for i in range(2) for j in range(3)])\n\n start = board2str(board)\n bfs = deque([(start... | false |
6,472 | 80d1979c5767d0ff90f464651c9d0ca6d65effb2 | def foo(x, y=5):
def bar(x):
return x + 1
return bar(y * 2)
print(foo(3)) | [
"def foo(x, y=5):\n def bar(x):\n return x + 1\n\n return bar(y * 2)\n\n\nprint(foo(3))",
"def foo(x, y=5):\n\n def bar(x):\n return x + 1\n return bar(y * 2)\n\n\nprint(foo(3))\n",
"def foo(x, y=5):\n\n def bar(x):\n return x + 1\n return bar(y * 2)\n\n\n<code token>\n",
... | false |
6,473 | 2d69a39be3931aa4c62cadff4cdfad76f6b32c59 | import face_recognition
from glob import glob
import os.path as osp
class FaceRecognitionLib(object):
"""
face_recognition library を利用した顔認証検証
"""
# クラス変数設定
__data_set_dir = './../../dataset/japanese' # データ・セットディレクトリ
__known_image_idx = (1,) # 既存画像のインデックス
... | [
"import face_recognition\r\nfrom glob import glob\r\nimport os.path as osp\r\n\r\n\r\nclass FaceRecognitionLib(object):\r\n \"\"\"\r\n face_recognition library を利用した顔認証検証\r\n \"\"\"\r\n # クラス変数設定\r\n __data_set_dir = './../../dataset/japanese' # データ・セットディレクトリ\r\n __known_image_idx = (1,) ... | false |
6,474 | 8f01934472805b5ad6dca328483a7ac79ae7748a | #This version assumes domains = train/test set
import numpy as np
from ..utils import Dataset
import math
import random
from .interface import TopicModel
from .man_model.models import *
from .man_model import utils
from .man_model.options import opt
import torch.utils.data as data_utils
from tqdm import tqdm
from colle... | [
"#This version assumes domains = train/test set\nimport numpy as np\nfrom ..utils import Dataset\nimport math\nimport random\nfrom .interface import TopicModel\nfrom .man_model.models import *\nfrom .man_model import utils\nfrom .man_model.options import opt\nimport torch.utils.data as data_utils\nfrom tqdm import ... | false |
6,475 | dab53d10958b36cf75ab53bf30f744b1ed8a09b6 | from .authenticators import CookieAuthenticator, HeaderAuthenticator
from .paginators import LimitOffsetPaginator, PageNumberPaginator
from .views import * # pylint:disable=W0401
| [
"from .authenticators import CookieAuthenticator, HeaderAuthenticator\nfrom .paginators import LimitOffsetPaginator, PageNumberPaginator\nfrom .views import * # pylint:disable=W0401\n",
"from .authenticators import CookieAuthenticator, HeaderAuthenticator\nfrom .paginators import LimitOffsetPaginator, PageNumber... | false |
6,476 | f39130099ccf467623d65ac328fd02538044d36a | import copy
import datetime
from sacred import Experiment
from tqdm import tqdm
from mms_msg.databases.classical.full_overlap import WSJ2Mix
import paderbox as pb
import padertorch as pt
ex = Experiment('mixture_generator_create_json')
@ex.config
def defaults():
json_path = 'database.json'
database = {
... | [
"import copy\nimport datetime\n\nfrom sacred import Experiment\nfrom tqdm import tqdm\n\nfrom mms_msg.databases.classical.full_overlap import WSJ2Mix\nimport paderbox as pb\nimport padertorch as pt\n\nex = Experiment('mixture_generator_create_json')\n\n\n@ex.config\ndef defaults():\n json_path = 'database.json'\... | false |
6,477 | 32066db8b43bc70c564cce5a33f50921285b3627 | #!/usr/bin/env python3
# coding: utf-8
# Time complexity: O()
# Space complexity: O()
import math
# 最大公约数 Greatest common divisor
def get_gcd(a, b):
if b == 0:
return a
print(a, b)
return get_gcd(b, a % b)
get_gcd(48, 30)
# 计算约数个数
# 时间复杂度 O(n)
def divisor1(num):
count = 0
for i in ran... | [
"#!/usr/bin/env python3\n# coding: utf-8\n\n# Time complexity: O()\n# Space complexity: O()\n\nimport math\n\n# 最大公约数 Greatest common divisor\ndef get_gcd(a, b):\n if b == 0:\n return a\n print(a, b)\n return get_gcd(b, a % b)\n\nget_gcd(48, 30)\n\n# 计算约数个数\n# 时间复杂度 O(n)\ndef divisor1(num):\n c... | false |
6,478 | 9b94e8aed2b0be2771a38cf2d1cf391772f3a9f0 | class SimulatorInfo(object):
def __init__(self, name=None, device_type=None, sdk=None, device_id=None, sim_id=None):
self.name = name
self.device_type = device_type
self.sdk = sdk
self.device_id = device_id
self.sim_id = sim_id
| [
"class SimulatorInfo(object):\n def __init__(self, name=None, device_type=None, sdk=None, device_id=None, sim_id=None):\n self.name = name\n self.device_type = device_type\n self.sdk = sdk\n self.device_id = device_id\n self.sim_id = sim_id\n",
"class SimulatorInfo(object):\n... | false |
6,479 | b48bc9475a8dc593ba858af8ed4e930ae290fd69 | from discord.ext import commands
import discord
import os
import random
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name}")
@bot.command()
async def ping(ctx):
await ctx.send("pong")
# Lucky command, it picks a number between 0-50 and spams your dm'... | [
"from discord.ext import commands\nimport discord\nimport os\nimport random\n\nbot = commands.Bot(command_prefix=\"!\")\n\n@bot.event\nasync def on_ready():\n print(f\"Logged in as {bot.user.name}\")\n\n\n@bot.command()\nasync def ping(ctx):\n await ctx.send(\"pong\")\n\n\n# Lucky command, it picks a number bet... | false |
6,480 | b99093fb13c59d4b9bb0a4f32fb62423d6752118 | # Generated by Django 3.0.8 on 2020-07-29 18:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('scenario', '0005_auto_20200729_1149'),
]
operations = [
migrations.RemoveField(
model_name='weapon',
name='vehicle',
... | [
"# Generated by Django 3.0.8 on 2020-07-29 18:30\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('scenario', '0005_auto_20200729_1149'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='weapon',\n name... | false |
6,481 | 8425ee79fcb41799e5edbbab822f93dd40e39d8e | from collections import defaultdict
class Solution:
def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
output = [[0 for j in range(len(B[0]))] for i in range(len(A))]
rows = defaultdict(list)
cols = defaultdict(list)
for i in ran... | [
"from collections import defaultdict\nclass Solution:\n def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \n output = [[0 for j in range(len(B[0]))] for i in range(len(A))]\n \n rows = defaultdict(list)\n cols = defaultdict(list)\n \n ... | false |
6,482 | e1cc4e17bffcbbae3e7785e4c55acde167a8a50a | import os
import RPi.GPIO as GPIO
from google.cloud import firestore
import time
############Explicit Credential environment
path="/home/pi/Desktop/Parking.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] =path
#GPIO starts
s1=2
s2=21
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(s1,GPIO.IN)
GPIO.... | [
"import os\nimport RPi.GPIO as GPIO\nfrom google.cloud import firestore\nimport time \n\n############Explicit Credential environment\npath=\"/home/pi/Desktop/Parking.json\"\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] =path\n\n#GPIO starts\ns1=2\ns2=21\nGPIO.setmode(GPIO.BCM) \nGPIO.setwarnings(False)\nGPIO.se... | false |
6,483 | 3153218fe1d67fdc1c1957ffcfdb380688c159c1 | from django.apps import AppConfig
class AutomationserverConfig(AppConfig):
name = 'automationserver'
| [
"from django.apps import AppConfig\n\n\nclass AutomationserverConfig(AppConfig):\n name = 'automationserver'\n",
"<import token>\n\n\nclass AutomationserverConfig(AppConfig):\n name = 'automationserver'\n",
"<import token>\n\n\nclass AutomationserverConfig(AppConfig):\n <assignment token>\n",
"<impor... | false |
6,484 | 70845ab4aab80d988a5c01d0b4fb76e63b800527 | import sys
byte = int(sys.argv[1])
qlty = float(sys.argv[2])
n = 0
while True:
o = sys.stdin.read(byte)
if qlty>(qlty*n)%1:
oo = o
sys.stdout.write(o)
else:
sys.stdout.write(oo)
if not o:
break
n=n+1 | [
"import sys\r\nbyte = int(sys.argv[1])\r\nqlty = float(sys.argv[2])\r\nn = 0\r\nwhile True:\r\n o = sys.stdin.read(byte)\r\n if qlty>(qlty*n)%1:\r\n oo = o\r\n sys.stdout.write(o)\r\n else:\r\n sys.stdout.write(oo)\r\n if not o:\r\n break\r\n n=n+1",
"import sys\nbyte = int(sys.argv[1])\nqlty = float(sys.argv... | false |
6,485 | 9f8fbfb8a9c849ca0e8881c479800c8e190e4a1c | import json
from logger import logger
def parse_json(text):
start = text.find("{")
end = text.find("}") + 1
try:
data = json.loads(text[start:end])
return data
except Exception:
logger.error("json解析失败:%s" % text)
| [
"import json\nfrom logger import logger\n\n\ndef parse_json(text):\n start = text.find(\"{\")\n end = text.find(\"}\") + 1\n try:\n data = json.loads(text[start:end])\n return data\n except Exception:\n logger.error(\"json解析失败:%s\" % text)\n",
"import json\nfrom logger import logg... | false |
6,486 | 0aad96de65cc125e5c026dfd72a9cc9f4ebd3dd2 | from nose.tools import with_setup, nottest
from tests.par_test_base import ParTestBase
from ProbPy import RandVar, Factor, ParFactor
class TestFactorMult(ParTestBase):
def __init__(self):
super().__init__()
def par_test_0(self):
"""
f(X), scalar
"""
for i in range(4)... | [
"from nose.tools import with_setup, nottest\n\nfrom tests.par_test_base import ParTestBase\nfrom ProbPy import RandVar, Factor, ParFactor\n\n\nclass TestFactorMult(ParTestBase):\n def __init__(self):\n super().__init__()\n\n def par_test_0(self):\n \"\"\"\n f(X), scalar\n \"\"\"\n\... | false |
6,487 | 22bf65a20f7398b82f528112d2ba50f1dccd465c |
class Thing3:
def __init__(self):
self.letters = 'xyz'
# print(Thing3.letters)
th = Thing3()
print(th.letters) | [
"\nclass Thing3:\n def __init__(self):\n self.letters = 'xyz'\n\n# print(Thing3.letters)\nth = Thing3()\nprint(th.letters)",
"class Thing3:\n\n def __init__(self):\n self.letters = 'xyz'\n\n\nth = Thing3()\nprint(th.letters)\n",
"class Thing3:\n\n def __init__(self):\n self.letters... | false |
6,488 | 15514d5636471b1a311641a40b6a00b81703cd2b | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of ... | [
"# Copyright (c) 2016, Xilinx, Inc.\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, \n# t... | false |
6,489 | 5f4d83aa2b530417ecb1598510fb4778b111700b | #%% [markdown]
# # Look at intron-less gene enrichment in Cyte biased expressed genes.
# This is a quick look at if parimary spermatocyte biased genes are enriched in intronless genes.
# Yes this is what we see.
#%%
import os
import pickle
import numpy as np
import pandas as pd
from scipy.stats import fisher_exact, c... | [
"#%% [markdown]\n# # Look at intron-less gene enrichment in Cyte biased expressed genes.\n\n# This is a quick look at if parimary spermatocyte biased genes are enriched in intronless genes.\n# Yes this is what we see.\n\n#%%\nimport os\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import... | false |
6,490 | 9e896d935cc57e580ed46cd501b41053bbaab38f | from datetime import datetime
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class BusLine(Base):
__tablename__ = "bus_lines"
id = Column(Integer, primary_key=True)... | [
"from datetime import datetime\n\nfrom sqlalchemy import Column, Integer, String, ForeignKey, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\n\nBase = declarative_base()\n\n\nclass BusLine(Base):\n __tablename__ = \"bus_lines\"\n id = Column(Integer,... | false |
6,491 | 20d480517226cb7fbced765554a02fa5cbc29033 | import secrets
from pathlib import Path
HASHCAT_WPA_CACHE_DIR = Path.home() / ".hashcat" / "wpa-server"
ROOT_PRIVATE_DIR = Path(__file__).parent.parent
WORDLISTS_DIR = ROOT_PRIVATE_DIR / "wordlists"
WORDLISTS_USER_DIR = HASHCAT_WPA_CACHE_DIR / "wordlists" # user custom wordlists
RULES_DIR = ROOT_PRIVATE_DIR / "rules... | [
"import secrets\nfrom pathlib import Path\n\nHASHCAT_WPA_CACHE_DIR = Path.home() / \".hashcat\" / \"wpa-server\"\nROOT_PRIVATE_DIR = Path(__file__).parent.parent\n\nWORDLISTS_DIR = ROOT_PRIVATE_DIR / \"wordlists\"\nWORDLISTS_USER_DIR = HASHCAT_WPA_CACHE_DIR / \"wordlists\" # user custom wordlists\nRULES_DIR = ROOT... | false |
6,492 | ab760ec4cbb9f616f38b0f0f2221987460c6f618 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 21:03:43 2019
@author: 00124175
"""
"""
读取txt文件
该文本中的分割符既有空格又有制表符('/t'),sep参数用'/s+',可以匹配任何空格。
"""
#header=None:没有每列的column name,可以自己设定
#encoding='gb2312':其他编码中文显示错误
#sep=',':用逗号来分隔每行的数据
#index_col=0:设置第1列数据作为index
import pandas as pd
data = pd.read_table("1206sjl.txt"... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 18 21:03:43 2019\n\n@author: 00124175\n\"\"\"\n\n\"\"\"\n读取txt文件\n该文本中的分割符既有空格又有制表符('/t'),sep参数用'/s+',可以匹配任何空格。\n\"\"\"\n#header=None:没有每列的column name,可以自己设定\n#encoding='gb2312':其他编码中文显示错误\n#sep=',':用逗号来分隔每行的数据\n#index_col=0:设置第1列数据作为index\nimport pandas as pd\nd... | false |
6,493 | 3bc9c6a66f749858ea5801202b0ac80755c1b347 | from sklearn.naive_bayes import *
from sklearn import svm
from sklearn.pipeline import Pipeline
from sklearn.metrics import classification_report, confusion_matrix
from optparse import OptionParser
from helper import FileHelper, Word2VecHelper, GraphHelper
import helper
from helper.VectorHelper import *
import os
impo... | [
"from sklearn.naive_bayes import *\nfrom sklearn import svm\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom optparse import OptionParser\nfrom helper import FileHelper, Word2VecHelper, GraphHelper\nimport helper\nfrom helper.VectorHelper import *\n\n... | false |
6,494 | 5890525b16b42578ac06e7ab2170c5613feea0a5 | # Benthic Parameters - USEPA OPP defaults from EXAMS
benthic_params = {
"depth": 0.05, # benthic depth (m)
"porosity": 0.65, # benthic porosity
"bulk_density": 1, # bulk density, dry solid mass/total vol (g/cm3)
"froc": 0, # benthic organic carbon fraction
"doc": 5, # benthic dissolved organic ... | [
"# Benthic Parameters - USEPA OPP defaults from EXAMS\nbenthic_params = {\n \"depth\": 0.05, # benthic depth (m)\n \"porosity\": 0.65, # benthic porosity\n \"bulk_density\": 1, # bulk density, dry solid mass/total vol (g/cm3)\n \"froc\": 0, # benthic organic carbon fraction\n \"doc\": 5, # benth... | false |
6,495 | f3895f38be29fb07903237d8846cc9d657b39ea9 | import numpy as np
import cv2
from pixcel import *
from scipy import ndimage
import math
from socket import *
from config import *
from time import time
def find_bounding_boxes(fimage, lables):
# initialize boxes array
boxes = []
for lable in lables:
# iterate all lables
# filter out i... | [
"import numpy as np\nimport cv2\nfrom pixcel import *\nfrom scipy import ndimage\nimport math\nfrom socket import *\nfrom config import *\nfrom time import time\n\n\ndef find_bounding_boxes(fimage, lables):\n\n # initialize boxes array\n boxes = []\n\n for lable in lables:\n\n # iterate all lables\n... | false |
6,496 | af152e0b739305866902ee141f94641b17ff03ea | """#########################################################################
Author: Yingru Liu
Institute: Stony Brook University
Descriptions: transer the numpy files of the midi songs into midi files.
(Cause the code privided by RNN-RBM tutorial to save midi
runs in python 2.7 but my ... | [
"\"\"\"#########################################################################\r\nAuthor: Yingru Liu\r\nInstitute: Stony Brook University\r\nDescriptions: transer the numpy files of the midi songs into midi files.\r\n (Cause the code privided by RNN-RBM tutorial to save midi\r\n runs in ... | false |
6,497 | 69a3471ee8d2c317264b667d6ae0f9b500c6222f | from xml.dom import minidom
import simplejson as json
import re
camel_split = re.compile(r'(^[a-z]+|[A-Z][a-z]+|[a-z0-9]+)')
def get_items(xml):
for obj_node in xml.getElementsByTagName('item'):
obj = dict(obj_node.attributes.items())
if 'name' in obj:
obj['title'] = (' '.join(camel_sp... | [
"from xml.dom import minidom\nimport simplejson as json\nimport re\n\ncamel_split = re.compile(r'(^[a-z]+|[A-Z][a-z]+|[a-z0-9]+)')\n\ndef get_items(xml):\n for obj_node in xml.getElementsByTagName('item'):\n obj = dict(obj_node.attributes.items())\n if 'name' in obj:\n obj['title'] = (' ... | true |
6,498 | 0ec3ca0f952dbc09c7a7a3e746c0aeab28ee9834 | from .base import BaseEngine
import re
class YandexSearch(BaseEngine):
base_url = "https://yandex.com"
search_url = "https://yandex.com/search/"
def get_params(self, query, **params):
params["text"] = query
params["p"] = None
return params
def next_url(self, soup):
if... | [
"from .base import BaseEngine\nimport re\n\n\nclass YandexSearch(BaseEngine):\n base_url = \"https://yandex.com\"\n search_url = \"https://yandex.com/search/\"\n\n def get_params(self, query, **params):\n params[\"text\"] = query\n params[\"p\"] = None\n return params\n\n def next_u... | false |
6,499 | 2ecd234753fabbca2829dc86db2f740e371e4ea7 |
# coding: utf-8
# # Configuration
# In[1]:
CONNECTION_STRING = "mongodb://localhost:27017"
DATABASE_NAME = "off"
COLLECTION_NAME = "products"
# # MongDB connection
# In[2]:
from pymongo import MongoClient
from bson.code import Code
import plotly, pymongo
plotly.offline.init_notebook_mode()
from plotly.graph_obj... | [
"\n# coding: utf-8\n\n# # Configuration\n\n# In[1]:\n\nCONNECTION_STRING = \"mongodb://localhost:27017\"\nDATABASE_NAME = \"off\"\nCOLLECTION_NAME = \"products\"\n\n\n# # MongDB connection\n\n# In[2]:\n\nfrom pymongo import MongoClient\nfrom bson.code import Code\nimport plotly, pymongo\nplotly.offline.init_noteboo... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.