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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
35428179764 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import copy
import os
import warnings
import cdflib
import numpy as np
import pandas as pd
import sunpy
from packaging.version import Version
from sunpy.net import Fido
from sunpy.net import attrs as a
from sunpy.timeseries import TimeSeries
from seppy... | serpentine-h2020/SEPpy | seppy/loader/psp.py | psp.py | py | 31,552 | python | en | code | 5 | github-code | 13 |
28614597959 |
import math
water_heat_capacity=4.186
electricity_price=8.9
kilowatth_hour=2777*math.e**-7
vol=float(input('Ingrese cantidad de agua:'))
temperature=float(input('Ingrese tempreatura: '))
q=vol*temperature*water_heat_capacity
print('Se requieren %d joules de energia' %q)
kwh=q+kilowatth_hour
costo=kwh+electricity_... | Lusarom/progAvanzada | ejercicio17.py | ejercicio17.py | py | 367 | python | en | code | 1 | github-code | 13 |
28880445475 | from checkers.constants import WIDTH, HEIGHT, SQUARE_SIZE, BLACK, DARK_BEIGE, WHITE
from checkers.game import Game
from minimax.minimax import minimax
from minimax.alpha_beta import alpha_beta
from monte_carlo.monte_carlo_tree_search import monte_carlo_tree_search
import pygame
FPS = 60
WINDOW = pygame.display.set_mod... | mh022396/Checkers-AI | src/main.py | main.py | py | 2,616 | python | en | code | 0 | github-code | 13 |
33259281187 | """Take a document that has a key values: list<int> and add the following keys
* total: the sum of all the values
* count: how many values
"""
import copy
import random
from streamparse import bolt
class SummariseBolt(bolt.Bolt):
auto_ack = False
def process(self, tup):
self.log(u"Received: {0}".for... | sujaymansingh/sparse_average | src/summarise.py | summarise.py | py | 1,517 | python | en | code | 1 | github-code | 13 |
36026572854 | """
main transfer protocol used in the web
Javascript object Notation (JSON): an object converted to string
similar to dictionary in Python
1. client prepares request
2. client sends HTTP request
3. Server recieves request and looks for data
4. Server sends back response
.get()
.post()
basics of https requests
"""
# i... | triggxl/Python3 | 04-requests.py | 04-requests.py | py | 877 | python | en | code | 0 | github-code | 13 |
19214605660 | import requests
import dict_users
import time
from bs4 import BeautifulSoup
import pytz
from datetime import datetime, timedelta
import exception_logger
current_datetime = time.strftime('%d.%m.%Y %H:%M')
dt_utc_arrive = datetime.strptime(current_datetime, '%d.%m.%Y %H:%M').replace(tzinfo=pytz.utc)
dt_minus_4... | azarovdimka/python | telebot/opensky_radar.py | opensky_radar.py | py | 4,338 | python | ru | code | 1 | github-code | 13 |
22477365648 | from pygame import *
from animations import *
class trainer():
def __init__(self, x, y, width, height):
# Pos. attributes
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
# Attributes for walk direction
self.l... | KarlMarkFuncion/Portfolio_1 | objectPlayers.py | objectPlayers.py | py | 1,709 | python | en | code | 1 | github-code | 13 |
6142009976 | import microgp4 as ugp
def test_make_shared_parameter():
for p in [
ugp.f.integer_parameter(0, 10_000_000),
ugp.f.float_parameter(0, 1.0),
ugp.f.choice_parameter(range(10_000)),
ugp.f.array_parameter("01X", 256),
]:
SharedParameter = ugp.f.make_shared_parameter(p)
... | microgp/microgp4 | test/microgp4/framework/_test_shared.py | _test_shared.py | py | 954 | python | en | code | 27 | github-code | 13 |
73539328338 | import numpy as np
import learning
import random
import time
positiveLabel = learning.positiveLabel
negativeLabel = learning.negativeLabel
data = "../common/cancer/wdbc.data"
def main():
startTime = time.time()
X, Y = load_data()
classifier, iters, error, (precision, recall, f1) = learning.learn(X, Y)
... | anton-bannykh/ml-2013 | artem.vasilyev/lab4-logistic/main.py | main.py | py | 1,009 | python | en | code | 4 | github-code | 13 |
24511360921 | from PyQt4.QtGui import *
from PyQt4.QtCore import *
import anki, anki.utils
from anki.sound import playFromText, stripSounds
from anki.latex import renderLatex, stripLatex
from anki.utils import stripHTML
from anki.hooks import runHook, runFilter
import types, time, re, os, urllib, sys, difflib
from ankiqt import ui
f... | scout-zz/ankiqt | ankiqt/ui/view.py | view.py | py | 10,795 | python | en | code | 4 | github-code | 13 |
2872516640 | import math
from django.db.models import Max, Min
from shop.filters.filters import ManufacturerFilter, PriceFilter, DimensionFilter
filter_mapping = {
'producer': ManufacturerFilter,
'price': PriceFilter,
'height': DimensionFilter,
'width': DimensionFilter,
'depth': DimensionFilter
}
def get_v... | slavkoBV/MebliLem | myshop/shop/filters/filters_utils.py | filters_utils.py | py | 2,131 | python | en | code | 1 | github-code | 13 |
21985738669 | import cv2
#Récupération de l'image
img = cv2.imread('Images/Mars_surface.pbm')
isize = img.shape #Propriétés de l'images
vPixMax = 0
vPix = 0
compteur = 0
tauxHumidité = 0
for i in range(0, isize[0]):
for j in range(0, isize[1]):
vPix = vPix + img[i][j]
compteur = compteur +1
vPixMax = comp... | Eager31/Projet-ExoLife | MissionA2.py | MissionA2.py | py | 524 | python | fr | code | 0 | github-code | 13 |
18484735844 | import time
import arcade
from typing import List, Tuple
import constants as c
import mapdata
import player
import isometric
import ui
import turn
import interaction
from bot import create_bot
class Mouse(arcade.Sprite):
def __init__(self, window):
super().__init__("assets/ui/cursor.png", c.SPRITE_SCAL... | DragonMoffon/Temporum | views.py | views.py | py | 19,235 | python | en | code | 2 | github-code | 13 |
7188629605 | #T# the following code shows how to draw a circle to show examples of segments and lines of circles
#T# to draw a circle to show examples of segments and lines of circles, the pyplot module of the matplotlib package is used
import matplotlib.pyplot as plt
#T# the patches module of the matplotlib package is used to dr... | Polirecyliente/SGConocimiento | Math/C01_Geometry_basics/Programs/S04/Segments_and_lines_of_a_circle_image.py | Segments_and_lines_of_a_circle_image.py | py | 3,083 | python | en | code | 0 | github-code | 13 |
15863858271 | import os
from django.core.files.storage import default_storage
from apps.common.models import BaseModel, Institucion, UbigeoPais
from django.db import models
from apps.persona.models import Persona
class Distincion(BaseModel):
institucion = models.ForeignKey(Institucion, on_delete=models.PROTECT)
distinci... | cpaucarc/legajos | apps/distincion/models.py | models.py | py | 1,369 | python | en | code | 2 | github-code | 13 |
27397459234 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
from aiohttp import web
import asyncio
from text_transformation.transformer import Transformer
class Server:
def __init__(self):
app = web.Application()
# adding current routes
routes = [
web.post("/transform_text", self.t... | TLReber/LSPT-TextTransformation | sandbox/_server.py | _server.py | py | 594 | python | en | code | 1 | github-code | 13 |
10977881958 | import ipaddress
from pathlib import Path
from typing import List, Optional, Any
import yaml
from model.manufacturer import Manufacturer
from repository.exceptions import (
ManufacturerAlreadyExistsException,
ManufacturerNotFoundException,
)
from .manufacturers import ManufacturersRepository
def ipv4_repres... | pedrolp85/pydevice | app/repository/manufacturers/manufacturersYAMLfile.py | manufacturersYAMLfile.py | py | 3,184 | python | en | code | 0 | github-code | 13 |
47005982804 | import numpy as np
def cross_v(a1='aroonlow',val11=100,df=None):
ar=a1+str(val11)+'_v'
df[ar]=None
if val11>0 :
df[ar]=np.where(df[a1]>=val11,df[a1],0)
else :
df[ar]=np.where(df[a1]<=val11,df[a1],0)
return df[ar] | aa3110/python-trading | biblio/trade/t_cross_v.py | t_cross_v.py | py | 240 | python | en | code | 1 | github-code | 13 |
37086085946 | from .internal import GradientLayer, MomentumNormalization, \
NeighborhoodReduction, \
PairwiseValueNormalization, PairwiseVectorDifference, \
PairwiseVectorDifferenceSum, VectorAttention
import flowws
from flowws import Argument as Arg
import numpy as np
import tensorflow as tf
from tensorflow import kera... | klarh/flowws-keras-geometry | flowws_keras_geometry/models/MoleculeForceRegression.py | MoleculeForceRegression.py | py | 8,004 | python | en | code | 6 | github-code | 13 |
30647468625 | import glob
import os
from typing import Tuple, Union
import subprocess
import pandas as pd
from PIL.Image import Image
from torch import Tensor
from torchvision.datasets import ImageFolder
OA_DATASET_FULL = 'OA_DATASET_FULL'
OA_DATASET_COLOR = 'OA_DATASET_COLOR'
OA_DATASET_FULL_25x25 = 'OA_DATASET_FULL_25x25'
OA_DA... | rogierknoester/omniart_eye_dataset | omniart_eye_dataset/OmniArtEyeDataset.py | OmniArtEyeDataset.py | py | 3,415 | python | en | code | 1 | github-code | 13 |
11426899558 | from project.roboti.female_robot import FemaleRobot
from project.roboti.male_robot import MaleRobot
from project.services.main_service import MainService
from project.services.secondary_service import SecondaryService
class RobotsManagingApp:
SERVICE_TYPES = {"MainService": MainService, "SecondaryService": Second... | KrisKov76/SoftUni-Courses | python_OOP_10_2023/Python OOP - Exams/Python OOP Exam - 8 April 2023/project/robots_managing_app.py | robots_managing_app.py | py | 3,410 | python | en | code | 0 | github-code | 13 |
8105214820 | import os
from typing import List
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import base64
import numpy as np
from io import BytesIO
FONT_PATH = os.path.join(os.path.dirname(
__file__), "TaipeiSansTCBeta-Regular.ttf")
FONT_PROP = fm.FontProperties(fname=FONT_PATH)
def process(data: List... | hanshino/redive_linebot | opencv/module/world/damage_chart.py | damage_chart.py | py | 1,814 | python | en | code | 21 | github-code | 13 |
41454898706 | import time
import math
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from data_helper import MyDataSet
from model import *
trainset = MyDataSet('data/x_training.txt','data/y_training.txt','data/word_dict','data/pos_dict','data/ner_dict',max_len=100,is_... | jxst539246/NLPCC-task-5 | train.py | train.py | py | 4,808 | python | en | code | 0 | github-code | 13 |
7770893740 | from mmcv.transforms.builder import TRANSFORMS
import cv2
import numpy as np
from typing import Optional
import mmengine
import numpy as np
import mmcv
from mmcv.transforms.base import BaseTransform
from mmcv.transforms.builder import TRANSFORMS
@TRANSFORMS.register_module()
class LoadImage(BaseTransform):
"""Lo... | FreeformRobotics/EAEFNet | EAEFNet_Detection/EAEF_mmyolo/mmyolo/datasets/LoadImageFromFile.py | LoadImageFromFile.py | py | 3,022 | python | en | code | 34 | github-code | 13 |
39186389614 | """Add land
Revision ID: 95979d057d0a
Revises: ed8c6f0d7b6b
Create Date: 2023-07-13 15:49:14.939055
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '95979d057d0a'
down_revision = 'ed8c6f0d7b6b'
branch_labels = None
depends_on = None
def upgrade():
# ### c... | DamyanBG/real-estate-flask-rest-api | migrations/versions/95979d057d0a_add_land.py | 95979d057d0a_add_land.py | py | 1,769 | python | en | code | 0 | github-code | 13 |
21313733623 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 14 12:11:22 2019
@author: Adarsh
"""
#logistic regression
import pandas as pd
import numpy as np
import seaborn as sb
import matplotlib.pyplot as plt
import statsmodels.formula.api as sm
from sklearn.model_selection import train_test_split # train and test... | adarshm93/Regression | bank_data.py | bank_data.py | py | 5,068 | python | en | code | 1 | github-code | 13 |
41297149032 | from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'djangotest.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^adm... | MinWangCop/djangotest | djangotest/urls.py | urls.py | py | 947 | python | en | code | 0 | github-code | 13 |
12607970954 | def accommodate_new_pets(hotel_capacity, max_weight, *args):
accommodated_pets = 0
dictionary = {}
for i in args:
pet_type = i[0]
pet_weight = i[1]
if accommodated_pets < hotel_capacity:
if pet_weight <= max_weight:
accommodated_pets += 1
i... | DianTenev/Programming-advanced | Python Advanced Retake Exam - 09 August 2023/03. Pets Hotel.py | 03. Pets Hotel.py | py | 1,182 | python | en | code | 1 | github-code | 13 |
9628126147 | from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local[8]").setAppName("PopularHero") # Trying out 8 threads
sc = SparkContext(conf=conf)
# Marvel-Names.txt data format:
# first value: Marvel hero ID
# Second value: Marvel hero name
#
# Example:
# 2549 "HULK III/BRUCE BANNE"
def parseNames(l... | MManopoli/TamingBigDataWithSparkAndPython | 19-22_more_examples_of_Spark_programs/most-popular-superhero.py | most-popular-superhero.py | py | 2,015 | python | en | code | 0 | github-code | 13 |
14989099669 | from menu import products
def get_product_by_id(id: int) -> dict:
if type(id) == int:
product_found = {}
for item in products:
if item['_id'] == id:
product_found = item
return product_found
raise TypeError('product id must be an int')
def get_produc... | jorgekimura2001/projeto-kiosque | management/product_handler.py | product_handler.py | py | 1,978 | python | en | code | 0 | github-code | 13 |
4321361401 | from financepy.utils.math import scale
from financepy.market.curves.discount_curve_nss import DiscountCurveNSS
from financepy.utils.date import Date
import numpy as np
tau1 = 2.0
tau2 = 0.5
times = np.linspace(0.0, 10.0, 5)
start_date = Date(1, 1, 2020)
dates = start_date.add_years(times)
def test_factor_loading_ze... | domokane/FinancePy | tests/test_FinDiscountCurveNSS.py | test_FinDiscountCurveNSS.py | py | 2,689 | python | en | code | 1,701 | github-code | 13 |
39018875242 | from cmath import inf
from typing import List
from collections import defaultdict
from sympy import deg
class Solution:
def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:
nodes = defaultdict(set)
for u, v in edges:
nodes[u].add(v)
nodes[v].add(u)
a... | sarveshbhatnagar/CompetetiveProgramming | connected_trio.py | connected_trio.py | py | 1,515 | python | en | code | 0 | github-code | 13 |
42654542052 | # add function
my_set = {1, 2, 3, 4, 5}
print(my_set)
# add a value, successfull
my_set.add(6)
print(my_set)
# add a value, unsuccessful, but doesn't throw error.
my_set.add(6)
print(f"Doesn't add 6 again, {my_set} ")
# remove function
# successful if element is in the set.
my_set.remove(3)
print(f"Removing 3, {my_... | abhinav-m/python-playground | tutorials/basics/data-structures/tuples_and_sets/set_methods.py | set_methods.py | py | 950 | python | en | code | 0 | github-code | 13 |
12365892372 | from PIL import Image
import math
import colorsys
import random
from time import sleep
class WaterPlayer:
def __init__(self, width,height):
self.width = width
self.height = height
self.caustic = Image.open("../assets/caustics-texture.gif").resize((32,32))
self.vec1 =[random.uniform(-0.2,0.2),random.... | andrewdyersmith/pingpongpi | daemon/water_player.py | water_player.py | py | 1,504 | python | en | code | 0 | github-code | 13 |
21850111552 | import util as ut
import xarray as xr
import absplots as apl
def main():
"""Main program called during execution."""
# initialize figure
fig, grid = apl.subplots_mm(
figsize=(135, 115), nrows=2, ncols=4, gridspec_kw=dict(
left=2.5, right=17.5, bottom=2.5, top=2.5, wspace=2.5, hspace=2... | juseg/cordillera | figures/ciscyc_hr_deglacshots.py | ciscyc_hr_deglacshots.py | py | 2,467 | python | en | code | 0 | github-code | 13 |
14379602352 | """Contains methods for loading data in various way."""
import tensorflow as tf
import download_and_convert as dc
import data_utils
# The default directory where the temporary files and the TFRecords are stored.
_DATA_DIR = 'data'
def load_data_numpy():
""" Get the data in ndarray format
Args:
None... | jenhokuo/LED-Digits-Recognition | dataset_led.py | dataset_led.py | py | 1,461 | python | en | code | 0 | github-code | 13 |
21332910639 | import matplotlib.pyplot as plt
import numpy as np
import os
import keras
from tensorflow.keras import layers
from PIL import Image
import tensorflow as tf
import tensorflow_addons as tfa
train_ds = tf.keras.utils.image_dataset_from_directory(
'sortedPics/forTraining',
label_mode='categorical',
validation_split=0... | nmayerfeld/summerProject | Model7.py | Model7.py | py | 4,160 | python | en | code | 2 | github-code | 13 |
28389641522 | import sys, os, time
PACKAGE_PARENT = '../..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
from master_bot.master import Bot as runeBot
player = runeBot(os.path.normpath(os.path.join(S... | SimSam115/orsr_bbb | tests/usingMaster_bot/cannonballMaker.py | cannonballMaker.py | py | 762 | python | en | code | 0 | github-code | 13 |
29831260945 | import numpy as np
import torch
from collections import defaultdict
import string
from sequence.data import traits
from enum import IntEnum
from typing import List, Dict, Optional, Union, Sequence
import functools
def lazyprop(fn):
attr_name = "_lazy_" + fn.__name__
@property
@functools.wraps(fn)
def... | ritchie46/sequence | sequence/data/utils.py | utils.py | py | 11,796 | python | en | code | 10 | github-code | 13 |
8093465008 | import bpy
import os
import subprocess
import codecs
from . import paths_doors_windows
from . import utils_doors_windows
from pc_lib import pc_types, pc_unit, pc_utils
def get_current_view_rotation(context):
'''
Gets the current view rotation for creating thumbnails
'''
for window in context.window_man... | CreativeDesigner3D/home_builder | assets/products/sample_doors_windows/ops_doors_windows.py | ops_doors_windows.py | py | 12,668 | python | en | code | 47 | github-code | 13 |
70706687698 | import yaml
import sys
import discord
import os
from dotenv import load_dotenv
# Loading configuration
load_dotenv()
with open('config.yml', 'rb') as f:
config = yaml.safe_load(f)
# Discord initialization
intents = discord.Intents.default()
discord_client = discord.Client(intents=intents)
# Get our data from argum... | Athexe/David-Bot | discord_messager.py | discord_messager.py | py | 2,524 | python | en | code | 0 | github-code | 13 |
27702446053 | """
Title: Open/parse FIA data
Author: Tony Chang
"""
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import norm
import matplotlib.mlab as mlab
def plot_fia(data):
plt.scatter(data['LON'],data['LAT'])
return()
def data_AOA(AOA, plot):
#returns the data filtered by bounding box AOA
lat =... | tonychangmsu/Python_Scripts | eco_models/wbp/FIA_piekielek_extractor.py | FIA_piekielek_extractor.py | py | 6,102 | python | en | code | 0 | github-code | 13 |
37175485494 | import sys, os
import six
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),
'..', 'modules', 'MCcubed', 'MCcubed', 'plots', ''))
from mcplots import trace, pairwise, histogram
__all__ = ["mc3plots"]
... | exosports/BART | code/mc3plots.py | mc3plots.py | py | 3,265 | python | en | code | 31 | github-code | 13 |
2296248693 | """Time-related utilities."""
import re
from typing import Optional
from dateutil.relativedelta import relativedelta
_DURATION_REGEX = re.compile(
r"((?P<years>\d+?) ?(years|year|Y|y) ?)?"
r"((?P<months>\d+?) ?(months|month|m) ?)?"
r"((?P<weeks>\d+?) ?(weeks|week|W|w) ?)?"
r"((?P<days>\d+?) ?(days|da... | bsoyka/roboben | bot/utils/time.py | time.py | py | 1,364 | python | en | code | 2 | github-code | 13 |
17035581924 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.Position import Position
class AdGroup(object):
def __init__(self):
self._ad_user_id = None
self._crowd_condition = None
self._group_id = None
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AdGroup.py | AdGroup.py | py | 4,596 | python | en | code | 241 | github-code | 13 |
39778030716 | import os
import pandas as pd
import logging
from tqdm import tqdm
from typing import Union, Optional
from logging import getLogger
tqdm.pandas()
logger = logging.getLogger(__file__)
formatter = logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s", "%Y-%m-%d %H:%M:%S"
)
# from config import umls_api_ke... | davidkartchner/biomedical-entity-linking | umls_utils.py | umls_utils.py | py | 22,206 | python | en | code | 2 | github-code | 13 |
33387389833 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from random import shuffle
import matplotlib
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3 # noqa: F401
import numpy as np
from matplotlib import animation
from more_itertools import peekable
from mpl_toolkits.mplot3d.art3d import Li... | simrit1/attractors | attractors/attractor.py | attractor.py | py | 10,423 | python | en | code | 0 | github-code | 13 |
41032947993 | alphabet = 'QWERTYUIOPASDFGHJKLZXCVBNM'
fin = open('sr-sample-input.txt')
fout = open('output.txt', 'w')
lines = [(i[:-1] if i[-1]=='\n' else i) for i in fin.readlines()]
lines = [''.join(['' if c.capitalize() not in alphabet else c.capitalize() for c in i]) for i in lines]
def ADF(a, b):
maxlen, maxpos = -1, (0, 0)
... | u8y7541/acsl | 2020senior2/2020senior2.py | 2020senior2.py | py | 913 | python | en | code | 0 | github-code | 13 |
74527289938 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 9 16:03:15 2020
@author: Hugo
"""
import math
f = lambda x: (1 +(2.5*math.e**(2.5*x))**2 )**(1/2)
g = lambda x: math.sqrt(1 + pow(2.5 * pow(math.e, 2.5 * x), 2))
def trapezios(f,a,b,h):
n = int((b-a)/h)
St = f(a) + f(b)
for i in range (1,n):
# ... | Hugomguima/FEUP | 1st_Year/1st_Semestre/Mnum/Exame/Exame 2017/Pergunta2.py | Pergunta2.py | py | 1,016 | python | en | code | 0 | github-code | 13 |
40927887543 | import pandas as pd
from lib.exp.summary import Summary
from lib.exp.evaluator.preproc_evaluator import PreprocEvaluator
from lib.exp.pre import Const
from lib.exp.pre import Reducer
from lib.exp.evaluator.accuracy import Accuracy
class _Exts(object):
def __init__(self):
pass
def __slide_count(self):... | speed-of-light/pyslider | lib/plotter/pre/exts.py | exts.py | py | 2,479 | python | en | code | 2 | github-code | 13 |
74287985616 | import math
def sumacomplex(c1,c2):
real=c1[0]+c2[0]
img=c1[1]+c2[1]
resultado=(real,img)
return resultado
def multcomplex(c1,c2):
real=((c1[0]*c2[0])-(c1[1]*c2[1]))
img=(c1[0]*c2[1])+(c1[1]*c2[0])
resultado=(real,img)
return resultado
def restacomplex(c1,c2):
real=... | Cristian5124/LibComplex | Libcomplex.py | Libcomplex.py | py | 1,916 | python | en | code | 1 | github-code | 13 |
7117420029 | """Adapted from clucker project"""
"""Post creation views."""
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, render
from django.views.generic.edit import CreateView
from django.urls import reverse
from bookclub.forms import UserPostForm
from bookclub.models import UserP... | EmmaSConteh/Ctrl_Intelligence | bookclub/views/user_post_views.py | user_post_views.py | py | 2,906 | python | en | code | 0 | github-code | 13 |
6709691245 | from django.shortcuts import render
from ticket.Zenpy import zenpy_client
from django.shortcuts import redirect
from user.forms import CreateTicket
from zenpy.lib.api_objects import Ticket, User,CustomField
from django.contrib import messages
# CREATE
def create_ticket(request):
form = CreateTicket(request.POST)
... | nikhilmp448/PeerXP-AcmeSupport | ticket/views.py | views.py | py | 1,775 | python | en | code | 0 | github-code | 13 |
39636259644 | #!/usr/bin/env python3
import os
import sys
import shutil
import argparse
import glob
def main():
args = parse_args()
copy_good_modules(args.module_names, args.cam_dir, args.dest_dir)
def parse_args():
description = """Given a directory path, and a list of module names,
copies each module into the d... | reticulatedpines/magiclantern_simplified | modules/copy_modules_with_satisfied_deps.py | copy_modules_with_satisfied_deps.py | py | 6,277 | python | en | code | 105 | github-code | 13 |
2401462663 | import pandas as pd
import os
from datetime import datetime
csv_data = os.path.join(os.getcwd(), '../bristol-air-quality-data.csv')
print(csv_data)
df = pd.read_csv(csv_data, sep = ';')
df = df.dropna(how='all')
'''
DATAFRAME TRANSFORMATION AND CLEANING
'''
def data_cleaning(df):
df['Date Time'] = pd.to_datetime(d... | nathphoenix/Air_analysis | question1/clean.py | clean.py | py | 1,864 | python | en | code | 0 | github-code | 13 |
39177668541 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np # linear algebra
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import confusion_matrix, roc_curve, roc_au... | ace825093791/worldcup | TheModel.py | TheModel.py | py | 17,594 | python | en | code | 0 | github-code | 13 |
25038912879 | import sys
# open 1-wire slaves list for reading
file = open('/sys/devices/w1_bus_master1/w1_master_slaves')
# read 1-wire slaves list
w1_slaves = file.readlines()
# close 1-wire slaves list
file.close()
# print header for results table
# repeat following steps with each 1-wire slave
for line in w1_slaves:
# ex... | unixweb/myweather | temperature.py | temperature.py | py | 864 | python | en | code | 10 | github-code | 13 |
11537030937 | #####Information section#########
## Name: Jiang Li
## Email: riverlee2008@gmail.com
###############################
import numpy as np
import matplotlib.pyplot as plt
## Ab array A with 12 elemetns beginning from number 5, containing consective odd numbers.
A = np.linspace(start = 5, stop = 27, num = 12,dtype=np.fl... | riverlee/Certificate-Program-in-Data-Science.old | CSX433.3/Midterm/a_Jiang_midterm.py | a_Jiang_midterm.py | py | 1,681 | python | en | code | 0 | github-code | 13 |
24632835939 | #!/usr/bin/env python3
# pip install netCDF4
# pip install numpy
# pip install json
# pip install matplotlib
from netCDF4 import Dataset
import numpy as np
from numpy import ma
import json
import calendar
import matplotlib.pyplot as plt
'''<==========SET_DEF_VAL==========>'''
lat = 15.46
long = 4... | artemk1337/ozon | ozon.py | ozon.py | py | 4,616 | python | en | code | 0 | github-code | 13 |
32212478340 | def solution(numbers):
num_list=numbers
answer = []
for index, value in enumerate(num_list):
for j in range(index+1,len(num_list)):
print("i",index,"J",j)
temp=value+num_list[j]
if not temp in answer:
answer.append(temp)
right=sorted(answer)
... | BlueScreenMaker/333_Algorithm | 백업/~220604/programmers/두개를뽑아더하기.py | 두개를뽑아더하기.py | py | 365 | python | en | code | 0 | github-code | 13 |
16840198967 | import cv2
import numpy as np
from functions import stack_images
img = cv2.imread('resources/lena.png')
kernel = np.ones((5,5),np.uint8)
#change image look
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #note: opencv uses BGR by default
imgBlur = cv2.GaussianBlur(imgGray,(7,7),0) # (7,7) is kernal size, ... | akshaysmin/opencv-practice | chapter2_pic_edits.py | chapter2_pic_edits.py | py | 2,003 | python | en | code | 0 | github-code | 13 |
39111335736 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
with open('README.rst') as f:
long_description = f.read()
setuptools.setup(
name='sportsref',
version='1.0.0',
description='Sports reference scraper',
long_description=long_description,
author='J. Scott Moreland',
author_emai... | morelandjs/sportsref | setup.py | setup.py | py | 446 | python | en | code | 1 | github-code | 13 |
22544362898 | r, g, b = map(int, input().split())
result = 0
for i in range(r):
for j in range(g):
for k in range(b):
print(i, j, k)
result += 1
print(result)
# print(r * g * b) result 선언 없이 이렇게 가능 | WeeYoungSeok/python_coding_study | codeup_100/problem_83.py | problem_83.py | py | 240 | python | en | code | 0 | github-code | 13 |
42648379172 | """A graph used for A* pathfinding"""
class Graph(object):
"""Class representing a Graph"""
inaccessible_nodes = []
width = -1
height = -1
def __init__(self):
return
def init(self, width, height):
"""Initializes the graph"""
self.width = width
self.height = hei... | dlsteuer/battlesnake | snake/Graph.py | Graph.py | py | 2,891 | python | en | code | 0 | github-code | 13 |
72338009939 | import os
import argparse
import random
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.metrics import mean_squared_error, mean_absolute_error
from model import ConvLSTMModel
from update_build_dataloader import get_dataloader
def return_perf(y_true, y_pred):
mse = mean_squ... | lepoeme20/daewoo | convlstm/update.py | update.py | py | 8,668 | python | en | code | 0 | github-code | 13 |
21571728736 | import params
from google.cloud import datastore, storage, logging
import time
import pickle
import hashlib
import sys
import numpy as np
import portfolioGeneration
import portfolio
import dataAck
import warnings
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
import multiprocessing as mp
... | SignalBuilders/walkforwardTrader | autoPortfolio.py | autoPortfolio.py | py | 7,694 | python | en | code | 1 | github-code | 13 |
27194590006 | # Url Shortner
import streamlit as st
import pyshorteners
import clipboard
def shorten_url(url):
shortener = pyshorteners.Shortener()
short_url = shortener.tinyurl.short(url)
return short_url
# Streamlit app
st.title("URL Shortener")
url_to_shorten = st.text_input("Enter the URL to shorten")... | akashbagwan2308/Sync_Intern_Python | Task_3_URL_Shortner.py | Task_3_URL_Shortner.py | py | 705 | python | en | code | 0 | github-code | 13 |
72436265937 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 15:56:48 2020
@author: cartervandemoore
"""
#create an initial version of a TextModel class,
#which will serve as a blueprint for objects that model a body of text
import math
#returns a list of words after 'cleaning' out a string txt
def clean... | cvmoore/authorFinder | TextMatching2.py | TextMatching2.py | py | 10,075 | python | en | code | 0 | github-code | 13 |
37630967052 | #! /usr/bin/env python3
import rospy
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
from geometry_msgs.msg import Point
import numpy as np
class Traffic_Light_Marker_Array:
def __init__(self, stopline=None):
self.mark_array = MarkerArray()
self.lights... | wasn-lab/Taillight_Recognition_with_VGG16-WaveNet | src/utilities/rviz_traffic_light/src/Traffic_light.py | Traffic_light.py | py | 12,637 | python | en | code | 2 | github-code | 13 |
29382549925 | #!/usr/bin/env python
import sys
import logging
import scapy.all as scapy
logging.getLogger('scapy.runtime').setLevel(logging.ERROR)
def broadcast_flood(interface, bssid):
packet = scapy.Dot11(
addr1='ff:ff:ff:ff:ff:ff',
addr2=bssid,
addr3=bssid
) / scapy.Dot11Deauth()
scapy.sen... | vodkabears/wifideath | wifideath.py | wifideath.py | py | 605 | python | en | code | 4 | github-code | 13 |
5264297756 | import torch
from torch import nn
import matplotlib.pyplot as plt
import requests
from pathlib import Path
from sklearn.datasets import make_circles
from sklearn.model_selection import train_test_split
import pandas as pd
# number of samples
n = 1000
#create circles
X, y = make_circles(n,
noise=0.... | puklu/Deep-Learning-PyTorch- | Practice/01_Binary_Classification/main.py | main.py | py | 6,970 | python | en | code | 0 | github-code | 13 |
9844827255 | # -*- coding: utf-8 -*-
import pytest
from raiden.mtree import merkleroot, check_proof, get_proof, NoHash32Error
from raiden.utils import keccak
def test_empty():
assert merkleroot([]) == ''
assert merkleroot(['']) == ''
def test_multiple_empty():
assert merkleroot(['', '']) == ''
def test_non_hash()... | utzig/raiden | raiden/tests/unit/test_mtree.py | test_mtree.py | py | 4,055 | python | en | code | null | github-code | 13 |
24415142310 | from unittest import TestCase
from walkoff.messaging import WorkflowAuthorization
class TestWorkflowAuthorization(TestCase):
def test_is_authorized(self):
users = [1, 2, 3]
roles = [3, 4]
auth = WorkflowAuthorization(users, roles)
for user in users:
self.assertTrue(aut... | xa7YvcR3/WALKOFF | tests/test_workflow_authorization.py | test_workflow_authorization.py | py | 1,515 | python | en | code | null | github-code | 13 |
29045224023 | import numpy as np
import os
from typing import List
import tensorflow.keras.models as models
from model import State
from agents import Agent
ThreeDimArr = List[List[List[int]]]
Board = List[List[int]]
# Agent that uses a neural network to (attempt to) compute the optimal move
class NeuralNetworkAgent(Agent):
... | chromium-52/reversi-ai | src/deepLearningAgents.py | deepLearningAgents.py | py | 1,761 | python | en | code | 0 | github-code | 13 |
3079789295 | # Import libraries
import re
import pandas as pd
from keras import Sequential
from keras.callbacks import TensorBoard
from keras.constraints import maxnorm
from keras.layers import Embedding, Conv1D, Dropout, MaxPooling1D, Flatten, Dense
from keras.optimizers import SGD
from keras.utils import to_categorical
f... | adtmv7/CS5590-490-Python-Deep-Learning | LAB2/Source/4_text_cnn.py | 4_text_cnn.py | py | 5,299 | python | en | code | 2 | github-code | 13 |
21552877216 | '''
accountTab class UI tab Accounting
statisticTab class UI tab Statistics
settingTab class UI tab Settings
mainTab class UI tab with all tabs
'''
import PySimpleGUI as sg
from logic import *
class accountTab(takeData):
def __init__(self):
super().__init__()
def accountLayout(self):
#self.r... | sikexe/expense-tracker-GUI | Lib/classes/widget.py | widget.py | py | 2,843 | python | en | code | 0 | github-code | 13 |
42323715010 | import pyqrcode
import PySimpleGUI as sg
import random
def Text():
layout2 = [ [sg.Text('Enter text in QR code')],
[sg.Input()],
[sg.OK()]]
window = sg.Window("text based qr").Layout(layout2)
while True:
event, values = window.read()
if event in (Non... | akionsight/QR-Code-Creator | QR_Code_Generator.py | QR_Code_Generator.py | py | 2,372 | python | en | code | 1 | github-code | 13 |
1694431033 | # task 1: visualize a satellite image and shapefile using python
# task 2: descriptive analysis and acreage calculation
# import required libraries
from osgeo import gdal
from osgeo import ogr
import numpy as np
import math
from scipy.stats import mode
import os
import matplotlib.pyplot as plt
img =... | jaypadariya/jay_class | crop1 jay.py | crop1 jay.py | py | 886 | python | en | code | 0 | github-code | 13 |
9525042555 | from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QIntValidator
from PyQt5.QtWidgets import QWidget
class SliderWidget(QWidget):
def __init__(self, parent, title):
super(QWidget, self).__init__(parent)
self.slider = QWidget()
self.slider.layout = QtWidg... | BaileyDalton007/Epidemic-Simulator | widgetTempletes.py | widgetTempletes.py | py | 2,066 | python | en | code | 1 | github-code | 13 |
13309757071 | from django.conf.urls import patterns, url
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from expenses.views import *
urlpatterns = patterns('',
url(r'^groups/$', GroupList.as_view(), name='group_list'),
url(r'^groups/add/$', GroupCreate.as_view(), name='group_creat... | nicbou/billsplitter | expenses/urls.py | urls.py | py | 1,343 | python | en | code | 4 | github-code | 13 |
28000944504 | from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
import re
from time import sleep
from dotenv import load_dotenv
import logging
import json
from settings.countries import alpha
load_dotenv()
logging.basicConfig(filename='footstats.log', filemode='a', level=logging.ERROR, format='%(asctime... | abnerrios/fbstats | fbcollect/squads.py | squads.py | py | 8,160 | python | en | code | 0 | github-code | 13 |
8094040564 | from django.conf.urls import include, url
from django.contrib.auth.decorators import login_required
from apps.mascota.views import (index,mascota_view,mascota_list,
mascota_edit,mascota_delete,MascotaList,MascotaCreate,MascotaUpdate,MascotaDelete,
listado)
urlpatterns = [
# Examples:
# url(r'^$', 'refugio.view... | josuesf/pythonexamplodjango | apps/mascota/urls.py | urls.py | py | 840 | python | en | code | 0 | github-code | 13 |
17521395927 | # Load packages
import openai
import os
from langchain.chat_models import ChatOpenAI
from langchain.schema import SystemMessage, HumanMessage
from dotenv import load_dotenv
# Declare functions
def SendPromptToChatGPT(user_prompt,
system_message="You are a helpful assistant.",
... | KyleProtho/AnalysisToolBox | Python/TextSummarizationAndGeneration/SendPromptToChatGPT.py | SendPromptToChatGPT.py | py | 2,260 | python | en | code | 0 | github-code | 13 |
71756412817 | """docup_core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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')
Class-ba... | arezoo88/docup_project | neuronio/urls.py | urls.py | py | 1,935 | python | en | code | 0 | github-code | 13 |
4886355545 | #!/usr/bin/env python3
# coding: utf-8
from winrm import Protocol
from winrm import Response
from base64 import b64encode
from datetime import datetime
from datetime import timedelta
import subprocess
import json
import os.path
import time
import platform
import re
vms = None
server = None
config = None
vms_cache_fil... | reinaldorossetti/hypy | hypy/hvclient.py | hvclient.py | py | 11,685 | python | en | code | null | github-code | 13 |
22437120755 | #!/usr/bin/python
import bz2
import argparse
import os
import re
import statistics as st
import numpy as np
import json
EXPECTED_END_OF_SIMULATION = "Correct End of Simulation"
class PowerData(object):
def __init__(self, leakage, internal, switching, cycles, valid):
self.leakage = leakage
self.in... | AlissonLinhares/riscv-power-tables | gen-power-table.py | gen-power-table.py | py | 5,980 | python | en | code | 0 | github-code | 13 |
21586187671 | """
Space Replacement
-----------------
Write a method to replace all spaces in a string with %20. The string
is given in a characters array, you can assume it has enough space for
replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
... | corenel/lintcode | algorithms/212_space_replacement.py | 212_space_replacement.py | py | 2,777 | python | en | code | 1 | github-code | 13 |
13140031331 | import json
from tradingkit.data.feed.websocket_feeder import WebsocketFeeder
from tradingkit.pubsub.event.book import Book
from tradingkit.pubsub.event.trade import Trade
class PublicKrakenFeeder(WebsocketFeeder):
# Converts symbols from normal to kraken vocab
denormalized_symbol = {
"BTC/EUR": "XBT... | logictraders/tradingkit | src/tradingkit/data/feed/public_kraken_feeder.py | public_kraken_feeder.py | py | 4,159 | python | en | code | 3 | github-code | 13 |
30569706292 | import discord
from discord.ui import Button, View
from discord import InteractionType
import os
import random
import copy
import asyncio
import random
import pytz
from datetime import datetime
import json
import pickle
from keep_alive import keep_alive
import csv
keep_alive()
timer_running = False
counter = 0
sales_c... | Hydraknight/AuctioneerDiscordBot | auction.py | auction.py | py | 62,558 | python | en | code | 0 | github-code | 13 |
13432993855 | import os
import pygame as pg
from utils.colors import *
class Piece:
def __init__(self):
self.is_white = True
self.x, self.y = 0,0
self.board_pos = (0,0)
self.board_x, self.board_y = self.board_pos
self.pos = (self.x, self.y)
self.texture = None
self.rect = pg.Rect(self.pos, (64,64))
sel... | Thinato/pygame-Chess | piece.py | piece.py | py | 2,825 | python | en | code | 0 | github-code | 13 |
31009696143 | import turtle
turtle.screensize(canvwidth=2000, canvheight=2000,
bg="black")
i = turtle.Turtle()
i.penup()
i.speed(5)
i.backward(600)
i.left(90)
i.forward(100)
i.right(90)
i.pendown()
i.pencolor("white")
i.hideturtle()
i.left(180)
i.penup()
i.hideturtle()
i.circle(-30,90)
i.pendown()
i.showturtle... | dmahesh9810/python-Turtle | iqBrave.py | iqBrave.py | py | 3,501 | python | en | code | 0 | github-code | 13 |
28517672074 | import os
import sys
import pickle
import argparse
import torch
from torchvision import transforms, utils
sys.path.append('skip-thoughts.torch/pytorch')
from constants import *
from data_pipeline import *
from model import *
from skipthoughts import *
from train import Trainer
from pytorch_pretrained_bert.modeling i... | lin-david/text2image | interpolate.py | interpolate.py | py | 3,269 | python | en | code | 0 | github-code | 13 |
73117872977 | class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {'}': '{', ')': '(', ']': '['}
for ch in s:
if ch in ['(', '{', '[']:
stack.append(ch)
else:
if not stack:
return False
elif not... | abaksy/leetcode-sol | 020/validParentheses.py | validParentheses.py | py | 466 | python | en | code | 1 | github-code | 13 |
14645360815 | from sqlalchemy import Column, Identity, Integer, Table, list
from . import metadata
BalanceDetailJson = Table(
"balance_detailjson",
metadata,
Column("available", list, comment="Funds that are available for use"),
Column("id", Integer, primary_key=True, server_default=Identity()),
)
__all__ = ["balan... | offscale/stripe-sql | stripe_openapi/balance_detail.py | balance_detail.py | py | 337 | python | en | code | 1 | github-code | 13 |
4965118748 | # coding: utf-8
# In[1]:
import pandas as pd
from pandas_highcharts.display import display_charts
import os
class financeMain:
pairList={}
currencyList=[]
def __init__(self):
self.OpenAllFile(r'C:\\Users\\simnk\\workspace\\finance\\HISTDATA2015', 'H')
#全ファイルを開いてデータを展開
@class... | KaiShimanaka/finance | financeMain.py | financeMain.py | py | 3,597 | python | en | code | 2 | github-code | 13 |
29278167162 | import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from keras.layers import Dropout
from keras.models import Sequential
from ... | MerlinEgalite/mail-classification | neural_network.py | neural_network.py | py | 2,402 | python | en | code | 0 | github-code | 13 |
22846164843 | # Get lyrics delivered to your CLI
import requests
from bs4 import BeautifulSoup
def lyrics_find(Artist, Song):
# Base URL to build on
URL = 'https://www.azlyrics.com/lyrics/'
# Modify Artist Name and Song Title to URL Format
Artist = Artist.lower().replace(" ","")
Song = Song.lower().replace(" "... | roopeshvs/LyricsPy | lyrics.py | lyrics.py | py | 1,533 | python | en | code | 0 | github-code | 13 |
36697692882 | from typing import Any, Callable, List, Optional, Tuple, Union
from typing_extensions import get_args
import jax
import jax.numpy as jnp
from .custom_types import Array, MoreArrays, PyTree, TreeDef
from .deprecated import deprecated
#
# Filter functions
#
_array_types = get_args(Array)
_morearray_types = get_args(... | codeaudit/equinox | equinox/filters.py | filters.py | py | 4,344 | python | en | code | null | github-code | 13 |
37127807934 | #For loop with string.
# name= input("Enter your name. ")
# for ch in name:
# print(ch)
#For loop with list.
phone_no_list=[9847620206,9845007122,9826835932,9860181886,9844375899,9867773888]
for ph_no in phone_no_list:
print(ph_no)
#For loop with list of string
name_list=["Nirajan",'Saurav']
for name in name_... | NirajanJoshi5059/python | for_loop.py | for_loop.py | py | 762 | python | en | code | 0 | github-code | 13 |
160299826 | """Implements the A2C Agent"""
# pylint: disable=E1129
import time
import tensorflow as tf
import numpy as np
from base_agent import BaseAgent
from layers import agent_network, fully_connected
from env_recorder import EnvRecorder
class A2CAgent(BaseAgent):
"""An Actor-Critic Advantage Network Agent"""
de... | codekitchen/udacity_machine_learning | capstone_project/a2c_agent.py | a2c_agent.py | py | 10,458 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.