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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
43077248506 | from math import sqrt
def isPrime(num):
for i in range(2, int(sqrt(num)) + 1):
if num % i == 0:
return False
return True
i = 1
count = 2
while True:
n1 = 6 * i + 1
n2 = 6 * i - 1
i += 1
if isPrime(n1):
count += 1
if count == 10001:
print(n1)
break
if isPrime(n2):
count += 1
if count == 1000... | filipelsilva/Project-Euler | solves/p007.py | p007.py | py | 344 | python | en | code | 0 | github-code | 1 |
29973260610 | # Se tiene una cantidad de números dada donde hay varios primos determinar
# si el primo 2 y el primo 3 de acuerdo al orden de entrada si son consecutivos.
# Son consecutivos si entre los dos no hay otro número primo
cantidad=int(input("Digite la cantidad de datos, debe contener al menos 3 primos"))
primo2=primo3=0
ca... | AndHak/Universidad-Semestre1-Python | Punto 16 taller 1.py | Punto 16 taller 1.py | py | 776 | python | es | code | 2 | github-code | 1 |
71187185633 | import gym
class GymSpec:
def __init__(self, name, env_id):
self.name = name
self.env_id = env_id
GYM_ENVS = [
GymSpec('gym_CartPole-v0', 'CartPole-v0'),
GymSpec('gym_CartPolev-1', 'CartPole-v1'),
]
def gym_env_by_name(name):
for cfg in GYM_ENVS:
if cfg.name == name:
... | Garytoner/Asynchronous-Reinforcement-Learning | Asynchronous_Reinforcement_Learning/envs/gym/gym_utils.py | gym_utils.py | py | 518 | python | en | code | 1 | github-code | 1 |
5281842157 |
import shutil
import gc
import copy
import numpy
import random
import cv2
from PIL import Image, ImageDraw
import os
from functools import partial
from scipy.ndimage.filters import gaussian_filter
import time
import pickle
import re
from sklearn import preprocessing
import scipy.io as sio
from Att_BiLSTM_training impo... | mikecheninoulu/SMG | online recognition/SMG/THDutils.py | THDutils.py | py | 28,848 | python | en | code | 6 | github-code | 1 |
23319819904 | from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from main.models.models import Devices, Like
@login_required
def add_like(request, device_id):
user=request.user
device = get_object_or_404(Devices, pk... | MarcinzNS/mdvos-priv | mdvos/main/views/like_devices.py | like_devices.py | py | 1,887 | python | en | code | 0 | github-code | 1 |
34498271094 | """add geographic name table
Revision ID: 4d1ddc1ec574
Revises: 36d2a94e6894
Create Date: 2020-11-09 13:45:37.277092
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '4d1ddc1ec574'
down_revision = '36d2a94e6894'
branch_labels = None
depends_on = None
def upgra... | ThreeSixtyGiving/360insights | migrations/versions/4d1ddc1ec574_add_geographic_name_table.py | 4d1ddc1ec574_add_geographic_name_table.py | py | 1,135 | python | en | code | 0 | github-code | 1 |
3945339864 | #!/usr/bin/python
import web
import smbus
import math
urls = (
'/', 'index'
)
import time
#Hard iron offsets
x_offset = -618.954
y_offset = 733.05
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
gyro_scale = 131.0
accel_scale = 16384.0
address = 0x68 # This is the address value read via... | brewerdaniel/Minerva | arduino/Orientation/server.py | server.py | py | 4,542 | python | en | code | 0 | github-code | 1 |
37919203191 | from django.utils import timezone
import math
from rest_framework.response import Response
from typing import List
from discordoauth2.models import User
from ranked.models import EloHistory, GameMode, Match, PlayerElo
from .elo_constants import N, K, R, B, C, D, A
def validate_post_match_req_body(body: dict, players_... | SecondRobotics/SecondWebsite | ranked/api/lib.py | lib.py | py | 6,502 | python | en | code | 6 | github-code | 1 |
44293252428 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 20:39:16 2020
@author: BryaN
"""
#easy1
n= input("Enter your string: ")
s=["a","e","i","o","u","A","E","I","O","U"]
v=[]
nv=[]
count=0
for i in n:
if i in s:
count+=1
v.append(i)
else:
nv.append(i)
j="".join(nv)
prin... | BryaN759/BRACU | CSE111/Assignment3/E1.py | E1.py | py | 345 | python | en | code | 0 | github-code | 1 |
39366146128 | import json, os
from PyQtX import QtWebKitWidgets, QtCore, QtWidgets, QtWebKit
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, view):
super(MainWindow, self).__init__()
self.installEventFilter(self)
self.view = view
self.setCentralWidget(view)
def eventFilter(self, object, event):
if event.... | kpj/WebWrapper | python/gui.py | gui.py | py | 2,402 | python | en | code | 2 | github-code | 1 |
37756167576 | class employee:
no_of_emp=0
percent=1.04
def __init__(self,first,last,pay):
self.fname=first
self.lname=last
self.pay=pay
self.mail=self.fname+self.lname+'@veoneer.com'
employee.no_of_emp+=1
def raise_amount(self):
self.pay=int(self.pay*self.percent)
d... | subhash-regati/practice_project | practice1.py | practice1.py | py | 2,310 | python | en | code | 0 | github-code | 1 |
29966016525 |
import types
import pickle
import os
import numpy as np
import pathlib
import pdb
import scipy.io as sio
import copy
from do_mpc.tools import load_pickle, save_pickle
import types
import logging
from inspect import signature
from typing import Union
class DataHandler:
"""Post-processing data created from a sampl... | do-mpc/do-mpc | do_mpc/sampling/_datahandler.py | _datahandler.py | py | 14,004 | python | en | code | 729 | github-code | 1 |
73034299553 | # _*_ coding: utf-8 _*_
import os
from datetime import datetime
from scrapy import Spider, Request
from pyquery import PyQuery as pq
class Itjuzi(Spider):
name = 'itjuzi_spider'
def start_requests(self):
meta = {}
meta['page'] = 0
meta['url'] = 'http://itjuzi.com/company?page=%d'
... | shineforever/ops | vdian_spider/python/itjuzi/itjuzi/spiders/itjuzi_spider.py | itjuzi_spider.py | py | 5,060 | python | en | code | 9 | github-code | 1 |
37441104113 | from random import randint
from time import sleep
import colorama
from colorama import Fore, Style
from multiprocessing import Process
print(Fore.BLUE + Style.BRIGHT)
game_open = """
------------------------------------------------------------------------
---------------------------------------------------------------... | PrairieWaltz/AviGame | avigame.py | avigame.py | py | 3,779 | python | en | code | 0 | github-code | 1 |
8048259675 | """
Проверим насколько модуль random является действительно случайным.
Напишите такую программу, которая будет подбрасывать "монетку", и выбирать что выпало "орел" или "решка".
Чтобы точнее понять результат, проведем несколько экспериментов с разным количеством подбрасываний - от 10 до 1000000.
Дальше найдем количест... | meat9/PyTestHSE | task_1.py | task_1.py | py | 3,738 | python | ru | code | 0 | github-code | 1 |
29727773984 | """
Various utility functions, probably mostly for plotting.
"""
from collections import OrderedDict
import pandas as pd
from .pymcGrowth import GrowthModel
def reformatData(dfd, alldoses, alldrugs, drug, params):
"""
Sample nsamples number of points from sampling results,
Reformat dataframe so that colum... | meyer-lab/ps-growth-model | grmodel/utils.py | utils.py | py | 2,238 | python | en | code | 4 | github-code | 1 |
6693882258 | def _package_from_path(package_path):
package = "com.google"
if not package_path.startswith("src/javatests/com/google"):
fail("Not in javatests", "package_path")
return package + package_path[24:].replace("/", ".")
def junit_test_suites(
name,
sizes = None,
deps = None):
... | google/device-infra | src/javatests/com/google/devtools/deviceinfra/builddefs/junit_test_suites.bzl | junit_test_suites.bzl | bzl | 1,434 | python | en | code | 26 | github-code | 1 |
44011211302 | import numpy as np
import matplotlib.pyplot as plt
import sys
# Define the van Leer flux limiter function
def vanLeerFunc(X):
return (X + np.abs(X)) / (1 + X)
# Define required constants
A = 4e3
R = 8.314
NA = 6.022e23
VmMolar = 1.65e-5 # m^3 mol^-1, molar volume of monomer
rmMolar = (3/4*np.pi) * po... | renjygit/FYP | Nucleation and Growth.py | Nucleation and Growth.py | py | 10,150 | python | en | code | 0 | github-code | 1 |
17794729372 | import pandas as pd
import classification
#for this lab
#true postive = edible mushrooms recognized as edible
#true negative = posionous mushrooms recongized as poisonous
#false positive = poisonous classified as edible
#false negaive = edible recognized as poisonous
def evaluate(prefix, y, predy):
correct = 0
... | RaidenXP/Classification | analysis.py | analysis.py | py | 2,502 | python | en | code | 0 | github-code | 1 |
14778728267 | import sqlalchemy
from sqlalchemy.orm import sessionmaker
import json
from models import create_tables, Publisher, Book, Shop, Stock, Sale
if __name__ == '__main__':
DSN = 'postgresql://postgres:postgres@localhost:5432/netology_db'
engine = sqlalchemy.create_engine(DSN)
create_tables(engine)
Session... | Stelihon/SQL6 | main.py | main.py | py | 1,254 | python | en | code | 0 | github-code | 1 |
22630967569 | """ Collection of general utilities """
import contextlib
import json
import logging
import os
from pathlib import Path
import shutil
import subprocess
from typing import Union
import yaml
from datalad.distribution.dataset import require_dataset
from datalad.support.exceptions import NoDatasetFound
class ConfigErro... | cbbs-md/data-pipeline | src/data_pipeline/utils.py | utils.py | py | 10,755 | python | en | code | 0 | github-code | 1 |
38948168626 | from copy import copy
import itertools
from typing import List, Union
import pytest # type: ignore[import]
from testlib import on_time
from cmk.base.plugins.agent_based import job
from cmk.base.plugins.agent_based.agent_based_api.v1 import (
clusterize,
Result,
State as state,
Metric,
type_defs,
... | superbjorn09/checkmk | tests/unit/cmk/base/plugins/agent_based/test_job.py | test_job.py | py | 17,925 | python | en | code | null | github-code | 1 |
69903728354 |
n=int(input())
temp=n
if(n<0):
n=abs(n)
rev=0
while(n):
d=n%10
rev=rev*10+d
n=n//10
if(temp<0):
print(-rev)
else:
print(rev) | tejaswinikanda2003/codemind-python | Reverse_Integer.py | Reverse_Integer.py | py | 149 | python | ru | code | 0 | github-code | 1 |
36043600775 | import numpy as np
np.random.seed(1)
from keras.layers import Dense
from keras.models import Sequential
import matplotlib.pyplot as plt
X = np.linspace(-1,1,200)
Y = X*0.3 +2 +np.random.normal(0,0.05,(200,))
X_train = X[:160]
X_test = X[160:]
Y_train = Y[:160]
Y_test = Y[160:]
model = Sequential(
[
Dense... | ByronGe/machine-Learning | keras/classifier_exampleTest.py | classifier_exampleTest.py | py | 895 | python | en | code | 0 | github-code | 1 |
35867607447 | import numpy as np
import pandas as pd
import os
cols = ['flap_te_pos', 'hbaro_m', 'hralt_m', 'hdot_1_mps', 'gs_mps', \
'gs_dev_ddm', 'loc_dev_ddm', 'n11_rpm', 'n12_rpm', 'n13_rpm', \
'n14_rpm', 'tas_mps', 'theta_rad', 'chi_rad', 'lg_squat_mr']
def get_crucial_df(df_fdm, alt_m, duration_s, sampling_ra... | rnsantosa/flight_analyzer | main/defs.py | defs.py | py | 947 | python | en | code | 0 | github-code | 1 |
41425319510 | import numpy as np
import pandas as pd
import csv
from datetime import datetime, timedelta
from polygon import RESTClient
import yfinance as yf
import matplotlib.pyplot as plt
d2 = datetime.today() - timedelta(days=1)
d1 = d2 - timedelta(days=365)
d3 = d2 - timedelta(days=30)
start_d = d1.strftime('%Y-%m-%d')
end_d = ... | amoszczynski/Mid-Term_Algo-Trader | v1/signaling.py | signaling.py | py | 7,971 | python | en | code | 1 | github-code | 1 |
2424736487 | from odoo import models, api, fields
from odoo.tools import float_compare
class SaleOrder(models.Model):
_inherit = 'sale.order'
sent_rate = fields.Float(
compute='_compute_sent_rate',
help='Rate of sent products',
)
task_rate = fields.Float(
compute='_compute_task_rate',
... | decgroupe/odoo-addons-dec | sale_delivery_rate/models/sale_order.py | sale_order.py | py | 2,498 | python | en | code | 2 | github-code | 1 |
28011080370 | '''
Defining a class that iterates N times in an object.
If N is bigger that the number of elements, repeats from the beginning.
Example: N = 4, object = "abc". Produces: abca
'''
class Circle():
'''
Our iterator with the property mentioned above.
Being an iterator, by defintion it must provide an __iter__... | bgppa/python_workout | chX_iterators_and_generators/ex47.py | ex47.py | py | 2,181 | python | en | code | 0 | github-code | 1 |
11807782156 | import os
import re
import csv
import spacy
import convert2txt
nlp = spacy.load('skill-cv-bn')
def create_dic(filename):
result = {
'Filename': filename,
'Name':[],
'Number':[],
'Email':[],
'Experience':[],
'Companies'... | remon-rakibul/FitFinder | test-skill-cv-bn.py | test-skill-cv-bn.py | py | 4,365 | python | en | code | 0 | github-code | 1 |
41287150445 | from django.db import models, transaction
from django.dispatch import receiver
from django.db.models.signals import post_delete
from api.espo_api_client import EspoClientMixin
from django.conf import settings
from petuni_main.celery import app
CRM_DO_NOTHING = 0
CRM_SOFT_DELETE = 1
CRM_TRUE_DELETE = 2
class CRMSign... | sdmitrievlolx/code_samples | crm/models.py | models.py | py | 5,118 | python | en | code | 0 | github-code | 1 |
44755585332 | from django.contrib import admin
from django.urls import path
from .views import *
urlpatterns = [
path('',MaincourseListView.as_view(),name='main-course-list'),
path('explore/',courseListView.as_view(),name='course-list'),
path('create/',courseCreateView.as_view(),name='course-create'),
# path('',cour... | Floran-Github/CoderHifi-Code | backend/course/urls.py | urls.py | py | 2,548 | python | en | code | 1 | github-code | 1 |
25290296184 | from dataclasses import dataclass
import cv2
import math
import numpy as np
import base64
import struct
from numpy import int16, int8, uint16, uint8, uint32, int32
def drawHor(frame, theta, phi):
widAngle = 65
heiAngle = widAngle*3.0/4.0
height, width, channels = frame.shape
pm = (width/2, height/2)
... | ksklorz/ITproj | src/cam/hud.py | hud.py | py | 2,095 | python | en | code | 0 | github-code | 1 |
31904766774 | from pyxavi.config import Config
from pyxavi.logger import Logger
from janitor.lib.system_info import SystemInfo
from janitor.lib.system_info_templater import SystemInfoTemplater
from janitor.lib.publisher import Publisher
from janitor.lib.mastodon_helper import MastodonHelper
from janitor.objects.queue_item import Que... | XaviArnaus/janitor | listen.py | listen.py | py | 5,150 | python | en | code | 1 | github-code | 1 |
28838376515 | from flask import Flask, jsonify, request
weather_data = {
'San Francisco': {'temperature': 14, 'weather': 'Cloudy'},
'New York': {'temperature': 20, 'weather': 'Sunny'},
'Los Angeles': {'temperature': 24, 'weather': 'Sunny'},
'Seattle': {'temperature': 10, 'weather': 'Rainy'},
'Austin': {'temperat... | 9802HEMENSAN/GPT-3.0 | sprint-2/pytest/pytest-whether-2/app.py | app.py | py | 2,081 | python | en | code | 0 | github-code | 1 |
4565998185 |
import json
from math import e
import stat
from typing import Dict
from data.google.google_email_repository import GooleCalendarEventRepository
from services.google_auth_service import GoogleAuthService
from framework.logger import get_logger
from googleapiclient.discovery import build
from google.oauth2.credentials ... | danleonard-nj/kube-tools-api | services/kube-tools/services/calendar_service.py | calendar_service.py | py | 5,734 | python | en | code | 0 | github-code | 1 |
15286175427 |
def bellmanford(graph, numV, numE):
INF = 1000000
dist = []
for i in range(numV):
dist.append(INF)
dist[0] = 0
for i in range(1,numV):
for j in range(numE):
u = graph[j][0]
v = graph[j][1]
w = graph[j][2]
if(dist[u] != INF and dist[u] ... | NonSenseGuy/AED_FP | uvaSolutions/Wormholes_Python3/Main.py | Main.py | py | 1,086 | python | en | code | 0 | github-code | 1 |
24535880130 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 15:10:04 2021
@author: davidfordjour
"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def Read_Two_Column_File(file_name):
"""Reading in the data for time and date."""
with open(file_name, 'r') as data:
x ... | davidfordjour/jog-times | jogtracker.py | jogtracker.py | py | 1,357 | python | en | code | 0 | github-code | 1 |
14005775602 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 15:42:52 2018
@author: liuyang
"""
from datetime import datetime
import numpy as np
import pandas as pd
import MYSQLPD as sql
import math
def DatetoDigit(date):
digitdate=date.year*10000+date.month*100+date.day
return digitdate
#读取交易日期列表
... | SamLiuYang/MFM | SFData.py | SFData.py | py | 3,509 | python | en | code | 0 | github-code | 1 |
21029279523 | from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("prices/", views.get_price, name="get_price"),
path("home/", views.trending_tickers_view, name="trending_tickers"),
path("new_stock/", views.new_user_stock, name="new_stock"),
]
| AirFryedCoffee/mystocksite | stocks/urls.py | urls.py | py | 309 | python | en | code | 1 | github-code | 1 |
13309845798 |
RESPONSE_OK = object()
RESPONSE_ERROR = object()
RESPONSE_WARN = object()
class Response(object):
def __init__(self):
self.content = ""
self.return_code = RESPONSE_OK
@staticmethod
def success(response_content=""):
r = Response()
r.content = response_content
r.re... | zalum/system-model-visualizer | smv/core/common.py | common.py | py | 875 | python | en | code | 0 | github-code | 1 |
24645949646 | # -*- coding: utf-8 -*-
"""
Created on Tue May 22 09:27:44 2018
@author: Administrator
"""
import math
# start+(end-start)/2 <--> (start+end)/2
def maxmin(L, start, end):
"""
求出L的最大最小值的元组
"""
if end-start <= 1:
return (max(L[start],L[end]),min(L[start],L[end]))
else:
... | smakerm/list | note/step4/爬虫笔记/17. Crawler01/day02/getMaxMin.py | getMaxMin.py | py | 599 | python | en | code | 0 | github-code | 1 |
24049590178 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__authors__ = 'Bruno Adelé <bruno@adele.im>'
__copyright__ = 'Copyright (C) 2013 Bruno Adelé'
__description__ = """A metar domolib"""
__license__ = 'GPL'
__version__ = '0.0.1'
# Require metar
# pip install git+https://github.com/tomp/python-metar.git
import re
try:
... | badele/domolib | domolib/plugins/weather/dlmetar/__init__.py | __init__.py | py | 2,849 | python | en | code | 0 | github-code | 1 |
39298570629 | import hmac
# The block size = 2 * hash digest length
BLK_SIZE = 32
def xor(a, b):
"""Implement xor for 2 bytearrays.
Arguments:
a (bytearray): First byte array.
b (bytearray): Second byte array.
Returns:
bytearray: The result of a XOR b.
"""
return bytearray([ai... | prateeknischal/fiestel | cipher.py | cipher.py | py | 3,131 | python | en | code | 0 | github-code | 1 |
14314103404 | import numpy as np
import pandas as pd
import tensorflow as tf
import json
from keras.models import Model, Sequential
from keras.layers import Input, Activation, Dense
from keras.optimizers import SGD
from keras.utils.np_utils import to_categorical
from flask import Flask, render_template, jsonify
app = Flask(__name__... | qualityassurancetools/JSTbackprop | dota2.py | dota2.py | py | 2,924 | python | en | code | 0 | github-code | 1 |
12168411543 | #imports csv functions
import csv
import datetime
from os import read
#Dictionary for storing products
prod_dict = {
}
#Dictionary for storing requests
req_dict = {
}
#Dictionary for the receipt
receipt_dict = {
}
number_of_items = 0
subtotal = 0
current_date_and_time = datetime.datetime.now()
# Format the cur... | Elijah3502/CSE110 | Programming with functinos/Week3/03Prove.py | 03Prove.py | py | 2,087 | python | en | code | 0 | github-code | 1 |
70735133154 | import os
import pandas as pd
from joblib import Parallel, delayed
from util import get_interfaces_path, iter_cdd
NUM_WORKERS = 20
def get_counts(sfam_id):
path = os.path.join(get_interfaces_path(dataset_name), "by_superfamily",
str(int(sfam_id)), "{}_bsa.h5".format(int(sfam_id)))
store = pd.HDFStore(... | bouralab/Prop3D | Prop3D/visualize/plot_ppi_types.py | plot_ppi_types.py | py | 1,264 | python | en | code | 16 | github-code | 1 |
32939752267 | # coding=utf-8
from glob import glob
import re
from time import time
import requests
import os
# from xml.dom import minidom
from lxml import etree
import base64
import traceback
import html2text as ht #
from selenium.webdriver.chrome.options import Options
import time
from selenium import webdriver
from selenium.web... | DuanShaoCheng/csdn_jianshu_to_makedown | csdn_jianshu_to_makedown.py | csdn_jianshu_to_makedown.py | py | 8,178 | python | en | code | 0 | github-code | 1 |
16953372863 | from classifiers.decision_tree import DecisionTree
from collections import Counter
from utils.utility import pick_result
from random import randrange
import numpy
__author__ = 'Simon & Oskar'
class RandomForest:
def __init__(self, max_depth = None, min_samples_leaf = 1, n_estimators = 10, sample_size = 200, max... | lazi3b0y/RandomActsOfPizza | classifiers/random_forest.py | random_forest.py | py | 3,293 | python | en | code | 0 | github-code | 1 |
9204198406 | from django.conf.urls.defaults import *
from django.contrib.auth.models import User
from django.views.generic.simple import direct_to_template
from board.feeds import LatestPosts
from board.rpc import rpc_post, rpc_lookup, rpc_preview, rpc_ban
from board.views import *
feeds = {'latest': LatestPosts}
js_info_dict = ... | bawaaaaah/django-torrent-tracker | board/urls.py | urls.py | py | 2,676 | python | en | code | 4 | github-code | 1 |
25224482568 | import logging
# import gevent
import asyncio
from typing import Optional
from xbox.sg.crypto import PKCS7Padding
from xbox.sg.utils.events import Event
from xbox.auxiliary import packer
from xbox.auxiliary.packet import aux_header_struct, AUX_PACKET_MAGIC
from xbox.auxiliary.crypto import AuxiliaryStreamCrypto
from x... | OpenXbox/xbox-smartglass-core-python | xbox/auxiliary/relay.py | relay.py | py | 4,650 | python | en | code | 71 | github-code | 1 |
8057072033 | from FileLoader import FileLoader
import pandas
def howManyMedals(data, name):
matchAthlete = data.loc[data['Name'] == name]
if matchAthlete.empty:
print("No information about this athlete.")
return None
matchAthlete = matchAthlete.dropna(subset=['Medal'])
if matchAthlete.empty:
... | Mporzier/piscine-python | day04/ex03/HowManyMedals.py | HowManyMedals.py | py | 698 | python | en | code | 0 | github-code | 1 |
15235514484 | import win32serviceutil
import win32service
import win32event
import servicemanager
import configparser
import os
import inspect
from multiprocessing import Process, Pipe
from db.sqlitemanager import SQLiteManager
from proc.node_client_process import NodeClientProcess
import utils.script_manager as sm
import utils.logg... | bensoer/vessel | node.py | node.py | py | 4,918 | python | en | code | 0 | github-code | 1 |
22743479426 | from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('monitoramento.urls')),
path('users/', include('users.urls')),
path('clientes/', include(... | joaaovitorrodrigues/trackerreine | TrackerReine/urls.py | urls.py | py | 724 | python | en | code | 0 | github-code | 1 |
5974963694 | import re
if __name__ == "__main__":
text_phrases = ["[[link#subheading|alttext]]", "[[link]]", "[[link#subheading]]", "[[link|alttext]]"]
for text in text_phrases:
result = re.search(r"\[\[([^#|\]]+)([^|\]]*)([^\]]*)\]\]", text)
groups = result.groups()
printText = ""
... | doglman/markdownCombiner | testing.py | testing.py | py | 536 | python | en | code | 0 | github-code | 1 |
26987174906 | # Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == '__main__':
n = int(input())
#print(n)
input_string = input()
numbers = list(map(int, input_string.split()))
#mean
numbersum = sum(numbers)
# print (numbersum)
mean = numbersum/n
print (mean)
#mea... | Seppel1985/HackerRank | 10_Days_of_Statistics/s10-basic-statistics.py | s10-basic-statistics.py | py | 773 | python | en | code | 0 | github-code | 1 |
22123154667 | import unittest
from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits is None or len(digits) == 0:
return []
res = [""]
alph = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def combine(res, str):
... | AllieChen02/LeetcodeExercise | String/P17LetterCombinationsOfAPhoneNumber/LetterCombinationsOfAPhoneNumber.py | LetterCombinationsOfAPhoneNumber.py | py | 842 | python | en | code | 0 | github-code | 1 |
20382049470 | import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import Adafruit_LSM303
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
# Raspberry Pi pin configuration:
RST = 24
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)
# Note you can change th... | pguiffr62/Engineering_4_Notebook | Python/headless.py | headless.py | py | 1,901 | python | en | code | 0 | github-code | 1 |
17324810580 | '''
Created on 2012/03/20
@author: hogelog
'''
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import threading
import logging
class HttpControlerHandler(SimpleHTTPRequestHandler):
def do_GET(self):
mapping = self.mapping()
path = self.path
if ... | hogelog/real-lamp | src/controler.py | controler.py | py | 1,977 | python | en | code | 1 | github-code | 1 |
28672285057 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import platform
import sys
import typing
import numpy as np
import pandas as pd
import tensorflow as tf
sys.path.append(".")
import delay
import delay.agents
import delay.core
tf.disable_eager_execution()
keras = tf.keras
if typing.TYPE_CHECKING:
from typ... | kmdict/FollowTheProphet | examples/delay_tencent2017.py | delay_tencent2017.py | py | 4,611 | python | en | code | 5 | github-code | 1 |
32159999356 | import unittest
from unittest import TestCase
import sys
sys.path.insert(0, '../uasyncio')
import queues
class QueueTestCase(TestCase):
def _val(self, gen):
"""Returns val from generator."""
while True:
try:
gen.send(None)
except StopIteration as e:
... | pfalcon/pycopy-lib | uasyncio.queues/tests/test.py | test.py | py | 1,462 | python | en | code | 229 | github-code | 1 |
30003130370 | #!/usr/bin/env python3
import os, sys, logging, subprocess, json, traceback
def main():
s = Setup()
s.interpret_arguments(sys.argv)
s.ensure_java_maven_exists()
s.ensure_conda_exists()
s.recreate_conda_environment()
s.install_via_pip('clingo==5.5.0.post3 jpype1==1.2.1')
s.reclone_hexlite('v1.4.0')
s.build_hex... | hexhex/hexlite-owlapi-plugin | setup_and_test_within_conda.py | setup_and_test_within_conda.py | py | 6,303 | python | en | code | 3 | github-code | 1 |
22039807700 | import sys
try:
i=int(input("enter a number or Enter to finish: "))
except:
print(" -_- ")
sys.exit(0)
l=[]
while True:
s=int(i)
l.append(s)
try:
i=int(input("enter a number or Enter to finish: "))
except:
break
print("numbers: ",l)
c=len(l)
su=0
hi=l[0]
low... | btg1998/Information-Systems | Book Solutions/Chapter 1/Q5.py | Q5.py | py | 738 | python | en | code | 0 | github-code | 1 |
42042144582 | import sqlite3
name = input("Name of the pdgm project you are working on: ")
db = sqlite3.connect(name + ".sqlite")
cursor = db.cursor()
print("""Please enter source and target of your dependencies.
After each entry you have to confirm the entry. The question can be answered in four ways:
y - yes: Valid entry, co... | grietje/proof-dependency-graph-maker | fill.py | fill.py | py | 1,438 | python | en | code | 0 | github-code | 1 |
33346534147 | import sys
N=int(input())
houses = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]
dir = [(-1,0),(1,0),(0,1),(0,-1)]
def posiible_path(x,y):
if (0<=x<N) and (0<=y<N):
return True
return False
def dfs(x,y,selected):
visited[x][y]=True
selected.append((x,y))
for dirx, di... | atg0831/algo | dfs&bfs/BOJ-2667.py | BOJ-2667.py | py | 912 | python | en | code | 0 | github-code | 1 |
12624694803 | from flask import Blueprint
from flask_restful import Api
from .resources import PersonResource, PersonIdResource, PostUserResource, PostAccountResource, GetAccountResource, GetAccountIdResource
bp = Blueprint("restapi", __name__, url_prefix="/api")
api = Api(bp)
def init_app(app):
api.add_resource(PersonResour... | danielfernandow/Ies-Bank | bank/blueprints/restapi/__init__.py | __init__.py | py | 678 | python | en | code | 0 | github-code | 1 |
5170747762 | import socket
remoteserver=input("Pls enter remote server name or ip for port scanning:")
remoteipaddress= socket.gethostbyname(remoteserver)
for port in range(131,151):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result= sock.connect_ex((remoteipaddress, port))
if result == 0:
... | padmalarai/Python | portscanner.py | portscanner.py | py | 426 | python | en | code | 0 | github-code | 1 |
29443696453 | ########################################################################################################
#
# Determinado banco possui os dados de histórico de empréstimo, vistos na tabela abaixo. Com esse dados,
# o banco solicitou que fosse construído um modelo que fornecendo os dados de entrada, indique se dev... | Grinduim/Bosch-2022.2 | Bosch/InnoHub/Treinamento de IA/materiais/Exemplos_1/NAIVE_BAYES_EXAMPLES/TREINO_DE_FUTEBOL.py | TREINO_DE_FUTEBOL.py | py | 2,980 | python | pt | code | 0 | github-code | 1 |
21973093016 | ## Import Statements
from helpers import filling_movie_name, movie_showboard, number_of_players, removing_spaces, spin_wheel, VOWELS, INTEGERS, SYMBOLS, ALPHABETS
from get_movie import get_movie_name
from create_players import HumanPlayer
import time
## GLobal variables
index = 0
guessed_letters = []
winner = False
p... | Ayush-Patel15/GuessTheMovie | src/main.py | main.py | py | 4,670 | python | en | code | 0 | github-code | 1 |
11001989881 | # Support Vector Machine (SVM)
# from https://www.superdatascience.com/machine-learning/
# Part 1 - Data Preprocessing
# Importing the libraries
import os
import glob
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
train_dir = os.path.join(os.path.curdir, "data/train")
validation_dir = os.path.j... | amelco/webcam-eyetracking | svm.py | svm.py | py | 2,928 | python | en | code | 1 | github-code | 1 |
29250118675 | import sys
from collections import deque
dq = deque()
N, K = map(int, sys.stdin.readline().rstrip().split(' '))
for i in range(1, N + 1):
dq.append(i)
eleminated = []
while len(dq) != 0:
count = 1
while count < K:
dq.append(dq.popleft())
count += 1
eleminated.append(dq.popleft())
prin... | ho991217/Python | BOJ/Data Structure/Queue/[11866] Yosefus.py | [11866] Yosefus.py | py | 463 | python | en | code | 0 | github-code | 1 |
36170474621 | # This file is Copyright 2020 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
import json
import logging
import ntpath
import os
import re
from typing import List, Dict, Union
from volatility3.framewor... | volatilityfoundation/volatility3 | volatility3/framework/plugins/windows/getsids.py | getsids.py | py | 8,864 | python | en | code | 1,879 | github-code | 1 |
22837266278 | # %% [markdown]
# # Extracting attributes from timedelta columns via a ColumnTransformationPlugin
#
# inspired by Sailu and the following stackoverflow question:
# - https://stackoverflow.com/questions/38355816/pandas-add-timedelta-column-to-datetime-column-vectorized
#
# __Goal:__ extract the number of weeks as float ... | hussien-hussien/bamboolib | plugins/examples/timedelta_extract_attributes.py | timedelta_extract_attributes.py | py | 2,343 | python | en | code | null | github-code | 1 |
5312981421 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: vm.py
@time: 2020/8/19 21:28
@project: wasm-python-book
@desc:
"""
from ch09.binary.module import Module, ImportTagFunc
from ch09.binary.opcodes import Call
from ch09.interpreter.instr_control import call
from ch09.interpreter.instructions import ins... | Relph1119/wasm-python-book | src/ch09/interpreter/vm.py | vm.py | py | 6,433 | python | en | code | 17 | github-code | 1 |
43220039182 | import yaml
from modulemd.components import ModuleComponents
from modulemd.content import ModuleContent
from modulemd.rpms import ModuleRPMs
from modulemd.profile import ModuleProfile
supported_mdversions = ( 0, )
class ModuleMetadata(object):
"""Class representing the whole module."""
REPODATA_FILENAME = "... | xsuchy/modulemd | modulemd/__init__.py | __init__.py | py | 25,774 | python | en | code | 0 | github-code | 1 |
19825709054 | from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
to_make=True
menu=Menu()
coffee_maker=CoffeeMaker()
money_machine=MoneyMachine()
# cost={
# "latte":2.5,
# "espresso":1.5,
# "cappuccino":3
# }
while to_make:
order=input("what do you want?:")
... | ArghyaAD/Python | coffee/main.py | main.py | py | 635 | python | en | code | 0 | github-code | 1 |
15340432546 | from pprint import pprint
import statistics
DEBUG = False
PATH = f"C:\\work\\SVN\\adventofcode\\2021\\day8_{'sample' if DEBUG else 'input'}.txt"
with open(PATH, 'r') as f:
#inp2 = [tuple(parse.parse("{:d},{:d} -> {:d},{:d}",
#l.strip()).fixed) for l in f.readlines()]
# print(inp2)
inp = ... | VirtualSatai/adventofcode | 2021/day8.py | day8.py | py | 2,321 | python | en | code | 0 | github-code | 1 |
29495188338 | # -*- coding: utf-8 -*-
# @Time : 2017/7/16 23:55
# @Author : chen
# @Site :
# @File : vector_util.py
# @Software: PyCharm
import pandas as pd
from load.import_util import file_to_dict, file_to_list
def deal_ida_format(types):
# f = open("D:/python/workspace/TextProcess/segment/data/lda/one... | chensian/TextProcess | segment/vector_transfer/statistics.py | statistics.py | py | 3,318 | python | en | code | 1 | github-code | 1 |
19957710129 | import random
import sqlite3
def sql_create():
global db, cursor
db = sqlite3.connect("bot.sqlite3")
cursor = db.cursor()
if db:
print("База данных подключена!")
db.execute("CREATE TABLE IF NOT EXISTS anketa "
"(id INTEGER PRIMARY KEY, "
"name ... | solvur/home-works | database/bot_db.py | bot_db.py | py | 1,134 | python | en | code | 1 | github-code | 1 |
8862670450 | import numpy as np
import matplotlib.pyplot as plt
black1 = np.zeros((50,50))
black2 = black1.copy()
white1 = np.ones((50,50))
white2 = white1.copy()
row1 = np.hstack((black1,white1))
row2 = np.hstack((white2, black2))
full = np.vstack((row1,row2))
plt.figure()
plt.imshow(full, cmap='gray')
plt.show() | MatanBuljubasic/OsnoveStrojnogUcenja_LV | LV2/zad4.py | zad4.py | py | 303 | python | en | code | 0 | github-code | 1 |
8529990174 | #!/bin/python3
import os
import pandas
import argparse
import traceback
import numpy as np
from datetime import datetime, timedelta
# lisflood
import lisf1
from lisflood.global_modules.decorators import Cache
from liscal import hydro_model, templates, config, subcatchment, calibration, objective
class ScalingModel(... | ec-jrc/lisflood-calibration | bin/scaling.py | scaling.py | py | 5,307 | python | en | code | 8 | github-code | 1 |
9417647037 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 17 05:15:30 2018
@author: LeeMH
"""
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
import requests
import re
from utils.processor_checker import timeit
from gobble.module.crawler import Crawler
class NaverRealtimeCrawler(Crawler):
'''
네이버... | veggieavocado/Gobble-v.1 | gobble/module/naver_rt_crawler.py | naver_rt_crawler.py | py | 2,620 | python | en | code | 1 | github-code | 1 |
64006031 | import cv2
from pykuwahara import kuwahara
image = cv2.imread('selfie.jpg')
image = (image / 255).astype('float32') # pykuwahara supports float32 as well
lab_image = cv2.cvtColor(image, cv2.COLOR_BGR2Lab)
l, a, b = cv2.split(lab_image)
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv_im... | yoch/pykuwahara | examples/selfie.py | selfie.py | py | 741 | python | en | code | 14 | github-code | 1 |
22377442955 | # Testzone para o apêndice
import apendice as ap
import matplotlib.pyplot as plt
#%% Plotando os sharp_test
## Sinal 1
vector1 = ap.sharpe_test_1(combined = combined, tam_p = 0.1, qtde = 200, inverso = True)
plt.hist(vector1.iloc[:,0], bins = 40)
plt.ylabel('Quantas vezes')
plt.xlabel('Sharpe')
plt.title('Para o S... | Insper-Data/Data_Fin_2021.1 | testzone_apendice.py | testzone_apendice.py | py | 1,176 | python | pt | code | 0 | github-code | 1 |
27513505787 | import math
def get_code_value(input):
min_val = 0
max_val = 2**len(input) - 1
for char in input:
mid_diff_val = (max_val - min_val) / 2
if char in ['F', 'L']: # Lower half
max_val = math.floor(max_val - mid_diff_val)
if char in ['B', 'R']: # Upper half
... | watksimo/advent-of-code | 2020/day-5/python/day_5.py | day_5.py | py | 1,928 | python | en | code | 3 | github-code | 1 |
27387352934 | from __future__ import print_function
import os.path
import sys
import densenet
import numpy as np
import sklearn.metrics as metrics
from keras.datasets import cifar10
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.callbacks impor... | nima200/densenet-ablation | src/cifar10/BNLGrowthRate/cifar10.py | cifar10.py | py | 10,546 | python | en | code | 0 | github-code | 1 |
36473075239 | from wsgiref.simple_server import make_server
import psutil,datetime
import sqlite3
def interview_scores(environ, start_response):
conn_result=sqlite3.connect("results.sqlite")
cursor_result = conn_result.cursor()
print_results = cursor_result.execute("select * from interview_results")
status = '200 O... | avikrb/PROGRAMS | Python/GUI interview program/check_scores_htlm.py | check_scores_htlm.py | py | 1,286 | python | en | code | 0 | github-code | 1 |
21255411852 | from sys import stdin
stdin = open("input.txt", "r")
res = 0
in_group = 0
seen = {chr(key): 0 for key in range(ord('a'), ord('z') + 1)}
for line in stdin:
if line == '' or line == '\n':
res += sum([v == in_group for v in seen.values()])
seen = {chr(key): 0 for key in range(ord('a'), ord('z') + 1)}
... | mmehas/advent_of_code_2020 | src/6_hard.py | 6_hard.py | py | 520 | python | en | code | 0 | github-code | 1 |
14794717807 | import os
# force TF to use CPU instead of GPU (sadly my discrete card is not support the latest CUDA version)
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import gym
from gym import envs
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
import matplo... | Ielay/ml-lunar-lander-problem-rl | src/train_model.py | train_model.py | py | 5,554 | python | en | code | 0 | github-code | 1 |
27089308927 | N = int(input())
c = list(input())
Nw, Nr = 0, 0
for i in range(len(c)):
Nw += 1 if c[i] == "W" else 0
Nr += 1 if c[i] == "R" else 0
if Nw == 0 or Nr == 0:
print(0)
exit()
left_w = 0
right_r = 0
if c[0] == "W":
left_w = 1
right_r = Nr
else:
left_w = 0
right_r = Nr - 1
#仕切りの位置をiの横とすると... | Intel-out-side/AtCoder | ABC174/d2.py | d2.py | py | 568 | python | en | code | 0 | github-code | 1 |
552754902 | from flask import Flask, render_template, request, redirect, flash, session, config
from flask_debugtoolbar import DebugToolbarExtension
from surveys import satisfaction_survey as survey
app = Flask(__name__)
app.config['SECRET_KEY'] = "austin"
debug = DebugToolbarExtension(app)
responses = []
currentNum = 0
RESPONS... | austindreosch/springboard | exercises/section2/flask-session/app.py | app.py | py | 3,081 | python | en | code | 0 | github-code | 1 |
22687443944 | # Write a program which will select a random name from a list of names.
# The person selected will have to pay for everybody's food bill.
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
import random
i = random.randint... | dsNikhilds/Python | Day 4/Day_4_name_selecter.py | Day_4_name_selecter.py | py | 430 | python | en | code | 0 | github-code | 1 |
38833961809 | # Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer,
# or a list -- whose elements may also be integers or other lists.
def depthSum(nestedList):
def dfs(array, depth):
nonlocal sumDepth
for item in array:
... | VJ-P/Daily-Leetcode | March-2020/depthSum.py | depthSum.py | py | 570 | python | en | code | 0 | github-code | 1 |
26308582150 | from flask.views import MethodView
from flask_jwt_extended import jwt_required
from flask_smorest import Blueprint, abort
from db import db
from Models import NoteModel, CategoryModel
from schemas import NoteSchema, NoteQuerySchema, CategorySchema
from sqlalchemy.exc import IntegrityError
blp = Blueprint("note", __na... | NATASHKAS/backlab1 | resources/NOTES.py | NOTES.py | py | 1,775 | python | en | code | 0 | github-code | 1 |
676494821 | '''
rate limit problem
'''
accepted_ip_addresses = []
accepted_time_stamps = []
def accept_or_reject(time_stamps, ip_addresses, limit, lower_ts_threshold, ip_address, time_stamp):
'''
Decision making function
'''
count = 0
for i,j in zip(ip_addresses, time_stamps):
if j >= lower_ts_thresho... | sanjeevik89/CodingPuzzles | RateLimitProblem/rate_limit.py | rate_limit.py | py | 1,337 | python | en | code | 0 | github-code | 1 |
2494095628 | import bson
import ujson
from bson import ObjectId
from .utils import db
def retrieve_info(object_id):
# Retrieve info from DB
mongo = db.MongoDBConnection()
result = list()
with mongo:
database = mongo.connection['mydb']
collection = database['registrations']
if object_id i... | zouhanrui/AWS_Serverless_CRUD_MongoDB | Organizations_pkg/user/read/app.py | app.py | py | 2,040 | python | en | code | 0 | github-code | 1 |
4200405665 | def solution(s):
answer = []
result = []
dic = {}
# 아이디어
# 1. 문자열 s를 {}별로 쪼개서 리스트에 넣는다.
# 2. 해당리스트를 오름차순 정렬한다.
# 3. 하나씩 꺼내면서 딕셔너리에 들어가는 값을 결과 리스트에넣는다.
arr = []
tmp = ''
open_mark = False
for i in range(1,len(s)-1):
if s[i] == '{':
arr = []
tmp = ''
... | hyeonwook98/Algorithm | Programmers/튜플.py | 튜플.py | py | 1,039 | python | ko | code | 0 | github-code | 1 |
25768257990 | config = {
# Dollar-Cost Averaging config
'SYMBOL': 'AAPL', # Stock symbol, string type
'ALLOCATION': 200, # Amount of money to allocate for each DCA in USD, int type
# config for TD
'TD_ID': '', # TD Ameritrade Account ID, string type
'TD_ACCESS_TOKEN': '', # Access Token, str... | Joash-JW/Auto-DCA | config_template.py | config_template.py | py | 1,264 | python | en | code | 10 | github-code | 1 |
32396154456 | import scipy.stats as sts
import argparse
import pandas as pd
import glob
def ParseArguments():
parser = argparse.ArgumentParser(description="Kolmogorov–Smirnov test")
parser.add_argument('--input-file', default="generated_numbers.pkl", required=False, help='input file (default: %(default)s)')
parser.add_a... | lorek/ZPS2021 | scripts/z3KStest.py | z3KStest.py | py | 2,157 | python | en | code | 0 | github-code | 1 |
9519485154 | from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from ..models import Posts
from django.db.models import Q, Count
def index(request, category=None):
page = request.GET.get('page', '1') # 페이지를 읽어온다. 없을경우 1을 뱉는다 ?page =
kw = request.GET.get('kw', '') # 검색어
... | Ksiyeong/MyDiary | main/views/base_views.py | base_views.py | py | 2,242 | python | en | code | 0 | github-code | 1 |
74390632034 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import random
# min-max 归一化
def normalization(data):
_range = np.max(data) - np.min(data)
return (data - np.min(data)) / _range
# 加载数据
def load_data(file_name):
df = pd.read_csv(file_name)
print('read csv data sha... | hello2mao/Learn-MachineLearning | StatisticalLearning/LogisticRegression/SimpleDemo/main.py | main.py | py | 2,651 | python | en | code | 1 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.