seq_id
stringlengths
4
11
text
stringlengths
113
2.92M
repo_name
stringlengths
4
125
sub_path
stringlengths
3
214
file_name
stringlengths
3
160
file_ext
stringclasses
18 values
file_size_in_byte
int64
113
2.92M
program_lang
stringclasses
1 value
lang
stringclasses
93 values
doc_type
stringclasses
1 value
stars
int64
0
179k
dataset
stringclasses
3 values
pt
stringclasses
78 values
239386283
from bs4 import BeautifulSoup import argparse as ap import requests, os, pickle # Pull PostMates HTML def pull_postmates_html(postmates_code): url = "https://postmates.com/merchant/" + postmates_code r = requests.get(url) encoding = r.encoding if 'charset' in r.headers.get('content-type', '').lower() else None sou...
null
scrape_postmates.py
scrape_postmates.py
py
1,873
python
en
code
null
code-starcoder2
50
490311790
# -*- coding: utf-8 -*- """ SmartWin回策框架 MacdMaWin策略 作者:Smart 新建时间:2018-09-02 """ from StrategyTemplate import StrategyTemplate import pandas as pd from Indexer import MA, MACD, dfCross class MacdMaWin(StrategyTemplate): strategy_name = 'MacdMaWin' strategy_para_name_list = ['MS', 'MM', 'ML', 'MA'] def _...
null
Strategy/MacdMaWin.py
MacdMaWin.py
py
6,443
python
en
code
null
code-starcoder2
50
57362755
import json#cPickle as pickle import cv2 import numpy as np from sys import stdout from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D from keras.layers import Dropout, Flatten, Dense from keras.models import Sequential from keras.callbacks import ModelCheckpoint from scipy.misc import imsave import t...
null
step2.py
step2.py
py
20,779
python
en
code
null
code-starcoder2
50
103667864
import numpy as np from .detections import associate_detections_to_trackers from .person_box_tracker import PersonBoxTracker class SORT(object): def __init__(self, max_age=3, min_hits=3): self.max_age = max_age self.min_hits = min_hits self.trackers = [] self.frame_count = 0 ...
null
sort/sort.py
sort.py
py
1,957
python
en
code
null
code-starcoder2
50
269595769
def baseN(num, base, numerals="0123456789abcdefghijklmnopqrstuvwxyz"): """ Convert any int to base/radix 2-36 string. Special numerals can be used to convert to any base or radix you need. This function is essentially an inverse int(s, base). For example: >>> baseN(-13, 4) '-31' >>> bas...
null
Python/calculator-base.py
calculator-base.py
py
2,059
python
en
code
null
code-starcoder2
50
135985996
# -*- coding: utf-8 -* # ----------------------------------------here we-import files--------------------------------------------------------------- from __future__ import unicode_literals from django.shortcuts import render,redirect from datetime import timedelta from demoapp.forms import SignUpForms,LoginForm,PostFo...
null
upload_to_win/upload_to_win/views.py
views.py
py
9,328
python
en
code
null
code-starcoder2
50
535992375
import os, argparse parser = argparse.ArgumentParser() parser.add_argument('--file-ext', help='file extension') parser.add_argument('--dir', help='directory path') parser.add_argument('--substr', help='Sub string for searching') args = parser.parse_args() extens = args.file_ext dir = args.dir substr = args.substr d...
null
dz-6/find.py
find.py
py
661
python
en
code
null
code-starcoder2
50
55885691
import numpy as np from scipy.interpolate import interp1d from scipy import ndimage import scipy.constants as sc import astropy.constants as const import astropy.units as u default_cmap = "inferno" sigma_to_FWHM = 2.0 * np.sqrt(2.0 * np.log(2)) FWHM_to_sigma = 1.0 / sigma_to_FWHM arcsec = np.pi / 648000 def spectra...
null
pymcfost/utils.py
utils.py
py
10,299
python
en
code
null
code-starcoder2
50
204739894
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
null
azure-mgmt-web/azure/mgmt/web/models/managed_hosting_environment.py
managed_hosting_environment.py
py
5,538
python
en
code
null
code-starcoder2
50
78999154
import numpy as np def create_all_subject_connectivity_matrices(subjects): connectivity_matrices = [] for subject in subjects: connectivity_matrices.append(np.load(subject)) connectivity_matrices = np.array(connectivity_matrices) connectivity_matrices = np.swapaxes(connectivity_matrices, 0, -1...
null
Tractography/group_analysis.py
group_analysis.py
py
1,543
python
en
code
null
code-starcoder2
50
132052169
from lib.scrapy_table import Scrapy_Table url="https://pt.wikipedia.org/wiki/C%C3%A2mara_Municipal_de_S%C3%A3o_Paulo" url_jato="https://pt.wikipedia.org/wiki/Lista_de_pessoas_envolvidas_na_Opera%C3%A7%C3%A3o_Lava_Jato" site_connect = Scrapy_Table(url) site_jato = Scrapy_Table(url_jato) tables = tuple(site_connect.g...
null
modulo1/Labs/myCode/ex7.py
ex7.py
py
697
python
en
code
null
code-starcoder2
50
4017268
print("**********Calule o tempo de viagem**********") #informa a finalidade do programa. distância = float(input("Qual a distância a ser percorrida: ")) #entrada de dados referente a distância percorrida. velocidade = int(input("Qual a velocidade média esperada: ")) #entrada de dados referente a velocidade media. ...
null
tempodeviagem.py
tempodeviagem.py
py
1,239
python
en
code
null
code-starcoder2
50
37623113
import inline as inline import numpy import matplotlib import matplotlib.pyplot as pyplot import scipy.special class NeuralNetwork: def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate): self.inodes = inputnodes self.hnodes = hiddennodes self.onodes = outputnodes #...
null
first.py
first.py
py
4,018
python
en
code
null
code-starcoder2
51
16308405
def main(): usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob'] username_input = str(input("Can i have your username: "...
null
Practical 4/security_checker.py
security_checker.py
py
532
python
en
code
null
code-starcoder2
51
396457645
from PIL import Image from PIL import ImageDraw import queue import math width = 100 background = (255, 255, 255, 255) fill_color = (0, 0, 0, 255) im = Image.new("RGBA", (width, width), background) pen = ImageDraw.Draw(im) weight = [[1/16, 1/8, 1/16], [1/8, 1/4, 1/8], [1/16, 1/8, 1/16]] a = 0 b = 0 c = 0 s = 0 def dr...
null
Draw Line Anti-Aliasing/pure.py
pure.py
py
1,980
python
en
code
null
code-starcoder2
51
122958924
import logging from gym.envs.registration import register logger = logging.getLogger(__name__) register( id='Qubit-v0', entry_point='gym_qubit.envs:TransmonEnv', timestep_limit=1000, reward_threshold=1.0, nondeterministic=False, )
null
gym_qubit/__init__.py
__init__.py
py
252
python
en
code
null
code-starcoder2
51
273748052
# importing all the required libraries import os import sys import torch import pandas as pd from os.path import abspath from argparse import ArgumentParser # importing local modules script_path = os.path.abspath('') sys.path.insert(0, abspath(script_path)) # print(abspath(script_path)) from utils.utilities import lo...
null
scripts/predict_using_trec.py
predict_using_trec.py
py
3,681
python
en
code
null
code-starcoder2
51
319801722
""" jim weisman spring 2019 PGR105 """ # Running on a treadmill you burn 4.2 calories per minute. # Write a program that uses a loop to display the number of calories burned after 10, 15, 20, 25 and 30 minutes. cal_minute = 4.2 for minutes in range(10, 31, 5): cal_burned = (minutes / 1) * cal_minute print("...
null
4.1 Calories Burned.py
4.1 Calories Burned.py
py
376
python
en
code
null
code-starcoder2
51
214930681
from flask import Flask from flask import request from flask import render_template app = Flask(__name__) @app.route("/write", methods=["GET", "POST"]) def board_write(): if request.method == "POST": name = request.form.get("name") title = request.form.get("title") contents = request.for...
null
run.py
run.py
py
472
python
en
code
null
code-starcoder2
51
245658143
import numpy as np import glob import matplotlib.pyplot as plt import matplotlib.patches as patches import fnmatch import os simulationInfo = np.genfromtxt('simulationInfo.txt') numberOfParticles = int(simulationInfo[0]) startTime = int(simulationInfo[1]) numberOfParticleFiles = len(fnmatch.filter(os.listdir('Particle...
null
Analysis/plot_borisPusher.py
plot_borisPusher.py
py
1,952
python
en
code
null
code-starcoder2
51
291694571
# File: GaudiMP/Parallel.py # Author: Pere Mato (pere.mato@cern.ch) """ GaudiMP.Parallel module. This module provides 'parallel' processing support for GaudiPyhton. It is adding some sugar on top of public domain packages such as the 'multiprocessing' or the 'pp' packages. The interface can be made ind...
null
ostap/parallel/mp_gaudi.py
mp_gaudi.py
py
3,123
python
en
code
null
code-starcoder2
51
535649408
import dash import dash_bootstrap_components as dbc import dash_table import dash_core_components as dcc import dash_html_components as html import plotly.graph_objects as go from dash.dependencies import Input, Output import pandas as pd ## variables coffee_flavours_1 = pd.read_csv('https://raw.githubusercontent.com/...
null
app_deploy.py
app_deploy.py
py
8,872
python
en
code
null
code-starcoder2
51
41861621
#!/usr/bin/python # -*- coding: utf-8 -*- """ RPS-LS Classic Rock Paper Scissors mini game and LS extension 1.0.0 Initial release Upcoming features latin to ascii comparisons (Lézard == Lezard) should be True Add multiple way to write a choice (ex. French: Pierre, Roche) """ # ---------------------------...
null
RPS-LS_StreamlabsSystem.py
RPS-LS_StreamlabsSystem.py
py
6,109
python
en
code
null
code-starcoder2
51
603303822
from flask import Flask, request, jsonify, abort, Response, render_template from flask_assets import Environment, Bundle from webassets_browserify import Browserify from latex import build_pdf, LatexBuildError from latex.jinja2 import make_env from songs import get_songs from string import digits,letters app = Flas...
null
audio.py
audio.py
py
2,562
python
en
code
null
code-starcoder2
51
352500380
from threading import Thread, Lock import cv2 from peekingduck.pipeline.nodes.input.utils.preprocess import set_res, mirror class VideoThread: ''' Videos will be threaded to prevent I/O blocking from affecting FPS. ''' def __init__(self, res, input_source, mirror_image): self.stream = cv2.V...
null
peekingduck/pipeline/nodes/input/utils/read.py
read.py
py
1,851
python
en
code
null
code-starcoder2
51
35049406
# -*- coding: utf-8 -*- # AlgoPlus量化投资开源框架范例 # 微信公众号:AlgoPlus # 项目地址:http://gitee.com/AlgoPlus/AlgoPlus # 项目网址:http://www.algo.plus # 项目网址:http://www.ctp.plus # 项目网址:http://www.7jia.com from AlgoPlus.CTP.TraderApi import TraderApi from AlgoPlus.CTP.ApiStruct import * import time class TraderEngine(TraderApi): de...
null
AlgoPlus入门手册/8客户端认证/trader_engine.py
trader_engine.py
py
10,481
python
en
code
null
code-starcoder2
51
582091359
import torch from torch.autograd import Variable import numpy as np import random import sys from collections import defaultdict import urllib, csv def data_to_dict(data): data_dict = defaultdict(list) items = set() for (user, item) in data: data_dict[user].append(item) items.add(item) ...
null
fm_core/train_fm.py
train_fm.py
py
10,702
python
en
code
null
code-starcoder2
51
477615728
def soma(num): if num > 0: num = str(num) lista = list(num) soma = 0 for valor in lista: soma = soma + int(valor) return f'A soma dos digitos é de {soma}' else: print('Numero invalido') print(soma(123))
null
section 8 Funções/ex12.py
ex12.py
py
274
python
en
code
null
code-starcoder2
51
197318180
import logging import re from secrets import token_urlsafe import time from django.conf import settings from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.contrib.auth.hashers import make_password from django.core.exceptions import ObjectDoesNotExist from djang...
null
aidants_connect_web/views/id_provider.py
id_provider.py
py
13,240
python
en
code
null
code-starcoder2
50
570520072
""" SOILICE to mrfso converter """ from __future__ import absolute_import, division, print_function, unicode_literals import cmor import cdms2 import logging import numpy as np from e3sm_to_cmip.lib import handle_variables # list of raw variable names needed RAW_VARIABLES = [str('SOILICE')] VAR_NAME = str('mrfso') V...
null
e3sm_to_cmip/cmor_handlers/mrfso.py
mrfso.py
py
1,524
python
en
code
null
code-starcoder2
50
563922917
"""add unique together constraint for shop item category and code name Revision ID: b412a7dfa61f Revises: 8ba89ef9391d Create Date: 2018-07-07 14:48:10.809261 """ from alembic import op # revision identifiers, used by Alembic. revision = "b412a7dfa61f" down_revision = "8ba89ef9391d" branch_labels = None depends_on ...
null
meme_machine/alembic/versions/b412a7dfa61f_add_unique_together_constraint_for_shop_.py
b412a7dfa61f_add_unique_together_constraint_for_shop_.py
py
737
python
en
code
null
code-starcoder2
51
376525253
# CPU functionality LDI = 0b10000010 HLT = 0b00000001 PRN = 0b01000111 MUL = 0b10100010 NOP = 0b00000000 POP = 0b01000110 RET = 0b00010001 CALL = 0b01010000 PUSH = 0b01000101 SP = 0b00000111 ADD = 0b10100000 SUB = 0b10100001 CMP = 0b10100111 EQ = 0b00000111 JMP = 0b01010100 JEQ = 0b01010101 JNE = 0b010...
null
cpu.py
cpu.py
py
5,962
python
en
code
null
code-starcoder2
51
595002045
#!/usr/bin/env python import time, sys, logging from daemon2x import Daemon from lib_oled96 import ssd1306 from PIL import ImageFont, ImageDraw, Image from smbus import SMBus # Logging logging.basicConfig(filename='/home/pi/oled/lib_oled96/clock.log', filemode='a', format='[%(asctim...
null
python/clock-dseg2-d.py
clock-dseg2-d.py
py
2,446
python
en
code
null
code-starcoder2
51
246563288
class Solver: def __init__(self): with open("../resources/d3/input") as f: self.lines = f.readlines() def solveP1(self): print(self.closest_intersection(self.lines)) def solveP2(self): print(self.minimum_steps(self.lines)) def closest_intersection(self, lines): ...
null
src/main/python/d3.py
d3.py
py
2,600
python
en
code
null
code-starcoder2
51
105123489
from tkinter import * import os root = Tk() root.wm_title("Terra Farmer") #Initialising images in Array mapImages= ["agriculturalLand.gif", "artesianBasinMap.gif", "populationMap.gif","rainfallMap.gif", "riverMap.gif", "sunshineHoursMap.gif", "temperatureMap.gif"] mapArray = [] for name in mapImages: ma...
null
GUIDemo.py
GUIDemo.py
py
3,071
python
en
code
null
code-starcoder2
51
1481758
# -*- coding: utf-8 -*- import json import os import sys import subprocess import shutil import time import glob import shutil DEBUG = False WS = '\t' TYPE_PRE = "de.julielab.jcore.types." PIPENAME = "" DEP_LIST = [] DIR_LIST = [] CAP_PROVIDED = [] JSON_FILE = "coordinates.json" ### HEADER ### HEAD = ( """<?xml vers...
null
jcore-cpe-builder/cpe-builder.py
cpe-builder.py
py
17,223
python
en
code
null
code-starcoder2
51
265588831
import traceback as _tb def execPy(varname=None,traceback=False): """Get array of python commands from tdi public variable ___TDI___cmds and execute them. The ___TDI___cmds variable should be either a scalar string or a string array. If varname is defined then set the tdi public variable ___TDI___answe...
null
mdsobjects/python/tdipy.py
tdipy.py
py
1,692
python
en
code
null
code-starcoder2
51
7621461
#!/usr/bin/env python3 import argparse import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.style.use('bmh') import pandas as pd import numpy as np import math import os import sys import json import glob def main(): # import sys # from IPython.core import ultratb # sys.excepthook...
null
sudoku/plot.py
plot.py
py
4,017
python
en
code
null
code-starcoder2
51
29452654
# Imports import time import datetime import win32api import socket import _thread if socket.gethostname().find('.')>=0: hostname=socket.gethostname() else: hostname=socket.gethostbyaddr(socket.gethostname())[0] # Functions def main(): idleflag = False work_start, work_stop = 0, 0 idle_start, idle_stop = 0...
null
Py-dle.py
Py-dle.py
py
1,289
python
en
code
null
code-starcoder2
51
384093639
#!/usr/bin/python # -*- coding: utf-8 -*- import tkMessageBox import MySQLdb import mysql.connector from fpdf import FPDF import decimal from datetime import * import os, sys from cargo import Cargo #Definimos la clase Recibo class Recibo(object): __numero_Recibo = None """Constructor * @param numero_Reci...
null
clases/recibo.py
recibo.py
py
9,951
python
en
code
null
code-starcoder2
51
290954816
import os import sys import hashlib import time import sqlite3 import zlib import datetime from sqlite3 import Error BLOCKSIZE = 524288 start_time = time.time() #walk_dir = sys.argv[1] walk_dir = "C:" conn = sqlite3.connect('C:\DataSets\listing2.db') c = conn.cursor() # Create table try: c.exe...
null
loopy2.py
loopy2.py
py
2,214
python
en
code
null
code-starcoder2
51
568134976
import os from gitpandas import Repository __author__ = 'willmcginnis' if __name__ == '__main__': repo = Repository(working_dir=os.path.abspath('../../git-pandas')) fc = repo.file_change_rates(include_globs=['*.py'], coverage=True) print(fc)
null
examples/file_change_rates.py
file_change_rates.py
py
256
python
en
code
null
code-starcoder2
51
143495959
import collections import re from buildbot.plugins import steps, util from buildbot.process import buildstep from buildbot.status.results import SUCCESS from twisted.internet import defer import yaml import environments as envs SERVO_REPO = "https://github.com/servo/servo" class CheckRevisionStep(buildstep.BuildS...
null
buildbot/master/files/config/factories.py
factories.py
py
9,654
python
en
code
null
code-starcoder2
51
158780335
import json from django.views.generic import FormView from hl_bigdata.forms import PostForm from django.shortcuts import render from hl_bigdata import models as m from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.template import Context, loader from date...
null
hl_bigdata/views.py
views.py
py
3,506
python
en
code
null
code-starcoder2
51
334046056
import asyncio import aiohttp semaphore = asyncio.Semaphore(10) def get_url(): url_lis = [] for i in range(0, 100): url = 'https://spa5.scrape.center/api/book/?limit=18&offset={}'.format(i * 18) url_lis.append(url) return url_lis url_lis = get_url() async def request(url): async wit...
null
util/spa4.py
spa4.py
py
749
python
en
code
null
code-starcoder2
51
554575420
""" @note:detection """ from PIL import Image import numpy as np from NN import CNN import matplotlib.pyplot as plt """ @note: 由于二值化无法将由于色调相近但有差别的图像 显示出,于是尝试采用四值化处理 """ # 多值化处理函数 def convert8(img): row, column = img.shape for i in range(row): for j in range(column): ...
null
pre.py
pre.py
py
7,763
python
en
code
null
code-starcoder2
51
380042036
import os import subprocess from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.conf import settings from FilmsApp.models import Film, Mark BASE_DIR = settings.BASE_DIR class Command(BaseCommand): def handle(self, *args, **options): self.create_al...
null
WTWApp/management/commands/make_learning.py
make_learning.py
py
928
python
en
code
null
code-starcoder2
51
579393952
# -*- coding: utf-8 -*- import os import re ALPHANUMERIC_REGEX = re.compile("[\W_]+") INSIDE_PARENTHESES_REGEX = re.compile("\([^)]*\)") INSIDE_BRACKETS_REGEX = re.compile("\[[^)]*\]") def find_files(root_folder, extension=None): """ :param root_folder: str Folder to scan :param extension: str o...
null
spotify/utils.py
utils.py
py
1,964
python
en
code
null
code-starcoder2
51
621885187
from dataclasses import dataclass from .color import Color from .point import Point @dataclass class Triangle: ''' Хранит информацию о трегуольнике. ''' color: Color a: Point b: Point c: Point @staticmethod def read(buffer) -> 'Triangle': color = Color.read(buffer) ...
null
AVS3/triangle.py
triangle.py
py
869
python
en
code
null
code-starcoder2
51
146214300
# encoding:utf-8 # memorizer main file from kivy.app import App # from kivy.uix.widget import Widget from kivy.uix.boxlayout import BoxLayout # from kivy.uix.label import Label from kivy.clock import Clock # from kivy.properties import ObjectProperty import time import random # count = 10 count = 3 class Memorize...
null
memorizer.py
memorizer.py
py
1,076
python
en
code
null
code-starcoder2
51
152628260
# -*- coding: utf-8 -*- """ Created on Mon Dec 18 21:30:29 2017 @author: rimikamajumdar """ # Exercise 44: Inheritance versus Composition # Inheritance: Override Explicitly class Parent(object): def override(self): print("PARENT override()") class Child(Parent): # if you want the c...
null
ex44/ex44b.py
ex44b.py
py
625
python
en
code
null
code-starcoder2
51
409642494
# -*- coding: utf-8 -*- """ Created on Thu Jul 03 09:40:19 2014 @author: Kyle Ellefsen """ from __future__ import (absolute_import, division,print_function, unicode_literals) from future.builtins import (bytes, dict, int, list, object, range, str, ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map...
null
process/binary.py
binary.py
py
16,297
python
en
code
null
code-starcoder2
51
335833383
from urllib.request import urlopen '''获取字符串函数 引用自作业说明 将URL请求转换成正常的字符串''' def newstr(link): doc = urlopen(link) docstr = doc.read() doc.close() jstr = docstr.decode() return jstr '''货币数目分离函数 彭金山 从字符串中获取所兑换货币的数量,并转化为浮点数''' def answer(newstr): money=newstr.split() eur=money[9][1:] eur1=f...
null
pyassign2/currency.py
currency.py
py
1,765
python
en
code
null
code-starcoder2
51
52831665
import requests from operator import itemgetter url='https://hacker-news.firebaseio.com/v0/topstories.json' r= requests.get(url) # get the result json from the topstories to an boject submission_ids submission_ids = r.json() # an empty list submission_dicts = [] # loops thorugh top 30 news from the above json for ...
null
API call in Python/hn_submissions.py
hn_submissions.py
py
1,638
python
en
code
null
code-starcoder2
51
410899419
# -*- coding: utf-8 -*- """ """ #%% download latest translations from crowdin #pip install crowdin-cli-py --upgrade import subprocess if subprocess.call(['crowdin-cli-py', 'download'])==1: raise ValueError("Download failes, maybe you need to adjust paths in corwdin.yaml!") #%% Build translations #pip install po...
null
manage/build.py
build.py
py
4,124
python
en
code
null
code-starcoder2
51
621086196
''' Name: Muhammad Khan Date: 03/20/2019 Assignment06 ''' import mailroom as m import pytest as p import os import sys def test_quit(): with p.raises(SystemExit): assert m.quit() def test_email_message(): msg = """ \rDear {:}, \rThank you so much for your generous donation of $ {:.2f}. ...
null
students/MzKhan/lesson10/mailroom/test_mailroom.py
test_mailroom.py
py
1,670
python
en
code
null
code-starcoder2
51
269940010
from torch import nn import torch from torch.nn import Sequential from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from hw_asr.base import BaseModel class RnnModel(BaseModel): def __init__(self, n_feats, n_class, fc_hidden=512, *args, **kwargs): super().__init__(n_feats, n_class, ...
null
hw_asr/model/rnn_model.py
rnn_model.py
py
1,088
python
en
code
null
code-starcoder2
51
68796074
import random def build_random_list(size,max_value): """ Parameters: size : the number of elements in the lsit max_value : the max random value to put in the list """ l = [] # start with an empty list # make a loop that counts up to size i = 0 while i < size: l.append(...
null
hw_04/lists.py
lists.py
py
1,739
python
en
code
null
code-starcoder2
51
530066595
import time, multiprocessing, queue def sumPart(q, a1, a2): s1 = 0 for i in range(a1, a2 + 1): s1 += i q.put(s1) if __name__ == "__main__": threadsCount = 2 limit = 2000000 da = int(limit / threadsCount) + (1 if (limit % threadsCount) > 0 else 0) print (da) threads = [] q = multiprocessing.Queue() startT...
null
multiprocessingORthread/stMP.py
stMP.py
py
659
python
en
code
null
code-starcoder2
51
159077660
from oscar.apps.shipping import methods from oscar.core import prices from decimal import Decimal as D class Standard(methods.Base): code = 'standard' name = 'Standard shipping' is_tax_known = True excl_tax = D('5.00') incl_tax = D('5.00') def calculate(self, basket): print('Calculatin...
null
guautotrade/appgu/oscar/shipping/methods.py
methods.py
py
652
python
en
code
null
code-starcoder2
51
296629896
## decoder group activity import datetime def main(): De_Or_En = input("Do you want to decode or encode a message? (D/E):> ") if(De_Or_En == 'd' or De_Or_En == 'D'): theMessage = input("What message do you want to decode? \n:> ") # startTime = datetime.datetime.now() finalMsg, elapsedTi...
null
Bullin_Decoder_GroupProject.py
Bullin_Decoder_GroupProject.py
py
2,010
python
en
code
null
code-starcoder2
51
628908392
import pytest from selenium import webdriver from selenium.webdriver import ChromeOptions, FirefoxOptions @pytest.fixture def chrome_browser(): options = ChromeOptions() options.add_argument('--headless') options.add_argument('--start-fullscreen') wd = webdriver.Chrome(options=options) yield wd ...
null
hw-selenium-1/conftest.py
conftest.py
py
1,263
python
en
code
null
code-starcoder2
51
127943662
import itertools import math import sys def input(): return sys.stdin.readline()[:-1] N = int(input()) XY = [] for _ in range(N): x, y = map(int, input().split()) XY.append([x, y]) sum_distance = 0 for x, y in list(itertools.combinations(range(N), 2)): sum_distance += math.sqrt(abs(XY[x][0]-XY[y][0...
null
ABC_C/ABC145_C.py
ABC145_C.py
py
379
python
en
code
null
code-starcoder2
51
105796094
from app import app from flask import Blueprint, jsonify, request, abort from .infra import check_auth_token from .models import Comment from .service import Service from .utils import response_message comment_module = Blueprint('comment', __name__, url_prefix="/comments") def web_filter(): token = request.head...
null
comments-api/app/comment/comment_api.py
comment_api.py
py
3,075
python
en
code
null
code-starcoder2
51
511748143
import csv import sqlite3 def load_csv(data, csv_file): with open(csv_file) as f: f_reader = csv.reader(f) # Skip Headers next(f_reader) for row in f_reader: data.append(row) def create_table(name, c): # # Create table if doesnt exist c.execute('''CREATE TABLE...
null
src/actors/player_class_seed.py
player_class_seed.py
py
1,529
python
en
code
null
code-starcoder2
51
151211167
#!/bin/python3 import math import os import random import re import sys def calculateDNA (genes , health , first , last , d) : sum = 0 for indx in range(len(d)) : st = d[indx:] for i , g in enumerate(genes) : if i >= first and i <= last : try : ...
null
Python/CalculateDNA.py
CalculateDNA.py
py
970
python
en
code
null
code-starcoder2
51
231416434
#!/usr/bin/env python from __future__ import print_function from astropy.io import fits import numpy as np import argparse import sys import os def stack(files, out): """ Combine a list of fits files into a single cube and save the output to out. Parameters ---------- files : list Lis...
null
make_cube.py
make_cube.py
py
1,808
python
en
code
null
code-starcoder2
51
237554207
import logging import json import sys from collections import namedtuple from datetime import datetime, timedelta, time from functools import wraps from telegram.ext import CommandHandler, Updater from telegram import ParseMode from dbmanager import DBManager as dbm from extras import * # load config with open("conf...
null
bot.py
bot.py
py
14,398
python
en
code
null
code-starcoder2
51
217803979
file_obj = open("rna_codon.txt", 'r') codon_raw = file_obj.readlines() codon_raw2 = [elem.strip('\n') for elem in codon_raw] # no argument splits at any whitespace codon_raw3 = [elem.split() for elem in codon_raw2] rna_dict = {} # select which in list are codons, which are amino acids codons = [0, 2, 4, 6] aas = [...
null
rosalind_py/read_in_codon.py
read_in_codon.py
py
766
python
en
code
null
code-starcoder2
51
70817364
import torch import torch.nn as nn import torch.nn.functional as F from torch import optim from torch.utils.data import DataLoader from HIGHLIGHTdataset import SEVDataset import argparse import numpy as np import os from tqdm import tqdm import time import IPython from torchvision import datasets, transform...
null
pretrain/HIGHLIGHTclassifier/efficientnet_train.py
efficientnet_train.py
py
8,333
python
en
code
null
code-starcoder2
50
653390793
########################################## # # # Draw a house! # # # ########################################## # Use create_line(), create_rectangle() and create_oval() to make a # drawing of a house using the tKin...
null
70-100pt.py
70-100pt.py
py
1,463
python
en
code
null
code-starcoder2
50
239125907
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def assert_parameters(file_, parameters): for k, v in parameters.items(): assert file_.contains("{} = {}".format(k, v)) def test_h...
null
molecule/default/tests/test_sysctl.py
test_sysctl.py
py
829
python
en
code
null
code-starcoder2
50
572708343
# coding: utf-8 """ restccnu::apis::apartment ````````````````````````` 部门信息 :MAINTAINER: neo1218 :OWNER: muxistudio """ _apartment_list = [ { 'apartment': "学生事务大厅", 'phone': ["67865591"], 'place': "文华公书林(老图书馆)3楼" }, { 'apar...
null
restccnu/spiders/apartment.py
apartment.py
py
2,150
python
en
code
null
code-starcoder2
50
60826114
# Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO" # le-se cidade[:5].capitalize() == 'Santo' --> se a cidade e igual == a 'Santo' cidade = str(input('Informe o nome de sua cidade: ')).strip() dividido = cidade.split() print('Santo' in dividido[0].capitalize()) #print(cid...
null
desafio24.py
desafio24.py
py
539
python
en
code
null
code-starcoder2
50
4519184
# urlretrieve : 요청하는 url의 정보를 로컬 파일로 저장 # csv 파일, api 데이터 등 많은 양의 데이터를 한꺼번에 저장할 때 사용 # 좋아하는 연예인 사진 저장하기 import urllib.request as req # 요청 url img_url = "https://search.pstatic.net/common/?src=http%3A%2F%2Fimgnews.naver.net%2Fimage%2F5242%2F2014%2F03%2F08%2F1394221104_thumb_59_20140308045602.jpg&type=sc96...
null
urllib/urlretrieve3.py
urlretrieve3.py
py
619
python
en
code
null
code-starcoder2
50
555225421
import curses from windows.window import Window class StatusWin(Window): def __init__(self, lines, cols, begin_y, begin_x, parent): super().__init__(lines, cols, begin_y, begin_x, parent) self.controller = self.parent.controller self.status = "Default mode" self.currentInput = "" ...
null
windows/status_win.py
status_win.py
py
4,608
python
en
code
null
code-starcoder2
50
89721936
from django.conf.urls import include, url from rest_framework import routers from olo.api import views as olo_api_views router = routers.DefaultRouter() router.register(r'match', olo_api_views.MatchView, 'match') urlpatterns = [ url(r'^', include(router.urls)), url(r'^userlist/$', olo_api_views.UserlistAPIVi...
null
olo/urls.py
urls.py
py
508
python
en
code
null
code-starcoder2
50
322896154
#!/usr/bin/env python # coding: utf-8 # In[4]: import numpy as np import matplotlib import matplotlib.pyplot as plt import pandas as pd from pandas import DataFrame import sys import array # In[5]: df_data = pd.read_csv("BITS AIC 2019 - Reflexis Raw Dataset (1).csv") # In[6]: df_cs = pd.read_csv("wow.csv") ...
null
AIC-Mean.py
AIC-Mean.py
py
1,647
python
en
code
null
code-starcoder2
50
553457420
import requests from os import path import os import http.cookiejar agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36' header = { 'HOST' : 'www.zhihu.com', 'referer' : 'https://www.zhihu.com/', 'user-agent' : agent } from selenium import webd...
null
ArticleSpider/ArticleSpider/utils/zhihu_login_requests.py
zhihu_login_requests.py
py
1,547
python
en
code
null
code-starcoder2
50
440657111
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 15 16:43:47 2017 @author: stevedeng """ import tkinter as tk from tkinter import ttk class tdList(tk.Tk): def __init__(self, tasks=None): super().__init__() self.title("TO DO APP") self.geometry("500x7...
null
src/todoList.py
todoList.py
py
3,920
python
en
code
null
code-starcoder2
51
428871614
#!/usr/bin/env python """Problem Set 1 Code for QCB505 Fall 2020 """ import numpy as np import matplotlib.pyplot as plt __author__ = "Scott Wolf" __date__ = "20200908" __credits__ = ["Scott Wolf"] __version__ = "1" __status__ = "Prototype" __url__ = "https://www.dropbox.com/sh/jauik83zfg0rtfe/AACugg-_9g4Mfo2fPIUq_z...
null
20200908_pset/20200908_pset.py
20200908_pset.py
py
1,551
python
en
code
null
code-starcoder2
51
111810308
import re import binascii from collections import OrderedDict from Crypto.Cipher import AES import cloudscraper import requests session = cloudscraper.create_scraper(interpreter='native', debug=False) def makeCookie(response): if 'slowAES.decrypt' in response.text: try: cryptVars = OrderedDict...
null
new-bypass.py
new-bypass.py
py
1,618
python
en
code
null
code-starcoder2
51
325556325
import gc import os import numpy as np import pandas as pd import torch from torch.utils import data class BenchmarkDataset(data.Dataset): def __init__(self, X, y): self.X = X self.y = y self.divide = False self.is_test = False self.debug = False def __len__(self):...
null
pytorch/torch_dataset.py
torch_dataset.py
py
883
python
en
code
null
code-starcoder2
51
209793644
import os import pickle import torch from torch import optim from core.network import LSTM, train, test # Load DataLoader DATA_PATH = os.path.join('..', 'data') DATA_NAME = 'data_loader.pkl' with open(os.path.join(DATA_PATH, DATA_NAME), 'rb') as f: data_dict = pickle.load(f) train_dl = data_dict['train_dl'] val_...
null
train.py
train.py
py
1,057
python
en
code
null
code-starcoder2
51
243793853
import requests import pymysql from bs4 import BeautifulSoup def download_page(url): headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0"} resource = requests.get(url, headers=headers) html = resource.text return html def get_article_list_from_html...
null
com/hello/crawler/1_qiushibaike_crawler.py
1_qiushibaike_crawler.py
py
2,353
python
en
code
null
code-starcoder2
51
46985470
import requests from bs4 import BeautifulSoup as bs import os def getTitle(soup): title=str(soup.find('div',attrs={'class':'red title'})) return title[title.find("title")+7:title.find("</div")] def comeonUrl(): url=input("input page's url : ") try: driver=requests.get(url) except: p...
null
Source/comeonURL.py
comeonURL.py
py
1,241
python
en
code
null
code-starcoder2
51
325147570
# Autoplay videodirectory import os, xbmc # set path to dir you want to play path="/mnt/movies/" dirList=os.listdir(path) videoList = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) videoList.clear() for fname in dirList: videoList.add(path + "\\" + fname) # shuffle playlist videoList.shuffle() # play playlist xbmc.Pla...
null
autoexec.py
autoexec.py
py
420
python
en
code
null
code-starcoder2
51
291217303
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'jfsu' import sys import os BASE_DIR = os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ) sys.path.append(BASE_DIR) from conf import config class users(object): def __init__(self): self.users_file = config.USERS_FILE+"user_db.txt" ...
null
第三部分,模块,面向对象/FTP作业 -实现简单ftp功能/FTP/core/userAuth.py
userAuth.py
py
881
python
en
code
null
code-starcoder2
51
541401871
from django.urls import path from . import views from django.contrib.auth.views import logout app_name = 'todo' urlpatterns = [ path('', views.home_view, name='index'), path('logout/', logout, {'next_page': 'todo:index'}, name='logout'), path('add', views.TodoCreateView.as_view(), name='add_todo'), pa...
null
todo/urls.py
urls.py
py
534
python
en
code
null
code-starcoder2
51
310803468
from htmlshow import * import datetime import locale locale.setlocale(locale.LC_TIME, "fr_FR") # swedish ''' # font-size:17px; font-family:pixlim; font-family:maniaccompact; font-family:smallishnarrow; font-family:consolas; font-family:smallishunaligne; font-size:...
null
_projlab/calendar-jog/cal2020-2.py
cal2020-2.py
py
7,239
python
en
code
null
code-starcoder2
51
50993001
# -*- coding: utf-8 -*- """ This code is open-sourced software licensed under the MIT license""" """ Copyright 2019 Marta Cortes, UbiComp - University of Oulu""" """ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to d...
null
Environmental/thess_env_cityofthess_dailyyearly.py
thess_env_cityofthess_dailyyearly.py
py
9,577
python
en
code
null
code-starcoder2
51
307690580
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException import chromedriver_binary # Adds chromedriver binary to path import functools #for error handling import re from time import sleep #to pause execution def exception(fn): ...
null
Forms/it-form-request.py
it-form-request.py
py
3,003
python
en
code
null
code-starcoder2
51
535691735
# coding: utf8 from __future__ import unicode_literals import argparse import os import sys import traceback from beastling.beastxml import BeastXml from beastling.report import BeastlingReport from beastling.report import BeastlingGeoJSON import beastling.configuration from beastling.extractor import extract def er...
null
beastling/cli.py
cli.py
py
5,078
python
en
code
null
code-starcoder2
51
248345009
from collections import OrderedDict from random import randint mydict = OrderedDict() mydict1 = dict() for i in range(1,31,1): n = randint(1,101) mydict[i] = i*2 mydict1[i] = i*2 # for i in range(2,31,3): # n = randint(1,101) # mydict[i] = i*2 # mydict1[i] = i*2 # # for i in range(3,31,3): # ...
null
com/ishaan/python/CollectionsExamples/OrderedDicts.py
OrderedDicts.py
py
565
python
en
code
null
code-starcoder2
51
105417969
# graphicsUtils.py # ---------------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero (denero@cs.berkeley.edu) and Dan Klei...
null
week03_model_free/crawler_and_pacman/seminar_py3/graphicsUtils.py
graphicsUtils.py
py
11,760
python
en
code
null
code-starcoder2
51
352731255
# Heuristic Greedy algorithm to deal with the Knapsack problem import readData print("Greedy Algorithm") print("- - - - - - - - - - - - - - - - - ") data, capacity = readData.main() print("DATA____:", data, "CAPACIRY____:", capacity) container = [] # the container to contain the objects in solution = [0] * len(data...
null
greedy.py
greedy.py
py
1,870
python
en
code
null
code-starcoder2
51
320849235
class Solution(object): def checkIfExist(self, arr): """ :type arr: List[int] :rtype: bool """ arr2 = [] for idx,num in enumerate(arr): arr2[:] = arr[:] arr2.pop(idx) if (num*2 in arr2): return True b...
null
Python/1346_Check_If_N_and_Its_Double_Exist.py
1346_Check_If_N_and_Its_Double_Exist.py
py
359
python
en
code
null
code-starcoder2
51
264514867
""" To draw Ref marker and Stop marker on A4 paper (A4 size = 210 x 297 mm) """ import cv2 import numpy as np paper_size = 2100, 2100 center = paper_size[0]//2, paper_size[1]//2 cross_size = 20 normal_marker = np.ones(paper_size)*255 cv2.circle(normal_marker, center, 940, (180, 180, 180), thickness=2) cv2.circle(n...
null
draw_marker.py
draw_marker.py
py
1,319
python
en
code
null
code-starcoder2
51
499967764
""" Author : ParkEunsik Date : 2019/07/16 url : https://www.acmicpc.net/problem/11650 """ import sys from operator import itemgetter coor = [] for i in range(int(sys.stdin.readline())): coor.append(list(map(int, sys.stdin.readline().split()))) coor.sort(key=itemgetter(0, 1)) # 우선적으로 y정렬하고 그 다음 ...
null
11650/11650.py
11650.py
py
414
python
en
code
null
code-starcoder2
51
519429431
# created: 2018-12-01 # see 'parser' for expected command-line arguments # goal: be FAST!!! ''' to test, run something like: python3 compare_inventories.py inventory-files_do-not-add-to-git/2018-12-15-imac-pro.jsonl inventory-files_do-not-add-to-git/2018-12-29-imac-pro.jsonl > /tmp/out TODOs: - display moved files ...
null
compare_inventories.py
compare_inventories.py
py
32,402
python
en
code
null
code-starcoder2
51