index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
8,300
cf6d3a0fbf2a2daf8432622f780e138784ec505d
import re IS_WITH_SINGLETON_REGEX = re.compile("(!=|==)\s*(True|False|None)") def check_is_with_singleton(physical_line, line_number): match_obj = IS_WITH_SINGLETON_REGEX.search(physical_line) if match_obj is not None: offset = match_obj.span()[0] return (0, 12, (line_number, offset), "Use eq...
[ "import re\n\nIS_WITH_SINGLETON_REGEX = re.compile(\"(!=|==)\\s*(True|False|None)\")\n\ndef check_is_with_singleton(physical_line, line_number):\n match_obj = IS_WITH_SINGLETON_REGEX.search(physical_line)\n\n if match_obj is not None:\n offset = match_obj.span()[0]\n return (0, 12, (line_number,...
false
8,301
f317d67b98eab1f0f192fa41f9bcc32b0c1e8eb0
# Run 'python setup.py build' on cmd import sys from cx_Freeze import setup, Executable import os.path PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 't...
[ "# Run 'python setup.py build' on cmd\r\n\r\nimport sys\r\nfrom cx_Freeze import setup, Executable\r\n\r\nimport os.path\r\nPYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))\r\nos.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')\r\nos.environ['TK_LIBRARY'] = os.path.join(P...
false
8,302
3b15767988f1d958fc456f7966f425f93deb9017
""" Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and b anagrams. Any characters can be deleted from either of the strings. """ from collections import Counter import math import os import random import re import sys # Com...
[ "\"\"\"\nGiven two strings, a and b, that may or may not be of the same length, \ndetermine the minimum number of character deletions required to make\na and b anagrams. Any characters can be deleted from either of the strings.\n\"\"\"\nfrom collections import Counter\nimport math\nimport os\nimport random\nimport ...
false
8,303
97029ac9f05037bf9304dacf86c35f5534d887c4
class Solution: def sumSubarrayMins(self, A: List[int]) -> int: stack = [] prev = [None] * len(A) for i in range(len(A)): while stack and A[stack[-1]] >= A[i]: stack.pop() prev[i] = stack[-1] if stack else -1 stack.append(i) stack =...
[ "class Solution:\n def sumSubarrayMins(self, A: List[int]) -> int:\n stack = []\n prev = [None] * len(A)\n for i in range(len(A)):\n while stack and A[stack[-1]] >= A[i]:\n stack.pop()\n prev[i] = stack[-1] if stack else -1\n stack.append(i)\n ...
false
8,304
56d5915d30e85285da549cc69ef25714bacc6f3a
from .alexnet import * from .lenet import * from .net import * from .vae import *
[ "from .alexnet import *\nfrom .lenet import *\nfrom .net import *\nfrom .vae import *", "from .alexnet import *\nfrom .lenet import *\nfrom .net import *\nfrom .vae import *\n", "<import token>\n" ]
false
8,305
09420360ddcf2f74c2e130b4e09ae2a959e42e50
class Solution: def uncommonFromSentences(self, A: str, B: str) -> List[str]: word_count = {} A = A.split() B = B.split() whole = A + B for word in whole: if word not in word_count: word_count[word] = 1 else: word_count[...
[ "class Solution:\n def uncommonFromSentences(self, A: str, B: str) -> List[str]:\n word_count = {}\n A = A.split()\n B = B.split()\n whole = A + B\n for word in whole:\n if word not in word_count:\n word_count[word] = 1\n else:\n ...
false
8,306
0964121d88fad2906311de7532eac52ff784fff6
""" Main CLI endpoint for GeoCube """ import importlib.metadata import click from click import group import geocube.cli.commands as cmd_modules from geocube import show_versions CONTEXT_SETTINGS = { "help_option_names": ["-h", "--help"], "token_normalize_func": lambda x: x.replace("-", "_"), } def check_ve...
[ "\"\"\"\nMain CLI endpoint for GeoCube\n\"\"\"\nimport importlib.metadata\n\nimport click\nfrom click import group\n\nimport geocube.cli.commands as cmd_modules\nfrom geocube import show_versions\n\nCONTEXT_SETTINGS = {\n \"help_option_names\": [\"-h\", \"--help\"],\n \"token_normalize_func\": lambda x: x.rep...
false
8,307
dce7fd0c9ed8e1d433f9131a8d137c8dcca4ac56
#!/bin/python3 # TODO: implement the stack O(N) version ''' Naive: O(N^3) or sum_{k=1...N}( O(N^2 (N-K)) ) for each size N for each window of size N in the array traverse the window to find the max Naive with heap: O(N^2 log N) for each size N O(N) traverse array and accumulate window of size N O(N...
[ "#!/bin/python3\n\n# TODO: implement the stack O(N) version\n\n'''\nNaive: O(N^3) or sum_{k=1...N}( O(N^2 (N-K)) )\n for each size N\n for each window of size N in the array\n traverse the window to find the max\n\nNaive with heap: O(N^2 log N)\n for each size N O(N)\n traverse array and accumulate win...
false
8,308
758e5b9a65132c4bdee4600e79c27f9c0f272312
import pymysql import pymssql import socket import threading from time import sleep address = ('127.0.0.1', 20176) usermode = {1: 'Wangcz_Students', 2: 'Wangcz_Teachers', 3: 'Wangcz_Admin' } def checkuser(username, password, cursor, user_db): cursor.execute('''select * from %s...
[ "import pymysql\nimport pymssql\nimport socket\nimport threading\nfrom time import sleep\n\naddress = ('127.0.0.1', 20176)\nusermode = {1: 'Wangcz_Students',\n 2: 'Wangcz_Teachers',\n 3: 'Wangcz_Admin'\n }\n\ndef checkuser(username, password, cursor, user_db):\n\n cursor.execute(...
false
8,309
dc28c3426f47bef8b691a06d54713bc68696ee44
#!/usr/bin/env python3 import numpy as np import os import random import pandas as pd def read_chunk(reader, chunk_size): data = {} for i in range(chunk_size): ret = reader.read_next() for k, v in ret.items(): if k not in data: data[k] = [] data[k].appe...
[ "#!/usr/bin/env python3\n\nimport numpy as np\nimport os\nimport random\nimport pandas as pd\n\ndef read_chunk(reader, chunk_size):\n\n data = {}\n for i in range(chunk_size):\n ret = reader.read_next()\n for k, v in ret.items():\n if k not in data:\n data[k] = []\n ...
false
8,310
a5eeafef694db04770833a4063358e8f32f467b0
import os from typing import List, Optional, Sequence import boto3 from google.cloud import storage from ..globals import GLOBALS, LOGGER def set_gcs_credentials(): if os.path.exists(GLOBALS.google_application_credentials): return secrets_client = boto3.client( "secretsmanager", reg...
[ "import os\nfrom typing import List, Optional, Sequence\n\nimport boto3\nfrom google.cloud import storage\n\nfrom ..globals import GLOBALS, LOGGER\n\n\ndef set_gcs_credentials():\n if os.path.exists(GLOBALS.google_application_credentials):\n return\n\n secrets_client = boto3.client(\n \"secretsm...
false
8,311
398c28265e61831ba65b4ae2a785e57c0fa5b6d2
class Solution: def toGoatLatin(self, S: str) -> str: def exchange(str2): if str2[0] in "aeiou": str2 = str2+"ma" else: str2 = str2[1:]+str2[0]+"ma" list2 = S.split(" ") for i in list2: res.append(exchange(i)) ...
[ "\n\n\nclass Solution:\n def toGoatLatin(self, S: str) -> str:\n \n def exchange(str2):\n if str2[0] in \"aeiou\":\n str2 = str2+\"ma\"\n else:\n str2 = str2[1:]+str2[0]+\"ma\"\n\n list2 = S.split(\" \")\n\n for i in list2:\n ...
true
8,312
b16ad4bae079159da7ef88b61081d7763d4ae9a0
#!/usr/bin/env python ##!/work/local/bin/python ##!/work/local/CDAT/bin/python import sys,getopt import matplotlib.pyplot as plt def read(): x = [] y = [] for line in sys.stdin: v1,v2 = line.split()[:2] x.append(float(v1)) y.append(float(v2)) return x,y #def plot(x,y): def ...
[ "#!/usr/bin/env python\n##!/work/local/bin/python\n##!/work/local/CDAT/bin/python\n\nimport sys,getopt\nimport matplotlib.pyplot as plt\n\n\ndef read():\n\n x = []\n y = []\n for line in sys.stdin:\n v1,v2 = line.split()[:2]\n x.append(float(v1))\n y.append(float(v2))\n return x,y\n...
true
8,313
19f202c32e1cf9f7ab2663827f1f98080f70b83e
from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from linebot import LineBotApi, WebhookParser from linebot.exceptions import InvalidSignatureError, LineBotApiError from linebot.models import ...
[ "from django.conf import settings\r\nfrom django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden\r\nfrom django.views.decorators.csrf import csrf_exempt\r\n\r\nfrom linebot import LineBotApi, WebhookParser\r\nfrom linebot.exceptions import InvalidSignatureError, LineBotApiError\r\nfrom lineb...
false
8,314
fd6cf903490ff4352e4721282354a68437ecb1e0
from socket import * from multiprocessing import Process import sys ADDR = ("127.0.0.1", 8888) udp_socket = socket(AF_INET, SOCK_DGRAM) # udp_socket.bind(("0.0.0.0",6955)) # udp套接字在一段时间不链接后,会自动重新分配端口,所以需要绑定 def login(): while True: name = input("请输入昵称(不能重复)") msg = "LOGIN" + "##" + name u...
[ "from socket import *\nfrom multiprocessing import Process\nimport sys\n\nADDR = (\"127.0.0.1\", 8888)\nudp_socket = socket(AF_INET, SOCK_DGRAM)\n# udp_socket.bind((\"0.0.0.0\",6955)) # udp套接字在一段时间不链接后,会自动重新分配端口,所以需要绑定\n\n\ndef login():\n while True:\n name = input(\"请输入昵称(不能重复)\")\n msg = \"LOGIN\...
false
8,315
88445d8466d7acbf29d2525c7e322611d66494cd
import sys if sys.version_info.major == 2: from itertools import izip else: izip = zip
[ "import sys\nif sys.version_info.major == 2:\n from itertools import izip\nelse:\n izip = zip\n\n", "import sys\nif sys.version_info.major == 2:\n from itertools import izip\nelse:\n izip = zip\n", "<import token>\nif sys.version_info.major == 2:\n from itertools import izip\nelse:\n izip = zi...
false
8,316
6e07dcc3f3b8c7fbf8ce8d481b9612e7496967bd
Ylist = ['yes', 'Yes', 'Y', 'y'] Nlist = ['no', 'No', 'N', 'n'] America = ['America', 'america', 'amer', 'rica'] TRW = ['1775', 'The Revolutionary war', 'the Revolutionary war', 'the revolutionary war', 'The Revolutionary War', 'trw', 'Trw', 'TRW'] TCW = ['1861', 'The civil war', 'The civil War', 'The Civil...
[ "Ylist = ['yes', 'Yes', 'Y', 'y']\r\nNlist = ['no', 'No', 'N', 'n']\r\nAmerica = ['America', 'america', 'amer', 'rica']\r\nTRW = ['1775', 'The Revolutionary war', 'the Revolutionary war', 'the revolutionary war', 'The Revolutionary War',\r\n 'trw', 'Trw', 'TRW']\r\nTCW = ['1861', 'The civil war', 'The civil W...
false
8,317
fcd2bd91dff3193c661d71ade8039765f8498fd4
''' Created on Dec 18, 2011 @author: ppa ''' import unittest from ultrafinance.pyTaLib.indicator import Sma class testPyTaLib(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testSma(self): sma = Sma(period = 3) expectedAvgs = [1, 1.5, 2, 3, 4] ...
[ "'''\nCreated on Dec 18, 2011\n\n@author: ppa\n'''\nimport unittest\nfrom ultrafinance.pyTaLib.indicator import Sma\n\nclass testPyTaLib(unittest.TestCase):\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def testSma(self):\n sma = Sma(period = 3)\n expectedAvgs = [...
false
8,318
0699c9f70f1c16b4cb9837edf7a4ef27f021faec
def modCount(n, m): if(m <= n): inBetween = n - m dividible = [] for x in range(m+1, n): if(x%m == 0): dividible.append(x) return 'There are {} numbers between {} and {} \nand the ones that are dividible by {} are {}'.format(inBetween, m, n, m, dividib...
[ "def modCount(n, m):\n if(m <= n):\n inBetween = n - m\n dividible = []\n for x in range(m+1, n):\n if(x%m == 0):\n dividible.append(x)\n\n return 'There are {} numbers between {} and {} \\nand the ones that are dividible by {} are {}'.format(inBetween, m,...
false
8,319
81c9cabaa611f8e884708d535f0b99ff83ec1c0d
from setuptools import setup from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='SumoSound', packages=['SumoSound'], version='1.0.2', license='MIT', description='A pyt...
[ "from setuptools import setup\nfrom os import path\n\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='SumoSound',\n packages=['SumoSound'],\n version='1.0.2',\n license='MIT',\n d...
false
8,320
edf704d720abdb09d176937664c9ba98bcd253a5
message = input() vowel = 'aeiouAEIOU' consonant = 'bcdfghjklmnpqrstvwxyz' consonant += consonant.upper() vowel_count = 0 consonant_count = 0 for c in message: if c in vowel: vowel_count += 1 elif c in consonant: consonant_count += 1 print(vowel_count, consonant_count)
[ "message = input()\n\nvowel = 'aeiouAEIOU'\nconsonant = 'bcdfghjklmnpqrstvwxyz'\nconsonant += consonant.upper()\n\nvowel_count = 0\nconsonant_count = 0\n\nfor c in message:\n if c in vowel:\n vowel_count += 1\n elif c in consonant:\n consonant_count += 1\n\nprint(vowel_count, consonant_count)\n"...
false
8,321
ad9bb34fdb05ab885f4871693729449f3618603a
#Script to extract features from chess score data file stockfish.csv import numpy as np import pandas as pd #Load in and format raw chess game scoring data raw_scores = [line.strip().split(",")[1].split() for line in open("stockfish.csv")][1:] #Initialize containers for features to extract game_length = [] average_sc...
[ "#Script to extract features from chess score data file stockfish.csv\nimport numpy as np\nimport pandas as pd\n\n#Load in and format raw chess game scoring data\nraw_scores = [line.strip().split(\",\")[1].split() for line in open(\"stockfish.csv\")][1:]\n\n#Initialize containers for features to extract\ngame_lengt...
false
8,322
45dc9d362a2ddfd408f93452bda0b7338057ca81
from django.db import models from django.utils import timezone from pprint import pprint class Cast(models.Model): name = models.CharField(max_length=50, blank=True, null=True) image = models.ImageField(upload_to='cast', blank=True, null=True) description = models.CharField(max_length=400, blank=True, null...
[ "from django.db import models\nfrom django.utils import timezone\nfrom pprint import pprint\n\nclass Cast(models.Model):\n name = models.CharField(max_length=50, blank=True, null=True)\n image = models.ImageField(upload_to='cast', blank=True, null=True)\n description = models.CharField(max_length=400, blan...
false
8,323
19221823f14cf06a55d445fc241fc04e64e5873c
# This is the template file for Lab #5, Task #1 import numpy import lab5 def digitize(samples,threshold): return 1*(samples > threshold) class ViterbiDecoder: # given the constraint length and a list of parity generator # functions, do the initial set up for the decoder. The # following useful instance ...
[ "# This is the template file for Lab #5, Task #1\nimport numpy\nimport lab5\n\ndef digitize(samples,threshold):\n\treturn 1*(samples > threshold)\n\nclass ViterbiDecoder:\n # given the constraint length and a list of parity generator\n # functions, do the initial set up for the decoder. The\n # following ...
true
8,324
32227029cb4e852536611f7ae5dec5118bd5e195
# SPDX-License-Identifier: Apache-2.0 """ .. _example-lightgbm-pipe: Convert a pipeline with a LightGbm model ======================================== .. index:: LightGbm *sklearn-onnx* only converts *scikit-learn* models into *ONNX* but many libraries implement *scikit-learn* API so that their models can be inclu...
[ "# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"\n.. _example-lightgbm-pipe:\n\nConvert a pipeline with a LightGbm model\n========================================\n\n.. index:: LightGbm\n\n*sklearn-onnx* only converts *scikit-learn* models into *ONNX*\nbut many libraries implement *scikit-learn* API so that their...
false
8,325
1e292872c0c3c7f4ec0115f0769f9145ef595ead
# -*- coding: utf-8 -*- # __author__ = 'XingHuan' # 3/27/2018 import os import imageio import time os.environ['IMAGEIO_FFMPEG_EXE'] = 'D:/Program Files/ffmpeg-3.4/bin/ffmpeg.exe' reader = imageio.get_reader('test1080.mov') print reader fps = reader.get_meta_data()['fps'] print fps # for i, im in enumerate(reader)...
[ "# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 3/27/2018\n\nimport os\nimport imageio\nimport time\n\nos.environ['IMAGEIO_FFMPEG_EXE'] = 'D:/Program Files/ffmpeg-3.4/bin/ffmpeg.exe'\n\n\nreader = imageio.get_reader('test1080.mov')\nprint reader\nfps = reader.get_meta_data()['fps']\nprint fps\n\n\n# for i, i...
true
8,326
e265b2b2ccc0841ccb8b766de4ae2a869f2d280d
import tensorflow as tf from keras import layers, Model, Input from keras.utils import Progbar, to_categorical from keras.datasets.mnist import load_data import numpy as np import matplotlib.pyplot as plt import config import datetime img_height, img_width, _ = config.IMAGE_SHAPE (X, Y), (_, _) = load_data() X = X.re...
[ "import tensorflow as tf\nfrom keras import layers, Model, Input\nfrom keras.utils import Progbar, to_categorical\nfrom keras.datasets.mnist import load_data\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport config\nimport datetime\n\nimg_height, img_width, _ = config.IMAGE_SHAPE\n\n(X, Y), (_, _) = load...
false
8,327
950b2906853c37cdeaa8ed1076fff79dbe99b6f8
import typing import torch.nn as nn from .torch_utils import get_activation, BatchNorm1d from dna.models.torch_modules.torch_utils import PyTorchRandomStateContext class Submodule(nn.Module): def __init__( self, layer_sizes: typing.List[int], activation_name: str, use_batch_norm: bool, use_skip: bo...
[ "import typing\n\nimport torch.nn as nn\n\nfrom .torch_utils import get_activation, BatchNorm1d\nfrom dna.models.torch_modules.torch_utils import PyTorchRandomStateContext\n\n\nclass Submodule(nn.Module):\n\n def __init__(\n self, layer_sizes: typing.List[int], activation_name: str, use_batch_norm: bo...
false
8,328
4e94e9e2b45d3786aa86be800be882cc3d5a80b5
""" table.py [-m] base1 base2 ... baseN Combines output from base1.txt, base2.txt, etc., which are created by the TestDriver (such as timcv.py) output, and displays tabulated comparison statistics to stdout. Each input file is represented by one column in the table. Optional argument -m shows a final column with the m...
[ "\"\"\"\ntable.py [-m] base1 base2 ... baseN\nCombines output from base1.txt, base2.txt, etc., which are created by\nthe TestDriver (such as timcv.py) output, and displays tabulated\ncomparison statistics to stdout. Each input file is represented by\none column in the table.\nOptional argument -m shows a final col...
false
8,329
0ac471d2cb30a21c1246106ded14cdc4c06d2d40
#!/usr/bin/env python3 from collections import OrderedDict import torch.nn as nn from fairseq.models import FairseqMultiModel, register_model from pytorch_translate import common_layers, utils @register_model("multilingual") class MultilingualModel(FairseqMultiModel): """ To use, you must extend this class ...
[ "#!/usr/bin/env python3\n\nfrom collections import OrderedDict\n\nimport torch.nn as nn\nfrom fairseq.models import FairseqMultiModel, register_model\nfrom pytorch_translate import common_layers, utils\n\n\n@register_model(\"multilingual\")\nclass MultilingualModel(FairseqMultiModel):\n \"\"\"\n To use, you m...
false
8,330
4dda122a8c3a2aab62bb202945f6fb9cb73cf772
from numpy import sqrt def Schout2ConTank(a, b, d): # This function converts parameters from Schoutens notation to Cont-Tankov # notation ## Code th = d * b / sqrt(a ** 2 - b ** 2) k = 1 / (d * sqrt(a ** 2 - b ** 2)) s = sqrt(d / sqrt(a ** 2 - b ** 2)) return th, k, s
[ "from numpy import sqrt\n\n\ndef Schout2ConTank(a, b, d):\n # This function converts parameters from Schoutens notation to Cont-Tankov\n # notation\n\n ## Code\n th = d * b / sqrt(a ** 2 - b ** 2)\n k = 1 / (d * sqrt(a ** 2 - b ** 2))\n s = sqrt(d / sqrt(a ** 2 - b ** 2))\n return th, k, s\n", ...
false
8,331
c9f1768e2f2dd47d637c2e577067eb6cd163e972
from functools import partial def power_func(x, y, a=1, b=0): return a*x**y + b new_func = partial(power_func, 2, a=4) print(new_func(4, b=1)) print(new_func(1))
[ "from functools import partial\n\n\ndef power_func(x, y, a=1, b=0):\n return a*x**y + b\n\n\nnew_func = partial(power_func, 2, a=4)\n\nprint(new_func(4, b=1))\nprint(new_func(1))\n", "from functools import partial\n\n\ndef power_func(x, y, a=1, b=0):\n return a * x ** y + b\n\n\nnew_func = partial(power_fun...
false
8,332
7eefcfdb9682cb09ce2d85d11aafc04977016ba4
from urllib import request, parse import pandas as pd import json import os class BusInfo: url = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:Bus' url_busstop = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:BusstopPole.json' url_routes = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:BusroutePatt...
[ "from urllib import request, parse\nimport pandas as pd\nimport json\nimport os\n\nclass BusInfo:\n\n url = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:Bus'\n url_busstop = 'https://api-tokyochallenge.odpt.org/api/v4/odpt:BusstopPole.json'\n url_routes = 'https://api-tokyochallenge.odpt.org/api/v4/odp...
false
8,333
7e23f5598ccfe9aff74d43eb662f860b0404b7ec
#!/usr/bin/env python """ A package that determines the current day of the week. """ from datetime import date import calendar # Set the first day of the week as Sunday. calendar.firstday(calendar.SUNDAY) def day_of_the_week(arg): """ Returns the current day of the week. """ if arg == "day": ...
[ "#!/usr/bin/env python\n\n\"\"\"\nA package that determines the current day of the week.\n\"\"\"\n\nfrom datetime import date \nimport calendar\n\n# Set the first day of the week as Sunday.\n\ncalendar.firstday(calendar.SUNDAY)\n\ndef day_of_the_week(arg):\n\n\t\"\"\"\n\tReturns the current day of the week.\n\t\"\"...
true
8,334
61c2a6499dd8de25045733f9061d660341501314
#!/usr/bin/python2 import gmpy2 p = 24659183668299994531 q = 28278904334302413829 e = 11 c = 589000442361955862116096782383253550042 t = (p-1)*(q-1) n = p*q # returns d such that e * d == 1 modulo t, or 0 if no such y exists. d = gmpy2.invert(e,t) # Decryption m = pow(c,d,n) print "Solved ! m = %d" % m
[ "#!/usr/bin/python2\nimport gmpy2\n\np = 24659183668299994531\nq = 28278904334302413829\ne = 11\nc = 589000442361955862116096782383253550042\nt = (p-1)*(q-1)\nn = p*q\n\n# returns d such that e * d == 1 modulo t, or 0 if no such y exists.\nd = gmpy2.invert(e,t)\n\n# Decryption\nm = pow(c,d,n)\nprint \"Solved ! ...
true
8,335
4a8fa195a573f8001e55b099a8882fe71bcca233
"""storeproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-...
[ "\"\"\"storeproject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name...
false
8,336
8c71bc5d53bf5c4cb20784659eddf8a97efb86ef
# #----------------------------------------# # 3.4 # # Question: # Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. #
[ "#\t#----------------------------------------#\n#\t3.4\n#\t\n#\tQuestion:\n#\tWrite a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].\n#\t\n", "" ]
false
8,337
98fb70e1911522365292c86603481656e7b86d73
from django.contrib import admin from .models import CarouselImage, Budget admin.site.register(CarouselImage) admin.site.register(Budget)
[ "from django.contrib import admin\nfrom .models import CarouselImage, Budget\n\nadmin.site.register(CarouselImage)\n\nadmin.site.register(Budget)\n", "from django.contrib import admin\nfrom .models import CarouselImage, Budget\nadmin.site.register(CarouselImage)\nadmin.site.register(Budget)\n", "<import token>\...
false
8,338
30986eb0a6cd82f837dd14fb383529a6a41def9a
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('c4c_app', '0006_c4cjob_complete'), ] operations = [ migrations.AlterModelOptions( ...
[ "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0001_initial'),\n ('c4c_app', '0006_c4cjob_complete'),\n ]\n\n operations = [\n migrations.AlterMod...
false
8,339
e560f2f202e477822729d1361b8d7ef7831a00e6
# ------------------------------------------ # # Project: VEXcode VR Maze Solver # Author: Hyunwoo Choi # Created: January 12 2021 # Description: Solves a VEXcode VR maze using the right hand rule # # ------------------------------------------ # Library imports from vexcode import * #main def main...
[ "# ------------------------------------------\n# \n# \tProject: VEXcode VR Maze Solver\n#\tAuthor: Hyunwoo Choi\n#\tCreated: January 12 2021\n#\tDescription: Solves a VEXcode VR maze using the right hand rule\n# \n# ------------------------------------------\n\n# Library imports\nfrom vexcode impor...
false
8,340
800573786913ff2fc37845193b5584a0a815533f
# use local image import io import os from google.cloud import vision from google.oauth2 import service_account creds = service_account.Credentials.from_service_account_file('./key.json') client = vision.ImageAnnotatorClient( credentials=creds, ) # The name of the image file to annotate file_name = os.path.joi...
[ "# use local image\n\nimport io\nimport os\n\nfrom google.cloud import vision\nfrom google.oauth2 import service_account\n\ncreds = service_account.Credentials.from_service_account_file('./key.json')\n\nclient = vision.ImageAnnotatorClient(\n credentials=creds,\n)\n\n# The name of the image file to annotate\nfil...
false
8,341
75837ab778e94693151de1c17b59e12f8b2336d3
def divide(file): index = 0 head = '' while True: if file[index].isnumeric(): head_index = index break if file[index].isalpha(): head += file[index].lower() else: head += file[index] index += 1 while True: if index ...
[ "def divide(file):\n index = 0\n head = ''\n while True:\n\n if file[index].isnumeric():\n head_index = index\n break\n if file[index].isalpha():\n head += file[index].lower()\n else:\n head += file[index]\n index += 1\n while True:...
false
8,342
b7632cc7d8fc2f9096f7a6bb61c471dc61689f70
import pandas as pd import numpy as np import urllib.request import urllib.parse import json def predict(input_text): URL = "http://127.0.0.1:8000/api/v1/predict/" values = { "format": "json", "input_text": input_text, } data = urllib.parse.urlencode({'input_text': i...
[ "import pandas as pd\r\nimport numpy as np\r\nimport urllib.request\r\nimport urllib.parse\r\nimport json\r\n\r\ndef predict(input_text):\r\n URL = \"http://127.0.0.1:8000/api/v1/predict/\"\r\n values = {\r\n \"format\": \"json\",\r\n \"input_text\": input_text,\r\n }\r\n data = ur...
false
8,343
1c8145007edb09d77a3b15de5c34d0bc86c0ba97
import argparse # for handling command line arguments import collections # for container types like OrderedDict import configparser import hashlib # for SHA-1 import os import re import sys import zlib # git compresses everything using zlib argparser = argparse.ArgumentParser(description="The stupid content tracker") ...
[ "import argparse # for handling command line arguments\nimport collections # for container types like OrderedDict\nimport configparser\nimport hashlib # for SHA-1\nimport os\nimport re\nimport sys\nimport zlib # git compresses everything using zlib\n\nargparser = argparse.ArgumentParser(description=\"The stupid con...
true
8,344
257a4d0b0c713624ea8452dbfd6c5a96c9a426ad
import pymysql import logging import socket from models.platformconfig import Pconfig class ncbDB(Pconfig): # I have to retrieve basic configuration attributes, listed below, from system config file # on ApplSrv, for example : /etc/ncb_applsrv/ncb_applsrv.conf hostname = None conferenceMediaStoragePa...
[ "import pymysql\nimport logging\nimport socket\nfrom models.platformconfig import Pconfig\n\n\nclass ncbDB(Pconfig):\n # I have to retrieve basic configuration attributes, listed below, from system config file\n # on ApplSrv, for example : /etc/ncb_applsrv/ncb_applsrv.conf\n\n hostname = None\n conferen...
false
8,345
15ca54aff4c688733c9c514ba5856e6bf29a3292
""" Compare 1-D analytical sphere solution to 1-D numerical and 3-D Comsol solutions for transient heat conduction in solid sphere with constant k and Cp. Assumptions: Convection boundary condition at surface. Symmetry about the center of the solid. Heat transfer via radiation assumed to be negligable. Particle does n...
[ "\"\"\"\nCompare 1-D analytical sphere solution to 1-D numerical and 3-D Comsol solutions\nfor transient heat conduction in solid sphere with constant k and Cp.\n\nAssumptions:\nConvection boundary condition at surface.\nSymmetry about the center of the solid.\nHeat transfer via radiation assumed to be negligable.\...
false
8,346
3b41bd59c133bb04dae3aa48dc0699388d5bf3d4
import os import json import random chapter_mode = True setname = 'test_other' use_chapter = '_chapter' minlen = 1000 maxlen = 1000 context = '_1000' info_json = 'bookinfo{}_{}{}.json'.format(use_chapter, setname, context) book_ID_mapping = {} with open('speaker_book.txt') as fin: for line in fin: elems ...
[ "import os\nimport json\nimport random\n\n\nchapter_mode = True\nsetname = 'test_other'\nuse_chapter = '_chapter'\nminlen = 1000\nmaxlen = 1000\ncontext = '_1000'\n\ninfo_json = 'bookinfo{}_{}{}.json'.format(use_chapter, setname, context)\nbook_ID_mapping = {}\nwith open('speaker_book.txt') as fin:\n for line in...
false
8,347
27fc11ae68531c7dbafdcf134f0eef019210e2de
from django import forms from django.forms import widgets from tsuru_dashboard import settings import requests class ChangePasswordForm(forms.Form): old = forms.CharField(widget=forms.PasswordInput()) new = forms.CharField(widget=forms.PasswordInput()) confirm = forms.CharField(widget=forms.PasswordInput...
[ "from django import forms\nfrom django.forms import widgets\nfrom tsuru_dashboard import settings\n\nimport requests\n\n\nclass ChangePasswordForm(forms.Form):\n old = forms.CharField(widget=forms.PasswordInput())\n new = forms.CharField(widget=forms.PasswordInput())\n confirm = forms.CharField(widget=form...
false
8,348
73e6930c6866d3ccdbccec925bfc5e7e4702feb9
""" eulerian_path.py An Eulerian path, also called an Euler chain, Euler trail, Euler walk, or "Eulerian" version of any of these variants, is a walk on the graph edges of a graph which uses each graph edge in the original graph exactly once. A connected graph has an Eulerian path iff it has at most two graph vertices ...
[ "\"\"\"\neulerian_path.py\nAn Eulerian path, also called an Euler chain, Euler trail, Euler walk, or \"Eulerian\" version of any of these\nvariants, is a walk on the graph edges of a graph which uses each graph edge in the original graph exactly once.\nA connected graph has an Eulerian path iff it has at most two g...
false
8,349
c00a8bfec46ed829e413257bf97c44add564080d
#!/usr/bin/env python import rospy import rosnode import csv import datetime import rosbag import sys import os import matplotlib.pyplot as plt import argparse import math from math import hypot import numpy as np from sensor_msgs.msg import LaserScan from std_msgs.msg import String import yaml as yaml start_time = Non...
[ "#!/usr/bin/env python\nimport rospy\nimport rosnode\nimport csv\nimport datetime\nimport rosbag\nimport sys\nimport os\nimport matplotlib.pyplot as plt\nimport argparse\nimport math\nfrom math import hypot\nimport numpy as np\nfrom sensor_msgs.msg import LaserScan\nfrom std_msgs.msg import String\nimport yaml as y...
true
8,350
a52762fb13c04ced07a41a752578c4173d1eac42
from queue import Queue class Node(): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def array_to_tree_dfs(array): n = len(array) if n>0: root = Node(array[0]) def dfs(node, index): # if index >= n: ...
[ "from queue import Queue\n\nclass Node():\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\ndef array_to_tree_dfs(array):\n n = len(array)\n if n>0:\n root = Node(array[0])\n\n def dfs(node, index):\n ...
false
8,351
12396130dc52866cc54d6dc701cf0f9a41a168b6
from PyInstaller.utils.hooks import collect_data_files hiddenimports = ['sklearn.utils.sparsetools._graph_validation', 'sklearn.utils.sparsetools._graph_tools', 'sklearn.utils.lgamma', 'sklearn.utils.weight_vector'] datas = collect_data_files('sklearn')
[ "from PyInstaller.utils.hooks import collect_data_files\n\nhiddenimports = ['sklearn.utils.sparsetools._graph_validation',\n 'sklearn.utils.sparsetools._graph_tools',\n 'sklearn.utils.lgamma',\n 'sklearn.utils.weight_vector']\n\ndatas = collect_data_files('sklearn')",...
false
8,352
8ca16947054b681a5f43d8b8029191d031d3a218
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Swking @File : ZDT.py @Date : 2018/12/28 @Desc : """ import numpy as np class ZDT1: def __init__(self): self.dimension = 30 self.objFuncNum = 2 self.isMin = True self.min = np.zeros(self.dimension) self.max = np.zeros(self.dimension) + 1 self.s...
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author: Swking\n@File : ZDT.py\n@Date : 2018/12/28\n@Desc : \n\"\"\"\nimport numpy as np\nclass ZDT1:\n\tdef __init__(self):\n\t\tself.dimension = 30\n\t\tself.objFuncNum = 2\n\t\tself.isMin = True\n\t\tself.min = np.zeros(self.dimension)\n\t\tself.max = ...
false
8,353
55ffcf5e6120cc07da461e30979dd8a36a599bee
#------------------------------------------------------------------------------- # rtlconverter.py # # PyCoRAM RTL Converter # # Copyright (C) 2013, Shinya Takamaeda-Yamazaki # License: Apache 2.0 #------------------------------------------------------------------------------- import sys import os import subprocess im...
[ "#-------------------------------------------------------------------------------\n# rtlconverter.py\n# \n# PyCoRAM RTL Converter\n#\n# Copyright (C) 2013, Shinya Takamaeda-Yamazaki\n# License: Apache 2.0\n#-------------------------------------------------------------------------------\nimport sys\nimport os\nimpor...
false
8,354
2e6f04c3ff3e47a2c3e9f6a7d93e7ce2955a2756
from __future__ import print_function from __future__ import absolute_import from builtins import str from builtins import range from builtins import object import hashlib from xml.sax.saxutils import escape from struct import unpack, pack import textwrap import json from .anconf import warning, error, CONF, enable_c...
[ "from __future__ import print_function\nfrom __future__ import absolute_import\n\nfrom builtins import str\nfrom builtins import range\nfrom builtins import object\nimport hashlib\nfrom xml.sax.saxutils import escape\nfrom struct import unpack, pack\nimport textwrap\n\nimport json\nfrom .anconf import warning, erro...
false
8,355
1deab16d6c574bf532c561b8d6d88aac6e5d996c
# Importing datasets wrangling libraries import numpy as np import pandas as pd incd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend']) print(incd_data.columns)
[ "# Importing datasets wrangling libraries\nimport numpy as np\nimport pandas as pd\n\nincd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend'])\nprint(incd_data.columns)\n", "import numpy as np...
false
8,356
c0f4f9eef12d99d286f5ad56f6554c5910b7cc71
users = { 'Students': [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ], 'Instructors': [ {'first_name' : 'Michael', 'last_name' : 'Choi'}, ...
[ "users = {\n 'Students': [\n {'first_name': 'Michael', 'last_name' : 'Jordan'},\n {'first_name' : 'John', 'last_name' : 'Rosales'},\n {'first_name' : 'Mark', 'last_name' : 'Guillen'},\n {'first_name' : 'KB', 'last_name' : 'Tonel'}\n ],\n 'Instructors': [\n {'first_name' : 'Michael', 'last_name...
true
8,357
4d0b08f8ca77d188aa218442ac0689fd2c057a89
import numpy as np import pandas as pd import matplotlib.pyplot as plt import os, shutil, time, pickle, warnings, logging import yaml from sklearn import preprocessing from sklearn.model_selection import StratifiedKFold, KFold from sklearn import metrics from scipy.special import erfinv from scipy.stats import mode wa...
[ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os, shutil, time, pickle, warnings, logging\nimport yaml\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import StratifiedKFold, KFold\nfrom sklearn import metrics\nfrom scipy.special import erfinv\nfrom scipy.stats i...
false
8,358
84d096a51fa052ee210e975ab61c0cbbf05bc5ae
class Day8MemoryManeuver: def __init__(self, use_reference_count=False): """ Args: use_reference_count (bool): True: If an entry has child nodes, the meta data are referring to the results of the child node False: Sum all meta data up ...
[ "class Day8MemoryManeuver:\n def __init__(self, use_reference_count=False):\n \"\"\"\n Args:\n use_reference_count (bool):\n True: If an entry has child nodes, the meta data are referring to the results of\n the child node\n False: Sum all...
false
8,359
e18ebf961c2daa7dd127d08f85edb6ea519e3470
#!/usr/bin/python """ Expression Parser Tree for fully parenthesized input expression """ from bintree import BinaryTree from stackModule import Stack def buildParseTree(expression): expList = expression.split() empTree = BinaryTree('') parentStack = Stack() parentStack.push(empTree) currentNode ...
[ "#!/usr/bin/python\n\n\"\"\"\nExpression Parser Tree for fully parenthesized input expression\n\"\"\"\n\nfrom bintree import BinaryTree\nfrom stackModule import Stack\n\ndef buildParseTree(expression):\n expList = expression.split()\n empTree = BinaryTree('')\n parentStack = Stack()\n parentStack.push(e...
true
8,360
a4c4a5cc63c345d1fa8cbf426f7857a0f3d4357f
# Generated by Django 3.2.4 on 2021-06-16 13:41 import ckeditor.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('FAQ', '0004_auto_20210616_1253'), ] operations = [ migrations.RemoveField( model_name='question', nam...
[ "# Generated by Django 3.2.4 on 2021-06-16 13:41\n\nimport ckeditor.fields\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('FAQ', '0004_auto_20210616_1253'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='questio...
false
8,361
ad94118b43e130aec5df3976fd0460164de17511
#!/usr/bin/python # coding: utf-8 # # import re # # import urllib # # # # # # def getHtml(url): # # page = urllib.urlopen(url) # # html = page.read() # # return html # # # # # # def getMp4(html): # # r = r"href='(http.*\.mp4)'" # # re_mp4 = re.compile(r) # # mp4List = re.findall(re_mp4, html) ...
[ "#!/usr/bin/python\n# coding: utf-8\n\n\n# # import re\n# # import urllib\n# #\n# #\n# # def getHtml(url):\n# # page = urllib.urlopen(url)\n# # html = page.read()\n# # return html\n# #\n# #\n# # def getMp4(html):\n# # r = r\"href='(http.*\\.mp4)'\"\n# # re_mp4 = re.compile(r)\n# # mp4List = ...
false
8,362
28851979c8f09f3cd1c0f4507eeb5ac2e2022ea0
''' Run from the command line with arguments of the CSV files you wish to convert. There is no error handling so things will break if you do not give it a well formatted CSV most likely. USAGE: python mycsvtomd.py [first_file.csv] [second_file.csv] ... OUTPUT: first_file.md second_file.md ... ''' import sys import cs...
[ "'''\nRun from the command line with arguments of the CSV files you wish to convert.\nThere is no error handling so things will break if you do not give it a well\nformatted CSV most likely.\n\nUSAGE: python mycsvtomd.py [first_file.csv] [second_file.csv] ...\n\nOUTPUT: first_file.md second_file.md ...\n'''\nimport...
true
8,363
37fdfddb471e2eec9e5867d685c7c56fc38c5ae7
import json import logging import os import sys from io import StringIO import pytest from allure.constants import AttachmentType from utils.tools import close_popups _beautiful_json = dict(indent=2, ensure_ascii=False, sort_keys=True) # LOGGING console ##############################################################...
[ "import json\nimport logging\nimport os\nimport sys\nfrom io import StringIO\n\nimport pytest\nfrom allure.constants import AttachmentType\n\nfrom utils.tools import close_popups\n\n_beautiful_json = dict(indent=2, ensure_ascii=False, sort_keys=True)\n\n# LOGGING console ############################################...
false
8,364
9320926c9eb8a03d36446f3692f11b242c4fc745
#!/usr/bin/env python3 # coding=utf-8 # date 2020-10-22 10:54:38 # author calllivecn <c-all@qq.com> import sys import random import asyncio import argparse def httpResponse(msg): response = [ "HTTP/1.1 200 ok", "Server: py", "Content-Type: text/plain", "Content-Le...
[ "#!/usr/bin/env python3\n# coding=utf-8\n# date 2020-10-22 10:54:38\n# author calllivecn <c-all@qq.com>\n\n\nimport sys\nimport random\nimport asyncio\nimport argparse\n\n\ndef httpResponse(msg):\n response = [\n \"HTTP/1.1 200 ok\",\n \"Server: py\",\n \"Content-Type: text/plain...
false
8,365
90a402cccf383ed6a12b70ecdc3de623e6e223f9
def ex7(*siruri, x=1, flag=True): res = () for sir in siruri: chars = [] for char in sir: if ord(char) % x == (not flag): chars.append(char) res += (chars,) return res print(ex7("test", "hello", "lab002", x=2, flag=False))
[ "def ex7(*siruri, x=1, flag=True):\n res = ()\n for sir in siruri:\n chars = []\n for char in sir:\n if ord(char) % x == (not flag):\n chars.append(char)\n res += (chars,)\n\n return res\n\n\nprint(ex7(\"test\", \"hello\", \"lab002\", x=2, flag=False))\n", "...
false
8,366
6e73625adc10064cdb1b5f0546a4fc7320e9f5dc
from django import template import random register = template.Library() @register.simple_tag def random_quote(): """Returns a random quote to be displayed on the community sandwich page""" quotes = [ "Growth is never by mere chance; it is the result of forces working together.\n-James Cash Penney", ...
[ "from django import template\n\nimport random\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef random_quote():\n \"\"\"Returns a random quote to be displayed on the community sandwich page\"\"\"\n quotes = [\n \"Growth is never by mere chance; it is the result of forces working together....
false
8,367
158b39a64d725bdbfc78acc346ed8335613ae099
#common method to delete data from a list fruits=['orange','apple','mango','grapes','banana','apple','litchi'] #l=[] #[l.append(i) for i in fruits if i not in l] #print(l) print(set(fruits)) print(fruits.count("orange")) #pop method in a list used to delete last mathod from a lis...
[ "#common method to delete data from a list\r\nfruits=['orange','apple','mango','grapes','banana','apple','litchi']\r\n#l=[]\r\n\r\n#[l.append(i) for i in fruits if i not in l]\r\n\r\n#print(l)\r\nprint(set(fruits))\r\n\r\nprint(fruits.count(\"orange\"))\r\n\r\n\r\n\r\n\r\n \r\n \r\n#pop method in a lis...
false
8,368
802eb0502c5eddcabd41b2d438bf53a5d6fb2c82
from django.db import models from NavigantAnalyzer.common import convert_datetime_string import json # A custom view-based model for flat outputs - RÖ - 2018-10-24 # Don't add, change or delete fields without editing the view in the Db class Results_flat(models.Model): race_id = models.IntegerField() race_name...
[ "from django.db import models\nfrom NavigantAnalyzer.common import convert_datetime_string\nimport json\n\n# A custom view-based model for flat outputs - RÖ - 2018-10-24\n# Don't add, change or delete fields without editing the view in the Db\nclass Results_flat(models.Model):\n race_id = models.IntegerField()\n...
false
8,369
77ae3ef1f6f267972a21f505caa7be29c19a6663
from models import Session, FacebookUser, FacebookPage, FacebookGroup from lib import get_scraper, save_user, save_page import logging logging.basicConfig(level=logging.DEBUG) session = Session() scraper = get_scraper(True) for user in session.query(FacebookUser).filter(FacebookUser.data=="todo").filter("username ~ '...
[ "from models import Session, FacebookUser, FacebookPage, FacebookGroup\nfrom lib import get_scraper, save_user, save_page\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\nsession = Session()\nscraper = get_scraper(True)\n\nfor user in session.query(FacebookUser).filter(FacebookUser.data==\"todo\").filte...
true
8,370
b0a49f5876bc3837b69a6dc274f9587a37351495
import myThread def main(): hosts={"127.0.0.1":"carpenter"} myThread.messageListenThread(hosts) if __name__ == '__main__': main()
[ "import myThread\r\n\r\ndef main():\r\n\thosts={\"127.0.0.1\":\"carpenter\"}\r\n\tmyThread.messageListenThread(hosts)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()", "import myThread\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\nif __name__ == '__main__...
false
8,371
f039ab104093eb42c3f5d3c794710a0997e85387
# coding: utf-8 # Aluno: Héricles Emanuel # Matrícula: 117110647 # Atividade: É quadrado Mágico? def eh_quadrado_magico(m): somas_all = [] eh_magico = True soma = 0 for e in range(len(m[0])): soma += m[0][e] # Linhas for i in range(len(m)): somados = 0 for e in range(len(m[i])): somados += (m[i][e]) s...
[ "# coding: utf-8\n# Aluno: Héricles Emanuel\n# Matrícula: 117110647\n# Atividade: É quadrado Mágico?\n\ndef eh_quadrado_magico(m):\n\tsomas_all = []\n\teh_magico = True\n\tsoma = 0\n\tfor e in range(len(m[0])):\n\t\tsoma += m[0][e]\n\n# Linhas\n\tfor i in range(len(m)):\n\t\tsomados = 0\n\t\tfor e in range(len(m[i]...
true
8,372
14e304f30364932910986f2dda48223b6d4b01c0
from tqdm import tqdm import fasttext import codecs import os import hashlib import time def make_save_folder(prefix="", add_suffix=True) -> str: """ 1. 現在時刻のハッシュをsuffixにした文字列の生成 2. 生成した文字列のフォルダが無かったら作る :param prefix:save folderの系統ラベル :param add_suffix: suffixを付与するかを選ぶフラグ, True: 付与, False: 付与しない ...
[ "from tqdm import tqdm\nimport fasttext\nimport codecs\nimport os\nimport hashlib\nimport time\n\n\ndef make_save_folder(prefix=\"\", add_suffix=True) -> str:\n \"\"\"\n 1. 現在時刻のハッシュをsuffixにした文字列の生成\n 2. 生成した文字列のフォルダが無かったら作る\n :param prefix:save folderの系統ラベル\n :param add_suffix: suffixを付与するかを選ぶフラグ, T...
false
8,373
96936b7f6553bee06177eb66a2e63064c1bf51a6
from __future__ import unicode_literals import requests try: import json except ImportError: import simplejson as json def main(app, data): MEDIUM_API_ENDPOINT = 'https://medium.com/{0}/latest?format=json' r = requests.get(MEDIUM_API_ENDPOINT.format(data.get('username'))) response_content = r....
[ "from __future__ import unicode_literals\n\nimport requests\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\n\ndef main(app, data):\n MEDIUM_API_ENDPOINT = 'https://medium.com/{0}/latest?format=json'\n\n r = requests.get(MEDIUM_API_ENDPOINT.format(data.get('username')))\n\n r...
false
8,374
36fb0d936be5c5d305c4076fd1c497664c9b770a
# -*- coding: utf-8 -*- from ..general.utils import log_errors from googleapiclient import discovery from oauth2client.client import SignedJwtAssertionCredentials from django.conf import settings from celery import shared_task from logging import getLogger import httplib2 _logger = getLogger(__name__) def create_ev...
[ "# -*- coding: utf-8 -*-\n\nfrom ..general.utils import log_errors\n\nfrom googleapiclient import discovery\nfrom oauth2client.client import SignedJwtAssertionCredentials\nfrom django.conf import settings\nfrom celery import shared_task\nfrom logging import getLogger\nimport httplib2\n\n_logger = getLogger(__name__...
false
8,375
64935ae910d5f330722b637dcc5794e7e07ab52d
from eval_lib.classification_results import analyze_one_classification_result from eval_lib.classification_results import ClassificationBatches from eval_lib.cloud_client import CompetitionDatastoreClient from eval_lib.cloud_client import CompetitionStorageClient from eval_lib.dataset_helper import DatasetMetadata from...
[ "from eval_lib.classification_results import analyze_one_classification_result\nfrom eval_lib.classification_results import ClassificationBatches\nfrom eval_lib.cloud_client import CompetitionDatastoreClient\nfrom eval_lib.cloud_client import CompetitionStorageClient\nfrom eval_lib.dataset_helper import DatasetMeta...
false
8,376
7491a17256b9bc7af0953202e45f0fd9d5c34c40
import ctypes import time from order_queue.order import Order class stock(ctypes.Structure): _fields_ = [('stock_id', ctypes.c_int), ('order_type',ctypes.c_int),('Time',ctypes.c_char * 40),('user_id',ctypes.c_int),('volume',ctypes.c_int), ('price',ctypes.c_double) ] class exchange(ctypes.St...
[ "import ctypes\nimport time\nfrom order_queue.order import Order\n\nclass stock(ctypes.Structure):\n _fields_ = [('stock_id', ctypes.c_int), ('order_type',ctypes.c_int),('Time',ctypes.c_char * 40),('user_id',ctypes.c_int),('volume',ctypes.c_int),\n ('price',ctypes.c_double)\n ]\nclass excha...
false
8,377
443ce5c2ec86b9f89ad39ef2ac6772fa002e7e16
class NumMatrix(object): def __init__(self, matrix): if matrix: self.dp = [[0] * (len(matrix[0]) + 1) for i in range(len(matrix)+1)] for i in xrange(1,len(matrix)+1): for j in xrange(1,len(matrix[0])+1): self.dp[i][j] = self.dp[i-1][j] + self....
[ "class NumMatrix(object):\n\n def __init__(self, matrix):\n if matrix:\n self.dp = [[0] * (len(matrix[0]) + 1) for i in range(len(matrix)+1)]\n for i in xrange(1,len(matrix)+1):\n for j in xrange(1,len(matrix[0])+1):\n self.dp[i][j] = self.dp[i-1...
true
8,378
2e3c1bf0a4c88bda35a48008cace8c21e071384e
disk = bytearray (1024*1024); def config_complete(): pass def open(readonly): return 1 def get_size(h): global disk return len (disk) def can_write(h): return True def can_flush(h): return True def is_rotational(h): return False def can_trim(h): return True def pread(h, count, of...
[ "disk = bytearray (1024*1024);\n\ndef config_complete():\n pass\n\ndef open(readonly):\n return 1\n\ndef get_size(h):\n global disk\n return len (disk)\n\ndef can_write(h):\n return True\n\ndef can_flush(h):\n return True\n\ndef is_rotational(h):\n return False\n\ndef can_trim(h):\n return T...
false
8,379
dfd2b515e08f285345c750bf00f6a55f43d60039
"""David's first approach when I exposed the problem. Reasonable to add in the comparison? """ import numpy as np from sklearn.linear_model import RidgeCV from sklearn.model_selection import ShuffleSplit def correlation(x, y): a = (x - x.mean(0)) / x.std(0) b = (y - y.mean(0)) / y.std(0) return a.T @ b / ...
[ "\"\"\"David's first approach when I exposed the problem.\nReasonable to add in the comparison?\n\"\"\"\nimport numpy as np\nfrom sklearn.linear_model import RidgeCV\nfrom sklearn.model_selection import ShuffleSplit\n\n\ndef correlation(x, y):\n a = (x - x.mean(0)) / x.std(0)\n b = (y - y.mean(0)) / y.std(0)\...
false
8,380
7e985f55271c8b588abe54a07d20b89b2a29ff0d
from codecool_class import CodecoolClass from mentor import Mentor from student import Student codecool_bp = CodecoolClass.create_local
[ "from codecool_class import CodecoolClass\nfrom mentor import Mentor\nfrom student import Student\n\ncodecool_bp = CodecoolClass.create_local\n", "from codecool_class import CodecoolClass\nfrom mentor import Mentor\nfrom student import Student\ncodecool_bp = CodecoolClass.create_local\n", "<import token>\ncodec...
false
8,381
6ba830aafbe8e4b42a0b927328ebcad1424cda5e
class Solution: ''' 先遍历整个string,并记录最小的character的出现次数。 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可; 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。 ''' ...
[ "class Solution:\n '''\n 先遍历整个string,并记录最小的character的出现次数。\n 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;\n 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。\...
false
8,382
ae7a2de8742e353818d4f5a28feb9bce04d787bb
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 13 17:34:32 2019 @author: fanlizhou Analyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt' Plot heatmap of amino acid usage and codon usage Plot codon usage in each gene for each amino acid. Genes were arranged so that the ge...
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Wed Mar 13 17:34:32 2019\n\n@author: fanlizhou\n\nAnalyze codon usage of sequence from 'SP_gene_seq.txt' and 'LP_gene_seq.txt'\nPlot heatmap of amino acid usage and codon usage\nPlot codon usage in each gene for each amino acid. Genes were arran...
false
8,383
e0c6fb414d87c0a6377538089226e37b044edc70
from django.shortcuts import render from django_filters.rest_framework import DjangoFilterBackend from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http import JsonResponse, Http404 from .serializers import * from .models import * from .filter import * from r...
[ "from django.shortcuts import render\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom django.http import JsonResponse, Http404\nfrom .serializers import *\nfrom .models import *\nfrom .filter imp...
false
8,384
3001534be3364be1148cd51a4a943fd8c975d87e
from flask import (Flask, render_template, request, url_for, redirect, flash, jsonify) app = Flask(__name__) @app.route('/', methods=['GET']) def showHomepage(): return render_template('home.html') if __name__ == '__main__': print('app started') app.secret_key = 'secretkey' app.run(debug=True)
[ "from flask import (Flask,\n\trender_template,\n\trequest,\n\turl_for,\n\tredirect,\n\tflash,\n\tjsonify)\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET'])\ndef showHomepage():\n\treturn render_template('home.html')\n\n\nif __name__ == '__main__':\n\tprint('app started')\n\tapp.secret_key = 'secretkey'\n...
false
8,385
2f64aac7032ac099870269659a84b8c7c38b2bf0
import pandas as pd import subprocess import statsmodels.api as sm import numpy as np import math ''' This function prcesses the gene file Output is a one-row file for a gene Each individual is in a column Input file must have rowname gene: gene ENSG ID of interest start_col: column number which the gene exp value st...
[ "import pandas as pd\nimport subprocess\nimport statsmodels.api as sm\nimport numpy as np\nimport math\n\n'''\nThis function prcesses the gene file\nOutput is a one-row file for a gene\nEach individual is in a column\n\nInput file must have rowname\ngene: gene ENSG ID of interest\nstart_col: column number which the...
false
8,386
edc66bdc365f9c40ee33249bd2d02c0c5f28256a
import torch import torch.nn as nn class ReconstructionLoss(nn.Module): def __init__(self, config): super(ReconstructionLoss, self).__init__() self.velocity_dim = config.velocity_dim def forward(self, pre_seq, gt_seq): MSE_loss = nn.MSELoss() rec_loss = MSE_loss(pre_seq[:, 1:-...
[ "import torch\nimport torch.nn as nn\n\n\nclass ReconstructionLoss(nn.Module):\n def __init__(self, config):\n super(ReconstructionLoss, self).__init__()\n self.velocity_dim = config.velocity_dim\n\n def forward(self, pre_seq, gt_seq):\n MSE_loss = nn.MSELoss()\n rec_loss = MSE_los...
false
8,387
9ca769ae8bbabee20b5dd4d75ab91d3c30e8d1bf
def filter(txt): # can be improved using regular expression output = [] for t in txt: if t == "(" or t == ")" or t == "[" or t == "]": output.append(t) return output result = [] while True: raw_input = input() line = filter(raw_input) if raw_input != ".": stack = [] err = False for l in line: ...
[ "def filter(txt): # can be improved using regular expression\n\toutput = []\n\tfor t in txt:\n\t\tif t == \"(\" or t == \")\" or t == \"[\" or t == \"]\":\n\t\t\toutput.append(t)\n\treturn output\n\nresult = []\nwhile True:\n\traw_input = input()\n\tline = filter(raw_input)\n\t\n\tif raw_input != \".\":\n\t\tstack ...
false
8,388
a8659ca7d7a5870fc6f62b3dfee1779e33373e7b
#!/usr/bin/python2.7 '''USAGE: completeness.py BLAST_output (tab formatted) Prints % completeness based on marker gene BLAST of caled genes from a genome Markers from Lan et al. (2016) ''' import sys with open(sys.argv[1],'r') as blastOut: geneHits = [] orgHits = [] hits = 0.0 for line in blastOut: hits += 1.0 ...
[ "#!/usr/bin/python2.7\n'''USAGE: completeness.py BLAST_output (tab formatted)\nPrints % completeness based on marker gene BLAST of caled genes from a genome\nMarkers from Lan et al. (2016)\n'''\nimport sys\n\nwith open(sys.argv[1],'r') as blastOut:\n\n\tgeneHits = []\n\torgHits = []\n\thits = 0.0\n\tfor line in bla...
false
8,389
dc2c9293040204f0ec2156c41b8be624f4e5cf99
# 라이브러리 환경 import pandas as pd import numpy as np # sklearn 테이터셋에서 iris 데이터셋 로딩 from sklearn import datasets iris = datasets.load_iris() # iris 데이터셋은 딕셔너리 형태이므로, key 값 확인 ''' print(iris.keys()) print(iris['DESCR']) print("데이터 셋 크기:", iris['target']) print("데이터 셋 내용:\n", iris['target']) ''' # data 속성의 데이터셋 크기 print("...
[ "# 라이브러리 환경\nimport pandas as pd\nimport numpy as np\n\n# sklearn 테이터셋에서 iris 데이터셋 로딩\nfrom sklearn import datasets\niris = datasets.load_iris()\n\n# iris 데이터셋은 딕셔너리 형태이므로, key 값 확인\n'''\nprint(iris.keys())\nprint(iris['DESCR'])\nprint(\"데이터 셋 크기:\", iris['target'])\nprint(\"데이터 셋 내용:\\n\", iris['target'])\n'''\n\n...
false
8,390
4c9a3983180cc75c39da41f7f9b595811ba0dc35
import urllib.request from urllib.request import Request, urlopen import json from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup """ Web Scraper ====================================================================== """ ...
[ "import urllib.request\r\nfrom urllib.request import Request, urlopen\r\nimport json\r\n\r\nfrom requests import get\r\nfrom requests.exceptions import RequestException\r\nfrom contextlib import closing\r\nfrom bs4 import BeautifulSoup\r\n\r\n\"\"\"\r\nWeb Scraper ===================================================...
false
8,391
e11a04cad967ae377449aab8b12bfde23e403335
import webbrowser import time total = 3 count = 0 while count<total: webbrowser.open('https://www.youtube.com/watch?v=GoSBNNgf_Vc') time.sleep(5*60*60) count+=1
[ "import webbrowser\nimport time\n\n\n\ntotal = 3\ncount = 0\nwhile count<total:\n\twebbrowser.open('https://www.youtube.com/watch?v=GoSBNNgf_Vc')\n\ttime.sleep(5*60*60)\n\tcount+=1\n", "import webbrowser\nimport time\ntotal = 3\ncount = 0\nwhile count < total:\n webbrowser.open('https://www.youtube.com/watch?v...
false
8,392
689c6c646311eba1faa93cc72bbe1ee4592e45bc
#!/usr/bin/env python3 from typing import ClassVar, List print(1, 2) # Annotated function (Issue #29) def foo(x: int) -> int: return x + 1 # Annotated variables #575 CONST: int = 42 class Class: cls_var: ClassVar[str] def m(self): xs: List[int] = [] # True and False are keywords in Python ...
[ "#!/usr/bin/env python3\nfrom typing import ClassVar, List\n\nprint(1, 2)\n\n\n# Annotated function (Issue #29)\ndef foo(x: int) -> int:\n return x + 1\n\n\n# Annotated variables #575\nCONST: int = 42\n\n\nclass Class:\n cls_var: ClassVar[str]\n\n def m(self):\n xs: List[int] = []\n\n\n# True and Fa...
false
8,393
a9947884e805cc8fcb6bff010a5f6e0ff0bb01fe
import math import numpy as np # import tkinter import tensorflow as tf from matplotlib import axis import os from sklearn.base import BaseEstimator, TransformerMixin from sklearn.cluster import KMeans from sklearn.metrics import confusion_matrix class MD(BaseEstimator, TransformerMixin): def __init__(self, data,...
[ "import math\nimport numpy as np\n# import tkinter\nimport tensorflow as tf\nfrom matplotlib import axis\nimport os\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import confusion_matrix\n\n\nclass MD(BaseEstimator, TransformerMixin):\n def __i...
false
8,394
86f33895e9ae0e026d7d6e40e611796b2dc2c713
"""@brief the routes for Flask application """ import hashlib import json import time import requests from flask import render_template, url_for from soco import SoCo from app import app app.config.from_pyfile("settings.py") sonos = SoCo(app.config["SPEAKER_IP"]) def gen_sig(): """@brief return the MD5 checksum...
[ "\"\"\"@brief the routes for Flask application\n\"\"\"\nimport hashlib\nimport json\nimport time\n\nimport requests\nfrom flask import render_template, url_for\nfrom soco import SoCo\nfrom app import app\n\napp.config.from_pyfile(\"settings.py\")\nsonos = SoCo(app.config[\"SPEAKER_IP\"])\n\n\ndef gen_sig():\n \"...
false
8,395
4a14265a9a2338be66e31110bba696e224b6a70f
from django.shortcuts import render from django.http import HttpResponse from chats.models import Chat from usuario.models import Usuario # Create your views here. def chat(request): chat_list = Chat.objects.order_by("id_chat") chat_dict = {'chat': chat_list} return render(request,'chats/Chat.html', ...
[ "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom chats.models import Chat\nfrom usuario.models import Usuario\n\n# Create your views here.\ndef chat(request):\n \n chat_list = Chat.objects.order_by(\"id_chat\")\n chat_dict = {'chat': chat_list}\n\n return render(request,'...
false
8,396
9816a8265bcdb8c099f599efbe1cfe1a554e71f5
from django.conf.urls import url from price_App import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r'^api/price/(?P<pk>[0-9]+)$', views.product_price), url(r'^api/price_history/(?P<pk>[0-9]+)$', views.product_history),] urlpatterns = format_suffix...
[ "from django.conf.urls import url \nfrom price_App import views\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nurlpatterns = [ \n \turl(r'^api/price/(?P<pk>[0-9]+)$', views.product_price),\n url(r'^api/price_history/(?P<pk>[0-9]+)$', views.product_history),] \n\nurlpatterns =...
false
8,397
76a22408bb423d9a5bc5bc007decdbc7c6cc98f7
""" Neuraxle Tensorflow V1 Utility classes ========================================= Neuraxle utility classes for tensorflow v1. .. Copyright 2019, Neuraxio Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obta...
[ "\"\"\"\nNeuraxle Tensorflow V1 Utility classes\n=========================================\nNeuraxle utility classes for tensorflow v1.\n\n..\n Copyright 2019, Neuraxio Inc.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License...
false
8,398
8364264851895ccabeb74fd3fab1d4f39da717f8
from django.apps import AppConfig class StonewallConfig(AppConfig): name = 'stonewall'
[ "from django.apps import AppConfig\r\n\r\n\r\nclass StonewallConfig(AppConfig):\r\n name = 'stonewall'\r\n", "from django.apps import AppConfig\n\n\nclass StonewallConfig(AppConfig):\n name = 'stonewall'\n", "<import token>\n\n\nclass StonewallConfig(AppConfig):\n name = 'stonewall'\n", "<import toke...
false
8,399
e6010ec05ec24dcd2a44e54ce1b1f11000e775ce
######################################################################### # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You...
[ "#########################################################################\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this fi...
false