index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
3,100 | baf3bde709ec04b6f41dce8a8b8512ad7847c164 | def multiple_parameters(name, location):
print(f"Hello {name}")
print(f"I live in {location}")
#positional arguments
multiple_parameters("Selva", "Chennai")
#keyword arguments
multiple_parameters(location="Chennai", name="Selva")
| [
"def multiple_parameters(name, location):\n print(f\"Hello {name}\")\n print(f\"I live in {location}\")\n\n#positional arguments\nmultiple_parameters(\"Selva\", \"Chennai\")\n\n#keyword arguments\nmultiple_parameters(location=\"Chennai\", name=\"Selva\")\n",
"def multiple_parameters(name, location):\n pr... | false |
3,101 | 00be3d813ce4335ff9ea02ed9f1884d3210f3d5a | #!/usr/bin/env python
import pathlib
from blastsight.view.viewer import Viewer
"""
In this demo, we'll show how you can create a basic animation.
An animation is interpreted as changing the state of the viewer one frame at the time.
That means we'll define a function that makes a change in one single frame.
The fun... | [
"#!/usr/bin/env python\n\nimport pathlib\n\nfrom blastsight.view.viewer import Viewer\n\n\"\"\"\nIn this demo, we'll show how you can create a basic animation.\n\nAn animation is interpreted as changing the state of the viewer one frame at the time.\nThat means we'll define a function that makes a change in one sin... | false |
3,102 | 342063b37038c804c2afa78091b1f1c2facbc560 | import base64
import json
from werkzeug.exceptions import Unauthorized
from ab import app
from ab.utils import logger
from ab.plugins.spring import eureka
def _login(username, password):
"""
only for test
:return the access token
"""
try:
logger.info('login as user {username}'.format(us... | [
"import base64\nimport json\n\nfrom werkzeug.exceptions import Unauthorized\n\nfrom ab import app\n\nfrom ab.utils import logger\nfrom ab.plugins.spring import eureka\n\n\ndef _login(username, password):\n \"\"\"\n only for test\n :return the access token\n \"\"\"\n try:\n logger.info('login a... | false |
3,103 | e2d8a1e13a4162cd606eec12530451ab230c95b6 | from unittest.mock import MagicMock
import pytest
from charpe.mediums.email_handler import EmailHandler
from charpe.errors import InsuficientInformation
def test_send_requirements(config):
handler = EmailHandler(config)
with pytest.raises(InsuficientInformation):
handler.publish({})
with pytest... | [
"from unittest.mock import MagicMock\nimport pytest\n\nfrom charpe.mediums.email_handler import EmailHandler\nfrom charpe.errors import InsuficientInformation\n\n\ndef test_send_requirements(config):\n handler = EmailHandler(config)\n\n with pytest.raises(InsuficientInformation):\n handler.publish({})\... | false |
3,104 | 71eadf5073b5ed13c7d4a58b2aeb52f550a32238 | #!/usr/bin/env python3
import argparse
import json
import os
import random
import timeit
from glob import glob
import numpy as np
def parse_args():
"""[summary]
Returns:
[type]: [description]
"""
parser = argparse.ArgumentParser()
parser.add_argument('--train_dir',
... | [
"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport os\nimport random\nimport timeit\nfrom glob import glob\n\nimport numpy as np\n\n\ndef parse_args():\n \"\"\"[summary]\n\n Returns:\n [type]: [description]\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--tra... | false |
3,105 | 6fd4df7370de2343fe7723a2d8f5aacffa333835 | import pickle
import pytest
from reader import EntryError
from reader import FeedError
from reader import SingleUpdateHookError
from reader import TagError
from reader.exceptions import _FancyExceptionBase
def test_fancy_exception_base():
exc = _FancyExceptionBase('message')
assert str(exc) == 'message'
... | [
"import pickle\n\nimport pytest\n\nfrom reader import EntryError\nfrom reader import FeedError\nfrom reader import SingleUpdateHookError\nfrom reader import TagError\nfrom reader.exceptions import _FancyExceptionBase\n\n\ndef test_fancy_exception_base():\n exc = _FancyExceptionBase('message')\n assert str(exc... | false |
3,106 | 5663ded291405bcf0d410041485487bb17560223 |
"""
《Engineering a Compiler》
即《编译器设计第二版》
https://www.clear.rice.edu/comp412/
"""
# 《parsing-techniques》 讲前端
## http://parsing-techniques.duguying.net/ebook/2/1/3.html
"""
前端看Parsing Techniques,后端看鲸书,都是最好的。
"""
# 《essential of programming language》
# sicp
"""
如果对编程语言设计方面感兴趣,想对编程语言和编译器设计有大概的概念,可以看看PLP。
想快速实践可以看《自制脚本语... | [
"\n\"\"\"\n《Engineering a Compiler》\n即《编译器设计第二版》\nhttps://www.clear.rice.edu/comp412/\n\"\"\"\n# 《parsing-techniques》 讲前端\n## http://parsing-techniques.duguying.net/ebook/2/1/3.html\n\n\"\"\"\n前端看Parsing Techniques,后端看鲸书,都是最好的。\n\"\"\"\n\n# 《essential of programming language》\n# sicp\n\n\"\"\"\n如果对编程语言设计方面感兴趣,想对编程语... | false |
3,107 | 29abcfc010453e3a67346ea2df238e07b85502a8 | """
Estructuras que extraen valores de una función y se almacenan en objetos iterables (que se pueden recorrer
Son mas eficientes que las funciones tradicionales
muy útiles con listas de valores infinitos
Bajos determinados escenarios, será muy útil que un generador devuelva los valores de uno en uno
Un generador ... | [
"\"\"\"\r\nEstructuras que extraen valores de una función y se almacenan en objetos iterables (que se pueden recorrer\r\nSon mas eficientes que las funciones tradicionales\r\nmuy útiles con listas de valores infinitos\r\nBajos determinados escenarios, será muy útil que un generador devuelva los valores de uno en un... | false |
3,108 | 46d6771fd9f589e2498cd019ba72232cbda06e5a | from editor.editor import Editor
e = Editor()
e.showWindow() | [
"from editor.editor import Editor\r\n\r\ne = Editor()\r\ne.showWindow()",
"from editor.editor import Editor\ne = Editor()\ne.showWindow()\n",
"<import token>\ne = Editor()\ne.showWindow()\n",
"<import token>\n<assignment token>\ne.showWindow()\n",
"<import token>\n<assignment token>\n<code token>\n"
] | false |
3,109 | 1829bd8e87c470a71fea97dd3a47c30477b6e6f1 | """"Pirata barba Negra ( màs de 2 pasos a las izquierda o a la derecha y se cae):
rampa para subir a su barco (5 pasos de ancho y 15 de largo")leer por teclado un valor entero.
a) si el entero es par 1 paso hacia adelante
b)si el entero es impar , pero el entero - 1 es divisible por 4, el pirata da un paso a la derec... | [
"\"\"\"\"Pirata barba Negra ( màs de 2 pasos a las izquierda o a la derecha y se cae): \nrampa para subir a su barco (5 pasos de ancho y 15 de largo\")leer por teclado un valor entero.\na) si el entero es par 1 paso hacia adelante\nb)si el entero es impar , pero el entero - 1 es divisible por 4, el pirata da un pas... | false |
3,110 | a1c1f18e7b95f36a214a1a16f2434be2825829c3 | import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
import matplotlib.pyplot as plt
from sympy import sympify, Symbol
curr_pos = 0
import numpy as np
def bisection(st,maxnum,maxer,xlf,xuf):
file2 = open("test.txt","w")
file2.write("Hello World")
file2.close()
fi = open("test.txt", "w")
x... | [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport sympy as sp\nimport matplotlib.pyplot as plt\nfrom sympy import sympify, Symbol\ncurr_pos = 0\nimport numpy as np\n\ndef bisection(st,maxnum,maxer,xlf,xuf):\n file2 = open(\"test.txt\",\"w\") \n file2.write(\"Hello World\") \n file2.close() \n fi = op... | false |
3,111 | 3272296bca0d6343540597baebef8d882a1267c0 | from ..core import promise, rule
_context = {
'@vocab': 'https://schema.org/',
'fairsharing': 'https://fairsharing.org/',
'html': 'fairsharing:bsg-s001284',
}
@promise
def resolve_html(url):
from urllib.request import urlopen
return urlopen(url).read().decode()
@rule({
'@context': _context,
'@type': 'W... | [
"from ..core import promise, rule\n\n_context = {\n '@vocab': 'https://schema.org/',\n 'fairsharing': 'https://fairsharing.org/',\n 'html': 'fairsharing:bsg-s001284',\n}\n\n@promise\ndef resolve_html(url):\n from urllib.request import urlopen\n return urlopen(url).read().decode()\n\n@rule({\n '@context': _con... | false |
3,112 | 01f4d097cc5f4173fa5a13268b91753566a9f7e1 | #!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: Sequitr
# Purpose: Sequitr is a small, lightweight Python library for common image
# processing tasks in optical microscopy, in particular, single-
# molecule imaging, super-resolution... | [
"#!/usr/bin/env python\n#-------------------------------------------------------------------------------\n# Name: Sequitr\n# Purpose: Sequitr is a small, lightweight Python library for common image\n# processing tasks in optical microscopy, in particular, single-\n# molecule imaging, super-... | true |
3,113 | 8397dcdcb9ec2f35dac0c26b8878a23f9149512b |
import os
# must pip install sox
# type sudo apt install sox into cmd
duration = .2 # seconds
freq = 550 # Hz
os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))
| [
"\nimport os\n# must pip install sox\n# type sudo apt install sox into cmd\nduration = .2 # seconds\nfreq = 550 # Hz\nos.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))\n",
"import os\nduration = 0.2\nfreq = 550\nos.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))\n",
"<im... | false |
3,114 | e045dc348fb2e9de51dbeada1d1826211cf89eae | from terminaltables import AsciiTable
import copy
table_data = [
['WAR', 'WAW'],
['S1 -> S2: R1', 'row1 column2'],
['row2 column1', 'row2 column2'],
['row3 column1', 'row3 column2']
]
table = AsciiTable(table_data)
def getDependenceStr(ins1, ins2, reg):
return f"{ins1} -> {ins2}: {reg}"
def get... | [
"from terminaltables import AsciiTable\nimport copy\n\ntable_data = [\n ['WAR', 'WAW'],\n ['S1 -> S2: R1', 'row1 column2'],\n ['row2 column1', 'row2 column2'],\n ['row3 column1', 'row3 column2']\n]\ntable = AsciiTable(table_data)\n\n\ndef getDependenceStr(ins1, ins2, reg):\n return f\"{ins1} -> {ins2... | false |
3,115 | f114a86a3c6bea274b01763ce3e8cd5c8aea44a0 | # -*- coding: utf-8 -*-
num = input().split()
A = float(num[0])
B = float(num[1])
C = float(num[2])
if A == 0:
print("Impossivel calcular")
else:
delta = B**2 - (4*A*C)
if delta < 0.0:
print("Impossivel calcular")
else:
raiz = delta ** 0.5
r1 = (-B+raiz)/(2*A)
r2 =... | [
"# -*- coding: utf-8 -*-\n\nnum = input().split()\nA = float(num[0])\nB = float(num[1])\nC = float(num[2])\n\nif A == 0:\n print(\"Impossivel calcular\")\nelse:\n delta = B**2 - (4*A*C)\n \n if delta < 0.0:\n print(\"Impossivel calcular\")\n else:\n raiz = delta ** 0.5\n r1 = (-B... | false |
3,116 | 1811c0c5aca9d209638e2221cad2c30e80ee5199 | #Takes - Contact Name(Must be saved in phone's contact list), Message, Time as input
# and sends message to the given contact at given time
# Accuracy Level ~ Seconds. (Also depends on your network speed)
from selenium import webdriver
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
f... | [
"#Takes - Contact Name(Must be saved in phone's contact list), Message, Time as input\n# and sends message to the given contact at given time\n# Accuracy Level ~ Seconds. (Also depends on your network speed)\n\nfrom selenium import webdriver\nPATH = 'C:\\Program Files (x86)\\chromedriver.exe'\ndriver = webdriver.C... | false |
3,117 | e50feccd583d7e33877d5fcc377a1d79dc247d3a |
import pickle
class myPickle:
def make(self, obj,fileName):
print("myPickle make file",fileName)
pickle.dump( obj, open(fileName,'wb') )
print(" DONE")
def load(self, fileName):
print("myPickle load file",fileName)
tr = pickle.load( open(fileName,'rb') ... | [
"\nimport pickle\n\nclass myPickle:\n \n def make(self, obj,fileName):\n print(\"myPickle make file\",fileName)\n pickle.dump( obj, open(fileName,'wb') )\n print(\" DONE\")\n \n def load(self, fileName):\n print(\"myPickle load file\",fileName)\n tr = pickle.loa... | false |
3,118 | 61085eecc8fd0b70bc11e5a85c3958ba3b905eaf | # Jython/Walk_comprehension.py
import os
restFiles = [os.path.join(d[0], f) for d in os.walk(".")
for f in d[2] if f.endswith(".java") and
"PythonInterpreter" in open(os.path.join(d[0], f)).read()]
for r in restFiles:
print(r)
| [
"# Jython/Walk_comprehension.py\nimport os\nrestFiles = [os.path.join(d[0], f) for d in os.walk(\".\")\n for f in d[2] if f.endswith(\".java\") and \n \"PythonInterpreter\" in open(os.path.join(d[0], f)).read()]\nfor r in restFiles:\n print(r)\n",
"import os\nrestFiles = [os.path.join(d... | false |
3,119 | 0aa0fcbb0ec1272bea93574a9287de9f526539c8 | import torch
def DiceLoss(pred,target,smooth=2):
# print("pred shape: ",pred.shape)
# print("target shape: ",target.shape)
index = (2*torch.sum(pred*target)+smooth)/(torch.sum(pred)+torch.sum(target)+smooth)
#if torch.sum(target).item() == 0:
#print("instersection: ",torch.sum(pred*target).item())
... | [
"import torch\ndef DiceLoss(pred,target,smooth=2):\n # print(\"pred shape: \",pred.shape)\n # print(\"target shape: \",target.shape)\n index = (2*torch.sum(pred*target)+smooth)/(torch.sum(pred)+torch.sum(target)+smooth)\n #if torch.sum(target).item() == 0:\n #print(\"instersection: \",torch.sum(pred*... | false |
3,120 | c233ce4e14e9a59a9fb0f29589ced947efeb73a9 | """Tests for flatten_me.flatten_me."""
import pytest
ASSERTIONS = [
[[1, [2, 3], 4], [1, 2, 3, 4]],
[[['a', 'b'], 'c', ['d']], ['a', 'b', 'c', 'd']],
[['!', '?'], ['!', '?']],
[[[True, False], ['!'], ['?'], [71, '@']], [True, False, '!', '?', 71, '@']]
]
@pytest.mark.parametrize("n, result", ASSERTI... | [
"\"\"\"Tests for flatten_me.flatten_me.\"\"\"\nimport pytest\n\n\nASSERTIONS = [\n [[1, [2, 3], 4], [1, 2, 3, 4]],\n [[['a', 'b'], 'c', ['d']], ['a', 'b', 'c', 'd']],\n [['!', '?'], ['!', '?']],\n [[[True, False], ['!'], ['?'], [71, '@']], [True, False, '!', '?', 71, '@']]\n]\n\n\n@pytest.mark.parametri... | false |
3,121 | ebe79cf1b54870055ce8502430f5fae833f3d96d | import matplotlib.pyplot as plt
def visualize_data(positive_images, negative_images):
# INPUTS
# positive_images - Images where the label = 1 (True)
# negative_images - Images where the label = 0 (False)
figure = plt.figure()
count = 0
for i in range(positive_images.shape[0]):
... | [
"import matplotlib.pyplot as plt\r\n\r\ndef visualize_data(positive_images, negative_images):\r\n # INPUTS\r\n # positive_images - Images where the label = 1 (True)\r\n # negative_images - Images where the label = 0 (False)\r\n\r\n figure = plt.figure()\r\n count = 0\r\n for i in range(positive_im... | false |
3,122 | a0086a9d27a091776378cd8bde31c59899fc07ac | """Tools for working with Scores."""
from typing import List, Optional
from citrine._serialization import properties
from citrine._serialization.polymorphic_serializable import PolymorphicSerializable
from citrine._serialization.serializable import Serializable
from citrine._session import Session
from citrine.informa... | [
"\"\"\"Tools for working with Scores.\"\"\"\nfrom typing import List, Optional\n\nfrom citrine._serialization import properties\nfrom citrine._serialization.polymorphic_serializable import PolymorphicSerializable\nfrom citrine._serialization.serializable import Serializable\nfrom citrine._session import Session\nfr... | false |
3,123 | 6782761bcbf53ea5076b6dfb7de66d0e68a9f45d | import json
import requests
import config
class RequestAnnotation:
def schedule(self,
command: str,
**kwargs):
response = requests.post(url=f"http://localhost:{config.annotation_port}/{command}",
json=kwargs)
# not 'text' for annotating, but... | [
"import json\n\nimport requests\nimport config\n\nclass RequestAnnotation:\n def schedule(self,\n command: str,\n **kwargs):\n response = requests.post(url=f\"http://localhost:{config.annotation_port}/{command}\",\n json=kwargs)\n\n # not 'text' ... | false |
3,124 | 65aa27addaec6014fe5fd66df2c0d3632231a314 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from connect import Connect
class Resource:
def __init__(self, row: tuple):
self.video_path = row[0]
self.pic_path = row[1]
| [
"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nfrom connect import Connect\n\n\nclass Resource:\n def __init__(self, row: tuple):\n self.video_path = row[0]\n self.pic_path = row[1]\n\n\n",
"from connect import Connect\n\n\nclass Resource:\n\n def __init__(self, row: tuple):\n self.video_... | false |
3,125 | fda73b5dac038f077da460d6ebfb432b756909d9 | #
# linter.py
# Linter for SublimeLinter version 4.
#
# Written by Brian Schott (Hackerpilot)
# Copyright © 2014-2019 Economic Modeling Specialists, Intl.
#
# License: MIT
#
"""This module exports the D-Scanner plugin class."""
from SublimeLinter.lint import Linter, STREAM_STDOUT
class Dscanner(Linter):
"""Pro... | [
"#\n# linter.py\n# Linter for SublimeLinter version 4.\n#\n# Written by Brian Schott (Hackerpilot)\n# Copyright © 2014-2019 Economic Modeling Specialists, Intl.\n#\n# License: MIT\n#\n\n\"\"\"This module exports the D-Scanner plugin class.\"\"\"\n\nfrom SublimeLinter.lint import Linter, STREAM_STDOUT\n\n\nclass Dsc... | false |
3,126 | f8c85f34fb55ee1c3b3020bcec87b60ae80e4ed2 | import sqlite3
class DatabaseHands(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS hands"
+ "(id INTEGER PRIMARY KEY, first INTEGER,"
+ ... | [
"import sqlite3\n\n\nclass DatabaseHands(object):\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute(\"CREATE TABLE IF NOT EXISTS hands\"\n + \"(id INTEGER PRIMARY KEY, first INTEGER,\"\n ... | false |
3,127 | a7d8efe3231b3e3b9bfc5ef64a936816e8b67d6c | """
Copyright © 2017 Bilal Elmoussaoui <bil.elmoussaoui@gmail.com>
This file is part of Authenticator.
Authenticator is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at ... | [
"\"\"\"\n Copyright © 2017 Bilal Elmoussaoui <bil.elmoussaoui@gmail.com>\n\n This file is part of Authenticator.\n\n Authenticator is free software: you can redistribute it and/or\n modify it under the terms of the GNU General Public License as published\n by the Free Software Foundation, either version 3 of the Li... | false |
3,128 | 20637e41df8a33e3837905a4729ae0b4a9f94dbb | """to get the all the module and its location"""
import sys
print(sys.modules)
| [
"\"\"\"to get the all the module and its location\"\"\"\r\nimport sys\r\nprint(sys.modules)\r\n",
"<docstring token>\nimport sys\nprint(sys.modules)\n",
"<docstring token>\n<import token>\nprint(sys.modules)\n",
"<docstring token>\n<import token>\n<code token>\n"
] | false |
3,129 | b4267612e7939b635542099e1ba31e661720607a | #from getData import getRatings
import numpy as np
num_factors = 10
num_iter = 75
regularization = 0.05
lr = 0.005
folds=5
#to make sure you are able to repeat results, set the random seed to something:
np.random.seed(17)
def split_matrix(ratings, num_users, num_movies):
#Convert data into (IxJ... | [
"#from getData import getRatings\r\nimport numpy as np \r\n\r\n\r\nnum_factors = 10\r\nnum_iter = 75\r\nregularization = 0.05\r\nlr = 0.005\r\nfolds=5\r\n\r\n#to make sure you are able to repeat results, set the random seed to something:\r\nnp.random.seed(17)\r\n\r\n\r\ndef split_matrix(ratings, num_users, num_movi... | false |
3,130 | 11163dc99ee65ab44494c08d81e110e9c42390ae | # -*- coding: utf-8 -*-
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.models import User
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.middleware.csrf import get_token
from django.template.context import Context
from django.utils.translation impor... | [
"# -*- coding: utf-8 -*-\nfrom django.contrib.auth import logout, login, authenticate\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.middleware.csrf import get_token\nfrom django.template.context import Context\nfrom django.utils.transl... | false |
3,131 | 8186b7bddbdcdd730a3f79da1bd075c25c0c3998 | import uuid
from website.util import api_v2_url
from django.db import models
from osf.models import base
from website.security import random_string
from framework.auth import cas
from website import settings
from future.moves.urllib.parse import urljoin
def generate_client_secret():
return random_string(lengt... | [
"import uuid\n\nfrom website.util import api_v2_url\n\nfrom django.db import models\nfrom osf.models import base\nfrom website.security import random_string\n\nfrom framework.auth import cas\n\nfrom website import settings\nfrom future.moves.urllib.parse import urljoin\n\n\ndef generate_client_secret():\n return... | false |
3,132 | 1d4df09256324cce50fad096cdeff289af229728 | from PyQt5.QtCore import QObject, pyqtSlot
from Controllers.BookController import BookController
from Model.BookModel import BookModel
from Controllers.DatabaseController import DatabaseController
#Issuance Controller class contains the issuance properties and performs database operations for the issuance
class Issuan... | [
"from PyQt5.QtCore import QObject, pyqtSlot\nfrom Controllers.BookController import BookController\nfrom Model.BookModel import BookModel\nfrom Controllers.DatabaseController import DatabaseController\n\n#Issuance Controller class contains the issuance properties and performs database operations for the issuance\nc... | false |
3,133 | be7fb94c3c423b67aa917a34328acda5926cf78a | from django.urls import path
from .views import PostListView, PostDetailView
urlpatterns = [
path('blog/', PostListView.as_view()),
path('blog/<pk>/', PostDetailView.as_view()),
] | [
"from django.urls import path\nfrom .views import PostListView, PostDetailView\n\nurlpatterns = [\n path('blog/', PostListView.as_view()),\n path('blog/<pk>/', PostDetailView.as_view()),\n]",
"from django.urls import path\nfrom .views import PostListView, PostDetailView\nurlpatterns = [path('blog/', PostLis... | false |
3,134 | 07a172c28057dc803efdbdc10a9e2e11df4e527b | from room import Room
from player import Player
from item import Item
# Declare all the rooms
items = {
'scimitar': Item('Scimitar', '+7 Attack'),
'mace': Item('Mace', '+13 Attack'),
'tower_shield': Item('Tower Shield', '+8 Block'),
'heraldic_shield': Item('Heraldic Shield', '+12 Block'),
'chainmail... | [
"from room import Room\nfrom player import Player\nfrom item import Item\n# Declare all the rooms\nitems = {\n 'scimitar': Item('Scimitar', '+7 Attack'),\n 'mace': Item('Mace', '+13 Attack'),\n 'tower_shield': Item('Tower Shield', '+8 Block'),\n 'heraldic_shield': Item('Heraldic Shield', '+12 Block'),\n... | false |
3,135 | b53b0e6ff14750bbba3c2e5e2ea2fc5bb1abccec | import math as m
import functions_by_alexandra as fba
import funs
from functions_by_alexandra import User, a
from pkg import bps, geom
print(type(funs))
print(type(funs.add ))
#
# print(add(2,3))
print("Result: ", funs.add(10, 20))
print("Result: ", fba.add(10,20))
print(type(fba ))
print(a )
print(m... | [
"import math as m\r\n\r\nimport functions_by_alexandra as fba\r\nimport funs\r\nfrom functions_by_alexandra import User, a\r\nfrom pkg import bps, geom\r\n\r\nprint(type(funs))\r\nprint(type(funs.add ))\r\n#\r\n# print(add(2,3))\r\nprint(\"Result: \", funs.add(10, 20))\r\nprint(\"Result: \", fba.add(10,20))\r\nprin... | false |
3,136 | ff1bb2634ffec6181a42c80a4b2a19c2c27a8f9f | import socket
from Server.MachineClient.Identification import Identification
from Server.SQL import DataBase
import threading
import time
from Server.Connection.AcceptClients import Accept
from Server.Connection.ConnectionCheck import ConnectionCheck
from Server.Clients_Data import Clients
class MachineClient:
de... | [
"import socket\nfrom Server.MachineClient.Identification import Identification\nfrom Server.SQL import DataBase\nimport threading\nimport time\nfrom Server.Connection.AcceptClients import Accept\nfrom Server.Connection.ConnectionCheck import ConnectionCheck\nfrom Server.Clients_Data import Clients\n\n\nclass Machin... | false |
3,137 | b32784bf398a58ba4b6e86fedcdc3ac9de0e8d51 | from django import forms
from django.core.exceptions import ValidationError
from django.db import connection
from customer.helper_funcs import dictfetchall
class OrderForm(forms.Form):
item_id = forms.IntegerField(required=True)
quantity = forms.IntegerField(required=True)
def clean(self):
cleane... | [
"from django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.db import connection\nfrom customer.helper_funcs import dictfetchall\n\n\nclass OrderForm(forms.Form):\n item_id = forms.IntegerField(required=True)\n quantity = forms.IntegerField(required=True)\n\n def clean(self):... | false |
3,138 | 16db443642746af4ae45862627baaa9eca54a165 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 18:45:08 2020
@author: Neeraj
"""
import cv2
import numpy as np
num_down=2
num_bilateral=50
img_rgb=cv2.imread("stunning-latest-pics-of-Kajal-Agarwal.jpg") #image path
img_rgb=cv2.resize(img_rgb,(800,800))
img_color=img_rgb
for _ in range(num_... | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Sep 3 18:45:08 2020\r\n\r\n@author: Neeraj\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nnum_down=2\r\nnum_bilateral=50\r\n\r\nimg_rgb=cv2.imread(\"stunning-latest-pics-of-Kajal-Agarwal.jpg\") #image path\r\nimg_rgb=cv2.resize(img_rgb,(800,800))\r\... | false |
3,139 | 87c413051ed38b52fbcc0b0cf84ecd75cd1e3f0c | import sys, getopt
import sys, locale
import httplib
import json
#sys.argv = [sys.argv[0], '--id=275', '--ofile=275.json']
def getRouteId(routeName, out_filename):
conn = httplib.HTTPConnection("data.ntpc.gov.tw")
qryString = "/od/data/api/67BB3C2B-E7D1-43A7-B872-61B2F082E11B?$format=json&$filter=nameZh%20eq%... | [
"import sys, getopt\nimport sys, locale\nimport httplib\nimport json\n\n#sys.argv = [sys.argv[0], '--id=275', '--ofile=275.json']\n\ndef getRouteId(routeName, out_filename):\n conn = httplib.HTTPConnection(\"data.ntpc.gov.tw\")\n qryString = \"/od/data/api/67BB3C2B-E7D1-43A7-B872-61B2F082E11B?$format=json&$fi... | true |
3,140 | 46b1991bba83968466390d306a4415b362b6a868 | #!/usr/bin/env python
import sys
import json
import time
import random
import pathlib
import argparse
import subprocess
proc = None
def get_wallpaper(FOLDER):
files = [path for path in pathlib.Path(FOLDER).iterdir()
if path.is_file()]
return random.choice(files)
def get_outputs():
cmd = ... | [
"#!/usr/bin/env python\n\nimport sys\nimport json\nimport time\nimport random\nimport pathlib\nimport argparse\nimport subprocess\n\nproc = None\n\n\ndef get_wallpaper(FOLDER):\n files = [path for path in pathlib.Path(FOLDER).iterdir()\n if path.is_file()]\n\n return random.choice(files)\n\n\ndef ... | false |
3,141 | 11ad3e1ab4ffd491e27998a7235b7e18857632ed | # Generated by Django 3.0.4 on 2020-03-29 09:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('portfolio_app', '0008_feedback_product'),
]
operations = [
migrations.RemoveField(
model_name='feedback',
name... | [
"# Generated by Django 3.0.4 on 2020-03-29 09:27\r\n\r\nfrom django.db import migrations\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('portfolio_app', '0008_feedback_product'),\r\n ]\r\n\r\n operations = [\r\n migrations.RemoveField(\r\n model_nam... | false |
3,142 | cb13011def8fc7ed6a2e98a794343857e3e34562 | import pickle
from sklearn import linear_model
from sklearn.model_selection import train_test_split
import random
from sklearn.manifold import TSNE
import matplotlib
def loadXY():
zippedXY = pickle.load(open("../Vectorizer/zippedXY_wff_2k.p","rb"))
#random.shuffle(zippedXY)
X,Y = zip(*zippedXY)
return X,Y
def out... | [
"import pickle\nfrom sklearn import linear_model\nfrom sklearn.model_selection import train_test_split\nimport random\nfrom sklearn.manifold import TSNE\nimport matplotlib\n\ndef loadXY():\n\tzippedXY = pickle.load(open(\"../Vectorizer/zippedXY_wff_2k.p\",\"rb\"))\n\t#random.shuffle(zippedXY)\n\tX,Y = zip(*zippedXY... | true |
3,143 | 8dfb1312d82bb10f2376eb726f75a4a596319acb | #!/usr/local/bin/python
import requests as rq
import sqlite3 as sq
from dateutil import parser
import datetime
import pytz
import json
from os.path import expanduser
import shutil
from os.path import isfile
import time
#FRED Config
urls = {'FRED':"http://api.stlouisfed.org/fred"}
urls['FRED_SER'] = urls['FRED'] + "/se... | [
"#!/usr/local/bin/python\nimport requests as rq\nimport sqlite3 as sq\nfrom dateutil import parser\nimport datetime\nimport pytz\nimport json\nfrom os.path import expanduser\nimport shutil\nfrom os.path import isfile\nimport time\n#FRED Config\nurls = {'FRED':\"http://api.stlouisfed.org/fred\"}\nurls['FRED_SER'] = ... | true |
3,144 | b29c11b11fd357c7c4f774c3c6a857297ff0d021 | """
losettings.py
Contains a class for profiles and methods to save and load them from xml files.
Author: Stonepaw
Version 2.0
Rewrote pretty much everything. Much more modular and requires no maintence when a new attribute is added.
No longer fully supports profiles from 1.6 and earlier.
Copy... | [
"\"\"\"\r\nlosettings.py\r\n\r\nContains a class for profiles and methods to save and load them from xml files.\r\n\r\nAuthor: Stonepaw\r\n\r\nVersion 2.0\r\n\r\n Rewrote pretty much everything. Much more modular and requires no maintence when a new attribute is added.\r\n No longer fully supports profiles f... | true |
3,145 | 83b65b951b06b117c2e85ba348e9b591865c1c2e | #--------------------------------------------------------------------------------
# G e n e r a l I n f o r m a t i o n
#--------------------------------------------------------------------------------
# Name: Exercise 2.6 - Planetary Orbits
#
# Usage: Calculate information for planetary orbits
#
# Description: ... | [
"#--------------------------------------------------------------------------------\r\n# G e n e r a l I n f o r m a t i o n\r\n#--------------------------------------------------------------------------------\r\n# Name: Exercise 2.6 - Planetary Orbits\r\n#\r\n# Usage: Calculate information for planetary orbits\r\n#... | false |
3,146 | a68d682ba6d441b9d7fb69ec1ee318a0ef65ed40 | """
Read a real number. If it is positive print it's square root, if it's not print the square of it.
"""
import math
print('Insert a number')
num1 = float(input())
if num1 > 0:
print(f'The square root of {num1} is {math.sqrt(num1)}')
else:
print(f'The square of {num1} is {num1**2}')
| [
"\"\"\"\n\nRead a real number. If it is positive print it's square root, if it's not print the square of it.\n\n\"\"\"\nimport math\n\nprint('Insert a number')\nnum1 = float(input())\n\nif num1 > 0:\n print(f'The square root of {num1} is {math.sqrt(num1)}')\nelse:\n print(f'The square of {num1} is {num1**2}')... | false |
3,147 | 6c65d63ef07b6cdb2029e6a6e99f6ee35b448c4b | individual = html.Div([
html.Div([ # input container
html.Div([
dcc.RadioItems(id='view-radio',
options=[
{'label': i, 'value': i} for i in ['Players',
'Tea... | [
"individual = html.Div([\n\n html.Div([ # input container\n \n html.Div([\n dcc.RadioItems(id='view-radio',\n options=[\n {'label': i, 'value': i} for i in ['Players',\n ... | true |
3,148 | 174c4c1ed7f2197e012644999cf23f5e82f4b7c3 | def has23(nums):
this = nums[0] == 2 or nums[0] == 3
that = nums[1] == 2 or nums[1] == 3
return this or that
| [
"def has23(nums):\n this = nums[0] == 2 or nums[0] == 3\n that = nums[1] == 2 or nums[1] == 3\n return this or that\n",
"def has23(nums):\n this = nums[0] == 2 or nums[0] == 3\n that = nums[1] == 2 or nums[1] == 3\n return this or that\n",
"<function token>\n"
] | false |
3,149 | dd4dc1c4a0dc47711d1d0512ef3f6b7908735766 |
import numpy as np
import tensorflow as tf
class LocNet:
def __init__(self, scope, buttom_layer):
self.scope = scope
with tf.variable_scope(scope) as scope:
self.build_graph(buttom_layer)
self.gt_loc = tf.placeholder(dtype=tf.float32, shape=(None,4),name='gt_loc')
... | [
"\n\nimport numpy as np \nimport tensorflow as tf\n\n\nclass LocNet: \n def __init__(self, scope, buttom_layer):\n self.scope = scope \n with tf.variable_scope(scope) as scope:\n self.build_graph(buttom_layer)\n self.gt_loc = tf.placeholder(dtype=tf.float32, shape=(None,4),nam... | false |
3,150 | 8c42e06fd92f0110b3ba8c4e7cc0ac45b9e44378 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__copyright__ = """
This code is licensed under the MIT license.
Copyright University Innsbruck, Institute for General, Inorganic, and Theoretical Chemistry, Podewitz Group
See LICENSE for details
"""
from scipy.signal import argrelextrema
from typing import List, Tuple
i... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n__copyright__ = \"\"\"\nThis code is licensed under the MIT license.\nCopyright University Innsbruck, Institute for General, Inorganic, and Theoretical Chemistry, Podewitz Group\nSee LICENSE for details\n\"\"\"\n\nfrom scipy.signal import argrelextrema\nfrom typing ... | false |
3,151 | 850310b6c431981a246832e8a6f5417a88587b99 | import torch
class Activation(torch.nn.Module):
def __init__(self):
super().__init__()
self.swish = lambda x: x * torch.sigmoid(x)
self.linear = lambda x: x
self.sigmoid = lambda x: torch.sigmoid(x)
self.neg = lambda x: -x
self.sine = lambda x: torch.sin(x)
self.params = torch.nn.Parameter(torch.zero... | [
"import torch\n\nclass Activation(torch.nn.Module):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.swish = lambda x: x * torch.sigmoid(x)\n\t\tself.linear = lambda x: x\n\t\tself.sigmoid = lambda x: torch.sigmoid(x)\n\t\tself.neg = lambda x: -x\n\t\tself.sine = lambda x: torch.sin(x)\n\t\t\n\t\tself.param... | false |
3,152 | 6f9f204cbd6817d5e40f57e71614ad03b64d9003 | # Generated by Django 3.2.6 on 2021-08-15 05:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('website', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='tasks',
name='cleanlinessLevel',
... | [
"# Generated by Django 3.2.6 on 2021-08-15 05:17\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('website', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tasks',\n name='clea... | false |
3,153 | b888745b3ce815f7c9eb18f5e76bacfadfbff3f5 | from libs.storage.blocks.iterators.base import BaseBlockIterator
from libs.storage.const import SEPARATOR
class ContentsBlockIterator(BaseBlockIterator):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.contents = self.block_content.split(SEPARATOR)
self.titles =... | [
"from libs.storage.blocks.iterators.base import BaseBlockIterator\nfrom libs.storage.const import SEPARATOR\n\n\nclass ContentsBlockIterator(BaseBlockIterator):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.contents = self.block_content.split(SEPARATOR)\n ... | false |
3,154 | 913e1f5a0af436ef081ab567c44b4149299d0ec6 | # Generated by Django 2.2.4 on 2019-08-19 19:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('application', '0003_auto_20190818_1623'),
]
operations = [
migrations.AlterField(
model_name='user',
name='visited',... | [
"# Generated by Django 2.2.4 on 2019-08-19 19:14\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('application', '0003_auto_20190818_1623'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n ... | false |
3,155 | ac459bff6d4281ce07b70dbccde3243412ddb414 | # processing functions for diagrams
import torch
import numpy as np
def remove_filler(dgm, val=np.inf):
"""
remove filler rows from diagram
"""
inds = (dgm[:,0] != val)
return dgm[inds,:]
def remove_zero_bars(dgm):
"""
remove zero bars from diagram
"""
inds = dgm... | [
"# processing functions for diagrams\r\n\r\nimport torch\r\nimport numpy as np\r\n\r\ndef remove_filler(dgm, val=np.inf):\r\n \"\"\"\r\n remove filler rows from diagram\r\n \"\"\"\r\n inds = (dgm[:,0] != val)\r\n return dgm[inds,:]\r\n\r\n\r\ndef remove_zero_bars(dgm):\r\n \"\"\"\r\n remove zer... | false |
3,156 | 284e4f79748c17d44518f2ce424db5b1697373dc | __version__ = '0.90.03'
| [
"__version__ = '0.90.03'\n",
"<assignment token>\n"
] | false |
3,157 | 5ddde3aa6eaa30b70743272a532874663067eed6 | #!/usr/bin/env python3
import sys
import os
import math
import random
if hasattr(sys, '__interactivehook__'):
del sys.__interactivehook__
print('Python3 startup file loaded from ~/.config/pystartup.py')
| [
"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport math\nimport random\n\nif hasattr(sys, '__interactivehook__'):\n del sys.__interactivehook__\n\nprint('Python3 startup file loaded from ~/.config/pystartup.py')\n\n",
"import sys\nimport os\nimport math\nimport random\nif hasattr(sys, '__interactivehook_... | false |
3,158 | 98dd7446045f09e6d709f8e5e63b0a94341a796e | # -*- coding: utf-8 -*-
import time
import re
from config import allowed_users, master_users, chat_groups
from bs4 import BeautifulSoup
import requests
import urllib.request, urllib.error, urllib.parse
import http.cookiejar
import json
import os
import sys
#from random import randint, choice
from random import uniform,... | [
"# -*- coding: utf-8 -*-\nimport time\nimport re\nfrom config import allowed_users, master_users, chat_groups\nfrom bs4 import BeautifulSoup\nimport requests\nimport urllib.request, urllib.error, urllib.parse\nimport http.cookiejar\nimport json\nimport os\nimport sys\n#from random import randint, choice\nfrom rando... | false |
3,159 | 0f0595793e98187c6aaf5b1f4b59affb06bb598e | from phylo_utils.data import fixed_equal_nucleotide_frequencies
from phylo_utils.substitution_models.tn93 import TN93
class K80(TN93):
_name = 'K80'
_freqs = fixed_equal_nucleotide_frequencies.copy()
def __init__(self, kappa, scale_q=True):
super(K80, self).__init__(kappa, kappa, 1, self._freqs, s... | [
"from phylo_utils.data import fixed_equal_nucleotide_frequencies\nfrom phylo_utils.substitution_models.tn93 import TN93\n\n\nclass K80(TN93):\n _name = 'K80'\n _freqs = fixed_equal_nucleotide_frequencies.copy()\n def __init__(self, kappa, scale_q=True):\n super(K80, self).__init__(kappa, kappa, 1, s... | false |
3,160 | 41698e9d8349ddf3f42aa3d4fc405c69077d1aa3 | from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor
import ATLAS1
import ATLAS_v2
from atlas.config import dbConfig
import pandas as pd
import ContentCategories
import NgramMapping
import SentimentAnalysis_2
import TrigDriv_2
import TopicModeling
import logging
import tr... | [
"from concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import ProcessPoolExecutor\nimport ATLAS1\nimport ATLAS_v2\nfrom atlas.config import dbConfig\nimport pandas as pd\nimport ContentCategories\nimport NgramMapping\nimport SentimentAnalysis_2\nimport TrigDriv_2\nimport TopicModeling\nimport l... | true |
3,161 | e235be879cf8a00eb9f39f90859689a29b26f1c6 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 10 12:18:06 2017
@author: wqmike123
"""
#%% build a simple CNN with gloVec as initial
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers impo... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 10 12:18:06 2017\n\n@author: wqmike123\n\"\"\"\n#%% build a simple CNN with gloVec as initial\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers import Embedding\n... | false |
3,162 | 87f3885b4357d66a745932f3c79804e6c15a57fa | import numpy as np
from ARA import *
from State import *
def theta_given_s(theta, q):
"""
Probability of an random event theta given current state s.
Args:
theta: Random event
s = [q, r, w]: State
Returns:
Unnormalized probability of the random event.
"""
if q == 0:
... | [
"import numpy as np\nfrom ARA import *\nfrom State import *\n\ndef theta_given_s(theta, q):\n \"\"\"\n Probability of an random event theta given current state s.\n Args:\n theta: Random event\n s = [q, r, w]: State\n Returns:\n Unnormalized probability of the random event.\n \"\... | false |
3,163 | 3f4f60ff315c8e7e4637a84629894012ed13280e | import src.integralimage as II
import src.adaboost as AB
import src.utils as UT
import numpy as np
if __name__ == "__main__":
pos_training_path = 'dataset-1/trainset/faces'
neg_training_path = 'dataset-1/trainset/non-faces'
pos_testing_path = 'dataset-1/testset/faces'
neg_testing_path = 'dataset-1/tes... | [
"import src.integralimage as II\nimport src.adaboost as AB\nimport src.utils as UT\nimport numpy as np \n\nif __name__ == \"__main__\":\n pos_training_path = 'dataset-1/trainset/faces'\n neg_training_path = 'dataset-1/trainset/non-faces'\n pos_testing_path = 'dataset-1/testset/faces'\n neg_testing_path ... | false |
3,164 | 4b075d8211d7047f6f08fe6f6f55e4703bdb6f1f | from django.db import models
# Create your models here.
class Todo(models.Model):
title = models.CharField(max_length=200)
completed = models.IntegerField(default=0)
| [
"from django.db import models\n\n# Create your models here.\nclass Todo(models.Model):\n\ttitle = models.CharField(max_length=200)\n\tcompleted = models.IntegerField(default=0)\n",
"from django.db import models\n\n\nclass Todo(models.Model):\n title = models.CharField(max_length=200)\n completed = models.In... | false |
3,165 | 4d18c056845403adc9c4b5848fafa06d0fe4ff4c | class Solution(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
left= 0
#for right in range(len(s)-1, -1, -1):
for right in reversed(range(len(s))):
if s[right] == s[left]:
left += 1
... | [
"class Solution(object):\n def shortestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n left= 0\n \n #for right in range(len(s)-1, -1, -1):\n for right in reversed(range(len(s))):\n if s[right] == s[left]:\n le... | false |
3,166 | 1fdb9db4c1c8b83c72eeb34f10ef9d289b43b79f | from Bio import SeqIO
def flatten(l):
return [j for i in l for j in i]
def filter_sequences_by_len_from_fasta(file, max_len):
with open(file) as handle:
return [str(record.seq) for record in SeqIO.parse(handle, 'fasta') if len(record.seq) <= max_len] | [
"from Bio import SeqIO\n\ndef flatten(l):\n return [j for i in l for j in i]\n\ndef filter_sequences_by_len_from_fasta(file, max_len):\n with open(file) as handle:\n return [str(record.seq) for record in SeqIO.parse(handle, 'fasta') if len(record.seq) <= max_len]",
"from Bio import SeqIO\n\n\ndef fla... | false |
3,167 | 2003060f7793de678b4a259ad9424cd5927a57f7 | """ Class implementing ReportGenerator """
from urllib.parse import urlparse
import requests
from src.classes.reporter.flag import Flag
from src.classes.reporter.line_finder import LineFinder
class ReportGenerator(object):
"""
Class designed to generate reports after CSP audition
The ReportGenerator cla... | [
"\"\"\" Class implementing ReportGenerator \"\"\"\n\nfrom urllib.parse import urlparse\nimport requests\nfrom src.classes.reporter.flag import Flag\nfrom src.classes.reporter.line_finder import LineFinder\n\n\nclass ReportGenerator(object):\n \"\"\"\n Class designed to generate reports after CSP audition\n\n ... | false |
3,168 | e94d66732a172286814bc0b0051a52c1374a4de5 | import asyncio
import sys
import aioredis
import msgpack
async def main(host: str, endpoint: str, message: str):
msg = msgpack.packb(
{
"endpoint": endpoint,
"headers": {"Content-Type": "text/json"},
"payload": message.encode("utf-8"),
},
)
redis = awai... | [
"import asyncio\nimport sys\n\nimport aioredis\nimport msgpack\n\n\nasync def main(host: str, endpoint: str, message: str):\n msg = msgpack.packb(\n {\n \"endpoint\": endpoint,\n \"headers\": {\"Content-Type\": \"text/json\"},\n \"payload\": message.encode(\"utf-8\"),\n ... | false |
3,169 | 20167058697450f342c2ac3787bd1721f860dc58 | from kraken.core.maths import Vec3, Vec3, Euler, Quat, Xfo
from kraken.core.objects.components.base_example_component import BaseExampleComponent
from kraken.core.objects.attributes.attribute_group import AttributeGroup
from kraken.core.objects.attributes.scalar_attribute import ScalarAttribute
from kraken.core.objec... | [
"from kraken.core.maths import Vec3, Vec3, Euler, Quat, Xfo\n\nfrom kraken.core.objects.components.base_example_component import BaseExampleComponent\n\nfrom kraken.core.objects.attributes.attribute_group import AttributeGroup\nfrom kraken.core.objects.attributes.scalar_attribute import ScalarAttribute\nfrom kraken... | false |
3,170 | 856afd30a2ed01a1d44bbe91a7b69998e9a51bb7 | from __future__ import print_function
import os, sys, time
import fitz
import PySimpleGUI as sg
"""
PyMuPDF utility
----------------
For a given entry in a page's getImagleList() list, function "recoverpix"
returns either the raw image data, or a modified pixmap if an /SMask entry
exists.
The item's first two entries ... | [
"from __future__ import print_function\nimport os, sys, time\nimport fitz\nimport PySimpleGUI as sg\n\n\"\"\"\nPyMuPDF utility\n----------------\nFor a given entry in a page's getImagleList() list, function \"recoverpix\"\nreturns either the raw image data, or a modified pixmap if an /SMask entry\nexists.\nThe item... | false |
3,171 | a598da0a749fcc5a6719cec31ede0eb13fab228e | import pytest
import app
import urllib.parse
@pytest.fixture
def client():
app.app.config['TESTING'] = True
with app.app.test_client() as client:
yield client
def test_query_missing_args(client):
response = client.get('/data/query')
assert 'errors' in response.json and '400' in response.sta... | [
"import pytest\nimport app\nimport urllib.parse\n\n\n@pytest.fixture\ndef client():\n app.app.config['TESTING'] = True\n\n with app.app.test_client() as client:\n yield client\n\n\ndef test_query_missing_args(client):\n response = client.get('/data/query')\n assert 'errors' in response.json and '... | false |
3,172 | cf2fcd013c3e9992da36806ca93aacb4b5399396 | from .tacotron_v2_synthesizer import Tacotron2Synthesizer
| [
"from .tacotron_v2_synthesizer import Tacotron2Synthesizer\n\n",
"from .tacotron_v2_synthesizer import Tacotron2Synthesizer\n",
"<import token>\n"
] | false |
3,173 | 5dffda8215b8cfdb2459ec6a9e02f10a352a6fd0 | from wtforms import Form as BaseForm
from wtforms.widgets import ListWidget
class Form(BaseForm):
def as_ul(self):
widget = ListWidget()
return widget(self)
| [
"from wtforms import Form as BaseForm\nfrom wtforms.widgets import ListWidget\n\n\nclass Form(BaseForm):\n def as_ul(self):\n widget = ListWidget()\n return widget(self)\n",
"from wtforms import Form as BaseForm\nfrom wtforms.widgets import ListWidget\n\n\nclass Form(BaseForm):\n\n def as_ul(s... | false |
3,174 | a9344151a997842972aa68c417a77b3ca80e6cfa | # -*- coding:utf-8 -*-
from flask import redirect, url_for, render_template
from flask.globals import request, session
from flask_admin import BaseView, expose
from util import navigator, common
class Billings(BaseView):
@expose('/')
def index(self):
return redirect(url_for('.billingHistory'))
... | [
"# -*- coding:utf-8 -*-\nfrom flask import redirect, url_for, render_template\nfrom flask.globals import request, session\nfrom flask_admin import BaseView, expose\n\nfrom util import navigator, common\n\n\nclass Billings(BaseView):\n\n @expose('/')\n def index(self):\n return redirect(url_for('.billin... | false |
3,175 | 2eb49d08136c3540e1305310f03255e2ecbf0c40 | import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.title('Loop')
############ Time consuming :
# nameLable1 = ttk.Label(win,text="Enter your name : ")
# nameLable1.grid(row=0,column=0,sticky=tk.W)
# ageLable1 = ttk.Label(win,text="Enter your age: ")
# ageLable1.grid(row=1,column=0,sticky=tk.W)
#... | [
"import tkinter as tk\nfrom tkinter import ttk\n\n\nwin = tk.Tk()\n\nwin.title('Loop')\n\n\n############ Time consuming :\n\n# nameLable1 = ttk.Label(win,text=\"Enter your name : \") \n# nameLable1.grid(row=0,column=0,sticky=tk.W) \n\n# ageLable1 = ttk.Label(win,text=\"Enter your age: \") \n# ageLable1.grid(row=1,c... | false |
3,176 | 967984444d9e26452226b13f33c5afbc96b5fe2b | import os
from enum import Enum
STAFF_CODE = os.getenv('STAFF_CODE', '20190607')
ADMIN_CODE = os.getenv('ADMIN_CODE', 'nerd-bear')
TEAM_NAMES = (
'밍크고래팀',
'혹등고래팀',
'대왕고래팀',
'향유고래팀',
)
TEAM_COUNT = 3
MAX_TEAM_MEMBER_COUNT = 10
class TIME_CHECK(Enum):
BEFORE_START = 0
DURING_TIME = 1
AFTER... | [
"import os\nfrom enum import Enum\n\nSTAFF_CODE = os.getenv('STAFF_CODE', '20190607')\nADMIN_CODE = os.getenv('ADMIN_CODE', 'nerd-bear')\n\nTEAM_NAMES = (\n '밍크고래팀',\n '혹등고래팀',\n '대왕고래팀',\n '향유고래팀',\n)\nTEAM_COUNT = 3\nMAX_TEAM_MEMBER_COUNT = 10\n\n\nclass TIME_CHECK(Enum):\n BEFORE_START = 0\n DU... | false |
3,177 | ae0ccbb9b0a2c61d9ee9615ba8d0c1a186a81c34 | # coding=utf-8
# oscm_app/cart/models
# django imports
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _
# OSCM imports
from ...constants import CARTS, CART_STATUSES, DEFAULT_CART_STATUS
from ...utils import get_attr
from ..cart_manager i... | [
"# coding=utf-8\n# oscm_app/cart/models\n\n# django imports\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\n# OSCM imports\nfrom ...constants import CARTS, CART_STATUSES, DEFAULT_CART_STATUS\nfrom ...utils import get_attr\nfrom ... | false |
3,178 | c9e0586942430fcd5b81c5716a06a4eef2c2f203 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 15:09:26 2017
@author: Jieun
"""
from scipy.stats import invgauss
from scipy.stats import norm
# rv = invgauss.ppf(0.95,mu)
# a = 8/(2*rv)
# print a
# norm.ppf uses mean = 0 and stddev = 1, which is the "standard" normal distribution
# can use a different mean and s... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 21 15:09:26 2017\n\n@author: Jieun\n\"\"\"\n\nfrom scipy.stats import invgauss\nfrom scipy.stats import norm\n\n# rv = invgauss.ppf(0.95,mu) \n# a = 8/(2*rv)\n# print a\n# norm.ppf uses mean = 0 and stddev = 1, which is the \"standard\" normal distribution\n# can... | true |
3,179 | 68a1d5a77abd19aece04bd560df121ceddccea42 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 13:34:46 2017
@author: Sven Geboers
"""
from math import pi,e
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
def LevelToIntensity(NoiseLevelIndB):
I0 = 10.**(-12) #This is the treshold hearing intensity, matchin... | [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 25 13:34:46 2017\r\n\r\n@author: Sven Geboers\r\n\"\"\"\r\n\r\nfrom math import pi,e\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import cm\r\n\r\ndef LevelToIntensity(NoiseLevelIndB):\r\n I0 = 10.**(-12) #This is th... | false |
3,180 | c4b4585501319fd8a8106c91751bb1408912827a | # from django.shortcuts import render
# from django.http import HttpResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.views import generic
from django.urls import reverse_lazy
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import aut... | [
"# from django.shortcuts import render\n# from django.http import HttpResponse\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.views import generic\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth... | false |
3,181 | f615e7bbfa9179d0bfb321242cd8df4ae7b48993 | import org.cogroo.gc.cmdline
import typing
class __module_protocol__(typing.Protocol):
# A module protocol which reflects the result of ``jp.JPackage("org.cogroo.gc")``.
cmdline: org.cogroo.gc.cmdline.__module_protocol__
| [
"import org.cogroo.gc.cmdline\nimport typing\n\n\nclass __module_protocol__(typing.Protocol):\n # A module protocol which reflects the result of ``jp.JPackage(\"org.cogroo.gc\")``.\n\n cmdline: org.cogroo.gc.cmdline.__module_protocol__\n",
"import org.cogroo.gc.cmdline\nimport typing\n\n\nclass __module_pro... | false |
3,182 | 32ca107fde4c98b61d85f6648f30c7601b31c7f3 | """
Django settings for geobombay project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... | [
"\"\"\"\nDjango settings for geobombay project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path... | false |
3,183 | d6791c8122129a46631582e7d9339ea08bd2e92b | # Default imports
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
data = pd.read_csv('data/house_prices_multivariate.csv')
# Your solution code here
def select_from_model(dataframe):
X = dataframe.iloc[:, :-1]
y... | [
"# Default imports\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('data/house_prices_multivariate.csv')\n\n\n# Your solution code here\n\ndef select_from_model(dataframe):\n X = dataframe.i... | false |
3,184 | 58d137d614a0d5c11bf4325c1ade13f4f4f89f52 | print("2 + 3 * 4 =")
print(2 + 3 * 4)
print("2 + (3 * 4) = ")
print(2 + (3 * 4))
| [
"print(\"2 + 3 * 4 =\")\nprint(2 + 3 * 4)\n\nprint(\"2 + (3 * 4) = \")\nprint(2 + (3 * 4))\n",
"print('2 + 3 * 4 =')\nprint(2 + 3 * 4)\nprint('2 + (3 * 4) = ')\nprint(2 + 3 * 4)\n",
"<code token>\n"
] | false |
3,185 | 006f499eed7cd5d73bb0cb9b242c90726fff35c1 | from odoo import models,fields, api
class director(models.Model):
#Clasica
_inherit = 'base.entidad'
_name = 'cinemateca.director'
name = fields.Char(string="name", required=True, help="Nombre del director")
apellidos = fields.Char(string="apellidos", required=True, help="Apellidos del director")
... | [
"from odoo import models,fields, api\n\nclass director(models.Model):\n #Clasica\n _inherit = 'base.entidad'\n _name = 'cinemateca.director'\n name = fields.Char(string=\"name\", required=True, help=\"Nombre del director\")\n apellidos = fields.Char(string=\"apellidos\", required=True, help=\"Apellid... | false |
3,186 | cce85d8a34fd20c699b7a87d402b34231b0d5dbb | from ..models import Empleado, Puesto, Tareas
from django.contrib.auth import login, logout
from django.contrib.auth.models import User, Group
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import EmpleadoSeri... | [
"from ..models import Empleado, Puesto, Tareas\r\nfrom django.contrib.auth import login, logout\r\nfrom django.contrib.auth.models import User, Group\r\nfrom rest_framework.permissions import AllowAny\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.views import APIView\r\nfrom .serializers im... | false |
3,187 | e71a23ef7a065bc4210e55552e19c83c428bc194 | """This module contains an algorithm to find the different
components in a graph represented as an adjacency matrix.
"""
def find_components(adjacency_matrix):
visited = set()
components = []
for node in range(len(adjacency_matrix)):
if node not in visited:
component = []
b... | [
"\"\"\"This module contains an algorithm to find the different\ncomponents in a graph represented as an adjacency matrix.\n\"\"\"\n\n\ndef find_components(adjacency_matrix):\n visited = set()\n components = []\n for node in range(len(adjacency_matrix)):\n if node not in visited:\n compone... | false |
3,188 | 0f3430cbfc928d26dc443fde518881923861f2e3 | from django.urls import path
from .views import PasswordList
urlpatterns = [
path('', PasswordList.as_view()),
]
| [
"from django.urls import path\n\nfrom .views import PasswordList\n\nurlpatterns = [\n path('', PasswordList.as_view()),\n]\n",
"from django.urls import path\nfrom .views import PasswordList\nurlpatterns = [path('', PasswordList.as_view())]\n",
"<import token>\nurlpatterns = [path('', PasswordList.as_view())]... | false |
3,189 | 5669476cc735f569263417b907e8f4a9802cd325 | import socket
import sys
TCP_IP = '192.168.149.129'
TCP_PORT = 5005
BUFFER_SIZE = 2000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
while 1:
print 'user data:'
content = sys.stdin.readline();
s.send(content)
data = s.recv(BUFFER_SIZE)
print "received data:", data
s.clo... | [
"import socket\nimport sys\nTCP_IP = '192.168.149.129'\nTCP_PORT = 5005\nBUFFER_SIZE = 2000\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \ns.connect((TCP_IP, TCP_PORT))\nwhile 1:\n print 'user data:'\n content = sys.stdin.readline();\n s.send(content)\n data = s.recv(BUFFER_SIZE)\n print \"received... | true |
3,190 | a917dd6171a78142fefa8c8bfad0110729fc1bb0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-15 18:46
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('aposta', '0003_aposta_nome'),
]
operations = [
... | [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-15 18:46\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('aposta', '0003_aposta_nome'),\n ]\n\n ... | false |
3,191 | aee8fa7bc1426945d61421fc72732e43ddadafa1 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 29 19:10:06 2018
@author: labuser
"""
# 2018-09-29
import os
import numpy as np
from scipy.stats import cauchy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import pandas as pd
def limit_scan(fname, ax):
data = pd.read_csv(fname, sep='\t', ... | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 29 19:10:06 2018\n\n@author: labuser\n\"\"\"\n\n\n# 2018-09-29\n\nimport os\nimport numpy as np\nfrom scipy.stats import cauchy\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef limit_scan(fname, ax):\n data =... | false |
3,192 | 309807e04bfbf6c32b7105fe87d6ad1247ae411a | #
# PySNMP MIB module ADTRAN-ATLAS-HSSI-V35-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-ATLAS-HSSI-V35-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:59:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.... | [
"#\n# PySNMP MIB module ADTRAN-ATLAS-HSSI-V35-MIB (http://snmplabs.com/pysmi)\n# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-ATLAS-HSSI-V35-MIB\n# Produced by pysmi-0.3.4 at Mon Apr 29 16:59:09 2019\n# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4\n# Using Python ... | false |
3,193 | 51b32972c97df50a45eb2b9ca58cdec0394e63ee | from fractions import Fraction as f
print f(49,98) * f(19, 95) * f(16, 64) * f(26, 65)
| [
"from fractions import Fraction as f\n\nprint f(49,98) * f(19, 95) * f(16, 64) * f(26, 65)\n"
] | true |
3,194 | 1630a3d0becac195feee95a1c3b23568612a48d2 | import preprocessing
import tokenization
import vectorspacemodel
import pickle
import collections
import os
import math
import operator
from itertools import islice
def take(n, iterable):
# "Return first n items of the iterable as a list"
return list(islice(iterable, n))
directory = os.getcwd()
... | [
"import preprocessing\r\nimport tokenization\r\nimport vectorspacemodel\r\nimport pickle\r\nimport collections\r\nimport os\r\nimport math\r\nimport operator\r\nfrom itertools import islice\r\n\r\ndef take(n, iterable):\r\n # \"Return first n items of the iterable as a list\"\r\n return list(islice(iterable, ... | false |
3,195 | ca3cdbd5d5d30be4f40925366994c3ea9d9b9614 | from django.db import models
from datetime import datetime
class Folder(models.Model):
folder = models.CharField(max_length=200, default = "misc")
num_of_entries = models.IntegerField(default=0)
def __str__(self):
return self.folder
class Meta:
verbose_name_plural = "Folders/Categories"
class Bookmark(model... | [
"from django.db import models\nfrom datetime import datetime\n\nclass Folder(models.Model):\n\tfolder = models.CharField(max_length=200, default = \"misc\")\n\tnum_of_entries = models.IntegerField(default=0)\n\n\tdef __str__(self):\n\t\treturn self.folder\n\n\tclass Meta:\n\t\tverbose_name_plural = \"Folders/Catego... | false |
3,196 | 8f554166c28fe4c9a093568a97d39b6ba515241b | # This implementation of EPG takes data as XML and produces corresponding pseudonymized data
from lxml import etree
from utils import generalize_or_supress
from hashlib import sha256
from count import getLast, saveCount
import pickle
from hmac import new
from random import random
from json import loads
from bigchain i... | [
"# This implementation of EPG takes data as XML and produces corresponding pseudonymized data\n\nfrom lxml import etree\nfrom utils import generalize_or_supress\nfrom hashlib import sha256\nfrom count import getLast, saveCount\nimport pickle\nfrom hmac import new\nfrom random import random\nfrom json import loads\n... | false |
3,197 | ba7f66a0f9cf1028add778315033d596e10d6f16 | import numpy as np
import tensorflow as tf
x_data = np.random.rand(100)
y_data = x_data * 10 + 5
#构造线性模型
b = tf.Variable(0.)
k = tf.Variable(0.)
y=k*x_data+b
#二次代价函数 square求平方
loss= tf.reduce_mean(tf.square(y_data-y))
#定义一个梯度下降法来进行训练的优化器
optimizer=tf.train.GradientDescentOptimizer(.2)
train=optimizer.minimize(... | [
"import numpy as np\nimport tensorflow as tf\n\nx_data = np.random.rand(100)\ny_data = x_data * 10 + 5\n\n#构造线性模型\nb = tf.Variable(0.)\nk = tf.Variable(0.)\ny=k*x_data+b\n\n\n#二次代价函数 square求平方\nloss= tf.reduce_mean(tf.square(y_data-y))\n\n#定义一个梯度下降法来进行训练的优化器\n\noptimizer=tf.train.GradientDescentOptimizer(.2)\n\nt... | false |
3,198 | ffd034eb5f0482c027dcc344bddb01b90249511c | import os
import io
import time
import multiprocessing as mp
from queue import Empty
import picamera
from PIL import Image
from http import server
import socketserver
import numpy as np
import cv2
class QueueOutputMJPEG(object):
def __init__(self, queue, finished):
self.queue = queue
self.finished ... | [
"import os\nimport io\nimport time\nimport multiprocessing as mp\nfrom queue import Empty\nimport picamera\nfrom PIL import Image\nfrom http import server\nimport socketserver\nimport numpy as np\nimport cv2\n\nclass QueueOutputMJPEG(object):\n def __init__(self, queue, finished):\n self.queue = queue\n ... | false |
3,199 | 1cf5ce11b965d65426ed421ef369954c59d7eba9 | # Generated by Django 3.2.4 on 2021-06-29 13:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_blogdetail'),
]
operations = [
migrations.RenameField(
model_name='bloglist',
old_name='about',
new... | [
"# Generated by Django 3.2.4 on 2021-06-29 13:20\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0002_blogdetail'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='bloglist',\n old_name='abou... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.