index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
9,400
451c353a949458f5f71783c4aba1888c40018bfa
from rest_framework import serializers from . import models class RaumSerializer(serializers.ModelSerializer): class Meta: model = models.Raum fields = [ "Raumnummer", "Anzahl_Sitzplaetze", "Beamer", "Whiteboard", ] class ZeitraumSerialize...
[ "from rest_framework import serializers\n\nfrom . import models\n\n\nclass RaumSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Raum\n fields = [\n \"Raumnummer\",\n \"Anzahl_Sitzplaetze\",\n \"Beamer\",\n \"Whiteboard\",\n ...
false
9,401
971187dc0e0f02282c8945940d07c011e247667a
""" Kontrollülesanne 7.4c - Elutee number (tähtaeg 28.okt. (incl)) Maksimaalne failide arv: 1 Töö liik: Individuaaltöö Numeroloogias peetakse tähtsaks elutee numbrit, mille arvutamiseks tuleb liita kokku sünnikuupäeva ja -aasta numbrid nii, et jõutakse lõpuks ühe numbrini. Näiteks, oletame, et sünnikuupäev on 15.05....
[ "\"\"\"\nKontrollülesanne 7.4c - Elutee number (tähtaeg 28.okt. (incl))\nMaksimaalne failide arv: 1\nTöö liik: Individuaaltöö\n\n\nNumeroloogias peetakse tähtsaks elutee numbrit, mille arvutamiseks tuleb liita kokku sünnikuupäeva ja -aasta numbrid\nnii, et jõutakse lõpuks ühe numbrini.\n\nNäiteks, oletame, et sünni...
false
9,402
6d042a2035eab579193452e4dc44c425125d9515
from flask_restful import Resource, reqparse import nltk from nltk.tokenize import sent_tokenize tokenizer = nltk.RegexpTokenizer(r"\w+") # CLASS DESCRIPTION: # Devides and clears the sentence of punctuation marks and builds a dependency tree on each sentence # Allocates its own names and verbs # added: Te...
[ "from flask_restful import Resource, reqparse\nimport nltk\nfrom nltk.tokenize import sent_tokenize\ntokenizer = nltk.RegexpTokenizer(r\"\\w+\")\n\n# CLASS DESCRIPTION:\n # Devides and clears the sentence of punctuation marks and builds a dependency tree on each sentence\n # Allocates its own names and verbs\...
false
9,403
1930aa258ac4fbcdb2972e19bdb2625d2dae4114
from console import Display import time images = ["/img/erni_l.txt", "/img/erni_s.txt", "/img/erni_logo.txt", "/img/github_logo.txt", "/img/upython_logo.txt", "/img/python_logo.txt", "/img/upython_logo_s.txt", "/img/MSC_logo.txt"] def show(): oled = Display() for image in images: ...
[ "from console import Display\nimport time\n\nimages = [\"/img/erni_l.txt\", \"/img/erni_s.txt\", \"/img/erni_logo.txt\", \"/img/github_logo.txt\",\n \"/img/upython_logo.txt\", \"/img/python_logo.txt\", \"/img/upython_logo_s.txt\",\n \"/img/MSC_logo.txt\"]\n\n\ndef show():\n \n oled = Display...
false
9,404
fe73a80b15cad025a33930ddd9abb31524cd0244
# coding: utf-8 from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import time from urllib import urlencode from urlparse import parse_qs, urlparse, urlunparse from flask import current_app as app from flask import url_for from jose import jwt from oauth2client.cl...
[ "# coding: utf-8\n\nfrom __future__ import (\n absolute_import,\n division,\n print_function,\n unicode_literals,\n)\n\nimport time\nfrom urllib import urlencode\nfrom urlparse import parse_qs, urlparse, urlunparse\n\nfrom flask import current_app as app\nfrom flask import url_for\nfrom jose import jwt\...
false
9,405
d1a179acfda9e76a11f362671fafb50773e2b9d3
# -- !/python3.10 # Mikhail (myke) Kolodin, 2021 # 2021-10-21 2021-10-21 1.2 # retext.py # Заменить во входном тексте указанное слово на случайный вариант # из предложенного набора заменителей. # Параметры - в командной строке. import re, random, sys fin = 'retext-in.txt' fot = 'retext-out.txt' t1 = """ here we go...
[ "# -- !/python3.10\n\n# Mikhail (myke) Kolodin, 2021\n# 2021-10-21 2021-10-21 1.2\n# retext.py\n# Заменить во входном тексте указанное слово на случайный вариант\n# из предложенного набора заменителей.\n# Параметры - в командной строке.\n\nimport re, random, sys\n\nfin = 'retext-in.txt'\nfot = 'retext-out.txt'\n\n...
false
9,406
5c5922fd3a7a5eec121d94e69bc972089e435175
################################################# ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### ################################################# # file to edit: dev_nb/10_DogcatcherFlatten.ipynb import pandas as pd import argparse import csv import os import numpy as np import string def FivePrimeArea(df): ...
[ "\n#################################################\n### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###\n#################################################\n# file to edit: dev_nb/10_DogcatcherFlatten.ipynb\nimport pandas as pd\nimport argparse\nimport csv\nimport os\n\nimport numpy as np\nimport string\n\ndef FiveP...
false
9,407
1c2967c26c845281ceb46cc1d8c06768298ef6b6
import numpy as np import pandas as pd from unrar import rarfile import numpy as np import pandas as pd import tushare as ts import os year_month='201911' contract_kind='NI' rar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/' main_code_path='C:/Users/lenovo/Documents/WeCha...
[ "import numpy as np \nimport pandas as pd\nfrom unrar import rarfile\nimport numpy as np \nimport pandas as pd\nimport tushare as ts\nimport os\n\nyear_month='201911'\ncontract_kind='NI'\nrar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/'\nmain_code_path='C:/Users/lenovo...
false
9,408
ba42c6af53329035f7ab72f3f1ac87cd90d9dc7f
# difference between size an shape of an image import cv2 img = cv2.imread('police.jpg') print img.size # byte size; slightly larger than the file size print img.shape # y,x or rows, cols cv2.imshow("My Picture", img) cv2.waitKey(0) cv2.destroyAllWindows()
[ "# difference between size an shape of an image\r\n\r\nimport cv2\r\n\r\nimg = cv2.imread('police.jpg')\r\nprint img.size # byte size; slightly larger than the file size\r\nprint img.shape # y,x or rows, cols\r\n\r\ncv2.imshow(\"My Picture\", img)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()" ]
true
9,409
9ffe350ff9a568111620ef7dafef83d341f6f01e
# -*- coding: utf-8 -*- # https://github.com/Raschka-research-group/coral-cnn/tree/master/model-code/resnet34 from absl import flags, app from Rank_consistent_model_fix import * from Rank_consistent_model import * from random import shuffle, random import tensorflow as tf import numpy as np # import cv2 import os impo...
[ "# -*- coding: utf-8 -*-\n# https://github.com/Raschka-research-group/coral-cnn/tree/master/model-code/resnet34\nfrom absl import flags, app\nfrom Rank_consistent_model_fix import *\nfrom Rank_consistent_model import *\nfrom random import shuffle, random\n\nimport tensorflow as tf\nimport numpy as np\n# import cv2\...
false
9,410
8c7fe90972feec19e280d3bccd39391af666608a
def play(): print("playing tank games...") print("runing tank now!!!")
[ "def play():\n print(\"playing tank games...\")\nprint(\"runing tank now!!!\")", "def play():\n print('playing tank games...')\n\n\nprint('runing tank now!!!')\n", "def play():\n print('playing tank games...')\n\n\n<code token>\n", "<function token>\n<code token>\n" ]
false
9,411
f9dd20a3b72c0c8e72029459244486f31eaff536
import dash_html_components as html import dash_core_components as dcc import dash_daq as daq import dash_bootstrap_components as dbc import src.common.common_layout as layout_common def build_navbar(): return html.Div( id="banner", children=[ html.Div( id="banner-text...
[ "import dash_html_components as html\nimport dash_core_components as dcc\nimport dash_daq as daq\nimport dash_bootstrap_components as dbc\n\nimport src.common.common_layout as layout_common\n\n\ndef build_navbar():\n return html.Div(\n id=\"banner\",\n children=[\n html.Div(\n ...
false
9,412
a0d1ef11d00e2ddd65b648a87f493b7adcda5115
class RankedHand(object): def __init__(self, remaining_cards): self._remaining_cards = remaining_cards self.rank = None def remaining_cards(self): return self._remaining_cards # Returns 1 if self is higher, 0 if equal, -1 if self is lower def compare_high_cards(self, other): s_cards = reversed...
[ "class RankedHand(object):\n def __init__(self, remaining_cards):\n self._remaining_cards = remaining_cards\n self.rank = None\n\n def remaining_cards(self):\n return self._remaining_cards\n\n # Returns 1 if self is higher, 0 if equal, -1 if self is lower\n def compare_high_cards(self, other):\n s_c...
false
9,413
b4454d92ab8380e0eded2f7aed737378e1710c72
#!/usr/bin/env python3 import sys, os import random import numpy as np import matplotlib as mpl if os.environ.get('DISPLAY','') == '': print('no display found. Using non-interactive Agg backend') mpl.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import sha...
[ "#!/usr/bin/env python3\n\nimport sys, os\nimport random\nimport numpy as np\n\nimport matplotlib as mpl\nif os.environ.get('DISPLAY','') == '':\n print('no display found. Using non-interactive Agg backend')\n mpl.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom mpl_toolkits.axes_grid1 import make_axes_loc...
false
9,414
39f1fc04911f8d22d07532add24cd1671a569e72
from airflow.plugins_manager import AirflowPlugin from flask import Blueprint, Flask from rest_api.log.views import views from rest_api.route.log_route import log from rest_api.route.mylog_route import my_log_pb from rest_api.route.native_log_route import native_log_bp class AirflowPlugin(AirflowPlugin): name = "...
[ "from airflow.plugins_manager import AirflowPlugin\nfrom flask import Blueprint, Flask\nfrom rest_api.log.views import views\nfrom rest_api.route.log_route import log\nfrom rest_api.route.mylog_route import my_log_pb\nfrom rest_api.route.native_log_route import native_log_bp\n\n\nclass AirflowPlugin(AirflowPlugin):...
false
9,415
0a459b4aeb2a16c06c1d89dafb656028b235a31e
import math def calcula_distancia_do_projetil(v, O, y0): g = 9.8 return ((v ** 2) / 2 * g) * (1 + math.sqrt(1 + ( 2 * g * y0 / (v ** 2) * (math.sin(O) ** 2)))) * math.sin(2 * O)
[ "import math\n\ndef calcula_distancia_do_projetil(v, O, y0):\n g = 9.8\n return ((v ** 2) / 2 * g) * (1 + math.sqrt(1 + ( 2 * g * y0 / (v ** 2) * (math.sin(O) ** 2)))) * math.sin(2 * O)", "import math\n\n\ndef calcula_distancia_do_projetil(v, O, y0):\n g = 9.8\n return v ** 2 / 2 * g * (1 + math.sqrt(...
false
9,416
2a799d81d963f73d8018a99cbd963af166681b35
def factorial(num): assert num >= 0 and int(num) == num, 'Only positive integer accept' if num in [0,1]: return 1 else: return num*factorial(num-1) print(factorial(4.4))
[ "def factorial(num):\n assert num >= 0 and int(num) == num, 'Only positive integer accept'\n if num in [0,1]:\n return 1\n else:\n return num*factorial(num-1)\n\nprint(factorial(4.4))", "def factorial(num):\n assert num >= 0 and int(num) == num, 'Only positive integer accept'\n if num...
false
9,417
657ac500c40ddbd29f5e3736a78ed43e7d105478
num=int(input("Enter the number: ")) table=[num*i for i in range(1,11)] print(table) with open("table.txt","a") as f: f.write(f"{num} table is: {str(table)}") f.write('\n')
[ "num=int(input(\"Enter the number: \"))\n\ntable=[num*i for i in range(1,11)]\nprint(table)\nwith open(\"table.txt\",\"a\") as f:\n f.write(f\"{num} table is: {str(table)}\")\n f.write('\\n')", "num = int(input('Enter the number: '))\ntable = [(num * i) for i in range(1, 11)]\nprint(table)\nwith open('table...
false
9,418
25595b5f86a41fee1dc43f199f3bcff73f6d256b
import ray import os import sys import random path_join = os.path.join real_path = os.path.realpath perfd_dir = real_path(path_join(os.getcwd())) microps_dir = path_join(perfd_dir, "thirdparty", "microps") sys.path += [perfd_dir, microps_dir] from thirdparty.microps.oracle.experiments.spark_sql_perf.main import Spar...
[ "import ray\nimport os\nimport sys\nimport random\n\npath_join = os.path.join\nreal_path = os.path.realpath\n\nperfd_dir = real_path(path_join(os.getcwd()))\nmicrops_dir = path_join(perfd_dir, \"thirdparty\", \"microps\")\nsys.path += [perfd_dir, microps_dir]\n\nfrom thirdparty.microps.oracle.experiments.spark_sql_...
false
9,419
0a5baacf17d33dbf6ea69114a8632f7fcef52c3c
import tkinter from tkinter import messagebox from random import randint tplyer = 0 tcomp = 0 player = 0 comp = 0 top = tkinter.Tk() top.resizable(width = False, height =False) top.geometry("200x100") def Yes(): global player global comp tplayer = randint(1,6) tcomp = randint(1,6) message ="" if tplay...
[ "import tkinter\nfrom tkinter import messagebox\nfrom random import randint\ntplyer = 0\ntcomp = 0\nplayer = 0\ncomp = 0\ntop = tkinter.Tk()\ntop.resizable(width = False, height =False)\ntop.geometry(\"200x100\")\ndef Yes():\n global player\n global comp\n tplayer = randint(1,6)\n tcomp = randint(1,6)\n m...
false
9,420
b569f0a0dda048d6337e1028a240caabf188a174
___author__ = 'acmASCIS' ''' by ahani at {9/24/2016} ''' import time class Freq(object): def __init__(self, array): self.__array = array self.__frequency_dict = {} self.__array_length = len(array) self.__running_time = round(time.time() * 1000) def get_original_array(sel...
[ "___author__ = 'acmASCIS'\n\n'''\n by ahani at {9/24/2016}\n'''\n\nimport time\n\n\nclass Freq(object):\n def __init__(self, array):\n self.__array = array\n self.__frequency_dict = {}\n self.__array_length = len(array)\n self.__running_time = round(time.time() * 1000)\n\n def g...
false
9,421
c0b6c0636d1900a31cc455795838eb958d1daf65
# Find a list of patterns in a list of string in python any([ p in s for p in patterns for s in strings ])
[ "# Find a list of patterns in a list of string in python\nany([ p in s for p in patterns for s in strings ])\n", "any([(p in s) for p in patterns for s in strings])\n", "<code token>\n" ]
false
9,422
00609c4972269c36bbfcf5bec2a8648f812b6092
# -*- coding: utf-8 -*- """ Created on Fri Oct 5 09:10:03 2018 @author: User """ from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import re url = "http://www.pythonscraping.com/pages/page3.html" html = urlopen(url) html_data = BeautifulSoup(html.read(), "lxml") img...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 5 09:10:03 2018\n\n@author: User\n\"\"\"\n\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\nimport re\n\nurl = \"http://www.pythonscraping.com/pages/page3.html\"\nhtml = urlopen(url)\nhtml_data = BeautifulSo...
false
9,423
02a228c479a6c94858f7e8ef73a7c8528def871e
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ plus = True # In the last digit, we should add one as the quesiton requries indexList = range(len(digits)) indexList.reverse() for i in indexList: ...
[ "class Solution(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n plus = True # In the last digit, we should add one as the quesiton requries\n indexList = range(len(digits))\n indexList.reverse()\n for ...
false
9,424
9cea998d7d5cad3ddc00f667ca06151a938d48a1
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : gan_loss.py # @Time : Created at 2019-07-11 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import torch import torch.nn as nn import config as cfg class ...
[ "# -*- coding: utf-8 -*-\n# @Author : William\n# @Project : TextGAN-william\n# @FileName : gan_loss.py\n# @Time : Created at 2019-07-11\n# @Blog : http://zhiweil.ml/\n# @Description : \n# Copyrights (C) 2018. All Rights Reserved.\n\nimport torch\nimport torch.nn as nn\n\nimport confi...
false
9,425
e99ff1c75d5108efc8d587d4533c34eeb15c6978
from django.contrib.staticfiles.storage import CachedFilesMixin from storages.backends.s3boto3 import S3Boto3Storage class CachedS3Storage(CachedFilesMixin, S3Boto3Storage): pass StaticRootS3BotoStorage = lambda: CachedS3Storage(location='static') MediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media'...
[ "from django.contrib.staticfiles.storage import CachedFilesMixin\nfrom storages.backends.s3boto3 import S3Boto3Storage\n\n\nclass CachedS3Storage(CachedFilesMixin, S3Boto3Storage):\n pass\n\n\nStaticRootS3BotoStorage = lambda: CachedS3Storage(location='static')\nMediaRootS3BotoStorage = lambda: S3Boto3Storage(lo...
false
9,426
97a362fc65731bb8fc3743c49a669b4cd3f0e155
import collections import numpy import pytest import random import conftest from svviz2.io import readstatistics from svviz2.remap import genotyping from svviz2.utility.intervals import Locus def get_read_stats(isize=400): stats = readstatistics.ReadStatistics(None) stats.insertSizes = numpy.random.normal(400...
[ "import collections\nimport numpy\nimport pytest\nimport random\n\nimport conftest\nfrom svviz2.io import readstatistics\nfrom svviz2.remap import genotyping\nfrom svviz2.utility.intervals import Locus\n\ndef get_read_stats(isize=400):\n stats = readstatistics.ReadStatistics(None)\n stats.insertSizes = numpy....
false
9,427
7bb49712c4ef482c64f3c2a457a766de691ba7c3
def bfs(graph, start): queue = [start] queued = list() path = list() while queue: print('Queue is: %s' % queue) vertex = queue.pop(0) print('Processing %s' % vertex) for candidate in graph[vertex]: if candidate not in queued: queued.append(candidate) queue.append(candidat...
[ "def bfs(graph, start):\n queue = [start]\n queued = list()\n path = list()\n\n while queue:\n print('Queue is: %s' % queue)\n vertex = queue.pop(0)\n print('Processing %s' % vertex)\n\n for candidate in graph[vertex]:\n if candidate not in queued:\n queued.append(candidate)\n que...
false
9,428
267276eab470b5216a2102f3e7616f7aecadcfe9
# ------------------------------------------- # Created by: jasper # Date: 11/24/19 # -------------------------------------------- from os import path, mkdir class IOHandler: def __init__(self, directory, fName, data_instance): """Save the setup of a class instance or...
[ "# -------------------------------------------\n\n# Created by: jasper\n# Date: 11/24/19\n\n# --------------------------------------------\n\nfrom os import path, mkdir\n\n\nclass IOHandler:\n\n def __init__(self, directory, fName, data_instance):\n \"\"\"Save the setup o...
false
9,429
7025cc896035c59e0bbb7943493b6ca24fd9e6ca
from flask import Flask, render_template, request app = Flask(__name__) def convert(decimal_num): roman = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'} num_to_roman = '' for i in roman.keys(): num_to_roman += roman[i]*(decimal_num/...
[ "from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\ndef convert(decimal_num):\n roman = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'}\n num_to_roman = ''\n for i in roman.keys():\n num_to_roman += roman[i]*...
false
9,430
7e318ae7317eac90d6ce9a6b1d0dcc8ff65abef0
from dataclasses import dataclass, field from typing import List @dataclass class Root: a: List[object] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 2, "max_occurs": 4, "sequence": 1, ...
[ "from dataclasses import dataclass, field\nfrom typing import List\n\n\n@dataclass\nclass Root:\n a: List[object] = field(\n default_factory=list,\n metadata={\n \"type\": \"Element\",\n \"namespace\": \"\",\n \"min_occurs\": 2,\n \"max_occurs\": 4,\n ...
false
9,431
eb81f1825c4ac8e20dde1daefbdad22f588e696e
#1.문자열에 홑따옴표 포함기키기 : 쌍따옴표 print("Python's Data Type") #2.문자열에 쌍따옴표 포함시키기 : 홑따옴표 print('"Python is very easy" he said.') #멀티라인(여러줄)표현하기 #1. 연속된 쌍따옴표 3개 사용하기 print("""No pain No gain""") #2. 연속된 쌍따옴표 3개 사용하기 print('''No pain No gain''') #3.이스케이프 코드 \n 삽입하기 print("No pain \n No gain") """ 이스케이프(es...
[ "#1.문자열에 홑따옴표 포함기키기 : 쌍따옴표\nprint(\"Python's Data Type\")\n\n#2.문자열에 쌍따옴표 포함시키기 : 홑따옴표\nprint('\"Python is very easy\" he said.')\n\n#멀티라인(여러줄)표현하기\n#1. 연속된 쌍따옴표 3개 사용하기\nprint(\"\"\"No pain\n No gain\"\"\")\n\n#2. 연속된 쌍따옴표 3개 사용하기\nprint('''No pain\n No gain''')\n\n#3.이스케이프 코드 \\n 삽입하기\nprint(\"N...
false
9,432
f5274f5d838d484ca0c1cc5a5192a2fd698cf827
from .. import CURRENT_NAME from ..cmd import call_cmd from .config import Configurator from .config import USER_INI from icemac.install.addressbook._compat import Path import argparse import os import pdb # noqa: T002 import sys def update(stdin=None): """Update the current address book installation.""" cur...
[ "from .. import CURRENT_NAME\nfrom ..cmd import call_cmd\nfrom .config import Configurator\nfrom .config import USER_INI\nfrom icemac.install.addressbook._compat import Path\nimport argparse\nimport os\nimport pdb # noqa: T002\nimport sys\n\n\ndef update(stdin=None):\n \"\"\"Update the current address book inst...
false
9,433
1e168cf6ba785a08244f47eb490b54605a09e4b0
traditional_investor_stage1 = \ "SELECT investor, investor_id, invest_amount, invest_change, security_id, isin, issue_date, maturity_date "\ "FROM "\ "(SELECT "\ "report_date, "\ "investor_holdings.investor_name AS investor,"\ "investor_id,"\ ...
[ "\n\ntraditional_investor_stage1 = \\\n \"SELECT investor, investor_id, invest_amount, invest_change, security_id, isin, issue_date, maturity_date \"\\\n \"FROM \"\\\n \"(SELECT \"\\\n \"report_date, \"\\\n \"investor_holdings.investor_name AS investor,\"\\\n ...
false
9,434
8bb67317ede277e03e8cbdefefeffa3d206ece65
from os import listdir import re import numpy as np from sklearn.metrics import f1_score from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import LeaveOneOut import matplotlib.pyplot as plt n_gram_range = (1, 1) alpha_smoothing = 1e-1...
[ "from os import listdir\nimport re\nimport numpy as np\nfrom sklearn.metrics import f1_score\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import LeaveOneOut\nimport matplotlib.pyplot as plt\n\nn_gram_range = (1, 1)\nalpha_s...
false
9,435
63068a15d750abb29398d687495d6001ba17ab8a
""""""""""""""" Write Data """"""""""""""" import json from city import City def load_json(file_name='data.json'): with open(file_name, 'r') as json_fp: json_data = json_fp.read() data_arr = json.loads(json_data) return data_arr if __name__ == '__main__': json_file = 'data.json' ...
[ "\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nWrite Data\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nimport json\nfrom city import City\n\ndef load_json(file_name='data.json'):\n with open(file_name, 'r') as json_fp:\n json_data = json_fp.read()\n data_arr = json.loads(json_data)\n return data_arr\n\nif __name__...
false
9,436
0d022291f9ace02ef1ee5c462657ea6376a0e6a4
import RPi.GPIO as GPIO import time from datetime import datetime led1 = [('g', 40), ('f', 38), ('a', 36), ('b', 32), ('e', 26), ('d', 24), ('c', 22)] led2 = [('g', 19), ('f', 15), ('a', 13), ('b', 11), ('e', 7), ('d', 5), ('c', 3)] numbers = [ ('a', 'b', 'c', 'd', 'e', 'f'), ('b', 'c'), ('...
[ "import RPi.GPIO as GPIO\nimport time\nfrom datetime import datetime\n\nled1 = [('g', 40), ('f', 38), ('a', 36), ('b', 32),\n ('e', 26), ('d', 24), ('c', 22)]\nled2 = [('g', 19), ('f', 15), ('a', 13),\n ('b', 11), ('e', 7), ('d', 5), ('c', 3)]\nnumbers = [\n ('a', 'b', 'c', 'd', 'e', 'f'),\n ('b...
false
9,437
d190eb27ea146cf99ac7f8d29fb5f769121af60e
M, N = 3, 16 prime = set(range(M, N+1)) for i in range(2, N+1): prime -= set(range(i**2, N+1, i)) for number in prime: print(number)
[ "M, N = 3, 16\nprime = set(range(M, N+1))\nfor i in range(2, N+1):\n prime -= set(range(i**2, N+1, i))\n\nfor number in prime:\n print(number)", "M, N = 3, 16\nprime = set(range(M, N + 1))\nfor i in range(2, N + 1):\n prime -= set(range(i ** 2, N + 1, i))\nfor number in prime:\n print(number)\n", "<...
false
9,438
56afde2a31ad9dddee35e84609dff2eb0fc6fe1a
# Mezzanine Django Framework createdb error on Max OSX 10.9.2 import django django.version
[ "# Mezzanine Django Framework createdb error on Max OSX 10.9.2\nimport django\ndjango.version\n", "import django\ndjango.version\n", "<import token>\ndjango.version\n", "<import token>\n<code token>\n" ]
false
9,439
8beafcd4f9c02657a828d8c37f2aecda325ba180
import pickle from numpy import * import math import matplotlib.pyplot as plt import numpy as np from matplotlib import animation from math import factorial def savitzky_golay(y, window_size, order, deriv=0, rate=1): order_range = range(order+1) half_window = (window_size -1) // 2 b = np.mat([[k**i for i i...
[ "import pickle\nfrom numpy import *\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import animation\nfrom math import factorial\n\ndef savitzky_golay(y, window_size, order, deriv=0, rate=1):\n order_range = range(order+1)\n half_window = (window_size -1) // 2\n b = np.ma...
false
9,440
f91e997b305348485698d180b97138b040285b60
class Line: def __init__(self,coor1,coor2): self.coor1 = coor1 self.coor2 = coor2 def slope(self): pass def distance(self): #x = self.coor1[0]-self.coor2[0] #y = self.coor2[1]-self.coor2[1] #return ((x**2)+(y**2))**0.5 return ((((self.coor2[0]-s...
[ "class Line:\n def __init__(self,coor1,coor2):\n self.coor1 = coor1\n self.coor2 = coor2 \n \n def slope(self):\n pass\n\n def distance(self):\n #x = self.coor1[0]-self.coor2[0]\n #y = self.coor2[1]-self.coor2[1]\n #return ((x**2)+(y**2))**0.5\n return ((...
false
9,441
8f854f4f2c807f988945af4dc53dba93cfb31168
## Author: Aleem Juma import os from app import app import pandas as pd # read in the quotes database q = pd.read_csv(os.path.join('app','data','quotes_all.csv'), sep=';', skiprows=1, header=0) # there are a few quote genres that don't occur in the model vocab # replace them with appropriate words so the similarity ...
[ "## Author: Aleem Juma\n\nimport os\nfrom app import app\nimport pandas as pd\n\n# read in the quotes database\nq = pd.read_csv(os.path.join('app','data','quotes_all.csv'), sep=';', skiprows=1, header=0)\n\n# there are a few quote genres that don't occur in the model vocab\n# replace them with appropriate words so ...
false
9,442
82c3bde5746d04c126a93851844f775e7ce65f4b
import torch import numpy as np # source: https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb def kernel(X1, X2, l=1.0, sigma_f=1.0): ''' Isotropic squared exponential kernel. Computes a covariance matrix from points in X1 and X2. Args: X1: Array of m points (m x d). X2: Arr...
[ "import torch\nimport numpy as np\n\n\n# source: https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb\ndef kernel(X1, X2, l=1.0, sigma_f=1.0):\n ''' Isotropic squared exponential kernel. Computes a covariance matrix from points in X1 and X2. Args: X1: Array of m points (m x ...
false
9,443
b9a262bd6ddbca3b214825a473d870e70e8b5e57
#!/usr/bin/env python import fileinput import sys import os from argparse import ArgumentParser from probin.model.composition import multinomial as mn from probin.dna import DNA from Bio import SeqIO from corrbin.misc import all_but_index, Uniq_id, GenomeGroup from corrbin.multinomial import Experiment from corrbin.co...
[ "#!/usr/bin/env python\nimport fileinput\nimport sys\nimport os\nfrom argparse import ArgumentParser\nfrom probin.model.composition import multinomial as mn \nfrom probin.dna import DNA\nfrom Bio import SeqIO\nfrom corrbin.misc import all_but_index, Uniq_id, GenomeGroup\nfrom corrbin.multinomial import Experiment\n...
false
9,444
814191a577db279389975e5a02e72cd817254275
""" Version information for NetworkX, created during installation. Do not add this file to the repository. """ import datetime version = '2.3' date = 'Thu Apr 11 20:57:18 2019' # Was NetworkX built from a development version? If so, remember that the major # and minor versions reference the "target" (rather than "...
[ "\"\"\"\nVersion information for NetworkX, created during installation.\n\nDo not add this file to the repository.\n\n\"\"\"\n\nimport datetime\n\nversion = '2.3'\ndate = 'Thu Apr 11 20:57:18 2019'\n\n# Was NetworkX built from a development version? If so, remember that the major\n# and minor versions reference the...
false
9,445
920f00632599945397364dd0f52f21234e17f9ef
from context import vicemergencyapi from vicemergencyapi.vicemergency import VicEmergency from geographiclib.geodesic import Geodesic from shapely.geometry import Point def geoDistance(p1, p2): return Geodesic.WGS84.Inverse(p1.y, p1.x, p2.y, p2.x)['s12'] melbourne = Point(144.962272, -37.812274) def compare(f...
[ "from context import vicemergencyapi\nfrom vicemergencyapi.vicemergency import VicEmergency\n\nfrom geographiclib.geodesic import Geodesic\nfrom shapely.geometry import Point\n\n\ndef geoDistance(p1, p2):\n return Geodesic.WGS84.Inverse(p1.y, p1.x, p2.y, p2.x)['s12']\n\n\nmelbourne = Point(144.962272, -37.812274...
false
9,446
fbd8af4ab3e4ebdcb07509db776d38f9c26fd06a
# # MIT License # # Copyright (c) 2018 Matteo Poggi m.poggi@unibo.it # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, c...
[ "#\n# MIT License\n#\n# Copyright (c) 2018 Matteo Poggi m.poggi@unibo.it\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 the righ...
false
9,447
293533d07b530be9e8f97f1720619bf6c3113cca
import os import sys import string from array import * from datetime import datetime #f = open('input_test.txt', 'r') f = open('input_task.txt', 'r') width = 60 height = 5000 sleepingMinutes = [[0 for x in range(width)] for y in range(height)] infos = [] # Change lines to tuples and store to array for sorting for l...
[ "import os\nimport sys\nimport string\nfrom array import *\nfrom datetime import datetime\n\n#f = open('input_test.txt', 'r')\nf = open('input_task.txt', 'r')\n\nwidth = 60\nheight = 5000\nsleepingMinutes = [[0 for x in range(width)] for y in range(height)]\n\ninfos = []\n\n# Change lines to tuples and store to arr...
false
9,448
1304b6373edeca394070b8a3d144608cf07172e3
from datetime import datetime from unittest import mock import pytest from freezegun import freeze_time from datahub.ingestion.api.common import PipelineContext from src.datahub.ingestion.source.aws.s3_util import make_s3_urn FROZEN_TIME = "2020-04-14 07:00:00" @pytest.mark.integration def test_athena_config_query...
[ "from datetime import datetime\nfrom unittest import mock\n\nimport pytest\nfrom freezegun import freeze_time\n\nfrom datahub.ingestion.api.common import PipelineContext\nfrom src.datahub.ingestion.source.aws.s3_util import make_s3_urn\n\nFROZEN_TIME = \"2020-04-14 07:00:00\"\n\n\n@pytest.mark.integration\ndef test...
false
9,449
39eecf1c7ec19f7c75721caa092c08569f53d3e5
#Classe do controlador do servidor SEEEEEEERVIDOOOOOOOOOOR from usuarioModel import * class ControllerSC: ''' O controlador define 2 ações: - adicionar_pessoa: para adicionar novas pessoas no banco de dados. - listar_pessoas: retornar a lista das pessoas Note que as 2 ações supracita...
[ "#Classe do controlador do servidor SEEEEEEERVIDOOOOOOOOOOR\n\nfrom usuarioModel import *\n\n\nclass ControllerSC:\n '''\n O controlador define 2 ações:\n - adicionar_pessoa: para adicionar novas pessoas no banco de\n dados. \n - listar_pessoas: retornar a lista das pessoas\n\n Note que as ...
false
9,450
b748c489b2c63546feada811aa3b66146ad8d28e
#!/usr/bin/python3 import json def from_json_string(my_str): """Function returns a JSON file representation of an object (string)""" return json.loads(my_str)
[ "#!/usr/bin/python3\nimport json\n\n\ndef from_json_string(my_str):\n \"\"\"Function returns a JSON file representation of an object (string)\"\"\"\n\n return json.loads(my_str)\n", "import json\n\n\ndef from_json_string(my_str):\n \"\"\"Function returns a JSON file representation of an object (string)\"...
false
9,451
369bffa21b5b8c0ca1d93da3aa30a38e2f4c82cc
import scrapy from kingfisher_scrapy.base_spiders import BigFileSpider from kingfisher_scrapy.util import components, handle_http_error class France(BigFileSpider): """ Domain France Swagger API documentation https://doc.data.gouv.fr/api/reference/ """ name = 'france' # SimpleSpi...
[ "import scrapy\n\nfrom kingfisher_scrapy.base_spiders import BigFileSpider\nfrom kingfisher_scrapy.util import components, handle_http_error\n\n\nclass France(BigFileSpider):\n \"\"\"\n Domain\n France\n Swagger API documentation\n https://doc.data.gouv.fr/api/reference/\n \"\"\"\n name = '...
false
9,452
956e63bf06255df4a36b5fa97aa62c0ed805c3f3
#!/bin/python from flask import Flask, jsonify, request import subprocess import os app = Flask(__name__) text = "" greetings = "'/play' and '/replay'\n" @app.route('/') def index(): return greetings @app.route('/play', methods=['POST']) def play(): global text text = request.data.decode('utf-8') o...
[ "#!/bin/python\nfrom flask import Flask, jsonify, request\nimport subprocess\nimport os\n\napp = Flask(__name__)\n\ntext = \"\"\ngreetings = \"'/play' and '/replay'\\n\"\n\n@app.route('/')\ndef index():\n return greetings\n\n@app.route('/play', methods=['POST'])\ndef play():\n global text\n text = request....
false
9,453
dd06847c3eb9af6e84f247f8f0dd03961d83688e
from battleship.board import Board from battleship.game import Game import string # Board row_num = list(string.ascii_lowercase[:10]) # A-J col_num = 10 board = Board(row_num, col_num) board.display_board() # Game guesses = 25 quit = 'q' game = Game(guesses, quit) game.take_shot("\nChoose a spot to fire at in enemy...
[ "from battleship.board import Board\nfrom battleship.game import Game\n\nimport string\n\n# Board\nrow_num = list(string.ascii_lowercase[:10]) # A-J\ncol_num = 10\nboard = Board(row_num, col_num) \nboard.display_board()\n\n# Game\nguesses = 25\nquit = 'q'\ngame = Game(guesses, quit)\ngame.take_shot(\"\\nChoose a sp...
false
9,454
356c817e254d8885beb447aa10759fff6a45ca25
from microbit import * import music while True: if button_a.is_pressed(): music.pitch(400,500)
[ "from microbit import *\n\nimport music\n\nwhile True:\n if button_a.is_pressed():\n music.pitch(400,500)\n", "from microbit import *\nimport music\nwhile True:\n if button_a.is_pressed():\n music.pitch(400, 500)\n", "<import token>\nwhile True:\n if button_a.is_pressed():\n music....
false
9,455
4569413c8ea985a010a1fea4835a5b368a23663a
#import bmm_mysql_connect # Import my connection module import csv import MySQLdb import os #bmm_mysql_connect.connect() # Connecting to mysql test database #mycur = conn.cursor() # Creating my cursor path = os.path.expanduser('~/Projects/bmm_private/login_test.txt') login = csv.reade...
[ "#import bmm_mysql_connect # Import my connection module\nimport csv \nimport MySQLdb \nimport os\n\n#bmm_mysql_connect.connect() # Connecting to mysql test database\n#mycur = conn.cursor() # Creating my cursor\n\npath = os.path.expanduser('~/Projects/bmm_private/login_test.txt')\nlogin...
true
9,456
fdef3e94bbeb29c25bf14e17cd1d013cf848bedc
# from magicbot import AutonomousStateMachine, timed_state, state # from components.drivetrain import Drivetrain, DrivetrainState # from components.intake import Intake # from fieldMeasurements import FieldMeasurements # class PushBotAuto(AutonomousStateMachine): # # this auto is intended to push other robots of...
[ "# from magicbot import AutonomousStateMachine, timed_state, state\n\n# from components.drivetrain import Drivetrain, DrivetrainState\n# from components.intake import Intake\n\n# from fieldMeasurements import FieldMeasurements\n\n# class PushBotAuto(AutonomousStateMachine):\n# # this auto is intended to push ot...
false
9,457
8050b757c20da7ad8dd3c12a30b523b752d6a3ff
friends = ["Vino", "Ammu", "Appu"] print(friends) print(friends[0]) # returns the last element in the list print(friends[-1]) # returns the second to last element in the list print(friends[-2])
[ "friends = [\"Vino\", \"Ammu\", \"Appu\"]\n\nprint(friends)\nprint(friends[0])\n\n# returns the last element in the list\nprint(friends[-1])\n# returns the second to last element in the list\nprint(friends[-2])", "friends = ['Vino', 'Ammu', 'Appu']\nprint(friends)\nprint(friends[0])\nprint(friends[-1])\nprint(fri...
false
9,458
937fd6aa7bd21258bd6e0f592d94a966519ef885
''' # AWS::Chatbot Construct Library AWS Chatbot is an AWS service that enables DevOps and software development teams to use Slack chat rooms to monitor and respond to operational events in their AWS Cloud. AWS Chatbot processes AWS service notifications from Amazon Simple Notification Service (Amazon SNS), and forwar...
[ "'''\n# AWS::Chatbot Construct Library\n\nAWS Chatbot is an AWS service that enables DevOps and software development teams to use Slack chat rooms to monitor and respond to operational events in their AWS Cloud. AWS Chatbot processes AWS service notifications from Amazon Simple Notification Service (Amazon SNS), an...
false
9,459
262d6722f4c158d0a41b22433792cdc35651d156
# coding=utf-8 """ Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example Given a binary tree as follow: 1 / \ 2 3 / \ 4 5 The maximum depth is 3. """ """ Definition of TreeNode: """ class ...
[ "# coding=utf-8\n\n\"\"\"\nGiven a binary tree, find its maximum depth.\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\nExample\nGiven a binary tree as follow:\n\n 1\n / \\ \n2 3\n / \\\n 4 5\nThe maximum depth is 3.\n\n\"\"\"\n\n\"\"\"\...
false
9,460
26289d88ac51ee359faa81ca70b01879d2b1f840
pairs = ['usdt', 'btc'] warn_msg = '** WARN ** ' info_msg = '** INFO **'
[ "pairs = ['usdt', 'btc']\nwarn_msg = '** WARN ** '\ninfo_msg = '** INFO **'\n\n\n\n", "pairs = ['usdt', 'btc']\nwarn_msg = '** WARN ** '\ninfo_msg = '** INFO **'\n", "<assignment token>\n" ]
false
9,461
2cd7d4fe87de66e85bc0d060e2eaa68be39eed02
from tasks import video_compress, video_upload if __name__ == '__main__': video_compress.apply_async(["a"],queue='high') video_compress.apply_async(["b"],queue='low') video_upload.apply_async(["c"], queue='low') video_upload.apply_async(["d"], queue='high')
[ "from tasks import video_compress, video_upload\nif __name__ == '__main__':\n video_compress.apply_async([\"a\"],queue='high')\n video_compress.apply_async([\"b\"],queue='low')\n video_upload.apply_async([\"c\"], queue='low')\n video_upload.apply_async([\"d\"], queue='high')\n", "from tasks import vid...
false
9,462
bec3d8546cd7d27f7da48f5658480cf17c36a255
import os import re import sys import traceback import readline from typing import NamedTuple, List from PyInquirer import prompt from pygments import highlight from pygments.formatters.terminal import TerminalFormatter from pygments.lexers.python import PythonLexer import argparse parser = argparse.ArgumentParser(d...
[ "import os\nimport re\nimport sys\nimport traceback\nimport readline\nfrom typing import NamedTuple, List\n\nfrom PyInquirer import prompt\nfrom pygments import highlight\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.lexers.python import PythonLexer\n\nimport argparse\n\nparser = argpar...
false
9,463
4c483636316dfa660f10b1aba900813bc3e95ebe
from django.http import HttpResponseRedirect from django.shortcuts import render __author__ = 'jhonjairoroa87' from rest_framework.views import APIView from rest_framework.response import Response from rest_framework_jsonp.renderers import JSONPRenderer from django.db import models from .form import NameForm def mu...
[ "from django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\n__author__ = 'jhonjairoroa87'\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework_jsonp.renderers import JSONPRenderer\nfrom django.db import models\nfrom .form import Nam...
false
9,464
e5abab3f718bbbd25dcfc49290383203d53248c3
import logging from exceptions.invalid_api_usage import InvalidAPIUsage from wgadget.endpoints.ep import EP class EPInfoLight(EP): NAME = 'info_light' URL = '/info' URL_ROUTE_PAR_PAYLOAD = '/' URL_ROUTE_PAR_URL = '/actuatorId/<actuatorId>' METHOD = 'GET' ATTR_ACTUATOR_ID = 'actuatorId' ...
[ "\nimport logging\nfrom exceptions.invalid_api_usage import InvalidAPIUsage\nfrom wgadget.endpoints.ep import EP\n\nclass EPInfoLight(EP):\n\n NAME = 'info_light'\n URL = '/info'\n\n URL_ROUTE_PAR_PAYLOAD = '/'\n URL_ROUTE_PAR_URL = '/actuatorId/<actuatorId>'\n\n METHOD = 'GET'\n\n ATTR_ACTUATOR_I...
false
9,465
c2b3594d25e2d1670d9b99e0d3484c680f59421f
import random import tqdm from keras.models import load_model from ModelUtil import precision, recall, f1 from tqdm import tqdm import cv2 as cv import numpy as np import os import pandas as pd from PIL import Image os.environ['CUDA_VISIBLE_DEVICES']='1' model_path = '/home/bo/Project/densenet.hdf5' train_img_path...
[ "\nimport random\nimport tqdm\nfrom keras.models import load_model\nfrom ModelUtil import precision, recall, f1\nfrom tqdm import tqdm\nimport cv2 as cv\nimport numpy as np\nimport os\nimport pandas as pd\nfrom PIL import Image\n\n\nos.environ['CUDA_VISIBLE_DEVICES']='1'\n\n\nmodel_path = '/home/bo/Project/densenet...
false
9,466
fedec397ac0346bad1790315b4f85fbb1a662a4e
import subprocess from dissamblerAbstract import disassemblerAbstract #lib/ZydisDisasm -64 /home/nislab2/Desktop/DissamblerEffect/metamorphic/00fe0c08024f7db771d6711787d890a3.exe class ZydisDisassembler(disassemblerAbstract): def diassemble(self,filename, bits='32bit'): """ Disassembly executa...
[ "import subprocess\nfrom dissamblerAbstract import disassemblerAbstract\n\n#lib/ZydisDisasm -64 /home/nislab2/Desktop/DissamblerEffect/metamorphic/00fe0c08024f7db771d6711787d890a3.exe\nclass ZydisDisassembler(disassemblerAbstract):\n\n def diassemble(self,filename, bits='32bit'):\n \"\"\"\n Dis...
false
9,467
caf83d35ce6e0bd4e92f3de3a32221705a529ec1
#!/usr/bin/env python3 # --------------------------------------------------- # SSHSploit Framework # --------------------------------------------------- # Copyright (C) <2020> <Entynetproject> # # This program is free soft...
[ "#!/usr/bin/env python3\n\n# ---------------------------------------------------\n# SSHSploit Framework \n# ---------------------------------------------------\n# Copyright (C) <2020> <Entynetproject> \n#\n# This program ...
false
9,468
fb53ea6a7184c0b06fb8a4cbfaf2145cc5c2e8e2
import hlp import pdb class Nnt(list): """ Generic layer of neural network """ def __init__(self): """ Initialize the neural network base object. """ self.tag = None def y(self, x): """ build sybolic expression of output {y} given input {x} t...
[ "import hlp\nimport pdb\n\nclass Nnt(list):\n \"\"\"\n Generic layer of neural network\n \"\"\"\n def __init__(self):\n \"\"\"\n Initialize the neural network base object.\n \"\"\"\n self.tag = None\n\n def y(self, x):\n \"\"\"\n build sybolic expression of o...
false
9,469
54276074d84e63e6418f8738bb7f910424f1c94d
import sys import os PROJ_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(PROJ_DIR)
[ "import sys\nimport os\n\nPROJ_DIR = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(PROJ_DIR)", "import sys\nimport os\nPROJ_DIR = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(PROJ_DIR)\n", "<import token>\nPROJ_DIR = os.path.dirname(os.path.dirname(__file__))\nsys.path.append(PROJ_D...
false
9,470
8173afbd82b8da04db4625ac686c0d052e65a21c
from PyQt4 import QtGui from PyQt4.QtCore import pyqtSignal, pyqtSlot, QObject, Qt from twisted.internet.defer import inlineCallbacks import numpy as np from connection import connection import pyqtgraph as pg from pyqtgraph.SignalProxy import SignalProxy import sys import time global harwareConfiguration class grap...
[ "from PyQt4 import QtGui\nfrom PyQt4.QtCore import pyqtSignal, pyqtSlot, QObject, Qt\nfrom twisted.internet.defer import inlineCallbacks\nimport numpy as np\nfrom connection import connection\nimport pyqtgraph as pg\nfrom pyqtgraph.SignalProxy import SignalProxy\nimport sys\nimport time\n\nglobal harwareConfigurati...
false
9,471
6b3f634f3f0108e678d44ef9c89150f9fd116f76
file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' request = drive_service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print "Download %d%%." % int(status.progress() * 100)
[ "file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'\nrequest = drive_service.files().get_media(fileId=file_id)\nfh = io.BytesIO()\ndownloader = MediaIoBaseDownload(fh, request)\ndone = False\nwhile done is False:\n status, done = downloader.next_chunk()\n print \"Download %d%%.\" % int(status.progress() * 100)\n" ]
true
9,472
210199ed217db0d7a05e280f20e33496c0795f06
from base64 import b64decode import time from lampost.context.resource import m_requires from lampost.datastore.dbo import KeyDBO from lampost.datastore.dbofield import DBOField from lampost.datastore.exceptions import DataError from lampost.model.player import Player from lampost.util.encrypt import make_hash, check_...
[ "from base64 import b64decode\nimport time\n\nfrom lampost.context.resource import m_requires\nfrom lampost.datastore.dbo import KeyDBO\nfrom lampost.datastore.dbofield import DBOField\nfrom lampost.datastore.exceptions import DataError\nfrom lampost.model.player import Player\nfrom lampost.util.encrypt import make...
false
9,473
4fba13d051a3aceb393a4473cdbf6d4fc684c7ac
fname = input('Enter the file name to open') fh = open(fname) lst1 = list() data = dict() for ln in fh : if ln.startswith("From"): if ln.startswith('From:'): continue else : word = ln.split() lst1.append(word[1]) for word in lst1: data[word] = dat...
[ "fname = input('Enter the file name to open')\r\nfh = open(fname)\r\nlst1 = list()\r\ndata = dict()\r\nfor ln in fh :\r\n if ln.startswith(\"From\"):\r\n if ln.startswith('From:'):\r\n continue\r\n else :\r\n word = ln.split()\r\n lst1.append(word[1])\r\nfor word i...
false
9,474
988e1f0631c434cbbb6d6e973792a65ebbd9405e
print(4 / 2, 4 / 3, 4 / 4) print(5 / 2, 5 / 3, 5 / 4) print(4 // 2, 4 // 3, 4 // 4) print(5 // 2, 5 // 3, 5 // 4) print(4.0 / 2, 4 / 3.0, 4.0 / float(4)) print(5.0 / 2, 5 / 3.0, 5.0 / float(4)) print(4.0 // 2, 4 // 3.0, 4.0 // float(4)) print(5.0 // 2, 5 // 3.0, 5.0 // float(4))
[ "print(4 / 2, 4 / 3, 4 / 4)\nprint(5 / 2, 5 / 3, 5 / 4)\nprint(4 // 2, 4 // 3, 4 // 4)\nprint(5 // 2, 5 // 3, 5 // 4)\nprint(4.0 / 2, 4 / 3.0, 4.0 / float(4))\nprint(5.0 / 2, 5 / 3.0, 5.0 / float(4))\nprint(4.0 // 2, 4 // 3.0, 4.0 // float(4))\nprint(5.0 // 2, 5 // 3.0, 5.0 // float(4))", "print(4 / 2, 4 / 3, 4 /...
false
9,475
8ae10aada79b0a687732e341d275eb3823ec0e4a
# Copyright 2021-2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
[ "# Copyright 2021-2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applica...
false
9,476
8a2fe83ab1adae7de94eb168290ce4843ab39fe1
import numpy import multiprocessing from functools import partial from textutil.text import read_file from textutil.util import B import mmap import tqdm class Growable(object): def __init__(self, capacity=1024, dtype=numpy.uint32, grow=2): self.grow = grow self.capacity=capacity self.dty...
[ "import numpy\nimport multiprocessing\nfrom functools import partial\nfrom textutil.text import read_file\nfrom textutil.util import B\nimport mmap\nimport tqdm\n\n\n\nclass Growable(object):\n def __init__(self, capacity=1024, dtype=numpy.uint32, grow=2):\n self.grow = grow\n self.capacity=capacit...
false
9,477
414cb9a173ac70ad9ad1fc540aec569321fd3f8b
#!/usr/bin/python # -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: text_type = unicode string_types = basestring, else: text_type = str string_types = str, def with_metaclass(meta, *bases): # This requires a bit of explanation: the basic idea is to make a dummy # met...
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport sys\n\nPY2 = sys.version_info[0] == 2\n\nif PY2:\n text_type = unicode\n string_types = basestring,\nelse:\n text_type = str\n string_types = str,\n\n\ndef with_metaclass(meta, *bases):\n # This requires a bit of explanation: the basic idea is to ma...
false
9,478
ff6dc347637a81c9f6a541775646b4901d719790
import math def sieve(limit): ans = [] a = [1] * limit a[0] = a[1] = 0 for i in range(2, limit): if a[i] == 0: continue ans.append(i) for j in range(i*i, limit, i): a[j] = 0; return ans is_square = lambda x: int(math.sqrt(x) + 1e-9) ** 2 == x N = 10...
[ "import math\n\ndef sieve(limit):\n ans = []\n a = [1] * limit\n a[0] = a[1] = 0\n for i in range(2, limit):\n if a[i] == 0:\n continue\n ans.append(i)\n for j in range(i*i, limit, i):\n a[j] = 0;\n return ans\n\nis_square = lambda x: int(math.sqrt(x) + 1e-9...
false
9,479
c076aed1bfff51f8edf5ab4ef029b7fa7ca2422c
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'meet.ui' # # Created by: PyQt5 UI code generator 5.8.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName...
[ "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'meet.ui'\n#\n# Created by: PyQt5 UI code generator 5.8.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\nclass Ui_Dialog(object):\n def setupUi(self, Dialog):\n Dia...
false
9,480
49ae9e90402d784fc3af3b47e96842fbfe842104
from utilities.MatplotlibUtility import * from utilities.PlotDefinitions.DrainSweep.OutputCurve import plot as importedOutputCurvePlot plotDescription = { 'name':'Chip Output Curves', 'plotCategory': 'chip', 'priority': 40, 'dataFileDependencies': ['DrainSweep.json'], 'plotDefaults': { 'figsize':(2,2.5), 'co...
[ "from utilities.MatplotlibUtility import *\nfrom utilities.PlotDefinitions.DrainSweep.OutputCurve import plot as importedOutputCurvePlot\n\n\nplotDescription = {\n\t'name':'Chip Output Curves',\n\t'plotCategory': 'chip',\n\t'priority': 40,\n\t'dataFileDependencies': ['DrainSweep.json'],\n\t'plotDefaults': {\n\t\t'f...
false
9,481
51b3beee8659bccee0fbb64b80fdce18b693674b
class Solution(object): def twoSum(self, numbers, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ idx1 = 0 idx2 = len(numbers)-1 while(idx1<idx2): # can also use a for-loop: for num in numbers: left = numbers[id...
[ "class Solution(object):\n def twoSum(self, numbers, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n idx1 = 0\n idx2 = len(numbers)-1\n while(idx1<idx2): # can also use a for-loop: for num in numbers: \n ...
false
9,482
f0b5ad49fc47adc54fb16a151b4a0ed563f53a42
from bottle import response,request,route,run from json import dumps import ConfigParser import pickle import pandas as pd import numpy as np from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.cross_...
[ "from bottle import response,request,route,run\nfrom json import dumps\nimport ConfigParser\nimport pickle\nimport pandas as pd\nimport numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom ...
true
9,483
87291d066b94aca1d94cbe5d9281fc72da1b0c35
import numpy as np from StudyCaseUdemy.Graph import Graph class OrderVector: def __init__(self, size): self.size = size self.last_pos = -1 self.values = np.empty(self.size, dtype=object) def insert(self, vertex): if self.last_pos == self.size - 1: print('Capacidad m...
[ "import numpy as np\nfrom StudyCaseUdemy.Graph import Graph\n\nclass OrderVector:\n def __init__(self, size):\n self.size = size\n self.last_pos = -1\n self.values = np.empty(self.size, dtype=object)\n\n def insert(self, vertex):\n if self.last_pos == self.size - 1:\n pr...
false
9,484
59170e6b0b0705b9908ed1c32bbea87373126594
#coding:utf-8 #base string opeate #rstrip()删除字符串末尾被指定的字符,默认是空格,如末尾有多个相同的字符,则一并删除 str1="djcc" str2="adcd" print("this's rstrip() function---------") print(str1.rstrip("c")) print(str1.rstrip("d")) #replace()用新字符替换字符串中被指定的字符,str.replace(old, new[, max]),max表示替换多少个,如不指定,全部替换 str3="this is history,it is not fake" prin...
[ "#coding:utf-8\n\n#base string opeate\n\n#rstrip()删除字符串末尾被指定的字符,默认是空格,如末尾有多个相同的字符,则一并删除\nstr1=\"djcc\"\nstr2=\"adcd\"\nprint(\"this's rstrip() function---------\")\nprint(str1.rstrip(\"c\"))\nprint(str1.rstrip(\"d\"))\n\n\n#replace()用新字符替换字符串中被指定的字符,str.replace(old, new[, max]),max表示替换多少个,如不指定,全部替换\n\nstr3=\"this i...
false
9,485
896d836ede533bad24f4077e5ba964105d96bf7a
list1=[('北京大洋路', '红蛋', '散框批发', '120-125', '44', '落', '8车'), ('北京回龙观', '红蛋', '散框批发', '124', '44', '落', ''), ('北京石门', '红蛋', '散框批发', '124', '44', '落', '') ] mysql_data=[] import numpy as np for l in list1: array = np.array(l) tolist = array.tolist() tolist.insert(0,'ppp') tolist.append('lll') mysql_dat...
[ "list1=[('北京大洋路', '红蛋', '散框批发', '120-125', '44', '落', '8车'), ('北京回龙观', '红蛋', '散框批发', '124', '44', '落', ''), ('北京石门', '红蛋', '散框批发', '124', '44', '落', '') ]\nmysql_data=[]\nimport numpy as np\nfor l in list1:\n array = np.array(l)\n tolist = array.tolist()\n tolist.insert(0,'ppp')\n tolist.append('lll')\n...
false
9,486
5dcb20f52b5041d5f9ea028b383e0f2f10104af9
from collections import deque s = list(input().upper()) new = list(set(s)) # 중복 제거 한 알파벳 리스트로 카운트 해줘야 시간초과 안남 n = {} for i in new: n[i] = s.count(i) cnt = deque() for k, v in n.items(): cnt.append(v) if cnt.count(max(cnt)) >1: print('?') else: print(max(n, key=n.get))
[ "from collections import deque\ns = list(input().upper())\nnew = list(set(s)) # 중복 제거 한 알파벳 리스트로 카운트 해줘야 시간초과 안남\nn = {}\nfor i in new:\n n[i] = s.count(i)\n\ncnt = deque()\nfor k, v in n.items():\n cnt.append(v)\n\nif cnt.count(max(cnt)) >1:\n print('?')\nelse:\n print(max(n, key=n.get))\n\n", "from ...
false
9,487
7618d7fde3774a04ac2005dad104e54b9988d3e8
def execute(n,dico): """ Prend en argument n, la position de la requête dans le dictionaire et dico le nom du dictionnaire. Renvoie une liste dont chaque élément est une réponse de la requête. """ l = [] import sqlite3 conn = sqlite3.connect('imdb.db') c = conn.cursor() c.execute(dic...
[ "def execute(n,dico):\n \"\"\"\n Prend en argument n, la position de la requête dans le dictionaire et dico le nom du dictionnaire.\n Renvoie une liste dont chaque élément est une réponse de la requête.\n \"\"\"\n l = []\n import sqlite3\n conn = sqlite3.connect('imdb.db')\n c = conn.cursor(...
false
9,488
570e0d46aa1ea88d1784447e8f693199e3c3b6ad
from __future__ import print_function from __future__ import absolute_import # # LinkedIn Sales Module # import requests from bs4 import BeautifulSoup import logging from plugins.base import PageGrabber from plugins.colors import BodyColors as bc import json try: import __builtin__ as bi except: import builtins...
[ "from __future__ import print_function\nfrom __future__ import absolute_import\n#\n# LinkedIn Sales Module\n#\nimport requests\nfrom bs4 import BeautifulSoup\nimport logging\nfrom plugins.base import PageGrabber\nfrom plugins.colors import BodyColors as bc\nimport json\ntry:\n import __builtin__ as bi\nexcept:\n...
false
9,489
67f09cd8b41c7a4fe457766dfed916aaf71cc20d
# -*- coding: utf-8 -*- """ Created on Thu Jul 27 18:34:40 2017 @author: Peiyong Jiang :jiangpeiyong@impcas.ac.cn Wangsheng Wang : wwshunan@impcas.ac.cn Chi Feng : fengchi@impcas.ac.cn supervised by Zhijun Wang & Yuan He """ import os from ...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 27 18:34:40 2017\r\n\r\n@author: Peiyong Jiang :jiangpeiyong@impcas.ac.cn\r\n Wangsheng Wang : wwshunan@impcas.ac.cn\r\n Chi Feng : fengchi@impcas.ac.cn\r\n \r\n supervised by\r\n Zhijun Wang & Yuan He\r\n\r\n ...
false
9,490
146487738006ce3efb5bd35c425835a1fd8e0145
# -*- coding: utf-8 -*- #some xml helpers from xml.dom.minidom import Document class XMLReport: def __init__(self, name): self.doc = Document() self.main_node = self.add(name, node=self.doc) def add(self, name, node=None): if node is None: node = self.main_node elem = self.doc.createElement(name) ...
[ "# -*- coding: utf-8 -*-\n#some xml helpers\nfrom xml.dom.minidom import Document\n\nclass XMLReport:\n def __init__(self, name):\n\tself.doc = Document()\n\tself.main_node = self.add(name, node=self.doc)\n \n def add(self, name, node=None):\n\tif node is None: node = self.main_node\n\telem = self.doc....
true
9,491
3bec28561c306a46c43dafc8bdc2e01f2ea06180
from mlagents_envs.registry import default_registry from mlagents_envs.envs.pettingzoo_env_factory import logger, PettingZooEnvFactory # Register each environment in default_registry as a PettingZooEnv for key in default_registry: env_name = key if key[0].isdigit(): env_name = key.replace("3", "Three")...
[ "from mlagents_envs.registry import default_registry\nfrom mlagents_envs.envs.pettingzoo_env_factory import logger, PettingZooEnvFactory\n\n# Register each environment in default_registry as a PettingZooEnv\nfor key in default_registry:\n env_name = key\n if key[0].isdigit():\n env_name = key.replace(\...
false
9,492
92dc0bd3cfcddd98f99d8152d0221f047beb4fb0
#! /usr/bin/python # -*- coding: utf8 -*- # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import unittest from pyama.filereader import FileReader,Segment class TestFileReader(unittest.TestCase): def test_reads_file(self): reader = FileReader( "sample_reader_test.txt", regexe...
[ "#! /usr/bin/python\n# -*- coding: utf8 -*-\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\nimport unittest\n\nfrom pyama.filereader import FileReader,Segment\n\n\nclass TestFileReader(unittest.TestCase):\n def test_reads_file(self):\n reader = FileReader(\n \"sample_reader_test.txt\",\...
false
9,493
f8a31cdf5f55b5aed33a407d2c008ba9b969d655
import cv2 import glob import numpy as np import csv import matplotlib.pyplot as plt from pydarknet import Detector,Image """ Calculates the average precision based on the precision and recall values, which are essentially the output of getPrecisionRecall Returns the 101pt interpolation curve and a single av...
[ "import cv2\r\nimport glob\r\nimport numpy as np\r\nimport csv\r\nimport matplotlib.pyplot as plt\r\nfrom pydarknet import Detector,Image\r\n\r\n\"\"\"\r\nCalculates the average precision based on the precision and recall values,\r\nwhich are essentially the output of getPrecisionRecall\r\nReturns the 101pt interpo...
false
9,494
9bb1fc4df80d183c70d70653faa3428964b93a94
from django.db import models class FoodCategory(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, default='') class Meta: db_table = 'kitchenrock_category' def __str__(self): return self.name
[ "from django.db import models\n\nclass FoodCategory(models.Model):\n id = models.AutoField(primary_key=True)\n name = models.CharField(max_length=200, default='')\n\n class Meta:\n db_table = 'kitchenrock_category'\n\n def __str__(self):\n return self.name", "from django.db import model...
false
9,495
f6d7ce2d020d11086640a34aac656098ab0b0f33
from datetime import date atual = date.today().year totmaior = 0 totmenor = 0 for pessoas in range (1, 8): nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: ')) idade = atual - nasc if idade >= 21: totmaior += 1 else: totmenor += 1 print(f'Ao todo tivemos {totmaior} pessoas mai...
[ "from datetime import date\natual = date.today().year\ntotmaior = 0\ntotmenor = 0\nfor pessoas in range (1, 8):\n nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: '))\n idade = atual - nasc\n if idade >= 21:\n totmaior += 1\n else:\n totmenor += 1\nprint(f'Ao todo tivemos {totma...
false
9,496
8a54a71b08d10c5da9ca440e8e4f61f908e00d54
A = input("입력해주세요.\n") #입력값을 in_AAA로 칭한다 #\n은 문법의 줄바꾸기 print(A.upper()+" World!") #in_AAA를 출력 + "World!") #upper()는 앞의 값을 대문자화+"
[ "A = input(\"입력해주세요.\\n\") #입력값을 in_AAA로 칭한다\r\n #\\n은 문법의 줄바꾸기\r\n\r\nprint(A.upper()+\" World!\") #in_AAA를 출력 + \"World!\")\r\n #upper()는 앞의 값을 대문자화+\"\r\n", "A = input('입력해주세요.\\n')\nprint(A.upper() + ' World!')\n", "<assignment to...
false
9,497
48755cf48c6696259d0c319d382021f33751ac01
def squirrel_play(temp, is_summer): if is_summer == True : if 60 <= temp <= 100 : return True else : return False if is_summer == False : if 60 <= temp <= 90 : return True else : return False
[ "def squirrel_play(temp, is_summer):\n\tif is_summer == True :\n\t\tif 60 <= temp <= 100 :\n\t\t\treturn True\n\t\telse : \n\t\t\treturn False\n\tif is_summer == False :\n\t\tif 60 <= temp <= 90 :\n\t\t\treturn True\n\t\telse :\n\t\t\treturn False", "def squirrel_play(temp, is_summer):\n if is_summer == True:\...
false
9,498
752679d2484b6b91a734c7cbe4a99bd5676661eb
import numpy as np def output(i, out): with open('B-large.out', 'a') as outfile: outfile.write("Case #{0}: {1}\n".format(i, out)) def solve(i, stack): cursymbol = stack[0] counter = 0 if stack[-1] == "+" else 1 for symbol in stack: if symbol != cursymbol: ...
[ "import numpy as np\r\n\r\ndef output(i, out):\r\n with open('B-large.out', 'a') as outfile:\r\n outfile.write(\"Case #{0}: {1}\\n\".format(i, out))\r\n\r\ndef solve(i, stack): \r\n cursymbol = stack[0]\r\n counter = 0 if stack[-1] == \"+\" else 1\r\n for symbol in stack:\r\n ...
false
9,499
f2d7f0b0d27bd43223d0eb6a6279b67968461dad
# binary search # iterative def Iter_BinarySearch(array,b,e,value): while(b<=e):#pay attention to the judgement! mid=(b+e)/2#floor if (array[mid]<value):#value in [mid,e] b=mid+1 elif (array[mid]>value):#value in [b,mid] e=mid-1 else: print "find ...
[ "# binary search\n\n# iterative\ndef Iter_BinarySearch(array,b,e,value):\n while(b<=e):#pay attention to the judgement!\n mid=(b+e)/2#floor\n if (array[mid]<value):#value in [mid,e]\n b=mid+1\n elif (array[mid]>value):#value in [b,mid]\n e=mid-1\n else:\n ...
true