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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
23965078219 | from tkinter.messagebox import YES
print("Welcome to my computer quiz challenge ")
playing = input("Do you want to play? ")
score = 0
if playing.lower() == "yes":
print("Okay let's play ")
else:
quit()
answer = input("When was the first computer invented? ")
if answer.lower() == "1943":
... | PriyenJoshi/Python-Practice-Programs | Python Programs/quiz_game.py | quiz_game.py | py | 1,162 | python | en | code | 0 | github-code | 13 |
74559992656 | from discord.ext import commands
from discord_components import Button, ButtonStyle
from database.Players import players_info
class Location(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='home')
async def home_location(self, ctx):
player = players_info(ctx.au... | GreenDevth/Discord_server_store | cogs/Location.py | Location.py | py | 491 | python | en | code | 0 | github-code | 13 |
15478580145 | #Data Visualization
import pandas as pd
import matplotlib.pyplot as plt
data=pd.read_csv('C:/Users/SPTINT-09/Desktop/tips (1).csv')
plt.scatter(data['day'],data['tip'])
plt.show()
plt.plot(data['tip'])
plt.plot(data['size'])
plt.show()
plt.bar(data['day'],data['tip'])
plt.show()
plt.hist(data['total_bill'])
plt.show()
| dhanushree1702/AIML | prg13.py | prg13.py | py | 320 | python | en | code | 0 | github-code | 13 |
37646442621 |
from Node import Node
class Queue():
def __init__(self) -> None:
self.first = None
self.last = None
self.length = 0
def peek(self):
return self.first
def enqueue(self, value):
new_node = Node(value)
if self.length == 0:
self.first = ... | aaxlss/python-some-datastructures-algoritms | Queue.py | Queue.py | py | 818 | python | en | code | 0 | github-code | 13 |
17493287925 | from opentelemetry import trace
import pyarrow.flight as flight
from opentelemetry.propagate import inject
from opentelemetry.trace import set_span_in_context
class ClientTracingMiddlewareFactory(flight.ClientMiddlewareFactory):
def __init__(self):
super().__init__()
self._tracer = trace.get_trace... | amoeba/arrow-flight-playground | test_flight_stress/client_python/tracing_middleware.py | tracing_middleware.py | py | 910 | python | en | code | 1 | github-code | 13 |
41949654368 | import random
import string
import requests
from bs4 import BeautifulSoup
import colorama
from os import getcwd
def randstr():
letters = string.ascii_lowercase+string.ascii_uppercase+string.digits
result_str = ''.join(random.choice(letters) for i in range(3))
return result_str
def main(tlets,sav... | blueshillz/dosyaupload-scraper | main.py | main.py | py | 1,489 | python | en | code | 0 | github-code | 13 |
8076372640 | from PyQt5 import QtWidgets , uic , QtGui
def somme():
a=u.ImpX.text()
b=u.ImpY.text()
if a.isnumeric() and (len(a)>0) and b.isnumeric() and (len(b)>0):
u.res.setText(str(int(a)+int(b)))
else :
u.res.setText("ERROR")
def fois():
a=u.ImpX.text()
b=u.ImpY.te... | HamoudaBenAbdennebi/calc | calc.py | calc.py | py | 1,594 | python | en | code | 0 | github-code | 13 |
27165930935 | '''
Platform specific file for Raspberry Pi devices. This system does NOT use extlinux for boot so
dynamic overlays are not needed or supported. GPIO's are provided as a simple GPIO # (i.e. 14, 21).
This configuration should also apply to other Raspberry Pi family devices and may be updated in
the future to include o... | LearningToPi/sbc_gpio | src/sbc_gpio/platforms/rpi.py | rpi.py | py | 2,647 | python | en | code | 0 | github-code | 13 |
38340454556 | from math import sqrt, pi, cos, sin
import draw
def canon(Xc, Yc, Ra, Rb, scene, pen, drawFlag=True):
"""
Отрисовка эллипса по
каноническому уравнению
"""
sqrA = Ra * Ra
sqrB = Rb * Rb
xRange = (int(round(sqrA / sqrt(sqrA + sqrB)))
if sqrA or sqrB else 0)
sqrtC... | MyMiDiII/bmstu-cg | lab_04/ellipse.py | ellipse.py | py | 3,918 | python | en | code | 0 | github-code | 13 |
25553832762 | import numpy as np
import random
import logging
import math
import gym
from gym import spaces
logger = logging.getLogger(__name__)
STATE_DESK = 0
STATE_BODY = 1
STATE_HEAD = 2
STATE_FOOD = 3
ACTIONS = [[-1, 0], [1, 0], [0, -1], [0, 1]] # 上/下/左/右
DIR_UP = 0
DIR_DOWN = 1
DIR_LEFT = 2
DIR_RIGHT = 3
class Snake(obje... | zjl-utopia/gym-custom | gym_custom/envs/snake.py | snake.py | py | 6,126 | python | en | code | 0 | github-code | 13 |
32839625135 | import tweetws
class UserProfile:
def __init__(self, username, tweets:list[tweetws.Tweetws], sntmntTweets, avglen, positivity, topics):
self.username = username
self.tweets = tweets
self.sntmntTweets = sntmntTweets
self.avglen = avglen
self.positivity = positivity
se... | MysticMatt/CSE-5914-Automated-Twitter-Matchmaker | userProfile.py | userProfile.py | py | 339 | python | en | code | 0 | github-code | 13 |
5906785614 | from unittest import TestCase
from salesdataanalyzer.helpers import Salesman
from salesdataanalyzer.parser import parse_salesman,\
WrongNumberOfFieldsError, InvalidCpfPatternError, InvalidSalaryPatternError
class ParseSalesmanTest(TestCase):
def test_parse_salesman(self):
salesman = parse_salesman('0... | dmertins/sales-data-analyzer | tests/unit/parse_salesman_test.py | parse_salesman_test.py | py | 2,313 | python | en | code | 0 | github-code | 13 |
14232507587 | import mock
import pytest
from rest_framework import exceptions
from backend.api.authorization.constants import OperateEnum
from backend.api.authorization.mixins import AllowItem, AuthorizationAPIAllowListCheckMixin, AuthViewMixin
from backend.apps.role.models import Role
from backend.biz.policy import PolicyBean, Pol... | TencentBlueKing/bk-iam-saas | saas/tests/api/authorization/mixins_tests.py | mixins_tests.py | py | 4,942 | python | en | code | 24 | github-code | 13 |
74370820498 | import numpy as np
def project_depth_to_points(
intrinsics: np.array,
depth: np.array,
instance_mask: np.array = None) -> [np.array, tuple]:
r"""Projection of depth map to points.
Input:
intrinsics: camera intrinsics, [3, 3]
depth: depth map, [H, W]
... | Gorilla-Lab-SCUT/gorilla-3d | gorilla3d/utils/project.py | project.py | py | 1,559 | python | en | code | 7 | github-code | 13 |
28247248876 | import csv
from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from data_handler.models import DataHandler, DataExporter, Charter, Mapper
def index(request):
return render(request, 'frontend/index.html', context={'current_site': 'index'})
def updates(reque... | avjves/HistSE | frontend/views.py | views.py | py | 3,902 | python | en | code | 0 | github-code | 13 |
39655883300 | from alive_progress import alive_bar
message = ""
def wpmToDps(wpm):
''' Words per minute = number of times PARIS can be sent per minute.
PARIS takes 50 dot lengths to send. Returns dots per seconds. '''
return wpm*50/60.0
def farnsworthScaleFactor(wpm, fs=None):
''' Returns the multiple that character... | SpaceNerden/TextToMorse | TextToMorse.py | TextToMorse.py | py | 6,006 | python | en | code | 0 | github-code | 13 |
1583264198 | """ Prepare Data to be uploaded to MySQL tables """
import pandas as pd
import pathlib
def prepare_customer_data(sales_df: pd.DataFrame, target_data_dir: pathlib.Path):
columns = [
"customer_name",
"customer_age",
"customer_segment",
"city",
"zip_code",
"state",
... | m-p-esser/mysql-walmart-data-model | src/process_data.py | process_data.py | py | 2,935 | python | en | code | 0 | github-code | 13 |
15918381694 | """empty message
Revision ID: ee6b7b2e6a16
Revises: 28f62b6e1f24
Create Date: 2016-03-01 11:46:58.147000
"""
# revision identifiers, used by Alembic.
revision = 'ee6b7b2e6a16'
down_revision = '28f62b6e1f24'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import ENUM
# enum type
... | joonaojapalo/trackem | migrations/versions/ee6b7b2e6a16_.py | ee6b7b2e6a16_.py | py | 863 | python | en | code | 0 | github-code | 13 |
71915692179 | import scrapy
import io
import json
from PyPDF2 import PdfReader
from flask import Flask,jsonify
from nltk.sentiment import SentimentIntensityAnalyzer
app = Flask(__name__)
class PdfCrawler(scrapy.Spider):
name = 'pdf_crawler'
start_urls = [
'https://iwgdfguidelines.org/wp-content/upload... | dashp21/Crawler-Flask | CrawlerFlask.py | CrawlerFlask.py | py | 3,791 | python | en | code | 0 | github-code | 13 |
36639567358 | from __future__ import division, print_function, unicode_literals
import sys
import codecs
import nscr
class LineReader(object):
# Nscripter uses commands like "goto" and "skip".
# Thus, we can't really make the script into trees.
# So we use a procedural approach.
START_LABEL = b"*define"
... | uvthenfuv/npynscr | onscr_parse.py | onscr_parse.py | py | 4,969 | python | en | code | 2 | github-code | 13 |
37153941194 | import sys
sys.path.insert(0,'./Modules/')
import numpy as np
from file_reader import read_file
import pandas as pd
from rdkit import Chem
from mol_utils import get_fragments
import numpy as np
import time
import sys
import matplotlib.pyplot as plt
import pickle
import argparse
import xgboost as xgb
import Show_Epoch
i... | mew-two-github/de-Novo-drug-Design | 3.6/viewing_outputs.py | viewing_outputs.py | py | 9,246 | python | en | code | 1 | github-code | 13 |
22396644132 | import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import chainconsumer
from math import ceil
# pyburst
from . import mcmc_versions
from . import mcmc_tools
from . import burstfit
from . import mcmc_params
from pyburst.observations import obs_tools
from pyburst.plotting import plot_tools
from pybu... | zacjohnston/pyburst | pyburst/mcmc/mcmc_plot.py | mcmc_plot.py | py | 23,197 | python | en | code | 3 | github-code | 13 |
41188096434 | import turtle
bob=turtle.Turtle()
bob.speed(0)
bob.shape('turtle')
bob.left(180)
bob.penup()
bob.forward(100)
bob.right(180)
bob.pendown()
def star():
bob.color('cyan')
for i in range(5):
bob.forward(10)
bob.right(144)
def stars():
bob.color('light blue')
for ... | Pankuu21/PyFun | python star turtle design.py | python star turtle design.py | py | 635 | python | en | code | 0 | github-code | 13 |
41881731950 | from lib.logging_config import logger
def find_occurrences(s, ch):
"""
Source:
https://stackoverflow.com/questions/13009675/find-all-the-occurrences-of-a-character-in-a-string
"""
return [i for i, letter in enumerate(s) if letter == ch]
def get_day_time_of_class(url: str) -> str:
# get the s... | DarkestAbed/dufur | backend/app/parse_dates.py | parse_dates.py | py | 1,518 | python | en | code | 0 | github-code | 13 |
42702873281 | import os
arquivo = open(os.path.join("C:/Users/Samsung Max/Desktop/Data Science Academy/Python/Arquivos/ManipulandoTexto.txt"),"w")
texto = "Manipulando arquivo de texto no python"
for palavra in texto.split():
arquivo.write(f"{palavra} ")
arquivo.close()
arquivo = open("C:/Users/Samsung Max/... | luizsouza1993/Data_Science_Python | Manipulando Textos.py | Manipulando Textos.py | py | 1,052 | python | pt | code | 0 | github-code | 13 |
1447911471 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Zhoutao
#create_date:2017-01-12-16:59
# Python 3.5
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Zhoutao
#create_date:2017-01-09-10:28
# Python 3.5
import logging
import logging,time,sys,os,time
sys.path.append(os.path.dirname(os.path.dirname(os.path.a... | 248808194/python | M2/ATM/core/logger.py | logger.py | py | 1,704 | python | en | code | 0 | github-code | 13 |
41243281784 | def number_of_customers_per_state(customers_dict):
final_dict = {}
count = 0
for k1, v1 in customers_dict.items():
for i in v1:
for k2, v2 in i.items():
if type(v2) == int:
if v2 > count:
count = v2
print (k2)
pri... | gsakkas/seq2parse | src/tests/parsing_test_29.py | parsing_test_29.py | py | 827 | python | en | code | 8 | github-code | 13 |
16566211698 | import hashlib
def encode_md5(temp: str) -> str:
md5 = hashlib.md5()
md5.update(temp.encode(encoding='utf-8'))
return md5.hexdigest()
def file_md5(file_path) -> str:
with open(file_path, 'rb') as f:
md5_obj = hashlib.md5()
while True:
d = f.read(8096)
if not ... | 14Days/back_web | app/utils/md5.py | md5.py | py | 453 | python | en | code | 0 | github-code | 13 |
30687027954 |
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import SimpleRouter
from core.views import (ProdutoAPIView, ProdutosAPIView, PedidoAPIView, PedidosAPIView,EnderecoAPIView,EnderecosAPIView,
EmpresasAPIView, EmpresaAPIView,ClientesAPIView, Clien... | Samuelssj/pede_comer | backend_pede_comer/core/urls.py | urls.py | py | 1,748 | python | pt | code | 1 | github-code | 13 |
34672445786 | #融合Gdelt和航空网络数据
import pandas as pd
header_names=['GlobalEventID', 'Day', 'MonthYear', 'Year', 'FractionDate',
'Actor1Code', 'Actor1Name', 'Actor1CountryCode', 'Actor1KnownGroupCode',
'Actor1EthnicCode', 'Actor1Religion1Code', 'Actor1Religion2Code',
'Actor1Type1Code', 'Actor1Type2Code', 'Actor1Type... | hinczhang/Graduate-Thesis | batchHandle.py | batchHandle.py | py | 4,537 | python | en | code | 0 | github-code | 13 |
19241863240 | from fvcore.common.registry import Registry
# from .backbone import Backbone
CLS_HEAD_REGISTRY = Registry("CLS_HEAD")
CLS_HEAD_REGISTRY.__doc__ = """
Registry for LOCALIZATION HEAD, which output target localization based on consecutive images
The registered object must be a callable that accepts two arguments:
1. A... | Flowerfan/Trackron | trackron/models/cls_heads/build.py | build.py | py | 887 | python | en | code | 46 | github-code | 13 |
34487583696 | import csv
def save_to_file(jobs):
file = open("jobs.csv", mode="w", encoding="UTF-8", newline='')
# 윈도우즈의 경우 csv 모듈에서 데이타를 쓸 때 각 라인 뒤에 빈 라인이 추가되는 문제가 있는데, 이를 없애기 위해 (파이썬 3 에서) 파일을 open 할 때 newline='' 와 같은 옵션을 지정한다
# http://pythonstudy.xyz/python/article/207-CSV-%ED%8C%8C%EC%9D%BC-%EC%82%AC%EC%9A%A9%ED%95%... | purple402/webscrapper | lecture/save.py | save.py | py | 629 | python | ko | code | 0 | github-code | 13 |
36590749345 | from mysqlconnection import connectToMySQL
from flask import flash
class Survey:
def __init__(self, data):
self.id = data['id']
self.name = data['name']
self.location = data['location']
self.language = data['language']
self.comments = data['comments']
self.created_at... | CSHepworth/Python-v21.1 | Python/flask_mysql/validation/dojo_survey_validation/survey.py | survey.py | py | 1,501 | python | en | code | 0 | github-code | 13 |
15832960846 | import torch
import torch.nn as nn
import torch.optim as optim
class PPO():
def __init__(self,
actor_critic,
value_loss_coef = 0.5,
entropy_coef = 0.01,
num_mini_batch = 32,
clip_param = 0.2,
symmetry_coef=0,
... | aayushwadhwa/av-simulation | ppo.py | ppo.py | py | 3,654 | python | en | code | 0 | github-code | 13 |
74316503377 | import numpy as np
import matplotlib.pyplot as plt
def I(delta_k):
return (np.sin( 2 * delta_k))**2 / ( 2 *delta_k )**2
Dk = np.linspace(-2*np.pi, 2*np.pi, 1e5)
plt.figure(figsize=(16, 9))
plt.plot(Dk, I(Dk), linewidth=4)
plt.ylabel(r'$\Gamma \, / \, \mathrm{a.u.} $', fontsize=20)
plt.xlabel(r'$\Delta k \, /... | beckstev/presentations | nonlinear_optics/presentation_elements/phase_matching/efficiency_plot/I_plot.py | I_plot.py | py | 469 | python | en | code | 0 | github-code | 13 |
36941557518 | """This script downloads all the csv files from a s3 bucket, updates the content, then write to another local directory
as the same filename."""
import boto3
import csv
import os
from tempfile import NamedTemporaryFile
s3_client = boto3.client('s3', 'us-east-1')
s3_resource = boto3.resource('s3', 'us-east-1')
BUCKET... | amandazhuyilan/Breakfast-Burrito | CheatSheet/download_and_update_cvs_inline.py | download_and_update_cvs_inline.py | py | 2,211 | python | en | code | 3 | github-code | 13 |
29162771731 | import dataclasses
import typing
from collections.abc import Callable, Iterable
from algokit_utils import ApplicationSpecification, CallConfig, MethodConfigDict, MethodHints, OnCompleteActionName
from algosdk.abi import Method
from algokit_client_generator import utils
@dataclasses.dataclass(kw_only=True)
class Con... | algorandfoundation/algokit-client-generator-py | src/algokit_client_generator/spec.py | spec.py | py | 7,466 | python | en | code | 2 | github-code | 13 |
26542418440 | import math
import serial
import serial.tools.list_ports
import time
upper_arm_length = 220 #mm
lower_arm_length = 160 #mm
basis_height = 253 #mm
hand_length = 65 #mm #65 + 142
hand_radial_offset = 0 #mm
hand_radial_offset_rot=0 #deg
base_encoder_0 = 9600
base_encoder_steps = 57600
upper_arm_encoder_0 = 2200
upp... | redoxcode/movemaster2-demo | MoveMasterLib.py | MoveMasterLib.py | py | 7,914 | python | en | code | 0 | github-code | 13 |
8305286364 | def recur(cur, s):
if cur == n:
res.add(" ".join(list(map(str, li)))) #int 를 str로 변환해서 배열로 담기
return
if len(li) > m:
return
for i in range(s, len(arr)):
if not v[i]:
li[cur] = arr[i]
v[i] = True
recur(cur + 1, i)
... | lion1735/Algorithm | Main_15664.py | Main_15664.py | py | 830 | python | ko | code | 0 | github-code | 13 |
17385515764 | import sys
import time
import paho.mqtt.client as mqtt
import json
import random
NETPIE_HOST = "broker.netpie.io"
CLIENT_ID = "4d046c4d-37c7-4978-953a-c851d596fad5" # Client ID ของ Device ที่สร้างขึ้นใน NETPIE
DEVICE_TOKEN = "M7ptbnbqoBZWgLzm72Jcb4gfJ2N6ahGd"# Token ของ Device ที่สร้างขึ้นใน NETPIE
sensor_da... | NesJaaTH/python | lab6/LAB6_6_129.py | LAB6_6_129.py | py | 3,009 | python | en | code | 0 | github-code | 13 |
33792993224 |
def getBMI (x,y):
return x/y
def display_category(x):
if x < 16.5:
return first_condition
elif x <= 18.4:
return second_condition
elif x <= 24.9:
return third_condition
elif x <= 30:
return fourth_condition
elif x <= 34.9:
return fifth_condition
eli... | sheenabasiga/ITE-260 | BMI.py | BMI.py | py | 1,020 | python | en | code | 0 | github-code | 13 |
11236697625 | import pickle
import pandas as pd
from utils import get_config
prot_table = pd.read_csv(snakemake.input.prot_table, sep="\t")
prot_data = pd.read_pickle(snakemake.input.prot_data)
prot_y = prot_table.set_index("Target_ID")["Y"].to_dict()
dims_config = get_config(prot_data, "prot")
dims_config["num_classes"] = len(pr... | ilsenatorov/rindti | workflow/scripts/pretrain_prot_data.py | pretrain_prot_data.py | py | 828 | python | en | code | 8 | github-code | 13 |
14343989441 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="learning-map",
version="0.0.1",
author="Jeremy Miller",
author_email="jeremymiller00@gmail.com",
description="An application for viewing and interacting with my Data Scie... | jeremymiller00/learning-map | setup.py | setup.py | py | 874 | python | en | code | 0 | github-code | 13 |
71003327058 | from tkinter import *
class MortgageCalculator(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.label = Label(self, text = "Principle: ")
self.label.grid(row = 0, column = 0, st... | Taylor365/Python | MortCalculator/mortgageCalculator.py | mortgageCalculator.py | py | 2,344 | python | en | code | 0 | github-code | 13 |
667152311 | from ecpy.curves import Curve,Point
from Crypto.Hash import SHA3_256, SHA256
import Crypto.Random.random # a bit better secure random number generation
import client_basics as cb
import client_basics_Phase2 as cb2
import client_basics_Phase3 as cb3
from Crypto.Hash import HMAC
from Crypto.Cipher import AES
#3.1 Down... | kaanatmacaa/cryptography_project | client_final_phase.py | client_final_phase.py | py | 16,719 | python | en | code | 0 | github-code | 13 |
71354454099 | import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import time
from itertools import count
import sys
import pandas as pd
from sklearn import preprocessing
import numpy as np
from scipy.signal import find_peaks
import os
import json
import seaborn
imp... | andmathisen/multimodal_emotion_recognition | misc/plot_phy.py | plot_phy.py | py | 8,851 | python | en | code | 1 | github-code | 13 |
14441023035 | from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.db.models import Q
from .models import User, Person,Lecture, Forum, Reply
from .forms import ForumForm, ReplyForm
def home(request):
person = Person.objects.filter(user=request.user)
context = {"person": perso... | jovanaivanovska11/LearningProjectDjango | ProjectLearning/views.py | views.py | py | 2,798 | python | en | code | 0 | github-code | 13 |
35403455976 | import os
import asyncio
import json
import uuid
import logging
import importlib
s3_client = importlib.import_module("liveness-tests-s3-client.s3-client.s3_client")
comm_client = importlib.import_module("liveness-tests-s3-client.s3-client.comm_client")
cc = comm_client.CommClient()
logging.basicConfig(
level=loggi... | Guipc10/PFG | detect_faces/liveness-face-regressor/tests/src/gen_ground_truths.py | gen_ground_truths.py | py | 3,207 | python | en | code | 0 | github-code | 13 |
23812143846 | import sys
import threading
from datetime import datetime
from PyQt5.QtCore import QDate
from PyQt5.QtWidgets import *
from matplotlib.figure import Figure
import numpy as np
import matplotlib.dates as mdates
import matplotlib
from mplfinance.original_flavor import candlestick_ohlc
from matplotlib.backends.backend_qt5... | luckyDaveKim/WUBU | src/main.py | main.py | py | 10,281 | python | en | code | 2 | github-code | 13 |
72388296657 | # @author wangjinzhao on 2020/12/9
import scrapy
from scrapy.utils.response import open_in_browser
from tutorial.items import Item
class AllSpider2(scrapy.Spider):
name = "all-2"
allowed_domains = ["toscrape.com"]
start_urls = [
"http://quotes.toscrape.com/"
]
def parse(self, response):
... | bigbaldy1128/scrapy-demo | tutorial/spiders/all_spider2.py | all_spider2.py | py | 1,134 | python | en | code | 0 | github-code | 13 |
25552307447 | class Computer:
def __init__(self):
self.name = 'Rachel'
self.age = 28
def update(self):
self.age = 30
c1 = Computer()
c2 = Computer()
c1.name = 'Emma'
c1.age = 12
c1.update()
print(c1.name)
print(c1.age) | draksha22/python | update.py | update.py | py | 243 | python | en | code | 0 | github-code | 13 |
37274133172 | __author__ = 'DafniAntotsiou'
from gym.envs.registration import register
register(
id='InvertedPendulum_ext-v2',
entry_point='gym_ext.envs:InvertedPendulumEnvExt',
max_episode_steps=1000,
)
register(
id='HalfCheetah_ext-v2',
entry_point='gym_ext.envs:HalfCheetahEnvExt',
max_episode_steps=100... | DaphneAntotsiou/Adversarial-Imitation-Learning-with-Trajectorial-Augmentation-and-Correction | gym_ext/__init__.py | __init__.py | py | 325 | python | en | code | 1 | github-code | 13 |
73381534418 | # -*- coding: utf-8 -*-
"""
@description:
@author: LiuXin
@contact: xinliu1996@163.com
@Created on: 2020/11/1 下午10:20
"""
import os
import time
import random
import numpy as np
import argparse
import datetime
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch... | UESTC-Liuxin/SKMT | SkmtSeg/main.py | main.py | py | 7,643 | python | en | code | 0 | github-code | 13 |
25730102895 | """
Crossflow-enabled classes for WElib
Provides crossflow-compatible building blocks to code weighted ensemble simulation
workflows.
Classes:
CrossflowFunctionStepper
CrossflowFunctionProgressCoordinator
"""
from .base import Recorder
class CrossflowFunctionStepper(object):
"""
A class for functio... | CharlieLaughton/WElib | WElib/crossflow.py | crossflow.py | py | 3,535 | python | en | code | 0 | github-code | 13 |
24637196240 | ########################################################################################################
# The RWKV Language Model - https://github.com/BlinkDL/RWKV-LM
########################################################################################################
import gradio as gr
import os, copy, types, gc,... | 1500231819/ChatRWKV-WebUI | chat.py | chat.py | py | 16,333 | python | en | code | null | github-code | 13 |
12767861870 |
def netIncomeCalculator(state, grossIncome):
statetax=0
netIncome=0
federalTax=10*grossIncome/100
if state == "Florida":
statetax=3*grossIncome/100
elif state == "Texas":
statetax=5*grossIncome/100
elif state == "Arizona":
statetax=7*grossIncome/100
elif state == "Ne... | Nazreen20/NazreenPractice2020 | assignments/calculateTax.py | calculateTax.py | py | 690 | python | en | code | 0 | github-code | 13 |
39896942351 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn import preprocessing
import pandas as pd
import random
import itertools
import seaborn as sns
sns.set(style = 'darkgri... | dante0007/Breast-cancer-prediction-using-ML-algorithms | svm.py | svm.py | py | 3,487 | python | en | code | 0 | github-code | 13 |
11759555806 | from ontology_changes import (
Commit,
CreateProperty,
DeleteClass,
DeleteProperty,
RenameProperty,
SubsumeProperty,
)
from ontology_changes.create_class import CreateClass
from rack.namespaces.rack_ontology import (
AGENTS,
ANALYSIS,
FILE,
PROCESS,
PROV_S,
TESTING,
)
co... | Michielyn/RACK | migration/rack/commits/commit40955e24b4e38d45df2ffd0ad8aa47a827a4c72f.py | commit40955e24b4e38d45df2ffd0ad8aa47a827a4c72f.py | py | 3,085 | python | en | code | null | github-code | 13 |
31320076224 | # noinspection PyUnresolvedReferences
import OPi.GPIO as GPIO # this was installed by sudo, so
from time import sleep # this lets us have a time delay
GPIO.setboard(GPIO.PCPCPLUS) # ZERO
GPIO.setmode(GPIO.BOARD)
clk = 18
dt = 16
R_PIN = 33
G_PIN = 35
B_PIN = 37
GPIO.setup(R_PIN, GPIO.OUT)
GPIO.setup(G_PIN, GPIO.... | ClaasM/OrangePiOneExperiments | rotary_encoder_rgb.py | rotary_encoder_rgb.py | py | 1,524 | python | en | code | 0 | github-code | 13 |
15747703886 | class MyClass:
@staticmethod ## static method can be called from an instance or a class
def stat_meth():
print("Look no self was passed")
a = 10 # class variable shared by all instances
def fn(self): # self is representaion of object inside class
print("Hello");
print(MyClass... | sharmas4/Python_Programs | ClassExample01.py | ClassExample01.py | py | 3,772 | python | en | code | 0 | github-code | 13 |
11628905005 | #!/usr/bin/env python
import pytest
from olympus import Observations, ParameterVector
from olympus.planners import Cma
# use parametrize to test multiple configurations of the planner
@pytest.mark.parametrize("stddev", [0.5, 0.4, 0.6])
def test_planner_ask_tell(two_param_space, stddev):
planner = Cma(stddev=std... | aspuru-guzik-group/olympus | tests/test_planners/test_planner_cma.py | test_planner_cma.py | py | 566 | python | en | code | 70 | github-code | 13 |
16408959877 | import pickle
import pandas as pd
def predict(p1, p2, p3, p4, p5, p6, p7, p8):
f = open('Recom_Pre/pkl/pred_group.pkl', 'rb')
deci_tree = pickle.load(f)
f.close()
dict = {'1':[p2], '2':[p3], '3':[p4], '4':[p5], '5':[p6], '6':[p7], '7':[p8]}
X_test = pd.DataFrame(dict)
y_pred = ... | glorylife/RecommendMining | Recom_Pre/Prediction/load_model.py | load_model.py | py | 502 | python | th | code | 0 | github-code | 13 |
38689358119 | import re
import numpy as np
import pandas as pd
#this function is used to tell if two features are aligned
#for example: key1 = 'humidity', key2 = 'wind',
#return False because this combination is not in the align rule
#and they should be two separate columns in the fusedata
#if key1 = 'humidity', key2 = 'rh'... | muzzi30/mdsassignment | myfusecode.py | myfusecode.py | py | 5,201 | python | en | code | 0 | github-code | 13 |
27283155662 | import numpy as np
import csv
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
import sys
np.set_printoptions(threshold=sys.maxsize)
with open("data/Grand-slams-men-2013.csv") as f:
teams_comb = list(csv.reader(f))
FSP1 = np.array([])
ACE1 = np.array([])
DBF1 = np.array([])
WNR1 ... | ontckr/475Labs | lab8.py | lab8.py | py | 3,208 | python | en | code | 0 | github-code | 13 |
26265819186 | import re
from os.path import join, basename
from glob import glob
DATA_DIR = 'tempdata'
pattern = "(yob19[5-9][0-9]\.txt)|(yob20[01][0-9]\.txt)"
alltxtfiles_names = glob(join(DATA_DIR, '*.txt'))
myfilenames = []
for fname in alltxtfiles_names:
matchobj = re.search(pattern, fname, flags=0)
if matchobj:
... | kbenitez/compciv-2016 | exercises/0020-gender-detector/c.py | c.py | py | 839 | python | en | code | 0 | github-code | 13 |
1954997884 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 11:42:11 2020
Problem 76: Counting summations
It is possible to write five as a sum in exactly six different ways:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
How many different ways can one hundred be written as a sum of at least two positive in... | KubiakJakub01/ProjectEuler | src/Problem76.py | Problem76.py | py | 764 | python | en | code | 0 | github-code | 13 |
40647694364 | import os
import ast
import json
import torch
import cv2
from data_preperation.utils import read_txt, read_json
from data_preperation.visualize import get_cords_for_pred, display_image, get_cords_from_yolo
from configs.getconfig import GetConfig
import numpy as np
class prediction():
'''This class is uesd to cr... | VipulAlgoSoul/odhybrid | prediction/prediction.py | prediction.py | py | 4,873 | python | en | code | 0 | github-code | 13 |
6993440616 | import torch
from torch import nn
class RS(nn.Module):
def __init__(self, reduced_dim = True):
super(RS, self).__init__()
if reduced_dim:
item_size = 1000
user_size = 1000
else:
item_size = 9560
user_size = 1157633
if reduced_dim:
... | shengy3/RecomSystem | RecomSysModel.py | RecomSysModel.py | py | 2,198 | python | en | code | 0 | github-code | 13 |
12860537832 | from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from rest_framework import mixins, permissions, decorators, generics, status
from django_filters import rest_framework as filters
from src.core.serializers import CarSerializer
from src.suppliers.models import SupplierModel... | ChainHokesss/whitesnake_project | CarshowroomProject/src/suppliers/views.py | views.py | py | 1,736 | python | en | code | 0 | github-code | 13 |
1223775377 | # /bin/etc/env Python
# -*- coding: utf-8 -*-
import sys
import pygame
from bullet import Bullet
def check_keydown_events(event, ai_settings, screen, ship, bullets):
"""响应按键"""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = Tru... | AidenSmith09/alien_invasion | game_fuctions.py | game_fuctions.py | py | 1,800 | python | en | code | 0 | github-code | 13 |
27406868767 | import sys
# Hack to work around PySide being imported from nowhere:
import qtpy
from xicam.plugins import GUIPlugin, GUILayout
from xicam.plugins import manager as pluginmanager
from xicam.plugins import manager as pluginmanager
from xicam.core import threads
# Note: qtconsole often fails to guess correctly which q... | Xi-CAM/Xi-cam.plugins.IPython | xicam/ipython/__init__.py | __init__.py | py | 2,797 | python | en | code | 0 | github-code | 13 |
73009272018 | from microdot_asyncio import Microdot, Response, send_file
from microdot_utemplate import render_template
from microdot_asyncio_websocket import with_websocket
from ldr_photoresistor_module import LDR
import time
# Initialize MicroDot
app = Microdot()
Response.default_content_type = 'text/html'
# LDR module
ldr = LDR... | donskytech/micropython-raspberry-pi-pico | websocket_using_microdot/main.py | main.py | py | 1,068 | python | en | code | 13 | github-code | 13 |
30970354891 | x = 14 # x variable equal 14 number
y = 23 # y variable equal 23 number
print('x = %d y = %d'%(x,y)) #This line print x and y values on screen
temp = x # X value writing in temporary location
x = y # y value writing on X old value in this way now x value is 23
y = temp # temp value writing on y old value in this wa... | VefikFiratAkman/Introduction-to-Computer-Science | Introduction to Computer Science_FirstTry(Fail)/CSE101_HW02/151044031_Vefik_Firat_Akman.py | 151044031_Vefik_Firat_Akman.py | py | 416 | python | en | code | 0 | github-code | 13 |
31406761579 | # Originally made by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings)
# The original BigGAN+CLIP method was by https://twitter.com/advadnoun
# Adapted from https://github.com/nerdyrodent/VQGAN-CLIP/blob/main/generate.py
# Various functions and classes
import argparse
import math
fr... | gramhagen/game-paint | server/app/model/utils.py | utils.py | py | 19,513 | python | en | code | 1 | github-code | 13 |
71842177617 | import socket
import os
import threading
import sys
import datetime
HOST = 'localhost'
PORT = 3337
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('0.0.0.0',4324))
server_socket.listen(1)
# server_socket.settimeout(10)
print("Server started... | ZacSchepis/acm_bot | server.py | server.py | py | 877 | python | en | code | 0 | github-code | 13 |
17058750894 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class RecruitContentConfig(object):
def __init__(self):
self._config_code = None
self._config_value = None
@property
def config_code(self):
return self._config_code
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/RecruitContentConfig.py | RecruitContentConfig.py | py | 1,441 | python | en | code | 241 | github-code | 13 |
71139548497 | import os
import discord
from dotenv import load_dotenv
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import gzip
import io
import csv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client... | Ketsuppimakkara/AoE4-Discord-Elo-bot | bot.pyw | bot.pyw | pyw | 1,832 | python | en | code | 0 | github-code | 13 |
69850321619 | class BSTNode:
def __init__(self):
self.key=None
self.parent=None
self.left=None
self.right=None
def display(self):
lines, _, _, _ = self._display_aux()
for line in lines:
print(line)
def _display_aux(self):
"""Returns list of strings, wi... | rogzan/ASD | trees/001 - BST all.py | 001 - BST all.py | py | 4,673 | python | en | code | 0 | github-code | 13 |
33104140901 | """
Author: Shuoyao Wang From Shenzhen University
Reinforcement Learning (A3C) using Pytroch + multiprocessing for the paper:
S. Wang, S. Bi and Y. A. Zhang,
"Reinforcement Learning for Real-Time Pricing and Scheduling Control in EV Charging Stations,"
in IEEE Transactions on Industrial Informatics, vol. 17, no. 2, p... | wsyCUHK/Reinforcement-Learning-for-Real-time-Pricing-and-Scheduling-Control-in-EV-Charging-Stations | code/HSA.py | HSA.py | py | 10,262 | python | en | code | 97 | github-code | 13 |
2131257439 | def hooke_jeeves(evalf, x0, s, a=1, r=0.5, kmax=1e5, smin=1e-6):
import numpy as np
import scipy as sp
# Hooke and Jeeves
k = 0 # function evaulation counter
n = x0.size
# first step
xb = x0
fxb = evalf(xb); k += 1
x, fx = pattern_search(xb, fxb, s); k += (2*n)
... | bradling/direct-search-opt | hooke_jeeves.py | hooke_jeeves.py | py | 2,058 | python | en | code | 0 | github-code | 13 |
31494275432 | #Faça um programa que leia 5 números e informe o maior número.
def limp(x):
x = x.strip()
x = x.replace(',','.')
x = float(x)
return x
a = int(input('Quantos números você deseja inserir? '))
l = []
for i in range(a):
b = input(f'Digite o {i+1}º número: ')
b = limp(b)
l.appen... | GuilhermeMastelini/Exercicios_documentacao_Python | Estrutura de Repetição/Lição 7.py | Lição 7.py | py | 370 | python | pt | code | 0 | github-code | 13 |
17050358094 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ContractAttach(object):
def __init__(self):
self._biz_status = None
self._file_location = None
self._file_name = None
self._file_type = None
self._file_url... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/ContractAttach.py | ContractAttach.py | py | 3,395 | python | en | code | 241 | github-code | 13 |
73654531217 | #!/usr/bin/python3
'''
Author: Björn Hendriks
See http://adventofcode.com/2017
'''
import sys
sys.path.append('..')
import helpers.puzzleInput
import re
def makeGraph(input):
'''Make neighboring graph stored as dictionary with values
as list of neighbors of keys'''
graph = {}
for line in input.inputLineIter()... | bjhend/adventofcode | 2017/day12.py | day12.py | py | 1,292 | python | en | code | 0 | github-code | 13 |
37184749855 | import Tkinter as Tk
from lib import tkwindows
def boot_strap():
application = Tk.Tk()
return application
def main():
application = boot_strap()
window = tkwindows.TkWindow(application)
window.bootEvent()
application.protocol("WM_DELETE_WINDOW", window.fileQuit)
application.mainloop()
i... | bluele/PyCliper | pycliper.py | pycliper.py | py | 358 | python | en | code | 1 | github-code | 13 |
28419731772 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 1 11:54:30 2022
@author: Lucian
"""
import numpy as np
def checkHeader(header):
for (n, ch) in enumerate(header):
if ch in header[n+1:]:
return True
return False
def checkMessage(header):
for (n, ch) in enumerate(header):
if ch ... | luciansmith/adventOfCode | 2022/day6.py | day6.py | py | 792 | python | en | code | 0 | github-code | 13 |
71109809937 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Nico Colic, June 2015
import nltk
import os.path
class Text_processing(object):
"""Allows to do tokenisation and PoS tagging on a given text"""
"""For now, needs manual downloading in NLTK of tokenizers/punkt and maxent_treebank_pos_tagger before it works"""
"""Str... | Aequivinius/python-ontogene | text_processing/text_processing.py | text_processing.py | py | 4,952 | python | en | code | 1 | github-code | 13 |
40406242651 | # Ejercicio 6
#
# Diseñar una función que calcule el área y el perímetro de una circunferencia.
# Utiliza dicha función en un programa principal que lea el radio de una circunferencia y muestre su área y perímetro.
import math
def area_perimetro(radio):
area = math.pi * radio ** 2
perimetro = 2 * math.pi * r... | mavb86/ejercicios-python | seccion7/ejercicio06.py | ejercicio06.py | py | 569 | python | es | code | 0 | github-code | 13 |
35988829651 | from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSum = 0
answer = 0
anyPositive = False
for number in nums:
if number > 0:
anyPositive = True
if maxSum + number > 0:
maxSum += number
... | MateuszKudla/30-day-leet-coding-challange | day-3/maximum-subarray.py | maximum-subarray.py | py | 632 | python | en | code | 0 | github-code | 13 |
22454145679 | import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db import IntegrityError
from django.shortcuts import redirect, render
from django.urls import reverse
from django.http import HttpResponse, H... | carlosjosedesign/finance | finance/views.py | views.py | py | 33,519 | python | en | code | 0 | github-code | 13 |
17034032484 | from __future__ import print_function
from typing import Dict, Optional
from pathlib2 import Path
from six.moves import input
from six.moves.urllib.parse import urlparse
from clearml_agent.backend_api.session import Session
from clearml_agent.backend_api.session.defs import ENV_HOST
from clearml_agent.backend_config... | allegroai/clearml-agent | clearml_agent/commands/config.py | config.py | py | 17,027 | python | en | code | 205 | github-code | 13 |
7389241920 | import requests
import pyttsx3
import json
engine = pyttsx3.init("sapi5")
voices = engine.getProperty('voices')
engine.setProperty("voice", voices[0].id)
engine.setProperty('rate', 170)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def latestnews():
apidict = {"sports":"https://newsapi.org/v2... | kanugoyal/Virtual-Assistant | newsRead.py | newsRead.py | py | 1,819 | python | en | code | 1 | github-code | 13 |
5141561121 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 3 11:56:14 2023
@author: Hannah Germaine
This is a collection of functions for plotting deviation bins
(To eventually replace parts of "plot_funcs.py")
"""
import tqdm, os
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import ... | hfgem/BlechCodes | functions/dev_plots.py | dev_plots.py | py | 18,054 | python | en | code | 1 | github-code | 13 |
22453074953 | import sqlite3
conexion = sqlite3.connect("ejemplo.db")
cursor = conexion.cursor()
alumnos = [('Derek',21,456789,6), ('Adri',19,563478,10), ('Adri',19,563478,10)]
cursor.executemany("INSERT INTO alumno VALUES(?,?,?,?)", alumnos)
cursor.execute("SELECT * FROM alumno")
alumnitos = cursor.fetchall()
print(alumnitos)
#Camb... | isgla/pythonProteco | Intermedio/Clase4/Clase 4-20190621/base2.py | base2.py | py | 462 | python | es | code | 1 | github-code | 13 |
45194878526 | from math import inf
def min_coin(coins, s):
n = len(coins)
t = [[inf for _ in range(s + 1)] for _ in range(n)]
counter = 1
t[0][0] = 0
for i in range(coins[0], s + 1, coins[0]):
t[0][i] = counter
counter += 1
for i in range(1, n):
t[i][0] = 0
f... | kkorta/ASD | DynamicProgramming/min_num_coin_changing.py | min_num_coin_changing.py | py | 1,126 | python | en | code | 0 | github-code | 13 |
5007044983 | import sys
import numpy as np
#import matplotlib as plt
import matplotlib.pyplot as plt
plt.rc("axes", titlesize=14)
plt.rc("axes", labelsize=14)
plt.rc("xtick", labelsize=12)
plt.rc("ytick", labelsize=12)
reduced_filename = sys.argv[1].split("/")[-1][:-4]
def get_comms_time(filename):
datafile = open(filename... | JosephMoore25/L3-Project-DPUs | Graphing-Code/graph_latency.py | graph_latency.py | py | 1,709 | python | en | code | 0 | github-code | 13 |
28081563890 | import os
import sys
from os.path import join as opj
import base64
import struct
import copy
import numpy as np
from scipy.spatial.distance import cdist
import cv2
def parse_pt(pt_file):
with open(pt_file) as f:
lines = f.readlines()
img_rects = dict()
for line in lines:
line = line.strip()... | he010103/Traffic-Brain | AI-City-MTMC/tools/trajectory_fusion.py | trajectory_fusion.py | py | 3,377 | python | en | code | 15 | github-code | 13 |
43972752156 | import random
import datetime
class Person:
def __init__(self,name,act,det,spe,hp=100,skip=0,sround=0,hit=100,times = 1.0):
self.act = act
self.det = det
self.hp = hp
self.spe =spe
self.name = name
self.skip = skip
self.sround = sround
self.hit = hit
... | findland/benghuai | simulation.py | simulation.py | py | 8,968 | python | en | code | 0 | github-code | 13 |
10012481416 | ################################################################
#
# File: update_features.py
# Author: Michael Souffront
# Date: 05/22/2018
# Last Modified: 09/12/2018
# Purpose: Update published service with new dissolved FTs
# Requirements: arcpy
#
###########################################################... | BYU-Hydroinformatics/Esri_Animation_workflow_py | update_features.py | update_features.py | py | 1,453 | python | en | code | 0 | github-code | 13 |
24479408913 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import gym
import numpy as np
from stable_baselines.sac.policies import FeedForwardPolicy
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines import SAC
import gym
import simglucose
import warnings
def fxn():
warnings.warn("deprecated",... | Projna42/Pancreas_controller | Projna/using_the_SAC.py | using_the_SAC.py | py | 2,597 | python | en | code | 0 | github-code | 13 |
38740374162 | #coding: utf-8
from django.shortcuts import render, get_object_or_404,redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import user_passes_test, login_required, permission_required
from django.core.urlresolvers import reverse
from django.contrib.auth.models import ... | lianhuness/hdcrm | records/transfer_view.py | transfer_view.py | py | 2,231 | 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.