index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
9,700 | 60b70171dededd758e00d6446842355a47b54cc0 | #!/usr/bin/env python3
import sys
import collections as cl
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
MOD = 998244353
def main():
N, K = MI()
kukan = []
for _ in range(K):
... | [
"#!/usr/bin/env python3\nimport sys\nimport collections as cl\n\n\ndef II(): return int(sys.stdin.readline())\n\n\ndef MI(): return map(int, sys.stdin.readline().split())\n\n\ndef LI(): return list(map(int, sys.stdin.readline().split()))\n\n\nMOD = 998244353\n\n\ndef main():\n N, K = MI()\n\n kukan = []\n ... | false |
9,701 | 51868f26599c5878f8eb976d928c30d0bf61547d | import collections
def range(state):
ran = state["tmp"]["analysis"]["range"]
rang = {
key : [ state["rank"][i] for i in val & ran ]
for key, val in state["tmp"]["analysis"]["keys"].items()
if val & ran
}
for item in state["tmp"]["items"]:
item.setdefault("rank", 0)
item_keys = set(item.keys())
rang_... | [
"import collections\n\ndef range(state):\n\tran = state[\"tmp\"][\"analysis\"][\"range\"]\n\n\trang = {\n\t\tkey : [ state[\"rank\"][i] for i in val & ran ]\n\t\tfor key, val in state[\"tmp\"][\"analysis\"][\"keys\"].items()\n\t\tif val & ran\n\t}\n\n\tfor item in state[\"tmp\"][\"items\"]:\n\t\titem.setdefault(\"r... | false |
9,702 | 986df5a41bc87ecb390dfbd1db9e1f5cd6c5b8fb |
import argparse
import cv2
import numpy as np
refPt = []
cropping = False
def click_and_crop(event, x, y, flags, param):
global refPt, cropping
if event == cv2.EVENT_LBUTTONDOWN:
refPt = [(x, y)]
cropping = True
elif event == cv2.EVENT_LBUTTONUP:
refPt.append((x, y))
cropping = False
cv2.rect... | [
"\nimport argparse\nimport cv2\nimport numpy as np\n \n\nrefPt = []\ncropping = False\n \ndef click_and_crop(event, x, y, flags, param):\n\tglobal refPt, cropping\n \n\tif event == cv2.EVENT_LBUTTONDOWN:\n\t\trefPt = [(x, y)]\n\t\tcropping = True\n \n\telif event == cv2.EVENT_LBUTTONUP:\n\t\trefPt.append((x, y))\n\... | true |
9,703 | dd0e96a1f93cbffedc11262a883dda285f5c224c | from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from extensions import bcrypt
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(255))
password = db.Column(db.String(255))
posts = db.relationship(
'Post',
... | [
"from flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import func\nfrom extensions import bcrypt\n\ndb = SQLAlchemy()\n\n\nclass User(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n username = db.Column(db.String(255))\n password = db.Column(db.String(255))\n posts = db.relationship(\n... | false |
9,704 | 78c4e14e5afdf857082b60bf4020f0f785d93a0d | from p5 import *
import numpy as np
from numpy.random import default_rng
from boids import Boid
from data import Data
n=30;
width = 1920
height = 1080
flock=[]
infected=[]
rng = default_rng()
frames=0
for i in range(n):
x = rng.integers(low=0, high=1920)
y = rng.integers(low=0, high=1080)
if i==0:
... | [
"from p5 import *\nimport numpy as np\nfrom numpy.random import default_rng\nfrom boids import Boid\nfrom data import Data\nn=30;\nwidth = 1920\nheight = 1080\nflock=[]\ninfected=[]\nrng = default_rng()\nframes=0\n\nfor i in range(n):\n x = rng.integers(low=0, high=1920)\n y = rng.integers(low=0, high=1080)\n... | false |
9,705 | 7764effac0b95ad8f62b91dd470c1d0e40704a7d | ''' tk_image_view_url_io.py
display an image from a URL using Tkinter, PIL and data_stream
tested with Python27 and Python33 by vegaseat 01mar2013
'''
import io
# allows for image formats other than gif
from PIL import Image, ImageTk
try:
# Python2
import Tkinter as tk
from urllib2 import urlopen
except... | [
"''' tk_image_view_url_io.py\ndisplay an image from a URL using Tkinter, PIL and data_stream\ntested with Python27 and Python33 by vegaseat 01mar2013\n'''\n\nimport io\n# allows for image formats other than gif\nfrom PIL import Image, ImageTk\ntry:\n # Python2\n import Tkinter as tk\n from urllib2 impor... | false |
9,706 | 91806afea92587476ac743346b88098b197a033c | import pygame
import time
from menus import MainMenu
from scenes import TestWorldGen
from scenes import TestAnimation
from scenes import TestLevel2
from scenes import MainGame
import random
class GameManager:
def __init__(self):
self.screen = pygame.display.set_mode((1280, 720),
... | [
"import pygame\nimport time\nfrom menus import MainMenu\nfrom scenes import TestWorldGen\nfrom scenes import TestAnimation\nfrom scenes import TestLevel2\nfrom scenes import MainGame\nimport random\n\n\nclass GameManager:\n def __init__(self):\n self.screen = pygame.display.set_mode((1280, 720),\n ... | false |
9,707 | 4f06d87ec79c20206ff45ba72ab77844076be553 |
import pandas as pd
from greyatomlib.pandas_project.q01_read_csv_data_to_df.build import read_csv_data_to_df
def get_runs_counts_by_match():
ipl_df = read_csv_data_to_df("data/ipl_dataset.csv")
df1 = pd.DataFrame(ipl_df[['match_code','runs','venue']])
df2 = df1.groupby(['match_code','runs'], as_index=Fals... | [
"\nimport pandas as pd\nfrom greyatomlib.pandas_project.q01_read_csv_data_to_df.build import read_csv_data_to_df\n\ndef get_runs_counts_by_match():\n ipl_df = read_csv_data_to_df(\"data/ipl_dataset.csv\")\n df1 = pd.DataFrame(ipl_df[['match_code','runs','venue']])\n df2 = df1.groupby(['match_code','runs'],... | false |
9,708 | 4b78c99dd6156afe960effcacb25804446310f7c | # MIT LICENSE
#
# Copyright 1997 - 2019 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,... | [
"# MIT LICENSE\n#\n# Copyright 1997 - 2019 by IXIA Keysight\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use,... | false |
9,709 | 0a42c54ef1412b7f3b8e95da1d65ee05dfa14089 | from dataframe import *
from chaid import SuperCHAID, SuperCHAIDVisualizer
supernode_features = [manufacturing_region]
features_list = [customer_region, product_family, make_vs_buy]
dependant_variable = gm
super_tree = SuperCHAID(supernode_features, features_list, dependant_variable)
super_tree.fit(df)
visualizer = ... | [
"from dataframe import *\nfrom chaid import SuperCHAID, SuperCHAIDVisualizer\n\nsupernode_features = [manufacturing_region]\nfeatures_list = [customer_region, product_family, make_vs_buy]\ndependant_variable = gm\n\nsuper_tree = SuperCHAID(supernode_features, features_list, dependant_variable)\nsuper_tree.fit(df)\n... | false |
9,710 | 239f055fd76a3ecb5f384c256ad850ea42739b8f |
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import math
from tkinter import *
from tkinter.ttk import *
from facedetectandtrack import *
x_vals = []
root = Tk()
counter=0
#def graph():
plt.style.use('seaborn')
def animate(i):
data = pd.read_csv('data.csv... | [
"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport math\nfrom tkinter import * \nfrom tkinter.ttk import *\nfrom facedetectandtrack import *\n \nx_vals = []\nroot = Tk()\n\n\ncounter=0\n#def graph():\nplt.style.use('seaborn')\n\ndef animate(i):\n data ... | false |
9,711 | 35647ed5e2c128a5bf819a1e47ead7e958172b1c | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 22:05:12 2019
@author: admin
"""
for index in range(test_set.shape[0]):
print(index) | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 24 22:05:12 2019\n\n@author: admin\n\"\"\"\n\nfor index in range(test_set.shape[0]):\n print(index)",
"<docstring token>\nfor index in range(test_set.shape[0]):\n print(index)\n",
"<docstring token>\n<code token>\n"
] | false |
9,712 | 6907a1e08d728732eebf81fec7c0dab8729448e2 | # Generated by Django 2.1.5 on 2019-01-20 18:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Destination',
fields=[
... | [
"# Generated by Django 2.1.5 on 2019-01-20 18:11\n\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 ]\n\n operations = [\n migrations.CreateModel(\n name='Destination',\n ... | false |
9,713 | e3417980599448f1293b56cb95312088e7a8abe3 | import os
import imageio
import h5py
import numpy as np
def create_segmentation_test_data(data_path, raw_key, label_key, shape, chunks):
with h5py.File(data_path, 'a') as f:
f.create_dataset(raw_key, data=np.random.rand(*shape), chunks=chunks)
f.create_dataset(label_key, data=np.random.randint(0, ... | [
"import os\nimport imageio\nimport h5py\nimport numpy as np\n\n\ndef create_segmentation_test_data(data_path, raw_key, label_key, shape, chunks):\n with h5py.File(data_path, 'a') as f:\n f.create_dataset(raw_key, data=np.random.rand(*shape), chunks=chunks)\n f.create_dataset(label_key, data=np.rand... | false |
9,714 | b7a7941b3555b30ac7e743a5457df76f9eb7cb15 | #write a program that displays the wor "Hello!"
print("Hello!")
| [
"#write a program that displays the wor \"Hello!\"\n\nprint(\"Hello!\")\n",
"print('Hello!')\n",
"<code token>\n"
] | false |
9,715 | c9be3d25824093528e2bee51c045d05e036daa67 | import sklearn.metrics as metrics
import sklearn.cross_validation as cv
from sklearn.externals import joblib
import MachineLearning.Reinforcement.InternalSQLManager as sqlManager
class ReinforcementLearner:
def __init__(self, clf=None, load=False, clfName=None):
"""
Initialise the Classifier, eith... | [
"import sklearn.metrics as metrics\nimport sklearn.cross_validation as cv\nfrom sklearn.externals import joblib\nimport MachineLearning.Reinforcement.InternalSQLManager as sqlManager\n\nclass ReinforcementLearner:\n\n def __init__(self, clf=None, load=False, clfName=None):\n \"\"\"\n Initialise the... | false |
9,716 | 13c55c313c740edce48fc979e8956fdd018e8aab | """This module contains a class supporting composition of AugraphyPipelines"""
class ComposePipelines:
"""The composition of multiple AugraphyPipelines.
Define AugraphyPipelines elsewhere, then use this to compose them.
ComposePipelines objects are callable on images (as numpy.ndarrays).
:param pipel... | [
"\"\"\"This module contains a class supporting composition of AugraphyPipelines\"\"\"\n\n\nclass ComposePipelines:\n \"\"\"The composition of multiple AugraphyPipelines.\n Define AugraphyPipelines elsewhere, then use this to compose them.\n ComposePipelines objects are callable on images (as numpy.ndarrays... | false |
9,717 | bcdd36b534fd3551de9cb40efc11581f4d95a002 | import sys
from Node import Node
from PriorityQueue import PriorityQueue
def Print(text):
if text is None or len(text) == 0:
print('invalid text.')
print('--------------------------------------------------------------')
return
text_set = set()
for i in text:
t... | [
"import sys\r\nfrom Node import Node\r\nfrom PriorityQueue import PriorityQueue\r\n\r\n\r\ndef Print(text):\r\n if text is None or len(text) == 0:\r\n print('invalid text.')\r\n print('--------------------------------------------------------------')\r\n return\r\n\r\n text_set = set()\r\n... | false |
9,718 | ae7fc034249b7dde6d6bca33e2e6c8f464284cfc | #!/usr/bin/env python3
import datetime
import time
import board
from busio import I2C
import adafruit_bme680
# Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)
# change this to match the location's pressure (hPa) at sea level
b... | [
"#!/usr/bin/env python3\nimport datetime\nimport time\nimport board\nfrom busio import I2C\nimport adafruit_bme680\n\n# Create library object using our Bus I2C port\ni2c = I2C(board.SCL, board.SDA)\nbme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)\n\n# change this to match the location's pressure (hPa... | false |
9,719 | 76664114382bdeb0bffb996e4dd4448b6c87520d | import sys
def ler (t):
i =0
for s in sys.stdin:
l=s.split(" ")
t.append(l)
def melhor (t):
i=1
x=int(t[0][0].strip("\n"))
n=len(t)
while(i<n):
u=int((t[i][2]).strip())
if(u<x)
i+=1
def vendedor():
t=[]
ler(t)
melhor(t)
vendedor() | [
"import sys \n\ndef ler (t):\n\ti =0\n\tfor s in sys.stdin:\n\t\tl=s.split(\" \")\n\t\tt.append(l)\n\ndef melhor (t):\n\ti=1\n\tx=int(t[0][0].strip(\"\\n\"))\n\tn=len(t)\n\twhile(i<n):\n\t\tu=int((t[i][2]).strip())\n\t\tif(u<x)\n\t\ti+=1\n\n\n\n\ndef vendedor():\n\tt=[]\n\tler(t)\n\tmelhor(t)\nvendedor()"
] | true |
9,720 | e0874554c326bb11b53552e362bc8073bb57bc93 | import widget
import column
class Columns(widget.Widget):
def __init__(self, parent):
super(Columns, self).__init__(parent)
# self.root.mouse.on_drag_release.append(self.on_drag_release)
"""
def on_drag_release(self, x0, y0, x, y):
if not self.contains_point(x0, y0):
re... | [
"import widget\nimport column\n\nclass Columns(widget.Widget):\n def __init__(self, parent):\n super(Columns, self).__init__(parent)\n # self.root.mouse.on_drag_release.append(self.on_drag_release)\n\n \"\"\"\n def on_drag_release(self, x0, y0, x, y):\n if not self.contains_point(x0, y... | false |
9,721 | 843901b65a556e57470f73be2657e9fd3c0facc6 | def parse(num):
strnum = str(num)
words = []
for item in range(len(strnum)-1, -1, -1):
words.append(strnum[item])
hundred = words[:3]
thousand = words[3:6]
million = words[6:len(words)]
hundred = hundred[::-1]
thousand = thousand[::-1]
million = million[::-1]
units = [... | [
"def parse(num):\n strnum = str(num)\n words = []\n for item in range(len(strnum)-1, -1, -1):\n words.append(strnum[item])\n\n hundred = words[:3]\n thousand = words[3:6]\n million = words[6:len(words)]\n\n hundred = hundred[::-1]\n thousand = thousand[::-1]\n million = million[::-... | false |
9,722 | b2a2e06c5db8b12acbc852bafc4ea869b006c1c8 | import itertools
import urllib
import word2vec
# MSD: http://corpus.leeds.ac.uk/mocky/ru-table.tab
# Universal: http://universaldependencies.org/ru/pos/index.html
def convert_pos_MSD_to_Universal(pos):
if pos.startswith('A'):
return 'ADJ'
elif pos.startswith('C'):
return 'CCONJ'
elif pos.... | [
"import itertools\n\nimport urllib\n\nimport word2vec\n\n# MSD: http://corpus.leeds.ac.uk/mocky/ru-table.tab\n# Universal: http://universaldependencies.org/ru/pos/index.html\ndef convert_pos_MSD_to_Universal(pos):\n if pos.startswith('A'):\n return 'ADJ'\n elif pos.startswith('C'):\n return 'CCO... | false |
9,723 | fb82724aab7e0819c9921d41dcb612b304b25753 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# 차트에 한글 가능하도록
from matplotlib import font_manager, rc, rcParams
font_name = font_manager.FontProperties(
fname="c:/windows/Fonts/malgun.ttf").get_name()
rc('font',family=font_name)... | [
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# 차트에 한글 가능하도록\nfrom matplotlib import font_manager, rc, rcParams\nfont_name = font_manager.FontProperties(\n fname=\"c:/windows/Fonts/malgun.ttf\").get_name()\nrc('font',f... | false |
9,724 | 4ea266d4f4c18efbba4204d7301652f8966c18a5 | # -*- coding: utf-8 -*-
"""
Animation practical output
The code that follows builds on the "Communications.py" file
Additional code that follows has in part been modified from that of
https://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part8/index.html
https://www.geog.leeds.ac.uk/courses... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nAnimation practical output\n\nThe code that follows builds on the \"Communications.py\" file\n\nAdditional code that follows has in part been modified from that of\nhttps://www.geog.leeds.ac.uk/courses/computing/practicals/python/agent-framework/part8/index.html\nhttps://www.geog.l... | false |
9,725 | c2b6e51622681ac916e860ed4ff5715808dff102 | import numpy as np
import matplotlib as plt
import math
from DoublePendulum import DP #imports useful modules and double pendulum class from DoublePendulum.py
import json
import pandas as pd
import copy
from pathlib import Path
#accessing config file
with open('config.json') as config_file:
initdata = ... | [
"import numpy as np \r\nimport matplotlib as plt\r\nimport math\r\nfrom DoublePendulum import DP #imports useful modules and double pendulum class from DoublePendulum.py\r\nimport json\r\nimport pandas as pd\r\nimport copy\r\nfrom pathlib import Path\r\n\r\n#accessing config file\r\nwith open('config.json') as conf... | false |
9,726 | e686d8617360c5a3ce35bd4d2bdeb2376b33f53a | #!/usr/bin/env python
import re
pdfs_file = './pdf_names_2017.txt'
sessions_file = './session_names_2017.txt'
with open(pdfs_file) as f:
pdf_names = f.read().splitlines()
with open(sessions_file) as f:
session_names = f.read().splitlines()
#for i in xrange(0,len(pdf_names)):
# print str(i+1).zfill(3) +... | [
"#!/usr/bin/env python\n\nimport re\n\n\npdfs_file = './pdf_names_2017.txt'\nsessions_file = './session_names_2017.txt'\n\nwith open(pdfs_file) as f:\n pdf_names = f.read().splitlines()\n\nwith open(sessions_file) as f:\n session_names = f.read().splitlines()\n\n#for i in xrange(0,len(pdf_names)):\n# print... | true |
9,727 | 5cb390b06026bc0899c0b10dc93f3ec1f2ffefa6 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Sponge_sy"
# Date: 2021/9/11
import numpy
from tqdm import tqdm
from bert4keras.tokenizers import Tokenizer
from bert4keras.models import build_transformer_model
from bert4keras.snippets import sequence_padding, DataGenerator
from utils import *
class d... | [
"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Sponge_sy\"\n# Date: 2021/9/11\n\n\nimport numpy\nfrom tqdm import tqdm\nfrom bert4keras.tokenizers import Tokenizer\nfrom bert4keras.models import build_transformer_model\nfrom bert4keras.snippets import sequence_padding, DataGenerator\nfrom utils ... | false |
9,728 | c9bc331f4805a956146619c59d183fc3bcbe47cb | from conans import ConanFile, CMake, tools
import os
class Demo(ConanFile):
name = "Demo"
version = "0.1"
license = "<Put the package license here>"
url = "<Package recipe repository url here, for issues about the package>"
description = "<Description of Testlib here>"
settings = "os", "compile... | [
"from conans import ConanFile, CMake, tools\nimport os\n\nclass Demo(ConanFile):\n name = \"Demo\"\n version = \"0.1\"\n license = \"<Put the package license here>\"\n url = \"<Package recipe repository url here, for issues about the package>\"\n description = \"<Description of Testlib here>\"\n s... | false |
9,729 | b4d48427dddc7c0240cf05c003cbf7b0163279ee | from django.contrib import admin
from .models import (AddressLink, Address, Child, Citation,
Configuration, Event, Exclusion, FactType,
Family, Group, Label, LinkAncestry,
Link, MediaLink, Multimedia, Name,
Person, Place, ResearchItem,... | [
"from django.contrib import admin\n\nfrom .models import (AddressLink, Address, Child, Citation,\n Configuration, Event, Exclusion, FactType,\n Family, Group, Label, LinkAncestry,\n Link, MediaLink, Multimedia, Name,\n Person, Place, Re... | false |
9,730 | 3a96ede91069df0c71905415e598dbbd9d3056fd | import os
import sys
import re
import traceback
import logging
import queue
import threading
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
import click
import inotify.adapters
from inotify.constants import (IN_ATTRIB, IN_DELETE, IN_MOVED_FROM,
IN_MOVED_TO,... | [
"import os\nimport sys\nimport re\nimport traceback\nimport logging\nimport queue\nimport threading\nfrom logging.handlers import TimedRotatingFileHandler\nfrom pathlib import Path\nimport click\nimport inotify.adapters\nfrom inotify.constants import (IN_ATTRIB, IN_DELETE, IN_MOVED_FROM,\n ... | false |
9,731 | 0726a4fa3af196e2ba1592019f09afb0e7bb47d7 | import os
import requests
def download(url: str, dest_folder: str):
#https://stackoverflow.com/a/56951135/8761164
if not os.path.exists(dest_folder):
os.makedirs(dest_folder) # create folder if it does not exist
filename = url.split('/')[-1].replace(" ", "_") # be careful with file names
fil... | [
"import os\nimport requests\n\ndef download(url: str, dest_folder: str):\n #https://stackoverflow.com/a/56951135/8761164\n if not os.path.exists(dest_folder):\n os.makedirs(dest_folder) # create folder if it does not exist\n\n filename = url.split('/')[-1].replace(\" \", \"_\") # be careful with f... | false |
9,732 | 9ad36f157abae849a1550cb96e650746d57f491d | from collections import Counter
from docx import Document
import docx2txt
plain_text = docx2txt.process("kashmiri.docx")
list_of_words = plain_text.split()
#print(Counter(list_of_words))
counter_list_of_words = Counter(list_of_words)
elements = counter_list_of_words.items()
# for a, b in sorted(elements, key=lambda x:... | [
"from collections import Counter\nfrom docx import Document\nimport docx2txt\n\nplain_text = docx2txt.process(\"kashmiri.docx\")\nlist_of_words = plain_text.split()\n#print(Counter(list_of_words))\ncounter_list_of_words = Counter(list_of_words)\nelements = counter_list_of_words.items()\n# for a, b in sorted(element... | false |
9,733 | 7016a7dda80c0cfae0e15cf239f6ae64eb9004b7 | # Jeremy Jao
# University of Pittsburgh: DBMI
# 6/18/2013
#
# This is the thing that returns the dictionary of the key. we can edit more code to return different values in the keys (gene) in each dictionary inside the dictionary.
# my sys.argv isn't working in my situation due to my IDE (nor do I not know how it w... | [
"# Jeremy Jao\r\n# University of Pittsburgh: DBMI\r\n# 6/18/2013\r\n#\r\n# This is the thing that returns the dictionary of the key. we can edit more code to return different values in the keys (gene) in each dictionary inside the dictionary.\r\n# my sys.argv isn't working in my situation due to my IDE (nor do I no... | true |
9,734 | b8b20d6c977a6c1df6a592188c6e799f12da6a23 | ##########################################################################################
## Scene Classification ##
## Authors : Chris Andrew, Santhoshini Reddy, Nikath Yasmeen, Sai Hima, Sriya Ragini ##
###############################################... | [
"##########################################################################################\n## Scene Classification ##\n## Authors : Chris Andrew, Santhoshini Reddy, Nikath Yasmeen, Sai Hima, Sriya Ragini ##\n#######################################... | false |
9,735 | c77ca4aa720b172d75aff2ceda096a4969057a00 | # coding=utf-8
# __author__ = 'liwenxuan'
import random
chars = "1234567890ABCDEF"
ids = ["{0}{1}{2}{3}".format(i, j, k, l) for i in chars for j in chars for k in chars for l in chars]
def random_peer_id(prefix="F"*8, server_id="0000"):
"""
用于生成随机的peer_id(后四位随机)
:param prefix: 生成的peer_id的前八位, 测试用prefix为... | [
"# coding=utf-8\n# __author__ = 'liwenxuan'\n\nimport random\n\nchars = \"1234567890ABCDEF\"\nids = [\"{0}{1}{2}{3}\".format(i, j, k, l) for i in chars for j in chars for k in chars for l in chars]\n\n\ndef random_peer_id(prefix=\"F\"*8, server_id=\"0000\"):\n \"\"\"\n 用于生成随机的peer_id(后四位随机)\n :param prefix... | true |
9,736 | 972c479ea40232e14fbf678ca2ccf9716e473fe8 | from rest_framework import serializers
from .models import data
from django.contrib.auth.models import User
class dataSerializer(serializers.ModelSerializer):
class Meta:
model = data
fields = ['id','task','duedate','person','done', 'task_user']
class userSerializer(serializers.ModelSerializer):
... | [
"from rest_framework import serializers\n\nfrom .models import data\nfrom django.contrib.auth.models import User\n\nclass dataSerializer(serializers.ModelSerializer):\n class Meta:\n model = data\n fields = ['id','task','duedate','person','done', 'task_user']\n\nclass userSerializer(serializers.Mod... | false |
9,737 | 0d07ad60c58828ce19153063fb5d7d80135cb9ec | from django.http import HttpResponse
from django.shortcuts import render
from dashboard.models import Farmer
import random, json, requests
from django.core import serializers
from collections import namedtuple
def sendSMS(message):
if message:
assert isinstance(message, (str, unicode))
payload = {... | [
"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom dashboard.models import Farmer\nimport random, json, requests\nfrom django.core import serializers\n\nfrom collections import namedtuple\n\ndef sendSMS(message):\n if message:\n assert isinstance(message, (str, unicode))\n ... | true |
9,738 | a5b74c31aed103b55404afc538af60c3eb18cb1b | """TcEx Framework Key Value Redis Module"""
class KeyValueRedis:
"""TcEx Key Value Redis Module.
Args:
context (str): The Redis context (hash) for hashed based operations.
redis_client (redis.Client): An instance of redis client.
"""
def __init__(self, context, redis_client):
... | [
"\"\"\"TcEx Framework Key Value Redis Module\"\"\"\n\n\nclass KeyValueRedis:\n \"\"\"TcEx Key Value Redis Module.\n\n Args:\n context (str): The Redis context (hash) for hashed based operations.\n redis_client (redis.Client): An instance of redis client.\n \"\"\"\n\n def __init__(self, con... | false |
9,739 | a67612e8301728d1fb366d7c8909fa830f04bf45 | #Max Low
#9-25-17
#quiz2.py -- numbers , bigger smaller same, divisible by 3, product and correct person
numone = int(input('Enter a number: '))
numtwo = int(input('Enter a 2nd number: '))
if numone > numtwo:
print('The first number is bigger')
elif numtwo > numone:
print('The second number is bigger')
else:
... | [
"#Max Low\n#9-25-17\n#quiz2.py -- numbers , bigger smaller same, divisible by 3, product and correct person\n\nnumone = int(input('Enter a number: '))\nnumtwo = int(input('Enter a 2nd number: '))\n\nif numone > numtwo:\n print('The first number is bigger')\nelif numtwo > numone:\n print('The second number is ... | false |
9,740 | cd8d95e2bf433020db2db06a21263f75e3f81331 | #!/bin/python
"""
len()
lower()
upper()
str()
"""
parrot = "Norwegian Blue"
print len(parrot)
| [
"#!/bin/python\n\n\"\"\"\nlen()\nlower()\nupper()\nstr()\n\"\"\"\n\nparrot = \"Norwegian Blue\"\nprint len(parrot)\n"
] | true |
9,741 | 2b8b5b893d61d11d2795f5be96fde759256a15e8 | """
This is the main script
"""
import datetime
import sqlite3
from sqlite3 import Error
import nltk.sentiment
from chatterbot import ChatBot
from pythonosc import udp_client
def _create_connection(db_file):
""" Create a database connection to the SQLite database """
try:
conn = sqlite3.connect(db_fi... | [
"\"\"\"\nThis is the main script\n\"\"\"\n\nimport datetime\nimport sqlite3\nfrom sqlite3 import Error\nimport nltk.sentiment\nfrom chatterbot import ChatBot\nfrom pythonosc import udp_client\n\n\ndef _create_connection(db_file):\n \"\"\" Create a database connection to the SQLite database \"\"\"\n try:\n ... | false |
9,742 | a315d01f0fb16f0c74c447c07b76f33e6ff6427d | from auth_passwordreset_reset import auth_passwordreset_reset
from auth_register import auth_register
from data import *
import pytest
#invalid reset code
def test_auth_passwordreset_reset1():
#create a test account
register = auth_register("Someemial@hotmail.com.au", "Hello123", "First", "Last")
... | [
"from auth_passwordreset_reset import auth_passwordreset_reset\nfrom auth_register import auth_register\nfrom data import *\nimport pytest\n\n\n#invalid reset code\ndef test_auth_passwordreset_reset1():\n \n #create a test account\n register = auth_register(\"Someemial@hotmail.com.au\", \"Hello123\", \"Fir... | false |
9,743 | 75b1674066958a8fa28e74121a35d688bcc473d9 | from odoo import models, fields, api, _
class SaleAdvancePaymentInv(models.TransientModel):
_inherit = "sale.advance.payment.inv"
date_start_invoice_timesheet = fields.Date(
string='Start Date',
help="Only timesheets not yet invoiced (and validated, if applicable) from this period will be inv... | [
"from odoo import models, fields, api, _\n\n\nclass SaleAdvancePaymentInv(models.TransientModel):\n _inherit = \"sale.advance.payment.inv\"\n\n date_start_invoice_timesheet = fields.Date(\n string='Start Date',\n help=\"Only timesheets not yet invoiced (and validated, if applicable) from this pe... | false |
9,744 | a718d82713503c4ce3d94225ff0db04991ad4094 | # Generated by Django 3.0 on 2020-05-04 16:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('game_skeleton', '0001_initial'),
('contenttypes', '0002_remove_content_type_name'),
('clas... | [
"# Generated by Django 3.0 on 2020-05-04 16:15\n\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 ('game_skeleton', '0001_initial'),\n ('contenttypes', '0002_remove_content_type_name'... | false |
9,745 | afdb14d60374049753b3c980c717a13456c7ff5c | from django.contrib import admin
from django.urls import path
from .views import NewsCreateListView, NewsDetailGenericView
urlpatterns = [
path('news/', NewsCreateListView.as_view()),
path('news_detailed/<int:id>/', NewsDetailGenericView.as_view()),
] | [
"from django.contrib import admin\nfrom django.urls import path\nfrom .views import NewsCreateListView, NewsDetailGenericView\n\n\nurlpatterns = [\n path('news/', NewsCreateListView.as_view()),\n path('news_detailed/<int:id>/', NewsDetailGenericView.as_view()),\n\n]",
"from django.contrib import admin\nfrom... | false |
9,746 | cb6f68c8b8a6cead1d9fcd25fa2a4e60f7a8fb28 | import math
def upsample1(d, p):
# 普通结界
assert 1 <= p <= 10
return d + p
def upsample2(d, p):
# 倍增结界
assert 2 <= p <= 3
return d * p
def downsample(d, p):
# 聚集结界
assert 2 <= p <= 10
return math.ceil(d / p)
# 初始化杀伤力范围
lethal_radius = 1
# 结界参数(z, p)
config = [(1, 6),
... | [
"import math\n\n\ndef upsample1(d, p):\n # 普通结界\n assert 1 <= p <= 10\n return d + p\n\n\ndef upsample2(d, p):\n # 倍增结界\n assert 2 <= p <= 3\n return d * p\n\n\ndef downsample(d, p):\n # 聚集结界\n assert 2 <= p <= 10\n return math.ceil(d / p)\n\n\n# 初始化杀伤力范围\nlethal_radius = 1\n\n# 结界参数(z, p... | false |
9,747 | 0972bd1241ad91f54f8dfde6327ee226c27bf2ca | from datetime import datetime
import time
from os import system
import RPi.GPIO as GPIO
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT) # este pin es de salida carro
GPIO.setup(26, GPIO.OUT) # este pin es... | [
"from datetime import datetime\nimport time\nfrom os import system\nimport RPi.GPIO as GPIO\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM) \nGPIO.setup(21, GPIO.OUT) # este pin es de salida carro\nGPIO.setup(26, GPIO.OUT... | false |
9,748 | f8c222b1a84a092a3388cb801a88495bc227b1d5 |
import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
from Crypto.PublicKey import RSA
# Part 1 - Building a Blockchain
class Blockchain:
#chain(emptylist) , farmer_details(emptylist), nodes(set), cre... | [
"\r\nimport datetime\r\nimport hashlib\r\nimport json\r\nfrom flask import Flask, jsonify, request\r\nimport requests\r\nfrom uuid import uuid4\r\nfrom urllib.parse import urlparse\r\nfrom Crypto.PublicKey import RSA\r\n\r\n# Part 1 - Building a Blockchain\r\n\r\nclass Blockchain:\r\n#chain(emptylist) , farmer_deta... | false |
9,749 | a1e563f94044ff7cd7e0e55542bc4ca2db81df28 | #
# Author:: Noah Kantrowitz <noah@coderanger.net>
#
# Copyright 2014, Noah Kantrowitz
#
# 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
#
# Unles... | [
"#\n# Author:: Noah Kantrowitz <noah@coderanger.net>\n#\n# Copyright 2014, Noah Kantrowitz\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/LICEN... | false |
9,750 | 084299da1c2f41de96e60d37088466c7b61de38e | from appJar import gui
app = gui("Calculator", "560x240")
### FUNCTIONS ###
n1, n2 = 0.0, 0.0
result = 0.0
isFirst = True
calc = ""
def doMath(btn):
global result, n1, n2, isFirst, calc
inputNumber()
if(btn == "Add"): calc = "a"
if(btn == "Substract"): calc = "s"
if(btn == "Multiply"): calc =... | [
"from appJar import gui\n\napp = gui(\"Calculator\", \"560x240\")\n\n### FUNCTIONS ###\n\nn1, n2 = 0.0, 0.0\nresult = 0.0\nisFirst = True\ncalc = \"\"\n\ndef doMath(btn):\n global result, n1, n2, isFirst, calc\n\n inputNumber()\n\n if(btn == \"Add\"): calc = \"a\"\n if(btn == \"Substract\"): calc = \"s... | false |
9,751 | 3319614d154b16190f3cd8f4f65c3b0e0da277e9 | # -*- coding: utf-8 -*-
class Solution:
"""
@param head: The first node of the linked list.
@return: The node where the cycle begins.
if there is no cycle, return null
"""
def detectCycle(self, head):
# write your code here
# 先确定是否有环,然后确定环的大小,再遍历确定位置。
cycle_... | [
"# -*- coding: utf-8 -*-\n\nclass Solution:\n \"\"\"\n @param head: The first node of the linked list.\n @return: The node where the cycle begins. \n if there is no cycle, return null\n \"\"\"\n def detectCycle(self, head):\n # write your code here\n # 先确定是否有环,然后确定环的大小,再遍... | false |
9,752 | b93f6c3192f8dd58b96dfdc6ea2b17e12cce34d0 | from collections import defaultdict, deque
N = int(input())
adj_list = defaultdict(list)
E = []
V_number = [None]*N
for _ in range(N-1):
a, b = map(int, input().split())
E.append((a, b))
adj_list[a].append(b)
adj_list[b].append(a)
C = sorted(list(map(int, input().split())), reverse=True)
q = deque([1])... | [
"from collections import defaultdict, deque\n\nN = int(input())\nadj_list = defaultdict(list)\nE = []\nV_number = [None]*N\nfor _ in range(N-1):\n a, b = map(int, input().split())\n E.append((a, b))\n adj_list[a].append(b)\n adj_list[b].append(a)\nC = sorted(list(map(int, input().split())), reverse=True... | false |
9,753 | 9535335c70129f997d7b8739444a503d0b984ac8 | import json
import os
import pickle
import random
import urllib.request
from pathlib import Path
import tensorflow as tf
from matplotlib import pyplot as plt
class CNN(object):
def __init__(self):
self.model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_... | [
"import json\nimport os\nimport pickle\nimport random\nimport urllib.request\nfrom pathlib import Path\n\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\n\n\nclass CNN(object):\n\n def __init__(self):\n self.model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(32, (3, 3), activ... | false |
9,754 | 76f2312a01bf8475220a9fcc16209faddfccd2ae | import os
import sys
import logging.config
import sqlalchemy as sql
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Float, String, Text, Integer
import pandas as pd
import numpy as np
sys.path.append('./config')
import config
logging.basicC... | [
"import os\nimport sys\nimport logging.config\nimport sqlalchemy as sql\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Float, String, Text, Integer\nimport pandas as pd\nimport numpy as np\nsys.path.append('./config')\nimport config\... | false |
9,755 | 388904b6b826a1c718b85f2951a3189bb5abea2a | # import adafruit_ads1x15 as adс
# from adafruit_ads1x15 import ads1x15 as adc
# from adafruit_ads1x15 import analog_in
import time
import busio
import board
from adafruit_ads1x15 import ads1015 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
i2c = busio.I2C(board.SCL, board.SDA)
ads = ADS.ADS1015(i2c... | [
"# import adafruit_ads1x15 as adс\r\n# from adafruit_ads1x15 import ads1x15 as adc\r\n# from adafruit_ads1x15 import analog_in\r\nimport time\r\nimport busio\r\nimport board\r\nfrom adafruit_ads1x15 import ads1015 as ADS\r\nfrom adafruit_ads1x15.analog_in import AnalogIn\r\n\r\ni2c = busio.I2C(board.SCL, board.SDA)... | false |
9,756 | 01128ebd156b24791548c50c92d2fc1969c42e70 | import numpy as np
import sklearn.cluster as sc
import sklearn.metrics as sm
import matplotlib.pyplot as mp
x = np.loadtxt('C:\\Users\\Administrator\\Desktop\\sucai\\ml_data\\perf.txt', delimiter=',')
# 准备训练模型相关数据
epsilons, scores, models = np.linspace(0.3, 1.2, 10), [], []
# 遍历所有的半径,训练模型,查看得分
for epsilon in eps... | [
"import numpy as np \nimport sklearn.cluster as sc \nimport sklearn.metrics as sm \nimport matplotlib.pyplot as mp \n\nx = np.loadtxt('C:\\\\Users\\\\Administrator\\\\Desktop\\\\sucai\\\\ml_data\\\\perf.txt', delimiter=',')\n\n# 准备训练模型相关数据\nepsilons, scores, models = np.linspace(0.3, 1.2, 10), [], []\n\n# 遍历所有的半径,训... | false |
9,757 | 9cad36de6231f310ef9022f16f6ed0da83a003b3 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 6 12:20:45 2017
@author: 7
"""
from os import listdir
from PIL import Image as PImage
from scipy import misc
import numpy as np
from Image_loader import LoadImages
"""
def LoadImages(path):
# return array of images
imagesList = listdir(path)
... | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 6 12:20:45 2017\r\n\r\n@author: 7\r\n\"\"\"\r\n\r\nfrom os import listdir\r\nfrom PIL import Image as PImage\r\nfrom scipy import misc\r\nimport numpy as np\r\nfrom Image_loader import LoadImages\r\n\"\"\"\r\ndef LoadImages(path):\r\n # return array of im... | false |
9,758 | 0fb424dafaac184882ea56f36265e0b19b5a4c50 |
import torch
import torch.nn.functional as f
import time
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU
N, D_in, H, D_out = 64, 1000, 100, 10
x = torch.randn(N, D... | [
"\nimport torch\nimport torch.nn.functional as f\nimport time\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport numpy as np\n\ndtype = torch.float\ndevice = torch.device(\"cpu\")\n# device = torch.device(\"cuda:0\") # Uncomment this to run on GPU\n\nN, D_in, H, D_out = 64, 1000, 100, 10\... | false |
9,759 | 09d32b48ae88b1066dd0aa435a351c4fb1fc04ec | from flask import Flask, request, render_template
from random import choice, sample
app = Flask(__name__)
horoscopes = [
'your day will be awesome',
'your day will be terrific',
'your day will be fantastic',
'neato, you have a fantabulous day ahead',
'your day will be oh-so-not-meh',
'this day... | [
"from flask import Flask, request, render_template\nfrom random import choice, sample\n\napp = Flask(__name__)\n\nhoroscopes = [\n 'your day will be awesome',\n 'your day will be terrific',\n 'your day will be fantastic',\n 'neato, you have a fantabulous day ahead',\n 'your day will be oh-so-not-meh'... | true |
9,760 | 5a895c864c496e1073d75937909c994432a71d75 | import socket
import json
from typing import Dict
listadionica = ["GS", "MS", "WFC", "VALBZ", "BOND", "VALE", "XLF"]
class Burza:
def __init__ (self, test):
if test:
host_name = "test-exch-partitivnisumari"
port = 25000
else:
host_name = "production"
... | [
"import socket\nimport json\n\nfrom typing import Dict\n\nlistadionica = [\"GS\", \"MS\", \"WFC\", \"VALBZ\", \"BOND\", \"VALE\", \"XLF\"]\n\nclass Burza:\n def __init__ (self, test):\n\n if test:\n host_name = \"test-exch-partitivnisumari\"\n port = 25000\n else:\n ... | true |
9,761 | 1ae69eaaa08a0045faad13281a6a3de8f7529c7a | # -*- coding: utf-8 -*-
import csv
import datetime
from django.conf import settings
from django.contrib import admin
from django.http import HttpResponse
from django.utils.encoding import smart_str
from djforms.scholars.models import *
def export_scholars(modeladmin, request, queryset):
"""Export t... | [
"# -*- coding: utf-8 -*-\r\n\r\nimport csv\r\nimport datetime\r\n\r\nfrom django.conf import settings\r\nfrom django.contrib import admin\r\nfrom django.http import HttpResponse\r\nfrom django.utils.encoding import smart_str\r\nfrom djforms.scholars.models import *\r\n\r\n\r\ndef export_scholars(modeladmin, request... | false |
9,762 | 0e73153d004137d374637abf70faffabf0bab1fb | # Generated by Django 3.1 on 2020-09-09 15:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='orderproduct',
old_name='products',
... | [
"# Generated by Django 3.1 on 2020-09-09 15:58\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='orderproduct',\n old_name='pro... | false |
9,763 | 398f9f52b83ffddfb452abbeaad2e83610580fee | # -*- coding: utf-8 -*-
# project: fshell
# author: s0nnet
# time: 2017-01-08
# desc: data_fuzzhash
import sys
sys.path.append("./dao")
from fss_data_fuzzhash_dao import *
class FssFuzzHash:
@staticmethod
def insert_node(agent_id, data):
return FssFuzzHashDao.insert_node(agent_id, data)
| [
"# -*- coding: utf-8 -*-\n\n# project: fshell\n# author: s0nnet\n# time: 2017-01-08\n# desc: data_fuzzhash\n\n\nimport sys\nsys.path.append(\"./dao\")\nfrom fss_data_fuzzhash_dao import *\n\n\nclass FssFuzzHash:\n \n @staticmethod\n def insert_node(agent_id, data):\n\n return FssFuzzHashDao.insert_n... | false |
9,764 | ac5c6a534d5131438d9590b070e6b392d4ebed0c | from pynhost.grammars import extension
from pynhost.grammars import baseutils as bu
class AtomExtensionGrammar(extension.ExtensionGrammar):
activate = '{ctrl+alt+8}'
search_chars = bu.merge_dicts(bu.OPERATORS, bu.ALPHABET, bu.CHAR_MAP)
def __init__(self):
super().__init__()
self.app_conte... | [
"from pynhost.grammars import extension\nfrom pynhost.grammars import baseutils as bu\n\nclass AtomExtensionGrammar(extension.ExtensionGrammar):\n\n activate = '{ctrl+alt+8}'\n search_chars = bu.merge_dicts(bu.OPERATORS, bu.ALPHABET, bu.CHAR_MAP)\n\n def __init__(self):\n super().__init__()\n ... | false |
9,765 | 3aa8c9b39174f0ed5799d6991516b34ca669b7d6 | from django.db import models # db에 있는 models을 가져옴
from django.utils import timezone # 유틸에 있는 timezone을 가져옴
# Create your models here.
class Post(models.Model):
# Post라는 객체를 정의함 인수로 장고모델을 가져왔음
# 장고모델이기 때문에 데이터베이스에 저장된다.
author = models.ForeignKey('auth.User') # 외래키, 다른 객체에 대한 링크
title = models.Char... | [
"from django.db import models # db에 있는 models을 가져옴\nfrom django.utils import timezone # 유틸에 있는 timezone을 가져옴\n\n\n# Create your models here.\n\nclass Post(models.Model):\n # Post라는 객체를 정의함 인수로 장고모델을 가져왔음\n # 장고모델이기 때문에 데이터베이스에 저장된다.\n author = models.ForeignKey('auth.User') # 외래키, 다른 객체에 대한 링크\n titl... | false |
9,766 | 1fbdb0b40f0d65fffec482b63aa2192968b01d4b | #define the simple_divide function here
def simple_divide(item, denom):
# start a try-except block
try:
return item/denom
except ZeroDivisionError:
return 0
def fancy_divide(list_of_numbers, index):
denom = list_of_numbers[index]
return [simple_divide(item, denom) for item in lis... | [
"#define the simple_divide function here\ndef simple_divide(item, denom):\n # start a try-except block\n try:\n return item/denom\n except ZeroDivisionError:\n return 0\n \ndef fancy_divide(list_of_numbers, index):\n denom = list_of_numbers[index]\n return [simple_divide(item, denom) ... | false |
9,767 | 9e511c769f6ccedc06845a382171fb3729913d05 | import generic
name = __name__
def options(opt):
generic._options(opt, name)
def configure(cfg):
generic._configure(cfg, name, incs=('czmq.h',), libs=('czmq',),
pcname = name.lower(),
uses = 'LIBZMQ', mandatory=True)
| [
"import generic\n\nname = __name__\n\ndef options(opt):\n generic._options(opt, name)\n\ndef configure(cfg):\n generic._configure(cfg, name, incs=('czmq.h',), libs=('czmq',),\n pcname = name.lower(),\n uses = 'LIBZMQ', mandatory=True)\n",
"import generic\nname = _... | false |
9,768 | 69ebdab4cd1f0b5154305410381db252205ff97d | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
@Description: 数据库迁移
@Author: Zpp
@Date: 2020-03-30 11:01:56
@LastEditors: Zpp
@LastEditTime: 2020-04-28 09:55:26
'''
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
from flask impor... | [
"#!/usr/bin/env python\n# -*- coding:UTF-8 -*-\n'''\n@Description: 数据库迁移\n@Author: Zpp\n@Date: 2020-03-30 11:01:56\n@LastEditors: Zpp\n@LastEditTime: 2020-04-28 09:55:26\n'''\nimport sys\nimport os\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath)... | false |
9,769 | bf04bf41f657a6ada4777fe5de98d6a68beda9d3 | import scipy.sparse
from multiprocessing.sharedctypes import Array
from ctypes import c_double
import numpy as np
from multiprocessing import Pool
import matplotlib.pyplot as plt
from time import time
import scipy.io as sio
import sys
# np.random.seed(1)
d = 100
n = 100000
k=10
learning_rate = 0.4
T_freq = 100
num_t... | [
"import scipy.sparse\nfrom multiprocessing.sharedctypes import Array\nfrom ctypes import c_double\nimport numpy as np\nfrom multiprocessing import Pool\nimport matplotlib.pyplot as plt\nfrom time import time\nimport scipy.io as sio\nimport sys\n# np.random.seed(1)\n\n\n\nd = 100\nn = 100000\nk=10\nlearning_rate = 0... | false |
9,770 | ebc2acbcbab787b07c97b0a4ea8fbaeb9d8e30aa | 30. Convertir P libras inglesas a D dólares y C centavos. Usar el tipo de cambio $2.80 = 1 libra
p=2.80
x=int(input("Desea convertir sus libras a dolar(1) o a centavos(2)"))
if x == 1:
d=float(input("¿Cuantas libras desea convertir a dólar?\n"))
conversion = (d/p)
if x == 2:
c=float(input("¿Cuan... | [
"30. Convertir P libras inglesas a D dólares y C centavos. Usar el tipo de cambio $2.80 = 1 libra\r\np=2.80\r\n\r\nx=int(input(\"Desea convertir sus libras a dolar(1) o a centavos(2)\"))\r\n\r\nif x == 1:\r\n d=float(input(\"¿Cuantas libras desea convertir a dólar?\\n\"))\r\n conversion = (d/p)\r\nif x == 2:... | true |
9,771 | eafe89de10c4187057b0cc1e0e9772f03a576b0d | __version__ = "1.2.0"
import hashlib
from collections import Counter
from re import findall
from secrets import choice
from string import ascii_letters, ascii_lowercase, ascii_uppercase
from string import digits as all_digits
from string import punctuation
import requests
def check_password(password):
"""Check ... | [
"__version__ = \"1.2.0\"\n\nimport hashlib\nfrom collections import Counter\nfrom re import findall\nfrom secrets import choice\nfrom string import ascii_letters, ascii_lowercase, ascii_uppercase\nfrom string import digits as all_digits\nfrom string import punctuation\n\nimport requests\n\n\ndef check_password(pass... | false |
9,772 | e7b96c0161e65f3f22f2ad0832fc6d1bb529f150 | """
In search.py, you will implement generic search algorithms which are called
by Pacman agents (in searchAgents.py).
"""
import util
class SearchProblem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class... | [
"\"\"\"\nIn search.py, you will implement generic search algorithms which are called\nby Pacman agents (in searchAgents.py).\n\"\"\"\n\nimport util\n\nclass SearchProblem:\n \"\"\"\n This class outlines the structure of a search problem, but doesn't implement\n any of the methods (in object-oriented termin... | false |
9,773 | 13e27c29839286988b37d2d3685f54d42fd57973 | # -*- coding: utf-8 -*-
# Copyright (c) 2018-2020 Christiaan Frans Rademan <chris@fwiw.co.za>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the ... | [
"# -*- coding: utf-8 -*-\n# Copyright (c) 2018-2020 Christiaan Frans Rademan <chris@fwiw.co.za>.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must... | false |
9,774 | f72cdf8d91c31760335b96052a34615307f48727 | from cpp_service.SubService import SubService
import config
if __name__ == "__main__":
gateway = config.gateway["trading_system_gateway"]
host = gateway["host"]
port = gateway["port"]
server_id = gateway["server_id"]
licences = gateway["licences"]
service = SubService(host, port, server_id, li... | [
"from cpp_service.SubService import SubService\nimport config\n\nif __name__ == \"__main__\":\n gateway = config.gateway[\"trading_system_gateway\"]\n host = gateway[\"host\"]\n port = gateway[\"port\"]\n server_id = gateway[\"server_id\"]\n licences = gateway[\"licences\"]\n\n service = SubServic... | false |
9,775 | 00b4a57537358797bfe37eee76bbf73ef42de081 |
#Define a function max_of_three() that takes three numbers as
#arguments and returns the largest of them.
def max_of_three(a,b,c):
max=0
if a > b:
max = a
else:
max = b
if max > c :
return max
else:
return c
print max(234,124,43)
def max_of_three2(a, b, ... | [
"\n\n\n#Define a function max_of_three() that takes three numbers as\n#arguments and returns the largest of them.\n\n\n\n\ndef max_of_three(a,b,c):\n\n max=0\n if a > b:\n max = a\n else:\n max = b\n\n if max > c :\n return max\n else:\n return c\n\n\n\nprint max(234,124,4... | true |
9,776 | 286953e381d03c0817d57f9ee4e15f2a0ce808a9 | from django_evolution.mutations import ChangeField
MUTATIONS = [
ChangeField('ReviewRequest', 'depends_on', initial=None, null=False),
ChangeField('ReviewRequestDraft', 'depends_on', initial=None, null=False),
]
| [
"from django_evolution.mutations import ChangeField\n\n\nMUTATIONS = [\n ChangeField('ReviewRequest', 'depends_on', initial=None, null=False),\n ChangeField('ReviewRequestDraft', 'depends_on', initial=None, null=False),\n]\n",
"from django_evolution.mutations import ChangeField\nMUTATIONS = [ChangeField('Re... | false |
9,777 | 8279f8a80d96a7231e35100d2c39fa5e1f34f5f5 | from scipy.cluster.hierarchy import dendrogram, linkage
from get_train import get, pre
import matplotlib.pyplot as plt
#%%
index = [
'BAC',
'JPM',
'GS',
'C',
'AAPL',
'IBM',
'MSFT',
'ORCL'
]
years = [
2010,
2013,
... | [
"from scipy.cluster.hierarchy import dendrogram, linkage\r\nfrom get_train import get, pre\r\nimport matplotlib.pyplot as plt\r\n#%%\r\nindex = [\r\n 'BAC', \r\n 'JPM', \r\n 'GS', \r\n 'C',\r\n 'AAPL', \r\n 'IBM', \r\n 'MSFT', \r\n 'ORCL'\r\n ]\r\n\r\nyears... | false |
9,778 | 6339a1a06319a748030b3411c7a8d00f36336e65 | # 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 in writing, software
# distributed under t... | [
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distr... | false |
9,779 | 2f9a081845685a4748c8b028ae4ee3a056a10284 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of CbM (https://github.com/ec-jrc/cbm).
# Author : Konstantinos Anastasakis
# Credits : GTCAP Team
# Copyright : 2021 European Commission, Joint Research Centre
# License : 3-Clause BSD
import os
import glob
from ipywidgets import (Text, Label... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# This file is part of CbM (https://github.com/ec-jrc/cbm).\n# Author : Konstantinos Anastasakis\n# Credits : GTCAP Team\n# Copyright : 2021 European Commission, Joint Research Centre\n# License : 3-Clause BSD\n\n\nimport os\nimport glob\nfrom ipywidgets im... | false |
9,780 | c2f859e0ed0e812768dec04b2b1f9ddd349350f6 | # open a converted base to bits file and convert it back to the base sequences
seq2 = ''
with open('chr01.txt') as a:
while 1:
seq = a.read(2)
# print(seq)
seq = seq.replace('00', 'c').replace('01', 'g').replace('10', 'a').replace('11', 't')
seq2 += seq
if not seq:
... | [
"# open a converted base to bits file and convert it back to the base sequences\n\nseq2 = ''\nwith open('chr01.txt') as a:\n while 1:\n seq = a.read(2)\n # print(seq)\n seq = seq.replace('00', 'c').replace('01', 'g').replace('10', 'a').replace('11', 't')\n seq2 += seq\n if not ... | false |
9,781 | 451a36eb205a269a05e3b3d89541278633d12aaa |
class ChartType:
Vanilla = "Vanilla"
Neopolitan = "Neopolitan"
| [
"\n\nclass ChartType:\n Vanilla = \"Vanilla\"\n Neopolitan = \"Neopolitan\"\n",
"class ChartType:\n Vanilla = 'Vanilla'\n Neopolitan = 'Neopolitan'\n",
"class ChartType:\n <assignment token>\n <assignment token>\n",
"<class token>\n"
] | false |
9,782 | 4ed6f4db4c9c3319d6289ba402f81bbd8accf915 | import numpy as np
import dxchange
import ptychotomo
if __name__ == "__main__":
# read object
u = dxchange.read_tiff('data/init_object.tiff')
u = u+1j*u/2
nz, n, _ = u.shape
# parameters
center = n/2
ntheta = 384
ne = 3*n//2
ngpus = 1
pnz = nz//2
theta = np.linspace(0... | [
"import numpy as np\nimport dxchange\nimport ptychotomo\n\nif __name__ == \"__main__\":\n \n # read object\n u = dxchange.read_tiff('data/init_object.tiff')\n u = u+1j*u/2\n\n nz, n, _ = u.shape\n\n # parameters\n center = n/2\n ntheta = 384\n ne = 3*n//2\n ngpus = 1\n pnz = nz//2\n... | false |
9,783 | 21c581131cff8cf2f4aa407055184d56865a6335 | #!/usr/bin/env python
# Title : STACK_BostonHousing.py
# Description : Stacking was the natural progression of our algorithms trial.
# In here, we'll use prediction from a number of models in order
# to improve accuracy as it add linearly independent data to our
# ... | [
"#!/usr/bin/env python\n# Title : STACK_BostonHousing.py\n# Description : Stacking was the natural progression of our algorithms trial.\n# In here, we'll use prediction from a number of models in order\n# to improve accuracy as it add linearly independent data to our\n# ... | false |
9,784 | 41ca762fe6865613ae4ef2f657f86b516353676f | from django.contrib.auth import authenticate, login, logout
from django.template import loader
from django.http import (HttpResponse, JsonResponse,
HttpResponseForbidden, HttpResponseBadRequest)
from django.shortcuts import redirect
from django.views.decorators.http import require_POST
import ... | [
"from django.contrib.auth import authenticate, login, logout\nfrom django.template import loader\nfrom django.http import (HttpResponse, JsonResponse,\n HttpResponseForbidden, HttpResponseBadRequest)\nfrom django.shortcuts import redirect\nfrom django.views.decorators.http import require_POS... | false |
9,785 | 518dcdca8f5e6b42624083e4327143dfba59b2ba | def emphasize(sentence):
words = sentence.split(" ")
for i, word in enumerate(words):
words[i] = word[0].upper() + word[1:].lower()
return " ".join(words)
exp1 = "Hello World"
ans1 = emphasize("hello world")
assert ans1 == exp1, f"expected {exp1}, got {ans1}"
exp2 = "Good Morning"
ans2 = emphasiz... | [
"def emphasize(sentence):\n words = sentence.split(\" \")\n for i, word in enumerate(words):\n words[i] = word[0].upper() + word[1:].lower()\n return \" \".join(words)\n\n\nexp1 = \"Hello World\"\nans1 = emphasize(\"hello world\")\nassert ans1 == exp1, f\"expected {exp1}, got {ans1}\"\n\nexp2 = \"Go... | false |
9,786 | 1c55cfa03cd9210b7cf9e728732afe19930e9a41 | import yet
import pickle
sources = pickle.load(open("./db/source_list"))
addr_list = sources.keys()
'''
for i in range(len(addr_list)):
print addr_list[i],
try:
a = yet.tree(None, sources[addr_list[i]])
print ' Owner :',
for i in a.owner.keys():
print i+ '() ' + a.owner[... | [
"import yet\nimport pickle\n\nsources = pickle.load(open(\"./db/source_list\"))\naddr_list = sources.keys()\n\n'''\nfor i in range(len(addr_list)):\n print addr_list[i], \n try:\n a = yet.tree(None, sources[addr_list[i]])\n\n print ' Owner :',\n\n for i in a.owner.keys():\n pri... | true |
9,787 | a78bbb85f4912e5f7ea23f689de65cb16a38d814 | import asyncio
from . import edit_or_reply, udy
plugin_category = "utils"
@udy.cod_cmd(
pattern="as$",
command=("as", plugin_category),
info={
"header": "salam.",
"usage": "{tr}as",
},
)
async def _(event):
"animation command"
event = await edit_or_reply(event, "as")
awai... | [
"import asyncio\n\nfrom . import edit_or_reply, udy\n\nplugin_category = \"utils\"\n\n\n@udy.cod_cmd(\n pattern=\"as$\",\n command=(\"as\", plugin_category),\n info={\n \"header\": \"salam.\",\n \"usage\": \"{tr}as\",\n },\n)\nasync def _(event):\n \"animation command\"\n event = awa... | false |
9,788 | fd059ae6e5eb3f7dc18dff6f9ed206002cea5fb2 | import os
print(os.name)
#print(os.environ)
print(os.environ.get('PATH'))
print(os.path.abspath('.'))
os.path.join(os.path.abspath('.'),'testdir')
os.mkdir(os.path.abspath('.')) | [
"import os\nprint(os.name)\n#print(os.environ)\nprint(os.environ.get('PATH'))\nprint(os.path.abspath('.'))\nos.path.join(os.path.abspath('.'),'testdir')\nos.mkdir(os.path.abspath('.'))",
"import os\nprint(os.name)\nprint(os.environ.get('PATH'))\nprint(os.path.abspath('.'))\nos.path.join(os.path.abspath('.'), 'tes... | false |
9,789 | 44e4151279884ce7c5d5a9e5c82916ce2d3ccbc2 | import random
from datetime import timedelta
from typing import Union, Type, Tuple, List, Dict
from django import http
from django.test import TestCase, Client
from django.utils import timezone
from exam_web import errors
from exam_web.models import Student, AcademyGroup, uuid_str, ExamSession, \
UserSession, Que... | [
"import random\nfrom datetime import timedelta\nfrom typing import Union, Type, Tuple, List, Dict\n\nfrom django import http\nfrom django.test import TestCase, Client\nfrom django.utils import timezone\n\nfrom exam_web import errors\nfrom exam_web.models import Student, AcademyGroup, uuid_str, ExamSession, \\\n ... | false |
9,790 | 1fda8274024bdf74e7fbd4ac4a27d6cfe6032a13 | from distutils.core import setup
setup(name='greeker',
version='0.3.2-git',
description="scrambles nouns in an XML document to produce a specimen for layout testing",
author="Brian Tingle",
author_email="brian.tingle.cdlib.org@gmail.com",
url="http://tingletech.github.com/greeker.py/",
... | [
"from distutils.core import setup\nsetup(name='greeker',\n version='0.3.2-git',\n description=\"scrambles nouns in an XML document to produce a specimen for layout testing\",\n author=\"Brian Tingle\",\n author_email=\"brian.tingle.cdlib.org@gmail.com\",\n url=\"http://tingletech.github.com... | false |
9,791 | 75217256d88c32ed1c502bc104c30092bf74382d | # Find sum/count of Prime digits in a number | [
"# Find sum/count of Prime digits in a number",
""
] | false |
9,792 | acd0b9019ef413699b47ecb2b66a0980cf3aa81f | from cudasim.ParsedModel import ParsedModel
import re
import copy
class Writer:
def __init__(self):
pass
# replace the species and parameters recursively
@staticmethod
def rep(string, find, replace):
ex = find + "[^0-9]"
while re.search(ex, string) is not None:
res... | [
"from cudasim.ParsedModel import ParsedModel\nimport re\nimport copy\n\nclass Writer:\n\n def __init__(self):\n pass\n\n # replace the species and parameters recursively\n @staticmethod\n def rep(string, find, replace):\n ex = find + \"[^0-9]\"\n while re.search(ex, string) is not N... | false |
9,793 | c9b62328a463fd38f3dbd1e7b5e1990f7eec1dba | from django.shortcuts import render
from django.http import HttpResponse
def view1(request):
return HttpResponse(" Hey..,This is the first view using HttpResponce!")
def view2(request):
context={"tag_var":"tag_var"}
return render(request,"new.html",context)
# Create your views here.
| [
"from django.shortcuts import render\nfrom django.http import HttpResponse\ndef view1(request):\n return HttpResponse(\" Hey..,This is the first view using HttpResponce!\")\ndef view2(request):\n context={\"tag_var\":\"tag_var\"}\n return render(request,\"new.html\",context)\n# Create your views here.\n",
... | false |
9,794 | 6cd250b3bffd87657ec7cc28eaffe817c6d9f73f | # Generated by Django 2.0.3 on 2018-04-30 16:25
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('threads', '0007_auto_20180430_1617'),
]
operations = [
migrations.AlterField(
model_name='thread',
... | [
"# Generated by Django 2.0.3 on 2018-04-30 16:25\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('threads', '0007_auto_20180430_1617'),\n ]\n\n operations = [\n migrations.AlterField(\n mo... | false |
9,795 | 00099cab0c816c76fc0fa94d7905175feb6919cf | import django.dispatch
property_viewed = django.dispatch.Signal(providing_args=["property","user", "request", "response"]) | [
"import django.dispatch\n\nproperty_viewed = django.dispatch.Signal(providing_args=[\"property\",\"user\", \"request\", \"response\"])",
"import django.dispatch\nproperty_viewed = django.dispatch.Signal(providing_args=['property', 'user',\n 'request', 'response'])\n",
"<import token>\nproperty_viewed = djang... | false |
9,796 | 8de36400f21bfb4e24703d5a65471a961e1afddc | #coding=utf-8
from selenium import webdriver
wd=webdriver.Firefox()
wd.get('https://www.baidu.com/')
wd.find_element_by_id('kw').send_keys(u'哈哈')
wd.quit()
| [
"#coding=utf-8\n\nfrom selenium import webdriver\n\nwd=webdriver.Firefox()\nwd.get('https://www.baidu.com/')\nwd.find_element_by_id('kw').send_keys(u'哈哈')\n\nwd.quit()\n",
"from selenium import webdriver\nwd = webdriver.Firefox()\nwd.get('https://www.baidu.com/')\nwd.find_element_by_id('kw').send_keys(u'哈哈')\nwd.... | false |
9,797 | a52f009a755b45f8ed653a4a0385b1eb667f2318 | __author__ = 'changwoncheo'
# -*- coding: utf-8 -*-
import threading
import logging
logging.basicConfig(filename='crawl2.log',level=logging.DEBUG)
class NoParsingFilter(logging.Filter):
def filter(self, record):
msg = record.getMessage()
return not ('Starting' in msg or 'GET' in msg)
logger = loggin... | [
"__author__ = 'changwoncheo'\n# -*- coding: utf-8 -*-\nimport threading\nimport logging\nlogging.basicConfig(filename='crawl2.log',level=logging.DEBUG)\nclass NoParsingFilter(logging.Filter):\n def filter(self, record):\n msg = record.getMessage()\n return not ('Starting' in msg or 'GET' in msg)\nl... | true |
9,798 | 93e534e8d425510b59310dcbfc5bca9cc32f245e | import sys
import random
#import matplotlib.pyplot as plt
import numpy as np
import time
class Waterfilling:
"""
initializes x and r with optimal flow allocations
and link fair share rates for traffic matrix routes and link
capacities c, and level with number of levels
after running the waterfillin... | [
"import sys\nimport random\n#import matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\nclass Waterfilling:\n \"\"\"\n initializes x and r with optimal flow allocations\n and link fair share rates for traffic matrix routes and link\n capacities c, and level with number of levels\n after runn... | true |
9,799 | c4c24c36fe0afba61f8046055690f0c36df7098c | # Developed by : Jays Patel (cyberthreatinfo.ca)
# This script is use to find the python Composer packages vulnerabilities from linux machine and python source project.
import time
import glob2
import random
import os.path
from os import path
import ast
import sys
import commands
import re
import requests
from pkg_res... | [
"# Developed by : Jays Patel (cyberthreatinfo.ca)\n# This script is use to find the python Composer packages vulnerabilities from linux machine and python source project.\n\nimport time\nimport glob2\nimport random\nimport os.path\nfrom os import path\nimport ast\nimport sys\nimport commands\nimport re\nimport requ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.