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
30582813202
import random def check(comp, user): if comp == user: return 0 if comp==0 and user==1: return -1 if comp==1 and user==2: return -1 if comp==2 and user==0: return -1 return 1 comp = random.randint(0,2) user = int(input("Enter 0 for Stone, 1 for Paper ...
jatingupta05/StonePaperScissor
StonePaperScissor.py
StonePaperScissor.py
py
524
python
en
code
0
github-code
6
70082164988
from routersim.interface import LogicalInterface from .messaging import FrameType from .messaging import ICMPType, UnreachableType from .mpls import MPLSPacket, PopStackOperation from .observers import Event, EventType from scapy.layers.inet import IP,ICMP,icmptypes from copy import copy import ipaddress class Forwa...
jdewald/router-sim
routersim/forwarding.py
forwarding.py
py
9,267
python
en
code
5
github-code
6
38573517447
from brian2 import * import math import queue numberGC = 10 defaultclock.dt = 0.01*second gT = 0 # target gain. Should vary a bit depexnding on day of training. pT = 0 # target phase shift. unitlessErrorDelay = 0 # set the delay here so that the file prints right errorDelay = unitlessErrorDelay*second ...
ThePerson2/CA6_Project
SMAE.py
SMAE.py
py
4,435
python
en
code
0
github-code
6
24650911393
import asyncio import curses import typing from curses_tools import draw_frame class Obstacle: def __init__( self, row: int, column: int, rows_size: int = 1, columns_size: int = 1, uid: str | None = None, ) -> None: self.row = row self.column = ...
Alex-Men-VL/space_game
src/obstacles.py
obstacles.py
py
4,841
python
en
code
0
github-code
6
22368252597
import os, sys import numpy as np import pandas as pd import pickle import argparse from keras import backend from keras.models import load_model from keras.optimizers import * from sklearn.metrics import accuracy_score from sklearn.decomposition import PCA from sklearn.neighbors import KNeighborsClassifier from model ...
tom6311tom6311/dlcv2018final
task2/knn/code/knn_test.py
knn_test.py
py
2,377
python
en
code
0
github-code
6
17875196708
#https://projecteuler.net/problem=5 #Smallest Multiple def lcm(a, b): if a > b: n = a else: n = b while not (n % a == 0) or not (n % b == 0): n += 1 return n n = 20 l = 1 for i in range(1, n+1): l = lcm(l, i) print(l)
SreenathSreekrishna/euler
python/p5.py
p5.py
py
257
python
en
code
0
github-code
6
18287710970
import random def GetQuestions(sub,quesNum): # Getting the questions inside a variable as a list with open(sub,"r") as f: unfilteredQuestion = f.readlines() # Removing new line escape sequence from the list filteredQuestions = [] for items in unfilteredQuestion: if items[0:-1] ==...
CharanGeek/DPP_Generator
GettingQuestions.py
GettingQuestions.py
py
824
python
en
code
0
github-code
6
4534308606
#!/usr/bin/env python # -*- coding: UTF-8 -*- # REF [site] >> https://scrapy.org/ import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://blog.scrapinghub.com'] def parse(self, response): for title in response.css('.post-header>h2'): yield {'title': title.css('a ::text').ge...
sangwook236/SWDT
sw_dev/python/ext/test/networking/scrapy_test.py
scrapy_test.py
py
581
python
en
code
17
github-code
6
3457609091
import RPi.GPIO as GPIO import time # ===== CONFIGURATIONS and FUNCTIONS ==== # ===== (Please, don't touch!) ========== ## ==== CARRIAGE CONFIGS ================ GPIO.setwarnings(False) DIR1 = 20 # Direction GPIO Pin Mag STEP1 = 21 # Step GPIO Pin Mag DIR2 = 16 # Direction GPIO Pin Car STEP2 = 12 # Step GPIO ...
Mekek/NTI-ATC
фабрика/AiOi/facility.py
facility.py
py
7,522
python
en
code
0
github-code
6
16312750556
print('-'*30) print('Kwik-E-Mart') print('-'*30) preçototal = thousand = menor = contador = 0 barato = '' while True: produto = str(input('Nome do Produto: ')) preço = float(input('preço R$: ')) preçototal += preço contador += 1 if preço > 1000: thousand += 1 if contador == 1 or preç...
igorfreits/Studies-Python
Curso-em-video/Mundo-2/AULA15-Interrompendo-repetições-while(break)/#070 - Estatísticas em produtos.py
#070 - Estatísticas em produtos.py
py
764
python
pt
code
1
github-code
6
33489134927
import sys import os fi = open(sys.argv[1], 'r') fo = open(sys.argv[2], 'w') vocab = {} for line in fi: u = line.split()[0] v = line.split()[1] vocab[u] = 1 vocab[v] = 1 for ent in vocab.keys(): fo.write(ent + '\n') fi.close() fo.close()
mnqu/REPEL
preprocess/entity.py
entity.py
py
245
python
en
code
26
github-code
6
37091838482
import RPi.GPIO as GPIO from RF24 import * import time import spidev GPIO.setmode(GPIO.BCM) pipes = [0xe7e7e7e7e7, 0xc2c2c2c2c2] radio = RF24(25,8) radio.begin() #radio.setPayloadSize(32) radio.setChannel(0x60) radio.setDataRate(RF24_2MBPS) radio.setPALevel(RF24_PA_MIN) radio.setAutoAck(True) radio.enableDynamicPay...
julio-burgos/Rx_TX_RF24
Basic/recv.py
recv.py
py
983
python
en
code
1
github-code
6
33623583816
import arcpy import traceback import split_tool name_mod = arcpy.GetParameterAsText(4) output_file = "G:\\GIS\\Models_Tools\\Production\\EPModel\\tests\\testing\\test_zone\\ep_model_testing\\errors\\{0}_errors.txt".format(name_mod) messages_file = "G:\\GIS\\Models_Tools\\Production\\EPModel\\tests\\testing\\test_zone\...
cwmat/ShapeSplitter
src/test_wrapper.py
test_wrapper.py
py
606
python
en
code
0
github-code
6
21632483915
# Вариант 29 # Дана строка, содержащая по крайней мере один символ пробела. Вывести подстроку, # расположенную между первым и вторым пробелом исходной строки. Если строка # содержит только один пробел, то вывести пустую строку. a = input('Введите строку: ') # Ввод строки с клавиатуры space_count = 0 # Счетчик количе...
Abyka12/Proj_1sem_Mogilko
PZ_7/PZ_7_2.py
PZ_7_2.py
py
1,715
python
ru
code
0
github-code
6
32129181331
import logging import pandas as pd from flask import Flask, request, jsonify from data_preprocessing import process_data_for_training import psycopg2 from psycopg2 import sql # Create a Flask app app = Flask(__name__) app.logger.setLevel(logging.DEBUG) app.logger.addHandler(logging.StreamHandler()) db_params = { ...
evialina/automotive_diagnostic_recommender_system
training-service/script.py
script.py
py
1,290
python
en
code
0
github-code
6
72474633149
""" ~ working with data in text files ~ A common thing to do with Python is to process data files. You can use the built-in `csv` module to work with delimited text. We'll open the files like this: - inside a `with` block -- notice the indentation on subsequent lines - in `r` ("read") mode - as some_variable that giv...
cjwinchester/ire-2017-python-101
completed/1-data-files-completed.py
1-data-files-completed.py
py
3,991
python
en
code
2
github-code
6
74750167547
import torch from transformers import T5ForConditionalGeneration, T5Tokenizer import re def title_generation(data): print("[!] Server logs: Title generation has started") text = data["content"] device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = T5ForConditionalGeneration.fro...
SVijayB/Gist
scripts/title_generation.py
title_generation.py
py
1,106
python
en
code
4
github-code
6
9634403295
''' Functions for computing energies of sets of auxiliaries. ''' import numpy as np from auxgf import util def energy_2body_aux(gf, se, both_sides=False): ''' Calculates the two-body contribution to the electronic energy using the auxiliary representation of the Green's function and self-energy,...
obackhouse/auxgf
auxgf/aux/energy.py
energy.py
py
3,055
python
en
code
3
github-code
6
30439578880
import networkx as nx from networkx.generators.degree_seq import expected_degree_graph # make a random graph of 500 nodes with expected degreees of 50 n = 500 # n nodes p = 0.1 w = [p * n for i in range(n)] # w = p*n for all nodes G = expected_degree_graph(w) # configuration model print("Degree Histogram") print...
oimichiu/NetworkX
graph/ex24.py
ex24.py
py
503
python
en
code
0
github-code
6
10769330374
"""my_first_django URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cla...
shine-codestove/my_first_django
my_first_django/urls.py
urls.py
py
1,750
python
en
code
1
github-code
6
28237649684
import typing import requests from requests import Session from zenora.errors import MissingAccess, AvatarError, InvalidSnowflake # Request functions def fetch( url: str, headers: typing.Dict[str, str], params: typing.Dict[str, str] = {}, ) -> typing.Dict: r = requests.get(url=url, headers=headers, p...
StarrMan303/zenora
zenora/utils/helpers.py
helpers.py
py
1,778
python
en
code
0
github-code
6
37187209809
# solved by satyam kumar (reference https://www.youtube.com/watch?v=gBTe7lFR3vc) # question link https://leetcode.com/problems/linked-list-cycle/ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def ha...
saty035/DSA_Python
Linked List Cycle_leetcode/Linked List Cycle.py
Linked List Cycle.py
py
1,397
python
en
code
2
github-code
6
21797961836
# make a time series of instantaneous electric power consumption graph from a csv file import csv import glob import re import os import numpy as np import matplotlib.pyplot as plt import pandas as pd from statistics import mean # define variables timestep = 0.01 def csv_to_graph(path): data = pd.read_csv(path, ...
is0232xf/BIWAKO_unit_test
csv_to_graph.py
csv_to_graph.py
py
4,460
python
en
code
0
github-code
6
42095752382
import os, settings from app import myApp import uuid from flask import request, render_template from pdf_core import PdfHelper from threading import Timer @myApp.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # create a list with all pdf files ...
icruces/blog-PDFMerging
app/views.py
views.py
py
1,305
python
en
code
2
github-code
6
74416653309
# Ta stała globalna przechowuje procent kwoty # wynagrodzenia przekazywany na fundusz emerytalny. CONTRIBUTION_RATE = 0.05 def main(): gross_pay = float(input('Podaj kwotę wynagrodzenia: ')) bonus = float(input('Podaj kwotę premii: ')) show_pay_contrib(gross_pay) show_bonus_contrib(bonus) # Funkcja sh...
JeanneBM/Python
Owoce Programowania/R05/28. Retirement.py
28. Retirement.py
py
1,038
python
pl
code
0
github-code
6
6185400966
# codesignal level1 n2 def centuryFromYear(year): return (year - 1) // 100 + 1 # tests print('century from hear 1905: ',centuryFromYear(1905)) # expected 20 print('century from hear 1700: ',centuryFromYear(1700)) # expected 17 # codesignal level1 n3 def checkPalindrome(inputString): length = len(inputString) ...
Venckus/tribeofai_workshop_class_e
study/codesignal_intro.py
codesignal_intro.py
py
11,981
python
en
code
0
github-code
6
26048697220
from sept.errors import OperatorNotFoundError, OperatorNameAlreadyExists class OperatorManager(object): def __init__(self): super(OperatorManager, self).__init__() self._cache = {} from sept.builtin.operators import ALL_OPERATORS for operator_klass in ALL_OPERATORS: s...
Ahuge/sept
sept/operator_manager.py
operator_manager.py
py
1,654
python
en
code
8
github-code
6
72940803068
# This is a sample Python script. # Press ⌃R to execute it or replace it with your code. # Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings. import os, requests, json # python request examples # https://www.pythonforbeginners.com/requests/using-requests-in-python def print...
lean35/python101
main.py
main.py
py
915
python
en
code
0
github-code
6
70132131389
from typing import Tuple from sqlalchemy import and_, desc from quizard_backend import db from quizard_backend.utils.exceptions import raise_not_found_exception from quizard_backend.utils.transaction import in_transaction def dict_to_filter_args(model, **kwargs): """ Convert a dictionary to Gino/SQLAlchemy'...
donjar/quizard
api/quizard_backend/utils/query.py
query.py
py
5,219
python
en
code
5
github-code
6
8255764779
from xadrez.tabuleiro.Cor import Cor from xadrez.tabuleiro.Peca import Peca from xadrez.tabuleiro.Posicao import Posicao from xadrez.xadrez.Torre import Torre class Rei(Peca): def __init__(self, tab, cor, partida): super().__init__(tab, cor) self.partida = partida def __str__(self): r...
josuelopes512/xadrez_python
xadrez/xadrez/Rei.py
Rei.py
py
4,027
python
pt
code
0
github-code
6
74199244988
from db import Mysql_Object import tkinter as tk import random as rd import tkinter.messagebox as msgbox class manage_page: def __init__(self, master): # 连接数据库 self.sql = Mysql_Object('localhost', 'root', '123456', 'parkinglot_management') self.win = master self.win.resi...
jmzdmj/ParkingLotSystem
ParkingLotSystem/managein_page.py
managein_page.py
py
4,638
python
en
code
0
github-code
6
1883488340
import sys import pefile import re # Pega os headers de um executável def get_headers(executable): pe = pefile.PE(executable) sections = [] for section in pe.sections: sections.append(section.Name.decode('utf-8')) return sections # Pega os headers dos argumentos de entrada sections1 = get_head...
kkatzer/CDadosSeg
T2/Parte2/T2P2b.py
T2P2b.py
py
1,323
python
en
code
0
github-code
6
19167053066
""" Common utilities for derp used by various classes. """ from collections import namedtuple import cv2 from datetime import datetime import heapq import logging import pathlib import numpy as np import os import socket import time import yaml import zmq import capnp import messages_capnp Bbox = namedtuple("Bbox", ["...
notkarol/derplearning
derp/util.py
util.py
py
9,198
python
en
code
40
github-code
6
41815384400
from urllib import response import requests from pprint import pprint from time import sleep import os from sqlalchemy import null url = "http://10.0.1.10:8080" # ------------------------ PRINT ------------------------ def menu(): os.system('clear') or None print("-------------------:-------------------") ...
hencabral/Python-BoxCode-API
cliente.py
cliente.py
py
8,346
python
pt
code
0
github-code
6
25182089444
# adapated from munch 2.5.0 from collections.abc import Mapping class Munch(dict): """A dictionary that provides attribute-style access. >>> b = Munch() >>> b.hello = 'world' >>> b.hello 'world' >>> b['hello'] += "!" >>> b.hello 'world!' >>> b.foo = Munch(lol=True) >>> b.foo.l...
SAIL-Labs/AMICAL
amical/externals/munch/__init__.py
__init__.py
py
11,370
python
en
code
9
github-code
6
37568054562
# import libraries import sys import nltk nltk.download(['punkt', 'wordnet', 'stopwords']) import re import numpy as np import pandas as pd from sqlalchemy import create_engine from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.metrics import...
goitom/project_2_disaster_response
models/train_classifier.py
train_classifier.py
py
5,371
python
en
code
0
github-code
6
25546051885
import os import json import flask from vrprot.alphafold_db_parser import AlphafoldDBParser import vrprot from . import map_uniprot from . import settings as st from . import util from .classes import NodeTags as NT def get_scales(uniprot_ids=[], mode=st.DEFAULT_MODE): return vrprot.overview_util.get_scale(uni...
menchelab/ProteinStructureFetch
src/workflows.py
workflows.py
py
5,793
python
en
code
0
github-code
6
3235447487
from __future__ import annotations from typing import TYPE_CHECKING from avilla.core.context import Context from avilla.core.event import RelationshipCreated, RelationshipDestroyed from avilla.core.selector import Selector from avilla.core.trait.context import EventParserRecorder from cai.client.events.group import (...
RF-Tar-Railt/Avilla-CAI
avilla/cai/event/group.py
group.py
py
2,023
python
en
code
3
github-code
6
23750393543
""" 최적화 비중을 계산해주는 모듈 @author: Younghyun Kim Created on 2021.10.05 """ import numpy as np import pandas as pd import cvxpy as cp import torch from cvxpylayers.torch import CvxpyLayer class ClassicOptimizer: """ Classic Optimizer """ def __init__(self, m=100, buying_fee=...
kimyoungh/singlemolt
statesman/classic_optimizer.py
classic_optimizer.py
py
11,771
python
en
code
0
github-code
6
35061353854
from tkinter import Button, Checkbutton, Entry, IntVar, Label, Tk from tkinter import messagebox from solve import Solver q = Solver() def show_plot(): if accur_entry.get().isdigit(): n = int(accur_entry.get()) else: messagebox.showerror(message="put integer") return potent...
shomarzzz/quantum-solver
gui.py
gui.py
py
2,469
python
en
code
0
github-code
6
39259262942
#!/usr/bin/env python3 import rclpy from rclpy.node import Node import speech_recognition as sr from custom_if.srv import SendSentence from functools import partial import time ### Node class class SpeechToText(Node): def __init__(self): super().__init__("stt_node") self.get_logger().info("STT node is up.") s...
Alessandro-Scarciglia/VoiceAssistant
speech_to_text/speech_to_text/speech_to_text.py
speech_to_text.py
py
1,732
python
en
code
0
github-code
6
22034975052
from lib2to3.pgen2 import token from brownie import Test, accounts, interface from eth_utils import to_wei from web3 import Web3 def main(): deploy() def deploy(): amount_in = Web3.toWei(1000000, "ether") # DAI address DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F" # DAI whale DAI_WHAL...
emrahsariboz/DeFi
uniswap/scripts/_deployAndAddLiquidity.py
_deployAndAddLiquidity.py
py
1,713
python
en
code
0
github-code
6
37272423624
import sys from aspartix_parser import Apx_parser import itertools def conflict_free(arguments, attacks): confl_free_sets = [] combs = [] for i in range(1, len(arguments) + 1): els = [list(x) for x in itertools.combinations(arguments, i)] combs.extend(els) combs_sorted =...
Vladimyr23/aspartix_file_parsing_and_reasoning_with_args
Python_parser_and_reasoning_semantics/semantics.py
semantics.py
py
3,690
python
en
code
0
github-code
6
27672884251
from typing import Dict, Tuple from copy import deepcopy import torch from config import tqc_config from modules import Actor, TruncatedQuantileEnsembledCritic class TQC: def __init__(self, cfg: tqc_config, actor: Actor, critic: TruncatedQuantileEnsembledCritic) ...
zzmtsvv/rl_task
offline_tqc/tqc.py
tqc.py
py
5,082
python
en
code
8
github-code
6
41267353320
from tkinter import * class JogoDaForca: def __init__(self, master): self.master = master master.title("Jogo da Forca") master.geometry("300x300") # palavra secreta self.palavra_secreta = "banana" # letras adivinhadas self.letras_adivinhadas = [] #...
Matheus-A-Santana/Estudos
Aprendendo Python/jogo-da-forca.py
jogo-da-forca.py
py
2,829
python
pt
code
0
github-code
6
24072421464
""" Parser.py Used to parse URLs into a linked list of dictionaries. """ from bs4 import BeautifulSoup import requests import re class Node: # pragma: no cover """ Creates a Node that contains data, and a next node Data holds any object. Next points to the next node, and should always be a node. ...
Jhawk1196/CS3250PythonProject
src/parser.py
parser.py
py
5,232
python
en
code
0
github-code
6
31111113064
#https://leetcode.com/problems/palindrome-linked-list/ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def makeList(arr): dummy = ListNode(0) curr = dummy for i in arr: curr.next = ListNode(i) curr = curr.next return dummy.next def traverse(head): ...
sparsh-m/30days
d6_2.py
d6_2.py
py
1,321
python
en
code
0
github-code
6
25354214474
def repeatedString(s, n): mul=n//len(s) rem=n%len(s) if rem>0: rem_string=s[:rem] s= list(s) num=s.count('a') num*=mul if rem>0: num+=rem_string.count('a')
nikjohn7/Coding-Challenges
Hackerrank/Python/4.py
4.py
py
199
python
en
code
4
github-code
6
39791046463
# -*- coding: utf-8 -*- # @Author: ShuaiYang # @Date: 2019-04-02 19:05:45 # @Last Modified by: ShuaiYang # @Last Modified time: 2019-04-02 19:05:47 # -*- coding: utf-8 -*- # @Author: ShuaiYang # @Date: 2019-04-02 16:57:49 # @Last Modified by: ShuaiYang # @Last Modified time: 2019-04-02 19:05:20 import tensorfl...
yangshuai8318243/TensorflowTestCode
netTestCode/testVar.py
testVar.py
py
852
python
en
code
1
github-code
6
38041664142
import random def cards(): cards_typs = [ ["Card 2", 2], ["Card 3", 3], ["Card 4", 4], ["Card 5", 5], ["Card 6", 6], ["Card 7", 7], ["Card 8", 8], ["Card 9", 9], ["Card 10", 10], ["Valete", 10], ["Dama", 10], ["Rei", 10...
arthurksilva/blackjack
blackjack.py
blackjack.py
py
1,896
python
pt
code
0
github-code
6
3229327686
#!/usr/bin/python ### File Information ### """ Rejector """ __author__ = 'duanqz@gmail.com' import os import fnmatch from config import Config class Rejector: """ Rejector: 1. Check whether conflicts happen. 2. Resolve conflicts automatically. """ CONFILCT_START = "<<<<<<<" CONFL...
baidurom/tools
autopatch/rejector.py
rejector.py
py
4,416
python
en
code
12
github-code
6
21273783061
class Session: def __init__(self, id, checkin_date, checkout_date): self.id = id self.checkin_date = checkin_date self.checkout_date = checkout_date class Reservation: def __init__(self,reservationid,date_of_arrival= None ,date_of_departure = None ,customerid = None ,paymentid = No...
zarif98sjs/innOcity
hotel/models.py
models.py
py
2,816
python
en
code
5
github-code
6
25847894028
import math from autocad_session import channel def extract_rectangles(): ret = [] cord_names = [f"{point}{value}" for point in ['a', 'b', 'c', 'd'] for value in ['x', 'y']] for obj in channel.session.doc.ModelSpace: # Test if it is a rectangle if "Polyline" in obj.ObjectName and obj.Close...
akila122/pycad
actions/extract_rectangle.py
extract_rectangle.py
py
1,237
python
en
code
0
github-code
6
18308754842
from tempfile import gettempdir import urllib.request import platform import zipfile from os.path import join from os import walk pth = "https://github.com/AequilibraE/aequilibrae/releases/download/V0.6.0.post1/mod_spatialite-NG-win-amd64.zip" outfolder = gettempdir() dest_path = join(outfolder, "mod_spatialite-NG-w...
AequilibraE/aequilibrae
tests/setup_windows_spatialite.py
setup_windows_spatialite.py
py
1,347
python
en
code
140
github-code
6
18609666305
#!/usr/bin/env python # -*- coding: UTF-8 -*- from waveapi import events from waveapi import model from waveapi import robot from pyactiveresource.activeresource import ActiveResource import logging import settings CC_XMPP = 'cc:xmpp' CC_TWITTER = 'cc:twitter' logger = logging.getLogger('GAE_Robot') logger.setLeve...
zh/gae-robot
gaerobot.py
gaerobot.py
py
2,435
python
en
code
4
github-code
6
14676087381
nums = input().split() print("Resumo dos Ímpares Positivos") print() cont = "" soma = 0 for l in nums: numero = int(l) if l % "2" != "0"and l > "0": soma += numero cont += nums[l] quant = len(cont) if quant == 0: print(f"Quantidade: {quant}") ...
lucas-santiagoo/Resumo-dos-mpares-Positivos
solucao.py
solucao.py
py
721
python
pt
code
0
github-code
6
14720838146
import torch import torch.nn as nn from collections import OrderedDict from networks.reshape import Reshape class ImageEncoder(nn.Module): def __init__(self, input_channels, layers_channels, prefix, useMaxPool=False, addFlatten=False): ''' If useMaxPool is set to True, Max pooling is used to reduce...
PradeepKadubandi/DemoPlanner
networks/imageencoder.py
imageencoder.py
py
1,593
python
en
code
0
github-code
6
3982882771
from time import time import sys, argparse, heightfield, os, povray_writer, load_info, read_lidar, cameraUtils, calculate_tile #/media/pablo/280F8D1D0A5B8545/TFG_files/cliente_local/ #/media/pablo/280F8D1D0A5B8545/TFG_files/strummerTFIU.github.io/ def tiles_to_render(c1, c2, zoom): """ Return the tiles needed to re...
strummerTFIU/TFG-IsometricMaps
src/main_program.py
main_program.py
py
18,332
python
en
code
0
github-code
6
34889766883
class Pitcher: """Class containing starting pitcher data""" def __init__(self, pitcher_block=None, home_team=None): self.pitcher_block = pitcher_block self.home_team = home_team self.player_name = None self.player_id = None self.player_handedness = None self.pitc...
xzachx/mlb_data_scraper
mlb_data_scraper/pitcher.py
pitcher.py
py
1,752
python
en
code
0
github-code
6
25003790859
import math from typing import Tuple import tensorflow as tf class ParityDataset(tf.keras.utils.Sequence): def __init__(self, n_samples: int, n_elems: int = 64, batch_size: int = 128): """ Parameters ---------- n_samples : int Number of samples. n_elems : int, ...
EMalagoli92/PonderNet-TensorFlow
pondernet_tensorflow/dataset/parity_dataset.py
parity_dataset.py
py
1,598
python
en
code
1
github-code
6
75092480826
from flint import acb class DirichletSeries: """ Class represents Dirichlet series with given coefficients. Can be called with various s values multiple times. """ def __init__(self, coefs): """ :param coefs: tuple of N series coefficients """ self.coefs = coefs ...
Deimos-Apollon/Dzeta-project
src/dirichlet_series/dirichlet_series_class.py
dirichlet_series_class.py
py
703
python
en
code
1
github-code
6
2888676781
import numpy as np from matplotlib import pyplot as plt if __name__ == '__main__': ch, time, date = np.genfromtxt("events220302_1d.dat", unpack=True, dtype=(int, float, 'datetime64[ms]')) mask1 = ch==1 mask2 = ch==2 time1 = time[mask1] time2 = time[mask2] date...
brinus/Sciami_lab4
UNIX_vs_FPGA.py
UNIX_vs_FPGA.py
py
841
python
en
code
0
github-code
6
30513150384
import json from .bx24.requests import Bitrix24 from .report.report_to_html import Report from .params import TYPE_MERGE_FIELD from.field_contacts_merge.data_update import FieldsContactsUpdate from api_v1.models import Email, Contacts, Companies, Deals bx24 = Bitrix24() # добавление контакта в БД def contacts_cre...
Oleg-Sl/Quorum_merge_contacts
merge_contacts/api_v1/service/handler.py
handler.py
py
12,833
python
ru
code
0
github-code
6
21299192914
"""Module to evaluate full pipeline on the validation set. python evaluate.py """ #!/usr/bin/env python # coding: utf-8 import os import sys import glob import numpy as np import image_preprocessing import cnn import bayesian_network import json import pandas as pd # class mapping classes = {"Positive": 0, "Neu...
samanyougarg/Group-Emotion-Recognition
evaluate.py
evaluate.py
py
3,390
python
en
code
43
github-code
6
23202639490
import struct import socket import sys import ipaddress import threading import os class client: """ Responsible for keeping track of the clients information """ def __init__(self, ip_address, ll_address): """ Initialises all variables needed Constructor: __init___(self, ip_address, ll_address) """ self....
TSampey/COMS3200-Assign3
assign3.py
assign3.py
py
12,355
python
en
code
0
github-code
6
73529467707
import os.path from sklearn import metrics from torch import nn, optim # noinspection PyUnresolvedReferences from tests.pytest_helpers.data import dataloaders, image # noinspection PyUnresolvedReferences from tests.pytest_helpers.nn import sample_model def test_fit(sample_model, dataloaders): try: model ...
default-303/easyTorch
tests/testUtils/test_trainer.py
test_trainer.py
py
1,039
python
en
code
2
github-code
6
27513864943
import copy from timsconvert import * def run_tims_converter(args): # Load in input data. logging.info(get_timestamp() + ':' + 'Loading input data...') if not args['input'].endswith('.d'): input_files = dot_d_detection(args['input']) elif args['input'].endswith('.d'): input_files = [ar...
orsburn/timsconvert
bin/run.py
run.py
py
7,351
python
en
code
null
github-code
6
74750230586
import os import pathlib import shutil from datetime import datetime from pathlib import Path from my_logger_object import create_logger_object def copy_component(component_kb_list, component_name, source_folder, target_folder): # source_folder = r"C:\CodeRepos\GetOfficeKBs\Folder_Office2016_KBs\x64_msp" # t...
FullStackEngN/GetOfficeKBs
get_msp_file_for_specified_msp_list.py
get_msp_file_for_specified_msp_list.py
py
3,495
python
en
code
1
github-code
6
23196116357
import pyspark import networkx as nx import pandas as pd from pyspark.sql.types import ( LongType, StringType, FloatType, IntegerType, DoubleType, StructType, StructField, ) import pyspark.sql.functions as f from pyspark.sql.functions import pandas_udf, PandasUDFType from networkx.algorithms...
moj-analytical-services/splink_graph
splink_graph/node_metrics.py
node_metrics.py
py
6,877
python
en
code
6
github-code
6
13162464659
grammar = [ ("S", ["P"]), # S -> P ("P", ["(", "P", ")"]), # P -> ( P ) ("P", []), # P -> ] tokens = ["(", "(", ")", ")"] grammar2 = [ ("P", ["S"]), ("S", ["S", "+", "M"]), ("S", ["M"]), ("M", ["M", "*", "T"]), ("M", ["T"]), ("T", ["1"]), ("T", ["2"]),...
panmengguan/Udacity_CS262
Unit4/Parser_Earley.py
Parser_Earley.py
py
4,707
python
en
code
0
github-code
6
1065053262
'''Calculus Chapter of Hacking Math Class''' from turtle import * from algebra import setup, graph from geometry2 import line,perpendicularLine, intersection speed(0) def f(x): return -0.2*x**5 + 1.4*x**4+x**3-5*x**2-1.5*x + 3 def derivative(a): '''Returns the derivative of a function at point x...
hackingmath/BayPIGgies-Talk
calculus.py
calculus.py
py
3,663
python
en
code
0
github-code
6
663159079
#! /usr/bin/env python import pandas as pd if __name__ == '__main__': dataset = 'D3' path = '/home/milan/workspace/strands_ws/src/battery_scheduler/data/csv_files/' eb_f = path+'taskbased_overall_'+dataset+'_models.csv' tb_f = path+'timebased_overall_'+dataset+'_models.csv' c_f = path+'combine...
milanmt/Battery-Scheduler
src/analysis/combined_statistics.py
combined_statistics.py
py
991
python
en
code
0
github-code
6
5479668707
import argparse import os, numpy as np import os.path as osp from multiprocessing import Process import h5py import json os.environ["D4RL_SUPPRESS_IMPORT_ERROR"] = "1" os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["MKL_NUM_THREADS"] = "1" os.environ["NUMEXPR_NUM_THREADS"] = "1" os.environ["OMP_NUM_THREADS"...
haosulab/ManiSkill2-Learn
tools/convert_state.py
convert_state.py
py
10,700
python
en
code
53
github-code
6
70098626428
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2, c = 0): # base case checking res = ListNode(0) if not l1 and not l2: return res elif not l1: return l2 elif not l2: return l1...
alexmai123/AlgoTime
Leetcode_problem/LinkedList/LinkedListSum.py
LinkedListSum.py
py
1,626
python
en
code
1
github-code
6
23303525367
import pandas as pd from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score import matplotlib.pyplot as plt def kmeans(): data = \ pd.read_csv( '2019-04-28xm_fish.csv', names=['房源名称', '租赁种类', '房源类型', '房源户型', '房源面积', '房源楼层', '房源朝向', '装修等级', '房源地址', '行政区划', '房...
Joy1897/Spider_58
kmeans.py
kmeans.py
py
2,423
python
en
code
0
github-code
6
72060297789
from flask import render_template, Flask, request, jsonify, url_for, redirect import requests from flask_pymongo import PyMongo import json from Model import * import time def after_request(response): response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'PUT...
xiechzh/Accomodation-Web-Portal
COMP9900_Proj/COMP9900_Proj.py
COMP9900_Proj.py
py
13,953
python
en
code
1
github-code
6
71567683388
import streamlit as st import pandas as pd @st.cache def load_data(): data = pd.read_csv('data.csv', sep=';', encoding='latin1') return data data = load_data() selected_country = st.selectbox("Select a Country", data['Country']) col1, col2 = st.columns(2) with col1: coal_percent = st.slider("Coal %",...
sneha-4-22/Energy-Calculator
app.py
app.py
py
3,135
python
en
code
0
github-code
6
32623837320
from base_factor import BaseFactor from data.data_module import DataModule class PEFactor(BaseFactor): def __init__(self): BaseFactor.__init__(self,'pe') def compute(self,begin_date,end_date): print(self.name,flush=True) dm =DataModule() df_daily = dm.get_k_data() prin...
bowenzz/Quant-Trading-System
factor/pe_factor.py
pe_factor.py
py
403
python
en
code
0
github-code
6
23268800112
# Here we will conduct a A/B test import math from hypo_testing import normal_probability_two_sided def estimated_parameter(n, N): p = n / N sigma = math.sqrt(p * N * (1- p)) return N * p, sigma def a_b_test_statistics(n_a, N_a, n_b, N_b): p_a, sigma_a = estimated_parameter(n_a, N_a) p_b, sigma_b =estimated_par...
shm4771/Data-Science-From-Scratch
src/hypothesis_testing/A_B_test.py
A_B_test.py
py
585
python
en
code
0
github-code
6
21003174437
# This code is in the Public Domain # ----------------------------------------------------------------------------- # This source file is part of Python-Ogre # For the latest info, see http://python-ogre.org/ # # It is likely based on original code from OGRE and/or PyOgre # For the latest info, see http://www.ogre3d.or...
only-a-ptr/ror-toolkit
windows/ogre/renderer/OGRE/sf_OIS.py
sf_OIS.py
py
23,588
python
en
code
4
github-code
6
24200680597
from collections import Counter class Solution: def func(self, strings, K): """ Args: strings: list[str] K: int """ counter = Counter(strings) counter_list = [(key, counter[key]) for key in counter] # 频数大, 字母序小 -> 频数小, 字母序大 counter_li...
AiZhanghan/Leetcode
秋招/腾讯/3.py
3.py
py
787
python
en
code
0
github-code
6
71353706429
# GMM implementation # good resource http://www.rmki.kfki.hu/~banmi/elte/bishop_em.pdf import numpy as np from scipy import stats import seaborn as sns from random import shuffle, uniform sns.set_style("white") #Generate some data from 2 different distributions x1 = np.linspace(start=-10, stop=10, num=1000) x2 = np.l...
cristian904/GMMs
GMM.py
GMM.py
py
2,456
python
en
code
0
github-code
6
14570677084
###=========================================================### ### ### ### Create Boundary Condition(BC) ### ### ### ###=========================================================### ...
caron14/2D-FEM
mod_set_BC.py
mod_set_BC.py
py
1,077
python
en
code
0
github-code
6
17936071521
__author__ = 'gilles.drigout' from proposal import * from numpy import zeros, random from numbapro import cuda from numbapro.cudalib import curand import math import time @cuda.autojit def cu_one_block(x_start, y, omega, uniforms, result, size, chain_length): i = cuda.grid(1) if i < size: result[i,0...
Jingoo88/Projet-3A-2015
Kernel method/blockIMH.py
blockIMH.py
py
4,087
python
en
code
0
github-code
6
3547587015
import numpy as np import tensorflow as tf from structure_vgg import CNN from datetime import datetime import os from tfrecord_reader import tfrecord_read import config os.environ['CUDA_VISIBLE_DEVICES'] = '1' FLAGS = tf.flags.FLAGS tf.flags.DEFINE_string('dataset', 'dset1', 'Choose dset1 or dset2 for training, defaul...
yikaiw/DL-hw2-CNN
main.py
main.py
py
4,806
python
en
code
0
github-code
6
38231691013
from django.shortcuts import render, get_object_or_404 from .models import Post, Group def index(request): posts = Post.objects.order_by('-pub_date')[:10] title = 'Это главная страница проекта Yatube' context = { 'posts': posts, 'title': title, } return render(request, 'posts/index...
NikitaKorovykovskiy/Yatube_project
yatube/posts/views.py
views.py
py
762
python
en
code
0
github-code
6
71781170429
import cv2 # read your picture and store into variable "img" img = cv2.imread('picture.jpg') # scale image down 3 times for i in range(3): img = cv2.pyrDown(img) # save scaled image cv2.imwrite(f'picture_scaled_{i}.jpg', img)
yptheangel/opencv-starter-pack
python/basic/image_pyramid.py
image_pyramid.py
py
240
python
en
code
8
github-code
6
21806123410
import sys def set_options(opt): opt.tool_options("compiler_cxx") def configure(conf): conf.check_tool("compiler_cxx") conf.check_tool("node_addon") if sys.platform == 'darwin': conf.env.append_value('LINKFLAGS', ['-framework','CoreMidi','-framework','CoreAudio','-framework','CoreFoundation']) else: ...
sksmatt/NodeJS-Ableton-Piano
node_modules/midi/wscript
wscript
725
python
en
code
104
github-code
6
7886651161
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 18 21:42:00 2021 @author: fyy """ import scipy.stats as stats import numpy as np import random import scipy.io as scio import matplotlib.pyplot as plt import math dataFile = './_dat/val_dataset.mat' ratio = 0.05 sample_num = ...
Carty-Bao/BNPHMM
code/gen_new.py
gen_new.py
py
9,565
python
en
code
0
github-code
6
16104264799
import gatt import numpy as np import time import datetime class BLE(gatt.Device): def __init__(self, Age, Height, Gender, Write, manager,mac_address): super().__init__(manager = manager , mac_address = mac_address) self.Age = Age self.Height = Height self.Gender = Gender ...
sanbuddhacharyas/MEDICAL_CARE
source_code/BLE.py
BLE.py
py
4,518
python
en
code
0
github-code
6
35800840346
import unittest import numpy as np from numpy import linalg from task import img_rescaled, img_array_transposed, U, s, Vt class TestCase(unittest.TestCase): def test_transpose(self): np.testing.assert_array_equal(img_array_transposed, np.transpose(img_rescaled, (2, 0, 1)), ...
jetbrains-academy/Python-Libraries-NumPy
Projects/SVD/Applying to All Colors/tests/test_task.py
test_task.py
py
1,073
python
en
code
1
github-code
6
72473999867
from math import sqrt import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D x1_list = [] x2_list = [] y_list = [] counter = 0 def show(x1_list, x2_list): N = int(x1_list.__len__()) if (N <= 0): return fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) ...
AlexSmirno/Learning
6 Семестр/Оптимизация/Lab_4_1.py
Lab_4_1.py
py
3,768
python
en
code
0
github-code
6
37056080424
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Simple univariate BLUP implementation for starting values estimation.""" import numpy as np from scipy.optimize import minimize def grad(sigmas: np.ndarray, y: np.ndarray, k: np.ndarray): v = 1 / (sigmas[0] + sigmas[1] * k) if np.any(v < 1e-12): return...
planplus/pysem
pysem/univariate_blup.py
univariate_blup.py
py
1,705
python
en
code
4
github-code
6
8257233523
# Use the environment variables DIANA_BROKER and DIANA_RESULT to attach the celery # app to a message queue. import os from celery import Celery app = Celery('diana') app.conf.update( result_expires = 3600, task_serializer = "pickle", accept_content = ["pickle"], result_serializer = "pickle", tas...
derekmerck/DIANA
packages/diana/diana/star/app.py
app.py
py
776
python
en
code
11
github-code
6
3337645854
import time from pyspark import SparkContext,SparkConf #----------------------------------------------- #spark map reduce练习 def mymap(line): return len(line) #在spark中这样对数字进行叠加是不可行对 由于闭包机制,每一份机器上都单独有一份所引用都对象 应该使用saprk提供都累加器 nums_all=0 def test_foreach(nums): global nums_all nums_all+=nums print(nums_...
zml1996/learn_record
learn_spark/test_spark2.py
test_spark2.py
py
1,066
python
fa
code
2
github-code
6
38633501754
def get_input(): done = False while not done: try: points = int(input('How many points does the post have?: ')) if points > 0: ratio = int(input('What is the percentage of users who upvoted the post?: ')) if ratio <= 100 and ratio > 50: ...
mthezeng/hello-world
redditvotes.py
redditvotes.py
py
1,372
python
en
code
0
github-code
6
12477690188
#!/ebio/abt1_share/toolkit_support1/sources/anaconda3/bin/python import glob import re import pandas as pd data_dir = '/tmp/global2/vikram/felix/master_thesis/data/alphafold/v2' data_dir = '/Users/felixgabler/PycharmProjects/master_thesis/data/alphafold/v2' def write_seq_to_file(accession: str, uniprot_id: str, se...
felixgabler/master_thesis
bin/utils/split_sequences.py
split_sequences.py
py
1,472
python
en
code
0
github-code
6
71666200828
from django.contrib import admin from .models import newdoc class DocAdmin(admin.ModelAdmin): fieldsets = [ (None, {"fields": ["title"]}), ("Date information", {"fields": ["created_time"]}), (None, {"fields": ["modified_time"]}), ("Au...
JarvisDong/Project-CGD
mysite/documents/admin.py
admin.py
py
652
python
en
code
0
github-code
6
664923791
#Import's import random #Variáveis #Classes guerreiro = [ #Nome(0) Vida(1) 'Guerreiro', 50, #Ataque básico(2) dano(3) 'Corte de espada', 10, #Ataque especial(4) dano(5) 'Lamina ardente', 20 ] arqueiro = [ ...
KancsSneed/Exercicios_python
Atividades/rpg.py
rpg.py
py
1,931
python
pt
code
0
github-code
6
26113491295
__authors__ = ["T. Vincent"] __license__ = "MIT" __date__ = "06/03/2018" from .. import qt class BoxLayoutDockWidget(qt.QDockWidget): """QDockWidget adjusting its child widget QBoxLayout direction. The child widget layout direction is set according to dock widget area. The child widget MUST use a QBoxL...
silx-kit/silx
src/silx/gui/widgets/BoxLayoutDockWidget.py
BoxLayoutDockWidget.py
py
2,125
python
en
code
106
github-code
6