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
567639815
#!/usr/bin/env python import argparse import sys, os from copy import deepcopy import logging import subprocess import numpy as np import biobox as bb import JabberDock as jd # Current path destination: current_p = str(os.path.dirname(os.path.realpath(__file__))) # A global script to auto run all the commands to go ...
Degiacomi-Lab/JabberDock
auto_scripts/jabberdock.py
jabberdock.py
py
4,841
python
en
code
12
github-code
54
19935031814
A = [0,1] lena = len(A) # dic= {j:A[j] for j in range(lena)} # print(dic) count = 0 temp = 0 for i in range(lena): if A[i] == 0: temp += 1 else: count += temp print('At end of loop {}, the value of temp is {} and value of count is {}.'.format(i, temp, count))
rmdotka92/Codility_training_exercises
5.1_codility_passingcars.py
5.1_codility_passingcars.py
py
289
python
en
code
0
github-code
54
22173133456
import json import requests from flask import jsonify, make_response, abort, Blueprint github_urls = { "user": "https://api.github.com/users/{0}", "user_repos": "https://api.github.com/users/{0}/repos", } bp = Blueprint("api", __name__, url_prefix="/api/v0.1") def github_request(url): try: respo...
prowincial/task-for-allegro
mserver/api.py
api.py
py
1,995
python
en
code
0
github-code
54
3775946257
#!python3 # downloadXkcd.py - Download every xkcd file. from email.mime import image import requests, os, bs4 url = 'https://xkcd.com' os.makedirs('xkcd', exist_ok=True) while not url.endswith('#'): # Donwload the page print('Downloading the page %s...' %url) res = requests.get(url) res.raise_for_stat...
thegoddo/Python
downloadXkcd.py
downloadXkcd.py
py
1,102
python
en
code
0
github-code
54
42108820230
set_a = {1, 2, 3, 4, 5} set_b = {4, 5, 6, 7, 8} set_c = {7, 8, 9, 10, 11} # Використовуючи set_a, set_b, set_c # 1. Отримати загальний set # res = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} res = {*set_a, *set_b, *set_c} # 2. Отримати різницю між set_a і set_b, set_b і set_c res_a_b = set_a.difference(set_b) res_b_c = set_b...
jamaicacat/python_basic_hw6
main.py
main.py
py
3,903
python
uk
code
0
github-code
54
29849330781
# Author : Ashish Nagar def tournament_schedule(players, schedule=None, day=None, i=None, j=None): # Count the number of players number_of_players = j - i + 1 # Create matrix to store the schedule if schedule is None: schedule = [] for _ in range(number_of_players - 1): sch...
algometrix/CSE-551-Foundations-of-Algorithms
tournament_problem.py
tournament_problem.py
py
2,691
python
en
code
2
github-code
54
35208155229
import logging from pathlib import Path import tensorflow as tf import typer from tf_agents.policies import tf_policy from tf_agents.utils import common from magpie.config.config import FioSettings from magpie.environment.controller import logger from magpie.types.distributed_file_system import DFS from magpie.types....
dos-group/magpie
magpie/tuner/eval.py
eval.py
py
4,323
python
en
code
0
github-code
54
2239111663
#!/usr/bin/env python # -*- coding: utf-8 -*- # author:ShidongDu time:2020/4/22 ''' 给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例: 输入: [1,2,3,null,5,null,4] 输出: [1, 3, 4] 解释: 1 <--- / \ 2 3 <--- \ \ 5 4 <--- 通过次数37,189提交次数58,398 ''' # Definition for a binary tree node...
weiyuyan/LeetCode
每日一题/April/199. 二叉树的右视图.py
199. 二叉树的右视图.py
py
1,632
python
en
code
2
github-code
54
39140413371
import numpy as np from numpy import linalg as LA import matplotlib.pyplot as plt import networkx as nx from networkx.generators.classic import empty_graph, path_graph, complete_graph from networkx.generators.random_graphs import barabasi_albert_graph, erdos_renyi_graph def initial_W(shape, low_bound, up_bo...
jingddong-zhang/Neural-Stochastic-Control
Neural Stochastic Control/Echo/generate_matrix_A.py
generate_matrix_A.py
py
1,669
python
en
code
1
github-code
54
72070278880
from __future__ import absolute_import, print_function, division import logging import numpy as np import pade.model import scipy.stats from collections import OrderedDict, namedtuple from itertools import combinations from pade.stat import ( OneSampleDifferenceTStat, FStat, MeansRatio, residuals, bootstrap) fro...
itmat/pade
pade/analysis.py
analysis.py
py
10,927
python
en
code
2
github-code
54
33809637609
import random import time seed = 1 random.seed(seed) # # random range # 随机 (0, 1) 不闭合区间 random.random() # 随机 [a, b) random.uniform(1.0, 2.0) # 随机整数[a, b]闭合区间 random.randint(0, 10) # 随机整数[a, b)左闭右开:不常用 random.randrange(0, 10, 2) # # sequence # 随机打乱 random.shuffle([1, 2, 3]) # 随机选 1 个 random.choice([1, 2, 3]) ...
amomorning/algorithm-py
random/basic.py
basic.py
py
545
python
zh
code
0
github-code
54
33335242664
""" CONSTANTS These predefined constants will be used to name context IDs and modifier IDs. (The IDs themselves are strings). In principle, although there are names coming from outside of the context, every context specific entity should have a defined constant. """ ########################## context CON...
peterwaksman/Narwhal
mouthContext/mouthCONSTS.py
mouthCONSTS.py
py
2,367
python
en
code
12
github-code
54
34758642650
import requests import re from bs4 import BeautifulSoup import mysql.connector from sklearn import tree from sklearn import preprocessing import pandas # TODO salam dr tamami todo ha tozihate lameze dade shode ast def ml(): print('این گزینه تا اطلاع ثانوی غیر فعال میباشد گزینه دیگری را انتخاب کنید') ...
saharfk/car-scrapping
carCompleted.py
carCompleted.py
py
9,552
python
en
code
2
github-code
54
2587741113
import numpy as np import pandas as pd from matplotlib import pyplot as plt def PrintImage(self,image): a = image.reshape(28,28) fig=plt.gcf() fig.set_size_inches(2,2) plt.imshow(a) plt.show() def ReadTrainingData(): with open('train-images-idx3-ubyte' , 'rb') as i: i.read(16) ...
el2k6xjp6/Machine-learning
Homework2/NaiveBayes/others.py
others.py
py
829
python
en
code
1
github-code
54
20823522674
""" BCDS1 message ------------- """ import cerberus from lxml import etree from .utils import min_digits, max_digits, strbool from .message import Message SCHEDULE_QUERY_TRUE = 0 SCHEDULE_QUERY_FALSE = 1 SCHEDULE_QUERY_DELETE = 3 class Patient(Message): class Meta: schema = { # Sex ...
odonto/odonto
fp17/bcds1.py
bcds1.py
py
21,060
python
en
code
11
github-code
54
22049261518
import PyPDF2 import os import traceback import time ''' 针对扫描版pdf添加目录 需要有目录文件,使用\t制表符组织目录 目录和扫描版页码有偏差手动设置起始页码 ''' def setsub(indexs, level): #递归方式遍历目录 生成目录树 sub = [] for i, index in enumerate(indexs): clevel = len(index.split('\t')) if clevel == level + 1: value,...
whxb69/pdf_tools
pdftag.py
pdftag.py
py
3,338
python
en
code
1
github-code
54
44877656059
import pandas as pd import numpy as np dfmay = pd.read_excel("file/May_Report.xlsx") dfjune = pd.read_excel("file/June_Report.xlsx") print(dfmay) # shows that dfmay != dfjune print(dfmay == dfjune) comparevalues = dfmay.values == dfjune.values print(comparevalues) rows,cols = np.where(comparevalues==False) # shows t...
Desewah/python_duplicates
compare/compare.py
compare.py
py
611
python
en
code
0
github-code
54
19484900792
#!/usr/bin/env python from waflib import Logs def build(ctx): if ctx.env.IMM: ctx.recurse('hill-climbing') ctx.recurse('imm') else: Logs.warn("No script will be generated for Ripples")
mminutoli/preempt-experimental-setup
experiments/wscript
wscript
219
python
en
code
0
github-code
54
1389988890
from __future__ import print_function, division import options import numpy as np import dynet as dy import data import evaluation import helpers import utils import sys import os def load_user_filepairs(file_list): src_files, trg_files = [], [] with open(file_list, 'r') as f: for l in f: ...
neulab/extreme-adaptation-for-personalized-translation
new_users.py
new_users.py
py
7,189
python
en
code
42
github-code
54
30129281829
import re data = "jr4jf34jfh4n2fh23j3l43kffjjk34fj32d23dmnasdf" # 문자열에서 숫자 제거 정규식 newdata = re.sub(r'[0-9]+',"", data) # newdata = re.sub(r'[^0-9]+',"", data) #문자제거 정규식 print(newdata) data2 = "g@g%^23dfsgf@sdf235g$#fg54%@gf#^g%345^&^%*d*()h(+_54)*g++f&%$#h" newdata2 = re.sub("[!@#$%^&*()_+-=]","", data2) # 특수문자 제거...
rodrng/control.py
정규식.py
정규식.py
py
550
python
ko
code
0
github-code
54
7933564594
import matplotlib.pyplot as plt import seaborn as sns import pandas as pd plt.figure(figsize=(12,12)) df = pd.read_csv("pima-indians-diabetes.csv", names=['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']) # take a sip of the file print("===only take 5 first rows from input csv file...
buildkdom/statistics-201807
ml/20180724tensorflow/02_Pima_Indian-visualize-by-seaborn.py
02_Pima_Indian-visualize-by-seaborn.py
py
489
python
en
code
0
github-code
54
18680025891
from ulogging import getLogger logger = getLogger(__name__) from config import location import web @web.action_handler(__name__) def www(page, args): gps = [ float(ll[:-1] if ll[-1] in ("N", "E") else ll) for ll in args["gps"].split(",") ] locations = location["locations"] locations.append({...
ondiiik/meteoink
simulator/web/page/locmake.py
locmake.py
py
415
python
en
code
13
github-code
54
21419788137
from nlp import nlp from preprocessing.preprocessors.preprocessors import get_advcl_sentence, get_conj_sentence, get_main_sentence, \ get_sub_sentence_loc, get_sub_sentence_standard class Preprocessor: methods = [ get_advcl_sentence, get_conj_sentence, get_sub_sentence_standard, ...
Hosstell/chat-helper
preprocessing/preprocessing.py
preprocessing.py
py
686
python
en
code
0
github-code
54
28023350841
# Hard Encode for the Prediction import pandas as pd import numpy as np import tensorflow as tf import time from tensorflow.keras import layers import mediapipe as mp import os import csv import cv2 as cv import matplotlib.pyplot as plt import matplotlib.image as mpimg from tensorflow.keras.utils import to_...
jasonxu1888/ASL-Aspire
model_communication.py
model_communication.py
py
5,008
python
en
code
1
github-code
54
19488602101
import enum import os import glob import subprocess from dateutil.parser import parse as dateparse from dotenv import load_dotenv import pandas as pd import geopandas as gpd from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # from postgis_models import Frame, Oil, Ship from postgis_models im...
suhendra0812/barata_db
ingest.py
ingest.py
py
6,156
python
en
code
0
github-code
54
42280878076
import os import subprocess import random import tkinter as tk from tkinter import messagebox from datetime import datetime from functools import partial from read_write import read_settings_file, write_settings_file, read_saved_plan, write_saved_plan from my_tkinter_settings import configure_window class App: "...
ribeirompl/144_blocks
144_blocks.py
144_blocks.py
py
15,140
python
en
code
4
github-code
54
73013442082
from turtle import Turtle, Screen import random screen = Screen() screen.addshape("C:/Users/WINDOWS 10/JetBrains/PycharmProjects/SnakeGame/Burger.gif") class Food(Turtle): def __init__(self): super().__init__() self.shape("C:/Users/WINDOWS 10/JetBrains/PycharmProjects/SnakeGame/Burger.gif") ...
GeeK1224/snake-game
food.py
food.py
py
607
python
en
code
0
github-code
54
25913876919
from flask import Flask, render_template, request from flask_bootstrap import Bootstrap import data_scraper as ds app = Flask(__name__) Bootstrap(app) @app.route('/') def index(): return render_template('index.html') @app.route('/basic_comparison', methods=['POST']) def height(): user_position = request.f...
dennisdeng2002/nba-comparison
nba_comparisons.py
nba_comparisons.py
py
570
python
en
code
0
github-code
54
17243641147
import sys import torch import torch.optim as optim import numpy as np import dataset as ds from save_load_model import * from mirnet3 import Mirnet, CrossEntropyLossWithGaussianSmoothedLabels2 from evaluation_functions import * USE_F_LAYER=False if(len(sys.argv) < 2): arg = "noname" else: arg = sys.argv[1] p...
GarettFogel/cse6521-final-project
train.py
train.py
py
5,497
python
en
code
0
github-code
54
21641815357
import re import subprocess from datetime import datetime, timedelta from hashlib import sha256 PUBKEY_CACHE: dict[str, str] = {} HANDSHAKE_CACHE = {"last_update": datetime.now() - timedelta(hours=1), "data": b""} ENDPOINT_CACHE = {"last_update": datetime.now() - timedelta(hours=1), "data": b""} def gen_key() -> st...
dunkelstern/wireguard-web
wireguard/utils.py
utils.py
py
2,954
python
en
code
2
github-code
54
70151704483
def fin(wich,cnt): global maximum global arr if wich == N-1: if maximum < cnt: maximum = cnt else: for i in range(wich+1, N): if arr[wich] < arr[i]: fin(i,cnt+1) N = eval(input()) arr = list(map(int,input().split())) def dynamic(): maximum = 1 g...
freshbell/Coding-Practice
Algorithm/DP/dp유형/최대 증가 부분 수열.py
최대 증가 부분 수열.py
py
589
python
en
code
0
github-code
54
11558296488
import gc from copy import deepcopy from Parser import parse_state_file from Intersection import * from Trafficlight import TrafficLight from Animation import Animation from time import sleep import random ''' How to use Simulation: parameter city_plan_data - object with data about the city plan to simulate, obtained ...
Viperxyzzz/FEUP-IA-Proj1
src/Simulation.py
Simulation.py
py
7,776
python
en
code
0
github-code
54
25947838297
from numpy import * def sigmoid(x): return 1 / (1 + exp(-x)) def logistic_classify(test_mat, weight_arr): m = test_mat.shape[0] test_mat = append(test_mat, ones((m, 1)), axis=1) predic = sigmoid(dot(test_mat, weight_arr.T)) predicted_vals = ones((m, 1)) predicted_vals[predic < 0.5] = -1 ...
Zhu0914/hust_machine_learning
logistic.py
logistic.py
py
2,409
python
en
code
1
github-code
54
33295005644
from fibula.actions.base import BaseAction class Images(BaseAction): """A collection of actions for manipulating Digital Ocean images.""" log_prefix = 'images' def list(self): """List all available images.""" images = sorted( self.do.manager.get_distro_images(), k...
justinlocsei/fibula
infrastructure/fibula/actions/images.py
images.py
py
535
python
en
code
0
github-code
54
28395808115
from django.urls import path, include from django.views.generic import TemplateView from messaging.views import UserApiView, UserDetail, MessageApiView, MessageDetail, SearchUser, AdminApiView, \ AdminDetail, LikeApiView, LikeDetail, SeenApiView, ArchiveApiView, ChannelApiView, ChannelDetail, GroupDetail, \ Gro...
sorooshmorshedi/messaging-backend
messaging/urls.py
urls.py
py
4,524
python
en
code
0
github-code
54
27073207872
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 7 10:43:51 2021 @author: caselll1 """ # inhibitor molar mass in g/mol bosutinib = 530.45 erlotinib = 429.90 gefitinib = 446.9 axitinib = 386.469 bosutinib_isomer = 530.46 neratinib = 557 ponatinib = 532.56 vandetanib = 475.354 drugs = ["bosutini...
lizacasella/calculation_scripts
ligand_concentration_calculation.py
ligand_concentration_calculation.py
py
1,235
python
en
code
0
github-code
54
33232221048
def parseIndent(f): """ parse indented file into tree skip empty lines or starting with ' (comments) """ tops=[]#('',nonwhtite,children)#lines without indentation pfxs=[]#(white,nonwhite,children) for line in f: nonwhite=line.lstrip() white=line[:len(line)-len(nonwhite)] nonwhite=nonwhite.strip() if no...
joru/fetpl
fetpl/parse.py
parse.py
py
847
python
en
code
0
github-code
54
71690652320
from .fetch import Fetch as ft_ class Forex(ft_): def __init__(self, *args, **kwargs): super(Forex, self).__init__(*args, **kwargs) self._append_type = False @ft_._output_format @ft_._call_api_on_func def get_currency_exchange_rate(self, from_currency, to_currency): _function...
kaiorferraz/trade_api
forex.py
forex.py
py
1,405
python
en
code
0
github-code
54
24349480648
import sys import pandas as pd import re import src.db.database as db import numpy as np projects = db.selectallfrom("project") currentProject = projects[projects['currentProject'] == 1]['projectid'].iloc[0] currentMethod = projects[projects['currentProject'] == 1]['fk_methodid'].iloc[0] def interpret(formula,df):...
sergioespana/openAggre
src/functions/indparse.py
indparse.py
py
5,170
python
en
code
0
github-code
54
26256617954
from pydm.widgets.base import ( PyDMPrimitiveWidget, PyDMWidget, PyDMWritableWidget) def pydmwidget_factory(widgetclass, pydm_class='read'): if pydm_class.lower().startswith('primi'): pydmclass = PyDMPrimitiveWidget elif pydm_class.lower().startswith('read'): pydmclass = PyDMWidget els...
lnls-sirius/hla
pyqt-apps/siriushla/widgets/widget_factory.py
widget_factory.py
py
868
python
en
code
3
github-code
54
73442562082
import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import sys import seaborn as sns import flask as fl from flask import Flask, render_template, url_for, request from jinja2 import Template import json # create a flask app app = fl.Flask(__name__) # Read the CSV file into a pandas DataFra...
xxGHS/assessment-1---data-science-callum-noah-finlay
main.py
main.py
py
3,989
python
en
code
0
github-code
54
37625098583
class Solution(object): def findNumberOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 length_list = [1] * len(nums) count_list = [1] * len(nums) for i in range(len(nums)): smaller = [(len...
qianlongzju/Leet_Code
Algorithms/py/673.NumberOfLongestIncreasingSubsequence.py
673.NumberOfLongestIncreasingSubsequence.py
py
762
python
en
code
0
github-code
54
8359577140
from flask import Flask, jsonify, request import json from routes.chipotle import blueprint as chipotle_bp from routes.papajohns import blueprint as papajohns_bp app = Flask(__name__) app.register_blueprint(chipotle_bp.bp) app.register_blueprint(papajohns_bp.bp) app.config['JSON_SORT_KEYS'] = False @app.route('/',...
agSant01/random-meal-generator-python
app.py
app.py
py
811
python
en
code
0
github-code
54
30984718041
# pylint: skip-file from io import open from setuptools import find_packages, setup with open("noiseblend_api/__init__.py", "r") as f: for line in f: if line.startswith("__version__"): version = line.strip().split("=")[1].strip(" '\"") break else: version = "0.0.1" wit...
Noiseblend/api
setup.py
setup.py
py
1,745
python
en
code
1
github-code
54
11360974356
'''GUI''' import tkinter as tk class App(tk.Frame): ''' Die Hauptklasse ''' def __init__(self, renamer): self.renamer = renamer self.root = tk.Tk() super().__init__(self.root) self.create_widgets() self.refresh_list_unsorted() def create_widgets(self): '...
eurethorstheit/Fileprefixer
app.py
app.py
py
1,594
python
en
code
0
github-code
54
6881484009
# !/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Author : Kesheng Zhang @B站:萧然哔哩哔 @Email : zks0053@163.com @Time : 2022/3/13 19:23 @File : time_series_segmentation.py @Software: PyCharm """ import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error from sklearn....
KeshengZhang/time_series_segmentation_python
time_series_segmentation.py
time_series_segmentation.py
py
4,610
python
en
code
8
github-code
54
20034997595
# -*- coding: utf-8 -*- # # libs/uix/flashcardEditorView.py # # view for editing/adding flashcards(including two popups view for picking flashcards # and flashcard editor) from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.uix.screenmanager import Screen from kivy.uix.label import Label f...
Bronn1/The-Vocab
libs/uix/flashcardEditorView.py
flashcardEditorView.py
py
10,544
python
en
code
1
github-code
54
71821360161
import sys from itertools import permutations input = sys.stdin.readline n = int(input()) arr = [i+1 for i in range(n)] l2 = list(permutations(arr,n)) for i in range(len(l2)): print(*l2[i],sep=' ') import sys input = sys.stdin.readline n = int(input()) arr = [i+1 for i in range(n)] visited= [0] * (n+1) def chk(idx...
maantano/Coding-Test
파이썬/2023.11.07 모든 순열(10974)_브루트포스.py
2023.11.07 모든 순열(10974)_브루트포스.py
py
482
python
en
code
0
github-code
54
31543756399
from CustomTransformer.model import TransformerModel import tensorflow as tf from pickle import load from keras.preprocessing.sequence import pad_sequences from data.CustomDataset import CustomDataset import numpy as np import argparse import json from CustomTransformer.params import Params from midi_neural_preprocesso...
Arnavkar/MusicTransformer
PyModel/CustomTransformer/inference.py
inference.py
py
4,485
python
en
code
0
github-code
54
40830836140
from torch.utils.data import Dataset, DataLoader import torch import numpy as np import os import math import networkx as nx from utils.hgnn_utils import one_hot_vec from utils.data_utils import process from utils.hyperbolicity import hyperbolicity_sample from hyperbolic_learning_master.utils.embed import train_embedd...
ColeSBaker/hyperBrain
dataset/GraphDataset.py
GraphDataset.py
py
26,479
python
en
code
0
github-code
54
68405408
# -*- coding: UTF-8 -*- import os from threading import Thread from PIL import Image from functools import reduce import math import time class MosaicPuzzle(object): ''' 马赛克拼图 ''' def __init__(self, source_path, output_path, aim_image_path, sub_image_width = 50, sub_image_height = 50, width_pixel_num ...
ShowLo/MosaicPuzzle
MosaicPuzzle.py
MosaicPuzzle.py
py
10,777
python
en
code
0
github-code
54
22865590571
import sys from collections import Counter from typing import List system_outputs = sys.argv[1:] def collector(filename: str, column_id: int = 2) -> List[str]: lines = [] with open(filename, "rt") as f_p: for line in f_p: line = line.strip() if not line or li...
dbmdz/clef-hipe
experiments/clef-hipe-2022/flair-ensembler.py
flair-ensembler.py
py
1,236
python
en
code
16
github-code
54
37777732000
import numpy as np import bpy from bpy.props import FloatProperty, EnumProperty, BoolProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level from sverchok.utils.curve.core import SvCurve from sverchok.utils.curve.primitives im...
nortikin/sverchok
nodes/surface/coons_patch.py
coons_patch.py
py
6,134
python
en
code
2,098
github-code
54
5622795410
# -*- coding: utf-8 -*- """ Created on Mon Dec 17 18:27:55 2018 @author: Leonardo """ # -------------------------------------------------------- # IMPORTS: from plotly.offline import plot import plotly.graph_objs as go import numpy as np # -------------------------------------------------------- # ------...
Leonardo767/plotlyExamples
multTable.py
multTable.py
py
2,205
python
en
code
0
github-code
54
13887589011
from collections import Counter def findShortestSubArray(nums): ans = len(nums) n = Counter(nums) maximum = max(n.values()) ch = {k: v for k, v in n.items() if v >= maximum} for i in range(len(nums)): if nums[i] in ch: ch[nums[i]] -= 1 if ch[nums[i]] == 0: ...
Kasiet2001/leetcode
degree_of_an_array.py
degree_of_an_array.py
py
428
python
en
code
0
github-code
54
18537759731
# 2.Есть список с четными и нечетными элементами. Посчитать количество четных и нечетных элементов. list_nums = [2, 3, 6, 9, 12, 14, 15, 21, 33, 56, 72, 75, 91] chet = 0 nechet = 0 for num in list_nums: if num % 2 == 0: chet += 1 else: nechet +=1 print(f'Четные: {chet} ') print(f'Нечетные: {nec...
AndreyBRST/Andrey_Martysevich_HomeWork
HomeWork 4/task_2.py
task_2.py
py
423
python
ru
code
0
github-code
54
31936795052
import numpy as np # 채널 별 mean 계산 def get_mean(dataset): meanRGB = [np.mean(image.numpy(), axis=(1,2)) for image,_ in dataset] meanR = np.mean([m[0] for m in meanRGB]) meanG = np.mean([m[1] for m in meanRGB]) meanB = np.mean([m[2] for m in meanRGB]) return [meanR, meanG, meanB] # 채널 별 str 계산 def get_std(dat...
donghquinn/cnn_stl10_padding_test
preprocess.py
preprocess.py
py
568
python
en
code
0
github-code
54
36569548022
import re # Define the regex query to match the hex values regex_query = r'0x07[0-9a-fA-F]{6}' # Define a function to process each match def process_match(match): offset = int(match.group(0)[4:], 16) return f"d_course_big_donut_packed_dl_{hex(offset)[2:].upper()}" # Open the input file with open("courses/big...
n64decomp/mk64
addr_to_sym.py
addr_to_sym.py
py
627
python
en
code
436
github-code
54
10975763668
T = int(input()) for i in range(T): quiz = list(map(str, input())) score = 0 sum = 0 for j in range(len(quiz)): if quiz[j] == 'X': score = 0 else: score += 1 sum += score print(sum)
kimsh8337/daliy-coding
baekjoon/단계별 문제/일차원배열/8958_OX퀴즈.py
8958_OX퀴즈.py
py
253
python
en
code
0
github-code
54
32488904037
import utils import EdgeFunctions as ef import collections def findIOEdges(): # Load samples and settings samples, settings = utils.loadSettings() # Check samples iteratively for s in samples: # Load merge result G_primitive, S_bounds, primitive_only, ConstraintType, constraint, loo...
zyrrron/Oriole_old
algorithm/separateIOEdges.py
separateIOEdges.py
py
1,210
python
en
code
0
github-code
54
71856332642
marks = [] num_students = int(input("Enter the number of students: ")) num_subjects = 5 for i in range(num_students): print(f"Enter marks for student {i + 1}:") student_marks = [] for j in range(num_subjects): mark = int(input(f"Subject {j + 1}: ")) student_marks.append(mark) ...
RHarish1/DataStructures
Expt 01 2D Matrix.py
Expt 01 2D Matrix.py
py
675
python
en
code
0
github-code
54
15708307505
#!/usr/bin/env python # coding: utf-8 # ### Titanic: Machine Learning from Disaster # - This Titanic dataset is a classic Machine Learning tutorial. # - I will perform data cleaning, EDA, feature engineering and use classifcation models to predict survivors on the Titanic. # - Analysis of this dataset was done during ...
nischalshrestha/automatic_wat_discovery
Notebooks/py/wutrng/a-newbie-data-scientist-take-on-titanic-rfc/a-newbie-data-scientist-take-on-titanic-rfc.py
a-newbie-data-scientist-take-on-titanic-rfc.py
py
23,512
python
en
code
2
github-code
54
18612670847
''' using discord.py version 1.0.0a ''' import discord import asyncio import re BOT_OWNER_ROLE = 'Bot Runner' # change to what you need #BOT_OWNER_ROLE_ID = "577462888793374738" lock = asyncio.Lock() answer_scores = { "1": 0, "2": 0, "3": 0, } answer_scores_last = { "1": 0, "2": 0, "3": 0, } ...
riteshmgr557/rock
main.py
main.py
py
7,900
python
en
code
0
github-code
54
22207463106
import os ORIG_INPUT_DATASET = "GlyphsDataset" BASE_PATH = "dataset" TRAIN = "training" TEST = "evaluation" VAL = "validation" BATCH_SIZE = 32 LE_PATH = os.path.sep.join(["output", "le.cpickle"]) BASE_CSV_PATH = "output"
alexandergg/Global-AI-Bootcamp-Glyphs-Classifier-on-EdgeTPU
Demo/glyphreader/settings/config.py
config.py
py
225
python
en
code
0
github-code
54
24843100966
#!/usr/bin env python import scapy.all as scapy def scan(ip): arp_req = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_req_brod = broadcast/arp_req #print(arp_req_brod.summary()) answered_list = scapy.srp(arp_req_brod, timeout=3, verbose=False)[0] client_list = [] ...
anilkandula06/Net_Scanner
Net_Scanner.py
Net_Scanner.py
py
971
python
en
code
0
github-code
54
13632474919
"""create cities table Revision ID: 9bfb5a6b6ae0 Revises: 844eb0010668 Create Date: 2021-02-06 18:14:53.082236 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9bfb5a6b6ae0' down_revision = '844eb0010668' branch_labels = None depends_on = None def upgrade(): ...
ChadCalcote/TasteWaste
migrations/versions/20210206_181453_create_cities_table.py
20210206_181453_create_cities_table.py
py
1,065
python
en
code
13
github-code
54
13429358338
from utils import load_model, move_to from problems.tsp.problem_tsp import nearest_neighbor_graph import logging import os import torch import requests import json import tqdm logger = logging.getLogger(__name__) def model_fn(model_dir): logger.info("In model_fn. Model directory is -") logger.info(model_dir...
aws-samples/amazon-sagemaker-tsp-deep-rl
src/inference.py
inference.py
py
2,494
python
en
code
14
github-code
54
18539895653
''' *4.5 (Find future dates) Write a program that prompts the user to enter an integer for today’s day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week. ''' # get user input todays_day ...
musawakiliML/Python-Exercises
Introduction to Programming using Python/Chapter 4/Ex4.5.py
Ex4.5.py
py
1,199
python
en
code
0
github-code
54
38511666087
# Exercício 4: Filtro de Elementos # Escreva um programa que crie uma nova lista contendo # apenas os elementos pares de uma lista de números # inteiros. lista = input("Digite numeros inteiros separados por espaço: ").split(" ") pares = [] for i in range(len(lista)): if int(lista[i])%2 == 0: pares.append(li...
Tjaos/atividade-estrutura-de-dados
q4.py
q4.py
py
349
python
pt
code
0
github-code
54
14971807088
#!/usr/bin/env python3 import re import os import sys import json import argparse import requests from json.decoder import JSONDecodeError """client.py: Client for interacting with the Halite II servers.""" __author__ = "Two Sigma" __copyright__ = "Copyright 2017, Two Sigma" __credits__ = ["David M. Li", "Jaques Cla...
xinnosuke/Halite-II-pre-launch
tools/hlt_client/hlt_client/client.py
client.py
py
7,191
python
en
code
0
github-code
54
2722566597
import torch import torch.nn as nn import torch.nn.functional as F from stable_diffusion.model.autoencoder import Autoencoder from utils import * class Polyffusion_Autoencoder(nn.Module): def __init__(self, autoencoder: Autoencoder): super(Polyffusion_Autoencoder, self).__init__() self.device = "...
aik2mlj/polyffusion
polyffusion/models/model_autoencoder.py
model_autoencoder.py
py
1,062
python
en
code
34
github-code
54
21663932470
#!/usr/bin/env python3 """Wrapper script for clazy.""" import sys from typing import List from .utils import StaticAnalyzerCmd class ClazyCmd(StaticAnalyzerCmd): """Class for the clazy command.""" command = "clazy" lookbehind = "clazy version " def __init__(self, args: List[str]): super()._...
dominikzaeuner/pre-commit-hooks
hooks/clazy.py
clazy.py
py
894
python
en
code
0
github-code
54
25717741078
import cv2 import matplotlib.pyplot as plt import numpy as np import pickle import os.path import glob import math as m def read_points(obj_file='obj_points.p', img_file='img_points.p', show=False, rewrite=False): if os.path.isfile(obj_file): obj_points = pickle.load(open(obj_file, 'rb')) if os.path...
Daard/CarND-P4-Advanced-Lane-Lines
methods.py
methods.py
py
13,623
python
en
code
0
github-code
54
22142733771
import sys import pdb import collections def findDiag(mat: list[list[int]]) -> list[int]: diag = collections.defaultdict(list) M = len(mat) N = len(mat[0]) for c in range(M): for r in range(N): diag[c+r].append(mat[c][r]) res = [] a=-1 for k,v in diag.items(): ...
ranajikrishna/private
codes_algo/code_python/leetcode/diagonal_traversal.py
diagonal_traversal.py
py
1,091
python
en
code
0
github-code
54
19686188042
"""题目:我们做了一个活动,根据用户的积分来抽奖,用户的积分都保存在一个数组里面 arr = [20, 34, 160, 2…],数组下标就是用户的 ID,则这里: ID 为 0 的用户的积分是 arr[0] 等于 20 分。 ID 为 1 的用户的积分是 arr[1] 等于 34 分。 请你设计一个抽奖算法,随机抽出一位中奖用户,要求积分越高中奖概率越高。 返回值是中奖用户的 ID PS: 1<= arr.length <= 50000 且 1<= arr[i] <= 50000 代码写出算法, 并分析其时间复杂度, 为其编写尽量多 unit test。 FAQ: 我可以上网吗?-- 可以,make you...
GerogeP/python
test/scored_random.py
scored_random.py
py
3,035
python
zh
code
0
github-code
54
42425868952
import cv2 as cv from cv2 import aruco import numpy as np # declare the variable MARKER_SIZE = 0.1 #pixel dist_coef = np.zeros((4,1)) calib_data_path="./calib_data/MultiMatrix.npz" calib_data=np.load(calib_data_path) cam_mat=calib_data["camMatrix"] r_vectors=calib_data["rVector"] t_vectors=calib_data["tVec...
ngoquangtu/aruco
GAMEARUCO.py
GAMEARUCO.py
py
2,809
python
en
code
0
github-code
54
28182063397
from sys import stdin from collections import deque input = stdin.readline n = int(input()) board = list(map(int, input().split())) def solv(): q = deque([(0,0)]) visited = [False]*n visited[0] = True while q: now,cnt = q.pop() if now == n-1: print(cnt) return...
alsgh9948/Problem-Solving
baekjoon/11060.py
11060.py
py
561
python
en
code
0
github-code
54
70863255843
#Day 2: #Python program to find Fibonacci series up to n #Step 1. Start #Step 2. Take a user input and store into int type num variable. #Step 3. Initialize n1, n2 variable to 0, 1. #Step 4. Run a for loop starts from 2 to num value. #Step 5. Inside for loop, using arithmetic addition method, and calculate the n3, whe...
githubmansi50/PrepCodes
day2_fibonacci.py
day2_fibonacci.py
py
620
python
en
code
0
github-code
54
37618688310
import pylab import numpy as np class DynamicPlot(object): def __init__(self, groups=1, items=1, opacity=1, hatch=False): self.groups = groups self.items = items self.hatch = hatch self.opacity = opacity self.font_size = 22 self.legend_font = 13 self...
ravi-0841/DynamicBarPlot
dynamic_plot.py
dynamic_plot.py
py
4,177
python
en
code
0
github-code
54
16782602043
n = int(input()) lst = list(map(int, input().split())) ans1 = [0 for _ in range(n)] ans2 = [0 for _ in range(n)] lst.sort() d = lst[:] idx, step = n//2, 0 while lst: ans1[idx + step] = lst.pop() if lst: ans1[idx - 1 - step] = lst.pop(0) if step < 0: step = - 1 - step + 1 else: st...
yyytae0/algorithm-training
baekjoon/10819.py
10819.py
py
681
python
en
code
0
github-code
54
23423345863
import tkinter as tk from tkinter import RIGHT, ttk from tkinter.messagebox import * from tkinter.filedialog import * class View(tk.Tk): _title = " - Notepad" _default_width = 1150 _default_height = 600 day_mode = "🌙" _zoom = 1.6 default_size = 9 n_font = default_size font_l...
eduardotrj/notepad-py
Main/view.py
view.py
py
9,972
python
en
code
0
github-code
54
3102117525
import pygame as pg import requests import os import math from Button import Button from camera import * from functions import can_move, load_level, load_image, near_store from player import Player from cell import Cell from store import store WIDTH = 500 HEIGHT = 500 WHITE = (255, 255, 255) lst = load_level('t...
SkullCandby/SIMULATOR
main.py
main.py
py
4,156
python
en
code
0
github-code
54
36216329500
from jaxgeometry.setup import * #%% Code def MobiusAddition(x:Array, y:Array, K:float=1. )->Array: xy_dot = jnp.dot(x,y) normx2 = jnp.dot(x,x) normy2 = jnp.dot(y,y) term1 = (1-K*(2*xy_dot-normy2))*x term2 = (1+K*normx2)*y term3...
FrederikMR/score_diffusion_mean
jaxgeometry/operators/Gyration.py
Gyration.py
py
962
python
en
code
0
github-code
54
2768057192
''' 处理定时操作和消息推送的函数集合 包括定时更新数据库,定时推送消息 ''' from django.http import HttpResponse from django.http import JsonResponse from django.http import FileResponse from django.core.files.storage import default_storage from django.core.files.base import ContentFile #import numpy as np #from io import BytesIO import requests impor...
SerCharles/THUAlumniWXMPBackend
backend/Alumni/DatabaseManager/TimeManager.py
TimeManager.py
py
13,188
python
en
code
8
github-code
54
42594513117
import gi from events import Events from fapolicy_analyzer.ui.strings import ( FILE_LIST_RULE_ID_HEADER, FILE_LIST_PERM_HEADER, ACCESS_ALLOWED_TOOLTIP, ACCESS_DENIED_TOOLTIP, ) from fapolicy_analyzer.ui.configs import Colors from fapolicy_analyzer.ui.subject_list import SubjectList gi.require_version(...
ctc-oss/fapolicy-analyzer
fapolicy_analyzer/ui/object_list.py
object_list.py
py
3,594
python
en
code
8
github-code
54
24031517145
def solve(a,d): n = len(a) i = n-1 while i>=0 and a[i]==d: i-=1 d+=1 if i>0: num = d c = a[0:i+1] gind = c.index(num) flag=True for j in range(gind+1,len(c)): if c[j]!=c[j-1]+1: flag = False break ...
ethicalrushi/cp
cf/1341/c.py
c.py
py
670
python
en
code
1
github-code
54
71888057442
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button from keras.preprocessing.image import ImageDataGenerator import os MAIN_PATH = 'Final_dataset_small' val_datagen = ImageDataGenerator(rescale=1./255) val_generator = val_datagen.flow_from_directory( os.path.join(MAIN_PATH, '...
juanmacaaz/ecomate
Pruebas - Otros/show_distribution.py
show_distribution.py
py
1,735
python
en
code
0
github-code
54
27385635099
from django.shortcuts import render, render_to_response from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext, loader from django.contrib.auth import login from django.contrib.auth.decorators import login_required, user_passes_test from django.core.mail import send_mail f...
upenu/oldWebsite
users/views.py
views.py
py
18,643
python
en
code
4
github-code
54
18570776788
import random from torch.nn.functional import dropout, dropout2d, interpolate, avg_pool2d import torch class SamplePatch(object): def __init__(self, size_min, size_max): assert ( size_min <= size_max ), "size_min should be equal or smaller than size_max." assert size_min >= 2,...
ekgren/StructuredDreaming
deprecated/utils.py
utils.py
py
6,510
python
en
code
54
github-code
54
69900099362
from common.myunit import StartEnd from business.loginView import LoginView import unittest import logging class TestLogin(StartEnd): csv_file='../data/account.csv' #@unittest.skip('test_login_zxw2018') def test_login_zxw2018(self): logging.info('======test_login_zxw2018=====') l=LoginView...
zhao8445/Python_Test
test_case/test_login.py
test_login.py
py
1,136
python
en
code
1
github-code
54
31416912141
import math a=float(input('Δώσε τιμή για το a:')) b=float(input('Δώσε τιμή για το b:')) c=float(input('Δώσε τιμή για το c:')) d=(b**2)-(4*a*c) if d<0: print('Δεν υπάρχουν πραγματικές ρίζες') elif d==0: x=(-b+math.sqrt(b**2-4*a*c))/2*a print('Μία λύση:',x) else: x1=(-b+math.sqrt((b**2)-(4*...
stamvas/coursity-tutorial
week2/άσκηση 2.1.py
άσκηση 2.1.py
py
502
python
el
code
0
github-code
54
20604954921
import yaml import os.path class Config: def __init__(self, _path, _logger): # Validate args. if _path is None: raise ValueError("No config path provided to Config.") if _logger is None: raise ValueError("No logger provided to Config.") # Assign logger. ...
Aurorastation/ServerMonitor
ServerMonitor/Subsystems/Config.py
Config.py
py
829
python
en
code
0
github-code
54
18836374008
import os def rename_file(oldfilepath,newname): if os.path.exists(oldfilepath): try : newfilepath =os.path.join(os.path.dirname(os.path.abspath(oldfilepath)),newname) print(newfilepath,'abcd') print(oldfilepath,newname) os.rename(oldfilepath,newfilepath) ...
zhuyurain888/python_test
home_work/day04/Newdir.py
Newdir.py
py
597
python
en
code
0
github-code
54
459953675
import os numeros = [] maior = 0 for num in range(0,5): numeros.append(float(input(f'digite o numero {num + 1}: '))) if num == 0: maior = numeros[num] else: if numeros[num] > maior: maior = numeros[num] print(f'maior numero digitado: {maior}') os....
WilliamSampaio/ExerciciosPython
exerc31/31.py
31.py
py
337
python
pt
code
0
github-code
54
72002629603
# -*- coding:utf-8 -*- # @File :urls.py # @Author:bc # @Date :18-10-26 # @Desc : from django.conf.urls import url from . import views urlpatterns = [ url(r"^image_codes/(?P<image_code_id>[\w-]+)/$", views.ImageCodeView.as_view()), url(r"^mobiles/(?P<mobile>\d+)/count/$", views.ValidateMobileView.as_view()),...
itbc9527/small
meiduo_mall/meiduo_mall/apps/users/urls.py
urls.py
py
598
python
en
code
0
github-code
54
35817031221
import ftplib import json import os import datetime from datetime import timedelta import httplib2 import urllib import urllib2 sizeWritten = 0 totalSize = 0 domain = 'http://parcels.downers.us/' def handleFTP(block): global sizeWritten global totalSize sizeWritten += 1024 # this line fail because sizeW...
jkopi11/examples
python/dg_generics.py
dg_generics.py
py
2,985
python
en
code
0
github-code
54
21786870981
import pytest from icevision.all import * @pytest.fixture() def record(samples_source): record = BaseRecord( ( BBoxesRecordComponent(), InstancesLabelsRecordComponent(), # InstanceMasksRecordComponent(), FilepathRecordComponent(), ) ) record...
airctic/icevision
tests/core/test_record.py
test_record.py
py
6,195
python
en
code
839
github-code
54
71586200801
"""Prepare cycle gan datasets""" import os import argparse import zipfile from gluoncv.utils import download, makedirs def parse_args(): parser = argparse.ArgumentParser( description='Initialize Cycle Gan dataset.', epilog='Example: python download_dataset.py --download-dir ./', formatter_c...
dmlc/gluon-cv
scripts/gan/cycle_gan/download_dataset.py
download_dataset.py
py
1,816
python
en
code
5,662
github-code
54
7194801888
import datetime from cerberus import Validator as _Validator from sqlalchemy import inspect from sqlalchemy.orm.collections import InstrumentedList from sqlalchemy.exc import NoInspectionAvailable def is_sqla_obj(obj): """Checks if an object is a SQLAlchemy model instance.""" try: inspect(obj) ...
mbarakaja/saraki
saraki/utility.py
utility.py
py
9,590
python
en
code
3
github-code
54
26921295500
startYear = 1901 startMonth = 1 startDay = 1 endYear = 2000 endMonth = 12 endDay = 31 daycount = 0 monthLenArr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def checkLeap(year): if (year % 4 == 0) and (year % 100 == 0) and (year % 400 == 0): return True elif (year % 100 == 0) and (year % 400 == ...
robinyn/python-projects
Counting_Sundays/countingsundays.py
countingsundays.py
py
1,213
python
en
code
0
github-code
54