index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
4,600 | 7fd5e83d28e919e7b94cea290c6b4db3378938b6 | from fastapi import APIRouter, Depends, status, Response
from typing import List
import schemas, database
from sqlalchemy.orm import Session
import repository.blog as blog
from .oauth2 import get_current_user
router = APIRouter(
prefix="/blog",
tags=['Blog'])
@router.get('/', status_code=statu... | [
"from fastapi import APIRouter, Depends, status, Response\nfrom typing import List\nimport schemas, database\nfrom sqlalchemy.orm import Session\nimport repository.blog as blog\nfrom .oauth2 import get_current_user\n\nrouter = APIRouter(\n prefix=\"/blog\",\n tags=['Blog'])\n\n@router.get('/',... | false |
4,601 | f7d29dd1d990b3e07a7c07a559cf5658b6390e41 |
#create a list
a = [2,3,4,5,6,7,8,9,10]
print(a)
#indexing
b = int(input('Enter indexing value:'))
print('The result is:',a[b])
print(a[8])
print(a[-1])
#slicing
print(a[0:3])
print(a[0:])
#conconteation
b=[20,30]
print(a+b)
#Repetition
print(b*3)
#updating
print(a[2])
a[2]=100
print(a)
#membership
print(5 in a)
... | [
"\n#create a list\na = [2,3,4,5,6,7,8,9,10]\nprint(a)\n#indexing\nb = int(input('Enter indexing value:'))\nprint('The result is:',a[b])\nprint(a[8])\nprint(a[-1])\n\n#slicing\nprint(a[0:3])\nprint(a[0:])\n\n#conconteation\nb=[20,30]\nprint(a+b)\n\n#Repetition\nprint(b*3)\n\n#updating\nprint(a[2])\na[2]=100\nprint(a... | false |
4,602 | 62fe29b0ac4dee8fec4908cf803dba9bd7e92fa5 | from tkinter import *
from get_train_set import *
from datetime import *
counter = 0
week = int ( datetime.today().isocalendar() [1] )
def update (a,b):
global counter
if b == 'x':
b = 0
a = week
counter = 0
else:
counter += b
a += counter
... | [
"from tkinter import *\r\nfrom get_train_set import *\r\nfrom datetime import *\r\n\r\ncounter = 0\r\n\r\nweek = int ( datetime.today().isocalendar() [1] )\r\n\r\n\r\ndef update (a,b):\r\n global counter\r\n \r\n if b == 'x':\r\n b = 0\r\n a = week\r\n counter = 0\r\n else:\r\n ... | false |
4,603 | 7474e60feff61c4ef15680ecc09d910e6e1d6322 | def IsPn(a):
temp = (24*a+1)**0.5+1
if temp % 6 == 0:
return True
else:
return False
def IsHn(a):
temp = (8*a+1)**0.5+1
if temp % 4 == 0:
return True
else:
return False
def CalTn(a):
return (a**2+a)/2
i = 286
while 1:
temp = CalTn(i)
if IsHn(temp) and IsPn(temp):
break
i += 1
print i,temp | [
"def IsPn(a):\n\ttemp = (24*a+1)**0.5+1\n\tif temp % 6 == 0:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef IsHn(a):\n\ttemp = (8*a+1)**0.5+1\n\tif temp % 4 == 0:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef CalTn(a):\n\treturn (a**2+a)/2\n\ni = 286\nwhile 1:\n\ttemp = CalTn(i)\n\tif IsHn(temp) and IsPn(t... | true |
4,604 | f56978d5738c2f8cb4ed5ce4f11d3aae6a9689b1 | import datetime
class Schedule:
def __init__(self, start, end, name, other): # Constructor
self.start = self.str_convert(start) # Schedule start time (ex. 9:00)
self.end = self.str_convert(end) # Schedule end time (ex. 22:00)
... | [
"import datetime\n\nclass Schedule:\n def __init__(self, start, end, name, other): # Constructor\n self.start = self.str_convert(start) # Schedule start time (ex. 9:00)\n self.end = self.str_convert(end) # Schedule end time (ex. 2... | false |
4,605 | 3923aed29006b4290437f2b0e11667c702da3241 | # %%
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA, TruncatedSVD
import matplotlib.patches as mpatches
import time
from sklearn.linear_model import LogisticRegression
from skle... | [
"# %%\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA, TruncatedSVD\nimport matplotlib.patches as mpatches\nimport time\n\nfrom sklearn.linear_model import LogisticRegr... | false |
4,606 | 97637e2114254b41ef6e777e60b3ddab1d4622e8 | from django.forms import ModelForm
from contactform.models import ContactRequest
class ContactRequestForm(ModelForm):
class Meta:
model = ContactRequest
| [
"from django.forms import ModelForm\nfrom contactform.models import ContactRequest\n\n\nclass ContactRequestForm(ModelForm):\n class Meta:\n model = ContactRequest\n\n",
"from django.forms import ModelForm\nfrom contactform.models import ContactRequest\n\n\nclass ContactRequestForm(ModelForm):\n\n\n ... | false |
4,607 | cca543f461724c3aac8fef23ef648883962bd706 | from os import getenv
LISTEN_IP = getenv('LISTEN_IP', '0.0.0.0')
LISTEN_PORT = int(getenv('LISTEN_PORT', 51273))
LISTEN_ADDRESS = LISTEN_IP, LISTEN_PORT
CONFIRMATION = getenv('CONFIRMATION')
if CONFIRMATION:
CONFIRMATION = CONFIRMATION.encode()
class UDPProtocol:
def __init__(self, consumer):
self... | [
"from os import getenv\n\n\nLISTEN_IP = getenv('LISTEN_IP', '0.0.0.0')\nLISTEN_PORT = int(getenv('LISTEN_PORT', 51273))\nLISTEN_ADDRESS = LISTEN_IP, LISTEN_PORT\n\nCONFIRMATION = getenv('CONFIRMATION')\nif CONFIRMATION:\n CONFIRMATION = CONFIRMATION.encode()\n\n\nclass UDPProtocol:\n\n def __init__(self, cons... | false |
4,608 | 0a7a95755924fd264169286cc5b5b7587d7ee8e4 | import turtle
import math
from tkinter import *
#活性边表节点:
class AetNode(object):
def __init__(self,x,tx,my):
self.x=x
self.tx=tx
self.my=my
def op(self):
return self.x
class AetList(object):
def __init__(self,y):
self.y=y
self.numy=0
self.l=[]
p... | [
"import turtle\nimport math\nfrom tkinter import *\n#活性边表节点:\nclass AetNode(object):\n def __init__(self,x,tx,my):\n self.x=x\n self.tx=tx\n self.my=my\n def op(self):\n return self.x\nclass AetList(object):\n def __init__(self,y):\n self.y=y\n self.numy=0\n ... | false |
4,609 | a8fb8ac3c102e460d44e533b1e6b3f8780b1145d | # Downloads images from http://www.verseoftheday.com/ and saves it into a DailyBibleVerse folder
import requests, os, bs4
os.chdir('c:\\users\\patty\\desktop') #modify location where you want to create the folder
if not os.path.isdir('DailyBibleVerse'):
os.makedirs('DailyBibleVerse')
res = request... | [
"# Downloads images from http://www.verseoftheday.com/ and saves it into a DailyBibleVerse folder \r\n\r\nimport requests, os, bs4\r\n\r\nos.chdir('c:\\\\users\\\\patty\\\\desktop') #modify location where you want to create the folder\r\nif not os.path.isdir('DailyBibleVerse'):\r\n os.makedirs('DailyBibleV... | false |
4,610 | 53519c704ca9aff62140f187d4246208350fa9ba | # Generated by Django 2.1.2 on 2018-11-05 12:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('PDPAPI', '0011_auto_20181105_1021'),
]
operations = [
migrations.RemoveField(
model_name='optionvoting',
name='total... | [
"# Generated by Django 2.1.2 on 2018-11-05 12:00\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('PDPAPI', '0011_auto_20181105_1021'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='optionvoting',\n ... | false |
4,611 | 63e5ead200fb2884d93f19e7d9b8dc76c7f4f0e3 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Python version 3.8.5
#
# Author Maria Catharina van Veen
#
# Purpose To provide users with a tool to create
# or edit an html file.
#
# Tested OS This code was written and tested to
# work with Windows 10.
... | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Python version 3.8.5\n#\n# Author Maria Catharina van Veen\n#\n# Purpose To provide users with a tool to create\n# or edit an html file.\n#\n# Tested OS This code was written and tested to\n# work wi... | false |
4,612 | d625e6724a3fe077a6f80b6de6b1f5bb0b95d47d | import requests
from bs4 import BeautifulSoup
import json
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
url = 'http://api.tvmaze.com/singlesearch/shows?q=game+of+throne&embed=episodes'
response = requests.get(url, headers = hea... | [
"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\nheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}\nurl = 'http://api.tvmaze.com/singlesearch/shows?q=game+of+throne&embed=episodes'\n\nresponse = requests.get(url, h... | false |
4,613 | 6c349b7b4d82b37ec1b1ff8e0d35a3557ed1af67 | def calculaEuclidiana(obj1,obj2):
soma = 0
for I in range(len(obj1)):
soma += (obj1[I] - obj2[I])**2
return soma ** 0.5
def calculaMinkowski(obj1,obj2,p):
# p = 2 => distancia Euclidiana
# p = 1 => distancia de Manhattan
soma = 0
for I in range(len(obj1)):
soma += (abs(obj1[... | [
"def calculaEuclidiana(obj1,obj2):\n soma = 0\n for I in range(len(obj1)):\n soma += (obj1[I] - obj2[I])**2\n return soma ** 0.5\n\ndef calculaMinkowski(obj1,obj2,p):\n # p = 2 => distancia Euclidiana\n # p = 1 => distancia de Manhattan\n soma = 0\n for I in range(len(obj1)):\n so... | false |
4,614 | d60a2100127db859162890204655d313cdc2a4a5 | # -*- coding: utf-8 -*-
import scrapy
import MySQLdb
import openpyxl
from scrapy.crawler import CrawlerProcess
import sys
class AllabolaSpider(scrapy.Spider):
name = 'allabola'
allowed_domains = ['https://www.allabolag.se']
start_urls = []
#'https://www.allabolag.se/7696250484/befattningar'
host =... | [
"# -*- coding: utf-8 -*-\nimport scrapy\nimport MySQLdb\nimport openpyxl\nfrom scrapy.crawler import CrawlerProcess\nimport sys\n\n\nclass AllabolaSpider(scrapy.Spider):\n name = 'allabola'\n allowed_domains = ['https://www.allabolag.se']\n start_urls = []\n #'https://www.allabolag.se/7696250484/befattn... | false |
4,615 | 66ae7f4ee01ca5516d8e3dc447eeb4709e2b6aec | import datetime
import time
def calculate(a):
return a
data = set()
class Bank:
amount = 0
def __init__(self):
self.Bank_name = "State Bank of India"
self.ifsc = 'SBI0N00012'
def __repr__(self):
return f'Bank Name: {self.Bank_name}, IFSC_Code : {self.ifsc} '
# se... | [
"import datetime\nimport time\n\ndef calculate(a):\n return a\n\n\ndata = set()\nclass Bank:\n amount = 0\n def __init__(self):\n self.Bank_name = \"State Bank of India\"\n self.ifsc = 'SBI0N00012'\n \n def __repr__(self):\n return f'Bank Name: {self.Bank_name}, IFSC_Code : {self... | false |
4,616 | d30129248f5245560ee0d3ee786e118427e169d7 | import numpy as np
er = ['why','who','how','where','which','what','when','was','were','did','do','does','is','are','many','much']
qst = []
txt = None
ans = None
fnd = []
def chek_qst(qst):
global er
for h in er:
for i in qst:
if i == h:
qst.remove(i)
# qst ... | [
"import numpy as np\n\ner = ['why','who','how','where','which','what','when','was','were','did','do','does','is','are','many','much']\nqst = []\ntxt = None\nans = None\nfnd = []\n\n\ndef chek_qst(qst):\n global er\n for h in er:\n for i in qst:\n if i == h:\n qst.remove(i)\n ... | false |
4,617 | 9cc672702d960088f0230cbd1694b295216d8b5a | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Especialidade(models.Model):
def __str__(self):
return self.nome
# add unique=True?
nome = models.CharField(max_length=200, verbose_name=_('Especialidade'), unique=True, blank=False, null=False)
| [
"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Especialidade(models.Model):\n def __str__(self):\n return self.nome\n\n # add unique=True?\n nome = models.CharField(max_length=200, verbose_name=_('Especialidade'), unique=True, blank=False, null=Fals... | false |
4,618 | 42743ee2a812d8fe6fc036ba97daaff5be35564d | from pytorch_lightning.callbacks import Callback
from evaluation.validator import Validator
class LSTMCallback(Callback):
def on_test_end(self, trainer, pl_module):
f = open('/evaluation.log', 'w')
for ev in pl_module.evaluation_data:
f.write(ev + '\n')
Validator(pl_module.eval... | [
"from pytorch_lightning.callbacks import Callback\nfrom evaluation.validator import Validator\n\n\nclass LSTMCallback(Callback):\n def on_test_end(self, trainer, pl_module):\n f = open('/evaluation.log', 'w')\n for ev in pl_module.evaluation_data:\n f.write(ev + '\\n')\n Validator... | false |
4,619 | dcef5f34a62939d992a109e991552e612bf5bad5 | import pandas as pd
import numpy as np
from datetime import timedelta
import scipy.optimize as optim
from scipy import stats
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from gen_utils.gen_io import read_run_params,log_msg
#############################################
params = read_run_pa... | [
"import pandas as pd\nimport numpy as np\nfrom datetime import timedelta\nimport scipy.optimize as optim\nfrom scipy import stats\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom gen_utils.gen_io import read_run_params,log_msg\n\n\n\n#############################################\n\np... | false |
4,620 | 8bce394c651931304f59bbca3e2f019212be9fc1 | import sys
sys.stdin = open("1868_input.txt")
dr = [-1, -1, -1, 0, 0, 1, 1, 1]
dc = [-1, 0, 1, -1, 1, -1, 0, 1]
def is_wall(r, c):
if r < 0 or r >= n or c < 0 or c >= n:
return True
return False
def find(r, c, cnt):
Q = []
Q.append((r, c))
visited[r][c] = 1
while Q:
tr, tc = Q... | [
"import sys\nsys.stdin = open(\"1868_input.txt\")\n\ndr = [-1, -1, -1, 0, 0, 1, 1, 1]\ndc = [-1, 0, 1, -1, 1, -1, 0, 1]\n\ndef is_wall(r, c):\n if r < 0 or r >= n or c < 0 or c >= n:\n return True\n return False\n\ndef find(r, c, cnt):\n Q = []\n Q.append((r, c))\n visited[r][c] = 1\n while... | false |
4,621 | d9f055301f050eea4281ce418974546c1245ac7e | strings = ['(())())', '(((()())()', '(()())((()))', '((()()(()))(((())))()', '()()()()(()()())()', '(()((())()(']
#print(string[0])
'''
for i in string:
testlist = []
for j in string[i]:
if j == ')':
if
'''
def isVPS(phrase):
testlist = []
for char in phrase:
if char == '(... | [
"strings = ['(())())', '(((()())()', '(()())((()))', '((()()(()))(((())))()', '()()()()(()()())()', '(()((())()(']\n\n#print(string[0])\n'''\nfor i in string:\n testlist = []\n for j in string[i]:\n if j == ')':\n if \n'''\n\ndef isVPS(phrase):\n testlist = []\n for char in phrase:\n ... | false |
4,622 | 420beba5b6fd575ab9be0c907ae0698ba7be5220 |
from xai.brain.wordbase.verbs._hinder import _HINDER
#calss header
class _HINDERED(_HINDER, ):
def __init__(self,):
_HINDER.__init__(self)
self.name = "HINDERED"
self.specie = 'verbs'
self.basic = "hinder"
self.jsondata = {}
| [
"\n\nfrom xai.brain.wordbase.verbs._hinder import _HINDER\n\n#calss header\nclass _HINDERED(_HINDER, ):\n\tdef __init__(self,): \n\t\t_HINDER.__init__(self)\n\t\tself.name = \"HINDERED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"hinder\"\n\t\tself.jsondata = {}\n",
"from xai.brain.wordbase.verbs._hinder impo... | false |
4,623 | 0c37806f0a7c0976711edd685fd64d2616147cb6 | """
Data pre-processing
"""
import os
import corenlp
import numpy as np
import ujson as json
from tqdm import tqdm
from collections import Counter
from bilm import dump_token_embeddings
import sys
sys.path.append('../..')
from LIB.utils import save
def process(json_file, outpur_dir, exclude_titles=None, include_titl... | [
"\"\"\"\nData pre-processing\n\"\"\"\nimport os\nimport corenlp\nimport numpy as np\nimport ujson as json\nfrom tqdm import tqdm\nfrom collections import Counter\nfrom bilm import dump_token_embeddings\nimport sys\nsys.path.append('../..')\n\nfrom LIB.utils import save\n\n\ndef process(json_file, outpur_dir, exclud... | false |
4,624 | 1cc14836808d70c1e53a9ca948a52776ebc89f4a | import dlib
import cv2
import imageio
import torch
from PIL import Image
from model import AgeGenderModel
from mix_model import MixModel
from torchvision.transforms import transforms
from tqdm import tqdm
from retinaface.pre_trained_models import get_model
transform = transforms.Compose([
transforms.Resize((112,... | [
"import dlib\nimport cv2\nimport imageio\nimport torch\nfrom PIL import Image \nfrom model import AgeGenderModel\nfrom mix_model import MixModel\nfrom torchvision.transforms import transforms\nfrom tqdm import tqdm\nfrom retinaface.pre_trained_models import get_model\n\n\ntransform = transforms.Compose([\n trans... | false |
4,625 | 11101273a02abec17fc884d5c1d5d182eb82ee0c | # -*- coding: utf-8 -*-
"""The main application module for duffy."""
from flask import Flask
from duffy import api_v1
from duffy.types import seamicro
from duffy.extensions import db, migrate, marshmallow
from duffy.config import ProdConfig,DevConfig
def create_app(config_object=DevConfig):
app = Flask(__name__... | [
"# -*- coding: utf-8 -*-\n\"\"\"The main application module for duffy.\"\"\"\nfrom flask import Flask\n\nfrom duffy import api_v1\nfrom duffy.types import seamicro\n\nfrom duffy.extensions import db, migrate, marshmallow\nfrom duffy.config import ProdConfig,DevConfig\n\n\ndef create_app(config_object=DevConfig):\n ... | false |
4,626 | 81fce5314a7611de11648e412151112e29271871 | import random
from z3 import *
def combine(iter):
tmp_list = [i for i in iter]
res = tmp_list[0]
for i in tmp_list[1:]:
res += i
return res
def co_prime(num1, num2):
for num in range(2, min(num1, num2) + 1):
if num1 % num == 0 and num2 % num == 0:
return False
re... | [
"import random\n\nfrom z3 import *\n\n\ndef combine(iter):\n tmp_list = [i for i in iter]\n res = tmp_list[0]\n for i in tmp_list[1:]:\n res += i\n return res\n\n\ndef co_prime(num1, num2):\n for num in range(2, min(num1, num2) + 1):\n if num1 % num == 0 and num2 % num == 0:\n ... | false |
4,627 | cf65966f5daf88bdefc7a8aa2ff80835cff0d0b6 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import (
StackingClassifier,
RandomForestClassifier
)
import pandas as pd
from sklearn.metrics import f1_score
# feel free to import any sklearn model here
from sklearn.linear_model import LogisticRegression
from ... | [
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import (\n StackingClassifier,\n RandomForestClassifier\n) \nimport pandas as pd\nfrom sklearn.metrics import f1_score\n# feel free to import any sklearn model here\nfrom sklearn.linear_model import Logistic... | false |
4,628 | f6838906c961a9ca7d91d2ab02fd2af72797b880 | from torch import nn
class MNIST3dModel(nn.Module):
def __init__(self, input_c=3, num_filters=8, num_classes=10):
super().__init__()
self.conv1 = nn.Conv3d(in_channels=input_c,
out_channels=num_filters,
kernel_size=3,
... | [
"from torch import nn\n\nclass MNIST3dModel(nn.Module):\n \n def __init__(self, input_c=3, num_filters=8, num_classes=10):\n super().__init__()\n self.conv1 = nn.Conv3d(in_channels=input_c,\n out_channels=num_filters,\n kernel_size=3,\n... | false |
4,629 | 1346bf78241b4be00f2da3c22731d2846f9d1ada | import shelve
from club import Club
#загальний бютжет клубів в заданій країні
#клуб який має найбільше трофеїв
country = input('country: ')
FILENAME = "clubs"
with shelve.open(FILENAME) as clubs:
clubs_by_country = list(filter(lambda s: s.country.lower() == country.lower(), clubs.values()))
if len(clubs_b... | [
"import shelve\nfrom club import Club\n\n#загальний бютжет клубів в заданій країні\n#клуб який має найбільше трофеїв\n\n\ncountry = input('country: ')\n\nFILENAME = \"clubs\"\n\nwith shelve.open(FILENAME) as clubs:\n clubs_by_country = list(filter(lambda s: s.country.lower() == country.lower(), clubs.values()))\... | false |
4,630 | a29a904290cb733ac7b526a75e0c218b952e2266 | import mysql.connector
# config = {
# "user":"root",
# "password":"Sm13481353",
# "host":"3"
# }
mydb = mysql.connector.connect(
user="seyed",
password="Sm13481353",
host="localhost",
database="telegram_bot",
auth_plugin="mysql_native_password"
)
mycursor = mydb.cursor()
query = "i... | [
"import mysql.connector\n# config = {\n# \"user\":\"root\",\n# \"password\":\"Sm13481353\",\n# \"host\":\"3\"\n# }\nmydb = mysql.connector.connect(\n user=\"seyed\",\n password=\"Sm13481353\",\n host=\"localhost\",\n database=\"telegram_bot\",\n auth_plugin=\"mysql_native_password\"\n ... | false |
4,631 | 872b13a93c9aba55c143ee9891543f059c070a36 | # dg_kernel plots
import os
import re
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import csv
import sys
NE_SIZE = 128
TITLE_SIZE = 35
TEXT_SIZE = 30
MARKER_SIZE = 10
LINE_WIDTH = 5
colors = { idx:cname for idx, cname in enumerate(mcolors.cnames) }
eventname = 'L1_DCM'
cal... | [
"# dg_kernel plots\n\nimport os\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nimport csv\nimport sys\n\nNE_SIZE = 128\nTITLE_SIZE = 35 \nTEXT_SIZE = 30 \nMARKER_SIZE = 10\nLINE_WIDTH = 5\ncolors = { idx:cname for idx, cname in enumerate(mcolors.cnames) }\n\nev... | true |
4,632 | a3ed47c285b26dca452fa192eb354a21a78b8424 | from math import sqrt, ceil
def encode_s(s):
encoded_s = ''
s_with_no_spaces = s.replace(' ', '')
step = ceil(sqrt(len(s_with_no_spaces)))
for j in range(0, step):
i = j
while i < len(s_with_no_spaces):
encoded_s = encoded_s + s_with_no_spaces[i]
i += step
... | [
"from math import sqrt, ceil\n\n\ndef encode_s(s):\n encoded_s = ''\n s_with_no_spaces = s.replace(' ', '')\n step = ceil(sqrt(len(s_with_no_spaces)))\n for j in range(0, step):\n i = j\n while i < len(s_with_no_spaces):\n encoded_s = encoded_s + s_with_no_spaces[i]\n ... | false |
4,633 | b43ea8c32207bf43abc3b9b490688fde0706d876 | A = int(input())
B = int(input())
C = int(input())
number = A * B * C
num = str(number)
for i in range(10): # 9를 입력해서 첨에 틀림 !
count = 0
for j in range(len(num)):
if i == int(num[j]):
count += 1
else:
continue
print(count)
| [
"A = int(input())\nB = int(input())\nC = int(input())\nnumber = A * B * C\nnum = str(number)\nfor i in range(10): # 9를 입력해서 첨에 틀림 !\n count = 0\n for j in range(len(num)):\n if i == int(num[j]):\n count += 1\n else:\n continue\n print(count)\n ",
"A = int(input())\n... | false |
4,634 | a6cc0078fb37f9c63e119046193f521290c9fb21 | # Generated by Django 3.2.8 on 2021-10-20 08:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0006_auto_20211020_0817'),
]
operations = [
migrations.AlterModelOptions(
name='currencies',
options={'verbose_name':... | [
"# Generated by Django 3.2.8 on 2021-10-20 08:25\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0006_auto_20211020_0817'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='currencies',\n optio... | false |
4,635 | 7273592ab8fea10d9a3cde58690063690c74b746 | newList = []
noDuplicate = []
while True:
elem = input("Enter a letter : (type quit to quit) ")
if elem.lower() != "quit":
newList.append(elem)
else:
break
for item in newList:
if item not in noDuplicate:
noDuplicate.append(item)
print(noDuplicate) | [
"newList = []\nnoDuplicate = []\n\nwhile True:\n elem = input(\"Enter a letter : (type quit to quit) \")\n if elem.lower() != \"quit\":\n newList.append(elem)\n else:\n break\n\nfor item in newList:\n if item not in noDuplicate:\n noDuplicate.append(item)\n\nprint(noDuplicate)",
"... | false |
4,636 | 551e9c696eaad6c78f2eae66e50cca34c153d9dd | print "test"
print "moreing"
print " a nnnnn" | [
"print \"test\"\n\nprint \"moreing\"\n\nprint \" a nnnnn\""
] | true |
4,637 | 1b3493322fa85c2fe26a7f308466c4a1c72d5b35 | import numpy as np
import scipy.sparse as sparse
from .world import World
from . import util
from . import fem
from . import linalg
def solveFine(world, aFine, MbFine, AbFine, boundaryConditions):
NWorldCoarse = world.NWorldCoarse
NWorldFine = world.NWorldCoarse*world.NCoarseElement
NpFine = np.prod(NWorl... | [
"import numpy as np\nimport scipy.sparse as sparse\n\nfrom .world import World\nfrom . import util\nfrom . import fem\nfrom . import linalg\n\ndef solveFine(world, aFine, MbFine, AbFine, boundaryConditions):\n NWorldCoarse = world.NWorldCoarse\n NWorldFine = world.NWorldCoarse*world.NCoarseElement\n NpFine... | false |
4,638 | 012e4112970a07559f27fa2127cdffcc557a1566 | list_angle_list = RmList()
variable_flag = 0
variable_i = 0
def user_defined_shoot():
global variable_flag
global variable_i
global list_angle_list
variable_i = 1
for count in range(3):
gimbal_ctrl.angle_ctrl(list_angle_list[1], list_angle_list[2])
gun_ctrl.fire_once()
variab... | [
"list_angle_list = RmList()\nvariable_flag = 0\nvariable_i = 0\ndef user_defined_shoot():\n global variable_flag\n global variable_i\n global list_angle_list\n variable_i = 1\n for count in range(3):\n gimbal_ctrl.angle_ctrl(list_angle_list[1], list_angle_list[2])\n gun_ctrl.fire_once()... | false |
4,639 | 0d3e1df1720812e8546b1f3509c83d1e6566e103 |
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib import messages
from datetime import datetime, timedelta
class DeadlineMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
re... | [
"\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.urls import reverse\r\nfrom django.contrib import messages\r\nfrom datetime import datetime, timedelta\r\n\r\nclass DeadlineMiddleware:\r\n def __init__(self, get_response):\r\n self.get_response = get_response\r\n \r\n def __call__(se... | false |
4,640 | 8417b63e2b7b16d3d58175022662c5b3e59e4aaf | import pytest
from ethereum.tools.tester import TransactionFailed
def test_cant_ever_init_twice(ethtester, root_chain):
ethtester.chain.mine()
with pytest.raises(TransactionFailed):
root_chain.init(sender=ethtester.k0)
with pytest.raises(TransactionFailed):
root_chain.init(sender=ethteste... | [
"import pytest\nfrom ethereum.tools.tester import TransactionFailed\n\n\ndef test_cant_ever_init_twice(ethtester, root_chain):\n ethtester.chain.mine()\n with pytest.raises(TransactionFailed):\n root_chain.init(sender=ethtester.k0)\n\n with pytest.raises(TransactionFailed):\n root_chain.init(... | false |
4,641 | b4d09b6d8ad5f0584f74adc0fd8116265bb6649b | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index_view, name='accounts.index'),
url(r'^login/$', views.login_view, name='accounts.login'),
url(r'^logout/$', views.logout_view, name='accounts.logout'),
url(r'^registro/$', views.registro_usuario_view, name='accou... | [
"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index_view, name='accounts.index'),\n url(r'^login/$', views.login_view, name='accounts.login'),\n url(r'^logout/$', views.logout_view, name='accounts.logout'),\n url(r'^registro/$', views.registro_usuario_view,... | false |
4,642 | dc05a441c21a67fbb3a1975b3fccb865a32731c8 | # Copyright (C) 2020 Francis Sun, all rights reserved.
"""A copyright utility"""
import datetime
import argparse
import os
import os.path
class Copyright:
_file_type = {
'c/c++': ['h', 'c', 'cpp', 'cc'],
'python': ['py'],
'cmake': ['cmake'],
'vim': ['vim'],
... | [
"# Copyright (C) 2020 Francis Sun, all rights reserved.\n\n\"\"\"A copyright utility\"\"\"\n\nimport datetime\nimport argparse\nimport os\nimport os.path\n\n\nclass Copyright:\n _file_type = {\n 'c/c++': ['h', 'c', 'cpp', 'cc'],\n 'python': ['py'],\n 'cmake': ['cmake'],\n ... | false |
4,643 | 2b928dad60bfb0ba863e9039a5462faa885644f3 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pywikibot
from pywikibot import pagegenerators
import re
from pywikibot import xmlreader
import datetime
import collections
from klasa import *
def fraz(data):
data_slownie = data[6:8] + '.' + data[4:6] + '.' + data[0:4]
lista_stron = getListFromXML(data)
... | [
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport pywikibot\nfrom pywikibot import pagegenerators\nimport re\nfrom pywikibot import xmlreader\nimport datetime\nimport collections\nfrom klasa import *\n\ndef fraz(data):\n\n data_slownie = data[6:8] + '.' + data[4:6] + '.' + data[0:4]\n\n lista_stron = getL... | false |
4,644 | 4863581a1a557186ceee8d544d1a996082edcf2c | #####coding=utf-8
import re
import urllib.request
import sys
import redis
from urllib.error import URLError, HTTPError
import urllib.parse
# /redis/cluster/23:1417694197540
def con():
pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password='/redis/cluster/1:1803528818953446384')
r = redis.Stric... | [
"#####coding=utf-8\n\nimport re\nimport urllib.request\nimport sys\nimport redis\nfrom urllib.error import URLError, HTTPError\nimport urllib.parse\n\n\n# /redis/cluster/23:1417694197540\n\ndef con():\n pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password='/redis/cluster/1:1803528818953446384')\n... | false |
4,645 | 2a13fffa105a5dd546c30c892e59888eb6ead996 | def fonct(valeur, a= None):
if type(a) is list:
a.append(valeur)
# a+= valeur
elif type(a) is tuple:
a += tuple((valeur,))
elif type(a) is str:
a += str(valeur)
elif type(a) is set:
a.add(valeur)
el... | [
"def fonct(valeur, a= None):\n if type(a) is list:\n a.append(valeur)\n # a+= valeur\n elif type(a) is tuple: \n a += tuple((valeur,)) \n elif type(a) is str: \n a += str(valeur) \n elif type(a) is set: \n a.add(vale... | false |
4,646 | 4fd4c9cf3bdb73a003ce860bf2ee0ccab01f0009 | # The error measures used in this project
#
# Rooth Mean Squared Error
# Mean Absolute Error
#
# ! Both calculated after descaling the output of the system first
import numpy as np
def RMSE(min_y, max_y, yhat, y):
# first scale output and target back to
# original scale, to prevent scale bias
yhat = descale(yhat,... | [
"# The error measures used in this project\n#\n# Rooth Mean Squared Error\n# Mean Absolute Error\n#\n# ! Both calculated after descaling the output of the system first\n\nimport numpy as np\n\ndef RMSE(min_y, max_y, yhat, y):\n\t# first scale output and target back to \n\t# original scale, to prevent scale bias\n\t... | false |
4,647 | cfa064611a4aa16638bd649c68d64872b9fac1ff | from math import sqrt
def prime_generator(n):
pp=[2,3]
for i in range(3,n):
i+=2
count=0
for ps in pp:
if ps>(sqrt(i)+1):
break
if i%ps==0:
count+=1
break
if count==0:
pp.append(i)
return pp
... | [
"from math import sqrt\ndef prime_generator(n):\n pp=[2,3]\n for i in range(3,n):\n i+=2\n count=0\n for ps in pp:\n if ps>(sqrt(i)+1):\n break\n if i%ps==0:\n count+=1\n break \n if count==0:\n pp.append... | false |
4,648 | 3dc3bbd00f9c2d00093bf8669963d96f5019b2da | import requests
from multiprocessing import Process
from atomic_counter import AtomicCounter
class Downloader:
def __init__(self, src_url, num_threads):
try:
header = requests.head(src_url).headers
self.url = src_url
self.file_size = int(header.get('content-length'))
... | [
"import requests\nfrom multiprocessing import Process\nfrom atomic_counter import AtomicCounter\n\n\nclass Downloader:\n def __init__(self, src_url, num_threads):\n try:\n header = requests.head(src_url).headers\n self.url = src_url\n self.file_size = int(header.get('conte... | false |
4,649 | 6369c692e358c0dfd1193c6e961ecf9b521ea9ba | # Import the SDK
import json
import boto3
from botocore.exceptions import ClientError
import uuid
#dbclient = boto3.client('dynamodb')
dbresource = boto3.resource('dynamodb', region_name='eu-west-1')
rekclient = boto3.client('rekognition','eu-west-1')
collection_name = 'swiftarycelebrity'
ScannedFacestable = dbresour... | [
"# Import the SDK\nimport json\nimport boto3\nfrom botocore.exceptions import ClientError\nimport uuid\n#dbclient = boto3.client('dynamodb')\ndbresource = boto3.resource('dynamodb', region_name='eu-west-1')\n\nrekclient = boto3.client('rekognition','eu-west-1')\ncollection_name = 'swiftarycelebrity'\n\nScannedFaces... | false |
4,650 | dff5a46c6f1eb715fe5e1eec87e42ceb295b0eae | from django.contrib import admin
from django.urls import path, include
from .views import hindex,galeria,mision_vision,direccion,registro,login,logout_vista,registro_insumo,admin_insumos
urlpatterns = [
path('',hindex,name='HINDEX'),
path('galeria/',galeria,name='GALE'),
path('mision/',mision_vision,name=... | [
"from django.contrib import admin\nfrom django.urls import path, include\nfrom .views import hindex,galeria,mision_vision,direccion,registro,login,logout_vista,registro_insumo,admin_insumos\n\n\nurlpatterns = [\n path('',hindex,name='HINDEX'),\n path('galeria/',galeria,name='GALE'),\n path('mision/',mision... | false |
4,651 | 18d7c486b9070a1c607ba2ba5876309246013182 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2021 Opensource ICT Solutions B.V.
# https://oicts.com
#
#version: 1.0.0
#date: 06-11-2021
import requests
import json
import sys
url = 'http://<URL>/zabbix/api_jsonrpc.php?'
token = '<TOKEN>'
headers = {'Content-Type': 'application/json'}
hostname = sys.... | [
"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2021 Opensource ICT Solutions B.V.\n# https://oicts.com\n#\n#version: 1.0.0\n#date: 06-11-2021\n\n\nimport requests\nimport json\nimport sys\n\nurl = 'http://<URL>/zabbix/api_jsonrpc.php?'\ntoken = '<TOKEN>'\n\nheaders = {'Content-Type': 'application/json... | false |
4,652 | e6aa28ae312ea5d7f0f818b7e86b0e76e2e57b48 | from rest_framework import serializers
from films.models import *
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
films = serializers.PrimaryKeyRelatedField(many=True, queryset=Film.objects.all())
theaters = serializers.PrimaryKeyRelatedField(many=True, queryset=F... | [
"from rest_framework import serializers\nfrom films.models import *\nfrom django.contrib.auth.models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n films = serializers.PrimaryKeyRelatedField(many=True, queryset=Film.objects.all())\n theaters = serializers.PrimaryKeyRelatedField(many=True,... | false |
4,653 | e2e2e746d0a8f6b01e6f54e930c7def2d48c2d62 | import json
import random
import uuid
from collections import OrderedDict
import docker
from .db_utils import DBUtils
from .models import DynamicDockerChallenge
class DockerUtils:
@staticmethod
def add_new_docker_container(user_id, challenge_id, flag, port):
configs = DBUtils.get_all_configs()
... | [
"import json\nimport random\nimport uuid\nfrom collections import OrderedDict\n\nimport docker\nfrom .db_utils import DBUtils\nfrom .models import DynamicDockerChallenge\n\n\nclass DockerUtils:\n\n @staticmethod\n def add_new_docker_container(user_id, challenge_id, flag, port):\n configs = DBUtils.get_... | false |
4,654 | ad59c1f0038294144b1c63db5f048b0a6b5ebb89 | # coding: utf-8
'''
Programa : py02_variavel.py
Homepage : http://www
Autor : Helber Palheta <hpalheta@outlook.com>
Execução:
python py02_variavel.py
'''
#variável curso e sua atribuição
curso = "Introdução a Biopython!"
#função print
print("Nome do Curso: "+curso) | [
"# coding: utf-8\n'''\n \n Programa : py02_variavel.py\n Homepage : http://www\n Autor : Helber Palheta <hpalheta@outlook.com>\n\n Execução:\n python py02_variavel.py\n\n''' \n#variável curso e sua atribuição\ncurso = \"Introdução a Biopython!\"\n\n#função print\nprint(\"Nome do Curso: \"+... | false |
4,655 | 17548459b83fe4dea29f20dc5f91196b2b86ea60 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 23 15:26:47 2015
@author: tomhope
"""
import cPickle as pickle
from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import CountVectorizer
import re
def tokenize_speeches(text):
text = re.sub('[\[\]<>\'\+\=\/(.?\",&*!_#:;@$%|)0-9]'," ", text)
... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 23 15:26:47 2015\n\n@author: tomhope\n\"\"\"\nimport cPickle as pickle\nfrom nltk.tokenize import word_tokenize\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport re\n\ndef tokenize_speeches(text):\n text = re.sub('[\\[\\]<>\\'\\+\\=\\/(.?\\\... | true |
4,656 | c6ef9154285dee3b21980801a101ad5e34a50cab |
import os
import yaml
import sys
import random
import shutil
import openpyxl
import yaml
import audioanalysis as aa
import numpy as np
import argparse
import logging
"""
manualtest.py
Script to create a listeneing test. The output, test
case directory and answer_key.yml file, can be
found in the root directory.
m... | [
"\nimport os \nimport yaml\nimport sys\nimport random\nimport shutil\nimport openpyxl\nimport yaml\nimport audioanalysis as aa\nimport numpy as np\nimport argparse\nimport logging\n\"\"\"\nmanualtest.py\n\nScript to create a listeneing test. The output, test \ncase directory and answer_key.yml file, can be \nfound ... | false |
4,657 | be1638638c70cf761bf5d2f0eb474b44684dfa47 |
from __future__ import division
import torch
import torch.nn as nn
import math
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU(inplace=True)
)
def conv_1x1_bn(inp, oup):
return nn.Sequential(
... | [
"\nfrom __future__ import division\nimport torch\nimport torch.nn as nn\nimport math\n\ndef conv_bn(inp, oup, stride):\n return nn.Sequential(\n nn.Conv2d(inp, oup, 3, stride, 1, bias=False),\n nn.BatchNorm2d(oup),\n nn.ReLU(inplace=True)\n )\n\n\ndef conv_1x1_bn(inp, oup):\n return nn... | false |
4,658 | aa2a268143856d8f33b1aaf24f4e28ffd95cab01 | __author__ = 'susperius'
"""
Abstract class used to implement own fuzzers
"""
class Fuzzer:
NAME = []
CONFIG_PARAMS = []
@classmethod
def from_list(cls, params):
raise NotImplementedError("ABSTRACT METHOD")
@property
def prng_state(self):
raise NotImplementedError("ABSTRACT M... | [
"__author__ = 'susperius'\n\n\"\"\"\nAbstract class used to implement own fuzzers\n\"\"\"\n\nclass Fuzzer:\n NAME = []\n CONFIG_PARAMS = []\n\n @classmethod\n def from_list(cls, params):\n raise NotImplementedError(\"ABSTRACT METHOD\")\n\n @property\n def prng_state(self):\n raise No... | false |
4,659 | 7c2d57a8368eb8d1699364c60e98766e66f01569 |
from flask import Blueprint, current_app
logging = Blueprint("logging", __name__)
@logging.route("/debug/")
def debug():
current_app.logger.debug("some debug message")
return ""
@logging.route("/warning/")
def warning():
current_app.logger.warning("some warning message")
return ""
@logging.ro... | [
"\nfrom flask import Blueprint, current_app\n\n\nlogging = Blueprint(\"logging\", __name__)\n\n\n@logging.route(\"/debug/\")\ndef debug():\n\n current_app.logger.debug(\"some debug message\")\n return \"\"\n\n\n@logging.route(\"/warning/\")\ndef warning():\n\n current_app.logger.warning(\"some warning mess... | false |
4,660 | 47c5fb03cb427d5c9f7703e1715e026b6f2c7a35 | #!/usr/bin/env python
import mcvine.cli
from numpy import array
from mcvine_workflow.singlextal.resolution import use_res_comps as urc
beam_neutrons_path = '/SNS/users/p63/ORNL_public_research/MCViNE_Covmat_comparison/mcvine_resolution/beams/beam_125_1e9/out/neutrons'
instrument = urc.instrument('ARCS', '3.*meter', '13... | [
"#!/usr/bin/env python\nimport mcvine.cli\nfrom numpy import array\nfrom mcvine_workflow.singlextal.resolution import use_res_comps as urc\nbeam_neutrons_path = '/SNS/users/p63/ORNL_public_research/MCViNE_Covmat_comparison/mcvine_resolution/beams/beam_125_1e9/out/neutrons'\ninstrument = urc.instrument('ARCS', '3.*m... | false |
4,661 | 635b75bc12718bccdfb9d04a54476c93fa4685ce | from django.db import models
import eav
from django.utils import timezone
class RiskType(models.Model):
"""A model class used for storing data
about risk types
"""
name = models.CharField(max_length=255)
created = models.DateTimeField(default=timezone.now)
modified = models.DateTimeField(auto_... | [
"from django.db import models\nimport eav\nfrom django.utils import timezone\n\n\nclass RiskType(models.Model):\n \"\"\"A model class used for storing data\n about risk types\n \"\"\"\n name = models.CharField(max_length=255)\n created = models.DateTimeField(default=timezone.now)\n modified = mode... | false |
4,662 | 0a38cf6e0518a08895ed7155069aa2257c7b352e | import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.ones((3, 4))*0, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.ones((3, 4))*1, columns=['a', 'b', 'c', 'd'])
df3 = pd.DataFrame(np.ones((3, 4))*2, columns=['a', 'b', 'c', 'd'])
# 竖向合并
# ignore_index对行索引重新排序
res1 = pd.concat([df1, df2, df3], axis=0, ig... | [
"import pandas as pd\nimport numpy as np\n\n\ndf1 = pd.DataFrame(np.ones((3, 4))*0, columns=['a', 'b', 'c', 'd'])\ndf2 = pd.DataFrame(np.ones((3, 4))*1, columns=['a', 'b', 'c', 'd'])\ndf3 = pd.DataFrame(np.ones((3, 4))*2, columns=['a', 'b', 'c', 'd'])\n\n# 竖向合并\n# ignore_index对行索引重新排序\nres1 = pd.concat([df1, df2, d... | false |
4,663 | b7c43f4242e38318c9e5423ea73e9d9d86759a53 | # -*- coding:utf-8 -*-
__author__ = 'yyp'
__date__ = '2018-5-26 3:42'
'''
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is ... | [
"# -*- coding:utf-8 -*-\n__author__ = 'yyp'\n__date__ = '2018-5-26 3:42'\n\n'''\nGiven a string, find the length of the longest substring without repeating characters.\nExamples:\nGiven \"abcabcbb\", the answer is \"abc\", which the length is 3.\nGiven \"bbbbb\", the answer is \"b\", with the length of 1.\nGiven \"... | false |
4,664 | 49ffa225d433ef2263159ba2145da5ba2a95d1f2 | #求11+12+13+。。。+m
m = int(input('请输入一个数:'))
S = m
for x in range(11,m):
S = S+x
print('sum =',S) | [
"#求11+12+13+。。。+m\nm = int(input('请输入一个数:'))\nS = m\nfor x in range(11,m):\n S = S+x\nprint('sum =',S)",
"m = int(input('请输入一个数:'))\nS = m\nfor x in range(11, m):\n S = S + x\nprint('sum =', S)\n",
"<assignment token>\nfor x in range(11, m):\n S = S + x\nprint('sum =', S)\n",
"<assignment token>\n<co... | false |
4,665 | 3c2a611fd001f145703853f5ecfe70d0e93844e4 | """
opsi-utils
Test utilities
"""
import os
import tempfile
from contextlib import contextmanager
from pathlib import Path
from typing import Generator
@contextmanager
def temp_context() -> Generator[Path, None, None]:
origin = Path().absolute()
try:
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) ... | [
"\"\"\"\nopsi-utils\n\nTest utilities\n\"\"\"\n\nimport os\nimport tempfile\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Generator\n\n\n@contextmanager\ndef temp_context() -> Generator[Path, None, None]:\n\torigin = Path().absolute()\n\ttry:\n\t\twith tempfile.TemporaryDirect... | false |
4,666 | b4491b5522e85fec64164b602045b9bd3e58c5b8 | #给你一个字符串 croakOfFrogs,它表示不同青蛙发出的蛙鸣声(字符串 "croak" )的组合。由于同一时间可以有多只青蛙呱呱作响,所以 croakOfFrogs 中会混合多个 “croak” 。请你返回模拟字符串中所有蛙鸣所需不同青蛙的最少数目。
#注意:要想发出蛙鸣 "croak",青蛙必须 依序 输出 ‘c’, ’r’, ’o’, ’a’, ’k’ 这 5 个字母。如果没有输出全部五个字母,那么它就不会发出声音。
#如果字符串 croakOfFrogs 不是由若干有效的 "croak" 字符混合而成,请返回 -1 。
#来源:力扣(LeetCode)
#链接:https://leetcode-cn.com/pr... | [
"#给你一个字符串 croakOfFrogs,它表示不同青蛙发出的蛙鸣声(字符串 \"croak\" )的组合。由于同一时间可以有多只青蛙呱呱作响,所以 croakOfFrogs 中会混合多个 “croak” 。请你返回模拟字符串中所有蛙鸣所需不同青蛙的最少数目。\n\n#注意:要想发出蛙鸣 \"croak\",青蛙必须 依序 输出 ‘c’, ’r’, ’o’, ’a’, ’k’ 这 5 个字母。如果没有输出全部五个字母,那么它就不会发出声音。\n\n#如果字符串 croakOfFrogs 不是由若干有效的 \"croak\" 字符混合而成,请返回 -1 。\n\n#来源:力扣(LeetCode)\n#链接:https://... | false |
4,667 | 60953878c377382f1c7f25ce284c9fa12b8eb25f | #coding: utf-8
import numpy as np
import cv2
leftgray = cv2.imread('../image/1.jpg')
rightgray = cv2.imread('../image/2.jpg')
hessian=500
surf=cv2.xfeatures2d.SURF_create(hessian) #将Hessian Threshold设置为400,阈值越大能检测的特征就越少
kp1,des1=surf.detectAndCompute(leftgray,None) #查找关键点和描述符
kp2,des2=surf.detectAndCompute(rightgr... | [
"#coding: utf-8\nimport numpy as np\nimport cv2\n\n\nleftgray = cv2.imread('../image/1.jpg')\nrightgray = cv2.imread('../image/2.jpg')\n \nhessian=500\nsurf=cv2.xfeatures2d.SURF_create(hessian) #将Hessian Threshold设置为400,阈值越大能检测的特征就越少\nkp1,des1=surf.detectAndCompute(leftgray,None) #查找关键点和描述符\nkp2,des2=surf.detectAn... | false |
4,668 | 7f7bd2e9ec1932ccfd8aa900956ce85473ee8dbd | #!/usr/bin/env python
"""Diverse wiskundige structuren weergeven in LaTeX in Jupyter Notebook."""
__author__ = "Brian van der Bijl"
__copyright__ = "Copyright 2020, Hogeschool Utrecht"
from IPython.display import display, Math, Markdown
import re
def show_num(x):
return re.compile(r"\.(?!\d)")... | [
"#!/usr/bin/env python\r\n\r\n\"\"\"Diverse wiskundige structuren weergeven in LaTeX in Jupyter Notebook.\"\"\"\r\n\r\n__author__ = \"Brian van der Bijl\"\r\n__copyright__ = \"Copyright 2020, Hogeschool Utrecht\"\r\n\r\nfrom IPython.display import display, Math, Markdown\r\nimport re\r\n\r\ndef show_num(x):\... | false |
4,669 | a83988e936d9dee4838db61c8eb8ec108f5ecd3f | import numpy as np
labels = np.load('DataVariationOther/w1_s500/targetTestNP.npy')
for lab in labels:
print(lab) | [
"import numpy as np \n\nlabels = np.load('DataVariationOther/w1_s500/targetTestNP.npy')\nfor lab in labels:\n\tprint(lab)",
"import numpy as np\nlabels = np.load('DataVariationOther/w1_s500/targetTestNP.npy')\nfor lab in labels:\n print(lab)\n",
"<import token>\nlabels = np.load('DataVariationOther/w1_s500/t... | false |
4,670 | 511c555c88fb646b7b87678044b43a5a623a5ac7 |
from django.contrib import admin
from django.urls import path
from . import view
urlpatterns = [
path('', view.enterMarks),
path('MarkSheet', view.getMarks, name='MarkSheet'),
]
| [
"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom . import view\n\nurlpatterns = [\n path('', view.enterMarks),\n path('MarkSheet', view.getMarks, name='MarkSheet'),\n]\n",
"from django.contrib import admin\nfrom django.urls import path\nfrom . import view\nurlpatterns = [path('', view... | false |
4,671 | 844c630d3fe2dda833064556228b524608cfece9 | import numpy as np
import cv2
from camera import load_K, load_camera_dist, load_camera_ret
def undistort_img(img):
'''
Return an undistorted image given previous calibrated parameters
References from OpenCV docs
'''
ret = load_camera_ret()
K = load_K()
dist = load_camera_dist()
h,w = img.sha... | [
"import numpy as np\nimport cv2\n\nfrom camera import load_K, load_camera_dist, load_camera_ret\n\ndef undistort_img(img):\n '''\n Return an undistorted image given previous calibrated parameters \n References from OpenCV docs\n '''\n ret = load_camera_ret()\n K = load_K()\n dist = load_camera_dist()\... | false |
4,672 | dd7c7fa6493a43988e1c8079797f6ff9b4d239dd | # -coding: UTF-8 -*-
# @Time : 2020/06/24 20:01
# @Author: Liangping_Chen
# @E-mail: chenliangping_2018@foxmail.com
import requests
def http_request(url,data,token=None,method='post'):
header = {'X-Lemonban-Media-Type': 'lemonban.v2',
'Authorization':token}
#判断是get请求还是post请求
if method=='ge... | [
"# -coding: UTF-8 -*-\n# @Time : 2020/06/24 20:01\n# @Author: Liangping_Chen\n# @E-mail: chenliangping_2018@foxmail.com\n\nimport requests\ndef http_request(url,data,token=None,method='post'):\n header = {'X-Lemonban-Media-Type': 'lemonban.v2',\n 'Authorization':token}\n #判断是get请求还是post请求\n ... | false |
4,673 | 5ef6b2ff89ee1667ddb01b1936557f1f11a49910 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from sqlalchemy import create_engine, MetaData, Table
class DoubanPipeline(object):
conn = None
film_table = None
... | [
"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom sqlalchemy import create_engine, MetaData, Table\n\n\nclass DoubanPipeline(object):\n conn = None\n film_t... | true |
4,674 | a2c93fd632a637d47f05e0a4fda851b465d03a31 | import os
import sqlite3
import datetime
directory = 'C:\PyHelp'
if not os.path.exists(directory):
os.makedirs(directory)
rand_facts = '''• Exception is used as a base class for all exceptions. It's strongly recommended (but not yet required) that user exceptions are derived from this class too.
• System... | [
"import os\r\nimport sqlite3\r\nimport datetime\r\ndirectory = 'C:\\PyHelp'\r\n\r\nif not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\nrand_facts = '''• Exception is used as a base class for all exceptions. It's strongly recommended (but not yet required) that user exceptions are derived from thi... | false |
4,675 | 2747b2563c83e11261a7113d69921c1affb20ac8 | class Balloon(object):
def __init__(self, color, size, shape):
self.color = color
self.size = size
self.shape = shape
self.inflated = False
self.working = True
def inflate(self):
if self.working:
self.inflated = True
else:
print "Y... | [
"class Balloon(object):\n def __init__(self, color, size, shape):\n self.color = color\n self.size = size\n self.shape = shape\n self.inflated = False\n self.working = True\n\n def inflate(self):\n if self.working:\n self.inflated = True\n else:\n ... | true |
4,676 | 0dce4ea8ef21f2535194330b82ce5706ae694247 | class Order:
"""
Initiated a new order for the store
"""
def __init__(self, order_number, product_id, item_type, name, product_details, factory, quantity, holiday):
"""
Construct a new order
:param order_number: str
:param product_id: str
:param item_type: str
... | [
"class Order:\n \"\"\"\n Initiated a new order for the store\n \"\"\"\n\n def __init__(self, order_number, product_id, item_type, name, product_details, factory, quantity, holiday):\n \"\"\"\n Construct a new order\n :param order_number: str\n :param product_id: str\n ... | false |
4,677 | 6e614d1235a98ef496956001eef46b4447f0bf9b | from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.touch_action import TouchAction
import time
import re
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import pymongo
def getSize():
x = driv... | [
"from appium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom appium.webdriver.common.touch_action import TouchAction\nimport time\nimport re\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport pymongo\n\ndef getSize()... | false |
4,678 | 752affdfa1481b9a19a9b7dfe76f9d5d11c80073 | #
# Copyright John Reid 2009
#
"""
Code to handle bootstrap analyses.
"""
from itertools import cycle
import random
import bisect
def generate_bootstrap_samples(num_samples, test_universe, test_set_sizes):
"""
Yield samples that match the sizes given in test_set_sizes
"""
for sample_idx, sample_siz... | [
"#\n# Copyright John Reid 2009\n#\n\n\n\"\"\"\nCode to handle bootstrap analyses.\n\"\"\"\n\nfrom itertools import cycle\nimport random\nimport bisect\n\n\ndef generate_bootstrap_samples(num_samples, test_universe, test_set_sizes):\n \"\"\"\n Yield samples that match the sizes given in test_set_sizes\n \"\... | false |
4,679 | 6707723b3d0b42271e49c08c639afc9103066dc7 | import numpy as np
import math
import datetime
def multi_strassen(A,B, check_ig = True, check_quad = True, check_pot = True, check_time = True):
def Strassen(matriz_1,matriz_2): # Função do algoritmo de Strassen para multiplicação de matrizes do tipo 2x2
if (matriz_1.shape[0] != 2) or (matriz_1.shape[... | [
"import numpy as np\nimport math\nimport datetime\n\ndef multi_strassen(A,B, check_ig = True, check_quad = True, check_pot = True, check_time = True):\n \n def Strassen(matriz_1,matriz_2): # Função do algoritmo de Strassen para multiplicação de matrizes do tipo 2x2\n if (matriz_1.shape[0] != 2) or (mat... | false |
4,680 | 68ea462f56ba029a7c977d9c8b94e6f913336fb7 | from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from model_utils.models import TimeStampedModel
user = settings.AUTH_USER_MODEL
commment_lenght = settings.COMMENT_LENGTH
# Entity Comment
class Comment(TimeStampedModel):
"""
Text comment po... | [
"from django.db import models\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils.models import TimeStampedModel\n\nuser = settings.AUTH_USER_MODEL\ncommment_lenght = settings.COMMENT_LENGTH\n\n\n# Entity Comment\nclass Comment(TimeStampedModel):\n \"\"\"\... | false |
4,681 | 66f3590381fe96c49a8926a806b4a845f0d7e25d | import inaccel.coral as inaccel
import numpy as np
import time
class StereoBM:
def __init__(self, cameraMA_l=None, cameraMA_r=None, distC_l=None, distC_r=None, irA_l=None, irA_r=None, bm_state=None ):
# allocate mem for camera parameters for rectification and bm_state class
with inaccel.allocator:
if cameraMA_... | [
"import inaccel.coral as inaccel\nimport numpy as np\nimport time\n\nclass StereoBM:\n\tdef __init__(self, cameraMA_l=None, cameraMA_r=None, distC_l=None, distC_r=None, irA_l=None, irA_r=None, bm_state=None ):\n\t\t# allocate mem for camera parameters for rectification and bm_state class\n\t\twith inaccel.allocator... | false |
4,682 | 0d321193d68b463e3dd04b21ee611afdc212a22b | def flat_list(array):
result = []
for element in array:
if type(element) == list:
result += flat_list(element)
else:
result.append(element)
return result
print flat_list([1, [2, 2, 2], 4])
print flat_list([-1, [1, [-2], 1], -1]) | [
"def flat_list(array):\n result = []\n for element in array:\n if type(element) == list:\n result += flat_list(element)\n else:\n result.append(element)\n return result\n\n\nprint flat_list([1, [2, 2, 2], 4])\nprint flat_list([-1, [1, [-2], 1], -1])"
] | true |
4,683 | 221a75d37fbb49e8508fc786ee8e6e90b19e12c0 | #!/usr/bin/python
# -*-coding:utf-8 -*-
import smtplib
import MySQLdb
import datetime
import types
def sendEmail(sender,passwd,host,port,receivers,date,mail) :
message = MIMEText(mail, 'html', 'utf-8')
message['From'] = Header("告警发送者<"+sender+">", 'utf-8')
subject = str(date) + '服务器告警通知'
message['Subjec... | [
"#!/usr/bin/python\n# -*-coding:utf-8 -*-\nimport smtplib\nimport MySQLdb\nimport datetime\nimport types\ndef sendEmail(sender,passwd,host,port,receivers,date,mail) :\n message = MIMEText(mail, 'html', 'utf-8')\n message['From'] = Header(\"告警发送者<\"+sender+\">\", 'utf-8')\n subject = str(date) + '服务器告警通知'\n... | true |
4,684 | af8a3fbce35685cd89dee72449a8be2a133b4a3f | from os import chdir
from os.path import dirname, realpath
import random
from flask import Flask, render_template, send_from_directory
app = Flask(__name__)
# gets list of list of all classes
def get_data():
class_list = []
with open('counts.tsv') as fd:
for line in fd.read().splitlines():
... | [
"from os import chdir\nfrom os.path import dirname, realpath\nimport random\n\nfrom flask import Flask, render_template, send_from_directory\n\napp = Flask(__name__)\n\n\n# gets list of list of all classes\ndef get_data():\n class_list = []\n with open('counts.tsv') as fd:\n for line in fd.read().split... | false |
4,685 | 822fc2941099cb9d7791580678cfb2a89a987175 | import os, random, string
from django.conf import settings
from django.template.loader import render_to_string
from django.core.mail import send_mail
def generate_temp_password():
length = 7
chars = string.ascii_letters + string.digits
rnd = random.SystemRandom()
return ''.join(rnd.choice(chars) for... | [
"import os, random, string\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom django.core.mail import send_mail\n\ndef generate_temp_password(): \n length = 7\n chars = string.ascii_letters + string.digits\n rnd = random.SystemRandom()\n return ''.join(rnd.cho... | false |
4,686 | 4948fd2062bdbd32bfa32d2b0e24587f0872132d | from .exceptions import InvalidUsage
class HTTPMethodView:
""" Simple class based implementation of view for the sanic.
You should implement methods (get, post, put, patch, delete) for the class
to every HTTP method you want to support.
For example:
class DummyView(HTTPMethodView):
... | [
"from .exceptions import InvalidUsage\n\n\nclass HTTPMethodView:\n \"\"\" Simple class based implementation of view for the sanic.\n You should implement methods (get, post, put, patch, delete) for the class\n to every HTTP method you want to support.\n\n For example:\n class DummyView(HTTPMethod... | false |
4,687 | 001198459b038186ab784b6a9bed755924784866 | from flask import Flask, render_template, redirect, request, session
app = Flask(__name__)
app.secret_key = 'ThisIsSecret' #this line is always needed when using the import 'session'
@app.route('/') #methods=['GET'] by default
def index():
return render_template('index.html')
@app.route('/ninja'... | [
"from flask import Flask, render_template, redirect, request, session\r\n\r\napp = Flask(__name__)\r\napp.secret_key = 'ThisIsSecret' #this line is always needed when using the import 'session'\r\n\r\n\r\n@app.route('/') #methods=['GET'] by default\r\ndef index():\r\n return render_template('index.html')\r... | true |
4,688 | 0656aba517023c003e837d5ad04daeb364f7fda8 | import os
CSRF_ENABLED = True
basedir = os.path.abspath(os.path.dirname(__file__))
# Heroku vs. Local Configs
if os.environ.get('HEROKU') is None:
# Database path
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
# CSRF Key
SECRET_KEY = os.urandom(24)
# Pocket API
CONSUM... | [
"import os\n\nCSRF_ENABLED = True\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# Heroku vs. Local Configs\nif os.environ.get('HEROKU') is None:\n # Database path\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')\n # CSRF Key\n SECRET_KEY = os.urandom(24)\n # Pocke... | false |
4,689 | 21526dabe8456c599e4409228fa69ffd0d672c5b | """Helpers for FormatCBFMiniPilatus..."""
from __future__ import annotations
import calendar
import time
def get_pilatus_timestamp(timestamp_string):
if "." in timestamp_string:
timestamp, milliseconds = timestamp_string.split(".")
else:
timestamp = timestamp_string
milliseconds = "... | [
"\"\"\"Helpers for FormatCBFMiniPilatus...\"\"\"\n\n\nfrom __future__ import annotations\n\nimport calendar\nimport time\n\n\ndef get_pilatus_timestamp(timestamp_string):\n if \".\" in timestamp_string:\n timestamp, milliseconds = timestamp_string.split(\".\")\n else:\n timestamp = timestamp_str... | false |
4,690 | be1ddaf5b4a7fb203fea62d061b06afb45d6867d |
def most_frequent_char(lst):
char_dict = {}
for word in lst:
for char in word:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
max_value = max(char_dict.values())
max_keys = []
for key, value in char_dict.items():
if value == max_value:
max_keys.... | [
"\ndef most_frequent_char(lst):\n char_dict = {}\n for word in lst:\n for char in word:\n if char in char_dict:\n char_dict[char] += 1\n else:\n char_dict[char] = 1\n max_value = max(char_dict.values())\n max_keys = []\n for key, value in char_dict.items():\n if value == max_value... | false |
4,691 | 9cf0174a8bd2bccbd8e5d0be1f0b031a1a23c9df | from Global import *
import ShuntingYard
from Thompson import *
def check_string(automaton, word):
inicial = automata['s'].closure
for i in word:
inicial = state_list_delta(inicial, i)
return automaton['f'] in inicial
def create_AFND(re):
deltas = []
initial_node = ShuntingYard.create_tree(ShuntingYard.to_rpn... | [
"from Global import *\nimport ShuntingYard\nfrom Thompson import *\n\ndef check_string(automaton, word):\n\tinicial = automata['s'].closure\n\tfor i in word:\n\t\tinicial = state_list_delta(inicial, i)\n\treturn automaton['f'] in inicial\n\ndef create_AFND(re):\n\tdeltas = []\n\n\tinitial_node = ShuntingYard.create... | false |
4,692 | 027a049ffced721f2cd697bc928bfdf718630623 | import os
from apps.app_base.app_utils.cryp_key import decrypt, get_secret_key
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = get_secret_key
DEBUG = True
ALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]']
# Application definition
INSTALLED_APPS = [
'corsheaders',
'd... | [
"import os\nfrom apps.app_base.app_utils.cryp_key import decrypt, get_secret_key\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = get_secret_key\n\nDEBUG = True\n\nALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]']\n\n\n# Application definition\n\nINSTALLED_APPS = [\n '... | false |
4,693 | 33ac328b2bf16380b50c58013bd0d4d888dc3952 | #!/usr/bin/env python
from anytree import Node, RenderTree
webtest = Node("WebappTest")
registration = Node("Registration", parent=webtest)
smsconfirm = Node("SMSconfirm", parent=registration)
login = Node("Login", parent=smsconfirm)
useruploadCV = Node("UserUploadCV", parent=l... | [
"#!/usr/bin/env python\n\nfrom anytree import Node, RenderTree\n\n\nwebtest = Node(\"WebappTest\")\nregistration = Node(\"Registration\", parent=webtest)\nsmsconfirm = Node(\"SMSconfirm\", parent=registration)\nlogin = Node(\"Login\", parent=smsconfirm)\nuseruploadCV = Node(\"... | false |
4,694 | 1ab5147ed8ce808de9667052b6d17f320d62484f | '''
手写识别系统
构建识别类
Recognize
调用getResult()函数即可
'''
import operator
from numpy import *
from PIL import Image
from os import listdir
from io import BytesIO
def classify(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0] #训练数据集的行数
# 计算距离
diffMat = tile(inX, (dataSetSize,1)) - dataSet
sqDiffMat = ... | [
"'''\n手写识别系统\n构建识别类\nRecognize\n调用getResult()函数即可\n'''\n\nimport operator\nfrom numpy import *\nfrom PIL import Image\nfrom os import listdir\nfrom io import BytesIO\n\ndef classify(inX, dataSet, labels, k):\n dataSetSize = dataSet.shape[0] #训练数据集的行数\n # 计算距离\n diffMat = tile(inX, (dataSetSize,1)) - dat... | false |
4,695 | 3302dc058032d9fe412bde6fd89699203526a72d | import random #import random module
guesses_taken = 0 #assign 0 to guesses_taken variable
print('Hello! What is your name?')# print Hello! What is your name? to console
myName = input()#take an input from user(name)
number = random.randint(1, 20)# make random number between 1 and 19 and save in number variable
print... | [
"import random #import random module\n\nguesses_taken = 0 #assign 0 to guesses_taken variable\n\nprint('Hello! What is your name?')# print Hello! What is your name? to console\nmyName = input()#take an input from user(name)\n\nnumber = random.randint(1, 20)# make random number between 1 and 19 and save in number va... | false |
4,696 | d9f176262dcaf055414fbc43b476117250249b63 | class Solution:
def levelOrder(self, root):
if root is None:
return []
currentList = [root]
nextList = []
solution = []
while currentList:
thisLevel = [node.val for node in currentList]
solution.append(thisLevel)
f... | [
"class Solution:\r\n def levelOrder(self, root):\r\n if root is None:\r\n return []\r\n\r\n currentList = [root]\r\n nextList = []\r\n solution = []\r\n\r\n while currentList:\r\n thisLevel = [node.val for node in currentList]\r\n solution.appen... | false |
4,697 | e550a2d46e46f0e07d960e7a214fbaa776bab0d5 | import tensorflow as tf
from rnn_cells import gru_cell, lstm_cell
from tensorflow.python.ops import rnn
def shape_list(x):
ps = x.get_shape().as_list()
ts = tf.shape(x)
return [ts[i] if ps[i] is None else ps[i] for i in range(len(ps))]
def bi_dir_lstm(X, c_fw, h_fw, c_bw, h_bw, units, scope='bi_dir_lstm')... | [
"import tensorflow as tf\nfrom rnn_cells import gru_cell, lstm_cell\nfrom tensorflow.python.ops import rnn\n\ndef shape_list(x):\n ps = x.get_shape().as_list()\n ts = tf.shape(x)\n return [ts[i] if ps[i] is None else ps[i] for i in range(len(ps))]\n\ndef bi_dir_lstm(X, c_fw, h_fw, c_bw, h_bw, units, scope=... | false |
4,698 | df828344b81a40b7101adcc6759780ea84f2c6b4 | from os import read
from cryptography.fernet import Fernet
#create a key
# key = Fernet.generate_key()
#When every we run this code we will create a new key
# with open('mykey.key','wb') as mykey:
# mykey.write(key)
#To avoid create a new key and reuse the same key
with open('mykey.key','rb') as myk... | [
"from os import read\r\nfrom cryptography.fernet import Fernet\r\n #create a key\r\n# key = Fernet.generate_key()\r\n\r\n#When every we run this code we will create a new key \r\n# with open('mykey.key','wb') as mykey:\r\n# mykey.write(key)\r\n\r\n#To avoid create a new key and reuse the same key\r\n\r\nwith op... | false |
4,699 | 5d92c68e0fe7f37d4719fb9ca4274b29ff1cbb43 | #!/usr/bin/python
#The MIT License (MIT)
#
#Copyright (c) 2015 Stephen P. Smith
#
#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... | [
"#!/usr/bin/python\n#The MIT License (MIT)\n#\n#Copyright (c) 2015 Stephen P. Smith\n#\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation ... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.