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
127045110
# 这样处理是错的:处理[3, 4]的时候, left=3, right=4, mid=3, 最后传入的时候list=[3, 4], # 因为它是按分开后的数据重新计数, 此时list的索引是从0开始的 # def merge_sort(list, left, right): # if len(list) <= 1: # return list # mid = int((left + right)/2) # left_list = merge_sort(list[: mid+1], left, mid) # right_list = merge_sort(list[mid+1:], ...
null
dir_sort/merge_sort.py
merge_sort.py
py
1,224
python
en
code
null
code-starcoder2
51
166823333
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 4 10:51:54 2018 @author: matthewszhang """ import time import os import os.path as osp import numpy as np from baselines import logger from collections import deque from baselines.feudal.models import I2AModel from baselines.feudal.runners impo...
null
baselines/feudal/i2a.py
i2a.py
py
6,286
python
en
code
null
code-starcoder2
51
51125941
#!/usr/bin/env python """ Add seizure names to LR results Input: LR_results, name = "obs_LRs.{species}.txt" Seizure file matching sample names to seizures """ import argparse def run(input_file, seizure_file): with open(input_file, 'r') as infile: header = infile.readline().strip().split('\t') ...
null
data_analysis/post_processing/1_add_seizures.py
1_add_seizures.py
py
1,504
python
en
code
null
code-starcoder2
51
432095531
#!/usr/bin/env python import os import sys import time import signal import argparse import project_root from os import path from subprocess import Popen, call from helpers.helpers import get_open_udp_port def run(args): # run worker.py on ps and worker hosts for job_name in ['ps', 'worker']: host_li...
null
a3c/train.py
train.py
py
3,739
python
en
code
null
code-starcoder2
51
433096351
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.Index.as_view(), name='index'), url(r'^clubs/$', views.ClubList.as_view(), name='club_list'), url(r'^clubs/add/$', views.ClubCreate.as_view(), name='club_create'), url(r'^clubs/(?P<club_slug>[\w-]+)/$', views.ClubDet...
null
core/urls.py
urls.py
py
1,124
python
en
code
null
code-starcoder2
51
389482296
import notifications from django.conf.urls import patterns, include, url from django.contrib import admin from app.views import ProjectViewSet, TaskViewSet, UserViewSet, ChatRoomViewSet, ChatViewSet from rest_framework import routers from django.conf import settings admin.autodiscover() router = routers.DefaultRouter(...
null
mybeez/urls.py
urls.py
py
2,033
python
en
code
null
code-starcoder2
51
585238684
def get_candies(ratings): if len(ratings) == 1: return 1 candies = list(1 for r in ratings) minima = list() for i,r in enumerate(ratings): prevr = ratings[i-1] if i > 0 else 10**6 nextr = ratings[i+1] if i < len(ratings)-1 else 10**6 if r <= prevr and r <= nextr: ...
null
algorithms/dynamic/candies.py
candies.py
py
844
python
en
code
null
code-starcoder2
51
618714890
# Import utilities import datetime from enum import Enum class Person: # Define gender enum class Sex(Enum): MALE = 1 FEMALE = 2 # Defining a method to print cumulative data for the family def print_data(self): print(self.name.title() + " " + self.last_name.title(...
null
Python version/Person.py
Person.py
py
1,421
python
en
code
null
code-starcoder2
51
510382768
""" print: (a), (b), (c), (d), (e), ...... (z) (a,b), (a,c), (a,d), ... (y,z) ... (a,b,c,d, ...,x,y,z) """ import string def calcPerm(s, temp, num, total, fro, to, array): if num > total: return if num == total: array.append(f"({','.join(temp)})") else: for i in range(fro, to+1): ...
null
learning-algorithm-book/1/1-3.py
1-3.py
py
651
python
en
code
null
code-starcoder2
51
518498478
def fibonacci(n): a=0 b=1 print ("The fibonacci series is:") print (a, end=" ") print (b, end=" ") for i in range(n-2): c=a+b a=b b=c print (c, end=" ") fibonacci(10)
null
Fibonacci.py
Fibonacci.py
py
251
python
en
code
null
code-starcoder2
51
275249893
import sys from model import SOS, EOS, PAD from utils import tokenize MIN_LENGTH = 3 MAX_LENGTH = 50 def load_data(): data = [] vocab_src = {PAD: 0, EOS: 1, SOS: 2} vocab_tgt = {PAD: 0, EOS: 1, SOS: 2} fo = open(sys.argv[1]) for line in fo: src, tgt = line.split("\t") tokens_src = ...
null
prepare.py
prepare.py
py
1,734
python
en
code
null
code-starcoder2
51
591538766
#coding=utf-8 # from selenium import webdriver # import time # browser=webdriver.Chrome() # browser.get("http://www.baidu.com") # time.sleep(5) # browser.quit() # from selenium import webdriver # driver=webdriver.Chrome() # driver.get("http://www.baidu.com") # print("浏览器最大化") # driver.maximize_window()#浏览器最大化 # driver....
null
Webtest/practice.py
practice.py
py
1,087
python
en
code
null
code-starcoder2
51
425628398
import numpy as np from keras.models import Sequential from keras.layers.core import Dense EPOCHS=2000 training_data = np.array([[0,0],[0,1],[1,0],[1,1]], "float32") target_data = np.array([[0],[1],[1],[0]], "float32") model = Sequential() model.add(Dense(16, input_shape=(2,), activation='relu')) model.add(Dense(1, ...
null
day16/mykeras02.py
mykeras02.py
py
693
python
en
code
null
code-starcoder2
51
110446893
class Node: data = -1 left = None right = None def __init__(self, data): self.data = data def buildBTRec(): d = int(input()) if d == -1: return None root = Node(d) root.left = buildBTRec() root.right = buildBTRec() return root def preorder(root): if(root == None): return print(root.data, end = ...
null
Basic_Data_Structures_Python/Lecture 18/BinaryTree.py
BinaryTree.py
py
1,339
python
en
code
null
code-starcoder2
51
481478560
#守护进程 #守护进程会随着主进程的代码执行结束而结束 #正常的子进程没有执行完的时候主进程要一直等着 #守护进程不能再开户子进程 import time from multiprocessing import Process def cal_time(): while True: time.sleep(1) print("过去了1s") if __name__ == '__main__': p = Process(target=cal_time) p.daemon = True # 一定在开启进程之前设置 p.start() for i in range(...
null
process/process_daemon.py
process_daemon.py
py
517
python
en
code
null
code-starcoder2
51
571550198
import unittest from torch.distributions import Normal, Exponential, Independent, LogNormal from pyfilter.filters import UKF, APF from pyfilter.timeseries import AffineProcess, LinearGaussianObservations from pyfilter.utils import concater from pyfilter.normalization import normalize import torch from pyfilter.inferenc...
null
test/inference.py
inference.py
py
3,115
python
en
code
null
code-starcoder2
51
326575857
""" This is an attempt at a simple royale test. I just wanna try a simple thing that doesn't get overengineered lol. That won't happen. On a scale of 1-10 how scared are you (in this battle royale) when someone else is nearby? Then use that to calculate fear levels which change which tasks are more likely? Only likel...
null
source/simpleroyaletest.py
simpleroyaletest.py
py
15,682
python
en
code
null
code-starcoder2
51
443419789
valor = float(input('Entre com o valor do produto=')) codigo = int(input('Entre com o codigo do produto=')) if codigo == 1: desconto = valor * 0.1 valor_final = valor - desconto print('Seu produto custara = {}'.format(valor_final)) elif codigo == 2: desconto = valor * 0.05 valor_final = valor - des...
null
Algoritmos - Python/Exercicios Python/exercicio11_2.8.py
exercicio11_2.8.py
py
784
python
en
code
null
code-starcoder2
51
230453446
#!/usr/bin/python3 """List all State objects from db""" import sys from sqlalchemy import create_engine from sqlalchemy.orm import Session from model_state import Base, State def first_state(): """ Arguments argv to connect to database argv[1]: mysql username argv[2]: mysql password argv[3]: database ...
null
0x0F-python-object_relational_mapping/8-model_state_fetch_first.py
8-model_state_fetch_first.py
py
813
python
en
code
null
code-starcoder2
51
166077480
import curses from output import OutputModule from input import InputModule from domains.Student import * from domains.Course import * from domains.Mark import * class MainModule: # main s = int(student_num()) l = 1 while l <= s: l += 1 add_student() show_list_student() c = in...
null
pw4/main.py
main.py
py
685
python
en
code
null
code-starcoder2
51
511095428
# coding=utf-8 """ pygame-menu https://github.com/ppizarror/pygame-menu WIDGET Base class for widgets. License: ------------------------------------------------------------------------------- The MIT License (MIT) Copyright 2017-2020 Pablo Pizarro R. @ppizarror Permission is hereby granted, free of charge, to any pe...
null
tetris/venv/Lib/site-packages/pygame_menu/widgets/core/widget.py
widget.py
py
26,029
python
en
code
null
code-starcoder2
51
279812286
import math num =2 result =0 wow=1 def find(n): check = int(math.sqrt(n))+1 for i in range(2,check): if n%i==0: return False return True while True: if find(num)==True: if wow==10001: result=num break wow=wow+1 num=num+1 print(result)
null
ProjectEuler/p7.py
p7.py
py
319
python
en
code
null
code-starcoder2
51
122682778
import collections class Graph: def __init__(self,v): self.nv=v self.graph=collections.defaultdict(list) self.count=0 def checkbc(self): ss=self.nv visited=[False]*ss d=[float('inf')]*ss low=[float('inf')]*ss parent=[-1]*ss if sel...
null
bicon.py
bicon.py
py
1,514
python
en
code
null
code-starcoder2
51
369843511
# -*- coding: utf-8 -*- import unittest from pageobjects.baidu_homepage import Baidupage from framework.browser_engine import Browser_open class Test_search(unittest.TestCase): def setUp(self): b = Browser_open() self.driver = b.browseropen() def tearDown(self): self.driver.qui...
null
selenium/src/testsuits/test_search.py
test_search.py
py
1,004
python
en
code
null
code-starcoder2
51
436405346
from flask_restplus import Api, Resource, fields from werkzeug.contrib.fixers import ProxyFix from flask import Flask, url_for, jsonify from elasticsearch import Elasticsearch import json ### Setup elastic search connection es_host = {"host": "elasticsearch1", "port": 9200} es = Elasticsearch([es_host], retry_on_timeo...
null
elastic-stack-geonames-cities/geonames-cities-api/geonames-cities-api-using-payload.py
geonames-cities-api-using-payload.py
py
4,546
python
en
code
null
code-starcoder2
51
622131904
import numpy import math execfile(os.path.join(os.path.dirname(__file__), 'rotations.py')) import numpy def rpyFunction(msg): return quat_to_euler([msg.pose.rotation.w, msg.pose.rotation.x, msg.pose.rotation.y, msg.pose.rotation.z]) def rollFunction(msg): '''roll''' return msg.utime, rpyFunction(msg)[0]*...
null
software/config/signal_scope/val/forcetorque.py
forcetorque.py
py
2,059
python
en
code
null
code-starcoder2
51
506532697
import os from dotenv import load_dotenv import pymongo import datetime from bson.objectid import ObjectId from flask import Flask, request, render_template, redirect, url_for, session, flash from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, login_required import bcrypt from functo...
null
app.py
app.py
py
18,677
python
en
code
null
code-starcoder2
51
472460838
# -*- coding: utf-8 -*- """ Deck of character cards. """ import csv from deck import Deck class CharacterCard: def __init__(self, cdict): self.category = cdict['category'] self.name = cdict['name'] self.effect1 = cdict['effect1'] self.effect2 = cdict['effect2'] ...
null
src/ui/character_deck.py
character_deck.py
py
2,719
python
en
code
null
code-starcoder2
51
632017191
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import * from scipy.interpolate import * from scipy.optimize import * # integration def f(x): return 3.0*x*x +1.0 I,err=quad(f,0,1) print("I= ",I,"err: ",err) x_given=np.linspace(0,10,10) y_given=np.cos(x_given**2.0/8.0) xx=np...
null
Bases/Section1.py
Section1.py
py
1,605
python
en
code
null
code-starcoder2
51
458971686
from products.models import Product from users.models import User from .models import OrderItem, Order from rest_framework import generics, status, permissions, pagination from core.permissions import * from rest_framework.response import Response from .serializers import * from django_filters.rest_framework import Dj...
null
core/orders/views.py
views.py
py
8,279
python
en
code
null
code-starcoder2
51
64128467
# encoding: UTF-8 from __future__ import absolute_import, unicode_literals from celery import shared_task from dapps.celeryCommon import RetryableError, Retryable, getMappedAs from dapps.sinaMaster.worker import thePROG import dapps.sinaCrawler.tasks_Dayend as CTDayend import crawler.crawlSina as sina import crawler...
null
src/dapps/sinaMaster/tasks_Archive.py
tasks_Archive.py
py
34,068
python
en
code
null
code-starcoder2
51
529211345
alternate_ir = 0.0 apd_Temperature = -9999 confidence_threshold = 1 depth_offset = 4.5 depth_units = 0.000250000011874363 digital_gain = 2 enable_ir_Reflectivity = 0.0 enable_max_usable_range = 0.0 error_polling_enabled = 1 frames_queue_size = 16 freefall_detection_enabled = 1 global_time_enabled = 0.0 host_performance...
null
misc/const.py
const.py
py
925
python
en
code
null
code-starcoder2
51
60173586
import re if __name__ == '__main__': print("<div style=\"margin:2em; background-color: #e0e0e0;\">", end="\n\n") try: lines = [] while True: try: line = input() lines.append(line) except EOFError: break lines = filt...
null
docs/data/learn/Bioinformatics/input/prereq_macro_block/input/Main.py
Main.py
py
576
python
en
code
null
code-starcoder2
51
338668698
from django.shortcuts import render, redirect from .models import * from df_user import user_decorator from django.http import JsonResponse # Create your views here. @user_decorator.login def cart(request): user_id = request.session.get('user_id') carts = CartInfo.objects.filter(user_id=int(user_id)) cont...
null
df_cart/views.py
views.py
py
1,549
python
en
code
null
code-starcoder2
51
114539526
import sys import os import hashlib import urllib.request def get_hash(name): readsize = 64 * 1024 with open(name, 'rb') as f: size = os.path.getsize(name) data = f.read(readsize) f.seek(-readsize, os.SEEK_END) data += f.read(readsize) return hashlib.md5(data).he...
null
main.py
main.py
py
1,222
python
en
code
null
code-starcoder2
51
400967713
#!/usr/bin/env python import rospy import numpy import tf import tf2_ros import geometry_msgs.msg def message_from_transform(T): msg = geometry_msgs.msg.Transform() q = tf.transformations.quaternion_from_matrix(T) translation = tf.transformations.translation_from_matrix(T) msg.translation.x = translation[0] msg.t...
null
myCode/catkin_ws/src/tf2_examples/scripts/tf2_examples.py
tf2_examples.py
py
2,269
python
en
code
null
code-starcoder2
51
380117872
# Paul J. Ruess # University of Illinois at Urbana-Champaign # Fall 2017 # Personal Research # US Virtual Water Storage by County import pandas ### READ IN RAW DATA ### class alldata: """Class for reading in and cleaning harvest, yield, and storage values from raw USDA data in .csv format""" ...
null
research/grain_storage/archives/calculate_county_vws_0.py
calculate_county_vws_0.py
py
15,780
python
en
code
null
code-starcoder2
51
609285759
import logging from qwdeploy import exception LOG = logging.getLogger(__name__) class Deploy(object): """Deploy a Stack""" name = 'deploy' help = __doc__ params = [] def run(self): raise exception.QwdeployError("command not implemented")
null
qwdeploy/commands/deploy.py
deploy.py
py
272
python
en
code
null
code-starcoder2
51
549886257
''' Using Reddit's api/v1/ ''' import os import requests import requests.auth import sys import time from .local_settings import * from ..write_joke import * # Files to read and write jokes = '/Users/joannejordan/Desktop/GitHub/dad-joke-ai/dadjokes-subreddit-\ archive/otherrjokes.csv' records = '/Users/joannejordan/D...
null
subreddits/limited_results_scripts/reddit_requests.py
reddit_requests.py
py
4,290
python
en
code
null
code-starcoder2
51
580020519
import numpy as np import math import networkx as nx import pickle,os from copy import deepcopy,copy from numpy import linalg as LA def checks(A,B,e): for eachA in range(len(A)): for eachB in range(len(A[0])): if abs(A[eachA][eachB] - B[eachA][eachB]) > e: return False ret...
null
bioDRN/blondel.py
blondel.py
py
3,679
python
en
code
null
code-starcoder2
51
204011246
ansl = [] MOD = 10**9+7 for _ in range(int(input())): n,a,b = map(int, input().split()) if a+b > n: ansl.append(0) continue d = n-a-b no_cross = (d+1)*(d+2) no_cross %= MOD ans1 = no_cross * (n-a+1) * (n-b+1) ans1 %= MOD cross = (n-a+1)*(n-b+1) - no_cross ans2 = n...
null
1_contest/previous/hhkb2020/d.py
d.py
py
501
python
en
code
null
code-starcoder2
51
375993987
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/05/02 13:40 # @Author : c0l0121 # @File : searcher.py # @Desc : def binary_search(array, value): """ 查找所给数值在有序数组中的位置,找不到则返回-1 :param array: 数组 :param value: 待查找的数值 :return: 找到则返回数值在数组中的下标,否则返回-1 """ ret = -1 start = 0 ...
null
data_structure/searcher.py
searcher.py
py
1,414
python
en
code
null
code-starcoder2
51
159965973
from collections import deque def wiki(xs): current_max_len = 0 m = [0 for x in xs] preds = [0 for x in xs] longest = 0 for i, x in enumerate(xs): lo, hi = 1, current_max_len mid = (lo + hi) // 2 if xs[m[mid]] < x: lo = mid + 1 else: hi = mi...
null
longest_increasing_subsequence.py
longest_increasing_subsequence.py
py
847
python
en
code
null
code-starcoder2
51
253861775
from random import choice import random import aiohttp import discord from discord.ext import commands from .utils.chat_formatting import * from .utils.dataIO import dataIO from .utils.dataIO import fileIO from cogs.utils import checks class TrustyBot: def __init__(self, bot): self.bot = bot self....
null
trustybot/trustybot.py
trustybot.py
py
9,979
python
en
code
null
code-starcoder2
51
282268603
#!coding:utf-8 import execjs import re import requests from urllib3 import disable_warnings from requests import Session import wx import io import time import uuid import json import base64 import sys import Crypto import traceback from Crypto.Cipher import AES # SECRET_KEY = 'B123JDVgT8WDGOWBgQv6EIhvxl4vDYvUnVdg-Vjd...
null
uploadFiles/ymc/main_old.py
main_old.py
py
104,427
python
en
code
null
code-starcoder2
51
288467779
# Copyright (c) 2021 The Toltec Contributors # SPDX-License-Identifier: MIT """Build recipes and create packages.""" import shutil from typing import ( Any, Deque, Dict, Iterable, List, MutableMapping, Optional, Tuple, ) from collections import deque import re import os import logging i...
null
scripts/toltec/builder.py
builder.py
py
16,413
python
en
code
null
code-starcoder2
51
73170860
#!/usr/bin/env python # coding: utf-8 import sys from hashlib import md5 from six import print_ def mine(secret): i = 0 while True: current = secret + str(i).encode("ascii") digest = md5(current).digest() if digest[0] == 0 and digest[1] == 0 and digest[2] <= 0x0f: return i ...
null
day4-1.py
day4-1.py
py
421
python
en
code
null
code-starcoder2
51
522031771
# -*- coding: utf-8 -*- from pytorchtools import EarlyStopping import torch import torch as t import torch.autograd as autograd import torch.nn as nn import torch.optim as optim from torch_model.Deep_NMT_model import LMLoss from torch_model.Attention_NMT import AttentionNMT from data.iwslt_Data_Loader import iwslt_Dat...
null
torch_attention_nmt.py
torch_attention_nmt.py
py
6,653
python
en
code
null
code-starcoder2
51
85523096
import pandas as pd import numpy as np import nltk from tensorflow.keras.utils import to_categorical from nltk import RegexpTokenizer from nltk.corpus import stopwords, wordnet try: nltk.data.find('tokenizers/punkt') except LookupError: nltk.download('punkt') try: nltk.data.find('corpus/stopwords') except...
null
src/TextDataset.py
TextDataset.py
py
5,582
python
en
code
null
code-starcoder2
51
431667763
# Jeff Austin # 7/16/2019 # Portland State University # CS350 # Daniel LeBlanche # HW3 # Merge sort code in pyhton 3 import sys import random import time import math # merge sort algorithm # taken from D. LeBlanche's slides: http://web.cecs.pdx.edu/~dleblanc/cs350/sorting.pdf def merge_sort(A): if len(A) == 0: ...
null
already_sorted_merge_sort.py
already_sorted_merge_sort.py
py
2,051
python
en
code
null
code-starcoder2
51
460143201
#Apresentação print('Conversor de binario para decimal') print('---------------------------------') #Valor do numero binario x = int(input('Digite o numero binario com no maximo 4 digitos: ')) #Calculos e condições if x >= 1: dig1 = x % 10 x = x - dig1 rdig1 = x % 100 else: dig1 = 0...
null
Python/Fabio lista 1/Fabio_01_Q31.py
Fabio_01_Q31.py
py
707
python
en
code
null
code-starcoder2
50
508787170
from pulp import * import time as time import numpy as np a = 10 NODE_CPU_INDEX = 0 NODE_MEMORY_INDEX = 1 NODE_POD_SPACE_INDEX = 2 POD_CPU_INDEX = 0 POD_MEMORY_INDEX = 1 podList = [ [10, 3], [10, 1], [10, 3] ] nodeList = [ [30, 5, 9], [40, 3, 7] ] def schedule_solve(podList, nodeList, VERBOSE =...
null
lp-solver.py
lp-solver.py
py
2,294
python
en
code
null
code-starcoder2
50
585383765
import tarfile import numpy as np from glob import glob from .utilities import * # PARSING UTILITY FUNCTIONS ==================================================== def get_files(path, name): """Gets list of files from directory.""" return glob(f"{path}**/{name}*.tar.xz") + glob(f"{path}**/{name}*.json") def ge...
null
scripts/parse.py
parse.py
py
4,195
python
en
code
null
code-starcoder2
50
40251915
#%% Project Euler Problem 6 # Justin Kim # Difference between the square of the sum and the sum of the squares def problem6(n): sumsq = 0 sqsum = 0 for i in range(n + 1): sumsq += i**2 sqsum += i sqsum *= sqsum ans = sqsum - sumsq return ans ans = problem6(100)
null
old/P6.py
P6.py
py
303
python
en
code
null
code-starcoder2
50
417326244
# Solved by Sunghyun Cho on August 25th, 2018. houseNum = int(input()) xList = [] yList = [] for a in range(houseNum): arr = input().split() xList.append(float(arr[0])) yList.append(float(arr[1])) print(sum(xList)/len(xList), sum(yList)/len(yList)) # ?????
null
4. 우물왕 김배찌/Q4.py
Q4.py
py
263
python
en
code
null
code-starcoder2
50
355276877
import argparse import datetime import os import pickle import uuid import torch import matplotlib.pyplot as plt import numpy as np from PIL import Image from moviepy.editor import VideoFileClip from torch.autograd import Variable from torchvision import transforms from .model import EncoderCNN, DecoderRNN def ...
null
lib/caption.py
caption.py
py
2,904
python
en
code
null
code-starcoder2
51
228051984
#WebGen for Windows by Liam Platt import os def GetSiteName(): '''Collects a name for the site''' SiteNameConfirm = "n" while SiteNameConfirm != "y": SiteName = input("Enter name of web site: ").lower() print() SiteNameConfirm = input("You entered '"+SiteName.title()+"', is this co...
null
WebGen.py
WebGen.py
py
2,713
python
en
code
null
code-starcoder2
51
310143459
from django.conf.urls import url from mysite.blog.views import post_list, post_detail, post_new, post_edit urlpatterns = [ url(r'^$', post_list), url(r'^post/(?P<pk>[0-9]+)/$', post_detail), url(r'^post/new/$', post_new, name='post_new'), url(r'^post/(?P<pk>[0-9]+)/edit/$', post_edit, name='post_edit'...
null
mysite/blog/urls.py
urls.py
py
325
python
en
code
null
code-starcoder2
51
351697920
from pytorch.finetune.imports import * from system.imports import * from pytorch.finetune.level_9_transforms_main import prototype_transforms class prototype_schedulers(prototype_transforms): @accepts("self", verbose=int, post_trace=False) #@TraceFunction(trace_args=True, trace_rv=True) def __init__(self...
null
monk/pytorch/finetune/level_10_schedulers_main.py
level_10_schedulers_main.py
py
8,708
python
en
code
null
code-starcoder2
51
95110167
import numpy as np import time import pygame from functools import reduce import random as ra from random import randint as ri import math as ma from pygame.locals import * from oop_phy_pygame import * # инициализация pygame pygame.init() # масштаб p = 1.91 scax = scay = 50 #40*p#87.5*p # сдвиг, в % от всего изобра...
null
oop_phy_pyg_values.py
oop_phy_pyg_values.py
py
3,205
python
en
code
null
code-starcoder2
51
6415726
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import os from pathlib import Path from datadog_checks.dev.tooling.constants import get_root, set_root from datadog_checks.dev.tooling.datastructures import JSONDict from datadog_checks.dev.tooling.manife...
null
datadog_checks_dev/tests/tooling/manifest_validator/test_validator.py
test_validator.py
py
2,193
python
en
code
null
code-starcoder2
51
308466528
# A test file for HTML reporting by coverage. def one(x): # This will be a branch that misses the else. if x < 2: a = 3 else: a = 4 one(1) def two(x): # A missed else that branches to "exit" if x: a = 5 two(1) def three_way(): # for-else can be a three-way branch. ...
null
test/farm/html/src/b.py
b.py
py
434
python
en
code
null
code-starcoder2
51
359433116
# whenever you import a file, python runs the code in that file, thats # why __name__ variable will be the the name of the file and not __main__ # now if python is running a file directly __name__ == '__main__' # This way you can run code you only want to run if the file is being ran directly # import asyncio_playgro...
null
test_imports.py
test_imports.py
py
424
python
en
code
null
code-starcoder2
51
199638814
# Objetivo: Receber 2 valores reais. Calcular e mostrar o maior deles. # Programador: Hugo Leça Ribeiro # Data de Elaboração: 24.10.2019 def Pmaior(n1, n2): if (n1 > n2): print("O maior número entre os dois é: ", n1) elif n2 > n1: print("O maior número entre os dois é: ", n2) else: ...
null
LT01_EstMod19.py
LT01_EstMod19.py
py
503
python
en
code
null
code-starcoder2
51
633401312
# -*- coding: utf-8 -*- # Author: Ji Yang <jiyang.py@gmail.com> # License: MIT import random import numpy as np from PIL import Image from torch.utils.data import Dataset from torchvision import transforms padding = transforms.Compose([transforms.Resize(160), transforms.Pad(30, padding...
null
salt_dataset_192.py
salt_dataset_192.py
py
3,801
python
en
code
null
code-starcoder2
51
48302102
for tc in range(1, 11): n = int(input()) tree = [[0]] for _ in range(n): tree.append(list(input().split())) for i in range(len(tree) - 1, 0, -1): if len(tree[i]) == 4: left = int(tree[int(tree[i][2])][1]) right = int(tree[int(tree[i][3])][1]) if tree[i...
null
SWEA/1232-사칙연산.py
1232-사칙연산.py
py
647
python
en
code
null
code-starcoder2
51
383096748
import numpy as np import matplotlib.pyplot as plt import bicycledataprocessor as bdp import canonical_system_id as csi # This gives the proportion of the lateral force which should be added to the # steer torque and roll torque equations in the canonical equations. F = {} for rider in ['Charlie', 'Jason', 'Luke']: ...
null
scripts/canonicalid/fit_canonical.py
fit_canonical.py
py
3,197
python
en
code
null
code-starcoder2
51
156326706
# coding:utf-8 # --author-- lanhua.zhou import maya.cmds as cmds import zfused_maya.node.core.check as check import zfused_maya.node.core.clear as clear import zfused_maya.widgets.checkwidget as checkwidget import zfused_maya.tool.modeling.materialcheck as materialcheck class ShadingCheck(checkwidget.CheckWidget): ...
null
zfused_maya/zfused_maya/tool/shading/shadingcheck.py
shadingcheck.py
py
7,569
python
en
code
null
code-starcoder2
51
423383072
def multiplesOf3and5(num): sum = 0 i = 1 while i < num: mul3 = i % 3 mul5 = i % 5 if mul3 == 0 or mul5 == 0: sum += i i += 1 return sum print(multiplesOf3and5(1000))
null
Python/Problem 1: Multiples of 3 and 5.py
Problem 1: Multiples of 3 and 5.py
py
182
python
en
code
null
code-starcoder2
51
285790298
n=int(input("enter the no oftimes u want run the operation")) name=list() found=list() def addword(name1): name.append(name1) def findprefix(pref): #print(pref) for i in name: if i.startswith(pref): found.append(i) for x in found: print(x,end=" ") ...
null
dictionaryProb.py
dictionaryProb.py
py
586
python
en
code
null
code-starcoder2
51
77461459
from Tkconstants import LEFT, BOTH, BOTTOM, RIGHT import Helper import Menu import Tkinter as tk import yahoo_finance as yf class Stocks(tk.Frame): def __init__(self, parent, controller): self.frame = tk.Frame self.frame.__init__(self, parent, background='red') self.parent = parent ...
null
src/Stocks.py
Stocks.py
py
2,636
python
en
code
null
code-starcoder2
51
81257666
from Crypto.Cipher import AES from Crypto.Random import random from Crypto.Util.number import long_to_bytes,bytes_to_long with open("flag_cipher","r") as f: c = f.read() f.close() c = [c[i:i+32] for i in range(0, len(c), 32)] for i in range(1, len(c)-1): cipher = AES.new(c[i], AES.MODE_ECB, "") print(cipher.dec...
null
crypto/[AFCTF2018]MyOwnCBC/fuck.py
fuck.py
py
333
python
en
code
null
code-starcoder2
51
122156768
import arcpy #CONSTANT DECLARATIONS PRIORITY_FIELDNAME = "wdpaid" # this is a bit of a hack but basically we can use this as the priority field to ensure that if the feature in question overlaps the cell by less than 50% then it will be selected #ENVIRONMENT VARIABLES arcpy.env.overwriteOutput = True arcpy.env.ou...
null
src/ProtectedAreaToRaster.py
ProtectedAreaToRaster.py
py
799
python
en
code
null
code-starcoder2
51
253514360
import logging import MySQLdb from common import ItemContainsNull class MySqlPipeline(object): def open_spider(self, spider): self.conn = MySQLdb.connect('IP', 'USERNAME', 'PASSWORD', 'TABLENAME', charset="utf8", use_unicode=True) self.cursor = self.conn.cursor() def close_spider(self, spider): self.conn.clos...
null
PriceInformation/pipelines.py
pipelines.py
py
724
python
en
code
null
code-starcoder2
51
357031212
from random import randint as age prove = print class Phil: In = { 2002: "I graduated from EE, TKU, and served in the Army.", 2004: "I entered an IC design house writing ATE programs.", 2005: "I enrolled in EE, NTNU for a master's degree.", 'the present': "I've become a teacher, sys...
null
PP.py
PP.py
py
620
python
en
code
null
code-starcoder2
51
614471316
# -*- coding:utf-8 -*- # # Copyright (C) 2008 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
null
subcmds/init.py
init.py
py
20,026
python
en
code
null
code-starcoder2
51
375771591
# This code is mainly excerpted from openai baseline code. # https://github.com/openai/baselines/blob/master/baselines/common/atari_wrappers.py import numpy as np from collections import deque import gym from gym import spaces import cv2 from abc import ABC,abstractmethod from multiprocessing import Process, Pipe from ...
null
Distributional_RL/wrappers.py
wrappers.py
py
13,103
python
en
code
null
code-starcoder2
51
279632711
import argparse import tokenizer def read_data_from_file(file_path): f = open(file_path, 'r') ret = f.read() f.close() return ret def main(args): dict_tokens = tokenizer.Tokenizer(read_data_from_file(args.dict)) dict_set = set() cur = dict_tokens.next_token() while cur is not None: ...
null
semester-1/fundamentals-of-computer-science/python/4-mistakes.py
4-mistakes.py
py
806
python
en
code
null
code-starcoder2
51
242464468
#!/usr/bin/env python # ------------------------------------------------------------------------------------------------------% # Created by "Thieu Nguyen" at 09:33, 16/03/2020 % # ...
null
mealpy/evolutionary_based/GA.py
GA.py
py
4,291
python
en
code
null
code-starcoder2
51
615031076
from flask import Flask,request,jsonify import telebot import json token="781229574:AAGC6K39EQ1VNcf2RTOlLpXg_KWoHPAZTI" app = Flask(__name__) bot=telebot.TeleBot(token) @app.route('/',methods=["POST","GET"]) def hello_world(): bot.set_webhook("https://weatherbetabot.herokuapp.com/") if request.method == "PO...
null
app/__init__.py
__init__.py
py
522
python
en
code
null
code-starcoder2
51
6181075
#import gevent.monkey #gevent.monkey.patch_all() from flask_sqlalchemy import SQLAlchemy from flask import Flask, render_template, request, Response from flask_socketio import SocketIO, join_room, emit import game from game import RequestDenied # initialize Flask from pylti.flask import lti VERSION = '0.0.1' app = Fla...
null
memory.py
memory.py
py
8,399
python
en
code
null
code-starcoder2
51
367143759
import operator def calculate_distance(self): all_distances = [] for house in self.houses.values(): x_house, y_house = house.x, house.y house_diff = {} counter = 0 for battery in self.batteries.values(): x_batt, y_batt = battery.x, battery.y x_diff = abs(...
null
test_scripts/test_area/hill_test/4th Time(ex-slowdown)/helpers.py
helpers.py
py
3,652
python
en
code
null
code-starcoder2
51
253470660
# -*- coding: utf-8 -*- from plone import api from ftw.testbrowser import browsing from ftw.testbrowser.pages import factoriesmenu from opengever.testing import IntegrationTestCase from zope.annotation.interfaces import IAnnotations class TestCreateDocFromOneoffixxTemplate(IntegrationTestCase): def setUp(self): ...
null
opengever/oneoffixx/tests/test_oneoffixx.py
test_oneoffixx.py
py
2,659
python
en
code
null
code-starcoder2
51
3002260
# coding: utf-8 # In[1]: import helper import matplotlib.pyplot as plt from keras.applications import * from keras.callbacks import EarlyStopping import os # In[2]: #设置各种参数 train_path = ['./data/train2/cat', './data/train2/dog'] test_path ='./data/test1/test1' img_size =(299,299) layer_num = 125 model_image ='....
null
p6_p7/py/fine_tuning_xception_no_outliers_final.py
fine_tuning_xception_no_outliers_final.py
py
2,225
python
en
code
null
code-starcoder2
51
126437936
from core.exceptions.exceptions import OptionValidationError class Option(object): def __init__(self, default, advanced=False): self.label = None try: self.advanced = bool(advanced) except ValueError: raise OptionValidationError("Invalid value. Cannot cast '{}' to...
null
core/resources/Option.py
Option.py
py
3,323
python
en
code
null
code-starcoder2
51
628289279
#!/usr/bin/env python3 import tensorflow import tensorflow.compat.v1 as tf from IPython import embed class Net(object): ''' CNN base ''' _X = None _y = None _num_labels = None _one_hot_y = None _mean = None _stddev = None _saver = None _learn_rate = None _dropout = None ...
null
python/model.py
model.py
py
7,311
python
en
code
null
code-starcoder2
51
405732069
def run(level): with open(f'output/{level}.txt', 'r') as f: s0 = [int(x[:-1]) for x in f.readlines()] with open(f'result/{level}.normal', 'r') as f: s1 = [int(x[:-1]) for x in f.readlines()] ret = [(max(s1[idx], s0[idx])/(min(s1[idx], s0[idx])+1e-1), idx) for idx in range(len(s1))] re...
null
lab2/analyse.py
analyse.py
py
560
python
en
code
null
code-starcoder2
51
407870143
from django import template from django.templatetags.static import static register = template.Library() # Django incluison tag plays elegant way to separete bootstrap template logic # from app template, that separation is need for theme the projects_type # Pass in kwargs the elements to fill the cards # Please note ...
null
core/templatetags/general_tags.py
general_tags.py
py
640
python
en
code
null
code-starcoder2
51
407203490
import sys import os import argparse # Add parent directory to path to import general.py sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Import ../general.py from general import * TEST_NAME = "network" CLIENT_NAME = "client-ngtcp2" CLIENT_IMPLEMENTATION = "ngtcp2" QUIC_RESULTS_DIR =...
null
scripts/network/network-emu-test.py
network-emu-test.py
py
2,979
python
en
code
null
code-starcoder2
51
606423008
import numpy as np import paddle from tqdm import tqdm from .abc_interpreter import Interpreter from ..data_processor.readers import preprocess_inputs, preprocess_save_path from ..data_processor.visualizer import explanation_to_vis, show_vis_explanation, save_image class SmoothGradInterpreter(Interpreter): """ ...
null
interpretdl/interpreter/smooth_grad.py
smooth_grad.py
py
5,840
python
en
code
null
code-starcoder2
51
367475446
import xml.etree.ElementTree as ET import cv2 import numpy as np import os import glob import matplotlib.pyplot as plt from pathlib import Path global radius radius = 5 def visualize_hsv(flow, name): flow = flow.astype("float32") hsv = np.zeros((flow.shape[0], flow.shape[1], 3)) hsv[..., 1] = 255 # ...
null
utils/cmf_gen_pseudo.py
cmf_gen_pseudo.py
py
8,767
python
en
code
null
code-starcoder2
51
442061271
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Author: Peter. Wong # @Time: 2018/12/29 10:17 import numpy as np # numpy库 from sklearn.ensemble.gradient_boosting import GradientBoostingRegressor # 集成算法 from sklearn.model_selection import cross_val_score # 交叉检验 from sklearn.metrics import explained_variance_score, mean...
null
Data_Analysis/131-2300/GBR_VA.py
GBR_VA.py
py
3,439
python
en
code
null
code-starcoder2
51
581015693
import re from plugins.uptime import Uptime from plugins.nsfw_image_detector import NSFWImageDetectorPlugin from plugins.read_links import ReadLinks from plugins.psywerx_history import PsywerxHistory from plugins.psywerx_groups import PsywerxGroups from plugins.psywerx_karma import PsywerxKarma import settings clas...
null
src/logic.py
logic.py
py
4,222
python
en
code
null
code-starcoder2
51
28002487
from __future__ import print_function import numpy as np import time import math from ..box import centered_box from ..tensor import WritableTensorData as WTD, \ WritableTensorDataWithMask as WTDM from ..emio import imsave def prepare_outputs(spec, locs, blend=False, blend_mode='', stride=None): blend_pool =...
null
python/dataprovider/inference/blend.py
blend.py
py
8,556
python
en
code
null
code-starcoder2
50
6401508
#coding=utf8 #__author__chry #__date:2018/4/23 from multiprocessing import Process,Manager def f(d,l,n): d[n] = '1' d['2'] = 2 d[0.25] = None l.append(n) print(l) if __name__=='__main__': with Manager() as manger: d = manger.dict() l = manger.list(range(5)) p_list=[] for i in range(10): p=Process(targe...
null
threading_learing/Manger.py
Manger.py
py
405
python
en
code
null
code-starcoder2
50
524586540
import sys TODO_FILE = 'todo.txt' ARCHIVE_FILE = 'done.txt' RED = "\033[1;31m" BLUE = "\033[0;34m" CYAN = "\033[1;36m" GREEN = "\033[0;32m" RESET = "\033[0;0m" BOLD = "\033[;1m" REVERSE = "\033[;7m" YELLOW = "\033[0;33m" ADICIONAR = 'a' REMOVER = 'r' FAZER = 'f' PRIORIZAR = 'p' LISTAR = 'l' def printCore...
null
projeto.py
projeto.py
py
10,348
python
en
code
null
code-starcoder2
50
306174066
import argparse import os import torch import posenet def valid_tensor(s): msg = "Not a valid resolution: '{0}' [CxHxW].".format(s) try: q = s.split('x') if len(q) != 3: raise argparse.ArgumentTypeError(msg) return [int(v) for v in q] except ValueError: raise a...
null
export.py
export.py
py
2,056
python
en
code
null
code-starcoder2
50
63967556
from socket import * import sys from time import ctime # 收集命令行信息(字符串类型),将参数传进来,作为对应的IP地址和端口号. HOST = sys.argv[1] PORT = int(sys.argv[2]) ADDR = (HOST, PORT) BUFFERSIZE = 1024 # 1.创建数据报套接字 sockfd = socket(AF_INET, SOCK_DGRAM) # 设置套接字选项,将端口号设置为立即重用 sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # 2.绑定本地IP和端口号 sockf...
null
aid1805/PythonNet/day02/udp_server.py
udp_server.py
py
707
python
en
code
null
code-starcoder2
50
108698527
import FWCore.ParameterSet.Config as cms process = cms.Process("Analyzer") ## configure message logger process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.threshold = 'INFO' process.MessageLogger.cerr.FwkReport.reportEvery = 10 ## define input process.source = cms.Source("PoolSource", ...
null
PhysicsTools/JetMCAlgos/test/genHFHadronMatcher.py
genHFHadronMatcher.py
py
1,166
python
en
code
null
code-starcoder2
50
222406497
from tkinter import * class WidgetsDemo: def __init__(self): window = Tk() window.title("Widgets Demo") frame1 = Frame(window) frame1.pack() self.v1 = IntVar() cbtBold = Checkbutton(frame1,text = "Bold", variable = self.v1, ...
null
zz/python二级/tkinter Demo.py
tkinter Demo.py
py
840
python
en
code
null
code-starcoder2
51