index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
5,000
7130a382784955780a3f258c81ce05c61915af56
import numpy as np def get_mask(mask): r = mask[:, :, 0] g = mask[:, :, 1] return r // (r.max() or 1) * -1 + g // (g.max() or 1) def calculate_brightness(image): weights = np.array([0.299, 0.587, 0.114]) brightness_matrix = (image*weights).sum(axis=2) return brightness_matrix def calculate...
[ "import numpy as np\n\n\ndef get_mask(mask):\n r = mask[:, :, 0]\n g = mask[:, :, 1]\n return r // (r.max() or 1) * -1 + g // (g.max() or 1)\n\n\ndef calculate_brightness(image):\n weights = np.array([0.299, 0.587, 0.114])\n brightness_matrix = (image*weights).sum(axis=2)\n return brightness_matri...
false
5,001
e204cbbf36ac180eba0e95916345088c77bca7c0
#!/usr/bin/python import wx class test(wx.Frame): def __init__(self,parent,id): wx.Frame.__init__(self,parent,id,"TestFrame",size=(500,500)) if __name__ == '__main__': app = wx.PySimpleApp() frame = test(parent=None,id=-1,) frame.show() app.mainloop()
[ "#!/usr/bin/python\nimport wx\n\nclass test(wx.Frame):\n def __init__(self,parent,id):\n wx.Frame.__init__(self,parent,id,\"TestFrame\",size=(500,500))\n\nif __name__ == '__main__':\n app = wx.PySimpleApp()\n frame = test(parent=None,id=-1,)\n frame.show()\n app.mainloop()\n", "import wx\n\n...
false
5,002
2bc3b0df720788e43da3d9c28adb22b3b1be8c58
import logging from django.contrib.auth.models import User import json from django.http import HttpResponse from enumfields.fields import EnumFieldMixin from Api.models import Status logger = logging.getLogger() logger.setLevel(logging.INFO) def check_cookie(request): # Post.objects.all().delete() result = ...
[ "import logging\nfrom django.contrib.auth.models import User\nimport json\nfrom django.http import HttpResponse\nfrom enumfields.fields import EnumFieldMixin\n\nfrom Api.models import Status\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef check_cookie(request):\n # Post.objects.all().dele...
false
5,003
13e2f474294edb7c78bd81456097d1389e6a0f1b
from .isearch import ISearcher __all__ = ['ISearcher']
[ "from .isearch import ISearcher\n\n__all__ = ['ISearcher']\n", "from .isearch import ISearcher\n__all__ = ['ISearcher']\n", "<import token>\n__all__ = ['ISearcher']\n", "<import token>\n<assignment token>\n" ]
false
5,004
d960d3d1680f825f0f68fc6d66f491bbbba805ce
# Kipland Melton import psutil import math def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("%", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return "%s %s" % (s, siz...
[ "# Kipland Melton\nimport psutil\nimport math\n\ndef convert_size(size_bytes):\n if size_bytes == 0:\n return \"0B\"\n size_name = (\"%\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\")\n i = int(math.floor(math.log(size_bytes, 1024)))\n p = math.pow(1024, i)\n s = round(size_bytes ...
false
5,005
b7606befe123c4fb6840a1bc62e43e6721edfcc3
import boto3 import json region = 'us-east-2' ec2 = boto3.resource('ec2',region) ImageId = 'ami-07efac79022b86107' KeyName = 'aws_keypair' InstanceType = 't2.micro' #IamInstanceProfile = instances = ec2.create_instances( ImageId =ImageId, MinCount = 1, MaxCount = 5, KeyName = KeyName, InstanceTyp...
[ "import boto3\nimport json\n\nregion = 'us-east-2'\n\nec2 = boto3.resource('ec2',region)\n\nImageId = 'ami-07efac79022b86107'\nKeyName = 'aws_keypair'\nInstanceType = 't2.micro'\n#IamInstanceProfile =\ninstances = ec2.create_instances(\n ImageId =ImageId,\n MinCount = 1,\n MaxCount = 5,\n KeyName = KeyN...
false
5,006
d90a4b00d97cecf3612915a72e48a363c5dcc97b
#!/usr/bin/python3 """Locked class module""" class LockedClass: """test class with locked dynamic attruibute creation """ __slots__ = 'first_name'
[ "#!/usr/bin/python3\n\"\"\"Locked class module\"\"\"\n\n\nclass LockedClass:\n \"\"\"test class with locked dynamic attruibute creation\n \"\"\"\n __slots__ = 'first_name'\n", "<docstring token>\n\n\nclass LockedClass:\n \"\"\"test class with locked dynamic attruibute creation\n \"\"\"\n __slots...
false
5,007
b1c8aceab44574d0f53d30969861be028c920ef2
# Create your views here. # -*- coding: utf-8 -*- from json import dumps from django.shortcuts import render_to_response from django.http import Http404, HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.conf import settings from utils import Utils, MERCS, ENTITY, PARTS, ARMY, D...
[ "# Create your views here.\n# -*- coding: utf-8 -*-\n\nfrom json import dumps\nfrom django.shortcuts import render_to_response\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.template import RequestContext\nfrom django.conf import settings\nfrom utils import Utils, MERCS, ENTITY, P...
true
5,008
fb2ef5a90b6e2582450726905868dd1b78e36166
# 2019/10/08 2019년10월8일 ss = input('날짜: 년/월/일 입력-> ') sslist = ss.split('/') print(sslist) print('입력하신 날짜의 10년 후 -> ', end='') year = int(sslist[0]) + 10 print(str(year) + "년", end='') print(sslist[1] + "월", end='') print(sslist[2] + "일")
[ "# 2019/10/08 2019년10월8일\r\n\r\nss = input('날짜: 년/월/일 입력-> ')\r\n\r\nsslist = ss.split('/')\r\nprint(sslist)\r\n\r\nprint('입력하신 날짜의 10년 후 -> ', end='')\r\nyear = int(sslist[0]) + 10\r\nprint(str(year) + \"년\", end='')\r\nprint(sslist[1] + \"월\", end='')\r\nprint(sslist[2] + \"일\")\r\n", "ss = input('날짜: 년/월/일...
false
5,009
14f3c941856ddf6bd7b3e046f21072f0b5f7b036
class Solution: def minimumDeletions(self, nums: List[int]) -> int: n = len(nums) a = nums.index(min(nums)) b = nums.index(max(nums)) if a > b: a, b = b, a return min(a + 1 + n - b, b + 1, n - a)
[ "class Solution:\n def minimumDeletions(self, nums: List[int]) -> int:\n n = len(nums)\n a = nums.index(min(nums))\n b = nums.index(max(nums))\n if a > b:\n a, b = b, a\n return min(a + 1 + n - b, b + 1, n - a)\n", "class Solution:\n\n def minimumDeletions(self, nums: List[int]) ->int:\n ...
false
5,010
394f835064d070a30040b6f01b25b6f0e005827d
""" Created on Fri Jan 07 20:53:58 2022 @author: Ankit Bharti """ from unittest import TestCase, main from cuboid_volume import * class TestCuboid(TestCase): def test_volume(self): self.assertAlmostEqual(cuboid_volume(2), 8) self.assertAlmostEqual(cuboid_volume(1), 1) self.assertAlmostE...
[ "\"\"\"\nCreated on Fri Jan 07 20:53:58 2022\n@author: Ankit Bharti\n\n\"\"\"\n\n\nfrom unittest import TestCase, main\nfrom cuboid_volume import *\n\n\nclass TestCuboid(TestCase):\n def test_volume(self):\n self.assertAlmostEqual(cuboid_volume(2), 8)\n self.assertAlmostEqual(cuboid_volume(1), 1)\n...
false
5,011
4bd6a7c7fc6a788b2cb010f6513872bd3e0d396c
import os import random readpath = './DBLP/' writepath = './DBLP/' dataname = 'dblp.txt' labelname = 'node2label.txt' testsetname = writepath + 'dblp_testset.txt' def run(save_rate): rdataname = readpath + dataname rlabelname = readpath + labelname wdataname = writepath + dataname wlabelname = writepath + labelna...
[ "import os\nimport random\n\nreadpath = './DBLP/'\nwritepath = './DBLP/'\ndataname = 'dblp.txt'\nlabelname = 'node2label.txt'\ntestsetname = writepath + 'dblp_testset.txt'\n\ndef run(save_rate):\n\trdataname = readpath + dataname\n\trlabelname = readpath + labelname\n\twdataname = writepath + dataname\n\twlabelname...
false
5,012
26ef7de89e2e38c419310cc66a33d5dc0575fc0d
# Generates an infinite series of odd numbers def odds(): n = 1 while True: yield n n += 2 def pi_series(): odd_nums = odds() approximation = 0 while True: approximation += (4 / next(odd_nums)) yield approximation approxim...
[ "# Generates an infinite series of odd numbers\ndef odds():\n n = 1\n while True:\n yield n\n n += 2\n\n\ndef pi_series():\n odd_nums = odds()\n approximation = 0\n while True:\n approximation += (4 / next(odd_nums))\n yield approximation\n ...
false
5,013
d386047c087155b1809d47349339eb6882cf8e26
import stock as stk import portfolio as portf import plot import sys import cmd import os import decision as des class CLI(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = '$> ' self.stk_data_coll = stk.StockDataCollection() self.add_to_plot_lst = [] ...
[ "import stock as stk\nimport portfolio as portf\nimport plot\nimport sys\nimport cmd\nimport os\nimport decision as des\n \n \nclass CLI(cmd.Cmd):\n\n def __init__(self):\n cmd.Cmd.__init__(self)\n self.prompt = '$> '\n self.stk_data_coll = stk.StockDataCollection()\n self.add_to_...
true
5,014
706f8d83bc9b4fab6f6d365c047c33913daece61
"""This module runs cdb on a process and !exploitable on any exceptions. """ import ctypes import logging import os from pprint import pformat from subprocess import Popen from threading import Timer import time from certfuzz.debuggers.debugger_base import Debugger as DebuggerBase from certfuzz.debuggers.ou...
[ "\"\"\"This module runs cdb on a process and !exploitable on any exceptions.\r\n\"\"\"\r\nimport ctypes\r\nimport logging\r\nimport os\r\nfrom pprint import pformat\r\nfrom subprocess import Popen\r\nfrom threading import Timer\r\nimport time\r\n\r\nfrom certfuzz.debuggers.debugger_base import Debugger as DebuggerB...
false
5,015
15e1ce95398ff155fe594c3b39936d82d71ab9e2
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, inspect from flask import Flask, jsonify, render_template, redirect from flask_pymongo import PyMongo from config import mongo_password, mongo_username, sql_username, sql_pass...
[ "import sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func, inspect\nfrom flask import Flask, jsonify, render_template, redirect\nfrom flask_pymongo import PyMongo\nfrom config import mongo_password, mongo_username, sql_usernam...
false
5,016
ba09dbe3fbca51ece8a7d482324a2dec32e7dc8a
import librosa import librosa.display import matplotlib.pyplot as plt import os import numpy as np import time import multiprocessing as mp from tempfile import TemporaryFile class DataSet(): def __init__(self,training_folder): self.training_folder = training_folder print("load Data") def load...
[ "import librosa\nimport librosa.display\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nimport time\nimport multiprocessing as mp\nfrom tempfile import TemporaryFile\n\nclass DataSet():\n def __init__(self,training_folder):\n self.training_folder = training_folder\n print(\"load Da...
false
5,017
52dc8a4f9165a88dddc1da16e0adb045c4d851ed
import json from typing import TYPE_CHECKING import pytest from eth_utils import is_checksum_address from rotkehlchen.globaldb.handler import GlobalDBHandler from rotkehlchen.types import ChainID if TYPE_CHECKING: from rotkehlchen.chain.ethereum.node_inquirer import EthereumInquirer def test_evm_contracts_data...
[ "import json\nfrom typing import TYPE_CHECKING\n\nimport pytest\nfrom eth_utils import is_checksum_address\n\nfrom rotkehlchen.globaldb.handler import GlobalDBHandler\nfrom rotkehlchen.types import ChainID\n\nif TYPE_CHECKING:\n from rotkehlchen.chain.ethereum.node_inquirer import EthereumInquirer\n\n\ndef test_...
false
5,018
fe45fc6cd16be37b320844c5a8b43a964c016dd1
# -*- coding: utf-8 -*- from Clases import Lugar from Clases import Evento import Dialogos import Funciones puntuacion_necesaria = 10 hp_inicial = 5 eventos = [ Evento("dormir", 2, False, -3, 4, Dialogos.descripciones_eventos[0], Dialogos.descripciones_triunfos[0], Dialogos.descripciones...
[ "# -*- coding: utf-8 -*-\r\nfrom Clases import Lugar\r\nfrom Clases import Evento\r\n\r\nimport Dialogos\r\nimport Funciones\r\n\r\npuntuacion_necesaria = 10\r\nhp_inicial = 5\r\n\r\n\r\neventos = [\r\n Evento(\"dormir\", 2, False, -3, 4, Dialogos.descripciones_eventos[0], Dialogos.descripciones_triunfos[0],\r\n...
false
5,019
4620b52a43f2469ff0350d8ef6548de3a7fe1b55
# -*- snakemake -*- # # CENTIPEDE: Transcription factor footprinting and binding site prediction # install.packages("CENTIPEDE", repos="http://R-Forge.R-project.org") # # http://centipede.uchicago.edu/ # include: '../ngs.settings.smk' config_default = { 'bio.ngs.motif.centipede' : { 'options' : '', ...
[ "# -*- snakemake -*-\n#\n# CENTIPEDE: Transcription factor footprinting and binding site prediction\n# install.packages(\"CENTIPEDE\", repos=\"http://R-Forge.R-project.org\") \n# \n# http://centipede.uchicago.edu/\n#\ninclude: '../ngs.settings.smk'\n\nconfig_default = {\n 'bio.ngs.motif.centipede' : {\n ...
false
5,020
cdc9bc97332a3914415b16f00bc098acc7a02863
L = "chaine de caractere" print("parcours par élément") for e in L : print("caractere : *"+e+"*")
[ "L = \"chaine de caractere\"\nprint(\"parcours par élément\")\nfor e in L :\n print(\"caractere : *\"+e+\"*\")\n", "L = 'chaine de caractere'\nprint('parcours par élément')\nfor e in L:\n print('caractere : *' + e + '*')\n", "<assignment token>\nprint('parcours par élément')\nfor e in L:\n print('carac...
false
5,021
69511933697905fb4f365c895264596f19dc1d8d
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 26 18:39:26 2020 @author: Fanny Fredriksson and Karen Marie Sandø Ambrosen """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from tqdm import tqdm #count ffor loops import math from sklearn.model_selection import GridSearch...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 26 18:39:26 2020\n\n@author: Fanny Fredriksson and Karen Marie Sandø Ambrosen\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tqdm import tqdm #count ffor loops\nimport math\nfrom sklearn.model_sel...
false
5,022
7d8c2aa5674704d4443034c29bbdc715da9fd567
""" db.集合.update() """ """ 实例 被替换了 > db.test1000.update({'name':'dapeng'},{'name':'大鹏'}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.test1000.find() { "_id" : ObjectId("5c35549d7ad0cf935d3c150d"), "name" : "大鹏" } { "_id" : ObjectId("5c3554f37ad0cf935d3c150e"), "nInserted" : 1 } { "_id" : Obj...
[ "\"\"\"\ndb.集合.update()\n\n\"\"\"\n\"\"\"\n实例 被替换了\n> db.test1000.update({'name':'dapeng'},{'name':'大鹏'})\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n> db.test1000.find()\n{ \"_id\" : ObjectId(\"5c35549d7ad0cf935d3c150d\"), \"name\" : \"大鹏\" }\n{ \"_id\" : ObjectId(\"5c3554f37ad0cf935d...
false
5,023
c0c0ed31a09f2b49448bc1f3519aa61daaba20af
import sys input = sys.stdin.readline from collections import deque size, num = map(int,input().split()) position = list(map(int,input().split())) cnt =0 nums = [] for k in range(1,size+1) : nums.append(k) size = deque(nums) position = deque(position) while position != deque([]) : if position[0]==1: si...
[ "import sys\ninput = sys.stdin.readline\nfrom collections import deque\n\nsize, num = map(int,input().split())\nposition = list(map(int,input().split()))\ncnt =0\nnums = []\nfor k in range(1,size+1) :\n nums.append(k)\nsize = deque(nums)\nposition = deque(position)\nwhile position != deque([]) :\n if position...
false
5,024
351421ef6a40e3a4bd4549a1851fbf4bed9ddf30
ghj=input("enter your first name:") print("Welcome to my Quiz:\nIf you go wrong once you lose but if you give all the answers correct then you win but no CHEATING.") print("Q1:-Who is the president of India?") winlist=("ramnath govind","multiple choice question","multiple choice questions","mumbai") enter=input("en...
[ "ghj=input(\"enter your first name:\")\r\nprint(\"Welcome to my Quiz:\\nIf you go wrong once you lose but if you give all the answers correct then you win but no CHEATING.\")\r\nprint(\"Q1:-Who is the president of India?\")\r\nwinlist=(\"ramnath govind\",\"multiple choice question\",\"multiple choice questions\",\"...
false
5,025
deff4eb3ae933a99036f39213ceaf2144b682904
from __future__ import print_function import re import sys from pyspark import SparkContext # define a regular expression for delimiters NON_WORDS_DELIMITER = re.compile(r'[^\w\d]+') def main(): if len(sys.argv) < 2: print('''Usage: pyspark q2.py <file> e.g. pyspark q2.py file:///home/cloudera/test...
[ "from __future__ import print_function\n\nimport re\nimport sys\nfrom pyspark import SparkContext\n\n\n# define a regular expression for delimiters\nNON_WORDS_DELIMITER = re.compile(r'[^\\w\\d]+')\n\n\ndef main():\n if len(sys.argv) < 2:\n print('''Usage: pyspark q2.py <file>\n e.g. pyspark q2.py file:...
false
5,026
2b9dfd0cfd62276330f1a4f983f318076f329437
def domain_name(url): while "https://" in url or "http://" in url or "www." in url: url = url.replace("https://", ' ') if "https://" in url else url.replace("http://", ' ') if "http://" in url else url.replace("www.", ' ') url = list(url) for i in range(len(url)): if url[i] == ".": ...
[ "def domain_name(url):\n while \"https://\" in url or \"http://\" in url or \"www.\" in url:\n url = url.replace(\"https://\", ' ') if \"https://\" in url else url.replace(\"http://\", ' ') if \"http://\" in url else url.replace(\"www.\", ' ')\n url = list(url)\n for i in range(len(url)):\n i...
false
5,027
bf3b529f8f06619c94d2dfca283df086466af4ea
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-26 16:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20170308_1949'), ] operations = [ migrations.AlterField( ...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.5 on 2017-03-26 16:51\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0002_auto_20170308_1949'),\n ]\n\n operations = [\n migra...
false
5,028
9bc15f063adc7d2a5ea81d090736ab6ce66a03d4
from django.db import models from django.utils.safestring import mark_safe from ondoc.authentication.models import TimeStampedModel, CreatedByModel, Image import datetime from django.contrib.contenttypes.models import ContentType from django.urls import reverse from ondoc.doctor.models import Doctor, PracticeSpecializ...
[ "from django.db import models\nfrom django.utils.safestring import mark_safe\nfrom ondoc.authentication.models import TimeStampedModel, CreatedByModel, Image\nimport datetime\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.urls import reverse\n\nfrom ondoc.doctor.models import Doctor, Pract...
false
5,029
cc160b1b0478446ba0daec4a0fe9e63453df3d96
N = int(input()) A_list = list(map(int,input().split())) B_list = list(map(int,input().split())) C_list = list(map(int,input().split())) ans = 0 for i in range(N): ans += B_list[A_list[i]-1] if i < N-1: if A_list[i]+1==A_list[i+1]: ans += C_list[A_list[i]-1] print(ans)
[ "N = int(input())\nA_list = list(map(int,input().split()))\nB_list = list(map(int,input().split()))\nC_list = list(map(int,input().split()))\nans = 0\nfor i in range(N):\n ans += B_list[A_list[i]-1]\n \n if i < N-1:\n if A_list[i]+1==A_list[i+1]:\n ans += C_list[A_list[i]-1]\nprint(ans)\n...
false
5,030
4c1fea4dcf143ec976d3956039616963760d5af6
# add some description here import glob import matplotlib.pyplot as plt import numpy as np import pandas as pd import xarray as xr import pandas as pd import os import pickle from scipy.interpolate import griddata from mpl_toolkits.basemap import Basemap from mpl_toolkits.axes_grid1 import make_axes_locatable from mat...
[ "# add some description here\n\nimport glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport pandas as pd\nimport os\nimport pickle\nfrom scipy.interpolate import griddata\nfrom mpl_toolkits.basemap import Basemap\nfrom mpl_toolkits.axes_grid1 import make_axes_l...
false
5,031
6025b8d4015572ea1a760c1b4bc7200a1019c802
from can.interfaces.ics_neovi.neovi_bus import NeoViBus
[ "from can.interfaces.ics_neovi.neovi_bus import NeoViBus\n", "<import token>\n" ]
false
5,032
0ff8743e54509a76e9a7add4be9da279bdee82a6
class Solution: def calculate(self, s: str) -> int: nums = [] ops = [] def cal(): a = nums.pop() b = nums.pop() c = ops.pop() if c == '+': nums.append(b + a) elif c == '-': nums.append(b - a) ...
[ "class Solution:\n def calculate(self, s: str) -> int:\n nums = []\n ops = []\n\n def cal():\n a = nums.pop()\n b = nums.pop()\n c = ops.pop()\n if c == '+':\n nums.append(b + a)\n elif c == '-':\n nums.appe...
false
5,033
d50618f7784e69b46cb665ec1a9c56f7a2867785
#n-repeated element class Solution: def repeatedNTimes(self, A): freq = {} for i in A: if i in freq.keys(): freq[i] += 1 else: freq[i] = 1 key = list(freq.keys()) val = list(freq.values()) m = max(val) return key...
[ "#n-repeated element\nclass Solution:\n def repeatedNTimes(self, A):\n freq = {}\n for i in A:\n if i in freq.keys():\n freq[i] += 1\n else:\n freq[i] = 1\n key = list(freq.keys())\n val = list(freq.values())\n m = max(val)\n ...
false
5,034
a8f200e0ae1252df4ad6560e5756347cd0e4c8ba
""" Client component of the Quartjes connector. Use the ClientConnector to create a connection to the Quartjes server. Usage ----- Create an instance of this object with the host and port to connect to. Call the start() method to establish the connection. Now the database and the stock_exchange variable can be used to...
[ "\"\"\"\nClient component of the Quartjes connector. Use the ClientConnector to create\na connection to the Quartjes server.\n\nUsage\n-----\nCreate an instance of this object with the host and port to connect to.\nCall the start() method to establish the connection.\nNow the database and the stock_exchange variabl...
false
5,035
fe01b78d29dc456f7a537dd5639bc658fc184e36
from collections import defaultdict, namedtuple from color import RGB, clamp import math import controls_model as controls from eyes import Eye, MutableEye from geom import ALL #from icicles.ice_geom import ALL def load_geometry(mapfile): """ Load sheep neighbor geometry Returns a map { panel: [(edge-ne...
[ "from collections import defaultdict, namedtuple\nfrom color import RGB, clamp\n\nimport math\n\nimport controls_model as controls\nfrom eyes import Eye, MutableEye\n\nfrom geom import ALL\n#from icicles.ice_geom import ALL\n\ndef load_geometry(mapfile):\n \"\"\"\n Load sheep neighbor geometry\n Returns a ...
true
5,036
beb536b6d8883daaa7e41da03145dd98aa223cbf
from room import Room from player import Player from item import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""...
[ "from room import Room\nfrom player import Player\nfrom item import Item\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassage...
false
5,037
222a02f97df5ded6fea49e9eb201ed784a2a2423
# # # ## from __future__ import print_function, unicode_literals import inspect import os import pprint as pp import time from time import gmtime, strftime import subprocess from local import * from slurm import * class Job_status( object ): """ Enumerate class for job statuses, this is done differently in pyt...
[ "#\n# \n# \n##\n\nfrom __future__ import print_function, unicode_literals\nimport inspect\nimport os\nimport pprint as pp\nimport time\nfrom time import gmtime, strftime\nimport subprocess\n\nfrom local import *\nfrom slurm import *\n\nclass Job_status( object ):\n \"\"\" Enumerate class for job statuses, this i...
true
5,038
0cef70b8d661fe01ef4a1eda83a21e1186419a0d
# coding: utf-8 """ Created on Mon Oct 29 12:57:40 2018 @authors Jzhu, Lrasmy , Xin128 @ DeguiZhi Lab - UTHealth SBMI Last updated Feb 20 2020 """ #general utilities from __future__ import print_function, division from tabulate import tabulate import numpy as np import random import matplotlib.pyplot as plt try: ...
[ "# coding: utf-8\n\"\"\"\nCreated on Mon Oct 29 12:57:40 2018\n\n@authors Jzhu, Lrasmy , Xin128 @ DeguiZhi Lab - UTHealth SBMI\n\nLast updated Feb 20 2020\n\"\"\"\n\n#general utilities\nfrom __future__ import print_function, division\nfrom tabulate import tabulate\nimport numpy as np\nimport random\nimport matplotl...
false
5,039
c2e9a93861080be616b6d833a9343f1a2f018a0b
def presses(phrase): keyboard = [ '1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9', '*', ' 0', '#' ] amount = 0 for lttr in phrase.upper(): for key in keyboard: try: ...
[ "def presses(phrase):\n keyboard = [\n '1',\n 'ABC2',\n 'DEF3',\n 'GHI4',\n 'JKL5',\n 'MNO6',\n 'PQRS7',\n 'TUV8',\n 'WXYZ9',\n '*',\n ' 0',\n '#'\n ]\n amount = 0\n for lttr in phrase.upper():\n for key in keyboa...
false
5,040
866ec11f6fe13fb2283709128376080afc7493bf
from datetime import datetime import httplib2 from apiclient.discovery import build from flask_login import UserMixin from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from oauth2client.client import OAuth2Credentials from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.types import...
[ "from datetime import datetime\nimport httplib2\n\nfrom apiclient.discovery import build\nfrom flask_login import UserMixin\nfrom flask_migrate import Migrate\nfrom flask_sqlalchemy import SQLAlchemy\nfrom oauth2client.client import OAuth2Credentials\nfrom sqlalchemy.dialects.postgresql import JSONB\nfrom sqlalchem...
false
5,041
1c668cf6f145b85a09b248fefda46e928de64e41
from django.shortcuts import render from rest_framework import status, viewsets , response from . import models from . import serializers # Create your views here. class TodoViewset(viewsets.ModelViewSet): queryset = models.Todo.objects.all() serializer_class = serializers.TodoSerializer
[ "from django.shortcuts import render\nfrom rest_framework import status, viewsets , response\n\nfrom . import models\nfrom . import serializers\n\n# Create your views here.\n\nclass TodoViewset(viewsets.ModelViewSet):\n queryset = models.Todo.objects.all()\n serializer_class = serializers.TodoSerializer\n ...
false
5,042
d7ff5bf5d8f397500fcac30b73f469316c908f15
def divisible_by(numbers, divisor): res = [] for e in numbers: if e % divisor == 0: res.append(e) return res
[ "def divisible_by(numbers, divisor):\n res = []\n for e in numbers:\n if e % divisor == 0:\n res.append(e)\n return res\n", "<function token>\n" ]
false
5,043
67385d6d58cc79037660be546d41ea9ba1f790fa
from datetime import date def solution(mon: int, day: int) -> str: return date(2016, mon, day).strftime("%a").upper()
[ "from datetime import date\n\ndef solution(mon: int, day: int) -> str:\n return date(2016, mon, day).strftime(\"%a\").upper()\n", "from datetime import date\n\n\ndef solution(mon: int, day: int) ->str:\n return date(2016, mon, day).strftime('%a').upper()\n", "<import token>\n\n\ndef solution(mon: int, day...
false
5,044
f1ca3d7ff7efcf500f1a16e415b13c47fd08688d
# 30_Days_Of_Code # Day 2 # Boolean print(True) print(False)
[ "# 30_Days_Of_Code\n# Day 2\n# Boolean\nprint(True)\nprint(False)\n", "print(True)\nprint(False)\n", "<code token>\n" ]
false
5,045
6d0b9523668bd0b302fdbc196d3d7ff25be10b23
def clear_firefox_driver_session(firefox_driver): firefox_driver.delete_all_cookies() # Note this only works if the browser is set to a location. firefox_driver.execute_script('window.localStorage.clear();') firefox_driver.execute_script('window.sessionStorage.clear();') class LocationNotSet(Exception...
[ "def clear_firefox_driver_session(firefox_driver):\n firefox_driver.delete_all_cookies()\n # Note this only works if the browser is set to a location.\n firefox_driver.execute_script('window.localStorage.clear();')\n firefox_driver.execute_script('window.sessionStorage.clear();')\n\n\nclass LocationNotS...
false
5,046
d36552cc589b03008dc9edab8d7e4a003e26bd21
from __future__ import print_function import tensorflow as tf # from keras.callbacks import ModelCheckpoint from data import load_train_data from utils import * import os create_paths() log_file = open(global_path + "logs/log_file.txt", 'a') X_train, y_train = load_train_data() labeled_index = np.arange(0, nb_labeled...
[ "from __future__ import print_function\nimport tensorflow as tf\n# from keras.callbacks import ModelCheckpoint\nfrom data import load_train_data\nfrom utils import *\nimport os\n\ncreate_paths()\nlog_file = open(global_path + \"logs/log_file.txt\", 'a')\n\nX_train, y_train = load_train_data()\nlabeled_index = np.ar...
false
5,047
e1a2b33a1ec7aca21a157895d8c7c5b5f29ff49c
#!/usr/bin/python3 """ Requests username and tasks from JSON Placeholder based on userid (which is sys.argv[1]) """ import json import requests import sys if __name__ == "__main__": url = "https://jsonplaceholder.typicode.com" if len(sys.argv) > 1: user_id = sys.argv[1] name = requests.get("{}...
[ "#!/usr/bin/python3\n\"\"\"\nRequests username and tasks from JSON Placeholder\nbased on userid (which is sys.argv[1])\n\"\"\"\nimport json\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n url = \"https://jsonplaceholder.typicode.com\"\n if len(sys.argv) > 1:\n user_id = sys.argv[1]\n ...
false
5,048
de819a72ab659b50620fad2296027cb9f4d3e4c0
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import platform import subprocess # try to import json module, if got an error use simplejson instead of json. try: import json except ImportError: import simplejson as json # if your server uses fqdn, you can suppress the domain, just change the bellow...
[ "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport os\nimport platform\nimport subprocess\n\n# try to import json module, if got an error use simplejson instead of json.\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\n# if your server uses fqdn, you can suppress the domain, just...
false
5,049
8d4ffed90e103e61a85a54d6163770966fb2e5c9
#!/usr/bin/env python3 """Test telegram_menu package."""
[ "#!/usr/bin/env python3\n\n\"\"\"Test telegram_menu package.\"\"\"\n", "<docstring token>\n" ]
false
5,050
1a730f4a5fa2be434af41a3e320cab8338d93644
def describe(): desc = """ Problem : Given a string, find the length of the longest substring in it with no more than K distinct characters. For example : Input: String="araaci", K=2 Output: 4 Explanation: The longest substring with no more than '2' distinct characters is "araa", where the distinct char...
[ "def describe():\n desc = \"\"\"\nProblem : Given a string, find the length of the longest substring in it with no more than K distinct characters.\nFor example :\n Input: String=\"araaci\", K=2\n Output: 4\n Explanation: The longest substring with no more than '2' distinct characters is \"araa\", where...
false
5,051
7455eb670c2c019b8d066fcc6f2878a2136b7fd0
__author__ = "Prikly Grayp" __license__ = "MIT" __version__ = "1.0.0" __email__ = "priklygrayp@gmail.com" __status__ = "Development" from contextlib import closing class RefrigeratorRaider: '''Raid a refrigerator''' def open(self): print('Open fridge door.') def take(self, food): print('...
[ "__author__ = \"Prikly Grayp\"\n__license__ = \"MIT\"\n__version__ = \"1.0.0\"\n__email__ = \"priklygrayp@gmail.com\"\n__status__ = \"Development\"\n\nfrom contextlib import closing\n\nclass RefrigeratorRaider:\n '''Raid a refrigerator'''\n\n def open(self):\n print('Open fridge door.')\n\n def take...
false
5,052
9cc6700ab14bed9d69d90c1540f6d42186033a19
from typing import List def sift_up(heap: List, pos: int = None): if pos is None: pos = len(heap) - 1 current, parent = pos, (pos - 1) // 2 while current > 0: if heap[current] > heap[parent]: heap[current], heap[parent] = heap[parent], heap[current] else: b...
[ "from typing import List\n\n\ndef sift_up(heap: List, pos: int = None):\n if pos is None:\n pos = len(heap) - 1\n current, parent = pos, (pos - 1) // 2\n\n while current > 0:\n if heap[current] > heap[parent]:\n heap[current], heap[parent] = heap[parent], heap[current]\n els...
false
5,053
3a878c91218dfbf23477ae5b7561e9eecfcd1350
""" Created on Dec 1, 2014 @author: Ira Fich """ import random from igfig.containers import WeightedList class Replacer(): """ A class that replaces itself with a subclass of itself when you instantiate it """ subclass_weight = 0 def __new__(cls, *args, **kwargs): subs = WeightedList(cls.__subclasses__(),...
[ "\"\"\"\nCreated on Dec 1, 2014\n\n@author: Ira Fich\n\"\"\"\n\n\nimport random\nfrom igfig.containers import WeightedList\n\n\nclass Replacer():\n\t\"\"\"\n\tA class that replaces itself with a subclass of itself when you instantiate it\n\t\"\"\"\n\tsubclass_weight = 0\n\t\n\tdef __new__(cls, *args, **kwargs):\n\t...
false
5,054
25a159ca2abf0176135086324ab355d6f5d9fe9e
#!/bin/python3 import sys from collections import deque def connectedCell(matrix,n,m): # Complete this function visit = [] for j in range(n): a = [] for i in range(m): a.append(True) visit.append(a) #print(visit) path = 0 for i in range(n): for j in ...
[ "#!/bin/python3\n\nimport sys\nfrom collections import deque\n\ndef connectedCell(matrix,n,m):\n # Complete this function\n visit = []\n for j in range(n):\n a = []\n for i in range(m):\n a.append(True)\n visit.append(a)\n #print(visit)\n path = 0\n for i in range(n...
false
5,055
1b741b34649193b64479724670244d258cfbbdfc
import RPi.GPIO as GPIO import numpy as np import array import time import json import LED_GPIO as led import BUTTON_GPIO as btn import parseJson as gjs rndBtnState = False interval = .1 rndbtn = gjs.getJsonRnd() gpioValues = gjs.getJsonData() strArray = gpioValues[0] btnArray = gpioValues[1] ledArray = gpioValue...
[ "import RPi.GPIO as GPIO\nimport numpy as np\nimport array\nimport time\nimport json\n\nimport LED_GPIO as led \nimport BUTTON_GPIO as btn\nimport parseJson as gjs\n\nrndBtnState = False\ninterval = .1\n\nrndbtn = gjs.getJsonRnd()\n\ngpioValues = gjs.getJsonData()\n\nstrArray = gpioValues[0]\nbtnArray = gpioValues[...
true
5,056
44dee207ffa4f78293484126234a3b606e79915b
#!/usr/bin/env python3 # Written by jack @ nyi # Licensed under FreeBSD's 3 clause BSD license. see LICENSE '''This class calls the system's "ping" command and stores the results''' class sys_ping: '''this class is a python wrapper for UNIX system ping command, subclass ping does the work, last stores data from t...
[ "#!/usr/bin/env python3\n# Written by jack @ nyi\n# Licensed under FreeBSD's 3 clause BSD license. see LICENSE\n\n'''This class calls the system's \"ping\" command and stores the results'''\n\nclass sys_ping:\n '''this class is a python wrapper for UNIX system ping command, subclass ping does the work, last stor...
false
5,057
e3071643548bb3a4e8d0a5710820ad39b8a6b04b
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to view and manage OPenn repositories. Use this script to list and update OPenn primary repositories, to view repository details, and to list documents in each repository. """ import os import sys import argparse import logging sys.path.insert(0, os.path.abspa...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Script to view and manage OPenn repositories. Use this script to list and\nupdate OPenn primary repositories, to view repository details, and to list\ndocuments in each repository.\n\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nimport logging\n\nsys.pat...
true
5,058
2fc2fd6631cee5f3737dadaac1a115c045af0986
# Libraries from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import relationship # Taskobra from taskobra.orm.base import ORMBase from taskobra.orm.relationships import SystemComponent class System(ORMBase): __tablename__ ...
[ "# Libraries\nfrom sqlalchemy import Column, ForeignKey, Integer, String\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom sqlalchemy.orm import relationship\n# Taskobra\nfrom taskobra.orm.base import ORMBase\nfrom taskobra.orm.relationships import SystemComponent\n\n\nclass System(ORMBase):\n ...
false
5,059
ac8c8dc4bcccef7942dd48d54902e13e811f950c
#!/usr/bin/env python # coding: utf-8 from unittest import TestCase from optimoida.logging import ( SUCCESS, FAILURE, logger) class LoggerTestCase(TestCase): def test_flag_value(self): self.assertEqual(SUCCESS, "\x1b[34mSUCCESS\x1b[0m") self.assertEqual(FAILURE, "\x1b[31mFAILURE\x1b[0m") ...
[ "#!/usr/bin/env python\n# coding: utf-8\n\nfrom unittest import TestCase\nfrom optimoida.logging import (\n SUCCESS, FAILURE, logger)\n\n\nclass LoggerTestCase(TestCase):\n\n def test_flag_value(self):\n\n self.assertEqual(SUCCESS, \"\\x1b[34mSUCCESS\\x1b[0m\")\n self.assertEqual(FAILURE, \"\\x1...
false
5,060
416f4c6bbd2f2b9562ab2d1477df4ebc45070d8d
#!/usr/bin/env python3 import argparse import boutvecma import easyvvuq as uq import chaospy import os import numpy as np import time from dask.distributed import Client from dask_jobqueue import SLURMCluster import matplotlib.pyplot as plt if __name__ == "__main__": parser = argparse.ArgumentParser(description...
[ "#!/usr/bin/env python3\n\nimport argparse\nimport boutvecma\nimport easyvvuq as uq\nimport chaospy\nimport os\nimport numpy as np\nimport time\nfrom dask.distributed import Client\nfrom dask_jobqueue import SLURMCluster\nimport matplotlib.pyplot as plt\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.Arg...
false
5,061
1a9cad6e49e5ed2bb7781f9fec930d48ec048b3b
#!/usr/bin/env python # coding: utf-8 # MIT Licensed # http://opensource.org/licenses/MIT led_dir = "/sys/class/gpio/gpio40/" led_pin = led_dir + "value" led_mode = led_dir + "direction" with open(led_mode, "wb") as f: f.write("out") with open(led_pin, "wb") as f: f.write(__import__("sys").argv[1]) """ Contrib...
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# MIT Licensed\n# http://opensource.org/licenses/MIT\n\nled_dir = \"/sys/class/gpio/gpio40/\"\nled_pin = led_dir + \"value\"\nled_mode = led_dir + \"direction\"\n\nwith open(led_mode, \"wb\") as f:\n f.write(\"out\")\n\nwith open(led_pin, \"wb\") as f:\n f.write(__import...
false
5,062
70c20b38edb01552a8c7531b3e87a9302ffaf6c5
# -*- coding: utf-8 -*- """Module providing views for asset storage folder""" from Products.Five.browser import BrowserView from plone import api from plone.app.contenttypes.interfaces import IImage class AssetRepositoryView(BrowserView): """ Folderish content page default view """ def contained_items(self, u...
[ "# -*- coding: utf-8 -*-\n\"\"\"Module providing views for asset storage folder\"\"\"\nfrom Products.Five.browser import BrowserView\nfrom plone import api\nfrom plone.app.contenttypes.interfaces import IImage\n\nclass AssetRepositoryView(BrowserView):\n \"\"\" Folderish content page default view \"\"\"\n\n d...
false
5,063
28077af0759e062078f7b9d1f7bbbb93c62835cb
version = (2, 5, 8) version_string = ".".join(str(v) for v in version) release_date = "2015.12.27"
[ "version = (2, 5, 8)\nversion_string = \".\".join(str(v) for v in version)\n\nrelease_date = \"2015.12.27\"\n", "version = 2, 5, 8\nversion_string = '.'.join(str(v) for v in version)\nrelease_date = '2015.12.27'\n", "<assignment token>\n" ]
false
5,064
ec19567b49f686f613308d79e439f6ff9053fa40
import sys import os import logging import sh from ..util.path import SmartTempDir, replace_path logger = logging.getLogger('pyrsss.gps.teqc') def rinex_info(rinex_fname, nav_fname, work_path=None): """ Query RINEX file *rinex_fname* and RINEX nav file *nav_fname* for usef...
[ "import sys\nimport os\nimport logging\n\nimport sh\n\nfrom ..util.path import SmartTempDir, replace_path\n\nlogger = logging.getLogger('pyrsss.gps.teqc')\n\n\ndef rinex_info(rinex_fname,\n nav_fname,\n work_path=None):\n \"\"\"\n Query RINEX file *rinex_fname* and RINEX nav file *...
false
5,065
ecd5097d9d497b62b89217ee3c46506f21fc15d2
from web3 import Web3, HTTPProvider, IPCProvider from tcmb.tcmb_parser import TCMB_Processor from ecb.ecb_parser import ECB_Processor from web3.contract import ConciseContract from web3.middleware import geth_poa_middleware import json import time tcmb_currencies = ["TRY", "USD", "AUD", "DKK", "EUR", "GBP", "CHF", "SE...
[ "from web3 import Web3, HTTPProvider, IPCProvider\nfrom tcmb.tcmb_parser import TCMB_Processor\nfrom ecb.ecb_parser import ECB_Processor\nfrom web3.contract import ConciseContract\nfrom web3.middleware import geth_poa_middleware\nimport json\nimport time\n\ntcmb_currencies = [\"TRY\", \"USD\", \"AUD\", \"DKK\", \"E...
false
5,066
d9cdcf64042c3c6c4b45ec0e3334ba756dd43fcd
# -*- coding: utf-8 -*- """ Created on Mon May 2 17:24:00 2016 @author: pasca """ # -*- coding: utf-8 -*- import os.path as op from nipype.utils.filemanip import split_filename as split_f from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec from nipype.interfaces.base import traits, File, Trait...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 2 17:24:00 2016\n\n@author: pasca\n\"\"\"\n\n# -*- coding: utf-8 -*-\nimport os.path as op\n\nfrom nipype.utils.filemanip import split_filename as split_f\n\nfrom nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec\nfrom nipype.interfaces.base im...
true
5,067
4a8d203872a1e86c54142dea6cd04c1cac6bcfb2
# coding: utf-8 # In[1]: import numpy as np import pandas as pd from sklearn.svm import SVR # In[2]: from sklearn.preprocessing import StandardScaler # In[3]: #import matplotlib.pyplot as plt # %matplotlib inline # In[90]: aapl = pd.read_csv('return_fcast.csv') # In[79]: y = aapl['return'] # In[80]: ...
[ "\n# coding: utf-8\n\n# In[1]:\n\nimport numpy as np\n\nimport pandas as pd\nfrom sklearn.svm import SVR\n\n\n# In[2]:\n\nfrom sklearn.preprocessing import StandardScaler\n\n\n# In[3]:\n\n#import matplotlib.pyplot as plt\n# %matplotlib inline\n\n\n# In[90]:\n\naapl = pd.read_csv('return_fcast.csv')\n\n\n# In[79]:\n...
false
5,068
2a09711e3e487c5d7790af592ff2eb03bb53cff2
def inplace_quick_sort(S, start, end): if start > end: return pivot = S[end] left = start right = end - 1 while left <= right: while left <= right and S[left] < pivot: left += 1 while left <= right and pivot < S[right]: right -= 1 ...
[ "def inplace_quick_sort(S, start, end):\r\n if start > end:\r\n return\r\n\r\n pivot = S[end]\r\n left = start\r\n right = end - 1\r\n\r\n while left <= right:\r\n while left <= right and S[left] < pivot:\r\n left += 1\r\n while left <= right and pivot < S[right]:\r\n ...
false
5,069
046db03b146ce0182ba7889908f536a09de051d5
from HDPython import * import HDPython.examples as ahe from enum import Enum, auto class counter_state(Enum): idle = auto() running = auto() done = auto() class Counter_cl(v_class_master): def __init__(self): super().__init__() self.counter = v_variable(v_slv(32)) self.cou...
[ "from HDPython import *\nimport HDPython.examples as ahe\nfrom enum import Enum, auto\n\nclass counter_state(Enum):\n idle = auto()\n running = auto()\n done = auto()\n\nclass Counter_cl(v_class_master):\n def __init__(self):\n super().__init__()\n self.counter = v_variable(v_slv(32))...
false
5,070
628fdf848079d0ecf5bf4f5bd46e07ad6cd10358
from threading import Thread import time def sleeping(): time.sleep(5) print('Ended') Thread(target=sleeping, daemon=True).start() print('Hello world') time.sleep(5.5)
[ "from threading import Thread\nimport time\n\n\ndef sleeping():\n time.sleep(5)\n print('Ended')\n\n\nThread(target=sleeping, daemon=True).start()\nprint('Hello world')\ntime.sleep(5.5)", "from threading import Thread\nimport time\n\n\ndef sleeping():\n time.sleep(5)\n print('Ended')\n\n\nThread(targe...
false
5,071
454f885e2254295ce6508e70c0348f5cbe855520
from handler.auth import provider_required from handler.provider import ProviderBaseHandler from forms.provider import ProviderAddressForm, ProviderVanityURLForm import logging from data import db from util import saved_message class ProviderEditAddressHandler(ProviderBaseHandler): @provider_required def get(s...
[ "from handler.auth import provider_required\nfrom handler.provider import ProviderBaseHandler\nfrom forms.provider import ProviderAddressForm, ProviderVanityURLForm\nimport logging\nfrom data import db\nfrom util import saved_message\n\nclass ProviderEditAddressHandler(ProviderBaseHandler):\n @provider_required\...
false
5,072
2dc4a4ae8e02e823073b1a9711dbd864a54bab43
class Account: '''은행계좌를 표현하는 클래스''' def __init__(self,name,account): self.name = name self._balance = amount def __str__(self): return '예금주 {}, 잔고 {}'.format(slef.name, self._balance) def _info(self): print('\t')
[ "class Account:\n '''은행계좌를 표현하는 클래스'''\n \n\n def __init__(self,name,account):\n self.name = name\n self._balance = amount\n\n def __str__(self):\n return '예금주 {}, 잔고 {}'.format(slef.name, self._balance)\n\n def _info(self):\n print('\\t')" ]
true
5,073
abf25cf3d4435754b916fa06e5e887b1e3589a1c
from django import forms from crawlr.models import Route, Category, UserProfile from django.contrib.auth.models import User class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text = "Please enter the category name.") views = forms.IntegerField(widget=for...
[ "from django import forms\nfrom crawlr.models import Route, Category, UserProfile\nfrom django.contrib.auth.models import User\n\nclass CategoryForm(forms.ModelForm):\n name = forms.CharField(max_length=128,\n help_text = \"Please enter the category name.\")\n views = forms.IntegerFi...
false
5,074
c2c1194ed23adda015b23897888d1a4cc11423d5
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014 Thibaut Lapierre <git@epheo.eu>. 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 # # ...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2014 Thibaut Lapierre <git@epheo.eu>. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the Licens...
false
5,075
fc8976141a19afd099f92cbbdb578e9c620cb745
array = [1, 7, 3, 8, 9, 2, 4] index = 0 while (index < len(array)): count = 0 while(count <= len(array)-2): if(count == len(array)-1): break if (array[count] > array[count+1]): sift = array[count] array[count] = array[count+1] array[count+1] = sift...
[ "array = [1, 7, 3, 8, 9, 2, 4]\nindex = 0\nwhile (index < len(array)):\n count = 0\n while(count <= len(array)-2):\n if(count == len(array)-1):\n break\n if (array[count] > array[count+1]):\n sift = array[count]\n array[count] = array[count+1]\n array[...
false
5,076
e7295336a168aa2361a9090e79465eab5f564599
__author__ = 'sushil' from .utilities import decompose_date from .DateConverter import _bs_to_ad, _ad_to_bs def convert_to_ad(bs_date): date_components = decompose_date(bs_date) year, month, day = date_components ad_year, ad_month, ad_day = _bs_to_ad(year, month, day) formatted_date = "{}-{:02}-{:02}"...
[ "__author__ = 'sushil'\nfrom .utilities import decompose_date\nfrom .DateConverter import _bs_to_ad, _ad_to_bs\n\ndef convert_to_ad(bs_date):\n date_components = decompose_date(bs_date)\n year, month, day = date_components\n\n ad_year, ad_month, ad_day = _bs_to_ad(year, month, day)\n formatted_date = \"...
false
5,077
839b3ebffebce95de25f75edc67a647bd1318268
#!/usr/bin/env python from __future__ import division from __future__ import print_function import numpy as np from mpi4py import MPI from parutils import pprint comm = MPI.COMM_WORLD pprint("-"*78) pprint(" Running on %d cores" % comm.size) pprint("-"*78) comm.Barrier() # Prepare a vector of N=5 elements to be ...
[ "#!/usr/bin/env python\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom mpi4py import MPI\n\nfrom parutils import pprint\n\ncomm = MPI.COMM_WORLD\n\npprint(\"-\"*78)\npprint(\" Running on %d cores\" % comm.size)\npprint(\"-\"*78)\n\ncomm.Barrier()\n\n# Prepare a ...
false
5,078
f1b36e3ce3189c8dca2e41664ac1a6d632d23f79
import ssl import sys import psycopg2 #conectarte python con postresql import paho.mqtt.client #pip install paho-mqtt import json conn = psycopg2.connect(host = 'raja.db.elephantsql.com', user= 'oyoqynnr', password ='myHVlpJkEO21o29GKYSvMCGI3g4y05bh', dbname= 'oyoqynnr') def on_connect(client, userdata, flags, r...
[ "import ssl\nimport sys\nimport psycopg2 #conectarte python con postresql\nimport paho.mqtt.client #pip install paho-mqtt\nimport json\n\nconn = psycopg2.connect(host = 'raja.db.elephantsql.com', user= 'oyoqynnr', password ='myHVlpJkEO21o29GKYSvMCGI3g4y05bh', dbname= 'oyoqynnr')\n\n \ndef on_connect(client, user...
false
5,079
1db397df2d030b2f622e701c46c15d653cb79e55
from ParseTree import ParseTree from Node import Node from NodeInfo import NodeInfo from TreeAdjustor import TreeAdjustor from model.SchemaGraph import SchemaGraph class TreeAdjustorTest: schema = None def __init__(self): return def getAdjustedTreesTest(self): T = ParseTree() ...
[ "\nfrom ParseTree import ParseTree\nfrom Node import Node\nfrom NodeInfo import NodeInfo\nfrom TreeAdjustor import TreeAdjustor\nfrom model.SchemaGraph import SchemaGraph\n\n\nclass TreeAdjustorTest:\n\n schema = None\n def __init__(self):\n return\n\n def getAdjustedTreesTest(self):\n\n\n\n ...
false
5,080
513aff6cf29bbce55e2382943767a9a21df2e98e
#-*-coding:utf-8-*- from Classify import get_train_data import sys ''' 获取训练集数据 ''' get_train_data(sys.argv[1], sys.argv[2])
[ "#-*-coding:utf-8-*-\nfrom Classify import get_train_data\nimport sys\n'''\n 获取训练集数据\n'''\nget_train_data(sys.argv[1], sys.argv[2])", "from Classify import get_train_data\nimport sys\n<docstring token>\nget_train_data(sys.argv[1], sys.argv[2])\n", "<import token>\n<docstring token>\nget_train_data(sys.argv[1...
false
5,081
dd7896e3beb5e33282b38efe0a4fc650e629b185
from gym_mag.envs.mag_control_env import MagControlEnv
[ "from gym_mag.envs.mag_control_env import MagControlEnv\n\n", "from gym_mag.envs.mag_control_env import MagControlEnv\n", "<import token>\n" ]
false
5,082
d86fe165e378e56650e3b76bf3d0f72e2a50a023
import requests rsp = requests.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s'%('wx27c0e6ef6a7f0716','6e29e232daf462652f66ee8acc11838b')) print(rsp.text)
[ "import requests\n\n\n\nrsp = requests.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s'%('wx27c0e6ef6a7f0716','6e29e232daf462652f66ee8acc11838b'))\nprint(rsp.text)", "import requests\nrsp = requests.get(\n 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_c...
false
5,083
e8e78610df4461a96f7d9858870de0e3482801fd
#!/usr/bin/env python import argparse import requests import sys import os import xml.dom.minidom __author__ = 'Tighe Schlottog || tschlottog@paloaltonetworks.com' ''' wf.py is a script to interact with the WildFire API to upload files or pull back reports on specific hashes. You need to have the argparse a...
[ "#!/usr/bin/env python\n\nimport argparse\nimport requests\nimport sys\nimport os\nimport xml.dom.minidom\n\n__author__ = 'Tighe Schlottog || tschlottog@paloaltonetworks.com'\n\n'''\n wf.py is a script to interact with the WildFire API to upload files or pull back reports on specific hashes. You\n need to ha...
true
5,084
7de3c0ab2e7c8ac00d37f1dfb5948027cfa7806c
######################################################### # Author: Todd A. Reisel # Date: 2/24/2003 # Class: StaticTemplateList ######################################################### from BaseClasses.TemplateList import *; class StaticTemplateList(TemplateList): def __init__(self, viewMode = None): Te...
[ "#########################################################\n# Author: Todd A. Reisel\n# Date: 2/24/2003\n# Class: StaticTemplateList\n#########################################################\n\nfrom BaseClasses.TemplateList import *;\n\nclass StaticTemplateList(TemplateList):\n def __init__(self, viewMode = Non...
false
5,085
f178ae70ce54244624c2254d0d6256b83144db33
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg # Define a function to compute color histogram features # Pass the color_space flag as 3-letter all caps string # like 'HSV' or 'LUV' etc. # KEEP IN MIND IF YOU DECIDE TO USE THIS FUNCTION LATER # IN YOUR PROJECT THAT IF ...
[ "import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n\n# Define a function to compute color histogram features \n# Pass the color_space flag as 3-letter all caps string\n# like 'HSV' or 'LUV' etc.\n# KEEP IN MIND IF YOU DECIDE TO USE THIS FUNCTION LATER\n# IN YOUR P...
false
5,086
6ce50552571594c7be77ac0bf3b5274f2f39e545
class Circle(): def __init__(self, radius, color="white"): self.radius = radius self.color = color c1 = Circle(10, "black") print("半径:{}, 色: {}".format(c1.radius, c1.color))
[ "class Circle():\n def __init__(self, radius, color=\"white\"):\n self.radius = radius\n self.color = color\n \nc1 = Circle(10, \"black\")\nprint(\"半径:{}, 色: {}\".format(c1.radius, c1.color))", "class Circle:\n\n def __init__(self, radius, color='white'):\n self.radius = radius\n...
false
5,087
4122da21abab462a28c925c1afa5792ec729a75a
import re print("Welcome to the Python Calculator") print("To stop calculator type: quit") previous = 0 run = True def perform_math(): '''(numbers) -> numbers accepts numbers from the user and performs continuous mathematical equations on them. precondition input must be numbers and m...
[ "import re\r\n\r\nprint(\"Welcome to the Python Calculator\")\r\nprint(\"To stop calculator type: quit\")\r\n\r\nprevious = 0\r\nrun = True\r\n\r\ndef perform_math():\r\n '''(numbers) -> numbers\r\n\r\n accepts numbers from the user and performs continuous\r\n mathematical equations on them.\r\n\r\n pre...
false
5,088
305554fc86ddc116677b6d95db7d94d9f2213c41
from .line_detection_research import score_pixel_v3p2
[ "from .line_detection_research import score_pixel_v3p2", "from .line_detection_research import score_pixel_v3p2\n", "<import token>\n" ]
false
5,089
3bb25cedc29f9063046329db1c00e7d9e10ce1cc
#!/usr/bin/env python # -*- coding: UTF-8 -*- from multiprocess.managers import BaseManager from linphonebase import LinphoneBase class MyManager(BaseManager): pass MyManager.register('LinphoneBase', LinphoneBase) manager = MyManager() manager.start() linphoneBase = manager.LinphoneBase()
[ "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nfrom multiprocess.managers import BaseManager\nfrom linphonebase import LinphoneBase\n\nclass MyManager(BaseManager):\n pass\n\nMyManager.register('LinphoneBase', LinphoneBase)\n\nmanager = MyManager()\nmanager.start()\nlinphoneBase = manager.LinphoneBase()\n", ...
false
5,090
5aaac757b766b0143ca3ea54d8fc4b8936160ec7
from django.urls import path from . import views # url configuration for view.index function app_name = 'movies' urlpatterns = [ path('', views.index, name='index'), # represents a root of this app path('<int:movie_id>', views.detail, name='detail') ]
[ "from django.urls import path\nfrom . import views\n\n# url configuration for view.index function\napp_name = 'movies'\nurlpatterns = [\n path('', views.index, name='index'), # represents a root of this app\n path('<int:movie_id>', views.detail, name='detail')\n]\n", "from django.urls import path\nfrom . i...
false
5,091
a7de079866d7ac80260b438043cf0403f598cebc
''' Write the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4. ''' x, y = 2.4, 6.4 perimeter = (x*2)+(y*2) area = x*y print("Perimeter is "+str(perimeter) + ", Area is " + str(area))
[ "'''\n\nWrite the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4.\n\n'''\nx, y = 2.4, 6.4\nperimeter = (x*2)+(y*2)\narea = x*y\nprint(\"Perimeter is \"+str(perimeter) + \", Area is \" + str(area))", "<docstring token>\nx, y = 2.4, 6.4\nperimeter = x * 2...
false
5,092
4ad3390f8f2c92f35acde507be7a7b713af997f2
from odoo import models, fields, api class Aceptar_letras_wizard(models.TransientModel): _name = 'aceptar_letras_wizard' _description = "Aceptar letras" def _get_letras(self): if self.env.context and self.env.context.get('active_ids'): return self.env.context.get('active_ids') ...
[ "from odoo import models, fields, api\n\n\nclass Aceptar_letras_wizard(models.TransientModel):\n _name = 'aceptar_letras_wizard'\n _description = \"Aceptar letras\"\n\n def _get_letras(self):\n if self.env.context and self.env.context.get('active_ids'):\n return self.env.context.get('acti...
false
5,093
68bcb76a9c736e21cc1f54c6343c72b11e575b5d
import time import torch from torch.utils.data import DataLoader from nn_model import NNModel def train(dataset: 'Dataset', epochs: int=10): loader = DataLoader(dataset, batch_size=2, shuffle=True) model = NNModel(n_input=2, n_output=3) # model.to(device='cpu') optimizer = torch.optim.Adam(model.p...
[ "import time\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom nn_model import NNModel\n\n\ndef train(dataset: 'Dataset', epochs: int=10):\n loader = DataLoader(dataset, batch_size=2, shuffle=True)\n\n model = NNModel(n_input=2, n_output=3)\n # model.to(device='cpu')\n\n optimizer = torch...
false
5,094
be867d600f5f267986368f5573006f63004dbf9e
seq = input('write a sequence of numbers: ') print(seq.split(',')) print(tuple(seq.split(',')))
[ "seq = input('write a sequence of numbers: ')\n\nprint(seq.split(','))\nprint(tuple(seq.split(',')))\n", "seq = input('write a sequence of numbers: ')\nprint(seq.split(','))\nprint(tuple(seq.split(',')))\n", "<assignment token>\nprint(seq.split(','))\nprint(tuple(seq.split(',')))\n", "<assignment token>\n<cod...
false
5,095
c9f4ae94dc901d34a3c0fb4371c8d35a7fe94507
"""Exercise 7.2. Encapsulate this loop in a function called square_root that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.""" def my_square_root(a,x) : e = 0.0001 while True : y=(x+a/x)/2 if abs(y-x) < e : return y ...
[ "\"\"\"Exercise 7.2. Encapsulate this loop in a function called square_root that takes a as a parameter,\nchooses a reasonable value of x, and returns an estimate of the square root of a.\"\"\"\n\ndef my_square_root(a,x) :\n e = 0.0001\n while True :\n y=(x+a/x)/2\n if abs(y-x) < e :\n ...
false
5,096
fed94e0affa1fe6c705577a63fabee839aa9f05c
# Generated by Django 2.0.1 on 2018-05-01 11:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rover', '0002_auto_20180501_1431'), ] operations = [ migrations.CreateModel( name='RoverPage', fields=[ ...
[ "# Generated by Django 2.0.1 on 2018-05-01 11:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('rover', '0002_auto_20180501_1431'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='RoverPage',\n fi...
false
5,097
eb99def75404bc3b674bcb633714009149f2d50d
# Named Entity Recognition on Medical Data (BIO Tagging) # Bio-Word2Vec Embeddings Source and Reference: https://github.com/ncbi-nlp/BioWordVec import os import re import torch import pickle from torch import nn from torch import optim import torch.nn.functional as F import numpy as np import random from DNC.dnc imp...
[ "# Named Entity Recognition on Medical Data (BIO Tagging)\n# Bio-Word2Vec Embeddings Source and Reference: https://github.com/ncbi-nlp/BioWordVec\n\nimport os\nimport re\nimport torch\nimport pickle\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\n\nimport numpy as np\nimport random\...
false
5,098
94cbd9554e3326897147dc417d9fc8f91974786a
#!/bin/env python3 """ https://www.hackerrank.com/challenges/triangle-quest-2 INPUT: integer N where 0 < N < 10 OUTPUT: print palindromic triangle of size N e.g.for N=5 1 121 12321 1234321 123454321 """ for i in range(1, int(input()) + 1): j = 1 while j < i: print(j,end='') j += 1 w...
[ "#!/bin/env python3\n\"\"\"\nhttps://www.hackerrank.com/challenges/triangle-quest-2\n\nINPUT:\n integer N\n where 0 < N < 10\n\nOUTPUT:\n print palindromic triangle of size N\n\n e.g.for N=5\n1\n121\n12321\n1234321\n123454321\n\n\"\"\"\nfor i in range(1, int(input()) + 1):\n j = 1\n while j < i:\n prin...
false
5,099
849db3a92e0544661dd465b3e7f6949f8de5633b
from PyQt5.QtWidgets import * from select_substituents_table import * from save_selection_dialog import * class SelectSubsDialog(QDialog): def __init__(self, r_group): super().__init__() self.r_group = r_group self.substituents = None self.new_set_saved = False self.setWi...
[ "from PyQt5.QtWidgets import *\n\nfrom select_substituents_table import *\nfrom save_selection_dialog import *\n\nclass SelectSubsDialog(QDialog):\n\n def __init__(self, r_group):\n super().__init__()\n self.r_group = r_group\n self.substituents = None\n self.new_set_saved = False\n\n...
false