index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
2,400 | cbf93eb96f40ff0aedc4b8d9238669da72934b27 | import time
from helpers.handler import port_handler
from helpers.functions import fetch_all
class ascii_handler(port_handler):
"""
Serve ASCII server list
"""
def handle_data(self):
"""
Show a nicely formatted server list and immediately close connection
"""
self.ls.... | [
"import time\n\nfrom helpers.handler import port_handler\nfrom helpers.functions import fetch_all\n\n\nclass ascii_handler(port_handler):\n \"\"\"\n Serve ASCII server list\n \"\"\"\n\n def handle_data(self):\n \"\"\"\n Show a nicely formatted server list and immediately close connection\n... | false |
2,401 | 19d86c64876575ed9b3f5e33dd44e7633c96e696 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2014 Elico Corp. All Rights Reserved.
# Alex Duan <alex.duan@elico-corp.com>
#
# This program is free software: you can redistribute it and... | [
"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (c) 2010-2014 Elico Corp. All Rights Reserved.\n# Alex Duan <alex.duan@elico-corp.com>\n#\n# This program is free software: you can redistr... | false |
2,402 | a7099b2506de08893ca849146813505d88784895 | #!/usr/bin/python3
#https://github.com/pfnet-research/chainer-gan-lib/blob/master/wgan_gp/updater.py
import numpy as np
import chainer
import chainer.functions as F
from chainer import Variable
from chainer.dataset import convert
class WGANUpdater(chainer.training.updaters.StandardUpdater):
def __init__(self, *a... | [
"#!/usr/bin/python3\n#https://github.com/pfnet-research/chainer-gan-lib/blob/master/wgan_gp/updater.py\n\nimport numpy as np\nimport chainer\nimport chainer.functions as F\nfrom chainer import Variable\nfrom chainer.dataset import convert\n\nclass WGANUpdater(chainer.training.updaters.StandardUpdater):\n\n def _... | false |
2,403 | cb904408486ad9ea8cc0c8ff2ec393e480309a57 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... | [
"# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n#\n# This work is licensed under the Creative Commons Attribution-NonCommercial\n# 4.0 International License. To view a copy of this license, visit\n# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to\n# Creative Commons, PO Box 1866,... | false |
2,404 | e30aaf1616a107662924da3671b179a1887974f7 | from flask import render_template, request, redirect, url_for, send_file
from flask_app import app
import re
import os
from werkzeug.utils import secure_filename
import numpy as np
import cv2 as cv
from flask_mail import Message, Mail
file_path_file = open('flask_app/file_path.txt', 'r')
vars = file_path_file.readline... | [
"from flask import render_template, request, redirect, url_for, send_file\nfrom flask_app import app\nimport re\nimport os\nfrom werkzeug.utils import secure_filename\nimport numpy as np\nimport cv2 as cv\nfrom flask_mail import Message, Mail\n\nfile_path_file = open('flask_app/file_path.txt', 'r')\nvars = file_pat... | false |
2,405 | d4361b169bf75d3af82eca3d26609961ccc2f27e | from find import Solution
array = [[1,2,3],[4,5,6],[7,8,9]]
solution = Solution.Find(6,array) | [
"from find import Solution\n\n\narray = [[1,2,3],[4,5,6],[7,8,9]]\n\nsolution = Solution.Find(6,array)",
"from find import Solution\narray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nsolution = Solution.Find(6, array)\n",
"<import token>\narray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nsolution = Solution.Find(6, array)\n"... | false |
2,406 | 74faeb1c09fe136ec4d9578173aeebe54b451e33 | from .import bp as authentication
from app import db
from flask import current_app as app, render_template, request, redirect, url_for, flash, session
from flask_login import login_user, logout_user, current_user, login_required
from .forms import Register, Login, Settings
from .models import User
# route for register... | [
"from .import bp as authentication\nfrom app import db\nfrom flask import current_app as app, render_template, request, redirect, url_for, flash, session\nfrom flask_login import login_user, logout_user, current_user, login_required\nfrom .forms import Register, Login, Settings\nfrom .models import User\n\n# route ... | false |
2,407 | 743aa4ccbb9a131b5ef3d04475789d3d1da1a2fa | # coding:utf-8
from flask_sqlalchemy import SQLAlchemy
from config.manager import app
from config.db import db
class Category(db.Model):
__tablename__ = 'category'
id = db.Column(db.Integer, primary_key=True) # 编号
name = db.Column(db.String(20), nullable=False) # 账号
addtime = db.Column(db.DateTime, ... | [
"# coding:utf-8\nfrom flask_sqlalchemy import SQLAlchemy\nfrom config.manager import app\nfrom config.db import db\n\n\nclass Category(db.Model):\n __tablename__ = 'category'\n id = db.Column(db.Integer, primary_key=True) # 编号\n name = db.Column(db.String(20), nullable=False) # 账号\n addtime = db.Colum... | false |
2,408 | 418f2e1cbe4fb3ef369e981e72bf40eeddfd052e | import torch.nn as nn
def my_loss():
return nn.CrossEntropyLoss() | [
"import torch.nn as nn\n\ndef my_loss():\n return nn.CrossEntropyLoss()",
"import torch.nn as nn\n\n\ndef my_loss():\n return nn.CrossEntropyLoss()\n",
"<import token>\n\n\ndef my_loss():\n return nn.CrossEntropyLoss()\n",
"<import token>\n<function token>\n"
] | false |
2,409 | 66b42791325a53172d4514cdd16ccd58d4edb186 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
class Gerenciador(ScreenManager):
pass
class Menu(Screen):
pass
class Tarefas(Screen):
def __init__(self, tarefas=[], **kwargs):
super().__init__(**kwargs)
for tar... | [
"from kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.screenmanager import ScreenManager, Screen\n\n\nclass Gerenciador(ScreenManager):\n pass\n\nclass Menu(Screen):\n pass\n \nclass Tarefas(Screen):\n def __init__(self, tarefas=[], **kwargs):\n super().__init__(**kwarg... | false |
2,410 | 0354445d255cc79d3cb9242f82d37e035ff61788 | /Users/jhajhajhajha1/anaconda/lib/python3.6/codecs.py | [
"/Users/jhajhajhajha1/anaconda/lib/python3.6/codecs.py"
] | true |
2,411 | c46495eebbe796253f56b7472d5548b41c5d0bc4 | def part_1() -> int:
start = 382345
end = 843167
total = 0
for number in range(start, end + 1):
if check_number(str(number)):
total += 1
return total
def check_number(problem_input: str) -> bool:
previous = 0
double = False
for current in range(1, len(problem_inpu... | [
"def part_1() -> int:\n start = 382345\n end = 843167\n total = 0\n\n for number in range(start, end + 1):\n if check_number(str(number)):\n total += 1\n\n return total\n\n\ndef check_number(problem_input: str) -> bool:\n previous = 0\n double = False\n for current in range... | false |
2,412 | 1c5ca920fe1f116a5bc52c9e5c53c13b1e1c925f | def tobin(n):
bin = "";
while(n/2!=0):
if n%2==0:
bin = bin + "0"
else:
bin = bin + "1"
if n%2==1:
bin = bin + "1"
return bin
n = int(input())
bin = tobin(5)
print(bin)
| [
"def tobin(n):\r\n bin = \"\";\r\n while(n/2!=0):\r\n if n%2==0:\r\n bin = bin + \"0\"\r\n else:\r\n bin = bin + \"1\"\r\n if n%2==1:\r\n bin = bin + \"1\"\r\n return bin\r\n\r\nn = int(input())\r\nbin = tobin(5)\r\nprint(bin)\r\n",
"def tobin(n):\n bin = ... | false |
2,413 | f193094c551df2a32860948b1a8710b53ca0dfb6 | import random
#quicksort a list of objects based on keys, which can be any of 3 values
# done in O(n) time in one pass, and O(1) additional space complexity
def quicksort(x, pivot_index):
key1_idx, key2_idx, key3_idx = 0, 0, len(x)
key1_val, key2_val= 'key1', 'key2'
while key2_idx < key3_idx:
if x... | [
"import random\n\n#quicksort a list of objects based on keys, which can be any of 3 values\n# done in O(n) time in one pass, and O(1) additional space complexity\ndef quicksort(x, pivot_index):\n key1_idx, key2_idx, key3_idx = 0, 0, len(x)\n key1_val, key2_val= 'key1', 'key2'\n\n while key2_idx < key3_idx:... | false |
2,414 | 0c7efa99dc22154f9835b277cba5057b213a28e7 | from django.apps import AppConfig
class NombreaplicacionConfig(AppConfig):
name = 'nombreAplicacion'
| [
"from django.apps import AppConfig\n\n\nclass NombreaplicacionConfig(AppConfig):\n name = 'nombreAplicacion'\n",
"<import token>\n\n\nclass NombreaplicacionConfig(AppConfig):\n name = 'nombreAplicacion'\n",
"<import token>\n\n\nclass NombreaplicacionConfig(AppConfig):\n <assignment token>\n",
"<impor... | false |
2,415 | d0364b7cad29c639af9df5c78e810144ffd6ce2e | from utils import to_device
from utils import build_dictionary,my_collate
from DataGenerator import DataGenerator
from torch.utils.data import DataLoader
from torch import optim
import torch.nn as nn
from ADSentimentModel import ADSentimentModel
import torch
def train(token2id, train_data, lr, batch_size, epochs,model... | [
"from utils import to_device\nfrom utils import build_dictionary,my_collate\nfrom DataGenerator import DataGenerator\nfrom torch.utils.data import DataLoader\nfrom torch import optim\nimport torch.nn as nn\nfrom ADSentimentModel import ADSentimentModel\nimport torch\n\ndef train(token2id, train_data, lr, batch_size... | false |
2,416 | 43d9edd9120351ce5065eb266d482ccaa2e56177 | from keras.models import Sequential
from keras.layers import Dense
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
x2 = np.array([11, 12, 13, 14, 15])
model = Sequential()
model.add(Dense(5, input_dim=1, activation='relu'))
model.add(Dense(3))
model.add(D... | [
"from keras.models import Sequential\nfrom keras.layers import Dense\n\nimport numpy as np\nx = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\ny = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\nx2 = np.array([11, 12, 13, 14, 15])\n\nmodel = Sequential()\nmodel.add(Dense(5, input_dim=1, activation='relu'))\nmodel.add(Dense(... | false |
2,417 | eca40c37e0e437a5f4e5643f5fb7cd3e38605471 | from django.shortcuts import render
from .models import Team,ContactForm
from cars.models import Car
from django.contrib import messages
# Create your views here.
def index(request):
teams=Team.objects.all()
cars = Car.objects.order_by("-created_date").filter(is_featured=True)
all_cars=Car.objects.order_by(... | [
"from django.shortcuts import render\nfrom .models import Team,ContactForm\nfrom cars.models import Car\nfrom django.contrib import messages\n# Create your views here.\ndef index(request):\n teams=Team.objects.all()\n cars = Car.objects.order_by(\"-created_date\").filter(is_featured=True)\n all_cars=Car.ob... | false |
2,418 | 77a82f99ab10e3d53e3f8466d43b67e8b87c1588 | print(1)
print(2)
print("Jenkins")
print("Jenkins2")
print("Jenkins3")
print("Jenkins44")
print("Jenkins55khlk")
print("3333333")
print("44444444")
print("jhjhj")
| [
"print(1)\nprint(2)\nprint(\"Jenkins\")\nprint(\"Jenkins2\")\nprint(\"Jenkins3\")\nprint(\"Jenkins44\")\nprint(\"Jenkins55khlk\")\n\nprint(\"3333333\")\nprint(\"44444444\")\n\nprint(\"jhjhj\")\n",
"print(1)\nprint(2)\nprint('Jenkins')\nprint('Jenkins2')\nprint('Jenkins3')\nprint('Jenkins44')\nprint('Jenkins55khlk... | false |
2,419 | 28f4f14c3c29ee96c370ffe71c268549552b915e | from django.db import models
from django.contrib.auth.models import User
from Event.models import Event
from University.models import University
from django.core.validators import validate_email
class Person(models.Model):
user = models.ForeignKey(
User, related_name='person', on_delete=models.CASCADE,
... | [
"from django.db import models\nfrom django.contrib.auth.models import User\n\nfrom Event.models import Event\nfrom University.models import University\n\nfrom django.core.validators import validate_email\n\nclass Person(models.Model):\n user = models.ForeignKey(\n User, related_name='person', on_delete=mo... | false |
2,420 | 660334be611c30397c2f33890e1bca1fc43bd01f | import numpy as np
import matplotlib.pyplot as plt
from math import *
from scipy.integrate import *
from pylab import *
from scipy.integrate import quad
MHD = np.zeros((80, 90, 5), dtype=float)
BGI = np.zeros((80, 90, 5), dtype=float)
Fp = np.zeros((80), dtype=float)
AngMHD = np.zeros((90,2), dtype=floa... | [
"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom math import * \r\nfrom scipy.integrate import *\r\nfrom pylab import * \r\nfrom scipy.integrate import quad\r\n\r\n\r\nMHD = np.zeros((80, 90, 5), dtype=float)\r\nBGI = np.zeros((80, 90, 5), dtype=float)\r\nFp = np.zeros((80), dtype=float) \r\nAngMHD = ... | false |
2,421 | 95ea8a21d3ac44c7760179bc4ebf67f0c16e6a19 | """
module : watcher.py
description : Script to automatically watch a directory (via watchdog) for tests and run them via py.test
"""
import sys
import os.path
import subprocess
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class SpecificationsEventHandler(Fil... | [
"\"\"\"\nmodule\t\t\t: watcher.py\ndescription\t: Script to automatically watch a directory (via watchdog) for tests and run them via py.test\n\"\"\"\nimport sys\nimport os.path\nimport subprocess\nimport time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\nclass Spec... | false |
2,422 | 18a49d46b39fe6e00e2ad137984cceab82f1e94b | import sys
import time
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import *
class PromptMessage(QWidget):
def __init__(self, parent = None):
super(PromptMessage,self).__init__(parent)
self.m_show_tm = QTimer()
self.m_stay_tm = QTimer()
... | [
"import sys\nimport time\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import *\n\n\nclass PromptMessage(QWidget):\n def __init__(self, parent = None):\n super(PromptMessage,self).__init__(parent)\n self.m_show_tm = QTimer()\n self.m_stay_t... | false |
2,423 | 74bc530d53cd86c52c44ba8e98d4d8f502032340 | # -*- encoding:utf-8 -*-
import os
import unittest
from HTMLTestRunner_cn import HTMLTestRunner
from time import sleep
from framework.SunFlower import SunFlower
from testcase.TestCRM import TestCRM
class TestCRMcreateCustomer(TestCRM):
# 创建客户
def createCustomer(self):
# 点击客户图标
self.driver.... | [
"# -*- encoding:utf-8 -*-\nimport os\nimport unittest\nfrom HTMLTestRunner_cn import HTMLTestRunner\nfrom time import sleep\n\nfrom framework.SunFlower import SunFlower\nfrom testcase.TestCRM import TestCRM\n\n\nclass TestCRMcreateCustomer(TestCRM):\n\n # 创建客户\n def createCustomer(self):\n\n # 点击客户图标\... | false |
2,424 | 825f3b930fee319314d520a32c2f9dcd718505ab | '''
Sample Input
1
5
1 2 3 2 1
Sample Output
3
'''
for _ in range(int(input())):
noe = int(input())
arr = [int(x) for x in input().split()]
left = arr[0]
rite = sum(arr) - left
mins = abs(rite - left)
for i in range(1, noe-1):
left += arr[i]
rite -= arr[i]
print(left, rit... | [
"'''\nSample Input\n1\n5\n1 2 3 2 1\nSample Output\n3\n'''\nfor _ in range(int(input())):\n noe = int(input())\n arr = [int(x) for x in input().split()]\n left = arr[0]\n rite = sum(arr) - left\n mins = abs(rite - left)\n for i in range(1, noe-1):\n left += arr[i]\n rite -= arr[i]\n ... | false |
2,425 | ff0495ee1f4aa1f243c82b709a974d3d7c37e8bd | """
Download the full CHIRPS 2.0 data for a specific type (dekads, pentads, daily ...)
with the possibility to automatically recut the data over Argentina.
"""
import os
import requests
import urllib.request
import time
from bs4 import BeautifulSoup
import subprocess
##############
# PARAMETERS to define
# Set a pre... | [
"\"\"\"\nDownload the full CHIRPS 2.0 data for a specific type (dekads, pentads, daily ...)\nwith the possibility to automatically recut the data over Argentina.\n\"\"\"\nimport os\nimport requests\nimport urllib.request\nimport time\nfrom bs4 import BeautifulSoup\nimport subprocess\n\n##############\n\n# PARAMETER... | false |
2,426 | 70b08b9e8c1510a9be48a4bc1de39c6c85b36eed | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import sys
import json
import math
from klpmln import MVPP
dprogram = '''
img(i1). img(i2).
addition(A,B,N) :- digit(A,1,N... | [
"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\nimport sys\nimport json\nimport math\n\nfrom klpmln import MVPP\n\ndprogram = '''\nimg(i1). img(i2).\n\naddition... | false |
2,427 | 2ea335dd8d879731aad7713499440db6d1f60d36 | #!/usr/bin/env python
#
# Copyright (C) 2016 The Android Open Source Project
#
# 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 req... | [
"#!/usr/bin/env python\n#\n# Copyright (C) 2016 The Android Open Source Project\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... | false |
2,428 | d6bc8afcdb7636085b01add860f808024fbe566d | import sys
lines = sys.stdin.readlines()
t = int(lines[0])
for i in range(t):
c = i*10+1
n = int(lines[c]) - 1
first = [x.strip() for x in [
lines[c+1],
lines[c+2],
lines[c+3],
lines[c+4]]]
first = [s.split() for s in first]
m = int(lines[c+5]) - 1
second = [x.... | [
"import sys\n\nlines = sys.stdin.readlines()\n\nt = int(lines[0])\n\nfor i in range(t):\n c = i*10+1\n n = int(lines[c]) - 1\n first = [x.strip() for x in [\n lines[c+1],\n lines[c+2],\n lines[c+3],\n lines[c+4]]]\n first = [s.split() for s in first]\n m = int(lines[c+5]) ... | true |
2,429 | 0b833276ca10118f2d60e229ff03400b03915958 | """Base class for an array of annotated genomic regions."""
import logging
from typing import Callable, Dict, Iterable, Iterator, Mapping, Optional, Sequence, Union
from collections import OrderedDict
import numpy as np
import pandas as pd
from .chromsort import sorter_chrom
from .intersect import by_ranges, into_ran... | [
"\"\"\"Base class for an array of annotated genomic regions.\"\"\"\nimport logging\nfrom typing import Callable, Dict, Iterable, Iterator, Mapping, Optional, Sequence, Union\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\n\nfrom .chromsort import sorter_chrom\nfrom .intersect import... | false |
2,430 | 5debc97e99bbd78b17e545896d718d4b0eac8519 | """
Urls for CAE_Web Audio_Visual app.
"""
from django.conf.urls import url
from . import views
app_name = 'cae_web_audio_visual'
urlpatterns = [
]
| [
"\"\"\"\nUrls for CAE_Web Audio_Visual app.\n\"\"\"\n\nfrom django.conf.urls import url\n\nfrom . import views\n\n\napp_name = 'cae_web_audio_visual'\nurlpatterns = [\n\n]\n",
"<docstring token>\nfrom django.conf.urls import url\nfrom . import views\napp_name = 'cae_web_audio_visual'\nurlpatterns = []\n",
"<doc... | false |
2,431 | af9adc0faad4fc1426a2bd75c1c77e23e37b60bf | # -*- coding: utf-8 -*-
# @Time : 2020/6/12 20:19
# @Author : damon
# @Site :
# @File : work0612
# @Software: PyCharm
import math
"""
1、给定n=10,计算1! + 2! + 3! + ... + n!的值
"""
# 解法1:
n = 10
factorial = 1
sum = 0
for i in range(1, n+1):
factorial = i * factorial
sum += factorial
print(f"阶乘之和{sum}")... | [
"# -*- coding: utf-8 -*-\n# @Time : 2020/6/12 20:19\n# @Author : damon\n# @Site : \n# @File : work0612\n# @Software: PyCharm\n\n\nimport math\n\n\n\"\"\"\n1、给定n=10,计算1! + 2! + 3! + ... + n!的值\n\"\"\"\n# 解法1:\nn = 10\nfactorial = 1\nsum = 0\nfor i in range(1, n+1):\n factorial = i * factorial\n sum +... | false |
2,432 | 2ee5991e2b6de6ee48c8207f2b78574fc8a02fc0 | #! /usr/bin/python
# Project Euler problem 21
"""Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 ... | [
"#! /usr/bin/python\n\n# Project Euler problem 21\n\n\"\"\"Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).\nIf d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.\n\nFor example, the proper d... | true |
2,433 | 6216a5e45fee8ade5ec9072c42c1b08f3b0f4c65 | class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def validateIPv4(IP):
digits = IP.split('.')
if len(digits) != 4:
return False
for digitstr in digits:
if len(digitstr)... | [
"class Solution:\n def validIPAddress(self, IP):\n \"\"\"\n :type IP: str\n :rtype: str\n \"\"\"\n \n def validateIPv4(IP):\n digits = IP.split('.')\n if len(digits) != 4:\n return False\n for digitstr in digits:\n ... | false |
2,434 | 59338170b44be037f749790a7942c2bcca1fc078 | #!/usr/bin/env python
###############################################################################
#
#
# Project:
# Purpose:
#
#
# Author: Massimo Di Stefano , epiesasha@me.com
#
###############################################################################
# Copyright (c) 2009, Massimo Di Stefano <epiesasha@me.c... | [
"#!/usr/bin/env python\n###############################################################################\n#\n#\n# Project:\n# Purpose:\n#\n#\n# Author: Massimo Di Stefano , epiesasha@me.com\n#\n###############################################################################\n# Copyright (c) 2009, Massimo Di Stefano... | true |
2,435 | e2f134f5ff00405396b8bbf4edc263b70ef5d972 | import re
import sys
import zipfile
import pathlib
from typing import IO, Any
from collections.abc import Mapping
import numpy.typing as npt
import numpy as np
from numpy.lib._npyio_impl import BagObj
if sys.version_info >= (3, 11):
from typing import assert_type
else:
from typing_extensions import assert_typ... | [
"import re\nimport sys\nimport zipfile\nimport pathlib\nfrom typing import IO, Any\nfrom collections.abc import Mapping\n\nimport numpy.typing as npt\nimport numpy as np\nfrom numpy.lib._npyio_impl import BagObj\n\nif sys.version_info >= (3, 11):\n from typing import assert_type\nelse:\n from typing_extension... | false |
2,436 | bbb23d606b081d2591699cb6b9336c8766eea5b2 | s=input("enter a string")
u=0
l=0
for i in s:
if i.isupper():
u+=1
elif i.islower():
l+=1
print(u,l,end="") | [
"s=input(\"enter a string\")\nu=0\nl=0\nfor i in s:\n if i.isupper():\n u+=1\n elif i.islower():\n l+=1\n \nprint(u,l,end=\"\")",
"s = input('enter a string')\nu = 0\nl = 0\nfor i in s:\n if i.isupper():\n u += 1\n elif i.islower():\n l += 1\nprint(u, l, end='')\n",
"<assignment t... | false |
2,437 | fdb680f12dfb4b29f25cfe4f7af80469dc4294cf | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.shtiker.CogPageGlobals
COG_QUOTAS = ((30, 25, 20, 15, 10, 5, 2, 1), (45, 40, 35, 30, 25, 20, 15, 10))
COG_UNSEEN = 1
COG_BATTLED = 2
COG_DEFEATED = 3
COG_COMPLETE1 = 4
COG_COMPLETE2 = 5 | [
"# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.shtiker.CogPageGlobals\r\nCOG_QUOTAS = ((30, 25, 20, 15, 10, 5, 2, 1), (45, 40, 35, 30, 25, 20, 15, 10))\r\nCOG_UNSEEN = 1\r\nCOG_BATTLED = 2\r\nCOG_DEFEATED = 3\r\nCOG_COMPLETE1 = 4\r\nCOG_COMPLETE2 = 5",
"COG_QUOTAS = (30, 25, 20, 15, 10, 5, 2... | false |
2,438 | 0b0282ade565eb4031cef3a2fa8605249f104d9d | import os
import sys
import platform
import numpy as np
import sklearn.preprocessing as sp
def deal_with_ohe(raw_sample):
# --------------------#
# 10 100 0001 #
# 01 010 1000 #
# 10 001 0100 #
# 01 100 0010 #
# --------------------#
ohe_sample... | [
"import os\r\nimport sys\r\nimport platform\r\nimport numpy as np\r\nimport sklearn.preprocessing as sp\r\n\r\n\r\ndef deal_with_ohe(raw_sample):\r\n # --------------------#\r\n # 10 100 0001 #\r\n # 01 010 1000 #\r\n # 10 001 0100 #\r\n # 01 100 0010 #\r\n # ------... | false |
2,439 | 7c2349810fc757848eeb5bddef4640d87d5f9ab9 | #!/usr/bin/env python
#-*-coding:utf-8-*-
#author:wuya
import os
import xlrd
import json
class Helper(object):
'''公共方法'''
def base_dir(self,filePath,folder='data'):
'''
返回公共路径
:parameter folder:文件夹
:parameter filePath:文件名称
'''
return os.path.join(
os.path.dirn... | [
"#!/usr/bin/env python\n#-*-coding:utf-8-*-\n\n#author:wuya\n\n\nimport os\nimport xlrd\nimport json\n\n\nclass Helper(object):\n '''公共方法'''\n\n def base_dir(self,filePath,folder='data'):\n '''\n 返回公共路径\n :parameter folder:文件夹\n :parameter filePath:文件名称\n '''\n return os.path.jo... | false |
2,440 | 9de2589cfb5bebba789ece8df9a0fcfbedb01173 | #!/usr/bin/env python
import sys, re, urllib, urllib2, string, time, os
from urllib2 import Request, urlopen, URLError, HTTPError
from urlparse import urlparse
joomla_version="undefined" #used for joomla veersin info
provided_url="" #the selected provided url
verbose_flag = 0 # If set to 1, prints... | [
"#!/usr/bin/env python\r\n\r\nimport sys, re, urllib, urllib2, string, time, os\r\nfrom urllib2 import Request, urlopen, URLError, HTTPError\r\nfrom urlparse import urlparse\r\n\r\njoomla_version=\"undefined\" #used for joomla veersin info\r\n\r\nprovided_url=\"\" #the selected provided url\r\n\r\nverbose_f... | true |
2,441 | f2397ba3fe1452238f251111f35b06b4a93e0359 | # __author__ = 'Vasudev Gupta'
import tf_lightning as tl
import tensorflow as tf
class TestModel(tl.LightningModule):
# just a random model with random dataset
def __init__(self):
# simple test model
super().__init__()
self.model = tf.keras.Sequential([
tf.keras.layers.D... | [
"# __author__ = 'Vasudev Gupta'\n\nimport tf_lightning as tl\nimport tensorflow as tf\n\n\nclass TestModel(tl.LightningModule):\n # just a random model with random dataset\n\n def __init__(self):\n # simple test model\n super().__init__()\n\n self.model = tf.keras.Sequential([\n ... | false |
2,442 | 4a63431aa71ca3f4b75fcd89a50bf599e7717645 | import argparse
import debug.debug as dbg
import helper.helper as hlp
import prep.preprocessor as pre
import sample.sample as s
def main(dir_train, C, gamma, number_partitions, do_subsampling, write_labels):
hlp.setup_logging()
# Files as folds?
if number_partitions is None or number_partitions == 0: #... | [
"import argparse\n\nimport debug.debug as dbg\nimport helper.helper as hlp\nimport prep.preprocessor as pre\nimport sample.sample as s\n\n\ndef main(dir_train, C, gamma, number_partitions, do_subsampling, write_labels):\n hlp.setup_logging()\n\n # Files as folds?\n if number_partitions is None or number_pa... | false |
2,443 | 8ede786526f4b730173777d9d3b9c7e4554fc887 | config_info = {
'n_input': 1,
'num_layers': 1,
'features': 20,
'sequence_length': 1344,
'num_steps' : None,
'lstm_size' : None,
'batch_size' : None,
'init_learning_rate' : None,
'learning_rate_decay' : None,
'init_epoch' : None,
'max_epoch' : None,
'dropout_ra... | [
"config_info = {\r\n 'n_input': 1,\r\n 'num_layers': 1,\r\n 'features': 20,\r\n 'sequence_length': 1344,\r\n 'num_steps' : None,\r\n 'lstm_size' : None,\r\n 'batch_size' : None,\r\n 'init_learning_rate' : None,\r\n 'learning_rate_decay' : None,\r\n 'init_epoch' : None,\r\n 'max_epoc... | false |
2,444 | 624ecf743d5be1acc33df14bd721b3103d232f0e | #!/bin/usr/python
'''
Author: SaiKumar Immadi
Basic DBSCAN clustering algorithm written in python
5th Semester @ IIIT Guwahati
'''
# You can use this code for free. Just don't plagiarise it for your lab assignments
import sys
from math import sqrt
from random import randint
import matplotlib.pyplot as plt
def main(a... | [
"#!/bin/usr/python\n'''\nAuthor: SaiKumar Immadi\nBasic DBSCAN clustering algorithm written in python\n5th Semester @ IIIT Guwahati\n'''\n\n# You can use this code for free. Just don't plagiarise it for your lab assignments\n\nimport sys\nfrom math import sqrt\nfrom random import randint\nimport matplotlib.pyplot a... | true |
2,445 | aeef27d667f95e3818f73533439385ea949b96a4 | #!/usr/bin/env python
import webapp2 # web application framework
import jinja2 # template engine
import os # access file system
import csv
from google.appengine.api import users # Google account authentication
from google.appengine.ext import db # datastore
# initialise template
jinja_environment = jinja2.Envir... | [
"#!/usr/bin/env python\n\nimport webapp2 # web application framework\nimport jinja2 # template engine\nimport os \t # access file system\nimport csv\nfrom google.appengine.api import users\t# Google account authentication\nfrom google.appengine.ext import db\t\t# datastore\n\n# initialise template\njinja_environ... | false |
2,446 | 7f5f16ea10980e0ade7357cdae38f47f8d7cdf01 | import re
from collections import defaultdict
def count_words(sentence):
# extract all the words as per definition
sentence = re.findall(r"\b[\w'-]+\b", sentence.lower().replace('_', ' '))
counts = defaultdict(lambda: 0)
# Counting the frequency of each words
for word in sentence:
counts[w... | [
"import re\nfrom collections import defaultdict\n\ndef count_words(sentence):\n # extract all the words as per definition\n sentence = re.findall(r\"\\b[\\w'-]+\\b\", sentence.lower().replace('_', ' '))\n counts = defaultdict(lambda: 0)\n\n # Counting the frequency of each words\n for word in sentenc... | false |
2,447 | f26e6164fc4c07fd3339171e316b3a1f7a4be669 | import os.path as osp
from evaluations.common import tiou
from evaluations.util import load_file
import generate_track_link
def eval_ground_scores(gt_relations, pred_relations, tiou_threshold):
"""
:param gt_relations:
:param pred_relations:
:param tiou_threshold:
:return:
"""
# pred_relat... | [
"import os.path as osp\nfrom evaluations.common import tiou\nfrom evaluations.util import load_file\nimport generate_track_link\n\ndef eval_ground_scores(gt_relations, pred_relations, tiou_threshold):\n \"\"\"\n\n :param gt_relations:\n :param pred_relations:\n :param tiou_threshold:\n :return:\n ... | false |
2,448 | 9555e5f75e3045afff6da9228764fca542caf539 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Beach',
fields=[
('id', models.AutoField(verbos... | [
"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Beach',\n fields=[\n ('id', mod... | false |
2,449 | 97ea837961c92b5c92a93ec33ac016de7ff1e876 | import numpy as np
import pandas as pd
import math
import sklearn
import sklearn.preprocessing
import datetime
import os
import matplotlib.pyplot as plt
import yfinance as yf
import math
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.layers impor... | [
"import numpy as np\nimport pandas as pd\nimport math\nimport sklearn\nimport sklearn.preprocessing\nimport datetime\nimport os\nimport matplotlib.pyplot as plt\nimport yfinance as yf\n\nimport math\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.... | false |
2,450 | ed7fa6e6f30eb06400cb38128617967a597f6c04 | '''
Implement GreedyMotifSearch
http://rosalind.info/problems/ba2d/
Given: Integers k and t, followed by a collection of strings Dna.
Return: A collection of strings BestMotifs resulting from running GreedyMotifSearch(Dna, k, t). If at any step you find more than one Profile-most probable k-mer in a given string, use... | [
"'''\nImplement GreedyMotifSearch\nhttp://rosalind.info/problems/ba2d/\n\nGiven: Integers k and t, followed by a collection of strings Dna.\n\nReturn: A collection of strings BestMotifs resulting from running GreedyMotifSearch(Dna, k, t). If at any step you find more than one Profile-most probable k-mer in a given ... | false |
2,451 | b46fe26f1a3c9e93e735b752e54132bd95408251 | # -*- coding: utf-8 -*-
"""
测试如何使用python的pymongo模块操作MongoDB
@author: hch
@date : 2020/10/8
"""
import logging
import time
import traceback
from pprint import pprint
from pymongo import MongoClient
from pymongo.cursor import Cursor
from pymongo.results import DeleteResult, InsertOneResult, UpdateResult
class MongoT... | [
"# -*- coding: utf-8 -*-\n\"\"\"\n测试如何使用python的pymongo模块操作MongoDB\n\n@author: hch\n@date : 2020/10/8\n\"\"\"\nimport logging\nimport time\nimport traceback\nfrom pprint import pprint\n\nfrom pymongo import MongoClient\nfrom pymongo.cursor import Cursor\nfrom pymongo.results import DeleteResult, InsertOneResult, Up... | false |
2,452 | 9583a97ae4b1fbf5ecdf33d848b13bf0b28d2eb4 | from package.pack import *
add(2,2)
sub(2,3) | [
"from package.pack import *\nadd(2,2)\nsub(2,3)",
"from package.pack import *\nadd(2, 2)\nsub(2, 3)\n",
"<import token>\nadd(2, 2)\nsub(2, 3)\n",
"<import token>\n<code token>\n"
] | false |
2,453 | 55cf99e3493c9c94955fc7e75ac428cbd88ac5cf | from django.conf import settings
from django.urls import resolve
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, JsonResponse, HttpResponseNotFound
from django.template.loader import get_template, render_to_string
from django.views.g... | [
"from django.conf import settings\nfrom django.urls import resolve\nfrom django.urls import reverse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponse, JsonResponse, HttpResponseNotFound\nfrom django.template.loader import get_template, render_to_string\nfrom dja... | false |
2,454 | c6821cb8dd6f8d74ca20c03f87dae321eb869c32 | import os
import attr
import click
import guitarpro
import psutil
ALL = object()
@attr.s
class GPTools:
input_file = attr.ib()
output_file = attr.ib()
selected_track_numbers = attr.ib(default=None)
selected_measure_numbers = attr.ib(default=None)
selected_beat_numbers = attr.ib(default=None)
... | [
"import os\n\nimport attr\nimport click\nimport guitarpro\nimport psutil\n\nALL = object()\n\n\n@attr.s\nclass GPTools:\n input_file = attr.ib()\n output_file = attr.ib()\n selected_track_numbers = attr.ib(default=None)\n selected_measure_numbers = attr.ib(default=None)\n selected_beat_numbers = attr... | false |
2,455 | 90218168841dc76febab67d1e992dfc993730ea4 | import math
import numpy as np
import matplotlib.pyplot as plt
def test_func(x):
# x is vector; here of length 1
x = x[0]
return math.cos(x) * x**2 + x
def run_smac(max_fun=30):
from smac.facade.func_facade import fmin_smac
x, cost, smac = fmin_smac(func=test_func,
... | [
"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef test_func(x):\n # x is vector; here of length 1\n x = x[0]\n return math.cos(x) * x**2 + x\n\n\ndef run_smac(max_fun=30):\n from smac.facade.func_facade import fmin_smac\n\n x, cost, smac = fmin_smac(func=test_func,\n ... | false |
2,456 | 2b1ec422a42af59a048c708f86b686eb0564b51f | from django.conf.urls import url
from django.urls import path
from .views import *
from flujo.views import *
"""
URL para el Sprint crear, listar y modificar
"""
urlpatterns = [
url(r'^$', SprintListView.as_view(), name='sprint_list'),
path('create/', view=CreateSprintView.as_view(), name='create_sprint'),
... | [
"from django.conf.urls import url\nfrom django.urls import path\nfrom .views import *\nfrom flujo.views import *\n\n\"\"\"\nURL para el Sprint crear, listar y modificar\n\"\"\"\nurlpatterns = [\n url(r'^$', SprintListView.as_view(), name='sprint_list'),\n path('create/', view=CreateSprintView.as_view(), name=... | false |
2,457 | a555226b14223dca688d10b811eb36fb229360ce | # ================================================== #
# MAIN WINDOW #
# ================================================== #
# Author: Brady Hammond #
# Created: 11/21/2017 #
# Last Edited: N/A ... | [
"# ================================================== #\n# MAIN WINDOW #\n# ================================================== #\n# Author: Brady Hammond #\n# Created: 11/21/2017 #\n# Last Edited: N/A ... | false |
2,458 | 9a40861239268aa62075b77b3ed452f31bb14fac | """
openAI gym 'cart pole-v0'
"""
import numpy as np
import tensorflow as tf
from collections import deque
import random
import dqn
import gym
import matplotlib.pyplot as plt
# define environment
env = gym.make('CartPole-v0')
# define parameters
INPUT_SIZE = env.observation_space.shape[0]
OUTPUT_SIZE = env.action_sp... | [
"\"\"\"\nopenAI gym 'cart pole-v0'\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom collections import deque\nimport random\nimport dqn\nimport gym\nimport matplotlib.pyplot as plt\n\n# define environment\nenv = gym.make('CartPole-v0')\n\n# define parameters\nINPUT_SIZE = env.observation_space.shape[0]\... | false |
2,459 | dcda8f26a06145579a9be6e5fbfdaed83d4908da | from typing import Tuple
#Creating a trie structure and it's node
class TrieNode(object):
def __init__(self, char: str):
self.char = char
self.children = []
#the last character of the word.`
self.word_finished = False
#counter for this character
self.counter = 1
... | [
"from typing import Tuple\n\n#Creating a trie structure and it's node\nclass TrieNode(object): \n def __init__(self, char: str):\n self.char = char\n self.children = []\n #the last character of the word.`\n self.word_finished = False\n #counter for this character\n self... | false |
2,460 | 8afaa69d3a20c5e39e6321869f25dbd9020a5b3a | import sqlite3
conn = sqlite3.connect("blog.db")
c = conn.cursor()
q = "CREATE TABLE users(Username text, Password text, UserID integer)"
c.execute(q)
q = "CREATE TABLE blogs(Title text, Content text, BlogID integer, UserID integer)"
c.execute(q)
q = "CREATE TABLE comments(Content text, CommentID integer, BlogID i... | [
"import sqlite3\n\nconn = sqlite3.connect(\"blog.db\")\n\nc = conn.cursor()\n\nq = \"CREATE TABLE users(Username text, Password text, UserID integer)\"\nc.execute(q)\n\nq = \"CREATE TABLE blogs(Title text, Content text, BlogID integer, UserID integer)\"\nc.execute(q)\n\nq = \"CREATE TABLE comments(Content text, Com... | false |
2,461 | e5a698979bc84fe733a9bf5cd51e2f078956d468 | import random
from elment.login_registration_element import LoginRegistration
from page.test_verification_code_page import VerificationCodeAction
public_number_vip = ['17800000000','17800000001','17800000002','17800000003','17800000004','17800000005','17800000006',
'17800000007','17800000008','1780000... | [
"import random\n\nfrom elment.login_registration_element import LoginRegistration\nfrom page.test_verification_code_page import VerificationCodeAction\npublic_number_vip = ['17800000000','17800000001','17800000002','17800000003','17800000004','17800000005','17800000006',\n '17800000007','17800000008... | false |
2,462 | 05cfd9d239b63c9b1e0c93a09e89cceb8d8e99e4 | import os
import time
try:
import cPickle as pickle
except:
import pickle
#-------------#
# Cache utils #
#-------------#
cachedir = os.path.expanduser('~/.cache/sherlock/')
_cachedict = {}
def get_cachefile(filename):
"""
Return full path to filename within cache dir.
"""
if not os.path.e... | [
"import os\nimport time\n\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\n\n#-------------#\n# Cache utils #\n#-------------#\n\ncachedir = os.path.expanduser('~/.cache/sherlock/')\n\n_cachedict = {}\n\ndef get_cachefile(filename):\n \"\"\"\n Return full path to filename within cache dir.\n... | false |
2,463 | 3f473701b186b5287258ba74e478cccdad0f29bf | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@File : corr2d.py
@Author : jeffsheng
@Date : 2020/1/3
@Desc : 卷积层中的互相关(cross-correlation)运算
卷积层需要学习的参数是:卷积核和偏置大小
"""
import tensorflow as tf
def corr2d(X, K):
"""
定义二维互相关运算函数
:param X:输入数组
:param K: 核数组
:return:二维互相关的运算结果
"""
h, w = K.sh... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@File : corr2d.py\n@Author : jeffsheng\n@Date : 2020/1/3\n@Desc : 卷积层中的互相关(cross-correlation)运算\n卷积层需要学习的参数是:卷积核和偏置大小\n\"\"\"\nimport tensorflow as tf\n\n\ndef corr2d(X, K):\n \"\"\"\n 定义二维互相关运算函数\n :param X:输入数组\n :param K: 核数组\n :return:二维... | false |
2,464 | de634c95fddf4591cb15cd0eb20e798043075798 | #Answer to The Ship Teams - https://py.checkio.org/en/mission/the-ship-teams/
def two_teams(sailors):
result = [] #To store the result
temp = [[],[]] #To store the intermediatary values
for i in sailors.items(): #To get the values of dictionary as Tuple
if i[1] > 40 or i[1] < 20: #To get the people... | [
"#Answer to The Ship Teams - https://py.checkio.org/en/mission/the-ship-teams/\n\ndef two_teams(sailors):\n result = [] #To store the result\n temp = [[],[]] #To store the intermediatary values\n for i in sailors.items(): #To get the values of dictionary as Tuple\n if i[1] > 40 or i[1] < 20: #To get... | false |
2,465 | 3c029adb59cd6db1e3d4a22e6561f5e2ae827d60 | # https://daphne-dev.github.io/2020/09/24/algo-022/
def solution(n):
arr = [[0 for _ in range(i+1)] for i in range(n)]
# 경우의수 는 3가지
# 1. y축이 증가하면서 수가 증가
# 2. x축이 증가하면서 수가 증가
# 3. y,x축이 감소하면서 수가 증가
size = n
num = 0
x = 0
y = -1
while True:
# 1번
for _ in range(size)... | [
"# https://daphne-dev.github.io/2020/09/24/algo-022/\ndef solution(n):\n arr = [[0 for _ in range(i+1)] for i in range(n)]\n # 경우의수 는 3가지\n # 1. y축이 증가하면서 수가 증가\n # 2. x축이 증가하면서 수가 증가\n # 3. y,x축이 감소하면서 수가 증가\n size = n\n num = 0\n x = 0\n y = -1\n while True:\n # 1번\n fo... | false |
2,466 | 6b5399effe73d27eade0381f016cd7819a6e104a | import tensorflow as tf
import cv2
img=cv2.imread('d:\st.jpg',0)
cv2.namedWindow('st',cv2.WINDOW_NORMAL)#可以调整图像窗口大小
cv2.imshow('st',img)
cv2.imwrite('mes.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows() | [
"import tensorflow as tf\r\nimport cv2 \r\nimg=cv2.imread('d:\\st.jpg',0)\r\ncv2.namedWindow('st',cv2.WINDOW_NORMAL)#可以调整图像窗口大小\r\ncv2.imshow('st',img)\r\ncv2.imwrite('mes.png',img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()",
"import tensorflow as tf\nimport cv2\nimg = cv2.imread('d:\\\\st.jpg', 0)\ncv2.namedW... | false |
2,467 | 72f1547ea7de78a5fe4b583523e592fa25c0ee77 | import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
username=st.text_input ("username")
upload=st.file_uploader("uploadfile",type=['csv'])
button=st.button("submit")
if button==True:
df=pd.read_csv(upload)
st.write(df.head())
fig = plt.figu... | [
"import streamlit as st\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nusername=st.text_input (\"username\")\r\nupload=st.file_uploader(\"uploadfile\",type=['csv'])\r\nbutton=st.button(\"submit\")\r\nif button==True:\r\n df=pd.read_csv(upload)\r\n st.write(df.he... | false |
2,468 | 657866affd653a99eb7d9a9a82b2f7d6503ec21a | from parser import read_expression_line, read_expression_lines, read_assignment_line, read_import_line, Import
def test_expression():
lines = ['a % b']
expression, left = read_expression_lines(lines)
assert expression is not None and len(left) == 0, left
print "test_expression 0: {} {}".format(expressi... | [
"from parser import read_expression_line, read_expression_lines, read_assignment_line, read_import_line, Import\n\ndef test_expression():\n lines = ['a % b']\n expression, left = read_expression_lines(lines)\n assert expression is not None and len(left) == 0, left\n print \"test_expression 0: {} {}\".fo... | true |
2,469 | 08c309645a4ee59716bdd00556096be1c784331a | # -*- coding: UTF-8 -*-
'''=================================================
@Project -> File :AutoMailApp -> handle_yaml
@IDE :PyCharm
@Author :Mr. wang
@Date :2019/11/15 0015 19:53
@Desc :
=================================================='''
import yaml
from Common.dir_path import YAML_FILE_PATH
class Han... | [
"# -*- coding: UTF-8 -*-\n'''=================================================\n@Project -> File :AutoMailApp -> handle_yaml\n@IDE :PyCharm\n@Author :Mr. wang\n@Date :2019/11/15 0015 19:53\n@Desc :\n=================================================='''\nimport yaml\nfrom Common.dir_path import YAML_FILE_PA... | false |
2,470 | a73dcfc21c31d4e984db39c072d11cb9a9c3d5e5 | """
The MIT License (MIT)
Copyright (c) 2021-present Pycord Development
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, ... | [
"\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2021-present Pycord Development\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rig... | false |
2,471 | ccd1e57518065963158984dda52297db45ce204e | # coding: utf-8
etc_dictionary = {
'2 30대': '이삼십대',
'20~30대': '이삼십대',
'20, 30대': '이십대 삼십대',
'1+1': '원플러스원',
'3에서 6개월인': '3개월에서 육개월인',
}
english_dictionary = {
'Devsisters': '데브시스터즈',
'track': '트랙',
# krbook
'LA': '엘에이',
'... | [
"# coding: utf-8\r\n\r\netc_dictionary = {\r\n '2 30대': '이삼십대',\r\n '20~30대': '이삼십대',\r\n '20, 30대': '이십대 삼십대',\r\n '1+1': '원플러스원',\r\n '3에서 6개월인': '3개월에서 육개월인',\r\n}\r\n\r\nenglish_dictionary = {\r\n 'Devsisters': '데브시스터즈',\r\n 'track': '트랙',\r\n\r\n # krbook... | false |
2,472 | ec0697d8d78fafe6bfd4630be2a1fb20eb9eb4cf | import boto3, os, shutil, datetime, time, sys
session = boto3.Session(profile_name='default')
s3 = boto3.resource('s3')
bucket = s3.Bucket('netball-ml-processed')
#print(bucket.objects)
#needs to be run with *** sudo **** otherwise it won't work...
while True:
#change to the motion working Directory
os.... | [
"import boto3, os, shutil, datetime, time, sys\n\nsession = boto3.Session(profile_name='default')\n\ns3 = boto3.resource('s3')\n\nbucket = s3.Bucket('netball-ml-processed')\n\n#print(bucket.objects)\n\n#needs to be run with *** sudo **** otherwise it won't work...\n\nwhile True:\n\n #change to the motion workin... | false |
2,473 | 316a34bbc2b3e3c818ef837f51bc1f86863ea59a | # Generated by Django 2.2.6 on 2020-05-27 19:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pancar', '0006_auto_20200526_1058'),
]
operations = [
migrations.AlterField(
model_name='process',
name='price',
... | [
"# Generated by Django 2.2.6 on 2020-05-27 19:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('pancar', '0006_auto_20200526_1058'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='process',\n ... | false |
2,474 | 9cb5573fada7a1529507da1d031f836044c10066 | class Solution:
def longestConsecutive(self, nums) -> int:
s = set(nums)
answer = 0
# n = len(s)
for value in s:
if value - 1 not in s:
j = value
while (j in s):
j = j + 1
answer = max(answer, j - val... | [
"class Solution:\n def longestConsecutive(self, nums) -> int:\n\n s = set(nums)\n answer = 0\n # n = len(s)\n\n for value in s:\n\n if value - 1 not in s:\n j = value\n while (j in s):\n j = j + 1\n\n answer = ... | false |
2,475 | 43ae01ffe35c6c4491f3f7e480dd6f5c1be86eb2 | # Generated by Django 3.1.1 on 2020-12-02 19:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('element', '0011_suggestion_suggestion_type'),
('bot', '0001_initial'),
]
operations = [
migrations.AddField(
model_name=... | [
"# Generated by Django 3.1.1 on 2020-12-02 19:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('element', '0011_suggestion_suggestion_type'),\n ('bot', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n ... | false |
2,476 | 24c1f5195bad17f995fb97a03218fc9bbe5ce4cd | """
Question 39:
Define a function which can generate a list where the values are square of numbers between 1 and
20 (both included). Then the function needs to print the last 5 elements in the list.
"""
#To get a value from console input.
input_num = input("Write number:")
lis1=[]
lis2=[]
def lis(n1,n2):
"""
Gener... | [
"\"\"\"\nQuestion 39:\nDefine a function which can generate a list where the values are square of numbers between 1 and\n20 (both included). Then the function needs to print the last 5 elements in the list.\n\"\"\"\n\n#To get a value from console input.\ninput_num = input(\"Write number:\")\nlis1=[]\nlis2=[]\n\ndef... | false |
2,477 | 671a7ee3fabee6ed8dfafe1bddefb1f94322b0e5 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-07-26 19:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0014_auto_20180726_0926'),
]
operations = [
migrations.AlterFi... | [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.11.12 on 2018-07-26 19:11\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('articles', '0014_auto_20180726_0926'),\n ]\n\n operations = [\n ... | false |
2,478 | 8c0377b70b902e6e61351869a4378b4c2c50a3a7 | def get_all_lefts(word,substring):
if len(substring) == 0:
yield ((len(word),word),)
else:
if substring[0] not in word:
yield (-1,)
else:
for i in range(len(word)):
if word[i] == substring[0]:
for sub_sequance in get_all_lefts(w... | [
"def get_all_lefts(word,substring):\n if len(substring) == 0:\n yield ((len(word),word),)\n else:\n if substring[0] not in word:\n yield (-1,)\n else:\n for i in range(len(word)):\n if word[i] == substring[0]:\n for sub_sequance in g... | false |
2,479 | 6d2581b83a2839dcbc644ca572b05b158d80b58d | from enum import Enum
# Genie
from genie.decorator import managedattribute
from genie.conf.base import Base, \
DeviceFeature, \
LinkFeature, \
Interface
import genie.conf.base.attributes
from genie.libs.conf.base.feature import consoli... | [
"from enum import Enum\n\n# Genie\nfrom genie.decorator import managedattribute\nfrom genie.conf.base import Base, \\\n DeviceFeature, \\\n LinkFeature, \\\n Interface\nimport genie.conf.base.attributes\nfrom genie.libs.conf.base.featu... | false |
2,480 | 3f4b484f435936137cb8511ec6e0aa89efb267c4 | # Given a stream of numbers, print average (or mean) of the stream at every point.
def getAverage(prev_avg, val, n):
return ((prev_avg * n) + val) / (n + 1)
def findAndPrintMovingAvgs(arr):
cur_avg = 0
for i in range(len(arr)):
cur_avg = getAverage(cur_avg, arr[i], i)
print "Avg at", i, "i... | [
"# Given a stream of numbers, print average (or mean) of the stream at every point.\n\ndef getAverage(prev_avg, val, n):\n return ((prev_avg * n) + val) / (n + 1)\n\ndef findAndPrintMovingAvgs(arr):\n cur_avg = 0\n for i in range(len(arr)):\n cur_avg = getAverage(cur_avg, arr[i], i)\n print \... | true |
2,481 | 32105a245f6945dbe8749140d811b20d634289bc | import chainer
import chainer.functions as F
import numpy as np
import argparse
from model import Generator, Discriminator
from chainer import cuda, serializers
from pathlib import Path
from utils import set_optimizer
from dataset import DatasetLoader
xp = cuda.cupy
cuda.get_device(0).use()
class CycleGANVC2LossCal... | [
"import chainer\nimport chainer.functions as F\nimport numpy as np\nimport argparse\n\nfrom model import Generator, Discriminator\nfrom chainer import cuda, serializers\nfrom pathlib import Path\nfrom utils import set_optimizer\nfrom dataset import DatasetLoader\n\nxp = cuda.cupy\ncuda.get_device(0).use()\n\n\nclas... | false |
2,482 | 3e1e2de555667bf09162cd6c62cad35dabbd0f54 | from flask import Flask
from flask import render_template
# Creates a Flask application called 'app'
app = Flask(__name__, template_folder='C:\Users\jwhitehead\Documents\Webdev\Angular Web App')
# The route to display the HTML template on
@app.route('/')
def host():
return render_template('index.html')
# Run the... | [
"from flask import Flask\nfrom flask import render_template\n\n# Creates a Flask application called 'app'\napp = Flask(__name__, template_folder='C:\\Users\\jwhitehead\\Documents\\Webdev\\Angular Web App')\n\n# The route to display the HTML template on\n@app.route('/')\ndef host():\n return render_template('inde... | true |
2,483 | e2573a5dc507e9aeb811fbc254129aeb6e54cc0b | from django.contrib import admin
from calc.models import CalcResult
class MyAdmin(admin.ModelAdmin):
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
class CalcResultAdmin(MyAdmin):
list_display = ('result', ... | [
"from django.contrib import admin\n\nfrom calc.models import CalcResult\n\n\nclass MyAdmin(admin.ModelAdmin):\n def has_add_permission(self, request, obj=None):\n return False\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n\nclass CalcResultAdmin(MyAdmin):\n list_di... | false |
2,484 | 7c9c13974e1deeb55f08c9e251e8c876cedcad6b | import math
import time
def calculate_time(func):
def inner_fn(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print("Time taken to execute \'{}\' function is: {} seconds".format(func.__name__, round(end - start, 2)))
return i... | [
"import math\r\nimport time\r\n\r\ndef calculate_time(func):\r\n\r\n def inner_fn(*args, **kwargs):\r\n start = time.time()\r\n func(*args, **kwargs)\r\n end = time.time()\r\n\r\n print(\"Time taken to execute \\'{}\\' function is: {} seconds\".format(func.__name__, round(end - start,... | false |
2,485 | fef4749ce7b8668a5a138aa1245010866a85c853 | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
output = []
index = 0
for i in asteroids:
if len(output) == 0:
index = 0
if index == 0:
output.append(i)
index+=1
... | [
"class Solution:\r\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\r\n output = []\r\n index = 0\r\n for i in asteroids:\r\n if len(output) == 0:\r\n index = 0\r\n if index == 0:\r\n output.append(i)\r\n ind... | false |
2,486 | 0372cdbae8c5b0bbcbade86a5a7de28c1ee513b1 | # Write files
# Writing to a file within a Python program:
# In order to write to a file, we use file.write(str).
# This method writes a string to a file.
# The method write() works like Python's print() function, except it does not add a newline ("\n") character.
# File dialogs:
# Module tkinter has a submodule cal... | [
"# Write files\n\n# Writing to a file within a Python program:\n# In order to write to a file, we use file.write(str).\n# This method writes a string to a file.\n# The method write() works like Python's print() function, except it does not add a newline (\"\\n\") character.\n\n# File dialogs:\n\n# Module tkinter ha... | false |
2,487 | 84db1803a352e0ed8c01b7166f522d46ec89b6f5 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import c... | [
"import numpy as np \r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.model... | false |
2,488 | 0b0b928aef9a4e9953b02639bf5e7769cc4389d7 | default_app_config = 'reman.apps.RemanConfig'
| [
"default_app_config = 'reman.apps.RemanConfig'\n",
"<assignment token>\n"
] | false |
2,489 | 34e902fbced13629657494eedfe385d3b5ae3f55 | # TUPLE IMUTAVEL
# GERALMENTE HETEORGENEA
# tupla com 1 ou 0 elementos
#
# empty = ()
# singleton = 'breno',
# print(type(empty))
# print(singleton)
# tuplas podem ser aninhadas
# t = 12345, 54321, 'hello!'
# u = t, (1, 2, 3, 4, 5)
#imutaveis
# t[0] = 88888 | [
"# TUPLE IMUTAVEL\n# GERALMENTE HETEORGENEA\n\n# tupla com 1 ou 0 elementos\n#\n# empty = ()\n# singleton = 'breno',\n# print(type(empty))\n# print(singleton)\n\n# tuplas podem ser aninhadas\n# t = 12345, 54321, 'hello!'\n# u = t, (1, 2, 3, 4, 5)\n\n#imutaveis\n# t[0] = 88888",
""
] | false |
2,490 | 93133b9a62d50e4e48e37721585116c1c7d70761 | from symcollab.algebra import *
from .ac import *
from copy import deepcopy
# This is a single arity function which only actually gets applied when called an odd number of times
# Useful for the inverse function later on
# A group G is an algebraic structure which satisfies the following properties
# (1) G is closed... | [
"from symcollab.algebra import *\nfrom .ac import *\nfrom copy import deepcopy\n\n# This is a single arity function which only actually gets applied when called an odd number of times\n# Useful for the inverse function later on\n\n\n# A group G is an algebraic structure which satisfies the following properties\n# (... | false |
2,491 | 994210b3de82af02ec7b1b7bee75ceb88ffb2bd5 |
HORIZONTAL_TABLE = b'\x09'
class ReagentInfoItem():
'''
This class if defined for a single reagent info unit, from the table's view, its a cell of the table.
'''
def __init__(self, reagent_name, reagent_count):
self.reagent_name = reagent_name
self.reagent_count = reagent_count
de... | [
"\nHORIZONTAL_TABLE = b'\\x09'\n\nclass ReagentInfoItem():\n '''\n This class if defined for a single reagent info unit, from the table's view, its a cell of the table.\n '''\n def __init__(self, reagent_name, reagent_count):\n self.reagent_name = reagent_name\n self.reagent_count = reagen... | true |
2,492 | a9df8e45c8b5068aeec2b79e21de6217a3103bb4 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
from bs4 import BeautifulSoup
url = "http://javmobile.net/?s=julia"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
imgs = soup.find_all("img" , {"class": "entry-thumb"})
images = []
titles = []
srcs = []
for img... | [
"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"http://javmobile.net/?s=julia\"\nr = requests.get(url)\n\nsoup = BeautifulSoup(r.content, \"html.parser\")\n\nimgs = soup.find_all(\"img\" , {\"class\": \"entry-thumb\"})\n\n\nimages = []\n... | true |
2,493 | 064792a6aba96a679bec606a85b19d4925861f7d | import webapp2
class RedirectToSiteRootHandler(webapp2.RequestHandler):
def get(self):
self.response.set_status(301)
self.response.headers['Location'] = '/'
class AppendTrailingSlashHandler(webapp2.RequestHandler):
def get(self, uri):
self.response.set_status(301)
redirect_uri = uri + ... | [
"import webapp2\n\nclass RedirectToSiteRootHandler(webapp2.RequestHandler):\n def get(self):\n self.response.set_status(301)\n self.response.headers['Location'] = '/'\n\nclass AppendTrailingSlashHandler(webapp2.RequestHandler):\n def get(self, uri):\n self.response.set_status(301)\n redire... | false |
2,494 | 6ad939ab541562efdaacb8b56865e76d1745176a | #!/usr/bin/env python
# Ben Suay, RAIL
# May 2013
# Worcester Polytechnic Institute
#
# http://openrave.org/docs/latest_stable/command_line_tools/
# openrave-robot.py /your/path/to/your.robot.xml --info=joints
# On that page you can find more examples on how to use openrave-robot.py.
from openravepy import *
import s... | [
"#!/usr/bin/env python\n# Ben Suay, RAIL\n# May 2013\n# Worcester Polytechnic Institute\n#\n\n# http://openrave.org/docs/latest_stable/command_line_tools/\n# openrave-robot.py /your/path/to/your.robot.xml --info=joints\n# On that page you can find more examples on how to use openrave-robot.py.\n\nfrom openravepy im... | true |
2,495 | 5d4585dc96d4ebdbc15b7382038cfea959c9a6f3 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
from statistics import mean
from tqdm import tqdm
import multiprocessing as mp
from . import model as dymod
class Filter:
"""誤ベクトル数の確認,誤ベクトル数によるフィルタリング処理"""
@classmethod
def get_incorrect_vector_examp... | [
"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as tick\nfrom statistics import mean\nfrom tqdm import tqdm\nimport multiprocessing as mp\n\nfrom . import model as dymod\n\n\nclass Filter:\n \"\"\"誤ベクトル数の確認,誤ベクトル数によるフィルタリング処理\"\"\"\n\n @classmethod\n def ... | false |
2,496 | 6161653fb789040d084e475e0ae25921e2e0676b | n=int(input())
k=[4,7,47,74,44,77,444,447,474,477,777,774,747,7444]
f=0
for i in k:
if(n%i==0):
f=1
print("YES")
break;
if(f==0):
print("NO")
| [
"n=int(input())\nk=[4,7,47,74,44,77,444,447,474,477,777,774,747,7444]\nf=0\nfor i in k:\n if(n%i==0):\n f=1\n print(\"YES\")\n break;\nif(f==0):\n print(\"NO\")\n",
"n = int(input())\nk = [4, 7, 47, 74, 44, 77, 444, 447, 474, 477, 777, 774, 747, 7444]\nf = 0\nfor i in k:\n if n % i =... | false |
2,497 | 2f0dc8697e979f307c86a08832b0eae86357d416 | filename = 'learning_python.txt'
# with open(filename) as file_object:
# contents = file_object.read()
# print(contents)
# with open(filename) as file_object:
# for line in file_object:
# print(line.rstrip())
with open(filename) as file_object:
lines = file_object.readlines()
c_string = ''
for line in lines:
... | [
"filename = 'learning_python.txt'\n\n# with open(filename) as file_object:\n# \tcontents = file_object.read()\n# print(contents)\n\n# with open(filename) as file_object:\n# \tfor line in file_object:\n# \t\tprint(line.rstrip())\n\nwith open(filename) as file_object:\n\tlines = file_object.readlines()\n\nc_string = ... | false |
2,498 | d14937aaa7a80d6b95825afa2a2d6ff8202e5f5c | # 出现频率特别高的和频率特别低的词对于文本分析帮助不大,一般在预处理阶段会过滤掉。
# 在英文里,经典的停用词为 “The”, "an"....
# 方法1: 自己建立一个停用词词典
stop_words = ["the", "an", "is", "there"]
# 在使用时: 假设 word_list包含了文本里的单词
word_list = ["we", "are", "the", "students"]
filtered_words = [word for word in word_list if word not in stop_words]
print (filtered_words)
# ... | [
"# 出现频率特别高的和频率特别低的词对于文本分析帮助不大,一般在预处理阶段会过滤掉。 \r\n# 在英文里,经典的停用词为 “The”, \"an\"....\r\n\r\n# 方法1: 自己建立一个停用词词典\r\nstop_words = [\"the\", \"an\", \"is\", \"there\"]\r\n# 在使用时: 假设 word_list包含了文本里的单词\r\nword_list = [\"we\", \"are\", \"the\", \"students\"]\r\nfiltered_words = [word for word in word_list if word not in stop... | false |
2,499 | 664f9d5aa981c3590043fae1d0c80441bda4fbb1 | #!/usr/bin/env python3
'''Глава 9. Распутываем Всемирную паутину'''
'''1. Если вы еще не установили Flask, сделайте это сейчас.
Это также установит werkzeug, jinja2 и, возможно, другие пакеты.'''
# pip3 install flask
print('\n================================ RESTART ================================\n')
'''2. Созда... | [
"#!/usr/bin/env python3\n\n'''Глава 9. Распутываем Всемирную паутину'''\n\n'''1. Если вы еще не установили Flask, сделайте это сейчас.\nЭто также установит werkzeug, jinja2 и, возможно, другие пакеты.'''\n\n# pip3 install flask\n\nprint('\\n================================ RESTART ================================\\... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.