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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
34829962744 | import sys
import random
from time import sleep
class Game:
def __init__(self):
self.wins = 0
self.loses = 0
self.RPS = ['Rock', 'Paper', 'Scissors']
self.confirm = ['Yes', 'Y', 'Okay']
def _game(self):
player_rps = input("Please select either rock, paper or scissors: ... | James-Rocker/pygames_portfolio | games/rock_paper_scissors.py | rock_paper_scissors.py | py | 2,260 | python | en | code | 0 | github-code | 6 |
21210874790 | '''
Practica 4
Escribir un programa que pida al usuario un número entero y muestre en pantalla
un triángulo como el siguiente (número ingresado 5):
1
3 1
5 3 1
7 5 3 1
9 7 5 3 1
@utor: Francisco Zamora Saldaña
Programación avanzada 2MM3
'''
print("Triangulo de numeros impare")
while True:
use... | FranciscoZS/PythonCode | practica4.py | practica4.py | py | 954 | python | es | code | 0 | github-code | 6 |
8779553577 | import requests
import logging
from bs4 import BeautifulSoup
logger = logging.getLogger()
logger.setLevel(level=logging.INFO)
class WikiWorker():
def __init__(self) -> None:
self._url = "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
@staticmethod
def _extract_company_sy... | atula28os/Multithreads | workers/WikiWorker.py | WikiWorker.py | py | 1,125 | python | en | code | 0 | github-code | 6 |
22852840076 | class Solution(object):
def groupStrings(self, strings):
"""
:type strings: List[str]
:rtype: List[List[str]]
"""
groups = collections.defaultdict(list)
for s in strings:
groups[tuple(map(lambda x: (ord(x) - ord(s[0])) % 26, s))] += s,
return map(s... | yuweishi/LeetCode | Algorithms/Group Shifted Strings/solution.py | solution.py | py | 344 | python | en | code | 0 | github-code | 6 |
32581486001 | import pickle
import pennylane as qml
from pennylane import numpy as np
from math import pi
from ChemModel import translator, quantum_net
from Arguments import Arguments
# load molecular datasets (OH: 12 qubits)
# OHdatasets = qml.data.load("qchem", molname="OH", basis="STO-3G", bondlength=0.9)
# OHdata = O... | katiexu/QC_Contest_test | chemistryOH.py | chemistryOH.py | py | 1,791 | python | en | code | 0 | github-code | 6 |
9506994070 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import lxml
import lxml.html.clean
import requests
import wikipedia as wp
from transliterate import translit
def get_html_from_text(raw_html):
# clean_args = {
# "javascript": True, # strip javascript
# "page_structure": False, # leave page structur... | OSLL/adfmp18-PiterSights | crawler/site_extractor.py | site_extractor.py | py | 4,706 | python | en | code | 0 | github-code | 6 |
70497736189 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 25 20:15:51 2021
@author: blgnm
"""
import george
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.optimize import minimize
from scipy.optimize import curve_fit
import random
from astropy.stats import biweight_location
impo... | Feliconut/PurduePHYS324-LSST | SupernovaClassification.py | SupernovaClassification.py | py | 36,879 | python | en | code | 0 | github-code | 6 |
7923689727 | import os
from multiprocessing.dummy import Pool as ThreadPool
# Set your opensmile Extracter and path here
exe_opensmile = './opensmile/bin/SMILExtract.exe'
path_config = './opensmile/config/prosody/prosodyShs.conf'
# Set your data path and output path here
data_path = "./wav/"
save_path = './features/' # output fo... | Saxon-Huang/EECS498_presentation_rating_system | extractProsody.py | extractProsody.py | py | 927 | python | en | code | 0 | github-code | 6 |
27411122966 | # original paper setting: -/77.21/87.85
# add char-cnn 200d: 57.30/77.64/87.75
# 1 layer highway body->subject<->comment: 56/76/86
# 1 layer unshared tanh body->subject<->comment: 57.51/77.18/86.41
import tensorflow as tf
# inpa,inpb (b,m,d) maska,maskb (b,m,1)
def ps_pb_interaction(ps, pb, ps_mask, pb_mask, keep_pro... | helloworld729/QCN | utils.py | utils.py | py | 5,047 | python | en | code | 0 | github-code | 6 |
44092813645 | from gym_compete_rllib import create_env
from ray.tune.registry import ENV_CREATOR, _global_registry
def test_create_env():
env_creator = _global_registry.get(ENV_CREATOR, "multicomp")
env_config = {'with_video': False,
"SingleAgentToMultiAgent": False,
"env_name": ... | HumanCompatibleAI/better-adversarial-defenses | gym_compete_rllib/test_load_rllib_env.py | test_load_rllib_env.py | py | 1,332 | python | en | code | 11 | github-code | 6 |
580269488 | import json, requests, pytest
from pydantic import BaseModel, field_validator
from unittest.mock import Mock, MagicMock
class Location:
def __init__(self, longitudecls, latitudecls):
self._longitude = longitudecls
self._latitude = latitudecls
def get_weather(self):
weather_data = requ... | MrDumper/Roma | weather_HW.py | weather_HW.py | py | 4,128 | python | en | code | 0 | github-code | 6 |
24126442093 | import gc
import sys
import wx
from weakref import ref
from testutil import check_collected
foo = 0
success = 0
def test_callafter_leak():
def func():
global foo
foo = 42
wr = ref(func)
wx.CallAfter(func)
del func
# make sure that func runs
wx.GetApp().Yield()
assert wr(... | ifwe/wxpy | src/tests/test_callafter.py | test_callafter.py | py | 804 | python | en | code | 0 | github-code | 6 |
855722734 | #!/usr/bin/env python
# Demonstrate how to use the vtkBoxWidget to control volume rendering
# within the interior of the widget.
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Load a volume, use the widget to control what's volume
# rendered. Basically the idea is that the vtk... | VisTrails/VisTrails | examples/vtk_examples/GUI/VolumeRenderWithBoxWidget.py | VolumeRenderWithBoxWidget.py | py | 4,067 | python | en | code | 100 | github-code | 6 |
25574251157 | """
Name:Hrishikesh Moholkar
file:wordData.py
This file is the main file for
all other working files
"""
from rit_lib import*
class YearCount(struct):
"""
slots for class:
year: integer representing particular year
count:an integer representing count for that year
return:none
"""
_slots=((... | hnm6500/csci141---python | hnm6500/wordData.py | wordData.py | py | 2,117 | python | en | code | 0 | github-code | 6 |
20825309063 | from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
def get_feature_matrix(N = 55):
#initialize the feature vector with zeros.
x_vec = np.zeros((N,3))
x = []
for i in range (N):
im = Image.open("images/image_{number}.jpg".format(number=i+1))
width, height = i... | laurivoipio/MLBP | Round3 - Classification/ML3_2.py | ML3_2.py | py | 4,065 | python | en | code | 0 | github-code | 6 |
15536903566 | import pandas as pd
from sklearn import model_selection
import numpy as np
from sklearn import datasets
def create_k_folds():
# csv with image id, image location and image label.
df = pd.read_csv("train.csv")
# create a new column called kfold and fill it with -1
df["kfold"] = -1
# the next step... | Vuong02011996/Book-Approaching-any-machine-learning-problem | B_Cross validation/cross-validation.py | cross-validation.py | py | 2,781 | python | en | code | 0 | github-code | 6 |
71493783548 | import numpy as np
def minimum_bbox(surface_points:np.ndarray):
'''
The minimum bounding box of a given point cloud
Parameters
----------
surface_points : np.ndarray(Ngamma,d)
The positions of points in a point cloud in 'd' dimensions
Returns
----------
domain : np.ndarray(d,... | LSDOlab/lsdo_genie | lsdo_genie/utils/bounding_boxes.py | bounding_boxes.py | py | 1,233 | python | en | code | 0 | github-code | 6 |
30823175530 | from django.urls import path
from payment import views
app_name = 'payment'
urlpatterns = [
path('canceled/$', views.payment_canceled, name='canceled'),
path('done/$', views.payment_done, name='done'),
path('(?P<id>\d+)/process', views.payment_process, name='process')
]
| studiosemicolon/onlineshop | payment/urls.py | urls.py | py | 287 | python | en | code | 23 | github-code | 6 |
8201001826 | def fight(posseser, intruder):
id = intruder.int_display()
pbid = posseser.pos_bid(id)
pd = posseser.pos_display()
ibid = intruder.int_bid(pd)
# print(round(pd,1), round(id,1), round(pbid,1), round(ibid,1), sep='\t\t\t')
posseser.base_health -= min(pbid,ibid)
posseser.health = min(posseser.h... | rswofxd/evolutionary-game-theory-sim | fight.py | fight.py | py | 579 | python | en | code | 0 | github-code | 6 |
17260440247 | """
Module that can parse chess notation for individual moves. Mostly to debug
things and/or introduce chess states without having to wire up the entire
camera setup on a physical board.
Note that we're using standard Algebraic Notation:
https://en.wikipedia.org/wiki/Algebraic_notation_(chess)
Maybe we move on to FE... | stay-whimsical/screamchess | src/chess/parser.py | parser.py | py | 4,334 | python | en | code | 3 | github-code | 6 |
71779936188 | from student import *
# 管理系统类
class Lms(object):
# 储存学员数据需要的列表
def __init__(self):
self.student_list = []
def bt(self):
print('学号|姓名|性别|年龄|联系电话|身份证号码')
# 功能检查函数--------------------------------------------------------------
def inspect(self):
try:
print(self.s... | goodsimba/LMS | managerSystem.py | managerSystem.py | py | 10,483 | python | en | code | 0 | github-code | 6 |
35351271287 | '''
started on 2022/06/13
end on 2022/xx/xx
@author zelo2
'''
import torch
import torch.nn as nn
class LightGCN(nn.Module):
def __init__(self, n_user, n_item, norm_adj, device, args):
super(LightGCN, self).__init__()
self.device = device
self.n_user = n_user
self.n_item = n_item
... | zelo2/NGCF | LightGCN/lightGCN_model.py | lightGCN_model.py | py | 4,989 | python | en | code | 2 | github-code | 6 |
25240115497 | N = int(input())
trilha = 0
subida = 0
for i in range (N):
valores = input()
valores = valores.split()
M = int(valores[0])
contador1 = 0
contador2 = 0
altura = int(valores[1])
for j in range(1, M+1):
alturanova = int(valores[j])
if alturanova > altura:
... | MateusFerreiraMachado/Programas_Python | Trilha.py | Trilha.py | py | 842 | python | pt | code | 0 | github-code | 6 |
28235938842 | # 寻找一个能复现bug的小图。
# 如果pattern大小为N,则会先检查所有大小为N的图(共2^(N*(N-1)/2)种),再检查大小为N+1的图……直到找到发生错误
# 由于原程序中输出的东西太多,需要先修改源程序,让其将答案输出至1.out和2.out,其余内容可以输出至stdout(本程序中不会做重定向)
# 使用本程序,需要修改N、bin1和bin2,编译一个正确版本和有bug版本的
# 由于我们的dataloader要求不能存在度数为0的点,所以很多生成的图是不合法的,如果报了“vertex number error!”是正常的
import os
N = 5
bin1 = "../build/bin/gpu_gr... | sth1997/GraphSet | scripts/small_graph_check.py | small_graph_check.py | py | 1,612 | python | zh | code | 5 | github-code | 6 |
26705804968 | from random import randint
class TokenGenerator:
def __init__(self, path):
f = open(path,'r')
self.list = []
self.size = 0
for line in f:
self.list.append(line.replace("\n",""))
self.size = self.size+1
def close(self):
f.close()
def get(self):
word = ""
for i in range(0,3):
word = word+self... | blin4444/pcrs | server_side/words.py | words.py | py | 366 | python | en | code | 0 | github-code | 6 |
19875967712 |
import numpy as np
import matplotlib.pyplot as plt
import time
import numpy as np
import pandas as pd
import time
import gc
import random
import sklearn
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_score, GridSearchCV, cross_validate, train_test_split
from sklearn.metrics import accur... | RuizeHu/Gatech_CS_7641_UnsupervisedLearning | code/Clusters_Plot.py | Clusters_Plot.py | py | 6,940 | python | en | code | 0 | github-code | 6 |
35463005885 | from collections import namedtuple, Counter
import warnings
from math import sqrt
import numpy as np
from scipy.stats import special_ortho_group
import pytest
import kwant
from ... import lattice
from ...builder import HoppingKind, Builder, Site
from ...system import NoSymmetry
from .. import gauge
## Utilities
sq... | kwant-project/kwant | kwant/physics/tests/test_gauge.py | test_gauge.py | py | 17,404 | python | en | code | 76 | github-code | 6 |
33522558184 | from django.contrib.auth import get_user_model
from django.utils import timezone
from django.core.mail import send_mail
User = get_user_model()
def wish_birthday():
today = timezone.now().date()
user_list = User.objects.filter(birthday__day=today.day, birthday__month=today.month)
for item in user_li... | napitsakun/backend_task | user/cron.py | cron.py | py | 497 | python | en | code | 0 | github-code | 6 |
26051387150 | with open("26data/26-J1.txt", "r") as f:
data = list(map(int, f.readlines()))[1:]
res = 0
for n in range(len(data)):
for k in range(n + 1, len(data)):
if data[n] + data[k] == 100:
res += 1
del data[k]
break
print(res)
# 3845 - CORRECT
| Woolfer0097/UGE_IT | 26 task/26.py | 26.py | py | 291 | python | en | code | 0 | github-code | 6 |
2710846372 | # just a seperate file for handling the logging
# of sanic to use with logging
from sanic.log import DefaultFilter
import sys
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'accessFilter': {
'()': DefaultFilter,
'param': [0, 10, 20]
},
'errorFilter': {
'()... | AggressivelyMeows/Ping | logging_config.py | logging_config.py | py | 2,044 | python | en | code | 0 | github-code | 6 |
72650125307 | def inputWitdhlong( ) :
wi = float( input('กว้าง : ') )
lo = float( input('ยาว : ') )
return wi, lo
def inputBaseHigh( ) :
ba = float( input('ฐาน : ') )
hi = float( input('สูง : ') )
return ba, hi
def calAndShowAreaSquare( ba, hi ) :
area = ba * hi / 2
print(f'สามเหลี่ยมฐาน {ba} สูง {h... | HowToPlayMeow/pythonproject04 | py5.py | py5.py | py | 567 | python | th | code | 0 | github-code | 6 |
12485496681 | # Create your views here.
id = int()
iditemcourant = int()
#-*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render , redirect
from utilisateur.forms import *
from utilisateur.models import *
#import time
from django.core.urlresolvers import reverse
def utilisateur(request):
if r... | 3SCS/hackaton-130813 | hommilliere/utilisateur/views.py | views.py | py | 8,734 | python | fr | code | 0 | github-code | 6 |
30358149781 | import contextlib
import datetime
import unittest
from traits.api import Date, HasTraits, List
from traitsui.api import DateEditor, View, Item
from traitsui.editors.date_editor import CellFormat
from traitsui.tests._tools import (
BaseTestMixin,
create_ui,
requires_toolkit,
reraise_exceptions,
Too... | enthought/traitsui | traitsui/tests/editors/test_date_editor.py | test_date_editor.py | py | 6,064 | python | en | code | 290 | github-code | 6 |
9489616666 | import healsparse as hs
import healpy as hp
import numpy as np
from optparse import OptionParser
def main():
usage = "%prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("--input_file",type="string",dest="infilename",help="Input file",default='/pool/cosmo01_data1/des/y6_sp_maps/mangle_map... | nsevilla/utilities | converthshp.py | converthshp.py | py | 4,218 | python | en | code | 0 | github-code | 6 |
15271938454 | """
Creating keyspaces in Cassandra:
CREATE KEYSPACE my_keyspace WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};
"""
from faker import Faker
faker = Faker()
def get_registered_user():
return faker.name()+"$"+faker.address()+"$"+faker.year()
"""return {
"name": faker.name(),
"address"... | imnikhilanand/Real-Time-ETL-with-Kafka-Spark-Cassandra | src/produce_data/generate_data.py | generate_data.py | py | 431 | python | en | code | 0 | github-code | 6 |
18308321752 | from unittest import TestCase
from sqlite3 import IntegrityError
import os
from shutil import copytree, rmtree
from random import randint, random
import uuid
from tempfile import gettempdir
from shapely.geometry import Point
import shapely.wkb
from aequilibrae.project import Project
from ...data import siouxfalls_proj... | AequilibraE/aequilibrae | tests/aequilibrae/project/test_node.py | test_node.py | py | 3,560 | python | en | code | 140 | github-code | 6 |
69868060029 | # 从列表中找出某个值第一个匹配项的索引位置
# list.index(obj)
# 参数
# obj -- 查找的对象。
# 返回值: 该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。
Array = [1, 2, 3, 4, 5]
print(Array.index(2)) # 1
Array2 = [
{
"name": "Tom",
"age": 18
},
{
"name": "Yang",
"age": 22
}
]
print(Array2.in... | yangbaoxi/dataProcessing | python/List(数组)/查找元素/index.py | index.py | py | 576 | python | zh | code | 1 | github-code | 6 |
30176892204 | #!/usr/bin/env python
#===============================================================================
# objdump2vmh.py
#===============================================================================
#
# -h --help Display this message
# -v --verbose Verbose mode
# -f --file Objdump file to parse
#
# Author... | cornell-brg/pydgin | ubmark-nosyscalls/scripts/objdump2vmh.py | objdump2vmh.py | py | 3,669 | python | en | code | 159 | github-code | 6 |
72128887548 | from OpenGL.GL import *
from common import get_namekey
import numpy as np
import pyglet
# #---badway
# vaoidx = VAO( {0:3,1:2},
# #np.array([0,0,0, 0,0, 0.5,0,0, 1,0, 0.5,0.5,0, 1,1, 0,0.5,0, 0,1, ]).astype('float32'),
# #np.array([0,0,0, 0,0, 1,0,0, 1,0, 1,1,0, 1,1, 0,1,0, 0,1, ]).astype('float32'),
# ... | liltmagicbox/3dkatsu | objects/vao_123123.py | vao_123123.py | py | 6,982 | python | en | code | 0 | github-code | 6 |
25129650646 | import numpy as np
import keras
from keras.datasets import mnist
class Dataset:
def __init__(self, path, local):
"""
Initialize the MNIST dataset.
Parameters path and local are only included to fit the interface of Dataset
:param path: Ignored
:param local: Ignored
... | jessica-dl/2XB3-ML-Training | trainer/mnist_dataset.py | mnist_dataset.py | py | 804 | python | en | code | 0 | github-code | 6 |
27834182031 | class Monitors:
name = 'Samsung'
matrix = 'VA'
res = 'WQHD'
freq = 60
class Headphones:
name = 'Sony'
sensitivity = 108
micro = True
monitor_1 = Monitors()
monitor_2 = Monitors()
monitor_2.freq = 144
monitor_3 = Monitors()
monitor_3.freq = 70
monitor_4 = Monitors()
headphone_1 = Headph... | MikhailRyskin/test1 | test242_2.py | test242_2.py | py | 542 | python | en | code | 0 | github-code | 6 |
35334534179 | '''
Escribir una funcion para ingresar desde el teclado una serie de numeros entre 1
y 20 guardarlos en una lista. En caso de ingresar un valor fuera de rango el
programa mostrara un mensaje de error solicitara un nuevo numero. Para finalizar
la carga se debera ingresar -1. La funcion no recibe ningun parametro, y
devu... | agsosa96/Fundamentos-De-La-Programacion | Trabajo Practico N°7/Ejercicio_1.py | Ejercicio_1.py | py | 830 | python | es | code | 0 | github-code | 6 |
31232927085 | import logging
import requests
from io import BytesIO
from django.core.management import BaseCommand
from places.models import Place, PlaceImage
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Load information about places with media files'
def add_arguments(self, parser):
... | vitaliy-pavlenko/where_to_go | places/management/commands/load_place.py | load_place.py | py | 2,202 | python | en | code | 0 | github-code | 6 |
75331159226 | import ops
import iopc
TARBALL_FILE="drbd-utils-8.9.10.tar.gz"
TARBALL_DIR="drbd-utils-8.9.10"
INSTALL_DIR="drbd-utils-bin"
pkg_path = ""
output_dir = ""
tarball_pkg = ""
tarball_dir = ""
install_dir = ""
install_tmp_dir = ""
cc_host = ""
def set_global(args):
global pkg_path
global output_dir
global tarb... | YuanYuLin/drbd-utils | Package/CONFIG.py | CONFIG.py | py | 3,434 | python | en | code | 0 | github-code | 6 |
75226773628 | import pymongo
from data_handlers import import_from_csv
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
core_db = myclient["core"]
indices_col = core_db["indices"]
historical_data_col = core_db["historical_data"]
instruments_file = "C:\\Users\\Prathiksha\\Documents\\Prashanth\\Trading\\instrumen... | prashanth470/trading | source/data/db_operations.py | db_operations.py | py | 1,622 | python | en | code | 0 | github-code | 6 |
4086684487 | import warnings
from functools import partial
from multiprocessing import Pool
import pandas as pd
import textacy
import textacy.preprocessing
import textacy.representations
import textacy.tm
from tqdm import tqdm
tqdm.pandas()
warnings.simplefilter(action="ignore", category=FutureWarning)
preproc = textacy.preproc... | charlesdedampierre/BunkaTopics | bunkatopics/functions/extract_terms.py | extract_terms.py | py | 5,458 | python | en | code | 35 | github-code | 6 |
32341699285 | import json
import numpy as np
import pandas as pd
import tensorflow as tf
class BalancedGroupSoftmax:
def __init__(self,
dataset_json,
category_map,
empty_class_id,
selected_locations=None,
n_groups=4,
sl_max_groups=[0, 10, 1... | alcunha/iwildcam2021ufam | classification/bags.py | bags.py | py | 6,432 | python | en | code | 11 | github-code | 6 |
26580948730 | def caminho_hamiltoniano(grafo, size, ponto, path=[]):
if ponto not in set(path):
path.append(ponto)
if len(path) == size:
return path
todos_candidatos = []
for prox_ponto in grafo.get(ponto, []):
res_path = [i for i in path]
candidatos = caminho_h... | LeandroGelain/PersonalGit | 2018-2019/Aulas_Algoritmos_avançados/TrabalhoGrafos/hamiltoniano.py | hamiltoniano.py | py | 1,538 | python | pt | code | 0 | github-code | 6 |
71345484349 | import logging
from typing import List
from DAL.ItemDAL.ItemDALInterface import ItemDALInterface
from Database.DBConnection import DBConnection
from Entities.Item import Item
class ItemDALImplementation(ItemDALInterface):
def create_item(self, item: Item) -> Item:
logging.info("Beginning DAL method crea... | dmerc12/143Designs | back-end/DAL/ItemDAL/ItemDALImplementation.py | ItemDALImplementation.py | py | 3,158 | python | en | code | 0 | github-code | 6 |
71401520189 | def getval(A, i, j, L, H):
if (i < 0 or i >= L or j < 0 or j >= H):
return 0
else:
return A[i][j]
def find_max_block(A, r, c, L, H, size, cntarr, maxsize):
if (r >= L or c >= H):
return
cntarr[r][c] = True
size += 1
if (size > maxsize):
maxsize = size
directi... | azaazato/algorithm_study_python | chapter2/find_connected.py | find_connected.py | py | 1,304 | python | en | code | 0 | github-code | 6 |
70929449148 | # Importeren modules
import copy
import math
ERROR_MARGIN = 0.01
def build_Best_Graph(n_dict, c_dict): # main function
# n_dict = Nodes Dict
# c_dict = Connections Dict
# f_nid = First Node Id
# o_nid_list = Ordered Nodes Ids List
solutions_list = []
for f_nid in n_dict: # for each node in... | jpbascur/SciMacro-noGUI | My_Module/My_chart.py | My_chart.py | py | 6,133 | python | en | code | 1 | github-code | 6 |
27228829856 | """This module implements classes and independent functions related to feature extraction
module of our work.
To be specific, this module helps identify handful of best features out of humongous number
of features; created from raw data """
import numpy as np
import pandas as pd
from namedlist import namedlist
from s... | waqasbukhari/optimal_pos_placement | best_feature_extraction.py | best_feature_extraction.py | py | 18,314 | python | en | code | 0 | github-code | 6 |
30063350104 |
# import tenTo8
import encdec_8b10b
import veri
# encdec_8b10b.trans10to8(ten)
def negate(Str):
X = Str.replace('0','x')
X = X.replace('1','0')
X = X.replace('x','1')
return X
K280_m = '0011110100'
K280_p = negate(K280_m)
K281_m = '0011111001'
K281_p = negate(K281_m)
K283_m = '0011110011'
K283_p... | greenblat/vlsistuff | verification_libs3/lvdsMonitor.py | lvdsMonitor.py | py | 14,045 | python | en | code | 41 | github-code | 6 |
9626855200 | import pandas as pd
import numpy as np
import os
import cv2
import json
from sklearn.model_selection import train_test_split
from trainer import Trainer
from sklearn.metrics import accuracy_score, mean_absolute_error, mean_squared_error
from collections import Counter
# read the images in the same order specified by ... | SebastianCojocariu/Detect-targets-in-radar-signals | src/main.py | main.py | py | 7,992 | python | en | code | 0 | github-code | 6 |
29456763062 | import abc
import os.path
from oslo_config import cfg
from oslo_log import log
import requests
import requests.certs
import six
from atrope import exception
from atrope import ovf
from atrope import paths
from atrope import utils
opts = [
cfg.StrOpt('download_ca_file',
default=paths.state_path_def... | alvarolopez/atrope | atrope/image.py | image.py | py | 6,812 | python | en | code | 2 | github-code | 6 |
33944686501 | # -*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics.scorer import make_scorer
from sklearn import model_selection
from sklearn.base import BaseEstimator, ClassifierMixin
from... | shahraizniazi/Regression-Simulation | Final_Final/Final.py | Final.py | py | 36,277 | python | en | code | 1 | github-code | 6 |
17484990800 | #Интеграл от неявнозаданной функции
from math import *
def func(x, y): #Неявнозаданная функция
f = exp(x**3)-(exp(y))*(x**6 - 2*(x**3)*y - 2*(x**3) + y**2 + 2*y +2)
return f
def found_y(x, eps = 1e-8):
y_left = -0.1
y_right = 0.1
while (func(x, y_left)*func(x, y_right) > 0):
y_left = y_lef... | orehovakatya/4sem | Вычислительные алгоритмы/lab1.integral/ВА_Задача1.py | ВА_Задача1.py | py | 1,483 | python | en | code | 0 | github-code | 6 |
18042025196 | # __init__.py
__version__ = "1.2.2" # Be sure to update version in setup.py as well
from difflib import SequenceMatcher
from sh3ll.command import command
from art import tprint
class IS(object):
def __init__(self, name="", font="", prefix="CLA>"):
self.name = name
self.font = font
self.... | HullaBrian/sh3ll | sh3ll/__init__.py | __init__.py | py | 6,104 | python | en | code | 2 | github-code | 6 |
25881575517 | #!/usr/bin/env python3
import ast
f = open("in.txt", "r").read().strip().split("\n\n")
xy = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def compare(first, second):
if type(first) is not list and type(second) is not list:
return 0 if first == second else (-1 if first < second else 1)
if type(first)... | Anja159/Advent_of_code_2022 | Day13/part2.py | part2.py | py | 1,335 | python | en | code | 1 | github-code | 6 |
9710578646 | import time
class Timer:
def __init__(self):
self.dt = -1.0
self.et = 0.0
self.currentTime = 0.0
self.lastTime = 0.0
self.timerRunning = False
def isTimerOn(self):
if self.dt > 0:
return True
return False
def start(self):
if... | zetwhite/2019_assignments | ComputerGraphics/PA02/Timer.py | Timer.py | py | 1,033 | python | en | code | 1 | github-code | 6 |
13130316582 | from django.conf.urls import url, include
from django.contrib.auth.decorators import login_required
from frontend.views import SPAView, UserConfigSPAWebService
# spa view
VIEWS_PATTERNS = [
url(regex=r'$',
view=login_required(SPAView.as_view()),
name='spa'),
]
# config endpoint
API_PATTERNS = [... | victordelval/spa-design-basics | frontend/urls.py | urls.py | py | 549 | python | en | code | 0 | github-code | 6 |
74473554749 |
import struct
import os
def reverse_string(string):
string_out =""
for i in range(len(string)-1,-1,-1):
string_out+=string[i]
return string_out
def print_hex(number):
num = number
string = ""
if num>0:
while num>=1:
ost = num%16
if ost<10:
string+=str(int(ost))
elif ost==10:
string+="A"
... | kvintagav/learning_to_program | Python/num_to_hex.py | num_to_hex.py | py | 695 | python | en | code | 0 | github-code | 6 |
5478969307 | # A simple MLP network structure for point clouds,
#
# Added by Jiadai Sun
import torch
import torch.nn as nn
import torch.nn.functional as F
class PointRefine(nn.Module):
def __init__(self, n_class=3,
in_fea_dim=35,
out_point_fea_dim=64):
super(PointRefine, self).__in... | haomo-ai/MotionSeg3D | modules/PointRefine/PointMLP.py | PointMLP.py | py | 1,699 | python | en | code | 206 | github-code | 6 |
73130357629 | # Multiples of 3 and 5 return 'Fizz' and 'Buzz' respectively while 15 returns 'FizzBuzz'
def fizzBuzz():
# Solution 1
'''
for i in range(1, 16):
if i in [3, 6, 9, 12]:
i='Fizz'
if i in [5, 10]:
i='Buzz'
if i==15:
i='FizzBuzz'
print(i)
'''
# Solution 2
for ii in range(1, 16):
... | Dzhud/fizzBuzz-Solution | fizzy.py | fizzy.py | py | 576 | python | en | code | 0 | github-code | 6 |
17598463073 | from PySide import QtCore, QtGui
class UserDialog(QtGui.QDialog):
def __init__(self, cl, text, parent=None):
super(UserDialog, self).__init__(parent)
textLabel = QtGui.QLabel(str('<b>%s</b>' % text))
mainbox = QtGui.QVBoxLayout()
mainbox.addWidget(textLabel)
vbox = QtGui.... | freepax/PysideSocketSkeletons | UserDialog.py | UserDialog.py | py | 1,002 | python | en | code | 0 | github-code | 6 |
9627877293 | from . import views
from django.urls import path, include
urlpatterns = [
path('', views.index, name="index"),
path('about/', views.about, name="about"),
path('contact/', views.contact, name="contact"),
path('services/', views.services, name="services"),
path('skill/', views.skill, name="sk... | abrahammmmmmmm/dynamicPortfolio | portfolio/app1/urls.py | urls.py | py | 329 | python | en | code | 0 | github-code | 6 |
70400872827 | """
Snake game view.
"""
import sys
import pygame
from snake_controller import get_mouse_position
def play_eaten_sound():
"""
Plays a crunch sound.
"""
food_eaten_sound = pygame.mixer.Sound('sounds/snake_eat_sound.wav')
pygame.mixer.Sound.play(food_eaten_sound)
def play_click_sound():
"""
... | olincollege/ultimate-snake | snake_view.py | snake_view.py | py | 9,976 | python | en | code | 0 | github-code | 6 |
17508200123 | from typing import List
def products_div(arr: List[int]) -> List[int]:
prod = 1
for x in arr:
prod *= x
res = [prod//x for x in arr]
return res
'''
arr: [2, 3, 4, 5,]
l: [2 23 234]
r: [5 54 543]
res: [.-345, 2-45, 23-5, 234-.]
l = []
prod = 1
for i in range(len(arr)-1):
prod *= arr[i]
... | soji-omiwade/cs | dsa/before_rubrik/array_of_array_of_products.py | array_of_array_of_products.py | py | 982 | python | en | code | 0 | github-code | 6 |
41584655028 | import json
import time
import requests
# 크롤링 대상 URL 리스트
PAGE_URL_LIST = [
'http://example.com/1.page'
'http://example.com/2.page',
'http://example.com/3.page',
]
def fetch_pages():
"""페이지의 내용을 추출합니다"""
# 처리 기록 전용 로그 파일을 append 모드로 엽니다
f_info_log = open('crawler_info.log', 'a')... | JSJeong-me/2021-K-Digital-Training | Web_Crawling/python-crawler/chapter_5/get_example_domain_pages.3.py | get_example_domain_pages.3.py | py | 1,939 | python | ko | code | 7 | github-code | 6 |
33120873994 | import json
import re
from typing import Any
from aiohttp import ClientSession
from .exceptions import FailedToParseIntialData
class Client:
"""YouTube API client."""
_session: ClientSession
@classmethod
async def new(cls, host: str = "https://www.youtube.com"):
"""Create a new YouTube cli... | Flowrey/youtube-bz | youtube_bz/api/youtube/api.py | api.py | py | 1,161 | python | en | code | 12 | github-code | 6 |
42641405385 | #!/usr/bin/env python3
# Simple Script to replace cron for Docker
import argparse
import sys
from subprocess import CalledProcessError, run
from time import sleep, time
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("interval", help="Time in seconds between runs", type=int)
ar... | osssanitizer/maloss | registries/rubygems/runner.py | runner.py | py | 985 | python | en | code | 98 | github-code | 6 |
17435637259 | import pytest
from collections import defaultdict
class UndergroundSystem:
def __init__(self):
self.user_table = defaultdict(list)
self.course_table = defaultdict(list)
def checkIn(self, id: int, stationName: str, t: int) -> None:
assert len(self.user_table[id]) == 0
self.use... | naubull2/codingtests | leetcode/solved/1512_Design_Underground_System/solution.py | solution.py | py | 3,711 | python | en | code | 0 | github-code | 6 |
36383540075 | import socket
import copy
import struct
import time
import board
import adafruit_bno055
import subprocess
from button import ToggleButton
from serial_read import DeviceInterface
class UDPSocket:
def __init__(self, IP_ADDR="192.168.0.198", PORT=65432):
self.IP_ADDR = "192.168.0.198"
self.APP_PORT =... | NMMallick/sd-drone | modules/rpi_client/client.py | client.py | py | 2,142 | python | en | code | 2 | github-code | 6 |
34529799093 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='quantile_transformer_tf',
version='1.2',
description='An implemen... | yandexdataschool/QuantileTransformerTF | setup.py | setup.py | py | 905 | python | en | code | 7 | github-code | 6 |
43367016676 | ###############################
# ProcessorBase.py
#
# Basic processor
###############################
import sys
import os
###############################
# Basic processor
###############################
class ProcessorBase:
def __init__(self, file):
self.file = file
@property
def description(self):
rai... | SillyBits/DumpMyRideUI | processors/ProcessorBase.py | ProcessorBase.py | py | 2,368 | python | en | code | 0 | github-code | 6 |
14011684325 | import numpy as np
from tqdm import tqdm
from collections import Counter
import pandas as pd
class PMI():
def __init__(self, text, lang):
self.text = text
self.lang = lang
self.p_1, self.c_1 = self.get_unigram_probs()
self.bigram = self.get_joint_probs()
self.distant = self... | awmcisaac/charles | winter/npfl067/hw2/best_friends.py | best_friends.py | py | 3,872 | python | en | code | 0 | github-code | 6 |
71184167229 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pl
from mpl_toolkits.basemap import Basemap
# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
# are the lat/lon values of the lower left and upper right corners
# of the map.
# lat_ts is the latitu... | ddboline/programming_tests | numpy/basemap_test.py | basemap_test.py | py | 847 | python | en | code | 0 | github-code | 6 |
33557423336 | from django.conf import settings
from django.contrib.sites.models import Site
from .models import SiteSettings
class SiteSettingsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
request.wf_site = Site.objects._get_s... | phildini/wordfugue | wordfugue/sitesettings/middleware.py | middleware.py | py | 684 | python | en | code | 0 | github-code | 6 |
9535093806 | #!/usr/bin/env python3
"""
RBE/CS549 Spring 2023: Computer Vision
Author(s):
Uday Sankar (usankar@wpi.edu)
Mechatronics, Robotics and Automation Engineering,
Worcester Polytechnic Institute
"""
# Dependencies:
# opencv, do (pip install opencv-python)
# skimage, do (apt install python-skimage)
# termco... | udaysankar01/Image-Classification-using-ResNet-ResNeXt-and-DenseNet | Train.py | Train.py | py | 11,349 | python | en | code | 0 | github-code | 6 |
6182705632 | import urllib.request
from bs4 import BeautifulSoup
f = open("Newyork_articles.txt", 'w')
html = 'http://www.nytimes.com/'
open_url = urllib.request.urlopen(html)
soup = BeautifulSoup(open_url, 'html.parser')
article_headings = soup.find_all(class_="indicate-hover")
head = "Articles for Today:\n"
i = 0
f.wri... | Jsid2022/Python | decode_web_page.py | decode_web_page.py | py | 437 | python | en | code | 0 | github-code | 6 |
18261510300 | from rackmond import configure_rackmond
# flag
# ascii 0x80XX
# 2'comp 0x4NXX
# decimal 0x20XX
# bitmap 1,2 0x10XX
reglist = [
{"begin": 0x0, "length": 8, "flags": 0x8000}, # MFR_MODEL # ascii
{"begin": 0x10, "length": 8, "flags": 0x8000}, # MFR_DATE # ascii
{"begin": 0x20, "length": 8, "flags"... | WeilerWebServices/Facebook | openbmc/meta-facebook/meta-wedge400/recipes-wedge400/rackmon/rackmon/rackmon-config.py | rackmon-config.py | py | 7,356 | python | en | code | 3 | github-code | 6 |
34429142094 | import glfw
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
gCamAng = 0.
def myLookAt(eye,at,up):
w = (eye-at)/np.sqrt(np.dot(eye-at,eye-at))
u = np.cross(up, w)/np.sqrt(np.dot(np.cross(up, w), np.cross(up,w)))
v = np.cross(w, u)
M= np.array([[u[0], u[1], u[2], -np... | vctr7/Computer_Graphics | hw8.py | hw8.py | py | 2,584 | python | en | code | 1 | github-code | 6 |
13442910609 | def gridRound( pos, w, h, roundToTopLeft=True, trueRounding=False ):
"""gridRound( pos, w, h, roundToTopLeft=True )\n""" \
"""This function rounds a given pos variable to the nearest lower or upper multiples \n""" \
""" of w and h in their respective directions. roundToTopLeft=True means it rounds towards t... | Occuliner/ThisHackishMess | modules/stockfunctions/gridrounding.py | gridrounding.py | py | 819 | python | en | code | 2 | github-code | 6 |
15412213880 | import sys
from random import shuffle
with open("all_eqs.txt") as f:
eq = f.readlines()
with open("all_text.txt") as f:
txt = f.readlines()
dat = list(range(len(txt)))
shuffle(dat)
valeq = open("val.eq",'w')
valtxt = open("val.txt",'w')
for i in dat[:200]:
valeq.write(eq[i])
valtxt.write(txt[i])
valeq = op... | rikkarikka/nn_math_solver | splitter.py | splitter.py | py | 560 | python | en | code | 0 | github-code | 6 |
19109148247 | import asyncio
import async_timeout
import aiohttp
class DiscordAttachmentHandler:
def __init__(self):
self.loop = asyncio.get_event_loop()
@staticmethod
async def fetch_json(session, url):
async with async_timeout.timeout(10):
async with session.get(url) as response:
... | Mirdalan/discord_astro_bot | dastro_bot/attachments_downloader.py | attachments_downloader.py | py | 762 | python | en | code | 2 | github-code | 6 |
4601203522 | import subprocess
import py_compile
import os
from hashlib import md5
from datetime import datetime
from django.db import models
from django.conf import settings
from .constants import TYPES
def get_filename(instance, filename):
now = datetime.now()
base = now.strftime('utility_files/%Y/%m/%d')
hash = m... | viljan/intraweb | viljan/utility/models.py | models.py | py | 2,595 | python | en | code | 0 | github-code | 6 |
39215055594 | import boto3
import random
import json
topic = 'arn:aws:sns:us-east-1:511086078676:temps'
client = boto3.client('sns')
def lambda_handler(event, context):
#id de la persona (editar con el id real)
#id = '11223344'
#simulador de aparato de medir la temperatura
temp = random.uniform(36,40)
... | ansmartin/Proyecto-PYGITIC-2020 | Pruebas/Ansel/temp_to_topic.py | temp_to_topic.py | py | 598 | python | es | code | 1 | github-code | 6 |
42890816740 | import time
from pathlib import Path
import shutil
import torch
import torch.nn
from torch.utils.tensorboard import SummaryWriter
import torch.backends.cudnn as cudnn
from . import utils
class Bone:
def __init__(self,
model,
datasets,
criterion,
... | EvgenyKashin/backbone | back/bone.py | bone.py | py | 7,736 | python | en | code | 4 | github-code | 6 |
17273180201 | import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
from scipy.sparse.linalg import norm as sparsenorm
from scipy.linalg import qr
# from sklearn.metrics import f1_score
def parse_index_file(filename):
"""Parse index... | matenure/FastGCN | utils.py | utils.py | py | 12,670 | python | en | code | 514 | github-code | 6 |
70276275707 |
"""
多头注意力机制:
每个头开始从词义层面分割输出的张量,也就是每个头都想获得一组Q,K,V进行注意力机制的计算,
但是句子中的每个词的表示只获得一部分,
也就是只分割了最后一维的词嵌入向量. 这就是所谓的多头.
将每个头的获得的输入送到注意力机制中, 就形成了多头注意力机制
多头注意力机制的作用:
这种结构设计能让每个注意力机制去优化每个词汇的不同特征部分,从而均衡同一种注意力机制可能产生的偏差,
让词义拥有来自更多元的表达,从而提升模型效果
"""
import copy
import torch
import math
import numpy as np
import t... | Jacquelin803/Transformers | transformerArc/MultiHeadAttention.py | MultiHeadAttention.py | py | 7,709 | python | zh | code | 1 | github-code | 6 |
71951318589 | from flask import Flask, render_template, request
import os
from Prediction import deep_ocr, easy_ocr
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, Length
# webserver gateway interf... | babakmbm/Optical-Character-Recognition-OCR-SYSTEM | App.py | App.py | py | 1,289 | python | en | code | 1 | github-code | 6 |
35765418423 | '''
Created on Apr 21, 2014
@author: Borja
'''
import os.path
import xlrd
import __data__
class XslReader(object):
def __init__(self):
if not os.path.exists(__data__.path()):
os.makedirs(__data__.path())
self._data_path = __data__.path();
def load_ind... | weso/landportal-importers | RAWImporter/es/weso/raw/ExcelManagement/excel_reader.py | excel_reader.py | py | 2,930 | python | en | code | 0 | github-code | 6 |
9773551663 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 2 19:36:10 2020
@author: lnajt
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 15 11:57:08 2018
@author: MGGG
"""
import networkx as nx
import random
import numpy as np
##############
'''Wilsons Algorithm'''
def random_spanning_tree_wilson(graph):
'''Th... | ElleNajt/TinyProjects | boundaryofUST.py | boundaryofUST.py | py | 4,806 | python | en | code | 4 | github-code | 6 |
74056208827 | import torch
import torch.nn as nn
import torch.nn.functional as F
class BiDirectionalTreeGRU(nn.Module):
def __init__(self, n_hidden=None, n_iters=1):
super().__init__()
self.n_hidden = n_hidden
self.n_iters = n_iters
self.down_root = nn.Linear(n_hidden, n_hidden)
self.dow... | isaachenrion/jets | src/architectures/utils/bidirectional_tree_gru.py | bidirectional_tree_gru.py | py | 3,809 | python | en | code | 9 | github-code | 6 |
19793355076 | # coding:utf-8
from bs4 import BeautifulSoup
import re
from urllib.parse import urljoin
from urllib.parse import quote
from ipdb import set_trace
class HtmlParser(object):
def replaceillgalchar(self, link_text):
# set_trace()
while link_text.find(':')>=0:
#
link_text = link_te... | BaikeSpider/Randomly-Selection | html_parser.py | html_parser.py | py | 10,632 | python | en | code | 0 | github-code | 6 |
36691623039 | import streamlit as st
from streamlit_chat import message
from streamlit_extras.colored_header import colored_header
from streamlit_extras.add_vertical_space import add_vertical_space
from hugchat import hugchat
from document_processing import index, chain
st.set_page_config(page_title="HugChat - An LLM-powered Strea... | Ubond-edu/PF1-Chatbot | streamlit_app.py | streamlit_app.py | py | 2,211 | python | en | code | 0 | github-code | 6 |
8261658572 | import functions
import utils
from functions import greet_user
# import ecommerce.shipping
# from ecommerce.shipping import calc_shipping
from ecommerce import shipping
shipping.calc_shipping()
import math
# Google search python 3 math module
price = 10
# variable must be lower case - booleans must be capitalized
i... | Rosenmatt1/Python-101 | App.py | App.py | py | 1,575 | python | en | code | 1 | github-code | 6 |
3438496641 | # 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
... | cuiy0006/Algorithms | leetcode/144. Binary Tree Preorder Traversal.py | 144. Binary Tree Preorder Traversal.py | py | 1,190 | python | en | code | 0 | github-code | 6 |
39259069256 | import logging
from django.db import transaction
from rest_framework import serializers
from rest_framework import status
from rest_framework.decorators import detail_route
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.response import Response
from rest_framework.routers import Defa... | unicefuganda/eums | eums/api/distribution_plan_node/distribution_plan_node_endpoint.py | distribution_plan_node_endpoint.py | py | 5,146 | python | en | code | 9 | github-code | 6 |
43085026671 | sqmesh_min_coord = [359919.189 - 360600.0, 3972158.559 - 3973000.0]
sqmesh_step = 2.0
import h5py
import math
tmesh_data = h5py.File("visdump_surface_mesh_jaramillo_384.h5",'r')
tmesh_key = '6234'
ME_len = len(tmesh_data[tmesh_key]['Mesh']['MixedElements'])
ntris = ME_len // 4;
tricells_inodes = [[0 for x in range(... | amanzi/ats | tools/square_to_tri_mesh_data_parser/tri_square_overlap_weights.py | tri_square_overlap_weights.py | py | 9,284 | python | en | code | 35 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.