index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
8,800 | 5ff0c6bde8f3ffcb1f5988b0bbd1dfdd7fa2e818 | # The project is based on Tensorflow's Text Generation with RNN tutorial
# Copyright Petros Demetrakopoulos 2020
import tensorflow as tf
import numpy as np
import os
import time
# The project is based on Tensorflow's Text Generation with RNN tutorial
# Copyright Petros Demetrakopoulos 2020
import tensorflow as tf
impor... | [
"# The project is based on Tensorflow's Text Generation with RNN tutorial\n# Copyright Petros Demetrakopoulos 2020\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport time\n# The project is based on Tensorflow's Text Generation with RNN tutorial\n# Copyright Petros Demetrakopoulos 2020\nimport tensorflo... | false |
8,801 | 9276c4106cbe52cf0e2939b5434d63109910a45c | from pymoo.model.duplicate import ElementwiseDuplicateElimination
class ChrDuplicates(ElementwiseDuplicateElimination):
"""Detects duplicate chromosome, which the base ElementwiseDuplicateElimination then removes."""
def is_equal(self, a, b):
"""
Checks whether two character chromosome elemen... | [
"from pymoo.model.duplicate import ElementwiseDuplicateElimination\n\n\nclass ChrDuplicates(ElementwiseDuplicateElimination):\n \"\"\"Detects duplicate chromosome, which the base ElementwiseDuplicateElimination then removes.\"\"\"\n\n def is_equal(self, a, b):\n \"\"\"\n Checks whether two chara... | false |
8,802 | cc6e827eec5256ce0dbe13958b6178c59bcd94a7 | from scipy.stats import rv_discrete
import torch
import torch.nn.functional as F
import numpy as np
from utils import *
def greedy_max(doc_length,px,sentence_embed,sentences,device,sentence_lengths,length_limit=200,lamb=0.2):
'''
prob: sum should be 1
sentence embed: [doc_length, embed_dim]
'''
x = list(range(do... | [
"from scipy.stats import rv_discrete\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nfrom utils import *\n\n\ndef greedy_max(doc_length,px,sentence_embed,sentences,device,sentence_lengths,length_limit=200,lamb=0.2):\n\t'''\n\tprob: sum should be 1\n\tsentence embed: [doc_length, embed_dim]\n\t''... | false |
8,803 | e54078f21176bbb7accb4164e7b56633b13cc693 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
BATCH_START=0
TIME_STEPS=20
BATCH_SIZE=50
INPUT_SIZE=1
OUTPUT_SIZE=1
CELL_SIZE=10
LR=0.006
#generate data
def get_batch():
global BATCH_START,TIME_STEPS
xs=np.arange(BATCH_START,BATCH_START+TIME_STEPS*BATCH_SIZE).reshape((BATCH_SIZE,T... | [
"import tensorflow as tf\nimport numpy as np \nimport matplotlib.pyplot as plt\n\nBATCH_START=0\nTIME_STEPS=20\nBATCH_SIZE=50\nINPUT_SIZE=1\nOUTPUT_SIZE=1\nCELL_SIZE=10\nLR=0.006\n\n#generate data\ndef get_batch():\n global BATCH_START,TIME_STEPS\n xs=np.arange(BATCH_START,BATCH_START+TIME_STEPS*BATCH_SIZE).r... | false |
8,804 | b3cb94a44f64091714650efb81c4cad27b211cef | import os
import math
import shutil
from evoplotter import utils
from evoplotter.dims import *
from evoplotter import printer
import numpy as np
CHECK_CORRECTNESS_OF_FILES = 1
STATUS_FILE_NAME = "results/status.txt"
OPT_SOLUTIONS_FILE_NAME = "opt_solutions.txt"
class TableGenerator:
"""Generates table from dat... | [
"import os\nimport math\nimport shutil\nfrom evoplotter import utils\nfrom evoplotter.dims import *\nfrom evoplotter import printer\nimport numpy as np\n\n\nCHECK_CORRECTNESS_OF_FILES = 1\nSTATUS_FILE_NAME = \"results/status.txt\"\nOPT_SOLUTIONS_FILE_NAME = \"opt_solutions.txt\"\n\n\n\nclass TableGenerator:\n \"... | false |
8,805 | 027e53d69cfece0672556e34fa901412e483bc3e | class Solution:
def uniquePaths(self, A, B):
# A - rows
# B - columns
if A == 0 or B == 0:
return 0
grid = [[1 for _ in range(B)] for _ in range(A)]
for i in range(1, A):
for j in range(1, B):
grid[i][j] = grid[i-1][j] + grid[i][j-1]
return grid[A-1][B-1]
s = Solution... | [
"class Solution:\n\n def uniquePaths(self, A, B):\n # A - rows\n # B - columns\n if A == 0 or B == 0:\n return 0\n\n grid = [[1 for _ in range(B)] for _ in range(A)]\n\n for i in range(1, A):\n for j in range(1, B):\n grid[i][j] = grid[i-1][j] + grid[i][j-1]\n\n return grid[A-1][... | true |
8,806 | 3c2fb3d09edab92da08ac8850f650a2fa22fad92 | from django.db import transaction
from django.forms import inlineformset_factory
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView
from forms.models.fund_operation import FundOperation
from forms.forms.fund_operation_forms import FundOperati... | [
"from django.db import transaction\nfrom django.forms import inlineformset_factory\nfrom django.shortcuts import render\nfrom django.urls import reverse_lazy\nfrom django.views.generic import CreateView, UpdateView\nfrom forms.models.fund_operation import FundOperation\nfrom forms.forms.fund_operation_forms import ... | false |
8,807 | 3f80c4c212259a8f3ff96bcc745fd28a85dac3ba | # Import
import sys
from .step import Step
from .repeat import Repeat
# Workout
class Workout(object):
def __init__(self):
self.workout = []
self.steps = []
self.postfixEnabled = True
# TODO: check that len(name) <= 6
def addStep(self, name, duration):
self.workout.append(... | [
"# Import\nimport sys\nfrom .step import Step\nfrom .repeat import Repeat\n\n# Workout\nclass Workout(object):\n\n def __init__(self):\n self.workout = []\n self.steps = []\n self.postfixEnabled = True\n\n # TODO: check that len(name) <= 6\n def addStep(self, name, duration):\n ... | false |
8,808 | c4ac7ff5d45af9d325f65b4d454a48ca0d8f86df | N, M = map(int, input().split()) # Nはスイッチの数、Mは電球の数
lights = [[0] * N for _ in range(M)]
for i in range(M):
temp = list(map(int, input().split())) # 0番目はスイッチの個数、1番目以降はスイッチを示す
k = temp[0]
switches = temp[1:]
for j in range(k):
lights[i][switches[j]-1] = 1
P = list(map(int, input().split())) # 個数を... | [
"N, M = map(int, input().split()) # Nはスイッチの数、Mは電球の数\nlights = [[0] * N for _ in range(M)]\nfor i in range(M): \n temp = list(map(int, input().split())) # 0番目はスイッチの個数、1番目以降はスイッチを示す\n k = temp[0]\n switches = temp[1:]\n for j in range(k):\n lights[i][switches[j]-1] = 1\nP = list(map(int, input().sp... | false |
8,809 | 24bc43c1fe035430afde05fec1330e27fb5f1d86 | import sys
import re
import math
s=sys.stdin.read()
digits=re.findall(r"-?\d+",s)
listline= [int(e) for e in digits ]
x=listline[-1]
del(listline[-1])
n=len(listline)//2
customers=listline[:n]
grumpy=listline[n:]
maxcus=0
if x==n:
print(sum(customers))
else:
for i in range(n-x):
total=0
for j in... | [
"import sys\nimport re\nimport math\ns=sys.stdin.read()\ndigits=re.findall(r\"-?\\d+\",s)\nlistline= [int(e) for e in digits ]\nx=listline[-1]\ndel(listline[-1])\nn=len(listline)//2\ncustomers=listline[:n]\ngrumpy=listline[n:]\nmaxcus=0\nif x==n:\n print(sum(customers))\nelse:\n for i in range(n-x):\n ... | false |
8,810 | 2402188380bc0189b88e3cfcbaabf64a9919b3d5 | import pygame
import sys
# класс для хранения настроек
class Settings():
"""docstring for Setting"""
def __init__(self):
# параметры экрана
self.colour = (230, 230, 230)
self.screen_width = 1200
self.screen_height = 800
# параметры коробля
self.ship_speed = 1.5
# параметры пули
self.bullet_speed = ... | [
"import pygame\nimport sys\n\n# класс для хранения настроек\nclass Settings():\n\t\"\"\"docstring for Setting\"\"\"\n\tdef __init__(self):\n\t\t# параметры экрана\n\t\tself.colour = (230, 230, 230)\n\t\tself.screen_width = 1200\n\t\tself.screen_height = 800\t\n\t\t# параметры коробля\n\t\tself.ship_speed = 1.5\n\n\... | false |
8,811 | 9c751dece67ef33ba8e5cb8281f024d2143e0808 | import os
import sys
import winreg
import zipfile
class RwpInstaller:
railworks_path = None
def extract(self, target):
with zipfile.ZipFile(target) as z:
if z.testzip():
return self.output('Corrupt file {}\n'.format(target))
self.output('{} file valid\n\n'.for... | [
"import os\nimport sys\nimport winreg\nimport zipfile\n\n\nclass RwpInstaller:\n\n railworks_path = None\n\n def extract(self, target):\n with zipfile.ZipFile(target) as z:\n if z.testzip():\n return self.output('Corrupt file {}\\n'.format(target))\n self.output('{}... | false |
8,812 | 97d128694709c4fe0d9ec2b2749d8e4ec5df7322 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from fieldsets import getSingleField, SortAsc
from sqlalchemy import func
from ladderdb import ElementNotFoundException, EmptyRankingListException
from db_entities import Player, Result
from bottle import route,request
from globe import db,env
@route('/player')
def output( ):... | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom fieldsets import getSingleField, SortAsc\nfrom sqlalchemy import func\nfrom ladderdb import ElementNotFoundException, EmptyRankingListException\nfrom db_entities import Player, Result\nfrom bottle import route,request\nfrom globe import db,env\n\n@route('/player')... | true |
8,813 | 347d468f15dee8a8219d201251cedffe21352f7c | from django.contrib.auth.models import User
from django.test import Client
from django.utils.timezone import localdate
from pytest import fixture
from operations.models import ToDoList
@fixture
def user(db):
return User.objects.create(
username='test', email='saidazimovaziza@gmail.com',
password=... | [
"from django.contrib.auth.models import User\nfrom django.test import Client\nfrom django.utils.timezone import localdate\nfrom pytest import fixture\n\nfrom operations.models import ToDoList\n\n\n@fixture\ndef user(db):\n return User.objects.create(\n username='test', email='saidazimovaziza@gmail.com',\n... | false |
8,814 | 8cc97ebe0ff7617eaf31919d40fa6c312d7b6f94 | # accessing array elements rows/columns
import numpy as np
a = np.array([[1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3]])
print(a.shape) # array shape
print(a)
print('\n')
# specific array element [r,c]
# item 6
print(a[0][5])
# item 8
print(a[1][1]) # or
print(a[1][-6])
# get a specific row/specific column
print(a... | [
"# accessing array elements rows/columns\nimport numpy as np\n\na = np.array([[1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3]])\nprint(a.shape) # array shape\nprint(a)\nprint('\\n')\n\n# specific array element [r,c]\n# item 6\nprint(a[0][5])\n\n# item 8\nprint(a[1][1]) # or\nprint(a[1][-6])\n\n# get a specific row/s... | false |
8,815 | a1b33d0a8a074bc7a2a3e2085b1ff01267e00d3b | def minutes to hours(minutes) :
hours = minutes/60
return hours
print(minutes to hours(70))
| [
"def minutes to hours(minutes) :\r\n hours = minutes/60\r\n return hours\r\n\r\nprint(minutes to hours(70))\r\n"
] | true |
8,816 | 070330f8d343ff65852c5fbb9a3e96fe1bfc55b5 | # pylint: disable=not-callable, no-member, invalid-name, missing-docstring, arguments-differ
import argparse
import itertools
import os
import torch
import torch.nn as nn
import tqdm
import time_logging
from hanabi import Game
def mean(xs):
xs = list(xs)
return sum(xs) / len(xs)
@torch.jit.script
def swis... | [
"# pylint: disable=not-callable, no-member, invalid-name, missing-docstring, arguments-differ\nimport argparse\nimport itertools\nimport os\n\nimport torch\nimport torch.nn as nn\nimport tqdm\n\nimport time_logging\nfrom hanabi import Game\n\n\ndef mean(xs):\n xs = list(xs)\n return sum(xs) / len(xs)\n\n\n@to... | false |
8,817 | 88af8b4eeb40ecf19622ecde1a5dea9a078bb66c | # Percy's playground.
from __future__ import print_function
import sympy as sp
import numpy as np
import BorderBasis as BB
np.set_printoptions(precision=3)
from IPython.display import display, Markdown, Math
sp.init_printing()
R, x, y = sp.ring('x,y', sp.RR, order=sp.grevlex)
I = [ x**2 + y**2 - 1.0, x + y ]
R, x, y... | [
"# Percy's playground.\n\nfrom __future__ import print_function\nimport sympy as sp\nimport numpy as np\nimport BorderBasis as BB\nnp.set_printoptions(precision=3)\nfrom IPython.display import display, Markdown, Math\nsp.init_printing()\n\nR, x, y = sp.ring('x,y', sp.RR, order=sp.grevlex)\nI = [ x**2 + y**2 - 1.0, ... | false |
8,818 | 38a79f5b3ce1beb3dc1758880d42ceabc800ece7 | # Generated by Django 3.0 on 2019-12-15 16:20
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blog', '0013_auto_20191215_1619'),
]
operations = [
migrations.AlterField(
m... | [
"# Generated by Django 3.0 on 2019-12-15 16:20\n\nimport datetime\nfrom django.db import migrations, models\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0013_auto_20191215_1619'),\n ]\n\n operations = [\n migrations.AlterF... | false |
8,819 | 32e60c672d6e73600d442c4344743deccaed6796 | from .core import S3FileSystem, S3File
from .mapping import S3Map
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| [
"from .core import S3FileSystem, S3File\nfrom .mapping import S3Map\n\nfrom ._version import get_versions\n__version__ = get_versions()['version']\ndel get_versions\n",
"from .core import S3FileSystem, S3File\nfrom .mapping import S3Map\nfrom ._version import get_versions\n__version__ = get_versions()['version']\... | false |
8,820 | 9fbf994cb99369ba0c20383007ce52c99248bacf |
# code below
#taking filename as pyscript.py
from distutils.core import setup
import py2exe
setup(console=['pyscript.py'])
# command to run
# python setup.py pytoexe
| [
"\n# code below \n#taking filename as pyscript.py \n\nfrom distutils.core import setup \n\n\nimport py2exe \n\nsetup(console=['pyscript.py'])\n\n\n\n# command to run \n# python setup.py pytoexe \n",
"from distutils.core import setup\nimport py2exe\nsetup(console=['pyscript.py'])\n",
"<import token>\nsetup(conso... | false |
8,821 | 78761eda403ad8f54187e5858a23c23d3dd79b09 | """"Module for miscellaneous behavior stuff
For example, stuff like extracting lick times or choice times.
TrialSpeak shouldn't depend on stuff like that.
# Also get the pldf and use that to get lick times
ldf = ArduFSM.TrialSpeak.read_logfile_into_df(bdf.loc[idx, 'filename'])
# Get the lick times
... | [
"\"\"\"\"Module for miscellaneous behavior stuff\n\nFor example, stuff like extracting lick times or choice times.\nTrialSpeak shouldn't depend on stuff like that.\n\n\n # Also get the pldf and use that to get lick times\n ldf = ArduFSM.TrialSpeak.read_logfile_into_df(bdf.loc[idx, 'filename']) \n \n # G... | false |
8,822 | f76a3fac75e7e2b156f4bff5094f11009b65b599 | # Generated by Django 3.1.7 on 2021-03-25 00:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('restaurante', '0003_auto_20210324_1932'),
]
operations = [
migrations.AlterModelOptions(
name='comprobantemodel',
options={'... | [
"# Generated by Django 3.1.7 on 2021-03-25 00:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('restaurante', '0003_auto_20210324_1932'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='comprobantemodel',\n ... | false |
8,823 | 6e9fd8ee2a187888df07c9dd1c32fe59a111c869 | #downloads project detail reports from the web and places them in the correct project folder created by makeFolders.py
import os, openpyxl, time, shutil
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
wb = openpyxl.load_workbook('ProjectSummary.xlsx')
sheet = wb.active
browser = webdri... | [
"#downloads project detail reports from the web and places them in the correct project folder created by makeFolders.py\n\nimport os, openpyxl, time, shutil\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nwb = openpyxl.load_workbook('ProjectSummary.xlsx')\nsheet = wb.active\n\nbr... | false |
8,824 | c5605f4770d61d435cc1817bad4d5cbe0aaf1d18 | from sys import stdin
read = lambda: stdin.readline().strip()
class Trie:
def __init__(self, me, parent=None):
self.me = me
self.parent = parent
self.children = {}
def get_answer(trie, count):
print(("--" * count) + trie.me)
trie.children = dict(sorted(trie.children.items(), key... | [
"from sys import stdin\nread = lambda: stdin.readline().strip()\n\n\nclass Trie:\n def __init__(self, me, parent=None):\n self.me = me\n self.parent = parent\n self.children = {}\n\n\ndef get_answer(trie, count):\n print((\"--\" * count) + trie.me)\n\n trie.children = dict(sorted(trie.... | false |
8,825 | 3dd9ce6d5d1ba0bebadae4068e2c898802180e1d | #!/usr/bin/env python
# $Id: iprscan5_urllib2.py 2809 2015-03-13 16:10:25Z uludag $
# ======================================================================
#
# Copyright 2009-2014 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex... | [
"#!/usr/bin/env python\n# $Id: iprscan5_urllib2.py 2809 2015-03-13 16:10:25Z uludag $\n# ======================================================================\n#\n# Copyright 2009-2014 EMBL - European Bioinformatics Institute\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not us... | true |
8,826 | 5cced6d9f5e01b88951059bc89c5d10cfd160f60 | """
Write two functions:
1. `to_list()`, which converts a number to an integer list of its digits.
2. `to_number()`, which converts a list of integers back to its number.
### Examples
to_list(235) ➞ [2, 3, 5]
to_list(0) ➞ [0]
to_number([2, 3, 5]) ➞ 235
to_number([0]) ➞ 0
### No... | [
"\"\"\"\r\n\n\nWrite two functions:\n\n 1. `to_list()`, which converts a number to an integer list of its digits.\n 2. `to_number()`, which converts a list of integers back to its number.\n\n### Examples\n\n to_list(235) ➞ [2, 3, 5]\n \n to_list(0) ➞ [0]\n \n to_number([2, 3, 5]) ➞ 235\n \n t... | true |
8,827 | 46b1fc975fbeedcafaa66c85c378e2249a495647 |
def read_int():
return int(input().strip())
def read_ints():
return list(map(int, input().strip().split(' ')))
def solve():
K, S = read_ints()
# X+Y+Z = S
# 0 <= X,Y,Z <= K
total = 0
for X in range(K+1):
if S-X < 0:
break
# Y+Z=S-X
Y_min = max(S-X-K,... | [
"\n\ndef read_int():\n return int(input().strip())\n\n\ndef read_ints():\n return list(map(int, input().strip().split(' ')))\n\n\ndef solve():\n K, S = read_ints()\n # X+Y+Z = S\n # 0 <= X,Y,Z <= K\n total = 0\n for X in range(K+1):\n if S-X < 0:\n break\n # Y+Z=S-X\n ... | false |
8,828 | 8ce468460a81c7869f3abb69035a033c58e0f699 | import numpy as np
"""
function for calculating integrals using the trapezoid method
x is a vector of independent variables
y is a vector of dependent variables
a is the initial value
b is the final value
n is the number of intervals
y_generator is the function to be integrated
"""
def tra... | [
"import numpy as np\n\n\"\"\"\n function for calculating integrals using the trapezoid method\n x is a vector of independent variables\n y is a vector of dependent variables\n a is the initial value\n b is the final value\n n is the number of intervals\n y_generator is the function to be integr... | false |
8,829 | e2f6e6e872f95471ebbc8b25bde08247fe8f7e61 | import media
import fresh_tomatoes
toy_story = media.Movie("Toy Story",
"A story of a boy and his toys that come to life",
'<p><a href="https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg"><img src="https://upload.wikimedia.org/wikipedia/en/1/13/To... | [
"import media\nimport fresh_tomatoes\n\ntoy_story = media.Movie(\"Toy Story\",\n \"A story of a boy and his toys that come to life\",\n '<p><a href=\"https://en.wikipedia.org/wiki/File:Toy_Story.jpg#/media/File:Toy_Story.jpg\"><img src=\"https://upload.wikimedia.org/wik... | false |
8,830 | 03f3fcb38877570dea830a56460061bd3ccb8927 | import os
import matplotlib.pyplot as plt
import cv2
import numpy as np
def divide_img(img_path, img_name, save_path):
imgg = img_path +'\\' +img_name
print(imgg)
img = cv2.imread(imgg)
print(img)
# img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
h = img.shape[0]
w = img.shape[1]
n = 8
... | [
"import os\nimport matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\n\n\ndef divide_img(img_path, img_name, save_path):\n imgg = img_path +'\\\\' +img_name\n print(imgg)\n img = cv2.imread(imgg)\n print(img)\n # img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n h = img.shape[0]\n w = img.sh... | false |
8,831 | 23f491bbf26ede9052ecdab04b8c00cc78db5a7e | from sklearn import preprocessing
from random import shuffle
import numpy as np
import collections
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D
from tensorflow.keras.models import Sequential, model_from_json
from t... | [
"from sklearn import preprocessing\nfrom random import shuffle\nimport numpy as np\nimport collections\n\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Conv1D, GlobalMaxPooling1D\nfrom tensorflow.keras.models import Sequential, model_fro... | false |
8,832 | f5f14e4d114855b7eef555db182ee991bdf26c39 | from django.contrib.auth.models import BaseUserManager
class MyUserManager(BaseUserManager):
def create_user(self, email, password, full_name, national_code, mobile, address):
if not email :
raise ValueError('ایمیل الزامی است')
if not full_name :
raise ValueError('نام و نام... | [
"from django.contrib.auth.models import BaseUserManager\n\n\nclass MyUserManager(BaseUserManager):\n def create_user(self, email, password, full_name, national_code, mobile, address):\n if not email :\n raise ValueError('ایمیل الزامی است')\n if not full_name :\n raise ValueErr... | false |
8,833 | 75270fb4ed059f134b47b8937717cb7fe05d9499 | from threading import Lock
from typing import Callable, Any
from remote.domain.commandCallback import CommandCallback
from remote.domain.commandStatus import CommandStatus
from remote.service.remoteService import RemoteService
from ui.domain.subroutine.iSubroutineRunner import ISubroutineRunner
class RemoteSubroutin... | [
"from threading import Lock\nfrom typing import Callable, Any\n\nfrom remote.domain.commandCallback import CommandCallback\nfrom remote.domain.commandStatus import CommandStatus\nfrom remote.service.remoteService import RemoteService\nfrom ui.domain.subroutine.iSubroutineRunner import ISubroutineRunner\n\n\nclass R... | false |
8,834 | 8f1e6ea93b2dd7add256cb31d2c621aa69721609 | import wx
import os
# os.environ["HTTPS_PROXY"] = "http://user:pass@192.168.1.107:3128"
import wikipedia
import wolframalpha
import pyttsx3
import webbrowser
import winshell
import json
import requests
import ctypes
import random
from urllib.request import urlopen
import speech_recognition as sr
import ssl
import urlli... | [
"import wx\nimport os\n# os.environ[\"HTTPS_PROXY\"] = \"http://user:pass@192.168.1.107:3128\"\nimport wikipedia\nimport wolframalpha\nimport pyttsx3\nimport webbrowser\nimport winshell\nimport json\nimport requests\nimport ctypes\nimport random\nfrom urllib.request import urlopen\nimport speech_recognition as sr\n... | false |
8,835 | 661b622708692bd9cd1b3399835f332c86e39bf6 | class Error(Exception):
pass
class TunnelInstanceError(Error):
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TunnelManagerError(Error):
def __init__(self, expression, message):
self.expression = expression
self.messag... | [
"class Error(Exception):\n pass\n\n\nclass TunnelInstanceError(Error):\n\n def __init__(self, expression, message):\n self.expression = expression\n self.message = message\n\n\nclass TunnelManagerError(Error):\n\n def __init__(self, expression, message):\n self.expression = expression\... | false |
8,836 | 11db76cba3dd76cad0d660a0e189d3e4c465071b | from typing import Any, Optional
from aiogram import types
from aiogram.dispatcher.middlewares import BaseMiddleware
from scene_manager.loader.loader import Loader
from scene_manager.utils import content_type_checker
class ScenesMiddleware(BaseMiddleware):
def __init__(self, *, loader: Optional[Loader] = None, ... | [
"from typing import Any, Optional\n\nfrom aiogram import types\nfrom aiogram.dispatcher.middlewares import BaseMiddleware\n\nfrom scene_manager.loader.loader import Loader\nfrom scene_manager.utils import content_type_checker\n\n\nclass ScenesMiddleware(BaseMiddleware):\n def __init__(self, *, loader: Optional[L... | false |
8,837 | f14ff29a1a76c2916cb211c476a56aaa5061bf71 | # -*- coding: utf-8 -*-
import sys
import setuptools
from distutils.core import setup
with open("README.md", "r") as fh:
long_description = fh.read()
def get_info():
init_file = 'PIKACHU/__init__.py'
with open(init_file, 'r') as f:
for line in f.readlines():
if "=" in line:
... | [
"# -*- coding: utf-8 -*-\n\nimport sys\nimport setuptools\nfrom distutils.core import setup\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ndef get_info():\n init_file = 'PIKACHU/__init__.py'\n with open(init_file, 'r') as f:\n for line in f.readlines():\n if... | false |
8,838 | decd5d50025fc3b639be2f803d917ff313cf7219 | from collections import Counter
N = int(input())
lst = list(map(int, input().split()))
ans = []
for i in range(N):
ans.append(abs(i+1-lst[i]))
s = Counter(ans)
rst = []
for i in s:
rst.append([i, s[i]])
rst.sort(key=lambda x: x[0], reverse=True)
for i in rst:
if i[1] > 1:
print(i[0], i[1])
| [
"from collections import Counter\n\nN = int(input())\nlst = list(map(int, input().split()))\nans = []\nfor i in range(N):\n ans.append(abs(i+1-lst[i]))\ns = Counter(ans)\nrst = []\nfor i in s:\n rst.append([i, s[i]])\nrst.sort(key=lambda x: x[0], reverse=True)\nfor i in rst:\n if i[1] > 1:\n print(i... | false |
8,839 | 728f9402b3ce4b297be82b3ba1a17c4180ac7c0d | '''
Statistics models module. This module contains the database models for the
Statistics class and the StatisticsCategory class.
@author Hubert Ngu
@author Jason Hou
'''
from django.db import models
class Statistics(models.Model):
'''
Statistics model class. This represents a single tuple in the
... | [
"'''\r\n Statistics models module. This module contains the database models for the\r\n Statistics class and the StatisticsCategory class.\r\n\r\n @author Hubert Ngu\r\n @author Jason Hou\r\n'''\r\n\r\nfrom django.db import models\r\n\r\nclass Statistics(models.Model):\r\n\t'''\r\n\tStatistics model class. This rep... | false |
8,840 | ae475dc95c6a099270cf65d4b471b4b430f02303 | """
Kernel desnity estimation plots for geochemical data.
"""
import copy
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator
from ...comp.codata import close
from ...util.log import Handle
from ...util.meta import get_additional_params, subkwargs
from ...util.plot.axes import... | [
"\"\"\"\nKernel desnity estimation plots for geochemical data.\n\"\"\"\nimport copy\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import MaxNLocator\n\nfrom ...comp.codata import close\nfrom ...util.log import Handle\nfrom ...util.meta import get_additional_params, subkwargs\nfrom .... | false |
8,841 | 96086885e5353f3b4b3277c1daf4ee74831c3b73 | from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import *
from kivy.clock import Clock
from kivy.properties import StringProperty, BooleanProperty
from kivy.uix.popup import Popup
import time
from math import sin, pi
from kivy.lang import Builder
from ui.custom_widgets import I18NPopup, I18NLabel
Builder.... | [
"from kivy.uix.boxlayout import BoxLayout\nfrom kivy.graphics import *\nfrom kivy.clock import Clock\nfrom kivy.properties import StringProperty, BooleanProperty\nfrom kivy.uix.popup import Popup\nimport time\nfrom math import sin, pi\n\nfrom kivy.lang import Builder\nfrom ui.custom_widgets import I18NPopup, I18NLa... | false |
8,842 | 4ca4d4bd684802b056417be4ee3d7d10e8f5dc85 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .authority import *
from .ca_pool import *
fro... | [
"# coding=utf-8\n# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***\n# *** Do not edit by hand unless you're certain you know what you are doing! ***\n\nfrom .. import _utilities\nimport typing\n# Export this package's modules as members:\nfrom .authority import *\nfrom .ca_pool... | false |
8,843 | e553da92b1bb5dfaa0fb7c702f5be4f66201c75b | # coding: UTF-8
import fileinput
import io
from locale import str
import os
__author__ = 'lidong'
def getDirList( p ):
p = p.replace( "/","\\")
if p[ -1] != "\\":
p = p+"\\"
a = os.listdir( p )
for x in a:
if(os.path.isfile( p + x )):
a, b = os.path.splitext( p + x )
... | [
"# coding: UTF-8\nimport fileinput\nimport io\nfrom locale import str\nimport os\n\n__author__ = 'lidong'\n\n\ndef getDirList( p ):\n p = p.replace( \"/\",\"\\\\\")\n if p[ -1] != \"\\\\\":\n p = p+\"\\\\\"\n a = os.listdir( p )\n for x in a:\n if(os.path.isfile( p + x )):\n a, b ... | false |
8,844 | ca7b0553e55e1c5e6cd23139a158101e72456a50 | from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth.models import User, Group
class UserTests(APITestCase):
def test_user_list(self):
# must be rejected without validation
response = self.client.get('/api/us... | [
"from django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom django.contrib.auth.models import User, Group\n\nclass UserTests(APITestCase): \n \n def test_user_list(self):\n # must be rejected without validation\n response = self.clien... | false |
8,845 | 252d6b381af09dbafb1d10c188eb154e53213033 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 15 06:50:48 2018
@author: Tony
"""
import glob
import pandas as pd
path =r'C:\Users\Tony\Downloads\daily_dataset\daily_dataset' # use your path
frame = pd.DataFrame()
list_ = []
def aggSumFn(path,grpByCol):
allFiles = glob.glob(path + "/*.csv")
... | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 15 06:50:48 2018\r\n\r\n@author: Tony\r\n\"\"\"\r\n\r\nimport glob\r\nimport pandas as pd\r\n\r\npath =r'C:\\Users\\Tony\\Downloads\\daily_dataset\\daily_dataset' # use your path\r\n\r\nframe = pd.DataFrame()\r\nlist_ = []\r\ndef aggSumFn(path,grpByCol):\r\n ... | false |
8,846 | 118380f58cd173d2de5572a1591766e38ca4a7f8 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
from datetime import datetime
class Config(object):
# ...
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'postgres' or 'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
MONGODB_DB... | [
"import os\nbasedir = os.path.abspath(os.path.dirname(__file__))\nfrom datetime import datetime\n\n\nclass Config(object):\n # ...\n SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \\\n 'postgres' or 'sqlite:///' + os.path.join(basedir, 'app.db')\n SQLALCHEMY_TRACK_MODIFICATIONS = False\... | false |
8,847 | 53cf2dfe3319c39ca6f1dc890eea578fae654b5b | # Evolutionary Trees contains algorithms and methods used in determining phylogenetic inheritance of various species.
# Main algos UPGMA and CLUSTALW
from dataclasses import dataclass
import FormattingET
@dataclass
class Node:
age: int
num: int
label: str
alignment: []
def __init__(self, child1=Non... | [
"# Evolutionary Trees contains algorithms and methods used in determining phylogenetic inheritance of various species.\n# Main algos UPGMA and CLUSTALW\nfrom dataclasses import dataclass\nimport FormattingET\n\n@dataclass\nclass Node:\n age: int\n num: int\n label: str\n alignment: []\n def __init__(... | false |
8,848 | 65bb3743ca569c295d85016c82c4f6f043778d3f | from django.contrib import admin
from .models import Recipe, Ingredient, ChosenIngredient, timezone
# Register your models here.)
admin.site.register(Ingredient)
admin.site.site_header = "Chef's Apprentice Admin"
admin.site.site_title = "Chef's Apprentice Admin Portal"
admin.site.index_title = "Welcome to Chef's Appre... | [
"from django.contrib import admin\nfrom .models import Recipe, Ingredient, ChosenIngredient, timezone\n\n# Register your models here.)\nadmin.site.register(Ingredient)\nadmin.site.site_header = \"Chef's Apprentice Admin\"\nadmin.site.site_title = \"Chef's Apprentice Admin Portal\"\nadmin.site.index_title = \"Welcom... | false |
8,849 | 72bbbe78db746febc9a36a676e0fa2d97bf5e81e | """ Crie um programa onde o usuario possa digitar sete valores numericos e cadastre-os em uma lisa unicaque mantenha
separados os valores pares e impares. No final, mostre os valores ares e impares em ordem crescente """
n = [[],[]]
for c in range(0,7):
num = int(input(f'Digite o {c+1} valor: '))
res = num % ... | [
"\"\"\" Crie um programa onde o usuario possa digitar sete valores numericos e cadastre-os em uma lisa unicaque mantenha\nseparados os valores pares e impares. No final, mostre os valores ares e impares em ordem crescente \"\"\"\n\nn = [[],[]]\n\nfor c in range(0,7):\n num = int(input(f'Digite o {c+1} valor: '))... | false |
8,850 | 81f49c55edff7678e9d1745e39a8370e2c31c9ea | """
___________________________________________________
| _____ _____ _ _ _ |
| | __ \ | __ (_) | | | |
| | |__) |__ _ __ __ _ _ _| |__) || | ___ | |_ |
| | ___/ _ \ '_ \ / _` | | | | ___/ | |/ _ \| __| |
| | | | __/ | | | (_| | |_| | | | | |... | [
"\"\"\"\n ___________________________________________________\n | _____ _____ _ _ _ |\n | | __ \\ | __ (_) | | | |\n | | |__) |__ _ __ __ _ _ _| |__) || | ___ | |_ |\n | | ___/ _ \\ '_ \\ / _` | | | | ___/ | |/ _ \\| __| |\n | | | | __/ | | | (_|... | true |
8,851 | 52426ec670dd5ca522c7fb0b659e3a42b16ff326 | #!/usr/bin/python
import sys
f = open('/etc/passwd','r')
users_and_ids = []
for line in f:
u,_,id,_ = line.split(':',3)
users_and_ids.append((u,int(id)))
users_and_ids.sort(key = lambda pair:pair[1])
for id,usr in users_and_ids:
print id,usr
| [
"#!/usr/bin/python\nimport sys\nf = open('/etc/passwd','r')\nusers_and_ids = []\nfor line in f:\n u,_,id,_ = line.split(':',3)\n users_and_ids.append((u,int(id)))\nusers_and_ids.sort(key = lambda pair:pair[1])\nfor id,usr in users_and_ids:\n print id,usr\n\n\n"
] | true |
8,852 | 806bdb75eed91d1429d8473a50c136b58a736147 | """
Visualize the predictions of a GQCNN on a dataset Visualizes TP, TN, FP, FN..
Author: Vishal Satish
"""
import copy
import logging
import numpy as np
import os
import sys
from random import shuffle
import autolab_core.utils as utils
from autolab_core import YamlConfig, Point
from perception import BinaryImage, Co... | [
"\"\"\"\nVisualize the predictions of a GQCNN on a dataset Visualizes TP, TN, FP, FN..\nAuthor: Vishal Satish \n\"\"\"\nimport copy\nimport logging\nimport numpy as np\nimport os\nimport sys\nfrom random import shuffle\n\nimport autolab_core.utils as utils\nfrom autolab_core import YamlConfig, Point\nfrom perceptio... | true |
8,853 | 06339e9cd506f147d03c54aee82473e233b4ec2e | from .routes import generate_routes | [
"from .routes import generate_routes",
"from .routes import generate_routes\n",
"<import token>\n"
] | false |
8,854 | 5f50b20bd044471ebb8e1350d1a75a250b255d8f | # ********************************************************************************** #
# #
# Project: Data Frame Explorer #
# Author: Pawel Rosikiewicz ... | [
"# ********************************************************************************** #\n# #\n# Project: Data Frame Explorer # \n# Author: Pawel Rosikiew... | false |
8,855 | 601ef4e1000348059dcfe8d34eec5f28368f2464 | /Users/alyssaliguori/anaconda3/lib/python3.7/tokenize.py | [
"/Users/alyssaliguori/anaconda3/lib/python3.7/tokenize.py"
] | true |
8,856 | bbd5eb1f80843efdd2709aa19a65bf325a88f473 | # Developed by Lorenzo Mambretti, Justin Wang
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://github.com/jtwwang/hanabi/blob/master/LICENSE
#
# Unless required by applic... | [
"# Developed by Lorenzo Mambretti, Justin Wang\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# https://github.com/jtwwang/hanabi/blob/master/LICENSE\r\n#\r\n# Un... | false |
8,857 | 0b4f070d30642449536118accffa371a89dd3075 | # views which respond to ajax requests
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.models import User
from social.models import Like, Post, Comment, Notification
from social.notifications import Notify
from social.forms import CommentForm
from django.http impor... | [
"# views which respond to ajax requests\r\n\r\nfrom django.contrib import messages\r\nfrom django.conf import settings\r\nfrom django.contrib.auth.models import User\r\nfrom social.models import Like, Post, Comment, Notification\r\nfrom social.notifications import Notify\r\nfrom social.forms import CommentForm\r\nf... | false |
8,858 | 4fc4bb81d47a33e4669df46033033fddeca6544e | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 11:52:48 2022
@author: ccamargo
"""
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import os
# 1. get filelist
path = "/Volumes/LaCie_NIOZ/data/steric/data/"
path_to_original_files = path + "original/"
flist = [file for ... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 1 11:52:48 2022\n\n@author: ccamargo\n\"\"\"\n\nimport xarray as xr\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\n# 1. get filelist\npath = \"/Volumes/LaCie_NIOZ/data/steric/data/\"\npath_to_original_files = path + \"... | false |
8,859 | d267bf82aee2eca29628fcd1d874a337adc1ae09 | import math
class Solution:
# @param {integer} n
# @param {integer} k
# @return {string}
def getPermutation(self, n, k):
res = ''
k -= 1
nums = [str(i) for i in range(1, n+1)]
while n > 0:
tmp = math.factorial(n-1)
res += nums[k/tmp]
d... | [
"import math\n\nclass Solution:\n # @param {integer} n\n # @param {integer} k\n # @return {string}\n def getPermutation(self, n, k):\n res = ''\n k -= 1\n nums = [str(i) for i in range(1, n+1)]\n while n > 0:\n tmp = math.factorial(n-1)\n res += nums[k/t... | true |
8,860 | ad5cdcfd9d7a3c07abcdcb701422f3c0fdc2b374 | from Bio import BiopythonWarning, SeqIO
from Bio.PDB import MMCIFParser, Dice, PDBParser
from Bio.SeqUtils import seq1
import time
import requests
import re
import warnings
warnings.simplefilter('ignore', BiopythonWarning)
def get_response(url):
response = requests.get(url)
cnt = 20
while cnt != 0:
... | [
"from Bio import BiopythonWarning, SeqIO\nfrom Bio.PDB import MMCIFParser, Dice, PDBParser\nfrom Bio.SeqUtils import seq1\n\nimport time\nimport requests\nimport re\nimport warnings\n\nwarnings.simplefilter('ignore', BiopythonWarning)\n\n\ndef get_response(url):\n response = requests.get(url)\n cnt = 20\n ... | false |
8,861 | b005f4657a1036044c2e6051207641fe621eb17e | # Constructor without arguments
class Demo:
def __init__(self):
print("\nThis is constructor")
obj = Demo()
# Constructor with arguments
class Demo2:
def __init__(self, number1, number2):
sumOfNumbers = number1 + number2
print(sumOfNumbers)
obj2 = Demo2(50,75... | [
"# Constructor without arguments\r\nclass Demo:\r\n def __init__(self):\r\n print(\"\\nThis is constructor\")\r\n \r\nobj = Demo()\r\n\r\n# Constructor with arguments\r\nclass Demo2:\r\n def __init__(self, number1, number2):\r\n sumOfNumbers = number1 + number2\r\n print(sumOfNumb... | false |
8,862 | 4f84cf80292e2764ca3e4da79858058850646527 | import json, requests, math, random
#import datagatherer
# Constants:
start_elo = 0 # Starting elo
decay_factor = 0.9 # Decay % between stages
k = 30 # k for elo change
d = 200 # Difference in elo for 75% expected WR
overall_weight = 0.60 # Weigts for different types o... | [
"import json, requests, math, random\n#import datagatherer\n\n# Constants:\nstart_elo = 0 # Starting elo\ndecay_factor = 0.9 # Decay % between stages\nk = 30 # k for elo change\nd = 200 # Difference in elo for 75% expected WR\noverall_weight = 0.60 # Weigts for diff... | false |
8,863 | de287d1bc644fdfd0f47bd8667580786b74444d0 | class Solution(object):
def smallestGoodBase(self, n):
"""
:type n: str
:rtype: str
"""
# k is the base and the representation is
# m bits of 1
# We then have from math
# (k**m - 1) / (k-1) = n
# m = log_k (n * k - n + 1)
# m needs to b... | [
"class Solution(object):\n def smallestGoodBase(self, n):\n \"\"\"\n :type n: str\n :rtype: str\n \"\"\"\n # k is the base and the representation is\n # m bits of 1\n # We then have from math\n # (k**m - 1) / (k-1) = n\n # m = log_k (n * k - n + 1)\n... | false |
8,864 | 6a4a5eac1b736ee4f8587adba298571f90df1cf9 | from .queue_worker import QueueWorker
import threading
class WorkersOrchestrator:
@classmethod
def worker_func(cls, worker):
worker.start_consumption()
def run_orchestrator(self, num_of_workers):
worker_list = []
for i in range(num_of_workers):
worker_list.append(Queu... | [
"from .queue_worker import QueueWorker\nimport threading\n\n\nclass WorkersOrchestrator:\n @classmethod\n def worker_func(cls, worker):\n worker.start_consumption()\n\n def run_orchestrator(self, num_of_workers):\n worker_list = []\n\n for i in range(num_of_workers):\n worke... | false |
8,865 | 61179dc734069017adaabd53804ed0102d9416e3 | from django.contrib.auth.models import User
from django.db import models
class Chat(models.Model):
category = models.CharField(unique=True, max_length=100)
def __str__(self):
return self.category
class ChatMessage(models.Model):
context = models.CharField(max_length=1000)
user = models.Fore... | [
"from django.contrib.auth.models import User\nfrom django.db import models\n\n\nclass Chat(models.Model):\n category = models.CharField(unique=True, max_length=100)\n\n def __str__(self):\n return self.category\n\n\nclass ChatMessage(models.Model):\n context = models.CharField(max_length=1000)\n ... | false |
8,866 | f5513bea4ca5f4c2ac80c4bf537a264a4052d1e9 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import random
a = random.sample(range(100), 10)
print("All items: {}".format(a))
it = iter(a) # call a.__iter__()
print("Num01: {}".format(next(it))) # call it.__next__()
print("Num02: {}".format(next(it)))
print("Num03: {}".format(it.__next__()))
it = iter(a)
i = 1
while... | [
"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport random\n\na = random.sample(range(100), 10)\nprint(\"All items: {}\".format(a))\n\nit = iter(a) # call a.__iter__()\n\nprint(\"Num01: {}\".format(next(it))) # call it.__next__()\nprint(\"Num02: {}\".format(next(it)))\nprint(\"Num03: {}\".format(it.__next__()))\... | false |
8,867 | 67793c8851e7107c6566da4e0ca5d5ffcf6341ad | import csv
from functools import reduce
class Csvread:
def __init__(self, fpath):
self._path=fpath
with open (fpath) as file:
read_f=csv.reader(file)
print(read_f) #<_csv.reader object at 0x000002A53144DF40>
self._sheet = list(read_f)[1:] #utworzenie listy
... | [
"import csv\nfrom functools import reduce\n\nclass Csvread:\n\n def __init__(self, fpath):\n self._path=fpath\n with open (fpath) as file:\n read_f=csv.reader(file)\n print(read_f) #<_csv.reader object at 0x000002A53144DF40>\n\n self._sheet = list(read_f)[1:] #utwo... | false |
8,868 | 67ac5d82bc37b67cfdae73b6667b73b70ed33cfb | '''
Paulie Jo Gonzalez
CS 4375 - os
Lab 0
Last modified: 02/14/2021
This code includes a reference to C code for my_getChar method provided by Dr. Freudenthal.
'''
from os import read
next_c = 0
limit = 0
def get_char():
global next_c, limit
if next_c == limit:
next_c = 0
limit = read(0, 10... | [
"'''\nPaulie Jo Gonzalez\nCS 4375 - os\nLab 0\nLast modified: 02/14/2021\nThis code includes a reference to C code for my_getChar method provided by Dr. Freudenthal.\n'''\n\nfrom os import read\n\nnext_c = 0\nlimit = 0\n\n\ndef get_char():\n global next_c, limit\n\n if next_c == limit:\n next_c = 0\n ... | false |
8,869 | 62c28b5eb31b90191dfbab4456fc5373ba51bf64 | import pytest
import os
import pandas as pd
import numpy as np
import math
import scipy
from scipy import stats
from sklearn import metrics, linear_model
from gpmodel import gpkernel
from gpmodel import gpmodel
from gpmodel import gpmean
from gpmodel import chimera_tools
n = 200
d = 10
X = np.random.random(size=(n, ... | [
"import pytest\nimport os\n\nimport pandas as pd\nimport numpy as np\nimport math\nimport scipy\nfrom scipy import stats\nfrom sklearn import metrics, linear_model\n\nfrom gpmodel import gpkernel\nfrom gpmodel import gpmodel\nfrom gpmodel import gpmean\nfrom gpmodel import chimera_tools\n\nn = 200\nd = 10\nX = np.r... | false |
8,870 | d49aa03cd6b8ba94d68a1bc1e064f77fded65000 | from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
import requests,pymysql,random,time
import http.cookiejar
from multiprocessing import Pool,Lock
def get_proxies_ip():
db = pymysql.connect("localhost","root","xxx","xxx",charset='utf8')
cursor = db.cursor()
sql = "SELECT * FROM proxies_info;"
... | [
"from bs4 import BeautifulSoup\n\nfrom bs4 import BeautifulSoup\nimport requests,pymysql,random,time\nimport http.cookiejar\nfrom multiprocessing import Pool,Lock\n\ndef get_proxies_ip():\n db = pymysql.connect(\"localhost\",\"root\",\"xxx\",\"xxx\",charset='utf8')\n cursor = db.cursor()\n sql = \"SELECT *... | false |
8,871 | f410a77d4041514383110d9fd16f896178924d59 | # coding: UTF-8
import os
import sys
if len(sys.argv) == 3:
fname = sys.argv[1]
out_dir = sys.argv[2]
else:
print "usage: vcf_spliter <input file> <output dir>"
exit()
count = 0
if not os.path.exists(out_dir):
os.makedirs(out_dir)
with open(fname, 'r') as f:
for l in f:
if l.strip()... | [
"# coding: UTF-8\n\nimport os \nimport sys\n\nif len(sys.argv) == 3:\n fname = sys.argv[1]\n out_dir = sys.argv[2]\nelse:\n print \"usage: vcf_spliter <input file> <output dir>\"\n exit()\n\ncount = 0\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\nwith open(fname, 'r') as f:\n for l in... | true |
8,872 | 25550cbaf6e0e5bdbbe3852bb8cdc05ac300d315 | # 运算符的优先级
# 和数学中一样,在Python运算也有优先级,比如先乘除 后加减
# 运算符的优先级可以根据优先级的表格来查询,
# 在表格中位置越靠下的运算符优先级越高,优先级越高的越优先计算
# 如果优先级一样则自左向右计算
# 关于优先级的表格,你知道有这么一个东西就够了,千万不要去记
# 在开发中如果遇到优先级不清楚的,则可以通过小括号来改变运算顺序
a = 1 + 2 * 3
# 一样 and高 or高
# 如果or的优先级高,或者两个运算符的优先级一样高
# 则需要先进行或运算,则运算结果是3
# 如果and的优先级高,则应该先计算与运算
# 则运算结果是1
a = 1 or 2 and 3
... | [
"# 运算符的优先级\n# 和数学中一样,在Python运算也有优先级,比如先乘除 后加减\n# 运算符的优先级可以根据优先级的表格来查询,\n# 在表格中位置越靠下的运算符优先级越高,优先级越高的越优先计算\n# 如果优先级一样则自左向右计算\n# 关于优先级的表格,你知道有这么一个东西就够了,千万不要去记\n# 在开发中如果遇到优先级不清楚的,则可以通过小括号来改变运算顺序\na = 1 + 2 * 3\n\n# 一样 and高 or高\n# 如果or的优先级高,或者两个运算符的优先级一样高\n# 则需要先进行或运算,则运算结果是3\n# 如果and的优先级高,则应该先计算与运算\n# 则运算结果是1... | false |
8,873 | 062b6133ba4de24f7eaf041e4b6c039501b47b9a | n_m_q=input().split(" ")
n=int(n_m_q[0])
m=int(n_m_q[1])
q=int(n_m_q[2])
dcc=[]
for i in range(n):
a=[]
dcc.append(a)
available=[]
for i in range(m):
x=input().split(" ")
a=int(x[0])
b=int(x[1])
available.append([a,b])
dcc[a-1].append(b)
dcc[b-1].append(a)
for i in range(q):
x=input(... | [
"n_m_q=input().split(\" \")\nn=int(n_m_q[0])\nm=int(n_m_q[1])\nq=int(n_m_q[2])\ndcc=[]\nfor i in range(n):\n a=[]\n dcc.append(a)\navailable=[]\nfor i in range(m):\n x=input().split(\" \")\n a=int(x[0])\n b=int(x[1])\n available.append([a,b])\n dcc[a-1].append(b)\n dcc[b-1].append(a)\nfor i ... | false |
8,874 | 887ae9b7c629be679bf4f5fb4311c31bff605c73 | import os
import shutil
from tqdm import tqdm
from pathlib import Path
from eval_mead import PERCENT
DATAPATH = '../../../data/test'
# MEAD_DIR = 'mead'
MEAD_DIR = os.path.abspath('mead')
MEAD_DATA_PATH = f'{MEAD_DIR}/data'
MEAD_BIN = f'{MEAD_DIR}/bin'
MEAD_LIB = f'{MEAD_DIR}/lib'
MEAD_FORMATTING_ADDONS = f'{MEAD_BIN}... | [
"import os\nimport shutil\nfrom tqdm import tqdm\nfrom pathlib import Path\nfrom eval_mead import PERCENT\n\nDATAPATH = '../../../data/test'\n# MEAD_DIR = 'mead'\nMEAD_DIR = os.path.abspath('mead')\nMEAD_DATA_PATH = f'{MEAD_DIR}/data'\nMEAD_BIN = f'{MEAD_DIR}/bin'\nMEAD_LIB = f'{MEAD_DIR}/lib'\nMEAD_FORMATTING_ADDO... | false |
8,875 | 74c60c9e37e4e13ed4c61f631c3426b685b5d38f | from django.conf.urls import patterns, include, url
from views.index import Index
from views.configuracoes import Configuracoes
from views.parametros import *
urlpatterns = patterns('',
url(r'^$', Index.as_view(), name='core_index'),
url(r'^configuracoes/', Configuracoes.as_view(), name='core.core_c... | [
"from django.conf.urls import patterns, include, url\r\n\r\nfrom views.index import Index\r\nfrom views.configuracoes import Configuracoes\r\n\r\nfrom views.parametros import *\r\n\r\nurlpatterns = patterns('',\r\n url(r'^$', Index.as_view(), name='core_index'),\r\n url(r'^configuracoes/', Configuracoes.as_vi... | false |
8,876 | a5c19ad60ac6312631273858cebaae944a2008ec | def contador_notas(multiplo, numero):
if(numero % multiplo == 0):
notas = numero / multiplo
return notas
else:
return -1
entrada = int(input())
resultado = contador_notas(100, entrada)
if (resultado != -1):
print("{} nota(s) de R$ {}".format(resultado, 100)) | [
"def contador_notas(multiplo, numero):\n if(numero % multiplo == 0):\n notas = numero / multiplo\n return notas\n else:\n return -1\n\n\nentrada = int(input())\nresultado = contador_notas(100, entrada)\nif (resultado != -1):\n print(\"{} nota(s) de R$ {}\".format(resultado, 100))",
"... | false |
8,877 | 905d8be76ef245a2b8fcfb3f806f8922d351ecf0 | import pickle
import numpy as np
import math
class AdaBoostClassifier:
'''A simple AdaBoost Classifier.'''
def __init__(self, weak_classifier, n_weakers_limit):
'''Initialize AdaBoostClassifier
Args:
weak_classifier: The class of weak classifier, which is recommend to be sklearn.t... | [
"import pickle\nimport numpy as np\nimport math\n\nclass AdaBoostClassifier:\n '''A simple AdaBoost Classifier.'''\n\n def __init__(self, weak_classifier, n_weakers_limit):\n '''Initialize AdaBoostClassifier\n\n Args:\n weak_classifier: The class of weak classifier, which is recommend... | false |
8,878 | c6d8b9faa610e817c449eee94d73c61cb62fa272 | print('test 123123')
| [
"print('test 123123')\n",
"<code token>\n"
] | false |
8,879 | 92e7a7825b3f49424ec69196b69aee00bc84da68 | #!/usr/bin/python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Antirollback clock user space support.
This daemon serves several purposes:
1. Maintain a file containing the minimum time, and periodically
update its value.
2. At startup, write the minimum time to /proc/ar_clock.
The kernel will n... | [
"#!/usr/bin/python\n# Copyright 2012 Google Inc. All Rights Reserved.\n\n\"\"\"Antirollback clock user space support.\n\nThis daemon serves several purposes:\n 1. Maintain a file containing the minimum time, and periodically\n update its value.\n 2. At startup, write the minimum time to /proc/ar_clock.\n ... | true |
8,880 | 6dafb60b79a389499ae2a0f17f9618426faf45a9 | def Return():
s = raw_input('Enter a s: ')
i = 0
s1 = ''
leng = len(s)
while i < leng:
if s[i] == s[i].lower():
s1 += s[i].upper()
else:
s1 += s[i].lower()
i += 1
return s1
if __name__ == '__main__':
print Return()
| [
"def Return():\n s = raw_input('Enter a s: ')\n i = 0\n s1 = ''\n leng = len(s)\n while i < leng:\n if s[i] == s[i].lower():\n s1 += s[i].upper()\n else:\n s1 += s[i].lower()\n i += 1\n \n return s1\n\nif __name__ == '__main__':\n \n print ... | true |
8,881 | 97fb2388777bcb459b9818495121fdf8318095ca | '''
check if word appear in file
'''
# easier solution :
def findKeyInFile(word, filepath):
with open(filepath) as f:
for line in f.readlines():
if line.count(word) > 0:
return line
return None
| [
"'''\ncheck if word appear in file\n'''\n# easier solution :\ndef findKeyInFile(word, filepath):\n with open(filepath) as f:\n for line in f.readlines():\n if line.count(word) > 0:\n return line\n return None\n\n\n",
"<docstring token>\n\n\ndef findKeyInFile(word, filepath):... | false |
8,882 | b1622aa65422fcb69a16ad48a26fd9ed05b10382 | import pytest
from components import models
pytestmark = pytest.mark.django_db
def test_app_models():
assert models.ComponentsApp.allowed_subpage_models() == [
models.ComponentsApp,
models.BannerComponent,
]
def test_app_required_translatable_fields():
assert models.ComponentsApp.get_r... | [
"import pytest\n\nfrom components import models\n\npytestmark = pytest.mark.django_db\n\n\ndef test_app_models():\n assert models.ComponentsApp.allowed_subpage_models() == [\n models.ComponentsApp,\n models.BannerComponent,\n ]\n\n\ndef test_app_required_translatable_fields():\n assert models... | false |
8,883 | 5f490d6a3444b3b782eed5691c82ab7e4b2e55db | from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdri... | [
"from selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom sele... | true |
8,884 | 493b29433f0c3646e7f80fca2f656fc4a5256003 | from functools import wraps
class aws_retry:
"""retries the call (required for some cases where data is not consistent yet in AWS"""
def __init__(self, fields):
self.fields = fields # field to inject
def __call__(self, function):
pass
#code ... | [
"from functools import wraps\n\n\nclass aws_retry:\n\n \"\"\"retries the call (required for some cases where data is not consistent yet in AWS\"\"\"\n def __init__(self, fields):\n self.fields = fields # field to inject\n\n def __call__(self, function):\n ... | false |
8,885 | 292c66bd5b7f56ee8c27cabff01cd97ff36a79dc | from django.contrib import admin
from .models import Wbs, Equipment_Type
class WbsAdmin(admin.ModelAdmin):
list_display = ('code','description','equipment_type')
list_filter = ('code','description','equipment_type')
readonly_fields = ('code','description')
class Equipment_TypeAdmin(admin.ModelAdmi... | [
"from django.contrib import admin\r\nfrom .models import Wbs, Equipment_Type\r\n\r\nclass WbsAdmin(admin.ModelAdmin):\r\n list_display = ('code','description','equipment_type')\r\n list_filter = ('code','description','equipment_type')\r\n readonly_fields = ('code','description')\r\n\r\nclass Equipment_Type... | false |
8,886 | 8b18f098080c3f5773aa04dffaff0639fe7fa74f | g=int(input())
num=0
while(g>0):
num=num+g
g=g-1
print(num)
| [
"g=int(input())\nnum=0\nwhile(g>0):\n num=num+g\n g=g-1\nprint(num)\n",
"g = int(input())\nnum = 0\nwhile g > 0:\n num = num + g\n g = g - 1\nprint(num)\n",
"<assignment token>\nwhile g > 0:\n num = num + g\n g = g - 1\nprint(num)\n",
"<assignment token>\n<code token>\n"
] | false |
8,887 | 62e0c3b6095a65a4508eddfa9c0a1cb31d6c917b | #OpenCV create samples commands
#opencv_createsamples -img watch5050.jpg -bg bg.txt -info info/info.lst -pngoutput info -maxxangle 0.5 -maxyangle 0.5 -maxzangle 0.5 -num 1950
#opencv_createsamples -info info/info.lst -num 1950 -w 20 -h 20 -vec positives.vec
#Training command
#opencv_traincascade -data data -vec p... | [
"#OpenCV create samples commands\r\n#opencv_createsamples -img watch5050.jpg -bg bg.txt -info info/info.lst -pngoutput info -maxxangle 0.5 -maxyangle 0.5 -maxzangle 0.5 -num 1950\r\n#opencv_createsamples -info info/info.lst -num 1950 -w 20 -h 20 -vec positives.vec\r\n\r\n#Training command\r\n#opencv_traincascade -d... | false |
8,888 | 1ba39cfc1187b0efc7fc7e905a15de8dc7f80e0d | from textmagic.rest import TextmagicRestClient
username = 'lucychibukhchyan'
api_key = 'sjbEMjfNrrglXY4zCFufIw9IPlZ3SA'
client = TextmagicRestClient(username, api_key)
message = client.message.create(phones="7206337812", text="wow i sent a text from python!!!!")
| [
"from textmagic.rest import TextmagicRestClient\n\nusername = 'lucychibukhchyan'\napi_key = 'sjbEMjfNrrglXY4zCFufIw9IPlZ3SA'\nclient = TextmagicRestClient(username, api_key)\n\nmessage = client.message.create(phones=\"7206337812\", text=\"wow i sent a text from python!!!!\")\n",
"from textmagic.rest import Textma... | false |
8,889 | dd91ba13177aefacc24ef4a004acae0bffafadf0 | #!/usr/bin/env conda-execute
# conda execute
# env:
# - python >=3
# - requests
# run_with: python
from configparser import NoOptionError
from configparser import SafeConfigParser
import argparse
import base64
import inspect
import ipaddress
import json
import logging
import logging.config
import o... | [
"#!/usr/bin/env conda-execute\r\n\r\n# conda execute\r\n# env:\r\n# - python >=3\r\n# - requests\r\n# run_with: python\r\n\r\nfrom configparser import NoOptionError\r\nfrom configparser import SafeConfigParser\r\nimport argparse\r\nimport base64\r\nimport inspect\r\nimport ipaddress\r\nimport json\r\nimport loggi... | true |
8,890 | 28a0ae0492fb676044c1f9ced7a5a4819e99a8d9 | import math
import numpy as np
import cv2
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from sklearn import metrics
from scipy.spatial.distance import cdist
if (__name__ == "__main__"):
cap = cv2.VideoCapture('dfd1.mp4')
mog = cv2.createBackgroundSubtractorMOG2(detectSha... | [
"import math\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom sklearn.cluster import KMeans\r\nfrom sklearn import metrics\r\nfrom scipy.spatial.distance import cdist\r\n\r\n\r\nif (__name__ == \"__main__\"):\r\n cap = cv2.VideoCapture('dfd1.mp4')\r\n mog = cv2.createBac... | false |
8,891 | b838d2230cb3f3270e86807e875df4d3d55438cd | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 8 22:11:53 2020
@author: Rick
"""
sum= 0;
with open('workRecord.txt') as fp:
for line in fp.readlines():
idx= line.rfind('x',len(line)-8,len(line))
if idx>=0:
sum+= float(line.rstrip()[idx+1:len(line)])
else:
sum+= 1
pr... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 8 22:11:53 2020\n\n@author: Rick\n\"\"\"\nsum= 0;\nwith open('workRecord.txt') as fp:\n for line in fp.readlines():\n idx= line.rfind('x',len(line)-8,len(line))\n if idx>=0:\n sum+= float(line.rstrip()[idx+1:len(line)])\n else:... | false |
8,892 | fd54bbfbc81aec371ad6c82bf402a5a3673a9f24 | # -*- encoding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 6
_modified_time = 1383550959.0389481
_template_filename='templates/webapps/tool_shed/repository/browse_repository.mako'
_template_uri='/webapps/tool_shed/r... | [
"# -*- encoding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 6\n_modified_time = 1383550959.0389481\n_template_filename='templates/webapps/tool_shed/repository/browse_repository.mako'\n_template_uri='/webapp... | false |
8,893 | 89e5e82c073f7f87c00fc844c861c6c5cbe6a695 |
import smart_imports
smart_imports.all()
class LogicTests(utils_testcase.TestCase):
def setUp(self):
super(LogicTests, self).setUp()
game_logic.create_test_map()
self.account_1 = self.accounts_factory.create_account()
self.account_1_items = prototypes.AccountItemsPrototype.ge... | [
"\nimport smart_imports\n\nsmart_imports.all()\n\n\nclass LogicTests(utils_testcase.TestCase):\n\n def setUp(self):\n super(LogicTests, self).setUp()\n\n game_logic.create_test_map()\n\n self.account_1 = self.accounts_factory.create_account()\n\n self.account_1_items = prototypes.Acco... | false |
8,894 | efed5c113e085e5b41d9169901c18c06111b9077 | from snake.snake import Snake
# Start application
if __name__ == '__main__':
s = Snake()
s.run() | [
"from snake.snake import Snake\n\n# Start application\nif __name__ == '__main__':\n s = Snake()\n s.run()",
"from snake.snake import Snake\nif __name__ == '__main__':\n s = Snake()\n s.run()\n",
"<import token>\nif __name__ == '__main__':\n s = Snake()\n s.run()\n",
"<import token>\n<code to... | false |
8,895 | 2d4680b63cdd05e89673c4bd6babda7ac6ebb588 | from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from crud.serializers import TodoListSerializer
from crud.models import TodoList
# Create your views here.
class TodoListViewSet(viewsets.ModelViewSet):
queryset = TodoList.objects.all()
seri... | [
"from django.shortcuts import render\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nfrom crud.serializers import TodoListSerializer\nfrom crud.models import TodoList\n\n# Create your views here.\n\nclass TodoListViewSet(viewsets.ModelViewSet):\n queryset = TodoList.objects... | false |
8,896 | e4fb932c476ca0222a077a43499bf9164e1f27d0 | import configparser
config = configparser.ConfigParser()
config.read('config.ini')
settings=config['Settings']
colors=config['Colors']
import logging
logger = logging.getLogger(__name__)
logLevel = settings.getint('log-level')
oneLevelUp = 20
#I don't know if this will work before loading the transformers module?
#s... | [
"import configparser\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nsettings=config['Settings']\ncolors=config['Colors']\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogLevel = settings.getint('log-level')\noneLevelUp = 20\n\n#I don't know if this will work before loading the transf... | false |
8,897 | 0738fc48bc367f1df75567ab97ce20d3e747dc18 | cassandra = {
'nodes': ['localhost'],
'keyspace': 'coffee'
}
| [
"cassandra = {\n 'nodes': ['localhost'],\n 'keyspace': 'coffee'\n}\n",
"cassandra = {'nodes': ['localhost'], 'keyspace': 'coffee'}\n",
"<assignment token>\n"
] | false |
8,898 | 4b5794ff79371c2e49c5d2b621805b08c4ff7acb | from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from ex.models import Teacher,Student,Group,Report,TeamEvaluation,PrivateLetter,ChatBoxIsOpen
from django.core import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from django.cont... | [
"from django.shortcuts import render\nfrom django.http import HttpResponse,JsonResponse\nfrom ex.models import Teacher,Student,Group,Report,TeamEvaluation,PrivateLetter,ChatBoxIsOpen\nfrom django.core import serializers\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfro... | false |
8,899 | a98d03b169b59704b3b592cee0b59f5389fd77b3 | #! /usr/bin/env python3
import sys
def stage_merge_checksums(
old_survey=None,
survey=None,
brickname=None,
**kwargs):
'''
For debugging / special-case processing, read previous checksums, and update them with
current checksums values, then write out the result.
'''
... | [
"#! /usr/bin/env python3\nimport sys\n\ndef stage_merge_checksums(\n old_survey=None,\n survey=None,\n brickname=None,\n **kwargs):\n '''\n For debugging / special-case processing, read previous checksums, and update them with\n current checksums values, then write out the resul... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.