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
19242121480
import numpy as np import torch import cv2 import time import copy from trackron.structures.tracklet import Tracklet, BaseTrack, TrackState from trackron.data.utils import resize_image, sample_target_brpadding, normalize_boxes from .utils.matching import ious, iou_distance, linear_assignment, fuse_score from .build ...
Flowerfan/Trackron
trackron/trackers/bytetracker.py
bytetracker.py
py
12,904
python
en
code
46
github-code
13
28109666320
import torch import math # from idr import connection from torchvision.datasets.vision import VisionDataset from torchvision.transforms import ToTensor import numpy as np from torch.utils.data import Dataset, DataLoader from torchvision.transforms import ToTensor import matplotlib.pyplot as plt from torchvision.datase...
BioImage-Archive/ai_data
bia_vision/utils.py
utils.py
py
1,699
python
en
code
0
github-code
13
40672541985
import glob import json import logging import os import random import sys import numpy as np import torch from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader, SequentialSampler, TensorDataset, ConcatDataset from tqdm import tqdm from transformers import ( WEIGHTS_NAME, ...
mourga/transformer-uncertainty
main_transformer.py
main_transformer.py
py
52,365
python
en
code
37
github-code
13
6999449973
import logging import time from enum import Enum from typing import Any, Dict, List, Iterable, Iterator, Optional from typing import Union, Tuple import requests from requests import HTTPError from requests.auth import HTTPBasicAuth Auth = Union[requests.auth.AuthBase, Tuple[str, str]] Verify = Union[bool, str] LOGG...
itnoobzzy/EasyAirflow
plugins/hooks/LivyBatches.py
LivyBatches.py
py
15,663
python
en
code
0
github-code
13
17592791124
# This is 0 1 Knapsack Using recurssion and Top Down Approach ''' Example : Input : n = 3 W = 4 val[] = {1,2,3} wt[] = {4,5,1} Output : 3 ''' def knapSack_Top_Down(self,W, wt, val, n): t=[ [ 0 for i in range(W+1) ] for j in range(len(wt)+1) ] for i in range(1,len(t)): for j in range(1,len(t[0]))...
Mukesh-kanna/python-content-repo
knapsack_0_1.py
knapsack_0_1.py
py
830
python
en
code
0
github-code
13
28541742109
import time import board import busio import adafruit_tcs34725 # 初始化I2C对象 I2C = busio.I2C(board.SCL, board.SDA) # 创建一个tcs34725对象 tcs34725 = adafruit_tcs34725.TCS34725(I2C) # 打印读取到的范围 def tcs34725_detect(): while True: # 读取传感器的颜色、色温和照度 color = tcs34725.color_rgb_bytes temp = tcs34725.co...
cocpy/raspberrypi4
第8章/5/tcs34725.py
tcs34725.py
py
729
python
en
code
0
github-code
13
5759056191
import numpy as np import matplotlib.pyplot as plt class K_Mean_Algorithm: def __init__(self, k, epochs): self.k = k self.epochs = epochs def train(self, S_x, S_y): # To define clusters, need to know the range max_X, min_X = np.max(S_x), np.min(S_x) max_Y, min_Y = np.max(S_y), np.min(S_y) # Cl...
SalihFurkan/KMeanAlgorithm
K_mean_Algorithm.py
K_mean_Algorithm.py
py
1,700
python
en
code
0
github-code
13
70195468818
import threading class StoppableThread(threading.Thread): def __init__(self, *args, **kwargs): self._stop_event = kwargs.pop("stop_event", None) if self._stop_event is None: self._stop_event = threading.Event() super(StoppableThread, self).__init__(*args, **kwargs) def st...
bennihepp/pybh
pybh/thread_utils.py
thread_utils.py
py
3,573
python
en
code
0
github-code
13
6366358576
import math from station_logic.train_station import TrainStation from train_logic.train import Train from train_logic.train_state import TrainState class Entrepot(TrainStation): """ Entrepot station where oil is unloaded """ def __init__(self, station_name: str, oil_volume:...
Bumstern/train_simulator
station_logic/entrepot.py
entrepot.py
py
9,413
python
en
code
0
github-code
13
2913477351
import pytesseract import cv2 from PIL import Image import os import logging if os.name == 'nt': TESSERACT_PATH = "C:/Users/soludev5/AppData/Local/Programs/Tesseract-OCR/tesseract.exe" # <------ /!\ CHANGE THIS /!\ pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH NUMBER_OF_IMAGE_IN_CAPTCHA = 4 def extract...
Xaalek/IkabotCaptchaSolver
SolveCaptcha.py
SolveCaptcha.py
py
3,622
python
en
code
3
github-code
13
42166473750
import time, pytest import sys,os sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib'))) from clsCommon import Common import clsTestService from localSettings import * import localSettings from utilityTestFunc import * import enums class Test: #=========================...
NadyaDi/kms-automation
web/tests/HomePage/test_1573.py
test_1573.py
py
10,161
python
en
code
0
github-code
13
29673427
def fatorial(num): calc = 1 cont = int(num) for i in range(1, cont+1): calc *= i*1 return calc def super_fatorial(num): cont = int(num) superFatorial = 1 for c in range(0, cont+1): superFatorial *= fatorial(c) return superFatorial num = input(' digite um numero: ...
Sancheslipe/atividades_python_basico_ao_avancado_secao_08
ex36.py
ex36.py
py
435
python
en
code
0
github-code
13
6549130628
# -*- coding: utf-8 -*- # Extension by Lionel Chalet from docutils import nodes from docutils.parsers.rst import Directive from sphinx.errors import SphinxError import os, sys, copy, hashlib, random __version__ = '0.1' question_number = 0 alternative_number = 0 language = 'en' translations = { 'fr':...
obonaventure/cnp3
book-2nd/mcq-ex/mcq/mcq.py
mcq.py
py
15,086
python
en
code
500
github-code
13
16179911565
import mdtraj as md import numpy as np from mdtraj.geometry.alignment import rmsd_qcp, compute_average_structure from mdtraj.testing import eq np.random.seed(52) def test_trajectory_rmsd(get_fn): t = md.load(get_fn('traj.h5')) for parallel in [True, False]: calculated = md.rmsd(t, t, 0, parallel=para...
mdtraj/mdtraj
tests/test_rmsd.py
test_rmsd.py
py
7,876
python
en
code
505
github-code
13
23372452389
import sys sys.path.append('../../') from slm.slm_classifier import SLMClassifier from numpy import vstack, log from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils.validation import check_X_y, column_or_1d from common.metrics import METRICS_DICT fro...
OnHoliday/DSLM_NOVA
dslm_new/algorithm/deep_semantic_learning_machine/deep_semantic_learning_machine_app.py
deep_semantic_learning_machine_app.py
py
12,701
python
en
code
0
github-code
13
86407521210
""" data:2017-7-10 author:alancheg 本程序的主要作用是计算 kmeans 聚类后的数据中心点 输入:需要聚类的内容,聚类的中心点个数 输出:聚类的中心点坐标 """ import csv from sklearn.cluster import KMeans import numpy as np from time import time CLUSTER_CENTER = 8 # 数据的格式 # img_name,feature_name,feature_num,cor_x,cor_y def data_generate(path): # 生成标准的位置信息 data = []...
alancheg/VideoIndex
data_cluster.py
data_cluster.py
py
1,212
python
en
code
0
github-code
13
28541524219
import serial # 引入serial包 ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1) # 打开端口 def main_loop(): """主循环,打印读取到的数据""" while True: str_hello = "Hello Arduino,I am Raspberry." b_hello = bytes(str_hello, encoding='utf-8') # 字符串转为字节 ser.write(b_hello) # 发送数据 response = s...
cocpy/raspberrypi4
第12章/5/serial_test.py
serial_test.py
py
624
python
en
code
0
github-code
13
26000569042
from tkinter import * import random # the game data for the initial game state def init(): data.playerX = 250 data.playerY = 550 data.circles = [] # store circles as [x, y, r, color] data.gameOver = False data.time = 0 data.score = 0 # events updating the game data def keyPressed(event): ...
Teknowledge/Curriculum
past_iterations/02_Homewood_Y/02_drawing/09_solution_advanced_circle_clash.py
09_solution_advanced_circle_clash.py
py
2,851
python
en
code
0
github-code
13
3235480924
import numpy as np import pandas as pd from scipy.optimize import minimize import matplotlib.pyplot as plt def tgt_fn(x, matches): """ Cost we will optimize to get the ELO ratings. :param x: current ratings of plots :param matches: all pairings of plots and their outcomes """ xr = np.hstack([0...
AndrejHafner/how-good-is-my-plot
src/plot_quality_prediction/elo_ratings.py
elo_ratings.py
py
2,825
python
en
code
4
github-code
13
40343154083
# -*- coding: utf-8 -*- import telnetlib, sys, select from django.http import HttpResponse from .auth import login_check def _pre_process_cmd(cmd): if cmd.endswith( b"\r\n" ): return cmd elif cmd[-1] == b"\r": cmd += b"\n" elif cmd[-1] == b"\n": cmd = cmd[:-1] + b"\r\n" else: cmd += b"\r\n" return cmd c...
kbengine/kbengine
kbe/tools/server/webconsole/WebConsole/telnet_console.py
telnet_console.py
py
3,306
python
en
code
5,336
github-code
13
24183689331
import copy import logging import os import pathlib import sys from unittest import TestCase from unittest.mock import patch from ws_sdk.client import WSClient class TestWSClient(TestCase): logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) class TestWS(TestCase): valid_token = "abcdefghijklmnopqr...
whitesource-ps/ws-sdk
ws_sdk/tests/test_client.py
test_client.py
py
2,080
python
en
code
17
github-code
13
14257807133
import codecs import csv from os import listdir from os.path import isfile, join def get_available_files(): # return the csv and ttl files from the "files/" directory, separated in two lists files = [f for f in listdir("files") if isfile(join("files", f))] csv_files = [f for f in files if f.endswith(".csv...
mdaubie/Triplifier
utils.py
utils.py
py
6,546
python
en
code
0
github-code
13
11672372818
import requests from imutils import paths import argparse import cv2 import os argparser = argparse.ArgumentParser() argparser.add_argument("-u", "--urls", required=True, help="path to file containing image URLs") argparser.add_argument("-o", "--output", required=True, help="path to output directory of...
robiColt/image-classifier-CNN-SVM
image_downloader.py
image_downloader.py
py
1,262
python
en
code
0
github-code
13
4511226972
#!python # -*- coding: utf8 -*- rootElement = 'elements' topElement = 'element' encoding = 'utf8' deletetext = 'delete' extra = '_anno' # entities show in the radiobox bar entities = [(u'产地', 'place'), (u'品种', 'type'), (u'等级', 'rank'), (u'其它', 'other')]
aisensiy/AnnotationTool
config.py
config.py
py
273
python
en
code
0
github-code
13
33804659941
from django.db import models SEMESTRES = [ ('1', '1er'), ('2', '2do'), ('3', '3er'), ('4', '4to'), ('5', '5to'), ('6', '6to'), ('7', '7mo'), ('8', '8vo'), ('9', '9no'), ('10', '10mo'), ] DIAS = [ ('1', 'Lunes'), ('2', 'Martes'), ('3', 'Miercoles'), ('4', 'Jueves...
DanielMCastillo/Frameworks
inscripciones/horarios/models.py
models.py
py
924
python
en
code
0
github-code
13
16178935095
from __future__ import print_function, division import os import itertools import numpy as np from mdtraj.utils import ensure_type, cast_indices, in_units_of from mdtraj.formats.registry import FormatRegistry from mdtraj.utils.six import string_types, PY3 from mdtraj.utils.six.moves import xrange __all__ = ['MDCRDTraj...
mdtraj/mdtraj
mdtraj/formats/mdcrd.py
mdcrd.py
py
17,213
python
en
code
505
github-code
13
71071815379
import os import json import cv2 as cv import numpy as np # dataset_path_list = ["E:/PythonCodes/bbox3d_annotation_tools/session0_center_data", # "E:/PythonCodes/bbox3d_annotation_tools/session0_right_data", # "E:/PythonCodes/bbox3d_annotation_tools/session6_right_data"] ra...
stjuliet/CenterLoc3D
utils/visualize_gt_pos.py
visualize_gt_pos.py
py
2,589
python
en
code
10
github-code
13
4913836591
import aepp from dataclasses import dataclass from aepp import connector from copy import deepcopy from typing import Union import time import logging import pandas as pd import json import re from .configs import ConnectObject json_extend = [ { "op": "replace", "path": "/meta:intendedToExtend", ...
pitchmuc/aepp
aepp/schema.py
schema.py
py
150,047
python
en
code
24
github-code
13
6948073764
from typing import * class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: if len(cost) <= 2: return min(cost) pre1, pre2 = cost[0], cost[1] tem = 0 for i in range(2, len(cost)): tem = min(pre1 + cost[i], pre2 + cost[i]) pre1 =...
Xiaoctw/LeetCode1_python
动态规划/使用最小花费爬楼梯_746.py
使用最小花费爬楼梯_746.py
py
512
python
en
code
0
github-code
13
30989289608
from flask import Flask, request, jsonify import requests app = Flask(__name__) # URLs de las dos instancias de la aplicación Flask app1_url = "http://127.0.0.1:5000" # Reemplaza con la URL de tu primera instancia app2_url = "http://127.0.0.1:5001" # Reemplaza con la URL de tu segunda instancia @app.route('/call_a...
Zanderz17/Soft_Sem11_Jueves
script.py
script.py
py
1,087
python
es
code
0
github-code
13
73506861776
#-*- coding:utf-8 -*- ''' Created on 2013-9-21 @author: lenovo ''' import time from bson.objectid import ObjectId from model import Model from const_var import ROOM_STATE_FREE, ROOM_STATE_CHATTING, TABLE_ROOM, TABLE_USER class Room(Model): table = TABLE_ROOM # def create_room(self, u...
conwaywang/daohe
model/room.py
room.py
py
2,303
python
en
code
0
github-code
13
38761625072
from flask import Blueprint, render_template, redirect, url_for, request, flash, jsonify, session, abort from flask_login import login_user, logout_user, login_required, current_user from werkzeug.security import generate_password_hash, check_password_hash from ..models.User import User from ..models.Course import Cour...
LEGS2001/Proyecto-IHM
backend/project/controllers/admin.py
admin.py
py
9,265
python
en
code
1
github-code
13
70234784337
import numpy as np from matplotlib import pyplot as plt #Exercicio1 t=np.arange(-1,3,0.001) x=2*np.cos(2*np.pi*10*t+(np.pi/4))+np.sin(2*np.pi*11*t-(np.pi/3)) plt.xlabel("t") plt.ylabel("x(t)") plt.title("ex1.I-> "+r"$x(t)=2cos(2\pi10t+\frac{\pi}{4})+sin(2\pi11t-\frac{\pi}{3})$") plt.plot(t,x) plt.show()
miguelTavora/Digital-Signal
Trabalho 1/exercicio 1/ex1.I.py
ex1.I.py
py
312
python
en
code
0
github-code
13
33251716990
#!/usr/bin/env python import urllib.request import urllib.parse import re user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25" check_url = 'http://wo.yao.cl/register.php' alphabeta = [chr(x+ord('a')) for x in range(26)] d...
donyfeng/cltest
cltest.py
cltest.py
py
1,748
python
en
code
0
github-code
13
35950959746
class sym_t(object): ''' symbol used in asm source, can use '.set <label>, <value>' if parse in label as tuple or list, then this label serve as indirect-indexed symbol in this case, value can be ommited ''' def __init__(self, label, value = 0, comments = ''): if type(label) in (tuple,...
ROCmSoftwarePlatform/MISA
python/codegen/symbol.py
symbol.py
py
2,498
python
en
code
29
github-code
13
35107130958
# from django.views.decorators.cache import cache_page from django.urls import path # from myapp import views from . import views urlpatterns = [ # path('', views.home, name="home"), path('', views.Home.as_view(), name="home"), path('about/', views.about, name="about"), # path('about/', cache_page(60)(...
ronysingh1209/mysite
mysite/myapp/urls.py
urls.py
py
1,022
python
en
code
0
github-code
13
73492686736
import os import pytest import torch import torch.distributed as dist from torch.utils.data import Dataset from dynapipe.model import TransformerModelSpec, get_uniform_cluster from dynapipe.pipe.data_loader import DynaPipeDataLoader, TrainingSpec from dynapipe.pipe.instructions import ExecutionPlan, ForwardPass torc...
awslabs/optimizing-multitask-training-through-dynamic-pipelines
tests/test_dataloader/test_dataloader.py
test_dataloader.py
py
12,642
python
en
code
1
github-code
13
1652730655
#我的思路就是先判断位数,然后分情况 #但感觉有点复杂 #查了个,用的DFS,用到了helper函数 class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ ans = [] self.helper(ans, s, 4, []) return ['.'.join(x) for x in ans] def helper(self, ans, s, k, te...
fire717/Algorithms
LeetCode/python/_093.RestoreIPAddresses.py
_093.RestoreIPAddresses.py
py
714
python
en
code
6
github-code
13
74358804178
#问题1 fi = open("test.txt", "r", encoding="utf-8") txt = fi.read() d = {} exclude = ",。!?、()【】<>《》=:+-*—“”…" for word in txt: if word in exclude: continue else: d[word] = d.get(word,0)+1 fi.close() ls = list(d.items()) ls.sort(key=lambda x:x[1],reverse=True) print(ls) print("{}:{}".format(ls[0][0...
dusizhong/python-examples
2.py
2.py
py
370
python
en
code
0
github-code
13
26215943984
import numpy as np import random # can replace colors with RGB values later COLORS = ['red', 'pink', 'lightblue', 'white', 'black', 'blue', 'green', 'yellow', 'none'] MAXIMUM_SQ = 6 GRID_ROWS = 2 NUM_TRIALS = 150 WINDOW_SIZE = (1440, 1080) def calculate_location(size, i): """ Calculate th...
amyflo/discretewholereport
wholereport.py
wholereport.py
py
2,898
python
en
code
1
github-code
13
70435957457
class ListNode: def __init__(self, val): self.val = val self.next = None class MyLinkedList(object): #Implementation with singly linked list def __init__(self): self.head = None self.size = 0 def get(self, index): """ :type index: int :r...
ItsMeeSeanLee337/LeetCode-Questions
707. Design Linked List/Design_Linked_List.py
Design_Linked_List.py
py
3,889
python
en
code
0
github-code
13
3874495997
# coding: utf-8 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.cluster import KMeans diabetes = pd.read_csv('diabetes_balanced.csv') X = np.array(diabetes.drop(['Outcome'], axis=1).astype(float)) y = np.array(diabetes['Outcome']...
ncd-surveillance-system/SIH_demogrphical_analysis
OldDataset/K-Means.py
K-Means.py
py
707
python
en
code
0
github-code
13
71831414098
from ultralytics import YOLO import os import cv2 model = YOLO(os.path.expanduser('~/overwrite_det/last_31_OWO.pt')) clip_limit = 78 # Set your desired clip limit (78 in this example) tile_size = 20 if __name__ == '__main__': image = cv2.imread("Sample4_1.png", cv2.IMREAD_GRAYSCALE) #image=cv2.imread("Samp...
CMA020/overwrite_det
Det_test.py
Det_test.py
py
553
python
en
code
0
github-code
13
23623838372
"""3d pose graph visualization utilities that use the Open3d library.""" from typing import List, Optional import gtsfm.visualization.open3d_vis_utils as open3d_vis_utils import numpy as np import open3d from gtsam import Pose3 import salve.utils.colormap as colormap_utils def get_colormapped_spheres(wTi_list: Lis...
zillow/salve
salve/visualization/utils.py
utils.py
py
3,499
python
en
code
4
github-code
13
23617476522
from django.forms import ModelForm from django import forms from administrativo.models import Estudiante, NumeroTelefonico class EstudianteForm(ModelForm): class Meta: model = Estudiante fields = ['nombre', 'apellido', 'cedula'] class NumeroTelefonicoForm(ModelForm): def __init__(se...
taw-desarrollo-plataformas-web/ejemplos5.3.7_1
ejemplo1/proyectoUno/administrativo/forms.py
forms.py
py
679
python
en
code
0
github-code
13
14936771205
import csv import operator import os import re from flask_script import Command, Option from user_agents import parse class UaParser(Command): """ Утилита для парсинга лога с юзер агентами Пример строки: Count "UserAgent" """ def __init__(self): super().__init__() self.top = 100 ...
DmitryShahbazov/UA-Parser
ua_parser.py
ua_parser.py
py
5,329
python
ru
code
0
github-code
13
21828381732
import json from itertools import groupby from team_league_elt.root import ROOT_DIR from typing import List, Dict def build_team_fifa_ranking_list(): with open(f'{ROOT_DIR}/world_cup_team_players_stats_raw.json') as json_file: team_stats_as_dicts = json.load(json_file) team_fifa_ranking: List[Dict] =...
tosun-si/world-cup-qatar-team-stats-kotlin-midgard
scripts/create_team_fifa_ranking_list.py
create_team_fifa_ranking_list.py
py
756
python
en
code
3
github-code
13
23905040301
#!/usr/bin/env python3 """Module used to""" import numpy as np def batch_norm(Z, gamma, beta, epsilon): """normalizes an unactivated output of a NN""" β = beta γ = gamma ε = epsilon μ = Z.mean(0) σ = Z.std(0) σ2 = Z.std(0) ** 2 z_normalized = (Z - μ) / ((σ2 + ε) ** (0.5)) Ẑ = γ *...
diego0096/holbertonschool-machine_learning
supervised_learning/0x03-optimization/13-batch_norm.py
13-batch_norm.py
py
366
python
en
code
0
github-code
13
73097435536
class Evaluator: """String weight evaluator""" @staticmethod def check_args(coefs, words): if len(coefs) != len(words): return(False) if not isinstance(coefs, list): return(False) if not isinstance(words, list): return(False) try: ...
Cizeur/Bootcamp_Python
day01/ex04/eval.py
eval.py
py
1,349
python
en
code
0
github-code
13
41818191376
from google.cloud import storage from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file("vision-6964-cec0e32a1768.json") CLIENT_ID = "GOOG1ELM7PJRRII5V3WQZJDFPLMVLU7BWMX3CPYOIF4QWXQGHG37DSZDCVYSY" CLIENT_SECRET = "Nk/1HI0zI00gx208y4Sm+ZiK/dP8sqpt7i+QoIWZ" storag...
sidharthmrao/RovicareOCR
ocr/cloudstoragetesting.py
cloudstoragetesting.py
py
568
python
en
code
1
github-code
13
73538982416
from pytube import YouTube from .step import Step from yt_concate.settings import VIDEOS_DIR import logging class DownloadVideos(Step): def process(self, data, inputs, utils): logger = logging.getLogger() yt_set = set ([found.yt for found in data]) logger.info(f'videos to download:, {len(y...
cindypai/yt-concate
yt_concate/pipeline/steps/download_videos.py
download_videos.py
py
709
python
en
code
0
github-code
13
43588848989
import logging import numpy as np import pandas as pd from sklearn import preprocessing from gzreduction.deprecated.uncertainty import uncertainty def reduced_votes_to_predictions(df, schema, save_loc): """ Calculate predicted answers and uncertainty from reduced vote counts. Args: df (pd.Data...
mwalmsley/gz-panoptes-reduction
gzreduction/votes_to_predictions/reduced_votes_to_predictions.py
reduced_votes_to_predictions.py
py
6,204
python
en
code
1
github-code
13
20859588889
import matplotlib.pyplot as plt import numpy as np import pandas as pd # BAR GRAPH 1 MEDIAN AGE plt.figure(figsize=(9,7)) data = pd.read_csv('data03sheet.csv') plt.title('Average (Median) Age in Different Regions', fontdict={'fontweight':'bold', 'fontsize': 18}) #sorting the data into ascending order myReg = data['Reg...
ari-abr/World-In-Numbers
py_demographics.py
py_demographics.py
py
2,898
python
en
code
0
github-code
13
22648280287
import json import logging import os from copy import deepcopy from urllib.parse import urljoin, urlparse from boto3utils import s3 from cirruslib import StateDB, stac, STATES logger = logging.getLogger(__name__) # envvars DATA_BUCKET = os.getenv('CIRRUS_DATA_BUCKET', None) # Cirrus state database statedb = StateDB...
cirrus-geo/cirrus-earth-search
core/api/lambda_function.py
lambda_function.py
py
5,104
python
en
code
21
github-code
13
30171855103
#!/usr/bin/env python # Note: This demo will only work if you have a Barobo breakout-board currently # attached to the linkbot. from barobo import Linkbot if __name__ == "__main__": linkbot = Linkbot() linkbot.connect() adcs = map(linkbot.getBreakoutADC, range(0,8)) print(map(lambda x: x/1024.0*5.0,...
davidko/PyBarobo
demo/test/with_BaroboLink/getBreakoutADC.py
getBreakoutADC.py
py
328
python
en
code
0
github-code
13
5132625046
# -*- coding: utf-8 -*- # python结巴分词使用停用词版本,根据输入的excel文件分词后输出到另一个excel中 import xlrd import xlwt import jieba def jiebafenci(input_path,output_path): jieba.load_userdict('userwords.txt') # userwords.txt 为文件类对象或自定义词典 # 读取停用词文件 with open('stopwords.txt', encoding='UTF-8') as f: stoplist = f...
yingtaoluo/51jobs-Text-Mining
sy4/jiebaWithStopwords.py
jiebaWithStopwords.py
py
2,374
python
en
code
0
github-code
13
32318289681
''' This file renders out the layers of a blend file to different names. It is configured by a JSON file that links a name to visible layers. For example: [ {'name':'image_name', 'layers':[2,5]}, ] The json file is provided by the command line arguments. Invoke this script using: blender path/to/blendfile.blend -...
sdfgeoff/LearningWhatAGameEngineIs
src/Scripts/render.py
render.py
py
1,092
python
en
code
0
github-code
13
32383172296
import matplotlib.pyplot as plt import numpy as np import os import matplotlib matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 matplotlib.rcParams.update({'font.size': 13}) """Plotting""" algorithms = ['Q'] # delays = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] delays = [2, 4, ...
baranwa2/DelayResolvedRL
W-Maze/Tabular-Q/plot.py
plot.py
py
2,796
python
en
code
3
github-code
13
12343804785
# Program to find the majority element that is the occurence should be greater than N/2 , where N is the size of the array # BELOW PROGRAMS IN VARIOUS SECTIONS ARE FOR N/2, N/3.... MAJORITY ELEMENTS. # ---------------------------------------------------------------------------------------------------------------- # NOT...
souravs17031999/100dayscodingchallenge
arrays/majority_element_array.py
majority_element_array.py
py
5,970
python
en
code
43
github-code
13
11653776738
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django import forms from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.forms import AdminPasswordChangeForm from models import * class Doc...
HoangJerry/bookingDoctor
api/admin.py
admin.py
py
3,689
python
en
code
0
github-code
13
38970834340
''' Написать программу которая считает количество строк в прикрепленном файле. Файл должен находиться в том же каталоге что и программа. P.S. в подсчет не включать строки которые обозначают пропуски между частями стихотворения ''' f = open('zadanie2.txt', encoding='utf-8') st = f.readlines() # псчитываем все строки c...
ArTdrums/zadania-s-failami
10. задание 2.py
10. задание 2.py
py
877
python
ru
code
0
github-code
13
7041750330
from o3seespy.command.element.base_element import ElementBase class TwoNodeLink(ElementBase): """ The TwoNodeLink Element Class This command is used to construct a twoNodeLink element object, which is defined by two nodes. The element can have zero or non-zero length. This element can have 1 to 6...
o3seespy/o3seespy
o3seespy/command/element/link.py
link.py
py
4,844
python
en
code
16
github-code
13
26445750684
import os import multiprocessing from multiprocessing import Process import pandas as pd import tqdm import sys base = '/datasets/xeno_canto/wav_16khz_XC/' def get_length(files): audios = os.listdir(files) audios = [f for f in audios if '_16.wav' not in f] if len(audios) == 0: print(files) ...
farrinfedra/bird_song_resynthesis
preprocessing/remove.py
remove.py
py
767
python
en
code
0
github-code
13
8326381437
lines = open('../data/ex7.txt', 'r').readlines() dir_size_map = dict() parent_map = dict() def add_to_parents(size, cur_dir): parent = parent_map[cur_dir] if parent == '': return dir_size_map[parent] += size try: add_to_parents(size, parent) except RecursionError as e: prin...
DonnyWhoLovedBowling/aoc2022
src/ex7.py
ex7.py
py
1,860
python
en
code
0
github-code
13
1680816946
#!/usr/bin/env python3 #encoding=utf-8 #------------------------------------------- # Usage: python3 global_scope_example.py # Description: global in function definition #------------------------------------------- x = 88 # Global x print('before func, x = %s' % x) def func(): global x x = 99 ...
mindnhand/Learning-Python-5th
Chapter17.Scopes/global_scope_example.py
global_scope_example.py
py
427
python
en
code
0
github-code
13
25397659347
import numpy as np import matplotlib.pyplot as plt import os def sigmoid(x): return 1/(1+np.exp(-x)) def logistic_regression_gradient_descent(x,y,W_init,learning_Rate,tol=10e-5,max_count=10000000): w=W_init count=0 while max_count>count: y_predict=sigmoid(np.dot(x.T,w)) #GD grad...
nhoxnho1212/logisticRegression
And.py
And.py
py
1,147
python
en
code
0
github-code
13
17015275115
""" Naive n cubed solution - works but is too slow """ import csv from itertools import combinations from pathlib import Path import pytest class Solution: def threeSum(self, nums: list[int]) -> list[list[int]]: solution = { tuple(sorted(comb)) for comb in combinations(nums, 3) if sum(comb) ...
chrisjdavie/interview_practice
leetcode/3sum/first.py
first.py
py
859
python
en
code
0
github-code
13
23555310626
import os import sys def list_files(*args): path = os.getcwd() dir_name = '.zeon_fs' file_path = os.path.join(path, dir_name) dir_files = os.listdir(file_path) print('Files: ', len(dir_files)) for i in dir_files: print(i) if __name__ == "__main__": args = sys.argv if not l...
azatuuluaman/zeon_fs2
commands/list_files.py
list_files.py
py
375
python
en
code
0
github-code
13
5253575605
from app.db.Models.flow_context import FlowContext def get_domain_tags(domain_id): cursor = FlowContext().db().aggregate([ {"$match": {"domain_id": domain_id}}, {"$project": {"upload_tags": 1}}, ]) tags_set = set() for i in cursor: for tag in i.get("upload_tags", []): ...
HassenMahdi/dcm-upload
app/main/service/tags_service.py
tags_service.py
py
854
python
en
code
0
github-code
13
70459644497
# making a request to fixer.io forex rates website # using user input for api parameters # NOT working anymore: base is always EURO for free accounts import requests def main(): base = input("First Currency: ") other = input("Second Currency: ") # the takeaway is that url params can be passed as below ...
amrfekryy/course-CS50W
lecture4 - ORM&API/21currency2.py
21currency2.py
py
672
python
en
code
0
github-code
13
2456556450
import sys from termcolor import colored, cprint #def answer(dimensions, ur_position, guard_position, distance): def debug(*objects): print(objects) dims = [3, 2] ur_pos = [1, 1] g_pos = [2, 1] dist = 4 # dims = [300, 275] # ur_pos = [150, 150] # g_pos = [185, 100] # dist = 500 # dims = [1000, 1000] # ur_pos = [250,...
damhonglinh/google-foobar
lvl-4a--bringing_a_gun_to_a_guard_fight/drawing-scripts/messy-solution_4a.py
messy-solution_4a.py
py
4,024
python
en
code
0
github-code
13
70192938897
import sqlite3 import pandas as pd try: sqliteConnection = sqlite3.connect('app.db') cursor = sqliteConnection.cursor() print("Successfully Connected to SQLite") #agency_domain_white_list cursor.execute("""DELETE FROM agency_domain_white_list""") data = pd.read_csv(r'agency_domain_whitelist.cs...
barhantas/coalitioninc-task
api/data-loader.py
data-loader.py
py
2,361
python
en
code
2
github-code
13
16853240085
# -*- coding:utf8 -*- import time import celery from celery import task from celery.schedules import crontab app = celery.Celery('cele', broker='redis://localhost:6379') @task def sayHello(): print ("hello...") time.sleep(3) print ('world...') ''' 设置执行的时间 ''' # 每分钟执行一次 c1 = crontab() # 每天凌晨十二点执行 c2 =...
ShuoDu/celery_used
showTime/task.py
task.py
py
912
python
zh
code
0
github-code
13
14817079557
############################################################################################ # This script is tested and compatible with the python version 3.10 # # make sure all python dependencies are installed to be able to import the listed modules. # # This script was written and executed on...
MrTam-Node/get_avg_cpu_usage
get_avg_cpu_ram.py
get_avg_cpu_ram.py
py
11,453
python
en
code
1
github-code
13
29201569515
import numpy as np import datetime def distance(v1, v2): # v1 = (T, T, T, F, F, F, F, F, T, T, F, T, F, F, T, T, T, T, F, F, T, T, T, T) # v2 = (F, T, T, F, F, T, T, F, F, T, F, T, T, T, T, T, T, F, T, F, T, T, F, T) return(sum([i[0]!=i[1] for i in zip(v1, v2)])) def has_dup(G): tmpG = {} for v in G: ...
sunanqi/learning
Greedy Algorithms- Minimum Spanning Trees- and Dynamic Programming by Tim Roughgarden/clustering_big.py
clustering_big.py
py
2,833
python
en
code
0
github-code
13
39103849650
__major__ = '2' __minor__ = '0' __patch__ = '0' __version__ = '.'.join([__major__, __minor__, __patch__]) __author__ = 'Misha Turnbull' __author_email__ = 'mishaturnbull@gmail.com' __tested_on__ = {"windows 10": ['gui'], "osx el capitan": ['gui'], "kali linux 2016.3": ['gui'], ...
mishaturnbull/EmailGUI
VERSION.py
VERSION.py
py
442
python
en
code
0
github-code
13
24283281205
def json_response(response, code): from flask import make_response resp = make_response(response.to_json(), code) resp.headers['Content-Type'] = "application/json" return resp def format_content_range(start, end, size): if start is None or end is None: range = '*' else: range =...
whisust/jellynote-backend
api/routes/utils.py
utils.py
py
427
python
en
code
1
github-code
13
27080975159
""" parsers.py parsers models, input ip address list collapse, or scanner results to parse. """ import fnmatch import ipaddress import os import argparse from libnmap.parser import NmapParser, NmapParserException from dscan import log def parse_args(): """ Used by main to parse the user arguments. :retu...
0x4E0x650x6F/dscan
dscan/models/parsers.py
parsers.py
py
5,012
python
en
code
15
github-code
13
35658457215
#!/usr/bin/python3 import sys import time from scapy.all import sendp, ARP, Ether if len(sys.argv) < 3: print(sys.argv[0] + ": <target> <spoof_ip>") sys.exit(1) iface = "wlp2s0" target_ip = sys.argv[1] fake_ip = sys.argv[2] ethernet = Ether() arp = ARP(pdst=target_ip, psrc=fake_ip, op="is-at") packet ...
balle/python-network-hacks
arp-spoof.py
arp-spoof.py
py
399
python
en
code
135
github-code
13
32276470753
# exercise 57: Cell Phone Bill minutes = int(input('enter number of minutes: ')) messages = int(input('enter number of text messages: ')) if minutes > 50: extra_mins = minutes - 50 else: extra_mins = 0 if messages > 50: extra_text = messages - 50 else: extra_text = 0 base_charge = 15 included_mins = ...
sara-kassani/1000_Python_example
books/Python Workbook/decision_making/ex57.py
ex57.py
py
1,015
python
en
code
1
github-code
13
6331738275
import os import numpy as np import argparse import gym import tqdm from keras.models import load_model from pid_lenya import Agent from run_pid_optimized import PIDPolicy model = load_model('model.hd5') def main(): parser = argparse.ArgumentParser() env = 'AttFC_GyroErr-MotorVel_M4_Ep-v0' seeds = [5,] ...
prokhn/onti-2019-bigdata
gymfc/examples/controllers/run_test.py
run_test.py
py
1,894
python
en
code
0
github-code
13
11593232912
# # 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020) # LAB 9-8 트윗 메시지를 깔끔하게 정제하자, 243쪽 # import re tweet = input('트윗을 입력하시오: ') tweet = re.sub('RT', '', tweet) # RT 문자열을 삭제 tweet = re.sub('#\S+', '', tweet) # 해시(#)다음에 나타나는 문자열을 삭제 tweet = re.sub('@\S+', '', tweet) # 앳사인(@)다음에 나타나는 문자열을 삭제 print(tweet)
dongupak/DataSciPy
src/파이썬코드(py)/Ch09/lab_9_8.py
lab_9_8.py
py
454
python
ko
code
12
github-code
13
73912529619
from urllib.parse import urlencode #------------------------------------------------------------------------------ from kivy.network.urlrequest import UrlRequest #------------------------------------------------------------------------------ _Debug = False #---------------------------------------------------------...
datahaven-net/recotra
lib/coinmarketcap_client.py
coinmarketcap_client.py
py
1,126
python
en
code
4
github-code
13
69927201619
import typing as tp from pathlib import Path import dataclasses import collections import itertools import pickle import logging import cv2 import imutils import numpy as np import shapely.geometry import matplotlib.pyplot as plt from .line import Line from .colors import Colors from .image_utils import get_image...
expertanalytics/digeeg
src/dgimage/image.py
image.py
py
5,793
python
en
code
0
github-code
13
34810975301
import glob import json import os import re import sys HEADING1 = "\n# " HEADING2 = "\n## " LINK_RE = re.compile("(\\[)([^\\[]*)(\\])(\\()([^\\)]*)(\\))") def main(target_dir): # Iterate over files local_dir = os.path.dirname(__file__) for fname in glob.glob(os.path.join(local_dir, "*.md")): if ...
miguelmorin/business
content/sync.py
sync.py
py
2,703
python
en
code
0
github-code
13
70524679057
import connector as DB dbCur = DB.Connection.cursor() def dbExec(sql): dbCur.execute(sql) DB.Connection.commit() # STUDENT def newAddress(AddressID, UnitNo, Street, Brgy, City, ZIP): sql = f"INSERT INTO ADDRESS(AddressID, UnitNo, StreetName, Brgy, City, ZipCode) VALUES('{AddressID}','{UnitNo}','{Stre...
DzhonPetrus/SanctionManagementSystem
DB/Address.py
Address.py
py
1,287
python
en
code
0
github-code
13
17053524224
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.InvoiceItemQueryOpenModel import InvoiceItemQueryOpenModel from alipay.aop.api.domain.InvoiceTradeFundItem import InvoiceTradeFundItem from alipay.aop.api.domain.InvoiceTradeGoodsIt...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/InvoiceTradeInfo.py
InvoiceTradeInfo.py
py
12,499
python
en
code
241
github-code
13
30138741392
import unittest import os from PIL import Image from werkzeug.datastructures import FileStorage from zou.app import app from zou.app.utils import thumbnail, fs TEST_FOLDER = os.path.join("tests", "tmp") class ThumbnailTestCase(unittest.TestCase): def get_fixture_file_path(self, relative_path): current...
cgwire/zou
tests/utils/test_thumbnail.py
test_thumbnail.py
py
5,232
python
en
code
152
github-code
13
19879049113
#PyBank# #Financial records analyzation #Import libraries and dependencies import csv import pandas as pd import numpy as np #path for CSV file file_path_input = ("budget_data.csv") file_to_output = ("analysis.data.txt") #Read CSV into Panadas and give it a variable name Budget_DF Budget_df = pd.read_csv(file_path_i...
KeepItOnTheDownload/PyBank
Pybank-Pandas.py
Pybank-Pandas.py
py
2,142
python
en
code
1
github-code
13
43611299736
import streamlit as st import functions # The order of functions, commands etc. in a webapp matters. # The script will be executed from top to bottom. todos = functions.get_todos() def add_todo(): todo = st.session_state["new_todo"] + "\n" todos.append(todo) functions.write_todos(todos) st.title("My To...
Henkel204/my-todo-app
web.py
web.py
py
808
python
en
code
0
github-code
13
1969198501
# import concurency import time from concurrent.futures.process import ProcessPoolExecutor import numpy as np from tqdm import tqdm def predict(input): time.sleep(.05) return np.sum(input*input.T) def single_process(in_dataset): result = list() for arr in tqdm(in_dataset): result.append(pre...
VadyusikhLTD/prjctr-ML-in-Prod
week2/multiple-process-inference/multiple_process_inference.py
multiple_process_inference.py
py
1,065
python
en
code
0
github-code
13
11408344026
from http.client import HTTPResponse from multiprocessing import context from django.shortcuts import render, redirect from django.http import HttpResponse from pages.models import Ticket from pages.forms import TicketForm, StatusForm # Create your views here. def home(request): return render(request, 'base.html'...
seepanas10/helpdesk-django
pages/views.py
views.py
py
1,267
python
en
code
0
github-code
13
9070569930
result_sum = 100 nums = [] nanjange_count = 9 for i in range(nanjange_count): nums.append(int(input())) sum_heights = sum(nums) for i in range(nanjange_count - 2): for j in range(i+1, nanjange_count): temp_sum = nums[i] + nums[j] if sum_heights - temp_sum == result_sum: x1 = nums...
mins1031/coding-test
baekjoon/CompleteSearch/SevenNanjange_2309.py
SevenNanjange_2309.py
py
717
python
ko
code
0
github-code
13
8954248870
import pickle import requests import streamlit as st from pydantic import BaseModel DATASET_INFO_PATH = "categorical_features_dict.pkl" st.title("Car prediction app") # when running from outside docker, replace api:8080 with localhost:8080 ENDPOINT_URL= f'http://api:8080/api/predict' class CarInformationRequest(B...
dsmoljan/Car-price-prediction
Code/app/frontend/main.py
main.py
py
2,775
python
en
code
0
github-code
13
74176775699
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 30 13:16:47 2019 @author: gregz """ import astropy.units as u import numpy as np import pickle from input_utils import setup_logging from astropy.io import fits from astropy.coordinates import SkyCoord from astropy.table import Table from hetdex_a...
grzeimann/Panacea
toy.py
toy.py
py
2,578
python
en
code
8
github-code
13
22467477403
""" Продолжить работу над первым заданием. Разработать методы, отвечающие за приём оргтехники на склад и передачу в определенное подразделение компании. Для хранения данных о наименовании и количестве единиц оргтехники, а также других данных, можно использовать любую подходящую структуру, например словарь. """ class ...
slavaprotogor/python_base
homeworks/lesson8/task5.py
task5.py
py
2,300
python
ru
code
0
github-code
13
33526917443
""" Character Class is the base class and used to create monsters. Also could add a skill class so monsters could hit harder. """ from assests.items import Weapon class Character: def __init__(self, name, hp, maxhp, mp, maxmp, atk, defence, inventory, exp): self.name = name # Health poin...
Asarmir/HeroQuest
users/char.py
char.py
py
4,684
python
en
code
0
github-code
13
13298265308
""" Data.py provides command line convenience access to the modules in the housinginsights.sources directory. Here is a brief explanation. BRIEF EXPLANATION ----------------- Use this script to download a csv file from an API. Specify the output file with the -o flag. Specify whatever parameters you need with --param...
jgordo04/housinginsights_temp
python/cmd/data.py
data.py
py
4,027
python
en
code
0
github-code
13
5891355685
import sys import numpy as np from fwl.helpers import most_common class KNN: def __init__(self, k: int = 1): self.k = k def fit(self, X: np.ndarray, y: np.ndarray, w: np.ndarray) -> None: self.X_train = X self.y_train = y self.w_train = w def predict(self, examples: np.nd...
mayoras/FWL-Metaheuristic
fwl/knn.py
knn.py
py
1,807
python
en
code
0
github-code
13
43896859182
class Person: country = "Bangladesh" def takeBreak(self): print('I am breathing...') class Employee(Person): company = "Honda" def getSalary(self): print(f"Salary is {self.salary}") def takeBreak(self): print('I am an Employee so I am breathing') class Programmer(Employee...
inadia748/PythonByHarry
Inheritance/4-multilevelinheritance.py
4-multilevelinheritance.py
py
597
python
en
code
0
github-code
13