seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
30489056010
# -*- coding: utf-8 -*- """ Created on Wed Aug 4 16:13:47 2021 @author: Roman """ from spektral.transforms import AdjToSpTensor from spektral.data import Dataset from spektral.transforms.normalize_one import NormalizeOne import numpy as np import pandas as pd from scipy.sparse import coo_matrix from astropy.coordin...
FusRoman/Alert-Association-previous-work
src/graph/motgraphdataset.py
motgraphdataset.py
py
9,253
python
en
code
0
github-code
6
29233364056
#!/usr/bin/env python3 import re import sys import os from os.path import dirname, join as path_join, abspath, exists extra_paths = [path_join(dirname(abspath(__file__)), "include")] def find_file(included_name, current_file): current_dir = dirname(abspath(current_file)) for idir in [current_dir] + extra_pat...
rapidsai/raft
cpp/include/raft/thirdparty/mdspan/make_single_header.py
make_single_header.py
py
2,236
python
en
code
452
github-code
6
27066275793
#! /usr/bin/python from Prettier import * from Solution_Checker import * from Words_List_Prep import * from Scorer import * from Word_Processor import * from Box_Maker import * def main(): """ Main IBM Puzzle find boxes that have between 2 and 5 solutions """ ### Intro Box Text introPrinter(...
tmangan/PonderThis
2022_December/solver.py
solver.py
py
2,591
python
en
code
0
github-code
6
8704975946
import time from stable_baselines3 import PPO, A2C from batkill_gym import BatkillEnv import os models_dir = "ppo" logdir = f"logs" if not os.path.exists(models_dir): os.makedirs(models_dir) if not os.path.exists(logdir): os.makedirs(logdir) env = BatkillEnv() env.reset() TIMESTEPS = 100000 model = PPO('MlpPoli...
polako/batkill
batkill_ai_train.py
batkill_ai_train.py
py
595
python
en
code
1
github-code
6
42448338704
from alpha_vantage.timeseries import TimeSeries from bs4 import BeautifulSoup import json with open("config.json", "r") as config_file: config = json.load(config_file) api_key = config.get("api_key") print("apik key: ", api_key) ts1 = TimeSeries(key=api_key) # Retrieve the monthly time series data for AAPL # da...
tokyo-lab/alpha
data_using_alpha_vantage_package.py
data_using_alpha_vantage_package.py
py
554
python
en
code
0
github-code
6
26804283291
num_cells, num_epochs = [int(data) for data in input().split()] cells = [int(data) for data in input()] new_cells = [0] * num_cells binary = bin(num_epochs)[2:] num_bits = len(binary) for bin_idx, bin_r_idx in zip(range(num_bits), reversed(range(num_bits))): if binary[bin_idx] == '1': shift = 2 ** bin_r_id...
Stevan-Zhuang/DMOJ
CCC/CCC '16 S5 - Circle of Life.py
CCC '16 S5 - Circle of Life.py
py
570
python
en
code
1
github-code
6
72743495547
from csv import reader from operator import add import datetime #fares dataset fares_rdd = sc.textFile("/user/hc2660/hw2data/Fares.csv", 1) fares_rdd = fares_rdd.mapPartitions(lambda x: reader(x)) #fares_rdd.take(10) #trips dataset trips_rdd = sc.textFile("/user/hc2660/hw2data/Trips.csv", 1) trips_rdd = trips_rdd.mapPa...
Zeus197/bigdata_assignment
assignment1/task3b.py
task3b.py
py
1,629
python
en
code
0
github-code
6
22893421369
# -*- coding: utf-8 -*- from collective.transmogrifier.interfaces import ISection from collective.transmogrifier.interfaces import ISectionBlueprint from collective.transmogrifier.utils import resolvePackageReferenceOrFile from zope.interface import classProvides from zope.interface import implements import os try: ...
eikichi18/collective.jsonmigrator
collective/jsonmigrator/blueprints/source_json.py
source_json.py
py
1,658
python
en
code
null
github-code
6
40333923387
import numpy as np import wave import pyaudio from scipy.io import wavfile from scipy import interpolate import math import matplotlib.pyplot as plt #MaxVal = 2147483647 MaxVal = 2147483647 #found relavant blog post: #http://yehar.com/blog/?p=197 def clippingFunction(inSample): threshold = MaxVal #maximum 24 bit out...
theshieber/Spline-Filter
splinefilterPOC.py
splinefilterPOC.py
py
3,288
python
en
code
0
github-code
6
70799503229
import numpy as np import matplotlib.pyplot as plt import pandas as pd import requests import random from itertools import count # Request fails unless we provide a user-agent api_response = requests.get('https://api.thevirustracker.com/free-api?countryTimeline=US', headers={"User-Agent": "Chrome"}) ...
it2515/Covid-19
Covid19.py
Covid19.py
py
1,590
python
en
code
0
github-code
6
24823838001
import ctypes from lone.util.struct_tools import ComparableStruct class RegsStructAccess(ComparableStruct): def read_data(self, get_func, offset, size_bytes): read_data = bytearray() for read_byte in range(size_bytes): read_data += get_func(offset).to_bytes(1, 'little') of...
edaelli/lone
python3/lone/nvme/spec/registers/__init__.py
__init__.py
py
3,603
python
en
code
3
github-code
6
13322067740
import sys import getopt import time import random import os import math import Checksum import BasicSender ''' This is a skeleton sender class. Create a fantastic transport protocol here. ''' class Sender(BasicSender.BasicSender): def __init__(self, dest, port, filename, debug=False): super(Sender, self)...
weichen-ua/MIS543O_Project2
Sender.py
Sender.py
py
2,910
python
en
code
3
github-code
6
20395581562
"""empty message Revision ID: fbfbb357547c Revises: 2152db7558b2 Create Date: 2021-05-07 17:56:36.699948 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'fbfbb357547c' down_revision = '2152db7558b2' branch_labels = None depends_on = None def upgrade(): # ...
metalsalmon/remote_monitoring
migrations/versions/fbfbb357547c_.py
fbfbb357547c_.py
py
653
python
en
code
0
github-code
6
38649574551
import csv import unicodedata import re def strip_accents(string): """ Remove acentos e caracteres especiais de uma string :param string: String para remoção dos acentos e caracteres especiais :return String sem acentos e caracteres especiais: """ return ''.join(ch for ch in unicodedata.normali...
RayBasilio123/desafio-estagio-desenvolvimento-2022Q1-Ray_da_Silva_Basilio
main.py
main.py
py
5,381
python
pt
code
0
github-code
6
72824107709
# [변수와 데이터타입] # 주석(comment) : # 입력 또는 ctrl + / 로 표현한다. 메모같은 것 # 변수(variable) : 변하는 수 id = "pencil" print(id) print("뭐로 쓸까요? - ",id,"으로 쓰죠.") # 숫자 변수 : ""를 입력하지 않으며, 숫자. 연산가능. 데이터타입이 숫자인 변수. num = 10 plus = 1 minus = 2 multiply = 3 divide = 5 print(num + plus) print(num - minus) print(num * multiply) # 30 print(num / d...
Azumait/grammar1
document1_수집/4_students_list1/교육완료자/전소연 파이썬/python jsy/1.py
1.py
py
3,141
python
ko
code
0
github-code
6
22877254400
import matplotlib.pyplot as plt import math for number in range(0,15,5): formatString = "%0.1f" % (number/10.0) filename = "data/stats_2000n_"+formatString+"00000th_"+str(int(number/10) + 1)+"00000times_0.600000kmin_0.200000kstep_2.000000kmax_10statsize.dat" f = open(filename, 'r') headers = f...
vitchyr/Research-in-Math
degree_model/data_analysis.py
data_analysis.py
py
1,119
python
en
code
4
github-code
6
25144655510
# pylint: disable=W0611, E0401 """ Main goal of this module is to scrape and parse data from "visityerevan.am" website """ import logging import sys from dataclasses import dataclass from urllib.parse import urljoin from httpx import Client from selectolax.parser import HTMLParser, Node logger = loggi...
EPguitars/events-parsing-archive
standalone/scraper_visityerevan.py
scraper_visityerevan.py
py
6,391
python
en
code
1
github-code
6
43462667811
import pyshorteners def shorten(url): link = pyshorteners.Shortener() return link.tinyurl.short(url) if __name__ == "__main__": url = input("Enter link for sorting:") print(f"\n {shorten(url)}") # https://github.com/urmil89
urmil404/url-Sorter
main.py
main.py
py
245
python
en
code
0
github-code
6
71861349309
import os import sys # 修改工作目录为程序所在目录,这样通过注册表实现开机自动启动时也能获取到正确的工作目录 # PS: 放到这个地方,是确保在所有其他初始化代码之前先修改掉工作目录 dirpath = os.path.dirname(os.path.realpath(sys.argv[0])) old_path = os.getcwd() os.chdir(dirpath) import argparse import datetime import time from multiprocessing import freeze_support import psutil import ga from...
fzls/djc_helper
main.py
main.py
py
10,763
python
zh
code
319
github-code
6
38750349973
from imagenet_c import * from torchvision.datasets import ImageNet import torchvision.transforms as transforms from torch.utils.data import DataLoader import os import torch import gorilla DATA_ROOT = './data' CORRUPTION_PATH = './corruption' corruption_tuple = (gaussian_noise, shot_noise, impulse_noise, defocus_blu...
Gorilla-Lab-SCUT/TTAC
imagenet/utils/create_corruption_dataset.py
create_corruption_dataset.py
py
1,892
python
en
code
37
github-code
6
71634339387
from flask import Flask import requests URL="https://en.wikipedia.org/w/api.php" app = Flask(__name__) #configuring the server name as required app.config['SERVER_NAME'] = "wiki-search.com:5000" @app.route("/") def home(): return 'Enter you query as the subdomain.' @app.route('/', subdomain="<SEA...
jubinjacob93/Opensearch-Server
wiksearch.py
wiksearch.py
py
1,513
python
en
code
0
github-code
6
20801954442
import math from os import TMP_MAX MAX = 700 lookup = [[0 for i in range(100001)] for j in range(20)] def buildSparseTable(arr, n): for i in range(0, n): lookup[i][0] = arr[i] j = 1 while (1 << j) <= n: i = 0 while (i + (1 << j) - 1) < n: ...
michbogos/olymp
eolymp/summation/RMQ.py
RMQ.py
py
1,109
python
en
code
0
github-code
6
22477012107
import pandas as pd import timeit pd.set_option('mode.chained_assignment', None) def main(): print('ok') def sortim(df): new_cols = ['PERFIL','BANDEIRA','LOCAL_NOVO','LOCAL','TAMANHO','REGIÃO','REGIAO 2','CONCATENADO','CONCATENADO 2','CONCATENADO 3','CONCATENADO 4','CONCATENADO 5'] for i i...
zameethi/Flask_Rel_New
apps/sortemp_sortim.py
sortemp_sortim.py
py
9,072
python
pt
code
0
github-code
6
10364079292
from wordbank import wbank import random state = { 'word': '', 'history' : [], 'gc' : 0 } def userguess(inp, state) -> dict: guess = list(inp.upper()) wo = list(state['word']) out = [] for lg in guess: if lg in wo: out.append(('yell...
aaronlael/cli_wordle
wordle.py
wordle.py
py
1,928
python
en
code
0
github-code
6
30814400750
__author__ = "https://github.com/kdha0727" import os import functools import contextlib import torch import torch.distributed as dist from torch.cuda import is_available as _cuda_available RANK = 0 WORLD_SIZE = 1 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ...
studio-YAIVERSE/studio-YAIVERSE
dist_util.py
dist_util.py
py
3,621
python
en
code
20
github-code
6
74987096188
from deep_rl_for_swarms.common import explained_variance, zipsame, dataset from deep_rl_for_swarms.common import logger import deep_rl_for_swarms.common.tf_util as U import tensorflow as tf, numpy as np import time import os from deep_rl_for_swarms.common import colorize from mpi4py import MPI from collections import d...
jparras/dla
deep_rl_for_swarms/rl_algo/trpo_mpi/trpo_mpi_attack.py
trpo_mpi_attack.py
py
17,701
python
en
code
0
github-code
6
18490735964
import boto3 import json import uuid print('Loading function') def lambda_handler(event, context): bucketName = event['Records'][0]['s3']['bucket']['name'] fileName = event['Records'][0]['s3']['object']['key'] return detect_labels_and_put_dynamoDB(fileName, bucketName) def detect_labels_and_put_dynam...
Samir42/RekognitionService
RekognitionLambda.py
RekognitionLambda.py
py
1,249
python
en
code
0
github-code
6
72279625789
import firebase_admin import googleapiclient from firebase_admin import credentials from firebase_admin import db import os from os.path import join, dirname from dotenv import load_dotenv from XmlParser import XmlParser class FirebaseService: dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_p...
CIDRA4023/Hologram-backend
FirebaseService.py
FirebaseService.py
py
2,457
python
ja
code
0
github-code
6
20157578435
import numpy as np import pandas as pd import time from metric import SampleScore,EventScore, AdjustedMutualInfoScore from joblib import Parallel, delayed class Experiment: def __init__(self,algorithms:list, configurations:list, thresholds = np.linspace(0,1,101),njobs=1,verbose = True) -> None: "...
thibaut-germain/lt-normalized
src/experiment.py
experiment.py
py
7,754
python
en
code
0
github-code
6
45483801886
import pickle import numpy as np import random import os import pandas as pd import yaml import copy from tqdm import tqdm from . import utils from . import visual import xarray as xr from .proxy import ProxyDatabase from .gridded import Dataset from .utils import ( pp, p_header, p_hint, p_success, ...
fzhu2e/LMRt
LMRt/reconjob.py
reconjob.py
py
45,613
python
en
code
9
github-code
6
35988325228
import joblib model = None def init_model( db, model_themes_path='./flaskr/model/log_reg_themes', model_cats_path='./flaskr/model/log_reg_cats' ): global model cur = db.cursor() query = """ select id from theme order by id; """ cur.execute(query) theme_ids = [id[0] for id in ...
dimayasha7123/kursach3
flaskr/model/model.py
model.py
py
1,979
python
en
code
0
github-code
6
74200612027
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : train.py # @Author: stoneye # @Date : 2023/09/01 # @Contact : stoneyezhenxu@gmail.com import tensorflow as tf import tensorflow.contrib.slim as slim import utils from models import ModelUtil from models import NextvladModel from models import TextExactor from m...
stoneyezhenxu/Multimodal_Video_Classification
src/video_model.py
video_model.py
py
23,282
python
en
code
0
github-code
6
14025841679
""" @author: Yuhao Cheng @contact: yuhao.cheng[at]outlook.com """ #!!!!! ignore the warning messages import warnings warnings.filterwarnings('ignore') import os import pickle import math import torch import time import numpy as np from PIL import Image from collections import OrderedDict import torchvis...
YuhaoCheng/PyAnomaly
pyanomaly/core/engine/functions/memae.py
memae.py
py
3,913
python
en
code
107
github-code
6
3167027289
#!/usr/bin/env python3 import random from typing import Tuple from functions.aes import AESCipher, pkcs7_pad, get_blocks, gen_random_bytes def _encryption_oracle(bytes_: bytes) -> Tuple[bytes, str]: key = gen_random_bytes(16) iv = gen_random_bytes(16) prefix = gen_random_bytes(random.randint(5, 10)) ...
svkirillov/cryptopals-python3
cryptopals/set2/challenge11.py
challenge11.py
py
1,185
python
en
code
0
github-code
6
27867118318
import tensorflow as tf from utils.nn import linear from .tdnn import TDNN def embed_characters(input, vocab_size, embed_dim=40, scope=None, reuse=None, use_batch_norm=True, use_highway=True, highway_layers=2): """ Character-level embedding """ with tf.variable_scope(scope or 'Embedder') as scop...
therne/logue
models/embedding.py
embedding.py
py
2,203
python
en
code
0
github-code
6
21897871134
import got3 import pymongo from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer # connect to mongo deamon connection = pymongo.MongoClient("mongodb://localhost") # connect to the collection called uber_tweets in the kubrick db db = connection.kubrick.uberban_tweets count = 0 try: while True: ...
JackJoeKul/cities-in-need
Old UberBan Tweets Scrape + Sentiment Analysis/old_tweets.py
old_tweets.py
py
906
python
en
code
0
github-code
6
26999768171
import random def structDataSampling(**kwargs): global tmp result = list() num = kwargs.get("num", -1) if num == -1: raise Exception("Wrong number input") for index in range(0, num): element = list() for key, value in kwargs.items(): if key == "int":...
wanghan79/2023_Python
2021011593陈俊聪/PythonFinalTest_2021011593cjc/work_1_cjc/RandomDataSampling.py
RandomDataSampling.py
py
1,194
python
en
code
8
github-code
6
30489464890
from .master import Master import numpy as np import poselib import time import math import test_module.linecloud as lineCloudTest import test_module.recontest as recontest import utils.pose.pose_estimation as pe import utils.pose.vector as vector from utils.pose import dataset from utils.pose import line from utils....
Fusroda-h/ppl
domain/olc.py
olc.py
py
5,682
python
en
code
3
github-code
6
31515309886
#!/usr/bin/env python3 """ Machine Translation model with RNN's """ import tensorflow as tf SelfAttention = __import__('1-self_attention').SelfAttention class RNNDecoder(tf.keras.layers.Layer): """ RNN Decoder part of the translation model """ def __init__(self, vocab, embedding, units, batch): ...
macoyulloa/holbertonschool-machine_learning
supervised_learning/0x11-attention/2-rnn_decoder.py
2-rnn_decoder.py
py
2,882
python
en
code
0
github-code
6
36153730574
import boto3 import traceback import datetime import os from botocore.exceptions import ClientError from ..models.bucket import Bucket from ..util.preprocessor import preprocess """ S3 functions """ def get_active_bucket_or_create_new(username): """ Returns the user's current active bucket. If there are no ...
jkausti/flask-textsapi
app/textsapi/service/s3buckets.py
s3buckets.py
py
5,725
python
en
code
1
github-code
6
1004762180
# -*- coding: utf-8 -*- """ Created on Fri Jan 11 20:06:31 2019 @author: saksake """ import numpy as np from sklearn.datasets import load_iris def datasets() : # LOAD BOSTON HOUSING DATASET boston = load_iris() # MAKE FEATURE DICTIONARY all_features = {} for i in range(len(boston.feature_nam...
rofiqq/Machine-Learning
High_API/classifier/iris/iris.py
iris.py
py
5,883
python
en
code
0
github-code
6
1197619153
""" 13. ​ Write a Python program that accepts a comma separated sequence of words as input and prints the unique words in sorted form (alphanumerically). """ def sort_comma_seperated_words(sentence): if not sentence.__contains__(","): raise Exception("Only Comma Separated sentences is Accepted!") slit...
asmitbhantana/Insight-Workshop
PythonProgrammingAssignmentsI/Data Types/q13.py
q13.py
py
553
python
en
code
0
github-code
6
8625677438
import numpy as np import copy import random import math value_points = { 'J' : 11, 'Q' : 12, 'K' : 13, 'A' : 14} hh_dict = { 'straight_flush' : 9, 'four_of_a_kind' : 8, 'full_house' : 7, 'flush' : 6, 'straight' : 5, 'three_of_a_kind' : 4, 'two_pair' : 3, 'pair' : 2, 'high_card' : 1} #Takes list of 5 C...
bspringw/poker
poker_functions.py
poker_functions.py
py
7,314
python
en
code
0
github-code
6
24506033331
from nose.tools import eq_ from mock import patch, Mock, sentinel from noderunner.process import open_process @patch("subprocess.Popen", return_value=sentinel.proc) def test_open_process(p): ret = open_process(sentinel.fd, sentinel.secret, nodepath=sentinel.node_path...
williamhogman/noderunner
tests/test_process.py
test_process.py
py
379
python
en
code
6
github-code
6
6827552389
""" https://adventofcode.com/2020/day/10 """ from typing import Dict, List from collections import defaultdict Adapters = List[int] def part1(adapters: Adapters) -> int: """ O(nLogn) solution """ jolts = 0 diffs: Dict[int, int] = defaultdict(int) for adapter in sorted(adapters): diffs[adapt...
pozhega/AoC
2020/d10.py
d10.py
py
1,164
python
en
code
0
github-code
6
6854075721
from flask import Flask,request,render_template,redirect, url_for from flask import jsonify import requests from cassandra.cluster import Cluster from collections import OrderedDict app = Flask(__name__) KEYSPACE = "twitterkeyspace" @app.route('/', methods=['GET']) def home(): if request.method == 'GET': return r...
piyush-jain1/Databases
Cassandra/Assignment2/app.py
app.py
py
3,427
python
en
code
0
github-code
6
22049716249
from os import name import sys import requests import time import threading sys.path.append('../') from DeskFoodModels.DeskFoodLib import Item, OrderStatus, Order from PyQt5.uic import loadUi from PyQt5 import QtWidgets from PyQt5.QtWidgets import QCheckBox, QComboBox, QDialog, QApplication, QListWidget, QMenu, QPushBu...
YY0NII/DeskFood
Frontend/Main.py
Main.py
py
33,421
python
en
code
1
github-code
6
41236533985
import rest_framework.authentication from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import permissions from user.auth.auth import JwtQueryParamsAuthentication schema_view = get_schema_view( openapi.Info( title="接口文档", default_version="1.0", term...
beishangongzi/porcelain-backend
swagger_doc/views.py
views.py
py
653
python
en
code
0
github-code
6
21998584846
from typing import List class Solution: def findPeakElement(self, nums: List[int]) -> int: n = len(nums) left = 0 right = n - 1 def get_num(i): if i == -1 or i == n: return float('-inf') return nums[i] ans = -1 while right >...
hangwudy/leetcode
100-199/162. 寻找峰值.py
162. 寻找峰值.py
py
620
python
en
code
0
github-code
6
16105808925
#Server from socket import * serverPort = 12002 listeningSocket = socket(AF_INET, SOCK_STREAM) listeningSocket.bind(('', serverPort)) listeningSocket.listen(1) print('Server ready, socket', listeningSocket.fileno(), 'listening on localhost :', serverPort) connectionSocket, addr = listeningSocket.accept() #client addres...
kelly870114/TCPSocket
TCPServer.py
TCPServer.py
py
598
python
en
code
0
github-code
6
9007439548
""" Week 2 - Data mining By Christopher Diaz Montoya """ # Problem 1!! store=[] # Empty array to store values for a in range (1000, 2000): # Loop to check over all numbers in range if (a % 11 == 0) and not (a % 3 == 0): # Above line makes sure if multiple of 11 and not of 3 execute line below sto...
diaz080800/Python-programming
Week 2/Week2.py
Week2.py
py
6,360
python
en
code
0
github-code
6
70327957627
#!/usr/bin/env python3 import rospy from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from math import sqrt, atan2, exp, atan, cos, sin, acos, pi, asin, atan2, floor from tf.transformations import euler_from_quaternion, quaternion_from_euler from time import sleep import sys import numpy as np impor...
lucca-leao/path-planning
scripts/Astar.py
Astar.py
py
9,706
python
en
code
1
github-code
6
9903389782
# UDP receiver # Olle Bergkvist & August M Rosenqvist from socket import * serverPort = 12000 counter = 10000 # Create UDP socket and bind to specified port serverSocket = socket(AF_INET, SOCK_DGRAM) serverSocket.bind(('', serverPort)) print ("The UDP receiver is ready to receive.\n") while True: # Read client...
ollebergkvist/telekom-lab2
UDPreceiver.py
UDPreceiver.py
py
821
python
en
code
0
github-code
6
37379213866
#影像命名:县(0表示西秀,1表示剑河县)_序号(在points列表中的序号,从0开始)_同一位置的序号(同一位置可能有多张,标个序号,从0开始)_年份(2021之类的)_img #施工标签命名:县(0表示西秀,1表示剑河县)_序号(在points列表中的序号,从0开始)_年份(2021之类的)_conslabel #分类标签命名:县(0表示西秀,1表示剑河县)_序号(在points列表中的序号,从0开始)_2021_classlabel from osgeo import gdal,osr import pickle import os import numpy def getSRSPair(dataset)...
faye0078/RS-ImgShp2Dataset
lee/clip_label.py
clip_label.py
py
5,260
python
en
code
1
github-code
6
74128409788
from collections import deque def find_correct(string): stack = [] for c in string: if c == "[" or c == "{" or c == "(": stack.append(c) else: if "[" in stack and c == "]" and stack[-1] == "[": stack.pop() elif "{" in stack and c == "}" and st...
Dayeon1351/TIL
programmers/level2/괄호회전하기/solution.py
solution.py
py
781
python
en
code
0
github-code
6
45364250336
import pygame import solveModuleNotFoundError from Game import * from Game.Scenes import * from Game.Shared import * class Breakout: def __init__(self): self.__lives = 5 self.__score = 0 self.__level = Level(self) self.__level.load(0) self.__pad = Pad((GameC...
grapeJUICE1/Grape-Bricks
Game/Breakout.py
Breakout.py
py
2,928
python
en
code
7
github-code
6
23915032189
from django.contrib.auth.decorators import login_required from django.contrib.auth import login from django.shortcuts import render_to_response, redirect from django.template import RequestContext from apps.data.models import Entry from apps.data.forms import DataForm from django.conf import settings from django.core.u...
msakhnik/just-read
apps/data/views.py
views.py
py
1,497
python
en
code
0
github-code
6
15802748190
from django.conf.urls import url, include from django.contrib import admin from rest_framework.documentation import include_docs_urls api_patterns = [ url(r'^docs/', include_docs_urls(title='Documentation')), url(r'^', include(('my_website.apps.youtube_download.urls', 'youtube_download'), namespace='yout...
zsoman/my-website
my_website/urls.py
urls.py
py
902
python
en
code
0
github-code
6
16398002041
import os import pygame from Engine import MainMenu from Entities.Maps.SimpleCheck import SimpleCheck, ConditionsType class BlockChecks(SimpleCheck): def __init__(self, ident, name, positions, linked_map): SimpleCheck.__init__(self, ident, name, positions, linked_map, True) self.position_logic_i...
linsorak/LinSoTracker
Entities/Maps/BlockChecks.py
BlockChecks.py
py
5,551
python
en
code
3
github-code
6
33272837414
import concurrent.futures import timeit import matplotlib.pyplot as plt import numpy from controller import Controller def mainUtil(): result = [] for i in range(50): c = Controller(300) c.GradientDescendAlgorithm(0.000006, 1000) result.append(c.testWhatYouHaveDone()) return result if _...
CMihai998/Artificial-Intelligence
Lab7 - GDA/main.py
main.py
py
1,133
python
en
code
3
github-code
6
73549678908
__doc__ = """ Script for collection of training data for deep learning image recognition. Saving standardised pictures of detected faces from webcam stream to given folder. Ver 1.1 -- collect_faces.py Author: Aslak Einbu February 2020. """ import os import cv2 import datetime import imutils import time import numpy...
aslake/family_deep_learning
collect_faces.py
collect_faces.py
py
3,826
python
en
code
1
github-code
6
20908637143
from python_app_configs import config from python_generic_modules import se_os from python_generic_modules import se_docker import re import os import glob import time import jinja2 template1 = jinja2.Template("{% for i in range(0,last_num)%}zookeepernode{{ i }}.{{ domain }}:2181{% if not loop.last %},{% endif %}{% en...
karthikmahesh2611/docker_hadoop
python_hadoop_modules/kafka.py
kafka.py
py
4,120
python
en
code
0
github-code
6
10775009029
def enumerate2(xs, start=0, step=1): for x in xs: yield (start, x) start += step data = list(open("./03-input.txt").read().splitlines()) for s in ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2)): data2 = [(d, i, i % len(d), d[i%len(d)]) for i, d in enumerate2(data[::s[1]], step=s[0])] print(sum([d...
knjmooney/Advent-Of-Code
2020/03-toboggan.py
03-toboggan.py
py
348
python
en
code
0
github-code
6
30061736104
import os,sys,random import veri NewName = os.path.expanduser('~') if os.path.exists('%s/vlsistuff' % NewName): sys.path.append('%s/vlsistuff/verification_libs3'%NewName) elif 'VLSISTUFF' in os.environ: sys.path.append('%s/verification_libs3'%os.environ['VLSISTUFF']) else: print("please set VLSISTUFF t...
greenblat/vlsistuff
rtl_library/round_robin/verilog.py
verilog.py
py
2,502
python
en
code
41
github-code
6
19092857489
from collections import namedtuple import csv import gzip import logging import sys import urllib.parse csv.field_size_limit(sys.maxsize) logging.basicConfig(level=logging.INFO) Switch = namedtuple("Switch", ['srclang', 'targetlang', 'country', 'qid', 'title', 'datetime', 'usertype', 'title_country_src_count']) Sessi...
geohci/language-switching
session_utils.py
session_utils.py
py
8,958
python
en
code
2
github-code
6
25508679765
#!/usr/bin/env python3 import shutil import psutil import socket import report_email import time import os def check_disk_usage(disk): disk_usage = shutil.disk_usage(disk) free = (disk_usage.free / disk_usage.total) * 100 return free > 20 def check_cpu_usage(): usage = psutil.cpu_percent(1) return usage < ...
paesgus/AutomationTI_finalproject
health_check.py
health_check.py
py
1,330
python
en
code
0
github-code
6
72143877628
''' Escribir un programa en Python que convierta millas a kilómetros. Se deben imprimir los siguientes mensajes: Bienvenido (ingrese su nombre): <nombre> Ingrese las millas a convertir: <millas> Hola <nombre>, la conversión resulta: <resultado> km Guarde el programa en un archivo que se llame m2k.py ''' name = input(...
levensworth/udesa-pc-tutorial
2022-b/1-operaciones/clase_3_e2.py
clase_3_e2.py
py
767
python
es
code
2
github-code
6
74227616828
from flask import render_template,request,redirect,url_for from . import main from ..request import get_news_sources,get_allArticles,get_headlines from ..models import Sources, Articles #views @main.route('/') def index(): ''' View root page function that returns the index page and its data ''' # getti...
chanaiagwata/News_API
app/main/views.py
views.py
py
1,612
python
en
code
0
github-code
6
27614632298
# coding:utf-8 from appium import webdriver class Werdriver: def get_driver(self): configure = { "platformName": "Android", "deviceName": "PBV0216922007470", "app": "/Users/luyunpeng/Downloads/ci_v1.5.0_2019-07-18_16-35_qa.apk", "noReset": "true" ...
lyp0129/study_appium
get_driver/test_driver.py
test_driver.py
py
497
python
en
code
0
github-code
6
22371526331
from odoo import api, SUPERUSER_ID def post_init_hook(cr, registry, vals=None): """For brand new installations""" env = api.Environment(cr, SUPERUSER_ID, {}) # Change only those with no weight already set products_init = env['product.product'].search([ ('weight', '=', 0), ]).filtered('is_w...
detian08/bsp_addons
product-attribute-11.0/product_weight_through_uom/hooks.py
hooks.py
py
425
python
en
code
1
github-code
6
21951291908
#Описать функцию AddRightDigit(D, K), добавляющуюю к целому числу положительному #числу К справа цифру D(D - входной параметр целого типа лежащий в диапазоне от 0 до 9, К - параметр целого типа, # являющийся входным и выходный одновременно). С помощью функции последовательно добавиить к данному числу К справа данный ц...
DaNil4594/EremenkoPythonProject
PZ_5/PZ_5_2.py
PZ_5_2.py
py
1,320
python
ru
code
0
github-code
6
5449785498
from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD import matplotlib.pyplot as plt from keras.datasets import cifar10 from keras.utils import np_utils (xtrain,ytrain),(xtest,ytest) = cifar10.load_data() print('xtrain.shape',xtrain.shape) print('ytrain.shape',ytrain.shape...
daftengineer/kerasSagemaker
test.py
test.py
py
1,101
python
en
code
0
github-code
6
23186461899
"""FECo3: Python bindings to a .fec file parser written in Rust.""" from __future__ import annotations import os from functools import cached_property from pathlib import Path from typing import TYPE_CHECKING, NamedTuple from . import _feco3, _version if TYPE_CHECKING: import pyarrow as pa __version__ = _versi...
NickCrews/feco3
python/src/feco3/__init__.py
__init__.py
py
5,512
python
en
code
2
github-code
6
1530038484
import requests import json from bs4 import BeautifulSoup def songwhip_it(url): html = requests.get('https://songwhip.com/'+url).content soup = BeautifulSoup(html, 'html.parser') links_text = list(soup.findAll('script'))[2].get_text() links_json = json.loads(links_text[links_text.index('{'):-1])['links...
kartikye/q
linker.py
linker.py
py
415
python
en
code
0
github-code
6
34142194304
import numpy as np import scipy.constants from pathlib import Path class ElectricAcceleration: bodies = [] def __init__(self, bodies): """This will allow the list of particles from the Accelerator module to be inserted letting the ElectricAcceleration class calculate their acceleration""" ...
Lancaster-Physics-Phys389-2020/phys389-2020-project-twgrainger
LidlFieldV1.py
LidlFieldV1.py
py
3,815
python
en
code
0
github-code
6
74179568189
''' To run test: move into same directory as spotify_api.py file ''' import unittest import spotify_api import spotipy import pandas as pd from spotipy.oauth2 import SpotifyClientCredentials client_id = 'ea776b5b86c54bd188d71ec087b194d3' client_secret = '1e0fcbac137c4d3eb2d4cc190693792a' # keep this ...
dylanmccoy/songtrackr
tests/spotify_unittest.py
spotify_unittest.py
py
2,431
python
en
code
0
github-code
6
3967140891
import torch def batch_horizontal_flip(tensor, device): """ :param tensor: N x C x H x W :return: """ inv_idx = torch.arange(tensor.size(3) - 1, -1, -1).long().to(device) img_flip = tensor.index_select(3, inv_idx) return img_flip def euclidean_dist(x: torch.Tensor, y: torch.Tensor): ...
clw5180/reid-baseline
utils/tensor_utils.py
tensor_utils.py
py
1,068
python
en
code
null
github-code
6
10137995508
import socket sock = socket.socket() server_address = ('localhost', 9080) print('connecting to {} port {}'.format(*server_address)) sock.connect(server_address) message = str.encode("CREATE TABLE VADICS (id int, name str);") try: print('sending {!r}'.format(message)) sock.sendall(message) amount_receive...
etozhezhenechka/VadikDB
client.py
client.py
py
574
python
en
code
0
github-code
6
43346750218
if __name__ == '__main__': from ovh import * import argparse import logging logger = logging.getLogger("ovh/download_db") parser = argparse.ArgumentParser(description='Creates N workers on the OVH cloud.') parser.add_argument('--db-name', default='Contrastive_DPG_v2', help='name for MySQL DB')...
charleswilmot/Contrastive_DPG
src/ovh_download_db.py
ovh_download_db.py
py
899
python
en
code
0
github-code
6
36407185173
import pytest from logging import getLogger from barbucket.domain_model.types import * _logger = getLogger(__name__) _logger.debug(f"--------- ---------- Testing Types") def test_api_correct() -> None: _logger.debug(f"---------- Test: test_api_correct") try: test_api = Api.IB except AttributeEr...
mcreutz/barbucket
tests/domain_model/test_types.py
test_types.py
py
3,398
python
en
code
0
github-code
6
73022500347
import threading def even_list_sum(numbers): even_sum = sum(x for x in numbers if x % 2 == 0) print(f"Sum of even elements: {even_sum}") def odd_list_sum(numbers): odd_sum = sum(x for x in numbers if x % 2 != 0) print(f"Sum of odd elements: {odd_sum}") def main(): input_str = input("Enter a list...
vedangthete30/Python-Assignments
Assignment 7/Assignment7_3.py
Assignment7_3.py
py
738
python
en
code
0
github-code
6
30168009886
import requests import pandas as pd import arrow import warnings import io from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib import logging warnings.filterwarnings('ignore', 'Unverified HTTPS request') url = "https://protect.cylance.com/Reports/ThreatDataReport...
cmoxley1/Cylance
MemTDREmail.py
MemTDREmail.py
py
2,128
python
en
code
0
github-code
6
43347425408
import numpy as np import os from collections import defaultdict, namedtuple import re from mpl_toolkits.axes_grid1.inset_locator import inset_axes class Collection(object): def __init__(self, path): self.path = path self.name = path.strip("/").split("/")[-1] self.data = defaultdict(list) ...
charleswilmot/lossy_compression
src/collection.py
collection.py
py
5,139
python
en
code
0
github-code
6
38200290752
import speech_recognition as sr import pyttsx3 import screen_brightness_control as sbc import geocoder from geopy.geocoders import Nominatim r = sr.Recognizer() def SpeakText(command): engine = pyttsx3.init() engine.say(command) engine.runAndWait() while(1): try: with sr.Microphon...
Priyanshu360-cpu/Machine-Learning
repeat_audio.py
repeat_audio.py
py
746
python
en
code
3
github-code
6
71053381947
import logging import os logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.propagate = False # do not propagate logs to previously defined root logger (if any). formatter = logging.Formatter('%(asctime)s - %(levelname)s(%(name)s): %(message)s') # console consH = logging.StreamHandler() consH...
ChenShengsGitHub/structure-based-peptide-generator
cfg.py
cfg.py
py
5,610
python
en
code
0
github-code
6
36766343172
from sys import stdin n, m, v = map(int, stdin.readline().split()) graph = [[0]*(n+1) for _ in range(n+1)] visited = [False]*(n+1) # 간선 입력받기 for _ in range(m): x, y = map(int, stdin.readline().split()) graph[x][y] = 1 graph[y][x] = 1 def dfs(v): visited[v] = True print(v, end=" ") for i in ra...
jiyoung-dev/Algorithm
2021study/dfs bfs/b1260_dfs와bfs.py
b1260_dfs와bfs.py
py
727
python
en
code
0
github-code
6
42862238176
import pgzrun import random import time import pygame.time # import pygame TITLE = "Brickbreaker" # initial score is 0 # time is use to get the initial time and stores in the variable 'start time' score = 0 # as ball hits the brick, score changes by 10 score_point = 10 start_time = time.time () elapsed_time = 0 # se...
Nirrdsh/py-game
Assignment.py
Assignment.py
py
6,033
python
en
code
1
github-code
6
34050613320
import tensorflow as tf import numpy as np def model(X): X = X / 255 conv1 = tf.layers.batch_normalization(tf.layers.conv2d(X, 64, 6, activation=tf.nn.leaky_relu, padding="SAME")) pool1 = tf.layers.max_pooling2d(conv1, 2, 2) conv2 = tf.layers.batch_normalization(tf.layers.conv2d(pool1, 128...
AbdelrahmanEldakrony/yolo-object-detection
yolo.py
yolo.py
py
4,066
python
en
code
0
github-code
6
71276866109
import setuptools with open("README.md", "r") as file: long_description = file.read() with open("requirements.txt", "r") as file: required_packages = file.read().splitlines() setuptools.setup( name="labscribe", version="0.4.7", author="Jay Morgan", author_email="jay.p.morgan@outlook.com", ...
jaypmorgan/labscribe
setup.py
setup.py
py
729
python
en
code
0
github-code
6
19124524287
from google.appengine.ext import ndb from components import utils import gae_ts_mon import config import model FIELD_BUCKET = 'bucket' # Override default target fields for app-global metrics. GLOBAL_TARGET_FIELDS = { 'job_name': '', # module name 'hostname': '', # version 'task_num': 0, # instance ...
mithro/chromium-infra
appengine/cr-buildbucket/metrics.py
metrics.py
py
4,246
python
en
code
0
github-code
6
40238915211
from setuptools import setup, find_packages requires = [ 'buildbot', 'python-debian', 'xunitparser', ] setup( name='buildbot-junit', version='0.1', description='Junit for buildbot', author='Andrey Stolbuhin', author_email='an.stol99@gmail.com', url='https://github.com/ZeeeL/buildb...
ZeeeL/buildbot-junit
setup.py
setup.py
py
535
python
en
code
3
github-code
6
26273852906
"""Module for test case fixturing functions. """ from birgitta import timing __all__ = ['dataframes', 'write_fixtures'] def dataframes(fixtures, variant_name, spark_session): """Makes dataframes from fixtures. Args: fixtures (dict): Dict of fixtures variant_name (str): Name of fixture varia...
telia-oss/birgitta
birgitta/recipetest/localtest/fixturing.py
fixturing.py
py
1,427
python
en
code
13
github-code
6
30078414055
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.models import Sequential import pandas as pd import matplotlib.pyplot as plt from tensorflow.keras.utils import to_categorical print(tf.__version__) train = pd.read_csv(r"sign_m...
daxjain789/Sign-Language-MNIST-with-CNN
sign_language.py
sign_language.py
py
2,118
python
en
code
0
github-code
6
4783520916
from railrl.misc.exp_util import * from railrl.launchers.exp_launcher import tdm_experiment import railrl.misc.hyperparameter as hyp from railrl.config.base_exp_config import variant as base_exp_variant from multiworld.envs.mujoco.cameras import * from multiworld.core.image_env import get_image_presampled_goals as ima...
snasiriany/leap
experiments/image/train_tdm.py
train_tdm.py
py
5,244
python
en
code
45
github-code
6
15909966165
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' def power_sum(exp): sum = 0 pow = 2 ** int(exp) for i in str(pow): sum = sum + int(i) return(sum) print(power_sum(1000))
beingnishas/projecteuler
016_Power_digit_sum.py
016_Power_digit_sum.py
py
276
python
en
code
0
github-code
6
23378159417
import torch import torch.nn.functional as F import torch.nn as nn import torch.nn.utils as utils LRELU_SLOPE = 0.1 def get_padding(kernel_size, dilation=1): return int((kernel_size*dilation - dilation)/2) def init_weights(m, mean=0.0, std=0.01): if isinstance(m, nn.Conv1d): m.weight.data.normal_(me...
uuzall/hifi_gan
model.py
model.py
py
10,620
python
en
code
0
github-code
6
19018842256
# https://atcoder.jp/contests/arc147/submissions/34636074 import sys N = int(sys.stdin.readline().rstrip()) P = [ int(x) for x in sys.stdin.readline().rstrip().split() ] ans = [] for i in range(N-2): for j in range(N-3, i-1, -1): if (j+1)%2 == P[j]%2 and (j+3)%2 != P[j+2]%2: P[j], P[j+2] = P...
minheibis/atcoder
questions/ARC147/B/ref_00.py
ref_00.py
py
743
python
en
code
0
github-code
6
2333095008
""" Random agent on Farm0 ===================== """ from rlberry.agents import AgentWithSimplePolicy from rlberry.manager import AgentManager, evaluate_agents, plot_writer_data from rlberry_farms.game0_env import Farm0 from rlberry.agents.torch.utils.training import model_factory_from_env import numpy as np env_ctor,...
farm-gym/rlberry-farms
examples/installation_test.py
installation_test.py
py
1,556
python
en
code
0
github-code
6
12424083867
__author__ = "Vanessa Sochat, Alec Scott" __copyright__ = "Copyright 2021-2022, Vanessa Sochat and Alec Scott" __license__ = "Apache-2.0" from .command import Command import json # Every command must: # 1. subclass Command # 2. defined what container techs supported for (class attribute) defaults to all # 3. define r...
syspack/paks
paks/commands/inspect.py
inspect.py
py
2,263
python
en
code
2
github-code
6
42666755991
# https://www.youtube.com/watch?v=y5DkiL6gIzY&ab_channel=Makekit # https://makecode.microbit.org/#editor pitch = 0 arm = 0 #Arm means on or off for the drone roll = 0 throttle = 0 yaw = 0 radio_group = 7 radio.set_group(radio_group) # Have the display show the radio set_group basic.show_number(radio_group) # To show t...
ogradyra/Cyber-Physical-Systems
weekly-code/week01/online_resources/youtube_video_code.py
youtube_video_code.py
py
2,541
python
en
code
1
github-code
6