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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
41307346874 | from tkinter import *
import threading
import hashlib
from threading import Thread
import time
from time import sleep
from random import randint
import RPi.GPIO as GPIO
import serial
import mariadb
from mfrc522 import SimpleMFRC522
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18... | MateuszLabun9/Bachelors-degree-project | last-form.py | last-form.py | py | 16,324 | python | pl | code | 1 | github-code | 1 |
25238645318 | from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.views.generic import ListView
from .forms import OrderForm
import datetime
from django.utils import timezone
from django.urls import reverse
from image.models import Images
from like.models import Likes
from .seri... | MaxOstermann/projectInsta | insta/views.py | views.py | py | 5,024 | python | en | code | 0 | github-code | 1 |
42223544906 | import sys_setup
from element import *
from linked_list import *
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
e5 = Element(5)
ll = Linked_List(e1)
ll.append(e2)
ll.append(e4)
ll.append(e5)
print("Before deleting")
ll.display()
ll.delete_first()
print("After deleting first element")
ll.display()
| pratikadarsh/ds-algo | collections/examples/linked_list/delete_first.py | delete_first.py | py | 318 | python | en | code | 0 | github-code | 1 |
22474648795 | import sys
import torch
import requests
from PIL import Image
from torchvision import transforms
from matplotlib import pyplot as plt
# from models.clipseg import ClipDensePredT
from models.clipseg import CLIPDensePredT
# load model
# model = ClipDensePredT(version="ViT-B/16", reduce_dim=64)
model = CLIPDensePredT... | Unknown-Box/tmp | main.py | main.py | py | 1,877 | python | en | code | 0 | github-code | 1 |
44323054852 | """"
Use Cases
1. Create an artifact for my project using 7zip. (This should not be the common installer's responsibility)
2. Install my artifact to my local maven repository.
3. Publish my artifact to a remote snapshot repository.
4. Publish my artifact to a remote release repository.
5. Pull down the latest release v... | chasefarmer2808/CommonInstaller | CommonInstaller.py | CommonInstaller.py | py | 2,931 | python | en | code | 0 | github-code | 1 |
43315270561 | # Taken from https://github.com/diode-dataset/diode-devkit/blob/master/metrics.py
import numpy as np
def errors(eval_preds):
pred, gt = eval_preds
valid_mask = gt > 0
pred_eval, gt_eval = pred[valid_mask], gt[valid_mask]
threshold = np.maximum((gt_eval / pred_eval), (pred_eval / gt_eval))
del... | sayakpaul/depth_estimation_trainer | metrics.py | metrics.py | py | 976 | python | en | code | 3 | github-code | 1 |
71894306274 | from django.shortcuts import render
from charts.echarts import line_chart, Colors
def dashboard_view(request):
total_page_views = {
"x": ["mon", "tue", "wed", "thur", "fri", "sat", "sun"],
"y": [8, 20, 15, 20, 50, 30, 35],
"chart_title": "Total Page Views",
}
unique_visitors = {
... | KiwiKid/ai-budget-bot | app/charts/views.py | views.py | py | 892 | python | en | code | 0 | github-code | 1 |
14936093270 | """Unit tests model_utils functions."""
from remedi import models
import pytest
import torch
def assert_equals(actual, expected, path="actual"):
"""Simple implementation of torch-friendly deep equality."""
assert type(actual) is type(expected), path
if isinstance(actual, torch.Tensor):
assert act... | evandez/REMEDI | tests/test_models.py | test_models.py | py | 1,470 | python | en | code | 91 | github-code | 1 |
2889337327 | import sys
readline = sys.stdin.buffer.readline
def map_readline(): return map(int, readline().split())
def is_all_light(idx, conditions, p_list):
for i, condition in enumerate(conditions):
switch = 0
for sw_idx in condition[1:]:
switch += (idx >> sw_idx - 1) & 1
if switch % 2 ... | Kumamoto-Hamachi/atcoder_pr | others/best_questions_for_middle/for_reference/abc128_c.py | abc128_c.py | py | 709 | python | en | code | 1 | github-code | 1 |
15497192299 | from hpp.corbaserver.rbprm.tools.com_constraints import get_com_constraint
from numpy import array
# # Creates a state given an Id pointing to an existing c++ state
#
# A RbprmDevice robot is a set of two robots. One for the
# trunk of the robot, one for the range of motion
class State(object):
# # Constructor
... | humanoid-path-planner/hpp-rbprm-corba | src/hpp/corbaserver/rbprm/rbprmstate.py | rbprmstate.py | py | 10,689 | python | en | code | 3 | github-code | 1 |
9349186636 | from django.contrib import admin
from .models import Question, Choice
class ChoiceInline(admin.TabularInline):
model = Choice
extra = 3
class QuestionAdmin(admin.ModelAdmin):
# Adjust which fields get shown on list display.
list_display = ('question_text', 'pub_date', 'was_published_recently')
... | danielhanold/docker-compose-sandbox | django-gunicorn/web/polls/admin.py | admin.py | py | 1,099 | python | en | code | 0 | github-code | 1 |
28610302176 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Authors: Veronika Kohler
# Katharina Schwarz
# Patrick Wieschollek <mail@patwie.com>
"""
Re-Implementation "Will People Like Your Image?" based on TensorPack to support
reproducible multi-gpu training.
"""
from arod_provider import Triplets
import arg... | cgtuebingen/will-people-like-your-image | training/ArodProcessing/triplets_to_txt_file.py | triplets_to_txt_file.py | py | 1,309 | python | en | code | 60 | github-code | 1 |
25650586638 | import requests
if __name__ == '__main__':
query = input("请输入搜索内容")
data={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
url = f'https://www.baidu.com/s?wd={query}'
resp = requests.get(url,headers=dat... | tgeuuy/Crawler | easy/01/request_get .py | request_get .py | py | 379 | python | en | code | 0 | github-code | 1 |
4762653150 | from django.conf.urls import patterns, url, include
from django.contrib import admin
admin.autodiscover()
from photos.views import *
urlpatterns = patterns('',
url(r'^login$', login),
url(r'^register$', register),
url(r'^logout$', logout),
url(r'^index/$', index),
url(r'^public/$', public),
url(r'addPhotoSet/$',... | tcOops/photoShare | photos/urls.py | urls.py | py | 438 | python | en | code | 1 | github-code | 1 |
34166704308 | #!/usr/bin/python3
import yaml, sys
import numpy as np
import matplotlib.pyplot as plt
def latex_float(x):
exp = int(np.log10(x*1.0))
if abs(exp) > 2:
x /= 10.0**exp
if ('%.1g' % x) == '1':
return r'10^{%.0f}' % (exp)
return r'%.1g\times10^{%.0f}' % (x, exp)
else:
... | droundy/sad-monte-carlo | plotting/cluster.py | cluster.py | py | 2,499 | python | en | code | 4 | github-code | 1 |
15253015713 | import sys
sys.path.insert(0, '../..')
import generatorUtils as gu
import random
from base import Decision
# Decision: IncrementX
# ------------------------
class IncrementX(Decision):
def registerChoices(self):
self.addChoice('incrementStyle', {
'+=': 100,
'full': 20,
'noAdd':10
})
def updateRubric(s... | malik-ali/generative-grading | src/rubricsampling/grammars/drawCircles/incrementX.py | incrementX.py | py | 1,223 | python | en | code | 5 | github-code | 1 |
1879661887 | import json
import time
import pandas as pd
start_time = time.time()
counter=0
file_path="list.json"
main_dictionary=dict()
with open(file_path, "r") as file:
for line in file:
data = json.loads(line)
if "tags" in data:
for element in data["tags"]:
if element not in main... | lorinco/ADM-HW2 | AWSQ/start.py | start.py | py | 865 | python | en | code | 0 | github-code | 1 |
35635247841 | import os
import sys
import copy
dir=os.getcwd()
dir_list=dir.split("/")
source_list=dir_list[:-1] + ["src"]
source_loc=("/").join(source_list)
sys.path.append(source_loc)
from EIS_class import EIS
from pandas import read_csv
import numpy as np
import matplotlib.pyplot as plt
from EIS_optimiser import EIS_optimiser, EI... | HOLL95/General_electrochemistry | EIS/laviron_param_scans.py | laviron_param_scans.py | py | 6,211 | python | en | code | 2 | github-code | 1 |
29973387040 | #Se tienen dos matrices con datos numéricos, formar un vector con los primos que están en los dos matrices sin repetidos.
import random
filas = random.randint(2,10)
columnas = random.randint(2,10)
matriz1 = []
matriz2 = []
for fila in range(filas):
fila_actual = []
for columna in range(columnas):
fil... | AndHak/Universidad-Semestre1-Python | Taller 3 - 6.py | Taller 3 - 6.py | py | 1,975 | python | pt | code | 2 | github-code | 1 |
74786758433 | from conans import ConanFile, CMake, tools
import os
class TracyConan(ConanFile):
name = "tracy"
license = "BSD-3-Clause"
author = "Stepan Gatilov stgatilov@gmail.com"
description = "A real time, nanosecond resolution, remote telemetry, hybrid frame and sampling profiler for games and other applicatio... | fholger/thedarkmodvr | ThirdParty/custom/tracy/conanfile.py | conanfile.py | py | 1,668 | python | en | code | 62 | github-code | 1 |
74419549154 | import torch
class PGDAttacker():
def __init__(self, radius, steps, step_size, random_start, norm_type, ascending=True):
self.radius = radius / 255.
self.steps = steps
self.step_size = step_size / 255.
self.random_start = random_start
self.norm_type = norm_type
self... | fshp971/robust-unlearnable-examples | attacks/pgd_attacker.py | pgd_attacker.py | py | 2,643 | python | en | code | 35 | github-code | 1 |
72339719074 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from locked_dropout import LockedDropout
from ON_LSTM import ONLSTMStack
from fakegcn import Graph
class Pos_choser(nn.Module):
### Take in the tree currently generated, and return the distribution of positions to inser... | ZacharyChenpk/temp_model | model.py | model.py | py | 7,679 | python | en | code | 3 | github-code | 1 |
21870447900 | import sqlite3
import time
import httplib2
import os
import sys
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
###############################... | penroff4/yt_tumblr_automation | ytdb_tools.py | ytdb_tools.py | py | 13,715 | python | en | code | 0 | github-code | 1 |
70510325155 | from __future__ import absolute_import
import celery
import json
import sys
import time
from collections import OrderedDict
from dateutil import parser
from django.core.cache import cache
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.urlresolvers import reverse
from django.test.util... | orcasgit/django-fitbit | fitapp/tests/test_retrieval.py | test_retrieval.py | py | 26,946 | python | en | code | 30 | github-code | 1 |
10786477846 | import tkinter as tk
import random
import string
from models import Store, Staff, Customer, Product, Order
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
class MainWindow(tk.Frame):
def __init__(self, *args, **kwargs):
... | JavokhirAbdirashidov/mini-python-project | view.py | view.py | py | 11,368 | python | en | code | 0 | github-code | 1 |
24504867120 | from blog_handler import BlogHandler
from models.post import Post
from google.appengine.ext import db
def blog_key(name='default'):
return db.Key.from_path('blogs', name)
class DeletePost(BlogHandler):
""" Handler for deleting posts
There is no GET because users shouldn't be visiting this
POST: Ge... | sunwrobert/fullstack-nd | projects/multi-user-blog/handlers/delete_post.py | delete_post.py | py | 1,121 | python | en | code | 1 | github-code | 1 |
5593236383 | t = int(input())
for i in range(t):
n,k = map(int, input().split())
if k>n:
print(n)
continue
ans = 0
# maxi = 0
for j in range(1,k+1):
temp = n%j
if ans<=temp:
ans = temp
# maxi = j
# print(j,ans)
print(ans) | mayank-kumar-giri/Competitive-Coding | CodeChefWorkshop/puppy.py | puppy.py | py | 300 | python | en | code | 0 | github-code | 1 |
30045890519 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | openstack/senlin | senlin/tests/unit/api/openstack/test_versions.py | test_versions.py | py | 2,052 | python | en | code | 44 | github-code | 1 |
37205559554 | # -*- coding: UTF-8 -*-
from network.packet import PacketBase
class PacketHandler:
packet_list = []
@classmethod
def register(cls, name, struct, opcode, recv = False):
cls.packet_list.append({
"name": name,
"recv": recv,
"opcode": opcode,
"struct": struct,
})
@classmethod
def get_packet_by_opcod... | xBrunoMedeiros/wyd-bot | network/handler.py | handler.py | py | 883 | python | en | code | 1 | github-code | 1 |
22062226069 | class Solution:
def numberOfArithmeticSlices(self, A: List[int]) -> int:
count = 0
carry = 0
for i in range(2,len(A)):
# Checking the difference of every slice of 3 numbers.
if A[i] - A[i - 1] == A[i - 1] - A[i - 2]:
# Adding one to carry if the differ... | isaiahbernados/LeetCodePractice | ArithmeticSlices/solution.py | solution.py | py | 504 | python | en | code | 0 | github-code | 1 |
1498862699 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 19 06:57:07 2023
@author: dpw
implement a Taylor series about x = 0 to calculate (approximate) the value of e
or any power of e.
"""
from sympy import factorial
def f(x, n):
return float(x**n / factorial(n))
def sum_series(x, *args, **kw... | darrylwest/python-play | maths/euler-sum.py | euler-sum.py | py | 560 | python | en | code | 0 | github-code | 1 |
2905458411 | #백준 11724 연결요소의 개수
import sys
sys.setrecursionlimit(10000) #재귀함수 최대 깊이 설정
input = sys.stdin.readline
N,M = map(int,input().split()) #노드, 에지 개수 입력
A = [[] for _ in range(N+1)] #인접 리스트
visited = [False] * (N+1) #방문 리스트
result = 0 #연결요소의 개수
def DFS(v): #DFS 탐색 실행
visited[v] = True
for i in A[v]:
if... | excel42/Python_practice | 11724.py | 11724.py | py | 759 | python | ko | code | 0 | github-code | 1 |
20616988771 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import warnings
warnings.filterwarnings(
'ignore', category=UserWarning)
import nltk.tokenize as tk
import nltk.corpus as nc
import nltk.stem.snowball as sb
import gensim.models.ldamodel as gm
import gensim.corpora as gc
doc = []
with open('topic.txt... | demo112/1809 | PythonWeb/基础/前端课程资料/买的网页/MS/day6/topic1.py | topic1.py | py | 1,417 | python | en | code | 0 | github-code | 1 |
72797706915 | # Import heapq
from heapq import *
# Function to return the minimum cost
def connectRopes(arr):
# Convert arr to min heap
heapify(arr)
# Initialize cost
cost = 0
# Traverse till only element remains in min heap
while len(arr) > 1:
# Pop the two smallest element
a = heappop(ar... | DataRohit/Data-Structures-and-Algorithms | 22_heaps/09_min_cost_ropes.py | 09_min_cost_ropes.py | py | 679 | python | en | code | 1 | github-code | 1 |
74386086752 | from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
import math
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = (
'mysql+pymysql://YanServer:123test@yanzzp.xyz:3306/test2'
)
db = SQLAlchemy(app)
class Calculation(db.Model):
id = db.Column(db.Integer, primar... | Yanzzp/calculator | app.py | app.py | py | 1,610 | python | en | code | 3 | github-code | 1 |
16615457674 | """
algorithm:实现软间隔化的核函数SVM二分类算法
reference:http://github.com/ajtulloch/svmpy
Note:上面参考地址给出了基于凸优化库cvxopt的svm实现版本,代码写的很棒,但是对于cvxopt库了解不多,后面如果有机会希望重写一下这个算法,相信会加深理解的。
采用slearn实现svm
dataset:lonosphere_dataset.txt
author:crazicoco
"""
from sklearn.svm import SVC
# sklearn.preprocessing 提供三种数据标准化的处理方式,... | crazicoco/ML-basic-algorithm | Soft-margin kernel SVM/main.py | main.py | py | 2,464 | python | en | code | 0 | github-code | 1 |
24324612905 | # !/usr/bin/env python
# ! _*_ coding:utf-8 _*_
# @TIME : 2018/12/14 19:26
# @Author : Noob
# @File : basepage.py
"""
Project:基础类BasePage,封装所有页面都公用的方法;
定义open函数,重定义find_element,switch_frame,send_keys等函数;
在初始化方法中定义驱动driver,基本url,title;
WebDriverWait提供了显示等待方式;
"""
from selenium.webdriver.support.ui import WebDrive... | NoobZeng/Selenium | chapter08/page_object/basepage.py | basepage.py | py | 6,383 | python | zh | code | 1 | github-code | 1 |
13325364489 | class Square:
def __init__(self, height="0", width="0"):
self.height = height
self.width = width
# Getter
# allows reference to individual fields
@property
def height(self):
print("Retrieving the Height")
# use __ to show that information is private
return ... | milleriishaun/py_fun | OOP_square.py | OOP_square.py | py | 1,408 | python | en | code | 0 | github-code | 1 |
23094470626 | """
Alexandra Pawlak
TCSS 554
November 30, 2017
Homework #1
Description: Implementation of PageRank. Reads in an adjacency matrix (inputfile)
through a text file. The input file must be in the matrix format
with 3 columns (i j k).
Each row denotes that the matrix contains a value k at the row i, column j.
The value k... | apawlak27/Information-Retrieval | Homework 2/hw2.py | hw2.py | py | 2,322 | python | en | code | 0 | github-code | 1 |
71912287713 | # Encode a text to prevent "shoulder surfing"
import base64, sys
if len(sys.argv) != 2:
print("Usage: " + sys.argv[0] + " text")
else:
enc = []
msg = "warning:"
for i, ch in enumerate(sys.argv[1]):
key_c = msg[i % len(msg)]
enc_c = chr((ord(ch) + ord(key_c)) % 256)
enc.append(enc... | CAST-Extend/com.castsoftware.aip.datamart | utilities/encode.py | encode.py | py | 405 | python | en | code | 1 | github-code | 1 |
3677143997 | from datetime import date
data_atual = date.today()
data_em_texto = "0{}/0{}/{}".format(data_atual.day, data_atual.month,data_atual.year)
listaNomes = ['Andre','Joao','Luccas']
listaIdades = [23,21,25]
listaNascimento = ['23/11/1998','05/07/2000','18/01/1996']
listaMesMenor = ['04', '06', '09', '11']
def men... | andreduarte07/python | cadastroFunc.py | cadastroFunc.py | py | 4,311 | python | pt | code | 1 | github-code | 1 |
10232725106 | #!/usr/bin/env python3
import sys
sys.setrecursionlimit(10000)
def paco(data, base):
N, M, X, K, XCa,YCa, XCo,YCo = data
dst = (XCo-1, YCo-1)
thr = int(X*K/2)
themap = [base[i*M:(i+1)*M] for i in range(N)]
def trace(path):
return sum(themap[x][y] for x,y in path)
invalid = (M*N+1,6666)
cache = [inv... | kopchik/itasks | tallentbuddy.co/paco.py | paco.py | py | 1,176 | python | en | code | 0 | github-code | 1 |
32656551753 | from server.db.db import db
from server.db.domain import Organisation, CollaborationRequest, CollaborationMembership, Collaboration
from server.test.abstract_test import AbstractTest
from server.test.seed import schac_home_organisation, amsterdam_uva_name, collaboration_request_name, uuc_name, \
schac_home_organisa... | SURFscz/SBS | server/test/api/test_collaboration_request.py | test_collaboration_request.py | py | 8,440 | python | en | code | 4 | github-code | 1 |
40928928603 | import base58
import json
import time
from Crypto.Hash import SHA3_256, SHA3_512, RIPEMD160
from Crypto.Signature import PKCS1_v1_5
from transaction import Transaction, TransactionMerkleTree
from wallet import Wallet
class Block:
def __init__(self, index, transactions, timestamp, previous_hash, nonce=0):
... | BleuHund/BlockChainTest | main.py | main.py | py | 4,775 | python | en | code | 0 | github-code | 1 |
25185509753 | import yaml
import logging
settings = dict()
log_levels = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL,
}
with open("../config.yaml", 'r') as stream:
try:
settings = yaml.safe_load(stream)
sett... | rkaganda/MBTL_NN | src/config.py | config.py | py | 427 | python | en | code | 2 | github-code | 1 |
23626582292 | import numpy as np
import backend
import nn
class Model(object):
"""Base model class for the different applications"""
def __init__(self):
self.get_data_and_monitor = None
self.learning_rate = 0.0
def run(self, x, y=None):
raise NotImplementedError("Model.run must be overriden by ... | jtiannn/Projects | Neural/models.py | models.py | py | 18,671 | python | en | code | 1 | github-code | 1 |
71052805793 | # -*- coding: utf-8 -*-
import scrapy
import re
import json
from Scrapy_Cnluqiao_V1.items import ScrapyCnluqiaoV1Item
import time
from scrapy.utils import request
from Scrapy_Cnluqiao_V1.start_urls import url1
class CnluqiaoV1Spider(scrapy.Spider):
name = 'cnluqiao_V1'
# allowed_domains = ['123']
# start_... | JevisCHF/Building | Information/Spider/Scrapy_Cnluqiao_V1/Scrapy_Cnluqiao_V1/spiders/cnluqiao_V1.py | cnluqiao_V1.py | py | 3,915 | python | en | code | 1 | github-code | 1 |
17968675619 |
# Hare and Tortise Algorithm
# https://www.youtube.com/watch?time_continue=1&v=-YiQZi3mLq0&feature=emb_title
# Use to dectect if a linked likst has a loop in a linked list
# ex: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> back to 2
# Tortise moves 1 node per iteration
# Hare moves 2 nodes per iteration
# Both start at 0. After 1... | NWood-Git/other_challenge_questions | hare_and_tortise_algorithim.py | hare_and_tortise_algorithim.py | py | 2,692 | python | en | code | 0 | github-code | 1 |
11721997882 | # -*- coding: utf-8 -*-
"""
Preppin' Data 2021: Week 39 - Painting Bikes
https://preppindata.blogspot.com/2021/09/2021-week-39-painting-bikes.html
- Input the Data
- Create a Datetime field
- Parse the Bike Type and Batch Status for each batch
- Parse the Actual & Target values for each parameter.
- Identify what tim... | kelly-gilbert/preppin-data-challenge | 2021/preppin-data-2021-39/preppin-data-2021-39.py | preppin-data-2021-39.py | py | 5,206 | python | en | code | 19 | github-code | 1 |
553169162 | """Blogly application."""
from flask import Flask, request, render_template, redirect, flash, session
from flask_debugtoolbar import DebugToolbarExtension
from models import db, connect_db, User, Post, Tag, PostTag
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///users'
app.config['SQLALC... | austindreosch/springboard | exercises/section2/sqlalchemy/users-posts-tags-part3/app.py | app.py | py | 4,821 | python | en | code | 0 | github-code | 1 |
10243797328 | from sys import stdin
import sys
def grammarize(regex):
stack = []
curr = 'A'
regex.replace(" ", "")
for char in regex:
if char is not ')' and char is not '+' and char is not '*':
stack.append(char)
elif char is ')':
term = ""
stack.append(')')
... | lvirgili/usp | pcs5730/src/regex2grammar.py | regex2grammar.py | py | 1,159 | python | en | code | 0 | github-code | 1 |
14844254155 | import logging
from PyQt5.QtCore import QObject, pyqtSignal
import ClientTools
import zlib
import serial
import base64
scanner = None
logger = logging.getLogger()
class ScannerSignalHandler(QObject):
barcode_result = pyqtSignal(str)
scanner_signal_handler = ScannerSignalHandler()
def get_scanner():
if sc... | B9527/pyqt_project | device/Scanner.py | Scanner.py | py | 2,225 | python | en | code | 1 | github-code | 1 |
72115662114 | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from account.models import User
from .models import Task
import sweetify
from twilio.rest import Client
import os
import environ
@login_required(log... | Geoslim/eattendance-with-face-recognition | eAttendance/tasks/views.py | views.py | py | 3,637 | python | en | code | 0 | github-code | 1 |
73527892194 | from nmigen import *
from nmigen_stdio.serial import *
class Uart(Elaboratable):
""" Uart peripheral using ngigen-stdio """
def __init__(self, pkt_size=16):
# Parameters
self.pkt_size = pkt_size
# Inputs
self.i_pkt = Signal(pkt_size * 8)
self.i_valid = Signal()
... | lawrie/qspi_periph | gateware/periph/uart.py | uart.py | py | 1,998 | python | en | code | 1 | github-code | 1 |
23896017996 | from core.Controller import Controller, Utils, Request, Response, HTTPStatus, Hooks, before_request
from models.Person import Person
from models.User import User, Role, List
from core.classes.middleware.Authenticator import Authenticator, Session
class UserController(Controller):
def on_get(self, req: Request, re... | Pachada/WSGI-Falcon-API | controllers/UserController.py | UserController.py | py | 3,755 | python | en | code | 1 | github-code | 1 |
8027393171 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''This module contains functions to perform operations on collections of FITS
files.
'''
#############
## LOGGING ##
#############
import logging
from fitsbits import log_sub, log_fmt, log_date_fmt
DEBUG = False
if DEBUG:
level = logging.DEBUG
else:
level = lo... | waqasbhatti/fitsbits | fitsbits/files.py | files.py | py | 33,561 | python | en | code | 1 | github-code | 1 |
665721454 | import json
import cv2
# PDI
from pipeline.PipelinePDI import PipelinePDI
pipelinePDI = PipelinePDI()
date, url_json, image = pipelinePDI.set_input('pdi_mocked.json')
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
cv2.imwrite('noe.jpg', image_rgb)
results = pipelinePDI.detect_offers(url_json, image, date)
with o... | maryane-castro/deploystreamlit | outro/main.py | main.py | py | 669 | python | en | code | 1 | github-code | 1 |
1632453575 | from copy import copy, deepcopy
from collections import defaultdict
# a: 14:55
# b:
WINSCORE = 21
KNOWN_STATES = dict()
scores = list()
for i in range(1, 4):
for j in range(1, 4):
for k in range(1, 4):
s = i + j + k
scores.append(s)
def play_quantum(p1, s1, p2, s2, player_i... | dumoulinj/aoc | aoc/2021/day21_v2.py | day21_v2.py | py | 1,342 | python | en | code | 0 | github-code | 1 |
25459838815 | from telemetry.internal.actions import page_action
from telemetry.internal.actions import utils
class PinchAction(page_action.PageAction):
def __init__(self, selector=None, text=None, element_function=None,
left_anchor_ratio=0.5, top_anchor_ratio=0.5,
scale_factor=None, speed_in_pixels... | hanpfei/chromium-net | third_party/catapult/telemetry/telemetry/internal/actions/pinch.py | pinch.py | py | 2,693 | python | en | code | 289 | github-code | 1 |
6383171021 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation
def getPerimeterPoints(targetPoint, S_inverse, angleStep, gateThreshold):
"""
Input:
targetPoint : np.array(shape = (dimX, 1))
S_inverse : np.array(shape = (dimZ, dimZ))
angleStep : float
... | Royzon/2020_staj | madeUpTracking/myHelpers/visualizeHelper.py | visualizeHelper.py | py | 9,581 | python | en | code | null | github-code | 1 |
2835711998 | from cgi import test
from basicsr.losses.losses import L_color
import torch
from collections import OrderedDict
from os import path as osp
from tqdm import tqdm
from basicsr.archs import build_network
from basicsr.losses import build_loss
from basicsr.metrics import calculate_metric
from basicsr.utils import get_root_... | zheng980629/CUE | basicsr/models/LearnablePrior_model.py | LearnablePrior_model.py | py | 13,065 | python | en | code | 9 | github-code | 1 |
6033947324 | from typing import List
"""
Summary: Iterate over the array in a while loop for len(arr) times. Pointer
starts at 0. If element is not zero, move pointer -> one step. Else, pop the
item and append to the end, don't move the pointer, the list shifts left.
---------------------------------------------------------------... | EvgeniiTitov/coding-practice | coding_practice/sample_problems/leet_code/easy/283_move_zeros.py | 283_move_zeros.py | py | 1,979 | python | en | code | 1 | github-code | 1 |
32099441902 | import cv2
import numpy as np
def find_list_files(pattern_filename, path):
'''
Find list of files following a pattern filename within a path
This returns a list of results, void list [] if items not found
'''
import os,fnmatch
result = []
for root, dirs, files in os.walk(path): # o... | rcolomina/ALOCC_Keras | landsat_data_loader.py | landsat_data_loader.py | py | 2,223 | python | en | code | null | github-code | 1 |
72228016995 | # USAGE
# python opencv-crop.py
# loading image from disk loads as NumPy array
# restate image = NumPy array
# to crop you need to know how opencv slices
# arrays start at 0 so the numbers are not inclusive
# ratio is row:column format
# if you go :, 3 you won't get 3..youll get up to 2
# 0 1 | 2| 3 4 5
# 10 11 |... | dmarcus-wire/opencv | cropping/opencv-crop.py | opencv-crop.py | py | 1,088 | python | en | code | 0 | github-code | 1 |
27801467597 | from test_framework import generic_test
from math import factorial
def compute_binomial_coefficient(n, k):
# (n!)/(r!(n-r)!)
result = factorial(n)/(factorial(k)*(factorial(n-k)))
return int(result)
def compute_binomial_coefficients_space_efficient(n, k):
k = min(k, n - k)
table = [1] + [0] * k
... | garciamilord/Elements-of-Programming-Interviews | epi_judge_python_solutions/binomial_coefficients.py | binomial_coefficients.py | py | 670 | python | en | code | null | github-code | 1 |
70343124194 | from socket import socket
def echoServer(port):
'''
Create a socket server that echos back the message sent.
'''
s = socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', port))
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(1024)
if not data:
... | s2e-lab/SecurityEval | Testcases_Insecure_Code/CWE-605/author_1.py | author_1.py | py | 379 | python | en | code | 31 | github-code | 1 |
16430495963 | # 1차 제출 때 시간초과가 떠서, 다음과 같이 수정함
# find_self_num 내의 index를 0부터 오름차순이 아닌 num-1부터 내림차순으로 수정
# 생성자가 하나라도 있다면, break 하도록 하는 코드 추가하여 불필요한 반복 없앰
# Pypy3로 제출시 시간초과 문제가 해결될 때도 있다. (참고)
def find_self_num(num):
count = 0 # 생성자 갯수 세기
constructor = 0 # 생성자 여부 판별
for i in range(num - 1, 0, -1): # num보다 작은 숫자 중에 생성자가... | ZIO-KIM/Baekjoon-Study | Function/4673.py | 4673.py | py | 953 | python | ko | code | 0 | github-code | 1 |
73910105634 | __author__ = 'Alexander Bruy'
__date__ = 'January 2016'
__copyright__ = '(C) 2016, Alexander Bruy'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
import re
from qgis.core import QgsCoordinateReferenceSystem
from qgis.utils import iface
from processing.core... | nextgis/nextgisqgis | python/plugins/processing/algs/qgis/DefineProjection.py | DefineProjection.py | py | 2,235 | python | en | code | 27 | github-code | 1 |
3199037024 | import telebot
from telebot import types
from aiogram.types import ReplyKeyboardRemove, \
ReplyKeyboardMarkup, KeyboardButton, \
InlineKeyboardMarkup, InlineKeyboardButton
import os
import django
from backend import local2 as local
from worker.models import Worker, TGBotCode
os.environ.setdefault('DJANGO_SET... | ScrollPage/Case-In | backend/service.py | service.py | py | 2,103 | python | ru | code | 0 | github-code | 1 |
25433127029 | n, s, m = map(int, input().split())
v = list(map(int, input().split()))
# dp 정의
# 행에는 최대볼륨 열에는 곡의 개수
dp = [[0] * (m+1) for i in range(n+1)]
dp[0][s] = 1
for i in range(1, n+1): # 곡의 개수만큼
for j in range(m+1): # 최대 볼륨
if dp[i-1][j] != 0: # 볼륨 조절 가능하다면
# print(dp[i-1][j])
... | reddevilmidzy/baekjoonsolve | 백준/Silver/1495. 기타리스트/기타리스트.py | 기타리스트.py | py | 750 | python | ko | code | 3 | github-code | 1 |
12121000296 | with open("text.txt") as f:
words = f.read().split()
counts = dict()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
def get_count(x):
return x[1]
result = sorted(counts.items(), key=get_count, reverse=True)
for key, count in result[:20]:
print(f... | pep-dortmund/toolbox-workshop | exercises-toolbox/1-python/6-wordcount/loesung1.py | loesung1.py | py | 338 | python | en | code | 25 | github-code | 1 |
18112717135 | from Client0 import Client
from Seq1 import Seq
from colorama import Fore, init
init(autoreset=True)
PRACTICE = 2
EXERCISE = 5
print(f"-----| Practice {PRACTICE}, Exercise {EXERCISE} |------")
s1 = Seq()
filename = Seq.get_file2()
s1.read_fasta(filename)
frag1 = s1.strbases[:10]
frag2 = s1.strbases[11:20]
frag... | loreaferreno/2021_2022-PNE-practices | P2 done again/Session 9 - Practice 2/Exercise 6.py | Exercise 6.py | py | 1,319 | python | en | code | 0 | github-code | 1 |
33761466474 | from io import StringIO
from copy import deepcopy
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if not args and not kwargs: # empty call
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
... | taucompling/morphophonology_spe | source/configuration.py | configuration.py | py | 2,880 | python | en | code | 5 | github-code | 1 |
1335028342 | from dataStructs import Stack
import re
def isdigit(ch):
return re.search("\d+",ch)
def isalpha(ch):
return re.search("\w+",ch)
def infixToPostfix(args):
precedence = {"*":3,"/":3,"+":2,"-":2,"(":1}
opStack = Stack() #operator stack.
outputList = []
for token in args:
if isdigit(token) or isalpha(token)... | joshiamey/python_problems | infixTopostfix.py | infixTopostfix.py | py | 1,096 | python | en | code | 0 | github-code | 1 |
25088650917 | import random as rn
gamesList = []
#read all games from txt file
file = open("gamesList.txt", "r")
#set each to list
for line in file:
gamesList.append(line)
#find random number from index of list
gameID = rn.randint(0, len(gamesList) - 1)
#print
print("The game I decided you shall play is:")
print(gamesLi... | theblindkarp/PythonProjects | GameRandom/gamerRandom.py | gamerRandom.py | py | 368 | python | en | code | 0 | github-code | 1 |
70752878113 | with open('day20.txt') as file:
lines = [line.strip() for line in file.readlines()]
enhancement = lines[0]
image = lines[2:]
def count(image, target):
count = 0
for row in image:
for pixel in row:
if pixel == target:
count += 1
return count
def enhance(image... | blat-blatnik/Advent-of-Code | 2021/day20.py | day20.py | py | 1,402 | python | en | code | 0 | github-code | 1 |
15149130683 | import subprocess
import os
from unittest import mock
from unittest.mock import patch, Mock
import pytest
import logging
import sys
from src.build_java import build_java
def test_update_path_for_jdk():
original_path = os.environ['PATH']
build_java.update_path_for_jdk('java8')
expected_path = '/usr/lib/j... | ariadne-pereira/projeto | test_build_java.py | test_build_java.py | py | 1,594 | python | en | code | 1 | github-code | 1 |
21563575484 | from typing import List
# lapsolver is quite hard to install on Windows. Fortunately, scipy offers a similar, albeit slower, function.
try:
from lapsolver import solve_dense as solver
except ImportError:
from scipy.optimize import linear_sum_assignment as solver
from authentication.models import User
from rep... | Mines-Paristech-Students/Portail-des-eleves | backend/repartitions/algorithm.py | algorithm.py | py | 8,907 | python | en | code | 23 | github-code | 1 |
33367938302 | import tensorflow as tf
from tensorflow.python.framework import ops
import sys
import os
import numpy as np
from hf.core import box_8c_encoder
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
cropping_module = tf.load_op_library(os.path.join(BASE_DIR, "tf_cropping_so.so"))
def pc_crop_... | zhaotudou/HeteroFusionRCNN | cropping/tf_cropping.py | tf_cropping.py | py | 3,629 | python | en | code | 1 | github-code | 1 |
41933406706 | import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import os
import time
from datetime import date, datetime
from datetime import timedelta
def wait_for_downloads(path):
print("Waiting for downloads", end="")
while... | rmmaf/Scraping-Indices-Economicos | scripts/sp500.py | sp500.py | py | 3,190 | python | en | code | 0 | github-code | 1 |
19545698962 | import csv
import os
from extract_file.extract_CSV import extract_csv_x
dir = r'/Users/peterchukwu/Desktop/CETM50'
def extract_csv_headers():
try:
directory = dir
data = extract_csv_x()
HEADER_S = next(data)
for file_name in os.listdir(directory):
if file_name.endswith... | peterchijioke/analysis | extract_file/extract_CSV_file_with_header.py | extract_CSV_file_with_header.py | py | 639 | python | en | code | 0 | github-code | 1 |
35681922206 | import logging
from conftest import Log_path
class LogData:
def getLogger(self):
logger = logging.getLogger(__name__)
logsone = logging.FileHandler(Log_path+"/logfile.log")
formatter = logging.Formatter("%(asctime)s :%(levelname)s :%(name)s :%(message)s")
logsone.setFormatter(forma... | harshalwarkar2020/AmazonApp | LogFeature/LogRecord.py | LogRecord.py | py | 424 | python | en | code | 0 | github-code | 1 |
22453535086 | import os
import json
import io
from wp import wp_database, wp_post_query
from mailing import mailer
WP_DB_CONFIG_FILE_PATH_VAR_KEY = "WP_DB_CONFIG_FILE_PATH"
DEFAULT_WP_DB_CONFIG_FILE_PATH = "resource/wp_db_config.json"
MAIL_CONFIG_FILE_PATH_VAR_KEY = "MAIL_CONFIG_FILE_PATH"
DEFAULT_MAIL_CONFIG_FILE_PATH = "resource... | KEN-00/wp_post_alert | main.py | main.py | py | 2,289 | python | en | code | 0 | github-code | 1 |
34863895895 | """
create table product (name varchar(20) primary key, price float, qty int)
drop table product # to delete the whole table
insert into product values ('Prod1', 34.56, 23)
select * from product
select * from product where qty > 20
delete from product where qty=0
update product set price=price*1.25 where nam... | MehrdadKianiOsh/Database-API-SQL- | session 3/testSQLite.py | testSQLite.py | py | 1,294 | python | en | code | 0 | github-code | 1 |
4364858639 | from PPlay.gameimage import *
from PPlay.gameobject import *
from PPlay.sprite import *
import pygame
import pickle
class Screen:
def __init__(self, screen, platforms, sprite, keyboard, slime, mouse, font_screen):
self.font_screen = font_screen
self.window = screen
self.platforms = platfor... | lscrispin/lab-jogos | camera.py | camera.py | py | 6,219 | python | en | code | 0 | github-code | 1 |
44067529059 | from urllib import request
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from dotFoods.celery import app
from dotFoods import settings
from wikiboto.utils import \
url_name_of, \
url_name_of_cat,\
LINK_FILTERS, \
bs_preprocess, \
can_access
from wikipage.models import \
WikiL... | dotkrnl/dotFoods | wikiboto/tasks.py | tasks.py | py | 3,869 | python | en | code | 0 | github-code | 1 |
73100306274 | """
Run a nongaussian Kalman Filter twin experiment with Lorenz-63
"""
# Load modules
import numpy as np
import pickle
import mod_KalmanDA as da
import LorenzModels as LM
import matplotlib.pyplot as plt
import tikzplotlib as tpl
# Options for DA run
n_wind = 25 # Number of DA window... | SnnVL/DynamicalGaussianLognormalReverseLognormalKalmanfilter | run_KF_one.py | run_KF_one.py | py | 13,036 | python | en | code | 0 | github-code | 1 |
12246184907 | def non_repeat(line: str) -> str:
"""
the longest substring without repeating chars
"""
if not line:
return line
line_uniques = []
for i in range(len(line)):
line_short = line[i:]
line_new = ''
for c in line_short:
if c and c in line_new:
... | krkmn/checkio | O'Reilly/long_non_repeat.py | long_non_repeat.py | py | 846 | python | en | code | 0 | github-code | 1 |
17480338489 | # A simple number guessing game
# Could you make something cooler?
import random
# Make n a random number between 1 and 99
n = random.randint(1, 10)
# Ask user to guess the number
guess = int(input("Enter an integer from 1 to 10: "))
while True:
if guess >= 1 or guess <= 10 :
if guess < n or ... | azzahrajanetan/Learning-Practices | Python/pyguess2.py | pyguess2.py | py | 509 | python | en | code | 0 | github-code | 1 |
71494978594 | from db_generator import choose_variant_from_dict
import os
def store_res_in_party(cursor, account, max_time):
cursor.execute("(select coalesce(max(party_id)+1,0) from party);")
party_id = cursor.fetchall()[0][0]
print("party_id = %d" % party_id)
cursor.execute("select * from get_ordered_result();")
... | DanilaEremenko/RDB | damned_capitalism/managing/statistic.py | statistic.py | py | 1,755 | python | en | code | 0 | github-code | 1 |
33815505971 | class Hero:
def __init__(self,name,health,attachPower,armor):
#public
self.name = name
self.health = health
self.attachPower = attachPower
self.armor = armor
#protected
self._tinggi = 15
#private
self.__exp = 10
#cara untuk mendapatkan v... | irfansantoso/Belajar-Python-Basic | BelajarOOP/modifierOOP.py | modifierOOP.py | py | 551 | python | id | code | 0 | github-code | 1 |
71728359075 | import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from matplotlib.widgets import Slider
import networkx as nx
########## Here we do some introductory stuff with percolation ###########
#update function
def update(val):
GW = G.copy()
for i,j in GW.edges():
if np.random.uniform(0,1) > val:
GW.... | mengsig/percolation | 2DLatticePercolation/bernoulliPercolationNumpy.py | bernoulliPercolationNumpy.py | py | 1,097 | python | en | code | 0 | github-code | 1 |
74541723872 | import pytest
from yarl import URL
async def _get_username(web_client_session, app_url):
"""
Visits /hub/home to get an _xsrf token set to cookies, that we can then
pass as a X-XSRFToken header when accessing /hub/api, then the function
visit /hub/api/user to get the username as recognized by JupyterH... | jupyterhub/tmpauthenticator | tests/test_tmpauthenticator.py | test_tmpauthenticator.py | py | 4,860 | python | en | code | 20 | github-code | 1 |
23231910795 | import os
import shutil
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
for name in files:
yield os.path.join(root, name)
source_dir = 'C:\\Users\\User\\Portabolt\\Portabolt - Documents'
destination_dir = 'C:\\Users\\User\\Documents\\Facturenfolder'
for file in list_fi... | PortaboltTom/Work | Plumbing/Get_All_PDF's.py | Get_All_PDF's.py | py | 409 | python | en | code | 1 | github-code | 1 |
28646283616 | '''
SCRIPT: ReadStoichiometry
@Authors:
Alberto Cuoci [1]
[1]: CRECK Modeling Lab, Department of Chemistry, Materials, and Chemical Engineering, Politecnico di Milano
@Contacts:
alberto.cuoci@polimi.it
@Additional notes:
This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRAN... | acuoci/PyTools4OpenSMOKEpp | examples/ReadStoichiometry.py | ReadStoichiometry.py | py | 11,438 | python | en | code | 3 | github-code | 1 |
42988519037 |
import os
import pkg_resources
###
# This was obtained from https://stackoverflow.com/questions/16294819/check-if-my-python-has-all-required-packages
###
def check():
# dependencies can be any iterable with strings,
# e.g. file line-by-line iterator
dependencies = []
dir_path = os.path.dirname(os.pa... | paulkass/jira-vim | python/util/pip_check.py | pip_check.py | py | 1,044 | python | en | code | 135 | github-code | 1 |
74857798754 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from .models import Tag, User, Image
from rest_framework import status
from rest_framework.request import Request
import json
from django.views.decorators.http import require_http_methods
import logging
from .utils impo... | muzzafer5/photosapp | backend/restapi/image_views.py | image_views.py | py | 12,613 | python | en | code | 0 | github-code | 1 |
16351746211 | import pandas as pd
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
import pickle
from sklearn.metrics import roc_curve
from matplotlib import pyplot
import numpy as np
x_train = pd.read_csv('x_train')
x_valid = pd.read_csv('x_valid')
y_train = pd.read_csv('y_train')
y_valid = pd.read_csv(... | Korge/MLProject | SVM K-Fold.py | SVM K-Fold.py | py | 1,671 | python | en | code | 0 | github-code | 1 |
18475234989 |
# Temperature calculator
def celicustempcalc():
try:
Current_F = float(input("What is the current temp in farenheit? "))
Current_C = 5.0 * (float(Current_F) - 32.0) / 9.0
print("The current temperature in celcius is: " + str(Current_C))
except Exception as e:
print("Error: " ... | r-lau/Python_Public | Temperature_Calculator.py | Temperature_Calculator.py | py | 1,045 | python | en | code | 0 | github-code | 1 |
31793166667 | import requests
from datetime import date, datetime, timedelta
from json import dump
import sys
def datespan(start, end, delta=timedelta(days=1)):
current = start
while current < end:
yield current
current += delta
with open(sys.argv[1], 'w') as file:
for dates in datespa... | ktshakhova/cloud_lab2 | get_course.py | get_course.py | py | 885 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.