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
10140997594
# -*- coding: utf-8 -*- # @Time : 19-1-24 下午9:35 # @Author : ccs import json from django.http import HttpResponse def calc(request): a = request.GET['a'] b = request.GET['b'] c = request.GET['c'] print(a,b,c) m = a+b+c n = b+a rets = {"m":m,"n":n} retsj = json.dumps(rets) retu...
ccs258/python_code
learn_api.py
learn_api.py
py
348
python
en
code
0
github-code
6
34702779543
from firebase_admin import firestore from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics.pairwise import cosine_similarity def get_user_skills(userid): item = firestore.client().collection('user').document(userid).get().to_dict()['skills'] user_skill_string = ' '.join(str(e) for e...
prajwol-manandhar/resume-analysis-website
analysis.py
analysis.py
py
869
python
en
code
1
github-code
6
1427353112
dic={ 'nile':'egypt', 'yellow river':'shandong', 'yangtze river':'shanghai', } for river,province in dic.items(): print(f"The {river} runs through {province}") for river in sorted(dic.keys()): print(f"{river}") for province in sorted(dic.values()): print(f"{province}")
HAL200000/Python
pcc6-5.py
pcc6-5.py
py
309
python
en
code
0
github-code
6
5291091637
def countdown(i: int) -> int: while i >= 0: yield i i -= 1 def countup(i: int) -> int: f = 0 while f < i: yield f f += 1 def range_countup(start: int, end: int) -> int: while start < end: yield start start += 1 def trim(data: list) -> li...
MichaelFulcher148/Batch-Folder-Create
code_tools.py
code_tools.py
py
1,757
python
en
code
1
github-code
6
21546810060
###IMPORT NECESSARY MODULES TO RUN BIOGEME from biogeme import * from headers import * from loglikelihood import * from statistics import * ### Variables # Piecewise linear definition of income ScaledIncome = DefineVariable('ScaledIncome',\ CalculatedIncome / 1000) ContIncome_0_4000 = DefineVariabl...
LiTrans/ICLV-RBM
biogeme/02oneLatentOrdered.py
02oneLatentOrdered.py
py
9,683
python
en
code
0
github-code
6
9721588822
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk ICONSIZE = Gtk.IconSize.SMALL_TOOLBAR class controlBar(Gtk.HeaderBar): def __init__(self): Gtk.HeaderBar.__init__(self) self.set_show_close_button(True) self.props.title = "PyFlowChart" self.info_bo...
steelcowboy/PyFlowChart
pyflowchart/interface/control_bar.py
control_bar.py
py
3,719
python
en
code
5
github-code
6
1128800769
def findMaxAverage(nums: list[int], k: int) -> float: max_sum = 0 for i in range(k): max_sum += nums[i] curr_sum = max_sum for i in range(1,len(nums)-k+1): curr_sum = curr_sum - nums[i-1] + nums[i+k-1] if curr_sum > max_sum: max_sum = curr_sum return max_sum / k ...
SleepingRedPanda/leetcode
643.py
643.py
py
350
python
en
code
0
github-code
6
7807070088
import logging from copy import deepcopy from itertools import permutations import numpy as np from scipy.special import softmax from scipy.stats import entropy def true_entropy(team_generator, batch_predict, num_items: int, num_selections: int): P_A = np.zeros((num_selections, num_items)) # basically P(A^i_j) ...
nianticlabs/metagame-balance
src/metagame_balance/entropy_fns.py
entropy_fns.py
py
3,539
python
en
code
3
github-code
6
16106061785
def _extend_pre_ranges(df, upstream:int=0, downstream:int=0, start:str="Start", end:str="End", strand:str="Strand"): strand_rm = False if strand not in df.columns: strand_rm = True df[strand] = "+" df.loc[df[strand] == "+", start] -= upstream df.loc[df[strand] == "-", start] -= downstre...
KellisLab/benj
benj/gene_estimation.py
gene_estimation.py
py
11,891
python
en
code
2
github-code
6
19766046195
from util import get_options, check_input import random def game_round(film_data, target_type, question_type, question): target = random.choice(film_data) options = get_options(film_data, target, target_type) print(f"{question}\n>>> {target[question_type]}") print(f"1: {options[0]}\n" f"2: ...
praerie/cinequiz
quiz.py
quiz.py
py
728
python
en
code
1
github-code
6
70267283389
import epyk as pk from epyk.mocks import urls as data_urls # Create a basic report object page = pk.Page() page.headers.dev() # retrieve some random json data data_rest = page.py.requests.csv(data_urls.BLOG_OBJECT) # create a json viewer object j = page.ui.json(data_rest, height=(100, 'px')) # change the default...
epykure/epyk-templates
locals/data/json_viewer.py
json_viewer.py
py
508
python
en
code
17
github-code
6
9766823930
from collections import * import numpy as np from common.session import AdventSession session = AdventSession(day=20, year=2017) data = session.data.strip() data = data.split('\n') p1, p2 = 0, 0 class Particle: def __init__(self, p, v, a, _id): self.p = np.array(p) self.v = np.array(v) ...
smartspot2/advent-of-code
2017/day20.py
day20.py
py
1,196
python
en
code
0
github-code
6
36659620035
# finding the right modules/packages to use is not easy import os import pyodbc from numpy import genfromtxt import pandas as pd import sqlalchemy as sa # use sqlalchemy for truncating etc from sqlalchemy import Column, Integer, Float, Date, String, BigInteger from sqlalchemy.ext.declarative import declarative_base...
BertrandLeroy/GPXReader
ProcessStravaGPX.py
ProcessStravaGPX.py
py
7,471
python
en
code
0
github-code
6
16149992177
# -*- coding: utf-8 -*- __author__ = 'xl' """ __date__ = TIME: 2018/10/02 上午9:24 describe:利用二分搜索树实现集合 """ from bst import BinarySearchTree import chardet import re class MySet: """ 利用二分搜索树实现集合 """ def __init__(self): self.bst = BinarySearchTree() def add(self,e): self.bst.add(e) ...
xStone9527/algorithm
set_.py
set_.py
py
1,354
python
en
code
0
github-code
6
36697678270
#Coded by: QyFashae import os from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import HashingVectorizer, TfidfTransformer from sklearn.metrics import accuracy_score, confusion_matrix from sklearn import tree # Paths to the directories cont...
Qyfashae/ML_IDS_EmailSec_Spam
smtp_assasin.py
smtp_assasin.py
py
2,150
python
en
code
1
github-code
6
27065743114
from abc import ABC from car import Car class Tires(Car, ABC): def __init__(self, last_service_date, left_front_tire_pressure, right_front_tire_pressure, left_rear_tire_pressure, right_rear_tire_presure): super().__init__(last_service_date) self.left_front_tire = left_front_tire_pressure ...
ak55m/Lyft-Forage
tires/all_tires.py
all_tires.py
py
888
python
en
code
0
github-code
6
27259428600
"""We are the captains of our ships, an we stay 'till the end. We see our stories through. """ """947. Most Stones Removed with Same Row or Column """ class Solution: def removeStones(self, stones): visited = {tuple(stone): False for stone in stones} def dfs(s1, visited): ...
asperaa/back_to_grind
Graphs/947. Most Stones Removed with Same Row or Column.py
947. Most Stones Removed with Same Row or Column.py
py
851
python
en
code
1
github-code
6
3954866418
# -*- coding: utf-8 -*- """view module prilog application * view function, and run Flask """ from glob import glob from flask import Flask, render_template, request, session, redirect, jsonify import os import re import json import urllib.parse import subprocess import time as tm import analyze as al import c...
Neilsaw/PriLog_web
app.py
app.py
py
21,596
python
en
code
30
github-code
6
40941005277
# github üzerinden yapılan arama sonuçlarını consola yazdırma from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() url = "https://github.com" driver.get(url) searchInput = driver.find_element_by_name("q") time.sleep(1) print("\n" + driver.titl...
furkan-A/Python-WS
navigate.py
navigate.py
py
588
python
en
code
0
github-code
6
34197446896
#!/bin/python import sys import os import time import datetime import hashlib from os import walk import mysql.connector from sys import argv import json import boto3 from botocore.exceptions import ClientError import requests from requests.exceptions import HTTPError game_client = argv[1] target_dir = argv[2] backof...
vlad-solomai/viam_automation
automation_gambling/deploy_game_client/deploy_game_client.py
deploy_game_client.py
py
8,482
python
en
code
1
github-code
6
36035072095
import tweepy import pandas as pd import re import time from textblob import TextBlob from sqlalchemy import create_engine import yaml import json TWITTER_CONFIG_FILE = '../auth.yaml' with open(TWITTER_CONFIG_FILE, 'r') as config_file: config = yaml.load(config_file) consumer_key = config['twitter']['consumer_key']...
dgletts/project-spirit-bomb
tweets.py
tweets.py
py
2,259
python
en
code
0
github-code
6
11464232803
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 4 18:23:32 2022 @author: sampasmann """ import numpy as np from src.functions.material import Material from src.functions.mesh import Mesh class URRb_H2Oa5_2_0_SL_init: def __init__(self, N=2**10, Nx=100, generator="halton"): self.N =...
spasmann/iQMC
src/input_files/URRb_H2Oa5_2_0_SL_init.py
URRb_H2Oa5_2_0_SL_init.py
py
1,118
python
en
code
2
github-code
6
8927043584
from collections import OrderedDict from concurrent import futures import six from nose import tools from tornado import gen from tornado import testing as tt import tornado.concurrent from flowz.artifacts import (ExtantArtifact, DerivedArtifact, ThreadedDerivedArtifact, WrappedArtifact,...
ethanrowe/flowz
flowz/test/artifacts/artifacts_test.py
artifacts_test.py
py
8,314
python
en
code
2
github-code
6
11275131068
from django.contrib import admin from django.urls import path, include from basesite import views urlpatterns = [ path('', views.index, name='index'), path('academics', views.academics, name='academics'), path('labs', views.labs, name='labs'), path('committee', views.committee, name='committe...
Mr-vabs/GPA
basesite/urls.py
urls.py
py
923
python
en
code
0
github-code
6
10420450933
from __future__ import annotations from typing import TYPE_CHECKING from randovania.games.prime1.layout.hint_configuration import PhazonSuitHintMode from randovania.games.prime1.layout.prime_configuration import ( LayoutCutsceneMode, PrimeConfiguration, RoomRandoMode, ) from randovania.layout.preset_descr...
randovania/randovania
randovania/games/prime1/layout/preset_describer.py
preset_describer.py
py
9,313
python
en
code
165
github-code
6
1868384059
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings # Create your models here. class Country(models.Model): name = models.CharField(_("Name"), db_column='name', max_length = 150, null=True, blank=True) code2 = models.CharField(_("Code2"), db_...
amlluch/vectorai
vectorai/restapi/models.py
models.py
py
696
python
en
code
0
github-code
6
11169933239
# from django.shortcuts import render from rest_framework import generics from review_app.models import FarmersMarket, Vendor from fm_api.serializers import FarmersMarketSerializer, VendorSerializer # Create your views here. class FarmersMarketListAPIView(generics.ListAPIView): queryset = FarmersMarket.objects.al...
dhcrain/FatHen
fm_api/views.py
views.py
py
783
python
en
code
0
github-code
6
12932593468
from django.db import models class UserMailmapManager(models.Manager): """A queryset manager which defers all :class:`models.DateTimeField` fields, to avoid resetting them to an old value involuntarily.""" @classmethod def deferred_fields(cls): try: return cls._deferred_fields ...
SoftwareHeritage/swh-web
swh/web/mailmap/models.py
models.py
py
3,525
python
en
code
11
github-code
6
70728232508
import frida import sys package_name = "com.jni.anto.kalip" def get_messages_from_js(message, data): print(message) print (message['payload']) def instrument_debugger_checks(): hook_code = """ setTimeout(function(){ Dalvik.perform(function () { var TM ...
antojoseph/frida-android-hooks
debugger.py
debugger.py
py
800
python
en
code
371
github-code
6
8179016390
import json import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def hello(event, context): logger.info(f"AWS Lambda processing message from GitHub: {event}.") body = { "message": "Your function executed successfully!", "input": event } response = { "st...
Qif-Equinor/serverless-edc2021
aws-demo/handler.py
handler.py
py
396
python
en
code
0
github-code
6
39304842298
import os from flask import Flask, jsonify, Blueprint from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_bcrypt import Bcrypt import flask_restplus from werkzeug.contrib import fixers # instantiate the extensions db = SQLAlchemy() migrate = Migrate() bcry...
guidocecilio/shows-on-demand-users
src/users/__init__.py
__init__.py
py
1,480
python
en
code
0
github-code
6
17016755905
import urllib.request as request import json src="https://padax.github.io/taipei-day-trip-resources/taipei-attractions-assignment.json" with request.urlopen(src) as response: data=json.load(response) spot_data=data["result"]["results"] with open("data.csv","w",encoding="UTF-8-sig") as file: for spot_item...
ba40431/wehelp-assignments
week_3/week_3.py
week_3.py
py
629
python
en
code
0
github-code
6
43022293294
"""Escribe una función qué reciba varios números y devuelva el mayor de ellos.""" def numero_mayor(lista_numeros): #encuentra el número mayor de una lista mayor = 0 mayor =lista_numeros[0] for item in range(0,len(lista_numeros)): if lista_numeros[item] > mayor : mayor = lista_numero...
lupitallamas/tareasjulio2
nummayor.py
nummayor.py
py
694
python
es
code
0
github-code
6
73931874429
#!python """ The 5-digit number, 16807=75, is also a fifth power. Similarly, the 9-digit number, 134217728=89, is a ninth power. How many n-digit positive integers exist which are also an nth power? """ def num_digits(x): return len(str(x)) if __name__=="__main__": m = 100 s = 0 for i in range(1,m+1): j=1 w...
DanMayhem/project_euler
063.py
063.py
py
412
python
en
code
0
github-code
6
24685520932
from . import views from django.urls import path app_name = 'bankapp' #namespace urlpatterns = [ path('',views.home,name='home'), path('login/',views.login,name='login'), path('register/',views.register,name='register'), path('logout/',views.logout,name='logout'), path('user/',views.user,name='...
simisaby/bank
Bank/bankapp/urls.py
urls.py
py
371
python
en
code
0
github-code
6
20468728047
# sourcery skip: do-not-use-staticmethod """ A module that contains the AIConfig class object that contains the configuration """ from __future__ import annotations import os from typing import Type import yaml class AIConfig: """ A class object that contains the configuration information for the AI At...
badboytuba/nancy
nancy/config/ai_config.py
ai_config.py
py
3,801
python
en
code
0
github-code
6
22626134896
# Name:- Anurag Rai msg1 = input("Enter the message 1 binary code: ") msg2 = input("Enter the message 2 binary code: ") if len(msg1) != len(msg2): print("Wrong Input: Both message is having diffrent length") exit(0) length = len(msg2) result = '' for index in range(length): if msg1[index] == ...
arironman/MSU-Computer-Network-Lab
lab-2 22-09-20/Q1.hamming Distance.py
Q1.hamming Distance.py
py
635
python
en
code
0
github-code
6
40696737073
import asyncio import importlib from abc import ABC, abstractmethod from functools import partial from typing import Any, Awaitable, Callable, Dict, List, Union ParamValueT = Union[str, int, float, bool, List[Union[str, int, float, bool]]] ExecutorFuncT = Callable[[Dict[str, ParamValueT]], Awaitable[Dict[str, Any]]] ...
magma/magma
orc8r/gateway/python/magma/magmad/generic_command/command_executor.py
command_executor.py
py
2,311
python
en
code
1,605
github-code
6
5759883314
# -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal """ import numpy as np import matplotlib.pyplot as plt from sklearn import svm #%% np.random.seed(5) X = np.r_[np.random.randn(20,2)-[2,2],np.random.randn(20,2)+[2,2]] Y = [0]*20+[1]*20 plt.scatter(X[:,0],X[:,1],c=Y) plt.show(...
OscarFlores-IFi/CDINP19
code/p18.py
p18.py
py
902
python
es
code
0
github-code
6
37588584638
from sqlalchemy import TypeDecorator from sqlalchemy.types import VARCHAR from sqlalchemy import dialects from sqlalchemy.dialects import postgresql, mysql import json from typing import Union, Optional DialectType = Union[postgresql.UUID, VARCHAR] ValueType = Optional[Union[dict, str]] class JSON(TypeDecorator): ...
infrascloudy/gandalf
gandalf/database/json_type.py
json_type.py
py
1,390
python
en
code
0
github-code
6
36474819729
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class SideMenuItem(QWidget): open_signal = pyqtSignal(int) def __init__(self, name, height, items=None, alignment="right", style=None, ): super(SideMenuItem, self).__init__() self.alignment = alignment ...
Mahmoud1478/icestore
globals/widgets/sidemenu_item/sidemenuitem.py
sidemenuitem.py
py
5,687
python
en
code
0
github-code
6
41749587001
import numpy as np import pandas as pd from _datetime import timezone, datetime, timedelta #data config (all methods) DATA_PATH = '../../dressipy/store.h5' DATA_PATH_PROCESSED = '../data/dressipi/preparedDS/' #DATA_FILE = 'yoochoose-clicks-10M' DATA_FILE = 'views' DATA_FILE_BUYS = 'transactions' SESSION_LENGTH = 30 * ...
rn5l/session-rec
preprocessing/session_based/preprocess_dressipi.py
preprocess_dressipi.py
py
12,917
python
en
code
362
github-code
6
20600597111
import functools import os import google.protobuf.json_format from synthtool.protos.preconfig_pb2 import Preconfig PRECONFIG_ENVIRONMENT_VARIABLE = "SYNTHTOOL_PRECONFIG_FILE" PRECONFIG_HELP = """ A json file containing a description of prefetch sources that this synth.py may us. See preconfig.proto for detail abou...
googleapis/google-cloud-java
owl-bot-postprocessor/synthtool/preconfig.py
preconfig.py
py
777
python
en
code
1,781
github-code
6
4369034891
# coding: utf-8 import pandas as pd import xgboost as xgb from sklearn.preprocessing import LabelEncoder import numpy as np train_df = pd.read_csv('../data/train.csv') test_df = pd.read_csv('../data/test.csv') # 填充空值,用中位数填充数值型空值,用众数填充字符型空值 from sklearn.base import TransformerMixin class DataFrameIm...
Gczaizi/kaggle
Titanic/XGBoost/XGBoost.py
XGBoost.py
py
1,786
python
en
code
0
github-code
6
37585700958
import tkinter as tk from tkinter import * from tkinter import ttk from tkinter.messagebox import showinfo import tkinter.font as tkFont import sqlite3, time, datetime, random name_of_db = 'inventory_master.db' my_conn = sqlite3.connect(name_of_db) cdb = my_conn.cursor() def create_table(): cdb.exec...
InfoSoftBD/Python
CustomerUpdate.py
CustomerUpdate.py
py
9,946
python
en
code
2
github-code
6
36830731053
import json import time from threading import Thread import pika from pika.exceptions import ConnectionClosed from utils import Logging class RabbitMQClient(Logging): _channel_impl = None def __init__(self, address, credentials, exchange, exchange_type='topic'): super(RabbitMQClient, self).__init__...
deepsense-ai/seahorse
remote_notebook/code/rabbit_mq_client.py
rabbit_mq_client.py
py
4,047
python
en
code
104
github-code
6
12998412388
import uuid from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL # Create your models here. class PlanCharge(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) tier = models.IntegerField() charge_id = models.CharField(max_len...
kapphire/99typos-server
plan/models.py
models.py
py
585
python
en
code
0
github-code
6
11579230306
import sklearn import cv2 import pandas as pd import numpy as np import math from sklearn.cluster import KMeans from sklearn.metrics import silhouette_samples, silhouette_score from collections import Counter from scipy.spatial import distance_matrix from scipy.sparse.csgraph import shortest_path class ImageClassifie...
elraffray/pyImage
imageclassifier.py
imageclassifier.py
py
6,442
python
en
code
0
github-code
6
49613121
from collections import deque, defaultdict import random class RandomizedSet: def __init__(self): self.vec = deque() self.hash_map = defaultdict(int) def insert(self, val: int) -> bool: if val in self.hash_map: return False self.vec.append(val) s...
code-cp/leetcode
solutions/380/main.py
main.py
py
1,102
python
en
code
0
github-code
6
75093396986
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from pprint import pprint from dotenv import load_dotenv import os EVENT_UPLOADED_MESSAGE = "message_uploaded" load_dotenv() UUID = os.getenv("...
deibid/radio-azar
my_modules/PubNubClient.py
PubNubClient.py
py
2,682
python
en
code
1
github-code
6
15430745288
class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ output = '' for i in digits: output += str(i) output_ = int(output) output_ += 1 return [ int(i) for i in str(output_)]
dipalira/LeetCode
Arrays/66.py
66.py
py
318
python
en
code
0
github-code
6
29778129362
from flask import Flask, render_template, request, url_for import y_u_so_stupid as fle import json app = Flask(__name__) correctAnswer = '' score = 0 highscore = 0 @app.route('/') def play(): global correctAnswer q = json.loads(fle.getRandomQuestion()) question = q['question'] choices...
asav13/PRLA-Verk5
part2/y_u_so_stupid_SERVER.py
y_u_so_stupid_SERVER.py
py
1,208
python
en
code
0
github-code
6
13564278099
class RockPaperScissors: def __init__(self, A, B) -> None: self.your_move = A self.my_move = B def __del__(self): pass def __str__(self): your_move_translated = { 'A' : 'rock', 'B' : 'paper', 'C' : 'scissors' } .get(self.your_move...
nicholaschungQR/Project2
Problem 2/problem2.py
problem2.py
py
852
python
en
code
0
github-code
6
42124061830
import requests import os from django.http import HttpResponse from django.conf import settings class ProductClient: global host def __init__(self): global host print("came inside product constructor") if os.getenv("PRODUCT_HOST") != "": host = os.getenv("PRODUCT_HOST") ...
Robinrrr10/storeorderui
client/productClient.py
productClient.py
py
738
python
en
code
0
github-code
6
7903436646
# 백준 7662번 문제 - 이중 우선순위 큐 import sys import heapq input = sys.stdin.readline test = int(input()) for _ in range(test): max_heap, min_heap = [], [] visit = [0] * 1_000_001 n = int(input()) for i in range(n): cmd = input().split() if cmd[0] == 'I': heapq.heappush(min_heap, ...
wnstjd9701/CodingTest
백준/category/Class3/이중우선순위큐.py
이중우선순위큐.py
py
1,920
python
ko
code
0
github-code
6
5769042811
import hashlib import json import os import pathlib import shutil import subprocess from typing import Mapping, Any, List class RunException(Exception): pass class ExecuteException(Exception): pass class style: reset = 0 bold = 1 dim = 2 italic = 3 underline = 4 blink = 5 rblink =...
Abdullahjavednesar/lpython
compiler_tester/tester.py
tester.py
py
9,744
python
en
code
null
github-code
6
32150278957
def solution(s): answer = [0,0] while s != '1': cnt = s.count('0') tranS = s.replace('0','') s = bin(len(tranS)) s = s[2:] answer[0] += 1 answer[1] += cnt return answer s = "1111111" print(solution(s))
HS980924/Algorithm
src/etc/src/04_19(화)/이진변환.py
이진변환.py
py
292
python
en
code
2
github-code
6
764504946
from sklearn.base import BaseEstimator, ClusterMixin, TransformerMixin from sklearn.cluster import DBSCAN, KMeans, SpectralClustering from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import LabelBinarizer class ClusterTransformer(TransformerMixin, BaseEstimator): """Turns sklearn clus...
x-tabdeveloping/blackbert
blackbert/cluster.py
cluster.py
py
4,673
python
en
code
0
github-code
6
42572073330
import abc import collections from typing import List, Callable, Optional, OrderedDict, Tuple import pandas as pd class PreProcessingBase: def __init__(self, df: pd.DataFrame, actions: Optional[OrderedDict[Callable, Tuple]] = None): self._df = df self._actions = ...
gilcaspi/COVID-19-Vaccinations
data_processing/preprocessing/pre_processing_base.py
pre_processing_base.py
py
791
python
en
code
0
github-code
6
33425710181
import time import math n=int(input()) start = time.time() def prime_testimony(n): if n == 1: return False elif n==2 or n==3 : return True elif n%6 == 1 or n%6 == 5: for i in range(3, math.floor(math.sqrt(n)) + 1, 2): if n%i == 0: return False...
harasees-singh/Ray_Traced_code
prime_testimony.py
prime_testimony.py
py
435
python
en
code
0
github-code
6
27094908089
import pandas as pd import random from tqdm.auto import tqdm tqdm.pandas() import re from tqdm import tqdm import numpy as np import cv2 from albumentations import ( Compose, OneOf, Normalize, Resize, HorizontalFlip, VerticalFlip, Rotate, RandomRotate90, CenterCrop ) from albumentations.pytorch import ToTensorV...
phelchegs/bms-molecular-translation
InChI/InChI_preprocessing.py
InChI_preprocessing.py
py
7,948
python
en
code
1
github-code
6
36040675316
import typing from datetime import datetime, timedelta import arrow from ParadoxTrading.Utils.DataStruct import DataStruct DATETIME_TYPE = typing.Union[str, datetime] class SplitAbstract: def __init__(self): self.cur_bar: DataStruct = None self.cur_bar_begin_time: DATETIME_TYPE = None s...
ppaanngggg/ParadoxTrading
ParadoxTrading/Utils/Split.py
Split.py
py
9,614
python
en
code
51
github-code
6
23857423265
"""Testing an common Anode RGB LED""" from time import sleep from picozero import RGBLED def main(): led = RGBLED(red=2, blue=3, green=4, active_high=False) try: while True: led.color = 255, 0, 0 sleep(1) led.color = 0, 0, 255 sleep(1) finally: ...
ValdezFOmar/micropython-projects
tests/misc/anode_rgb_led.py
anode_rgb_led.py
py
375
python
en
code
1
github-code
6
42363921059
#part-1 # file = open("day2Input.txt", "r") # my_dict = {'X':1, 'Y':2, 'Z':3} # score = 0 # for line in file: # opponent = line[0] # you = line[2] # score += my_dict[you] # if (opponent == 'A' and you == 'X') or (opponent == 'B' and you == 'Y') or (opponent == 'C' and you == 'Z'): # score+=3 # ...
JayAtSeneca/Advent-of-code-2022
day 2/day2.py
day2.py
py
1,605
python
en
code
0
github-code
6
5500500071
import time import base64 from google.cloud import pubsub_v1 from google.oauth2 import service_account project_id = "<gcp_project_id>" topic_name = "<topic_name>" credentials = service_account.Credentials.from_service_account_file("<gcp_Service_account_file_path>") print(credentials) publisher = pubsub_v1.PublisherC...
natsu1628/hackathons
ML/GCP-python-ML2/to_pubsub.py
to_pubsub.py
py
1,772
python
en
code
1
github-code
6
31036024397
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # function to convert linked list to list for addition def toList(self, linked): convt = [] while linked is not None: ...
notkshitijsingh/leetcode-solutions
2. Add Two Numbers.py
2. Add Two Numbers.py
py
1,560
python
en
code
0
github-code
6
28398915179
import datetime import termux from sync.misc.Config import config from sync.misc.Logger import logger class Notification: __instance__ = None def __init__(self): self.sync_all = {} self.watchers = {} self.global_status = "Active" now_date = datetime.datetime.now() se...
dpjl/termux-sync
sync/misc/Notification.py
Notification.py
py
3,522
python
en
code
0
github-code
6
41152326339
from tkinter import * from datetime import datetime, timedelta import tkinter as tk from tkinter import Entry, Label, StringVar, ttk, Checkbutton, Button, messagebox import numpy as np import pandas as pd def generarCodigo(texto): sumar = 0 codigo = texto[:3] if texto[len(texto) // 2] == " ": suma...
Moisesmp75/TkinterForms
Trabajo2/Biblioteca.py
Biblioteca.py
py
23,516
python
es
code
0
github-code
6
4785005840
n = int(input()) l = list(map(int,input().split())) l.sort(reverse=True) oddl = [] evenl = [] for i in l: if i%2 == 0: evenl.append(i) else: oddl.append(i) ans = -1 if 2 <= len(oddl): ans = max(ans,oddl[0]+oddl[1]) if 2 <= len(evenl): ans = max(ans,evenl[0]+evenl[1]) print(ans)
K5h1n0/compe_prog_new
VirtualContest/008/7.py
7.py
py
310
python
en
code
0
github-code
6
22546128961
# import random # import time #* Génération de la liste # TAILLE = int(1e5) # BORNE_SUP = int(1e2) # liste_a_trier = [random.randint(0,BORNE_SUP) for _ in range(TAILLE)] # print(liste_a_trier) def fusion(A,p,q,r): """ Opére la fusion de la liste A[p,q] et A[q,r] """ # on stocke les deux...
PsychoLeo/Club_Informatique
7-Sorting/mergeSort.py
mergeSort.py
py
1,532
python
fr
code
0
github-code
6
24102936874
from helpers import ReadLines from typing import Tuple, List class DayFive(ReadLines): def __init__( self, file_path="/home/jonathan/projects/2020-advent-of-code/five/input.txt" ): super().__init__(file_input=file_path) self.seat_ids = sorted( [DayFive.identify_seat(seat_co...
jonodrew/2020-advent-of-code
five/five.py
five.py
py
1,952
python
en
code
0
github-code
6
24940438785
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import hashlib import sys import struct def getPIN(username): ''' According to code from https://github.com/nowind/sx_pi ''' current_time = time.time() time_divided_by_five = int(current_time) // 5 time_char = [0] * 4 temp = ...
novakoki/shanxun-linux
shanxun.py
shanxun.py
py
2,198
python
en
code
5
github-code
6
73928014588
from collections import Set import random from cardboard import events __all__ = ["UnorderedZone", "OrderedZone", "zone"] # TODO: Clarify / make zone operations atomic ENTER, LEAVE = events.ENTERED_ZONE, events.LEFT_ZONE def _zone(name): """ Create a zone classmethod from the zone name. """ @cl...
Julian/cardboard
cardboard/zone.py
zone.py
py
5,366
python
en
code
7
github-code
6
36341309654
# 세준이는 양수와 +, -, 그리고 괄호를 가지고 식을 만들었다. 그리고 나서 세준이는 괄호를 모두 지웠다. # 그리고 나서 세준이는 괄호를 적절히 쳐서 이 식의 값을 최소로 만들려고 한다. # 괄호를 적절히 쳐서 이 식의 값을 최소로 만드는 프로그램을 작성하시오. import sys formula = sys.stdin.readline().split('-') result = [] for i in formula: cnt = 0 s = i.split('+') for j in s: cnt += int(j) result.appe...
jujinyoung/CodingTest
bakjjun_codingTest/1541.py
1541.py
py
609
python
ko
code
0
github-code
6
24829002801
import pygame pygame.init() pygame.display.set_caption("WannabePong") size = 800, 600 screen = pygame.display.set_mode(size) width, height = size speed = [1, 1] bgc = 255, 255, 255 fontControls = pygame.font.SysFont("monospace", 16) font = pygame.font.SysFont("monospace", 26) fontCount = pygame.font.SysFont("monospa...
vsanjorge/localMultiplayerPong
main.py
main.py
py
3,327
python
en
code
0
github-code
6
5188129194
def quick_sort(a_list): if len(a_list) < 2: return a_list else: pivot = a_list[0] less = quick_sort([i for i in a_list if i < pivot]) greater = quick_sort([i for i in a_list if i > pivot]) return less + [pivot] + greater print(quick_sort([7,6,3,99]))
IshGill/DSA-Guides
Sorting and searching/Quicksort.py
Quicksort.py
py
320
python
en
code
9
github-code
6
70945120828
# 형태소 분석 from konlpy.tag import Okt from docutils.parsers.rst.directives import encoding okt = Okt() #result = okt.pos('고추 등 매운음식을 오랫동안 너무 많이 먹었을 경우 인지능력과 기억력을 저하시킬 위험이 높다는 연구결과가 나왔다.') #result = okt.morphs('고추 등 매운음식을 오랫동안 너무 많이 먹었을 경우 인지능력과 기억력을 저하시킬 위험이 높다는 연구결과가 나왔다.') #result = okt.nouns('고추 등 매운음식을 오랫동안 너...
kangmihee/EX_python
py_morpheme/pack/morp1.py
morp1.py
py
2,358
python
ko
code
0
github-code
6
71567915387
def get_next_pos(row, col, direction): if direction == 'up': return row - 1, col if direction == 'down': return row + 1, col if direction == 'left': return row, col - 1 if direction == 'right': return row, col + 1 def is_inside(row, col, size): return 0 <= row < siz...
lorindi/SoftUni-Software-Engineering
Python-Advanced/4.Multidimensional Lists/07_present_delivery.py
07_present_delivery.py
py
2,416
python
en
code
3
github-code
6
39426129134
''' Strategy to be backtested. ''' import backtrader as bt # Create a Stratey class TestStrategy(bt.Strategy): ''' Base class to be subclassed for user defined strategies. ''' # Moving average parameters params = (('pfast',2),('pslow',184),) def __init__(self): self.dataclose = self.datas[0...
Kyle-sn/PaperStreet
python/backtest/strategy.py
strategy.py
py
2,714
python
en
code
1
github-code
6
70488593467
import csv import functools import json import math import random def cycle_call_parametrized(string_q: int, left_b: int, right_b: int): def cycle_call(func): # print(f'LALA') def wrapper_(*args, **kwargs): # creating a csv-file: generate_csv(string_q, left_b, right_b) ...
LocusLontrime/Python
Dive_into_python/HomeWork9/Decorators.py
Decorators.py
py
1,807
python
en
code
1
github-code
6
19241458582
def FiveCnt(K): cnt = 0 while K: cnt += K//5 K //= 5 return cnt def TwoCnt(K): cnt = 0 while K: cnt += K//2 K //= 2 return cnt N, M = map(int, input().split()) print(min(FiveCnt(N)-FiveCnt(N-M)-FiveCnt(M), TwoCnt(N)-TwoCnt(N-M)-TwoCnt(M)))
sdh98429/dj2_alg_study
백준/Silver/2004. 조합 0의 개수/조합 0의 개수.py
조합 0의 개수.py
py
286
python
en
code
0
github-code
6
6363938887
def calcRedundantBits(m): for i in range(m): if 2**i >= m + i + 1: return i def posRedundantBits(data, r): # Redundancy bits are placed at the positions # which correspond to the power of 2. j = 0 k = 1 m = len(data) res = "" # If position is power of 2 then inse...
SwarupKharul/NetCom
error-detection/hamming.py
hamming.py
py
1,704
python
en
code
0
github-code
6
71634215547
INTRODUCTION = ''' \U0001F6E1 Health Insurance Risk Calculator\U0001F6E1 \U0001F534*************************************************************\U0001F534 Welcome to the Health Insurance Risk Calculator, where we'll give you enough information to get an idea of how much you owe us. We'...
JubinJ0110/HealthInsuranceRiskCalculator
InsuranceCalculatorJJJ.py
InsuranceCalculatorJJJ.py
py
6,808
python
en
code
0
github-code
6
27923745620
from sklearn.model_selection import train_test_split from tensorflow.keras.layers import Dense from keras.utils import np_utils from tensorflow.keras.models import Sequential import matplotlib.pyplot as plt from scipy.io import loadmat import numpy as np def display(i): img = X[i] plt.title('Example'...
ankitlohiya212/basic-ml-problems
Basic ML problems/Mnist.py
Mnist.py
py
2,107
python
en
code
0
github-code
6
14839954104
from PyQt5 import QtCore, QtGui, QtWidgets, uic import sys from AssignmentCategoryDict import AssignmentCategoryDict from Assignment import Assignment import uuid class EditCategories(object): def __init__(self, course, reload_gradesheet): col_headers = ['Category Name', 'Drop Count'] self.ECate...
meeksjt/SuperTeacherGradebook499
src/EditCategories.py
EditCategories.py
py
5,236
python
en
code
1
github-code
6
37612660256
from django.shortcuts import render from .models import * import cv2 import numpy as np from pytesseract import * pytesseract.tesseract_cmd="C:/Program Files/Tesseract-OCR/tesseract.exe" def main(request): return render(request,'main.html') def maintest(request): return render(request,'maintest.html')...
YounngR/Graduation-work
DB/views.py
views.py
py
1,680
python
en
code
0
github-code
6
23262217725
######################################################## ### Programmers: Steffan Davies ### ### Contact: steffanclentdavies@gmail.com ### ### Date: 27/12/2022 ### ######################################################## # This script will demonstrate dic...
SteffanDavies/python-crash-course-exercises
chapter-06/06-10/favorite_numbers_2.py
favorite_numbers_2.py
py
729
python
en
code
0
github-code
6
15047866942
# from __future__ import absolute_import import torch import torch.nn as nn import onnx from typing import List, Dict, Union, Optional, Tuple, Sequence import copy from .util import* from torch.autograd import Variable class onnxTorchModel(nn.Module): def __init__(self,onnx_model: onnx.ModelProto,cfg:dict): ...
diamour/onnxQuanter
onnx_torch_engine/converter.py
converter.py
py
16,899
python
en
code
1
github-code
6
33225197622
# -*- coding: utf-8 -*- """ #+begin_org * *[Summary]* :: A =CmndLib= for providing currents configuration to CS-s. #+end_org """ ####+BEGIN: b:py3:cs:file/dblockControls :classification "cs-u" """ #+begin_org * [[elisp:(org-cycle)][| /Control Parameters Of This File/ |]] :: dblk ctrls classifications=cs-u #+BEGIN_SRC...
bisos-pip/currents
py3/bisos/currents/currentsConfig.py
currentsConfig.py
py
33,875
python
en
code
0
github-code
6
26057428953
import re import requests from bs4 import BeautifulSoup URL = "https://sourcesup.renater.fr/scm/viewvc.php/rec/2019-CONVECS/REC/" page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") for link in soup.find_all('a', href=True): print(link['href']) if 'name' in link: print(link['nam...
philzook58/egglog-rec
scraper.py
scraper.py
py
711
python
en
code
1
github-code
6
40327690661
from pyecharts import options as opts from typing import Any,Optional from pyecharts.charts import Radar import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from easy_pyechart import constants,baseParams,radar_base_config,round_radar_base_config class eRadar(): def...
jayz2017/easy_pyechart.py
easy_pyechart/easy_radar.py
easy_radar.py
py
1,470
python
en
code
1
github-code
6
44407917630
''' Created on 16/ago/2011 @author: Marco ''' from reportlab.pdfgen import canvas from reportlab.lib.units import cm from math import sqrt import ModelsCache import Configuration class PdfStructure(object): ''' classdocs ''' __markerList = [] __modelsCache = ModelsCache.ModelsCache() @...
mziccard/RuneTagDrawer
PdfStructure.py
PdfStructure.py
py
3,883
python
en
code
3
github-code
6
23775563757
import flask import grpc import search_pb2_grpc as pb2_grpc import search_pb2 as pb2 import redis import json from google.protobuf.json_format import MessageToJson from flask import request, jsonify app = flask.Flask(__name__) app.config["DEBUG"] = True class SearchClient(object): """ Client for...
manfruta/Sistemas-Tarea1
cliente_app.py
cliente_app.py
py
1,587
python
en
code
0
github-code
6
71608254269
import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from djtransgan.dataset import batchlize class DataLoaderSampler(): def __init__(self, dataset, batch_size, drop_last=True, shuffle=True): self.count = 0 self.dataset = dataset self.batch_size = ba...
ChenPaulYu/DJtransGAN
djtransgan/dataset/datasampler.py
datasampler.py
py
911
python
en
code
86
github-code
6
35841523790
from .player import Player1 from .enemy import ( Enemy1, Enemy2, Boss1, Boss2 ) from .asteroids import Asteroid1 from .background import ( Backgr_lev1, Backgr_lev1a, Backgr_lev2, Backgr_lev2a, Backgr_lev3, Backgr_lev3a, Backgr_lev4, Backgr_lev4a, Backgr_lev5, Backgr_lev5a ) from .startboard import StartBoard from .expl...
MMiirrkk/Galaxy_Shooter_I
objects/unitfactory.py
unitfactory.py
py
2,700
python
en
code
0
github-code
6
21546390354
import re from collections import Counter, defaultdict from itertools import combinations from typing import Dict, List, Tuple, Set import numpy as np from helper import load_input def create_input(): '''Extract puzzle input and transform''' # creates pattern for extracting replcements pattern = r"(\w+)...
rick-62/advent-of-code
advent_of_code_2015/solutions/day19.py
day19.py
py
2,647
python
en
code
0
github-code
6
32802770666
from elasticsearch import Elasticsearch, helpers import csv import json import time mvar = "clara" matching_query = { "query_string": { "query": mvar } } def main(): #sundesh es = Elasticsearch(host = "localhost", port = 9200) #anagn...
d4g10ur0s/InformationRetrieval_21_22
save_books.py
save_books.py
py
627
python
en
code
0
github-code
6
38649682103
import http import requests import telegram from flask import Blueprint, Response, request from sqlalchemy_utils import create_database, database_exists from config import BUILD_NUMBER, DATABASE_URL, REBASE_URL, VERSION from .bot import dispatcher from .db import db, test_db from .utils import log routes = Blueprin...
andrewscwei/python-telegram-bot-starter-kit
app/routes.py
routes.py
py
1,370
python
en
code
1
github-code
6
39697340199
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d # plots intensity time series for MDRE model def plotIntensity (): # index boundaries for time 3D plot nStart = 0 nEnd = 10000 with open("time_series.txt", "r") as file: lines = file.readlines() time = [] int...
sir-aak/microscopically-derived-rate-equations
plotscripts/mdre_plotscript_intensity_inversion.py
mdre_plotscript_intensity_inversion.py
py
3,810
python
en
code
1
github-code
6
34652323206
# Subgroup enumeration for cyclic, dicyclic, and tricyclic integer groups. # PM Larsen, 2019 # # The theory implemented here is described for two-dimensional groups in: # Representing and counting the subgroups of the group Z_m x Z_n # Mario Hampejs, Nicki Holighaus, László Tóth, and Christoph Wiesmeyr # Jo...
pmla/evgraf
evgraf/subgroup_enumeration.py
subgroup_enumeration.py
py
6,050
python
en
code
13
github-code
6