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
74491938593
import gzip import math import os import pickle import numpy as np from bage_utils.char_one_hot_vector import CharOneHotVector from nlp4kor.config import log class DataSet(object): def __init__(self, features: np.ndarray = None, labels: np.ndarray = None, features_vector: CharOneHotVector = None, ...
bage79/nlp4kor
bage_utils/dataset.py
dataset.py
py
6,987
python
en
code
50
github-code
1
39998858334
import heppy.framework.config as cfg from heppy.configuration import Collider # select b quarks for jet to parton matching def is_bquark(ptc): '''returns True if the particle is an outgoing b quark, see http://home.thep.lu.se/~torbjorn/pythia81html/ParticleProperties.html ''' return abs(ptc.pdgid()...
cbernet/heppy
heppy/test/btag_parametrized_cfg.py
btag_parametrized_cfg.py
py
1,085
python
en
code
9
github-code
1
25375937714
from Thornhill.celery import app from thornhillsystem.email_system.email_sender import Sender from thornhillsystem.models import Message @app.task def test(param): return 'The test task executed with argument "%s" ' % param @app.task def send_email_task(from_email, to_mail, subject, message, attachment_path=Non...
mchalecki/Thornhill
Thornhill/thornhillsystem/tasks.py
tasks.py
py
576
python
en
code
0
github-code
1
41897699827
import smtplib from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import traceback import os def build_content(sender, receiver, subject, body): # 设置邮件正文,这里是支持HTML的 # 设置正文为符合邮件格式的HTML内容 m = MIMEText(_text=body, _subtype='h...
ChrisLi716/pythondemo
demo/email_01.py
email_01.py
py
3,203
python
en
code
0
github-code
1
32990921522
import socket from threading import Thread IP_ADDRESS = '127.0.0.1' PORT = 8050 SERVER = None BUFFER_SIZE = 4096 clients = {} def acceptConnections(): global SERVER global clients while True: client,addr = SERVER.accept() print(addr) def setup(): print('\t\t\t\t\t\t...
Seth-Joseph/PRO-C208
server.py
server.py
py
657
python
en
code
0
github-code
1
40823649994
import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import time import torch.utils.model_zoo as model_zoo import numpy as np import torch.utils.data as data_utils import math from collections import OrderedDict ...
htcao/AI_project
train.py
train.py
py
3,891
python
en
code
0
github-code
1
18746685398
""" Service class includes functionalities for implementing program features """ from src.domain.entity import complexNumber import random #import sys class complexNumbersList: """ Functionalities for the (list of) complex numbers """ def __init__(self): """ Creat...
pauladam2001/Sem1_FundamentalsOfProgramming
a5-pauladam2001/services/service.py
service.py
py
8,335
python
en
code
0
github-code
1
27801967937
import functools from test_framework import generic_test import math MAPPING = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10,'K':11,'L':12,'M':13,'N':14,'O':15, 'P':16,'Q':17,'R':18,'S':19,'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26} MULTIPLIER = 26 def ss_decode_col_id(col): if l...
garciamilord/Elements-of-Programming-Interviews
epi_judge_python_solutions/spreadsheet_encoding.py
spreadsheet_encoding.py
py
895
python
en
code
null
github-code
1
33195845551
# # # # # # # # # # # # # # # CAPTAINHOOK IDENTIFIER # # # # # # # # # # # # # # # import os import sys from contextlib import contextmanager from os.path import join from .utils import filter_python_files, get_config_file try: from StringIO import StringIO except ImportError: from io import StringIO DEFAU...
alexcouper/captainhook
captainhook/checkers/flake8_checker.py
flake8_checker.py
py
1,705
python
en
code
54
github-code
1
28040382633
import queue import sys import datetime import time from scipy.stats import poisson # event = Event(bus, eventData) class Event(object): def __init__( self, bus, eventData ): self.bus=bus self.timestamp = bus.timestamp self.route = bus.route self.eventType = eventData.eventType ...
glorianachen/simulation
event.py
event.py
py
6,078
python
en
code
0
github-code
1
42321692074
import warnings from typing import Tuple import geopandas as gpd import matplotlib import matplotlib.pyplot as plt import pandas as pd # Use codes as defined by the [codebook](https://www.mass.gov/files/documents/2016/08/wr/classificationcodebook.pdf) USE_CODES = { "101": "Single Family", "102": "Condominium...
ahasha/milton_maps
milton_maps/milton_maps.py
milton_maps.py
py
7,614
python
en
code
1
github-code
1
20897746681
import pickle import numpy as np import tensorflow as tf import os def load_label_names(path): # Load data with open(path + "batches.meta", mode='rb') as file: data = pickle.load(file, encoding='bytes') # Load label names label_names = data[b'label_names'] # Convert from binary strings ...
ztaal/Deep-learning-with-convolution-neural-networks-on-a-super-computer
cifar10_input.py
cifar10_input.py
py
956
python
en
code
0
github-code
1
40785984696
import pytest from werkzeug.exceptions import NotFound, BadRequest from app import api from app.models import Camera def test_get_query_string_params(application): with application.test_request_context('/?foo=bar&life=42'): assert api.get_query_string_params() == {'foo': 'bar', 'life': '42'} ...
percurnicus/opportunity
app/tests/test_api.py
test_api.py
py
6,004
python
en
code
0
github-code
1
74623068192
from utils.datasets import * import cv2 # dataset = MDFA(base_dir='MDFA/') dataset = SIRST(base_dir='sirst/') for i in range(dataset.__len__()): img, mask = dataset.__getitem__(i) if img.shape == mask.shape: continue else: print(i) print(img.shape) print(mask.shape) ...
Tianfang-Zhang/ISTD-python
data/__init__.py
__init__.py
py
526
python
en
code
5
github-code
1
71778251555
from limite.tela_coordenador import TelaCoordenador from entidades.coordenador import Coordenador from entidades.organizador import Organizador from persistencia.coordenadordao import CoordenadorDAO from persistencia.organizadordao import OrganizadorDAO class ControladorCoordenador: def __init__(self, con...
leminosso/projeto-aps
controlador_coordenador.py
controlador_coordenador.py
py
1,970
python
pt
code
0
github-code
1
23481077423
# Recode By @mrismanaziz # FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot> # t.me/SharingUserbot & t.me/Lunatic0de import importlib import logging import os import sys from pathlib import Path from userbot import CMD_HELP, DEVS, LOGS, TEMP_DOWNLOAD_DIRECTORY, bot from userbot.events import register from...
rainbowgirlidx/Man_Userbot
userbot/modules/core.py
core.py
py
3,876
python
en
code
0
github-code
1
7296684256
import cv2 from cv2 import UMat def crop_and_resize(frame:UMat,width:int,height:int)->UMat: aspect=float(height)/float(width) [original_height,original_width]=frame.shape[0:2] original_aspect=float(original_height)/float(original_width) if aspect < original_aspect: # 高さが不要 temporary_height=int(original...
novogrammer/echo-of-art
echo_of_art/image_utils.py
image_utils.py
py
758
python
en
code
0
github-code
1
29882430075
from rest_framework.response import Response from rest_framework import status, mixins, generics, viewsets from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.exceptions import NotFound from .models import Drop from .renderers import DropJSONRenderer from .serializers import DropSerial...
rmbrntt/deaddrop
deaddrop-api/deaddrop/apps/drops/views.py
views.py
py
2,893
python
en
code
0
github-code
1
690977689
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('behavior_subjects', '0007_auto_20151119_1117'), ] operations = [ migrations.AddField( model_name='session', ...
c-wilson/behavior_monitor
behavior_subjects/migrations/0008_session_exh_inh_delay.py
0008_session_exh_inh_delay.py
py
460
python
en
code
0
github-code
1
13310547888
import plotly.offline as py import plotly.graph_objs as go import sensor_input import random from pandas import Series def plot_spectrum_from_files(name,files): spectrums = [] for file in files: spectrums.append(sensor_input.read_spectrum_from_file(file)) plot_spectrums(name,spectrums) def plot_d...
zalum/tum-milk
sensor/sensor_output.py
sensor_output.py
py
1,564
python
en
code
0
github-code
1
12771861930
#!/usr/bin/python3 # runs VK modules in correct way """ Developer and Author: Thomas Fire https://github.com/thomasfire (Telegram: @Thomas_Fire) ### Main manager: Uliy Bee """ from logging import exception from os import getpid import getmsg import makeseq import sendtovk import updatemedia def get_last_msg(): ...
thomasfire/agent_smith
vk_run.py
vk_run.py
py
1,972
python
en
code
1
github-code
1
11012367902
from django.urls import path from app1.views import * urlpatterns = [ path('', inicio, name="Inicio"), path('vuelo/', vuelo), path('personal/', personal), path('pasajero/', pasajero), path('formulario1/', formulariovuelo, name="Crear Vuelos"), path('formulario2/', formulariopersonal, name="Cr...
Luciano02-web/Entrega1-Bogarin
app1/urls.py
urls.py
py
725
python
es
code
0
github-code
1
38904399549
import pandas as pd from silx.gui.qt import QMessageBox from datetime import datetime def save_csv(self): filepath = self.imagepath q_choice = self.q_combo.currentText() loadedlist = self.loadedlistwidget curvelist = [item.text() for item in loadedlist.selectedItems()] curvenames = [] for curve...
IdanKes/SAXS
Main Code/saving_methods.py
saving_methods.py
py
1,452
python
en
code
0
github-code
1
5337207653
def test_add_group(app): old_list = app.groups.get_group_list() groups_from_excel = app.groups.\ get_groups_from_excel("C:\\Users\\AleksandrKoygerov\\PycharmProjects\\python-gui-tests\\groups.xlsx") if len(groups_from_excel) == 0: print("NO GROUPS LIST, CHECK EXCEL FILE") assert Fals...
koyger/python-gui-tests
test/test_add_groups_from_excel.py
test_add_groups_from_excel.py
py
541
python
en
code
0
github-code
1
6649268514
import copy import logging from typing import Optional import requests from ocean_provider.utils.basics import get_web3 from ocean_provider.utils.consumable import ConsumableCodes from ocean_provider.utils.credentials import AddressCredential from ocean_provider.utils.data_nft import get_data_nft_contract from ocean_p...
oceanprotocol/provider
ocean_provider/utils/asset.py
asset.py
py
4,033
python
en
code
25
github-code
1
43495796464
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 7 17:53:40 2023 @author: mingjunsun This code is an example of solving LASSO-like optimization problems. """ import cvxpy as cp import numpy as np import matplotlib.pyplot as plt import pandas as pd import os from sklearn import linear_model #f...
Sho-Shoo/36490-F23-Group1
example_code/code_example.py
code_example.py
py
4,282
python
en
code
0
github-code
1
38827167045
""" The RAD record format defines what a flat record should look like. It's an unifying format that is used through out the application. This record is passed around the different components of the application to keep a consistent data format. Also it is a good model for other people in the team looking for data. It g...
radremedy/radrecord
radrecord/rad_record.py
rad_record.py
py
9,585
python
en
code
0
github-code
1
39273846847
import os import sys import torch import torch.utils.data as data import numpy as np from PIL import Image import glob import random from torchvision import transforms import matplotlib.pyplot as plt import scipy.misc class SALICON(data.Dataset): def __init__(self, stimuli_train_path, stimuli_val_path, gt_train_...
pengqianli/ACNet
src/dataloader.py
dataloader.py
py
1,863
python
en
code
3
github-code
1
11038920804
import os import boto3 import time import copy import subprocess import threading import multiprocessing MAX_WORKERS = 1 SRC_ACCESS_KEY = os.environ['SRC_ACCESS_KEY'] SRC_SECRET_KEY = os.environ['SRC_SECRET_KEY'] SRC_REGION = os.environ['SRC_REGION'] DST_ACCESS_KEY = os.environ['DST_ACCESS_KEY'] DST_SECRET_KEY ...
quintilesims/d.ims.io
tools/migrate.py
migrate.py
py
3,876
python
en
code
2
github-code
1
11163016053
import copy dr=[-1,1,0,0] dc=[0,0,-1,1] N,M = map(int,input().split()) pan=[] for _ in range(N): pan.append(list(map(int,input().split()))) zero_list=[] virus_list=[] visited=[[0]*M for _ in range(N)] for r in range(N): for c in range(M): if pan[r][c]==0: zero_list.append((r,c)) ...
ahrtz/study
코로나 기간 알고/백준연구소.py
백준연구소.py
py
1,532
python
en
code
0
github-code
1
16736609895
import random as r import math import numpy as np import tkinter as tk import heapq import itertools import random class Player: polygons = [] n = None def __init__(self, n, score=0): self.n = n self.polygons = [] self.score = 0 def add_pol(self, pol): self.polygons.ap...
PaulWtlr/projet_info_2022
DataType.py
DataType.py
py
5,451
python
en
code
1
github-code
1
40239161316
#!/usr/bin/env python # -*- coding: utf-8 -*- # external import numpy as np import matplotlib.pyplot as plt import pandas # local from dtk import walk obinna = pandas.read_csv('../data/obinna-walking.txt', delimiter='\t', index_col="TimeStamp", na_values='0.000000') # change the degrees to ...
csu-hmc/gait-control-direct-id-paper
src/control_solver_example.py
control_solver_example.py
py
1,779
python
en
code
3
github-code
1
1091161094
import cv2 print(cv2.__version__) cam = cv2.VideoCapture(0) while True: output1, frame = cam.read() greyFrame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) cv2.imshow("CameraWindow", greyFrame) cv2.moveWindow("CameraWindow", 500,0) if cv2.waitKey(1) & 0xff == ord("q"): break cam.release() ...
kseeger-code/AI_for_Everyone
openCV-1.py
openCV-1.py
py
321
python
en
code
0
github-code
1
1586045599
# -*- coding: utf-8 -*- """ ******************* tests.conftest ******************* Utility functions that are used to configure Py.Test context. """ import os import pytest def pytest_addoption(parser): """Define options that the parser looks for in the command-line. Pattern to use:: parser.addopt...
highcharts-for-python/highcharts-core
tests/conftest.py
conftest.py
py
2,420
python
en
code
40
github-code
1
21310661684
class Base: def __init__(self, *specs, **kwargs): for spec in specs: try: spec_dict = dict(spec) self.digest(spec_dict) except ValueError: print(f'Element cannot be cast into dict, and is being discarded: {type(spec)} {spec}') ...
oaao/objgen
objgen/generators/generic.py
generic.py
py
2,356
python
en
code
0
github-code
1
43128390785
""" __author__: Jiaming Shen __description__: extract entity pair document level co-occurrence features Input: 1) the sentence.json Output: 1) eidDocPairCounts.txt, 2) eidDocPairPPMI.txt """ import sys import json import itertools import math from collections import defaultdict import mmap from tqdm import tqdm...
mickeysjm/HiExpan
src/featureExtraction/extractEidDocPairFeature.py
extractEidDocPairFeature.py
py
2,434
python
en
code
71
github-code
1
6255000766
from python_graphql_client import GraphqlClient import feedparser import httpx import json import pathlib import re import os import datetime root = pathlib.Path(__file__).parent.resolve() client = GraphqlClient(endpoint="https://api.github.com/graphql") TOKEN = os.environ.get("GH_TOKEN", "") def replace_chunk(con...
wintermorn1ng/wintermorn1ng
build_readme.py
build_readme.py
py
2,078
python
en
code
0
github-code
1
73967433954
import discogs_client import config import pandas as pd #Connect using auth token d = discogs_client.Client('discogsAnalytics', user_token=config.discogs_token) me=d.identity() collection_data = [] for album in me.collection_folders[1].releases: formatlist = album.release.formats[0] format_desc = formatlist[...
scottpmchugh/DiscogsAnalytics
extraction/discogsExtraction.py
discogsExtraction.py
py
684
python
en
code
0
github-code
1
42568375826
import os import shutil from typing import List def main(source_dir: str, des_dir: str, ext: str): files = list_file_with_ext(source_dir, ext) for file in files: shutil.copy(file, des_dir) # List all music files with path. Get file type by extension name. def list_file_with_ext(file_path: str, ext_l...
zhiwenliang/scripts
file/colect_files_from_folder.py
colect_files_from_folder.py
py
747
python
en
code
0
github-code
1
21725750288
#your code needs the ability to take different actions #based on different conditions price = float(input('enter the price: ')) if price >= 1.00: tax = .07 print(tax) else: tax = 0 print(tax) # > greater # < less # >= greater than or EQUAL # <= less than or equal # == is equal to #...
udaymannepalli/Python_scripts_for_beginners
condition.py
condition.py
py
337
python
en
code
0
github-code
1
3176992392
import tweepy from app.models.twitter import auth from app.models.twitter import utils def get_friends(username): api = auth.get_api() return api.friends(screen_name=username, include_user_entities='false', skip_status='true') def screen_names_of_friends(username): friends = get_...
amtsh/vdeos.me
app/models/twitter/Twitter.py
Twitter.py
py
883
python
en
code
0
github-code
1
37670160302
## Top 5 restaurant types from pymongo import MongoClient def get_node(db): return list(db.OSMLagny.aggregate([{"$match":{"amenity":{"$exists":1}, "amenity":"restaurant"}}, {"$group":{"_id":"$cuisine", "count":{"$sum":1}}},{"$sort":{"count":-1}}, {"$limit":5}])) def get_db(): client = MongoC...
narquie/Data-Wrangling-Nanodegree
Python Scripts Queries/Top 5 Restaurants.py
Top 5 Restaurants.py
py
461
python
en
code
0
github-code
1
26401013242
piada = input() piadas_boas = 0 piadas_ruins = 0 bom = True ruim = True mediano = True while (piada != 'Fim do Show!'): reacao = input() piada = input() if (reacao == 'BAZINGA!'): piadas_boas += 1 elif (reacao != 'BAZINGA!'): piadas_ruins += 1 if ((piadas_boas/(piadas_boas + piadas_...
amandaarruda/introduction-to-programming
lista-big-bang-theory/bazinga.py
bazinga.py
py
791
python
pt
code
0
github-code
1
70072116194
def main(): gsn = 9445 powerGrid = createPowerGrid(gsn) maxPower = 0 coords = [] for l in range(1,30): # Part1: l = 3 print(l) for r in range(len(powerGrid) - l): row = powerGrid[r] for c in range(len(row) - l): squareSum = 0 for i in range(l): for j in range(l):...
FredrikLastow/advent-of-code
2018/day11/main.py
main.py
py
915
python
en
code
0
github-code
1
8272993033
# MAGIC CODEFORCES PYTHON FAST IO import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) # END OF MAGIC CODEFORCES P...
elsantodel90/cses-problemset
stick_divisions.py
stick_divisions.py
py
852
python
en
code
0
github-code
1
70337480994
#!/bin/python3 import sys # x1 + v1 * t = x2 + v2 * t # x1 - x2 = ( v2 - v1 ) * t # (x1 - x2) / ( v2 - v1 ) = t def kangaroo(x1, v1, x2, v2): if v1 == v2: if x1 == x2: return 'YES'; else: return 'NO'; t = (x1 - x2) / ( v2 - v1 ) if t < 0: return 'NO...
exsky/hackerrank
Algorithms/implementation/kangaroo.py
kangaroo.py
py
532
python
pt
code
1
github-code
1
14467272098
""" Dimensionality Reduction using Dense_AutoEncoder input:data in shape (784,n), Dimension output:data in shape (Dimension,n) """ from keras.layers import * from keras.models import Model def dense_AE(data,dim): x_train = data / 255 x_train = x_train.reshape((x_train.shape[0], -1)) encoding_dim = dim ...
Mateguo1/KMNIST
cluster/Dense_AutoEncoder.py
Dense_AutoEncoder.py
py
1,300
python
en
code
0
github-code
1
5719940935
# correlation between googleTrendsCovidValue and cdcValue in path import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import ttest_ind path = "./data/cdcAnxiety_googleCovid_COMBINED.csv" missingPath = "./data/cdcAnxiety_googleCovid_COMBINED_withMissing.csv" cdcOGPath = "./data/cdc/c...
Xyloidzzz/covid-depression-social
Correlations/cdc_google_correlation.py
cdc_google_correlation.py
py
3,257
python
en
code
0
github-code
1
25730146075
import shutil import gradio as gr import time import yaml import openai import os from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from prepare_vectordb import PrepareVectorDB from typing import List, Tuple import re import ast import html from cfg import l...
Farzad-R/LLM-playground
RAG-GPT/gradio_app_utils.py
gradio_app_utils.py
py
10,047
python
en
code
0
github-code
1
10048371514
""" Minimum Swaps to Arrange a Binary Grid Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be vali...
okaysidd/Interview_material
Extras/Minimum Swaps to Arrange a Binary Grid.py
Minimum Swaps to Arrange a Binary Grid.py
py
1,652
python
en
code
0
github-code
1
72538152994
import tkinter as tk class ScreenCapture: def __init__(self, root): print("Starting screenshot process ...") self._root = root self._root.attributes('-fullscreen', True) self._root.attributes('-topmost', True) self._root.attributes('-alpha', 0.1) self._canvas = tk...
LeFi8/img-text-search
src/screen_capture.py
screen_capture.py
py
2,463
python
en
code
0
github-code
1
75143000674
import os import imageio.v3 as iio import imageio import torch import argparse import torchvision import matplotlib.pyplot as plt import numpy as np from torchvision import datasets, transforms from torchvision.transforms.functional import hflip, vflip from utils import initialize_equi_model, set_seed device = torch....
basusourya/lambda_equitune
EquiClassification/feature_visualization.py
feature_visualization.py
py
5,072
python
en
code
5
github-code
1
9925796207
import json import logging from typing import Optional from ph4_walkingpad.profile import Profile, calories_walk2_minute, calories_rmrcb_minute from ph4_walkingpad.reader import reverse_file logger = logging.getLogger(__name__) class StatsAnalysis: def __init__(self, profile=None, profile_file=None, stats_file=...
ph4r05/ph4-walkingpad
ph4_walkingpad/analysis.py
analysis.py
py
6,736
python
en
code
47
github-code
1
29860315580
import collections def get_matrix(path_to_file="input.txt"): matrix_str = "" with open(path_to_file,"r") as file: count = file.readline() matrix_str = file.read() matrix = [] lines = matrix_str.split("\n") for line in lines: elements = line.split(" ") ...
KeiserKholod/Cycles_BFS_Python
KA1.py
KA1.py
py
3,093
python
ru
code
0
github-code
1
71222805155
# coding=utf-8 from functools import reduce num = [1, 2, 3] nums = [num for i in range(3)] def all_aa(nums): mfunc = lambda x, y: ["%s%s" % (i, j) for i in x for j in y] # reduce(mfunc, nums) # result1 = mfunc(nums[0], nums[1]) # result2 = mfunc(result1, nums[2]) dataresult = reduce(mfunc, nums...
FYPYTHON/PathOfStudy
Algorithm/python_reduce.py
python_reduce.py
py
1,157
python
en
code
0
github-code
1
3322408496
from difflib import Differ import re def get_index_positions(list_of_elems, element): # To find the '^' positions in the 'differ' command ''' Returns the indexes of all occurrences of give element in the list- listOfElements ''' index_pos_list = [] index_pos = 0 while True: try: ...
Petit-Benjamin/VulnerabilityInjectionNLP
PythonScripts/confuzzion/set_seed_var_value_in_mutant.py
set_seed_var_value_in_mutant.py
py
5,033
python
en
code
1
github-code
1
71773984674
from tkinter import * root=Tk() miFrame=Frame(root, width=700, height=600) miFrame.pack() #miLabel=Label(miFrame,text="Hoy es 18 de junio de 2021") #miLabel.place(x=120, y=125) #si pongo pack() el Frame se adapta al tamaño del Label, no ocupa nada más. #le estoy indicando que el texto se desplace a esas distancias x...
dvidals/python
TrabajoConLabelTkinter.py
TrabajoConLabelTkinter.py
py
547
python
es
code
0
github-code
1
36250456309
#bfs1 단지번호 붙이기 from collections import deque n = int(input()) maps = [] for _ in range(n): tmp = [int(i) for i in input()] maps.append(tmp) def bfs(coord,maps,visited): dirs = [(1,0),(-1,0),(0,1),(0,-1)] queue = deque() queue.append((coord)) count = 0 while queue: y,x = queue.poplef...
Choisiz/coding-test-Team
김수빈/BFS/단지번호붙이기.py
단지번호붙이기.py
py
1,293
python
en
code
0
github-code
1
31369997290
import sys import unittest sys.path.append("pig") from unittest.mock import patch from pig.computer_player import ComputerPlayer from io import StringIO class TestComputerPlayer(unittest.TestCase): def test_take_turn_easy(self): # Test that an easy computer player correctly holds their turn player...
sams258/Dice-game-Pig-
test/test_computer_player.py
test_computer_player.py
py
3,248
python
en
code
2
github-code
1
25626976499
from django import forms from .models import ContinuingEducationLog, UserProfile from django.contrib.auth.models import User class CELogForm(forms.ModelForm): class Meta: model = ContinuingEducationLog fields = ('required_CE', 'oversight_entity', 'repeat', 'hours', 'date_completed', 'top_items_learned',) class ...
lydia-rodriguez/compliance
compliance/forms.py
forms.py
py
1,024
python
en
code
0
github-code
1
15725734700
from os import listdir, path from time import clock from pickle import dumps, loads from gzip import compress, decompress from random import shuffle from sklearn.feature_selection import SelectKBest import logging class Vectors(object): def __init__(self, corpos_folder_path, corpora_label_dict, debugging_output_f...
Orenef11/NLP-Lab
Vectors.py
Vectors.py
py
11,821
python
en
code
0
github-code
1
73691830112
import glob, configparser, os old = "1.0.0.127.in-addr.arpa" new = "example.com" def fix(x): print(x) f = open(x) fcon = f.read() f.close() fcon = fcon.replace("email." + old, "email." + new) fcon = fcon.replace(old, new) f = open(x, "w") f.write(fcon) f.close() def main(): files = glob.glob("**/*", re...
EncryptedKitten/Minecraft_Server_Emulator
replace_domain.py
replace_domain.py
py
448
python
en
code
31
github-code
1
25378129987
import psycopg2 from opentelemetry.instrumentation import dbapi from opentelemetry.instrumentation.instrumentor import BaseInstrumentor from opentelemetry.instrumentation.psycopg2.version import __version__ from opentelemetry.trace import get_tracer class Psycopg2Instrumentor(BaseInstrumentor): _CONNECTION_ATTRI...
NathanielRN/clone-opentelemetry-python
instrumentation/opentelemetry-instrumentation-psycopg2/src/opentelemetry/instrumentation/psycopg2/__init__.py
__init__.py
py
2,023
python
en
code
0
github-code
1
71377845154
#!/usr/bin/env python """ Basic tests """ import unittest import time import numpy as np import pygimli as pg import pygimli.meshtools as mt run_solve = True class ModellingMT(pg.core.ModellingBase): def __init__(self, nPars, verbose): """ """ pg.core.ModellingBase.__init__(self, verbose) ...
gimli-org/gimli
pygimli/testing/test_FOP.py
test_FOP.py
py
3,103
python
en
code
312
github-code
1
30267108046
#!/usr/bin/env python # -*- encoding:UTF-8 -*- import doctest from typing import Generator, MutableSequence from common import CT def rank(mseq: MutableSequence[CT], k: CT) -> CT: """Return the `k` rank element of `seq` Args: seq (MutableSequence[CT]): input sequence k (CT): element index ...
ChangeMyUsername/algorithms-sedgewick-python
chapter_2/module_2_5.py
module_2_5.py
py
6,830
python
en
code
272
github-code
1
36343046109
# -*- coding: utf-8 -*- # 有时候人们会用重复写一些字母来表示额外的感受,比如 "hello" -> "heeellooo", "hi" -> "hiii"。我们将相邻字母都相同的一串字符定义为相同字母组,例如:"h", "eee", "ll", "ooo"。 # # 对于一个给定的字符串 S ,如果另一个单词能够通过将一些字母组扩张从而使其和 S 相同,我们将这个单词定义为可扩张的(stretchy)。 # 扩张操作定义如下:选择一个字母组(包含字母c),然后往其中添加相同的字母c使其长度达到 3 或以上。 # # 例如,以"hello" 为例,我们可以对字母组"o" 扩张得到 "hellooo",但是无法...
Liabaer/Test
learn_algorithm/leetcode/expressive_words.py
expressive_words.py
py
2,483
python
zh
code
0
github-code
1
2931427678
import email from typing import Any, List from fastapi import APIRouter, Body, Depends, HTTPException from fastapi.encoders import jsonable_encoder from pydantic.networks import EmailStr from app import crud, models from app.models.user import * from app.api import deps from app.core.config import settings from app.u...
VittorioYan/full-stack-fastapi-mongodb
{{cookiecutter.project_slug}}/backend/app/app/api/api_v1/endpoints/users.py
users.py
py
4,083
python
en
code
0
github-code
1
6912557640
#!/usr/bin/env python3 """ Benchmark on calling C methods for FASTCALL. http://bugs.python.org/issue29263 Created at 2017-01-14 by INADA Naoki. """ import pyperf runner = pyperf.Runner() runner.timeit('b"".decode()', "empty_bytes.decode()", setup="empty_bytes = b''", duplic...
vstinner/pymicrobench
bench_fastcall_c_method.py
bench_fastcall_c_method.py
py
611
python
en
code
4
github-code
1
30211562412
from concurrent.futures.thread import ThreadPoolExecutor from contextlib import asynccontextmanager import asyncio class AsyncFile: def __init__(self, file, loop=None, executor=None): if not loop: loop = asyncio.get_running_loop() if not executor: executor = ThreadPoolExecu...
Smile-Cats/asyncio-demo
my_asyncio_demo/编写异步上下文管理器.py
编写异步上下文管理器.py
py
1,765
python
en
code
0
github-code
1
2033204475
import gzip from keybert import KeyBERT from yake import KeywordExtractor import re import setup_dir NWORDS=100 FMT="{}\t{}\t{}\t{}\t{}\n" cleans={ #important give all in lowercase!!! r"international\s+water\s+management\s+institute": "iwmi", r"sunil\s+mawatha": "", r"the\s+consultative\s+group\s+on\s+international\...
asselapathirana/waybackcrawler
src/process_keywords.py
process_keywords.py
py
2,190
python
en
code
0
github-code
1
32770379108
import random import subprocess def make_example(): n = random.randint(1, 10) cur_leaves = [] gas = [] edges = [] for i in range(n): gas.append(random.randint(1, 10)) cur_leaves.append(1) for i in range(2, n + 1): from_v = random.choice(list(cur_leaves)) to_v = i ...
vladshablinsky/algo
1084/test.py
test.py
py
1,402
python
en
code
1
github-code
1
12943532357
import timeit import matplotlib.pyplot as plt def algoritm1(item): uniq_dict = {} for x in item: if x in uniq_dict: return False uniq_dict[x] = True return True def algoritm2(item): uniq_lst = [] for x in item: if x in uniq_lst: return False ...
Polinaaa567/university_ipynb
5_term/Alg/lab1_begin/2.2.py
2.2.py
py
817
python
en
code
0
github-code
1
3281837914
# -*- coding: utf-8 -*- # import accounts from raven.contrib.flask import Sentry from flask import Flask, request, redirect, abort import ses import urlparse # from util import jsonify app = Flask(__name__) sentry = Sentry() sentry.init_app(app) @app.route('/') def hello(): return 'Hello World!\n' @app.route('...
Unholster/unholster-forms
web.py
web.py
py
2,366
python
en
code
0
github-code
1
37022607442
import matplotlib matplotlib.use('Agg') import time import argparse import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os import gc # Models Packages from sklearn import metrics from sklearn.metrics import mean_squared_error from sklearn import feature_se...
vuhoangminh/Kaggle-Avito
codes/train_tune_params.py
train_tune_params.py
py
10,360
python
en
code
0
github-code
1
18075673144
import numpy as np import pandas as pd from scipy.interpolate import make_interp_spline, BSpline import matplotlib as mpl import matplotlib.pyplot as plt plt.switch_backend('agg') mpl.rcParams['svg.hashsalt'] = 42 np.random.seed(42) #print (plt.style.available) #https://matplotlib.org/3.1.1/gallery/style_sheets/style_...
adithya8/ContextualEmbeddingDR
nvskplotter.py
nvskplotter.py
py
7,467
python
en
code
3
github-code
1
70010352033
import time def is_ceiling(a, a0, sub): num_coef = len(a) # condition i s = sum(a[t] for t in sub) if s > a0: return False # condition ii for t in range(num_coef): if t not in sub and s + a[t] < a0 + 1: return False # condition iii for t in range(num_coef): ...
Lyxn/or-model
util/reduce.py
reduce.py
py
3,334
python
en
code
0
github-code
1
41880736603
from django.conf import settings from django.conf.urls.static import static from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from users.views import home, register, profileDetials, question1, question2, question3, compatibility, editProfile urlpatterns = [ path('', home, na...
NethraGunti/ProfileCompatibility
users/urls.py
urls.py
py
1,015
python
en
code
0
github-code
1
33697293829
import numpy as np # Задаем начальное значение границ LOWER_PREDICTED_NUMBER = 1 UPPER_PREDICTED_NUMBER = 100 # Функция возвращает случайные значения в пределах нижней и верхней границы def do_predict(lower_boundary, upper_boundary): return (np.random.randint(lower_boundary, upper_boundary + 1)) def game_core_v5...
199019681967/skillfactory-project-1-malik
module_0/Module.0.Malik.py
Module.0.Malik.py
py
1,497
python
en
code
0
github-code
1
30199637561
# In python we can do for else nums = [33,7,67,86,3,9] # for i in nums: # if i % 5 ==0: # print(i) # break # else: # print("not found") # Here we will get not found 5 times, we want it only once so we write else for for not if for i in nums: if i % 5 == 0: print(i) ...
salonikalsekar/Python
for_else.py
for_else.py
py
358
python
en
code
0
github-code
1
4213543541
"""berrybeef.beef: provides entry point main().""" import sys from PyQt5.QtWidgets import QApplication from .Info import Info from BERRYBEEF.Main import MainWindow from BERRYBEEF.constants import * def main(): try: app = QApplication(sys.argv) screen = app.primaryScreen() print('Scre...
ferlete/BerryBeef
BERRYBEEF/berrybeef.py
berrybeef.py
py
849
python
en
code
0
github-code
1
74718431073
import requests from PIL import Image from bs4 import BeautifulSoup import os import xlwt import re def get_captcha(si_code): captcha_url = "http://my.ujs.edu.cn/" + si_code print(captcha_url) r = session.get(captcha_url, headers=header) with open("captcha.jpg","wb") as f: f.write(r.content) ...
beenlyons/Allspder
PySpider/ujsScore/get_score.py
get_score.py
py
1,871
python
en
code
0
github-code
1
19547549511
import datetime import subprocess log_file = open("logs.log", "a") def log(message: str) -> None: text = str(datetime.datetime.now()) + ": " + message + "\n" print(text, end="") log_file.write(text) log("Checking to see if package 'MariaDB' is installed...") check_stat_proc = subprocess.run(["dpkg", "-s"...
anay-p/mysql-for-termux
installer.py
installer.py
py
2,407
python
en
code
36
github-code
1
45645200524
from django.http import JsonResponse from django.shortcuts import redirect, get_object_or_404 from django.views import View from django.views.decorators.csrf import csrf_exempt from vigil.models import AlertChannel, Alert from celery import uuid, signature from vigil import tasks from vigil.models import VigilTaskRes...
inuitwallet/vigil
vigil/views/api_views.py
api_views.py
py
2,058
python
en
code
0
github-code
1
31509600396
from django import forms from .models import General, HotWorks, ElectricalWorks form_styles = {'contractor': forms.TextInput(attrs={'class': 'textinputfield'}), 'contractor_name': forms.TextInput(attrs={'class': 'textinputfield'}), 'facility': forms.TextInput(attrs={'class': 'textinputfi...
Megaprotas/work_project
permits/forms.py
forms.py
py
3,621
python
en
code
0
github-code
1
42631122942
from tkinter.filedialog import askopenfilename, asksaveasfile import numpy as np import matplotlib.pyplot as plt class Calibration: def __init__(self, defaultPath="calibration_files/kalib.txt", plot=None): self.filepath = defaultPath self.nm = [] self.pixels = [] self.model = None ...
TIS2022-FMFI/spektroskop-mikroskop
gui_widgets/Calibration.py
Calibration.py
py
5,407
python
en
code
0
github-code
1
5796985227
import torch import torchvision from torch import nn import os class autoencoder(nn.Module): def __init__(self, n_channel=1, n_class=36): super(autoencoder, self).__init__() self.encoder = nn.Sequential( nn.Conv2d(n_channel, 32, 5, stride=3, padding=2), # b, 16, 10, 10 nn.R...
purelyvivid/captcha5
model.py
model.py
py
1,442
python
en
code
0
github-code
1
22525702483
import collections import glob import logging import os from typing import List import torch from torch import nn from torch.optim.lr_scheduler import LambdaLR from torch.serialization import default_restore_location logger = logging.getLogger() CheckpointState = collections.namedtuple( "CheckpointState", [ ...
microsoft/LMOps
uprise/DPR/dpr/utils/model_utils.py
model_utils.py
py
4,819
python
en
code
2,623
github-code
1
10990266944
from torch import nn from towhee.models.vis4mer.transposelinear import TransposedLinear from towhee.models.vis4mer.activation import Activation from towhee.models.vis4mer.get_initializer import get_initializer def LinearActivation( d_input, d_output, bias=True, zero_bias_init=False, ...
towhee-io/towhee
towhee/models/vis4mer/linearactivation.py
linearactivation.py
py
1,645
python
en
code
2,843
github-code
1
10603942515
from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout from django.contrib.auth.decorators import login_required def signup(request): '''signup function''' if re...
nopalpite/OCP9
LITReview/accounts/views.py
views.py
py
1,175
python
en
code
0
github-code
1
29558607777
from pathlib import Path from . import data from . import plot from . import excel from . import config from . import latex import subprocess class Document: def __init__(self, prefix, title, subtitle, author, date): self.prefix = prefix self.title = title self.subtitle = subtitle ...
HerveFrezza-Buet/bilan
pybilan/pybilan/report.py
report.py
py
3,261
python
en
code
0
github-code
1
870075297
''' In our first example we want to show how to read data from a file. The way of telling Python that we want to read from a file is to use the open function. The first parameter is the name of the file we want to read and with the second parameter, assigned to the value "r", we state that we want to read from the...
aarontinn13/Winter-Quarter-History
Tutorial/readingwriting,io4.py
readingwriting,io4.py
py
3,335
python
en
code
0
github-code
1
74262849954
from app.models import Booking,db,SCHEMA,environment from sqlalchemy.sql import text from datetime import datetime from faker import Faker fake = Faker() def seed_bookings(): booking1 = Booking( class_id=1, user_id=3, time_start=datetime(2023,7,6, hour = 9,minute = 30), time_end= ...
xuantien93/IronReligion
app/seeds/bookings.py
bookings.py
py
1,731
python
en
code
0
github-code
1
29928571724
import networkx as nx import numpy as np import torch from datanetAPI import DatanetAPI POLICIES = np.array(['WFQ', 'SP', 'DRR']) def sample_to_dependency_graph(sample): G = nx.DiGraph(sample.get_topology_object()) R = sample.get_routing_matrix() T = sample.get_traffic_matrix() P = sample.get_perf...
Mengxue12/RouteNet-E_pytorch
scheduling/read_dataset.py
read_dataset.py
py
8,871
python
en
code
2
github-code
1
40793798969
import uuid import speech_recognition as sr r = sr.Recognizer() language='ru_RU' def recognise(filename): with sr.AudioFile(filename) as source: audio_text = r.listen(source) try: text = r.recognize_google(audio_text,language=language) print(text) return text ...
setta1a/bot_god
first/botTelegram/for stt/stt.py
stt.py
py
1,251
python
en
code
5
github-code
1
44709118271
class Solution: def isCousins(self, root: TreeNode, x: int, y: int) -> bool: # 如果根节点为空,或者x值为根节点,或者y值为根节点,这些都为false if (root is None or x == root.val or y == root.val): return False parent = {} depth = {} # 获取到深度和父节点 字典 def dfs(node, par=None): if...
Mszmy/leetcode
993. 二叉树的堂兄弟节点-python.py
993. 二叉树的堂兄弟节点-python.py
py
742
python
zh
code
0
github-code
1
5299224856
# -*- coding: utf-8 -*- import torch as t import sys sys.path.append("../") from models import HRcanNet import cv2 import numpy as np import h_psnr import os import time class CIR: def __init__(self, weights_file="../weights/dejpeg_HRcanNet2_1_33_best.pth"): self._device = 'cuda' # self._net = HS...
riverlight/HSR
scripts/ir_video.py
ir_video.py
py
2,697
python
en
code
1
github-code
1
30297889715
""" Module to analyze vessel pulsatility during the heart cycle in ecg-gated CT radius change - area change - volume change Authors: Almar Klein and Maaike Koenrades. Created 2019. """ import os import sys import time import openpyxl import pirt import numpy as np import visvis as vv from stentseg.util...
almarklein/stentseg
lspeas/analysis/vessel_dynamics.py
vessel_dynamics.py
py
24,229
python
en
code
3
github-code
1
11003028307
import collections import heapq class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: lookup = {} for item in tasks: lookup[item] = lookup.get(item, 0) + 1 hold = [] for value in lookup.values(): heapq.heappush(hold, -value) time =...
peaqi/mock
Python/621. Task Scheduler/heap, queue.py
heap, queue.py
py
725
python
en
code
0
github-code
1
4561858275
#DAVID GARCIA # DO NOT FORGET TO ADD COMMENTS!!! #3/3/23 #FIX: RENAMED "calculator.py" to "Calculator.py" to accomodate the def "calculator" in "calculatorGUI.py" from stack import Stack from tree import ExpTree def infix_to_postfix(infix): opStack = Stack() prio = {'*':3,'/':3,'-':2,'+':2,'(':1} #prior...
david04g/python-calculator
Calculator.py
Calculator.py
py
1,653
python
en
code
0
github-code
1
8967287236
# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality # P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. # Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009. """ CREATE LOCAL mlruns """...
shippedbrain/shipped-brain-api
tests/resources/train.py
train.py
py
6,467
python
en
code
2
github-code
1