index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
8,200
610fde0db6e3fe0a54a008287e0c36b25b7a482f
from __future__ import division __author__ = 'Vladimir Iglovikov' import pandas as pd from sklearn.preprocessing import LabelEncoder import numpy as np from sklearn.cross_validation import ShuffleSplit from sklearn.metrics import mean_squared_error import math from sklearn.ensemble import RandomForestRegressor joined...
[ "from __future__ import division\n__author__ = 'Vladimir Iglovikov'\n\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nimport numpy as np\nfrom sklearn.cross_validation import ShuffleSplit\nfrom sklearn.metrics import mean_squared_error\nimport math\nfrom sklearn.ensemble import RandomForestReg...
true
8,201
a8cf8d0965cb877d50cee403fbc30f27484f4f36
import torch import torch.nn as nn class DehazeNet(nn.Module): def __init__(self, input=16, groups=4): super(DehazeNet, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5) self.relu1 = nn.ReLU() self.conv2 = nn.Conv2d(in_channels=4, out_channels=...
[ "import torch\nimport torch.nn as nn\n\nclass DehazeNet(nn.Module):\n def __init__(self, input=16, groups=4):\n super(DehazeNet, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5)\n self.relu1 = nn.ReLU()\n\n self.conv2 = nn.Conv2d(in_channels=4...
false
8,202
5a092150896e4082431849828793f86adcd2211c
LOGIN_USERNAME = 'YOUR_USERNAME' LOGIN_PASSWORD = 'YOUR_PASSWORD'
[ "LOGIN_USERNAME = 'YOUR_USERNAME'\nLOGIN_PASSWORD = 'YOUR_PASSWORD'", "LOGIN_USERNAME = 'YOUR_USERNAME'\nLOGIN_PASSWORD = 'YOUR_PASSWORD'\n", "<assignment token>\n" ]
false
8,203
8488fdd216c30c3cb4b0060305af6708d890bc86
#!/usr/bin/env python # coding: utf-8 # # PyCity School Analysis # 1. Charter school types show better performace than District School types in all the scores. # 2. Overall students are performing better in english between (80 to 84%), than math (76 to 84%) # ### Note # * Instructions have been included for each seg...
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# # PyCity School Analysis\n# 1. Charter school types show better performace than District School types in all the scores. \n# 2. Overall students are performing better in english between (80 to 84%), than math (76 to 84%)\n\n# ### Note\n# * Instructions have been included...
false
8,204
caac9dfc7d52607c2af67ddc03a3a7bdae9911bb
#coding=utf-8 ''' Created on 04/09/2012 @author: Johnny ''' from ckeditor.widgets import CKEditorWidget from django.conf.urls import patterns, url from django.shortcuts import render_to_response from django.template import RequestContext from django.templatetags.static import static import views from portfolio.models ...
[ "#coding=utf-8\n'''\nCreated on 04/09/2012\n\n@author: Johnny\n'''\nfrom ckeditor.widgets import CKEditorWidget\nfrom django.conf.urls import patterns, url\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.templatetags.static import static\nimport views\nfrom ...
false
8,205
775900d4c059c89bfb10f5c3c2a924a41a049438
import time import numpy as np import matplotlib.pyplot as plt class stochasticGradient : def __init__( self , kwargs ) : self.inputVectors = kwargs["inputVectors"] self.expectedOutput = kwargs["expectedOutput"] self.noOfEpochs = kwargs["noO...
[ "import time\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nclass stochasticGradient :\r\n def __init__( self , kwargs ) :\r\n self.inputVectors = kwargs[\"inputVectors\"]\r\n self.expectedOutput = kwargs[\"expectedOutput\"]\r\n self.noOfEpochs ...
false
8,206
5cc18af40befab444df44bf3da1f0175e5d18983
import datetime import shutil from pathlib import Path from jinja2 import Environment, FileSystemLoader from dataclasses import dataclass PATH_TO_TEMPLATES = Path('TEMPLATES/') PATH_TO_RESOURCES = Path('RESOURCES/') PATH_TO_OUTPUT = Path('../docs/') URL_ROOT = "https://katys.cz/" link_to_homepage = "/" # TODO: alwa...
[ "import datetime\nimport shutil\nfrom pathlib import Path\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom dataclasses import dataclass\n\nPATH_TO_TEMPLATES = Path('TEMPLATES/')\nPATH_TO_RESOURCES = Path('RESOURCES/')\nPATH_TO_OUTPUT = Path('../docs/')\nURL_ROOT = \"https://katys.cz/\"\n\nlink_to_homepage ...
false
8,207
1e344330b88b336598295e2a7be6a6dc57cb3d59
# -*- encoding: utf-8 -*- import requests import time import random STATS = True INFINITE = True VOTING_ENDPOINT = 'http://www.adressa.no/poll/vote.do' # These are the required fields from the voting form payload = { "vote": "svar4", "mentometerId": "10790638", "publicationId": "167", "redirectTo": "...
[ "# -*- encoding: utf-8 -*-\n\nimport requests\nimport time\nimport random\n\nSTATS = True\nINFINITE = True\nVOTING_ENDPOINT = 'http://www.adressa.no/poll/vote.do'\n\n# These are the required fields from the voting form\npayload = {\n \"vote\": \"svar4\",\n \"mentometerId\": \"10790638\",\n \"publicationId\...
true
8,208
43d5bf79f16e8530797cdd13cdfcc91f0d3aef5e
import sys import numpy as np sys.setrecursionlimit(10 ** 7) read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N, M = map(int, input().split()) def cumprod(arr, MOD): L = len(arr) Lsq = int(L ** 0.5 + 1) arr = np.resize(arr, Lsq ** 2).reshape(Lsq, ...
[ "import sys\nimport numpy as np\n\nsys.setrecursionlimit(10 ** 7)\n\nread = sys.stdin.buffer.read\nreadline = sys.stdin.buffer.readline\nreadlines = sys.stdin.buffer.readlines\n\nN, M = map(int, input().split())\n\n\ndef cumprod(arr, MOD):\n L = len(arr)\n Lsq = int(L ** 0.5 + 1)\n arr = np.resize(arr, Lsq...
false
8,209
647aa37c53aac7c620e5095c7a9368f4ad038608
import serial, time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.OUT) GPIO.setup(17, GPIO.OUT) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) GPIO.setup(23, GPIO.OUT) GPIO.setup(24, GPIO.OUT) GPIO.setup(7, GPIO.OUT) pwm1 = GPIO.PWM(23,100) pwm2 = GPIO.PWM(24,100) pwm1.start(100) pwm2.start(100...
[ "import serial, time\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(4, GPIO.OUT)\nGPIO.setup(17, GPIO.OUT)\nGPIO.setup(27, GPIO.OUT)\nGPIO.setup(22, GPIO.OUT)\nGPIO.setup(23, GPIO.OUT)\nGPIO.setup(24, GPIO.OUT)\nGPIO.setup(7, GPIO.OUT)\n\npwm1 = GPIO.PWM(23,100)\npwm2 = GPIO.PWM(24,100)\npwm1.start(...
true
8,210
22706d7d9c04bb660c9bf0df66de89ed6bd480c2
class Solution: def minWindow(self, s: str, t: str) -> str: char_cnt = {} for character in t: if character not in char_cnt: char_cnt[character] = 1 else: char_cnt[character] += 1 dq = [] # add index & character min_substring = ...
[ "class Solution:\n def minWindow(self, s: str, t: str) -> str:\n char_cnt = {}\n for character in t:\n if character not in char_cnt:\n char_cnt[character] = 1\n else:\n char_cnt[character] += 1\n\n dq = [] # add index & character\n m...
false
8,211
f652fa6720582d50f57f04d82fb2f5af17859ebd
# Mac File import platform import os def Mac(SystemArray = [], ProcessorArray = []): # System Info OSName = str() OSVersionMajor = str() OSArchitecture = str() # Processor Info command = '/usr/sbin/sysctl -n machdep.cpu.brand_string' ProcInfo = os.popen(command).read().strip() ProcNam...
[ "# Mac File\nimport platform\nimport os\n\ndef Mac(SystemArray = [], ProcessorArray = []):\n\n # System Info\n OSName = str()\n OSVersionMajor = str()\n OSArchitecture = str()\n\n # Processor Info\n command = '/usr/sbin/sysctl -n machdep.cpu.brand_string'\n ProcInfo = os.popen(command).read().s...
false
8,212
9f831b8c90dd428879319b63712bd03fcc01b631
# The purpose of this bot is to cick the first black pixel. # Testing a change here done by Git. # changes through branches import pyautogui import keyboard import win32api import win32con import time # click function, with a 0.01 pause inorder to properly run the script def click(x, y): win32api...
[ "# The purpose of this bot is to cick the first black pixel.\r\n# Testing a change here done by Git. \r\n# changes through branches\r\n\r\nimport pyautogui\r\nimport keyboard\r\nimport win32api\r\nimport win32con\r\nimport time\r\n\r\n# click function, with a 0.01 pause inorder to properly run the script\r\n\r\n\r\...
false
8,213
aa515b1b919eb557cd8c7e5f4d22773980b5af96
# -*- coding: utf-8 -*- import datetime from unittest.mock import patch from odoo.tests import common import odoo from .common import RunbotCase class TestSchedule(RunbotCase): def setUp(self): # entering test mode to avoid that the _schedule method commits records registry = odoo.registry() ...
[ "# -*- coding: utf-8 -*-\nimport datetime\nfrom unittest.mock import patch\nfrom odoo.tests import common\nimport odoo\nfrom .common import RunbotCase\n\n\nclass TestSchedule(RunbotCase):\n\n def setUp(self):\n # entering test mode to avoid that the _schedule method commits records\n registry = odo...
false
8,214
dfcb095b26a21ba0c8ccc2a2c664bcfab29b8351
""" All requests will be sent to backend as: { name: <class name>, data: { <all instance variables> } } """ class NewDriver: def __init__(self, uri, authToken): self.uri = uri self.authorizationToken = authToken class DriverClose: def __init__(self...
[ "\n\"\"\"\nAll requests will be sent to backend as:\n {\n name: <class name>,\n data: {\n <all instance variables>\n }\n }\n\"\"\"\n\nclass NewDriver:\n def __init__(self, uri, authToken):\n self.uri = uri\n self.authorizationToken = authToken\n\n\nclass Driver...
false
8,215
88a3c3fad9717675ed13bcbc778d635f6552c4b1
from PySide.QtCore import (qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand, Qt, QTime,QSettings,QSize,QPoint) from PySide.QtGui import (QBrush, QKeySequence, QColor, QLinearGradient, QPainter, QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene, QGra...
[ "\nfrom PySide.QtCore import (qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand,\n Qt, QTime,QSettings,QSize,QPoint)\nfrom PySide.QtGui import (QBrush, QKeySequence, QColor, QLinearGradient, QPainter,\n QPainterPath, QPen, QPolygonF, QRadialGradient, QApplication, QGraphicsItem, QGraphicsScene,\n ...
false
8,216
41a80feeb1fdc8ad783706ad261f5fc1124371d6
""" Solution to Codeforces problem 50A Copyright (c) GeneralMing. All rights reserved. https://github.com/GeneralMing/codeforces """ n = input().split() n[0] = int(n[0]) n[1] = int(n[1]) print((n[0]*n[1])//2)
[ "\"\"\"\n\tSolution to Codeforces problem 50A\n\tCopyright (c) GeneralMing. All rights reserved.\n\n\thttps://github.com/GeneralMing/codeforces\n\"\"\"\n\nn = input().split()\nn[0] = int(n[0])\nn[1] = int(n[1])\nprint((n[0]*n[1])//2)", "<docstring token>\nn = input().split()\nn[0] = int(n[0])\nn[1] = int(n[1])\np...
false
8,217
6b2161379bdd27980d3a515cdf4719ab036845fe
#!/usr/bin/env python # coding: utf-8 # In[5]: import re def phonenumbervalidate(phone): pattern ='^[6-9][0-9]{9}$' phone =str(phone) if re.match(pattern,phone): return True return False print(phonenumbervalidate(998855451)) print(phonenumbervalidate(9955441)) # In[10]: import re def pho...
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport re\ndef phonenumbervalidate(phone):\n pattern ='^[6-9][0-9]{9}$'\n phone =str(phone)\n if re.match(pattern,phone):\n return True \n return False\nprint(phonenumbervalidate(998855451))\nprint(phonenumbervalidate(9955441))\n\n\n# In[10...
false
8,218
eb4bc008b7e68f8a6e80e837fa970d77a5ed3547
import pandas as pd import numpy as np import random import copy class Node(object): ''' Defines a Node Class for storing characteristics and CPT of each node ''' def __init__(self,name): self.parents = [] self.children = [] self.name = name self.cpt=[] self...
[ "import pandas as pd\nimport numpy as np\nimport random\nimport copy\n\nclass Node(object):\n '''\n Defines a Node Class for storing characteristics and CPT of each node\n '''\n \n def __init__(self,name):\n self.parents = []\n self.children = []\n self.name = name\n self....
false
8,219
faebefcadbc184fab29deb2988089223a8f09e7e
nome = str(input('Digite um nome completo: ')).lower() silva = 'silva' in nome if silva == True: print('Existe Silva nesse nome') else: print('Não há Silva nesse nome')
[ "nome = str(input('Digite um nome completo: ')).lower()\nsilva = 'silva' in nome\nif silva == True:\n print('Existe Silva nesse nome')\nelse:\n print('Não há Silva nesse nome')", "nome = str(input('Digite um nome completo: ')).lower()\nsilva = 'silva' in nome\nif silva == True:\n print('Existe Silva ness...
false
8,220
049d83bc1a31ef170654fda47d1f58e024befb44
# Generated by Django 3.0.4 on 2021-03-27 19:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('electra', '0009_remove_response_img'), ] operations = [ migrations.AddField( model_name='response', name='date_time'...
[ "# Generated by Django 3.0.4 on 2021-03-27 19:18\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('electra', '0009_remove_response_img'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='response',\n ...
false
8,221
e983db4b99e73929c02eb84fab1ee56138048052
from django.shortcuts import render, redirect from django.contrib import messages from .models import * from django.views.decorators.csrf import csrf_exempt def index(request): notes = Note.objects.all().order_by('-created_at') context = { "notes" : notes } return render(request, 'notes/index.h...
[ "from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom .models import *\nfrom django.views.decorators.csrf import csrf_exempt\n\ndef index(request):\n notes = Note.objects.all().order_by('-created_at')\n context = {\n \"notes\" : notes\n }\n return render(reques...
false
8,222
b2fb5564d44f7481c6de2a5d4af09df4903026b8
# user_events.py import dataclasses from typing import Optional @dataclasses.dataclass class UserUpdateMessage: id: str name: Optional[str] = None age: Optional[int] = None async def receive_user_update(message: UserUpdateMessage) -> None: print(f"Received update for user id={message.id}")
[ "# user_events.py\n\nimport dataclasses\nfrom typing import Optional\n\n\n@dataclasses.dataclass\nclass UserUpdateMessage:\n id: str\n name: Optional[str] = None\n age: Optional[int] = None\n\n\nasync def receive_user_update(message: UserUpdateMessage) -> None:\n print(f\"Received update for user id={me...
false
8,223
d551cab1856fbdb91918f9171d5c02b8dab84aba
# coding=UTF-8 #!/usr/bin/env python # for models.py from django.db import models from django.db.models import F, Q, Sum, Avg from django.db import transaction from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.sites.models import Site # from ...
[ "# coding=UTF-8\n#!/usr/bin/env python\n\n# for models.py\nfrom django.db import models\nfrom django.db.models import F, Q, Sum, Avg\nfrom django.db import transaction\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.sites.models impor...
false
8,224
3cb3361e8777d31575d81d2a1191f137e4174492
a = [1, 11, 21, 1211, 111221] for i in range(30): #next_num_list = [] next_num = '' next_char = '' step = 0 count = 0 # Analyze the string. for char in str(a[i+4]): if step == 0: next_char = char count += 1 step = 1 elif step == 1: ...
[ "a = [1, 11, 21, 1211, 111221]\n\nfor i in range(30):\n\n #next_num_list = []\n next_num = ''\n\n next_char = ''\n\n step = 0\n count = 0\n\n # Analyze the string.\n for char in str(a[i+4]):\n if step == 0:\n next_char = char\n count += 1\n step = 1\n\n ...
true
8,225
10a981e35ce00ee8e32a613823d3bc919fafaae8
import sqlite3 connection = sqlite3.connect("../db.sqlite3") cursor = connection.cursor() sql_file = open("sample.sql") sql_as_string = sql_file.read() cursor.executescript(sql_as_string) for row in cursor.execute("SELECT * FROM results_states"): print(row)
[ "import sqlite3\n\nconnection = sqlite3.connect(\"../db.sqlite3\")\n\ncursor = connection.cursor()\n\nsql_file = open(\"sample.sql\")\nsql_as_string = sql_file.read()\ncursor.executescript(sql_as_string)\n\nfor row in cursor.execute(\"SELECT * FROM results_states\"):\n print(row)\n", "import sqlite3\nconnectio...
false
8,226
36c1d75171d772138b820651e11a3a7bc3a6521c
import unittest from month import Month class MonthUnitTests(unittest.TestCase): def test_header(self): cal = Month(5, 2012) result = cal.header() self.assertEqual(" May 2012", result) def test_header_different_month(self): cal = Month(3, 2012) result = cal.header() self.assertEqual(" March 20...
[ "import unittest\nfrom month import Month\n\nclass MonthUnitTests(unittest.TestCase):\n\n\tdef test_header(self):\n\t\tcal = Month(5, 2012)\n\t\tresult = cal.header()\n\t\tself.assertEqual(\" May 2012\", result)\n\n\tdef test_header_different_month(self):\n\t\tcal = Month(3, 2012)\n\t\tresult = cal.header()\n\...
false
8,227
4d059d1ca407ef60f1fbf9d8bead1cf45c90c28a
from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse_lazy from django.shortcuts import get_object_or_404 from rest_framework import status, viewsets from rest_framework.exceptions import PermissionDenied from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_f...
[ "from django.contrib.auth import get_user_model\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.shortcuts import get_object_or_404\n\nfrom rest_framework import status, viewsets\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\...
false
8,228
9f3fcc6e097e37479e3ccf1385f20d70d7c3b6c7
#! /usr/bin/python3 import pprint import tkinter as tk from tkinter import messagebox from PIL import Image from tkinter import * from prettytable import PrettyTable import ttk import os import subprocess import mysql.connector from datetime import datetime import time db=mysql.connector.connect(host='localhost',user...
[ "#! /usr/bin/python3\nimport pprint\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom PIL import Image\nfrom tkinter import *\nfrom prettytable import PrettyTable\nimport ttk\nimport os\nimport subprocess\nimport mysql.connector\nfrom datetime import datetime\nimport time\n\n\ndb=mysql.connector.connect(h...
false
8,229
598a0771dd1447034f2db95c67dd0dcf968f43a7
import bcrypt as bcrypt from config.configuration import Configuration class Usuario(Configuration.db.Model): __tablename__ = "usuario" id = Configuration.db.Column(Configuration.db.BIGINT, primary_key=True, autoincrement=True) code = Configuration.db.Column(Configuration.db.String(80), unique=True, nul...
[ "import bcrypt as bcrypt\n\nfrom config.configuration import Configuration\n\nclass Usuario(Configuration.db.Model):\n\n __tablename__ = \"usuario\"\n\n id = Configuration.db.Column(Configuration.db.BIGINT, primary_key=True, autoincrement=True)\n code = Configuration.db.Column(Configuration.db.String(80), ...
false
8,230
228852f960e9343d9f45abdd3204cfab7bb54bc6
""" * Team Id : LM#4787 * Author List : Arjun S, Vinod, Arvind, Vishnu * Filename: ArenaPreprocessor.py * Theme: Launch A Module * Functions: arena_preprocess, getTransformationMatrix, get_robot_space * Global Variables: None """ import cv2 import numpy as np """ * Function Name...
[ "\"\"\"\n* Team Id : LM#4787\n* Author List : Arjun S, Vinod, Arvind, Vishnu\n* Filename: ArenaPreprocessor.py\n* Theme: Launch A Module\n* Functions: arena_preprocess, getTransformationMatrix, get_robot_space\n* Global Variables: None\n\"\"\"\n\nimport cv2\nimport numpy as np\...
false
8,231
16c4dbd472f9d32e5fa48a28dff4a40914f7d29e
from . import colorbar_artist from . import subplot_artist from . import surface_3d_with_shadows from .colorbar_artist import * from .subplot_artist import * from .surface_3d_with_shadows import * __all__ = [ 'colorbar_artist', 'subplot_artist', 'surface_3d_with_shadows'] __all__.extend(colorbar_artist.__...
[ "from . import colorbar_artist\nfrom . import subplot_artist\nfrom . import surface_3d_with_shadows\n\nfrom .colorbar_artist import *\nfrom .subplot_artist import *\nfrom .surface_3d_with_shadows import *\n\n__all__ = [\n 'colorbar_artist',\n 'subplot_artist',\n 'surface_3d_with_shadows']\n__all__.extend(c...
false
8,232
55977a673bb36900e1d797cb9ec330ce6d9aa717
import numpy as np import pandas as pd import matplotlib.pyplot as plt import csv file_open = open("C:/Users/DI_Lab/Desktop/20년도 Kisti 과제/HMM/HMM(Up,Down).csv", 'r', encoding='UTF8') save_file = open("C:/Users/DI_Lab/Desktop/20년도 Kisti 과제/HMM/HMM사후확률.csv", 'w', encoding='UTF8',newline='') write = csv.writer(save_file)...
[ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport csv\n\nfile_open = open(\"C:/Users/DI_Lab/Desktop/20년도 Kisti 과제/HMM/HMM(Up,Down).csv\", 'r', encoding='UTF8')\nsave_file = open(\"C:/Users/DI_Lab/Desktop/20년도 Kisti 과제/HMM/HMM사후확률.csv\", 'w', encoding='UTF8',newline='')\nwrite = csv.w...
false
8,233
30a2358e8396d24d6c3cd72d04321aa9f9f83995
import json from week2.Stack import Stack class TransactionStack: def __init__(self): self.stack = Stack() with open("json_file/Transaction_Stack.json") as data: try: temp = json.load(data) except Exception: pass else: ...
[ "import json\n\nfrom week2.Stack import Stack\n\n\nclass TransactionStack:\n def __init__(self):\n\n self.stack = Stack()\n with open(\"json_file/Transaction_Stack.json\") as data:\n try:\n temp = json.load(data)\n except Exception:\n pass\n ...
false
8,234
e3d886dedaf5b120392d0dc81c4c71398f08f8d6
import numpy as np import pandas as pd import time from sklearn.metrics import log_loss from keras.models import Sequential, Model from keras.layers import Dense, Input from keras.layers import Dropout from keras.layers import Flatten from keras.layers import LSTM from keras.layers.convolutional import Convolution3D f...
[ "import numpy as np\nimport pandas as pd\nimport time\nfrom sklearn.metrics import log_loss\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Input\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.layers import LSTM\nfrom keras.layers.convolutional import ...
false
8,235
1ca20b0cd9217623ff039ab352acd09df8dfae1b
class Enumerator(object): """For Python we just wrap the iterator""" def __init__(self, next): self.iterator = next def __next__(self): return next(self.iterator) # Python 2.7 next = __next__ def __iter__(self): return self
[ "class Enumerator(object):\n \"\"\"For Python we just wrap the iterator\"\"\"\n\n def __init__(self, next):\n self.iterator = next\n\n def __next__(self):\n return next(self.iterator)\n\n # Python 2.7\n next = __next__\n\n def __iter__(self):\n return self\n", "class Enumera...
false
8,236
8566e30a6450a72a0e441155321bd03363944b5a
import pymysql db= pymysql.connect(host = 'localhost', port = 3306, user = 'root', password = 'Wubaba950823', database = 'mydb', charset = 'utf8mb4' ) # 使用cursor()方法获取操作游标 curso...
[ "import pymysql\n\ndb= pymysql.connect(host = 'localhost',\n port = 3306,\n user = 'root',\n password = 'Wubaba950823',\n database = 'mydb',\n charset = 'utf8mb4'\n )\n \n# 使用cursor()...
false
8,237
7deaee28674c465694c348c21e87addbcc8ea923
from pymongo import MongoClient from datetime import datetime import sys import requests import urllib import json import xml.etree.ElementTree as ET import xmltodict import pandas from lxml import etree from bson.json_util import dumps bornTables = pandas.read_html("http://statis.moi.gov.tw/micst/stmain.jsp?sys=220&y...
[ "from pymongo import MongoClient\nfrom datetime import datetime\nimport sys\nimport requests\nimport urllib\nimport json\nimport xml.etree.ElementTree as ET\nimport xmltodict\nimport pandas\nfrom lxml import etree\nfrom bson.json_util import dumps\n\nbornTables = pandas.read_html(\"http://statis.moi.gov.tw/micst/st...
true
8,238
a6cb7a134fb8480d344743bcb7bc8766146d256f
# Generated by Django 2.1.5 on 2019-01-21 22:51 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
[ "# Generated by Django 2.1.5 on 2019-01-21 22:51\n\nfrom django.conf import settings\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 migrations.swappable_dependency(settings.AUTH_USER_MODEL...
false
8,239
632fdb95874f0beeb6d178788f7c7e7c9e8512e5
a = 10 b = 20 c = a+b d = b-a print(c) print(d)
[ "a = 10\nb = 20\nc = a+b\nd = b-a\nprint(c)\nprint(d)", "a = 10\nb = 20\nc = a + b\nd = b - a\nprint(c)\nprint(d)\n", "<assignment token>\nprint(c)\nprint(d)\n", "<assignment token>\n<code token>\n" ]
false
8,240
a68de7555fdab06014fd562e7db29ca2da03f443
# coding=utf-8 import re import traceback from pesto_common.config.configer import Configer from pesto_common.log.logger_factory import LoggerFactory from pesto_orm.core.base import db_config from pesto_orm.core.executor import ExecutorFactory from pesto_orm.core.model import BaseModel from pesto_orm.core.repository i...
[ "# coding=utf-8\nimport re\nimport traceback\n\nfrom pesto_common.config.configer import Configer\nfrom pesto_common.log.logger_factory import LoggerFactory\nfrom pesto_orm.core.base import db_config\nfrom pesto_orm.core.executor import ExecutorFactory\nfrom pesto_orm.core.model import BaseModel\nfrom pesto_orm.cor...
false
8,241
92391f17380b2e09cc9b3913f15ce35189d9893d
def check_integer(a): if type(a) != int: print("please input an integer") exit() def is_even(a): check_integer(a) if a % 2 == 0: print("true") return True else: print("false") return False is_even(2) is_even(3) is_even("cat")
[ "\n\ndef check_integer(a):\n if type(a) != int:\n print(\"please input an integer\")\n exit()\n\n\ndef is_even(a):\n check_integer(a)\n if a % 2 == 0:\n print(\"true\")\n return True\n else:\n print(\"false\")\n return False\n\n\nis_even(2)\nis_even(3)\nis_even(...
false
8,242
520672f8607751b65fe9e4b975a9978ed0ab71b6
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the file entry implementation using pyfshfs.""" import unittest from dfvfs.lib import definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from dfvfs.vfs import hfs_attribute from dfvfs.vfs import hfs_file_entry f...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Tests for the file entry implementation using pyfshfs.\"\"\"\n\nimport unittest\n\nfrom dfvfs.lib import definitions\nfrom dfvfs.path import factory as path_spec_factory\nfrom dfvfs.resolver import context\nfrom dfvfs.vfs import hfs_attribute\nfrom dfvfs.vfs im...
false
8,243
1c13a9ca3617dc6f1a1f1aa8249cce37062a449b
#!/usr/bin/python import xml.dom.minidom import os import matplotlib.pyplot as plt import cPickle as p import numpy as np def modifyXML(name,numCar): DOMTree = xml.dom.minidom.parse(name) objects=DOMTree.getElementsByTagName('object') for object in objects: if object.getElementsByTagName('name')[0].childNodes[0]....
[ "#!/usr/bin/python\nimport xml.dom.minidom\nimport os\nimport matplotlib.pyplot as plt\nimport cPickle as p\nimport numpy as np\n\ndef modifyXML(name,numCar):\n\tDOMTree = xml.dom.minidom.parse(name)\n\tobjects=DOMTree.getElementsByTagName('object')\n\tfor object in objects:\n\t\tif object.getElementsByTagName('nam...
true
8,244
6ad2014191215dac97ad6fc6a026512c3d1866dc
from wtforms import StringField, PasswordField from wtforms.validators import DataRequired from flask_wtf import FlaskForm # ... class LoginForm(FlaskForm): """登录表单类""" username = StringField('用户名', validators=[DataRequired()]) password = PasswordField('密码', validators=[DataRequired()])
[ "from wtforms import StringField, PasswordField\nfrom wtforms.validators import DataRequired\nfrom flask_wtf import FlaskForm\n\n\n# ...\nclass LoginForm(FlaskForm):\n \"\"\"登录表单类\"\"\"\n username = StringField('用户名', validators=[DataRequired()])\n password = PasswordField('密码', validators=[DataRequired()]...
false
8,245
f7d487ec99e2fa901677ab9aec0760a396722e12
""" ********************************************************************* * Project : POP1 (Practical Exam) * Program name : q2.py * Author : varunk01 * Purpose : Attempts to solve the question 2 from the exam paper * Date created : 28/05/2018 * * Date Author Ver Comment * 28/05/2018 varunk...
[ "\"\"\"\n*********************************************************************\n* Project : POP1 (Practical Exam)\n* Program name : q2.py\n* Author : varunk01\n* Purpose : Attempts to solve the question 2 from the exam paper\n* Date created : 28/05/2018\n*\n* Date Author Ver Comment\n* 28/0...
false
8,246
4eb7abb24451f3f895d0731de7b29a85d90c1539
from flask import Blueprint, request from ecdsa import SigningKey, NIST384p import base64, codecs from cryptography.fernet import Fernet ecdsa_app = Blueprint('ecdsa_app', __name__, url_prefix='/ecdsa_app') f = Fernet(Fernet.generate_key()) sk = SigningKey.generate(curve=NIST384p) vk = sk.get_verifying_key() @ecd...
[ "from flask import Blueprint, request\nfrom ecdsa import SigningKey, NIST384p\nimport base64, codecs\nfrom cryptography.fernet import Fernet\n\necdsa_app = Blueprint('ecdsa_app', __name__, url_prefix='/ecdsa_app')\nf = Fernet(Fernet.generate_key())\n\nsk = SigningKey.generate(curve=NIST384p)\nvk = sk.get_verifying_...
false
8,247
ce28462621a423c6661c672cf92d7e9c91875cfa
""" Copyright (C) 2018-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
[ "\"\"\"\n Copyright (C) 2018-2020 Intel Corporation\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 applicable...
false
8,248
be238268b9fdd565f3cb0770839789b702940ef9
#!/usr/bin/env python # This file just executes its arguments, except that also adds OUT_DIR to the # environ. This is for compatibility with cargo. import subprocess import sys import os os.environ["OUT_DIR"] = os.path.abspath(".") assert os.path.isdir(os.environ["OUT_DIR"]) sys.exit(subprocess.call(sys.argv[1:], env...
[ "#!/usr/bin/env python\n# This file just executes its arguments, except that also adds OUT_DIR to the\n# environ. This is for compatibility with cargo.\nimport subprocess\nimport sys\nimport os\n\nos.environ[\"OUT_DIR\"] = os.path.abspath(\".\")\nassert os.path.isdir(os.environ[\"OUT_DIR\"])\nsys.exit(subprocess.ca...
false
8,249
f6846bfc6c4d803cedaf37e079e01188733938c7
#!/usr/bin/env python3 import collections import glob import os import pandas as pd import numpy as np import torch.nn.functional as F import PIL.Image as Image from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params from inference.metrics.fid.fid_score import _compute_...
[ "#!/usr/bin/env python3\nimport collections\nimport glob\nimport os\n\nimport pandas as pd\nimport numpy as np\nimport torch.nn.functional as F\nimport PIL.Image as Image\n\nfrom inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\nfrom inference.metrics.fid.fid_score ...
false
8,250
0074b0cd1e4317e36ef4a41f8179464c2ec6c197
rf = open('A-large.in', 'r') wf = open('A-large.out', 'w') cases = int(rf.readline()) for case in range(1, cases + 1): digits = [False] * 10 n = int(rf.readline()) if n == 0: wf.write('Case #%s: INSOMNIA\n' % case) continue for i in range(1, 999999): cur = n * i for c in str(cur): digits[int(c)] = True...
[ "rf = open('A-large.in', 'r')\nwf = open('A-large.out', 'w')\n\ncases = int(rf.readline())\n\nfor case in range(1, cases + 1):\n\tdigits = [False] * 10\n\tn = int(rf.readline())\n\tif n == 0:\n\t\twf.write('Case #%s: INSOMNIA\\n' % case)\n\t\tcontinue\n\tfor i in range(1, 999999):\n\t\tcur = n * i\n\t\tfor c in str...
false
8,251
a2a3e8d52fd467178460b178c5dbf9ccd72706e7
pokerAssignments = {'2': 20, '3': 30, '4': 40, '5': 50, '6': 60, '7': 70, '8': 80, '9': 90, 'T': 100, 'J': 110, 'Q': 120, 'K': 130, 'A': 140, 'C': 0, 'S': 1, 'H': 2, 'D': 3} #Used to assign each card to a unique three-digit integer configScoring = {(1, 1): 0, (1, 2): 1, (2, 2): 2, (1, 3): 3, (2, 3): 6, (1, 4): 7} #Tra...
[ "pokerAssignments = {'2': 20, '3': 30, '4': 40, '5': 50, '6': 60, '7': 70, '8': 80, '9': 90, 'T': 100, 'J': 110, 'Q': 120, 'K': 130, 'A': 140, 'C': 0, 'S': 1, 'H': 2, 'D': 3} #Used to assign each card to a unique three-digit integer\n\nconfigScoring = {(1, 1): 0, (1, 2): 1, (2, 2): 2, (1, 3): 3, (2, 3): 6, (1, 4): ...
false
8,252
245e407c9e92b3ac34389a48fcef4fc1b349ea18
from rest_framework import generics from animals.models import Location from animals.serializers import LocationSerializer class LocationList(generics.ListCreateAPIView): queryset = Location.objects.all() serializer_class = LocationSerializer name = 'location-list' class LocationDetail(generics.Retriev...
[ "from rest_framework import generics\n\nfrom animals.models import Location\nfrom animals.serializers import LocationSerializer\n\n\nclass LocationList(generics.ListCreateAPIView):\n queryset = Location.objects.all()\n serializer_class = LocationSerializer\n name = 'location-list'\n\n\nclass LocationDetail...
false
8,253
591b1a2e245ae0f3c9b2a81769bbf5988574ed07
#!/usr/bin/env python3 import math from PIL import Image as Image # NO ADDITIONAL IMPORTS ALLOWED! def in_bound(dim , s): """Get inbound pixel coordinate for out-of-bound Args: dim (int): Image height or width s (int): Coordinate Returns: int: Inbound """ if s <= -1: ...
[ "#!/usr/bin/env python3\n\nimport math\n\nfrom PIL import Image as Image\n\n# NO ADDITIONAL IMPORTS ALLOWED!\n\ndef in_bound(dim , s):\n \"\"\"Get inbound pixel coordinate for out-of-bound\n\n Args:\n dim (int): Image height or width\n s (int): Coordinate \n\n Returns:\n int: Inbound\n...
false
8,254
dc3a3f5675860792ecfa7dcd5180402d89b669b1
# -*-coding:utf-8-*- import os import time import shutil import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--dir', type=str, required=True) parser.add_argument('--task', type=str, required=True) args = parser.parse_args() if not os.path.exists(args...
[ "# -*-coding:utf-8-*-\n\nimport os\nimport time\nimport shutil\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--dir', type=str, required=True)\n parser.add_argument('--task', type=str, required=True)\n args = parser.parse_args()\n\n if not...
false
8,255
c2ee716b72652035502a1f07dfe8aa68a104b2bb
import numpy as np import os # ---------------------------------------------------------------------------- # Common variables # shifting channels based on rules: # CH_SHIFT[rule_name] = {src_1_based_ch:new_1_based_ch} CH_SHIFT = {} CH_SHIFT[None] = None # for 1-to-1 cards CH_SHIFT['1to1'] = {} for ch1 in xrange(1,...
[ "import numpy as np\nimport os\n\n# ----------------------------------------------------------------------------\n# Common variables\n\n# shifting channels based on rules:\n# CH_SHIFT[rule_name] = {src_1_based_ch:new_1_based_ch}\nCH_SHIFT = {}\nCH_SHIFT[None] = None\n# for 1-to-1 cards\nCH_SHIFT['1to1'] = {}\nfor...
true
8,256
c972f732553f27261d2a4a03e6e353f2e1b5f5d3
import numpy as np from .basic import scRefData, featureSelection from .utils import find_variable_genes, dropout_linear_model from .process import find_de_tt, find_de_anova """ after normalization befor cluster or nn_indexing """ class highlyVarSelecter(featureSelection): """ select highly varable genes; ...
[ "import numpy as np\nfrom .basic import scRefData, featureSelection\nfrom .utils import find_variable_genes, dropout_linear_model\nfrom .process import find_de_tt, find_de_anova\n\"\"\"\nafter normalization\nbefor cluster or nn_indexing\n\"\"\"\n\n\nclass highlyVarSelecter(featureSelection):\n \"\"\"\n select...
false
8,257
61019a5439a6f0c1aee51db9b048a26fb9b5bf5d
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word...
[ "# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:\n# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n# By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, t...
false
8,258
cccf6ec50ae00d8e00a1a53ea06fa8b6d061b72e
from django.core.management.base import BaseCommand, CommandError from tasks.redisqueue import RedisQueue from django.conf import settings class Command(BaseCommand): def handle(self, *args, **options): rqueue = RedisQueue(settings.REDIS_URL) rqueue.worker()
[ "from django.core.management.base import BaseCommand, CommandError\nfrom tasks.redisqueue import RedisQueue\nfrom django.conf import settings\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n rqueue = RedisQueue(settings.REDIS_URL)\n rqueue.worker()\n \n", "from django...
false
8,259
89ed30411c624e3d930db0bc0b5b716a10908727
"""inactivate fb posts Revision ID: f37637c1bcf8 Revises: 43c7ecf8ed02 Create Date: 2017-06-22 12:01:59.623040 """ from alembic import op from pd.facebook.models import MediaType # revision identifiers, used by Alembic. revision = 'f37637c1bcf8' down_revision = '43c7ecf8ed02' branch_labels = None depends_on = None ...
[ "\"\"\"inactivate fb posts\n\nRevision ID: f37637c1bcf8\nRevises: 43c7ecf8ed02\nCreate Date: 2017-06-22 12:01:59.623040\n\n\"\"\"\nfrom alembic import op\nfrom pd.facebook.models import MediaType\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f37637c1bcf8'\ndown_revision = '43c7ecf8ed02'\nbranch_labels ...
false
8,260
cc33d0cf1b922a6b48fb83be07acb35a62372f2e
from .interface import AudioInterface from .config import AudioConfig from .buffer import CustomBuffer
[ "from .interface import AudioInterface\nfrom .config import AudioConfig\nfrom .buffer import CustomBuffer\n", "<import token>\n" ]
false
8,261
909ea7b9335a858662f83abc71b4d58578bd0850
"""Settings module for test app.""" ENV = "development" TESTING = True SQLALCHEMY_DATABASE_URI = "sqlite://" SECRET_KEY = "not-so-secret-in-tests" DEBUG_TB_ENABLED = False SQLALCHEMY_TRACK_MODIFICATIONS = False APP_ENV = "testing" JWT_SECRET_KEY = ( "-----BEGIN RSA PRIVATE KEY-----\n" "MIICWwIBAAKBgQDdlatRjR...
[ "\"\"\"Settings module for test app.\"\"\"\nENV = \"development\"\nTESTING = True\nSQLALCHEMY_DATABASE_URI = \"sqlite://\"\nSECRET_KEY = \"not-so-secret-in-tests\"\nDEBUG_TB_ENABLED = False\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n\nAPP_ENV = \"testing\"\n\n\nJWT_SECRET_KEY = (\n \"-----BEGIN RSA PRIVATE KEY----...
false
8,262
75d2dcbb0c131930602e3c1f2cf30c0e4c5e3c42
import unittest from display import Display class TestDisplay(unittest.TestCase): def setUp(self): self.display = Display(None) def test_set_pixels(self): self.display.clear_buffer() self.display.set_pixel(0, 1, 1) self.assertEqual(self.display.get_pixel(0, 1), 1, "pixel was n...
[ "import unittest\nfrom display import Display\n\n\nclass TestDisplay(unittest.TestCase):\n def setUp(self):\n self.display = Display(None)\n\n def test_set_pixels(self):\n self.display.clear_buffer()\n self.display.set_pixel(0, 1, 1)\n self.assertEqual(self.display.get_pixel(0, 1),...
false
8,263
7dd4dc60b23c72ba450025bececb0e6d89df69c3
from asteroidhunter import __version__ import unittest, requests, json, os, pytest from dotenv import load_dotenv load_dotenv() from asteroidhunter.asteroid_closest_approach import asteroid_closest_approach def test_version(): assert __version__ == '0.1.0' @pytest.mark.vcr() def test_asteroid_closest_approach(): ...
[ "from asteroidhunter import __version__\nimport unittest, requests, json, os, pytest\nfrom dotenv import load_dotenv\nload_dotenv()\nfrom asteroidhunter.asteroid_closest_approach import asteroid_closest_approach\n\n\ndef test_version():\n assert __version__ == '0.1.0'\n\n@pytest.mark.vcr()\ndef test_asteroid_close...
false
8,264
0d322bdaf1bfed2b76172cc4dfb1b9af52bdc641
import urlparse def parse_url(url): """ Parse a url into a ParseResult() object then evolve that ParseResult() instance into an EasyUrl() object, finally return the EasyUrl() instance. """ url = urlparse.urlparse(url) #print url.__class__ return EasyUrl.EvolveParseResult(url) class ...
[ "import urlparse\n\n\n\n\ndef parse_url(url):\n \"\"\" \n Parse a url into a ParseResult() object then evolve that ParseResult()\n instance into an EasyUrl() object, finally return the EasyUrl() instance.\n \"\"\"\n url = urlparse.urlparse(url)\n #print url.__class__\n return EasyUrl.EvolvePars...
true
8,265
8c652f30cd256912512b6b91d1682af7da0ff915
import requests seesion=requests.Session() header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3387.400 QQBrowser/9.6.11984.400'} cookie={'Cookie':'_ga=GA1.2.1866009938.1500885157; xmuuid=XMGUEST-B6484440-71B8-11E7-AF2E-EFCFEDA...
[ "import requests\n\nseesion=requests.Session()\nheader={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3387.400 QQBrowser/9.6.11984.400'}\n\ncookie={'Cookie':'_ga=GA1.2.1866009938.1500885157; xmuuid=XMGUEST-B6484440-71B8-11E7-AF...
false
8,266
78e008b4a51cdbbb81dead7bc5945ee98ccad862
def test(x): print x
[ "def test(x):\n print x\n" ]
true
8,267
cde2454c68a0d6a0c86b7d647e41a86d3aa97a0d
""" r - reading fike w - writing to file a - append to file / add to the end of the file - always at the end r+ - read and write to file (writing based on python cursor position) -> by default at the beginning of file -> won't insert and shift things over, will overwrite the contents. -> r+ can only be used with alread...
[ "\"\"\"\nr - reading fike\nw - writing to file\na - append to file / add to the end of the file - always at the end\nr+ - read and write to file (writing based on python cursor position) -> by default at the beginning of file -> won't insert and shift things over,\nwill overwrite the contents. -> r+ can only be use...
false
8,268
4f36c7e98c54d38aaef9f2ebdafd0c34a157fcd7
class Area : def circle(self): rad = int(input("Enter the radius:")) area = (22/7)*(rad**2) print("Area is :" , area , "cm square") def square(self): side = int(input("Enter the length of a side:")) area = side**2 print("Area is :" , area , "cm s...
[ "class Area :\n def circle(self):\n rad = int(input(\"Enter the radius:\"))\n area = (22/7)*(rad**2)\n print(\"Area is :\" , area , \"cm square\")\n \n \n def square(self):\n side = int(input(\"Enter the length of a side:\"))\n area = side**2\n print(\"A...
false
8,269
cffc64970cb82072e5fb949f62e9778942b2be96
#!ipython3 pi_f = 0.1415926 pi = [] for i in range(10): pi.append(str(pi_f * i*16)[0]) print(pi) def convertBase(digits, baseA, baseB, precisionB): return output #0.56 b8 to b10 #(1/base) ^ (i+1) *x to10('56') test = list(str(56)) test 27 9 3 33 0.3212 * 3 4*1.5 0.3212* 4/6 3*3**-1 2*3**-2 1*3**...
[ "#!ipython3\n\npi_f = 0.1415926\npi = []\nfor i in range(10):\n pi.append(str(pi_f * i*16)[0])\n\nprint(pi)\n\n\ndef convertBase(digits, baseA, baseB, precisionB):\n return output\n\n#0.56 b8 to b10\n#(1/base) ^ (i+1) *x\n\n\nto10('56')\n\ntest = list(str(56))\ntest\n\n27 9 3\n 33\n\n\n0.3212 * 3\n4*1.5\n0...
true
8,270
d95cbca8e892f18f099b370e139176770ce0c1b7
# 文字列(結合) str1 = "py" str2 = "thon" print(str1+str2)
[ "# 文字列(結合)\n\nstr1 = \"py\"\nstr2 = \"thon\"\nprint(str1+str2)\n", "str1 = 'py'\nstr2 = 'thon'\nprint(str1 + str2)\n", "<assignment token>\nprint(str1 + str2)\n", "<assignment token>\n<code token>\n" ]
false
8,271
264b48c2b9ce4ec948ca5ba548e708848760f3dc
# Merge sort is used to sort the elements def merge_sort(arr): if len(arr) > 1: # Recursion is used to continuously split the array in half. mid = len(arr) // 2 # Using Auxiliary storage here left = arr[:mid] right = arr[mid:] # Traverse the left side of the array ...
[ "# Merge sort is used to sort the elements\ndef merge_sort(arr):\n if len(arr) > 1:\n # Recursion is used to continuously split the array in half.\n mid = len(arr) // 2\n # Using Auxiliary storage here\n left = arr[:mid]\n right = arr[mid:]\n # Traverse the left side of ...
false
8,272
e5a4ae2ec0fab1ca8cdce229c69725ece2dcc476
import numpy as np import ipywidgets as widgets from ipywidgets import interact, interactive, fixed, Layout, VBox, HBox import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.tri as tri import matplotlib.colors as colors from matplotlib.colors import LinearSegmentedColormap import scipy.stats as sps...
[ "import numpy as np\nimport ipywidgets as widgets\nfrom ipywidgets import interact, interactive, fixed, Layout, VBox, HBox\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport matplotlib.tri as tri\nimport matplotlib.colors as colors\nfrom matplotlib.colors import LinearSegmentedColormap\nimport scipy...
false
8,273
eb827998f1ba75ffb95751ddb2b31d4d0e54358b
import numpy as np import csv class PriceTracker: def __init__(self): pass def getValue(self, i): pass class CsvTracker: def __init__(self, csv_file): self.current_row = 61 self.csv_file_content = [] self.csv_file = csv.reader(csv_file, delimiter =',') fo...
[ "import numpy as np\nimport csv\n\nclass PriceTracker:\n\n def __init__(self):\n pass\n\n def getValue(self, i):\n pass\n\n\nclass CsvTracker:\n def __init__(self, csv_file):\n self.current_row = 61\n self.csv_file_content = []\n self.csv_file = csv.reader(csv_file, delim...
true
8,274
12fdeae0ae1618139b20176846e7df5b82f7aa01
from pyspark import SparkContext, RDD from pyspark.sql import SparkSession, DataFrame from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils import string from kafka import KafkaProducer import time import pyspark sc = SparkContext(master='local[4]') ssc = StreamingContext(sc, b...
[ "from pyspark import SparkContext, RDD\nfrom pyspark.sql import SparkSession, DataFrame\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nimport string\nfrom kafka import KafkaProducer\nimport time\nimport pyspark\n\n\nsc = SparkContext(master='local[4]')\nssc = Stream...
false
8,275
414fb437783fcfb55f542f072aaf3a8bb02b441e
import ipaddress import subprocess from subprocess import Popen, PIPE import time ip_net = ipaddress.ip_network('192.168.0.100/30') for i in ip_net.hosts(): # print(i) host_add = str(i) toping = subprocess.Popen(['ping', '-n', '3',host_add],stdout=PIPE) output = toping.communicate()[0] ...
[ "import ipaddress\r\nimport subprocess\r\nfrom subprocess import Popen, PIPE\r\nimport time\r\n\r\nip_net = ipaddress.ip_network('192.168.0.100/30')\r\nfor i in ip_net.hosts():\r\n # print(i)\r\n host_add = str(i)\r\n toping = subprocess.Popen(['ping', '-n', '3',host_add],stdout=PIPE)\r\n\r\n output = t...
false
8,276
010a132645883915eff605ae15696a1fac42d570
import math import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def value(energy, noise, x, gen): logp_x = energy(x) logq_x = noise.log_prob(x).unsqueeze(1) logp_gen = energy(gen) logq_ge...
[ "import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\ndef value(energy, noise, x, gen):\n logp_x = energy(x)\n logq_x = noise.log_prob(x).unsqueeze(1)\n logp_gen = ener...
false
8,277
2804d49fc9f0e40859de1e8eb4f04a849639b1d4
__author__ = 'Freek' __build__ = 'versie 1.0' from iNStagram.file_io.fileio import lees_stationgegevens from iNStagram.api_requests.app_requests import request_instagram from tkinter import * startscherm = Tk() startscherm.title('Foto of video in de buurt!') startscherm.minsize(width=790, height=600, ) startscherm.c...
[ "__author__ = 'Freek'\n__build__ = 'versie 1.0'\n\nfrom iNStagram.file_io.fileio import lees_stationgegevens\nfrom iNStagram.api_requests.app_requests import request_instagram\n\nfrom tkinter import *\n\nstartscherm = Tk()\nstartscherm.title('Foto of video in de buurt!')\nstartscherm.minsize(width=790, height=600, ...
false
8,278
fd1b871c5cf79874acf8d5c4f1f73f7a381e23f7
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders. import datetime import scrapy from ScrapyProject.items import ScrapyItem class ThalesSpider(scrapy.Spider): #item_id = ScrapyItem() name = 'thales' allo...
[ "# This package will contain the spiders of your Scrapy project\n#\n# Please refer to the documentation for information on how to create and manage\n# your spiders.\n\nimport datetime\nimport scrapy\nfrom ScrapyProject.items import ScrapyItem\n\nclass ThalesSpider(scrapy.Spider):\n\t#item_id = ScrapyItem()\n\tname ...
false
8,279
0edc0c2f86bda0122d4b231eed700d7a5b08ec1e
from proxmin import nmf from proxmin.utils import Traceback from proxmin import operators as po from scipy.optimize import linear_sum_assignment import numpy as np import matplotlib.pyplot as plt import time from functools import partial # initialize and run NMF import logging logging.basicConfig() logger ...
[ "from proxmin import nmf\r\nfrom proxmin.utils import Traceback\r\nfrom proxmin import operators as po\r\nfrom scipy.optimize import linear_sum_assignment\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nfrom functools import partial\r\n\r\n# initialize and run NMF\r\nimport logging\r\nlog...
false
8,280
faf2f5da92cf45cfedda91955688b3ca1c7c0db9
# ------------------------------- # --------- Set Methods --------- # ------------------------------- # difference() return the values in the first set that not in the second set set1 ={1, 2, 3, 4, 5, 6, 7, 8 , 9} set2 = {1, 2, 3, 4, 5, 6, "A", "B"} print(set1) print(set2) print(set1.difference(set2)) print(set1-set2...
[ "# -------------------------------\n# --------- Set Methods ---------\n# -------------------------------\n\n\n# difference() return the values in the first set that not in the second set\nset1 ={1, 2, 3, 4, 5, 6, 7, 8 , 9}\nset2 = {1, 2, 3, 4, 5, 6, \"A\", \"B\"}\nprint(set1)\nprint(set2)\nprint(set1.difference(set...
false
8,281
4af573fa17f86ee067b870dce1f6ee482d1b14ff
""" Декоратор parser_stop - парсер результата вывода комманды docker stop. """ from functools import wraps def parser_stop(func): @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) stdout = result['stdout'] """ stdout: строки разделены \n """ ...
[ "\"\"\"\nДекоратор parser_stop - парсер результата вывода комманды docker stop.\n\"\"\"\n\nfrom functools import wraps\n\n\ndef parser_stop(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n result = func(*args, **kwargs)\n stdout = result['stdout']\n\n \"\"\"\n stdout: строки...
false
8,282
51358ac7d4fc093f8291cfd9f098e3ac3db86cce
#!/usr/bin/python # -*- coding: utf-8 -*- import os, uuid, re, sys from decimal import Decimal from datetime import date, time, datetime from functools import lru_cache from typing import Iterator import pyodbc, pytest # WARNING: Wow Microsoft always manages to do the stupidest thing possible always trying to be # ...
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os, uuid, re, sys\nfrom decimal import Decimal\nfrom datetime import date, time, datetime\nfrom functools import lru_cache\nfrom typing import Iterator\n\nimport pyodbc, pytest\n\n\n# WARNING: Wow Microsoft always manages to do the stupidest thing possible alway...
false
8,283
ff9376ab4d6a88849167fb6e180fd9c4f9ab4dad
# -*- coding: utf-8 -*- import os import sys import base64 import cdutil import json import os from array import array from uuid import uuid4 import cdms2 import numpy as np import matplotlib as mpl mpl.rcParams['mathtext.default'] = 'regular' mpl.use('qt4agg') import matplotlib.pyplot as plt from mpl_toolkits.ba...
[ " # -*- coding: utf-8 -*-\nimport os\nimport sys\n\nimport base64\nimport cdutil\nimport json\nimport os\nfrom array import array\nfrom uuid import uuid4\n\nimport cdms2\nimport numpy as np\nimport matplotlib as mpl\nmpl.rcParams['mathtext.default'] = 'regular'\nmpl.use('qt4agg')\nimport matplotlib.pyplot as plt...
true
8,284
6962bf99e3ecae473af54ded33fde09527cb82c0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 25 18:40:07 2021 @author: tomachache """ import numpy as np from qiskit import * # Various state preparation def state_preparation(m, name, p): # m : nb of qubits # name : name of the state we want # p : proba associated with nois...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 25 18:40:07 2021\n\n@author: tomachache\n\"\"\"\n\nimport numpy as np\n\nfrom qiskit import *\n\n\n# Various state preparation\ndef state_preparation(m, name, p): \n # m : nb of qubits \n # name : name of the state we want \n # p ...
false
8,285
f502290cc8ffa9571454a214497aff1d1c5e1c9f
var blackList = []string{ // global "document", "window", "top", "parent", "global", "this", //func "console", "alert", "log", "promise", "fetch", "eval", "import", //char "<", ">", "`", "\\*", "&", "#", "%", "\\\\", //key "if", "set", "get", "with", "yield", "async", "wait", "func", "for", "error", "string", ...
[ "var blackList = []string{\n\t// global\n\t\"document\", \"window\", \"top\", \"parent\", \"global\", \"this\",\n\t//func\n\t\"console\", \"alert\", \"log\", \"promise\", \"fetch\", \"eval\", \"import\",\n\t//char\n\t\"<\", \">\", \"`\", \"\\\\*\", \"&\", \"#\", \"%\", \"\\\\\\\\\",\n\t//key\n\t\"if\", \"set\", \"g...
true
8,286
3ebd455056f168f8f69b9005c643c519e5d0b436
import os import glob import pandas as pd classes = os.listdir(os.getcwd()) for classf in classes: #if os.path.isfile(classf) or classf == 'LAST': #continue PWD = os.getcwd() + "/" + classf + "/" currentdname = os.path.basename(os.getcwd()) csvfiles=glob.glob(PWD + "/*.csv") df = pd.DataFrame(columns=['im...
[ "import os\nimport glob\nimport pandas as pd\n\nclasses = os.listdir(os.getcwd())\n\nfor classf in classes:\n\t#if os.path.isfile(classf) or classf == 'LAST':\n\t\t#continue\n\t\t\n\tPWD = os.getcwd() + \"/\" + classf + \"/\"\n\tcurrentdname = os.path.basename(os.getcwd())\n\tcsvfiles=glob.glob(PWD + \"/*.csv\")\n\...
false
8,287
eab2cdd92d3be5760f13e747b05ca902eaf9aca8
import sys import os arcpy_path = [r'D:\software\ArcGIS\python 27\ArcGIS10.2\Lib\site-packages', r'D:\software\ArcGIS\Desktop 10.2\Desktop10.2\arcpy', r'D:\software\ArcGIS\Desktop 10.2\Desktop10.2\bin', r'D:\software\ArcGIS\Desktop 10.2\Desktop10.2\ArcToolbox\Scripts'] sys.pa...
[ "import sys\nimport os\n\narcpy_path = [r'D:\\software\\ArcGIS\\python 27\\ArcGIS10.2\\Lib\\site-packages',\n r'D:\\software\\ArcGIS\\Desktop 10.2\\Desktop10.2\\arcpy',\n r'D:\\software\\ArcGIS\\Desktop 10.2\\Desktop10.2\\bin',\n r'D:\\software\\ArcGIS\\Desktop 10.2\\Desktop10...
false
8,288
cce40ff190f7790ac4eca7d6cb3c032955bb4849
""" Copyright 2020 Google LLC 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
[ "\"\"\"\nCopyright 2020 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in w...
false
8,289
8f5b7711d913c7375d6816dd94731f1ce5ca1a62
from template.db import Database from template.query import Query import os ''' READ ME!! Before using this demo, be sure that the Tail_Const is set to a value high enough to guaranteed that all updates are contained within the same block. config.py -> TAIL_CONST = 4 This program is mean...
[ "from template.db import Database\r\nfrom template.query import Query\r\nimport os\r\n\r\n'''\r\nREAD ME!!\r\n Before using this demo, be sure that the Tail_Const is set to a value high enough\r\n to guaranteed that all updates are contained within the same block.\r\n config.py -> TAIL_CONST = 4\r\n\r\...
false
8,290
781cb59fb9b6d22547fd4acf895457868342e125
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-17 14:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('votes', '0003_choice_votes'), ] operations = [ migrations.CreateModel( ...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.3 on 2016-11-17 14:47\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('votes', '0003_choice_votes'),\n ]\n\n operations = [\n migration...
false
8,291
97d84f99264afa5e7df4b5d22cf4c49b2d14ff7a
def word_count(s): # Your code here cache = {} ignore = '":;,.-+=/\\|[]{}()*^&' lower = s.lower() for i in lower: if i in ignore: lower = lower.replace(i, '') words = lower.split() for j in words: if j not in cache: cache[j] = 1 else: ...
[ "def word_count(s):\n # Your code here\n cache = {}\n ignore = '\":;,.-+=/\\\\|[]{}()*^&'\n lower = s.lower()\n\n for i in lower:\n if i in ignore:\n lower = lower.replace(i, '')\n words = lower.split()\n for j in words:\n if j not in cache:\n cache[j] = 1\n ...
false
8,292
02f196623907703255bf149db0435104d086da97
import numpy as np import cv2 import time from itertools import chain, compress from collections import defaultdict, namedtuple class FeatureMetaData(object): """ Contain necessary information of a feature for easy access. """ def __init__(self): self.id = None # int ...
[ "import numpy as np\r\nimport cv2\r\nimport time\r\n\r\nfrom itertools import chain, compress\r\nfrom collections import defaultdict, namedtuple\r\n\r\n\r\n\r\nclass FeatureMetaData(object):\r\n \"\"\"\r\n Contain necessary information of a feature for easy access.\r\n \"\"\"\r\n def __init__(self):\r\n...
false
8,293
19b55b2de3d2ed16275cef572e3518fbb2457f84
from django import forms class photoForm(forms.Form): iso = forms.ChoiceField(label='ISO', choices=[("100", 100), ("200", 200), ("300", 300), ("400", 400), ...
[ "from django import forms\n\nclass photoForm(forms.Form):\n iso = forms.ChoiceField(label='ISO', choices=[(\"100\", 100),\n (\"200\", 200),\n (\"300\", 300),\n (\"400\", 400)...
false
8,294
1d1576825f80c3b65ce1b7f8d1daccbbf8543d7d
# -*- coding: utf-8 -*- import numpy as np import pickle import os import feature_extraction #import topic file1 = open('vecdict_all.p', 'r') file2 = open('classif_all.p','r') vec = pickle.load(file1) classifier = pickle.load(file2) file1.close() file2.close() #sentence = "I never miss the lecture of Dan Moldovan...
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pickle\nimport os\nimport feature_extraction\n#import topic\n\n\nfile1 = open('vecdict_all.p', 'r')\nfile2 = open('classif_all.p','r')\n\nvec = pickle.load(file1)\nclassifier = pickle.load(file2)\n\nfile1.close()\nfile2.close()\n\n#sentence = \"I never miss the...
true
8,295
e8b0e6e5e68933703e2ac8c9b2b62d68c0c2f53d
# coding=gbk from numpy import * import fp_growth ''' #创建树的一个单节点 rootNode=fp_growth.treeNode('pyramid',9,None) #为其增加一个子节点 rootNode.children['eye']=fp_growth.treeNode('eye',13,None) rootNode.disp() #导入事务数据库实例 simpData=fp_growth.loadSimpData() #print("simpData:") #print(simpData) #对数据进行格式化处理 initSet=fp_growth.cre...
[ "# coding=gbk\nfrom numpy import *\n\nimport fp_growth\n\n\n'''\n#创建树的一个单节点\nrootNode=fp_growth.treeNode('pyramid',9,None)\n#为其增加一个子节点\nrootNode.children['eye']=fp_growth.treeNode('eye',13,None)\n\nrootNode.disp()\n\n\n\n#导入事务数据库实例\nsimpData=fp_growth.loadSimpData()\n#print(\"simpData:\")\n#print(simpData)\n\n#对数据进...
false
8,296
8fb559810fbf79f0849ed98e51d3f2ad1ccc4b8b
from typing import List h = 5 w = 4 horizontalCuts = [3] verticalCuts = [3] class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.sort() verticalCuts.sort() horizontalCuts.append(h) verticalCuts.append(w) ...
[ "from typing import List\nh = 5\nw = 4\nhorizontalCuts = [3]\nverticalCuts = [3]\nclass Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n horizontalCuts.sort()\n verticalCuts.sort()\n horizontalCuts.append(h)\n verticalCuts.app...
false
8,297
7b920545a0241b30b66ff99f330dbb361f747f13
card = int(input()) last4 = card % 10000 print(last4)
[ "card = int(input())\r\nlast4 = card % 10000\r\nprint(last4)", "card = int(input())\nlast4 = card % 10000\nprint(last4)\n", "<assignment token>\nprint(last4)\n", "<assignment token>\n<code token>\n" ]
false
8,298
faafc7cfd900d3f6fd6df30af5580f71eecfb279
import torch import torch_scatter import torchgraphs as tg import textwrap from . import autograd_tricks as lrp def patch(): torch.add = lrp.add torch.cat = lrp.cat torch.index_select = lrp.index_select tg.utils.repeat_tensor = lrp.repeat_tensor torch_scatter.scatter_add = lrp.scatter_add ...
[ "import torch\nimport torch_scatter\nimport torchgraphs as tg\n\nimport textwrap\n\nfrom . import autograd_tricks as lrp\n\n\n\ndef patch():\n torch.add = lrp.add\n torch.cat = lrp.cat\n torch.index_select = lrp.index_select\n\n tg.utils.repeat_tensor = lrp.repeat_tensor\n\n torch_scatter.scatter_add...
false
8,299
086aefaad7a4b743e5a05b3a44db971dbdbf16b6
import tensorflow as tf from sklearn.cluster import KMeans import tensorflow.keras as keras from copy import deepcopy import numpy as np import h5py from collections import defaultdict, namedtuple from heapq import heappush, heappop, heapify import struct tf.enable_eager_execution() mnist = tf.keras.datasets.mnist (x...
[ "import tensorflow as tf\nfrom sklearn.cluster import KMeans\nimport tensorflow.keras as keras\nfrom copy import deepcopy\nimport numpy as np\nimport h5py\nfrom collections import defaultdict, namedtuple\nfrom heapq import heappush, heappop, heapify\nimport struct\ntf.enable_eager_execution()\n\nmnist = tf.keras.da...
false