index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
1,800 | ea2183530667437e086bc89f137e464dec6f363a | from django.db import models
class Kit(models.Model):
name = models.CharField(max_length=100, null=True)
main_image_url = models.URLField(max_length=1000)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
description = models.CharField(max_length=1000, null=T... | [
"from django.db import models\n\nclass Kit(models.Model):\n name = models.CharField(max_length=100, null=True)\n main_image_url = models.URLField(max_length=1000)\n price = models.DecimalField(max_digits=10, decimal_places=2, default=0)\n description = models.CharField(max_length=1... | false |
1,801 | e4e2e8ca65d109805b267f148e8d255d81d4ee83 | from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, logout, login
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views import View
class login_view(View):
template... | [
"from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, logout, login\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views import View\n\nclass login_view(View):\... | false |
1,802 | 2ad326f739b42b9c7c252078b8c28e90da17b95d | import multiprocessing
name = "flask_gunicorn"
workers = multiprocessing.cpu_count() * 2 + 1
loglevel = "debug"
bind = f"0.0.0.0:18080"
| [
"import multiprocessing\n\nname = \"flask_gunicorn\"\nworkers = multiprocessing.cpu_count() * 2 + 1\nloglevel = \"debug\"\nbind = f\"0.0.0.0:18080\"\n\n",
"import multiprocessing\nname = 'flask_gunicorn'\nworkers = multiprocessing.cpu_count() * 2 + 1\nloglevel = 'debug'\nbind = f'0.0.0.0:18080'\n",
"<import tok... | false |
1,803 | 01900c1d14a04ee43553c8602a07e0c6ecfabded | # -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from rest_framework import serializers
from tandlr.core.api.serializers import ModelSerializer
from tandlr.users.models import DeviceUser, User, UserSettings
from tandlr.utils.refresh_token import create_token
class LoginSerializer(serializers.S... | [
"# -*- coding: utf-8 -*-\nfrom django.shortcuts import get_object_or_404\n\nfrom rest_framework import serializers\n\nfrom tandlr.core.api.serializers import ModelSerializer\nfrom tandlr.users.models import DeviceUser, User, UserSettings\nfrom tandlr.utils.refresh_token import create_token\n\n\nclass LoginSerialize... | false |
1,804 | 3b381668dbb9b4e5a2e323dc4d6b5e3951736882 | from collections import namedtuple
import argparse
import pdb
import traceback
import sys
import os
from qca_hex_analyzer import WmiCtrlAnalyzer, HtcCtrlAnalyzer, HttAnalyzer, AllAnalyzer
import hexfilter
description = \
"Tool used to analyze hexdumps produced by a qca wireless kernel " \
"driver (such as ath... | [
"from collections import namedtuple\n\nimport argparse\nimport pdb\nimport traceback\nimport sys\nimport os\nfrom qca_hex_analyzer import WmiCtrlAnalyzer, HtcCtrlAnalyzer, HttAnalyzer, AllAnalyzer\nimport hexfilter\n\ndescription = \\\n \"Tool used to analyze hexdumps produced by a qca wireless kernel \" \\\n ... | false |
1,805 | bebe098c5abb579eb155a1dc325347d100ddfa8f | def coroutine(func):
def start_coroutine(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr) #cr.send(None)
return cr
return start_coroutine
@coroutine
def grep(pattern):
print('start grep')
try:
while True:
line = yield
if pattern in line:
print(line)
except GeneratorExit:
print('stop grep'... | [
"def coroutine(func):\n\tdef start_coroutine(*args, **kwargs):\n\t\tcr = func(*args, **kwargs)\n\t\tnext(cr) #cr.send(None)\n\t\treturn cr\n\treturn start_coroutine\n\n@coroutine\ndef grep(pattern):\n\tprint('start grep')\n\ttry:\n\t\twhile True:\n\t\t\tline = yield\n\t\t\tif pattern in line:\n\t\t\t\tprint(line)\n... | false |
1,806 | af903feda57e4ace0c7f909abbeb86bb9a7e4d8c | from data.dataframe_sequence_multi import DataFrameSequenceMulti
from metrics import Metrics
from models.models_ts_multi import lstm_model_multi
import threading
import sys
from keras import optimizers
from data.data_helper import plot_history
epochs = 100
start = 6
end = 18
res = []
sets = []
min_vals = []
min_loss ... | [
"from data.dataframe_sequence_multi import DataFrameSequenceMulti\nfrom metrics import Metrics\nfrom models.models_ts_multi import lstm_model_multi\nimport threading\nimport sys\nfrom keras import optimizers\nfrom data.data_helper import plot_history\n\nepochs = 100\nstart = 6\nend = 18\n\nres = []\nsets = []\nmin_... | false |
1,807 | 43179b8b096836758271a791b4aacb7bbe398ea9 | import sys
from Decks.Virtual_World.vw_sets import *
from tools import *
hand_3playable_hts = ["Nibiru, the Primal Being", "Effect Veiler", "Fantastical Dragon Phantazmay", "Dragon Buster Destruction Sword", "Dragon Buster Destruction Sword"]
hand_2playable_hts = ["Nibiru, the Primal Being", "Nibiru, the Primal Being"... | [
"import sys\nfrom Decks.Virtual_World.vw_sets import *\nfrom tools import *\n\nhand_3playable_hts = [\"Nibiru, the Primal Being\", \"Effect Veiler\", \"Fantastical Dragon Phantazmay\", \"Dragon Buster Destruction Sword\", \"Dragon Buster Destruction Sword\"]\nhand_2playable_hts = [\"Nibiru, the Primal Being\", \"Ni... | false |
1,808 | c599a75788e3548c52ebb3b29e7a2398ff1b28a2 | from sklearn.metrics import roc_auc_score, matthews_corrcoef, f1_score, confusion_matrix
import numpy as np
from scipy.stats import rankdata
def iou_score(target, prediction):
intersection = np.logical_and(target, prediction)
union = np.logical_or(target, prediction)
iou_score = np.sum(intersection) / (np... | [
"from sklearn.metrics import roc_auc_score, matthews_corrcoef, f1_score, confusion_matrix\nimport numpy as np\nfrom scipy.stats import rankdata\n\n\ndef iou_score(target, prediction):\n intersection = np.logical_and(target, prediction)\n union = np.logical_or(target, prediction)\n iou_score = np.sum(inters... | false |
1,809 | 1db16ae1fc6546575150187432265ac1cf834ec2 | import pandas as pd
import numpy as np
import datetime as dt
def sum_unique(x):
return np.unique(x).shape[0]
def analyze_count(data):
"""real time, vk, itemid, action"""
dsct_vk = pd.unique(data['vk'])
dsct_itemid = pd.unique(data['itemid'])
print 'number of user:', dsct_vk.shape
print ... | [
"import pandas as pd\nimport numpy as np\nimport datetime as dt\n\ndef sum_unique(x):\n return np.unique(x).shape[0]\n\ndef analyze_count(data):\n \n \"\"\"real time, vk, itemid, action\"\"\"\n\n dsct_vk = pd.unique(data['vk'])\n dsct_itemid = pd.unique(data['itemid'])\n\n print 'number of user:',... | true |
1,810 | 5749f30d1a1efd5404654d755bca4515adcf4bca | import json
from django.db import models
from django.conf import settings
from django.core.serializers import serialize
# Create your models here.
def upload_updated_image(instance,filename):
return '/MyApi/{user}/{filename}'.format(user=instance.user,filename=filename)
class UpdateQueryset(models.QuerySet):
... | [
"import json\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.serializers import serialize\n\n# Create your models here.\n\ndef upload_updated_image(instance,filename):\n return '/MyApi/{user}/{filename}'.format(user=instance.user,filename=filename)\n\nclass UpdateQueryset(models... | false |
1,811 | 3a09cbd71d23b1320af9b8ddcfc65b223e487b21 | import random
import csv
# 提取随机问,同类组成正例,异类组成负例,正:负=1:3
with open('final_regroup.csv', 'w', newline='') as train:
writer = csv.writer(train)
with open('final_syn_train.csv', 'r') as zhidao:
reader = csv.reader(zhidao)
cluster = []
cur = []
stand = ''
# 将同一标准问... | [
"import random\r\nimport csv\r\n\r\n\r\n# 提取随机问,同类组成正例,异类组成负例,正:负=1:3\r\nwith open('final_regroup.csv', 'w', newline='') as train:\r\n writer = csv.writer(train)\r\n with open('final_syn_train.csv', 'r') as zhidao:\r\n reader = csv.reader(zhidao)\r\n cluster = []\r\n cur = []\r\n s... | false |
1,812 | 707855a4e07b68d9ae97c2e1dc8bfd52f11c314c | import nltk
import spacy
import textacy
from keras.layers import Embedding, Bidirectional, Dense, Dropout, BatchNormalization
from keras_preprocessing.sequence import pad_sequences
from keras_preprocessing.text import Tokenizer
from nltk import word_tokenize, re
from rasa import model
import pandas as pd
from spacy imp... | [
"import nltk\nimport spacy\nimport textacy\nfrom keras.layers import Embedding, Bidirectional, Dense, Dropout, BatchNormalization\nfrom keras_preprocessing.sequence import pad_sequences\nfrom keras_preprocessing.text import Tokenizer\nfrom nltk import word_tokenize, re\nfrom rasa import model\nimport pandas as pd\n... | false |
1,813 | ab5400f4b44a53cb5cc2f6394bcdb8f55fd218f0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | [
"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n ... | false |
1,814 | 2872c86294037b4585158e7ff6db414ba7ab90cc | from django.db import models
# Create your models here.
class AlertMailModel(models.Model):
receipient_mail = models.EmailField()
host_mail = models.EmailField()
host_smtpaddress = models.CharField(max_length=25)
mail_host_password = models.CharField(max_length=200)
use_tls=models.BooleanField(defa... | [
"from django.db import models\n\n# Create your models here.\nclass AlertMailModel(models.Model):\n receipient_mail = models.EmailField()\n host_mail = models.EmailField()\n host_smtpaddress = models.CharField(max_length=25)\n mail_host_password = models.CharField(max_length=200)\n use_tls=models.Bool... | false |
1,815 | 07ed8c12e8e5c568c897b6b632c48831267eba51 |
t_dim_2 = [[1, 2], [3, 4]]
def z(i, j, dim):
t = dim ** 2
if dim == 2:
return t_dim_2[i-1][j-1]
d = dim//2
if i <= d: # I or II
if j <= d:
return z(i, j, d) #I
else:
j -= d
return t//4 + z(i, j, d) # II
else: # III or IV
if j <=d... | [
"\nt_dim_2 = [[1, 2], [3, 4]]\n\ndef z(i, j, dim):\n t = dim ** 2\n if dim == 2:\n return t_dim_2[i-1][j-1]\n\n d = dim//2\n if i <= d: # I or II\n if j <= d:\n return z(i, j, d) #I\n else:\n j -= d\n return t//4 + z(i, j, d) # II\n else: # III or... | false |
1,816 | d6cfea95c76021bdbfbb4471878c653564c9accd | import urllib.request
from bs4 import BeautifulSoup
def getTitlesFromAll(amount, rating='all'):
output = ''
for i in range(1, amount+1):
try:
if rating == 'all':
html = urllib.request.urlopen('https://habr.com/all/page'+ str(i) +'/').read()
else:
... | [
"import urllib.request\nfrom bs4 import BeautifulSoup\n\ndef getTitlesFromAll(amount, rating='all'):\n output = ''\n for i in range(1, amount+1):\n try:\n if rating == 'all':\n html = urllib.request.urlopen('https://habr.com/all/page'+ str(i) +'/').read()\n else:\n ... | false |
1,817 | 5f13866bd5c6d20e8ddc112fb1d1335e3fd46c3e | import requests
import json
import base64
import re
def main(targetsrting):
email="" #email
key="" #key
#targetsrting='ip="202.107.117.5/24"' #搜索关键字
target=base64.b64encode(targetsrting.encode('utf-8')).decode("utf-8")
url="https://fofa.so/api/v1/search/all?email={}&key={}&qbase64={}&fields=hos... | [
"import requests\nimport json\nimport base64\nimport re\n\ndef main(targetsrting):\n email=\"\" #email\n key=\"\" #key\n #targetsrting='ip=\"202.107.117.5/24\"' #搜索关键字\n target=base64.b64encode(targetsrting.encode('utf-8')).decode(\"utf-8\")\n url=\"https://fofa.so/api/v1/search/all?email={}&key=... | false |
1,818 | c1bb2052b3f623c6787ba080dff2dc81f4d6f55e | import pandas as pd
import numpy as np
import json
from pprint import pprint
from shapely.geometry import shape, Point
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
from geopy.exc import GeocoderServiceError
import collections
from matplotlib import pyplot as plt
import time
import csv
... | [
"import pandas as pd\nimport numpy as np\nimport json\nfrom pprint import pprint\nfrom shapely.geometry import shape, Point\nfrom geopy.geocoders import Nominatim\nfrom geopy.exc import GeocoderTimedOut\nfrom geopy.exc import GeocoderServiceError\nimport collections\nfrom matplotlib import pyplot as plt\nimport tim... | true |
1,819 | 1b4c86fe3aae25aeec6cd75fa8177983ce9d14a2 | #!/usr/bin/python2.7
import os, sys
COMPILER = "gcc"
SRC_DIR = "../src"
INCLUDE_DIR = "../src"
BIN_DIR = "../bin"
BIN_NAME = False
CFLAGS = ["-O3", "-Wall", "-Wextra", "--std=c89", "-pedantic"]
DLIBS = ["ws2_32"] if os.name == "nt" else []
DEFINES = []
def strformat(fmt, var):
for k in... | [
"#!/usr/bin/python2.7\nimport os, sys\n\nCOMPILER = \"gcc\"\nSRC_DIR = \"../src\"\nINCLUDE_DIR = \"../src\"\nBIN_DIR = \"../bin\"\nBIN_NAME = False\nCFLAGS = [\"-O3\", \"-Wall\", \"-Wextra\", \"--std=c89\", \"-pedantic\"]\nDLIBS = [\"ws2_32\"] if os.name == \"nt\" else []\nDEFINES = []\... | true |
1,820 | 1aed8e92a31ee42a3a609123af927f7074598ec1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/14 下午6:06
# @Author : Huang HUi
# @Site :
# @File : Longest Common Prefix.py
# @Software: PyCharm
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
... | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/7/14 下午6:06\n# @Author : Huang HUi\n# @Site : \n# @File : Longest Common Prefix.py\n# @Software: PyCharm\n\nclass Solution(object):\n def longestCommonPrefix(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: str\... | false |
1,821 | 63edbbbad9561ddae005d2b5e22a089819dc34c5 | import torch
import random
from itertools import product
from Struct import Action
class Agent(object):
"""the agent"""
def __init__(self, q, epsilon=0.8, discount=0.9, learningRate=0.5, traceDecay=0.3):
# action set
possibleChangesPerMagnet = (1e-2, 1e-3, 0, -1e-2, -1e-3)
# possible... | [
"import torch\nimport random\nfrom itertools import product\n\nfrom Struct import Action\n\n\nclass Agent(object):\n \"\"\"the agent\"\"\"\n\n def __init__(self, q, epsilon=0.8, discount=0.9, learningRate=0.5, traceDecay=0.3):\n # action set\n possibleChangesPerMagnet = (1e-2, 1e-3, 0, -1e-2, -1... | false |
1,822 | 41842e8b75860c65e87e9db1f7ae058957e37e45 | #Import Discord Package
import discord
from discord.ext import commands
import asyncio
import glob
from dotenv import load_dotenv
import os
load_dotenv() # Load your Discord Token
TOKEN = os.getenv("TOKEN")
bot = commands.Bot(command_prefix='.',case_insensitive=True)
print('Ready!')
@bot.command()
async def stop... | [
"#Import Discord Package\nimport discord\nfrom discord.ext import commands\nimport asyncio\nimport glob\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv() # Load your Discord Token\n\nTOKEN = os.getenv(\"TOKEN\") \n\nbot = commands.Bot(command_prefix='.',case_insensitive=True)\n \nprint('Ready!')\n\n@bot.c... | false |
1,823 | e3e6f1b6580a223558791cebfcb1a92d45553162 | def digital_sum(n):
if n < 10:
return n
return n % 10 + digital_sum(n // 10)
def digital_root(n):
if n < 10:
return n
return digital_root(digital_sum(n))
| [
"def digital_sum(n):\n if n < 10:\n return n\n return n % 10 + digital_sum(n // 10)\n\ndef digital_root(n):\n if n < 10:\n return n\n return digital_root(digital_sum(n))\n",
"def digital_sum(n):\n if n < 10:\n return n\n return n % 10 + digital_sum(n // 10)\n\n\ndef digital_... | false |
1,824 | c5ac37ce09f7cd76ccd9b93c64e602209a04c55c | import requests
from pyrogram import Client as Bot
from samantha.config import API_HASH, API_ID, BG_IMAGE, BOT_TOKEN
from samantha.services.callsmusic import run
response = requests.get(BG_IMAGE)
file = open("./etc/tg_vc_bot.jpg", "wb")
file.write(response.content)
file.close()
bot = Bot(
":memory:",
API_ID,... | [
"import requests\nfrom pyrogram import Client as Bot\n\nfrom samantha.config import API_HASH, API_ID, BG_IMAGE, BOT_TOKEN\nfrom samantha.services.callsmusic import run\n\nresponse = requests.get(BG_IMAGE)\nfile = open(\"./etc/tg_vc_bot.jpg\", \"wb\")\nfile.write(response.content)\nfile.close()\n\nbot = Bot(\n \"... | false |
1,825 | f4c90a6d6afdcf78ec6742b1924a5c854a5a4ed6 | import os
def take_shot(filename):
os.system("screencapture "+filename+".png")
| [
"import os\n\ndef take_shot(filename):\n os.system(\"screencapture \"+filename+\".png\")\n",
"import os\n\n\ndef take_shot(filename):\n os.system('screencapture ' + filename + '.png')\n",
"<import token>\n\n\ndef take_shot(filename):\n os.system('screencapture ' + filename + '.png')\n",
"<import toke... | false |
1,826 | 1e41cc5d2661f1fb4f3a356318fabcb2b742cbdf | from flask import Flask,Response,render_template,url_for,request,jsonify
from flask_bootstrap import Bootstrap
import pandas as pd
import gpt_2_simple as gpt2
import json
app = Flask(__name__)
Bootstrap(app)
#Main Page
@app.route('/')
def interactive_input():
return render_template('main.html')
#Creating the diff... | [
"from flask import Flask,Response,render_template,url_for,request,jsonify\nfrom flask_bootstrap import Bootstrap\nimport pandas as pd \nimport gpt_2_simple as gpt2\nimport json\n\n\napp = Flask(__name__)\nBootstrap(app)\n\n#Main Page\n@app.route('/')\ndef interactive_input():\n\treturn render_template('main.html')\... | false |
1,827 | fab7ee8a7336ba2c044adce4cc8483af78b775ba | #!/usr/bin/env python
from distutils.core import setup
setup(
name='RBM',
version='0.0.1',
description='Restricted Boltzmann Machines',
long_description='README',
install_requires=['numpy','pandas'],
)
| [
"#!/usr/bin/env python\n\nfrom distutils.core import setup\n\nsetup(\n name='RBM',\n version='0.0.1',\n description='Restricted Boltzmann Machines',\n long_description='README',\n install_requires=['numpy','pandas'],\n)\n",
"from distutils.core import setup\nsetup(name='RBM', version='0.0.1', descr... | false |
1,828 | 3329db63552592aabb751348efc5d983f2cc3f36 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 21 09:46:47 2020
@author: Carlos Jose Munoz
"""
# se importa el modelo y vista para que sesten comunicados por medio del controlador
from Modelo import ventanadentrada
from Vista import Ventanainicio,dosventana
import sys
from PyQt5.QtWidgets import QApplication
clas... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 21 09:46:47 2020\n\n@author: Carlos Jose Munoz\n\"\"\"\n# se importa el modelo y vista para que sesten comunicados por medio del controlador \nfrom Modelo import ventanadentrada\nfrom Vista import Ventanainicio,dosventana\n\nimport sys\n\nfrom PyQt5.QtWidgets imp... | false |
1,829 | 05573b4ff68ca8638f8e13946b410df2a012840a | from datetime import timedelta, datetime
import glob
import json
import os
import re
import pickle
import os,time
import pandas as pd
import numpy as np
from collections import Counter
from sentencepiece import SentencePieceTrainer
from sentencepiece import SentencePieceProcessor
from sklearn.feature_extraction.text i... | [
"from datetime import timedelta, datetime\nimport glob\nimport json\nimport os\nimport re\nimport pickle\n\nimport os,time\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nfrom sentencepiece import SentencePieceTrainer\nfrom sentencepiece import SentencePieceProcessor\nfrom sklearn.feature... | false |
1,830 | b29f85ccf396640c2a63bf634b549a3eaa0dbb1b | #!/usr/bin/env python2
from Crypto.PublicKey import RSA
from Crypto.Util.number import *
from timeit import default_timer as timer
import os
import gmpy2
import itertools as it
def extract2(inp):
two = 0
while inp % 2 == 0:
inp //= 2
two += 1
return inp, two
def genkey():
while 1:
... | [
"#!/usr/bin/env python2\n\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Util.number import *\nfrom timeit import default_timer as timer\n\nimport os\nimport gmpy2\nimport itertools as it\n\n\ndef extract2(inp):\n two = 0\n while inp % 2 == 0:\n inp //= 2\n two += 1\n return inp, two\n\ndef g... | false |
1,831 | f1fbbbe4258d0fb0a43505f4718730934fd595ec | import socket
import threading
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 12321
server.bind(('', port))
server.listen()
client_names = []
clients = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
... | [
"import socket\nimport threading\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nport = 12321\n\nserver.bind(('', port))\nserver.listen()\n\nclient_names = []\nclients = []\n\ndef broadcast(message):\n for client in clients:\n client.send(message)\n\n\ndef handle(client):\n while True:\n... | false |
1,832 | 018b9533074d2766dc5010ff9c5e70888d249b45 | a = range(10)
[x*x for x in a]
| [
"a = range(10)\n[x*x for x in a]\n",
"a = range(10)\n[(x * x) for x in a]\n",
"<assignment token>\n[(x * x) for x in a]\n",
"<assignment token>\n<code token>\n"
] | false |
1,833 | 7f33effa86fc3a80fce0e5e1ecf97ab4ca80402d | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import requests
BASE_URL = 'http://www.omdbapi.com/'
def rating_msg(rating):
if rating > 80:
return 'You should watch this movie right now!\n'
elif rating < 50:
return 'Avoid this movie at all cost!\n'
else:
re... | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport json\n\nimport requests\n\n\nBASE_URL = 'http://www.omdbapi.com/'\n\n\ndef rating_msg(rating):\n if rating > 80:\n return 'You should watch this movie right now!\\n'\n elif rating < 50:\n return 'Avoid this movie at all cost!\\n... | false |
1,834 | 23bcef07326db084d4e0e6337beb00faba329193 | // Time Complexity : O(n)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// // Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res=[]
... | [
"// Time Complexity : O(n)\n// Space Complexity : O(n)\n// Did this code successfully run on Leetcode : Yes\n// // Any problem you faced while coding this : No\n\n// Your code here along with comments explaining your approach\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n ... | true |
1,835 | 7d5f41cfa2d5423c6db2678f1eb8160638b50c02 | import re
class CoordinatesDataParser:
def __init__(self):
return
def get_coords(self, response):
html = response.xpath('.//body').extract_first()
longitude = re.search(r'-\d+\.\d{5,}', html)
longitude = longitude.group() if longitude else None
if longitude:
... | [
"import re\n\nclass CoordinatesDataParser:\n def __init__(self):\n return\n\n def get_coords(self, response):\n html = response.xpath('.//body').extract_first()\n longitude = re.search(r'-\\d+\\.\\d{5,}', html)\n longitude = longitude.group() if longitude else None\n if long... | false |
1,836 | b720a52f1c2e6e6be7c0887cd94441d248382242 | from joecceasy import Easy
def main():
paths = ['..','.']
absOfEntries = [ i.abs for i in Easy.WalkAnIter(paths) ]
for i in absOfEntries:
print( i )
if __name__=='__main__':
main()
"""
def main(maxEntries = 99):
i = -1
print( "Walker test, Walking cu... | [
"from joecceasy import Easy\r\n\r\ndef main():\r\n \r\n paths = ['..','.']\r\n absOfEntries = [ i.abs for i in Easy.WalkAnIter(paths) ]\r\n for i in absOfEntries:\r\n print( i )\r\n \r\nif __name__=='__main__':\r\n main()\r\n \r\n \r\n\"\"\"\r\ndef main(maxEntries = 99):\r\n i = -... | false |
1,837 | de884413dcbd0e89e8bfcf5657fe189156d9a661 | from setuptools import setup, find_packages
setup(name="sk_processor", packages=find_packages()) | [
"from setuptools import setup, find_packages\n\nsetup(name=\"sk_processor\", packages=find_packages())",
"from setuptools import setup, find_packages\nsetup(name='sk_processor', packages=find_packages())\n",
"<import token>\nsetup(name='sk_processor', packages=find_packages())\n",
"<import token>\n<code token... | false |
1,838 | b3bba1119bfaf0c1e684e8835259ec6fa8c42cf7 | from text_to_word_cloud import *
from collections import Counter
from preprocess import *
if __name__ == '__main__':
data = load_data('train.json')
words = text_to_words(get_all_text(data), as_set=False)
cnt = Counter(words)
save_il_to_word_cloud_file("cloudofw.txt",cnt,len(words),call_R=True... | [
"from text_to_word_cloud import *\r\nfrom collections import Counter\r\nfrom preprocess import *\r\n\r\n\r\nif __name__ == '__main__':\r\n data = load_data('train.json')\r\n words = text_to_words(get_all_text(data), as_set=False)\r\n cnt = Counter(words)\r\n save_il_to_word_cloud_file(\"cloudofw.txt\",c... | false |
1,839 | c67cd3c16c15d6aab02a07736c83bbdd5bd98514 | # -*- coding: utf-8 -*-"
"""
getMetaStream action for graphingwiki
- alternative meta retrieval action that uses
abuse-sa query language for filtering metas
and returns Line Delimeted JSON or event-stream
@copyright: 2015 Lauri Pokka <larpo@codenomicon.com>
@license: MIT <http://www.openso... | [
"# -*- coding: utf-8 -*-\"\n\"\"\"\n getMetaStream action for graphingwiki\n - alternative meta retrieval action that uses\n abuse-sa query language for filtering metas\n and returns Line Delimeted JSON or event-stream\n\n @copyright: 2015 Lauri Pokka <larpo@codenomicon.com>\n @license: MIT <... | false |
1,840 | 7f72f6a2ff0c7ceacb0f893d04c20402e850421a | ss=str(input())
print(len(ss)-ss.count(' '))
| [
"ss=str(input())\nprint(len(ss)-ss.count(' '))\n",
"ss = str(input())\nprint(len(ss) - ss.count(' '))\n",
"<assignment token>\nprint(len(ss) - ss.count(' '))\n",
"<assignment token>\n<code token>\n"
] | false |
1,841 | 1972e3733918da654cd156a500432a35a239aed4 | tn=int(input())
for ti in range(tn):
#ans = work()
rn,cn = [int(x) for x in input().split()]
evenRow='-'.join(['+']*(cn+1))
oddRow='.'.join(['|']*(cn+1))
artrn = rn*2+1
print(f'Case #{ti+1}:')
for ri in range(artrn):
defaultRow = evenRow if ri%2==0 else oddRow
if ri//2==0:
... | [
"tn=int(input())\nfor ti in range(tn):\n #ans = work()\n rn,cn = [int(x) for x in input().split()]\n evenRow='-'.join(['+']*(cn+1))\n oddRow='.'.join(['|']*(cn+1))\n artrn = rn*2+1\n print(f'Case #{ti+1}:')\n for ri in range(artrn):\n defaultRow = evenRow if ri%2==0 else oddRow\n ... | false |
1,842 | 07a0ba3ded8a2d4a980cfb8e3dbd6fd491ea24b0 | import web
import datetime
# run with sudo to run on port 80 and use GPIO
urls = ('/', 'index', '/survey', 'survey')
render = web.template.render('templates/')
class survey:
def GET(self):
return render.survey()
class index:
def GET(self):
i = web.input(enter=None)
... | [
"import web\nimport datetime\n\n# run with sudo to run on port 80 and use GPIO\n\nurls = ('/', 'index', '/survey', 'survey')\nrender = web.template.render('templates/')\n\nclass survey:\n def GET(self):\n return render.survey()\n\nclass index:\n def GET(self):\n i = web.i... | false |
1,843 | d07046e33bbfa404c354fef3e8990a3fa0203060 | #Task 4 - writing a code that prints all the commit message from repository
import requests
r = requests.get('https://api.github.com/repos/smeiklej/secu2002_2017/commits')
text = r.json()
#asking the code to print out the commit message for all rows in the text
for row in text:
print row['commit']['message']
| [
"#Task 4 - writing a code that prints all the commit message from repository\nimport requests\nr = requests.get('https://api.github.com/repos/smeiklej/secu2002_2017/commits')\ntext = r.json()\n\n#asking the code to print out the commit message for all rows in the text\nfor row in text:\n print row['commit']['mes... | true |
1,844 | 72d41f939a586fbd8459927983d9d62a96b650e2 | from __future__ import division, print_function
import numpy as np
from copy import deepcopy
class IntegratedRegressor():
regs = []
def __init__(self, reg, predict_log=True):
self.reg = reg
self.predict_log = predict_log
def fit(self, X, y):
self.regs = []
for target in ... | [
"from __future__ import division, print_function\n\nimport numpy as np\nfrom copy import deepcopy\n\n\nclass IntegratedRegressor():\n regs = []\n\n def __init__(self, reg, predict_log=True):\n self.reg = reg\n self.predict_log = predict_log\n\n def fit(self, X, y):\n self.regs = []\n ... | false |
1,845 | 6946601050802aaaa559d25612d0d4f5116559eb | from django.shortcuts import render, redirect, get_object_or_404
from .models import Article, Comment
# from IPython import embed
# Create your views here.
def article_list(request):
articles = Article.objects.all()
return render(request, 'board/list.html', {
'articles': articles,
})
def articl... | [
"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Article, Comment\n# from IPython import embed\n\n# Create your views here.\n\n\ndef article_list(request):\n articles = Article.objects.all()\n return render(request, 'board/list.html', {\n 'articles': articles,\n ... | false |
1,846 | 81da2aab9ca11e63dafdd4eefc340d37b326fc6f | # =======
# Imports
# =======
import os
import sympy
import numpy
from distutils.spawn import find_executable
import matplotlib
import matplotlib.pyplot as plt
from .Declarations import n,t
# =============
# Plot Settings
# =============
def PlotSettings():
"""
General settings for the plot.
"""
# C... | [
"# =======\n# Imports\n# =======\n\nimport os\nimport sympy\nimport numpy\nfrom distutils.spawn import find_executable\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom .Declarations import n,t\n\n# =============\n# Plot Settings\n# =============\n\ndef PlotSettings():\n \"\"\"\n General settings for ... | false |
1,847 | 3bfe4021d5cf9bd24c0fb778b252bc04c6ac47ed | import json
import requests
class Bitcoin:
coindesk = 'https://api.coindesk.com/v1/bpi/currentprice.json'
def __init__(self):
pass
def get_current_price(self, url=coindesk):
self.resp = requests.get(url)
if self.resp.status_code == 200:
return json.loads(self.resp.con... | [
"import json\nimport requests\n\n\nclass Bitcoin:\n coindesk = 'https://api.coindesk.com/v1/bpi/currentprice.json'\n\n def __init__(self):\n pass\n\n def get_current_price(self, url=coindesk):\n self.resp = requests.get(url)\n if self.resp.status_code == 200:\n return json.l... | false |
1,848 | 1dd62264aafe8ee745a3cfdfb994ac6a40c1af42 | import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
class LogisticRegression:
'''LogisticRegression for binary classification
max_iter: the maximum iteration times for training
learning_rate: learing rate for gradiend decsend training
Input's shape shoul... | [
"import numpy as np\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\n\n\nclass LogisticRegression:\n '''LogisticRegression for binary classification\n \n max_iter: the maximum iteration times for training\n learning_rate: learing rate for gradiend decsend training\n\n I... | false |
1,849 | aa817b86e26cf8cd9771aeb276914a1f5869c737 | #!/usr/bin/python
import csv
import sys
import os.path
#Versao 2 do gerador das RawZones
#global
DIR_PYGEN = "/bid/_temporario_/pythonGeneration/"
DIR_INTGR_PAR = "/bid/integration_layer/par/"
DIR_INTGR_JOB = "/bid/integration_layer/job/"
def Sqoop(filename,source_database,source_table, split_field, sourcesystem, ta... | [
"#!/usr/bin/python\nimport csv\nimport sys\nimport os.path\n\n#Versao 2 do gerador das RawZones\n\n#global\nDIR_PYGEN = \"/bid/_temporario_/pythonGeneration/\"\nDIR_INTGR_PAR = \"/bid/integration_layer/par/\"\nDIR_INTGR_JOB = \"/bid/integration_layer/job/\"\n\ndef Sqoop(filename,source_database,source_table, split_... | true |
1,850 | 29298ee7ddb4e524a23000abf86854d72f49954c | from app import db
from datetime import datetime
from sqlalchemy.orm import validates
class Posts(db.Model):
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
title = db.Column(db.String(200))
content = db.Column(db.Text)
category = db.Column(db.String(100))
created_date = db.Column(db.Date... | [
"from app import db\nfrom datetime import datetime\nfrom sqlalchemy.orm import validates\n\nclass Posts(db.Model):\n id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)\n title = db.Column(db.String(200))\n content = db.Column(db.Text)\n category = db.Column(db.String(100))\n created_date = db.... | false |
1,851 | 20ac73789fa7297a9230a6a2b814349d2b7da5fb | import hashlib
a = hashlib.pbkdf2_hmac("sha256", b"hallo", b"salt", 1)
b = hashlib.pbkdf2_hmac("sha256", a, b"salt", 1)
c = hashlib.pbkdf2_hmac("sha256", b"hallo", b"salt", 2)
print(b)
print(c) | [
"import hashlib\r\na = hashlib.pbkdf2_hmac(\"sha256\", b\"hallo\", b\"salt\", 1)\r\nb = hashlib.pbkdf2_hmac(\"sha256\", a, b\"salt\", 1)\r\nc = hashlib.pbkdf2_hmac(\"sha256\", b\"hallo\", b\"salt\", 2)\r\nprint(b)\r\nprint(c)",
"import hashlib\na = hashlib.pbkdf2_hmac('sha256', b'hallo', b'salt', 1)\nb = hashlib.... | false |
1,852 | 7040db119f8fd6da78499fc732e291280228ca10 | # Generated by Django 3.2.3 on 2021-05-16 07:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('problem', '0002_problem_... | [
"# Generated by Django 3.2.3 on 2021-05-16 07:56\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 dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('problem'... | false |
1,853 | e267108177841110493061a4f84ae3d29850d028 | from django.urls import path
from . import views
urlpatterns = [
# @app.route("/")
path('', views.home),
path("teams", views.showTeams),
path("teams/new", views.new),
path("teams/<teamname>", views.showSpecificTeam),
# path("allfood", views.showAllFoodItems),
# path("team/<teamname>",... | [
"from django.urls import path \nfrom . import views\n\n\nurlpatterns = [\n # @app.route(\"/\")\n path('', views.home),\n path(\"teams\", views.showTeams),\n path(\"teams/new\", views.new),\n path(\"teams/<teamname>\", views.showSpecificTeam),\n # path(\"allfood\", views.showAllFoodItems),\n ... | false |
1,854 | 080110e404cf5edfe53622a5942b53f9188ddd76 | import pickle
if __name__ == '__main__':
with open('id_generator.bin', 'rb') as f:
print(pickle.load(f)) | [
"import pickle\n\nif __name__ == '__main__':\n\twith open('id_generator.bin', 'rb') as f:\n\t\tprint(pickle.load(f))",
"import pickle\nif __name__ == '__main__':\n with open('id_generator.bin', 'rb') as f:\n print(pickle.load(f))\n",
"<import token>\nif __name__ == '__main__':\n with open('id_gener... | false |
1,855 | e9a6baf10efc5b6bd07af1fe352b0b17ecc172bd | import numpy as np
import json
import random
from encapsulate_state import StateEncapsulator
from scalar_to_action import ActionMapper
import pickle
from basis_functions import identity_basis, interactive_basis, actions_only_basis, actions_cubic_basis, BASIS_MAP
import matplotlib.pyplot as plt
STATE_FILENAME = "stat... | [
"import numpy as np \nimport json \nimport random\nfrom encapsulate_state import StateEncapsulator\nfrom scalar_to_action import ActionMapper\nimport pickle\nfrom basis_functions import identity_basis, interactive_basis, actions_only_basis, actions_cubic_basis, BASIS_MAP\nimport matplotlib.pyplot as plt\n\nSTATE_FI... | false |
1,856 | 365e2059d5ed3d7f8d9dbb4e44f563b79d68b087 | from keras.preprocessing.text import text_to_word_sequence
import os
# keras NLP tools filter out certain tokens by default
# this function replaces the default with a smaller set of things to filter out
def filter_not_punctuation():
return '"#$%&()*+-/:;<=>@[\\]^_`{|}~\t\n'
def get_first_n_words(text, n):
... | [
"from keras.preprocessing.text import text_to_word_sequence\nimport os\n\n\n# keras NLP tools filter out certain tokens by default\n# this function replaces the default with a smaller set of things to filter out\ndef filter_not_punctuation():\n return '\"#$%&()*+-/:;<=>@[\\\\]^_`{|}~\\t\\n'\n\n\ndef get_first_n_... | false |
1,857 | d17f1176ac60a3f6836c706883ab1847b61f50bf | import ConfigParser
''' Merge as many as ConfigParser as you want'''
def Config_Append(SRC_Config ,DST_Config):
import tempfile
temp_src = tempfile.NamedTemporaryFile(delete=True)
temp_dst = tempfile.NamedTemporaryFile(delete=True)
with open(temp_src.name,'wb') as src, open(temp_dst.name,'wb') as dst:
... | [
"import ConfigParser\n''' Merge as many as ConfigParser as you want'''\n\ndef Config_Append(SRC_Config ,DST_Config):\n import tempfile\n temp_src = tempfile.NamedTemporaryFile(delete=True)\n temp_dst = tempfile.NamedTemporaryFile(delete=True)\n with open(temp_src.name,'wb') as src, open(temp_dst.name,'w... | true |
1,858 | afacc2c54584c070963c4cb3cabbae64bb0e3159 | # Generated by Django 2.2.16 on 2020-11-04 12:48
import ckeditor_uploader.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course', '0002_auto_20201103_1648'),
]
operations = [
migrations.AddField(
model_name='course',... | [
"# Generated by Django 2.2.16 on 2020-11-04 12:48\n\nimport ckeditor_uploader.fields\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('course', '0002_auto_20201103_1648'),\n ]\n\n operations = [\n migrations.AddField(\n m... | false |
1,859 | 3135483c68880eeeaf7ebc085a6cd3c0c7f0550c | import pymysql
def main():
conn = pymysql.connect(host='127.0.0.1', port=3306,user='root',password='383240gyz',db='bycicle',charset='utf8')
print(conn)
try:
with conn.cursor() as cursor: # 上下文语法否则需要 # cursor.close()
cursor.execute('''drop table if exists pymysql''')
curs... | [
"import pymysql\n\n\ndef main():\n conn = pymysql.connect(host='127.0.0.1', port=3306,user='root',password='383240gyz',db='bycicle',charset='utf8')\n print(conn)\n try:\n with conn.cursor() as cursor: # 上下文语法否则需要 # cursor.close()\n cursor.execute('''drop table if exists pymysql''')\n ... | false |
1,860 | 9666c87b4d4dc721683ea33fdbbeadefc65a0cd1 | #!/usr/bin/env python
number=int(input("Enter an integer"))
if number<=100:
print("Your number is smaller than equal to 100")
else:
print("Your number is greater than 100")
| [
"#!/usr/bin/env python\n\nnumber=int(input(\"Enter an integer\"))\nif number<=100:\n print(\"Your number is smaller than equal to 100\")\nelse:\n print(\"Your number is greater than 100\")\n",
"number = int(input('Enter an integer'))\nif number <= 100:\n print('Your number is smaller than equal to 100')\... | false |
1,861 | 6e5b8be6182f39f185f4547f0abd84a4e404bf34 | import numpy as np
mydict = {}
mylist0 = np.array([1, 2, 3, 4, 5])
mylist1 = np.array([2, 3, 4, 5, 6])
print(mydict)
print(mylist0)
print(mylist1)
for c in ('0', '1'):
if c in mydict:
mydict[c] += mylist0
else:
mydict[c] = mylist0
print(mydict)
for c in ('0', '1'):
... | [
"import numpy as np\r\n\r\nmydict = {}\r\nmylist0 = np.array([1, 2, 3, 4, 5])\r\nmylist1 = np.array([2, 3, 4, 5, 6])\r\n\r\nprint(mydict)\r\nprint(mylist0)\r\nprint(mylist1)\r\n\r\n\r\n\r\nfor c in ('0', '1'):\r\n if c in mydict:\r\n mydict[c] += mylist0\r\n else:\r\n mydict[c] = mylist0\r\n\r\n... | false |
1,862 | 0527dc2b6fa0fe703b604c6e28fba44fe6def83b | def main():
# defaults to 0
print a
a = 7
a *= 6
print a
| [
"def main():\n # defaults to 0\n print a\n\n a = 7\n a *= 6\n print a\n"
] | true |
1,863 | 6424fccb7990b0a1722d5d787e7eb5acb4ff1a74 | import boto3
ec2 = boto3.resource('ec2')
response = client.allocate_address(
Domain='standard'
)
print(response)
| [
"import boto3\r\nec2 = boto3.resource('ec2')\r\n\r\nresponse = client.allocate_address(\r\n Domain='standard' \r\n)\r\nprint(response)\r\n\r\n\r\n\r\n\r\n",
"import boto3\nec2 = boto3.resource('ec2')\nresponse = client.allocate_address(Domain='standard')\nprint(response)\n",
"<import token>\nec2 = boto3.r... | false |
1,864 | 2561db1264fe399db85460e9f32213b70ddf03ff | #!/usr/bin/env python
# encoding: utf-8
"""
@author: swensun
@github:https://github.com/yunshuipiao
@software: python
@file: encode_decode.py
@desc: 字符串编解码
@hint:
"""
def encode(strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ''
... | [
"#!/usr/bin/env python\n\n# encoding: utf-8\n\n\"\"\"\n@author: swensun\n\n@github:https://github.com/yunshuipiao\n\n@software: python\n\n@file: encode_decode.py\n\n@desc: 字符串编解码\n\n@hint:\n\"\"\"\n\n\ndef encode(strs):\n \"\"\"Encodes a list of strings to a single string.\n :type strs: List[str]\n ... | false |
1,865 | fc5a4c27a21c2bd3900a6ad0bff68c249fe29d7a | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
import time
driver = webdriver.Chrome(executable_path='/home/bc/桌面/chromedriver')
driver.get('https://www.zhaopin.com/')
time.sleep(5)
driver.find_element_by_id('KeyWord_kw2').send_keys('技术')
driver.find_element_by_class_na... | [
"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport requests\nimport time\ndriver = webdriver.Chrome(executable_path='/home/bc/桌面/chromedriver')\n\ndriver.get('https://www.zhaopin.com/')\ntime.sleep(5)\ndriver.find_element_by_id('KeyWord_kw2').send_keys('技术')\ndriver.find_eleme... | false |
1,866 | 03a024140d8d0136bf9838f8942539f6d19bb351 | from cmd import Cmd
class CMD(Cmd):
def __init__(self):
pass
def do_move(self, direction):
if direction == "up":
self.game.movePlayer(0, 1)
elif direction == "down":
self.game.movePlayer(0, -1)
elif direction == "left":
self.game.movePlayer(-... | [
"from cmd import Cmd\n\nclass CMD(Cmd):\n def __init__(self):\n pass\n\n def do_move(self, direction):\n if direction == \"up\":\n self.game.movePlayer(0, 1)\n elif direction == \"down\":\n self.game.movePlayer(0, -1)\n elif direction == \"left\":\n ... | false |
1,867 | 8fe71e87512dfd2ccfcd21c9c175cb50274d9661 | """
Tests based on: https://github.com/pydata/xarray/blob/071da2a900702d65c47d265192bc7e424bb57932/xarray/tests/test_backends_file_manager.py
"""
import concurrent.futures
import gc
import pickle
from unittest import mock
import pytest
from rioxarray._io import URIManager
def test_uri_manager_mock_write():
mock... | [
"\"\"\"\nTests based on: https://github.com/pydata/xarray/blob/071da2a900702d65c47d265192bc7e424bb57932/xarray/tests/test_backends_file_manager.py\n\"\"\"\nimport concurrent.futures\nimport gc\nimport pickle\nfrom unittest import mock\n\nimport pytest\n\nfrom rioxarray._io import URIManager\n\n\ndef test_uri_manage... | false |
1,868 | 9627e8a468d3a75787c5a9e01856913fc8beb3c4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 14 22:09:56 2014
@author: duhan
"""
#arrayMapPath = r'/usr/local/lib/python2.7/dist-packages/ticketpitcher/data/3'
arrayMapPath = r'C:\Python27\Lib\site-packages\ticketpitcher\data'
#tempPath = r'/tmp/'
tempPath = 'd:\\temp\\'
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 14 22:09:56 2014\n\n@author: duhan\n\"\"\"\n#arrayMapPath = r'/usr/local/lib/python2.7/dist-packages/ticketpitcher/data/3'\narrayMapPath = r'C:\\Python27\\Lib\\site-packages\\ticketpitcher\\data'\n#tempPath = r'/tmp/'\ntempPath = 'd:\\\\temp\\\\'\n\n",
"<docstr... | false |
1,869 | 97857c1c5468a96187d44abc23ffaaf2a7ead1a6 | # data={
# "name":"Alby",
# "age":23
# }
# print (data['age'])
# def foo():
# print("Hellow world")
# return 1
# print (foo())
a="aa"
def add():
print(a)
add() | [
"# data={\n# \"name\":\"Alby\",\n# \"age\":23\n# }\n\n\n# print (data['age'])\n\n# def foo():\n# print(\"Hellow world\")\n# return 1\n\n# print (foo())\na=\"aa\"\n\ndef add():\n \n print(a)\n\n\nadd()",
"a = 'aa'\n\n\ndef add():\n print(a)\n\n\nadd()\n",
"<assignment token>\n\n\ndef add... | false |
1,870 | ed4c97913a9dba5cf6be56050a8d2ce24dbd6033 | '''
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given two integers A and B,
print the number of primes between them, inclusively.
'''
a = int(input())
b = int(input())
count = 0
for i in range(a, b+1):
true_prime = True
for num in range(2, i):
... | [
"'''\nA prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given two integers A and B, \nprint the number of primes between them, inclusively.\n'''\n\na = int(input())\nb = int(input())\ncount = 0\nfor i in range(a, b+1):\n true_prime = True\n \n for num ... | false |
1,871 | c435b0f162512bb2bc0c35e1817f64c5ef9ff7bc | # vim:fileencoding=utf-8:noet
from __future__ import absolute_import, unicode_literals, print_function
import os
BINDINGS_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bindings')
TMUX_CONFIG_DIRECTORY = os.path.join(BINDINGS_DIRECTORY, 'tmux')
DEFAULT_SYSTEM_CONFIG_DIR = None
| [
"# vim:fileencoding=utf-8:noet\n\nfrom __future__ import absolute_import, unicode_literals, print_function\nimport os\n\nBINDINGS_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bindings')\nTMUX_CONFIG_DIRECTORY = os.path.join(BINDINGS_DIRECTORY, 'tmux')\nDEFAULT_SYSTEM_CONFIG_DIR = None\n",
... | false |
1,872 | cf5a9b8dad5a02610fa5ce2a849b6f9fc50a0aa8 | #2) write a program to make banking system develop business logic
#in one module and call functionality in another .py file
class Customer: #user defined class
def __init__(self,name,phoneno,address,pin,accno,balance) : #constructor with multiple arguments
self._name=name
self._pno=phoneno
... | [
"#2) write a program to make banking system develop business logic\r\n#in one module and call functionality in another .py file\r\n\r\nclass Customer: #user defined class\r\n def __init__(self,name,phoneno,address,pin,accno,balance) : #constructor with multiple arguments\r\n self._name=name \r\n se... | false |
1,873 | 0f0b3eea9dc397d32e81749304041abaf6651e94 | from common.get_keyword import GetKeyword
from common.operation_Excel import OperationExcel
from common.op_database import OpDatabase
from interface.login import Login
from interface.address import Address
import unittest
import ddt
# 测试数据
op_excel = OperationExcel()
add_file = r'D:\pyCharm\Demo\pycode\Requests\201911... | [
"from common.get_keyword import GetKeyword\nfrom common.operation_Excel import OperationExcel\nfrom common.op_database import OpDatabase\nfrom interface.login import Login\nfrom interface.address import Address\nimport unittest\nimport ddt\n\n# 测试数据\nop_excel = OperationExcel()\nadd_file = r'D:\\pyCharm\\Demo\\pyco... | false |
1,874 | f3bfa30f51c4a91844457c72fbf2b2b8368d8476 | import datetime
interval_length_minutes = 10 # 10 minutes per interval
tek_rolling_period = 144 # 24*60//10 - 24 hours per day, 60 minutes per hour, 10 minutes per interval
def get_timestamp_from_interval(interval_number):
return interval_number * interval_length_minutes * 60 # 60 seconds per minute
def get... | [
"import datetime\n\ninterval_length_minutes = 10 # 10 minutes per interval\ntek_rolling_period = 144 # 24*60//10 - 24 hours per day, 60 minutes per hour, 10 minutes per interval\n\n\ndef get_timestamp_from_interval(interval_number):\n return interval_number * interval_length_minutes * 60 # 60 seconds per minu... | false |
1,875 | 6eecf0ff1ad762089db6e9498e906e68b507370c | import spacy
nlp = spacy.load("en_core_web_sm")
text = (
"Chick-fil-A is an American fast food restaurant chain headquartered in "
"the city of College Park, Georgia, specializing in chicken sandwiches."
)
# Disable the tagger and parser
with ____.____(____):
# Process the text
doc = ____
# Print ... | [
"import spacy\n\nnlp = spacy.load(\"en_core_web_sm\")\ntext = (\n \"Chick-fil-A is an American fast food restaurant chain headquartered in \"\n \"the city of College Park, Georgia, specializing in chicken sandwiches.\"\n)\n\n# Disable the tagger and parser\nwith ____.____(____):\n # Process the text\n d... | false |
1,876 | b3f62c331ff4ae9f909fc90cc7303997b32daceb | '''
O(n) time complexity
O(n) space complexity
'''
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
seenum = dict()
for idx, val in enumerate(nums):
if target - val in seenum:
... | [
"'''\nO(n) time complexity\nO(n) space complexity\n'''\n\nclass Solution:\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n seenum = dict()\n for idx, val in enumerate(nums):\n if targe... | false |
1,877 | 471cab65aac29f5b47de0ffef8f032dbbadf8dd0 | from flask import Flask, render_template, send_from_directory
from flask import request, send_file
from flask_cors import CORS
import os
import json
from crossdomain import crossdomain
import constants
import generation_tools
from music_theory import name_chords_in_tracks
import midi_tools
from client_logging import Cl... | [
"from flask import Flask, render_template, send_from_directory\nfrom flask import request, send_file\nfrom flask_cors import CORS\nimport os\nimport json\nfrom crossdomain import crossdomain\nimport constants\nimport generation_tools\nfrom music_theory import name_chords_in_tracks\nimport midi_tools\nfrom client_lo... | false |
1,878 | da69fd937153fe2112b9f64411882527274247ef | from sys import exit
from os import stat
file = open("fiunamfs.img","r")
nombre = file.read(8)
file.seek(10)
version = file.read(3)
file.seek(20)
etiqueta = file.read(15)
file.seek(40)
cluster = file.read(5)
file.seek(47)
numero = file.read(2)
file.seek(52)
numeroCompleto = file.read(8)
file.close()
archivos = []
tam... | [
"from sys import exit\nfrom os import stat\n\nfile = open(\"fiunamfs.img\",\"r\")\nnombre = file.read(8)\nfile.seek(10)\nversion = file.read(3)\nfile.seek(20)\netiqueta = file.read(15)\nfile.seek(40)\ncluster = file.read(5)\nfile.seek(47)\nnumero = file.read(2)\nfile.seek(52)\nnumeroCompleto = file.read(8)\nfile.cl... | false |
1,879 | b28ae19f31ae746f901dea645dfeaa211a15cd31 | from mcpi.minecraft import Minecraft
from time import sleep
import random
mc = Minecraft.create()
myID=mc.getPlayerEntityId("Baymax1112")
mineral = [14,15,16,56,73,129,57]
while True:
sleep(0.5)
r=random.choice(mineral)
x,y,z = mc.entity.getTilePos(myID)
mc.setBlocks(x+1,y+3,z+1,x-1,y-3,z-1,r) | [
"from mcpi.minecraft import Minecraft\nfrom time import sleep\nimport random \nmc = Minecraft.create()\nmyID=mc.getPlayerEntityId(\"Baymax1112\")\nmineral = [14,15,16,56,73,129,57]\nwhile True:\n sleep(0.5)\n r=random.choice(mineral)\n x,y,z = mc.entity.getTilePos(myID)\n mc.setBlocks(x+1,y+3,z+1,x-1,y-... | false |
1,880 | 5c0ee6e8a0d80dbb77a7a376c411b85bf1405272 | from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from math import sqrt
from sys import exit
from subprocess import Popen, DEVNULL
from resmon import LineSegment, reorder_step
def write_head(file):
with open("head.tex", "r") as head:
for line in head:
f.write(line)
def writ... | [
"from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom math import sqrt\nfrom sys import exit\n\nfrom subprocess import Popen, DEVNULL\n\nfrom resmon import LineSegment, reorder_step\n\n\ndef write_head(file):\n with open(\"head.tex\", \"r\") as head:\n for line in head:\n f.... | false |
1,881 | 016c004fd95d901a6d55b6f7460397223a6baa3b | # -*- coding: UTF-8 -*-
from flask import Blueprint, jsonify, request, abort, current_app
import json
from config import config_orm_initial
orm = config_orm_initial.initialize_orm()
session = orm['dict_session']
Article_list = orm['dict_Articlelist']
user = orm['dict_user']
app = Blueprint('api_get_comments', __name_... | [
"# -*- coding: UTF-8 -*-\nfrom flask import Blueprint, jsonify, request, abort, current_app\nimport json\nfrom config import config_orm_initial\n\norm = config_orm_initial.initialize_orm()\nsession = orm['dict_session']\nArticle_list = orm['dict_Articlelist']\nuser = orm['dict_user']\n\napp = Blueprint('api_get_com... | false |
1,882 | 4e6401672d4762b444bb679e4cc39ada04193a26 |
import tkinter as tk
from tkinter import Tk, BOTH,RIGHT,LEFT,END
from tkinter.ttk import Frame, Label, Style,Entry
from tkinter.ttk import Frame, Button, Style
import random
import time
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Frame.configu... | [
"\nimport tkinter as tk\nfrom tkinter import Tk, BOTH,RIGHT,LEFT,END\nfrom tkinter.ttk import Frame, Label, Style,Entry\nfrom tkinter.ttk import Frame, Button, Style\nimport random\nimport time\n\nclass StartPage(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, master)\n \n ... | false |
1,883 | a2e4e4a0c49c319df2adb073b11107d3f520aa6e | import itertools
def odds(upper_limit):
return [i for i in range(1,upper_limit,2)]
def evens(upper_limit):
return [i for i in range(0,upper_limit,2)]
nested = [i**j for i in range(1,10) for j in range(1,4)]
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = [chr(i) for i in range(97,123) if chr(i) not in vowe... | [
"import itertools\n\ndef odds(upper_limit):\n return [i for i in range(1,upper_limit,2)]\n\ndef evens(upper_limit):\n return [i for i in range(0,upper_limit,2)]\n\nnested = [i**j for i in range(1,10) for j in range(1,4)]\n\nvowels = ['a', 'e', 'i', 'o', 'u']\n\nconsonants = [chr(i) for i in range(97,123) if c... | false |
1,884 | 7611a57705939ce456e34d5ae379d6ca748b13c3 | #!/usr/bin/env python
# encoding: utf8
#from __future__ import unicode_literals
class RefObject(object):
def __init__(self,):
self.pose = []
self.name = []
self.time = None
self.id = None
def set_data(self,pose, name, time, Id):
self.pose = pose
self.... | [
"#!/usr/bin/env python\r\n# encoding: utf8\r\n#from __future__ import unicode_literals\r\n\r\nclass RefObject(object):\r\n def __init__(self,):\r\n self.pose = []\r\n self.name = []\r\n self.time = None\r\n self.id = None\r\n def set_data(self,pose, name, time, Id):\r\n self... | false |
1,885 | 7bcdd6c5c6e41b076e476e1db35b663e34d74a67 | from urllib import request
from urllib import error
from urllib.request import urlretrieve
import os, re
from bs4 import BeautifulSoup
import configparser
from apng2gif import apng2gif
config = configparser.ConfigParser()
config.read('crawler.config')
# 下載儲存位置
directoryLocation = os.getcwd() + '\\img'
# 設置要爬的頁面
urlLis... | [
"from urllib import request\nfrom urllib import error\nfrom urllib.request import urlretrieve\nimport os, re\nfrom bs4 import BeautifulSoup\nimport configparser\nfrom apng2gif import apng2gif\n\nconfig = configparser.ConfigParser()\nconfig.read('crawler.config')\n# 下載儲存位置\ndirectoryLocation = os.getcwd() + '\\\\img... | false |
1,886 | d423b0bc6cd9ea9795317750141ad5f5eab01636 | import sys
import os
sys.path.append("C:/Users/Laptop/Documents/Repos/udacity_stats_functions/descriptive")
import normal_distribution_06
#import sampling_distributions_07
def lower_upper_confidence_intervals(avg, SD):
#avg is x bar. The mean value at the "would be" point. ie Bieber Tweeter
#SD is standard err... | [
"import sys\nimport os\nsys.path.append(\"C:/Users/Laptop/Documents/Repos/udacity_stats_functions/descriptive\")\nimport normal_distribution_06\n#import sampling_distributions_07\n\ndef lower_upper_confidence_intervals(avg, SD):\n #avg is x bar. The mean value at the \"would be\" point. ie Bieber Tweeter\n #S... | false |
1,887 | f69351474fb3eb48eeb65eaf1aa46d2f4a390471 | # -*- coding: utf-8 -*-
from nose.tools import * # noqa
import mock
import httpretty
from tests.base import OsfTestCase
from tests.factories import AuthUserFactory, ProjectFactory
import urlparse
from framework.auth import Auth
from website.addons.mendeley.tests.factories import (
MendeleyAccountFactory,
... | [
"# -*- coding: utf-8 -*-\nfrom nose.tools import * # noqa\n\nimport mock\nimport httpretty\n\nfrom tests.base import OsfTestCase\nfrom tests.factories import AuthUserFactory, ProjectFactory\n\nimport urlparse\n\nfrom framework.auth import Auth\n\nfrom website.addons.mendeley.tests.factories import (\n MendeleyA... | false |
1,888 | 08ccc58fe139db3f4712aa551b80f6ea57e0ad76 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 23 10:16:40 2014
@author: Yusuke
"""
import math
result = []
for i in range(6 * 9**5):
sum_num = 0
for j_digit in str(i):
sum_num += int(j_digit) ** 5
if sum_num == i:
print i
result.append(i)
print math.fsum(result)
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 23 10:16:40 2014\n\n@author: Yusuke\n\"\"\"\nimport math\n\nresult = []\nfor i in range(6 * 9**5):\n sum_num = 0\n for j_digit in str(i):\n sum_num += int(j_digit) ** 5\n \n if sum_num == i:\n print i\n result.append(i)\n \... | true |
1,889 | 4989d01f31ca034aacdda28eff56adb2e0bb15da | """
Modulo collection - Counter
Collections -> High-performance Container Datatypes
Counter -> Recebe um interável como parametro e cria um objeto do tipo Collections Counter
que é parecido com um dicionario, contendo como chave o elemento da lista passada como
parametro e como valor a quantidade de ocorrencia... | [
"\"\"\"\r\nModulo collection - Counter\r\n\r\nCollections -> High-performance Container Datatypes\r\n\r\nCounter -> Recebe um interável como parametro e cria um objeto do tipo Collections Counter\r\nque é parecido com um dicionario, contendo como chave o elemento da lista passada como\r\nparametro e como valor a qu... | false |
1,890 | 57d6b9e7f48d32e5d10bfd6a340ea56281f5d82d | # O(logn) T O(1) S
def binarySearch(array, target):
if len(array) == 0:
return -1
else:
return binarySearchR(array, target, 0, len(array) - 1)
def binarySearchR(array, target, leftPointer, rightPointer):
if leftPointer > rightPointer:
return -1
else:
midPointer = (leftP... | [
"# O(logn) T O(1) S\ndef binarySearch(array, target):\n if len(array) == 0:\n return -1\n else:\n return binarySearchR(array, target, 0, len(array) - 1)\n\n\ndef binarySearchR(array, target, leftPointer, rightPointer):\n if leftPointer > rightPointer:\n return -1\n else:\n mi... | false |
1,891 | 9b7ffa2bb62a8decbec51c6bdea38b4338726816 | # -*- coding: utf-8 -*-
"""pytest People functions, fixtures and tests."""
import pytest
import ciscosparkapi
from tests.utils import create_string
# Helper Functions
# pytest Fixtures
@pytest.fixture(scope="session")
def me(api):
return api.people.me()
| [
"# -*- coding: utf-8 -*-\n\n\"\"\"pytest People functions, fixtures and tests.\"\"\"\n\n\nimport pytest\n\nimport ciscosparkapi\nfrom tests.utils import create_string\n\n\n# Helper Functions\n\n\n\n\n# pytest Fixtures\n\n@pytest.fixture(scope=\"session\")\ndef me(api):\n return api.people.me()\n",
"<docstring ... | false |
1,892 | d22ebe24605065452ae35c44367ee21a726ae7a1 | # Databricks notebook source
#import and create sparksession object
from pyspark.sql import SparkSession
spark=SparkSession.builder.appName('rc').getOrCreate()
# COMMAND ----------
#import the required functions and libraries
from pyspark.sql.functions import *
# COMMAND ----------
# Convert csv file to Spark Data... | [
"# Databricks notebook source\n#import and create sparksession object\nfrom pyspark.sql import SparkSession \nspark=SparkSession.builder.appName('rc').getOrCreate()\n\n# COMMAND ----------\n\n#import the required functions and libraries\nfrom pyspark.sql.functions import *\n\n# COMMAND ----------\n\n# Convert csv f... | false |
1,893 | d6cfe7132855d832d8fd1ea9ca9760bd22109a92 | # -*- utf-8 -*-
from django.db import models
class FieldsTest(models.Model):
pub_date = models.DateTimeField()
mod_date = models.DateTimeField()
class BigS(models.Model):
s = models.SlugField(max_length=255)
class Foo(models.Model):
a = models.CharField(max_length=10)
d = models.DecimalField(... | [
"# -*- utf-8 -*-\n\nfrom django.db import models\n\n\nclass FieldsTest(models.Model):\n pub_date = models.DateTimeField()\n mod_date = models.DateTimeField()\n\n\nclass BigS(models.Model):\n s = models.SlugField(max_length=255)\n\n\nclass Foo(models.Model):\n a = models.CharField(max_length=10)\n d =... | false |
1,894 | 3dcca85c8003b57ad37734bbbe171ab8cef0f56c | # This package includes different measures to evaluate topics
| [
"# This package includes different measures to evaluate topics\n",
""
] | false |
1,895 | b360ba7412bd10e2818511cee81302d407f88fd1 | # 3번 반복하고 싶은 경우
# 별 10개를 한줄로
for x in range(0, 10, 3): # 3번째 숫자는 증감할 양을 정해줌.
# print(x)
print("★", end=" ")
print()
print("------------------------")
#이중 for문
for y in range(0, 10):
for x in range(0, 10):
# print(x)
print("★", end=" ")
print() | [
"# 3번 반복하고 싶은 경우\r\n\r\n# 별 10개를 한줄로\r\nfor x in range(0, 10, 3): # 3번째 숫자는 증감할 양을 정해줌.\r\n # print(x)\r\n print(\"★\", end=\" \")\r\nprint()\r\nprint(\"------------------------\")\r\n#이중 for문\r\nfor y in range(0, 10):\r\n for x in range(0, 10):\r\n # print(x)\r\n print(\"★\", end=\" \")\r\n ... | false |
1,896 | a79c9799ed237a943ae3d249a4d66eb2f8693e83 | # Runtime: 44 ms, faster than 62.95% of Python3 online submissions for Rotate List.
# Memory Usage: 13.9 MB, less than 6.05% of Python3 online submissions for Rotate List.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class... | [
"# Runtime: 44 ms, faster than 62.95% of Python3 online submissions for Rotate List.\r\n# Memory Usage: 13.9 MB, less than 6.05% of Python3 online submissions for Rotate List.\r\n# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.nex... | false |
1,897 | 0f0ea6f07f9a082042ed9aff7a95d372c32b5a13 | from __future__ import absolute_import, division, print_function
import numbers
import torch
from torch.distributions import constraints
from pyro.distributions.distribution import Distribution
from pyro.distributions.score_parts import ScoreParts
from pyro.distributions.util import broadcast_shape, sum_rightmost
... | [
"from __future__ import absolute_import, division, print_function\n\nimport numbers\n\nimport torch\nfrom torch.distributions import constraints\n\nfrom pyro.distributions.distribution import Distribution\nfrom pyro.distributions.score_parts import ScoreParts\nfrom pyro.distributions.util import broadcast_shape, su... | false |
1,898 | 9bc955def6250908050a1f3046dd78480f25e0a1 | from pyplasm import *
doorY = [.2,.18,.08,.18,.08,.18,.4,.18,.08,.18,.08,.18,.2]
doorX = [.2,.5,.2,1.8,.08,.18,.08,.18,.2]
doorOccurrency = [[True]*13,
[True, False, True, False, True, False, True, False, True, False, True, False, True],
[True]*13,
[True, False, True, False, True, False, True, False, T... | [
"from pyplasm import *\n\ndoorY = [.2,.18,.08,.18,.08,.18,.4,.18,.08,.18,.08,.18,.2]\ndoorX = [.2,.5,.2,1.8,.08,.18,.08,.18,.2]\n\ndoorOccurrency = [[True]*13,\n\t\t\t\t\t[True, False, True, False, True, False, True, False, True, False, True, False, True],\n\t\t\t\t\t[True]*13,\n\t\t\t\t\t[True, False, True, False,... | false |
1,899 | 8126af930ec75e2818455d959f00285bdc08c044 | import unittest
from LempelZivWelchDecoder import LempelZivWelchDecoder
class TestLempelZivWelchDecoder(unittest.TestCase):
def test_decode(self):
test_value = ['t', 256, 257, 'e', 's', 260, 't', '1']
run_length_decoder = LempelZivWelchDecoder()
self.assertRaises(ValueError,
... | [
"import unittest\n\nfrom LempelZivWelchDecoder import LempelZivWelchDecoder\n\n\nclass TestLempelZivWelchDecoder(unittest.TestCase):\n def test_decode(self):\n test_value = ['t', 256, 257, 'e', 's', 260, 't', '1']\n run_length_decoder = LempelZivWelchDecoder()\n\n self.assertRaises(ValueErro... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.