index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
10,200 | 358d39b8b4bbc07a64bd16edb25b5e963e9c3bd0 | from PIL import Image
im = Image.open("monalisa.jpg","r")
def effect_spread(self, distance):
"""
Randomly spread pixels in an image.
:param distance: Distance to spread pixels.
"""
self.load()
return self._new(self.im.effect_spread(distance))
im2 = im.effect_spread(100)
im2.show()
| [
"from PIL import Image\nim = Image.open(\"monalisa.jpg\",\"r\")\n\ndef effect_spread(self, distance):\n \"\"\"\n Randomly spread pixels in an image.\n :param distance: Distance to spread pixels.\n \"\"\"\n self.load()\n return self._new(self.im.effect_spread(distance))\n\n\nim2 = im.effect_spread(... | false |
10,201 | 88fc3e904ba286b2d4f8852be2aeec59f85de83c | # -*- coding: utf-8 -*-
import csv
import xml.dom.minidom
import os
import time
import openpyxl
import requests
cook='foav0m0k120tcsrq32n82pj0h6'
def getImporter(name):
name = name.replace(',', '').replace('\'', '')
r = requests.post('https://fsrar.gov.ru/frap/frap', data={'FrapForm[name_prod]': nam... | [
"# -*- coding: utf-8 -*-\r\nimport csv\r\nimport xml.dom.minidom\r\nimport os\r\nimport time\r\nimport openpyxl\r\nimport requests\r\ncook='foav0m0k120tcsrq32n82pj0h6'\r\ndef getImporter(name):\r\n\r\n name = name.replace(',', '').replace('\\'', '')\r\n r = requests.post('https://fsrar.gov.ru/frap/frap', data... | false |
10,202 | d4a1e7f0043eb35305b63689130e09501c1ce57d | from app.core import Forca
def test_animais():
f = Forca('animais')
assert isinstance(f.palavra(), str)
def test_paises():
f = Forca('paises')
assert isinstance(f.palavra(), str) | [
"from app.core import Forca\r\n\r\ndef test_animais():\r\n f = Forca('animais')\r\n\r\n assert isinstance(f.palavra(), str)\r\n\r\ndef test_paises():\r\n f = Forca('paises')\r\n\r\n assert isinstance(f.palavra(), str)",
"from app.core import Forca\n\n\ndef test_animais():\n f = Forca('animais')\n ... | false |
10,203 | 2127dc0db40f6f76a95cabdc1bcf4372b14b87f3 | # -*- coding: utf-8 -*-
"""
Created on Sat May 19 21:19:56 2018
@author: 王磊
"""
import os
def loadintxt(fileName):
with open(fileName, 'r', encoding='utf-8') as file:
comment = file.readlines()
return comment
def addtxt(textcomments, fileName='D:\\Python\\Spider\\allcommen... | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat May 19 21:19:56 2018\r\n\r\n@author: 王磊\r\n\"\"\"\r\n\r\nimport os\r\n\r\n\r\ndef loadintxt(fileName):\r\n with open(fileName, 'r', encoding='utf-8') as file:\r\n comment = file.readlines()\r\n \r\n return comment\r\n\r\ndef addtxt(textcommen... | false |
10,204 | 50218e8f7eb43cbc010748ea3215ad9134a7ad53 | import discord
from discord.ext import commands
import asyncio
import os
class Others(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(brief='Shows you my ping', help="Using this command i'll tell you my latency")
async def ping(self, ctx):
await ctx.s... | [
"import discord\nfrom discord.ext import commands\nimport asyncio\nimport os\n\nclass Others(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n \n @commands.command(brief='Shows you my ping', help=\"Using this command i'll tell you my latency\")\n async def ping(self, ctx):\n... | false |
10,205 | 027e69f64c3a06db55de882c1499177345fe0784 | #!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
#n = int( input().strip() )
for n in [ 1, 4, 6, 8, 21, 24 ]:
res = ""
if n%2 == 0 and ( n in range( 2, 6 ) or n > 20 ):
res += "Not"
res += "Weird"
print( str( n ) +... | [
"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n\nif __name__ == '__main__':\n #n = int( input().strip() )\n for n in [ 1, 4, 6, 8, 21, 24 ]:\n res = \"\"\n if n%2 == 0 and ( n in range( 2, 6 ) or n > 20 ):\n res += \"Not\"\n res += \"Weird\... | false |
10,206 | db0a963a8de1b3db7b73fdff09bdb87895fde7f6 | from pyvmmonitor_core.compat import * | [
"from pyvmmonitor_core.compat import *",
"from pyvmmonitor_core.compat import *\n",
"<import token>\n"
] | false |
10,207 | 1f06bfd8f5226e1c8bdd3824da1dfab299b6c115 | def myfunc(*args):
evens = []
for item in args:
if item%2 == 0:
evens.append(item)
return evens
nums = myfunc(1,2,3,4,5,6)
print(nums)
def myfunc(string):
s = ''
counter = 1
for letter in string:
if counter%2 != 0:
s += letter.lower()
else:
s += letter.upper()
counter += 1
print(s)
word = m... | [
"def myfunc(*args):\n\tevens = []\n\tfor item in args:\n\t\tif item%2 == 0:\n\t\t\tevens.append(item)\n\treturn evens\n\nnums = myfunc(1,2,3,4,5,6)\n\nprint(nums)\n\n\ndef myfunc(string):\n\ts = ''\n\tcounter = 1\n\tfor letter in string:\n\t\tif counter%2 != 0:\n\t\t\ts += letter.lower()\n\t\telse:\n\t\t\ts += lett... | false |
10,208 | fc1c6d6b8cd08d3c35c3057e60206bb9aeff0d38 | from django.core.management.base import BaseCommand, CommandError
from django.core.serializers.json import DjangoJSONEncoder
from urllib.request import urlopen
import json
from shows.models import Episode
from shows.models import Show
from datetime import date
from datetime import datetime
from datetime import timedelt... | [
"from django.core.management.base import BaseCommand, CommandError\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom urllib.request import urlopen\nimport json\nfrom shows.models import Episode\nfrom shows.models import Show\nfrom datetime import date\nfrom datetime import datetime\nfrom datetime im... | false |
10,209 | 93e3bc6c103b47aa13c79f7f60b0b6656efd2a82 | class Model1(object):
def __init__( self, root = None, expanded = None):
self.root = root or []
self.expanded = expanded or []
self.flattened_list = []
self.listeners = []
self.depths = {}
self.filters = []
self.donotexpand = []
class Model2(object):
def ... | [
"class Model1(object):\n def __init__( self, root = None, expanded = None):\n self.root = root or []\n self.expanded = expanded or []\n self.flattened_list = []\n self.listeners = []\n self.depths = {}\n self.filters = []\n self.donotexpand = []\n\nclass Model2(ob... | true |
10,210 | c859908f65cda4fbc88d717f662b7259779007a6 | # An OAuth access token is needed, see: https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token
# Rate limit is 500 per day or 50 if you do not meet certain requirements.
# For more informations see: https://docs.github.com/en/free-pro-team@latest/rest/reference/... | [
"# An OAuth access token is needed, see: https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token\n# Rate limit is 500 per day or 50 if you do not meet certain requirements.\n# For more informations see: https://docs.github.com/en/free-pro-team@latest/rest/ref... | false |
10,211 | bf5653c6239e12b362f8eeebce1c0d0570c29d73 | from rest_framework.response import Response
from rest_framework.views import APIView
from .serializer import ProfileSerializer,ProjectSerializer
from django.http.response import HttpResponseRedirect
from django.urls import reverse
from review.forms import ReviewForm, SignUpForm,UserProfileForm,ProjectForm
from review.... | [
"from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .serializer import ProfileSerializer,ProjectSerializer\nfrom django.http.response import HttpResponseRedirect\nfrom django.urls import reverse\nfrom review.forms import ReviewForm, SignUpForm,UserProfileForm,ProjectForm\nf... | false |
10,212 | 7f42f7f2815ce595c5b5a061f7c54aa3d4777ed8 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from mysite.views import test,welcome,books
admin.autodiscover()
urlpatterns = patterns('',
('^test/',test),
('^welcome/',welcome),
('^books/',books),
(r'^admin/',include(admin.site.urls)),
)
| [
"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nfrom mysite.views import test,welcome,books\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n ('^test/',test),\n ('^welcome/',welcome),\n ('^books/',books),\n (r'^admin/',include(admin.site.urls)),\n)\n",
"... | false |
10,213 | c40e1d3c794232f6d2f7311067eba0b851c46067 | from procedures import BuildProcedure
from buildbot.steps.source import Git
from buildbot.steps.shell import Test, SetProperty
from buildbot.steps.slave import SetPropertiesFromEnv
from buildbot.process.properties import WithProperties
def Emacs():
return WithProperties(
'%(EMACS)s'
, EMACS=lambda ... | [
"from procedures import BuildProcedure\nfrom buildbot.steps.source import Git\nfrom buildbot.steps.shell import Test, SetProperty\nfrom buildbot.steps.slave import SetPropertiesFromEnv\nfrom buildbot.process.properties import WithProperties\n\ndef Emacs():\n return WithProperties(\n '%(EMACS)s'\n ,... | false |
10,214 | 2a974f2c94a6c46c3ba7a1d34c65a4acb9f4c6b0 | # -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... | [
"# -*- coding: utf-8 -*-\n\n# Copyright 2018 IBM.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by appli... | false |
10,215 | 99084c12239034766371f8fce3538a3a8f5736ba | def cruise(filename, outname):
infile = open(filename, "r+")
outfile = open(outname, "w+")
lines = infile.readlines()
T = int(lines[0])
line_num = 1
for i in range(T):
D = int(lines[line_num].split(" ")[0])
N = int(lines[line_num].split(" ")[1])
max_time = 0
line_... | [
"def cruise(filename, outname):\n infile = open(filename, \"r+\")\n outfile = open(outname, \"w+\")\n lines = infile.readlines()\n T = int(lines[0])\n line_num = 1\n for i in range(T):\n D = int(lines[line_num].split(\" \")[0])\n N = int(lines[line_num].split(\" \")[1])\n max_... | false |
10,216 | 63026794355a652feb605695eec7ab379364d51b | import numpy
import tkinter
from tkinter import filedialog
from matplotlib import pyplot as plt
def LoadTexturesFromBytes(texturesBytes):
dataTypeMap = { 2 : 'float16', 4 : 'float32' }
totalBytesToRead = len(texturesBytes)
bytesRead = 0
textures = {}
while bytesRead < totalBytesToRead:
re... | [
"import numpy\nimport tkinter\nfrom tkinter import filedialog\nfrom matplotlib import pyplot as plt\n\ndef LoadTexturesFromBytes(texturesBytes):\n dataTypeMap = { 2 : 'float16', 4 : 'float32' }\n\n totalBytesToRead = len(texturesBytes)\n bytesRead = 0\n textures = {}\n\n while bytesRead < totalBytesT... | false |
10,217 | 7b540b0c3aacc8fe379e095c9a26d6ec724eaad1 | """
test_get_webpage.py -- Given a URI of a webpage, return a python
structure representing the attributes of the webpage
Version 0.1 MC 2013-12-27
-- Initial version
Version 0.2 MC 2014-09-21
-- Update for PEP 8, Tools 2
"""
__author__ = "Michael Conlon"
__copyright__ = "Copyright 2014, Un... | [
"\"\"\"\n test_get_webpage.py -- Given a URI of a webpage, return a python\n structure representing the attributes of the webpage\n\n Version 0.1 MC 2013-12-27\n -- Initial version\n Version 0.2 MC 2014-09-21\n -- Update for PEP 8, Tools 2\n\n\"\"\"\n\n__author__ = \"Michael Conlon\"\n__copyrigh... | true |
10,218 | fadb4967afd5bd91e56243d84119169fb8c42d44 | import os
import cv2 as cv
import numpy as np
from time import sleep
def save_image(img, path):
cv.imwrite(path, img)
def show_image(img):
cv.imshow('frame', img)
def detect_face(cascade, image):
image_copy = image.copy()
grayscale = cv.cvtColor(image_copy, cv.COLOR_BGR2GRAY)
faces = cascade.... | [
"import os\n\nimport cv2 as cv\nimport numpy as np\nfrom time import sleep\n\n\ndef save_image(img, path):\n cv.imwrite(path, img)\n\n\ndef show_image(img):\n cv.imshow('frame', img)\n\n\ndef detect_face(cascade, image):\n image_copy = image.copy()\n grayscale = cv.cvtColor(image_copy, cv.COLOR_BGR2GRAY... | false |
10,219 | f7edfb23d4bc14900e1a3ea7d2496fc5b14ac52f | import unittest
import os
from org.geppetto.recording.creators import NeuronRecordingCreator
from org.geppetto.recording.creators.tests.abstest import AbstractTestCase
class NeuronRecordingCreatorTestCase(AbstractTestCase):
"""Unittests for the NeuronRecordingCreator class."""
def test_text_recording_1(self)... | [
"import unittest\nimport os\nfrom org.geppetto.recording.creators import NeuronRecordingCreator\nfrom org.geppetto.recording.creators.tests.abstest import AbstractTestCase\n\n\nclass NeuronRecordingCreatorTestCase(AbstractTestCase):\n \"\"\"Unittests for the NeuronRecordingCreator class.\"\"\"\n\n def test_te... | false |
10,220 | a8c00f46b749a7454169cfe8c2bfa521f81cd24e | # gensim modules
from gensim import utils
from gensim.models.doc2vec import TaggedDocument
from gensim.models import Doc2Vec
from sources import sources
import string
# numpy
import numpy
# shuffle
from random import shuffle
# logging
import logging
import os.path
import sys
import _pickle as pickle
log = logging... | [
"# gensim modules\nfrom gensim import utils\nfrom gensim.models.doc2vec import TaggedDocument\nfrom gensim.models import Doc2Vec\nfrom sources import sources\n\nimport string\n\n# numpy\nimport numpy\n\n# shuffle\nfrom random import shuffle\n\n# logging\nimport logging\nimport os.path\nimport sys\nimport _pickle as... | false |
10,221 | 63433e91668d0a19a6072a881599b611b7d5be72 | from django.urls import path
from curricula.api.views import (
carrera,
anio_lectivo,
anio,
materia,
evaluacion,
)
urlpatterns = [
# Carrera
path("carrera/", carrera.create_carrera, name="carrera-create"),
path(
"carrera/<int:pk>/",
carrera.view_edit_carrera,
nam... | [
"from django.urls import path\nfrom curricula.api.views import (\n carrera,\n anio_lectivo,\n anio,\n materia,\n evaluacion,\n)\n\nurlpatterns = [\n # Carrera\n path(\"carrera/\", carrera.create_carrera, name=\"carrera-create\"),\n path(\n \"carrera/<int:pk>/\",\n carrera.view_... | false |
10,222 | fc5bd65b75cdbb48386de74da0798bf7656b7fc3 | ####################################################
# A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
# 1/2 = 0.5
# 1/3 = 0.(3)
# 1/4 = 0.25
# 1/5 = 0.2
# 1/6 = 0.1(6)
# 1/7 = 0.(142857)
# 1/8 = 0.125
# 1/9 = 0.(1)
# 1/10 = 0.... | [
"####################################################\n# A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:\n\n# 1/2\t= \t0.5\n# 1/3\t= \t0.(3)\n# 1/4\t= \t0.25\n# 1/5\t= \t0.2\n# 1/6\t= \t0.1(6)\n# 1/7\t= \t0.(142857)\n# 1/8\t= \t0.125... | false |
10,223 | 2f3238eeb45a1684a218ee6f8ac401f31b005c2d | # 按题目说明解法
class Solution(object):
def lastRemaining(self, n):
nums = [i+1 for i in range(n)]
res = []
while len(nums) > 1:
for i in range(1, len(nums), 2):
res.append(nums[i])
nums, res = res[::-1], []
return nums[0]
# 找规律,如果输入a输出b,则输入2a输出2*(... | [
"# 按题目说明解法\nclass Solution(object):\n def lastRemaining(self, n):\n nums = [i+1 for i in range(n)]\n res = []\n while len(nums) > 1:\n for i in range(1, len(nums), 2):\n res.append(nums[i])\n nums, res = res[::-1], []\n return nums[0]\n\n\n# 找规律,如果... | false |
10,224 | 7cdd60a42d19d37584d268be06322fce5b011e84 | # -*- coding: utf-8 -*-
import os
import re
import csv
import unicodedata
csv_path = r"C:\Users\glago\YandexDisk\Fests\AtomCosCon 2022\AtomCosCon 22 - Заявки.csv"
id_row = '#'
folder_path = r"C:\Users\glago\YandexDisk\Fests\AtomCosCon 2022\Tracks"
id_regex_filename = r"^(?P<id>\d{3})"
def make_name(d):
return ... | [
"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport csv\nimport unicodedata\n\ncsv_path = r\"C:\\Users\\glago\\YandexDisk\\Fests\\AtomCosCon 2022\\AtomCosCon 22 - Заявки.csv\"\nid_row = '#'\n\nfolder_path = r\"C:\\Users\\glago\\YandexDisk\\Fests\\AtomCosCon 2022\\Tracks\"\nid_regex_filename = r\"^(?P<id>\\d{3}... | false |
10,225 | a0349cfa08a5095d7b20d9e26953d614655b415f | # Generated by Django 3.2.7 on 2021-09-02 23:58
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='City',
fields=[
... | [
"# Generated by Django 3.2.7 on 2021-09-02 23:58\n\nimport django.db.models.deletion\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='City',\n ... | false |
10,226 | 5d0d2d9c5c32f9da54462c15fd48d0862f4cdb4c | # Copyright (c) 2007 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
See how fast deferreds are.
This is mainly useful to compare cdefer.Deferred to defer.Deferred
"""
from twisted.internet import defer
from timer import timeit
benchmarkFuncs = []
def benchmarkFunc(iter, args=()):
"""
A decora... | [
"# Copyright (c) 2007 Twisted Matrix Laboratories.\n# See LICENSE for details.\n\n\"\"\"\nSee how fast deferreds are.\n\nThis is mainly useful to compare cdefer.Deferred to defer.Deferred\n\"\"\"\n\n\nfrom twisted.internet import defer\nfrom timer import timeit\n\nbenchmarkFuncs = []\n\ndef benchmarkFunc(iter, args... | true |
10,227 | 32cffe48918261c0094c8ca59d6f72d01884ac2b | from sdoc.application.SDocApplication import SDocApplication
def main():
"""
The main of the sdoc program.
"""
sdoc_application = SDocApplication()
sdoc_application.run()
# ----------------------------------------------------------------------------------------------------------------------
| [
"from sdoc.application.SDocApplication import SDocApplication\n\n\ndef main():\n \"\"\"\n The main of the sdoc program.\n \"\"\"\n sdoc_application = SDocApplication()\n sdoc_application.run()\n\n# -------------------------------------------------------------------------------------------------------... | false |
10,228 | 519119ceb5a3bd526ffb5af741eb28969298863d | # -*- coding: utf-8 -*-
# !/usr/bin/env python3
# Function decorator: prints when a function is called along
# with its parameters
def debug(func):
def decorated(*args, **kwargs):
print('Function: {} called with args: {} and kwargs: {}'.format(
func.__name__,
args,
kwarg... | [
"# -*- coding: utf-8 -*-\n# !/usr/bin/env python3\n\n# Function decorator: prints when a function is called along\n# with its parameters\ndef debug(func):\n def decorated(*args, **kwargs):\n print('Function: {} called with args: {} and kwargs: {}'.format(\n func.__name__,\n args,\n ... | false |
10,229 | 866930e9038c3f7fc528ef470c4b3e5d3c4fce1f | import monitors
myPR650 = monitors.Photometer(1)
myPR650.measure()
spec = myPR650.getLastSpectrum()
| [
"import monitors\n\nmyPR650 = monitors.Photometer(1)\nmyPR650.measure()\nspec = myPR650.getLastSpectrum()\n",
"import monitors\nmyPR650 = monitors.Photometer(1)\nmyPR650.measure()\nspec = myPR650.getLastSpectrum()\n",
"<import token>\nmyPR650 = monitors.Photometer(1)\nmyPR650.measure()\nspec = myPR650.getLastSp... | false |
10,230 | 61ab2006f29d1fb7b040b1f2f63317d1a81c1990 | from abc import ABC, abstractmethod
class IMove(ABC):
@abstractmethod
def move(self):
pass
| [
"from abc import ABC, abstractmethod\n\nclass IMove(ABC):\n \n @abstractmethod\n def move(self): \n pass\n\n\n",
"from abc import ABC, abstractmethod\n\n\nclass IMove(ABC):\n\n @abstractmethod\n def move(self):\n pass\n",
"<import token>\n\n\nclass IMove(ABC):\n\n @abstractmethod... | false |
10,231 | aecab19cb45a60895ccbc91df2f45bcb3221f3c3 | # import the necessary packages
from tracker.centroidtracker import CentroidTracker
from tracker.trackableobject import TrackableObject
from imutils.video import VideoStream
from imutils.video import FPS
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2
# import pretrained SSD Model ... | [
"# import the necessary packages\nfrom tracker.centroidtracker import CentroidTracker\nfrom tracker.trackableobject import TrackableObject\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nimport numpy as np\nimport argparse\nimport imutils\nimport time\nimport dlib\nimport cv2\n\n# import pret... | false |
10,232 | c72e625760e2a94320146539cabfd247be029298 | import itertools
import os
import re
import jieba
from wordcloud import WordCloud
def get_rhyme(f_name):
f = open('./lyrics/' + f_name, 'r', encoding='UTF-8')
text = f.readlines()
f.close()
'''处理开头'''
for m, n in enumerate(text):
if '编曲:' in n:
lyric_drop_head = text[m + 1:]
... | [
"import itertools\nimport os\nimport re\n\nimport jieba\nfrom wordcloud import WordCloud\n\n\ndef get_rhyme(f_name):\n f = open('./lyrics/' + f_name, 'r', encoding='UTF-8')\n text = f.readlines()\n f.close()\n\n '''处理开头'''\n for m, n in enumerate(text):\n if '编曲:' in n:\n lyric_drop... | false |
10,233 | 449a58836d1fffaaa465707d2f7e5caf5678a255 | #deltoid curve
#x = 2cos(theta) + cos(2theta)
#y = 2sin(theta) + sin(2theta)
#0 <= theta < 2pi
#polar plot r = f(theta)
#x = rcos(theta), y = rsin(theta)
#Galilean spiral = r=(theta)^2 for 0 <= theta < 10pi
# Fey's Function
#r = e^(cos(theta)) - 2 cos(4theta) + sin^5(theta/12)
from numpy import pi, cos, sin,... | [
"#deltoid curve\r\n#x = 2cos(theta) + cos(2theta)\r\n#y = 2sin(theta) + sin(2theta)\r\n#0 <= theta < 2pi\r\n#polar plot r = f(theta)\r\n#x = rcos(theta), y = rsin(theta)\r\n#Galilean spiral = r=(theta)^2 for 0 <= theta < 10pi\r\n# Fey's Function\r\n#r = e^(cos(theta)) - 2 cos(4theta) + sin^5(theta/12)\r\n\r\nfrom n... | false |
10,234 | 4f83c902cb8ac4afd6d1a83eb26c74f1567302f1 |
from .discriminator import Discriminator
| [
"\nfrom .discriminator import Discriminator\n",
"from .discriminator import Discriminator\n",
"<import token>\n"
] | false |
10,235 | c83e84a08e6668409441cc3ec89e0352c6ed1aee | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2019, Adam Miller (admiller@redhat.com)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
---
module: rule
short_descri... | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2019, Adam Miller (admiller@redhat.com)\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nDOCUMENTATION = \"\"\"\n---\nmodul... | false |
10,236 | 0b59b3e8721b8d251c1c79b73db8d2caa5155e63 | """ DataFiles
"""
from autodir import factory
import autofile
import autoinf
def information(ddir, file_prefix, function=None):
""" generate information DataFile
"""
def writer_(inf_obj):
if function is not None:
assert autoinf.matches_function_signature(inf_obj, function)
inf_... | [
"\"\"\" DataFiles\n\"\"\"\nfrom autodir import factory\nimport autofile\nimport autoinf\n\n\ndef information(ddir, file_prefix, function=None):\n \"\"\" generate information DataFile\n \"\"\"\n def writer_(inf_obj):\n if function is not None:\n assert autoinf.matches_function_signature(in... | false |
10,237 | 4788c86a3f78d5877fb07b415209fe9b5d8ddd34 | import numpy as np
def unpickle(file):
import cPickle
with open(file, 'rb') as fo:
dict = cPickle.load(fo)
return dict
#Exctracts 8-bit RGB image from arr of size nxm starting at i0
def extract_img(arr, n,m, i0):
im = np.zeros((n,m,3),dtype=np.uint8)
for i in range(3):
for j in r... | [
"import numpy as np\n\ndef unpickle(file):\n import cPickle\n with open(file, 'rb') as fo:\n dict = cPickle.load(fo)\n return dict\n\n\n#Exctracts 8-bit RGB image from arr of size nxm starting at i0\ndef extract_img(arr, n,m, i0):\n im = np.zeros((n,m,3),dtype=np.uint8)\n for i in range(3): \n... | false |
10,238 | c9baccb09e5ac57daef9000707807c94034c59e4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 28 2020
@author: Cassio (chmendonca)
Description: This class was created as a container to the game characteristics
and configurations
"""
from random import randint
class Settings():
"""A class that have all configurations of the game"""
def __init__(self):
... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 28 2020\n@author: Cassio (chmendonca)\nDescription: This class was created as a container to the game characteristics\nand configurations\n\"\"\"\nfrom random import randint\n\nclass Settings():\n \"\"\"A class that have all configurations of the game\"\"\"\n ... | false |
10,239 | 1c9626b5654166f6c5022d38fd8f15fbd1b46b0f | # coding=utf8
import matplotlib.pyplot as plt
import numpy as np
open,close=np.loadtxt('G:\\PythonCode\\DataBase\\000001.csv',delimiter=',',skiprows=1,usecols=(1,4),unpack=True)
change=close-open
print(change)
yesterday=change[:-1]
today=change[1:]
plt.scatter(yesterday,today,10,'r','<',alpha=0.5)
plt.show() | [
"# coding=utf8\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nopen,close=np.loadtxt('G:\\\\PythonCode\\\\DataBase\\\\000001.csv',delimiter=',',skiprows=1,usecols=(1,4),unpack=True)\nchange=close-open\nprint(change)\nyesterday=change[:-1]\ntoday=change[1:]\nplt.scatter(yesterday,today,10,'r','<',alpha=0.5)\... | false |
10,240 | 1c099dc8e0c13102164b7368b0ed091d1ee0fbe1 | import rospy
import ros_numpy
import cv2
import darknet
import math
import numpy as np
from sensor_msgs.msg import Image, PointCloud2, PointField
from std_msgs.msg import Header, String
from cv_bridge import CvBridge, CvBridgeError
from pose_detector import PoseDetector
import sensor_msgs.point_cloud2 as pc2
class Bl... | [
"import rospy\nimport ros_numpy\nimport cv2\nimport darknet\nimport math\nimport numpy as np\n\nfrom sensor_msgs.msg import Image, PointCloud2, PointField\nfrom std_msgs.msg import Header, String\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom pose_detector import PoseDetector\nimport sensor_msgs.point_cloud2 ... | true |
10,241 | 1828198d2a146d96420050f5925a8456eeb66b3a | # Lendo valores inteiros e guardando em um vetor para mostrar no final o menor valor lido
num = []
maior = 0
menor = 0
print('Insira dez números e descubra qual é o menor dentre eles!')
for c in range(0,10):
num.append(int(input('Insira um número: ')))
if c == 0:
maior = menor = num[c]
else:
... | [
"# Lendo valores inteiros e guardando em um vetor para mostrar no final o menor valor lido\nnum = []\nmaior = 0\nmenor = 0\nprint('Insira dez números e descubra qual é o menor dentre eles!')\nfor c in range(0,10):\n num.append(int(input('Insira um número: ')))\n if c == 0:\n maior = menor = num[c]\n ... | false |
10,242 | 2698d0e6904bdf38b0d10cfd2b630da2ad529e66 | # from .sgf import *
from dlgo.gosgf.sgf import Sgf_game
| [
"# from .sgf import *\nfrom dlgo.gosgf.sgf import Sgf_game\n\n",
"from dlgo.gosgf.sgf import Sgf_game\n",
"<import token>\n"
] | false |
10,243 | 63baadbcc6d44d06d30d3d752cf93e4bc8d05a46 | string = input("Enter String: ")
word_list = str.split(string.lower())
word_dict = {}
for word in word_list:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
list_of_words = sorted(word_dict.keys())
word_length = []
for word in word_dict:
word_length.append(len(word))... | [
"string = input(\"Enter String: \")\n\nword_list = str.split(string.lower())\n\nword_dict = {}\nfor word in word_list:\n if word in word_dict:\n word_dict[word] += 1\n else:\n word_dict[word] = 1\n\nlist_of_words = sorted(word_dict.keys())\n\nword_length = []\nfor word in word_dict:\n word_le... | false |
10,244 | d82ef65caf5ba2f4fe44ac09d4c179b1f19a17fc | #!/usr/bin/env python
#
# VMAccess extension
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | [
"#!/usr/bin/env python\n#\n# VMAccess extension\n#\n# Copyright 2014 Microsoft Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/L... | false |
10,245 | a89649153fa3127dc789ec79efd8c7e2e862e09e | #!/usr/bin/env python
import numpy
def estimate_norm(X):
return X.mean(axis=0), X.std(axis=0, ddof=1)
def normalize(X, norm):
return numpy.array([(k - norm[0]) / norm[1] for k in X])
| [
"#!/usr/bin/env python\n\nimport numpy\n\n\ndef estimate_norm(X):\n return X.mean(axis=0), X.std(axis=0, ddof=1)\n\n\ndef normalize(X, norm):\n return numpy.array([(k - norm[0]) / norm[1] for k in X])\n",
"import numpy\n\n\ndef estimate_norm(X):\n return X.mean(axis=0), X.std(axis=0, ddof=1)\n\n\ndef normali... | false |
10,246 | 812c892a78f9c399b48033c1c36f8780d4a2bcfa | from django import template
register = template.Library()
@register.filter()
def sweat_change(value):
try:
if value:
strlist = value.split('-',1)
class_int = strlist[0]
seat_int = strlist[1]
return '第%s试室%s号'%(class_int, seat_int)
else:
... | [
"from django import template\n\nregister = template.Library()\n\n\n@register.filter()\ndef sweat_change(value):\n try:\n if value:\n strlist = value.split('-',1)\n class_int = strlist[0]\n seat_int = strlist[1]\n return '第%s试室%s号'%(class_int, seat_int)\n ... | false |
10,247 | 6ba7c55a3c0b71d4991595aab2601ee559b347bb | import sys
import requests
def getem(key):
url = ('http://beta.content.guardianapis.com/search?'
'section=film&api-key=%s&page-size=50&page=%i')
with open('results.json', 'w') as fout:
page = 1
total = 0
while True:
r = requests.get(
url % (key, p... | [
"import sys\nimport requests\n\n\ndef getem(key):\n url = ('http://beta.content.guardianapis.com/search?'\n 'section=film&api-key=%s&page-size=50&page=%i')\n with open('results.json', 'w') as fout:\n page = 1\n total = 0\n while True:\n r = requests.get(\n ... | true |
10,248 | 1dbcbf97893eb6f6096be082f74ac14d4f7ced8e | import image
img =image.Image("img.jpg")
print(img.getWidth())
print(img.getHeight())
p = img.getPixel(45, 55)
print(p.getRed(), p.getGreen(), p.getBlue())
| [
"import image\nimg =image.Image(\"img.jpg\")\n\nprint(img.getWidth())\nprint(img.getHeight())\n\np = img.getPixel(45, 55)\nprint(p.getRed(), p.getGreen(), p.getBlue())\n",
"import image\nimg = image.Image('img.jpg')\nprint(img.getWidth())\nprint(img.getHeight())\np = img.getPixel(45, 55)\nprint(p.getRed(), p.getG... | false |
10,249 | 3d10ffaa55daab465e84eef0e313371af7c269f7 | import torch
class Memory_OnPolicy():
def __init__(self):
self.actions = []
self.states = []
self.next_states = []
self.logprobs = []
self.rewards = []
self.dones = []
def push(self, state, action, reward,next_state,done, logprob):
self.act... | [
"import torch\r\nclass Memory_OnPolicy():\r\n def __init__(self):\r\n self.actions = []\r\n self.states = []\r\n self.next_states = []\r\n self.logprobs = []\r\n self.rewards = []\r\n self.dones = []\r\n \r\n def push(self, state, action, reward,next_state,done, lo... | false |
10,250 | 9948cbc5f8bfbb4516e7d5effebdd0224d24e0f3 | #!/usr/bin/python
'''
Calculate the overall sentiment score for a review.
'''
import sys
import hashlib
def sentiment_score(text,pos_list,neg_list):
pos_score=0
neg_score=0
for w in text.split(' '):
if w in pos_list: pos_score+=1
if w in neg_list: neg_score+=1
return pos_score-neg_sco... | [
"#!/usr/bin/python\n\n'''\nCalculate the overall sentiment score for a review.\n'''\nimport sys\nimport hashlib\n\ndef sentiment_score(text,pos_list,neg_list):\n pos_score=0\n neg_score=0\n\n for w in text.split(' '):\n if w in pos_list: pos_score+=1\n if w in neg_list: neg_score+=1\n retu... | true |
10,251 | 581d1b9e6cd9df5fb1fdae1bcc26818938f5906d | import os
from datetime import datetime
from nest_py.core.db.sqla_resources import JobsSqlaResources
from nest_py.nest_envs import ProjectEnv, RunLevel
from nest_py.ops.nest_sites import NestSite
def generate_db_config(project_env=None, runlevel=None):
if project_env is None:
project_env = ProjectEnv.hel... | [
"import os\n\nfrom datetime import datetime\n\nfrom nest_py.core.db.sqla_resources import JobsSqlaResources\nfrom nest_py.nest_envs import ProjectEnv, RunLevel\nfrom nest_py.ops.nest_sites import NestSite\n\ndef generate_db_config(project_env=None, runlevel=None):\n if project_env is None:\n project_env =... | false |
10,252 | 4771fc205e78947925bfa7bcbf45e44114836226 | from flask import Flask, render_template, flash, request, redirect, url_for, session, send_file
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
import sendgrid
import os
users = 0
class ContactForm(Form):
name = TextField('Full Name', validators=[validators.DataRequired()], r... | [
"from flask import Flask, render_template, flash, request, redirect, url_for, session, send_file\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\nimport sendgrid\nimport os\n\nusers = 0\n\nclass ContactForm(Form):\n\tname = TextField('Full Name', validators=[validators.Data... | false |
10,253 | 2a6abf28c23a925b8cc02621b5210a579cfe65de | # Generated by Django 2.0.4 on 2018-06-25 10:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('postcontent', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='author',
name='slug',
f... | [
"# Generated by Django 2.0.4 on 2018-06-25 10:42\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('postcontent', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='author',\n name='s... | false |
10,254 | a07ef98502948a5cbb1a306bf65d80b256eaf28c |
import dynet as dy
import Saxe
import numpy as np
class MLP:
""" MLP with 1 hidden Layer """
def __init__(self, model, input_dim, hidden_dim, output_dim, dropout = 0, softmax=False):
self.input = input_dim
self.hidden = hidden_dim
self.output = output_dim
self.dropout = dropo... | [
"\nimport dynet as dy\nimport Saxe\nimport numpy as np\n\nclass MLP:\n \"\"\" MLP with 1 hidden Layer \"\"\"\n\n def __init__(self, model, input_dim, hidden_dim, output_dim, dropout = 0, softmax=False):\n\n self.input = input_dim\n self.hidden = hidden_dim\n self.output = output_dim\n ... | false |
10,255 | 0181084a016f075cd0626db2522e0cd12accecdd | import numpy as np
file_data = np.loadtxt('./data/final1.csv',delimiter=',')
# Using Min - Max normalisation
data =[]
final_data= []
target_data = []
valmean_nor = ((file_data[:,0]) - min(file_data[:,0]))/(max(file_data[:,0]) - min(file_data[:,0]))
valmax_nor = ((file_data[:,1]) - min(file_data[:,1]))/(max(file_da... | [
"import numpy as np\n\n\nfile_data = np.loadtxt('./data/final1.csv',delimiter=',')\n\n# Using Min - Max normalisation\n\ndata =[]\nfinal_data= []\ntarget_data = []\n\nvalmean_nor = ((file_data[:,0]) - min(file_data[:,0]))/(max(file_data[:,0]) - min(file_data[:,0]))\nvalmax_nor = ((file_data[:,1]) - min(file_data[:,... | false |
10,256 | e9100720fc706803ca5208c335a4a3b2ef5044c2 | from typing import List
from django.urls import (path, URLPattern)
from . import views
urlpatterns: List[URLPattern] = [
path(route='', view=views.StaffView.as_view(), name='staff'),
path(route='products/', view=views.ProductListView.as_view(), name='product-list'),
path(route='create/', view=views.Produ... | [
"from typing import List\n\nfrom django.urls import (path, URLPattern)\n\nfrom . import views\n\nurlpatterns: List[URLPattern] = [\n path(route='', view=views.StaffView.as_view(), name='staff'),\n path(route='products/', view=views.ProductListView.as_view(), name='product-list'),\n path(route='create/', vi... | false |
10,257 | 46e3803cdc972f8411c14ac338e5ff0eb84e8023 | __author__ = 'wangqiushi'
| [
"__author__ = 'wangqiushi'\n",
"<assignment token>\n"
] | false |
10,258 | 555063bb8c1fa7a0c857f88f1a034a7fda00d56d | import pandas as pd
import numpy as np
import os
import pickle
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Model, load_model
from azure_stt import speech_to_text
from google_tts import text_to_audio
from text_analytics import keyword_ext... | [
"import pandas as pd\nimport numpy as np\nimport os\nimport pickle\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Model, load_model\nfrom azure_stt import speech_to_text\nfrom google_tts import text_to_audio\nfrom text_analytics impo... | false |
10,259 | 82fa4a87b4d8cfc45577bc519f62d06b7369b242 | # Generated by Django 3.0.2 on 2020-08-04 15:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exam', '0002_profile'),
]
operations = [
migrations.AddField(
model_name='profile',
name='About_me',
... | [
"# Generated by Django 3.0.2 on 2020-08-04 15:04\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('exam', '0002_profile'),\r\n ]\r\n\r\n operations = [\r\n migrations.AddField(\r\n model_name='profile',\... | false |
10,260 | af39fa086691c48f157863c791e3f07b96152fc6 |
# def TwoSum(nums:list,target):
# nums.sort()
# begin = 0
# end = len(nums) - 1
# while begin < end:
# sum = nums[begin] + nums[end]
# if sum== target:
# print(begin,end)
# begin += 1
# end -= 1
# else:
# if sum < target:
# ... | [
"\n# def TwoSum(nums:list,target):\n# nums.sort()\n# begin = 0\n# end = len(nums) - 1\n# while begin < end:\n# sum = nums[begin] + nums[end]\n# if sum== target:\n# print(begin,end)\n# begin += 1\n# end -= 1\n# else:\n# if sum <... | false |
10,261 | 3413c8d24d8d411f98a9d1148b47d3f8dab32ffc | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import configparser
from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters
import wiki2txt
import web_browser
import holiday
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport logging\nimport configparser\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler, Filters\n\nimport wiki2txt\nimport web_browser\nimport holiday\n\nlogging.basicConfig(format='%(asctime)s - %(nam... | false |
10,262 | a15c714afa5ecd3bb7424db44f82a620602c6963 | import requests
url = 'https://ipinfo.io'
username = ''
password = ''
proxy = f'socks5h://{username}:{password}@gate.smartproxy.com:7000'
response = requests.get(url, proxies= {'http': proxy, 'https': proxy})
print(response.text)
| [
"import requests\n\nurl = 'https://ipinfo.io'\nusername = ''\npassword = ''\n\nproxy = f'socks5h://{username}:{password}@gate.smartproxy.com:7000'\n \nresponse = requests.get(url, proxies= {'http': proxy, 'https': proxy})\n\nprint(response.text)\n",
"import requests\nurl = 'https://ipinfo.io'\nusername = ''\npas... | false |
10,263 | fcaf05a0f83ee78a37ca9726e1c111597fce6dfc | from models.usuario import UsuarioModel
import bcrypt
class Usuario(object):
def __init__(self, id, username):
self.id = id
self.username=username
def __str__(self):
return "Usuario(id='%s')" % self.id
# return "Usuario(id='{}')".format(self.id)
def autenticacion(username, pass... | [
"from models.usuario import UsuarioModel\nimport bcrypt\n\nclass Usuario(object):\n def __init__(self, id, username):\n self.id = id\n self.username=username\n def __str__(self):\n return \"Usuario(id='%s')\" % self.id\n # return \"Usuario(id='{}')\".format(self.id)\n\ndef autentic... | false |
10,264 | d47d487cd3213f98980041ebb22d33dc2b58baed | #!/usr/bin/python3
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import pyautogui
#import random
from random import randint
import cv2
import h5py
import numpy as np
from matplotlib import pyplot as plt
from pylab import *
from tkinter import messagebox
from matplotlib.backends.backend_t... | [
"#!/usr/bin/python3\n\nimport tkinter as tk\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\nimport pyautogui\n#import random\nfrom random import randint\nimport cv2\nimport h5py\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom pylab import *\nfrom tkinter import messagebox\n\nfrom matplotli... | false |
10,265 | b30cc79dd8f7db6001158bef66aeee89e1d60558 | # -*- coding: utf-8 -*-
"""Plant disease detection
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1p_O39hjZ9J9CzX2lDWWqH_rNa8cp-mg1
"""
from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizer... | [
"# -*- coding: utf-8 -*-\n\"\"\"Plant disease detection\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1p_O39hjZ9J9CzX2lDWWqH_rNa8cp-mg1\n\"\"\"\n\nfrom keras import applications\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom ... | false |
10,266 | 4273e7dcdb038ff83a89e785b34b217509b3a4ce | #20微巴斯卡=0分貝,定義為v0;此式代表多少微巴斯卡=多少分貝
import numpy as np
print(20*np.log10(20000/20))
#分貝=20log10(微巴斯卡/20)
print((10**(30/20+np.log10(20)))/(10**(50/20+np.log10(20))))
| [
"#20微巴斯卡=0分貝,定義為v0;此式代表多少微巴斯卡=多少分貝\nimport numpy as np\nprint(20*np.log10(20000/20))\n#分貝=20log10(微巴斯卡/20)\nprint((10**(30/20+np.log10(20)))/(10**(50/20+np.log10(20))))\n",
"import numpy as np\nprint(20 * np.log10(20000 / 20))\nprint(10 ** (30 / 20 + np.log10(20)) / 10 ** (50 / 20 + np.log10(20)))\n",
"<import ... | false |
10,267 | 092bb2ec1e09147f69e251597c8b141471429784 | import sys
import numpy as np
import numpy.linalg as la
import pandas as pd
import patsy
import statsmodels.api as sm
from feature_selection_utils import select_features_by_variation
from sklearn.feature_selection import mutual_info_regression
from sklearn.preprocessing import StandardScaler
# Auxiliary functions of... | [
"import sys\n\nimport numpy as np\nimport numpy.linalg as la\nimport pandas as pd\nimport patsy\nimport statsmodels.api as sm\nfrom feature_selection_utils import select_features_by_variation\nfrom sklearn.feature_selection import mutual_info_regression\nfrom sklearn.preprocessing import StandardScaler\n\n\n# Auxil... | false |
10,268 | 0b1b8da0467298471c3f9487b753c801a3c6f514 | import pymssql #引入pymssql模块
import xlwt
##==============写入第一个数据库10.42.90.92========================
connect = pymssql.connect('10.42.90.92', 'fis', 'fis', 'cab') #服务器名,账户,密码,数据库名
print("连接10.42.90.92成功!")
crsr = connect.cursor()
# select name from sysobjects where xtype='u'
# select * from sys.tables
#查询全部表名称
# cu... | [
"import pymssql #引入pymssql模块\nimport xlwt\n\n##==============写入第一个数据库10.42.90.92========================\nconnect = pymssql.connect('10.42.90.92', 'fis', 'fis', 'cab') #服务器名,账户,密码,数据库名\n\nprint(\"连接10.42.90.92成功!\")\ncrsr = connect.cursor() \n# select name from sysobjects where xtype='u'\n# select * from sys.tables... | false |
10,269 | d64480d370113edf14f7fda9f9551604af779439 | from django.conf.urls import url
from django.conf import settings
from .views import fill_clients, fill_accounts, fill_account_analytics, fill_products, fill_product_analytics, fill_product_track_record_evolution, fill_account_track_record_composition, fill_account_track_record_evolution
urlpatterns = [
url(r'^cl... | [
"from django.conf.urls import url\nfrom django.conf import settings\n\nfrom .views import fill_clients, fill_accounts, fill_account_analytics, fill_products, fill_product_analytics, fill_product_track_record_evolution, fill_account_track_record_composition, fill_account_track_record_evolution\n\nurlpatterns = [\n ... | false |
10,270 | f5c41d4c9a974da27a39e1f6936f2895c7a9f447 | n=int(input())
ss=input()
a=[int(i) for i in ss.split(' ')]
h=[0 for i in range(100)]
t=-1
for i in range(n):
t=max(a[i],t)
h[a[i]]+=1
ans=0
while n:
cnt=0
for i in range(t+1):
while h[i] and i>=cnt:
h[i]-=1
cnt+=1
n-=1
ans+=1
print(ans) | [
"n=int(input())\nss=input()\na=[int(i) for i in ss.split(' ')]\nh=[0 for i in range(100)]\nt=-1\nfor i in range(n):\n t=max(a[i],t)\n h[a[i]]+=1\nans=0\nwhile n:\n cnt=0\n for i in range(t+1):\n while h[i] and i>=cnt:\n h[i]-=1\n cnt+=1\n n-=1\n ans+=1\nprint(a... | false |
10,271 | 259b25eee48c1670e3c28d70b663a5123574d66f | # coding=utf-8
import random
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlSlemProductfamilie(KeuzelijstField):
"""De mogelijke productfami... | [
"# coding=utf-8\nimport random\nfrom OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField\nfrom OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde\n\n\n# Generated with OTLEnumerationCreator. To modify: extend, do not edit\nclass KlSlemProductfamilie(KeuzelijstField):\n \"\"\"De mogel... | false |
10,272 | 73d2b2cba0c76020cbd22b2783b7eeeec9f0123a | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-11 15:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('originacion', '0004_rvgl'),
]
operations = [
migrations.AddField(
... | [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.9.2 on 2016-03-11 15:36\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('originacion', '0004_rvgl'),\n ]\n\n operations = [\n migrations.A... | false |
10,273 | 9481b4b2f24b440fb01e863d8bd44e1c760dcaed | d = "Привет!".upper()
print(d)
e = "Hallo!".replace("a", "@")
print(e)
| [
"d = \"Привет!\".upper()\nprint(d)\ne = \"Hallo!\".replace(\"a\", \"@\")\nprint(e)\n",
"d = 'Привет!'.upper()\nprint(d)\ne = 'Hallo!'.replace('a', '@')\nprint(e)\n",
"<assignment token>\nprint(d)\n<assignment token>\nprint(e)\n",
"<assignment token>\n<code token>\n<assignment token>\n<code token>\n"
] | false |
10,274 | e999d8d23215c6b2bece36753f107be96af9e855 | ################################################################################
# MIT License
#
# Copyright (c) 2017 Jean-Charles Fosse & Johann Bigler
#
# 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 t... | [
"################################################################################\n# MIT License\n#\n# Copyright (c) 2017 Jean-Charles Fosse & Johann Bigler\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\"), t... | false |
10,275 | 4aea5ce6c195f5b9a72299166118bb96c984b8a5 | #importing serial module(need pyserial)
import serial
try:
arduino = serial.Serial(timeout = 1, baudrate = 9600)
except:
print('Check port')
rawData = []
def clean(L):
newl = []
for i in range(len(L)):
temp = L[i][2:]
newl.append(temp[:-5])
return newl
cleanData = clean(rawData)
#write t... | [
"#importing serial module(need pyserial)\nimport serial\n\ntry:\n arduino = serial.Serial(timeout = 1, baudrate = 9600)\nexcept:\n print('Check port')\n \nrawData = []\n\ndef clean(L):\n newl = []\n \n for i in range(len(L)):\n temp = L[i][2:]\n newl.append(temp[:-5])\n return newl\n\ncleanData = c... | false |
10,276 | 623037c96b2a2f97fc218432c5621c311986dfd1 | from PIL import Image
import re
import os
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def add_thumbnail(self, image_path, size):
image = Image.open(os.getcwd() + "/" + image_path)
name = re.search('(?<=\/)\w+', image_path).group(0)
... | [
"from PIL import Image\nimport re\nimport os\n\nclass Product:\n def __init__(self, name, price):\n self.name = name\n self.price = price\n\n \n def add_thumbnail(self, image_path, size):\n image = Image.open(os.getcwd() + \"/\" + image_path)\n name = re.search('(?<=\\/)\\w+', i... | false |
10,277 | dcdfe6937f33fb444aab8dce19cad7cfe91bb210 | import openpyxl,os
wb = openpyxl.Workbook()
print(wb.sheetnames)
sheet = wb['Sheet']
sheet['A1'] = 32
sheet['A2'] = 'hello'
wb.save('example2.xlsx')
sheet2= wb.create_sheet()
print(wb.sheetnames) | [
"import openpyxl,os\nwb = openpyxl.Workbook()\n\nprint(wb.sheetnames)\nsheet = wb['Sheet']\n\nsheet['A1'] = 32\nsheet['A2'] = 'hello'\nwb.save('example2.xlsx')\n\nsheet2= wb.create_sheet()\nprint(wb.sheetnames)",
"import openpyxl, os\nwb = openpyxl.Workbook()\nprint(wb.sheetnames)\nsheet = wb['Sheet']\nsheet['A1'... | false |
10,278 | b12cd6667c8de6dde35f1f00442b1cba0e965caf | #!flask/bin/python3.7
from flask import Flask, jsonify, abort, make_response
app = Flask(__name__)
devices = [
{
'id': 1,
'description': u'Keith\'s Desktop',
'ip': u'192.168.1.182'
},
{
'id': 2,
'description': u'Keith\'s Macbook Air',
'ip': u'192.168.1.15'
... | [
"#!flask/bin/python3.7\nfrom flask import Flask, jsonify, abort, make_response\n\napp = Flask(__name__)\n\ndevices = [\n {\n 'id': 1,\n 'description': u'Keith\\'s Desktop',\n 'ip': u'192.168.1.182'\n },\n {\n 'id': 2,\n 'description': u'Keith\\'s Macbook Air',\n 'i... | false |
10,279 | 8b9f86094b652776ede67f32117440ed8f456b47 | import torch
from pyro.distributions import (
Independent, RelaxedBernoulliStraightThrough
)
from pyro.distributions.torch import RelaxedOneHotCategorical # noqa: F401
from torch import nn
from torch.distributions.utils import clamp_probs, broadcast_all
from counterfactualms.distributions.deep import DeepCondition... | [
"import torch\nfrom pyro.distributions import (\n Independent, RelaxedBernoulliStraightThrough\n)\nfrom pyro.distributions.torch import RelaxedOneHotCategorical # noqa: F401\nfrom torch import nn\nfrom torch.distributions.utils import clamp_probs, broadcast_all\nfrom counterfactualms.distributions.deep import D... | false |
10,280 | c05e4d33ed802cdc74d3a432417e3b66ed042dad | #!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | [
"#!/usr/bin/python\n#\n# Copyright 2018-2022 Polyaxon, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless requir... | false |
10,281 | c0aaacb3f6961f5b6d12b6aacc2eb9a4bf2f6827 | import pytest
from twindb_backup.destination.gcs import GCS
@pytest.fixture
def gs():
return GCS(
bucket='test-bucket',
gc_credentials_file='foo'
)
| [
"import pytest\n\nfrom twindb_backup.destination.gcs import GCS\n\n\n@pytest.fixture\ndef gs():\n return GCS(\n bucket='test-bucket',\n gc_credentials_file='foo'\n )\n",
"import pytest\nfrom twindb_backup.destination.gcs import GCS\n\n\n@pytest.fixture\ndef gs():\n return GCS(bucket='test-b... | false |
10,282 | 5be342f5a24437ec1570b44ce54b473e38229646 | def dupfiles_count(input_dict):
count = 0
for val in input_dict.values():
count += len(val)
return count
| [
"def dupfiles_count(input_dict):\n count = 0\n for val in input_dict.values():\n count += len(val)\n return count\n",
"<function token>\n"
] | false |
10,283 | 945db3ea014f4828af2a1a58fbb1db491cbe30a7 | lat = 51
lon = 4
startyear = 2015
endyear = 2015
angle = 0
aspect = 0
optimalangles = 0
outputformat = "json" | [
"lat = 51\nlon = 4\nstartyear = 2015\nendyear = 2015\nangle = 0\naspect = 0\noptimalangles = 0\noutputformat = \"json\"",
"lat = 51\nlon = 4\nstartyear = 2015\nendyear = 2015\nangle = 0\naspect = 0\noptimalangles = 0\noutputformat = 'json'\n",
"<assignment token>\n"
] | false |
10,284 | e621363a0bb29ba95b102bf0409b4afe27b35c1d | import functions
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib import colors as mcolors
def legendre(a,p):
return functions.fast_power(a, (p-1)//2, p)
def jacobi(a,n):
# print(a, n)
if n <= 0 or n % 2 == 0:
return -2 # Undefined
re... | [
"import functions\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nfrom matplotlib import colors as mcolors\n\n\ndef legendre(a,p):\n return functions.fast_power(a, (p-1)//2, p)\n\n\ndef jacobi(a,n):\n # print(a, n)\n if n <= 0 or n % 2 == 0:\n return -2 ... | false |
10,285 | b7bfdfe671f8683f56f0194a730ef8da49c4452b | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright 2018-2020 ARM Limited or its affiliates
#
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ----------------------------------------------------------------------------\n# Copyright 2018-2020 ARM Limited or its affiliates\n#\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use t... | false |
10,286 | 53a0d0204591653bd13a6b392e1f2b8d138df8ab | '''
Python wrapper for libgtpnl
'''
from ctypes import CDLL,c_int,c_uint16,c_char_p,c_void_p
from ctypes import pointer,byref
from socket import socket,inet_aton,AF_INET,SOCK_DGRAM,AF_NETLINK # IPv4
from struct import unpack
from .gtpsock import GtpSocket
from .structures import *
import logging
from time import slee... | [
"'''\nPython wrapper for libgtpnl\n'''\n\nfrom ctypes import CDLL,c_int,c_uint16,c_char_p,c_void_p\nfrom ctypes import pointer,byref\nfrom socket import socket,inet_aton,AF_INET,SOCK_DGRAM,AF_NETLINK # IPv4\nfrom struct import unpack\nfrom .gtpsock import GtpSocket\nfrom .structures import *\nimport logging\n\nfrom... | false |
10,287 | cdb78a8996cd517f5f49d5a6e5faca73b5d94033 | from django.core.management.base import NoArgsCommand
import pdb
class Command(NoArgsCommand):
def handle_noargs(self, **options):
'''
deletes all keys from given keyring
'''
from onboarding.interactive_brokers import encryption as encr
from onboarding.interactive_brokers i... | [
"from django.core.management.base import NoArgsCommand\nimport pdb\n\nclass Command(NoArgsCommand):\n def handle_noargs(self, **options):\n '''\n deletes all keys from given keyring\n '''\n\n from onboarding.interactive_brokers import encryption as encr\n from onboarding.intera... | false |
10,288 | 44e86828ff8acb96a1d1c2dd4c2cef5d5eff25ac | """
You can call the function find_largest_water_body by passing in a 2D matrix of 0s and 1s as an argument. The function
will return the size of the largest water body in the matrix.
Here's a Python solution that uses a recursive approach to find the largest water body in a 2D matrix of 0s and 1s:
"""
def _wbs(i, j... | [
"\"\"\"\nYou can call the function find_largest_water_body by passing in a 2D matrix of 0s and 1s as an argument. The function\nwill return the size of the largest water body in the matrix.\n\nHere's a Python solution that uses a recursive approach to find the largest water body in a 2D matrix of 0s and 1s:\n\"\"\"... | false |
10,289 | 93c34b54593993816f83802353ce8a334a546b45 | from django.db import models
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
class Manufacturer(models.Model):
ManID = models.IntegerField(primary_key=True, serialize=True)
Name = models.CharField(max_length=255)
def __str__(self):
return self.Name
... | [
"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.sessions.models import Session\n\n\nclass Manufacturer(models.Model):\n ManID = models.IntegerField(primary_key=True, serialize=True)\n Name = models.CharField(max_length=255)\n def __str__(self):\n retur... | false |
10,290 | 2e96d36b19fd9aef031c0dd18853d01730ef7b12 | import csv
import numpy as np
import cv2
def run():
with open("./data_base.csv") as file:
n_cols = len(file.readline().split(";"))
print(n_cols)
X = np.loadtxt("./data_base.csv", delimiter=";", usecols=np.arange(0, n_cols - 1))
Y = np.loadtxt("./data_base.csv", delimiter=";", usecols=n_c... | [
"import csv\nimport numpy as np\nimport cv2\n\n\ndef run():\n\n with open(\"./data_base.csv\") as file:\n n_cols = len(file.readline().split(\";\"))\n print(n_cols)\n\n X = np.loadtxt(\"./data_base.csv\", delimiter=\";\", usecols=np.arange(0, n_cols - 1))\n Y = np.loadtxt(\"./data_base.csv\",... | false |
10,291 | 584944ea2122fcffe7c72f8df3922aeb2765eba7 | # 6-11. Cities: Make a dictionary called cities. Use the names of three
# cities as keys in your dictionary. Create a dictionary of information about
# each city and include the country that the city is in, its approximate
# population, and one fact about that city. The keys for each city’s
# dictionary should be somet... | [
"# 6-11. Cities: Make a dictionary called cities. Use the names of three\n# cities as keys in your dictionary. Create a dictionary of information about\n# each city and include the country that the city is in, its approximate\n# population, and one fact about that city. The keys for each city’s\n# dictionary should... | false |
10,292 | 237b38605e007edfa0e25cc0cd68534073a15c66 | # -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2017, Battelle Memorial Institute.
#
# 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... | [
"# -*- coding: utf-8 -*- {{{\n# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:\n#\n# Copyright 2017, Battelle Memorial Institute.\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\... | false |
10,293 | bcd750a204aef76f974e22121ebcf33221b908c5 | index = 0
fruits = ["apple", "mango", "strawberry", "grapes", "pear", "kiwi", "orange", "banana"]
print(fruits)
print(len(fruits))
while index < len(fruits): # while loop goes on executing until the condition inside it is satisfied
fruit_new = fruits[index]
print(index)
print(fruit_new)
index = index ... | [
"index = 0\nfruits = [\"apple\", \"mango\", \"strawberry\", \"grapes\", \"pear\", \"kiwi\", \"orange\", \"banana\"]\nprint(fruits)\nprint(len(fruits))\n\nwhile index < len(fruits): # while loop goes on executing until the condition inside it is satisfied\n fruit_new = fruits[index]\n print(index)\n print(... | false |
10,294 | c62458e4e7ea2b87068c4172bcabed4f1c48bdc8 | INPUT = {
4: ['Masters', 'Doctorate', 'Prof-school'],
6: ['HS-grad'],
3: ['Bachelor']
}
wynik = {}
for key, value in INPUT.items():
for education in value:
wynik[education] = str(key)
## Alternatywnie:
#
# wynik = {education: str(key)
# for key, value in EDUCATION_GROUPS.items()
# ... | [
"INPUT = {\n 4: ['Masters', 'Doctorate', 'Prof-school'],\n 6: ['HS-grad'],\n 3: ['Bachelor']\n}\n\nwynik = {}\n\nfor key, value in INPUT.items():\n for education in value:\n wynik[education] = str(key)\n\n## Alternatywnie:\n#\n# wynik = {education: str(key)\n# for key, value in EDUCATION_GROU... | false |
10,295 | 1534cc3b4c6f1554213512f16738b57f0d77b41e | age = int(input('나이 입력: '))
if (age >= 60):
print('30% 요금 할인대상입니다')
cost = 14000*0.7
elif (age <= 10):
print('20% 요금할인 대상입니다')
cost = 14000*0.8
else:
print('요금할인 대상이 아닙니다')
cost = 14000
print('요금: ' + str(int(cost)))
| [
"age = int(input('나이 입력: '))\r\n\r\nif (age >= 60):\r\n print('30% 요금 할인대상입니다')\r\n cost = 14000*0.7\r\nelif (age <= 10):\r\n print('20% 요금할인 대상입니다')\r\n cost = 14000*0.8\r\nelse:\r\n print('요금할인 대상이 아닙니다')\r\n cost = 14000\r\nprint('요금: ' + str(int(cost)))\r\n",
"age = int(input('나이 입력: '))\nif... | false |
10,296 | 28ed2f4c981db5cb41aa51dc691285b4c64086d8 | import FWCore.ParameterSet.Config as cms
process = cms.Process("Gen")
process.load("FWCore.MessageService.MessageLogger_cfi")
# control point for all seeds
#
process.load("Configuration.StandardSequences.SimulationRandomNumberGeneratorSeeds_cff")
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
# physics eve... | [
"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"Gen\")\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\n# control point for all seeds\n#\nprocess.load(\"Configuration.StandardSequences.SimulationRandomNumberGeneratorSeeds_cff\")\n\nprocess.load(\"SimGeneral.HepPDTESSource.pythiapdt... | false |
10,297 | efc631f75aa1b4780fef1ec559d0ff439818e95a | from django.urls import path
from backend.reviews import views
urlpatterns = [
path('', views.ListReviews.as_view(), name="list_review"),
path('add/', views.AddReview.as_view(), name="add_review")
# api
# path('add/', views.AddReview.as_view()),
# path('all/', views.AllReviews.as_view()),
# pat... | [
"from django.urls import path\nfrom backend.reviews import views\n\nurlpatterns = [\n path('', views.ListReviews.as_view(), name=\"list_review\"),\n path('add/', views.AddReview.as_view(), name=\"add_review\")\n # api\n # path('add/', views.AddReview.as_view()),\n # path('all/', views.AllReviews.as_v... | false |
10,298 | b5623cad90b2c4d14a2a7a505665abe6c953662e | import numpy
n = int(input())
array_a = []
array_b = []
for i in range(n):
a = list(map(int, input().split()))
array_a.append(a)
for i in range(n):
b = list(map(int, input().split()))
array_b.append(b)
array_a = numpy.array(array_a)
array_b = numpy.array(array_b)
print(numpy.dot(array_a, array_b))
| [
"import numpy\nn = int(input())\narray_a = []\narray_b = []\nfor i in range(n):\n a = list(map(int, input().split()))\n array_a.append(a)\n\nfor i in range(n):\n b = list(map(int, input().split()))\n array_b.append(b)\n\narray_a = numpy.array(array_a)\narray_b = numpy.array(array_b)\nprint(numpy.dot(arr... | false |
10,299 | a1ffa9403118d9afcb718525da331082d0932e6d | async def herro(*args):
return await dnd_bot.say("herro dere") | [
"async def herro(*args):\r\n\treturn await dnd_bot.say(\"herro dere\")",
"async def herro(*args):\n return await dnd_bot.say('herro dere')\n",
"<code token>\n"
] | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.