index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
7,800
63f155f7da958e9b6865007c701f7cf986b0cbac
# -*- coding: utf-8 -*- """ Created on Tue Mar 24 12:16:15 2020 @author: zhangjuefei """ import sys sys.path.append('../..') import numpy as np from sklearn.datasets import fetch_openml from sklearn.preprocessing import OneHotEncoder import matrixslow as ms # 加载MNIST数据集,取一部分样本并归一化 X, y = fetch_openml('mnist_784', v...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 24 12:16:15 2020\n\n@author: zhangjuefei\n\"\"\"\n\nimport sys\nsys.path.append('../..')\n\nimport numpy as np\nfrom sklearn.datasets import fetch_openml\nfrom sklearn.preprocessing import OneHotEncoder\nimport matrixslow as ms\n\n# 加载MNIST数据集,取一部分样本并归一化\nX, y = ...
false
7,801
881afd6877508243fa5056d2a82d88ba69ffb8c0
from graphviz import Digraph from math import log2, ceil def hue_to_rgb(p, q, t): if t < 0: t += 1 if t > 1: t -= 1 if t < 1/6: return p + (q - p) * 6 * t if t < 1/2: return q if t < 2/3: return p + (q - p) * (2/3 - t) * 6 return p def hsl_to_rgb(h, s, l): h /= 360 q = l * (1 + s) if l...
[ "from graphviz import Digraph\nfrom math import log2, ceil\n\ndef hue_to_rgb(p, q, t):\n if t < 0: t += 1\n if t > 1: t -= 1\n if t < 1/6: return p + (q - p) * 6 * t\n if t < 1/2: return q\n if t < 2/3: return p + (q - p) * (2/3 - t) * 6\n return p\n\ndef hsl_to_rgb(h, s, l):\n h /= 360\n q ...
false
7,802
a5dff32dfbe93ba081144944381b96940da541ad
# Generated by Django 2.0.5 on 2019-06-12 08:03 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('doctor', '0257_merge_20190524_1533'), ('doctor', '0260_merge_20190604_1428'), ] operations = [ ]
[ "# Generated by Django 2.0.5 on 2019-06-12 08:03\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('doctor', '0257_merge_20190524_1533'),\n ('doctor', '0260_merge_20190604_1428'),\n ]\n\n operations = [\n ]\n", "from django.db import ...
false
7,803
9cfbb06df4bc286ff56983d6e843b33e4da6ccf8
""" Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center). Example 1: Input: root = [1, 2, 2, 3, 4, 4, 3] Output: true 1 / \ 2 2 / \ / \ 3 4 4 3 Example 2: Input: root = [1, 2, 2, None, 3, None, 3] Output: false 1 / ...
[ "\"\"\"\nGiven the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).\n\nExample 1:\n\nInput: root = [1, 2, 2, 3, 4, 4, 3]\nOutput: true\n\n 1\n / \\\n 2 2\n / \\ / \\\n 3 4 4 3\n\nExample 2:\nInput: root = [1, 2, 2, None, 3, None, 3]\...
false
7,804
b63dc8b9aa2f0593a4a7eb52a722a9c4da6c9e08
import pandas as pd from pandas import Series, DataFrame def load_excel( data_path, data_name, episode_Num): data_name = data_name + str(episode_Num)+'.xlsx' dataframe = pd.read_excel(data_path + data_name,index_col=0) return dataframe def dataframe_to_numpy(dataframe): numpy_array = dataframe.to_nump...
[ "import pandas as pd\nfrom pandas import Series, DataFrame\n\ndef load_excel( data_path, data_name, episode_Num):\n data_name = data_name + str(episode_Num)+'.xlsx'\n dataframe = pd.read_excel(data_path + data_name,index_col=0)\n return dataframe\n\ndef dataframe_to_numpy(dataframe):\n numpy_array = dat...
false
7,805
8a1f024be00200218782c919b21161bf48fc817e
# from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models # from applications.models import ApplicationReview # from profiles.models import Restaurant, Program, Courier # Enum f...
[ "# from django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager\nfrom django.db import models\n\n# from applications.models import ApplicationReview\n# from profiles.models import Restaurant, Program, Courier\n\...
false
7,806
c967aa647a97b17c9a7493559b9a1577dd95263a
# -*- coding: utf-8 -*- import math # 冒泡排序(Bubble Sort) # 比较相邻的元素。如果第一个比第二个大,就交换它们两个; # 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数; # 针对所有的元素重复以上的步骤,除了最后一个; # 重复步骤1~3,直到排序完成。 # 冒泡排序总的平均时间复杂度为:O(n^2) def bubble_sort(input): print("\nBubble Sort") input_len = len(input) print("length of input: %d" % i...
[ "# -*- coding: utf-8 -*-\nimport math\n\n\n# 冒泡排序(Bubble Sort)\n# 比较相邻的元素。如果第一个比第二个大,就交换它们两个;\n# 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样在最后的元素应该会是最大的数;\n# 针对所有的元素重复以上的步骤,除了最后一个;\n# 重复步骤1~3,直到排序完成。\n# 冒泡排序总的平均时间复杂度为:O(n^2)\n\n\ndef bubble_sort(input):\n print(\"\\nBubble Sort\")\n input_len = len(input)\n print(\"...
false
7,807
bef16443f77b2c1e09db9950a4617703085d9f71
import datetime import numpy as np import tensorflow as tf from alphai_time_series.performance_trials.performance import Metrics import alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval import alphai_cromulon_oracle.cromulon.train as crocubot_train from alphai_cromulon_oracle.cromulon.helpers import Tensorfl...
[ "import datetime\n\nimport numpy as np\nimport tensorflow as tf\nfrom alphai_time_series.performance_trials.performance import Metrics\n\nimport alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval\nimport alphai_cromulon_oracle.cromulon.train as crocubot_train\n\nfrom alphai_cromulon_oracle.cromulon.helpers i...
false
7,808
8bc465a1b546907d8a9e5eee2cae672befb1ea13
n = int(input()) b = 0 p = [0,0] flg = True for i in range(n): t,x,y = map(int,input().split()) diff = abs(x - p[0]) + abs(y - p[1]) time = t - b if(diff > time or time%2 != diff %2): flg = False break else: b = t p[0] = x p[1] = y if flg: print("Yes") else: print("No")
[ "n = int(input())\n\nb = 0\np = [0,0]\n\nflg = True\n\n\n\nfor i in range(n):\n t,x,y = map(int,input().split())\n\n diff = abs(x - p[0]) + abs(y - p[1])\n time = t - b\n if(diff > time or time%2 != diff %2):\n flg = False\n break\n else:\n b = t\n p[0] = x\n p[1] = y\n\nif flg:\n print(\"Yes\"...
false
7,809
f9d8280d765826b05bfa7989645e487431799f85
from flask import Flask from flask_script import Manager app = Flask(__name__) manager = Manager(app) @app.route('/') def index(): return '2018/6/1 hello python' @app.route('/news') def news(): return '内蒙古新闻资讯,请选择浏览' if __name__ == '__main__': manager.run()
[ "from flask import Flask\nfrom flask_script import Manager\n\napp = Flask(__name__)\n\nmanager = Manager(app)\n\n@app.route('/')\ndef index():\n return '2018/6/1 hello python'\n\n@app.route('/news')\ndef news():\n return '内蒙古新闻资讯,请选择浏览'\n\nif __name__ == '__main__':\n manager.run()\n\n", "from flask impo...
false
7,810
f73a316b6020908472e35a7b78959a9bda6e8e56
# 导包 from time import sleep from selenium import webdriver # 实例化浏览器 driver = webdriver.Firefox() # 打开页面 driver.get(r"F:\BaiduYunDownload\webdriverspace\sources\注册实例.html") driver.maximize_window() sleep(2) # 定位注册A按钮并点击 driver.find_element_by_link_text("注册A网页").click() # 获取当前敞口句柄 current_handle = driver.current_windo...
[ "# 导包\nfrom time import sleep\nfrom selenium import webdriver\n\n# 实例化浏览器\ndriver = webdriver.Firefox()\n# 打开页面\ndriver.get(r\"F:\\BaiduYunDownload\\webdriverspace\\sources\\注册实例.html\")\ndriver.maximize_window()\nsleep(2)\n\n# 定位注册A按钮并点击\ndriver.find_element_by_link_text(\"注册A网页\").click()\n\n# 获取当前敞口句柄\ncurrent_h...
false
7,811
0547751af7bbac42351476dde591d13d40fb37eb
#!/usr/bin/env python """ Otsu method for automatic estimation of $T$ threshold value - assumes two maxima of grayscale histogram & searches for optimal separation Parameters Usage Example $ python <scriptname>.py --image ../img/<filename>.png ## Explain """ import numpy as np import argparse import mahota...
[ "#!/usr/bin/env python\n\"\"\"\nOtsu method for automatic estimation of $T$ threshold value\n - assumes two maxima of grayscale histogram & searches for optimal separation\n\nParameters\n\nUsage\n\nExample\n $ python <scriptname>.py --image ../img/<filename>.png\n\n## Explain\n\n\"\"\"\nimport numpy as np\nim...
false
7,812
03284f20e614a5f8f5c21939acf49490d6ffd3a3
import json startTime = "" endTime = "" controller = 0 for files in range(30): file = open("NewResults" + str(files+1) + ".data") for line in file: if line != "\n": j = json.loads(line) if controller == 0: startTime = j['metrics'][0]['startTime'] helper = startTime.split(" ") hour = helper[1].sp...
[ "import json\n\nstartTime = \"\"\nendTime = \"\"\n\ncontroller = 0\nfor files in range(30):\n\tfile = open(\"NewResults\" + str(files+1) + \".data\")\n\tfor line in file:\n\t\tif line != \"\\n\":\n\t\t\tj = json.loads(line)\n\t\t\tif controller == 0:\n\t\t\t\tstartTime = j['metrics'][0]['startTime']\n\t\t\t\thelper...
false
7,813
a1b0e72b62abc89d5292f199ec5b6193b544e271
DEBUG = True SQLALCHEMY_DATABASE_URI = "postgresql://username:password@IPOrDomain/databasename" SQLALCHEMY_TRACK_MODIFICATIONS = True DATABASE_CONNECT_OPTIONS = {} THREADS_PER_PAGE = 2
[ "DEBUG = True\nSQLALCHEMY_DATABASE_URI = \"postgresql://username:password@IPOrDomain/databasename\"\n\nSQLALCHEMY_TRACK_MODIFICATIONS = True\nDATABASE_CONNECT_OPTIONS = {}\nTHREADS_PER_PAGE = 2\n", "DEBUG = True\nSQLALCHEMY_DATABASE_URI = (\n 'postgresql://username:password@IPOrDomain/databasename')\nSQLALCHEM...
false
7,814
1c685514f53a320226402a4e4d8f3b3187fad615
import uuid from datetime import date import os import humanize class Context: def __init__(self, function_name, function_version): self.function_name = function_name self.function_version = function_version self.invoked_function_arn = "arn:aws:lambda:eu-north-1:000000000000:function:{}".f...
[ "import uuid\nfrom datetime import date\nimport os\nimport humanize\n\n\nclass Context:\n def __init__(self, function_name, function_version):\n self.function_name = function_name\n self.function_version = function_version\n self.invoked_function_arn = \"arn:aws:lambda:eu-north-1:00000000000...
false
7,815
cdbc7d703da69adaef593e6a505be25d78beb7ce
import numpy as np class EdgeListError(ValueError): pass def check_edge_list(src_nodes, dst_nodes, edge_weights): """Checks that the input edge list is valid.""" if len(src_nodes) != len(dst_nodes): raise EdgeListError("src_nodes and dst_nodes must be of same length.") if edge_weights is N...
[ "import numpy as np\n\n\nclass EdgeListError(ValueError):\n pass\n\n\ndef check_edge_list(src_nodes, dst_nodes, edge_weights):\n \"\"\"Checks that the input edge list is valid.\"\"\"\n\n if len(src_nodes) != len(dst_nodes):\n raise EdgeListError(\"src_nodes and dst_nodes must be of same length.\")\n...
false
7,816
4c5b3042a785342d6ef06fdc882e0dcf91a787c3
from datetime import date import config import datetime import numpy import pandas import data_sources from data_sources import POPULATION, convert_to_ccaa_iso import material_line_chart import ministry_datasources HEADER = '''<html> <head> <title>{}</title> <script type="text/javascript" src="https://w...
[ "\nfrom datetime import date\nimport config\n\nimport datetime\n\nimport numpy\nimport pandas\n\nimport data_sources\nfrom data_sources import POPULATION, convert_to_ccaa_iso\nimport material_line_chart\nimport ministry_datasources\n\n\nHEADER = '''<html>\n <head>\n <title>{}</title>\n <script type=\"text/ja...
false
7,817
907f0564d574f197c25b05a79569a8b6f260a8cd
import math from os.path import join, relpath, dirname from typing import List, Tuple from common import read_input convert_output = List[str] class GridWalker: def __init__(self): self._current_pos = [0, 0] self._heading = math.pi / 2 @property def position(self): return self....
[ "import math\nfrom os.path import join, relpath, dirname\nfrom typing import List, Tuple\nfrom common import read_input\n\n\nconvert_output = List[str]\n\n\nclass GridWalker:\n def __init__(self):\n\n self._current_pos = [0, 0]\n self._heading = math.pi / 2\n\n @property\n def position(self):...
false
7,818
5b7567129d447ae2b75f4a8f9c26127f8b7553ec
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' #app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True; #db = SQLAlchemy(app) # MONGODB CREATION #Creating a pymongo client client = MongoClient('localhost', 27017) #Getting the database instance db = client['mydb'] print("Database created........") #Verif...
[ "#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'\n#app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True;\n#db = SQLAlchemy(app)\n\n\n# MONGODB CREATION\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\nprint(\"Database created....
false
7,819
772e2e0a442c1b63330e9b526b76d767646b0c7c
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsOpacityEffect, \ QPushButton from PyQt5.QtCore import Qt class ToolBar(QWidget): """ Window for entering parameters """ def __init__(self, parent): super().__init__(parent) self._main_wnd = parent self.setAttribut...
[ "from PyQt5.QtWidgets import QWidget, QHBoxLayout, QGraphicsOpacityEffect, \\\n QPushButton\nfrom PyQt5.QtCore import Qt\n\n\nclass ToolBar(QWidget):\n \"\"\"\n Window for entering parameters\n \"\"\"\n\n def __init__(self, parent):\n super().__init__(parent)\n self._main_wnd = parent\n...
false
7,820
243794d36a1c6861c2c3308fe6a52ec19b73df72
"""Activate coverage at python startup if appropriate. The python site initialisation will ensure that anything we import will be removed and not visible at the end of python startup. However we minimise all work by putting these init actions in this separate module and only importing what is needed when needed. For...
[ "\"\"\"Activate coverage at python startup if appropriate.\n\nThe python site initialisation will ensure that anything we import\nwill be removed and not visible at the end of python startup. However\nwe minimise all work by putting these init actions in this separate\nmodule and only importing what is needed when...
false
7,821
d47ea763ac1a4981fc5dee67cd396ad49570f923
#coding=utf-8 from numpy import * #代码5-1,Logistic回归梯度上升优化算法。 def loadDataSet(): """解析文件 Return: dataMat 文档列表 [[1,x1,x2]...]; labelMat 类别标签列表[1,0,1...] @author:VPrincekin """ dataMat = []; labelMat= [] fr = open('testSet.txt') #每行前两个分别是X1和X2,第三个只是数据对应的类别 for line in fr.readlines(): ...
[ "#coding=utf-8\nfrom numpy import *\n\n#代码5-1,Logistic回归梯度上升优化算法。\ndef loadDataSet():\n \"\"\"解析文件\n Return: dataMat 文档列表 [[1,x1,x2]...]; labelMat 类别标签列表[1,0,1...]\n @author:VPrincekin\n \"\"\"\n dataMat = []; labelMat= []\n fr = open('testSet.txt')\n #每行前两个分别是X1和X2,第三个只是数据对应的类别\n for line ...
false
7,822
e0fbb5ad6d822230865e34c1216b355f700e5cec
from bisect import bisect_left as bisect while True: xp, yp = set(), set() veneer = [] W, H = map(int, input().split()) if not W: break N = int(input()) for i in range(N): x1, y1, x2, y2 = map(int, input().split()) veneer.append((x1, y1, x2, y2)) xp.add(x1) ...
[ "from bisect import bisect_left as bisect\nwhile True:\n xp, yp = set(), set()\n veneer = []\n W, H = map(int, input().split())\n if not W:\n break\n N = int(input())\n for i in range(N):\n x1, y1, x2, y2 = map(int, input().split())\n veneer.append((x1, y1, x2, y2))\n x...
false
7,823
34009d1aa145f4f5c55d0c5f5945c3793fbc6429
with open('vocabulary.txt', 'r') as f: for line in f: information = line.strip().split(': ') # print(information[0], information[1]) question = information[1] answer = information[0] my_answer = input(f'{question}:') if my_answer == answer: print('맞았습니다!'...
[ "with open('vocabulary.txt', 'r') as f:\n for line in f:\n information = line.strip().split(': ')\n # print(information[0], information[1])\n question = information[1]\n answer = information[0]\n\n my_answer = input(f'{question}:')\n if my_answer == answer:\n ...
false
7,824
b1a6593e7b528238e7be5ea6da4d1bfee0d78067
import serial import mysql.connector ser = serial.Serial('/dev/serial0', 9600) while True: data = ser.readline() if data[0]==";": print(data) data = data.split(";") if data[1] == "1": fonction = data[1] add = data[2] tmp = data[3] debit = data[4] ser.write([123]) #test affichage print "Sa...
[ "import serial\nimport mysql.connector\n\nser = serial.Serial('/dev/serial0', 9600)\n\nwhile True:\n\tdata = ser.readline()\n\tif data[0]==\";\":\n\t\tprint(data)\n\t\tdata = data.split(\";\")\n\t\tif data[1] == \"1\":\n\t\t\tfonction = data[1]\n\t\t\tadd = data[2]\n\t\t\ttmp = data[3]\n\t\t\tdebit = data[4]\n\t\t\...
true
7,825
0509afdce0d28cc04f4452472881fe9c5e4fbcc4
from rest_framework import serializers from .models import * class MovieSerializer(serializers.Serializer): movie_name = serializers.ListField(child=serializers.CharField()) class FilmSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__'
[ "from rest_framework import serializers\nfrom .models import *\n\nclass MovieSerializer(serializers.Serializer):\n movie_name = serializers.ListField(child=serializers.CharField())\n\n\nclass FilmSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Movie\n fields = '__all__'", "f...
false
7,826
c02f46e8d89dd4b141c86df461ecbb8ed608b61b
#!/usr/bin/python import gzip import os infiles = [] ids=[] ages=[] with open('all_C_metadata.txt') as f: f.readline() f.readline() for line in f: infiles.append(line.split('\t')[0]) ids.append(line.split('\t')[1]) ages.append(line.split('\t')[2]) with open('all_C_samples/diversi...
[ " #!/usr/bin/python\n\nimport gzip\nimport os\n\ninfiles = []\nids=[]\nages=[]\nwith open('all_C_metadata.txt') as f:\n f.readline()\n f.readline()\n for line in f:\n infiles.append(line.split('\\t')[0])\n ids.append(line.split('\\t')[1])\n ages.append(line.split('\\t')[2])\n\nwith ope...
true
7,827
bf98e81c160d13b79ebe9d6f0487b57ad64d1322
""" Author: Le Bui Ngoc Khang Date: 12/07/1997 Program: Write a script that inputs a line of plaintext and a distance value and outputs an encrypted text using a Caesar cipher. The script should work for any printable characters. Solution: Enter a message: hello world Enter distance value: 3 khoor#zruog """ # Reque...
[ "\"\"\"\nAuthor: Le Bui Ngoc Khang\nDate: 12/07/1997\nProgram: Write a script that inputs a line of plaintext and a distance value and outputs an encrypted text using\na Caesar cipher. The script should work for any printable characters.\n\nSolution:\n\nEnter a message: hello world\nEnter distance value: 3\nkhoor#z...
false
7,828
b164dc8183c0dc460aa20883553fc73acd1e45ec
def count_singlekey(inputDict, keyword): # sample input # inputDict = { # abName1: { dna: 'atgc', protein: 'x' } # abName2: { dna: 'ctga', protein: 'y' } # } countDict = {} for abName, abInfo in inputDict.iteritems(): if countDict.has_key(abInfo[keyword]): countDict[abInfo[keyword]...
[ "def count_singlekey(inputDict, keyword):\n # sample input\n # inputDict = {\n # abName1: { dna: 'atgc', protein: 'x' }\n # abName2: { dna: 'ctga', protein: 'y' }\n # }\n\n countDict = {}\n for abName, abInfo in inputDict.iteritems():\n if countDict.has_key(abInfo[keyword]):\n countDict[...
false
7,829
f6e0215f9992ceab51887aab6a19f58a5d013eb4
from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse class CampaignNegativeKeywords(Client): @sp_endpoint('/v2/sp/campaignNegativeKeywords/{}', method='GET') def get_campaign_negative_keyword(self, keywordId, **kwargs) -> ApiResponse: r""" get_campaign_negative_keyword(...
[ "from ad_api.base import Client, sp_endpoint, fill_query_params, ApiResponse\n\nclass CampaignNegativeKeywords(Client):\n\n @sp_endpoint('/v2/sp/campaignNegativeKeywords/{}', method='GET')\n def get_campaign_negative_keyword(self, keywordId, **kwargs) -> ApiResponse:\n r\"\"\"\n\n get_campaign_n...
false
7,830
d99fd3dc63f6a40dde5a6230111b9f3598d3c5fd
from torchvision import datasets, transforms import torch def load_data(data_folder, batch_size, train, num_workers=0, **kwargs): transform = { 'train': transforms.Compose( [transforms.Resize([256, 256]), transforms.RandomCrop(224), transforms.RandomHorizontalFli...
[ "from torchvision import datasets, transforms\nimport torch\n\ndef load_data(data_folder, batch_size, train, num_workers=0, **kwargs):\n transform = {\n 'train': transforms.Compose(\n [transforms.Resize([256, 256]),\n transforms.RandomCrop(224),\n transforms.Random...
false
7,831
04822e735c9c27f0e0fcc9727bcc38d2da84dee6
import logging from django.contrib.auth import get_user_model from django.db import models from rest_framework import serializers from rest_framework.test import APITestCase from ..autodocs.docs import ApiDocumentation from .utils import Deferred log = logging.getLogger(__name__) def get_serializer(endpoint, met...
[ "import logging\n\nfrom django.contrib.auth import get_user_model\nfrom django.db import models\n\nfrom rest_framework import serializers\nfrom rest_framework.test import APITestCase\n\nfrom ..autodocs.docs import ApiDocumentation\n\nfrom .utils import Deferred\n\nlog = logging.getLogger(__name__)\n\n\ndef get_seri...
false
7,832
e15ea7d167aad470d0a2d95a8a328b35181e4dc3
############################################################################## # Copyright by The HDF Group. # # All rights reserved. # # # # Th...
[ "##############################################################################\n# Copyright by The HDF Group. #\n# All rights reserved. #\n# ...
false
7,833
4ecd756b94b0cbab47a8072e9bccf26e2dd716d0
import pytest import numpy as np from GSPA_DMC import SymmetrizeWfn as symm def test_swap(): cds = np.load('h3o_data/ffinal_h3o.npy') dws = np.load('h3o_data/ffinal_h3o_dw.npy') cds = cds[:10] a = symm.swap_two_atoms(cds, dws, atm_1=1,atm_2=2) b = symm.swap_group(cds, dws, atm_list_1=[0,1],atm_lis...
[ "import pytest\nimport numpy as np\nfrom GSPA_DMC import SymmetrizeWfn as symm\n\n\ndef test_swap():\n cds = np.load('h3o_data/ffinal_h3o.npy')\n dws = np.load('h3o_data/ffinal_h3o_dw.npy')\n cds = cds[:10]\n a = symm.swap_two_atoms(cds, dws, atm_1=1,atm_2=2)\n b = symm.swap_group(cds, dws, atm_list_...
false
7,834
d218b72d1992a30ad07a1edca1caf04b7b1985f6
from introduction import give_speech from staring import stare_at_people from dow_jones import visualize_dow_jones from art_critic import give_art_critiques from hipster import try_hipster_social_interaction from empathy import share_feelings_with_everyone from slapstick import perform_slapstick_humor from ending impor...
[ "from introduction import give_speech\nfrom staring import stare_at_people\nfrom dow_jones import visualize_dow_jones\nfrom art_critic import give_art_critiques\nfrom hipster import try_hipster_social_interaction\nfrom empathy import share_feelings_with_everyone\nfrom slapstick import perform_slapstick_humor\nfrom ...
false
7,835
7edd833103e1de92e57559c8a75379c26266963b
# -*- encoding: utf-8 -*- from openerp.tests.common import TransactionCase from openerp.exceptions import ValidationError class GlobalTestOpenAcademySession(TransactionCase): ''' Global Test to openacademy session model. Test create session and trigger constraint ''' # Pseudo-constructor methods...
[ "# -*- encoding: utf-8 -*-\n\nfrom openerp.tests.common import TransactionCase\nfrom openerp.exceptions import ValidationError\n\n\nclass GlobalTestOpenAcademySession(TransactionCase):\n '''\n Global Test to openacademy session model.\n Test create session and trigger constraint\n '''\n\n # Pseudo-co...
false
7,836
94e9e7c4c09c8c4de4c8f2649707a949d5f5f856
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models import Max from django.core.validators import RegexValidator from django.utils import timezone class User(AbstractUser): is_developer = models.BooleanField('developer status', default=False) is_marketing = mo...
[ "from django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom django.db.models import Max\nfrom django.core.validators import RegexValidator\nfrom django.utils import timezone\n\nclass User(AbstractUser):\n is_developer = models.BooleanField('developer status', default=False)\n is_m...
false
7,837
8c055816def1c0a19e672ab4386f9b9a345b6323
#!/usr/bin/env python # -*- coding: utf-8 -*- import cProfile import re import pstats import os import functools # cProfile.run('re.compile("foo|bar")') def do_cprofile(filename): """ decorator for function profiling :param filename: :return: """ def wrapper(func): @functools.wraps...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport cProfile\nimport re\nimport pstats\nimport os\nimport functools\n\n\n# cProfile.run('re.compile(\"foo|bar\")')\n\ndef do_cprofile(filename):\n \"\"\"\n decorator for function profiling\n :param filename: \n :return: \n \"\"\"\n\n def wrapper(...
false
7,838
9f31694d80f2dcc50a76b32aa296871694d3644d
from machine import Pin, PWM import time # externe LED zit op pin D1 (GPIO5) PinNum = 5 # pwm initialisatie pwm1 = PWM(Pin(PinNum)) pwm1.freq(60) pwm1.duty(0) step = 100 for i in range(10): # oplichten while step < 1000: pwm1.duty(step) time.sleep_ms(500) step+=100 # uitdoven ...
[ "from machine import Pin, PWM\nimport time\n\n# externe LED zit op pin D1 (GPIO5)\nPinNum = 5\n\n# pwm initialisatie\npwm1 = PWM(Pin(PinNum))\npwm1.freq(60)\npwm1.duty(0)\n\nstep = 100\nfor i in range(10):\n # oplichten\n while step < 1000:\n pwm1.duty(step)\n time.sleep_ms(500)\n step+=1...
false
7,839
dd95d14f35b6a92b3363d99a616678da18733a61
import os import redis class Carteiro(): if os.environ.get("REDIS_URL") != None: redis_pool = redis.ConnectionPool.from_url(os.environ.get("REDIS_URL")) else: redis_pool = '' def __init__(self, id, pacote): if os.environ.get("REDIS_URL") != None: self.redis_bd ...
[ "import os\nimport redis\n\nclass Carteiro():\n\n if os.environ.get(\"REDIS_URL\") != None:\n redis_pool = redis.ConnectionPool.from_url(os.environ.get(\"REDIS_URL\"))\n else:\n redis_pool = ''\n \n def __init__(self, id, pacote):\n if os.environ.get(\"REDIS_URL\") != None:\n ...
false
7,840
3fe98c865632c75c0ba0e1357379590f072bf662
../pyline/pyline.py
[ "../pyline/pyline.py" ]
true
7,841
44d9e628e31cdb36088b969da2f6e9af1b1d3efe
from collections import Counter from copy import deepcopy from itertools import count from traceback import print_exc #https://www.websudoku.com/?level=4 class SudukoBoard: side=3 sz=side*side class Cell: def __init__(self,board,row,col): self._values= [None] * SudukoBoard.sz ...
[ "from collections import Counter\nfrom copy import deepcopy\nfrom itertools import count\nfrom traceback import print_exc\n\n#https://www.websudoku.com/?level=4\n\nclass SudukoBoard:\n side=3\n sz=side*side\n class Cell:\n def __init__(self,board,row,col):\n self._values= [None] * SudukoB...
false
7,842
5bd2cf2ae68708d2b1dbbe0323a5f83837f7b564
import requests from urllib.parse import urlparse, urlencode from json import JSONDecodeError from requests.exceptions import HTTPError def validate_response(response): """ raise exception if error response occurred """ r = response try: r.raise_for_status() except HTTPError as e: ...
[ "import requests\nfrom urllib.parse import urlparse, urlencode\nfrom json import JSONDecodeError\nfrom requests.exceptions import HTTPError\n\n\ndef validate_response(response):\n \"\"\"\n raise exception if error response occurred\n \"\"\"\n\n r = response\n try:\n r.raise_for_status()\n e...
false
7,843
15a894e6f94fc62b97d1614a4213f21331ef12a0
import collections s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = collections.defaultdict(list) d2 = {'test':121} for k, v in s: d[k].append(v) d['test'].append('value') print list(d.items()) print d print d['blue'] print type(d) print type(d2)
[ "import collections\ns = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]\n\nd = collections.defaultdict(list)\nd2 = {'test':121}\nfor k, v in s:\n d[k].append(v)\n\nd['test'].append('value')\n\nprint list(d.items())\nprint d\nprint d['blue']\nprint type(d)\nprint type(d2)" ]
true
7,844
de88e2d2cf165b35f247ea89300c91b3c8c07fea
# Copyright (c) 2023 Intel Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writ...
[ "# Copyright (c) 2023 Intel Corporation\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# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agree...
false
7,845
15c1db535beb115c45aeba433a946255f70fa86e
# -*- coding: utf-8 -*- import base64 import logging from decimal import Decimal import requests from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from currencies.currencies import decimal_round from payments.systems import base from payments.systems.ban...
[ "# -*- coding: utf-8 -*-\nimport base64\nimport logging\nfrom decimal import Decimal\n\nimport requests\nfrom django import forms\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom currencies.currencies import decimal_round\nfrom payments.systems import base\nfrom pay...
false
7,846
44b6ee8488869da447882457897ce87b2fdea726
import getpass print('****************************') print('***** Caixa Eletronico *****') print('****************************') account_typed = input("Digite sua conta: ") password_typed = getpass.getpass("Digite sua senha: ")
[ "import getpass\r\n\r\nprint('****************************')\r\nprint('***** Caixa Eletronico *****')\r\nprint('****************************')\r\n\r\naccount_typed = input(\"Digite sua conta: \")\r\npassword_typed = getpass.getpass(\"Digite sua senha: \")\r\n", "import getpass\nprint('****************************...
false
7,847
89ce3d3ec9691ab8f54cc0d9d008e06c65b5f2cc
#grabbed the following from moses marsh -- https://github.com/sidetrackedmind/gimme-bus/blob/master/gimmebus/utilities.py from datetime import datetime as dt from math import radians, cos, sin, acos, asin, sqrt import networkx as nx ## These functions will go in model.py for matching historical GPS ## positions to th...
[ "#grabbed the following from moses marsh -- https://github.com/sidetrackedmind/gimme-bus/blob/master/gimmebus/utilities.py\n\nfrom datetime import datetime as dt\nfrom math import radians, cos, sin, acos, asin, sqrt\nimport networkx as nx\n\n## These functions will go in model.py for matching historical GPS\n## pos...
false
7,848
c48d5d9e088acfed0c59e99d3227c25689d205c6
naam = raw_input("Wat is je naam?") getal = raw_input("Geef me een getal?") if naam == "Barrie": print "Welkom " * int(getal) else: print "Helaas, tot ziens"
[ "naam = raw_input(\"Wat is je naam?\")\ngetal = raw_input(\"Geef me een getal?\")\nif naam == \"Barrie\":\n\tprint \"Welkom \" * int(getal)\nelse:\n\tprint \"Helaas, tot ziens\"" ]
true
7,849
29c25721a4754650f0d5d63d6cc3215cb0ea1b3e
""" bubble sort start at beginning switch to left if smaller - very naive approach n-1 comparisons, n-1 iterations (n-1)^2 worst case: O(n^2) = average case best case: O(n) space complexity: O(1) """ def bubbleSort(list): for num in range(len(list)-1,0,-1): for i in range(num): if list[i] > list...
[ "\"\"\"\nbubble sort\nstart at beginning switch to left if smaller - very naive approach\nn-1 comparisons, n-1 iterations\n(n-1)^2\nworst case: O(n^2) = average case\nbest case: O(n)\nspace complexity: O(1)\n\"\"\"\ndef bubbleSort(list):\n for num in range(len(list)-1,0,-1):\n for i in range(num):\n ...
false
7,850
1a1a217b382f3c58c6c4cd3c1c3f556ae945f5a7
from selenium import webdriver; from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome(Chr...
[ "from selenium import webdriver;\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\ndriver = webdriv...
false
7,851
22e24e8dd49367ae57d1980c4addf48d65c5e897
''' Created on Nov 20, 2012 @author: shriram ''' import xml.etree.ElementTree as ET from xml.sax.saxutils import escape ''' Annotating only Sparse and Non Sparse Lines ''' class Trainer: def html_escape(self,text): html_escape_table = { '"': "&quot;", "'": "&apos;" } re...
[ "'''\nCreated on Nov 20, 2012\n\n@author: shriram\n'''\nimport xml.etree.ElementTree as ET\nfrom xml.sax.saxutils import escape\n\n'''\n Annotating only Sparse and Non Sparse Lines\n'''\nclass Trainer:\n def html_escape(self,text):\n html_escape_table = {\n '\"': \"&quot;\",\n \"'\": \"&a...
false
7,852
f3a3746c48617754aad5ae8d0d7a0b8908c34562
# coding: utf-8 # In[5]: import os import numpy as np import pandas as pd from PIL import Image import argparse import time import shutil from sklearn.metrics import accuracy_score, mean_squared_error import torch import torch.optim from torch.utils.data import Dataset, DataLoader from torch.autograd import Variab...
[ "\n# coding: utf-8\n\n# In[5]:\n\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport argparse\nimport time\nimport shutil\nfrom sklearn.metrics import accuracy_score, mean_squared_error\n\nimport torch\nimport torch.optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch...
false
7,853
bacd0c729193f064b21ab8e01e98dfc276094458
# -*- coding: utf-8 -*- # # Copyright (C) 2011 Taobao .Inc # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://code.taobao.org/license.html. # # This software consists of voluntary ...
[ "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2011 Taobao .Inc\n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at http://code.taobao.org/license.html.\n#\n# This software consists...
false
7,854
c3719f30bcf13061134b34b0925dfa2af4535f14
#!/usr/bin/env python from setuptools import setup import NagAconda setup(name=NagAconda.__name__, version=NagAconda.__version__, description="NagAconda is a Python Nagios wrapper.", long_description=open('README').read(), author='Steven Schlegel', author_email='steven@schlegel.tech', ...
[ "#!/usr/bin/env python\n\nfrom setuptools import setup\nimport NagAconda\n\nsetup(name=NagAconda.__name__,\n version=NagAconda.__version__,\n description=\"NagAconda is a Python Nagios wrapper.\",\n long_description=open('README').read(),\n author='Steven Schlegel',\n author_email='steven@s...
false
7,855
d205c38e18b1acf8043a5976a90939b14358dc40
#-*- coding: utf-8 -*- espacos = ["__1__", "__2__", "__3__", "__4__"] facil_respostas=["ouro","leao","capsula do poder","relampago de plasma"] media_respostas=["Ares","Saga","Gemeos","Athena"] dificil_respostas=["Shion","Aries","Saga","Gemeos"] def inicio_game(): apresentacao=raw_input("Bem vindo ao qui...
[ "#-*- coding: utf-8 -*-\r\nespacos = [\"__1__\", \"__2__\", \"__3__\", \"__4__\"]\r\nfacil_respostas=[\"ouro\",\"leao\",\"capsula do poder\",\"relampago de plasma\"]\r\nmedia_respostas=[\"Ares\",\"Saga\",\"Gemeos\",\"Athena\"]\r\ndificil_respostas=[\"Shion\",\"Aries\",\"Saga\",\"Gemeos\"]\r\n\r\n\r\n\r\ndef inicio_...
true
7,856
2d5abcd75dcbeb1baa3f387035bdcc3b7adbfe3f
''' 8-6. 도시 이름 도시와 국가 이름을 받는 city_country() 함수를 만드세요. 이 함수는 다음과 같은 문자열을 반환해야 합니다. 'Santiago, Chile' - 최소한 세 개의 도시-국가 쌍으로 함수를 호출하고 반환값을 출력하세요. Output: santiago, chile ushuaia, argentina longyearbyen, svalbard '''
[ "'''\n8-6. 도시 이름\n도시와 국가 이름을 받는 city_country() 함수를 만드세요. 이 함수는 다음과 같은 문자열을 반환해야 합니다.\n'Santiago, Chile'\n- 최소한 세 개의 도시-국가 쌍으로 함수를 호출하고 반환값을 출력하세요.\n\nOutput:\nsantiago, chile\nushuaia, argentina\nlongyearbyen, svalbard\n'''\n\n", "<docstring token>\n" ]
false
7,857
f715628da2f1b950b8fbf8aa5b033e5299d3e224
lc_headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15", "authority": "leetcode.com", } lc_all = "https://leetcode.com/api/problems/all/" lc_submissions = "https://leetcode.com/api/submissions/?off...
[ "lc_headers = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15\",\n \"authority\": \"leetcode.com\",\n }\n\nlc_all = \"https://leetcode.com/api/problems/all/\"\nlc_submissions = \"https://leetcode.co...
false
7,858
fe5398b03d2f0cfc7c972677faa0ea3ec701469e
# Create your models here. from django.db import models from django.utils import timezone from django.db import models # Create your models here. #필드 개수가 다르다. class Post(models.Model): #이 Post의 저자이다라는 의미, CASCADE : 종속이라는 의미 author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.C...
[ "# Create your models here.\nfrom django.db import models\nfrom django.utils import timezone\nfrom django.db import models\n\n# Create your models here.\n#필드 개수가 다르다.\n\nclass Post(models.Model):\n #이 Post의 저자이다라는 의미, CASCADE : 종속이라는 의미\n author = models.ForeignKey('auth.User', on_delete=models.CASCADE)\n ...
false
7,859
62de629d8f28435ea8dc3dc093cac95e7cedf128
# 6. Evaluate Classifier: you can use any metric you choose for this assignment # (accuracy is the easiest one). Feel free to evaluate it on the same data you # built the model on (this is not a good idea in general but for this assignment, # it is fine). We haven't covered models and evaluation yet, so don't worry ...
[ "# 6. Evaluate Classifier: you can use any metric you choose for this assignment \n# (accuracy is the easiest one). Feel free to evaluate it on the same data you \n# built the model on (this is not a good idea in general but for this assignment, \n# it is fine). We haven't covered models and evaluation yet, so don'...
false
7,860
90e475dfd128689dd4e1a5375ced6e4cbfb73c07
import sys N = int(input()) card = [int(x+1) for x in range(N)] trash = [] while len(card)>1: topCard = card.pop(0) trash.append(topCard) card.append(card.pop(0)) outputStr = "" for i in range(len(trash)): outputStr += str(trash[i]) + " " outputStr += str(card[0]) print(outputStr)
[ "import sys\n\nN = int(input())\ncard = [int(x+1) for x in range(N)]\ntrash = []\nwhile len(card)>1:\n topCard = card.pop(0)\n trash.append(topCard)\n card.append(card.pop(0))\n\noutputStr = \"\"\nfor i in range(len(trash)):\n outputStr += str(trash[i]) + \" \"\n\noutputStr += str(card[0])\nprint(output...
false
7,861
4da1a97c2144c9aaf96e5fe6508f8b4532b082d4
import tweepy import time import twitter_credentials as TC auth = tweepy.OAuthHandler(TC.CONSUMER_KEY, TC.CONSUMER_SECRET) auth.set_access_token(TC.ACCESS_TOKEN, TC.ACCESS_TOKEN_SECRET) api = tweepy.API(auth) count = 1 # Query to get 50 tweets with either Indiana or Weather in them for tweet in tweepy.Cursor(api.sea...
[ "import tweepy\nimport time\nimport twitter_credentials as TC\n\nauth = tweepy.OAuthHandler(TC.CONSUMER_KEY, TC.CONSUMER_SECRET)\nauth.set_access_token(TC.ACCESS_TOKEN, TC.ACCESS_TOKEN_SECRET)\n\napi = tweepy.API(auth)\ncount = 1\n\n# Query to get 50 tweets with either Indiana or Weather in them\nfor tweet in tweep...
false
7,862
db36c82717aa0bacffce7a3e2724ed2bb586c7fb
from solution import find_days import pudb def test(): T = [1, 2, 3, 1, 0, 4] # pudb.set_trace() res = find_days(T) assert res == [1, 1, 3, 2, 1, 0]
[ "from solution import find_days\nimport pudb\n\n\ndef test():\n T = [1, 2, 3, 1, 0, 4]\n # pudb.set_trace()\n res = find_days(T)\n assert res == [1, 1, 3, 2, 1, 0]\n", "from solution import find_days\nimport pudb\n\n\ndef test():\n T = [1, 2, 3, 1, 0, 4]\n res = find_days(T)\n assert res == [...
false
7,863
3a6eaa238e78e7a818bcf6e18cc7881eadf94b07
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_googlesearch # Purpose: Searches Google for content related to the domain in question. # # Author: Steve Micallef <steve@binarypool.com> # # Created: 07/05/2012 # Copyright...
[ "# -*- coding: utf-8 -*-\r\n# -------------------------------------------------------------------------------\r\n# Name: sfp_googlesearch\r\n# Purpose: Searches Google for content related to the domain in question.\r\n#\r\n# Author: Steve Micallef <steve@binarypool.com>\r\n#\r\n# Created: 07/0...
false
7,864
9aaaa744780dbd32b14e09a34976a2a0a3ce34f7
from packages import data as DATA from packages import plot as PLOT from packages import universal as UNIVERSAL from packages import currency_pair as CP import matplotlib.pyplot as plt import mpl_finance as mpf from packages import db as DB import CONSTANTS import datetime from matplotlib.pylab import date2num from mat...
[ "from packages import data as DATA\nfrom packages import plot as PLOT\nfrom packages import universal as UNIVERSAL\nfrom packages import currency_pair as CP\nimport matplotlib.pyplot as plt\nimport mpl_finance as mpf\nfrom packages import db as DB\nimport CONSTANTS\nimport datetime\nfrom matplotlib.pylab import dat...
false
7,865
5e1398ed628917a42cc465e7cc2979601f0f4fbc
#!/usr/bin/env python #**************************************************************************** # fieldformat.py, provides non-GUI base classes for field formating # # TreeLine, an information storage program # Copyright (C) 2006, Douglas W. Bell # # This is free software; you can redistribute it and/or modify it ...
[ "#!/usr/bin/env python\n\n#****************************************************************************\n# fieldformat.py, provides non-GUI base classes for field formating\n#\n# TreeLine, an information storage program\n# Copyright (C) 2006, Douglas W. Bell\n#\n# This is free software; you can redistribute it and/...
false
7,866
3ffcab4b36c6ca05f1e667c628ebb873ebdc0d25
# -*- coding: utf-8 -*- import serial import time import argparse def write_command(serial, comm, verbose = False, dt = None): """ Encodes a command and sends it over the serial port """ if verbose and comm != "": if dt is None: print("{} \t\t-> {}".format(comm, serial.port...
[ "# -*- coding: utf-8 -*-\r\n\r\nimport serial\r\nimport time\r\nimport argparse\r\n\r\n \r\ndef write_command(serial, comm, verbose = False, dt = None):\r\n \"\"\" Encodes a command and sends it over the serial port \"\"\"\r\n if verbose and comm != \"\":\r\n if dt is None:\r\n print(\"{}...
false
7,867
f29ad02f3781c7a7d2a1f0c97626dd5c7ea2417e
""" CP1404 Practical unreliable car test """ from unreliable_car import UnreliableCar def main(): good_car = UnreliableCar("good car", 100, 80) bad_car = UnreliableCar("bad car", 100, 10) for i in range(10): print("try to drive {} km".format(i)) print("{:10} drove {:2}km".format(good_car....
[ "\"\"\"\nCP1404 Practical\nunreliable car test\n\"\"\"\nfrom unreliable_car import UnreliableCar\n\n\ndef main():\n good_car = UnreliableCar(\"good car\", 100, 80)\n bad_car = UnreliableCar(\"bad car\", 100, 10)\n\n for i in range(10):\n print(\"try to drive {} km\".format(i))\n print(\"{:10}...
false
7,868
656927013d9a0254e2bc4cdf05b7cfd5947feb05
from .proxies import Proxies from .roles import Roles from .products import Products from .resourcefiles import ResourceFiles class Apigee(object): """Provides easy access to all endpoint classes Args: domain (str): Your Auth0 domain, e.g: 'username.auth0.com' token (str): Management API v2...
[ "from .proxies import Proxies\nfrom .roles import Roles\nfrom .products import Products\nfrom .resourcefiles import ResourceFiles\n\n\n\nclass Apigee(object):\n \"\"\"Provides easy access to all endpoint classes\n\n Args:\n domain (str): Your Auth0 domain, e.g: 'username.auth0.com'\n\n token (st...
false
7,869
b459919e779063247c176e127368c687c903cf0f
from checkio.home.long_repeat import long_repeat def test_long_repeat(): assert long_repeat("sdsffffse") == 4, "First" assert long_repeat("ddvvrwwwrggg") == 3, "Second" def test_fails_1(): assert long_repeat("") == 0, "Empty String" def test_fails_2(): assert long_repeat("aa") == 2
[ "from checkio.home.long_repeat import long_repeat\n\n\ndef test_long_repeat():\n assert long_repeat(\"sdsffffse\") == 4, \"First\"\n assert long_repeat(\"ddvvrwwwrggg\") == 3, \"Second\"\n\n\ndef test_fails_1():\n assert long_repeat(\"\") == 0, \"Empty String\"\n\n\ndef test_fails_2():\n assert long_rep...
false
7,870
f546eb40ee8a7308ded62532731561029e5ec335
import requests import os from slugify import slugify as PipSlugify import shutil # will install any valid .deb package def install_debian_package_binary(package_path): os.system("sudo dpkg -i {package_path}".format( package_path=package_path )) os.system("sudo apt-get install -f") def download_inst...
[ "import requests\nimport os\nfrom slugify import slugify as PipSlugify\nimport shutil\n\n# will install any valid .deb package\ndef install_debian_package_binary(package_path):\n os.system(\"sudo dpkg -i {package_path}\".format(\n package_path=package_path\n ))\n os.system(\"sudo apt-get install -f\")...
false
7,871
57c911c9a10f9d116f1b7099c5202377e16050f1
from typing import * class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: cells = {} for i in range(9): for j in range(9): if board[i][j] != ".": val = board[i][j] # is unique in r...
[ "from typing import *\n\n\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n cells = {}\n \n for i in range(9):\n for j in range(9):\n if board[i][j] != \".\":\n val = board[i][j]\n \n ...
false
7,872
85f5f9370896eac17dc72bbbf8d2dd1d7adc3a5b
""" """ import cPickle as pickle def convert_cpu_stats_to_num_array(cpuStats): """ Given a list of statistics (tuples[timestamp, total_cpu, kernel_cpu, vm, rss]) Return five numarrays """ print "Converting cpus stats into numpy array" c0 = [] c1 = [] c2 = [] c3 = [] c4 = [] ...
[ "\"\"\"\n\n\"\"\"\nimport cPickle as pickle\n\n\ndef convert_cpu_stats_to_num_array(cpuStats):\n \"\"\"\n Given a list of statistics (tuples[timestamp, total_cpu, kernel_cpu, vm, rss])\n Return five numarrays\n \"\"\"\n print \"Converting cpus stats into numpy array\"\n c0 = []\n c1 = []\n c...
true
7,873
63a9060e9933cc37b7039833be5f071cc7bf45bf
#import getCanditatemap() from E_18_hacksub import operator, pdb, collections, string ETAOIN = """ etaoinsrhldcumgyfpwb.,vk0-'x)(1j2:q"/5!?z346879%[]*=+|_;\>$#^&@<~{}`""" #order taken from https://mdickens.me/typing/theory-of-letter-frequency.html, with space added at the start, 69 characters overall length = 128 #ETA...
[ "#import getCanditatemap() from E_18_hacksub\nimport operator, pdb, collections, string\n\nETAOIN = \"\"\" etaoinsrhldcumgyfpwb.,vk0-'x)(1j2:q\"/5!?z346879%[]*=+|_;\\>$#^&@<~{}`\"\"\" #order taken from https://mdickens.me/typing/theory-of-letter-frequency.html, with space added at the start, 69 characters overall\n...
false
7,874
e766bba4dec0d37858f1f24083c238763d694109
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) import random import itertools doc = """ Public good game section (Rounds and feedback). """ class Constants(BaseConstants): name_in_url = 'public_goods' players...
[ "from otree.api import (\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\n Currency as c, currency_range\n)\nimport random\nimport itertools\n\ndoc = \"\"\"\n Public good game section (Rounds and feedback).\n \"\"\"\n\nclass Constants(BaseConstants):\n name_in_url = 'pu...
true
7,875
5ee1d8ef7ec4b191e0789ceb9c6dd2d58af526a0
# -*- coding: utf-8 -*- import pytest from bravado.client import ResourceDecorator from bravado.client import SwaggerClient def test_resource_exists(petstore_client): assert type(petstore_client.pet) == ResourceDecorator def test_resource_not_found(petstore_client): with pytest.raises(AttributeError) as ex...
[ "# -*- coding: utf-8 -*-\nimport pytest\n\nfrom bravado.client import ResourceDecorator\nfrom bravado.client import SwaggerClient\n\n\ndef test_resource_exists(petstore_client):\n assert type(petstore_client.pet) == ResourceDecorator\n\n\ndef test_resource_not_found(petstore_client):\n with pytest.raises(Attr...
false
7,876
07b6ded9b4841bdba62d481664a399f0b125fcbf
import pandas as pd; import time; import matplotlib.pyplot as plt; import matplotlib.cm as cm import matplotlib.patches as mpatch; import numpy as np; import sys; sys.path.append("/uufs/chpc.utah.edu/common/home/u0403692/prog/prism/test") import bettersankey as bsk; datapath = "/uufs/chpc.utah.edu/common/home/u04036...
[ "import pandas as pd;\nimport time;\nimport matplotlib.pyplot as plt;\nimport matplotlib.cm as cm\nimport matplotlib.patches as mpatch;\nimport numpy as np;\nimport sys;\n\nsys.path.append(\"/uufs/chpc.utah.edu/common/home/u0403692/prog/prism/test\")\nimport bettersankey as bsk;\n\n\ndatapath = \"/uufs/chpc.utah.ed...
false
7,877
df518fd719b7eafffd8fee92c926d4d24b65ce18
import os import json import pathlib from gql import gql, Client from gql.transport.aiohttp import AIOHTTPTransport # Select your transport with a defined url endpoint transport = AIOHTTPTransport(url="https://public-api.nbatopshot.com/graphql") # Create a GraphQL client using the defined transport client = Client(tr...
[ "import os\nimport json\nimport pathlib\nfrom gql import gql, Client\nfrom gql.transport.aiohttp import AIOHTTPTransport\n\n# Select your transport with a defined url endpoint\ntransport = AIOHTTPTransport(url=\"https://public-api.nbatopshot.com/graphql\")\n\n# Create a GraphQL client using the defined transport\nc...
false
7,878
ccc2a976d06e2fa6c91b25c4f95a8f0da32e9b5e
""" Author: Yudong Qiu Functions for solving unrestricted Hartree-Fock """ import numpy as np from qc_python import basis_integrals from qc_python.common import chemical_elements, calc_nuclear_repulsion def solve_unrestricted_hartree_fock(elems, coords, basis_set, charge=0, spinmult=1, maxiter=150, enable_DIIS=True...
[ "\n\"\"\"\nAuthor: Yudong Qiu\nFunctions for solving unrestricted Hartree-Fock\n\"\"\"\n\nimport numpy as np\n\nfrom qc_python import basis_integrals\nfrom qc_python.common import chemical_elements, calc_nuclear_repulsion\n\ndef solve_unrestricted_hartree_fock(elems, coords, basis_set, charge=0, spinmult=1, maxiter...
false
7,879
0ceb9eac46e3182821e65a1ae3a69d842db51e62
STATUS_DISCONNECT = 0 STATUS_CONNECTED = 1 STATUS_OPEN_CH_REQUEST = 2 STATUS_OPENED = 3 STATUS_EXITING = 4 STATUS_EXITTED = 5 CONTENT_TYPE_IMAGE = 0 CONTENT_TYPE_VIDEO = 1 STATUS_OK = 0 STATUS_ERROR = 1 class Point(object): def __init__(self, x = 0, y = 0): self.x = x self.y = y class ObjectDe...
[ "\nSTATUS_DISCONNECT = 0\nSTATUS_CONNECTED = 1\nSTATUS_OPEN_CH_REQUEST = 2\nSTATUS_OPENED = 3\nSTATUS_EXITING = 4\nSTATUS_EXITTED = 5\n\nCONTENT_TYPE_IMAGE = 0\nCONTENT_TYPE_VIDEO = 1\n\nSTATUS_OK = 0\nSTATUS_ERROR = 1\n\nclass Point(object):\n def __init__(self, x = 0, y = 0):\n self.x = x\n self....
false
7,880
f7283750923e1e430ff1f648878bbb9a0c73d2c4
from settings import * helpMessage = ''' **Vocal / Musique** `{0}join` Va rejoindre le salon vocale dans laquelle vous êtes. `{0}leave` Va partir du salon vocale dans laquelle vous êtes. `{0}play [YouTube Url]` *ou* `{0}play [musique ou video à rechercher]` Commencera à jouer l'audio de la vidéo / chans...
[ "from settings import *\r\n\r\nhelpMessage = '''\r\n**Vocal / Musique**\r\n\r\n`{0}join`\r\nVa rejoindre le salon vocale dans laquelle vous êtes.\r\n\r\n`{0}leave`\r\nVa partir du salon vocale dans laquelle vous êtes.\r\n\r\n`{0}play [YouTube Url]` *ou* `{0}play [musique ou video à rechercher]`\r\nCommencera à joue...
false
7,881
5e14eeaa3c79bfdd564f3bfd1575c9bbf1a3773d
"""Command generator for running a script against a BigQuery cluster. Contains the method to compile the BigQuery specific script execution command based on generic arguments (sql script, output destination) and BigQuery specific arguments (flag values). """ __author__ = 'p3rf@google.com' from absl import flags fla...
[ "\"\"\"Command generator for running a script against a BigQuery cluster.\n\nContains the method to compile the BigQuery specific script execution command\nbased on generic arguments (sql script, output destination) and BigQuery\nspecific arguments (flag values).\n\"\"\"\n\n__author__ = 'p3rf@google.com'\n\nfrom ab...
false
7,882
e877f16e604682488d85142174ce4f3f6cee3f18
from sys import argv from pyspark import SparkContext import json import re import math from _datetime import datetime start_time = datetime.now() input_file = argv[1] model_file = argv[2] stopwords = argv[3] sc = SparkContext(appName='inf553') lines = sc.textFile(input_file).map(lambda x: json.loads(x)) stopwords = sc...
[ "from sys import argv\nfrom pyspark import SparkContext\nimport json\nimport re\nimport math\nfrom _datetime import datetime\nstart_time = datetime.now()\ninput_file = argv[1]\nmodel_file = argv[2]\nstopwords = argv[3]\nsc = SparkContext(appName='inf553')\nlines = sc.textFile(input_file).map(lambda x: json.loads(x)...
false
7,883
b849a2902c8596daa2c6da4de7b9d1c07b34d136
# Generate some object patterns as save as JSON format import json import math import random from obstacle import * def main(map): obs = [] for x in range(1,35): obs.append(Obstacle(random.randint(0,map.getHeight()), y=random.randint(0,map.getWidth()), radius=20).toJsonObject()) jsonOb={'map': {'obstacle': obs}}...
[ "# Generate some object patterns as save as JSON format\nimport json\nimport math\nimport random\nfrom obstacle import *\n\ndef main(map):\n\tobs = []\n\tfor x in range(1,35):\n\t\tobs.append(Obstacle(random.randint(0,map.getHeight()), y=random.randint(0,map.getWidth()), radius=20).toJsonObject())\n\n\tjsonOb={'map...
true
7,884
b9a75f4e106efade3a1ebdcfe66413107d7eccd0
from distutils.core import setup setup( name='dcnn_visualizer', version='', packages=['dcnn_visualizer', 'dcnn_visualizer.backward_functions'], url='', license='', author='Aiga SUZUKI', author_email='tochikuji@gmail.com', description='', requires=['numpy', 'chainer', 'chainercv'] )
[ "from distutils.core import setup\n\nsetup(\n name='dcnn_visualizer',\n version='',\n packages=['dcnn_visualizer', 'dcnn_visualizer.backward_functions'],\n url='',\n license='',\n author='Aiga SUZUKI',\n author_email='tochikuji@gmail.com',\n description='', requires=['numpy', 'chainer', 'cha...
false
7,885
1cdd315eec6792a8588dc2e6a221bc024be47078
import pygame import textwrap import client.Button as Btn from client.ClickableImage import ClickableImage as ClickImg from client.CreateDisplay import CreateDisplay import client.LiverpoolButtons as RuleSetsButtons_LP import client.HandAndFootButtons as RuleSetsButtons_HF import client.HandManagement as HandManagement...
[ "import pygame\nimport textwrap\nimport client.Button as Btn\nfrom client.ClickableImage import ClickableImage as ClickImg\nfrom client.CreateDisplay import CreateDisplay\nimport client.LiverpoolButtons as RuleSetsButtons_LP\nimport client.HandAndFootButtons as RuleSetsButtons_HF\nimport client.HandManagement as Ha...
false
7,886
dc97703d39e7db29e0ba333c2797f4be6d015fd7
# -*- coding: utf-8 -*- """ Created on Mon Apr 16 21:26:03 2018 @author: Brandon """os.getcwd() Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'os' is not definimport os >>> os.getcwd() 'C:\\Users\\Brandon\\AppData\\Local\\Programs\\Python\\Python36-32' >>> os.chdir() Tracebac...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 16 21:26:03 2018\n\n@author: Brandon\n\"\"\"os.getcwd()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'os' is not definimport os\n>>> os.getcwd()\n'C:\\\\Users\\\\Brandon\\\\AppData\\\\Local\\\\Programs\\\\Python\\\...
true
7,887
94ca18088664393fdfdc68bfb8bcad8b78e9e36a
# bot.py import os import shutil import discord import youtube_dl from discord.ext import commands import urllib.parse import urllib.request import re import dotenv from pathlib import Path # Python 3.6+ only from dotenv import load_dotenv env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) client = disc...
[ "# bot.py\nimport os\nimport shutil\nimport discord\nimport youtube_dl\nfrom discord.ext import commands\nimport urllib.parse\nimport urllib.request\nimport re\nimport dotenv\nfrom pathlib import Path # Python 3.6+ only\nfrom dotenv import load_dotenv\n\nenv_path = Path('.') / '.env'\nload_dotenv(dotenv_path=env_p...
false
7,888
4545ce36c4d3df50e263d3323c04c53acb2b50e0
#!/usr/bin/env python3 import csv import math def load_data_from_file(filename): """ Load that data, my dude(tte) :param filename: The file from which you want to load data :return: Time and position data of the file """ time = [] position = [] with open(filename, 'r') a...
[ "#!/usr/bin/env python3\r\n\r\nimport csv\r\nimport math\r\n\r\n\r\ndef load_data_from_file(filename):\r\n \"\"\"\r\n Load that data, my dude(tte)\r\n :param filename: The file from which you want to load data\r\n :return: Time and position data of the file\r\n \"\"\"\r\n time = []\r\n position...
false
7,889
3472dc0c9d00c10ab0690c052e70fbf6a4bdb13d
"""Utilities for AnalysisModules.""" import inspect from mongoengine import QuerySet from numpy import percentile from .modules import AnalysisModule def get_primary_module(package): """Extract AnalysisModule primary module from package.""" def test_submodule(submodule): """Test a submodule to see ...
[ "\"\"\"Utilities for AnalysisModules.\"\"\"\n\nimport inspect\n\nfrom mongoengine import QuerySet\nfrom numpy import percentile\n\nfrom .modules import AnalysisModule\n\n\ndef get_primary_module(package):\n \"\"\"Extract AnalysisModule primary module from package.\"\"\"\n def test_submodule(submodule):\n ...
false
7,890
19e387cb731dad21e5ee50b0a9812df984c13f3b
import openpyxl as opx import pyperclip from openpyxl import Workbook from openpyxl.styles import PatternFill wb = Workbook(write_only=True) ws = wb.create_sheet() def parseSeq(lines,seqName): '''splits each column''' data = [] for line in lines: data.append(line.split(' ')) '''remov...
[ "import openpyxl as opx\r\nimport pyperclip\r\nfrom openpyxl import Workbook\r\nfrom openpyxl.styles import PatternFill\r\nwb = Workbook(write_only=True)\r\nws = wb.create_sheet()\r\n\r\n\r\ndef parseSeq(lines,seqName):\r\n \r\n '''splits each column'''\r\n data = []\r\n for line in lines: data.append(l...
false
7,891
c76fd9b196b50e6fcced7e56517c0cd8ab30e24e
from . import preprocess from . import utils import random import pickle import feather import time import datetime import sys import os import numpy as np import pandas as pd import json from ...main import api from flask import request from flask_restplus import Resource, fields import warnings warnings.simplefilter...
[ "from . import preprocess\nfrom . import utils\nimport random\nimport pickle\nimport feather\nimport time\nimport datetime\nimport sys\nimport os\nimport numpy as np\nimport pandas as pd\nimport json\nfrom ...main import api\nfrom flask import request\nfrom flask_restplus import Resource, fields\n\nimport warnings\...
false
7,892
b3095f181032727544ce3ee6f1ad3a70976c0061
# Copyright (c) 2018-2020, NVIDIA CORPORATION. import os import shutil import subprocess import sys import sysconfig from distutils.spawn import find_executable from distutils.sysconfig import get_python_lib import numpy as np import pyarrow as pa from Cython.Build import cythonize from Cython.Distutils import build_e...
[ "# Copyright (c) 2018-2020, NVIDIA CORPORATION.\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport sysconfig\nfrom distutils.spawn import find_executable\nfrom distutils.sysconfig import get_python_lib\n\nimport numpy as np\nimport pyarrow as pa\nfrom Cython.Build import cythonize\nfrom Cython.Distuti...
false
7,893
548c4dbfc1456fead75c22927ae7c6224fafeace
#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run inside-block # https://py.checkio.org/mission/inside-block/ # When it comes to city planning it's import to understand the borders of various city structures. Parks, lakes or living blocks can be represented as closed polygon and...
[ "#!/home/porosya/.local/share/virtualenvs/checkio-VEsvC6M1/bin/checkio --domain=py run inside-block\n\n# https://py.checkio.org/mission/inside-block/\n\n# When it comes to city planning it's import to understand the borders of various city structures. Parks, lakes or living blocks can be represented as closed po...
false
7,894
8a4fe88bfa39eeeda42198260a1b22621c33183e
import datetime from threading import Thread import cv2 class WebcamVideoStream: #Constructor def __init__(self, src=0): # initialize the video camera stream and read the first frame # from the stream self.stream = cv2.VideoCapture(src) (self.grabbed, self.frame) = self.stream.read() # initialize the v...
[ "import datetime\nfrom threading import Thread\nimport cv2\n\nclass WebcamVideoStream:\n\n #Constructor\n\tdef __init__(self, src=0):\n\t\t# initialize the video camera stream and read the first frame\n\t\t# from the stream\n\t\tself.stream = cv2.VideoCapture(src)\n\t\t(self.grabbed, self.frame) = self.stream.re...
false
7,895
f82ddc34fde76ddfbbe75116526af45b83c1b102
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # 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 required by appl...
[ "# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.\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-2.0\n#\n# Unless r...
false
7,896
9b02ce0b3acb14bdd6463c5bdba865b28253767c
from platypush.message.event import Event class ClipboardEvent(Event): def __init__(self, text: str, *args, **kwargs): super().__init__(*args, text=text, **kwargs) # vim:sw=4:ts=4:et:
[ "from platypush.message.event import Event\n\n\nclass ClipboardEvent(Event):\n def __init__(self, text: str, *args, **kwargs):\n super().__init__(*args, text=text, **kwargs)\n\n\n# vim:sw=4:ts=4:et:\n", "from platypush.message.event import Event\n\n\nclass ClipboardEvent(Event):\n\n def __init__(self...
false
7,897
b4f522398cd2658c2db926216e974781e10c44df
import requests #!/usr/bin/env python from confluent_kafka import Producer, KafkaError import json import ccloud_lib delivered_records = 0 url = "https://api.mockaroo.com/api/cbb61270?count=1000&key=5a40bdb0" # Optional per-message on_delivery handler (triggered by poll() or flush()) # when a message has be...
[ "import requests\n#!/usr/bin/env python\n\nfrom confluent_kafka import Producer, KafkaError\nimport json\nimport ccloud_lib\n\ndelivered_records = 0\nurl = \"https://api.mockaroo.com/api/cbb61270?count=1000&key=5a40bdb0\"\n\n\n # Optional per-message on_delivery handler (triggered by poll() or flush())\n # wh...
false
7,898
50ae2b4c6d51451031fc31ebbc43c820da54d827
import math def hipotenusa(a,b): return math.sqrt((a*a)+(b*b)) def main(): cateto1=input('dime un cateto') cateto2=input('dime el otro cateto') print ('la hipotenusa es: '),hipotenusa(cateto1,cateto2) main()
[ "import math\r\ndef hipotenusa(a,b):\r\n return math.sqrt((a*a)+(b*b))\r\n\r\ndef main():\r\n cateto1=input('dime un cateto')\r\n cateto2=input('dime el otro cateto')\r\n print ('la hipotenusa es: '),hipotenusa(cateto1,cateto2)\r\n\r\nmain()\r\n", "import math\n\n\ndef hipotenusa(a, b):\n return ma...
false
7,899
db920f4aadfb53bb26c5ba1fb182f12b95e14a2f
# Generated by Django 3.1.6 on 2021-02-05 00:27 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main_app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='tea', ...
[ "# Generated by Django 3.1.6 on 2021-02-05 00:27\n\nimport django.core.validators\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('main_app', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name=...
false