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
31432720813
from conectie import Server from DC_Motor import dc_motor from accu import battery import RPi.GPIO as GPIO class robot(): def __init__(self): self.speed = 1 #initialisatie code GPIO.setmode(GPIO.BOARD) #board setten run = True robots = robot() Connecting = Server() Motor = dc_motor() Battery = battery() server ...
remblim/rasp_stofzuiger
stofzuiger.py
stofzuiger.py
py
2,516
python
en
code
0
github-code
36
14823356169
# # @lc app=leetcode.cn id=94 lang=python3 # # [94] 二叉树的中序遍历 # # https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/ # # algorithms # Medium (64.80%) # Likes: 189 # Dislikes: 0 # Total Accepted: 31.5K # Total Submissions: 48.1K # Testcase Example: '[1,null,2,3]' # # 给定一个二叉树,返回它的中序 遍历。 # #...
ZodiacSyndicate/leet-code-solutions
medium/94.二叉树的中序遍历/94.二叉树的中序遍历.py
94.二叉树的中序遍历.py
py
1,040
python
en
code
45
github-code
36
74667028905
# -*- coding: utf-8 -*- # https://mathmod.deviantart.com/art/Pseudo-Hopf-Tori-565531249 import os from math import pi, atan2, asin, sqrt, cos, sin import numpy as np import pyvista as pv import quaternion def quaternion2hab(q): "Quaternion to heading, attitude, bank" c = 180 / pi t = q.x*q.y +...
stla/PyVistaMiscellanous
pseudoHopfTorus_anim.py
pseudoHopfTorus_anim.py
py
3,991
python
en
code
4
github-code
36
30876974819
import pandas as pd nfa = {} n = int(input("Enter the total states in NFA: ")) t = int(input("Enter the number of transitions: ")) for i in range(n): state = input('State name: ') nfa[state] = {} for j in range(t): path = input("Enter the path: ") reaching_state = [x for x in input("Enter t...
19nixon19/NFA-to-DFA-Complier-Design
main.py
main.py
py
1,729
python
en
code
0
github-code
36
3045874520
#Parse Code Coverage json file from SFDX Cli import os import os.path from os import path import sys import json import math #take args from std in filepath = sys.argv[1] with open(filepath) as f: tests = json.load(f) #open file for writing dirPath = input("Enter file output dir: ") filePath = dirPath+'.txt' ...
bspeelm/SFDX_CC_Tool
SFDX_CC_Parser.py
SFDX_CC_Parser.py
py
1,020
python
en
code
0
github-code
36
23830783598
#!/usr/bin/python3 """ this function returns a lst of integers representing pascal's triangle returns empty lst if n<= 0 we assume n will always be an integer """ def pascal_triangle(n): """returns integers in pascal's triangle""" if n <= 0: return [] # returns empty lst if lst is < 0 shape ...
MagzShiku/alx-higher_level_programming
0x0B-python-input_output/12-pascal_triangle.py
12-pascal_triangle.py
py
616
python
en
code
0
github-code
36
11394943095
from argparse import Namespace opts = Namespace() # StyleGAN2 setting opts.size = 1024 opts.ckpt = "pretrained_models/ffhq.pt" opts.channel_multiplier = 2 opts.latent = 512 opts.n_mlp = 8 # loss options opts.percept_lambda = 1.0 opts.l2_lambda = 1.0 opts.p_norm_lambda = 1e-3 # arguments opts.device = 'cuda' opts.s...
ZPdesu/MindTheGap
options/face_embed_options.py
face_embed_options.py
py
561
python
en
code
47
github-code
36
3644272928
#GUI CODE import threading import time import tkinter as tk import openai from tkinter import ttk, filedialog from NL_SQL_Engine import * from entity import * CREATE_SCHEMA_RESULTS="EMPTY" CREATE_QUERY_RESULTS="EMPTY" ASSESS_SCHEMA_RESULTS="EMPTY" CREATE_SCHEMA_ID = 1 CREATE_QUERY_ID= 2 ASSESS_SCHEMA_ID= 3 #main...
MatthewMcNatt/CSE4322SQL
GUI_DRIVER.py
GUI_DRIVER.py
py
13,710
python
en
code
0
github-code
36
8172670109
from __future__ import absolute_import from __future__ import division import os import sys import argparse __author__ = "Jonathan Madsen" __copyright__ = "Copyright 2020, The Regents of the University of California" __credits__ = ["Jonathan Madsen"] __license__ = "MIT" __version__ = "@PROJECT_VERSION@" __maintainer_...
NERSC/timemory
timemory/analyze/__init__.py
__init__.py
py
8,843
python
en
code
328
github-code
36
6141168752
from sklearn import datasets, model_selection, metrics from sklearn.externals import joblib from sklearn.linear_model import LogisticRegression iris = datasets.load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.3, shuffle=True, random_state=...
10kaoru12/4y-university-information-recommender-system
3/samplecode_201904_v1/chapter07/train.py
train.py
py
558
python
en
code
0
github-code
36
14292500742
import numpy as np import matplotlib.pyplot as plt def plot_sun(sunposition, d): ''' ''' fig = plt.figure(figsize=d['figsize']) tks = [np.deg2rad(a) for a in np.linspace(0,360,8,endpoint=False)] xlbls = np.array(['N','45','E','135','S','225','W','315']) ax = fig.add_subplot(111, projection='...
cisaacstern/horpyzon
_plot.py
_plot.py
py
897
python
en
code
0
github-code
36
8254543042
# coding: utf-8 # 9를 가지고 있는 n번째 숫자 제곱하 # 입력받아 리스트형태로 저장하기 N = int(input()) num_string = input() num_list = num_string.split(' ') # 9가 아닌 리스트 새로 생성 not_9_list = [int(num) for num in num_list if '9' not in num] # 잘못된 입력값일 경우 처리 (1 9가 없는 숫자가 없는 경우, 2. N번째 숫자가 없는 경우) if len(not_9_list) == 0 or len(not_9_list) < N: ...
smothly/ToBigs
week1/algorithm_1/week1_1_최승호.py
week1_1_최승호.py
py
526
python
ko
code
0
github-code
36
73052622504
with open('day14_in.txt') as f: lines = f.readlines() points = [[[int(x) for x in coord.split(',')] for coord in line.split(' -> ')] for line in lines] rock_lines = [] rocks = set() for l in points: rock_line = [] for c1,c2 in zip(l[:-1], l[1:]): x1 = c1[0] x2 = c2[0] y1 = c1[1] ...
levivk/advent-of-code
2022/day14.py
day14.py
py
2,813
python
en
code
0
github-code
36
10197325599
# nosetests --nocapture tests/test_field.py import os import unittest from fit_tool.fit_file import FitFile class TestActivityFiles(unittest.TestCase): def setUp(self): super().setUp() # stream_handler = logging.StreamHandler(sys.stdout) # stream_handler.setFormatter(formatter) ...
soh55/python_fit_tool
fit_tool/tests/test_activity_files.py
test_activity_files.py
py
1,377
python
en
code
0
github-code
36
17754412541
from BaseSolver import BaseSolver from random import randrange import math # Time complexity: O(N) # Space complexity: O(1) def getRouteCost(route): cost = 0 routeLength = len(route) for i in range(1, routeLength): previous = route[i - 1] current = route[i] cost += previous.costTo...
cameronjoebrown/cs312_group_tsp
GreedySolver.py
GreedySolver.py
py
2,704
python
en
code
0
github-code
36
42162243208
#!/usr/bin/env python # coding: utf-8 # # 1. Character Input # # <i>Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.</i> # In[1]: name = input("Enter your Name: ") age = int(input("Enter your age...
Bhaveshdinesh/PythonPractice
1. Charecter Input/program.py
program.py
py
434
python
en
code
0
github-code
36
9216785537
''' Created on 26 Jul 2017 @author: zhi liang ''' # current stamp duty tiers STAMP_DUTY_TIER_ONE = 180000 STAMP_DUTY_TIER_TWO = 360000 ONE_PERCENT = 0.01 TWO_PERCENT = 0.02 THREE_PERCENT = 0.03 def calculateStampDuty(propertyPrice): if (propertyPrice <= STAMP_DUTY_TIER_ONE): return ONE_PER...
chenzhiliang94/SG-HDB
AffordabilityCalculator/getCPFToTopUp.py
getCPFToTopUp.py
py
1,132
python
en
code
0
github-code
36
347769393
from PySimpleGUI import PySimpleGUI as sg import pyautogui as ag from time import sleep def automatic(nf, frota, fornecedor, responsavel, saude, educacao, outros, viagemSim, qtd, data, preco, obs, km): if (viagemSim == True): precoViagem = sg.popup_get_text('Preço da viagem: ') # saindo do automa...
GuiGolfeto/AppAlmoxarifado
screen/cadastro.py
cadastro.py
py
6,592
python
pt
code
1
github-code
36
22555828419
import pandas as pd from sklearn.model_selection import train_test_split from sklearn import preprocessing # odczyt danych film_data = pd.read_csv('MoviesOnStreamingPlatforms_updated.csv') # Czyszczenie wierszy z pustymi warościami. film_data.dropna(inplace=True) # Usunięcie zbędnych kolumn film_data.drop(film_data....
jarmosz/ium_CML
get_data.py
get_data.py
py
1,385
python
en
code
0
github-code
36
11532751793
import os import re from typing import TypeVar, Optional from argparse import ArgumentParser, Namespace from urllib.request import urlopen from pathlib import Path from hashlib import sha256 ARTIFACTS = [ "opa_darwin_amd64", "opa_darwin_arm64_static", "opa_linux_amd64", "opa_linux_amd64_static", "o...
ticketmaster/rules_opa
tools/opa_upgrade.py
opa_upgrade.py
py
3,005
python
en
code
4
github-code
36
1849580311
import unittest from functions.decrypt import Decrypt from functions.encrypt import Encrypt class TestEncryptDecrypt(unittest.TestCase): def test_encrypt_function(self): text = 'Get this message to the main server' expected = 'trg guvf zrffntr gb gur znva freire' shift = 13 resu...
zideano/Python-Bootcamp
unittests/TestEncryptDecrypt.py
TestEncryptDecrypt.py
py
932
python
en
code
0
github-code
36
40241943573
""" Vasya's classmates came to visit. His mother decided to treat the boys with cookies. But it's not that easy. Cookies can be different sizes. And each child has a greedy factor - the minimum size of a cookie he will take. You have to figure out how many kids will be satisfied at best when they act optimally. Each ...
nastyatonkova/ya_algorithms
sprint_13/D_cookies.py
D_cookies.py
py
874
python
en
code
1
github-code
36
20437878434
#!/usr/bin/env python # -*- coding:Utf-8 -*- # ########################################################################### # # # Nao Challenge 2014 Main Program # # # ########################################################################### # # # File: ihm.py ...
NSenaud/NaoChallengeProject
Nao/naoqi/NaoChallenge/ihm.py
ihm.py
py
2,747
python
en
code
0
github-code
36
20637675592
#!/usr/bin/env python # coding: utf-8 # In[2]: import networkx as nx import pandas as pd import matplotlib.pyplot as plt df = pd.read_excel('Dataset.xlsx', index = None) df.head() G=nx.from_pandas_edgelist(df, 'Departure Station', 'Arrival Station','Time of Travel') nx.draw(G, with_labels=False) df['Route'] = df['D...
aseemkc/Travel-Planner1
Travel Planner/Algorithm.py
Algorithm.py
py
1,280
python
en
code
0
github-code
36
36631030239
import argparse from pathlib import Path import numpy as np from localisation import run_convergence_localisation_on_file, run_localisation_on_file import Models.models as models import Utils.constants as const from plotting import parameter_plot, comparison_plot, plot_evaluation_metric def rmse(predictions: dict): ...
TechTurtle11/ble-geolocation
src/evaluate.py
evaluate.py
py
10,742
python
en
code
0
github-code
36
2616418614
#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/incorrect-regex import re if __name__ == '__main__': t = int(input()) for i in range(t): s = input() try: x = re.compile(s) print("True") except: print("False")
shomeier/hackerrank
python/src/incorrect-regex/incorrect_regex.py
incorrect_regex.py
py
295
python
en
code
0
github-code
36
13507362
''' filters.py Roman Schiffino 151B Fall Semester This is one of the main project files. It does what the lab asks it to do. I made a bunch of filters because I was just testing all the options. I finally settled on three of these for the final warholl image. I use the matrix class to keep track of the color at each...
schiffinor/CS-151
CodingProjects/Project06/Project06Folder/filters.py
filters.py
py
20,864
python
en
code
0
github-code
36
71878708903
#!/usr/bin/python import sys import logging from random import randint from dataclasses import dataclass, field from typing import Optional, List import datasets import numpy as np from datasets import load_dataset, load_metric import transformers from transformers import ( AutoConfig, AutoModelForTokenClassif...
haowang-cqu/graduation-project
fine-tune/ner/run_ner.py
run_ner.py
py
9,700
python
en
code
6
github-code
36
39556047469
# This is the model that agent acts on. import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn.parameter import Parameter import math class DownsampleB(nn.Module): def __init__(self, nIn, nOut, stride=2): super(DownsampleB, self).__init__() ...
chrisVat/GumDrop
network.py
network.py
py
5,534
python
en
code
0
github-code
36
33723847712
""" write a program that given the name of a text file can write its content with each sentence on a separate line. Test your program with the following short text: Mr. Miyagi bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn't. In any case, this isn't ...
Jocelin21/AlgorithmSirJude
Forum/S12 File Exercises/4. Sentence Splitting/Sentence Splitting.py
Sentence Splitting.py
py
542
python
en
code
0
github-code
36
16313772281
import requests _BASE_WORD_URL = 'http://www.dictionary.com/browse/' _DEFAULT_HEADERS = { 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36', 'host': 'www.dictionary.com' } _DEFAULT_AUDIO_HEADERS = { 'user-agent': 'Mozilla/5.0 (Wind...
mradlinski/dictcom
dictcom/download.py
download.py
py
807
python
en
code
5
github-code
36
30389595402
import os import pickle import numpy as np import matplotlib.pyplot as plt import csv FILE_PATH = "C:\\data\\fh_mal_train" GRAPH_PATH = "C:\\code\\count_mal.pickle" def get_size(start_path = '.'): total_size = 0 total_count =0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filen...
siklee/mal_deep
check_file.py
check_file.py
py
2,063
python
en
code
0
github-code
36
17701301018
from cgi import print_environ import torch from collections import OrderedDict from maml import MAML def adaptation(model, optimizer, train_x,train_y, val_x,val_y, loss_fn, lr, train_step, train, device): predictions = [] labels = [] epoch_loss = 0 # x_train, y_train = trainbatch #x_train テンソル化...
fukitani/MAML_AD
train.py
train.py
py
3,833
python
en
code
0
github-code
36
13217323943
# coding: utf-8 # In[ ]: # In[29]: #起始標準起手式~ import requests as rq from bs4 import BeautifulSoup as bs from collections import OrderedDict as od import json import csv import traceback as tb import re # In[30]: HOST = 'http://www.dodocook.com/recipe/' # In[31]: #def dodocook_crawler(開始文章ID,結束文章ID) def ...
nick800608/TeamProject-FoodRecipe
dodocook_cralwer.py
dodocook_cralwer.py
py
2,435
python
en
code
0
github-code
36
34036855952
# Задание №1 from sys import argv hours_worked_out, rate_for_the_time, prize = argv hours_worked_out = int(hours_worked_out) rate_for_the_time = int(rate_for_the_time) prize = int(prize) result = int(hours_worked_out * rate_for_the_time + prize) print(f"Зраработная плата сотрудника составит - {result}") # Задание №2 ...
TBidnik/python
lesson_4_hw.py
lesson_4_hw.py
py
2,236
python
ru
code
0
github-code
36
7342764849
import blockvis import newapp import nfinder import numpy as np #File Initialization file_name = 'blocks.xlsx' coordinates, sizes = newapp.excel_to_arrays(file_name) path=[] while len(coordinates)>0: #CREATES A MASK TO REMOVE ALL BLOCKS THAT ARE NOT MINEABLE mask = np.ones(len(coordinates), dtype=bool) ...
mehrsachal/Voxels
main.py
main.py
py
1,982
python
en
code
0
github-code
36
24630926789
from database.database import Databases import uuid import time class scoreDB(Databases): def __init__(self): super().__init__() self.avg_score_table = "avg_score" self.realtime_score_table = "realtime_score" self.subject_name_table = "subject" self.user_subject_rel = "user_...
kojunseo/TTancent
web/database/score.py
score.py
py
5,238
python
en
code
0
github-code
36
37937108471
from dataclasses import dataclass import os import sys import time from datetime import datetime import tempfile import shutil import json from fastapi import APIRouter, HTTPException, UploadFile, Response from app.controllers.processors import image as PI from app.core import logger from app.utils import utilities as...
KiranCHIHX/Handwritten
app/api/hw_classifier.py
hw_classifier.py
py
3,047
python
en
code
0
github-code
36
3106439706
import argparse import json import os import re import time from simplex_sdk import SimplexClient from car_rewrite_model.model import CarRewriteSynonymsReplace, CarRewriteBaseKeywordsNewProcess # phrases_before_colon_file='/data/share/liuchang/car_rewirte_compare/remove_words' # with open(phrases_before_colon_file,...
flyliu2017/car_rewrite_model
tests/local_predict.py
local_predict.py
py
5,639
python
en
code
0
github-code
36
30072780652
# -*- coding: utf-8 -*- """ Download excel files and transform to correct format in csv files. """ """ Excel files are linked in href attribute of <a> elements in the given URL (Not nested URLs)""" """ Each station, in stations array, is linked to a numerical code in this file""" """ Longitude and latitude and locati...
CUTLER-H2020/DataCrawlers
Environmental/thess_env_cityofthess_dailyyearly.py
thess_env_cityofthess_dailyyearly.py
py
12,139
python
en
code
3
github-code
36
30306014313
import random #this is the output file name filename = "ThreesInput.txt" #this is the total number of pieces noOfPieces = 200 #these are the proportions of 1, 2, 3, 6, 12, etc. #the proportions are summed and rounded, so the number of pieces returned won't always be exact #the easiest way to make it exact is for prop...
deanrobertcook/CITS3001
createThreesFiles.py
createThreesFiles.py
py
1,856
python
en
code
0
github-code
36
23412324414
# -*- coding: utf-8 -*- """ Config initialization """ from .runtime import RuntimeEnum, current_runtime from .config_def import Configuration from .boto_ses import lbd_boto_ses from pysecret import AWSSecret def _local() -> Configuration: from .boto_ses import dev_boto_ses stage = "dev" param_name = f"t...
MacHu-GWU/aws_text_insight-project
aws_text_insight/config_init.py
config_init.py
py
904
python
en
code
0
github-code
36
18870036238
import pandas as pd import json import re import os '../source_file/analysis.table' explist = [] leftlist = [] rightlist = [] index=0 S={} def read_data(): path=os.getcwd()+'/source_file/analysis.table' try: table = pd.read_table(path) except: table=pd.read_table(path,encoding='gbk') ...
YAMY1234/flask-parser
basic/maketree.py
maketree.py
py
2,032
python
en
code
3
github-code
36
11836116546
from numpy import exp, log as ln from styles import mark_styles from constants_calculation import logistic_fraction_logs, ln99 def logistic(t, y0, A, t_half, k_L): return y0 + A/(1 + exp(-k_L*(t - t_half))) logistic.title = 'Non-normalized logistic' logistic.title_lowercase = 'non-normalized logistic' logistic.equ...
hingels/CoOP-Assembly-Analyzer
Curves/logistic.py
logistic.py
py
2,622
python
en
code
0
github-code
36
30722824431
#baekjoon_5557_1학년 N = int(input()); S = list(map(int,input().split())); dp = [[0 for _ in range(21)] for _ in range(N)] dp[0][S[0]] = 1; for i in range(N-2): #N-2까지만 하면 됨. for j in range(21): if dp[i][j] == 0: continue; #더하기 sum = j + S[i+1] if sum <= 20: dp[i+1][su...
Hoony0321/Algorithm
2022_03/19/baekjoon_5557.py
baekjoon_5557.py
py
483
python
en
code
0
github-code
36
12371111911
#N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오. #시간제한 3초 메모리제한 8MB import sys input = sys.stdin.readline n = int(input()) M = 10001 cnt_list = [0]*M for i in range(n): cnt = int(input()) cnt_list[cnt] += 1 for i in range(M): if cnt_list[i] != 0: for j in range(cnt_list[i]): print(i)
hwangstone1/Algorithm_repository
Algorithm_sorting/exercise_8.py
exercise_8.py
py
395
python
ko
code
0
github-code
36
70990945383
import torch import torch.nn.functional as F from torch import nn from torch import optim from torch.distributions import Categorical import numpy as np import matplotlib.pyplot as plt from statistics import stdev, mean import multiprocessing import gym from model import Network from utils import set_seed def plo...
dylanamiller/actor_critic
actor_critic.py
actor_critic.py
py
3,065
python
en
code
0
github-code
36
13225956088
import xml.sax from itertools import accumulate import logging import os from collections import OrderedDict class XMLHandler(xml.sax.ContentHandler): def __init__(self): self.CurrentData = "" self.date = "" self.post_date = "" self.debit_credit_flag = "" self.response_...
cathrinejchristy/Automation
XmlCompare_test.py
XmlCompare_test.py
py
13,268
python
en
code
0
github-code
36
7795728408
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : 矩阵中的最长递增路径.py # @Author: smx # @Date : 2020/2/18 # @Desc : # 最普通的方法:深度搜索,超时! # 超时-> 保存中间变量!!!!!!!! # 超时-> 保存中间变量!!!!!!!! # 超时-> 保存中间变量!!!!!!!! # 超时-> 保存中间变量!!!!!!!! # 超时-> 保存中间变量!!!!!!!! # 超时-> 保存中间变量!!!!!!!! class Solution: def DFS(self, x, y, mat, m, n, ...
20130353/Leetcode
target_offer/dfs+bfs+动态规划/DFS+BFS/矩阵中的最长递增路径.py
矩阵中的最长递增路径.py
py
1,453
python
en
code
2
github-code
36
15860824543
import logging import scrapy from crawler.items import MusicItem, ArtistItem from crawler.spiders.base import BaseSpider class ZkSpider(BaseSpider): name = 'zk' allowed_domains = ['zk.fm'] handle_httpstatus_list = [304, 404] base_url = 'https://zk.fm' count_page = 10 ** 6 def start_requests...
Arthur264/music_data
code/crawler/spiders/zk.py
zk.py
py
2,581
python
en
code
2
github-code
36
25843955389
#pythogoran triplet def pythogoran(arr,n): for i in range(n): arr[i]=arr[i]*arr[i] for i in range(n-1,1,-1): j=0 k=i-1 while j<k: if arr[j]+arr[k]==arr[i]: return True elif arr[j]+arr[k]<arr[i]: j=j+1 elif arr[j]+arr[k]>arr[i]: k=k-1 return False t=int(input()) for j in range(t): ...
LundPiyush/Hackerrank
pythogorean_triplets.py
pythogorean_triplets.py
py
464
python
en
code
0
github-code
36
12366554892
# -*- coding: utf-8 -*- # # AMPLE documentation build configuration file, created by # sphinx-quickstart on Thu May 26 11:57:09 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
rigdenlab/ample
docs/conf.py
conf.py
py
12,912
python
en
code
6
github-code
36
14379387806
import json from typing import List from django.forms import model_to_dict from wagtail.contrib.routable_page.models import RoutablePageMixin from wagtail.core.models import Page from main.models import Thematic from main.models.country import Country from main.models.country import WorldZone from main.models.models ...
TelesCoop/geodev
main/models/resources_page.py
resources_page.py
py
1,959
python
en
code
0
github-code
36
8446011858
import unittest import numpy from cupy import testing @testing.parameterize(*testing.product({ 'decimals': [-2, -1, 0, 1, 2], })) class TestRound(unittest.TestCase): shape = (20,) @testing.for_all_dtypes() @testing.numpy_cupy_allclose(atol=1e-5) def test_round(self, xp, dtype): if dtyp...
cupy/cupy
tests/cupy_tests/core_tests/test_ndarray_math.py
test_ndarray_math.py
py
3,529
python
en
code
7,341
github-code
36
73494811625
from cmath import sqrt print("ax2 + bx +c = 0") a=int(input("a:")) b=int(input("b:")) c=int(input("c:")) d=(b**2)-(4*a*c) e=(((b-2*b)+sqrt(d))/2*a) f=(((b-2*b)-sqrt(d))/2*a) g=(b-2*b)/2*a if d<0: print("error") elif d==0: print(g) elif d>0: print("x1=",e) print("x2=",f)
dam1koss/sdfsdfs
damir/practice work2/prac3.py
prac3.py
py
293
python
fa
code
0
github-code
36
70947855465
""" accept a list of integer data, determine if there is a pair of product is odd, and the two numbers are different note: only odd * odd = odd number """ def find_pair(data): # this is my solution, use double loop, but too tedious for i in data[:-1]: if (i & 1 == 1): for j in data[1:]: ...
luke-mao/Data-Structures-and-Algorithms-in-Python
chapter1/q14.py
q14.py
py
1,301
python
en
code
1
github-code
36
34070093752
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: queue = [] queue.append(root) all_nodes...
ken24ny/LeetCode
230. Kth Smallest Element in a BST/Solution.py
Solution.py
py
583
python
en
code
0
github-code
36
10666109053
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + # 2839 설...
chahyeonnaa/algorithm
greedy/2839 설탕배달.py
2839 설탕배달.py
py
783
python
ko
code
0
github-code
36
4004022772
from collections import namedtuple from test.mock import MockArgs import os import proze import unittest # The output of all test projects are compiled to the same file. OUTPUT_PATH = 'test/sample/tmp/output.txt' Case = namedtuple('Case', ['root_path', 'expected_output']) dark_and_stormy = Case( 'test/sample/dark...
RobotNerd/proze-python-converter
test/test_compile_text.py
test_compile_text.py
py
3,295
python
en
code
0
github-code
36
74223738662
from calendar import c from pathlib import Path import tempfile import mlflow import pandas as pd from src.modelling.evaluating.eval import evaluate from src.modelling.model.model import Model from src.utils.config import Config from src.utils.utils import create_artifact class MlFlowModel(mlflow.pyfunc.PythonModel):...
DaveFantini/ML-template
src/utils/mlflow.py
mlflow.py
py
4,018
python
en
code
0
github-code
36
74112522982
from rest_framework import routers from .viewsets import CustomUserViewSet, AccountViewset from django.urls import path from . import views urlpatterns = [ path( 'user/login', views.login ), path( 'user/register', views.Register ), path( 'account/getAccount', views.getAccountByEmail ), path( 'account/...
cacero95/LocalTelBack
locatelBank/bank/urls.py
urls.py
py
556
python
en
code
0
github-code
36
72774363945
# This modules reads data from already collected data from APIF and transfer it to our DB hosted with # MongoDB import json from DataBaseObjects.DataBaseObjects import FixtureResult from pymongo import MongoClient for season in range(2011, 2020): # Load file (Static process for now) file = open(f"C:\\Users\\rferre...
SigmaFireFox/SigmaFox
apps/eleven10ths/src/app/11sixteen-desktop-app/DatabaseBuilding/API-Football.com-FixtureResults-TxtToDB.py
API-Football.com-FixtureResults-TxtToDB.py
py
1,380
python
en
code
0
github-code
36
13431297301
import cv2 import boto3 import numpy as np from botocore.exceptions import NoCredentialsError # AWS S3 접근 정보 설정 ACCESS_KEY = '보호처리' SECRET_KEY = '보호처리' BUCKET_NAME = '보호처리' OBJECT_NAME = '보호처리' # S3 클라이언트 초기화 s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) try: # S3 버킷에서 이...
kmyobin/capstone_demo_web
image_download.py
image_download.py
py
913
python
ko
code
0
github-code
36
13583790814
import timing class Node: def __init__(self, data=None, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insert_at_beginning(self, data): node =Node(data, self.head) self.head = node def print(self):...
skaushikk/Mini_projects
codebasics-ll.py
codebasics-ll.py
py
2,653
python
en
code
0
github-code
36
4240863887
start = 0 people = int(input('Количество человек: ')) counting = int(input('Какое число в считалке? ')) print(f'Значит,выбывает каждый {counting}-й человек') list_people = list(range(1, people + 1)) stop = (start + counting - 1) % len(list_people) while len(list_people) > 1: # iterate until there is one item left in...
KriziMV/ruter
Module16/07_rhyme_cnt/main.py
main.py
py
1,989
python
ru
code
0
github-code
36
476956710
from __future__ import annotations from typing import Any, Dict, List, Set, Union from collections import OrderedDict from .rows import Rows from .option import Option from .columns.column import Column from .index import Index from .constraint import Constraint from ..operations.create_table import CreateTable class T...
cmancone/mygrations
mygrations/core/definitions/table.py
table.py
py
26,764
python
en
code
10
github-code
36
317321346
#!/usr/bin/python """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" 05.04.Next Number Given a positive integer, print the next smallest and the next largest num- ber that have the same number of 1 bits in their binary representation. """"""""""""""""""""""""""""""""""""""""""""""""""""""...
DStheG/ctci
05_Bit_Manipulation/04_Next_Number.py
04_Next_Number.py
py
1,991
python
en
code
0
github-code
36
28866132568
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler, LabelEncoder, OneHotEncoder from scipy import stats from sklearn.linear_model import LinearRegression, Ridge from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import make_pipeline from sklearn.metrics ...
Pain122/MLAssignment1
script.py
script.py
py
6,330
python
en
code
0
github-code
36
8754923295
# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, fields, api from of_datastore_product import DATASTORE_IND # Création/édition d'objets incluant un article centralisé class OfDatastoreProductReference(models.AbstractModel): _name = 'of.datastore.pr...
odof/openfire
of_datastore_product/models/of_datastore_product_reference.py
of_datastore_product_reference.py
py
7,676
python
en
code
3
github-code
36
8023958832
import matplotlib.pyplot as plt import compiled def draw(): x_points = [] y_points = [] for x in range(-1000, 1000): try: y_points.append(compiled.compiled_func(x)) x_points.append(x) except: print("Error, posible discontinuidad en: ", x) plt.scatte...
danieltes/tp_solver
draw.py
draw.py
py
357
python
en
code
0
github-code
36
16020153398
import unittest import sqlite3 import json import os import matplotlib.pyplot as plt import requests import plotly.graph_objects as go import plotly.express as px import pandas as pd import csv # starter code def setUpDatabase(db_name): path = os.path.dirname(os.path.abspath(__file__)) conn = sql...
lbibbo6012/2022-finalproject
calculate.py
calculate.py
py
5,532
python
en
code
0
github-code
36
23950768357
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Setup script """ from setuptools import setup import os def read(fname): """returns the text of a file""" return open(os.path.join(os.path.dirname(__file__), fname), 'r').read() def get_requirements(filename="requirements.txt"): """returns a list of al...
nightvisi0n/dockgraph
setup.py
setup.py
py
1,496
python
en
code
2
github-code
36
8285806055
import logging import sqlite3 from sqlite3 import Error logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) class RecordsHandler: def __init__(self, db_file): self.sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS Records ( id integ...
pauligb/TC4002.1_Analisis_Diseno
Lab3/src/records_handler.py
records_handler.py
py
2,868
python
en
code
1
github-code
36
71920474345
class malDataExport: # data can be the map from anilist.trimList def __init__(self, data): self.entries = [] for x in data: self.entries.append(malEntry(x)) def mal_skeleton(self, name): # chr(10) == '\n' return f"""<?xml version="1.0" encoding="UTF-8" ?> <myan...
em-ilia/anilist-sync
myanimelist.py
myanimelist.py
py
2,194
python
en
code
0
github-code
36
71704127463
import pandas as pd import pickle def clean(list_): list_ = list_.replace(' ','') list_ = list_.replace(',', ' ') list_ = list_.replace("'", '') list_ = list_.replace('[', '') list_ = list_.replace(']', '') return list_ # rate all movies based in the true bayesian estimation (refer README.md) ...
esh04/Movie-Recommender
PyScripts/prepping.py
prepping.py
py
2,560
python
en
code
2
github-code
36
4391861651
import torch, torchvision from torch import nn img_hidden_sz = 512 num_image_embeds = 5 #?? 8907 n_classes = 8790 img_embed_pool_type = 'avg' class ImageEncoder18(nn.Module): def __init__(self): super(ImageEncoder18, self).__init__() model = torchvision.models.resnet18(pretrained=True) m...
harveyaot/AlphaTaiBai
azure-functions-python/imgclf/model.py
model.py
py
1,576
python
en
code
24
github-code
36
678009931
import os import sys sys.path.append('..') sys.path.append('../..') import argparse import utils from tsp_helper import * from student_utils import * OUTPUT_FILENAME = "naive_output.txt" """ ====================================================================== Complete the following function. =====================...
anniezhang21/carpool-problem
irrelevant/naive_solver.py
naive_solver.py
py
6,380
python
en
code
0
github-code
36
10663384237
# -*- coding: utf-8 -*- """ Created on Thu Mar 31 16:17:59 2016 Consider Rotation and Glide vector both @author: Neo """ # #def Rotation_Glide(ua,ud,sigua,sigud,alp0,det0): # return [w,sigw,wx,wy,wz,sigwx,sigwy,sigwz,\ # g,sigg,gx,gy,gz,siggx,siggy,siggz,chi] from fun import Rotation_Glide from Da...
Niu-Liu/thesis-materials
sou-selection/icrf/progs/RotationAndGlideFitting.py
RotationAndGlideFitting.py
py
1,048
python
en
code
0
github-code
36
36255605610
from .models import Doc, FileCabinet, Block, Reg # from users.serializers import NotifSerializer from users.models import Notif from rest_framework import serializers import datetime from django.utils import timezone class FileCabinetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = F...
Spanri/edsm-v1
docs/serializers.py
serializers.py
py
2,214
python
en
code
5
github-code
36
40885550378
import os import logging import shutil import tempfile import json from urllib.parse import urlparse from pathlib import Path from typing import Tuple, Union, IO from hashlib import sha256 from nlp_architect import LIBRARY_OUT from nlp_architect.utils.io import load_json_file import requests logger = logging.getLogg...
IntelLabs/nlp-architect
nlp_architect/utils/file_cache.py
file_cache.py
py
5,769
python
en
code
2,921
github-code
36
13989709117
# -*- coding: utf-8 -*- import os import sys os.chdir(os.path.dirname(__file__)) sys.path.insert(0, os.path.abspath(r'../')) from hagworm.extend.logging import LogFileRotator from hagworm.frame.tornado.base import Launcher from routing import router from setting import ConfigStatic, ConfigDynamic from service.base ...
wsb310/hagworm
example/main.py
main.py
py
1,342
python
en
code
13
github-code
36
18520521850
""" Computes a separate frequency dataframe for a sample of 100 songs by each age group. """ import pickle import pandas as pd from compute_aggregate_song_frequencies import compute_frequency_dataframe from random import sample SONGS_FILEPATH = "../../data/processed/songs_with_ages.p" OUTPUT_DIRECTORY = "../../data/pr...
benpry/COG403-songlyrics
code/read_data/compute_frequencies_by_age.py
compute_frequencies_by_age.py
py
1,229
python
en
code
0
github-code
36
35112699995
# implements Kafka topic consumer functionality import os import threading from confluent_kafka import Consumer, OFFSET_BEGINNING import json from producer import proceed_to_deliver import base64 import subprocess UPDATE_CWD = "updater/" STORAGE_PATH = "tmp/" UPDATE_SCRIPT_NAME = "./update-and-restart-app.sh" APP_PAT...
sergey-sobolev/secure-update
updater/consumer.py
consumer.py
py
4,295
python
en
code
2
github-code
36
27549716670
import re import sys import datetime from itertools import zip_longest from email.utils import getaddresses, parsedate_to_datetime from email.header import decode_header, Header from typing import AnyStr, Union, Optional, Tuple, Iterable, Any, List, Dict, Iterator from .consts import SHORT_MONTH_NAMES, MailMessageFlag...
ikvk/imap_tools
imap_tools/utils.py
utils.py
py
7,673
python
en
code
608
github-code
36
205804702
import torch import torch.nn as nn from transformers import BertModel class SentimentClassifier(nn.Module): def __init__(self, freeze_bert = True): super(SentimentClassifier, self).__init__() #Instantiating BERT model object self.bert_layer = BertModel.from_pretrained('bert-base-uncased')...
kabirahuja2431/FineTuneBERT
src/model.py
model.py
py
1,191
python
en
code
44
github-code
36
957907182
# the earliest cached bytecode import os import sys import shutil def fire(): # we need structural pattern matching in templates and cbuild itself if sys.version_info < (3, 10): sys.exit("Python 3.10 or newer is required") # required programs in the system for prog in ["git", "tee"]: ...
chimera-linux/cports
src/early.py
early.py
py
893
python
en
code
119
github-code
36
29612486523
from collections import deque # recursive solution """ runtime O(n), space O(n) """ def getHeight(root): if not root: return 0 return 1 + max(getHeight(root.left), getHeight(root.right)) # max height of the tree should be max height of stack """ runtime O(n), space O(n) """ def getHeight_iter(root): ...
jungwook-lee/coding-practice
tree/getHeight.py
getHeight.py
py
700
python
en
code
0
github-code
36
15024245302
import os from tqdm import tqdm import datetime import pandas as pd import logging logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO, # datefmt='%d-%b-%y %H:%M:%S' ) def get_date_df(file_folder, days): ...
wenyuan-wu/corpus_preprocess_dong
sort_by_day.py
sort_by_day.py
py
2,760
python
en
code
0
github-code
36
7231791491
import json from glob import glob import yaml def get_problems_by_name(response_file): with open(response_file) as f: response = json.load(f) def get_name(place): return place.get("permalink", place.get("id")) name_to_problems = { get_name(place): place["districtingP...
districtr/districtr-process
scripts/add_problems.py
add_problems.py
py
974
python
en
code
2
github-code
36
31561327120
#!/usr/bin/env python # coding=utf-8 """ 给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。   示例: 输入: [1,2,3,4] 输出: [24,12,8,6]   提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。 说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 进阶: 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。) 链接:ht...
lee3164/newcoder
leetcode/238. 除自身以外数组的乘积/main.py
main.py
py
1,615
python
zh
code
1
github-code
36
37823447895
"""Engi Init Walks through the setup enabling a user to work with ENGI. Usage: engi init engi (-h | --help) engi --version Options: -h --help Show this screen """ from git import Repo from gitsecrets import GitSecrets import gnupg import os import re import sys from pathlib import Path import ...
engi-network/cli
src/engi_cli/engi_init.py
engi_init.py
py
3,737
python
en
code
3
github-code
36
40922739466
from typing import List import numpy as np from advent2022 import utils DAY = 9 def load_and_parse_data(day: int, test: bool = False) -> List[str]: data = utils.get_input(day, test) return [l.split(" ") for l in data] def new_pos(h, t): if abs(h[0] - t[0]) > 1 or abs(h[1] - t[1]) > 1: for move_...
c-m-hunt/advent-of-code-2022
advent2022/day9.py
day9.py
py
1,434
python
en
code
0
github-code
36
16239961373
def add_books(): # Функция для добавления книг в словарь books = {} # Инициализация пустого словаря while True: author = input("Введите фамилию автора (или введите 'stop' чтобы закончить): ") if author == 'stop': break book = input("Введите название книги: ") ...
Merlin0108/rep2
lab8/2.py
2.py
py
1,187
python
ru
code
0
github-code
36
4875660942
import os from django.conf import settings from django.shortcuts import render, redirect import face_recognition import numpy as np import cv2 from os.path import dirname, join from django.apps import apps from django.core.files.storage import FileSystemStorage from django.contrib.auth.views import LoginView from djang...
hashir-ashraf/Attendance-System
AttendanceSystem/Instructor/views.py
views.py
py
6,146
python
en
code
0
github-code
36
30699830411
from django.shortcuts import render, get_object_or_404 from zoo.models import Category, Product from django.views.generic import ListView from django.core.paginator import Paginator from zoo.forms import ZooSearchForm class CategoryListView(ListView): model = Product template_name = 'catalog.htm...
Yurevtsev13Pavel/zoolavka
zoo/views.py
views.py
py
2,283
python
en
code
0
github-code
36
21216811074
import io import runoff_class as runoff import unittest from unittest import mock class TestRunoff(unittest.TestCase): def setUp(self) -> None: self.candidates = ["Marta", "Joni", "Fran", "Linda"] self.voter_number = 5 self.model = runoff.Runoff(self.candidates, self.voter_number) ...
SOUADSARAH/Harvard_CS50x_2022_Psets_and_Labs
1.Psets/1.Python_solutions/8.Runoff/test_runoff.py
test_runoff.py
py
8,139
python
en
code
0
github-code
36
18824343900
import unittest import importlib import mock import datetime from oslo_utils import timeutils evacuate_lbaas = importlib.import_module("neutron-evacuate-lbaasv2-agent") class FakeSqlResult(): def fetchall(self): return [ ['1', 'healthy', timeutils.utcnow()], ['2', 'dead', timeuti...
skazi0/cookbook-openstack-network
files/default/test-neutron-evacuate-lbaasv2-agent.py
test-neutron-evacuate-lbaasv2-agent.py
py
2,753
python
en
code
null
github-code
36
837645453
from http.server import HTTPServer, BaseHTTPRequestHandler import sys, io, json, cgi import MolDisplay, molsql, molecule # Create DB db = molsql.Database(reset=True) db.create_tables() # Set our default element values db['Elements'] = (1, 'H', 'Hydrogen', 'FFFFFF', '050505', '020202', 25) db['Elements'] = (6, 'C', '...
acandrewchow/Molecule-Viewer
server.py
server.py
py
9,751
python
en
code
0
github-code
36
14540004948
from __future__ import division # This to be sure that the result of the division of integers is a real, not an integer # Import modules import sys import os import copy import numpy as np ######################## def builddictcave(): """ """ ######################## # Define parameters # thlang: lang...
robertxa/pytherion
pytro2th/buildparam.py
buildparam.py
py
2,047
python
en
code
3
github-code
36
5515870088
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import itertools import tensorflow as tf import numpy as np import cifar10_utils import cifar10_siamese_utils from convnet import ConvNet from siamese import Siamese from sklearn.mult...
frhrdr/dlc2016
practical_3/train_model.py
train_model.py
py
19,281
python
en
code
1
github-code
36