index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
7,600
7a6a8b5e344a7b60e369f100885d1e26afa28f46
from django.apps import AppConfig class AppValidationsConfig(AppConfig): name = 'app_validations'
[ "from django.apps import AppConfig\n\n\nclass AppValidationsConfig(AppConfig):\n name = 'app_validations'\n", "<import token>\n\n\nclass AppValidationsConfig(AppConfig):\n name = 'app_validations'\n", "<import token>\n\n\nclass AppValidationsConfig(AppConfig):\n <assignment token>\n", "<import token>...
false
7,601
3a0bf031b76d2df03cdb5b37861cb8942307709c
import spacy nlp = spacy.load("en_core_web_lg") def find_entities(corpus): doc = nlp(corpus) entities = {} for ent in doc.ents: entity_type = ent.label_ entity_name = ent.text values = entities.get(entity_type, set()) values.add(entity_name) entities[entity_type]...
[ "import spacy\n\nnlp = spacy.load(\"en_core_web_lg\")\n\n\ndef find_entities(corpus):\n doc = nlp(corpus)\n entities = {}\n\n for ent in doc.ents:\n entity_type = ent.label_\n entity_name = ent.text\n\n values = entities.get(entity_type, set())\n values.add(entity_name)\n ...
false
7,602
74ffbd55867c4b2c6ccbef7d94e0c65aef139057
import os import pathlib from global_settings import * def get_bits(x): return np.where(x < 0, 0, 1) def check_wrong_bits(bits, bits_estimated): return len(np.argwhere(bits != bits_estimated)) def mkdir(file_path): folder = os.path.dirname(file_path) if not os.path.exists(folder): os.make...
[ "import os\nimport pathlib\n\nfrom global_settings import *\n\n\ndef get_bits(x):\n return np.where(x < 0, 0, 1)\n\n\ndef check_wrong_bits(bits, bits_estimated):\n return len(np.argwhere(bits != bits_estimated))\n\n\ndef mkdir(file_path):\n folder = os.path.dirname(file_path)\n if not os.path.exists(fol...
false
7,603
1c5884c10ac0b6a3335f8e677007fc52311245e2
# coding=utf-8 """Advent of Code 2018, Day 7""" import networkx import re G = networkx.DiGraph() with open("puzzle_input") as f: for line in f.read().split("\n"): match = re.search("Step (?P<pre>[A-Z]).*step (?P<post>[A-Z])", line) G.add_edge(match.group("pre"), match.group("post")) def part_one...
[ "# coding=utf-8\n\"\"\"Advent of Code 2018, Day 7\"\"\"\n\nimport networkx\nimport re\n\nG = networkx.DiGraph()\nwith open(\"puzzle_input\") as f:\n for line in f.read().split(\"\\n\"):\n match = re.search(\"Step (?P<pre>[A-Z]).*step (?P<post>[A-Z])\", line)\n G.add_edge(match.group(\"pre\"), match...
false
7,604
d4bc6bfe6bef730273db38f3c99352bbc3f48a5f
import os from celery import Celery import django from django.conf import settings from django.apps import apps os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings') #celery_app = Celery('nightcrawler.tasks.keep_it', broker=settings.CELERY_BROKER_URL) celery_app = Celery('nightcrawler', broker=sett...
[ "import os\nfrom celery import Celery\nimport django\nfrom django.conf import settings\nfrom django.apps import apps\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nightcrawler.settings')\n\n#celery_app = Celery('nightcrawler.tasks.keep_it', broker=settings.CELERY_BROKER_URL)\ncelery_app = Celery('nightcrawler...
false
7,605
e24a62f2a3ff0122922f472a7b37f1773dfe9c11
import tensorflow as tf from util.helper import focal_loss from util.helper import conv_elu_bn from util.helper import deconv_elu_bn from util.helper import residual_block_elu from util.helper import conv_elu from util.helper import conv from util.helper import reg_l1_loss from util.helper import conv_bn from util.hel...
[ "import tensorflow as tf\n\nfrom util.helper import focal_loss\nfrom util.helper import conv_elu_bn\nfrom util.helper import deconv_elu_bn\nfrom util.helper import residual_block_elu\nfrom util.helper import conv_elu\nfrom util.helper import conv\nfrom util.helper import reg_l1_loss\nfrom util.helper import conv_bn...
false
7,606
75754f4032d6e22e53cdbed0f6c640247473faec
import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.feature import ShapelyFeature from shapely.geometry import shape def plot(s): proj = ccrs.PlateCarree() ax = plt.axes(projection=proj) ax.set_extent((s.bounds[0], s.bounds[2], s.bounds[1], s.bounds[3]), crs=ccrs.PlateCarree()) sha...
[ "import matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nfrom cartopy.feature import ShapelyFeature\nfrom shapely.geometry import shape\n\n\ndef plot(s):\n proj = ccrs.PlateCarree()\n ax = plt.axes(projection=proj)\n ax.set_extent((s.bounds[0], s.bounds[2], s.bounds[1], s.bounds[3]), crs=ccrs.PlateCar...
false
7,607
cd1987f09ca3e09ac251b1ebdec4168fd5dbdd0e
# 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив, # заданный случайными числами на промежутке [0; 50). # Выведите на экран исходный и отсортированный массивы. from random import randint # создаем массив [0, 50) случайных чисел size = 13 array = [randint(0, 50) for x in range(s...
[ "# 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив,\r\n# заданный случайными числами на промежутке [0; 50).\r\n# Выведите на экран исходный и отсортированный массивы.\r\n\r\nfrom random import randint\r\n\r\n# создаем массив [0, 50) случайных чисел\r\n\r\nsize = 13\r\narray = [randint(...
false
7,608
517436d61ac9993bee5ecfd932f272dbb8bec60b
class Region: """ A region (represented by a list of long/lat coordinates). """ def __init__(self, coords, r_votes, d_votes, o_votes): self.coords = coords def lats(self): "Return a list of the latitudes of all the coordinates in the region" return [y for x,y in self.coords...
[ "class Region:\n \"\"\"\n A region (represented by a list of long/lat coordinates).\n \"\"\"\n\n def __init__(self, coords, r_votes, d_votes, o_votes):\n self.coords = coords\n\n def lats(self):\n \"Return a list of the latitudes of all the coordinates in the region\"\n return [y...
false
7,609
b7521a604fb49591df814d469f53d35574126fdb
import pandas def ludwig_get_model_definition(df: 'Dataframe', target: str, features: list): input_features, output_features = [], [] for p in features: if (pandas.api.types.is_numeric_dtype(df[p])): input_features.append({'name': p, 'type': 'numerical', 'preprocessing'...
[ "import pandas\n\ndef ludwig_get_model_definition(df: 'Dataframe', target: str, features: list):\n input_features, output_features = [], []\n for p in features:\n if (pandas.api.types.is_numeric_dtype(df[p])):\n input_features.append({'name': p, 'type': 'numerical', \n 'pr...
false
7,610
d03669924233edf33fcb6645f5ed7ab118f54a95
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Check mean system norm errors in regression tests This script determines the pass/fail status of a regression test by comparing the "Mean System Norm" values output at each timestep against "gold values" from the reference file provided by the user. Success is deter...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCheck mean system norm errors in regression tests\n\nThis script determines the pass/fail status of a regression test by comparing\nthe \"Mean System Norm\" values output at each timestep against \"gold values\"\nfrom the reference file provided by the use...
false
7,611
2540e2752edaedbf2a011a25cb90f220ae770757
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue May 19 17:27:57 2020 @author: li """ import numpy as np from opendr.renderer import ColoredRenderer from opendr.lighting import LambertianPointLight from opendr.camera import ProjectPoints import cPickle as pkl from models.smpl import Smpl, copy_smpl,...
[ "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 19 17:27:57 2020\n\n@author: li\n\"\"\"\n\nimport numpy as np\nfrom opendr.renderer import ColoredRenderer \nfrom opendr.lighting import LambertianPointLight\nfrom opendr.camera import ProjectPoints\nimport cPickle as pkl\nfrom models.smpl...
false
7,612
cb77696a90716acdee83a1cf6162a8f42c524e11
#!/usr/bin/env python3 import sys class Parse: data = [] def __parseLine(line): """Parse the given line""" # extract name name_len = line.index(" ") name = line[:name_len] line = line[name_len + 3:] # array-ize 'electron' val elec_pos = line.index("e...
[ "#!/usr/bin/env python3\n\nimport sys\n\n\nclass Parse:\n data = []\n\n def __parseLine(line):\n \"\"\"Parse the given line\"\"\"\n\n # extract name\n name_len = line.index(\" \")\n name = line[:name_len]\n line = line[name_len + 3:]\n\n # array-ize 'electron' val\n ...
false
7,613
dd7e8556405f07172ce2b1e9f486c2cd2f4bad58
# -*- coding: utf-8 -*- ''' Задание 12.3 Создать функцию print_ip_table, которая отображает таблицу доступных и недоступных IP-адресов. Функция ожидает как аргументы два списка: * список доступных IP-адресов * список недоступных IP-адресов Результат работы функции - вывод на стандартный поток вывода таблицы вида: ...
[ "# -*- coding: utf-8 -*-\n'''\nЗадание 12.3\n\n\nСоздать функцию print_ip_table, которая отображает таблицу доступных и недоступных IP-адресов.\n\nФункция ожидает как аргументы два списка:\n* список доступных IP-адресов\n* список недоступных IP-адресов\n\nРезультат работы функции - вывод на стандартный поток вывода...
false
7,614
77d545d1a4fc5f96ae19f654a32ab75707434d46
# encoding=utf-8 from lib.calculate_time import tic,toc import scipy as sp import numpy as np from lib.make_A import make_A from lib.make_distance import make_distance from lib.lambda_sum_smallest import lambda_sum_smallest from lib.fiedler import fiedler from lib.make_al import make_al import math from lib.newmatrix i...
[ "# encoding=utf-8\nfrom lib.calculate_time import tic,toc\nimport scipy as sp\nimport numpy as np\nfrom lib.make_A import make_A\nfrom lib.make_distance import make_distance\nfrom lib.lambda_sum_smallest import lambda_sum_smallest\nfrom lib.fiedler import fiedler\nfrom lib.make_al import make_al\nimport math\nfrom ...
true
7,615
6261d06ac7bdcb3ae25cd06338c4c41c3c5f5023
# import time module, Observer, FileSystemEventHandler import os import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import pyAesCrypt import logging logging.basicConfig(filename="Decryptor.log", level=logging.INFO, format="%(asctime)s:%(filename)s:...
[ "# import time module, Observer, FileSystemEventHandler\nimport os\nimport time\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nimport pyAesCrypt\nimport logging\nlogging.basicConfig(filename=\"Decryptor.log\",\n level=logging.INFO, format=\"%(asctime...
false
7,616
b57b6df1b7e551f64033a0c47e5a22eab9fd5fd4
import sys sys.path.append('.') import torch from torch.nn import functional as F import os import yaml from src.new_grad_cam import gc def test(conf): device = conf['device'] dataset = conf['test_dataset'] classes = conf['data']['classes'] weights_path = conf['weights_path'] results_dir = conf['r...
[ "import sys\nsys.path.append('.')\nimport torch\nfrom torch.nn import functional as F\nimport os\nimport yaml\nfrom src.new_grad_cam import gc\n\n\ndef test(conf):\n device = conf['device']\n dataset = conf['test_dataset']\n classes = conf['data']['classes']\n weights_path = conf['weights_path']\n re...
false
7,617
9da995184641525cd763ecdb0bca4f28159ae740
import datetime import os import uuid from abc import ABC, abstractmethod from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.contrib.contenttypes.fields import (GenericForeignKey, GenericRelation) from django.contrib.conten...
[ "import datetime\nimport os\nimport uuid\nfrom abc import ABC, abstractmethod\n\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.contenttypes.fields import (GenericForeignKey,\n GenericRelation)\nfrom django....
false
7,618
e79505e802a06f091bbb12708c45e04c4e80da60
import FWCore.ParameterSet.Config as cms from RecoTracker.MeasurementDet.UpdaterService_cfi import * from RecoTracker.MeasurementDet.MeasurementTrackerESProducer_cfi import *
[ "import FWCore.ParameterSet.Config as cms\n\nfrom RecoTracker.MeasurementDet.UpdaterService_cfi import *\nfrom RecoTracker.MeasurementDet.MeasurementTrackerESProducer_cfi import *\n\n", "import FWCore.ParameterSet.Config as cms\nfrom RecoTracker.MeasurementDet.UpdaterService_cfi import *\nfrom RecoTracker.Measure...
false
7,619
b5f88a6d119f2c3ce8fb77cf8c45b6c9252f5128
from pymongo import MongoClient class MongoDB(): def __init__(self, host, port, db, table): self.host = host self.port = port self.client = MongoClient(host=self.host, port=self.port) self.db = self.client[db] self.table = self.db[table] # 获取一条数据 def get_one(self, q...
[ "from pymongo import MongoClient\n\nclass MongoDB():\n def __init__(self, host, port, db, table):\n self.host = host\n self.port = port\n self.client = MongoClient(host=self.host, port=self.port)\n self.db = self.client[db]\n self.table = self.db[table]\n\n # 获取一条数据\n def...
false
7,620
9289eb32db145187c5b4140e32acff520be8366e
from models import Ban from django.shortcuts import render_to_response class IPBanMiddleware(object): """ Simple middleware for taking care of bans from specific IP's Redirects the banned user to a ban-page with an explanation """ def process_request(self, request): ip = request.META['REMOTE_ADDR'] # use...
[ "from models import Ban\nfrom django.shortcuts import render_to_response\n\nclass IPBanMiddleware(object):\n \"\"\"\n Simple middleware for taking care of bans from specific IP's\n Redirects the banned user to a ban-page with an explanation\n \"\"\"\n def process_request(self, request):\n ip = request.META[...
false
7,621
70964ac617847dd4bf4a60a142afc94d0f284a24
#!/usr/bin/env python # coding: utf-8 # # Lesson 2 Demo 3: Creating Fact and Dimension Tables with Star Schema # # <img src="images/postgresSQLlogo.png" width="250" height="250"> # ### Walk through the basics of modeling data using Fact and Dimension tables. In this demo, we will:<br> # <ol><li>Create both Fact and...
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# # Lesson 2 Demo 3: Creating Fact and Dimension Tables with Star Schema\n# \n# <img src=\"images/postgresSQLlogo.png\" width=\"250\" height=\"250\">\n\n# ### Walk through the basics of modeling data using Fact and Dimension tables. In this demo, we will:<br>\n# <ol><li>C...
false
7,622
4cefaa964251e77a05066af1f61f9fd2a4350d38
#!/usr/bin/env python import sys,re print('\n'.join(re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',sys.stdin.read())))
[ "#!/usr/bin/env python\nimport sys,re\nprint('\\n'.join(re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',sys.stdin.read())))\n", "import sys, re\nprint('\\n'.join(re.findall(\n 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\\\(\\\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n...
false
7,623
fa566eb77b17830acad8c7bfc2b958760d982925
from django.db import models # from rest_framework import permissions from drawAppBackend import settings # from django.contrib.auth.models import AbstractUser # Create your models here. class DrawApp(models.Model): title = models.CharField(max_length=120) description = models.TextField() completed = mo...
[ "from django.db import models\n# from rest_framework import permissions\nfrom drawAppBackend import settings\n\n# from django.contrib.auth.models import AbstractUser\n\n# Create your models here.\n\n\nclass DrawApp(models.Model):\n title = models.CharField(max_length=120)\n description = models.TextField()\n ...
false
7,624
f0e4cd13571728d61566c4093586c91323629e0b
# coding: utf-8 import numpy as np def sparse(n, k): u""" return k sparse vector, the value of non-zero entries are normal distributed N(0,1). [args] n: size of vector k: number of nonzero entries [return] k-sparse vector """ z = np.zeros(n) for i in np.r...
[ "# coding: utf-8\nimport numpy as np\n\n\n\ndef sparse(n, k):\n u\"\"\"\n return k sparse vector, \n the value of non-zero entries are \n normal distributed N(0,1).\n [args]\n n: size of vector\n k: number of nonzero entries\n [return]\n k-sparse vector\n \"\"\"\n z = np...
true
7,625
7d873ed216355d1688ec79ff337304d8ebfd2754
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: ''' ans = set() n = len(nums) for x, val in enumerate(nums): for y in range(x + 1, n + 1): ans.add(frozenset(nums[x:y])) for u in range(0, x + 1): fo...
[ "class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n '''\n ans = set()\n n = len(nums)\n for x, val in enumerate(nums):\n for y in range(x + 1, n + 1):\n ans.add(frozenset(nums[x:y]))\n for u in range(0, x + 1):\n ...
false
7,626
9c60d82d42716abb036dc7297a2dca66f0508984
import os import numpy as np import torch from torch import nn from torch.nn import functional as F import torch.utils.data as td import torchvision as tv import pandas as pd from PIL import Image from matplotlib import pyplot as plt from utils import imshow, NNRegressor class DnCNN(NNRegressor): def __init__(se...
[ "import os\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nimport torch.utils.data as td\nimport torchvision as tv\nimport pandas as pd\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom utils import imshow, NNRegressor\n\n\nclass DnCNN(NNRegressor):\n\...
false
7,627
991b124d365443744c946b258504c97e9076dcea
from django.urls import path, include from django.conf.urls import url, re_path #from rest_framework.urlpatterns import format_suffix_patterns from .views import (HomePageView, WordViewSet, WordNormalViewSet, TextViewSet, TextNormalViewSet, TextTagViewSet, TagSetViewSet, TagViewSet...
[ "from django.urls import path, include\nfrom django.conf.urls import url, re_path\n#from rest_framework.urlpatterns import format_suffix_patterns\nfrom .views import (HomePageView, \n WordViewSet, WordNormalViewSet,\n TextViewSet, TextNormalViewSet, TextTagViewSet, \n TagSetViewSet,...
false
7,628
98a1fab8cee91f37ceee2cfd868d3a5756a055b0
import numpy as np from sklearn.naive_bayes import BernoulliNB X = np.array([[1, 2, 3, 3], [1, 3, 4, 4], [2, 4, 5, 5]]) y = np.array([1, 2, 3]) """ alpha: 平滑系数 binarize: 将特征二值化的阈值 fit_prior: 使用数据拟合先验概率 """ clf = BernoulliNB(alpha=2.0, binarize=3.0, fit_prior=True) clf.fit(X, y) print("class_prior:", clf.class_prior) ...
[ "import numpy as np\n\nfrom sklearn.naive_bayes import BernoulliNB\n\nX = np.array([[1, 2, 3, 3], [1, 3, 4, 4], [2, 4, 5, 5]])\ny = np.array([1, 2, 3])\n\"\"\"\nalpha: 平滑系数\nbinarize: 将特征二值化的阈值\nfit_prior: 使用数据拟合先验概率\n\"\"\"\nclf = BernoulliNB(alpha=2.0, binarize=3.0, fit_prior=True)\nclf.fit(X, y)\nprint(\"class_p...
false
7,629
fd4d785d933c3a200f4aba094ecfe1e1c76737a5
from django.apps import AppConfig class Sharem8Config(AppConfig): name = 'ShareM8'
[ "from django.apps import AppConfig\n\n\nclass Sharem8Config(AppConfig):\n name = 'ShareM8'\n", "<import token>\n\n\nclass Sharem8Config(AppConfig):\n name = 'ShareM8'\n", "<import token>\n\n\nclass Sharem8Config(AppConfig):\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
7,630
235623c3f557dbc28fbff855a618e4d26932ca65
from . import cli cli.run()
[ "from . import cli\n\ncli.run()\n", "from . import cli\ncli.run()\n", "<import token>\ncli.run()\n", "<import token>\n<code token>\n" ]
false
7,631
06627821c09d02543974a3c90664e84e11c980ed
"""PriceTrail URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
[ "\"\"\"PriceTrail URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, nam...
false
7,632
f1d813ccaf49c8941bf594e22d8683c0ab422a22
from flask import Flask from flask_bcrypt import Bcrypt from flask_jwt_extended import JWTManager from flask_migrate import Migrate from flask_restful import Api from flask_apispec.extension import FlaskApiSpec from server.admin import add_admin from server.config import Config from server.db import db from server.cli...
[ "from flask import Flask\nfrom flask_bcrypt import Bcrypt\nfrom flask_jwt_extended import JWTManager\nfrom flask_migrate import Migrate\nfrom flask_restful import Api\nfrom flask_apispec.extension import FlaskApiSpec\n\nfrom server.admin import add_admin\nfrom server.config import Config\nfrom server.db import db\n...
false
7,633
0677e12bc9733c76bff7ed3fe83e3800e64e9a10
import re import requests import numpy as np import json import os from collections import OrderedDict import pandas as pd import json import datetime import time #将数组写入json文件方便pandas的读取 def write_list_to_json(list, json_file_name, json_file_save_path): os.chdir(json_file_save_path) with open(json_file_name, 'w...
[ "import re\nimport requests\nimport numpy as np\nimport json\nimport os\nfrom collections import OrderedDict\nimport pandas as pd\nimport json\nimport datetime\nimport time\n#将数组写入json文件方便pandas的读取\ndef write_list_to_json(list, json_file_name, json_file_save_path):\n os.chdir(json_file_save_path)\n with open(...
false
7,634
5807d1c2318ffa19d237d77fbe3f4c1d51da8601
import numpy as np import matplotlib.pyplot as plt from sklearn import mixture, metrics import utils import spsa_clustering N = 5000 mix_prob = np.array([0.4, 0.4, 0.2]) clust_means = np.array([[0, 0], [2, 2], [-3, 6]]) clust_gammas = np.array([[[1, -0.7], [-0.7, 1]], np.eye(2), [[1, 0.8], [0.8, 1]]]) data_set = [] t...
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import mixture, metrics\nimport utils\nimport spsa_clustering\n\n\nN = 5000\nmix_prob = np.array([0.4, 0.4, 0.2])\nclust_means = np.array([[0, 0], [2, 2], [-3, 6]])\nclust_gammas = np.array([[[1, -0.7], [-0.7, 1]], np.eye(2), [[1, 0.8], [0.8, 1]]])\...
false
7,635
2f7be68f08716d5d04d064d81eecb53eb9b80174
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-03 14:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('productores', '0002_auto_20170327_0841'), ] operations = [ migrations.AddFi...
[ "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-03 14:45\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('productores', '0002_auto_20170327_0841'),\n ]\n\n operations = [\n ...
false
7,636
44d1412d48886eb9126a895d61004e6ccbd4850b
#!/usr/bin/env python import sys import random def apply(mine, target, diff): if mine == [1, 1, 1, 1] or target == [1, 1, 1, 1]: return -1 if diff < 0: for i in range(0, 4): if i - diff < 4: mine[i] = mine[i - diff] else: mine[i] = 0 elif diff > 0: for i in range(3, -1, -1): if i - diff > -1...
[ "#!/usr/bin/env python\nimport sys\nimport random\n\ndef apply(mine, target, diff):\n\tif mine == [1, 1, 1, 1] or target == [1, 1, 1, 1]:\n\t\treturn -1\n\n\tif diff < 0:\n\t\tfor i in range(0, 4):\n\t\t\tif i - diff < 4:\n\t\t\t\tmine[i] = mine[i - diff]\n\t\t\telse:\n\t\t\t\tmine[i] = 0\n\telif diff > 0:\n\t\tfor...
true
7,637
069d85370d8358aa884b5195a1b52c0014efd161
from collections import Counter class Solution: def minDominoRotations(self, A: List[int], B: List[int]) -> int: if not A or not B: return 0 if len(A) != len(B): return -1 cnt_a, cnt_b = Counter(A), Counter(B) check_list = [] for num, freq in cnt_a.ite...
[ "from collections import Counter\nclass Solution:\n def minDominoRotations(self, A: List[int], B: List[int]) -> int:\n if not A or not B:\n return 0\n if len(A) != len(B):\n return -1\n cnt_a, cnt_b = Counter(A), Counter(B)\n check_list = []\n for num, fre...
false
7,638
45658cdfcd1529bbf803294cd7cec32d6d2c2198
import pygame class DrawingBrush(): def __init__(self, size, color, radius): self.drawSurface = pygame.Surface(size, pygame.SRCALPHA, 32).convert_alpha() self.drawColor = color self.size = radius self.winSize = size self.winSurface = pygame.display.get_surface() def Dra...
[ "import pygame\n\nclass DrawingBrush():\n def __init__(self, size, color, radius):\n self.drawSurface = pygame.Surface(size, pygame.SRCALPHA, 32).convert_alpha()\n self.drawColor = color\n self.size = radius\n self.winSize = size\n self.winSurface = pygame.display.get_surface()...
false
7,639
bf160bd2fc924a11d340bd466b4a879d1cdcd86e
# Generated by Django 3.1.7 on 2021-03-20 14:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('restapp', '0021_auto_20210320_1421'), ] operations = [ migrations.AddField( model_name='order', name='phone', ...
[ "# Generated by Django 3.1.7 on 2021-03-20 14:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('restapp', '0021_auto_20210320_1421'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='order',\n n...
false
7,640
5f022b7f20b8aef1e3538a6b1e69dc302752cdc7
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import re import sys import time import os # directory 현재 경로에 download폴더 생성 dirPath = "download" try: if not (os.path.isdi...
[ "from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport re\nimport sys\nimport time\nimport os\n\n# directory 현재 경로에 download폴더 생성\ndirPath = \"download\"\ntry:\n\t...
false
7,641
c12d45644098aef5c042a62095eeae5829d70f45
#! /usr/bin/python # encode:utf-8 import subprocess import sys import pdb argvs = sys.argv if len(argvs) != 2: print "Please input 1 argument" quit() searchWord = argvs[1] cmd1 = "ls -a /etc/" p1 = subprocess.Popen(cmd1.strip().split(" "), stdout=subprocess.PIPE) stdout_data, stderr_data = p1.communicate() p1.st...
[ "#! /usr/bin/python\n# encode:utf-8\nimport subprocess\nimport sys\nimport pdb\n\nargvs = sys.argv\nif len(argvs) != 2:\n print \"Please input 1 argument\"\n quit()\n\nsearchWord = argvs[1]\n\ncmd1 = \"ls -a /etc/\"\np1 = subprocess.Popen(cmd1.strip().split(\" \"), stdout=subprocess.PIPE)\nstdout_data, stderr_dat...
true
7,642
ce9e1ac0f1596ba4db904289f91f5ab95c2de4b8
from django.shortcuts import render,redirect from django.http import HttpResponseRedirect from . import forms,models from django.contrib.auth.models import Group from django.contrib import auth from django.contrib.auth.decorators import login_required,user_passes_test from datetime import datetime,timedelta,date from d...
[ "from django.shortcuts import render,redirect\nfrom django.http import HttpResponseRedirect\nfrom . import forms,models\nfrom django.contrib.auth.models import Group\nfrom django.contrib import auth\nfrom django.contrib.auth.decorators import login_required,user_passes_test\nfrom datetime import datetime,timedelta,...
false
7,643
c6d9b971ab6919846807b740313d450d086ecc23
import VL53L1X from sensor_msgs.msg import Range class _VL53L1(): def __init__(self, address=0x29): address = int(address, 16) print("initialising sensor with address: {}".format(hex(address))) try: self.tof = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=address) ...
[ "import VL53L1X\n\nfrom sensor_msgs.msg import Range\n\nclass _VL53L1():\n\n def __init__(self, address=0x29):\n address = int(address, 16)\n print(\"initialising sensor with address: {}\".format(hex(address)))\n \n try:\n self.tof = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=a...
false
7,644
6aa762165dba891a3638d13862019dd342a7e05a
# Generated by Django 3.0.1 on 2020-01-11 19:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0004_auto_20191230_2037'), ] operations = [ migrations.AddField( model_name='user', name='cir...
[ "# Generated by Django 3.0.1 on 2020-01-11 19:59\r\n\r\nfrom django.db import migrations, models\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('users', '0004_auto_20191230_2037'),\r\n ]\r\n\r\n operations = [\r\n migrations.AddField(\r\n model_name...
false
7,645
c22651437094723b711a959e031f1c7f928f735a
data = [ "........#.............#........", "...#....#...#....#.............", ".#..#...#............#.....#..#", "..#......#..##............###..", "..........#......#..#..#.......", ".#..#.......#.........#.#......", ".........#..#....##..#.##....#.", "..#....##...#..................",...
[ "data = [\n \"........#.............#........\",\n \"...#....#...#....#.............\",\n \".#..#...#............#.....#..#\",\n \"..#......#..##............###..\",\n \"..........#......#..#..#.......\",\n \".#..#.......#.........#.#......\",\n \".........#..#....##..#.##....#.\",\n \"..#.....
false
7,646
94a0b341aac3683712578b31e98a0a5a6a643b57
# Pass Function def hello_func(): pass hello_func() print(hello_func()) def hello_func(): hello_func() print(hello_func) # Function allows to reuse ,without repeat def hello_func(): print('hello function!') hello_func()
[ "# Pass Function\n\ndef hello_func():\n pass\n\n\nhello_func()\nprint(hello_func())\n\n\ndef hello_func():\n hello_func()\n\n\nprint(hello_func)\n\n# Function allows to reuse ,without repeat\n\n\ndef hello_func():\n print('hello function!')\n hello_func()\n", "def hello_func():\n pass\n\n\nhello_fu...
false
7,647
9a02e09cbfe2c9b6ebb9d20ba6cea639871f0838
import datetime import discord def getTeams(reign, uprising, hunters, fuel, mayhem, gladiators, charge, outlaws, spark, spitfire, excelsior, eternal, fusion, dynasty, shock, dragons, defiant, valiant, titans, justice) : teamList = discord.Embed( title="Overwatch League Teams", description="2021 Sea...
[ "import datetime\nimport discord\n\ndef getTeams(reign, uprising, hunters, fuel, mayhem, gladiators, charge, outlaws, spark,\nspitfire, excelsior, eternal, fusion, dynasty, shock, dragons, defiant, valiant, titans,\njustice) :\n teamList = discord.Embed(\n title=\"Overwatch League Teams\",\n descri...
false
7,648
547935a67fb079e551534126534234ceb96ed0dd
# Generated by Django 2.0.13 on 2019-05-23 14:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0001_initial'), ('users', '0003_user_projects'), ] operations = [ migrations.RemoveField( model_name='user'...
[ "# Generated by Django 2.0.13 on 2019-05-23 14:12\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('projects', '0001_initial'),\n ('users', '0003_user_projects'),\n ]\n\n operations = [\n migrations.RemoveField(\n ...
false
7,649
dbd04f7b88fa43ae920a6744e3979dbf917d3fc6
import requests import toml from pathlib import Path imgs:list config:dict def parseTex(lines:list): new_lines = [] for i, line in enumerate(lines): if line == "\n": continue inline = False if (line[0] == "$" and line[1] != "$"): inline = True line = li...
[ "import requests\nimport toml\nfrom pathlib import Path\n\nimgs:list\nconfig:dict\n\ndef parseTex(lines:list):\n new_lines = []\n for i, line in enumerate(lines):\n if line == \"\\n\":\n continue\n\n inline = False\n if (line[0] == \"$\" and line[1] != \"$\"):\n inli...
false
7,650
a1ea0f269a20ff608d10ee01804eeee7e7232b1d
# -*- coding: utf-8 -*- ## https://atcoder.jp/contests/abs/tasks/abc083_b import sys def gets(input): return input.readline().strip() def run(input): n, a, b = gets(input).split() N, A, B = int(n), int(a), int(b) # total = 0 for i in range(1, N+1): x = sum( int(ch) for ch in str(i) )...
[ "# -*- coding: utf-8 -*-\n\n## https://atcoder.jp/contests/abs/tasks/abc083_b\n\nimport sys\n\ndef gets(input):\n return input.readline().strip()\n\ndef run(input):\n n, a, b = gets(input).split()\n N, A, B = int(n), int(a), int(b)\n #\n total = 0\n for i in range(1, N+1):\n x = sum( int(ch...
false
7,651
e4a05cbfd0959402eacf21959c68e449d15b1e74
#!/usr/bin/env python3 # # Exploit for "assignment" of GoogleCTF 2017 # # CTF-quality exploit... # # Slightly simplified and shortened explanation: # # The bug is a UAF of one or both values during add_assign() if a GC is # triggered during allocate_value(). The exploit first abuses this to leak a # pointer into the he...
[ "#!/usr/bin/env python3\n#\n# Exploit for \"assignment\" of GoogleCTF 2017\n#\n# CTF-quality exploit...\n#\n# Slightly simplified and shortened explanation:\n#\n# The bug is a UAF of one or both values during add_assign() if a GC is\n# triggered during allocate_value(). The exploit first abuses this to leak a\n# po...
false
7,652
a6f242a0443ffbad835f86098b70ede41c03515b
import aiohttp import asyncio import base64 import discord import json from discord.ext import commands class BasicMC(commands.Cog): def __init__(self, bot): self.bot = bot self.session = aiohttp.ClientSession() @commands.command(name="stealskin", aliases=["skinsteal", "skin"]) @command...
[ "import aiohttp\nimport asyncio\nimport base64\nimport discord\nimport json\nfrom discord.ext import commands\n\n\nclass BasicMC(commands.Cog):\n\n def __init__(self, bot):\n self.bot = bot\n\n self.session = aiohttp.ClientSession()\n\n @commands.command(name=\"stealskin\", aliases=[\"skinsteal\...
false
7,653
825c9510b055c0fa570f577b1c9616e8bde9c98b
from django.test import TestCase from .models import Post, Category, Tag # Create your tests here. class TestPost(TestCase): def test_str(self): my_title = Post(title='This is a basic title for a basic test case') self.assertEquals(str(my_title), 'This is a basic title for a basic test case') c...
[ "from django.test import TestCase\n\nfrom .models import Post, Category, Tag\n\n# Create your tests here.\n\nclass TestPost(TestCase):\n\n def test_str(self):\n my_title = Post(title='This is a basic title for a basic test case')\n self.assertEquals(str(my_title), 'This is a basic title for a basic...
false
7,654
37c42a5e52832c81660e88f45d93e6a9f0300de0
class Node: def __init__(self, char = None): self.char = char self.children = [] self.end = False root = Node('*') curr = root # recursive insert into the trie def insert(s, curr): if curr.children and curr.children[0].char == s[0]: curr = curr.children[0] elif len(curr.chi...
[ "class Node:\n def __init__(self, char = None):\n self.char = char\n self.children = []\n self.end = False\n\nroot = Node('*')\ncurr = root\n\n# recursive insert into the trie\ndef insert(s, curr):\n if curr.children and curr.children[0].char == s[0]:\n curr = curr.children[0]\n ...
false
7,655
c8975306473dda49be6c5f19f6663214ec7e7105
import numpy as np import cPickle as pkl data_l = [] data_path = "/home/marc/data/" with open(data_path+'covtype.data') as fp: for line in fp: tmp_l = [ int(elem) for elem in line.split(',') ] data_l.append(tmp_l) data = np.array(data_l) np.random.shuffle(data) quintil = data.shape[0]/5 train_x = data[:qu...
[ "import numpy as np\nimport cPickle as pkl\n\n\n\ndata_l = []\ndata_path = \"/home/marc/data/\"\nwith open(data_path+'covtype.data') as fp:\n for line in fp:\n\t\ttmp_l = [ int(elem) for elem in line.split(',') ]\n\t\tdata_l.append(tmp_l)\n\n\ndata = np.array(data_l)\nnp.random.shuffle(data)\n\nquintil = data.sh...
true
7,656
c6ce6ffe46be993bfe74ccb240e1ebf586c9f556
import numpy as np from math import sqrt import warnings from collections import Counter import pandas as pd import random def k_NN(data, predict, k=3): if len(data) >= k: warnings.warn("K is set to a value less than total voting groups !") distances = [] [[ distances.append([np.linalg.norm(np.array(features) - ...
[ "import numpy as np\nfrom math import sqrt\nimport warnings\nfrom collections import Counter\nimport pandas as pd\nimport random\n\ndef k_NN(data, predict, k=3):\n\tif len(data) >= k:\n\t\twarnings.warn(\"K is set to a value less than total voting groups !\")\n\n\tdistances = []\n\t[[ distances.append([np.linalg.no...
false
7,657
d287a5128ca9352b2edc459c9e42a57ef800ec9c
#!/usr/bin/python import sys def get_params(fname): d = dict() with open(fname) as f: for line in f: l = line.strip() if (line[0] == '#'): continue param = line.split('=') v = ' '.join(param[1:]) d[param[0]] = v.strip('\n') return d usage_text = "Compares boot configs of two kernels\n" \ "U...
[ "#!/usr/bin/python\n\nimport sys\n\ndef get_params(fname):\n\td = dict()\n\twith open(fname) as f:\n\t\tfor line in f:\n\t\t\tl = line.strip()\n\t\t\tif (line[0] == '#'):\n\t\t\t\tcontinue\n\t\t\tparam = line.split('=')\n\t\t\tv = ' '.join(param[1:])\n\t\t\td[param[0]] = v.strip('\\n') \n\treturn d\n\nusage_text = ...
true
7,658
2b3a7d0c28d1bf7d4400b0e5558b0527a96af781
import sys import math from random import randrange from utilities import * from EffectiveThueLemma import * def getZ(value): s = str(value) p10 = 1 if s[0] != '0': p10 = 10 for i in range(1, len(s)): if s[i] == '.': break p10 *= 10 z = [] first = int(s[0] == '0') for i in range(first, len(s)): if s...
[ "import sys\nimport math\nfrom random import randrange\nfrom utilities import *\nfrom EffectiveThueLemma import *\n\n\ndef getZ(value):\n\ts = str(value)\n\tp10 = 1\n\tif s[0] != '0':\n\t\tp10 = 10\n\tfor i in range(1, len(s)):\n\t\tif s[i] == '.':\n\t\t\tbreak\n\t\tp10 *= 10\n\tz = []\n\tfirst = int(s[0] == '0')\n...
false
7,659
1cf4fc37e030a895cb36f537ce9e92df34acfb8b
""" Counted List Create a class for an list like object based on UserList wrapper https://docs.python.org/3/library/collections.html#collections.UserList That object should have a method to return a Counter https://docs.python.org/3/library/collections.html#collections.Counter for all objects in the list Counter should...
[ "\"\"\"\nCounted List\nCreate a class for an list like object based on UserList wrapper\nhttps://docs.python.org/3/library/collections.html#collections.UserList\nThat object should have a method to return a Counter\nhttps://docs.python.org/3/library/collections.html#collections.Counter\nfor all objects in the list\...
false
7,660
62bad8eeb3b51a5012dad761a60639d36429d8e8
import pymysql from app_module.models import User, Vehicle, Address, Customer, Location, Coupon, VehicleClass, Corporation, Corporate from datetime import datetime HOSTNAME = 'localhost' USERNAME = 'root' PASSWORD = '123456' DATABASE = 'proj_p2' def get_connection(): my_sql_connection = pymysql.connect(host=HOST...
[ "import pymysql\nfrom app_module.models import User, Vehicle, Address, Customer, Location, Coupon, VehicleClass, Corporation, Corporate\nfrom datetime import datetime\n\nHOSTNAME = 'localhost'\nUSERNAME = 'root'\nPASSWORD = '123456'\nDATABASE = 'proj_p2'\n\n\ndef get_connection():\n my_sql_connection = pymysql.c...
false
7,661
1803f634c8e833f4a92ae35bcfafb04dfd1d2305
#!/usr/bin/env python import sys def solve(n, k): wrap = 2 ** n snaps_that_matter = k % wrap return snaps_that_matter == wrap - 1 def main(): lines = sys.stdin.readlines() T = int(lines[0]) for i, line in enumerate(lines[1:]): N, K = line.split(' ') on = solve(int(N), int...
[ "#!/usr/bin/env python\n\nimport sys\n\ndef solve(n, k):\n wrap = 2 ** n\n snaps_that_matter = k % wrap\n return snaps_that_matter == wrap - 1\n\ndef main():\n lines = sys.stdin.readlines()\n T = int(lines[0])\n \n for i, line in enumerate(lines[1:]):\n N, K = line.split(' ')\n on...
true
7,662
299b437c007d78c3d9a53205de96f04d2c6118e0
# -*- coding: utf-8 -*- """ Created on Mon Sep 11 07:41:34 2017 @author: Gabriel """ months = 12 balance = 4773 annualInterestRate = 0.2 monthlyPaymentRate = 434.9 monthlyInterestRate = annualInterestRate / 12 while months > 0: minimumMonPayment = monthlyPaymentRate * balance monthlyUnpaidBa...
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 11 07:41:34 2017\r\n\r\n@author: Gabriel\r\n\"\"\"\r\n\r\nmonths = 12\r\nbalance = 4773\r\nannualInterestRate = 0.2\r\nmonthlyPaymentRate = 434.9\r\nmonthlyInterestRate = annualInterestRate / 12\r\n\r\nwhile months > 0:\r\n minimumMonPayment = monthlyPay...
false
7,663
632c690261b31c7ac0e1d90c814e3b9a7a0dcb29
# # @lc app=leetcode.cn id=784 lang=python3 # # [784] 字母大小写全排列 # # @lc code=start # 回溯法 --> 通过 64 ms 13.5 MB class Solution: def __init__(self): self.result = [] def letterCasePermutation(self, S: str) -> List[str]: arr = list(S) self.backtracing(arr, 0) return self.result ...
[ "#\n# @lc app=leetcode.cn id=784 lang=python3\n#\n# [784] 字母大小写全排列\n#\n\n# @lc code=start\n# 回溯法 --> 通过 64 ms 13.5 MB\nclass Solution:\n def __init__(self):\n self.result = []\n\n def letterCasePermutation(self, S: str) -> List[str]:\n arr = list(S)\n self.backtracing(arr, 0)\n ret...
false
7,664
214585956e44ce006db0702fd23692b11459f9e1
from five import grok from zope.formlib import form from zope import schema from zope.interface import implements from zope.component import getMultiAdapter from plone.app.portlets.portlets import base from plone.memoize.instance import memoize from plone.portlets.interfaces import IPortletDataProvider from Products.Fi...
[ "from five import grok\nfrom zope.formlib import form\nfrom zope import schema\nfrom zope.interface import implements\nfrom zope.component import getMultiAdapter\nfrom plone.app.portlets.portlets import base\nfrom plone.memoize.instance import memoize\nfrom plone.portlets.interfaces import IPortletDataProvider\nfro...
false
7,665
bd726c86bdecd0b63eb48d056932706d3ecf147d
import os,sys import logging from flask import Flask from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy def create_app(): app = Flask(__name__) Bootstrap(app) return app logging.basicConfig(level=logging.DEBUG) app = create_app() app.config['WTF_CSRF_ENABLED'] = True app.config[...
[ "import os,sys\nimport logging\nfrom flask import Flask\nfrom flask_bootstrap import Bootstrap\nfrom flask_sqlalchemy import SQLAlchemy\n\ndef create_app():\n app = Flask(__name__)\n Bootstrap(app)\n return app\n\nlogging.basicConfig(level=logging.DEBUG)\napp = create_app()\napp.config['WTF_CSRF_ENABLED'] ...
false
7,666
a1141e6aae6992a5037d53093378f0d346f2ca29
#!/usr/bin/env python from pathlib import Path import os from setuptools import setup, find_packages install_requires = [ "numpy", "tensorflow-hub==0.4.0", "bert-tensorflow==1.0.1", "click" ] # Hacky check for whether CUDA is installed has_cuda = any("CUDA" in name.split("_") for name in os.environ....
[ "#!/usr/bin/env python\nfrom pathlib import Path\nimport os\n\nfrom setuptools import setup, find_packages\n\n\ninstall_requires = [\n \"numpy\",\n \"tensorflow-hub==0.4.0\",\n \"bert-tensorflow==1.0.1\",\n \"click\"\n]\n\n# Hacky check for whether CUDA is installed\nhas_cuda = any(\"CUDA\" in name.spli...
false
7,667
87f672919f6019e549508b239c798301d5f549bd
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015-2016 Applatix, Inc. All rights reserved. # ''' cAdvisor CLI. Used by axstats temporarily before moving to Heapster ''' import requests import logging import time logger = logging.getLogger(__name__) CHECK_LIVELINESS_INTERVAL = 5 CONNECTION_TIMEOUT = 5 ...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2015-2016 Applatix, Inc. All rights reserved.\n#\n\n'''\ncAdvisor CLI. Used by axstats temporarily before moving to Heapster\n'''\n\nimport requests\nimport logging\nimport time\n\nlogger = logging.getLogger(__name__)\nCHECK_LIVELINESS_INTERVAL = 5\nCO...
false
7,668
68e1e39f193537367d899c5fd01c1361ed93ef29
n, k = raw_input().split() n = int(n) k = int(k) div = 0 for i in range(n): new = int(raw_input()) if (new % k) == 0: div += 1 print div
[ "n, k = raw_input().split()\nn = int(n)\nk = int(k)\n\ndiv = 0\n\nfor i in range(n):\n new = int(raw_input())\n if (new % k) == 0:\n div += 1\n\nprint div" ]
true
7,669
7ee3301b55d323d156bd394f8525e37502d19430
number = int(input()) bonus = 0 if number <= 100: bonus = 5 total_point = number + bonus elif number > 1000: bonus = 0.1 * number total_point = number + bonus else: bonus = 0.2 * number total_point = number + bonus if number % 2 == 0: bonus = bonus + 1 total_point = number +...
[ "number = int(input())\r\nbonus = 0\r\nif number <= 100:\r\n bonus = 5\r\n total_point = number + bonus\r\nelif number > 1000:\r\n bonus = 0.1 * number\r\n total_point = number + bonus\r\nelse:\r\n bonus = 0.2 * number\r\n total_point = number + bonus\r\nif number % 2 == 0:\r\n bonus = bonus + ...
false
7,670
c6fa8c33630fc2f7ffb08aace1a260e6805ddfa2
"""Main application for FastAPI""" from typing import Dict from fastapi import FastAPI from fastapi.openapi.utils import get_openapi from cool_seq_tool.routers import default, mane, mappings, SERVICE_NAME from cool_seq_tool.version import __version__ app = FastAPI( docs_url=f"/{SERVICE_NAME}", openapi_url=...
[ "\"\"\"Main application for FastAPI\"\"\"\nfrom typing import Dict\n\nfrom fastapi import FastAPI\nfrom fastapi.openapi.utils import get_openapi\n\n\nfrom cool_seq_tool.routers import default, mane, mappings, SERVICE_NAME\nfrom cool_seq_tool.version import __version__\n\n\napp = FastAPI(\n docs_url=f\"/{SERVICE_...
false
7,671
66f6639ae62fe8c0b42171cf3e3fb450d8eee2b2
from pypc.a_primitives.nand import nand # nand gates used: 5 def half_adder(a: bool, b: bool) -> (bool, bool): """Returns a + b in the form of a tuple of two bools representing the two bits.""" nand_a_b = nand(a, b) nand_c = nand(nand_a_b, a) nand_d = nand(nand_a_b, b) high = nand(na...
[ "from pypc.a_primitives.nand import nand\r\n\r\n\r\n# nand gates used: 5\r\ndef half_adder(a: bool, b: bool) -> (bool, bool):\r\n \"\"\"Returns a + b in the form of a tuple of two bools representing the two\r\n bits.\"\"\"\r\n nand_a_b = nand(a, b)\r\n nand_c = nand(nand_a_b, a)\r\n nand_d = nand(nan...
false
7,672
90c9456bf22745d99fa76dbc752beae1a3835682
from field import print_field from math_utilite import sign, col def start_parameter_2(par): global cell_king, castling_control, trans, take_on_aisle cell_king = par[0] castling_control = par[1] trans = par[2] take_on_aisle = par[3] def det_cell_king(field): global cell_king cell_king...
[ "from field import print_field\nfrom math_utilite import sign, col\n\n\ndef start_parameter_2(par):\n global cell_king, castling_control, trans, take_on_aisle\n cell_king = par[0]\n castling_control = par[1]\n trans = par[2]\n take_on_aisle = par[3]\n \ndef det_cell_king(field):\n global cell_k...
false
7,673
52872804a069cd954bea247b64041eceafd8d139
__author__ = 'Administrator' #coding:utf-8 def calculate_score(calculation_params): """ 计算选手在一跳中的得分,共7名裁判,去掉两个最高分和两个最低分,余下3名裁判员的分数之和乘以运动员所跳动作的难度系数,便得出该动作的实得分 传入参数为字典 calculation_params["score_list"] = [] calculation_params["difficulty"] = float """ score_list = calculation_params["score_list...
[ "__author__ = 'Administrator'\n#coding:utf-8\ndef calculate_score(calculation_params):\n \"\"\"\n 计算选手在一跳中的得分,共7名裁判,去掉两个最高分和两个最低分,余下3名裁判员的分数之和乘以运动员所跳动作的难度系数,便得出该动作的实得分\n 传入参数为字典\n calculation_params[\"score_list\"] = []\n calculation_params[\"difficulty\"] = float\n \"\"\"\n score_list = calcul...
true
7,674
4958d6d88b762e6fbe860123b7274c16b6452605
import sqlalchemy from .base import Base from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship class ModelSpellVariantPair(Base): __tablename__ = "spell_variant_pair" uuid = Column( UUID(as_uuid=True), ...
[ "import sqlalchemy\nfrom .base import Base\nfrom sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.orm import relationship\n\n\nclass ModelSpellVariantPair(Base):\n __tablename__ = \"spell_variant_pair\"\n\n uuid = Column(\n UUID(as_...
false
7,675
af1eab58fd641b14ac054fa26e28d52c9741fb16
import copy import os from datetime import datetime import numpy as np from sklearn.neighbors import NearestNeighbors from sklearn.preprocessing import normalize ROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../') DATA_FILE = os.path.join(ROOT_DIR, 'data/data_train.csv') TRAINING_FILE_NAME = os....
[ "import copy\nimport os\nfrom datetime import datetime\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.preprocessing import normalize\n\nROOT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')\nDATA_FILE = os.path.join(ROOT_DIR, 'data/data_train.csv')\nTRAINING_F...
false
7,676
87562ce2a957de3fa2eb84cbb0de18c6ce264c6b
# -*- coding: utf-8 -*- """ This file is part of pyCMBS. (c) 2012- Alexander Loew For COPYING and LICENSE details, please refer to the LICENSE file """ import unittest from pycmbs import data4D class TestPycmbsData4D(unittest.TestCase): def setUp(self): pass def test_DummyTest(self): pass i...
[ "# -*- coding: utf-8 -*-\n\"\"\"\nThis file is part of pyCMBS.\n(c) 2012- Alexander Loew\nFor COPYING and LICENSE details, please refer to the LICENSE file\n\"\"\"\n\nimport unittest\nfrom pycmbs import data4D\n\nclass TestPycmbsData4D(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def test_DummyT...
false
7,677
3e19ede2112a109a776b607e927e2f0a095ba5cc
from .__init__ import * def surfaceAreaCone(maxRadius=20, maxHeight=50, unit='m'): a = random.randint(1, maxHeight) b = random.randint(1, maxRadius) slopingHeight = math.sqrt(a**2 + b**2) problem = f"Surface area of cone with height = {a}{unit} and radius = {b}{unit} is" ans = int(math.pi * b * s...
[ "from .__init__ import *\n\n\ndef surfaceAreaCone(maxRadius=20, maxHeight=50, unit='m'):\n a = random.randint(1, maxHeight)\n b = random.randint(1, maxRadius)\n\n slopingHeight = math.sqrt(a**2 + b**2)\n problem = f\"Surface area of cone with height = {a}{unit} and radius = {b}{unit} is\"\n ans = int...
false
7,678
d27a7ca04e12d50aca5a9f9db199102dbeb4e9f1
from django.http import JsonResponse from django.shortcuts import render from phone_number_parser.forms import TextForm import re def parse_text(request): ########################################################################### # # Parse Text is the lone view for this project. A GET request renders a ...
[ "from django.http import JsonResponse\nfrom django.shortcuts import render\nfrom phone_number_parser.forms import TextForm\nimport re\n\n\ndef parse_text(request):\n ###########################################################################\n #\n # Parse Text is the lone view for this project. A GET reque...
false
7,679
9f6cfeff9e00079715827a2887263c14a1bb51ff
import os, tempfile, shutil from flask import Flask, flash, request, redirect, url_for, send_from_directory, send_file from werkzeug.utils import secure_filename from contextlib import contextmanager """ Flask stores uploaded FileStorage objects in memory if they are small. Otherwise, it internally uses tempfile.gett...
[ "import os, tempfile, shutil\nfrom flask import Flask, flash, request, redirect, url_for, send_from_directory, send_file\nfrom werkzeug.utils import secure_filename\nfrom contextlib import contextmanager\n\n\n\"\"\"\nFlask stores uploaded FileStorage objects in memory if they are small. Otherwise, it internally use...
false
7,680
26a6fe0b2a98aa77b63a336cd6c2afcfe81d9058
#!/usr/bin/env python3 import os import subprocess import emailgen # # Header information # recipient = input("recipient: ") sender = input("sender: ") password = input("sender password: ") subject = "hdd temp alert" # # Get hdd temp, format for email # output = subprocess.check_output('sudo hddtemp /dev/sda /dev/sd...
[ "#!/usr/bin/env python3\nimport os\nimport subprocess\nimport emailgen\n\n\n#\n# Header information\n#\nrecipient = input(\"recipient: \")\nsender = input(\"sender: \")\npassword = input(\"sender password: \")\nsubject = \"hdd temp alert\"\n\n#\n# Get hdd temp, format for email\n#\noutput = subprocess.check_output(...
false
7,681
cc23eeed44ff66d68c700163cca8b9f4986d497d
# Copyright (C) 2019 Catalyst Cloud 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 la...
[ "# Copyright (C) 2019 Catalyst Cloud Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required b...
false
7,682
6ef78e4308f6e693f50df714a5d7af1785e49d7a
from utils import * import copy import torch.nn as nn CUDA = torch.cuda.is_available() def train_one_epoch(data_loader, net, loss_fn, optimizer): net.train() tl = Averager() pred_train = [] act_train = [] for i, (x_batch, y_batch) in enumerate(data_loader): if CUDA: ...
[ "\r\nfrom utils import *\r\nimport copy\r\nimport torch.nn as nn\r\n\r\nCUDA = torch.cuda.is_available()\r\n\r\n\r\ndef train_one_epoch(data_loader, net, loss_fn, optimizer):\r\n net.train()\r\n tl = Averager()\r\n pred_train = []\r\n act_train = []\r\n for i, (x_batch, y_batch) in enumerate(data_loa...
false
7,683
14d31a4b7491a7f7a64cd151e79c23546e4a3cd2
#ABC114 A - クイズ print("ABC" if input()=="1" else "chokudai")
[ "#ABC114 A - クイズ\nprint(\"ABC\" if input()==\"1\" else \"chokudai\")\n", "print('ABC' if input() == '1' else 'chokudai')\n", "<code token>\n" ]
false
7,684
aaa9665ac6d639e681fddd032058f490ce36d12a
from django.shortcuts import render from django.views.generic import DetailView from .models import Course # Create your views here. def courses_list_view(request): products = Course.objects.all() title = "دوره ها" context = { "object_list": products, "title": title, } return re...
[ "from django.shortcuts import render\nfrom django.views.generic import DetailView\nfrom .models import Course\n\n\n# Create your views here.\n\ndef courses_list_view(request):\n products = Course.objects.all()\n title = \"دوره ها\"\n context = {\n \"object_list\": products,\n \"title\": title...
false
7,685
ba26aa2f33983019b515c5ea287bd5d5d190eeac
N,M=map(int,input().split()) if N>=M//2: print(M//2) else: answer=N M-=2*N N=0 print(answer+M//4)
[ "N,M=map(int,input().split())\n\nif N>=M//2:\n print(M//2)\nelse:\n answer=N\n M-=2*N\n N=0\n print(answer+M//4)", "N, M = map(int, input().split())\nif N >= M // 2:\n print(M // 2)\nelse:\n answer = N\n M -= 2 * N\n N = 0\n print(answer + M // 4)\n", "<assignment token>\nif N >= M // 2:\n ...
false
7,686
ca6a9656efe439c9e90f2724e38e652a09e46dae
""" Test 1, problem 1. Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder, their colleagues and Nathan Gupta. March 2016. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. def main(): """ Calls the TEST functions in this module. """ test_problem1a() test_problem1b() t...
[ "\"\"\"\nTest 1, problem 1.\n\nAuthors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,\n their colleagues and Nathan Gupta. March 2016.\n\"\"\" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.\n\n\ndef main():\n \"\"\" Calls the TEST functions in this module. \"\"\"\n test_problem1a()...
false
7,687
5c80561a3344c0240e59500e5dadc1f1ef7f380e
str="mama" stringlength=len(str) slicedString=str[stringlength::-1] print (slicedString)
[ "str=\"mama\"\r\nstringlength=len(str)\r\nslicedString=str[stringlength::-1]\r\nprint (slicedString)", "str = 'mama'\nstringlength = len(str)\nslicedString = str[stringlength::-1]\nprint(slicedString)\n", "<assignment token>\nprint(slicedString)\n", "<assignment token>\n<code token>\n" ]
false
7,688
7633944366c6655306bc41087b19a474e9c414b5
from django.contrib import admin from .models import Spot from leaflet.admin import LeafletGeoAdmin class SpotAdmin(LeafletGeoAdmin): pass admin.site.register(Spot, SpotAdmin)
[ "from django.contrib import admin\nfrom .models import Spot\nfrom leaflet.admin import LeafletGeoAdmin\n\n\nclass SpotAdmin(LeafletGeoAdmin):\n pass\n\nadmin.site.register(Spot, SpotAdmin)\n", "from django.contrib import admin\nfrom .models import Spot\nfrom leaflet.admin import LeafletGeoAdmin\n\n\nclass Spot...
false
7,689
ea045d04b40341f34c780dceab1f21df93b7207a
# A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object # import connect # from connect import connect #create class import pymysql # import MySQLdb conn = pymysql.connect(host='127.0.0.1',user='root',password='',...
[ "# A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object\n# import connect \n# from connect import connect\n#create class\n\nimport pymysql\n# import MySQLdb\nconn = pymysql.connect(host='127.0.0.1',user='root',...
false
7,690
39643454cbef9e6fa7979d0f660f54e07d155bc7
#!/usr/bin/env python3 '''Testing File''' import tensorflow.keras as K def test_model( network, data, labels, verbose=True ): '''A Function that tests a neural network''' return network.evaluate( x=data, y=labels, verbose=verbose )
[ "#!/usr/bin/env python3\n'''Testing File'''\nimport tensorflow.keras as K\n\n\ndef test_model(\n network, data, labels, verbose=True\n):\n '''A Function that tests\n a neural network'''\n return network.evaluate(\n x=data,\n y=labels,\n verbose=verbose\n )\n", "<docstring token...
false
7,691
8766003a85b1ed83927988df147b0b3004cb91f9
def solution(name): Len = len(name) nameList = [name[i] for i in range(Len)] nameField = ['A' for i in range(Len)] answer = 0 # 정방향 for i in range(Len): a = ord(nameField[i]) b = ord(nameList[i]) if b-a <= 13 : # 절반 이하면 그냥 더하고 answer += b-a ...
[ "def solution(name):\n Len = len(name)\n nameList = [name[i] for i in range(Len)]\n nameField = ['A' for i in range(Len)]\n answer = 0\n \n # 정방향\n for i in range(Len):\n a = ord(nameField[i])\n b = ord(nameList[i])\n if b-a <= 13 : # 절반 이하면 그냥 더하고\n a...
false
7,692
ea876d903263c907f63b2f37a81f2576345dae62
botnet = open("bots.txt","r") bots = botnet.read() print(bots.split('\n')) botnet.close()
[ "botnet = open(\"bots.txt\",\"r\")\nbots = botnet.read()\nprint(bots.split('\\n'))\nbotnet.close()", "botnet = open('bots.txt', 'r')\nbots = botnet.read()\nprint(bots.split('\\n'))\nbotnet.close()\n", "<assignment token>\nprint(bots.split('\\n'))\nbotnet.close()\n", "<assignment token>\n<code token>\n" ]
false
7,693
d3b00a8d410248aedb1c43354e89ccc298b56a3c
# -*- coding: utf-8 -*- # @Time : 2020/3/4 10:34 # @Author : YYLin # @Email : 854280599@qq.com # @File : Skip_GAN.py from Dataload import load_anime_old, save_images, load_CelebA from Srresnet_Model import Generator_srresnet, Discriminator_srresnet import tensorflow as tf import numpy as np import sys...
[ "# -*- coding: utf-8 -*-\r\n# @Time : 2020/3/4 10:34\r\n# @Author : YYLin\r\n# @Email : 854280599@qq.com\r\n# @File : Skip_GAN.py\r\nfrom Dataload import load_anime_old, save_images, load_CelebA\r\nfrom Srresnet_Model import Generator_srresnet, Discriminator_srresnet\r\nimport tensorflow as tf\r\nimport nu...
false
7,694
211ef4c64e42c54423ac8dab2128952874a2cf5a
# Generated by Django 2.2.10 on 2020-03-13 14:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('system', '0005_location'), ] operations = [ migrations.AddField( model_name='setting', name='runned_locations_initi...
[ "# Generated by Django 2.2.10 on 2020-03-13 14:02\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('system', '0005_location'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='setting',\n name='run...
false
7,695
bce16762c0739087a8309872da4ac04298c50893
"""Step (with Warm up) learning rate scheduler module.""" from typing import Union import torch from torch.optim.lr_scheduler import _LRScheduler from typeguard import check_argument_types from espnet2.schedulers.abs_scheduler import AbsBatchStepScheduler class WarmupStepLR(_LRScheduler, AbsBatchStepScheduler): ...
[ "\"\"\"Step (with Warm up) learning rate scheduler module.\"\"\"\nfrom typing import Union\n\nimport torch\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom typeguard import check_argument_types\n\nfrom espnet2.schedulers.abs_scheduler import AbsBatchStepScheduler\n\n\nclass WarmupStepLR(_LRScheduler, AbsBat...
false
7,696
83fe635e35711c2c41d043a59d00a50cc87e69fa
"Base document saver context classes." import copy import os.path import sys import flask from . import constants from . import utils class BaseSaver: "Base document saver context." DOCTYPE = None EXCLUDE_PATHS = [["_id"], ["_rev"], ["doctype"], ["modified"]] HIDDEN_VALUE_PATHS = [] def __ini...
[ "\"Base document saver context classes.\"\n\nimport copy\nimport os.path\nimport sys\n\nimport flask\n\nfrom . import constants\nfrom . import utils\n\n\nclass BaseSaver:\n \"Base document saver context.\"\n\n DOCTYPE = None\n EXCLUDE_PATHS = [[\"_id\"], [\"_rev\"], [\"doctype\"], [\"modified\"]]\n HIDD...
false
7,697
f4dd9500835cb22a859da8bd57487052522bb593
alien_0 = {} # 声明一个空字典 alien_0['color'] = 'green' # 向空字典中添加值 alien_0['points'] = 5 print(alien_0) x = alien_0['color'] print(f"\nThe alien is {alien_0['color']}") # 引号的用法 alien_0['color'] = 'yellow' # 对字典中的元素重新赋值 print(f"The alien is now {alien_0['color']}")
[ "\nalien_0 = {} # 声明一个空字典\n\nalien_0['color'] = 'green' # 向空字典中添加值\nalien_0['points'] = 5\n\nprint(alien_0)\n\nx = alien_0['color']\n\nprint(f\"\\nThe alien is {alien_0['color']}\") # 引号的用法\n\nalien_0['color'] = 'yellow' # 对字典中的元素重新赋值\n\nprint(f\"The alien is now {alien_0['color']}\")\n\n", "alien_0 = {}\nalien_...
false
7,698
64c4b64b6fb0cfa25c17f66243c60a5dc0166017
#!/usr/bin/python #Autor: Jesus Fabian Cubas <jfabian@computer.org> #if sesion = 2 if sesion == 1 : print 'estamos en la sesion 01' elif sesion == 2 : print 'estamos en la sesion 02' else : print 'no estamos en la sesion 01' #while edad = 0 while edad < 18 : edad = edad + 1 print edad #for lista = ["a", "b", "c"...
[ "#!/usr/bin/python\n#Autor: Jesus Fabian Cubas <jfabian@computer.org>\n\n#if\nsesion = 2\nif sesion == 1 :\n\tprint 'estamos en la sesion 01'\nelif sesion == 2 :\n\tprint 'estamos en la sesion 02'\nelse :\n\tprint 'no estamos en la sesion 01'\n\n#while\nedad = 0\nwhile edad < 18 :\n\tedad = edad + 1\nprint edad\n\n...
true
7,699
2b7bb02a25504e7481d3bc637ea09bcf9addb990
import os from xml.dom import minidom import numpy as np def get_branches_dir(root_dir): branches_dir = [] folds = os.listdir(root_dir) while folds: branch_dir = root_dir + '/' + folds.pop() branches_dir.append(branch_dir) return branches_dir def tolist(xml, detname): try: ...
[ "import os\nfrom xml.dom import minidom\nimport numpy as np\n\n\ndef get_branches_dir(root_dir):\n branches_dir = []\n folds = os.listdir(root_dir)\n while folds:\n branch_dir = root_dir + '/' + folds.pop()\n branches_dir.append(branch_dir)\n return branches_dir\n\n\ndef tolist(xml, detnam...
false