index int64 0 100k | blob_id stringlengths 40 40 | code stringlengths 7 7.27M | steps listlengths 1 1.25k | error bool 2
classes |
|---|---|---|---|---|
1,400 | 62601eca767800f00b461ef46d72bddc5cf75de0 | """Encoder module of Monodepth2
Code partially borrowed from
https://github.com/nianticlabs/monodepth2/blob/master/networks/resnet_encoder.py
"""
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import mxnet as mx
from mxnet.gluon import nn
from mxnet.context import cpu
fr... | [
"\"\"\"Encoder module of Monodepth2\nCode partially borrowed from\nhttps://github.com/nianticlabs/monodepth2/blob/master/networks/resnet_encoder.py\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport numpy as np\nimport mxnet as mx\n\nfrom mxnet.gluon import nn\nfrom mxnet... | false |
1,401 | 67be25e8fdf004515e18e1c20b8d0238222a2172 | import torch
import torch.nn as nn
import numpy as np
class EuclideanLoss(nn.Module):
def __init__(self, c_p, c_h):
super().__init__()
self.c_p = c_p
self.c_h = c_h
def forward(self, y, d):
'''
y: prediction, size = (n_product, n_obs)
d: actual sales, size = ... | [
"import torch\nimport torch.nn as nn\nimport numpy as np\n\nclass EuclideanLoss(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n '''\n y: prediction, size = (n_product, n_obs)\n d: ac... | false |
1,402 | 22909e41e4f9ad0280c22ec11ecfbccff87efae1 | import sys
if __name__ == '__main__':
cases = sys.stdin.readline()
for i in range(int(cases)):
sys.stdin.readline()
lineas, columnas = sys.stdin.readline().strip().split(" ")
lineas = int(lineas)
columnas = int(columnas)
list_lines = []
for linea in range(linea... | [
"import sys\n\n\nif __name__ == '__main__':\n cases = sys.stdin.readline()\n for i in range(int(cases)):\n sys.stdin.readline()\n lineas, columnas = sys.stdin.readline().strip().split(\" \")\n lineas = int(lineas)\n columnas = int(columnas)\n list_lines = []\n\n for l... | false |
1,403 | a3301180e53da4a6970c082e72d8721b29dcae2e | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
# importing regular stuff
import os
import sys
import thread
import threading
import time
import datetime
from datetime import datetime
import random
import filecmp
import ConfigParser
import socket
#my stuff will go here
import include.action as action
import include.l... | [
"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\n# importing regular stuff\nimport os\nimport sys\nimport thread\nimport threading\nimport time\nimport datetime\nfrom datetime import datetime\nimport random\nimport filecmp\nimport ConfigParser\nimport socket\n\n#my stuff will go here\nimport include.action as a... | true |
1,404 | 8928c2ff49cbad2a54252d41665c10437a471eeb | from contextlib import contextmanager
from filecmp import cmp, dircmp
from shutil import copyfile, copytree, rmtree
import pytest
from demisto_sdk.commands.common.constants import PACKS_DIR, TEST_PLAYBOOKS_DIR
from demisto_sdk.commands.common.tools import src_root
TEST_DATA = src_root() / 'tests' / 'test_files'
TEST_... | [
"from contextlib import contextmanager\nfrom filecmp import cmp, dircmp\nfrom shutil import copyfile, copytree, rmtree\n\nimport pytest\nfrom demisto_sdk.commands.common.constants import PACKS_DIR, TEST_PLAYBOOKS_DIR\nfrom demisto_sdk.commands.common.tools import src_root\n\nTEST_DATA = src_root() / 'tests' / 'test... | false |
1,405 | 28233cb4a56ee805e66f34e6abd49137503d5f7b | from django.db import models
class Article(models.Model):
created = models.DateTimeField(auto_now_add=True)
published = models.DateTimeField(null=True, blank=True)
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
content = models.TextField()
| [
"from django.db import models\n\n\nclass Article(models.Model):\n\n created = models.DateTimeField(auto_now_add=True)\n published = models.DateTimeField(null=True, blank=True)\n\n title = models.CharField(max_length=100)\n slug = models.SlugField(max_length=100)\n content = models.TextField()\n",
"... | false |
1,406 | e59763991974f4bfcd126879dd9aabd44bd89419 | """
This is a module containing convenience functions to create the JWST aperture and coronagraphic images with WebbPSF.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
import logging
import poppy
from pastis.config import CONFIG_PASTIS
import pastis.util as util
log = loggi... | [
"\"\"\"\nThis is a module containing convenience functions to create the JWST aperture and coronagraphic images with WebbPSF.\n\"\"\"\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport astropy.units as u\nimport logging\nimport poppy\n\nfrom pastis.config import CONFIG_PASTIS\nimport pastis.uti... | false |
1,407 | 39b6ca21b8d4856e2b2edfcbd00b75fbce6dfff7 | from django import forms
from django.core.validators import RegexValidator
from dashboard.validators import validate_domainonly_email
class addUserForm(forms.Form):
username = forms.CharField(label='User Name', required="required", disabled="", min_length=6, max_length=128,
help_tex... | [
"from django import forms\nfrom django.core.validators import RegexValidator\nfrom dashboard.validators import validate_domainonly_email\n\n\nclass addUserForm(forms.Form):\n username = forms.CharField(label='User Name', required=\"required\", disabled=\"\", min_length=6, max_length=128,\n ... | false |
1,408 | 0b0b22043dda94ea57344fb3bf47255ad85c7f5b | # -*- coding: utf-8 -*-
from rest_framework.views import APIView
from ..Models.ConnectToDBModel import *
from ..Models.RegionInfoModel import *
from .CommonView import *
def get_one_spot(region):
comments_data = get_comment_data();
data = {};
data['id'] = region.id;
data['name'] = r... | [
"# -*- coding: utf-8 -*-\nfrom rest_framework.views import APIView\nfrom ..Models.ConnectToDBModel import *\nfrom ..Models.RegionInfoModel import *\nfrom .CommonView import *\n\n\n\ndef get_one_spot(region):\n\n comments_data = get_comment_data();\n\n data = {};\n data['id'] = region.id;\n ... | false |
1,409 | 11576597429e119cf4887a88139df4a9e6d7eb66 | from tkinter import *
from tkinter import filedialog
from tkinter import scrolledtext
import tkinter as tk
import os
import sys
import subprocess
import shlex
from subprocess import check_output
import pathlib
| [
"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import scrolledtext\nimport tkinter as tk\nimport os\nimport sys\nimport subprocess\nimport shlex\nfrom subprocess import check_output\nimport pathlib\n\n",
"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import scrolledtext... | false |
1,410 | 18bc8a8b1cbb544cfbe581e32ee5e509d67beafd | from connection import Machine
from credentials import get_credentials
targets = ['45.32.13.245']
#targets = ['localhost']
input_file = 'cmd'
def main():
global targets
username, password = get_credentials('laozi')
remote_host = Machine(username, password)
for target in targets:
remote_host.co... | [
"from connection import Machine\nfrom credentials import get_credentials\n\ntargets = ['45.32.13.245']\n#targets = ['localhost']\ninput_file = 'cmd'\n\ndef main():\n global targets\n username, password = get_credentials('laozi')\n remote_host = Machine(username, password)\n for target in targets:\n ... | false |
1,411 | 7701a98d836dc9551a4e2eb4b7d9c10307b3f665 | from pyNastran.bdf.fieldWriter import print_card
from pyNastran.bdf.bdfInterface.assign_type import (integer, integer_or_blank,
double_or_blank, string_or_blank)
class NLPARM(object):
"""
Defines a set of parameters for nonlinear static analysis iteration
strategy.
+--------+--------+------+-----... | [
"from pyNastran.bdf.fieldWriter import print_card\nfrom pyNastran.bdf.bdfInterface.assign_type import (integer, integer_or_blank,\n double_or_blank, string_or_blank)\n\n\nclass NLPARM(object):\n \"\"\"\n Defines a set of parameters for nonlinear static analysis iteration\n strategy.\n\n +--------+---... | false |
1,412 | 456d79a69c170a59af742648f16e0171cd5a2412 | '''
Generate the output images and videos, including rendering of the pipeline
'''
import os
import matplotlib.image as mpimg
import cv2
from moviepy.editor import VideoFileClip
from networkx.drawing.nx_agraph import to_agraph
import lanespipeline
import lanefinder
from compgraph import CompGraph, CompGraphRunner
C... | [
"'''\nGenerate the output images and videos, including rendering of the pipeline\n'''\n\nimport os\nimport matplotlib.image as mpimg\nimport cv2\nfrom moviepy.editor import VideoFileClip\nfrom networkx.drawing.nx_agraph import to_agraph\n\nimport lanespipeline\nimport lanefinder\nfrom compgraph import CompGraph, Co... | false |
1,413 | 86b24ddaae0d3477a3f82295224b7e84805eed91 | # Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | [
"# Copyright 2023 Google LLC\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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in... | false |
1,414 | 8c05259ce577e6b6a6efdf778832e9bb817e47fd | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-14 19:37
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | [
"# -*- coding: utf-8 -*-\n# Generated by Django 1.10.2 on 2016-10-14 19:37\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH... | false |
1,415 | 5fdcbccb99880da79eb0efbdecd328ca1cf73d7f | from wagtail.tests.utils import WagtailPageTests
from setup_guide.models import SetupGuideLandingPage, SetupGuidePage
from home.models import HomePage
class SetupGuideLandingPageTests(WagtailPageTests):
def test_can_create_under_homepage(self):
self.assertCanCreateAt(HomePage, SetupGuideLandingPage)
... | [
"from wagtail.tests.utils import WagtailPageTests\nfrom setup_guide.models import SetupGuideLandingPage, SetupGuidePage\nfrom home.models import HomePage\n\n\nclass SetupGuideLandingPageTests(WagtailPageTests):\n def test_can_create_under_homepage(self):\n self.assertCanCreateAt(HomePage, SetupGuideLandin... | false |
1,416 | 678189ac5b0105c90178647843335f9d4402dc66 | #!/usr/bin/python3
# Distributed with a free-will license.
# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.
# ADC121C_MQ131
# This code is designed to work with the ADC121C_I2CGAS_MQ131 I2C Mini Module available from ControlEverything.com.
# https://www.controleveryth... | [
"#!/usr/bin/python3\n# Distributed with a free-will license.\n# Use it any way you want, profit or free, provided it fits in the licenses of its associated works.\n# ADC121C_MQ131\n# This code is designed to work with the ADC121C_I2CGAS_MQ131 I2C Mini Module available from ControlEverything.com.\n# https://www.cont... | false |
1,417 | f2056ff46ce6e38c3b6ca553bbdec7f59d60b198 | # Ejercicio 28 - Hoja VI (5) - Indicar la nota ponderada según el criterio dado
# (parte teórica 60%, práctica 40%) de cada uno de un número determinado de alumnos
numalumnos=int(input("Introduce el número total de alumnos:\n"))
print("Usa el punto '.' para los decimales")
for contador in range(1,numalumnos+1):
... | [
"# Ejercicio 28 - Hoja VI (5) - Indicar la nota ponderada según el criterio dado\n# (parte teórica 60%, práctica 40%) de cada uno de un número determinado de alumnos\n\nnumalumnos=int(input(\"Introduce el número total de alumnos:\\n\"))\nprint(\"Usa el punto '.' para los decimales\")\nfor contador in range(1,numalu... | false |
1,418 | a52cbe6dbf4b4fc82d09e5f34e6e135933f3af38 | #!/usr/bin/python3
'''
generator.py
This program inputs a strings, and outputs the corresponding hex
Creator: Ethan Knight
Email: ethantknight@gmail.com
Published: 20181116
'''
import sys
import time
import binascii
def main():
print("\n", sys.version_info)
try:
while True:
... | [
"#!/usr/bin/python3\n\n'''\n generator.py\n This program inputs a strings, and outputs the corresponding hex\n Creator: Ethan Knight\n Email: ethantknight@gmail.com\n Published: 20181116\n'''\n\nimport sys\nimport time\nimport binascii\n\ndef main():\n print(\"\\n\", sys.version_info)\n t... | false |
1,419 | 67516551b595c02e70a0ba4005df8a97ba71b17e | # Uses python3
import numpy as np
def fibonaci(n):
if n <= 1:
return n
F = np.empty(shape=(n + 1))
F[0] = 0
F[1] = 1
for i in range(2, len(F)):
F[i] = F[i - 1] + F[i - 2]
return F[n]
n = int(input())
print(int(fibonaci(n)))
| [
"# Uses python3\nimport numpy as np\n\n\ndef fibonaci(n):\n if n <= 1:\n return n\n\n F = np.empty(shape=(n + 1))\n F[0] = 0\n F[1] = 1\n for i in range(2, len(F)):\n F[i] = F[i - 1] + F[i - 2]\n\n return F[n]\n\n\nn = int(input())\nprint(int(fibonaci(n)))\n",
"import numpy as np\n... | false |
1,420 | 9c8a213fc8a7397662eebb74d6ee1ad34cb884d9 | import time
import os, os.path
import random
import cv2
import glob
import keras
import matplotlib
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from sklearn.decomposition import PCA
import pandas as ... | [
"import time\nimport os, os.path\nimport random\nimport cv2\nimport glob\nimport keras\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.decomposition import PCA\n\n... | false |
1,421 | e03dfa0e02313c5478d4e97dcaf3bc27915bd878 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar as cal
import random
import pytz
from datetime import datetime, timedelta, time
from dateutil import rrule
from dateutil.relativedelta import relativedelta
from babel.dates import format_datetime
from od... | [
"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nimport calendar as cal\nimport random\nimport pytz\nfrom datetime import datetime, timedelta, time\nfrom dateutil import rrule\nfrom dateutil.relativedelta import relativedelta\nfrom babel.dates import format_dat... | false |
1,422 | 1aaace83af0235341d10b8ac3b47d00a944dac37 | # Generated by Django 3.1.2 on 2020-10-17 15:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('story1', '0006_visitor'),
]
operations = [
migrations.RenameField(
model_name='visitor',
old_name='identitiy_n... | [
"# Generated by Django 3.1.2 on 2020-10-17 15:46\r\n\r\nfrom django.db import migrations\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('story1', '0006_visitor'),\r\n ]\r\n\r\n operations = [\r\n migrations.RenameField(\r\n model_name='visitor',\r\n... | false |
1,423 | 6aff61ce5cef537e6b1b19e382d8bf80e3a61693 | import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
options = VarParsing.VarParsing()
options.register(
'file','',VarParsing.VarParsing.multiplicity.singleton,
VarParsing.VarParsing.varType.string,
'File path for storing output')
options.parseArguments()
file_path = options.f... | [
"import FWCore.ParameterSet.Config as cms\nimport FWCore.ParameterSet.VarParsing as VarParsing\noptions = VarParsing.VarParsing()\noptions.register(\n\t'file','',VarParsing.VarParsing.multiplicity.singleton,\n\tVarParsing.VarParsing.varType.string,\n\t'File path for storing output')\noptions.parseArguments()\nfile_... | false |
1,424 | d0981d279f7090d5309aa564252dba731a34a66b | import csv
from pprint import pprint as pp
with open('nodes_tags.csv', 'r') as f:
tags = csv.DictReader(f)
for row in tags:
if row['key'] == 'FIXME':
pp(row)
| [
"import csv\nfrom pprint import pprint as pp\n\n\nwith open('nodes_tags.csv', 'r') as f:\n tags = csv.DictReader(f)\n for row in tags:\n if row['key'] == 'FIXME':\n pp(row)\n",
"import csv\nfrom pprint import pprint as pp\nwith open('nodes_tags.csv', 'r') as f:\n tags = csv.DictReader(f... | false |
1,425 | f0a54feaa165a393c4e87cbac2a38347633acf5a | from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
def index(request):
context = 'Welcome home'
return render(request,'base.html',{'context':context})
class HomePageView(TemplateView):
template_name = 'base.html'
| [
"from django.shortcuts import render\nfrom django.views.generic import TemplateView\n\n# Create your views here.\ndef index(request):\n context = 'Welcome home'\n return render(request,'base.html',{'context':context})\n\nclass HomePageView(TemplateView):\n template_name = 'base.html'\n",
"from django.sho... | false |
1,426 | 5000663e3cde9c1a1100c9022707ccae13db0034 | class BaseService:
def __init__(self, context):
self._context = context
def post(self, path, body):
result = self._context.http.post(path, body)
return result.json()["Data"]
| [
"class BaseService:\n\n def __init__(self, context):\n self._context = context\n\n def post(self, path, body):\n result = self._context.http.post(path, body)\n\n return result.json()[\"Data\"]\n",
"class BaseService:\n\n def __init__(self, context):\n self._context = context\n... | false |
1,427 | da55d9a6534525e58b6c1d2db997e90a1c9b0f36 | import torch
import tarfile
import pickle
import pandas
import json
import argparse
from pathlib import Path
import numpy as np
import shutil
from shutil import copyfile
import os
import re
import pandas as pd
import sys
from numpy import asarray
from numpy import savetxt
sys.path.append("..")
def parse_arguments():
... | [
"import torch\nimport tarfile\nimport pickle\nimport pandas\nimport json\nimport argparse\nfrom pathlib import Path\nimport numpy as np\nimport shutil\nfrom shutil import copyfile\nimport os\nimport re\nimport pandas as pd\nimport sys\nfrom numpy import asarray\nfrom numpy import savetxt\nsys.path.append(\"..\")\nd... | false |
1,428 | 325cc2fd82c44d0b7e291384159bd48d068e60f1 | import time
from numba import njit
import scipy.sparse as sparse
import scipy.sparse.linalg as sparse_alg
L = 12
Nup = 6
Ndown = 6
t = -2.0
U = 10.0
hoppings = [(i, j, t) for i in range(L) for j in range(L) if abs(i - j) == 1]
@njit
def hammingWeight(n):
res = 0
for i in range(32):
if n & (1 << i):
... | [
"import time\n\nfrom numba import njit\nimport scipy.sparse as sparse\nimport scipy.sparse.linalg as sparse_alg\n\n\nL = 12\nNup = 6\nNdown = 6\nt = -2.0\nU = 10.0\nhoppings = [(i, j, t) for i in range(L) for j in range(L) if abs(i - j) == 1]\n\n@njit\ndef hammingWeight(n):\n res = 0\n for i in range(32):\n ... | false |
1,429 | d7dee3311e202ae50172077940fc625f1cc6836d | #time:2020-11-28
import xlrd #读取库
def get_teacherData():
excelDir = r'../data/松勤-教管系统接口测试用例-v1.4.xls'
workBook = xlrd.open_workbook(excelDir, formatting_info=True) # 保存原样---样式
# 2-操作对应的用例表
workSheet = workBook.sheet_by_name('3-老师模块') # 通过表名获取
dataList = []
for cnt in range(1, 2): # 到第四行
... | [
"#time:2020-11-28\n\nimport xlrd #读取库\ndef get_teacherData():\n\n excelDir = r'../data/松勤-教管系统接口测试用例-v1.4.xls'\n workBook = xlrd.open_workbook(excelDir, formatting_info=True) # 保存原样---样式\n # 2-操作对应的用例表\n workSheet = workBook.sheet_by_name('3-老师模块') # 通过表名获取\n dataList = []\n for cnt in range(1,... | false |
1,430 | 2d17229afe154937132c1e4f8c138896da34ab61 | from django.apps import AppConfig
class FilebasedUniqueConfig(AppConfig):
name = 'papermerge.filebased_unique'
label = 'filebased_unique'
| [
"from django.apps import AppConfig\n\n\nclass FilebasedUniqueConfig(AppConfig):\n name = 'papermerge.filebased_unique'\n label = 'filebased_unique'\n",
"<import token>\n\n\nclass FilebasedUniqueConfig(AppConfig):\n name = 'papermerge.filebased_unique'\n label = 'filebased_unique'\n",
"<import token>... | false |
1,431 | cb469b69bf974d39609f79c4f3be686d8106f971 | from __future__ import print_function
import zmq
import time
import random
import numpy as np
import msgpack as serializer
port = '42000'
# let the OS choose the IP and PORT
ipc_sub_url = 'tcp://*:*'
ipc_push_url = 'tcp://*:*'
# starting communication threads
zmq_ctx = zmq.Context()
pub_socket = zmq_ctx.socket(zmq.... | [
"from __future__ import print_function\nimport zmq\nimport time\nimport random\nimport numpy as np \nimport msgpack as serializer\n\nport = '42000'\n\n# let the OS choose the IP and PORT\nipc_sub_url = 'tcp://*:*'\nipc_push_url = 'tcp://*:*'\n\n# starting communication threads\nzmq_ctx = zmq.Context()\npub_socket =... | false |
1,432 | 17b3f51779bda5a48c4d77c35d6bbdd2aadb13cd | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
def fully_connected(prev_layer, num_units, batch_norm, is_training=False):
layer = tf.layers.dense(prev_layer, num_units, use_bias=False, activation=None)... | [
"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True, reshape=False)\n\ndef fully_connected(prev_layer, num_units, batch_norm, is_training=False):\n layer = tf.layers.dense(prev_layer, num_units, use_bias=False, acti... | false |
1,433 | 1ddc261cf174c109583fd0ead1f537673d29090a | #rules used for pattern matching
# #1. x='[abc]' either a,b or c
#eg:
# import re
# x="[abc]"
# matcher=re.finditer(x,"abt cq5kz")
# for match in matcher:
# print(match.start())
# print(match.group())
#2. x='[^abc]' except abc
#eg:
# import re
# x="[^abc]"
# matcher=re.finditer(x,"abt cq5kz")
# for match in ... | [
" #rules used for pattern matching\n # #1. x='[abc]' either a,b or c\n#eg:\n# import re\n# x=\"[abc]\"\n# matcher=re.finditer(x,\"abt cq5kz\")\n# for match in matcher:\n# print(match.start())\n# print(match.group())\n\n#2. x='[^abc]' except abc\n#eg:\n# import re\n# x=\"[^abc]\"\n# matcher=re.finditer(x,\"a... | false |
1,434 | b220189d506737bf8cff9e600d1cfd4d7bc8435d | # -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... | [
"# -*- coding:utf-8 -*-\n\n# Copyright 2015 NEC Corporation. #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"); #\n# you may not use this file except in compliance with... | true |
1,435 | f94894e5d3e6a0ff367911c72f4d863ac32c8baa | import requests
# url="http://www.google.com"
# response=requests.get(url)
# print(response.status_code)
url = "http://icanhazdadjoke.com/"
response = requests.get(url, headers={"Accept": "application/json"})
data = response.text
print(type(data))
data = response.json()
print(data)
| [
"import requests\n\n# url=\"http://www.google.com\"\n# response=requests.get(url)\n# print(response.status_code)\n\n\nurl = \"http://icanhazdadjoke.com/\"\nresponse = requests.get(url, headers={\"Accept\": \"application/json\"})\ndata = response.text\nprint(type(data))\ndata = response.json()\nprint(data)\n",
"im... | false |
1,436 | 507251113d80eaa3684081f7814470053b04dda9 | #
#River Sheppard
#
#
from PIL import Image
if __name__ == "__main__":
scale = 768
# creating the new image in RGB mode
bitmap = Image.new("RGB", (scale, scale), "white")
# Allocating the storage for the image and
# loading the pixel data.
pix = bitmap.load()
... | [
"#\r\n#River Sheppard\r\n#\r\n#\r\n\r\nfrom PIL import Image\r\n\r\nif __name__ == \"__main__\":\r\n scale = 768\r\n \r\n # creating the new image in RGB mode\r\n bitmap = Image.new(\"RGB\", (scale, scale), \"white\")\r\n \r\n # Allocating the storage for the image and\r\n # loading the pixel data... | false |
1,437 | 086c74669b6762a6b35e8a46f816db2f4f172caa | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 30 14:34:56 2019
ref :
https://stackoverflow.com/questions/11140163/plotting-a-3d-cube-a-sphere-and-a-vector-in-matplotlib
@author: jiedeng
"""
import numpy as np
from itertools import product, combinations
from mpl_toolkits.mplot3d.art3d impor... | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 30 14:34:56 2019\nref : \n https://stackoverflow.com/questions/11140163/plotting-a-3d-cube-a-sphere-and-a-vector-in-matplotlib\n\n@author: jiedeng\n\"\"\"\nimport numpy as np\nfrom itertools import product, combinations\nfrom mpl_toolki... | false |
1,438 | 36e350e0d578e169efaafb9e311566d71d6bc59e | import retro # pip install gym-retro
import numpy as np # pip install numpy
#import cv2 # pip install opencv-python
import neat # pip install neat-python
import pickle # pip install cloudpickle
import os
import multiprocessing
import cv2
import time
env = retro.make(game='Pong-... | [
"import retro # pip install gym-retro\r\nimport numpy as np # pip install numpy\r\n#import cv2 # pip install opencv-python\r\nimport neat # pip install neat-python\r\nimport pickle # pip install cloudpickle\r\nimport os\r\nimport multiprocessing\r\nimport cv2\r\nimport time\r\n\r\nenv... | false |
1,439 | fd96bf5595ce6ec1f95d0f7a9d1c4ff582826ac0 | from django.db import models
from utils.models import BaseModel
# Create your models here.
class ContentCategory(BaseModel):
'''广告内容类别'''
name = models.CharField(verbose_name='名称',max_length=50)
key = models.CharField(verbose_name='类别键名',max_length=50)
class Meta:
db_table = 'tb_content_catego... | [
"from django.db import models\nfrom utils.models import BaseModel\n\n# Create your models here.\nclass ContentCategory(BaseModel):\n '''广告内容类别'''\n name = models.CharField(verbose_name='名称',max_length=50)\n key = models.CharField(verbose_name='类别键名',max_length=50)\n\n class Meta:\n db_table = 'tb... | false |
1,440 | c1e649b73c207ea08235d295c28daad8c91398a7 | """
Python 3.3 introduces the new "yield from" statement to provide straightforward way for
a generator to call out to other generators
"""
def gen1():
yield 'foo'
yield 'bar'
def gen2():
yield 'spam'
yield 'eggs'
"""
For python versions < 3.3
"""
def full_gen():
for word in gen1():
yiel... | [
"\"\"\"\nPython 3.3 introduces the new \"yield from\" statement to provide straightforward way for\na generator to call out to other generators\n\"\"\"\n\ndef gen1():\n yield 'foo'\n yield 'bar'\n\ndef gen2():\n yield 'spam'\n yield 'eggs'\n\n\"\"\"\nFor python versions < 3.3\n\"\"\"\ndef full_gen():\n... | true |
1,441 | 263a853f33eb9724101ca87f12b914282dea9981 | import xadmin
from .models import EmailVerifyRecord,Banner
from xadmin import views
class EmailVerifyRecordAdmin(object):
pass
class BannerAdmin(object):
list_display=('title','url','index')
class BaseSetting(object):
enable_themes=True
user_bootswatch=True
#设置xadmin页面标题和页脚
class GlobalSetting(objec... | [
"import xadmin\nfrom .models import EmailVerifyRecord,Banner\nfrom xadmin import views\n\nclass EmailVerifyRecordAdmin(object):\n pass\n\n\nclass BannerAdmin(object):\n list_display=('title','url','index')\n\nclass BaseSetting(object):\n enable_themes=True\n user_bootswatch=True\n#设置xadmin页面标题和页脚\nclass... | false |
1,442 | ae38995d153deed2e6049b7b65fb5f28dfcef470 | import inspect
import json
import socket
import sys
import execnet
import logging
from remoto.process import check
class BaseConnection(object):
"""
Base class for Connection objects. Provides a generic interface to execnet
for setting up the connection
"""
executable = ''
remote_import_system... | [
"import inspect\nimport json\nimport socket\nimport sys\nimport execnet\nimport logging\nfrom remoto.process import check\n\n\nclass BaseConnection(object):\n \"\"\"\n Base class for Connection objects. Provides a generic interface to execnet\n for setting up the connection\n \"\"\"\n executable = ''... | false |
1,443 | 55c9fe8caf1983f22d5a752574f590fa129e8017 | def pin():
print('wqeqwwqe')
from tkinter import *
from tkinter import messagebox
from PIL import Image
from PIL import ImageTk
window = Tk() #创建一个窗口
window.title('爱你吆') #定义窗口标题
window.geometry('400x400+800+200') #定义窗口大小 窗口显示位置
# window.protocol('WM_DELETE_WINDOW', pin) #摧毁窗口,引到另一个函数命令
window.protocol(... | [
"def pin():\n print('wqeqwwqe')\n\n\n\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom PIL import Image\nfrom PIL import ImageTk\nwindow = Tk() #创建一个窗口\nwindow.title('爱你吆') #定义窗口标题\nwindow.geometry('400x400+800+200') #定义窗口大小 窗口显示位置\n# window.protocol('WM_DELETE_WINDOW', pin) #摧毁窗口,引到另一个函数命令... | false |
1,444 | 11045cffc6d47902be7236e1d684422317f2c5f9 | """ Interfaces to Juju API ModelManager """
from conjureup import juju
@juju.requires_login
def list_models(user='user-admin'):
""" Lists Juju Models
Arguments:
user: Name of user to list models for.
Returns:
Dictionary of known Juju Models (default: user-admin)
"""
models = juju.CLIENT... | [
"\"\"\" Interfaces to Juju API ModelManager \"\"\"\n\nfrom conjureup import juju\n\n\n@juju.requires_login\ndef list_models(user='user-admin'):\n \"\"\" Lists Juju Models\n\n Arguments:\n user: Name of user to list models for.\n\n Returns:\n Dictionary of known Juju Models (default: user-admin)\n ... | false |
1,445 | 7af0566161c909457d40d3856434f1fb1e800aab | import math
import datetime as dt
import cv2
import os
from face import Face
class Video:
def __init__(self, vidSource, variableList=[], showWindow=True):
self.vidcap = cv2.VideoCapture(vidSource)
self.cascade = cv2.CascadeClassifier("face_cascade2.xml")
self.visibleFaceList = [] # contains all Face objects wi... | [
"import math\nimport datetime as dt\nimport cv2\nimport os\nfrom face import Face\n\nclass Video:\n\tdef __init__(self, vidSource, variableList=[], showWindow=True):\n\t\tself.vidcap = cv2.VideoCapture(vidSource)\n\t\tself.cascade = cv2.CascadeClassifier(\"face_cascade2.xml\")\n\t\tself.visibleFaceList = []\t\t# co... | true |
1,446 | aea196566bbbe9d37bf03b9b17a4062659a27bb6 | import unittest
from common.ReqLogin import req
import os
import yaml
from common import util
from TestCase.runnerBase import TestInterfaceCase
import paramunittest
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p)
)
def getYam(homeyaml):
try:
with open(homeyaml, encoding='ut... | [
"import unittest\nfrom common.ReqLogin import req\nimport os\nimport yaml\nfrom common import util\nfrom TestCase.runnerBase import TestInterfaceCase\nimport paramunittest\n\nPATH = lambda p: os.path.abspath(\n os.path.join(os.path.dirname(__file__), p)\n)\ndef getYam(homeyaml):\n try:\n with open(home... | false |
1,447 | c2cf74893c7f7515a95141bb10be6a446b45a0cc | import os
import time
#if __name__ == "__main__":
# os.system('xterm -e "pwd ; cd ~ ; torcs -r ~/quickrace.xml ; echo press RETURN to close this window ; read" &') # delete the echo and the read to don't stop the process and make it run quickly
# os.system('xterm -e "pwd ; ./start.sh ; echo press RETURN to close... | [
"import os\nimport time\n#if __name__ == \"__main__\":\n# os.system('xterm -e \"pwd ; cd ~ ; torcs -r ~/quickrace.xml ; echo press RETURN to close this window ; read\" &') # delete the echo and the read to don't stop the process and make it run quickly\n# os.system('xterm -e \"pwd ; ./start.sh ; echo press R... | false |
1,448 | 65da68d33aa382ed6deeff3c66a063ee299c2567 | a=[1,2,3,4,5]
max=0
for i in a:
if i>=max:
max=i
elif i<=min:
min=i
print max
print min
| [
"a=[1,2,3,4,5]\nmax=0\nfor i in a:\n\tif i>=max:\n\t\tmax=i\n\telif i<=min:\n\t\tmin=i\nprint max\nprint min\n\n"
] | true |
1,449 | d6f8ec0fd8be0fa7019a84af47d08ab8b5b32d92 | """Resolwe collection serializer."""
import logging
from rest_framework import serializers
from resolwe.flow.models import Collection, Data, DescriptorSchema
from resolwe.rest.fields import ProjectableJSONField
from .base import ResolweBaseSerializer
from .descriptor import DescriptorSchemaSerializer
from .fields im... | [
"\"\"\"Resolwe collection serializer.\"\"\"\nimport logging\n\nfrom rest_framework import serializers\n\nfrom resolwe.flow.models import Collection, Data, DescriptorSchema\nfrom resolwe.rest.fields import ProjectableJSONField\n\nfrom .base import ResolweBaseSerializer\nfrom .descriptor import DescriptorSchemaSerial... | false |
1,450 | 80c3d9165c1b592122fabf6382e265465604989c | from flask_restful import Api, Resource, reqparse
class HelloApiHandler(Resource):
def get(self):
return {
'resultStatus': 'SUCCESS',
'message': "Hello Api Handler"
}
def post(self):
print(self)
parser = reqparse.RequestParser()
parser.add_argument('type', type=str)
parser.ad... | [
"from flask_restful import Api, Resource, reqparse\n\nclass HelloApiHandler(Resource):\n def get(self):\n return {\n 'resultStatus': 'SUCCESS',\n 'message': \"Hello Api Handler\"\n }\n\n def post(self):\n print(self)\n parser = reqparse.RequestParser()\n parser.add_argument('type', type... | false |
1,451 | ed3fbae19c88100690dd5c558c0dc6d36a4849c8 | '''
Author: Iris Peng. Date: Feb 21, 2016
Usage: Scrape Weibo posts from Zhongsou for the first time for a query
In the terminal, type
$ python3 scrape_weibo.py
and follow the prompts
'''
import requests
from bs4 import BeautifulSoup
from pandas import DataFrame
import time
import pandas
import glob, os
global QUE... | [
"'''\nAuthor: Iris Peng. Date: Feb 21, 2016\nUsage: Scrape Weibo posts from Zhongsou for the first time for a query\n\nIn the terminal, type\n$ python3 scrape_weibo.py\n\nand follow the prompts\n\n'''\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pandas import DataFrame\nimport time\nimport pandas\nimport g... | false |
1,452 | feb912ac899208618f00c894458c1fda7a402652 | from collections import deque
n = -1
D = [(-1 , 0) , (0 , 1) , (1 , 0) , (0 , -1)]
B = -1
up = 0
right = 1
down = 2
left = 3
dic = {}
dic[0] = 'up'
dic[1] = 'right'
dic[2] = 'down'
dic[3] = 'left'
def possi(y , x):
global n
if y < 0 or y >= n or x < 0 or x >= n or B[y][x]:
return False
return True
... | [
"from collections import deque\nn = -1\nD = [(-1 , 0) , (0 , 1) , (1 , 0) , (0 , -1)]\nB = -1\nup = 0\nright = 1\ndown = 2\nleft = 3\ndic = {}\ndic[0] = 'up'\ndic[1] = 'right'\ndic[2] = 'down'\ndic[3] = 'left'\n\ndef possi(y , x):\n global n\n if y < 0 or y >= n or x < 0 or x >= n or B[y][x]:\n return ... | false |
1,453 | efc0b8f1c4887810a9c85e34957d664b01c1e92e | N = int(input("ingrese el numero de datos a ingresar "))
SP = 0
SO = 0
CP = 0
for i in range(1,N+1,1):
NUM = int(input("ingrese un numero entero "))
if NUM > 0:
SP += NUM
CP += 1
else:
SO += NUM
PG = (SP+SO)/N
PP = SP/CP
print(f"hay { CP } numeros positivos, el promedio general es de... | [
"N = int(input(\"ingrese el numero de datos a ingresar \"))\nSP = 0\nSO = 0\nCP = 0\nfor i in range(1,N+1,1):\n NUM = int(input(\"ingrese un numero entero \"))\n if NUM > 0:\n SP += NUM\n CP += 1\n else:\n SO += NUM\nPG = (SP+SO)/N\nPP = SP/CP\nprint(f\"hay { CP } numeros positivos, el... | false |
1,454 | 3240a7fb9fbd5cd84165e68f8406e0a146c2b6b6 | #!/usr/bin/python
# coding:utf-8
#
#这个脚本主要是对apache日志文件的处理分析,过滤出需要的信息
#处理后得到的数据是: 主机IP:192.168.14.44 访问流量:814 K
#使用说明 python 脚本名 文件名; eg:python python.analysis.apachelog.py access.log
#
# by wangdd 2016/02/02
#
import os
import re
import sys
import shelve
#re 模块,利用re模块对apahce日志进行分析
#通过 re.match(……) 和 re.compile(……... | [
"#!/usr/bin/python\n# coding:utf-8\n#\n#这个脚本主要是对apache日志文件的处理分析,过滤出需要的信息\n#处理后得到的数据是:\t主机IP:192.168.14.44 访问流量:814 K\n#使用说明 python 脚本名 文件名; eg:python python.analysis.apachelog.py access.log\n#\n#\tby wangdd 2016/02/02\n#\nimport os\nimport re\nimport sys\nimport shelve\n\n#re 模块,利用re模块对apahce日志进行分析\n#通过 re.mat... | true |
1,455 | 3ffbef142d8fb53b734567ebea874f9c59ff9a9e | num1 = 101
num2 = 20
add = num1 + num2
sub = num1 - num2
mul = num1 * num2
div = num1 / num2
mod = num1 % num2
exp = num1 ** num2
fd = num1 // num2
print(num1)
print(num2)
print(add)
print(sub)
print(mul)
print(div)
print(mod)
print(exp)
print(fd) | [
"num1 = 101\nnum2 = 20\n\nadd = num1 + num2\nsub = num1 - num2\nmul = num1 * num2\ndiv = num1 / num2\n\nmod = num1 % num2\nexp = num1 ** num2\nfd = num1 // num2\n\nprint(num1)\nprint(num2)\nprint(add)\nprint(sub)\nprint(mul)\nprint(div)\nprint(mod)\nprint(exp)\nprint(fd)",
"num1 = 101\nnum2 = 20\nadd = num1 + num... | false |
1,456 | 4d4f7db6d5b4ed7eac3ced73aca76d3c952c84f4 | from day19.rules import Rule, CharacterMatch, OrRule, ListRule
def parse_rule(rules: dict, rule_str: str = None) -> Rule:
if rule_str is None:
rule_str: str = rules[0]
if '"' in rule_str:
return CharacterMatch(rule_str.strip('"'))
elif '|' in rule_str:
or_rules = [
par... | [
"from day19.rules import Rule, CharacterMatch, OrRule, ListRule\n\n\ndef parse_rule(rules: dict, rule_str: str = None) -> Rule:\n if rule_str is None:\n rule_str: str = rules[0]\n\n if '\"' in rule_str:\n return CharacterMatch(rule_str.strip('\"'))\n elif '|' in rule_str:\n or_rules = ... | false |
1,457 | 92dea316889192824c353002670cdcf03dfbcd4c | #Question:
"""
The parcel section of the Head Post Office is in a mess. The parcels that need to be loaded to the vans have been lined up in a row in an arbitrary order of weights. The Head Post Master wants them to be sorted in the increasing order of the weights of the parcels, with one exception. He wants the heavi... | [
"#Question:\n\n\"\"\"\nThe parcel section of the Head Post Office is in a mess. The parcels that need to be loaded to the vans have been lined up in a row in an arbitrary order of weights. The Head Post Master wants them to be sorted in the increasing order of the weights of the parcels, with one exception. He want... | false |
1,458 | e9c81be79d9107433e00182c27488e64f1ca779f | #!/usr/bin/env python
# coding=utf-8
from django.core.management.base import BaseCommand
from BanBanTong.utils import task_scheduler
class Command(BaseCommand):
'''
启动BanBanTong.tasks定时任务
'''
def handle(self, *args, **options):
task_scheduler.start()
| [
"#!/usr/bin/env python\n# coding=utf-8\nfrom django.core.management.base import BaseCommand\nfrom BanBanTong.utils import task_scheduler\n\n\nclass Command(BaseCommand):\n '''\n 启动BanBanTong.tasks定时任务\n '''\n\n def handle(self, *args, **options):\n task_scheduler.start()\n",
"from django.co... | false |
1,459 | d437d77d5a57a6f2f4a2d530be05c3845dce93bc | from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from .models import Flight, Passenger, Reservation
from .serializers import FlightSerializer, Passenger... | [
"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.permissions import IsAuthenticated\nfrom .models import Flight, Passenger, Reservation\nfrom .serializers import FlightSerializer... | false |
1,460 | 2cc9f8c476026311456857d3395a14a45e2f4b80 | import argparse
p = argparse.ArgumentParser()
p.add_argument("--foo", action="store_true")
args = p.parse_args()
print(args.foo)
| [
"import argparse\n\np = argparse.ArgumentParser()\np.add_argument(\"--foo\", action=\"store_true\")\nargs = p.parse_args()\nprint(args.foo)\n",
"import argparse\np = argparse.ArgumentParser()\np.add_argument('--foo', action='store_true')\nargs = p.parse_args()\nprint(args.foo)\n",
"<import token>\np = argparse.... | false |
1,461 | 0d9c50e55df5aa5614bd5a9679729cf7fa69c5df | #!/usr/bin/python3
"""takes in a URL and an email address, sends a POST request to the passed
URL with the email as a parameter, and finally
displays the body of the response.
"""
import requests
import sys
if __name__ == "__main__":
url_arg = sys.argv[1]
email = sys.argv[2]
params = {'email': email}
... | [
"#!/usr/bin/python3\n\"\"\"takes in a URL and an email address, sends a POST request to the passed\nURL with the email as a parameter, and finally\ndisplays the body of the response.\n\"\"\"\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n url_arg = sys.argv[1]\n email = sys.argv[2]\n param... | false |
1,462 | 38c21fb959d8b98b616006ea48bd720cc6f9995c | # Generated by Django 2.0 on 2018-03-06 16:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('digressions', '0004_auto_20180303_1158'),
]
operations = [
migrations.RemoveField(
model_name='ex... | [
"# Generated by Django 2.0 on 2018-03-06 16:21\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('digressions', '0004_auto_20180303_1158'),\n ]\n\n operations = [\n migrations.RemoveField(\n ... | false |
1,463 | 760a62a94347171eb9e40015c0c43d72df8f4fc8 | from unv.app.base import Application
def multiply():
print('multiply', 2 * 2)
def setup(app: Application):
app.register_run_task(multiply)
| [
"from unv.app.base import Application\n\n\ndef multiply():\n print('multiply', 2 * 2)\n\n\ndef setup(app: Application):\n app.register_run_task(multiply)\n",
"<import token>\n\n\ndef multiply():\n print('multiply', 2 * 2)\n\n\ndef setup(app: Application):\n app.register_run_task(multiply)\n",
"<impo... | false |
1,464 | d0a73385db0dd6f729d267095ef83b9fec72e40c | """product_ingredient unique constraint
Revision ID: a07768b0d4c0
Revises: a80cd9a35e58
Create Date: 2017-05-18 11:39:52.258266
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a07768b0d4c0'
down_revision = 'a80cd9a35e58'
branch_labels = None
depends_on = None
... | [
"\"\"\"product_ingredient unique constraint\n\nRevision ID: a07768b0d4c0\nRevises: a80cd9a35e58\nCreate Date: 2017-05-18 11:39:52.258266\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a07768b0d4c0'\ndown_revision = 'a80cd9a35e58'\nbranch_labels ... | false |
1,465 | ddabceb223f4e457a0f69af5abf793ae72e5f432 | ## PURPOSE: get reads for certain motifs across certain tumors
## INPUT: manifest data all-tumor-manifest.csv
## collapsed fastq files sample.converted.unpaired.fastq.collapsed
## OUTPUT: table containing reads for specific motif across samples motif.tumor.common.reads.fastq.collapsed.summary.tsv
import... | [
"## PURPOSE: get reads for certain motifs across certain tumors\n## INPUT: manifest data \t\t\t\t\t\t\t all-tumor-manifest.csv\n## \t\t collapsed fastq files \tsample.converted.unpaired.fastq.collapsed\n## OUTPUT: table containing reads for specific motif across samples \tmotif.tumor.common.reads.fastq.collapsed... | false |
1,466 | e2feb12b88babbbfa4cc8447c91e8a5b6c30f78b | #coding=utf-8
# ycat 2017-10-20 create
# AGV的控制
import sys,os
import json
import setup
if __name__ == '__main__':
setup.setCurPath(__file__)
import utility
import enhance
import threading
import time
import log
import re
import lock
import json_codec
import driver.agv.hdcAgvApi as api
g_threads =[]
g_carts = No... | [
"#coding=utf-8\n# ycat\t\t\t2017-10-20\t create\n# AGV的控制 \nimport sys,os \nimport json\nimport setup\nif __name__ == '__main__':\n\tsetup.setCurPath(__file__)\nimport utility\nimport enhance\t\nimport threading\nimport time\nimport log\nimport re\nimport lock\nimport json_codec\nimport driver.agv.hdcAgvApi as api... | false |
1,467 | fcca845b60b050fa5dd0a3c50b3c36c154022f07 | """
题目描述
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。
今天测试组开完会后,他又发话了:在古老的一维模式识别中,
常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。
但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?
例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。
给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
"""
# -*- coding:utf-8 -*-
class Solution:
def FindGreatestSumOfSubArray(self, ar... | [
"\"\"\"\n题目描述\nHZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。\n今天测试组开完会后,他又发话了:在古老的一维模式识别中,\n常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。\n但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?\n例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。\n给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)\n\"\"\"\n# -*- coding:utf-8 -*-\nclass Solution:\n def FindGreatest... | false |
1,468 | 997b68e42547b8f8a1059776c55c3ad16df494da | ii = [('LeakWTI2.py', 6)] | [
"ii = [('LeakWTI2.py', 6)]",
"ii = [('LeakWTI2.py', 6)]\n",
"<assignment token>\n"
] | false |
1,469 | e675283f14a3d29fba878e7f6d9592130611c2be | import sqlite3
import hashlib
users = []
class UserModel:
id = 0
def __init__(self, name, password, birth, sex, phone, email, id=0):
if(id == 0):
self.id = self.id + 1
else:
self.id = id
self.name = name
self.email = email
#處理密碼
s = has... | [
"import sqlite3\nimport hashlib\n\nusers = []\n\nclass UserModel:\n id = 0\n\n def __init__(self, name, password, birth, sex, phone, email, id=0):\n if(id == 0):\n self.id = self.id + 1\n else:\n self.id = id\n self.name = name\n self.email = email\n\n ... | false |
1,470 | e056a1600b620519e729c597dcec57793284019a | # -*- coding: utf-8 -*-
from flask import Blueprint, render_template, redirect, url_for, flash
import subprocess
def check_output(*args):
return subprocess.Popen(*args, stdout=subprocess.PIPE).communicate()[0]
mod = Blueprint('system', __name__)
@mod.route('/')
def index():
uptime = check_output(["uptime"])
... | [
"# -*- coding: utf-8 -*-\nfrom flask import Blueprint, render_template, redirect, url_for, flash\nimport subprocess\n\ndef check_output(*args):\n return subprocess.Popen(*args, stdout=subprocess.PIPE).communicate()[0]\n\nmod = Blueprint('system', __name__)\n\n@mod.route('/')\ndef index():\n uptime = check_out... | false |
1,471 | 4d30f4294a9f3aab8cae20dca9d280c53b37ed25 | num = int(input())
bull_str = input().split(' ')
bull_list = []
for i in range(len(bull_list)):
bull_list.append(int(bull_str[i]))
flag = 0
while True:
flag += 1
for i in range(len(bull_list)):
if bull_list[i] == 1:
for j in range(bull_list.index(bull_list[i]), len(bull_list)):
... | [
"num = int(input())\nbull_str = input().split(' ')\nbull_list = []\nfor i in range(len(bull_list)):\n bull_list.append(int(bull_str[i]))\n\nflag = 0\nwhile True:\n flag += 1\n for i in range(len(bull_list)):\n if bull_list[i] == 1:\n for j in range(bull_list.index(bull_list[i]), len(bull_... | false |
1,472 | d4d47f7abc5c8224188430546a65bfb8f358802f | """
purpose :Take an string as input and construct an algorithm
to input a string of characters and check whether
it is a palindrome.
@Author : Reshma Y. Kale
"""
from com.bridgelabz.utility.Data_structure_utility import *
if __name__=="__main__":
dq = Deque()
dq.palindrom() | [
"\"\"\"\npurpose :Take an string as input and construct an algorithm\n to input a string of characters and check whether\n it is a palindrome.\n\n@Author : Reshma Y. Kale\n\n\"\"\"\nfrom com.bridgelabz.utility.Data_structure_utility import *\nif __name__==\"__main__\":\n\n dq = Deque()\n... | false |
1,473 | ae1aab7563443db3a31fe98b5b26b32944d57c9d | from unittest import TestCase
from tests import AuthHelperTestCase
class TestTestHelper(TestCase):
"""
Test our helper functions
"""
def test_assertAnyIn_fails(self):
"""
Make sure assertInAny fails correctly
:return:
"""
test_case = AuthHelperTestCase('asse... | [
"from unittest import TestCase\n\nfrom tests import AuthHelperTestCase\n\n\nclass TestTestHelper(TestCase):\n \"\"\"\n Test our helper functions\n \"\"\"\n\n def test_assertAnyIn_fails(self):\n \"\"\"\n Make sure assertInAny fails correctly\n\n :return: \n \"\"\"\n tes... | false |
1,474 | f9a255a464b5f48a1a8be2e2887db721a92e7f4e | import unittest
import json
import os
import copy
from nested.nested_dict import NestedDict
from pprint import pprint
class TestNestedDict(unittest.TestCase):
@classmethod
def setUpClass(cls):
path = os.path.dirname(__file__)
cls.afile = os.path.join(path, '../nested/data/food_nested_dict.jso... | [
"import unittest\nimport json\nimport os\nimport copy\nfrom nested.nested_dict import NestedDict\nfrom pprint import pprint\n\n\nclass TestNestedDict(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n path = os.path.dirname(__file__)\n cls.afile = os.path.join(path, '../nested/data/fo... | false |
1,475 | 021efe01c21db4d3bd936ba4eb75dc03dde91cc6 | from applitools.selenium import Target, eyes
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
def test_verify_home_page(eyes, driver):
eyes.open(driver, "FlyDubai IBE", "Verify Home Page")
eye... | [
"from applitools.selenium import Target, eyes\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n \ndef test_verify_home_page(eyes, driver):\n eyes.open(driver, \"FlyDubai IBE\", \"Verify Home ... | false |
1,476 | 22aa6042b77c3cfd1f102a0ea22a43223e366d2f | import re, glob, os
lst = []
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
#title = title[22:]
#hexa = []
#hexb = []
hexa = title[:2]
hexb = title... | [
"import re, glob, os\nlst = []\ndef rename(dir, pattern, titlePattern):\n for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):\n title, ext = os.path.splitext(os.path.basename(pathAndFilename))\n #title = title[22:]\n #hexa = []\n #hexb = []\n hexa = title[:2]\n ... | false |
1,477 | e4b6304be10ee5a741c8a193dcf65950299ef11a | import logging
from random import randint
import pygame
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
from playsound import playsound
app = Flask(__name__)
ask = Ask(app, "/")
logging.getLogger("flask_ask").setLevel(logging.DEBUG)
@ask.launch
def new_game():
p... | [
"import logging\n\nfrom random import randint\nimport pygame\n\nfrom flask import Flask, render_template\nfrom flask_ask import Ask, statement, question, session\nfrom playsound import playsound\n\napp = Flask(__name__)\nask = Ask(app, \"/\")\nlogging.getLogger(\"flask_ask\").setLevel(logging.DEBUG)\n\n\n@ask.launc... | false |
1,478 | 5ac489a2d30155bb92767184ad546247817e28ea | """
Create a list of words and with it, create a new dictionary
in which the key is the word and the value is the same word
reversed.
"""
word_list = ['Tree','Apple','Snake','flowers']
word_dict = {word:word[::-1] for word in word_list}
print(word_dict)
#Output: {'Tree': 'eerT', 'Apple': 'elppA', 'Snake': 'ekanS', 'fl... | [
"\"\"\"\nCreate a list of words and with it, create a new dictionary\nin which the key is the word and the value is the same word\nreversed.\n\"\"\"\n\nword_list = ['Tree','Apple','Snake','flowers']\nword_dict = {word:word[::-1] for word in word_list}\nprint(word_dict)\n#Output: {'Tree': 'eerT', 'Apple': 'elppA', '... | false |
1,479 | a5a7cd112faad1096ce4c6f04b2179fbdf732702 | from setuptools import setup, find_packages
setup(
packages=find_packages(),
setup_requires=["flask"],
name="mith1",
) | [
"from setuptools import setup, find_packages\nsetup(\n packages=find_packages(),\n setup_requires=[\"flask\"],\n name=\"mith1\",\n)",
"from setuptools import setup, find_packages\nsetup(packages=find_packages(), setup_requires=['flask'], name='mith1')\n",
"<import token>\nsetup(packages=find_packages()... | false |
1,480 | 594479c22cada665dcdc76737085ce342d7d5faf | # program name: an2_colour.py
# no optional arguments: Uses Wine data to display information about the relationship of
# various attributes with colour and hue
print('========================================================================================')
print('===================================================... | [
"# program name: an2_colour.py\n\n# no optional arguments: Uses Wine data to display information about the relationship of \n# various attributes with colour and hue \n\nprint('========================================================================================')\nprint('========================================... | false |
1,481 | b2cfd397e48213a540608fc232db2eab282935bb | # 总管buffer和policy
from os import path
import torch
import torch.nn as nn
import torch.optim as optim
import torch.distributions as distributions
import numpy as np
from torch.serialization import load
import global_var as gv
torch.set_default_dtype(gv.torch_default_type)
class PG_Agent(object):
def __init__(
... | [
"# 总管buffer和policy\n\n\n\nfrom os import path\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.distributions as distributions\nimport numpy as np\nfrom torch.serialization import load\n\nimport global_var as gv\n\ntorch.set_default_dtype(gv.torch_default_type)\n\nclass PG_Agent(object... | false |
1,482 | f644ff322d1268092dbdcbfc1a3c76006424184b | import unittest
from game_of_life.board import Board
from game_of_life.cell import Cell, ALIVE, DEAD
def create_test_board(size):
board = Board(size)
board[0, 0].state = ALIVE
board[0, 1].state = ALIVE
board[2, 1].state = ALIVE
return board
class BoardTests(unittest.TestCase):
def test_get_n... | [
"import unittest\nfrom game_of_life.board import Board\nfrom game_of_life.cell import Cell, ALIVE, DEAD\n\n\ndef create_test_board(size):\n board = Board(size)\n board[0, 0].state = ALIVE\n board[0, 1].state = ALIVE\n board[2, 1].state = ALIVE\n return board\n\n\nclass BoardTests(unittest.TestCase):\... | false |
1,483 | 3461e9dceb2c0bfc49002809154f8be4cd8c66e2 | import dataset
import json
import gc
import os
jsonDir = "/home/jr/share/python/music-visualizer/merged"
db = dataset.connect('sqlite:///test.db')
table = db['Songs']
for root, subFolders, files in os.walk(jsonDir):
for f in files:
print("file:{}".format(f))
gc.collect()
tmpJson = json.lo... | [
"import dataset\nimport json\nimport gc\nimport os\n\njsonDir = \"/home/jr/share/python/music-visualizer/merged\"\n\ndb = dataset.connect('sqlite:///test.db')\ntable = db['Songs']\n\nfor root, subFolders, files in os.walk(jsonDir):\n for f in files:\n print(\"file:{}\".format(f))\n gc.collect()\n ... | true |
1,484 | af02cd0778e19df7b11145c4863776a1afd1cca6 | """ Implements BCFW for DIFFRAC objectives. """
import numpy as np
import os
from tqdm import tqdm
from numpy.linalg import norm as matrix_norm
import time
def get_feat_block(feats, block_idx, memory_mode, bias_value=-1.0):
"""Get feature for a given block."""
if memory_mode == 'RAM':
feat = feats[bl... | [
"\"\"\" Implements BCFW for DIFFRAC objectives. \"\"\"\n\nimport numpy as np\nimport os\nfrom tqdm import tqdm\nfrom numpy.linalg import norm as matrix_norm\nimport time\n\n\ndef get_feat_block(feats, block_idx, memory_mode, bias_value=-1.0):\n \"\"\"Get feature for a given block.\"\"\"\n if memory_mode == 'R... | true |
1,485 | ca93f49fbdc1d64e0616bca035a6043b3cc80ddc | import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib.framework.python.ops import arg_scope
from tensorflow.contrib.layers.python.layers import initializers
from tensorflow.contrib.layers.python.layers import layers as layers_lib
from tensorflow.contrib.layers.python.layers import regula... | [
"import tensorflow as tf\nfrom tensorflow.contrib import layers\nfrom tensorflow.contrib.framework.python.ops import arg_scope\nfrom tensorflow.contrib.layers.python.layers import initializers\nfrom tensorflow.contrib.layers.python.layers import layers as layers_lib\nfrom tensorflow.contrib.layers.python.layers imp... | false |
1,486 | 5c174dd514d0a7d9aa932fcb436f22d9a44d2327 | '''
Aluno: Lucas Airam Castro de Souza
Resumo: Programa para calcular a raiz com a precisão n de casas decimais
def raiz(numero, casas_decimais=0):
if ((numero == 0) or (numero == 1)):
return "O resultado eh: " + str(numero)
elif (numero<0):
return "A raiz nao existe no conjunto rea... | [
"'''\r\n\r\nAluno: Lucas Airam Castro de Souza\r\nResumo: Programa para calcular a raiz com a precisão n de casas decimais\r\n\r\n\r\ndef raiz(numero, casas_decimais=0):\r\n if ((numero == 0) or (numero == 1)):\r\n return \"O resultado eh: \" + str(numero)\r\n elif (numero<0):\r\n return \"A rai... | false |
1,487 | dbc3e51fed63fe0fadea67d05c4b4efc693938a3 | test_case = int(input())
while test_case != 0:
test_case -= 1
(n, m) = map(int, input().split())
ans = n * m
A = []
for i in range(n):
t = list(map(int, input().split()))
A.append(t)
for i in range(1, n - 1):
for j in range(1, m - 1):
k = 1
while ... | [
"test_case = int(input())\nwhile test_case != 0:\n test_case -= 1\n (n, m) = map(int, input().split())\n ans = n * m\n A = []\n for i in range(n):\n t = list(map(int, input().split()))\n A.append(t)\n\n for i in range(1, n - 1):\n for j in range(1, m - 1):\n k = 1\n... | false |
1,488 | c9f3e956d4016846c8efe0382b79882559d6ce64 | x, y = map(int, input().split())
print(max((y - x + 9) // 10, 0)) | [
"x, y = map(int, input().split())\nprint(max((y - x + 9) // 10, 0))",
"x, y = map(int, input().split())\nprint(max((y - x + 9) // 10, 0))\n",
"<assignment token>\nprint(max((y - x + 9) // 10, 0))\n",
"<assignment token>\n<code token>\n"
] | false |
1,489 | ba54b3a148a34ced74a337665ddd5f2d9084553b | """
This file goes through the data to find the frequencies of words in the corpus
"""
import csv
import time, datetime
import calendar
from collections import defaultdict
import chardet
import re
REVIEW_ID_COL = 0;
USER_ID_COL = 1
BUSINESS_ID_COL = 2
STARS_COL = 3
DATE_COL = 4
TEXT_COL = 5
USEFUL_CO... | [
"\"\"\"\r\nThis file goes through the data to find the frequencies of words in the corpus\r\n\"\"\"\r\n\r\nimport csv\r\nimport time, datetime\r\nimport calendar\r\nfrom collections import defaultdict\r\nimport chardet\r\nimport re\r\n\r\nREVIEW_ID_COL = 0;\r\nUSER_ID_COL = 1\r\nBUSINESS_ID_COL = 2\r\nSTARS_COL = 3... | false |
1,490 | 46d85a3babab4b18f4e0e0384f254f6105cf691d | """
Remove tool_consumer_info_product_family_code from GradingInfo.
Revision ID: 106d94be7705
Revises: 973c9358b616
Create Date: 2023-07-06 11:23:10.850486
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "106d94be7705"
down_revision = "973c9358b616"
def upgrad... | [
"\"\"\"\nRemove tool_consumer_info_product_family_code from GradingInfo.\n\nRevision ID: 106d94be7705\nRevises: 973c9358b616\nCreate Date: 2023-07-06 11:23:10.850486\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"106d94be7705\"\ndown_revision = \... | false |
1,491 | 51642dbb210600f9ca4e035fb884fbdda030fd04 | _registry = []
def registry(name):
_registry.append(name)
def registry_names():
return iter(_registry)
| [
"_registry = []\n\n\ndef registry(name):\n _registry.append(name)\n\n\ndef registry_names():\n return iter(_registry)\n",
"<assignment token>\n\n\ndef registry(name):\n _registry.append(name)\n\n\ndef registry_names():\n return iter(_registry)\n",
"<assignment token>\n\n\ndef registry(name):\n _r... | false |
1,492 | 5b919bde9f4fe1da867695ece58f151abb9b70fb | import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense,Activation,Dropout
from keras.optimizers import SGD,Adam,RMSprop
from keras.utils import np_utils
x_train=n... | [
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import KFold\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense,Activation,Dropout\nfrom keras.optimizers import SGD,Adam,RMSprop\nfrom keras.utils import np_util... | true |
1,493 | ac5c4edda8a5df7abc030fd637866fa4c8fc4bfc | # coding=utf-8
from django.test import TestCase
from django_mptt_admin.util import get_tree_queryset, get_javascript_value
from ..models import Country
from .utils import read_testdata
class UtilTestCase(TestCase):
def setUp(self):
super(UtilTestCase, self).setUp()
read_testdata()
def tes... | [
"# coding=utf-8\nfrom django.test import TestCase\n\nfrom django_mptt_admin.util import get_tree_queryset, get_javascript_value\n\nfrom ..models import Country\n\nfrom .utils import read_testdata\n\n\nclass UtilTestCase(TestCase):\n def setUp(self):\n super(UtilTestCase, self).setUp()\n\n read_test... | false |
1,494 | 08420d31713859946b2f19cebf68c333331cb80e | '''OpenGL extension EXT.YUV_target
This module customises the behaviour of the
OpenGL.raw.GLES2.EXT.YUV_target to provide a more
Python-friendly API
Overview (from the spec)
This extension adds support for three new YUV related items: first
rendering to YUV images, second sampling from YUV images while keeping ... | [
"'''OpenGL extension EXT.YUV_target\n\nThis module customises the behaviour of the \nOpenGL.raw.GLES2.EXT.YUV_target to provide a more \nPython-friendly API\n\nOverview (from the spec)\n\t\n\tThis extension adds support for three new YUV related items: first\n\trendering to YUV images, second sampling from YUV imag... | false |
1,495 | e4422010337eade12226d84c79532cdbcae68d67 | from rest_framework import serializers
from issue.models import Issue
class IssueSerializer(serializers.ModelSerializer):
"""DRF Serializer For Listing Published Issue"""
class Meta:
model = Issue
fields = ['issueName', 'website', 'issueBody', 'impact', 'published_on']
class IssueCreateSer... | [
"from rest_framework import serializers\n\nfrom issue.models import Issue\n\n\nclass IssueSerializer(serializers.ModelSerializer):\n \"\"\"DRF Serializer For Listing Published Issue\"\"\"\n\n class Meta:\n model = Issue\n fields = ['issueName', 'website', 'issueBody', 'impact', 'published_on']\n... | false |
1,496 | 7159b447ed6fcb2005f63c7b7359970defbc9d43 | from django.db import models
from datetime import datetime
class Message(models.Model):
text = models.CharField(max_length=200)
votes = models.IntegerField()
date_added = models.DateTimeField(default=datetime.now)
score = models.BigIntegerField()
next_vote = models.IntegerField(default=3600) # 8640... | [
"from django.db import models\nfrom datetime import datetime\n\nclass Message(models.Model):\n text = models.CharField(max_length=200)\n votes = models.IntegerField()\n date_added = models.DateTimeField(default=datetime.now)\n score = models.BigIntegerField()\n next_vote = models.IntegerField(default... | false |
1,497 | 8d9f4bce998857bcc7bc2fda0b519f370bf957fe | # Identify a vowel
class MainInit(object):
def __init__(self):
self.vowel = str(input("Please type the character: \n"))
if len(self.vowel) > 1:
print("Invalid number of character")
else:
Vowel(self.vowel)
class Vowel(object):
def __init__(self, vo... | [
"# Identify a vowel\r\n\r\n\r\nclass MainInit(object):\r\n def __init__(self):\r\n self.vowel = str(input(\"Please type the character: \\n\"))\r\n if len(self.vowel) > 1:\r\n print(\"Invalid number of character\")\r\n else:\r\n Vowel(self.vowel)\r\n\r\n\r\nclass Vowel(o... | false |
1,498 | 9fea76b1612bd02f512072692090f8ef60e8a0fe | from .exenv import * | [
"from .exenv import *",
"from .exenv import *\n",
"<import token>\n"
] | false |
1,499 | bacaaf5c91232d85f451c2c17a42cd2ec6966684 | # In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
# The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
# What is the greatest product of four adjacent numbers in the same direction
# (up, down, left, right, or diagonally) in the 20×20 grid?
import numpy as np
data = np.ge... | [
"# In the 20×20 grid below, four numbers along a diagonal line have been marked in red.\n# The product of these numbers is 26 × 63 × 78 × 14 = 1788696.\n# What is the greatest product of four adjacent numbers in the same direction\n# (up, down, left, right, or diagonally) in the 20×20 grid?\n\nimport numpy as np\nd... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.