index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
7,300
1305991a9cd82ddeaffff1545a35ced992e6792f
#################################################################################### # # Kaggle Competition: https://www.kaggle.com/c/msk-redefining-cancer-treatment # Sponsor : Memorial Sloan Kettering Cancer Center (MSKCC) # Author: Amrut Shintre # #####################################################################...
[ "####################################################################################\n#\n# Kaggle Competition: https://www.kaggle.com/c/msk-redefining-cancer-treatment\n# Sponsor : Memorial Sloan Kettering Cancer Center (MSKCC)\n# Author: Amrut Shintre\n#\n##########################################################...
false
7,301
aec374ffa368755350d0d75c96860f760e8524e1
from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .models import Post from django.shortcuts import redirect from django.core.exceptions import ObjectDoesNotExist def index(request): blogs = Post.objects.filter(status=...
[ "from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom .models import Post\nfrom django.shortcuts import redirect\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\ndef index(request):\n blogs = Post.objects....
false
7,302
e8ef3a5e41e68b4d219aa1403be392c51cc010e6
""" 对自定义的类进行排序 """ import operator class User: def __init__(self, name, id): self.name = name self.id = id def __repr__(self): return 'User({},{})'.format(self.name, self.id) def run(): users = [User('wang', 1), User('zhao', 4), User('chen', 3), User('wang', 2)] # 这种方式相对速度快...
[ "\"\"\"\n 对自定义的类进行排序\n\"\"\"\nimport operator\n\n\nclass User:\n def __init__(self, name, id):\n self.name = name\n self.id = id\n\n def __repr__(self):\n return 'User({},{})'.format(self.name, self.id)\n\n\ndef run():\n users = [User('wang', 1), User('zhao', 4), User('chen', 3), User(...
false
7,303
562888201719456ed2f3c32e81ffd7d2c39dabc3
# Generated by Django 3.1.2 on 2020-10-25 01:19 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0001_initial'), ] operations = [ migrations.AddField( model_name='job', name='link', ...
[ "# Generated by Django 3.1.2 on 2020-10-25 01:19\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jobs', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='job',\n ...
false
7,304
01e9ceb516a323a2017c65e368da419c6570dce2
# -* coding: utf-8 -*- # A headless media player based on gstreamer. from gi.repository import Gst Gst.init(None) class Player: def __init__(self, uri=None): # Creates a playbin (plays media from an uri). self.player = Gst.ElementFactory.make('playbin', 'player') self.uri = uri @pro...
[ "# -* coding: utf-8 -*-\n# A headless media player based on gstreamer.\n\nfrom gi.repository import Gst\nGst.init(None)\n\n\nclass Player:\n def __init__(self, uri=None):\n # Creates a playbin (plays media from an uri).\n self.player = Gst.ElementFactory.make('playbin', 'player')\n\n self.ur...
false
7,305
b6ee3c980357ab22a7969c21207b34546c87092d
from .exec_generator import *
[ "from .exec_generator import *", "from .exec_generator import *\n", "<import token>\n" ]
false
7,306
bb64da929ff2e1e04267518ec93a28bedb5a4de5
# ---------------------MODULE 1 notes-------------------- # . # . # . # . # . # . # . # . # . # . # save as (file).py first if not it will not work print("Hello") # control s to save
[ "# ---------------------MODULE 1 notes--------------------\r\n# .\r\n# .\r\n# .\r\n# .\r\n# .\r\n# .\r\n# .\r\n# .\r\n# .\r\n# .\r\n\r\n# save as (file).py first if not it will not work\r\nprint(\"Hello\")\r\n\r\n# control s to save\r\n", "print('Hello')\n", "<code token>\n" ]
false
7,307
0cf90cd7704db9f7467e458b402fadb01c701148
from search import SearchEngine import tkinter as tk if __name__ == "__main__": ghettoGoogle = SearchEngine() def searchButtonEvent(): search_query = searchQueryWidget.get() search_results = ghettoGoogle.search(search_query) resultsCanvas = tk.Tk() if search_results == None: ...
[ "from search import SearchEngine\nimport tkinter as tk \n\nif __name__ == \"__main__\":\n ghettoGoogle = SearchEngine()\n\n def searchButtonEvent(): \n search_query = searchQueryWidget.get()\n search_results = ghettoGoogle.search(search_query)\n resultsCanvas = tk.Tk()\n if search_...
false
7,308
282dbdb3a8d9ed914e8ca5c7fa74d2873920e18c
def area (a, b): resultado = a * b return (resultado) def main(): #escribe tu código abajo de esta línea num1 = float(input("INTRODUCE LA BASE: ")) num2 = float(input("INTRODUCE LA ALTURA: ")) print ("EL AREA DEL RECTANGULO ES: ", area (num1, num2)) pass if __name__ == '__main__': main()
[ "def area (a, b):\n resultado = a * b \n return (resultado)\n\ndef main():\n #escribe tu código abajo de esta línea\n num1 = float(input(\"INTRODUCE LA BASE: \"))\n num2 = float(input(\"INTRODUCE LA ALTURA: \"))\n\n print (\"EL AREA DEL RECTANGULO ES: \", area (num1, num2))\n\npass\n\n\nif __name__ == '__m...
false
7,309
f311b803d8c0ee68bc43526f56e6b14f3a2836b8
#### As an example below shell script can be used to execute this every 300s. ####!/bin/bash ####while true ####do #### /usr/bin/sudo python3 /path/of/the/python/script.sh ####done #!/usr/bin/python import sys import time import paho.mqtt.client as mqtt broker_url = "<IP_Address_of_MQTT_broker>" b...
[ "#### As an example below shell script can be used to execute this every 300s.\r\n####!/bin/bash\r\n####while true\r\n####do\r\n#### /usr/bin/sudo python3 /path/of/the/python/script.sh\r\n####done\r\n\r\n#!/usr/bin/python\r\nimport sys\r\nimport time\r\nimport paho.mqtt.client as mqtt\r\n\r\nbroker_url = \"<...
true
7,310
b5568e84e19719f0fd72197ead47bd050e09f55d
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # groupby() # groupby()把迭代器中相邻的重复元素挑出来放在一起: import itertools for key, group in itertools.groupby('ABAABBBCCAAA'): print(key, list(group)) # 小结 # itertools模块提供的全部是处理迭代功能的函数,它们的返回值不是list,而是Iterator,只有用for循环迭代的时候才真正计算。
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n# groupby()\n# groupby()把迭代器中相邻的重复元素挑出来放在一起:\nimport itertools\nfor key, group in itertools.groupby('ABAABBBCCAAA'):\n print(key, list(group))\n\n\n# 小结\n# itertools模块提供的全部是处理迭代功能的函数,它们的返回值不是list,而是Iterator,只有用for循环迭代的时候才真正计算。\n", "import itertools\nfor key...
false
7,311
54d6121898dc027d6ecaf9c9e7c25391778e0d21
#!/usr/bin/env python # -*- coding: utf-8 -*- # sockdemo.py # # test import struct, threading, signal a = '' if not a: print 'a' else: print 'b' import datetime, time, os print datetime.datetime.now().strftime('%m-%d %H:%M:%S') def double(x): return x*x arr = [1, 2, 3, 4, 5] print map(double, arr) print 2**16 ...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# sockdemo.py\n#\n# test\n\nimport struct, threading, signal\n\na = ''\n\nif not a:\n\tprint 'a'\nelse:\n\tprint 'b'\n\nimport datetime, time, os\n\nprint datetime.datetime.now().strftime('%m-%d %H:%M:%S')\n\ndef double(x): return x*x\n\narr = [1, 2, 3, 4, 5]\nprint ...
true
7,312
5f84c8654c976bca2fa33e8f9ba5e28e3249253d
import numpy as np import faiss from util import vecs_io, vecs_util from time import time import os ''' 提取vecs, 输出numpy文件 ''' def vecs2numpy(fname, new_file_name, file_type, file_len=None): if file_type == 'bvecs': vectors, dim = vecs_io.bvecs_read_mmap(fname) elif file_type == 'ivecs':...
[ "import numpy as np\r\nimport faiss\r\nfrom util import vecs_io, vecs_util\r\nfrom time import time\r\nimport os\r\n\r\n'''\r\n提取vecs, 输出numpy文件\r\n'''\r\n\r\n\r\ndef vecs2numpy(fname, new_file_name, file_type, file_len=None):\r\n if file_type == 'bvecs':\r\n vectors, dim = vecs_io.bvecs_read_mmap(fname)\...
false
7,313
8340872f03c1bf7c1aee0c437258ac8e44e08bb8
# 5.2 Training a convnet from scratch on a "small dataset" (p.131) # Preprocessing (p.133) # Copying images to train, validation and test directories import os, shutil # The path to the directory where the original dataset was uncompressed original_dataset_dir = 'E:/train/' # The directory where we will store our sma...
[ "# 5.2 Training a convnet from scratch on a \"small dataset\" (p.131)\n# Preprocessing (p.133)\n# Copying images to train, validation and test directories\nimport os, shutil\n\n# The path to the directory where the original dataset was uncompressed\noriginal_dataset_dir = 'E:/train/'\n\n# The directory where we wil...
false
7,314
800d87a879987c47f1a66b729932279fc8d4fa38
#Homework 2 PyPoll #The total number of votes cast #A complete list of candidates who received votes #The percentage of votes each candidate won #The total number of votes each candidate won #The winner of the election based on popular vote. #First we'll import the os module # This will allow us to create file pat...
[ " #Homework 2 PyPoll\n #The total number of votes cast\n#A complete list of candidates who received votes\n#The percentage of votes each candidate won\n#The total number of votes each candidate won\n#The winner of the election based on popular vote.\n \n #First we'll import the os module\n# This will allow us to cr...
false
7,315
3ef114dd35ef3995ae73bf85bbe38db4fb7045d8
#from __future__ import absolute_import #import os from celery import Celery #from django.conf import settings #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning.settings') app = Celery('tasks', broker="redis://localhost") #app.config_from_object('django.conf:settings') #app.autodiscover_tasks(lambda: setti...
[ "\n#from __future__ import absolute_import\n#import os\nfrom celery import Celery\n#from django.conf import settings\n\n#os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning.settings')\napp = Celery('tasks', broker=\"redis://localhost\")\n\n\n#app.config_from_object('django.conf:settings')\n#app.autodiscover_t...
false
7,316
7c80c98e32f386362003ac3cd729fa9b279b8e8e
import numpy as np import cv2 import serial import serial.tools.list_ports import time import random import math #import mcpi.minecraft as minecraft #import mcpi.block as block #from house import House #Arduino Serials ports = list(serial.tools.list_ports.comports()) print (ports) for p in ports: print (p[1]) ...
[ "import numpy as np\nimport cv2\nimport serial\nimport serial.tools.list_ports\nimport time\nimport random\nimport math\n#import mcpi.minecraft as minecraft\n#import mcpi.block as block\n#from house import House\n\n\n\n#Arduino Serials\nports = list(serial.tools.list_ports.comports())\nprint (ports)\nfor p in ports...
false
7,317
50e759ff24cdb8fbb5a98d9381afb13ebc1a74f1
import json from bottle import request, response, route, get, run, default_app app = application = default_app() @route('/candidate/hired', method=['POST']) def update_delete_handler(): response.content_type = 'application/json' return json.dumps({"hired": True}) def main(): run(host='localhost', port...
[ "import json\n\nfrom bottle import request, response, route, get, run, default_app\n\n\napp = application = default_app()\n\n\n@route('/candidate/hired', method=['POST'])\ndef update_delete_handler():\n response.content_type = 'application/json'\n return json.dumps({\"hired\": True})\n\ndef main():\n run(h...
false
7,318
ad84a5bfcf82dff1f4a7e8f08f3c4243ad24de52
from foods.fruits import * orange.eat() apple.eat()
[ "from foods.fruits import *\n\norange.eat()\napple.eat()\n", "from foods.fruits import *\norange.eat()\napple.eat()\n", "<import token>\norange.eat()\napple.eat()\n", "<import token>\n<code token>\n" ]
false
7,319
2867a7b24b4911b2936cb34653fa57431c14d6a3
#Displaying multiple images using matplotlib import pandas as pd import numpy as np import cv2 import matplotlib.pyplot as plt def main(): imgpath1="C:\Shreyas\OpenCv\DIP_OpenCV\lena.png" imgpath2="C:\Shreyas\OpenCv\DIP_OpenCV\lena.png" img1=cv2.imread(imgpath1,1) img2=cv2.imread(imgpath2,...
[ "#Displaying multiple images using matplotlib\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\ndef main():\n \n imgpath1=\"C:\\Shreyas\\OpenCv\\DIP_OpenCV\\lena.png\"\n imgpath2=\"C:\\Shreyas\\OpenCv\\DIP_OpenCV\\lena.png\"\n \n img1=cv2.imread(imgpath1,1) \n ...
false
7,320
8142585827590f6d951f0fcc375e8511aa75e9c8
# from https://github.com/tensorflow/models/tree/master/research/object_detection/dataset_tools # and https://gist.github.com/saghiralfasly/ee642af0616461145a9a82d7317fb1d6 import tensorflow as tf from object_detection.utils import dataset_util import os import io import hashlib import xml.etree.ElementTree as ET imp...
[ "# from https://github.com/tensorflow/models/tree/master/research/object_detection/dataset_tools\n# and https://gist.github.com/saghiralfasly/ee642af0616461145a9a82d7317fb1d6\n \nimport tensorflow as tf\nfrom object_detection.utils import dataset_util\nimport os\nimport io\nimport hashlib\nimport xml.etree.ElementT...
false
7,321
1c5cb9363c2903905f1026ede77615e8373c250b
from django.db import models # Create your models here. class Login(models.Model): trinity_id = models.CharField('',max_length=200) trinity_password = models.CharField('',max_length=500) objects = models.Manager()
[ "from django.db import models\n\n# Create your models here.\n\nclass Login(models.Model):\n trinity_id = models.CharField('',max_length=200)\n trinity_password = models.CharField('',max_length=500)\n\n objects = models.Manager()", "from django.db import models\n\n\nclass Login(models.Model):\n trinity...
false
7,322
c91be6cc332139c5b1e7ee5a3512482d0f8620b1
def selectionSort(arr, low, high): for i in range(len(arr)): mini = i for j in range(i + 1, len(arr)): if arr[mini] > arr[j]: mini = j arr[i], arr[mini] = arr[mini], arr[i] return arr
[ "\ndef selectionSort(arr, low, high):\n for i in range(len(arr)):\n mini = i\n for j in range(i + 1, len(arr)):\n if arr[mini] > arr[j]:\n mini = j\n arr[i], arr[mini] = arr[mini], arr[i]\n return arr\n", "def selectionSort(arr, low, high):\n for i in range(...
false
7,323
58667da8898c2277ecc3d9d738d6553dd3416436
############################################-############################################ ################################ F I L E A U T H O R S ################################ # MIKE - see contacts in _doc_PACKAGE_DESCRIPTION ####################################### A B O U T #######################################...
[ "############################################-############################################\n################################ F I L E A U T H O R S ################################\n# MIKE - see contacts in _doc_PACKAGE_DESCRIPTION\n\n####################################### A B O U T ##############################...
false
7,324
1ebf92cf40053e561b04a666eb1dd36f54999e2c
if __name__ == '__main__': import sys import os.path srcpath = sys.argv[1] if len(sys.argv) >= 1 else './' verfn = sys.argv[2] if len(sys.argv) >= 2 else None try : with open(os.path.join(srcpath,'.svn/entries'),'r') as fp: x = fp.read().s...
[ "\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n import sys\r\n import os.path\r\n \r\n srcpath = sys.argv[1] if len(sys.argv) >= 1 else './'\r\n verfn = sys.argv[2] if len(sys.argv) >= 2 else None\r\n \r\n try :\r\n \r\n with open(os.path.join(srcpath,'.svn/entries'),'r') as f...
true
7,325
3f1715763a066fb337b3ff3d03e3736d0fb36b3f
from PyQt5 import QtCore from PyQt5.QtWidgets import QTableWidgetItem, QDialog from QT_view.PassportAdd import PassportAddDialog from QT_view.PassportWin import Ui_Dialog from Repository.Rep_Passport import PassportRepository class PassportQt(QDialog): def __init__(self): super(PassportQt, self...
[ "from PyQt5 import QtCore\r\nfrom PyQt5.QtWidgets import QTableWidgetItem, QDialog\r\n\r\nfrom QT_view.PassportAdd import PassportAddDialog\r\nfrom QT_view.PassportWin import Ui_Dialog\r\n\r\nfrom Repository.Rep_Passport import PassportRepository\r\n\r\nclass PassportQt(QDialog):\r\n def __init__(self):\r\n ...
false
7,326
5af5c10c149c7b0e2a969be7895780d26a4294d0
import csv with open('faculty.csv') as facultycsv: emails = list() #all email addresses for line in facultycsv: line = line.split(',') if line[0] == 'name' : continue try: email = line[3].rstrip() emails.append(email) except: continue with o...
[ "import csv\n\nwith open('faculty.csv') as facultycsv:\n emails = list() #all email addresses\n\n for line in facultycsv:\n line = line.split(',')\n if line[0] == 'name' : continue\n try:\n email = line[3].rstrip()\n emails.append(email)\n except:\n ...
false
7,327
956adc5961188458393b56564649ad0a3a787669
x = 5 y = x print(id(x)) print(id(y)) print() y = 3 print(id(x)) print(id(y)) print() z = [1, 4, 3, 25] w = z print(z) print(w) print(id(z)) print(id(w)) print() w[1] = 10 print(z) print(w) print(id(z)) print(id(w)) # So when you assign a mutable, you're actually assigning a reference to the mutable, # and I...
[ "x = 5\ny = x\n\nprint(id(x))\nprint(id(y))\n\nprint()\n\ny = 3\n\nprint(id(x))\nprint(id(y))\n\nprint()\n\nz = [1, 4, 3, 25]\nw = z\n\nprint(z)\nprint(w)\nprint(id(z))\nprint(id(w))\n\nprint()\n\nw[1] = 10\n\nprint(z)\nprint(w)\nprint(id(z))\nprint(id(w))\n\n# So when you assign a mutable, you're actually assignin...
false
7,328
af5ebdcd818fdf9c607240733b7b5dbb793cf55e
# put your python code here a = int(input()) b = int(input()) # and i = 1 if a == b: print(a) else: while True: if i // a > 0 and i % a == 0 and i // b > 0 and i % b == 0: print(i) break else: i += 1
[ "# put your python code here\na = int(input())\nb = int(input())\n\n# and\ni = 1\nif a == b:\n print(a)\nelse:\n while True:\n if i // a > 0 and i % a == 0 and i // b > 0 and i % b == 0:\n print(i)\n break\n else:\n i += 1\n", "a = int(input())\nb = int(input()...
false
7,329
3b9193fcd69b0387222feab96c50bf3617606cdd
from typing import List, cast import numpy as np from ..dataset import Transition from .base import TransitionIterator class RandomIterator(TransitionIterator): _n_steps_per_epoch: int def __init__( self, transitions: List[Transition], n_steps_per_epoch: int, batch_size: in...
[ "from typing import List, cast\n\nimport numpy as np\n\nfrom ..dataset import Transition\nfrom .base import TransitionIterator\n\n\nclass RandomIterator(TransitionIterator):\n\n _n_steps_per_epoch: int\n\n def __init__(\n self,\n transitions: List[Transition],\n n_steps_per_epoch: int,\n ...
false
7,330
5c4a48de94cf5bfe67e6a74c33a317fa1da8d2fa
from django.db import models from django.urls import reverse from django.conf import settings from embed_video.fields import EmbedVideoField from django.contrib.auth.models import AbstractBaseUser User = settings.AUTH_USER_MODEL # Create your models here. """class User(models.Model): username = models.CharField(...
[ "from django.db import models\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom embed_video.fields import EmbedVideoField\nfrom django.contrib.auth.models import AbstractBaseUser\n\nUser = settings.AUTH_USER_MODEL\n\n# Create your models here.\n\n\"\"\"class User(models.Model):\n username ...
false
7,331
86345702bcd423bc31e29b1d28aa9c438629297d
# -*- coding: utf-8 -*- """ Created on Wed Aug 18 16:11:44 2021 @author: ignacio """ import matplotlib.pyplot as plt from numpy.linalg import inv as invertir from time import perf_counter import numpy as np def matriz_laplaciana(N, t=np.single): # funcion obtenida de clase e=np.eye(N)-np.eye(N,N,...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 18 16:11:44 2021\r\n\r\n@author: ignacio\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.linalg import inv as invertir\r\nfrom time import perf_counter\r\nimport numpy as np\r\n\r\ndef matriz_laplaciana(N, t=np.single): # funcion obtenida de...
false
7,332
84a63f60a45f1f8fc1efec8f30345a43c3c30c63
def html_print(text, title=''): from IPython.core.display import display, HTML # create title for the content display(HTML("<h4>" + str(title) + "</h4>")) # create content html = display(HTML("<font size=2 face=Verdana>" + text + "</font>")) return html
[ "def html_print(text, title=''):\n\n from IPython.core.display import display, HTML\n\n # create title for the content\n display(HTML(\"<h4>\" + str(title) + \"</h4>\"))\n\n # create content\n html = display(HTML(\"<font size=2 face=Verdana>\" + text + \"</font>\"))\n\n return html\n", "def html...
false
7,333
aafadcbf946db8ed85e3df48f5411967ec35c318
#!/usr/bin/env python # ---------------------------------------------------------- # RJGlass Main Program version 0.2 8/1/07 # ---------------------------------------------------------- # Copyright 2007 Michael LaBrie # # This file is part of RJGlass. # # RJGlass is free software; you can redistribute it and/or ...
[ "#!/usr/bin/env python\n# ----------------------------------------------------------\n# RJGlass Main Program version 0.2 8/1/07\n# ----------------------------------------------------------\n# Copyright 2007 Michael LaBrie\n#\n# This file is part of RJGlass.\n#\n# RJGlass is free software; you can redistribu...
true
7,334
4843239a41fe1ecff6c8c3a97aceef76a3785647
import operator def group_by_owners(files): print(files, type(files)) for k, v in files.items(): # for v in k: print(k, v) # if k[v] == k[v]: # print("same", v) for f in files: print(f[0]) for g in v: print(g) _files = sorted(files.items(...
[ "import operator\n\n\ndef group_by_owners(files):\n print(files, type(files))\n for k, v in files.items():\n # for v in k:\n print(k, v)\n # if k[v] == k[v]:\n # print(\"same\", v)\n for f in files:\n print(f[0])\n for g in v:\n print(g)\n _files ...
false
7,335
5a13c7e3be8a0b5f3baf7106a938fc97f078c5bc
''' Created on May 17, 2016 @author: Shauryadeep Chaudhuri ''' import json import tornado from engine import Constants as c from engine.ResultGenerator import ResultGenerator from ..ServerLogger import ServerLogger class GetFromURL(tornado.web.RequestHandler): ''' This class fetches the d...
[ "'''\r\nCreated on May 17, 2016\r\n\r\n@author: Shauryadeep Chaudhuri\r\n'''\r\n\r\nimport json\r\n\r\nimport tornado\r\n\r\nfrom engine import Constants as c\r\nfrom engine.ResultGenerator import ResultGenerator\r\nfrom ..ServerLogger import ServerLogger\r\n\r\n\r\nclass GetFromURL(tornado.web.RequestHandler):\r\n...
false
7,336
eb1fbe2de3c8548175eb3c8720353e466e3b68c7
import rdflib import csv from time import sleep gtypes = {} dtypes = {} atypes = {} g = rdflib.Graph() g.parse("http://geographicknowledge.de/vocab/CoreConceptData.rdf#") g.parse("./ontology.ttl", format="ttl") sleep(.5) results = g.query(""" prefix skos: <http://www.w3.org/2004/02/skos/core#> prefix ccd: ...
[ "import rdflib\nimport csv\n\nfrom time import sleep\n\ngtypes = {}\ndtypes = {}\natypes = {}\n\ng = rdflib.Graph()\ng.parse(\"http://geographicknowledge.de/vocab/CoreConceptData.rdf#\")\ng.parse(\"./ontology.ttl\", format=\"ttl\")\n\nsleep(.5)\n\nresults = g.query(\"\"\"\n prefix skos: <http://www.w3.org/2004/0...
false
7,337
47d72379b894826dad335f098649702ade195f78
n=int(input("Digite um número")) m=n-1 o=n+1 print("Seu número é {} seu antecessor é {} e seu sucessor é {}".format(n,m,o))
[ "n=int(input(\"Digite um número\"))\nm=n-1\no=n+1\nprint(\"Seu número é {} seu antecessor é {} e seu sucessor é {}\".format(n,m,o))", "n = int(input('Digite um número'))\nm = n - 1\no = n + 1\nprint('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o)\n )\n", "<assignment token>\nprint('...
false
7,338
a72d878d246a459038640bf9c1deff562994b345
def solution(skill, skill_trees): answer = 0 for tree in skill_trees: able = True for i in range(len(skill) - 1, 0, -1): index = tree.find(skill[i]) if index != -1 and i > 0: if tree[:index].find(skill[i - 1]) == -1: able = False ...
[ "def solution(skill, skill_trees):\n answer = 0\n \n for tree in skill_trees:\n able = True\n for i in range(len(skill) - 1, 0, -1):\n index = tree.find(skill[i])\n if index != -1 and i > 0:\n if tree[:index].find(skill[i - 1]) == -1:\n ...
false
7,339
42d26ef51bb4dafc8a0201a828652e166a3905e4
def unique(lisst): setlisst = set(lisst) return len(setlisst) print(unique({4,5,1,1,3}))
[ "def unique(lisst):\r\n setlisst = set(lisst) \r\n return len(setlisst)\r\nprint(unique({4,5,1,1,3}))", "def unique(lisst):\n setlisst = set(lisst)\n return len(setlisst)\n\n\nprint(unique({4, 5, 1, 1, 3}))\n", "def unique(lisst):\n setlisst = set(lisst)\n return len(setlisst)\n\n\n<code token...
false
7,340
8e443d136a4e9fcdd18a106192f9c097928b8c99
from typing import List, Any, Callable, Iterable, TypeVar, Tuple T = TypeVar('T') def partition(pred: Callable[[T], bool], it: Iterable[T]) \ -> Tuple[List[T], List[T]]: ...
[ "from typing import List, Any, Callable, Iterable, TypeVar, Tuple\n\nT = TypeVar('T')\n\ndef partition(pred: Callable[[T], bool], it: Iterable[T]) \\\n -> Tuple[List[T], List[T]]: ...\n", "from typing import List, Any, Callable, Iterable, TypeVar, Tuple\nT = TypeVar('T')\n\n\ndef partition(pred: Callable[[...
false
7,341
62dab85b7ab5fdae8117827b2f56bccf99615cb7
a=[[*map(int,input().split())]for _ in range(int(input()))] a.sort() s=0 l0,h0=a[0] for l,h in a: if h0<h:s+=(l-l0)*h0;l0,h0=l,h l1,h1=a[-1] for l,h in a[::-1]: if h>h1:s+=(l1-l)*h1;l1,h1=l,h s+=(l1-l0+1)*h1 print(s)
[ "a=[[*map(int,input().split())]for _ in range(int(input()))]\na.sort()\ns=0\nl0,h0=a[0]\nfor l,h in a:\n if h0<h:s+=(l-l0)*h0;l0,h0=l,h\nl1,h1=a[-1]\nfor l,h in a[::-1]:\n if h>h1:s+=(l1-l)*h1;l1,h1=l,h\ns+=(l1-l0+1)*h1\nprint(s)", "a = [[*map(int, input().split())] for _ in range(int(input()))]\na.sort()\n...
false
7,342
8bb86cae3387a0d4ce5987f3e3c458c8298174e0
from .settings import * # Heroku Configurations # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES = {'default': dj_database_url.config()} # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # loading local_se...
[ "from .settings import *\n\n\n\n# Heroku Configurations\n# Parse database configuration from $DATABASE_URL\nimport dj_database_url\n\nDATABASES = {'default': dj_database_url.config()}\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n...
false
7,343
db231ea92319414dd10ca8dfbc14e5a70ed2fe44
from QnA_processor.question_analysis.google_question_classifier import GoogleQuestionClassifier def classify_question(query): try: """ Get answer-type from google autoML classifier (by making POST requests with authorization key) """ question_c...
[ " \r\n \r\nfrom QnA_processor.question_analysis.google_question_classifier import GoogleQuestionClassifier\r\n \r\ndef classify_question(query):\r\n \r\n try:\r\n \"\"\"\r\n Get answer-type from google autoML classifier \r\n (by making POST requests with authorization key)\r\n ...
false
7,344
f704742b9e023a1c3386fed293032fd8196b875e
# -*- coding: utf-8 -*- # Author : Seungyeon Jo # e-mail : syjo@seculayer.co.kr # Powered by Seculayer © 2018 AI-Core Team from mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract class Substr(ConvertAbstract): def __init__(self, **kwargs): super().__init__(**kwargs) def apply(self,...
[ "# -*- coding: utf-8 -*-\n# Author : Seungyeon Jo\n# e-mail : syjo@seculayer.co.kr\n# Powered by Seculayer © 2018 AI-Core Team\n\nfrom mlps.core.data.cnvrtr.ConvertAbstract import ConvertAbstract\n\n\nclass Substr(ConvertAbstract):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n \n ...
false
7,345
12fd4e3bfb6821205a9b65b4d236b4158ec4ef1e
#!/usr/bin/env python # # Copyright 2017-2021 University Of Southern California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
[ "#!/usr/bin/env python\n#\n# Copyright 2017-2021 University Of Southern California\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-...
false
7,346
357ee02060cbfa391920b3d45dfbe16e679a6c8d
def spam(divide_by): return 42 / divide_by try: print(spam(2)) print(spam(12)) print(spam(0)) print(spam(1)) print(spam("dog")) except Exception: print("Error: Invalid argument.")
[ "def spam(divide_by):\n return 42 / divide_by\n\ntry:\n print(spam(2))\n print(spam(12))\n print(spam(0))\n print(spam(1))\n print(spam(\"dog\"))\nexcept Exception:\n print(\"Error: Invalid argument.\")\n\n \n", "def spam(divide_by):\n return 42 / divide_by\n\n\ntry:\n print(spam(2))\n print(spam...
false
7,347
4473971552aa48236b19dec7e7c1ea1e622d5795
from subprocess import check_output import json import sys import time import os import numpy as np from hutch_python.utils import safe_load from ophyd import EpicsSignalRO from ophyd import EpicsSignal from bluesky import RunEngine from bluesky.plans import scan from bluesky.plans import list_scan from bluesky.plan_...
[ "from subprocess import check_output\n\nimport json\nimport sys\nimport time\nimport os\n\nimport numpy as np\nfrom hutch_python.utils import safe_load\nfrom ophyd import EpicsSignalRO\nfrom ophyd import EpicsSignal\nfrom bluesky import RunEngine\nfrom bluesky.plans import scan\nfrom bluesky.plans import list_scan\...
false
7,348
e247ffb5b6e4319ff17d0b8ae9f67e10c282c4ff
# 多角色认证装饰器 def auth(role): from core import admin_view,student_view,teacher_view def deco(func): def wrapper(*args,**kwargs): if role == 'admin': if admin_view.admin_user == None: admin_view.login() else: res = func(...
[ "\n# 多角色认证装饰器\n\ndef auth(role):\n\n from core import admin_view,student_view,teacher_view\n def deco(func):\n def wrapper(*args,**kwargs):\n\n if role == 'admin':\n if admin_view.admin_user == None:\n admin_view.login()\n else:\n ...
false
7,349
8c96c38a67c2eb97e30b325e4917ba4888731118
import json import boto3 import os import datetime regionName = os.environ['AWS_REGION'] BUCKET_PATH = os.environ['BUCKET_PATH'] SENSITIVIT = os.environ['SENSITIVIT'] s3_client = boto3.client('s3', region_name=regionName) ddb_resource = boto3.resource('dynamodb', region_name=regionName) def lambda_handler(event, co...
[ "import json\nimport boto3\nimport os\nimport datetime\n\n\nregionName = os.environ['AWS_REGION']\nBUCKET_PATH = os.environ['BUCKET_PATH']\nSENSITIVIT = os.environ['SENSITIVIT']\n\ns3_client = boto3.client('s3', region_name=regionName)\nddb_resource = boto3.resource('dynamodb', region_name=regionName)\n\ndef lambda...
false
7,350
f9cee552dde5ecf229fda559122b4b0e780c3b88
class Solution: def countLetters(self, S: str) -> int: ans = 0 for _, g in itertools.groupby(S): cnt = len(list(g)) ans += (1 + cnt) * cnt // 2 return ans
[ "class Solution:\n def countLetters(self, S: str) -> int:\n ans = 0\n for _, g in itertools.groupby(S):\n cnt = len(list(g))\n ans += (1 + cnt) * cnt // 2\n return ans\n", "class Solution:\n\n def countLetters(self, S: str) ->int:\n ans = 0\n for _, g...
false
7,351
e1751cc6f76f56e62cd02d61db65f1c27a4ff1b9
#encoding=utf-8 import pytest from frame_project.实战2.main_page import MainPage class TestMian: def test_mian(self): MainPage().goto_marketpage().goto_search().search() if __name__ == '__main__': pytest.main(['test_case.py','-s','-v'])
[ "#encoding=utf-8\nimport pytest\n\nfrom frame_project.实战2.main_page import MainPage\n\n\nclass TestMian:\n def test_mian(self):\n MainPage().goto_marketpage().goto_search().search()\n\nif __name__ == '__main__':\n pytest.main(['test_case.py','-s','-v'])\n", "import pytest\nfrom frame_project.实战2.main...
false
7,352
1b091d139635e90fb53b3fecc09bb879514c7b38
import os import json from google.appengine.ext import webapp from generic import JsonRpcService class ViewService(JsonRpcService): def json_create(self): return "Hello, World!"
[ "import os\nimport json\n\nfrom google.appengine.ext import webapp\nfrom generic import JsonRpcService\n\nclass ViewService(JsonRpcService):\n def json_create(self):\n return \"Hello, World!\"\n", "import os\nimport json\nfrom google.appengine.ext import webapp\nfrom generic import JsonRpcService\n\n\nclass V...
false
7,353
3cf2ffbc8163c2a447016c93ff4dd13e410fff2b
# -*- coding: utf-8 -*- class Task: def __init__(self): self.title = '' self.subtasks = [] def set_title(self, title): self.title = title def set_subtasks(self, subtasks): self.subtasks = subtasks
[ "# -*- coding: utf-8 -*-\nclass Task:\n def __init__(self):\n self.title = ''\n self.subtasks = []\n\n def set_title(self, title):\n self.title = title\n\n def set_subtasks(self, subtasks):\n self.subtasks = subtasks\n", "class Task:\n\n def __init__(self):\n self.ti...
false
7,354
98dbc6c3bdc3efb4310a2dbb7b1cc1c89eb4582b
import urllib3 with open('python.jpg', 'rb') as f: data = f.read() http = urllib3.PoolManager() r = http.request('POST', 'http://httpbin.org/post', body=data, headers={'Content-Type': 'image/jpeg'}) print(r.data.decode())
[ "import urllib3\n\nwith open('python.jpg', 'rb') as f:\n data = f.read()\nhttp = urllib3.PoolManager()\nr = http.request('POST', 'http://httpbin.org/post', body=data, headers={'Content-Type': 'image/jpeg'})\nprint(r.data.decode())", "import urllib3\nwith open('python.jpg', 'rb') as f:\n data = f.read()\nhtt...
false
7,355
a9b1cc9b928b8999450b6c95656b863c476b273b
import sys from PyQt5 import QtWidgets from PyQt5.QtWidgets import QMainWindow, QApplication #---Import that will load the UI file---# from PyQt5.uic import loadUi import detechRs_rc #---THIS IMPORT WILL DISPLAY THE IMAGES STORED IN THE QRC FILE AND _rc.py FILE--# #--CLASS CREATED THAT WILL LOAD THE UI FILE...
[ "import sys\r\nfrom PyQt5 import QtWidgets\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication\r\n\r\n#---Import that will load the UI file---#\r\nfrom PyQt5.uic import loadUi\r\n\r\nimport detechRs_rc #---THIS IMPORT WILL DISPLAY THE IMAGES STORED IN THE QRC FILE AND _rc.py FILE--#\r\n\r\n#--CLASS CREATED THA...
false
7,356
bb3c42c9f87a463b9f18601c9e3897b6d21351d5
from django.db import models from django.utils import timezone from django.db.models.signals import post_save from django.urls import reverse # Create your models here. class Purchase(models.Model): invoice = models.SmallIntegerField(primary_key=True,blank=False) ch_no = models.SmallIntegerField(blank=True,nul...
[ "from django.db import models\nfrom django.utils import timezone\nfrom django.db.models.signals import post_save\nfrom django.urls import reverse\n# Create your models here.\n\nclass Purchase(models.Model):\n invoice = models.SmallIntegerField(primary_key=True,blank=False)\n ch_no = models.SmallIntegerField(b...
false
7,357
3328c2ae0816c146398ecde92a056d1e77683696
import tkinter as tk from telnetConn import telnetConnection fields = 'Host Address', 'UserName', 'Password', 'Message To', 'Text' def fetch(entries): input_list = [] for entry in entries: field = entry[0] text = entry[1].get() input_list.append(text) # print('%s:...
[ "import tkinter as tk\r\nfrom telnetConn import telnetConnection\r\n\r\n\r\nfields = 'Host Address', 'UserName', 'Password', 'Message To', 'Text'\r\n\r\ndef fetch(entries):\r\n input_list = []\r\n for entry in entries:\r\n field = entry[0]\r\n text = entry[1].get()\r\n input_list.append(...
false
7,358
ff8b6bc607dac889da05b9f7e9b3595151153614
import requests import json from concurrent import futures from tqdm import trange def main(): ex=futures.ThreadPoolExecutor(max_workers=50) for i in trange(1,152): url="https://api.bilibili.com/pgc/season/index/result?season_version=-1&" \ "area=-1&is_finish=-1&copyright=-1&season...
[ "import requests\r\nimport json\r\nfrom concurrent import futures\r\nfrom tqdm import trange\r\n\r\ndef main():\r\n ex=futures.ThreadPoolExecutor(max_workers=50)\r\n for i in trange(1,152):\r\n url=\"https://api.bilibili.com/pgc/season/index/result?season_version=-1&\" \\\r\n \"area=-1&is_fi...
false
7,359
2305d0b7ec0d9e08e3f1c0cedaafa6ed60786e50
#! /usr/bin/env python3 import common, os, shutil, sys def main(): os.chdir(common.root) shutil.rmtree('shared/target', ignore_errors = True) shutil.rmtree('platform/build', ignore_errors = True) shutil.rmtree('platform/target', ignore_errors = True) shutil.rmtree('tests/target', ignore_errors = True) shut...
[ "#! /usr/bin/env python3\nimport common, os, shutil, sys\n\ndef main():\n os.chdir(common.root)\n shutil.rmtree('shared/target', ignore_errors = True)\n shutil.rmtree('platform/build', ignore_errors = True)\n shutil.rmtree('platform/target', ignore_errors = True)\n shutil.rmtree('tests/target', ignore_errors =...
false
7,360
cf5ab10ce743aa261867501e93f498022e5908fe
#!python3 import configparser parser = configparser.ConfigParser() parser.read("sim.conf") print(parser.get("config", "option1")) print(parser.get("config", "option2")) print(parser.get("config", "option3"))
[ "#!python3\nimport configparser\nparser = configparser.ConfigParser()\n\nparser.read(\"sim.conf\")\n\nprint(parser.get(\"config\", \"option1\"))\nprint(parser.get(\"config\", \"option2\"))\nprint(parser.get(\"config\", \"option3\"))\n", "import configparser\nparser = configparser.ConfigParser()\nparser.read('sim....
false
7,361
e47d6b5d46f2dd84569a2341178b2ea5e074603a
import cv2 import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import SeparableConv2D, Conv2D, MaxPooling2D from keras.layers import BatchNormalization, Activation, Dropo...
[ "import cv2\nimport numpy as np\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import SeparableConv2D, Conv2D, MaxPooling2D\nfrom keras.layers import BatchNormalization, Acti...
false
7,362
bcc2977f36ecc775f44ae4251ce230af9abf63ba
''' This module demonstrates how to use some functionality of python built-in csv module ''' import csv def csv_usage(): ''' This function demonstrates how to use csv module to read and write csv files ''' with open('example.csv', 'r', newline='') as csvfile: reader_c = csv.reader(csvfile, deli...
[ "'''\nThis module demonstrates how to use some functionality of python built-in csv module\n'''\nimport csv\n\ndef csv_usage():\n '''\n This function demonstrates how to use csv module to read and write csv files\n '''\n with open('example.csv', 'r', newline='') as csvfile:\n reader_c = csv.reade...
false
7,363
5066c2a5219cf1b233b4985efc7a4eb494b784ca
def gen_metadata(fn): metadata = {} lines = open(fn,'r').readlines() for line in lines: line = line.rstrip() if len(line) == 0: continue elif line.startswith('#'): continue elif line.startswith('%'): continue else: # Special case RingThresh firstWord = line.split()[0] if line.startswith('...
[ "def gen_metadata(fn):\n\tmetadata = {}\n\tlines = open(fn,'r').readlines()\n\tfor line in lines:\n\t\tline = line.rstrip()\n\t\tif len(line) == 0:\n\t\t\tcontinue\n\t\telif line.startswith('#'):\n\t\t\tcontinue\n\t\telif line.startswith('%'):\n\t\t\tcontinue\n\t\telse:\n\t\t\t# Special case RingThresh\n\t\t\tfirst...
false
7,364
0d8a26ef4077b40e8255d5bb2ce9217b51118780
#!/usr/bin/python3 # encoding: utf-8 """ @author: ShuoChang @license: (C) MIT. @contact: changshuo@bupt.edu.cn @software: CRNN_STN_SEQ @file: decoder_base.py @time: 2019/7/22 17:21 @blog: https://www.zhihu.com/people/chang-shuo-59/activities """ from abc import ABCMeta from abc import abstractmethod class DecoderBas...
[ "#!/usr/bin/python3\n# encoding: utf-8\n\"\"\"\n@author: ShuoChang\n@license: (C) MIT.\n@contact: changshuo@bupt.edu.cn\n@software: CRNN_STN_SEQ\n@file: decoder_base.py\n@time: 2019/7/22 17:21\n@blog: https://www.zhihu.com/people/chang-shuo-59/activities\n\"\"\"\n\nfrom abc import ABCMeta\nfrom abc import abstractm...
false
7,365
c2dba981b0d628aebdf8cebfb890aad74a629b08
from enum import Enum from app.utilities.data import Prefab class Tags(Enum): FLOW_CONTROL = 'Flow Control' MUSIC_SOUND = 'Music/Sound' PORTRAIT = 'Portrait' BG_FG = 'Background/Foreground' DIALOGUE_TEXT = 'Dialogue/Text' CURSOR_CAMERA = 'Cursor/Camera' LEVEL_VARS = 'Level-wide Unlocks and ...
[ "from enum import Enum\nfrom app.utilities.data import Prefab\n\nclass Tags(Enum):\n FLOW_CONTROL = 'Flow Control'\n MUSIC_SOUND = 'Music/Sound'\n PORTRAIT = 'Portrait'\n BG_FG = 'Background/Foreground'\n DIALOGUE_TEXT = 'Dialogue/Text'\n CURSOR_CAMERA = 'Cursor/Camera'\n LEVEL_VARS = 'Level-wi...
false
7,366
4745d81558130440d35d277b586572f5d3f85c06
import unittest import userinput class Testing(unittest.TestCase): def test_creation(self): x = userinput.UserInput() self.assertNotEqual(x, None) def test_charset_initialization(self): x = userinput.UserInput() self.assertEqual(x.character_set, userinput.CHARACTERS) def ...
[ "import unittest\nimport userinput\n\n\nclass Testing(unittest.TestCase):\n def test_creation(self):\n x = userinput.UserInput()\n self.assertNotEqual(x, None)\n\n def test_charset_initialization(self):\n x = userinput.UserInput()\n self.assertEqual(x.character_set, userinput.CHARA...
false
7,367
e14b8d0f85042ceda955022bee08b3b3b4c2361d
# Generated by Django 3.0.8 on 2021-03-25 13:47 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Asha', '0005_baby'), ] operations = [ migrations.AlterField( model_name='baby', ...
[ "# Generated by Django 3.0.8 on 2021-03-25 13:47\r\n\r\nfrom django.db import migrations, models\r\nimport django.db.models.deletion\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('Asha', '0005_baby'),\r\n ]\r\n\r\n operations = [\r\n migrations.AlterField(\r\...
false
7,368
a0460b100a750b685f3e831a19379b0e26da4b35
# x = 10 # # def increment(): # x += 1 # # ^^ Non-working code x = 10 def increment(number): number += 1 return number # If we want to change a global variable, # we have to do it like this x = increment(x)
[ "# x = 10\n#\n# def increment():\n# x += 1\n# \n# ^^ Non-working code\n\nx = 10\n\ndef increment(number): \n number += 1\n return number\n\n# If we want to change a global variable,\n# we have to do it like this\nx = increment(x)", "x = 10\n\n\ndef increment(number):\n number += 1\n return number\n...
false
7,369
72b5e76f63e347d7275b0b711fa02b7f327785f6
#!/usr/bin/python import os import sys fdatadir = "/fdata/hepx/store/user/taohuang/NANOAOD/" datasets = []; NumSample = []; sampleN_short = [] Nanodatasets = []; localdirs = {} MCxsections = [] #doTT=True; doDY=True; doVV=True; doSingleT=True; doWjets=True; dottV=True ##DoubleEG datasets.append('/DoubleEG/Run2016B-0...
[ "#!/usr/bin/python\nimport os\nimport sys\n\nfdatadir = \"/fdata/hepx/store/user/taohuang/NANOAOD/\"\ndatasets = []; NumSample = []; sampleN_short = []\nNanodatasets = []; localdirs = {}\nMCxsections = []\n#doTT=True; doDY=True; doVV=True; doSingleT=True; doWjets=True; dottV=True\n\n##DoubleEG\ndatasets.append('/D...
true
7,370
975b2f3443e19f910c71f872484350aef9f09dd2
class Solution: def minimumDeviation(self, nums: List[int]) -> int: hq, left, right, res = [], inf, 0, inf for num in nums: if num % 2: num = num * 2 heapq.heappush(hq, -num) left = min(left, num) while True: right = -heapq.heap...
[ "class Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n hq, left, right, res = [], inf, 0, inf\n for num in nums:\n if num % 2:\n num = num * 2\n heapq.heappush(hq, -num)\n left = min(left, num)\n while True:\n right...
false
7,371
452d5d98b6c0b82a1f4ec18f29d9710a8c0f4dc9
""" This handy script will download all wallpapears from simpledesktops.com Requirements ============ BeautifulSoup - http://www.crummy.com/software/BeautifulSoup/ Python-Requests - http://docs.python-requests.org/en/latest/index.html Usage ===== cd /path/to/the/script/ python simpledesktops.py """ from StringIO imp...
[ "\"\"\"\nThis handy script will download all wallpapears from simpledesktops.com\n\nRequirements\n============\nBeautifulSoup - http://www.crummy.com/software/BeautifulSoup/\nPython-Requests - http://docs.python-requests.org/en/latest/index.html\n\nUsage\n=====\ncd /path/to/the/script/\npython simpledesktops.py\n\"...
true
7,372
7c3569c43d27ba605c0dba420690e18d7f849965
from django import forms from .models import User,Profile from django.contrib.auth.forms import UserCreationForm class ProfileForm(forms.ModelForm): ''' Form for the profile ''' class Meta: model = Profile exclude = ('user',) ## we will create the user with the signals class SignUpForm(Use...
[ "from django import forms\nfrom .models import User,Profile\nfrom django.contrib.auth.forms import UserCreationForm\n\n\nclass ProfileForm(forms.ModelForm):\n ''' Form for the profile '''\n class Meta:\n model = Profile\n exclude = ('user',) ## we will create the user with the signals\n\n\n\n\nc...
false
7,373
4dfdbc692858a627248cbe47d19b43c2a27ec70e
#!/usr/bin/env python # Core Library modules import os # Third party modules import nose # First party modules import lumixmaptool.copy as copy # Tests def get_parser_test(): """Check if the evaluation model returns a parser object.""" copy.get_parser() def parse_mapdata_test(): current_folder = os.p...
[ "#!/usr/bin/env python\n\n# Core Library modules\nimport os\n\n# Third party modules\nimport nose\n\n# First party modules\nimport lumixmaptool.copy as copy\n\n\n# Tests\ndef get_parser_test():\n \"\"\"Check if the evaluation model returns a parser object.\"\"\"\n copy.get_parser()\n\n\ndef parse_mapdata_test...
false
7,374
f15bb4ab93ecb2689bf74687852e60dfa98caea9
"""Project agnostic helper functions that could be migrated to and external lib. """
[ "\"\"\"Project agnostic helper functions that could be migrated to and external lib.\n\"\"\"\n", "<docstring token>\n" ]
false
7,375
0259fddbe3ce030030a508ce7118a6a03930aa51
from flask import Flask import os app = Flask(__name__) @app.route("/healthz") def healthz(): return "ok" @app.route("/alive") def alive(): return "ok" @app.route("/hello") # def healthz(): # introduces application crash bug def hello(): myhost = os.uname()[1] body = ("V1 - Hello World! - %s" % m...
[ "from flask import Flask\nimport os\n\napp = Flask(__name__)\n\n\n@app.route(\"/healthz\")\ndef healthz():\n return \"ok\"\n\n\n@app.route(\"/alive\")\ndef alive():\n return \"ok\"\n\n\n@app.route(\"/hello\")\n# def healthz(): # introduces application crash bug\ndef hello():\n myhost = os.uname()[1]\n b...
false
7,376
5c643dfce9cf7a9f774957ff4819d3be8ac4f1da
#list,for replacing element we use {a[0='']}:for adding element we use {append()} a=['somesh','aakash','sarika','datta','rudra','4mridula'] a[2] = 'nandini' a.append('sarika') print(a[2]) print(a)
[ "#list,for replacing element we use {a[0='']}:for adding element we use {append()}\r\na=['somesh','aakash','sarika','datta','rudra','4mridula']\r\na[2] = 'nandini'\r\na.append('sarika')\r\nprint(a[2])\r\nprint(a)\r\n", "a = ['somesh', 'aakash', 'sarika', 'datta', 'rudra', '4mridula']\na[2] = 'nandini'\na.append('...
false
7,377
7a920b3609bb29cd26b159b48290fa6978839416
def bullets(chunks): print("bullets") final_string = "Your list in latex can be created with the following command: \n" final_string += "> \\begin{itemize} \n" for e in chunks: print(final_string) final_string += f"> \item {e} \n" final_string += "> \end{itemize}" retur...
[ "def bullets(chunks):\n print(\"bullets\")\n final_string = \"Your list in latex can be created with the following command: \\n\"\n final_string += \"> \\\\begin{itemize} \\n\"\n \n for e in chunks:\n print(final_string)\n final_string += f\"> \\item {e} \\n\"\n \n final_string +=...
false
7,378
f8e287abc7e1a2af005aa93c25d95ce770e29bf9
from odoo import models, fields, api from datetime import datetime, timedelta from odoo import exceptions import logging import math _logger = logging.getLogger(__name__) class BillOfLading(models.Model): _name = 'freight.bol' _description = 'Bill Of Lading' _order = 'date_of_issue desc, writ...
[ "from odoo import models, fields, api\r\nfrom datetime import datetime, timedelta\r\nfrom odoo import exceptions\r\nimport logging\r\nimport math\r\n\r\n_logger = logging.getLogger(__name__)\r\n\r\n\r\nclass BillOfLading(models.Model):\r\n _name = 'freight.bol'\r\n _description = 'Bill Of Lading'\r\n _orde...
false
7,379
92d689e5caa2d8c65f86af0f8b49b009d162a783
from turtle import * from shapes import * #1- #1.triangle def eTriangle(): forward(100) right(120) forward(100) right(120) forward(100) right(120) mainloop() #2.square def square(): forward(100) right(90) forward(100) right(90) forward(100) right(90) forwa...
[ "from turtle import *\nfrom shapes import *\n#1-\n #1.triangle\ndef eTriangle():\n forward(100)\n right(120)\n forward(100)\n right(120)\n forward(100)\n right(120)\n mainloop()\n #2.square\ndef square():\n forward(100)\n right(90)\n forward(100)\n right(90)\n forward(100)\...
false
7,380
e4f194c3dbc3e1d62866343642e41fa1ecdeab93
#!/usr/bin/python3 import os, re import csv, unittest from langtag import langtag from sldr.iana import Iana langtagjson = os.path.join(os.path.dirname(__file__), '..', 'pub', 'langtags.json') bannedchars = list(range(33, 45)) + [47] + list(range(58, 63)) + [94, 96] def nonascii(s): cs = [ord(x) for x in s] i...
[ "#!/usr/bin/python3\n\nimport os, re\nimport csv, unittest\nfrom langtag import langtag\nfrom sldr.iana import Iana\n\nlangtagjson = os.path.join(os.path.dirname(__file__), '..', 'pub', 'langtags.json')\nbannedchars = list(range(33, 45)) + [47] + list(range(58, 63)) + [94, 96]\ndef nonascii(s):\n cs = [ord(x) fo...
false
7,381
6b3cb7a42c8bc665e35206b135f6aefea3439758
""" DB models. """ from sqlalchemy import Column, Integer, String, ForeignKey, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from db.session import map_engine, replay_engine MapBase = declarative_base(bind=map_engine) ReplayBase = declarative_base(bind=replay...
[ "\"\"\" DB models.\n\"\"\"\nfrom sqlalchemy import Column, Integer, String, ForeignKey, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\n\nfrom db.session import map_engine, replay_engine\n\nMapBase = declarative_base(bind=map_engine)\nReplayBase = declarat...
false
7,382
c6ab82d7f59faeee2a74e90a96c2348b046d0889
#Multiple Word Palindromes #Ex 72 extended word = input("Word: ") new = [] o = [] r = [] #canceling out the spaces for i in range(len(word)): if word[i] in ".,?!" or word[i] == ' ': pass else: new.append(word[i]) #original for i in range(len(new)): o.append(new[i]) #reverse for i in range(...
[ "#Multiple Word Palindromes\n#Ex 72 extended\n\nword = input(\"Word: \")\nnew = []\no = []\nr = []\n#canceling out the spaces\nfor i in range(len(word)):\n if word[i] in \".,?!\" or word[i] == ' ':\n pass\n else:\n new.append(word[i])\n\n#original\nfor i in range(len(new)):\n o.append(new[i])...
false
7,383
cdabb4a118cb0ef55c271a446fa190a457ebe142
#!/usr/bin/env python # -*- coding:utf-8 _*- """ :Author :weijinlong :Time: :2020/1/10 17:22 :File :graph.py :content: """ import tensorflow as tf from .base import TFLayer class TFModel(TFLayer): def build_model(self): raise NotImplementedError def add_outputs(self, *a...
[ "#!/usr/bin/env python\r\n# -*- coding:utf-8 _*-\r\n\r\n\"\"\"\r\n:Author :weijinlong\r\n:Time: :2020/1/10 17:22\r\n:File :graph.py\r\n:content:\r\n \r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\n\r\nfrom .base import TFLayer\r\n\r\n\r\nclass TFModel(TFLayer):\r\n\r\n def build_model(self):\r\n raise No...
false
7,384
401c6b09edf593e00aecf5bbb1b2201effc9e78c
# # @lc app=leetcode id=14 lang=python3 # # [14] Longest Common Prefix # # @lc code=start class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: pass # At the moment I just wanna test my workspace so it's working tomorrow it's time for the problems # @lc code=end
[ "#\n# @lc app=leetcode id=14 lang=python3\n#\n# [14] Longest Common Prefix\n#\n\n# @lc code=start\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n pass\n # At the moment I just wanna test my workspace so it's working tomorrow it's time for the problems\n \n# @lc code=e...
false
7,385
1dd09a09f542099091d94d466ebd7cc149884eb4
import time from junk.keyboard_non_blocking import NonBlockingKeyboard TICK_DURATION = 0.05 INITIAL_FOOD_LEVEL = 100 FOOD_PER_TICK = -1 FOOD_PER_FEED = 10 MAX_FOOD_LEVEL = 100 INITIAL_ENERGY_LEVEL = 50 ENERGY_PER_TICK_AWAKE = -1 ENERGY_PER_TICK_ASLEEP = 5 MAX_ENERGY_LEVEL = 100 INITIAL_IS_AWAKE = False INITIAL_PO...
[ "import time\n\nfrom junk.keyboard_non_blocking import NonBlockingKeyboard\n\nTICK_DURATION = 0.05\n\nINITIAL_FOOD_LEVEL = 100\nFOOD_PER_TICK = -1\nFOOD_PER_FEED = 10\nMAX_FOOD_LEVEL = 100\n\nINITIAL_ENERGY_LEVEL = 50\nENERGY_PER_TICK_AWAKE = -1\nENERGY_PER_TICK_ASLEEP = 5\nMAX_ENERGY_LEVEL = 100\n\nINITIAL_IS_AWAK...
false
7,386
70188d011ef60b1586864c4b85a9f9e70e5a4caf
from fastapi import FastAPI, Header, Cookie, Form, Request, requests, Body, Response, HTTPException, status, Path, Query from fastapi.responses import HTMLResponse from typing import Optional from fastapi.testclient import TestClient from typing import List, Callable from fastapi.staticfiles import StaticFiles from fas...
[ "from fastapi import FastAPI, Header, Cookie, Form, Request, requests, Body, Response, HTTPException, status, Path, Query\nfrom fastapi.responses import HTMLResponse\nfrom typing import Optional\nfrom fastapi.testclient import TestClient\nfrom typing import List, Callable\nfrom fastapi.staticfiles import StaticFile...
false
7,387
2d20bac0f11fa724b2d0a2e0676e5b9ce7682777
# -*- coding: utf-8 -*- # Copyright (c) 2018-2019 Linh Pham # wwdtm_panelistvspanelist is relased under the terms of the Apache License 2.0 """WWDTM Panelist Appearance Report Generator""" import argparse from collections import OrderedDict from datetime import datetime import json import os import shutil from typing ...
[ "# -*- coding: utf-8 -*-\n# Copyright (c) 2018-2019 Linh Pham\n# wwdtm_panelistvspanelist is relased under the terms of the Apache License 2.0\n\"\"\"WWDTM Panelist Appearance Report Generator\"\"\"\n\nimport argparse\nfrom collections import OrderedDict\nfrom datetime import datetime\nimport json\nimport os\nimpor...
false
7,388
5172819da135600d0764033a85a4175098274806
import numpy as np import pandas as pd import datetime import time from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import cross_val_score from sklearn import preprocessing from sklearn.model...
[ "import numpy as np\nimport pandas as pd\nimport datetime\nimport time\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import preprocessing\nfrom...
false
7,389
ec0113dbd79e936e614bb7ee7e48d29aa616d511
num=int(input()) i=10 while i>=1: print(i,end=" ") i-=1
[ "num=int(input())\r\ni=10\r\nwhile i>=1:\r\n print(i,end=\" \")\r\n i-=1\r\n", "num = int(input())\ni = 10\nwhile i >= 1:\n print(i, end=' ')\n i -= 1\n", "<assignment token>\nwhile i >= 1:\n print(i, end=' ')\n i -= 1\n", "<assignment token>\n<code token>\n" ]
false
7,390
e9a1fd8464f6c1e65aa2c1af60becbfcbf050814
import tensorflow as tf import numpy as np import tensorflow.contrib.layers as layers class Model(object): def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10, keep_prob=0.5, scope="model"): self._batch_size = batch_size self._learning_rate = learning_rate self._num_labels ...
[ "import tensorflow as tf\nimport numpy as np\nimport tensorflow.contrib.layers as layers\n\nclass Model(object):\n def __init__(self, batch_size=128, learning_rate=0.01, num_labels=10, keep_prob=0.5, scope=\"model\"):\n self._batch_size = batch_size\n self._learning_rate = learning_rate\n se...
false
7,391
34a456efc72b303aed5f722bb415d30ff62addab
import numpy as np import argparse import torch from gridworlds.envs import GridWorldEnv, generate_obs_dict from gridworlds.constants import possible_objects import nengo_spa as spa from collections import OrderedDict from spatial_semantic_pointers.utils import encode_point, ssp_to_loc, get_heatmap_vectors import mat...
[ "import numpy as np\nimport argparse\nimport torch\nfrom gridworlds.envs import GridWorldEnv, generate_obs_dict\nfrom gridworlds.constants import possible_objects\n\nimport nengo_spa as spa\nfrom collections import OrderedDict\nfrom spatial_semantic_pointers.utils import encode_point, ssp_to_loc, get_heatmap_vector...
false
7,392
1af9fb91e69ea78709c47fca6b12e4f7a6fd17a8
import unittest import os import tempfile import numpy as np from keras_piecewise.backend import keras from keras_piecewise import Piecewise2D from .util import MaxPool2D class TestPool2D(unittest.TestCase): @staticmethod def _build_model(input_shape, layer, row_num, col_num, pos_type=Piecewise2D.POS_TYPE_SE...
[ "import unittest\nimport os\nimport tempfile\nimport numpy as np\nfrom keras_piecewise.backend import keras\nfrom keras_piecewise import Piecewise2D\nfrom .util import MaxPool2D\n\n\nclass TestPool2D(unittest.TestCase):\n\n @staticmethod\n def _build_model(input_shape, layer, row_num, col_num, pos_type=Piecew...
false
7,393
096d82e1f9e8832f6605d23c8bb324e045b6b14f
## Script (Python) "after_rigetta" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=state_change ##title= ## doc = state_change.object #Aggiornamento dello stato su plominoDocument doc.updateStatus() if script.run_script(doc, script....
[ "## Script (Python) \"after_rigetta\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=state_change\n##title=\n##\ndoc = state_change.object\n\n#Aggiornamento dello stato su plominoDocument\ndoc.updateStatus()\n\nif script.ru...
false
7,394
303d56c18cce922ace45de1b8e195ebfdd874e23
class product(object): def __init__(self, item_name, price, weight, brand, status = "for sale"): self.item_name = item_name self.price = price self.weight = weight self.brand = brand self.cost = price self.status = status self.displayInfo() def displayInfo...
[ "class product(object):\n def __init__(self, item_name, price, weight, brand, status = \"for sale\"):\n self.item_name = item_name\n self.price = price\n self.weight = weight\n self.brand = brand\n self.cost = price\n self.status = status\n self.displayInfo()\n ...
true
7,395
a538c6d8c9f99bc37def5817a54c831393c051f3
#!/usr/bin/python try: fh = open('testfile','w') try: fh.write('This is my test file for this exception') finally: print "Going to close file" fh.close() except IOError: print" Error: can\'t find file or read data"
[ "#!/usr/bin/python\n\n\ntry:\n fh = open('testfile','w')\n try:\n fh.write('This is my test file for this exception')\n finally:\n print \"Going to close file\"\n fh.close()\n\nexcept IOError:\n print\" Error: can\\'t find file or read data\"\n" ]
true
7,396
582cbacd26f4a3ed0b4f5c85af67758de7c05836
### To run the test use: ### python3 -m unittest test_script.py import unittest import re class TestCustomerDetails(unittest.TestCase): def test_cu_name(self): ### Our script has a class ConfigurationParser, which will have method ParseCuNames cp = ConfigurationParser() ### expected nam...
[ "### To run the test use:\n### python3 -m unittest test_script.py\nimport unittest\nimport re\n\n\nclass TestCustomerDetails(unittest.TestCase):\n def test_cu_name(self):\n ### Our script has a class ConfigurationParser, which will have method ParseCuNames\n cp = ConfigurationParser()\n #...
false
7,397
0ebd3ca5fd29b0f2f2149dd162b37f39668f1c58
from xgboost import XGBRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import pandas as pd import numpy as np from ghg import GHGPredictor predictor = GHGPredictor() dataset_df = pd.read_csv("db-wheat.csv", index_col=0) # print(dataset_df.iloc[1]) dataset_d...
[ "from xgboost import XGBRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport pandas as pd\nimport numpy as np\n\nfrom ghg import GHGPredictor\n\npredictor = GHGPredictor()\n\ndataset_df = pd.read_csv(\"db-wheat.csv\", index_col=0)\n\n# print(dataset_df....
false
7,398
7af19f69e6c419649a5999f594118ad13833a537
# -*- coding: utf-8 -*- """ Created on Mon Aug 13 14:10:15 2018 9.5 项目:将一个文件夹备份到一个 ZIP 文件 @author: NEVERGUVEIP """ #! python3 import zipfile,os def backupToZip(folder): #backup the entire contents of 'folder' into a ZIP file folder = os.path.abspath(folder) os.chdir(folder) #figure out the fil...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 13 14:10:15 2018\n9.5 项目:将一个文件夹备份到一个 ZIP 文件 \n\n@author: NEVERGUVEIP\n\"\"\"\n#! python3\n\nimport zipfile,os\n\ndef backupToZip(folder):\n #backup the entire contents of 'folder' into a ZIP file\n \n folder = os.path.abspath(folder)\n os.chdir(folde...
false
7,399
d39965c3070ec25230b4d6977ff949b3db070ab6
""" Add requests application (adding and managing add-requests) """ from flask import Blueprint __author__ = 'Xomak' add_requests = Blueprint('addrequests', __name__, template_folder='templates', ) from . import routes
[ "\"\"\"\nAdd requests application (adding and managing add-requests)\n\"\"\"\n\nfrom flask import Blueprint\n\n__author__ = 'Xomak'\n\nadd_requests = Blueprint('addrequests', __name__, template_folder='templates', )\n\nfrom . import routes", "<docstring token>\nfrom flask import Blueprint\n__author__ = 'Xomak'\na...
false