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
16070369380
#the three cup monte game in python from random import shuffle def three_cup_monte(): cups = ["","0",""] #...list of cups shuffle(cups) #...shuffling the cups guess = int(input("Enter any choice between 0, 1 and 2 : ")) if cups[guess] == "0": #...if the guess is correct, the '...
Shusovan/Practice-Programs
practice.py
practice.py
py
3,472
python
en
code
0
github-code
13
14468237764
data = [] with open("day21.txt") as f: data = [x.strip() for x in f.readlines()] monkies = {} for row in data: tokens = row.split(":") monkey = tokens[0] rules = tokens[1].strip().split(" ") if len(rules) == 1: monkies[monkey] = (int(rules[0]), None) else: monkies[monkey] = (No...
PeterDowdy/AdventOfCode2022
day21_1.py
day21_1.py
py
1,155
python
en
code
0
github-code
13
16397470691
from ._base_api import BaseRequests from requests.models import Response class GenresRequests(BaseRequests): def __init__(self): super().__init__() self.base_url += '/genres' # Get all genres def get_all_genres(self, auth_token: str): url = f"{self.base_url}" headers = { ...
dneprokos/python-rest-api-tests
api/genres_requests.py
genres_requests.py
py
3,754
python
en
code
0
github-code
13
38203893927
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('team', '0004_auto_20160403_1033'), ] operations = [ migrations.AddField( model_name='fieldplayerstats', ...
snikers12/Hockey_club
team/migrations/0005_auto_20160403_1054.py
0005_auto_20160403_1054.py
py
1,182
python
en
code
0
github-code
13
7406452460
# File: EasterSunday.py # Description: EasterSunday assignment # Student Name: Lei Liu # Student UT EID: LL28379 # Course Name: CS 303E # Unique Number: 51200 # Date Created: 9/10/16 # Date Last Modified: 9/10/16 months=["January", "February", "March", "April", "May"] def main(): ...
LeiLiu95/Python-Projects
EasterSunday/EasterSunday.py
EasterSunday.py
py
740
python
en
code
0
github-code
13
28306385939
from flask_app.config.mysqlconnection import connectToMySQL import datetime from flask import flash, session from flask_app.models import user, comment class Post: DB = "CodingDojo_Wall_schema" def __init__( self , data ): self.id = data['id'] self.content = data['content'] self.created...
meghann-mccall/testing_deployment
flask_app/models/post.py
post.py
py
2,257
python
en
code
0
github-code
13
13187967325
import json import pandas as pd import time import glob from pathlib import Path from variables import outputFolder, outputCSV, outputJSON # Storing the current time in seconds since the Epoch. start_time = time.time() # Reading all the files in the folder and subfolders. read_files = glob.glob(outputFolder + "dev/*....
0xPale/project-sorare-data
Python/DEV/test.py
test.py
py
1,058
python
en
code
2
github-code
13
1528154256
class Node: def __init__(self,val,left=None,right=None): self.val=val self.left=left self.right=right class Tree: def __init__(self,root): self.root=root def count(self,node): if node==None: return 0 return 1+self.count(node.left)+self.count(nod...
stuntmartial/DSA
Trees/Checking_Printing/CompleteBinTree_Rec.py
CompleteBinTree_Rec.py
py
869
python
en
code
0
github-code
13
33549161053
# -*- coding: utf-8 -*- import sys import time from PyQt5.QtWidgets import * #ウィンドウのリサイズを禁止するクラス class SampleWindow(QWidget): def __init__(self): QWidget.__init__(self) self.setWindowTitle("Sample Window") self.setGeometry(300,300,200,150) self.setMinimumHeight(100) ...
kyoush/GUI
win01.py
win01.py
py
1,000
python
ja
code
0
github-code
13
32020159674
from PyQt4 import QtCore, QtGui import FrameBrowser import NumpyArrayTableView class NumpyArrayTableWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QTableWidget.__init__(self, parent) self.mainLayout = QtGui.QVBoxLayout(self) self.mainLayout.setMargin(0) self.mainLayou...
platipodium/mossco-code
scripts/postprocess/GUI/lib/table_view/NumpyArrayTableWidget.py
NumpyArrayTableWidget.py
py
1,607
python
en
code
3
github-code
13
4997976995
import numpy as np class TrainDatasetConfig(object): """ Configuration of the training routine (params passed to the Dataset and DataLoader""" def __init__(self): self.data = "/gpfswork/rech/rnt/uuj49ar/bird_dataset" self.sigma = 7 # internal, changing is likely to break code or accuracy ...
victoria-brami/BRAMI_Victoria_a3
optimization/optuna_training_configuration.py
optuna_training_configuration.py
py
3,112
python
en
code
0
github-code
13
73797745616
# Built-in package # Third-party packages import graphene as gql from django.db.transaction import atomic # Local packages from api_v1.domain.planet import models, types, crud class CreatePlanet(types.PlanetOutputMutation, gql.Mutation): class Arguments: data = types.PlanetCreateInput(required=True) ...
dbritto-dev/lqn-graphql-challenge
api_v1/domain/planet/schema.py
schema.py
py
2,179
python
en
code
0
github-code
13
22085284704
import os import dgl import time import torch import random import numpy as np import pandas as pd import dgl.function as fn from ogb.nodeproppred import DglNodePropPredDataset from datasets.dgl_planetoid_dataset import DglPlanetoidDataset from networks.gcn import GCN_Node from networks.gat import GAT_Node from networ...
chenchkx/SuperNorm
utils/utils_node.py
utils_node.py
py
6,107
python
en
code
5
github-code
13
17053174524
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class InstalmentPlanTuitionDTO(object): def __init__(self): self._amount = None self._biz_time = None self._order_id = None self._partner_id = None self._plan_op...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/InstalmentPlanTuitionDTO.py
InstalmentPlanTuitionDTO.py
py
5,610
python
en
code
241
github-code
13
72342597779
''' IMPORTING NECCESARY PACKAGES''' from tkinter import * #tkinter is a GUI package for python from tkinter import ttk from tkinter import messagebox from PIL import ImageTk,Image import webbrowser ''' IMPORTING SUCCESSFUL''' #Compilation of various phone models #[a,b,c,d,e] # a = Phone Name...
AnujTimsina/Phone-Recommendation-System
project.py
project.py
py
17,924
python
en
code
0
github-code
13
37785254506
import numpy as np from scipy import interpolate from matplotlib import pyplot as plot x = np.array([0, 6, 0, -17, -31, -28, 0, 39, 63]) y = np.array([0, 6, 16, 17, 0, -28, -47, -39, 0]) x = np.r_[x, x[0]] y = np.r_[y, y[0]] tck = (interpolate.splprep([x, y], s=0, per=True))[0] u = (interpolate.splprep([x,...
pdelfino/numerical-analysis
lista-4/delfino-5-questao.py
delfino-5-questao.py
py
547
python
en
code
0
github-code
13
18347492038
import mxnet as mx import numpy as np import cv2 from tools.rand_sampler import RandSampler class DetRecordIter(mx.io.DataIter): """ The new detection iterator wrapper for mx.io.ImageDetRecordIter which is written in C++, it takes record file as input and runs faster. Supports various augment operation...
zhreshold/mxnet-ssd
dataset/iterator.py
iterator.py
py
11,058
python
en
code
763
github-code
13
1060825849
from skimage.io import imread from skimage import img_as_float64 from sklearn.cluster import KMeans import numpy as np import matplotlib.pyplot as plt import warnings import math def get_MSE(I, K): sum = 0 for i in range(len(I)): for j in range(len(I[0])): for k in range(len(I[0][0])): ...
rrtty0/image_clustering
image_clustering.py
image_clustering.py
py
5,135
python
en
code
0
github-code
13
22991327813
import cv2 import os from env import OUTPUT_FOLDER, join_path from library.image import to_tk_image, apply_adjustments class Video: def __init__(self): self.path = "" self.video = None self.fps = 29 self.delay = 33 self.process_this_frame = True self.valid = False ...
iammeosjin/face-recognition
library/video.py
video.py
py
3,382
python
en
code
0
github-code
13
20774509571
import tkinter from Scripts.ex1 import get_u __authors__ = ["Mihaila Alexandra Ioana", "Dupu Robert-Daniel"] __version__ = "1.1" __status__ = "Dev" def plus_asociativ(x, y, z): if (x + y) + z == x + (y + z): return True return False def inmultire_asociativa(x, y, z): while (x * y) * z == x * ...
alexandra-mihaila/CN
Tema1/Scripts/ex2.py
ex2.py
py
1,307
python
en
code
1
github-code
13
12003522576
from os import sep import sys from collections import deque input = sys.stdin.readline def dfs(graph, v): dfs_visited[v] = True dfs_list.append(v) for i in graph[v]: if not dfs_visited[i]: dfs(graph, i) def bfs(graph, v): queue = deque([v]) bfs_visited[v] = True while queue: v = queue.pople...
TK-moon/algorithm
baekjoon/1260.py
1260.py
py
1,057
python
en
code
0
github-code
13
31077664287
from fastapi import FastAPI from server.routes.peopleRoute import PeopleRouter app = FastAPI() app.include_router(PeopleRouter, tags=["People"], prefix="/people") @app.get("/", tags=["Root"]) async def read_root(): return {"message": "Hello there people, add yourself :)"}
tanvinsharma/fastapi_sample_app
server/app.py
app.py
py
280
python
en
code
0
github-code
13
37777338021
# -*- coding: utf-8 -*- # This code shows an example of text translation from English to Simplified-Chinese. # This code runs on Python 2.7.x and Python 3.x. # You may install `requests` to run this code: pip install requests # Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document import requ...
code-novice/image_tool
fanyi.py
fanyi.py
py
1,568
python
en
code
1
github-code
13
3944522075
# 나눠지는 수가 존재하면 더 이상 소수가 아니므로, break # check를 이용하여 나눠지는 수가 있을 때만 출력용 배열에 append 하여 합과 첫 값을 출력하거나, # 아무 것도 없을 때는 -1을 출력 M = int(input()) N = int(input()) prime = [] for i in range(M, N+1): if i != 1:#1이 아닌 요소(i)를 하나씩 꺼내면서 2~ i-1까지 나눠지는 수가 없을 때만을 골라낸다. check = True for j in range(2, i): ...
hinhyu/Algorithm
단계별문제풀이/09.수학2/2소수.py
2소수.py
py
704
python
ko
code
0
github-code
13
2574819803
from bs4 import BeautifulSoup movie_list=[] import requests html = "https://movie.douban.com/top250?start=" for i in range(0,10): url = html+str(i*25) r = requests.get(url,timeout=10) soup = BeautifulSoup(r.text,"html.parser") title = soup.find_all("div",class_="hd") for each in title: print(each.a.span.text) ...
1208606234/Python
豆瓣250爬虫.py
豆瓣250爬虫.py
py
327
python
en
code
2
github-code
13
70865563537
import os from PIL import Image import numpy as np in_dir = '/home/haojieyuan/Data/caltech101/eval_imgs' out_dir = '/home/haojieyuan/Data/caltech101/eval_imgs_resized' #in_dir = '/home/haojieyuan/Data/oxfordFlowers/eval_imgs' #out_dir = '/home/haojieyuan/Data/oxfordFlowers/eval_imgs_resized' fraction = 0.875 for i...
HaojieYuan/autoAdv
benchmark/fine_grain_datsets/eval/preprocess_imgs.py
preprocess_imgs.py
py
1,724
python
en
code
1
github-code
13
72941912978
from collections import defaultdict from typing import List class Solution: def numPairsDivisibleBy60(self, time: List[int]) -> int: #same with "two sum"用dict记录remainders #time:o(n), space:o(1) d = defaultdict(int) res = 0 for song in time: if song % 60 == 0: ...
isabellakqq/Alogorithm
HashMap/1010.PairsofSongsWithTotalDurationsDivisibleby60.py
1010.PairsofSongsWithTotalDurationsDivisibleby60.py
py
468
python
en
code
2
github-code
13
33375873754
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit, minimize def true_fun(x): return np.cos(1.5 * np.pi * x) def main(): n_samples = 30 np.random.seed(0) x = np.sort(np.random.rand(n_samples)) y = true_fun(x) + np.random.randn(n_samples)...
scarrazza/DL2023
Lecture_2/solutions/exercise7.py
exercise7.py
py
2,585
python
en
code
1
github-code
13
34758867499
""" PyTorch implementation of: Learning Deep Features for Discriminative Localization """ import argparse import copy import os import cv2 import numpy as np import torchvision import torch from PIL import Image from torchvision.models.resnet import resnet152, resnet18, resnet50 import ImageNetLabels model_name_to_...
adeeplearner/ClassActivationMaps
class_activation_map.py
class_activation_map.py
py
7,132
python
en
code
0
github-code
13
16755353865
"""Test depolarizing.""" import numpy as np from toqito.channel_ops import apply_channel from toqito.channels import depolarizing def test_depolarizing_complete_depolarizing(): """Maps every density matrix to the maximally-mixed state.""" test_input_mat = np.array( [[1 / 2, 0, 0, 1 / 2], [0, 0, 0, 0]...
vprusso/toqito
toqito/channels/tests/test_depolarizing.py
test_depolarizing.py
py
1,073
python
en
code
118
github-code
13
19945505372
#!/bin/env python3 import subprocess import json import re def PortList(): CMD = "sudo netstat -pntl | awk '{print $4,$7}'|grep [0-9] |egrep -vw '%s'" Result_str = subprocess.getoutput(CMD) #print(Result_str) tmp_list = Result_str.split("\n") #print(tmp_list) port_dict = {} for line in tmp...
cuijianzhe/work_scripts
port_discovery.py
port_discovery.py
py
852
python
en
code
3
github-code
13
4502167142
from TreeNode import TreeNode def pathSumRecursive(root, targetSum): res = [] def dfs(root, currSum, arr): if not root: return arr.append(root.val) if not root.left and not root.right and root.val == currSum: res.append(list(arr)) else: dfs(r...
anhduy1202/Leetcode-Prep
Tree Concept/pathSumII.py
pathSumII.py
py
1,271
python
en
code
0
github-code
13
10438620456
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from src.CustomWidget import MySettingTableModel from uifiles.Ui_parseANNT_settings import Ui_ParAnnt_settings from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from uifiles.Ui_parseANNT import Ui_parseANNT from sr...
dongzhang0725/PhyloSuite
PhyloSuite/src/Lg_parseANNT.py
Lg_parseANNT.py
py
58,110
python
en
code
118
github-code
13
26925052196
class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums_set = set(nums) ans = 0 for num in nums: if num - 1 not in nums_set: tmp = 1 while num + 1 in nums_set: num += 1 tmp += 1 ...
hwngenius/leetcode
learning/Array/128.py
128.py
py
543
python
zh
code
1
github-code
13
70179488979
""" Convert any colour to the ANSI format to write in colours in your terminal. Note: The conversion to an ANSI escape sequence may induce some colour variations. Also notice that some colours can't be mixed together as foreground and background. """ RESET = "\x1b[0m" def RGBtoANSI(text: str, foregound=[255, 255, ...
SpcFORK/iASCII
venv/lib/python3.10/site-packages/ansiconverter/converter.py
converter.py
py
2,718
python
en
code
1
github-code
13
38032949698
__author__ = "Tulay Cuhadar Donszelmann <tcuhadar@cern.ch>" __version__ = '0.10.21' import logging import os import sys from ART.docopt_dispatch import dispatch from ART import ArtBase, ArtGrid, ArtBuild from ART.art_misc import get_atlas_env, set_log MODULE = "art" # # First list the double commands # @dispatc...
rushioda/PIXELVALID_athena
athena/Tools/ART/scripts/art.py
art.py
py
7,142
python
en
code
1
github-code
13
35967395544
class RandomAgent: def __init__(self, env): self.env = env self.actions_cnt = env.action_space.n self._max_iter = 2 self._gamma = 0.99 self._final_reward_weight = 1.0 def predict_action(self, state): """ Return action that should be ...
PotapovaSofia/NextBestViewRL
rl/random_agent.py
random_agent.py
py
1,788
python
en
code
1
github-code
13
9713477057
def checkio(game_result): # create entries for columns (down results) columns = ["".join(col) for col in list(zip(*game_result))] # create angle entries from top left to bot right # and bot left to top right top_left = "" bot_left = "" for n in range(0, 3): top_left += game_res...
stroke-one/CheckiO_Solutions
home/x-o-referee.py
x-o-referee.py
py
1,076
python
en
code
0
github-code
13
40787832502
terrain = [[int(c) for c in line.strip()] for line in open('Day 09.input')] for t in terrain: t.insert(0, 9) t.append(9) terrain.insert(0, [9] * len(terrain[0])) terrain.append([9] * len(terrain[0])) total = 0 for x in range(1, len(terrain)-1): for y in range(1, len(terrain[0])-1): tile = terrain[...
Mraedis/AoC2021
Day 09/Day 09.1.py
Day 09.1.py
py
576
python
en
code
1
github-code
13
28188913635
""" Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the leng...
brownhash/leetcode
longest_substring.py
longest_substring.py
py
1,071
python
en
code
0
github-code
13
21307810332
import turtle import random t = turtle.Turtle() t.speed(0) p1c = turtle.Turtle() #player1 cash display p2c = turtle.Turtle() #player2 cash display r = turtle.Turtle() #rent and winning message display def screen(): # SCREEN COLOUR, SIZE sc = turtle.Screen() sc.bgcolor('dark sea green') sc.setup(width=60...
imk8/Monopoly
Monopoly V4.py
Monopoly V4.py
py
9,754
python
en
code
0
github-code
13
10546779873
import os import shlex import subprocess def executeOnBenchmarks(fptaylorpath, folder_path, results_folder): if os.path.exists(folder_path+results_folder): print("WARNING!!! FPTaylor results already computed!") return else: os.makedirs(folder_path+results_folder) for file in os.list...
soarlab/paf
src/FPTaylor.py
FPTaylor.py
py
3,308
python
en
code
0
github-code
13
37376083979
import os import ee import json import requests import numpy as np import pandas as pd import datetime as dt service_account = "fire-water-chart@appspot.gserviceaccount.com" credentials = ee.ServiceAccountCredentials(service_account, "privatekey.json") ee.Initialize(credentials) def serializer(df_pre, df_fire): ...
Vizzuality/mongabay-data
cloud_functions/fire_tool/main.py
main.py
py
8,299
python
en
code
0
github-code
13
17159219517
import matplotlib.pyplot as plt import numpy as np q0=-5; qf = 80; tf = 4 min_acc = 4*abs(qf-q0)/tf**2 print("acc needs to be bigger than ", min_acc) mode_aorv = 0 if mode_aorv == 0: acc = 30 tb = tf/2 -np.sqrt( acc**2 * tf**2 -4*acc*np.abs(qf-q0)) /2/acc if (qf-q0)>=0: vel = acc * tb else: ...
Phayuth/robotics_manipulator
trajectory_planner/traj_plan_linear_parabolic.py
traj_plan_linear_parabolic.py
py
1,499
python
en
code
0
github-code
13
9087156470
#https://www.acmicpc.net/problem/14699 #백준 14699번 관악산 등산(위상정렬) #import sys #input = sys.stdin.readline from collections import deque n,m = map(int, input().split()) heights = list(map(int, input().split())) indegree = [0]*n graph = [[] for _ in range(n)] for _ in range(m): a, b = map(int, input().split()) i...
MinsangKong/DailyProblem
06-08/2-2.py
2-2.py
py
909
python
ko
code
0
github-code
13
26073185684
from conexion import ConexionPG from atributos_conexion import ATRIBUTOS class Modelo: _conexion = None @classmethod def inicializar_conexion(cls): if cls._conexion is None: cls._conexion = ConexionPG( **ATRIBUTOS ) class Editorial(Modelo): def __in...
benjymb/asesoria_10_1
modelos.py
modelos.py
py
2,760
python
es
code
0
github-code
13
74084859857
import pytest from twisted.internet.error import DNSLookupError @pytest.mark.parametrize( 'retry_middleware_response', (({'FAKEUSERAGENT_FALLBACK': 'firefox'}, 503), ), indirect=True ) def test_random_ua_set_on_response(retry_middleware_response): assert 'User-Agent' in retry_middleware_response.heade...
alecxe/scrapy-fake-useragent
tests/test_retry_middleware.py
test_retry_middleware.py
py
621
python
en
code
658
github-code
13
23607475192
from pathlib import Path from torch.utils.data import Dataset, ConcatDataset, DataLoader from torchvision import transforms from torchvision.datasets import ImageFolder from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import numpy as np import cv2 import bcolz import pickle import torch import m...
CN1Ember/feathernet_mine
quan_table/insightface_v2/insightface_data/iccv_ms1m_data_pipe.py
iccv_ms1m_data_pipe.py
py
5,559
python
en
code
1
github-code
13
38586861242
import cv2 from pyzbar import pyzbar if __name__ == "__main__": barcodes = ['images/barcode-3.jpg'] for barcode_file in barcodes: # load the image to opencv img = cv2.imread(barcode_file) # decode detected barcodes & get the image # that is drawn img = pyzbar.decode(img)...
pawelzakieta97/BHL2020Melson
test.py
test.py
py
399
python
en
code
0
github-code
13
15724680361
from huaweicloudsdkcore.auth.credentials import BasicCredentials from huaweicloudsdkcore.exceptions import exceptions from huaweicloudsdkcore.http.http_config import HttpConfig from huaweicloudsdkecs.v2 import * from VPC.VPC import VPC from error import error class ECS: def __init__(self, ak: str, sk: ...
Belka258/cloud_tg_bot
ECS/ECS.py
ECS.py
py
4,587
python
en
code
0
github-code
13
28350910903
class Solution: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: mini=min(numsDivide) seti=set(numsDivide) dic=Counter(nums) nums=list(set(nums)) nums.sort() ans=0 for i in nums: if i>mini: break f...
saurabhjain17/leetcode-coding-questions
2344-minimum-deletions-to-make-array-divisible/2344-minimum-deletions-to-make-array-divisible.py
2344-minimum-deletions-to-make-array-divisible.py
py
560
python
en
code
1
github-code
13
18818597224
from rest_framework.routers import DefaultRouter from django.urls import path, include from myapp.views.user_views import ( MyTokenObtainPairView, RegisterViewSet, ) from myapp.views.article_views import ArticleListView router = DefaultRouter() router.register('accounts/register', RegisterViewSet, b...
nabeelahmdd/blog-api
myapp/urls.py
urls.py
py
580
python
en
code
0
github-code
13
24975834963
""" The `GPM` module contains all functions related to the *processing* of the GPM-IMERG near realtime satellite derived precipitation for the Southwest Pacific """ # ignore user warnings import warnings warnings.simplefilter("ignore", UserWarning) # import matplotlib import matplotlib # matplotlib.use('Agg') # unc...
nicolasfauchereau/ICU_Water_Watch
ICU_Water_Watch/GPM.py
GPM.py
py
29,920
python
en
code
11
github-code
13
6904164898
from keras.datasets import mnist import numpy as np (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], -1)/255 X_test = X_test.reshape(X_test.shape[0], -1)/255 y_train = np.eye(10)[y_train] y_test = np.eye(10)[y_test]
ousinnGitHub/ML_Study
AI_study/Python/demo05/src/KNN.py
KNN.py
py
270
python
en
code
0
github-code
13
17625334645
#!/usr/bin/env python3 from src.euler import Euler from math import exp class ExpEuler(Euler): def initial_values(self): """ Initial value for variable y. """ self.y = 1 self.y_list = [] def diff_equation_system(self, x: float, dx: float): """ Derivative 'dy/dx = y'. Hence it i...
Zazzik1/Euler
exp.py
exp.py
py
718
python
en
code
2
github-code
13
9525034485
from PyQt5 import QtWidgets from PyQt5.QtWidgets import QWidget from widgetTempletes import SliderWidget, intInputWidget class DiseaseTab(QWidget): def __init__(self, parent, plotCanvas, simulation): super(QWidget, self).__init__(parent) self.layout = QtWidgets.QVBoxLayout() self.plotCanv...
BaileyDalton007/Epidemic-Simulator
tabs/disease_tab.py
disease_tab.py
py
1,817
python
en
code
1
github-code
13
26083606654
import cplex import itertools #import para fazer o permutation import math from math import sin, cos, sqrt, atan2, radians,e c=list() c1=list() c2=list() latitude = list() longitude = list() texto = open('testecoord.txt') #testecoord - burma14, testecoord2- att48, testecoord3 - bayg29 for linha in texto:...
vinimartins6/TravelingSalesmanProblem
TSP_Subrotas_versao_4.1(lat,long).py
TSP_Subrotas_versao_4.1(lat,long).py
py
7,159
python
pt
code
0
github-code
13
72651273939
# -*- coding: utf-8 -*- # code for console Encoding difference. Dont' mind on it import imp import sys imp.reload(sys) try: sys.setdefaultencoding("UTF8") except Exception as E: pass import testValue from popbill import CashbillService, PopbillException cashbillService = CashbillService(testValue.LinkID, tes...
linkhub-sdk/popbill.cashbill.example.py
sendEmail.py
sendEmail.py
py
1,363
python
ko
code
0
github-code
13
6238882254
from django.conf import settings from django.contrib.auth.decorators import login_required from django.core.cache import cache from django.core.cache.backends.base import DEFAULT_TIMEOUT from django.shortcuts import render from django.urls import reverse_lazy from rest_framework.decorators import api_view from rest_fra...
NazarSenchuk/TestSite
backend/api/views.py
views.py
py
3,374
python
en
code
0
github-code
13
8145231451
import os import dropbox from dropbox.files import WriteMode class TransferData: def __init__(self, access_token): self.access_token = access_token def upload_file(self, file_from, file_to): dbx = dropbox.Dropbox(self.access_token) for root,dirs,files in os.walk(file_from): ...
Raghavkhandelwal7/dropbox-boom-box-
dropbox.py
dropbox.py
py
1,141
python
en
code
0
github-code
13
73055113937
#!/usr/bin/env python3 # coding:utf-8 import re import os from bs4 import BeautifulSoup import requests Url = 'http://www.cnblogs.com/kuangbin/archive/2012/10/02/2710606.html' Headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:41.0) Gecko/20100101 Firefox/41.0'} def get_link_from_html(url): links ...
flintx/PythonExecrise
0009/0009.py
0009.py
py
813
python
en
code
1
github-code
13
19466134025
import random import string import sys import os import time from time import gmtime, strftime import scores def rand_capital(): cap_and_countries = [] with open("countries-and-capitals.txt", "r") as f: for line in f.readlines(): line = line.strip("\n") line = line.split(" | ")...
turo62/exercise
exercise/sandbox1.py
sandbox1.py
py
3,889
python
en
code
0
github-code
13
20135497380
import sys def split_columns(line): """Splits the tokens separated by two or more spaces. This is the format of the "table" that's emitted by llvm-cov report. """ return [item.strip() for item in line.split(' ') if item] def parse_llvm_cov_report_from_stdin(): """Interprets the whole stdin as a "table" fr...
GoogleChromeLabs/chromeos_smart_card_connector
scripts/parse-coverage-output.py
parse-coverage-output.py
py
1,702
python
en
code
131
github-code
13
42783500565
import streamlit as st import pandas as pd def process(input_df, sample_time, sample_mode): # 数据处理,根据采样时间和模式来判断 # 采样时间【每秒:1S;每分钟:1Min;每小时:1H】 # 采样模式【周期首个值:first;周期均值:mean;周期末值:last】 input_df['时间'] = pd.to_datetime(input_df['时间'], format='%Y年%m月%d日 %H:%M:%S') # 转格式 input_df.set_index('时间'...
AWei02/Huangguan
app.py
app.py
py
8,435
python
zh
code
0
github-code
13
22193444413
from ovirtsdk.api import API from ovirtsdk.xml import params try: api = API(url="https://HOST", username="Subhayu", password="a@123", ca_file="ca.crt") vm_name = "dummy1" vm_memory = 512 * 1024 * 1024 vm_cluster = api.clusters.get(name="Default") vm_templa...
subhayuroy/ComputationalForensics
Virtualization/virtual.py
virtual.py
py
978
python
en
code
3
github-code
13
3693421145
from datetime import date from unittest.mock import MagicMock from django.contrib import admin from django.test import TestCase from djmoney.money import Money from salesmanagement.manager.admin import ProductAdmin from salesmanagement.manager.factories import CompanyFactory, ProductFactory, ProductsSaleFactory from ...
rubimpassos/finxiChallenge
salesmanagement/manager/tests/test_admin_product.py
test_admin_product.py
py
5,540
python
en
code
0
github-code
13
29903430763
import sys # from rdflib import Graph, URIRef import sys from perseo.main import get_files, nt2ttl, uniqid, nt2ttl_quad # # from ..pyperseo.perseo.main import get_files , nt2ttl, uniqid # from pyperseo.functions import get_files, nt2ttl, uniqid argv = sys.argv[1:] if argv[0] == "uniqids": all_files = get_files(...
pabloalarconm/PERSEO
cde_implementation/medusa.py
medusa.py
py
764
python
en
code
0
github-code
13
28986708353
import torch import torch.nn as nn import torch.nn.functional as F from actor import Actor class Critic(Actor): """Critic (Value) Model.""" def __init__(self, state_size, action_size, seed): """Initialize parameters and build model. Params ====== state_size (int): Dim...
afilimonov/udacity-deeprl-p2-continous-control
critic.py
critic.py
py
1,619
python
en
code
0
github-code
13
26312106012
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 1 18:45:15 2022 @author: nathan """ import pandas as pd import os #Enter the path to the demand file def main(path_result, path_input, scenario): path = f'{path_input}/{scenario}_Demand_Real_Forecasted.xlsx' demand = pd.read_excel(path, ...
NathanDeMatos/UVic-ESD
OutputAnalysis/Scenario Analysis/demand_Summary.py
demand_Summary.py
py
926
python
en
code
0
github-code
13
36979023839
from flask import Flask,jsonify from main.service import user_service app = Flask(__name__) @app.route('/new-user', methods=['POST']) def create_new_user(): user = user_service.create_new_user() return jsonify(user.__str__()) @app.route('/get-user/<idUser>',methods=['GET']) def getUser(idUser): us...
RafaelTeckGomes/my-project
apps-python/main/controller/user_controller.py
user_controller.py
py
444
python
en
code
0
github-code
13
2336975191
# Tuples are a type of data sequences # tuples are immutable you cannot append or delete the elements x = (40,41,42) # () denotes declaration of the tuples. all 3 values are packed into a tuple. x[0] # will give 40 # this is basically assiging the values 30 to age and 17 to years_of_school # where split is comm...
mayurguptaiiitm/python_learning
tuples_learn.py
tuples_learn.py
py
544
python
en
code
0
github-code
13
6971912636
import tensorflow as tf from tensorflow.python.ops.rnn_cell import LSTMCell import numpy as np class LSTMAutoencoder(object): """Basic version of LSTM-autoencoder. (cf. http://arxiv.org/abs/1502.04681) Usage: ae = LSTMAutoencoder(hidden_num, inputs) sess.run(ae.train) """ def __init__( ...
icucockpit/PatientMonitoring-DeepLearning-py
blueprint/ICUCockpit/anomaly_detection/LSTM_autoencoder_.py
LSTM_autoencoder_.py
py
3,344
python
en
code
0
github-code
13
7828034634
import astropy import astropy.io.fits as fits import numpy as np import gfs_sublink_utils as gsu import make_color_image import matplotlib import matplotlib.pyplot as pyplot import glob import os import time import sys sq_arcsec_per_sr = 42545170296.0 c = 3.0e8 def export_image(hdulist,camnum,filtername,label='',out...
gsnyder206/mock-surveys
original_illustris/export_images.py
export_images.py
py
7,324
python
en
code
7
github-code
13
70523840339
#!/usr/bin/env python # -*- coding: utf-8 -*- from typing import Counter import back_link as link def get_pwd(ID): db,cursor=link.conn() cursor.execute("select pwd from ID_pwd where ID= '"+ID+"'") li='' row=cursor.fetchone() li=str(row[0]) db.close() return li
CUG-LXY/undergraduateproject
py&sqlfor数据库/back_login.py
back_login.py
py
317
python
en
code
0
github-code
13
1966347101
from Balance.conversor import converte_amount_str from Balance.conversor import negative_amount """arquivo que contem uma unica funcao que converte o valor inserido em string para ser retornado no final""" class Category: ledger: list = [] # e o extrato, aquilo q e mostrado quando damos print no objeto ba...
vagamerous/FreeCodeCamp-Projects
Balance/freeCodeCampProject3.py
freeCodeCampProject3.py
py
5,787
python
en
code
0
github-code
13
17034183124
from __future__ import unicode_literals, division import logging import os import shlex from collections import deque from itertools import starmap from threading import Thread, Event from time import time from typing import Text, Sequence import attr import psutil from pathlib2 import Path from clearml_agent.session...
allegroai/clearml-agent
clearml_agent/helper/resource_monitor.py
resource_monitor.py
py
11,656
python
en
code
205
github-code
13
15505240734
from typing import List from app.api import crud from app.api.models import BookDB, BookSchema from fastapi import APIRouter, HTTPException, Path router = APIRouter() @router.post("/", response_model=BookDB, status_code=201) async def create_book(payload: BookSchema): book_id = await crud.post(payload) res...
jitsejan/fastapi-postgres-crud-vuejs
backend/app/api/books.py
books.py
py
1,499
python
en
code
0
github-code
13
18089515767
import sys from ctypes import * import time import pysdl2.sdl2 as sdl2 from pysdl2.sdl2.keycode import * from glfuncs import * from glconstants import * import Square import Hexagon from Program import Program def debugcallback(source,typ, id_,severity, length, message, obj ): print(message) sdl2.SDL_Init(sdl2.S...
TylermEvans/Portfolio
ETGG2801 Labs/lab 3/main.py
main.py
py
2,680
python
en
code
1
github-code
13
69829707219
import numpy as np class Matrix: def __init__(self , shape , elems = []): ''' Summary: Initializes a matrix with a given shape. At the init phase, the user can pass elements if they would like. Else, they will be zeros. Parameters ---------- ...
brendrach/Computational_Astro_ASTP720
Assignment_2/matrix.py
matrix.py
py
10,263
python
en
code
2
github-code
13
7882722233
''' INFER GDI VALUES BY SIMULATING GENETREES UNDER THE MSC+M MODEL ''' import re import copy import subprocess import os from .classes import BppCfile, BppCfileParam, GeneTrees, gdi, AlgoMode, MigrationRates from .module_ete3 import Tree, TreeNode from .module_helper import readlines, dict_merge, get_bundled_bpp_path...
abacus-gene/hhsd
hhsd/module_gdi_simulate.py
module_gdi_simulate.py
py
7,931
python
en
code
0
github-code
13
10008771909
# -*- coding: utf-8 -*-\ import psutil import socket import time import datetime import array import redis import pyodbc import telnetlib # telnet HOST = "localhost" PORT = 1433 TIMEOUT = 1 t = telnetlib.Telnet() # sql server sqlstr01 = "SELECT isnull(datediff(ss,min(dtd.database_transaction_begin_time),getdate()),0)...
zhangjiongcn/BR
Client/win/ccidbv2.py
ccidbv2.py
py
3,893
python
en
code
0
github-code
13
23145540323
import pyrebase import os from datetime import datetime firebaseConfig = { } def initFirebase(): return pyrebase.initialize_app(firebaseConfig) def getStorage(firebase): return firebase.storage() def uploadImages(firebase, ip): storage = getStorage(firebase) images = os.listdir('./images') currDateTime...
SyedAhris/folio3GANsFastAPI
app/firebase.py
firebase.py
py
620
python
en
code
0
github-code
13
40244845245
import unittest from unittest.mock import MagicMock from proto_pb2.links.links_pb2 import CreateLinksRequest, ReadLinksRequest, UpdateLinksRequest, DeleteLinksRequest from server_functions.servicers.links_servicer import LinksServicer class TestCreateRecordLinks(unittest.TestCase): def setUp(self): self...
YaroslavaShyt/API
server_functions/servicers/tests/test_links_servicer.py
test_links_servicer.py
py
2,690
python
en
code
0
github-code
13
39109595492
import numpy as np import tensorflow as tf from gym import utils from gym.envs.mujoco import mujoco_env from asynch_mb.meta_envs.base import MetaEnv class InvertedPendulumEnv(mujoco_env.MujocoEnv, utils.EzPickle, MetaEnv): def __init__(self): utils.EzPickle.__init__(self) mujoco_env.MujocoEnv.__...
zzyunzhi/asynch-mb
asynch_mb/envs/mb_envs/inverted_pendulum.py
inverted_pendulum.py
py
1,815
python
en
code
12
github-code
13
31843765421
import re import sys import requests if __name__ == "__main__": fp = sys.argv[1] bad_links = [] with open(fp) as f: try: for x in re.findall('(?:http|ftp|https):\/\/[\w_-]+(?:(?:\.[\w_-]+)+)[\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-]?', f.read()): print(x) if(re.match('404',requests.get(x).text))...
oliverclark15/continuous-cv
deadlinker.py
deadlinker.py
py
459
python
en
code
0
github-code
13
70756536659
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Программа pcad_univ_tk.py - графическая оболочка для программы-модуля pcad_univ_cp.py (командной строки) для получения заготовок файлов "Перечня элементов" и "Спецификации" из PCB-файла. """ # Автор: Л.М.Матвеев import common common.pyscr =...
leonid-matvieiev/pcad_univ
pcad_univ_tk.py
pcad_univ_tk.py
py
5,975
python
ru
code
0
github-code
13
18888050420
import pytest from unittest import TestCase from gensim.models import LdaModel, Nmf, LsiModel from ..src.model.tm.tm_train import ( build_gensim_model, compute_coherence_score, evaluate_topic_models) import pandas as pd from ..src.preprocessing.rawdata_preprocessing import PREPROCESS_RAW from ..src.preproc...
nivii26/DSA4263-Voice-of-Customer-VOC-analysis
root/unit_testing/test_tm_train.py
test_tm_train.py
py
3,049
python
en
code
2
github-code
13
12329827648
# # @lc app=leetcode.cn id=399 lang=python # # [399] 除法求值 # # @lc code=start class Solution(object): def calcEquation(self, equations, values, queries): """ :type equations: List[List[str]] :type values: List[float] :type queries: List[List[str]] :rtype: List[float] ...
Llunch4w/leetcode-cn
399.除法求值.py
399.除法求值.py
py
2,656
python
en
code
0
github-code
13
10669336465
import os import click from flask import Flask from flask_login import current_user from todoism.blueprints.home import home_bp from todoism.blueprints.auth import auth_bp from todoism.blueprints.todo import todo_bp from todoism.extensions import babel, db, login_manager, csrf from todoism.settings import config from...
parkerhsu/Flask_Practice
Todoism/todoism/__init__.py
__init__.py
py
1,697
python
en
code
0
github-code
13
35381091215
def solution(phone_book): answer = True # print(phone_book) # map을 만듦 # map 안에 element가 존재하는지 여부 확인 # dictOfPhone = { i : 1 for i in phone_book } dictOfPhone = {} for phone in phone_book: phone_len = len(phone) for i in range(1, phone_len+1): #...
gitJaesik/algorithm_archive
programmers/전화번호_목록/python.py
python.py
py
707
python
en
code
0
github-code
13
36256597633
from tkinter import * from tkinter import ttk from tkinter import messagebox from poke_api import get_poke_info #Creating the window root = Tk() root.title("Pokemon Info Viewer") root.resizable(False, False) # adding frame to the window frm_top = ttk.Frame(root) frm_top.grid(row=0, column=0, columnspan=2, padx=10,...
kunjthakkar/Lab_009
poke_viewer.py
poke_viewer.py
py
4,152
python
en
code
0
github-code
13
16128317553
def my_gen(): try: yield "value" except ValueError: yield "Handling Exception" finally: print("cleaning up") x = my_gen() next(x) e = ValueError("some error") print(x.throw(e)) # "Handling Exception" print(x.close()) # Cleaning Up
udhayprakash/PythonMaterial
python3/09_Iterators_generators_coroutines/03_generators/08_error_handling.py
08_error_handling.py
py
274
python
en
code
7
github-code
13
21642475925
from django.shortcuts import render from ArchiveApp.models import Movies, MovieReview, Admin from django.http.response import HttpResponseRedirect from django.core.files.storage import FileSystemStorage # Main Screetn def Main(request): datas = Movies.objects.all() return render(request, "Main.html", {"recento...
LeeKwanDong/MovieArchive
ArchiveApp/views.py
views.py
py
5,622
python
en
code
0
github-code
13
15807281999
import os from shutil import copyfile from sys import exit ritogame = input("Please enter the location of your Riot Games folder (default C:/Riot Games/)\n>") if ritogame == "": # Sets default if user did not enter anything. ritogame = "C:/Riot Games/" if ritogame[-1] != "/": # Adds trailing slash. ritog...
SingedSimp/lolkeys
startup.py
startup.py
py
1,365
python
en
code
0
github-code
13
27249786110
import io import os import re from setuptools import find_packages from setuptools import setup def read(filename): filename = os.path.join(os.path.dirname(__file__), filename) text_type = type(u"") with io.open(filename, mode="r", encoding='utf-8') as fd: return re.sub(text_type(r':[a-z]+:`~?(.*...
nogoodusername/py-useless-package
setup.py
setup.py
py
1,199
python
en
code
0
github-code
13
7997485807
# Author: Charse ''' 在特征降维中, 主成分分析(Principal Componment Analysis) 是最为经典个实用的特征降维技术,特别时在辅助图像识别方面有突出的表现 ''' import pandas import numpy from sklearn.svm import LinearSVC from sklearn.decomposition import PCA from matplotlib import pyplot as plt from sklearn.metrics import classification_report digits_train = pandas.read_...
Wangchangchung/ClassicModel
non-supervision/dimensionality-reduction/PCAreduction.py
PCAreduction.py
py
3,044
python
zh
code
0
github-code
13
39466033860
class lcs: def __init__(self,x,y): self.x=x self.y=y m=len(x) n=len(y) self.c=[] self.b=[] for i in range(m+1): new_c=[] new_b=[] for j in range(n+1): new_b.append("") new_c.append(0) self.c.append(new_c) self.b.append(new_b) def lcs_compute(self): m=...
anubhabMajumdar/Classic-Algorithms-in-Python-
lcs.py
lcs.py
py
1,264
python
en
code
0
github-code
13
4533298325
n = int(input()) a = 2 nums = [] while True: if n == 1: break if n % a == 0: nums.append(a) n = n / a a = 2 else: a += 1 for i in nums: print(i)
hajihye123/Cherry_picker
treecreeper/step09/11653.py
11653.py
py
202
python
en
code
0
github-code
13
73526045456
def main(): import pandas as pd import numpy as np import seaborn as sns import geopandas as gpd from matplotlib import cm from scipy import stats from itertools import permutations import matplotlib.pyplot as plt plt.rcParams['svg.fonttype'] = 'none' meta = pd.read_tab...
BigDataBiology/AMPsphere
General_Scripts/11_host_non_host_amps/main.py
main.py
py
13,572
python
en
code
0
github-code
13
14386340720
import json import datetime from restrepo.utils import flatten, string_to_datetime, datetime_to_string_zulu from restrepo.utils import cleanup_string, content_tostring from restrepo.db.mixins import DictAble from restrepo.db.ead import c_node_selector from restrepo.db.solr import build_equality_query from restrepo.db.a...
sejarah-nusantara/repository
src/restrepo/restrepo/db/eadcomponent.py
eadcomponent.py
py
10,508
python
en
code
0
github-code
13