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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
37273642245 | import rosbag
import sys
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import csv
import glob
import os
from tf.transformations import euler_from_quaternion
from scipy.interpolate import interp1d
from scipy.spatial.transform import Rotation as R
import numpy as np
if (len(s... | ZiyouZhang/rotors_datmo | scripts/bag_analysis.py | bag_analysis.py | py | 13,599 | python | en | code | 4 | github-code | 6 |
24429656200 | # Isaiah Grace
# May 13 2020
import colorsys
import random
import rpi_ws281x
import threading
class StripDriver():
def __init__(self, config):
self.strip = rpi_ws281x.PixelStrip(
config['COUNT'],
config['PIN'],
config['FREQ_HZ'],
config['DMA'],
... | IsaiahGrace/lightRemote | pi/stripDriver.py | stripDriver.py | py | 7,953 | python | en | code | 0 | github-code | 6 |
5539453892 | import cv2
import numpy as np
"""
YUV란?
빛의 밝기를 나타내는 휘도(Y)와 색상신호 2개(U, V)로 표현하는 방식이다.
The Y′UV model defines a color space in terms of one luma component (Y′) and
two chrominance components, called U (blue projection) and V (red projection) respectively.
Y = 0.299R + 0.587G + 0.114B
"""
src = cv2.imread('../resou... | daebakk/Image-Processing | Assignment/Fundamentals of Image processing/BGRToY.py | BGRToY.py | py | 794 | python | en | code | 0 | github-code | 6 |
7755753027 | from __future__ import absolute_import
from __future__ import unicode_literals
import argparse
from .. import api, utils
from ..command import Command, CMD_SUCCESS, HELP_LIST
from ..exceptions import InvalidDateError, NotFoundError, WrappedValueError
class Log(Command):
"""List enrollment information available ... | timhayduk/glusterDashboard | gitlab/lib/python3.5/site-packages/sortinghat/cmd/log.py | log.py | py | 4,198 | python | en | code | 1 | github-code | 6 |
32672095851 | #!python
import collections
#text=haystack, pattern=needle
def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
#fu... | ckim42/Core-Data-Structures | Lessons/source/strings.py | strings.py | py | 3,840 | python | en | code | 0 | github-code | 6 |
70096885309 | from collections import deque
def solution(progresses, speeds):
progresses = deque(progresses)
speeds = deque(speeds)
answer = []
while progresses:
count = 0
for i in range(len(speeds)):
progresses[i] += speeds[i]
while True:
if progresses[0] < 100:
... | YooGunWook/coding_test | 프로그래머스_복습/스택_기능개발.py | 스택_기능개발.py | py | 697 | python | en | code | 0 | github-code | 6 |
24958905519 | import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class SwitchNode(Node, ArmLogicTreeNode):
'''Switch node'''
bl_idname = 'LNSwitchNode'
bl_label = 'Switch'
bl_icon = 'CURVE_PATH'
min_inputs = 1
min_outputs = 1
def __init__(... | phillipmacon/armory-3d-engine | blender/arm/logicnode/logic_switch.py | logic_switch.py | py | 1,162 | python | en | code | 0 | github-code | 6 |
19663543751 | import tensorflow as tf, numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from baselines.bench.monitor import load_results
logger_dir = '/home/lihepeng/Documents/Github/tmp/ev/cpo/train'
df_train = load_results(logger_dir)
logger_dir =... | liudading/tmp | ev/plot_d.py | plot_d.py | py | 5,409 | python | en | code | 0 | github-code | 6 |
6642507334 | from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializer import perfil_usuarioSerializer
from .models import perfil_usuario
@api_view(['GET', 'POST'])
def lista_usuarios(request):
if request.method == 'GET':
users = perfi... | MarcoToloza/Caso_A_Parte-2-API | Api_qr/AppPi/views.py | views.py | py | 1,057 | python | en | code | 0 | github-code | 6 |
29462931299 | from evdev import ecodes
from datetime import datetime, timedelta
from four_button_pages import StaticMenu, TokenEntryMenu, PAYGStatusMenu, ServiceMenu
class FourButtonUserInterface(object):
BACKLIGHT_TIMEOUT = 300
def __init__(self, lcd, conn, kbd, static_pages):
self.conn = conn
self.disp ... | victronenergy/dbus-characterdisplay | four_button_ui.py | four_button_ui.py | py | 4,511 | python | en | code | 0 | github-code | 6 |
3066916179 | tokens = "this is a decent enough test sentence".split(" ")
cap = len(tokens)
degree = 2
for ti in range(cap):
lower = ti if ti < degree else degree
upper = cap - ti -1 if ti >= cap - degree -1 else degree
# the -1 is because (range(1, 1) won't run once for 1
for i in range(upper):
print(i, ti... | sendakvmahr/c_sea | text/one-shots/test iterationing.py | test iterationing.py | py | 395 | python | en | code | 0 | github-code | 6 |
12100401616 | '''
Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is taht the frist and lsat ltteers be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey ... | Shaywei/MyDevTools | Python/misc/mock_iterview_quinn.py | mock_iterview_quinn.py | py | 1,757 | python | en | code | 0 | github-code | 6 |
22648817021 | import matplotlib.pyplot as plt
from scipy.io import loadmat
import numpy as np
import pandas
from os.path import join,exists
from os import mkdir
import cv2
import math
import os
rho = 1
actions = ['No-Action', 'sweeping', 'gargling', 'opening cupboard', 'washing hands', 'eating', 'writing', 'wiping',
'dr... | Vincent-Fer/activity-recognition-prediction-online | encodage/encodage.py | encodage.py | py | 11,449 | python | en | code | 0 | github-code | 6 |
71484029308 | def parser(l, r):
if all(S[i].isdigit() for i in range(l, r + 1)):
return int(S[l:r + 1]) // 2 + 1
ret = []
cnt = 0
start = 0
for i in range(l, r + 1):
if S[i] == '[':
cnt += 1
if cnt == 1:
start = i
elif S[i] == ']':
if cnt... | knuu/competitive-programming | aoj/11/aoj1188.py | aoj1188.py | py | 543 | python | en | code | 1 | github-code | 6 |
18349597036 | #To Calcculate the Roots for Quadratic Equation
import cmath
num1 = int(input("Enter the first number:"))#Take three numbers from user as num1,num2,num3
num2 = int(input("Enter the Second number:"))
num3 = int(input("Enter the Third number:"))
def Quadratic(num1, num2, num3):#Defining function
delta = (num2 ** ... | MayuriTambe/FellowshipPrograms | Quadratic.py | Quadratic.py | py | 699 | python | en | code | 1 | github-code | 6 |
25815068031 | import csv
from utils import DateCounter
def pad(filename: str):
#---------------read_in---------------
data = []
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
data.append(row)
#---------------padding---------------
newdata = []
... | UX404/Financial-data-processing | data_process/padding.py | padding.py | py | 1,068 | python | en | code | 0 | github-code | 6 |
21952104219 | import itertools
import logging
from django.conf import settings
from django.core.management.base import BaseCommand
from autoslug.utils import slugify
from rainboard.models import (
Forge,
Namespace,
Project,
Robotpkg,
update_github,
update_gitlab,
)
class Command(BaseCommand):
help = ... | Gepetto/dashboard | rainboard/management/commands/project.py | project.py | py | 2,763 | python | en | code | 0 | github-code | 6 |
29224887814 | """ Plot cross-section profile: Multiple cross-sections
"""
import sys
sys.path.append('/home/zhouyj/software/seis_view')
import numpy as np
import matplotlib.pyplot as plt
from reader import read_ctlg, slice_ctlg
import warnings
warnings.filterwarnings("ignore")
# i/o paths
fctlg = 'input/catalog_example.csv'
title =... | ali4413/Seismicity-Visualization | Python/plot_prof_multi-cross-sec.py | plot_prof_multi-cross-sec.py | py | 3,432 | python | en | code | null | github-code | 6 |
74471480187 | #SpinLIne.py
import turtle as tt
import time
tt.pensize(2)
tt.bgcolor("black")
colors = ['red','yellow','purple','blue']
tt.tracer(False)
for x in range(400):
tt.forward(10*x)
tt.color(colors[x%4])
tt.left(95)
tt.tracer(True)
time.sleep(10) | izhiman/python-learning | Python-basic/basic-week1/SpinLIne.py | SpinLIne.py | py | 243 | python | en | code | 0 | github-code | 6 |
32187914747 | # 백준 - 9012번 괄호
n = int(input()) # 숫자 입력
for _ in range(n): # 입력한 숫자만큼 range를 돌려준다.
stack = [] # 데이터를 집어넣어준 stack을 만들어준다.
vpss = input() # 예를 들어, (())()가 들어가게 된다.
for vps in vpss: # (())()가 for문을 사용해서 한개씩 들어가게 된다.
if vps == '(': # 만약에 (가 나오게 되면 append
stack.append(vps)
elif vps == ')': # 만약에 )가 나오... | kcw0331/python-for-coding-test | baekjoo/9012.py | 9012.py | py | 890 | python | ko | code | 0 | github-code | 6 |
39671957475 | """ Класс для работы с контестами """
import os
import re
import json
import string
import shutil
import configparser, itertools
from collections import OrderedDict
from bs4 import BeautifulSoup
from mysite import settings
from .models import Cntsregs, Logins, Contests, Problems
from problems.classes import ProblemsCre... | Raftor74/ejudge-web-app | contests/classes.py | classes.py | py | 19,662 | python | ru | code | 0 | github-code | 6 |
20913974107 | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_... | almazuulu/BookCatalogue | bookcatalogue/bookcatalogue/urls.py | urls.py | py | 1,502 | python | en | code | 0 | github-code | 6 |
37158413403 | from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
data = load_iris()
X = data.data
X[:, 0] /= 2.54
X[:, 1] /= 100
def scikit_pca(X):
X_std = StandardScaler().fit_transform(X)
sklearn_pca = PCA(n_compone... | QiliWu/Python-datavis | datavis/PCA.py | PCA.py | py | 668 | python | en | code | 2 | github-code | 6 |
32802746456 |
import gensim
import gensim.downloader as api
from gensim.models import Word2Vec as w2v
import inspect
import logging
import warnings
import numpy as np
from sklearn import *
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics.pairwise import pairwise_distances
import os
... | d4g10ur0s/InformationRetrieval_21_22 | paradotea/erwthma_4.py | erwthma_4.py | py | 9,321 | python | en | code | 0 | github-code | 6 |
16627798046 | from flask import Flask, request
import json
app = Flask(__name__)
# create python dictionary to hold user data
user_account = {
1:
{"first_name": 'betty',
"last_name": 'joy',
"phone_number": '0493827405',
"email_address": 'bettyjoy@accounts.com'
}
}
user_count = 1
... | rikiapst/cephaloPy | user.py | user.py | py | 995 | python | en | code | 0 | github-code | 6 |
8717492636 | from .. import Connector
from ..libs.Connection import Connection
class SICS(Connector):
"""
Mettler Toledo Standard Interface Command Set
Commands:
- '1': self.get_weight,
- '2': self.get_info
"""
def __init__(self, config: dict):
super(SICS, self).__init__(config)
self.... | SmartBioTech/DeviceControl | app/workspace/devices/MettlerToledo/classes/SICS.py | SICS.py | py | 1,518 | python | en | code | 2 | github-code | 6 |
30728525190 | r, c = [int(x) for x in input().strip().split()]
#print( sum([x*x for x in [1,4,2,9,7]]))
def prime(n):
P = [1,2]
k = 3
while len(P) < n:
is_prime = True
for j in P[1:]:
if k % j == 0 :
is_prime = False
break
elif j*j... | mdaw323/alg | codeforces/1266/c.py | c.py | py | 575 | python | en | code | 0 | github-code | 6 |
26833816694 | # https://pypi.org/project/firebirdsql/
# pip install firebirdsql
import firebirdsql
from decouple import config
# pip install mysql-connector-python
import mysql.connector
import re
import os
try:
# Mysql Local
# con_mysql = mysql.connector.connect(
# host=config("host"),
# user=config("user... | sistemadevsys/db_firebird_mysql | update_clientes.py | update_clientes.py | py | 1,549 | python | en | code | 0 | github-code | 6 |
8757517027 | from urllib3.exceptions import ProtocolError, ReadTimeoutError
import tweepy
import dataset
import json
from tweepy import StreamListener
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from textblob import TextBlob
from models import *
import pandas as pd
import numpy as np
from config import *
e... | paulinaczheng/twitter_flu_tracking | twitter_package/tweet-stream.py | tweet-stream.py | py | 6,168 | python | en | code | 11 | github-code | 6 |
40095183195 | from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from datetime import datetime
from Tecnocasa.tecnocasa_main import scrape_tecnocasa_url
default_args = {
'start_date': datetime(2023, 1, 1),
'retries': 1,
}
dag = DAG... | pasqualepescina/AIHome | dags/dag.py | dag.py | py | 630 | python | en | code | 0 | github-code | 6 |
6942872733 | #!/usr/bin/env python3
import rospy
from ros_assignment.srv import ComputeAngVel, ComputeAngVelResponse
from std_msgs.msg import Float64
def compute_ang_vel_server(req):
# Assuming linear velocity of 0.1
linear_velocity = 0.1
radius = req.radius
# Compute angular velocity using v = ω * r
angular_v... | Suraj945gh/Antariksh | ros_assignment/scripts/compute_ang_vel_server.py | compute_ang_vel_server.py | py | 642 | python | en | code | 0 | github-code | 6 |
11120230113 | def vowel_remover(text):
vowels = ('a', 'e', 'i', 'o', 'y', 'A', 'E', 'I', 'O', 'Y', 'U') #I consider y as a vowel
for char in text:
if char in vowels:
text = text.replace(char, '')
return text
with open('aaa.txt', 'r') as myfile:
words = myfile.read().... | GiorgosMeg/Python_University | askhsh1.py | askhsh1.py | py | 1,749 | python | en | code | 0 | github-code | 6 |
15125626664 | from data_higher_lower import data
from art_higher_lower import logo, vs
from random import choice
from functions_higher_lower import check_followers
updated_data = data
a_card = choice(list(updated_data))
updated_data.remove(a_card)
should_continue = True
print(logo)
score = 0
while should_continue:
b_card = ch... | Tulip2MF/100_Days_Challenge | day_014/higher_lower_main.py | higher_lower_main.py | py | 1,153 | python | en | code | 0 | github-code | 6 |
17961034725 | from flask import render_template, redirect, url_for, request
from surv import app
from .storage import c, new_game, save_game, load_game
@app.route('/')
def home():
return redirect(url_for('new'))
@app.route('/new/')
def new():
new_game()
return redirect(url_for('list'))
@app.route('/list/')
def list():... | pkugelmass/survivor | surv/routes.py | routes.py | py | 1,892 | python | en | code | 0 | github-code | 6 |
71484374588 | N = int(input())
A = [int(x) for x in input().split()]
ret = 0
for state in range(1 << N):
flag = False
ans = 1
for i in range(N):
if (state >> i & 1):
if A[i] % 2 == 1:
flag = True
ans *= 2
else:
if A[i] % 2 == 0:
flag = Tr... | knuu/competitive-programming | atcoder/corp/cf17_qc_b.py | cf17_qc_b.py | py | 366 | python | en | code | 1 | github-code | 6 |
72531854269 | from typing import Final
import sqlalchemy as sa
def column_created_datetime(*, timezone: bool = True) -> sa.Column:
return sa.Column(
"created",
sa.DateTime(timezone=timezone),
nullable=False,
server_default=sa.sql.func.now(),
doc="Timestamp auto-generated upon creation",... | ITISFoundation/osparc-simcore | packages/postgres-database/src/simcore_postgres_database/models/_common.py | _common.py | py | 2,235 | python | en | code | 35 | github-code | 6 |
18537342899 | # prob_link: https://www.codingninjas.com/codestudio/problems/job-sequencing-problem_8230832?challengeSlug=striver-sde-challenge&leftPanelTab=0
def jobScheduling(jobs):
maxi = 0
for t, profit in jobs:
maxi = max(maxi, t)
maxi += 1
flag = [0] * maxi
jobs.sort(key=lambda x: x[1], revers... | Red-Pillow/Strivers-SDE-Sheet-Challenge | P45_Job_Sequencing_Problem.py | P45_Job_Sequencing_Problem.py | py | 521 | python | en | code | 0 | github-code | 6 |
1124184800 | palavra1 = input()
palavra2 = input()
for i in list(range(len(palavra2))):
contador = 0
for j in list(range(len(palavra1))):
if palavra1[j] == palavra2[i]:
if contador > 0:
print(" ", end = "")
print(j, end = "")
contador += 1
x = (len(palavra2)-... | vitorbarbosa123/lp1-python | Semana4/indices/indices.py | indices.py | py | 390 | python | pt | code | 0 | github-code | 6 |
20146094706 | from datetime import datetime, timedelta
from tqdm import tqdm
import aiohttp
import asyncio
from pymongo import MongoClient
from private import royale_token
client = MongoClient('mongodb://localhost:27017/')
MAX_TROPHIES = "Соперник(и) с наибольшим количеством кубков:"
MAX_BEST_TROPHIES = "Соперник(и) с наибольши... | dfomin/clashroyaledata | data_analyzer.py | data_analyzer.py | py | 8,146 | python | en | code | 0 | github-code | 6 |
5635045727 | import time
import socket
import struct
from collections import deque
class ClientClass:
def __init__(self, clientID, connection, addr):
self.clientID = clientID
self.addr = addr
self.clientSocket = connection
self.UDPAddr = None
self.name = ""
self.lastPacket = time... | LogFlames/WandAndSwordServer | zombie hunt server/clientClass.py | clientClass.py | py | 672 | python | en | code | 0 | github-code | 6 |
16496474868 | import re
def calculate_profanity_degree(tweet, racial_slurs):
words = re.findall(r'\b\w+\b', tweet.lower())
total_words = len(words)
profanity_count = 0
for word in words:
if word in racial_slurs:
profanity_count += 1
return profanity_count / total_words if total_words > 0 e... | nameisvid/ebank | index.py | index.py | py | 738 | python | en | code | 0 | github-code | 6 |
75149559227 | """
Question 13
Level 2
Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3
Hints: In case of input data being supplied to the question, it should be a... | BYN13K/Learning | zhiwehu_Python_exercises/Q13.py | Q13.py | py | 519 | python | en | code | 0 | github-code | 6 |
8561287023 | import requests
import json
from typing import Dict, List
from config.config_secret import secret_file_path
class Auth:
@classmethod
def get_secret(cls, secret_types: List[str]) -> Dict[str,str]:
"""json 파일로부터 요구되는 시크릿키 목록을 읽어 반환한다.
Args:
secret_types : 요구되는 시크릿 키 이름들을 담은 배열
... | Ywoosang/Dossa-Notification | app/auth/auth.py | auth.py | py | 4,905 | python | ko | code | 0 | github-code | 6 |
40276685615 | import gc
import machine
import time
import dht
import network
import urequests
from umqttsimple import MQTTClient
import ubinascii
import micropython
import esp
from boot import ip
sensor23 = dht.DHT22(machine.Pin(23))
sensor23.measure()
client_id = ubinascii.hexlify(machine.unique_id())
client_id_str = ubinascii.h... | andrevdm/dht_sensor | esp/main.py | main.py | py | 2,028 | python | en | code | 0 | github-code | 6 |
20831019932 | from django.urls import path
from posts.views import *
urlpatterns = [
path("", MainPage.as_view(), name="main"),
path("follow_post/", FollowPost.as_view(), name="follow_post"),
path("posts/<int:user_id>/", PostByUserId.as_view(), name="post"),
path("posts/view_post/<int:post_id>", ViewPost.as_view()... | YevheniiMorozov/social | gramm/posts/urls.py | urls.py | py | 632 | python | en | code | 0 | github-code | 6 |
14958626079 | # -*- coding: utf-8 -*-
from datetime import datetime, date
import logging
import re
ERROR_PARSING_DATE = "Error parsing date"
def from_iso_format(string):
parts = [int(a) for a in string.split("-")]
if len(parts) != 3:
raise ValueError
return date(parts[0], parts[1], parts[2])
def datetime... | getyoti/yoti-python-sdk | yoti_python_sdk/date_parser.py | date_parser.py | py | 1,157 | python | en | code | 9 | github-code | 6 |
19024426652 | from enum import Enum
from typing import Union
from typing import NamedTuple
from typing import Callable
class TaskType(Enum):
"""Type of machine learning task
Attributes
----------
MULTI_CLASS_CLASSIFICATION
multi-class classification
MULTI_LABEL_CLASSIFICATION
multi-label classi... | DanRuta/xva-trainer | lib/_dev/pyannote/audio/train/task.py | task.py | py | 5,402 | python | en | code | 78 | github-code | 6 |
30859953212 | import configparser
import pandas as pd
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, dayofweek, date_format
import pyspark.sql.functions as F
from pyspark.sql.types imp... | yashth/Data_Lake | etl.py | etl.py | py | 7,406 | python | en | code | 0 | github-code | 6 |
3323951129 | #!/usr/bin/python
import os
import re
import math
import matplotlib.pyplot as plt
import numpy
from numpy import sin, pi, arange
import astropy.io
from astropy.io import fits
from PIL import Image
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# This script contrasts photon index and l... | aprilcotwut/photon_index_binning | compare_bin.py | compare_bin.py | py | 15,988 | python | en | code | 0 | github-code | 6 |
563107290 | import re
#dictionary for rule mapping such that each rule by id maps to class label
rule_dict={}
rule_dict[0]=1 #location , key is rule ID and value is Label id. here it means rule 1 labels example as location
rule_dict[1]=5 #Cuisine
rule_dict[2]=1 #Location
rule_dict[3]=4 #Price
rule_dict[4]=8 #Rating
rule_dict[5]=2 ... | yueyu1030/COSINE | data/mitr/rules.py | rules.py | py | 10,114 | python | en | code | 197 | github-code | 6 |
39269918095 | import copy
import os
import shlex
import sys
import textwrap
from functools import wraps
def bash_quote(w, quote):
'''
Quote word *w* with quote character *quote* which may be empty, single quote or double quote.
'''
assert quote in ('', '"', "'")
if quote == "'":
w = w.replace("'", quote... | 1and1/dim | ndcli/dimcli/cliparse.py | cliparse.py | py | 19,558 | python | en | code | 39 | github-code | 6 |
28021381750 | name_of_file = input("Введите имя файла для анализа")
name_of_file += '.txt'
amount = 0
with open(name_of_file, 'r') as file:
lines = file.readlines()
for line in lines:
amount += int(line)
print("Общая сумма у нас состоявляет", amount)
print("Среднее у нас получается: ", amount/len(lines))
| isakura313/01_2_2 | files/all_sum.py | all_sum.py | py | 389 | python | ru | code | 0 | github-code | 6 |
16748915300 | #!/usr/bin/python3
"""This is a function that prints stuffies"""
def say_my_name(first_name, last_name=""):
"""This functions does the printing
Args:
first_name (string)
last_name (string)
Raises:
TypeError: when the names aren't a string
"""
if not isinstance(first_nam... | Mourad-Azouga/alx-higher_level_programming | 0x07-python-test_driven_development/3-say_my_name.py | 3-say_my_name.py | py | 526 | python | en | code | 0 | github-code | 6 |
29479738416 | # https://leetcode.com/problems/find-all-duplicates-in-an-array/description/
#Time: O(n), Space: O(N)
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
lst = []
hashMap = {}
for num in nums:
if num not in hashMap:
hashMap[num] = 0
... | Suraj7879/-CrackYourInternship | Day2/4.py | 4.py | py | 424 | python | en | code | 0 | github-code | 6 |
25262905175 | import datetime
import logging
from concurrent import futures
from google.appengine.ext import ndb
from upvote.gae.bigquery import tables
from upvote.gae.datastore.models import exemption as exemption_models
from upvote.gae.datastore.models import host as host_models
from upvote.gae.datastore.models import policy as... | google/upvote_py2 | upvote/gae/lib/exemption/api.py | api.py | py | 21,555 | python | en | code | 449 | github-code | 6 |
71344819069 | #sets não permitem valores duplicados
numeros = set([1,2,1,3,3,4,5,2,6]) #valido somente 1,2,3,4,5,6
carros = set(('palio','gol','celta','palio'))#valido somente palio,gol,celta
print(numeros)
print(carros)
#Unindo conjuntos com union
conjunto_a = {1,2}
conjunto_b = {3,4}
print(conjunto_a.union(conjunto_b))
#Adi... | Dnx0/trilha-python-dio | conjuntos.py | conjuntos.py | py | 538 | python | pt | code | 1 | github-code | 6 |
22388129127 | import pygame
# Initialize pygame
pygame.init()
# Set up window
size = (400, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Circle Line")
# Set up colors
WHITE = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
click_sound = pygame.mixer.Sound("clicked_sound.mp3")
# Set up circles
circle_ra... | Vormamim/boxes | matrix_stage3.py | matrix_stage3.py | py | 2,268 | python | en | code | 1 | github-code | 6 |
18910107031 | # -*- coding: utf-8 -*-
"""
Created on Tue May 24 18:36:51 2022
@author: User
"""
# -*- coding: utf-8 -*-
"""
Created on Thu May 19 20:12:51 2022
@author: User
"""
import urllib.request
# pretty-print python data structures
from pprint import pprint
from nsetools import Nse
from nsepy import get_history
from html_t... | karthickbmca/Trade_code | rough.py | rough.py | py | 6,475 | python | en | code | 0 | github-code | 6 |
71150102587 | def solution(start, length):
checksum = 0
l = length
while l:
checksum^=xor_sum(start)^xor_sum(start+l)
start+=length
l-=1
return checksum
def xor_sum(n):
if n == 0:
return 0
elif (n-1) % 4 == 0:
return n-1
elif (n-1) % 4 == 1:
return 1
el... | leander-dsouza/Google_Foobar_2020 | Level 3/queue-to-do/solution.py | solution.py | py | 383 | python | en | code | 4 | github-code | 6 |
71903724669 | # -*- coding: utf-8 -*-
from .core import *
from .. import _logging as logging
import tensorflow as tf
__all__ = [
'StackLayer',
'UnStackLayer',
]
class StackLayer(Layer):
"""
The :class:`StackLayer` class is layer for stacking a list of rank-R tensors into one rank-(R+1) tensor, see `tf.stack() <ht... | feilab-hust/VCD-Net | vcdnet/tensorlayer/layers/stack.py | stack.py | py | 3,434 | python | en | code | 25 | github-code | 6 |
14761591721 | import os
from twisted.internet import reactor, defer
def read_mail(mailitems):
print(mailitems)
return "Junk Mail... Sending to shredder: " + mailitems
def shred_mail(mailitems):
print('buzzzzz: ' + mailitems)
os.remove('mail')
reactor.stop()
def create_mail(msg):
with open("mail","w") as f:... | mina32/APT_Black | mailExample/mailPolling.py | mailPolling.py | py | 826 | python | en | code | 0 | github-code | 6 |
30056444826 | import re
from collections import defaultdict
def parse_rule_container(rule):
regex = re.compile(r'(.*) bags contain(.*)')
matches = regex.match(rule)
return matches.group(1), matches.group(2)
def parse_contained_rule(rule):
regex = re.compile(r'((\d+) ([a-z ]+) bag)+')
all_matches = regex.finda... | nithish-thomas/adventOfCode2020 | aoc20/day7/day7_1.py | day7_1.py | py | 1,700 | python | en | code | 0 | github-code | 6 |
24529853326 | import numpy as np
import torch
import torch.nn as nn
from lib.datasets.utils import class2angle
from utils import box_ops
import math
padsize = np.array([28.,11.],dtype=np.float32)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def affine_transform(pt, t):
new_pt = np.array([pt[0], pt[1... | HIYYJX/MonoGAE | lib/helpers/decode_helper.py | decode_helper.py | py | 10,233 | python | en | code | 4 | github-code | 6 |
40974269745 | import numpy
import os
numpy.seterr('ignore')
luz = int(300000000)
while True:
inicio = input("¿que deseas?(entrar, salir o limpiar): \n>")
print ("")
if inicio == "entrar" or inicio == "enter":
opcion = input("elige la magnitud(energia, fuerza o recorrido): \n>")
if opcion == "energia" or opcion == ... | infra-determista/calculadora-relativista | Calculadora-relativista.py | Calculadora-relativista.py | py | 3,349 | python | es | code | 0 | github-code | 6 |
36010827079 | import json
import serial
import numpy as np
class CameraMLX90640(serial.Serial):
"""
Implements communications camera_mlx90640_firmware
"""
FRAME_HEIGHT = 24
FRAME_WIDTH = 32
def __init__(self, port):
self.port_param = {'port': port, 'baudrate': 115200, 'timeout': 2.0}
super(... | willdickson/camera_mlx90640 | camera_mlx90640/camera_mlx90640.py | camera_mlx90640.py | py | 1,876 | python | en | code | 0 | github-code | 6 |
29951489140 | from .base import Shape
class Circle(Shape):
def __init__(self, radius, **kwargs):
super().__init__(**kwargs)
self.radius = radius
def draw(self, turtle):
turtle.penup()
turtle.goto(self.center_x, self.center_y - self.radius) # From docs: The center is radius units left of t... | disulfiram/SoftUni-PythonProgramming | 06 Python OOP/01 Shape Extension/Shapes/circle.py | circle.py | py | 424 | python | en | code | 0 | github-code | 6 |
41814241194 | from django.shortcuts import render, get_object_or_404
from django.http import Http404
from .models import Question
# Create your views here.
def index(request):
try:
latest_question_list = Question.objects.order_by('pub_date')[:5]
except Question.DoesNotExist:
raise Http404('Question does ... | Vladimir-vut/django_mysite | mysite/pools/views.py | views.py | py | 1,074 | python | en | code | 0 | github-code | 6 |
36947412448 | from functools import partial
from random import shuffle
from kivy.clock import Clock
from kivy.app import App
from kivy.lang import Builder
import ani_property
ani_property.install()
KV_CODE = r'''
GridLayout:
rows: 4
cols: 4
padding: 20
spacing: 20
'''
def shuffle_children(widget, dt):
childr... | gottadiveintopython/ani-property | examples/magnet.py | magnet.py | py | 1,011 | python | en | code | 0 | github-code | 6 |
11342650070 | # -*- encoding: utf-8 -*-
import requests
from scdl import CLIENT_ID
class Client():
def get_collection(self, url, token, maxpage):
params = {
'client_id': CLIENT_ID,
'linked_partitioning': '1',
}
if token:
params['oauth_token'] = token
resourc... | jz1/scdl | scdl/client.py | client.py | py | 1,399 | python | en | code | null | github-code | 6 |
29906192183 | # ***** BEGIN GPL LICENSE BLOCK *****
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distribute... | meshonline/Surface-Heat-Diffuse-Skinning | addon/surface_heat_diffuse_skinning/__init__.py | __init__.py | py | 14,549 | python | en | code | 170 | github-code | 6 |
10812461830 | # -*- coding: utf-8 -*-
import os
from sys import path
from django.conf.global_settings import (TEMPLATE_CONTEXT_PROCESSORS,
STATICFILES_FINDERS)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
path.append(os.path.join(BASE_DIR, 'apps'))
SECRET_KEY = '_c#^&2xzwd@xt@i2b... | andreyshipilov/wknd_django | wknd_project/settings/common.py | common.py | py | 2,378 | python | en | code | 1 | github-code | 6 |
40899444822 | """DeviceManagement URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | BensonXiong/DeviceManagement | DeviceManagement/DeviceManagement/urls.py | urls.py | py | 1,371 | python | en | code | 0 | github-code | 6 |
19593396615 | import h5py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from mpl_toolkits.mplot3d import Axes3D
from sklearn.metrics import roc_auc_score, roc_curve
import numpy as np
from tensorflow.keras import datasets, layers, models
from sklearn.metrics import confusion_matrix
... | Yoichiro-Y/oc-nn-ensemble | .history/mnist_20221216201506.py | mnist_20221216201506.py | py | 1,596 | python | en | code | 0 | github-code | 6 |
34253272584 | from flask_app.config.mysqlconnection import connectToMySQL
from flask import flash
from flask import re # the regex module
# create a regular expression object that we'll use later
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class User:
def __init__( self , data ):
self.... | gerald-cakoni/PythonAssignments | flask_mysql/validation/dojo_survey/flask_app/models/user.py | user.py | py | 2,765 | python | en | code | 0 | github-code | 6 |
23555067153 | #!/usr/bin/python3
import numpy, tqdm, json, os, random
import scipy.signal
import util
import speech_features
RATE = 8000
NUMCEP = 16
CLASSES = 45
LENGTH = 4000
DELTA = 2000
LABEL_SCALE = 100
LABEL_SAVE_JSON = "switchboard-labels.json"
OUT_FILE = "melspecs-switchboard.npy"
EMPTY = "<EMPTY>"
SIL = "SIL"
SIL_DROPO... | ychnlgy/Switchboard2.0 | src/load.py | load.py | py | 5,989 | python | en | code | 0 | github-code | 6 |
24370174876 | import unittest
import matplotlib.pyplot as plt
class TestCreateParticles(unittest.TestCase):
def test_create_particles(self):
from src.dataio import GridIO, FlowIO
from src.create_particles import Particle, LaserSheet, CreateParticles
# Read-in the grid and flow file
grid = GridI... | kalagotla/syPIV | test/test_create_paritcles.py | test_create_paritcles.py | py | 2,496 | python | en | code | 0 | github-code | 6 |
16103320682 | # 8*8 + 입력좌표에 대해 검사하는 기능 만들기
n, m = map(int, input().split());
arr = list();
for i in range(0, n):
arr.append(input());
rtn2 = 64;
flag = 0;
for y0 in range(0, n - 8 + 1):
for x0 in range(0, m - 8 + 1):
rtn = 0;
for y in range (0, 8):
for x in range(0, 8):
if arr[y0 + y][x0 + x] == 'W' and flag ... | hynoes/baekjoon | bj1018s5.py | bj1018s5.py | py | 545 | python | en | code | 1 | github-code | 6 |
72109396027 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().run_line_magic('pylab', 'inline')
import pandas
import seaborn
# # Load CSV file into memory
# In[2]:
data = pandas.read_csv('~/Documents/python/uber-raw-data-apr14.csv')
# In[3]:
data.tail()
# #convert datetime and insert coloumn
# In[4]:
dt... | dennyalfani/Learn_data_analys | Data Visualisation/Uber/data analysis uber.py | data analysis uber.py | py | 3,244 | python | en | code | 0 | github-code | 6 |
18481146182 | import time
t1 = time.time()
def divn(num):
l = []
arr = [1,2,3,4,5,6,7,8,9]
for i in range(2,int(num**0.5)+1):
b = num%i
if b == 0:
rem = int(num/i)
g = [int(i) for i in list(str(num) + str(rem) + str(i))]
if len(g) == 9:
res = [x for x ... | BreadBug007/Project-Euler | Prob_32.py | Prob_32.py | py | 798 | python | en | code | 0 | github-code | 6 |
24488924931 | from serre_biblio import *
from toit import Toit
from uselect import poll, POLLIN
from machine import Pin, ADC
from time import sleep, ticks_ms
try:
import usocket as socket
except:
import socket
toit = Toit( )
# ============================================================================= b_poussoir (...)
bp_fl... | SoproLab/MiniSerre | main_MiniSerre.py | main_MiniSerre.py | py | 3,626 | python | fr | code | 0 | github-code | 6 |
2310558186 | import requests
import os
from requests_oauthlib import OAuth2Session
from dotenv import load_dotenv
load_dotenv()
from config import twitter_scopes
from mongo_db import mongo
redirect_uri = os.environ.get("REDIRECT_URI")
client_id = os.environ.get("CLIENT_ID")
class Token_Manager():
def __init__(self):
... | tyrovirtuosso/Twitter_Bookmark-Manager | token_manager.py | token_manager.py | py | 1,780 | python | en | code | 6 | github-code | 6 |
39869333421 | from django import forms
from .models import Order, ProductReview
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
class CustomSelectWidget(forms.Select):
template_name = 'store/tst.html'
class OrderForm(forms.Form):
'''in the single_product view, we pass the product instance to the form.'''
... | TodorToshev/Own-Blueprint | store/forms.py | forms.py | py | 1,612 | python | en | code | 1 | github-code | 6 |
42663326199 | import os
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
plt.ioff()
import seaborn
def compare_abs_auroc_differences(results_dir,
model_a_path, model_a_descriptor,
model_b_path, model_b... | rachellea/explainable-ct-ai | src/evals/eval_by_scan_attr_compare.py | eval_by_scan_attr_compare.py | py | 7,694 | python | en | code | 3 | github-code | 6 |
4143583368 | import torch
import torchvision
from torchvision.io import read_image
import os
from torch.utils.data import Dataset
"""
This part of the script is an easy API to load and get the datasets
"""
def get_dataset(dataset: str, c_angle=30, new_size=[32, 32], batch_size=300):
"""
:param new_size:
:param c_ang... | TamirShazman/ML2-Project | code/datasets.py | datasets.py | py | 3,740 | python | en | code | 0 | github-code | 6 |
36387303386 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_openml
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from sklearn.model_selection import train_test_split
from matplotlib.colors import Linear... | quentinRolld/Adversarial_attack | generalization/train_gen.py | train_gen.py | py | 9,674 | python | en | code | 1 | github-code | 6 |
43226628267 | from org.eclipse.swt import SWT
from org.eclipse.swt.widgets import Shell, Menu, MenuItem, ExpandBar, ExpandItem, Label, Composite, Button, Listener, Text
from org.eclipse.swt.layout import FillLayout, GridLayout
shell = Shell()
display = shell.getDisplay()
shell.setLayout(FillLayout())
shell.setText("ExpandBar Exampl... | texttest/storytext-selftest | swt/expandbar/target_ui.py | target_ui.py | py | 3,595 | python | en | code | 0 | github-code | 6 |
71592748667 | import datetime
import json
import math
import threading
import traceback
import asyncio
import pandas as pd
from constants import (
MAP_MARKET_ID_TO_NAME as MARKET_MAP,
AVAILABLE_MARKETS,
ALL_MARKET_LABEL,
QUERY_INTERVAL,
MINT_DIVISOR,
CONTRACT_ADDRESS
)
from prometheus_metrics import metrics... | overlay-market/ChainMonitoring | metrics/upnl.py | upnl.py | py | 9,876 | python | en | code | 0 | github-code | 6 |
24643790845 |
class Board:
""" Defines the game board """
def __init__(self, COL, ROW, BINDS, COUNT):
# self.board = [[0]*COL]*ROW # problematic echoing...!
self._cols, self._rows = COL, ROW
self._board = [[0 for i in range(ROW)] for j in range(COL)] # The COLxROW large board, all zeroes, i.e. un... | MartinHvidberg/games | Bismarck_puzzle/bp_board.py | bp_board.py | py | 3,115 | python | en | code | 0 | github-code | 6 |
71964995709 | from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_auc_score
import os
import dill as dpickle
import numpy as np
import pandas as pd
imp... | kubeflow/code-intelligence | py/label_microservice/mlp.py | mlp.py | py | 6,621 | python | en | code | 55 | github-code | 6 |
24365811740 | from itertools import groupby
from datetime import datetime, timedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
class website(models.Model):
_inherit = 'website'
def get_dynamic_count(self,prods):
filters = self.env['product.filter.value'].sudo().search([])
... | suningwz/netaddiction_addons | website_all_in_one/models/product_template.py | product_template.py | py | 3,630 | python | en | code | 0 | github-code | 6 |
32382361329 | '''
input number and print whether even or odd.
'''
while True :
inputNum = int(input("Enter the number: "))
if (inputNum == 0) :
print("Good-bye!")
break
if (inputNum % 2 == 0) :
print("Even!")
else :
print("Odd!")
| museRhee/basicPython | evenodd.py | evenodd.py | py | 267 | python | en | code | 0 | github-code | 6 |
71916938749 | from userbot.events import register
from userbot import CMD_HELP, bot
PENIS_TEMPLATE = """
╔╦╦
╠╬╬╬╣
╠╬╬╬╣ I ♥
╠╬╬╬╣ Chocolate
╚╩╩╩╝ CeteUserBot
"""
@register(outgoing=True, pattern=r"^\.(?:cho)\s?(.)?")
async def emoji_nah(e):
emoji = e.pattern_match.group(1)
await e.edit("Cete...")
message = PENIS_TEM... | inflamesinFun/CeteUserBot | userbot/modules/cho.py | cho.py | py | 545 | python | en | code | 0 | github-code | 6 |
44408183986 | #!/usr/bin/env python
# coding: utf-8
# ## This Jupyter notebook will show you to perform basic calculations and plots with 2 dimensional data (matrices, )
#
# ## We will compare two images:
# ### * MODIS-AQUA - 31st August 2005
# ### * MODIS-AQUA - 16th Feburary 2017
#
# Now, we will need to import several packages... | afonsomferreira/ppm_jupyter | 2D_oceancolour_plots.py | 2D_oceancolour_plots.py | py | 7,930 | python | en | code | 0 | github-code | 6 |
32284937669 | #!/usr/bin/env python
from pwn import *
from pwnlib.elf.elf import dotdict
import os
p = lambda x: pack(x)
u = lambda x: unpack(x, len(x)*8)
class Environment:
def __init__(self, *envs):
self.__env = None
self.env_list = list(set(envs))
for env in self.env_list:
setattr(self, e... | shift-crops/CTFProblemArchive | 2017/SECCON Beginners/NextTokyo/next_note/exploit/sc_expwn.py | sc_expwn.py | py | 3,682 | python | en | code | 1 | github-code | 6 |
34268869156 | import pandas as pd
import numpy as np
import numpy as np
import pandas as pd
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from numpy import concatenate
from flask import Flask, request, jsonify
import json
app = Flask(__name__)
@app.route('/', methods=['GET'])
def getMill():
... | Francis-Walker/AI_api | api_deploy/model_api.py | model_api.py | py | 9,209 | python | en | code | 0 | github-code | 6 |
19053013321 | from functools import wraps
import re
from collections import defaultdict
from datetime import datetime, timedelta, timezone
import humanize
import simplejson as json
from dateutil.tz import tzutc
from flask import Blueprint, g, redirect, request, url_for, current_app, jsonify
from flask_login import current_user, log... | ONSdigital/census-survey-runner | app/views/questionnaire.py | questionnaire.py | py | 32,299 | python | en | code | 0 | github-code | 6 |
26486257932 | import dcos.config
import dcos.http
import dcos.package
import json
import logging
import os
import re
import requests
import s3
import shakedown
import subprocess
import urllib
def _init_logging():
logging.basicConfig(level=logging.INFO)
logging.getLogger('dcos').setLevel(logging.WARNING)
logging.getLog... | KoddiDev/spark-streaming-mesos | tests/utils.py | utils.py | py | 8,430 | python | en | code | 1 | github-code | 6 |
33975836628 | from flask import Flask, g
from flask.ext.login import LoginManager
import user_model
DEBUG = True
PORT = 8000
HOST = '0.0.0.0'
app = Flask(__name__)
app.secret_key = 'randomstuff'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user... | kaka21garuda/FlaskSocial | app.py | app.py | py | 972 | python | en | code | 0 | github-code | 6 |
35243133405 | import sys
import os
import json
if "test_script" not in sys.modules:
from pyakaikkr.CompareCifKkr import CompareCifKkr
def get_kkr_struc_from_cif(ciffilepath: str, specx: str, displc: bool,
use_bravais=True, remove_temperaryfiles=True,
fmt="cif"):
"""get... | AkaiKKRteam/AkaiKKRPythonUtil | util/cif2kkr_test_script/cif2kkr_convert_to_akaikkrparam_sample.py | cif2kkr_convert_to_akaikkrparam_sample.py | py | 3,825 | python | en | code | 4 | github-code | 6 |
5308162380 | N, K = map(int, input().split())
K = K - 5
def dfs(idx, cnt):
global answer
# 글자수 사용 다 한 경우
if cnt == K:
print(learn)
read_cnt = 0
for word in words:
for w in word:
# 해당 단어 중 안 배운 알파벳 있으면 break
if not learn[ord(w)-ord('a')]:
... | louisuss/Algorithms-Code-Upload | Python/Baekjoon/BF/1062+.py | 1062+.py | py | 1,480 | python | ko | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.