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
40347657143
# Fill these in from your Azure app (see https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app). CLIENT_ID = 'YOUR_CLIENT_ID' CLIENT_SECRET = 'YOUR_CLIENT_SECRET' # App redirect URI and allowed scopes. REDIRECT_URI = 'http://localhost:5000/login/authorized' SCOPES = [ "User.Read", ...
KasumiL5x/PyTeamsExporter
app_config.py
app_config.py
py
785
python
en
code
1
github-code
13
3402293306
# import the necessary packages from imutils import contours from skimage import measure import numpy as np import argparse import imutils import cv2 from google.colab.patches import cv2_imshow import PIL import os def cropONH(imageName): left_bias = 128 output_dim = 512 def calc_gt_bounds(msk_path): gt = PIL.Ima...
pascuale2/Glaucoma-Identification
Dataset/crop_ONH.py
crop_ONH.py
py
5,108
python
en
code
2
github-code
13
71148567379
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from dateutil.parser import parse conntrack = open('conntrack.txt', 'r') #archivo conntrack date = open('date.txt', 'r')# archivo data con = [] fechas = [] for linea in open('conntrack.txt', 'r'): con.append(linea) for fecha in date.readli...
amcabezas/grafico-conntrack-python
grafico_conntrack.py
grafico_conntrack.py
py
692
python
es
code
0
github-code
13
15798625578
a = [1, 4.9,"dhruv", 1+5j, 2, 54.88, "patel", 9+6j, 2, 8.44] #ans2 lst = [1, 2.5, "Consultadd", 1+2j, 2] print(lst[::-1]) print(lst[::2]) print(lst[2:]) print(lst[:3]) #ans3 lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] lst1 = 0 lst2 = 1 for i in lst: lst1 += i for i in lst: lst2 *= i print("Sum of all numbers in the ...
pdhruv1805/consultadd
assignment3.py
assignment3.py
py
1,178
python
en
code
0
github-code
13
27736259266
import time from tkinter import * from tkinter import messagebox # creating Tk window root = Tk() root.geometry("300x250") root.title("Time Counter") # Declaration of variables hour = StringVar() minute = StringVar() second = StringVar() # setting the default value as 0 hour.set(" 00") minute.set(" 00") second.s...
Swapnil-Singh-99/PythonScriptsHub
timer/main.py
main.py
py
1,934
python
en
code
19
github-code
13
15447884553
#/usr/bin/python import csv import sys import argparse import torch from torch import nn import torch.nn.functional as F from tqdm import tqdm import os import torchvision.models as models from torch.utils.data import DataLoader, Dataset import torchvision.transforms as transforms import json from PIL import Image im...
iacercalixto/visualsem-kg
multisense/multi_train.py
multi_train.py
py
16,396
python
en
code
2
github-code
13
18915488230
given_list=[{'first':'1'},{'second':'2'},{'third':'1'},{'four':'5'},{'five':'5'},{'six':'9'},{'seven':'7'}] i=0 req_list=[] while i<len(given_list): for item in given_list[i]: value=given_list[i][item] if value not in req_list: req_list.append(value) i+=1 print(req_list) # how to imp...
gmswati/Dictionary_Meraki
Q7.py
Q7.py
py
363
python
en
code
0
github-code
13
14386235805
# # @lc app=leetcode.cn id=144 lang=python3 # # [144] 二叉树的前序遍历 # from collections import deque from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # @lc code=start # Definition for a binary tree node....
largomst/leetcode-problem-solution
144.二叉树的前序遍历.2.py
144.二叉树的前序遍历.2.py
py
1,078
python
en
code
0
github-code
13
32986673794
import PyPDF2 from openpyxl import Workbook import os workbook_stock = Workbook() workbook_tax = Workbook() # Select the active sheet sheet_stock = workbook_stock.active sheet_tax = workbook_tax.active stock_feature=["Date","Order Number","Trade Number","Security/Contract Description","Buy/Sell","Qty"] tax_feature=...
PonnaSrikar/collecting-data-from-pdf-of-stocks-and-tax-then-creating-elx-using-python
creating_app_for_shinde.py
creating_app_for_shinde.py
py
1,761
python
en
code
0
github-code
13
20886800929
from models.calcular import Calcular def main() -> None: pontos: int = 0 # Iniciando o jogo com 0 pontos. jogar(pontos) def jogar(pontos: int) -> None: # Função principal # Recebendo a dificuldade do jogo dificuldade: int = int(input("Informe o nível de dificuldade desejado [1, 2, 3 ou 4]:")) ...
ari-barbosa/Game-operacoesPy
game.py
game.py
py
1,186
python
pt
code
1
github-code
13
31993684505
# Criar pequenas listas para mostrar os elementos contidos nelas lista_de_fruta = ['banana', 'maça', 'uva', 'abacate', 'laranja', 'limao', 'melao'] for frutas in lista_de_fruta: print(frutas) #Conte a quantidade de frutas na lista lista_de_frutas contador = 0 for frutas in lista_de_fruta: conta...
jemalicisou/Python-basico
estruturas_de_laco_python.py
estruturas_de_laco_python.py
py
998
python
pt
code
0
github-code
13
24718332124
import numpy as np from scipy.stats import gamma from matplotlib import pyplot as plt import seaborn as sns def m1(env_state): return env_state["t"] def m2(env_state): time_since = list(reversed(env_state["rews"][:(env_state["t"]+1)])).index(env_state["rewsize"]) return time_since def m3(env_state): ...
sternj98/patchForagingQLearning
integrators_demo.py
integrators_demo.py
py
2,382
python
en
code
2
github-code
13
30933676745
import numpy as np import tensorflow as tf class PolicyGradient: def __init__(self, min_action, max_action, feature_size, hidden_units=10, learning_rate=0.01, gamma=0.95, tf_log_dir=None): self.min_action = min_action self.max_action = max_action self.feature_size = featur...
zengxy/rl_exercise
learner/PolicyGradient_Continuous.py
PolicyGradient_Continuous.py
py
3,465
python
en
code
0
github-code
13
20244910544
import sys n=int(sys.stdin.readline()) s=[] for i in range(n): m=sys.stdin.readline().split() if m[0]=='push': s.append(m[1]) elif m[0]=='top': print(s[-1] if s else -1) elif m[0]=='pop': print(s.pop() if s else -1) elif m[0]=='size': print(len(s)) elif m[0]=='empty': print(0 if s else ...
chaeyeon-yang/Algorithm
new/datastructure/10828.py
10828.py
py
322
python
en
code
0
github-code
13
29807397956
import fcntl from pathlib import Path lock_file_path = Path(Path('/tmp') / 'lyrebird.lock') def place_lock(): ''' Places a lockfile file in the user's home directory to prevent two instances of Lyrebird running at once. Returns lock file to be closed before application close, if `None` returned th...
lyrebird-voice-changer/lyrebird
app/core/lock.py
lock.py
py
737
python
en
code
1,770
github-code
13
4818769380
def dfs(k, graph, visited): visited[k] = 1 for i in range(len(graph[k])): if visited[i] == 0 and graph[k][i] == 1: dfs(i, graph, visited) def solution(n, computers): visited = [0] * n answer = 0 for i in range(n): if visited[i] == 0: dfs(i, computers, visite...
gilbutITbook/080338
12장/네트워크.py
네트워크.py
py
367
python
en
code
32
github-code
13
43084839642
# # @lc app=leetcode.cn id=653 lang=python3 # # [653] 两数之和 IV - 输入 BST # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findTarget(se...
Guo-xuejian/leetcode-practice
653.两数之和-iv-输入-bst.py
653.两数之和-iv-输入-bst.py
py
900
python
en
code
1
github-code
13
4555187047
import json from datetime import datetime from dashboard.models import Complaint, Notification, serialize from dashboard.views.Customers import extractComplaintObj from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.shortcuts import redirect @login_required def...
avisionx/fms-portal-iiitd
dashboard/views/Common.py
Common.py
py
1,679
python
en
code
0
github-code
13
38424605822
from models.template import * class User(Template): meta = { 'db_alias': 'youtube', 'collection': 'User' } index = { "id": None } fields = { "id": {"type": "string"}, "name": {"type": "string", "xpath": "//*[@id='text-container']"}, "subscriber_count...
t4iv0i/multiplatform_crawler
models/youtube/user.py
user.py
py
1,033
python
en
code
1
github-code
13
18396323614
### SNEK GAME ### # just another snek game # -dsplayerX # # from tkinter import * import random # Game space parameters GAME_WIDTH = 600 GAME_HEIGHT = 600 SPACE_SIZE = 30 # Starting snake size BODY_PARTS = 3 # Snake speed parameters START_SPEED = 120 MAX_SPEED = 20 SPEED_REDUCTION = 2 # Color values for background...
dsplayerX/Snek-Game
snek.py
snek.py
py
6,295
python
en
code
0
github-code
13
2883610088
from absl.testing import absltest from absl.testing import parameterized import flax import jax import numpy as np from sam.sam_jax.models import load_model class LoadModelTest(parameterized.TestCase): # Parametrized because other models will be added in following CLs. @parameterized.named_parameters( ('Wi...
google-research/sam
sam_jax/models/load_model_test.py
load_model_test.py
py
1,617
python
en
code
492
github-code
13
25240501376
from itertools import count as count_from LANGUAGE = { 'А': 0, 'Б': 1, 'В': 2, 'Г': 3, 'Д': 4, 'Е': 5, 'Ж': 6, 'З': 7, 'И': 8, 'К': 9, 'Л': 10, 'М': 11, 'Н': 12, 'О': 13, 'П': 14, 'Р': 15, 'С': 16, 'Т': 17, 'У': 18, 'Ф': 19, 'Х': 20, 'Ц': 21, 'Ч': 22, 'Ш': 23, 'Щ': 24, 'Ъ': 25, 'Ы': 26, 'Ь'...
RMalsonR/Crypt
Block Ciphers/bigram_cipher_ports.py
bigram_cipher_ports.py
py
2,304
python
en
code
0
github-code
13
8036345543
#!/usr/bin/python3 """ Fewest coins for change""" def makeChange(coins, total): """ fewest number of coins to meet total """ if total <= 0: return 0 coins.sort(reverse=True) change = 0 for coin in coins: if total <= 0: break remainder = total // coin c...
Muna-Redi/alx-interview
0x08-making_change/0-making_change.py
0-making_change.py
py
431
python
en
code
0
github-code
13
2055340453
import numpy as np import matplotlib.pyplot as plt import seaborn as sns arr = np.array([1,2,3,4,5]) print(arr) print(type(arr)) #no different between tuple and list arr = np.array((1, 2, 3, 4, 5)) print(arr) print(type(arr)) #Scalar or 0-D arrays scalar = np.array(42) print(scalar) print(type(scalar))...
hatimbenjebara/numpy_in_python
numpy_lib.py
numpy_lib.py
py
13,365
python
en
code
1
github-code
13
2609945827
from random import randint b = randint(1, 6) a = input("Do you want to roll the die: ") while (a=="yes"): b = randint(1, 6) print("Dice rolling...") print(b,"\n") a = input("Do you want to roll the die: ") print("Thanks for playing")
Aadhithr/Personal
PythonWork/PythonCourse/homework/uses_random/diceSimulator.py
diceSimulator.py
py
257
python
en
code
0
github-code
13
7067614679
from draftfast.orm import Player from typing import Optional from copy import deepcopy class ShowdownPlayer(Player): def __init__( self, player: Player, captain: bool = False, pos: Optional[str] = None ): for k, v in player.__dict__.items(): if hasattr(self,...
sam1rm/draftfast
draftfast/showdown/orm.py
orm.py
py
1,406
python
en
code
null
github-code
13
22337977927
#!/bin/env python import random, redis teams = ['ARG','BWS','BWS2','BGR','BRK','BSG','CLF','CLF2','EMM','GRS','GMR','HRS','HZW','MFG','MUC','PSC','PSC2','QEH','QMC','SEN','SEN2','TTN'] actor = redis.Redis(host='localhost',port=6379,db=0) def game_points(score): total = 0 total += int(score[2]) ...
Scarzy/compd_test
scoremaker.py
scoremaker.py
py
835
python
en
code
2
github-code
13
42855697480
#!/usr/bin/env python3 import os import time import hashlib from pathlib import Path from functools import lru_cache import logging import fire from tqdm import tqdm import pandas as pd import numpy as np BASE_PATH = Path.cwd() LOG_PATH = BASE_PATH / 'log' LOG_PATH.mkdir(parents=True, exist_ok=True) class Logger(ob...
rlditr23/RL-DITR
ts/datasets/pipe.py
pipe.py
py
42,396
python
en
code
10
github-code
13
38390639103
price=1000000 is_goodcredit=False is_goodcredit=True print(is_goodcredit) if is_goodcredit: print("Put down price by 10%") #price=price-0.1*price downpayment=0.1*price price-=0.1*price #print(price) else: print("Put down price by 20%") # price=price-0.2*price downpayment = 0.1 * price ...
NiyatiSinha-yb/PYTHON-Codes-By-Niyati-Sinha
Python Codes by NIYATI SINHA/app18.py
app18.py
py
421
python
en
code
1
github-code
13
73370907856
from tensorflow.keras.applications import ResNet50 from tensorflow.keras.applications.resnet import preprocess_input from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.applications import imagenet_utils from imutils.object_detection import non_max_suppression from detection_helper ...
BasitJaved/Object-Detection
Object-Detection-using-preTrained-CNN/detect_with_classifier.py
detect_with_classifier.py
py
5,631
python
en
code
0
github-code
13
43261922442
def main(): a = sorted(set(ai for ai, _ in AB)) a_dic = {a[i]: i+1 for i in range(len(a))} b = sorted(set(bi for _, bi in AB)) b_dic = {b[i]: i+1 for i in range(len(b))} for ai, bi in AB: print(a_dic[ai], b_dic[bi]) return if __name__ == '__main__': H, W, N = map(int, input().spli...
Shirohi-git/AtCoder
abc211-/abc213_c.py
abc213_c.py
py
398
python
en
code
2
github-code
13
13960225778
from sqlalchemy import create_engine, text db_connection_string = "mysql+pymysql://2tbapi8bc3m9cvx8pnww:pscale_pw_10YnHMfHSznFMKXdkv2uL0FzkGIzEKh9Dx9hyjKJmol@aws.connect.psdb.cloud/sdn_test01?charset=utf8mb4" engine = create_engine(db_connection_string, connect_args={"ssl": { ...
Thipekesh28/SDN_TESTCASE_01
database.py
database.py
py
586
python
en
code
0
github-code
13
23111651618
from src.parsing.DataReader import DataReader import os import pickle import datetime PRECIPITATION_THRESHOLD = 1.25 # inches of precipitation def compute_monthly_deviation(): # Load weather data weather_pickle_path = os.path.join('data', 'serialized', 'weather_data_by_day.pkl') weather_data = load_weat...
ReeseHatfield/DataDynamics
src/weather_analysis/computation/compute_monthly_deviation.py
compute_monthly_deviation.py
py
4,166
python
en
code
0
github-code
13
27188594093
import sys input = sys.stdin.readline A, B, C = map(int, input().split()) def find(A, B, C): if B == 1: return A % C else: s = find(A, B // 2, C) if B % 2 == 0: return s * s % C else: return s * s * A % C print(find(A, B, C))
Nam4o/Algorithm
백준/Silver/1629. 곱셈/곱셈.py
곱셈.py
py
307
python
en
code
1
github-code
13
43261653442
from heapq import heappop, heappush def weighted_nearlist(N): mat = [[-1] * N for _ in range(N)] for a, b, c in abc: if mat[a - 1][b - 1] > c or mat[a - 1][b - 1] < 0: mat[a - 1][b - 1] = c NEAR = [set() for _ in range(N)] for i in range(n): for j in range(n): i...
Shirohi-git/AtCoder
abc191-/abc191_e.py
abc191_e.py
py
1,176
python
en
code
2
github-code
13
10160033295
import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv("data_tiempo.csv") # Sin sdc df_00 = df[df['prob_entrar'] == 0.2] choque_normal_00 = 0 for i in range(df_00.shape[0]): for choque in eval(df_00["datos_choques"][df_00.index[i]]): max_velocity = max(choque[4],choque[1])...
Bony2002/TP_APN
plots/plot_2.py
plot_2.py
py
3,743
python
en
code
0
github-code
13
34766394040
import logging import re from abc import ABC from piicatcher.log_mixin import LogMixin from piicatcher.scanner import ColumnNameScanner, NERScanner, RegexScanner from piicatcher.piitypes import PiiCategories class NamedObject(ABC, LogMixin): def __init__(self, name, include, exclude): self._name = name ...
dm03514/piicatcher
piicatcher/explorer/metadata.py
metadata.py
py
5,610
python
en
code
null
github-code
13
18659411184
import boto3 import json import yelp_fusion_api import datetime #api_key="-5dBnE7ZnbVw1RshcBve1t-Ayg00nnw4PEMj-in726bQM4jODmHTgdUKIEQXzKKgq4hrainJdwniItyA5tZOFg71e9yrEDuqa-tDoxlPpxxzFtQ20Jlr6AcSXRDlW3Yx" API_HOST = 'https://api.yelp.com' SEARCH_PATH = '/v3/businesses/search' #details = {"area": "Manhattan", "time":...
dhruvarora2/Yelper
Backend/aws lambdas/vYelper-sqs_Handler/yelp_handler.py
yelp_handler.py
py
2,386
python
en
code
0
github-code
13
6343660440
import bs4 import requests def getip(): try: step = '0' s = requests.get('https://2ip.ua/ua/') step = '1' b = bs4.BeautifulSoup(s.text, "html.parser") step = '2' a = b.select(" Ваша IP адреса")[0].getText() step = '3' a = a.strip() ...
NSWPro/AVIASTSStatus
myip.py
myip.py
py
540
python
ru
code
0
github-code
13
18145777119
io = start() exploit = f"%198$p" io.sendline(exploit) io.recvuntil(b"Your input is:") io.recvline() leaked_rbp = io.recvline(keepends=False) rip= int(leaked_rbp, 16)-72 buf=b"%058038d%83$hn"+p64(rip) io.sendline(buf)
aditya70/ss-course
parch/share/2.py
2.py
py
217
python
en
code
0
github-code
13
33759115361
"""Helpful functions for de-wedging research.""" import itertools import logging import os import numpy as np from astropy import constants def get_coverage(antpos, freqs, bin_edges=None, mode="u"): """ Determine the number of baselines that sample each mode. Unless bin edges for an array of u(vw)-modes...
HERA-Team/hera_sandbox
rfp/scripts/dewedge/utils.py
utils.py
py
5,062
python
en
code
1
github-code
13
28892475070
from batchrunner import BatchRunnerMP from model import BeeEvolutionModel from agents import * import argparse import pickle def main(): """ This function should run the model for the global sensitivity anlysis, using the datafile variable_parameters.pickle. In that file there are all the set of parameters produ...
AnkurSatya/uva_abm_bumblebee
bumblebee_evolution/batch_run.py
batch_run.py
py
1,140
python
en
code
1
github-code
13
808942212
"""Trains and evaluates a given model. Also constructs Kaggle submissions, and save various plots (e.g. confusion matrix, learning curve) and pickled models to files with a unique id. """ import argparse import numpy as np import pandas as pd from keras.utils import to_categorical import matplotlib.pyplot as plt from...
christabella/music-genre-classification
classifiers.py
classifiers.py
py
6,740
python
en
code
0
github-code
13
21254109776
class Solution: # @param A : list of list of integers # @param B : integer # @return an integer def solve(self, A, B): n = len(A) m = len(A[0]) h = [] for i in range(n): for j in range(m): if len(h) < B: h.append(A[i][j]) ...
sundar91/dsa
Heap/Bth-smallest-element.py
Bth-smallest-element.py
py
1,329
python
en
code
0
github-code
13
74429731217
import Preprocess as pp import re import nltk from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer from sklearn.ensemble import RandomForestClassifier import pandas as pd import numpy as np def reviewsToWords(review): letters_only = re.sub("[^a-zA-Z]", # The pattern to...
Eimisas/Sentimental-analysis
Code/Random forest/BagOfWords.py
BagOfWords.py
py
3,613
python
en
code
0
github-code
13
9368008419
import asyncio import aiohttp_cors from aiohttp import web from routes import setup_routes from settings import load_configuration def set_cors(app): # Configure default CORS settings. cors = aiohttp_cors.setup(app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, ...
jindada1/Relaxion
main.py
main.py
py
1,199
python
en
code
5
github-code
13
10511718601
from mod_python import apache, Session from mod_python import util from xml.dom.minidom import getDOMImplementation, parse, parseString import urllib #tutkitaan, onko sivulle tulija kirjautunut vai ei #näytetään kirjautumissivu, jos ei def handler(req): try: if req.session["kirjautunut"] == "ok": ...
helireki/TIEA218-15
demo4/autentikointi.py
autentikointi.py
py
1,500
python
fi
code
0
github-code
13
41149702163
# Third-party libraries import os import numpy as np # Set paths to folders def set_paths(): # Path to the output folder work_dir = '../work/' if not os.path.exists(work_dir): sys.exit('WORKING FOLDER DOES NOT EXIST!') # Path to the data directory data_dir = work_dir + 'data/...
aiskhak/NN_PDE
CS1/inout.py
inout.py
py
2,751
python
en
code
0
github-code
13
39575906903
my_array = [] def helper(n, target, index, temp_arr, temp_sum): # print(temp_sum, temp_arr) if temp_sum == target: my_array.append(temp_arr.copy()) return if index == len(n): return if temp_sum > target: return temp_arr.append(n[index]) temp_sum += n[index] ...
KillerStrike17/CP-Journey
Codein10/BackTracking/Combination_sum_II.py
Combination_sum_II.py
py
841
python
en
code
0
github-code
13
29208173553
''' Python module dependencies: biopython==1.63 fastcluster==1.1.13 numpy==1.7.1 python-Levenshtein==0.11.2 scipy==0.12.0 Under Ubuntu, scipy, numpy and biopython can be installed as: sudo apt-get install python-biopython python-numpy python-scipy fastcluster and python-Levenshtein can be installed using pip: pip ...
SuLab/Antibody-Clustering-Challenge
original_python_code.py
original_python_code.py
py
8,052
python
en
code
1
github-code
13
11069452254
from bson import ObjectId import uuid import sqlalchemy as db from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import relationship, synonym __all__ = [ 'MongoReference', 'MongoEmbedded', 'MongoEmbeddedList', 'Base', 'UserBase',...
closeio/flask-common
flask_common/db.py
db.py
py
3,814
python
en
code
26
github-code
13
70730835219
W_str = r"W" + r"\rightarrow" + r"l" + r"\nu_{l}" Z_str = r"Z" + r"\rightarrow" + r"l^{+}" + r"l^{-}" ttbar_str = r"t" + r"\bar{t}" config = { "Luminosity": 10064, "InputDirectory": "results", "Histograms" : { "WtMass" : {}, "etmiss" : {}, "lep_n" : {}, "lep_pt" ...
jegarcian/hep-ml
createImages/Configurations/PlotConf_TTbarAnalysis.py
PlotConf_TTbarAnalysis.py
py
2,385
python
en
code
0
github-code
13
21521017043
from model import kwsmodel import os import tensorflow as tf from tqdm import tqdm from tensorflow.keras import optimizers from dataloader import train_iterator from utils import * def train_step(model, images, labels, optimizer): with tf.GradientTape() as tape: prediction = model(images, tra...
yuyun2000/kws
train.py
train.py
py
2,599
python
en
code
1
github-code
13
29188020072
import numpy as np class StateSpace: # Classical canonical state space time simulation def __init__(self, n=0, p=0, q=0): self.n = n self.p = p self.q = q self.u = np.zeros(shape=p) self.A = np.zeros(shape=(n, n)) self.B = np.zeros(shape=(n, p)) self.C ...
davegutz/myStateOfCharge
SOC_Particle/Battery State/EKF/sandbox/StateSpace.py
StateSpace.py
py
4,669
python
en
code
1
github-code
13
11148196810
from curses import raw import pytest from unittest.mock import Mock, patch import json import numpy as np from copy import deepcopy from uuid import uuid4 import tasks.cluster_texts as clusterer from tasks.cluster_texts import KeywordItem from tests.data.fixtures import ( CLUSTERED_DATA, NESTED_DATA, MULTI...
visda-app/service-mapping
tests/tasks/test_clusterer.py
test_clusterer.py
py
5,866
python
en
code
0
github-code
13
1228993977
import urllib.request, urllib.parse, urllib.error import json # Resets calls to 0 if worldclockapi indicates new day def check(current, calls): # Connect with worldclockapi url = 'http://worldclockapi.com/api/json/est/now' doc = urllib.request.urlopen(url) data = doc.read().decode() # Create JSON o...
aidenszeto/Dictionary-Bot
timer.py
timer.py
py
940
python
en
code
2
github-code
13
39686495582
"""Test case.""" # -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import sys import traceback import unittest from eql import Schema from eql.ast import * # noqa: F403 from eql.errors import EqlSchemaError, EqlSyntaxError, EqlSemanticError, EqlTypeMismatchError, EqlParseError from eql.p...
endgameinc/eql
tests/test_parser.py
test_parser.py
py
39,771
python
en
code
203
github-code
13
41410155928
#import pandas as pd import matplotlib.pyplot as plt def bubbleSort(lista, listaCount): for i in range(len(lista)): for j in range(len(lista)): if int(lista[int(i)]) < int(lista[int(j)]): lista[int(i)], lista[int(j)] = lista[int(j)], lista[int(i)] listaCount[int(...
BrunoViotto18/Bosch
1 - Python/Aula 76 - 20_12_2021 - REVISÃO PYTHON/Revisão - SemiCópia/ExercicioEdjalma.py
ExercicioEdjalma.py
py
3,216
python
pt
code
0
github-code
13
5293963074
import pickle import matplotlib.pyplot as plt import pandas as pd import numpy as np def plot_result(fin_data_df, titulo, columna, y_label, idx, per_long=730): x = fin_data_df['Dates'][idx:idx+per_long] y = fin_data_df.iloc[idx:idx+per_long, columna] plt.figure(figsize=(8, 6)) plt.plot(x, y, ...
falamo1969/AgenteInversionTFM
graficos.py
graficos.py
py
1,192
python
en
code
0
github-code
13
16007318470
import torch import numpy as np import nimblephysics as nimble from solver.envs.rigidbody3d.r3d_pickup import PickUp from solver.train_rpg import Trainer from solver.envs.rigidbody3d.hooks import print_gpu_usage, record_rollout from solver.envs.rigidbody2d.hooks import save_traj from solver.envs.rigidbody3d.utils impor...
haosulab/RPG
solver/envs/rigidbody3d/r3d_pick3cube.py
r3d_pick3cube.py
py
7,681
python
en
code
18
github-code
13
70061790099
import sys from socket import * import zlib # There is no need for Bob to detect end of transmission and terminate. If you need to # manually terminate it, press <Ctrl> + c. #Algorithm planning #Global variables are here and initialised clientAddress = 0 serverPort = int(sys.argv[1]) #Get the arguments bobSocke...
Deunitato/CS2105_Assignments
meh/Bob.py
Bob.py
py
4,334
python
en
code
0
github-code
13
29113393906
def divide_errors(y_pred, y_test): wrong_indices = {} for i, (pred, ans) in enumerate(zip(y_pred, y_test)): if pred != ans: wrong_indices.setdefault(f"{ans}-{pred}", []) wrong_indices[f"{ans}-{pred}"].append(i) return wrong_indices def count_pred_labels(y): # count each ro...
Kumamoto-Hamachi/knn_projects
divide.py
divide.py
py
939
python
en
code
1
github-code
13
44625095981
import numpy as np from torch.utils.data import Dataset import os from PIL import Image as Image import random import torch def random_crop(lr, hr, size, scale): lr_left = random.randint(0, lr.shape[1] - size) lr_right = lr_left + size lr_top = random.randint(0, lr.shape[0] - size) lr_bottom = lr_top ...
bigbye/RDN-SISR
code/custom_datasets.py
custom_datasets.py
py
3,002
python
en
code
1
github-code
13
28905282158
#! /usr/bin/python # -*- coding: utf-8 -*- import re,string #import data_structure def Save(lineid,sub,dec,output_file): new_line = str(lineid) + "/dec:" + dec for s in sub: if not s[1] == "-": input_sub = s[1] #主語 else: input_sub = "-" new_line = new_line + ",...
pauwau/workspace
knp_distance/text_to_frame/ex_relates.py
ex_relates.py
py
1,748
python
en
code
0
github-code
13
613750536
#!/usr/bin/env python3 #coding: utf8 import lib import numpy as np import matplotlib.pyplot as plt def delta(x,x0,N=1): ''' should only be used on-grid. Implementation of the Dirac-delta. ''' return N*np.isclose(x,x0) class initialValues: ''' Just a storage for initial values. Can be used in ...
alcubierre-drive/NTNU-TFY4235-2018
Assignments/PartialDifferentialEquations/helpers.py
helpers.py
py
3,942
python
en
code
0
github-code
13
32406715272
import argparse import rospkg import json import cv2 import numpy as np import os.path class mapDetails: def __init__(self, args): self.shelves = list() self.shelves_h = list() self.capture_stops = list() rospack = rospkg.RosPack() base_path = rospack.get_path('storeplanner') map_filename ...
vrai-group/storeplanner
scripts/map_details.py
map_details.py
py
4,227
python
en
code
0
github-code
13
36115388685
import cv2 import numpy as np def translate(img, translation, target_size=None): ''' Translates an image by a particular amount. translation: x, y target_size: w, h ''' tx, ty = translation translation_matrix = np.float32([ [1,0,tx], [0,1,ty]]) return _warp_affine(img, translation_mat...
carnotresearch/cr-vision
src/cr/vision/geom/projective2d_actions.py
projective2d_actions.py
py
1,825
python
en
code
2
github-code
13
10006307763
#!/usr/bin/python2 ''' DAVID LETTIER (C) 2016. http://www.lettier.com/ Slackotron ''' import sys import os import subprocess import signal import time execfile( '../bin/activate_this.py', dict(__file__='../bin/activate_this.py') ) ENV = os.environ.copy() ENV['PYTHONPATH'] = ":".join(sys.path) SLA...
lettier/slackotron
run.py
run.py
py
580
python
en
code
16
github-code
13
30918365173
# https://gist.github.com/NikolayOskolkov/277d65621267658e71d06eb59b577e44#file-autoencoderciteseq-py # Input Layer ncol_scRNAseq = X_scRNAseq.shape[1] input_dim_scRNAseq = Input(shape = (ncol_scRNAseq, ), name = "scRNAseq") ncol_scProteomics = X_scProteomics.shape[1] input_dim_scProteomics = Input(shape = (ncol_sc...
zkxshg/Test_of_machine_learning
cite_AutoencoderCITEseq.py
cite_AutoencoderCITEseq.py
py
2,012
python
en
code
0
github-code
13
19602662290
import json from rediscluster import RedisCluster import redis import os #rc = RedisCluster(host=os.getenv('REDIS'), port=6379, decode_responses=True) rc = redis.Redis(host=os.getenv('REDIS'), port=6379, decode_responses=True) def initExclude(): """Add the defualt list to redis""" # Opening JSON file f...
mantiser-com/finder-email
exclude/initExclude.py
initExclude.py
py
863
python
en
code
0
github-code
13
72678372498
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging import torch import torch.nn as nn import numpy # from DCNv2 import dcn_v2_conv, DCNv2, DCN # from DCNv2 import dcn_v2_pooling, DCNv2Pooling, DCNPooling # import layers.ConvOffset2D ...
chenrobin/DVLPose-
lib/models/deformation.py
deformation.py
py
17,661
python
en
code
0
github-code
13
17092790154
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.OperatorBaseInfo import OperatorBaseInfo class KoubeiMerchantOperatorSearchQueryResponse(AlipayResponse): def __init__(self): super(KoubeiMerchantOperato...
alipay/alipay-sdk-python-all
alipay/aop/api/response/KoubeiMerchantOperatorSearchQueryResponse.py
KoubeiMerchantOperatorSearchQueryResponse.py
py
1,360
python
en
code
241
github-code
13
15939874987
import ctypes.wintypes from pathlib import Path from typing import Union import aiofiles def align(_string, _length, _type='L') -> str: """ Look at https://www.jianshu.com/p/74500b7dc278 中英文混合字符串对齐函数 :param _string:[str]需要对齐的字符串 :param _length:[int]对齐长度 :param _type:[str]对齐方式('L':默认,左对齐;'R'...
Senvlin/AnimeCrawler
AnimeCrawler/utils/file.py
file.py
py
2,917
python
en
code
1
github-code
13
38006098118
### configure trigger filters if len(primRPVLLDESDM.VH_DV_triggerFilterFlags.TriggerNames) == 0: if rec.triggerStream() == "Egamma": primRPVLLDESDM.VH_DV_triggerFilterFlags.TriggerNames = primRPVLLDESDM.VH_DV_triggerFilterFlags.EgammaTriggerNames elif rec.triggerStream() == "JetTauEtmiss": prim...
rushioda/PIXELVALID_athena
athena/PhysicsAnalysis/SUSYPhys/LongLivedParticleDPDMaker/share/PhysDESDM_VH_DV.py
PhysDESDM_VH_DV.py
py
9,185
python
en
code
1
github-code
13
7159983981
from django.http import HttpResponse from django.shortcuts import render #from conf import access_token,refresh_token from codechef_mayukh45.MAIN import get_college import sys #username = "" #friends = [] own_college = 0 friends_college = 0 import time def index(request): global own_college global friends_c...
mayukh45/Ranklist_App
codechef_mayukh45/creation/views.py
views.py
py
1,999
python
en
code
0
github-code
13
1590015
from collections import deque def bfs(graph: dict[int, list[int]], start: int) -> list[int]: """ V = number of vertices in the graph E = number of edges in the graph ------------- Time: O(V + E) Space: O(V) """ q = deque([start]) visited = {start} res = [] while q: ...
ironwolf-2000/Algorithms
Graphs/Traversals/BFS/bfs.py
bfs.py
py
708
python
en
code
2
github-code
13
2244821279
""" Overview ======== This plugin attempt to set the actual project attribute for the current AreaVi instance. It tries to find project folders like .git, .svn, .hg or a ._ that's a vy project file. """ from os.path import exists, dirname, join from vyapp.stderr import printd def get_sentinel_file(path, *args): ...
vyapp/vy
vyapp/plugins/project.py
project.py
py
1,236
python
en
code
1,145
github-code
13
23015863407
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter class WeatherPipeline(object): def open_...
leng-bing-bing/homework
6/weather/weather/pipelines.py
pipelines.py
py
1,045
python
en
code
1
github-code
13
70161175699
from __future__ import annotations from abc import ABC, abstractmethod from typing import Type, Tuple import discord from difflib import get_close_matches from disputils import BotMultipleChoice class OSBcmd(ABC): """ Command Patter Interface. """ @abstractmethod async def execute(self, **kwar...
jarrett-m/OnStudy_Bot
source/osb_commands.py
osb_commands.py
py
3,281
python
en
code
0
github-code
13
5832468796
#!/usr/bin/env python # coding: utf-8 # This reads from HD5 files and sends over network. # This file sends drone position data over a server as x, y, z by sending at the right timestamp. # Change the HOST and PORT variables accordingly. import h5py import numpy as np import math import struct import time import sock...
immersive-command-system/RadiationVisualization
LBL/GeneratePosData.py
GeneratePosData.py
py
1,666
python
en
code
3
github-code
13
10844205105
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Assignment in BMP course - Program Mapping Table parser Author: Jakub Lukac E-mail: xlukac09@stud.fit.vutbr.cz Created: 22-10-2019 Testing: python3.6 """ import sys from descriptor import parse_descriptors from psi import PSI class PMT(PSI): def ...
cubolu/School-Projects
Python/BMS/dvb-t/pmt.py
pmt.py
py
4,701
python
en
code
0
github-code
13
14530341692
import pandas as pd import networkx as nx import numpy as np import time def build_year(year): print('start') file_read = 'pruned_data/pruned_data_{}.csv'.format(year) df_actual = pd.read_csv(file_read) # reformat so triangle generator can differentiate df_actual['defense'] = 'Defense_' + df_actu...
abeard1/IndependentStudy
src/build_df_possibles.py
build_df_possibles.py
py
2,229
python
en
code
0
github-code
13
6991250955
import pandas as pd import numpy as np data = pd.read_csv("raions.csv") cat = ["young_", "work_", "ekder_"] man = ["all", "male", "female"] tar = "raion_popul" for i in cat: for j in man: data[i + j] = data[i + j] / data[tar] data.to_csv("raions_popul_percentaged.csv", index=None)
ZiyaoLi/KaggleSberbank
codes_and_preprocessed_data/preproc_&_feature_eng_codes/cnt2pct_raion_popul.py
cnt2pct_raion_popul.py
py
298
python
en
code
0
github-code
13
27563472500
############################################# # CSC 242 Section 602 Spring 2017 # Lab 3: User-defined classes # # LEXUS NGUYEN # # Fill in the 4 methods below. Also, # be sure to define the distance method # in the Point class (in the point.py file) ############################################# from point ...
nguyenlexus/work
CSC242/triangle.py
triangle.py
py
1,764
python
en
code
0
github-code
13
37502785864
""" @author: Hayeon Lee 2020/02/19 Script for downloading, and reorganizing CUB few shot Run this file as follows: python get_data.py """ import pickle import os import numpy as np from tqdm import tqdm import requests import tarfile from PIL import Image import glob import shutil import pickle def download_file(...
YuanWanglll/l2b
data/cub/get_data.py
get_data.py
py
2,652
python
en
code
null
github-code
13
9984220361
# -*- coding: utf-8 -*- ############################################### #created by : lxy #Time: 2018/06/28 14:09 #project: Face recognize #company: Senscape #rversion: 0.1 #tool: python 2.7 #modified: #description opencv face detector #################################################### import os import sys impo...
jimeffry/face-anti-spoofing
src/face_test/Detector.py
Detector.py
py
9,170
python
en
code
37
github-code
13
74005965139
import importlib import logging from collections import defaultdict from axel import Event from hmcs import config log = logging.getLogger(__name__) class PluginManager(): def __init__(self): self.system_init = Event() self.socket_event_received = Event() self.socket_event_received += se...
Flid/hmcs
server/hmcs/plugins/base.py
base.py
py
1,682
python
en
code
0
github-code
13
6693206925
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: l = [] r = [] for x in nums: if x % 2 == 0: l.append(x) else: r.append(x) return l + r
weastur/leetcode
941-sort-array-by-parity/main.py
main.py
py
253
python
en
code
0
github-code
13
37862132113
import numpy as np from PyAstronomy.pyaC import pyaErrors as PE class BallesterosBV_T: """ Black-body based conversion between effective temperature and B-V color. Ballesteros 2012 (EPL 97, 34008) present a conversion between effective temperature and B-V color index based on a black body spectr...
sczesla/PyAstronomy
src/pyasl/asl/aslExt_1/ballesterosBV_T.py
ballesterosBV_T.py
py
1,647
python
en
code
134
github-code
13
40242623492
''' lets say we have 2 arrays a1 = [a,b] and a2 = [c,d] Intervals can be merged if a1[0] < a2[0] => this is acheived by sorting the intervals Intervals can be merged if a2[0] < a1[1] ''' class Solution: def merge(self, intervals): intervals.sort(key =lambda x: x[0]) merged = [] for i in int...
ltoco/DSA
merge_intervals.py
merge_intervals.py
py
986
python
en
code
0
github-code
13
27227523674
from model.contact import Contact import re class ContactHelper: def __init__(self, app): self.app = app def change_field_value(self, field_name, text): wd = self.app.wd if text is not None: wd.find_element_by_name(field_name).click() wd.find_element_by_name(f...
AlexGraf71/test_python
fixture/contact.py
contact.py
py
5,085
python
en
code
0
github-code
13
29187517042
# Using sockets to transfer data between Ren'Py and MASM # TODO: Ping-Pong alive check messages import json import time import socket import threading class MASM: data = {} commThread = None serverSocket = None commRun = threading.Event() commLock = threading.Lock() @staticmethod def _startThread(): MASM._co...
DatCaptainHorse/MAS-Additions
Submods/MAS Additions/MASM/scripts/socketer.py
socketer.py
py
2,797
python
en
code
17
github-code
13
43254452311
# import sys # # sys.stdin = open('김병완_2579_계단오르기.txt', 'r') # N = int(input()) # stair = [] # for i in range(N): # stair.append(int(input())) # # dp = [] # dp.append(stair[0]) # dp.append(max(stair[0] + stair[1], stair[1])) # dp.append(max(stair[0] + stair[2], stair[1] + stair[2])) # # for j in range(3, N): # ...
KimSoomae/Algoshipda
week2(dp)/0915WED/김병완_2579_계단오르기_S3.py
김병완_2579_계단오르기_S3.py
py
736
python
en
code
0
github-code
13
17061306394
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class VehModelDto(object): def __init__(self): self._acid = None self._body_type = None self._brand_id = None self._brand_logo_url = None self._brand_name = None...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/VehModelDto.py
VehModelDto.py
py
17,811
python
en
code
241
github-code
13
5661290639
import numpy as np from scipy import constants from mantid.geometry import CrystalStructure, ReflectionGenerator, ReflectionConditionFilter from mslice.models.labels import is_momentum, is_twotheta from mslice.models.workspacemanager.workspace_provider import get_workspace_handle from mslice.util.mantid.mantid_algor...
mantidproject/mslice
src/mslice/models/powder/powder_functions.py
powder_functions.py
py
2,795
python
en
code
1
github-code
13
43356236537
data = input() result = int(data[0]) for i in range(1, len(data)): num = int(data[i]) if result <= 1 or num <= 1: # 두 수 중 하나라도 1 이하의 수라면 더하기 수행 result += num else: result *= num print(result)
tr0up2r/coding-test
greedy_algorithms/023_mul_or_add.py
023_mul_or_add.py
py
259
python
ko
code
0
github-code
13
31418984932
# # # Copyright (C) University of Melbourne 2012 # # # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify...
zarppy/MUREIL_2014
test_regression/ge_test.py
ge_test.py
py
3,072
python
en
code
0
github-code
13
32799560271
import os from python.request.endpoint.EndpointUtils import EndpointType from python.utils import ConfigUtils # Class handling the creation of Endpoint objects # In particular, it manages the corresponding urls depending on each endpoint type class EndPointGenerator: def __init__(self, flask_port): ...
EVOLVED-5G/ImmersionNetApp
src/python/request/endpoint/EndPointGenerator.py
EndPointGenerator.py
py
1,904
python
en
code
0
github-code
13
22787953051
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # 递归超时 class Solution(object): def rob(self, root): if root is None: return 0 left_sum = 0 if root.left ...
lmb633/leetcode
337rob.py
337rob.py
py
2,012
python
en
code
0
github-code
13
5186419565
import cv2 import numpy as np img = cv2.imread('im.jpg',0) kernel = np.ones((5,5),np.uint8) # Erosion erosion = cv2.erode(img,kernel,iterations = 1) compare_ero = np.hstack((img,erosion)) cv2.imshow('Erosion',compare_ero) cv2.imwrite('Erosion.jpg',erosion) cv2.waitKey(0) cv2.destroyAllWindows() # Dilat...
PimKanjana/Morphological-Filters
morpho.py
morpho.py
py
2,321
python
en
code
0
github-code
13