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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
32228650765 | '''
Created on 06/01/2014
@author: jcpenuela
'''
def modifica(lista):
lista[0]=100
def original():
lista = [0,1,2,3]
print(lista)
modifica(lista)
print(lista)
if __name__ == '__main__':
print('prueba')
original()
| jcpenuela/Pruebas | Pruebas/paso_listas_a_funciones.py | paso_listas_a_funciones.py | py | 257 | python | es | code | 0 | github-code | 1 |
21841245355 | import sys
input = sys.stdin.readline
N = int(input())
cnt = 0
letter = []
no = False
for _ in range(N):
for i in input().strip():
if not i in letter:
letter.append(i)
else:
if i == letter[-1]:
continue
else:
no = Tr... | pearl313/BOJ | 백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py | 그룹 단어 체커.py | py | 430 | python | en | code | 0 | github-code | 1 |
24993118256 | import sys
import numpy as np
from fractions import Fraction
if __name__ == "__main__":
readFile = open(sys.argv[1], "r")
writeFile = open("out.txt", "w")
numeroCasos = int(readFile.readline())
casoMinimo = int(sys.argv[2])
casoMaximo = int(sys.argv[3])
for _ in range(casoMinimo-1):
... | marc-gav/TuentiChallenge9 | Ch4/challenge4.py | challenge4.py | py | 967 | python | en | code | 0 | github-code | 1 |
1165332467 | from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn import metrics
from sklearn.experime... | goodPointP/AuthorshipAttribution | model_evaluation.py | model_evaluation.py | py | 2,788 | python | en | code | 0 | github-code | 1 |
7413718188 | from functools import partial
from typing import Callable, Dict, Tuple
import jax
import jax.numpy as jnp
from chex import dataclass, Array, Scalar, PRNGKey
from tensorflow_probability.substrates import jax as tfp
from ml4wifi.utils.wifi_specs import *
from ml4wifi.utils.measurement_manager import measurement_manager... | ml4wifi-devs/ftmrate | ml4wifi/envs/simple_wifi/ftmrate_sim.py | ftmrate_sim.py | py | 8,913 | python | en | code | 1 | github-code | 1 |
25053971536 | from CodeBreakers.Data_structures_interview.LinkedList.LinkedList import LinkedList
def remove_duplicates(lst):
list_len = lst.length()
if list_len == 0:
return lst
elif list_len == 1:
return lst
d = dict()
current = lst.get_head()
prev = None
for i in range(0, list_len):
... | snk95/Sarvesh-Code | LinkedList/Remove_duplicates_from_linkedlist.py | Remove_duplicates_from_linkedlist.py | py | 1,858 | python | en | code | 0 | github-code | 1 |
40872798888 | from flask import Flask, render_template , request
import numpy as np
from utils import CarPrice
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/valuation' , methods = ['POST','GET'])
def valuation():
if request.method == 'POST':
data = request.form.... | supriya-vedpathak/carpro | interface.py | interface.py | py | 1,115 | python | en | code | 0 | github-code | 1 |
43200991376 | from jinja2 import Environment, FileSystemLoader
file_loader = FileSystemLoader('templates_dz')
env = Environment(loader=file_loader)
tm = env.get_template('main_dz.html')
msg = tm.render(title='Домашнее задание')
print(msg)
| Mil6734/git_class | Python2/dz40/dz40.py | dz40.py | py | 246 | python | en | code | 0 | github-code | 1 |
4444262235 | import numpy as np
from tqdm import tqdm
import networkx as nx
import scipy.sparse as sp
import dgl
import random
from time import time
from collections import defaultdict
import warnings
warnings.filterwarnings('ignore')
n_users = 0
n_items = 0
n_entities = 0
n_relations = 0
n_nodes = 0
train_user_set = defaultdict(... | gayeon603/kgin | utils/data_loader.py | data_loader.py | py | 7,149 | python | en | code | 1 | github-code | 1 |
40467668840 | import uuid
from teine import models, personality_operations
DEFAULT_SHOW_TITLE = 'My first show'
def get_by_id(show_id):
return models.Show.load(show_id)
def update(show_id, title='', author='', tagline='', description='',
show_hosts=[], image_id='', language='en-us'):
show = models.Show.load(s... | hirogwa/teine | teine/show_operations.py | show_operations.py | py | 1,419 | python | en | code | 0 | github-code | 1 |
28437711680 | from azureml.core import Run
import pickle
import argparse
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score
from dataloader import DataLoader
# model params
C = 0.025
kernel = "linear"
# cross validation params
cv = 5
def get_args():
parser ... | liupeirong/MLOpsManufacturing | samples/edge-inferencing-and-mlops/model/main.py | main.py | py | 2,029 | python | en | code | 21 | github-code | 1 |
71458557795 | #!usr/bin/env python3
#Jacob Foppes Project 6 Game
#game like pokenmon where you go down differnent paths and can run into pokemon on the way.
# Uses random to randomly slect a pokemon from a list for you to fight
# you fight the poken nad it cna wither be cought or run away attacks are effective or ineffective
#... | jfoppes/week_6 | project_6.py | project_6.py | py | 17,314 | python | en | code | 0 | github-code | 1 |
35656410164 | # Import Package
import matplotlib.pyplot as plt
import time
# membuat fungsi integral
def funcSingle(x):
return (5*x**7) - (9*x**4) + (4*x) - 2
def funcDouble(x, y):
return (5*x**7) - (9*y**4) + (4*x) - 2
def funcTriple(x, y, z):
return (5*x**7) - (9*y**4) + (4*z) - 2
# Nilai Exact
lipat1 = 234880.40
l... | ilhamaziz45/Integration | Trapezoid.py | Trapezoid.py | py | 3,050 | python | en | code | 0 | github-code | 1 |
73547403554 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Upsampler(nn.Module):
def __init__(self, in_channels=3, ngf=128):
super(Upsampler, self).__init__()
self.up = nn.Sequential(
nn.ConvTranspose2d(in_channels, ngf * 4, 4, 2, 1, bias=False),
nn.BatchNorm2... | julschoen/DC-VAE | vae.py | vae.py | py | 6,085 | python | en | code | 0 | github-code | 1 |
73262110115 | import sys
if len(sys.argv) == 2:
file_path = sys.argv[1]
if not file_path.endswith('.py'):
print("Not a Python file")
sys.exit(1)
try:
with open(file_path, "r") as file:
lines = file.readlines()
count = 0
for line in lines:
if not... | pmagalha/CS50-Python | Problem Set 6/lines/lines.py | lines.py | py | 654 | python | en | code | 0 | github-code | 1 |
18651362555 | import wargaming
from datetime import datetime, timedelta
#I use pretty print to print dictionary nicely since returned data is in json structure
import pprint
#My account ID is 1012192478
wotb = wargaming.WoTB('demo', language='en', region='na', enable_parser=True)
#Wargaming .NET
wgn = wargaming.WGN('demo', languag... | lperiaka/World-Of-Tanks-Blitz | secondTry.py | secondTry.py | py | 1,505 | python | en | code | 1 | github-code | 1 |
7486582215 | from maya import cmds,mel
from PySide import QtGui
from .lib import qt
def cpy():
mel.eval("timeSliderCopyKey;")
def pst():
mel.eval("timeSliderPasteKey false;")
def dlt():
mel.eval("timeSliderClearKey;")
def cut():
mel.eval("timeSliderCutKey;")
class MainWindow(QtGui.QMainWindow):
def __init__... | Mocson/mocTools | pyTest/keyFrameBox.py | keyFrameBox.py | py | 1,299 | python | en | code | 0 | github-code | 1 |
3807116907 | """
helper.py Walid Zeineldin Virginia Tech Dec 5th, 2020
This file holdes the helper classes that are used by optimizer
Track: holds track information and track realted functions
Vehical: holds vehical infromation
VelocityMap: Holds and updates velocity map for a specific car, around a specific path
"""
f... | ECE4574/Raceline-Optimizer | helpers.py | helpers.py | py | 3,520 | python | en | code | 0 | github-code | 1 |
33875985145 | def grade():
average = float(input("What is your average for the course? "))
if average >= 90:
print("A")
elif average >= 80:
print("B")
elif average >= 70:
print("C")
else:
print("You can do better! ")
return
if __name__ == "__main__":
grade() | pdewar/Python | IO/Grading.py | Grading.py | py | 305 | python | en | code | 0 | github-code | 1 |
35349481168 | '''
asyncio task loop to validate ledger close time and UNL status
using keys stored in an exiting database.
'''
import asyncio
import logging
import supplemental_data.get_data
def sup_data_loop(settings):
'''
Run the .asyncio event loop.
:param settings: Configuration file
'''
loop = asyncio.get... | jscottbranson/xrpl-validation-tracker | xrpl_validation_tracker/supplemental_data/sd_loop.py | sd_loop.py | py | 805 | python | en | code | 1 | github-code | 1 |
264717597 | from django.shortcuts import render
import json
from django.http import HttpResponse
from django.http import JsonResponse
from .models import ServerCategorys,ServerPosts,Keywords,Aquestions,Attachments,Centers
from school.models import Schools
from major.models import Majors
# Create your views here.
#服务中心文章列表展示
def s... | zhouf1234/django_obj | server/views.py | views.py | py | 22,643 | python | en | code | 0 | github-code | 1 |
70839121313 | num = int(input())
# DP = [[0] * 3 for _ in range(10**6)]
visited = [[0] * 3 for _ in range(10**6)]
result = 10**6
k = 0
while True:
k += 1
cnt = 0
N = num
# print('a', N)
for i in range(10**6):
if N % 3 == 0 and visited[i][0] == 0: # 1번 명령어
N //= 3
visited[i][... | ckdfh0917/Algorithm | 기웅스터디/DP/test.py | test.py | py | 812 | python | en | code | 0 | github-code | 1 |
5479029740 | #!/usr/bin/python
#coding=utf-8
#用于线程间通信 通过事件标识控制
import threading
from time import sleep,ctime
def wait_for_event(e):
'''在事件被设置之前,一直等待'''
print('等待事件开始')
event_is_set = e.wait() #事件没有被设置前,一直阻塞
print('事件set1:%s'%event_is_set)
def wait_for_event_timeout(e,t):
'''等待一段时间后,进行超时操作'''
while not e.... | jasonfight/backup | HOME/笔记/待整理笔记/线程/event.py | event.py | py | 993 | python | en | code | 0 | github-code | 1 |
20596278467 | import pandas as pd
dict_test = {
'col1': [1, 2, 3],
'col2': [4, 5, 6]
}
df_test = pd.DataFrame(dict_test)
df_test.to_excel('item_list.xlsx', index=False, sheet_name='item_list')
print('Process finished') | QuhiQuhihi/news_analysis | test.py | test.py | py | 215 | python | en | code | 3 | github-code | 1 |
41034161404 | from __future__ import annotations
import typing
from typing import Any
from typing import cast
from typing import Dict
from typing import Generic
from typing import Iterator
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import Optional
from typing import overload
fro... | sqlalchemy/sqlalchemy | lib/sqlalchemy/event/base.py | base.py | py | 14,301 | python | en | code | 8,024 | github-code | 1 |
19752234298 | import json
import torch
from SAC.Agent import AgentV2
if __name__ == "__main__":
jsonFilePath = "./cfg/RealTrain.json"
with open(jsonFilePath) as file:
json_dict = json.load(file)
agentDict = json_dict['Agent']
x = AgentV2(agentDict)
rstate = torch.zeros((32, 8))
lidarpt = ... | seungju-mmc/SAC | agenttest.py | agenttest.py | py | 450 | python | en | code | 0 | github-code | 1 |
43498491928 | from IPython import display
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from gym.envs.mujoco import *
from envs.hopper_env import HopperModEnv
from envs.cheetah_env import CheetahModEnv
import numpy as np
import copy
import gym
from scipy.io import loadmat
from scipy.io import savemat
import mov... | tpvt99/robotics | cs287hw2/part_b.py | part_b.py | py | 7,732 | python | en | code | 1 | github-code | 1 |
8691161609 | from typing import List
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
if n == 0 or 1 not in nums:
return 1
i = 0
while i < n:
idx = nums[i] - 1
if 0 <= idx < n and nums[idx] != nums[i]:
nums... | songkuixi/LeetCode | Python/First Missing Positive.py | First Missing Positive.py | py | 507 | python | en | code | 1 | github-code | 1 |
40249595923 | # File : fileName.py
# Author : your name
# Saibt Id : your saibt id
# Description : Assignment 2 place assignment description here . . .
# This is my own work as defined by the University ’s
# Academic Misconduct pol icy .
# Function length() - get the length of given list, return the length
def length(my_list):
... | nummy/exec | liam/PSP_Assignment_2_201702/list_function.py | list_function.py | py | 2,226 | python | en | code | 0 | github-code | 1 |
13395702605 | """Remove order in shop product and replace with the unwieldy row/column again :/
Revision ID: 4f786f3c132b
Revises: 2d4ea6b57d6e
Create Date: 2016-03-20 07:11:09.422825
"""
# revision identifiers, used by Alembic.
revision = '4f786f3c132b'
down_revision = '2d4ea6b57d6e'
from alembic import op
import sqlalchemy as ... | fenriz07/flask-hippooks | migrations/versions/4f786f3c132b_.py | 4f786f3c132b_.py | py | 4,089 | python | en | code | 2 | github-code | 1 |
33410335386 | import csv, json
from geojson import Feature, FeatureCollection, Point
features = []
with open('../data2.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader,None)
for row in reader:
# print(row[0])
latitude, longitude = map(float, (row[1], row[0]))
... | evo0522/squirrelTracker | utilities/create_geojson.py | create_geojson.py | py | 669 | python | en | code | 0 | github-code | 1 |
34197087850 | # 3
print('Члены ряда, подходящие под условие:\n')
print('-' * 30)
cnt = int(input('Кол-во чисел: '))
arr = []
c = 0
eps = float(input('Точность: '))
def factorial(a):
n = 1
while a > 1:
n *= a
a -= 1
return n
while True:
c += 1
num = int(input('{} Число: '.format(c)))
arr.... | mash2000/famen | task18/task18-c.py | task18-c.py | py | 736 | python | ru | code | 0 | github-code | 1 |
23519662780 | import os
import logbook
import gossip
from .project import get_project
# from .celery_utils import celery_app
_logger = logbook.Logger(__name__)
_cached_app = None
_building = False
def build_app(*, use_cached=False, config_overrides=None):
from flask import Flask
global _cached_app # pylint: disable=g... | getweber/cob | cob/app.py | app.py | py | 1,246 | python | en | code | 4 | github-code | 1 |
29376997811 | # CPE 101-01
# LAB 8: File i/o
# Name: Tyler Baxter
# Section: 03
# main function that runs the code
# none -> none
def main():
file_r = open('std_info.txt', 'r')
lst = read_file(file_r)
file_w = open('student_avg.txt', 'w')
write_average(file_w, write_file(lst, file_w))
# reads the file and puts the... | baxtertyler/CSC101-Lab8 | student_avg.py | student_avg.py | py | 1,909 | python | en | code | 0 | github-code | 1 |
22358279402 | #reverse a number
num=input("Enter the number :")
length=len(num)
numrev=""
for i in range(0,length):
numrev=numrev+num[length-1-i]
numrev=int(numrev)
print(f"\nThe reverse of {num} is {numrev}")
| arunar1/python-practice-problem | practice_problem_python-1/4.py | 4.py | py | 212 | python | en | code | 0 | github-code | 1 |
19121216961 | # hcm/util/file_utils.py
"""File utilities. """
import os
import sys
import logging
import pandas as pd
logger = logging.getLogger(__name__)
pd.set_option('display.width', 1000)
def days_suffix(obs_period):
return obs_period.replace('-', '_').replace(' ', '_')
def progress(count, total, status=''):
bar_len... | giorgio-o/hcm2 | util/file_utils.py | file_utils.py | py | 6,148 | python | en | code | 0 | github-code | 1 |
73034152673 | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON
)
ensure_in_sysp... | shineforever/ops | salt/tests/unit/modules/oracle_test.py | oracle_test.py | py | 2,902 | python | en | code | 9 | github-code | 1 |
35955470914 | import os
import sys
from dataclasses import dataclass
from src.logger import logging
from src.exception import CustomException
from src.utils import save_object, evaluate_model
from sklearn.ensemble import AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import LinearReg... | magaji-ahmed/mlproject | src/components/model_trainer.py | model_trainer.py | py | 2,634 | python | en | code | 0 | github-code | 1 |
18936228182 | class Student:
def __init__(self, name: str, age: int = 0, country: str = 'France') -> None:
self.name = name
self.age = age
self.country = country
def __str__(self):
return f'Hello! My name is {self.name}. I am {self.age} years old. I am from {self.country}.'
def print_da... | MatveyKormich/Matvey | main.py | main.py | py | 656 | python | en | code | 0 | github-code | 1 |
70875903393 | from typing import Iterable
from minecraft_launch.modules.interface.iresource import IResource
from minecraft_launch.modules.models.launch.game_core import GameCore
from minecraft_launch.modules.utils.extend_util import ExtendUtil
class ResourceInstaller():
max_download_threads: int = 64
def __init__(self, g... | Blessing-Studio/minecraft-launch-p | modules/installer/resource_installer.py | resource_installer.py | py | 901 | python | en | code | 5 | github-code | 1 |
32162016856 | """Functions for various pipeline use cases.
Author: Seth Axen
E-mail: seth.axen@gmail.com
"""
from .config.params import params_to_sections_dict
from .conformer.util import mol_from_smiles, mol_from_sdf, mol_to_sdf
from .conformer.generate import generate_conformers
from .fingerprint.generate import fprints_dict_from... | keiserlab/e3fp | e3fp/pipeline.py | pipeline.py | py | 2,929 | python | en | code | 114 | github-code | 1 |
5175296459 | import numpy as np
import rdkit.Chem as Chem
from rdkit import DataStructs
from rdkit.Chem import rdMolDescriptors
import copy
class CandidatePool():
def __init__(self,
candidate_pool_size=50):
self.candidate_pool_size = candidate_pool_size
self.pool = []
def _calc... | tong2shudong/calm | a_candidate_pool.py | a_candidate_pool.py | py | 3,126 | python | en | code | 1 | github-code | 1 |
34153222102 | from tkinter import *
from tkinter import messagebox
from tkinter import PhotoImage
def boton_aceptar():
# Segunda ventana
ventana2 = Tk()
ventana2.geometry("320x320")
ventana2.title("¿Edad actual que tienes?")
ventana2.config(bg="Slategray2")
ventana2.resizable(0, 0)
Lab... | Cayalam/Proyecto | Vida-Saludable/Vida_Saludable.py | Vida_Saludable.py | py | 6,747 | python | es | code | 0 | github-code | 1 |
2818687083 | from flask import current_app
from marshmallow import Schema, ValidationError, fields, validates_schema
from marshmallow.validate import Length
class CreateTaskSchema(Schema):
title = fields.Str(
required=True,
validate=Length(min=1),
)
description = fields.Str(required=True, validate=Leng... | sidddhesh100/factwise-assingment | schema/CreateTaskSchema.py | CreateTaskSchema.py | py | 1,036 | python | en | code | 0 | github-code | 1 |
13441935554 | import graph_tool.topology as topology
from graph_tool.all import *
import numpy as np
class gt_Graph(Graph):
def __init__(self):
Graph.__init__(self)
self.cnodes = []
self.dedges = {}
@staticmethod
def get_comps(G):
labels, _ = topology.label_components(G)
label... | mjhosseini/entgraph_eval | graph/gt_Graph.py | gt_Graph.py | py | 1,086 | python | en | code | 1 | github-code | 1 |
35938876208 | import numpy as np
import scipy.spatial
import itertools
from sklearn import metrics
def rand_score( X, labels_true, labels_pred ):
correct = 0
total = 0
arr2 = []
opop = len(X)
for i in range(opop):
arr2.append( i )
for index_combo in itertools.combinations(arr2, 2... | deepak0004/Assignments | 2014036_HW_1/my_kmeans.py | my_kmeans.py | py | 3,097 | python | en | code | 0 | github-code | 1 |
23650238154 | from bs4 import BeautifulSoup
import requests
import xlsxwriter
base_trade_url = 'https://www.realmeye.com/offers-by/'
pots = {
2793: "Life Potion",
2592: "Defense Potion",
2591: "Attack Potion",
2593: "Speed Potion",
2636: "Dexterity Potion",
2613: "Wisdom Potion",
2612: "Vitality Potion"... | mm1013g/Realmeye-Potion-Trade-Scraper | rotmgtrader.py | rotmgtrader.py | py | 4,784 | python | en | code | 0 | github-code | 1 |
13354526775 | class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
if set(word1) != set(word2):
return False
word_one_cnt = Counter(word1)
word_two_cnt = Counter(word2)
return Counter(word_one_cnt.values()) == Counter(word_two_cnt.values())
... | Biruk-Tassew/Competitive_programming | 1657-determine-if-two-strings-are-close/1657-determine-if-two-strings-are-close.py | 1657-determine-if-two-strings-are-close.py | py | 338 | python | en | code | 0 | github-code | 1 |
8445031902 | from pyspark.sql import SparkSession
import numpy as np
import pandas as pd
import gc
from pyspark.ml.feature import StringIndexer, VectorIndexer, VectorAssembler
from pyspark.sql.functions import col
from pyspark.sql.types import StringType,BooleanType,DateType,DoubleType
from pyspark.ml import Pipeline
from pyspark.m... | TommasoD/SEASHELL | MLicu_lr_hdfs.py | MLicu_lr_hdfs.py | py | 5,353 | python | en | code | 0 | github-code | 1 |
21217993775 | #!/usr/bin/env python
#coding:utf-8
"""
Author: --<v1ll4n>
Purpose: Test ZSRPS
Created: 07/19/17
"""
import unittest
import time
from vikitx.core.proto import zsrps
from vikitx.core.workpool import task
########################################################################
class ZSRPSTester(unittest.TestCa... | xisafe/vikitx | tests/test_zsrps_s.py | test_zsrps_s.py | py | 1,017 | python | en | code | 0 | github-code | 1 |
11506319058 | #pylint: disable=no-member
import tcod
from random import randint
from game_messages import Message
class Brute:
def take_turn(self, target, fov_map, game_map, entities):
results=[]
monster=self.owner
if tcod.map_is_in_fov(fov_map, monster.x, monster.y):
if monster.distance_to(t... | propfeds/project-regular | components/ai.py | ai.py | py | 1,201 | python | en | code | 1 | github-code | 1 |
11530574790 | from LinkedList import LinkedList
from LinkedListHelper import CreateLinkedList
def isIdentical(head1,head2):
while head1 and head2:
if head1.val != head2.val:
return False
head1 = head1.next
head2 = head2.next
if not head1 and not head2:
return True
return False
... | ANKITPODDER2000/LinkedList | 41_identical.py | 41_identical.py | py | 523 | python | en | code | 0 | github-code | 1 |
45871652881 | from .models import Course,Registration
from rest_framework import serializers
from course.models import Course
from users.serializer import UserSerializer
class CourseSerializer(serializers.ModelSerializer):
c_teacher = UserSerializer()
class Meta:
model = Course
fields = (
'c_id',... | iris19990802/HDUSamaritan-backend | course/serializer.py | serializer.py | py | 1,746 | python | en | code | 3 | github-code | 1 |
38252725617 | from rest_framework import viewsets, status, generics
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny... | UAACC/404-project | backend/api/views.py | views.py | py | 43,464 | python | en | code | 0 | github-code | 1 |
43694490704 | from itertools import product
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
class Dataset:
def __init__(self, protein, fitxer, model_target='tetramers', randomize_fce=False,
chosen_features=('full_fce', 'avg'), score='Median_intensity',
sel... | Jalbiti/DNAffinity | dataset.py | dataset.py | py | 9,421 | python | en | code | 0 | github-code | 1 |
24769331873 | from helper.help_functions import extract_list
def solve():
lines = extract_list("inputs/input_04")
points = 0
points2 = 0
for line in lines:
try:
pairs = line.split(",")
code_a = pairs[0].split("-")
code_b = pairs[1].split("-")
if contained(int(... | Koell/AdventOfCode | 2022/04.py | 04.py | py | 1,185 | python | en | code | 1 | github-code | 1 |
12993456149 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
from keras.datasets import mnist
(X_train, _), (X_test, _) = mnist.load_data()
X_train = X_train.reshape(-1,784)
X_train = X_train/255
# In[2]:
from sklearn.neural_network import BernoulliRBM
rbm = BernoulliRBM(n_components=10... | Arijit-Debnath111/RBM- | RBM .py | RBM .py | py | 625 | python | en | code | 0 | github-code | 1 |
72506182755 | from ..core import recipe, remove
import glob
import shutil
import urllib.request
import os
from os.path import *
from glob import glob
# --------------------------------------------------------------------
@recipe("dst", check="src")
def copy(src, dst, log: "log"):
if isdir(src):
log.trace("Copying dire... | lainproliant/bakery | bakery/recipes/file.py | file.py | py | 1,619 | python | en | code | 0 | github-code | 1 |
38786133703 | '''
# @ Author: Andrew Hossack
# @ Create Time: 2022-05-28 13:56:14
'''
import configparser
from typing import List, Union
def _get_config() -> List[str]:
"""
Get the config file
"""
config = configparser.ConfigParser()
config.read('config.ini')
return config
def get_config_value(key: str... | andrew-hossack/dash-tools | src/dashtools/data/configUtils.py | configUtils.py | py | 912 | python | en | code | 79 | github-code | 1 |
17360221735 | """hotjar_tracking
Revision ID: 5cdf7f1bbd6f
Revises: d788fb44fa0e
Create Date: 2022-04-01 11:02:46.044381
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5cdf7f1bbd6f'
down_revision = 'd788fb44fa0e'
branch_labels = None
depends_on = None
def upgrade():
... | bcgov/namex | api/migrations/versions/5cdf7f1bbd6f_hotjar_tracking.py | 5cdf7f1bbd6f_hotjar_tracking.py | py | 821 | python | en | code | 6 | github-code | 1 |
16804833584 | import threading
from socket import *
from threading import Timer
from time import sleep
def foo(socket):
# print("reach here")
sentence = input()
if sentence == "q":
raise KeyboardInterrupt
else:
socket.send(sentence.encode())
serverName = "45.76.123.227"
serv... | OceanicSix/Python_program | Socket_programming/Tcp_relay_messaging/TCP_Client.py | TCP_Client.py | py | 1,078 | python | en | code | 1 | github-code | 1 |
36284428225 | import sys
from collections import deque
#sys.stdin = open('input.txt', 'r')
def eat(p, depth):
visited = [[0 for _ in range(N)] for _ in range(N)]
q = deque([[p[0], p[1], depth]])
compare = []
mind = 401
visited[p[0]][p[1]] = 1
while len(q) > 0:
r, c, d = q.popleft()
... | kyeong8/Algorithm | 백준/Gold/16236. 아기 상어/아기 상어.py | 아기 상어.py | py | 1,809 | python | en | code | 0 | github-code | 1 |
71547040355 | #!/usr/bin/python3
"""API for Users"""
from tasks.users import User
from tasks import storage
from api.v1.views import app_views
from flask import jsonify, abort, request, make_response
from flasgger.utils import swag_from
@app_views.route('/users', methods=['GET'], strict_slashes=False)
@swag_from('documentation/us... | stepholo/RESTful-API-BASED-TASK-MANAGEMENT-SYSTEM | api/v1/views/user.py | user.py | py | 3,178 | python | en | code | 1 | github-code | 1 |
20652999633 | from template2.database.Mongoconnection import Mongoconnection
from bson.objectid import ObjectId
import pymongo
class PolicyDao(Mongoconnection):
print("insidepolicydao")
def __init__(self):
super(PolicyDao, self).__init__()
print("inside_init")
self.get_collection("policies")
def ... | Nimanita/mongodjangoproject | template2/dao/action.py | action.py | py | 3,465 | python | en | code | 0 | github-code | 1 |
73839829152 | from PyQt5.QtWidgets import *
import sys
class SignalSlotDemo(QWidget):
def __init__(self):
super(SignalSlotDemo,self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300,300,500,400)
self.setWindowTitle('信号(signal)与槽(slot)')
self.btn=QPushButton('我的按钮',self)#... | puhaoran12/pyqt5_note | 105.信号与槽.py | 105.信号与槽.py | py | 715 | python | en | code | 0 | github-code | 1 |
37698370333 | from movies.models import Movie, Person, Movie_genre
import pandas as pd
import os
def run():
movie_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Sri_database/moviesfinal.csv')
df_movie = pd.read_csv(movie_path, encoding="ISO-8859-1", usecols=['movie_id', 'Movie_name'])
# ../movies/pos... | unsw-cse-capstone-project/capstone-project-comp9900-w15a-nearestneighbors | backend/filmfinder/scripts/add_posters.py | add_posters.py | py | 914 | python | en | code | 0 | github-code | 1 |
25431459229 | import sys
input = sys.stdin.readline
n = 9
def verify(players:dict):
no = set()
can = set()
p = set([i for i in range(1, n+1)])
for player, guess in players.items():
if not guess:
continue
can_be,can_not = sum(guess), len(guess) - sum(guess)
if can_be > ... | reddevilmidzy/baekjoonsolve | 백준/Gold/17349. 1루수가 누구야/1루수가 누구야.py | 1루수가 누구야.py | py | 1,242 | python | en | code | 3 | github-code | 1 |
18779847895 | import numpy as np
from collections import namedtuple
Coordinate = namedtuple('Coordinate', ['latitude', 'longitude'])
def sin_d(angle):
return np.sin(np.deg2rad(angle))
def cos_d(angle):
return np.cos(np.deg2rad(angle))
def distance_in_km(coordinate_a, coordinate_b):
lat_sine = sin_d((coordinate_b.latitude -... | coproduto/mobile_location | mobile_localization/geo.py | geo.py | py | 2,369 | python | en | code | 1 | github-code | 1 |
2423149387 | from odoo import api, fields, models
class RefMarketCategory(models.Model):
_name = 'ref.market.category'
_description = 'Market Category'
_rec_name = 'description'
_order = 'sequence'
prefix = fields.Char(
string='Prefix',
required=True,
)
description = fields.Char(
... | decgroupe/odoo-addons-dec | product_reference_market/models/ref_market_category.py | ref_market_category.py | py | 683 | python | en | code | 2 | github-code | 1 |
23086769061 | import pandas as pd
def howManyMedalsByCountry(df, name):
if isinstance(df, pd.DataFrame) is False or \
isinstance(name, str) is False:
return None
dct = {}
team_sports = ['Basketball', 'Football', 'Tug-Of-War',
'Badminton', 'Sailing', 'Handball', 'Water Polo',
... | adbenoit-9/42_python_modules | module04/ex05/HowManyMedalsByCountry.py | HowManyMedalsByCountry.py | py | 1,169 | python | en | code | 0 | github-code | 1 |
39286320369 | """
Modified from https://github.com/pytorch/vision.git
"""
import math
import torch.nn as nn
import torch.nn.init as init
# fmt: off
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
# fmt: on
class VGG(nn.Module):
"""
VGG model
"""
de... | PrateekMunjal/TorchAL | pycls/models/vgg_style/vgg_2.py | vgg_2.py | py | 3,872 | python | en | code | 56 | github-code | 1 |
34265319700 | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
This file registers pre-defined datasets at hard-coded paths, and their metadata.
We hard-code metadata for common datasets. This will enable:
1. Consistency check when loading the datasets
2. Use models on th... | YutingXiao/Amodal-Segmentation-Based-on-Visible-Region-Segmentation-and-Shape-Prior | detectron2/data/datasets/builtin.py | builtin.py | py | 13,024 | python | en | code | 40 | github-code | 1 |
31626582935 | # //////////////////////////////////////////////////////////////////////////////
# Pierre Mahé (mahe.pierre@live.fr)
# L3I
# Université de La Rochelle
# 20-Jan-2019
#
# Based on idea from:
# Sylvain Marchand and Stanislaw Gorlow
# sylvain.marchand@univ-lr.fr and stanislaw.gorlow@labri.fr
# LaBRI CNRS
# Université Borde... | Pmea/ReaLiTy | src/erb_stuff.py | erb_stuff.py | py | 3,450 | python | en | code | 0 | github-code | 1 |
264569740 | import os
import requests
SHEETY_API = "https://api.sheety.co/d2dd5f6e5713c07f78a8b0452cbb68a8/flightDeals/users/"
SHEETY_TOKEN = os.environ["SHEETY_PRICES_TOKEN"]
class User:
def add_user(self) -> None:
bearer_headers = {
"Authorization": f'Bearer {SHEETY_TOKEN}'
}
para... | hollymartiniosos/100dayspython | 39. Flight deal finder/users.py | users.py | py | 1,534 | python | en | code | 0 | github-code | 1 |
72150906594 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
dp={}
def getHeight(root):
if root==None: return 0
if root in dp: return dp[root]
height = 1+max(getHeight(root.left), getHeight(root.right))
dp[root] = height
return height
d... | hyelong/algorithms | python/longest_path_node_to_node.py | longest_path_node_to_node.py | py | 700 | python | en | code | 0 | github-code | 1 |
27287309066 | import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import math
from display import Display
(X_TRAIN, Y_TRAIN), (X_TEST, Y_TEST) = tf.keras.datasets.cifar10.loa... | EthanWander/CIFAR10-image-classification | main.py | main.py | py | 2,482 | python | en | code | 0 | github-code | 1 |
13944543228 | from collections import deque
n, k= map(int, input().split())
L=deque()
for i in range(1,n+1):
L.append(i)
ans=[]
while L:
for _ in range(k-1):
q= L.popleft()
L.append(q)
q= L.popleft()
ans.append(str(q))
print('<',end='')
print(', '.join(ans),end='')
print('>',end='') | Taein2/PythonAlgorithmStudyWithBOJ | Minjae/2021-03-09/1159_Josephus.py | 1159_Josephus.py | py | 303 | python | en | code | 1 | github-code | 1 |
22347796562 | import requests
import unittest
token_ya = 'Место для вашего токена'
api_base_url = 'https://cloud-api.yandex.net/'
headers = {
'accept': 'application/json',
'authorization': f'OAuth {token_ya}'
}
class TestDocuments(unittest.TestCase):
def test_create_folder1(self):
res... | ZlayaZayaZ/unittest | unit_tests2.py | unit_tests2.py | py | 1,116 | python | en | code | 0 | github-code | 1 |
23008791513 | import requests
from autopr.models.rail_objects import PullRequestDescription
import structlog
log = structlog.get_logger()
class PublishService:
def publish(self, pr: PullRequestDescription):
raise NotImplementedError
def update(self, pr: PullRequestDescription):
raise NotImplementedError
... | chikib89/AutoPR | autopr/services/publish_service.py | publish_service.py | py | 2,993 | python | en | code | null | github-code | 1 |
15994920309 | import re
import collections
def mostCommon(paragraph, banned):
words = [word for word in re.sub(r'[^\w]', ' ', paragraph)
.lower().split()
if word not in banned]
counts = collections.Counter(words)
print(counts)
return counts.most_common(1)[0][0]
if __name__ == "__main__"... | Kynel/algorithm | python/문자열 조작/code/most_common.py | most_common.py | py | 458 | python | en | code | 0 | github-code | 1 |
33310905012 | import numpy as np
__all__ = ['insert_gaps']
def insert_gaps(timeorig,time,brightness,max_gap_size = 0.1):
"""
Insert gaps into a time series by getting gaps
from another time series.
Parameters
----------
timeorig : array-like
Time values of the original light curve.
time : array... | konkolyseismolab/seismolab | seismolab/inpainting/tools.py | tools.py | py | 1,227 | python | en | code | 1 | github-code | 1 |
21022710543 | import hashlib
import json
import requests
import time
import salt_gen
time_start = time.perf_counter()
print(time_start)
salt = salt_gen.generator() # 首次启动获取盐值
def w_rid(): # 每次请求生成w_rid参数
global time_start, salt
if (time.perf_counter() - time_start) > 24 * 60 * 60: # 一天更新一次salt
time_start = time.... | velvetflame/liveStatusCheck | main.py | main.py | py | 2,496 | python | en | code | 13 | github-code | 1 |
2715600905 | # start
# annotation
import os
import glob
import copy
from Bio import SeqIO
from Bio.Seq import Seq
import argparse
############################################ Arguments and declarations ##############################################
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatte... | caozhichongchong/snp_finder | snp_finder/scripts/annotate.py | annotate.py | py | 9,730 | python | en | code | 2 | github-code | 1 |
25256431774 | """
DM decay spectra and associated functions.
Everything is provided and output in natural units!
"""
import os, sys
from scipy.special import erf
from scipy.interpolate import interp1d
import numpy as np
import pandas as pd
from units import *
from scipy import integrate
class Particle:
def __init__(self, chann... | laurajchang/IG-NPTF | DMFiles/particle_decay.py | particle_decay.py | py | 2,236 | python | en | code | 0 | github-code | 1 |
75073514912 | import sys
with open(sys.argv[1], 'r') as students:
with open(sys.argv[2], 'r') as delinquents:
students = set(students.readlines())
delinquents = set(delinquents.readlines())
matches = sorted(list(students.intersection(delinquents)))
i = 1
for match in matches:
print('{}. {}'.format(i, mat... | Crone1/College-Python | Year Two - Semester One/Week 3/Sets_and_files.py | Sets_and_files.py | py | 343 | python | en | code | 0 | github-code | 1 |
43512595598 | class Solution:
def intToRoman(self, num):
luoma=''
i=0
# 限制条件,保证整数在[1,3999]内
if num >=4000 and num <1:
return ""
# 用于判断该数是否大于1000,若大于1000 ,则添加 int(num/1000) 个“M”
if num >= 1000:
for i in range(0,int(num/1000)):
luoma = luoma+"M... | km1994/leetcode | old/t20190402_number2luoma/num2luoma.py | num2luoma.py | py | 1,900 | python | zh | code | 24 | github-code | 1 |
6694377295 | import tkinter as tk
from tkinter import ttk
from gui.commands import get_rwi_widgets
class MainWindow(tk.Tk):
def __init__(self):
super().__init__()
self.title("Add RWI")
# fields = ["План?", "Тип", "Рамзер", "Заголовок", "Комментарий", "Id"]
# labels = [tk.Label(self, text=f) fo... | Shal1928/EcivresStrach | gui/main_window.py | main_window.py | py | 1,411 | python | en | code | 0 | github-code | 1 |
38985538027 |
class Settings():
'''Class to magane game's static settings'''
def __init__(self):
# screen
self.bg_path = r"python_crash_course\part_2\pygame_excercises\sideways_shooter\images\bg_image.png"
self.screen_width = 1280
self.screen_height = 720
# ship
s... | AgaOlejniq/sideways_shooter | settings.py | settings.py | py | 1,891 | python | en | code | 0 | github-code | 1 |
73062296675 | from app import app
from flask import Flask, jsonify, make_response, request
records = [
{
'id':1,
'title':u'aaa',
'descrption':u'bbb',
'done':False
},
{
'id':2,
'title':u'ccc',
'description':u'ddd',
'done':True
}
]
@app.route('/')
def in... | ineqwij/CloudComputing | app/views.py | views.py | py | 2,081 | python | en | code | 0 | github-code | 1 |
15644491492 | import random
name=input("enter your name")
print("HEY",name,"WELCOME TO OUR HANGMAN GAME")
IMAGES= ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
0 |
|
|
|
=========''', '''
+---+
| |
0 |
/ |
... | rekha9983/hangman | hangman.py | hangman.py | py | 3,900 | python | en | code | 1 | github-code | 1 |
34333957743 | class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
stck = []
for i in range(n-2, -1, -1):
while len(stck) != 0 and nums[i] >= stck[-1]:
stck.pop()
stck.append(nums[i])
res = []
for i in r... | siddiqui-sana/Leetcode-Challenge | Leetcode Challenge/Extra/Next_Greater_Element_II.py | Next_Greater_Element_II.py | py | 623 | python | en | code | 1 | github-code | 1 |
21547836374 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import logging
from srm.file_operations import get_full_path
def setup_console_logger(str_format="%(levelname)s: %(message)s", level=logging.INFO):
"""
Setup console logger.
"""
root_logger = logging.getLogger()
formatter = logging.Formatter(str_... | oderiver/project1 | srm/logger_tools.py | logger_tools.py | py | 912 | python | en | code | 0 | github-code | 1 |
42320016204 | # -*- coding:utf-8 -*-
# author:
# -*- coding: utf-8 -*-
'''百度坐标转换'''
import urllib
import math
import csv
import json
import pandas as pd
if __name__ == '__main__':
input_file='scope.csv'
output_file = open('scope.json', 'w')
csv_col_name = list(pd.read_csv(input_file,encoding='gb18030').columns) # 取到列... | Ahmelie/Experimental-Teaching-System-for-Big-Data-Analysis-and-Processing-of-Transportation | src/assets/canditatDataChange.py | canditatDataChange.py | py | 787 | python | en | code | 7 | github-code | 1 |
36343188679 | # -*- coding: utf-8 -*-
x = 121
y = str(x)
i = 0
a = True
for z in reversed(y):
if z != y[i]:
a = False # 只要出现一次就不是回文数
break
i = i + 1
print(a)
| Liabaer/Test | learn_algorithm/leetcode/palindrome.py | palindrome.py | py | 194 | python | en | code | 0 | github-code | 1 |
35476188136 | import requests
import threading
import sys
import re
import time
handle = str(input("please enter the cf handle : "))
roundID = int(input("please enter the contestID : "))
url = "https://codeforces.com/api/contest.standings?contestId={0}&handles={1}&showUnofficial=true".format(roundID, handle)
file = open("cf_logg... | lazymon4d/cf_rank_logger | cf.py | cf.py | py | 770 | python | en | code | 0 | github-code | 1 |
4490056792 | import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape) # (60000, 28, 28), (60000,)
print(x_test.shape, y_test.shape) # (10000, 28, 28), (10000,)
print(x_train[0])
print(y_t... | Taerimmm/ML | keras/keras45_ModelCheckPoint2_datatime.py | keras45_ModelCheckPoint2_datatime.py | py | 4,189 | python | en | code | 3 | github-code | 1 |
18753641833 | import sys
from format.fasta import Fasta
"""
Author:Zhu Sitao
Date : 2018-3-28
Dest : extract Fasta
"""
InputFile = sys.argv[1]
IdList = sys.argv[2]
fastaFile = Fasta(InputFile)
ID = open(IdList,'r')
for line in ID:
line = line.strip()
if len(line) != 0:
fastaFile[line]
ID.close() | SitaoZ/ngs-tools | util/getFasta.py | getFasta.py | py | 289 | python | en | code | 1 | github-code | 1 |
34722377604 | ## IMPORTS
import socket
import threading
import time
try:
from resources import game as gm
except ModuleNotFoundError:
import game as gm
## Plan is we import game and run it from here during multiplayer
## Then access attributes and send them to connected people
# SEPARATOR token to divide parts of mes... | WarriorThirteen/compsci-project | resources/multiplayer.py | multiplayer.py | py | 10,007 | python | en | code | 1 | github-code | 1 |
239644110 | # -*- coding: utf-8 -*-
# @Time : 2021-3-5
# @Author : huangjing
# @File : test_org.py
import time
import random
from TestCase.initEnv import *
import unittest
from ApiCommon.org_interface import *
from ApiCommon.Login_interface import *
from Params.params import *
import json
class TestOrg(unittest.TestCase)... | huangjing1990/somstest | somstest/API_Automation/TestCase/test_org.py | test_org.py | py | 4,139 | python | en | code | 0 | github-code | 1 |
74477664033 | from pixelpusher import pixel, bound, is_pixel_blank, multiply_pixel
class PostProcess(object):
@staticmethod
def apply(service, new_frame):
return new_frame
class Blur(PostProcess):
@staticmethod
def safe_get_pixel(line, size, index):
if index < 0 or index >= size:
return pixel(0, 0, 0)
return line[inde... | graham/pixels | postprocess.py | postprocess.py | py | 1,633 | python | en | code | 4 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.