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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
46525020186 | import pygame
from robot import Robot
from manual_robot import ManualRobot
from automated_robot import AutomatedRobot
from automated_robots.robots_concursantes import *
from automated_robots.robots_zimatek import *
from robot_hub import RobotHub
from coin import Coin
import numpy as np
import os
class Combat:
"""... | zimatek/RobotCombat | combat.py | combat.py | py | 11,303 | python | en | code | 0 | github-code | 6 |
42452241894 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
from calculator_1 import add, sub, mul, div
args = sys.argv[1:]
no_of_args = len(args)
if no_of_args != 3:
print("Usage: ./100-my_calculator.py <a> <operator> <b>")
sys.exit(1)
op = args[1]
operators = {"+": add, "-... | timmySpark/alx-higher_level_programming | 0x02-python-import_modules/100-my_calculator.py | 100-my_calculator.py | py | 575 | python | en | code | 0 | github-code | 6 |
32544533358 | import json
import glob
from flask import Flask , send_file
import os
from flask_cors import CORS
app = Flask (__name__)
cors = CORS(app)
@app.route('/')
def DownloadMergedJson() -> str:
result = {}
logs = {}
node_ids =[]
for f in glob.glob(os.path.join("..", "history_*.json")):
print(str(f))
... | SiyiGuo/COMP90020 | pythonproxy/getNodeData.py | getNodeData.py | py | 648 | python | en | code | 0 | github-code | 6 |
25144954100 | import requests
import collections
import csv
from bs4 import BeautifulSoup
from bs4.element import Tag
class ParseAnimals:
def __init__(self) -> None:
self.animals_names = {}
def parse(self) -> None:
"""
Make a while loop until calegory letter != Я
Saves each animal ... | enamsaraev/tetrika-test | task2/solution.py | solution.py | py | 2,239 | python | en | code | 0 | github-code | 6 |
17650565567 | import nltk
from newspaper import Article
# nltk.download('punkt') is a Python command that is used to download the "punkt" dataset or resource from the Natural Language Toolkit (NLTK) library.
# NLTK is a popular library in Python for working with human language data, including tasks like tokenization, parsing, and... | AnukulSri/summarize-news-article | news.py | news.py | py | 1,033 | python | en | code | 0 | github-code | 6 |
17669758792 | """2020_02_18
Revision ID: 000001
Revises:
Create Date: 2020-02-18 03:57:38.958091
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "000001"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic... | ichux/elog | migrations/versions/000001_2020_02_18.py | 000001_2020_02_18.py | py | 2,743 | python | en | code | 2 | github-code | 6 |
73264679548 | from pyglet.text import Label
from audio import explosion
from fonts.fonts import press_start_2p
from interfaces.interface import Interface
from system import system
import menus.menu
import menus.game_over_menu
class GameOverInterface(Interface):
game_over_label: Label = None
game_over_menu: menus.menu.Men... | KimPalao/Headshot | interfaces/game_over_interface.py | game_over_interface.py | py | 1,110 | python | en | code | 0 | github-code | 6 |
24363848040 | # This script should be executed inside a NetAddiction Odoo 9 shell.
import json
def remove_duplicate_attributes(product):
seen_ids = set()
duplicate_list = []
for attr in product.attribute_value_ids:
if attr.attribute_id.id not in seen_ids:
seen_ids.add(attr.attribute_id.id)
... | suningwz/netaddiction_addons | scripts/remove_duplicates_attribute.py | remove_duplicates_attribute.py | py | 1,150 | python | en | code | 0 | github-code | 6 |
34879700956 | import re
from requests import get
from sys import argv as cla
from readabilipy import simple_json_from_html_string
from ebooklib import epub
def valid_url(url):
regex = re.compile(
r'^(?:http)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.... | eklop/web2epub | web2epub.py | web2epub.py | py | 2,797 | python | en | code | 0 | github-code | 6 |
2600836089 | # Import thư viện
from sklearn.linear_model import LinearRegression
import numpy as np
import csv
from vnstock import*
data=[]
cp=listing_companies()
check='ngân hàng thương mại cổ phần'
nh=[]
for n in range(len(cp)):
if check in cp.loc[n][2].lower():
nh.append(cp.loc[n][0])
print(len(nh))
for ticket in nh:... | vanvy102/code | Code-test/linear.py | linear.py | py | 1,070 | python | vi | code | 0 | github-code | 6 |
22779752732 | def create_triangle(size):
triangle = ""
# first part
for r in range(1, size + 1):
for c in range(1, r + 1):
triangle += f"{c} "
triangle += "\n"
# second part
for r in range(size - 1, -1, -1):
for c in range(1, r + 1):
triangle += f"{c} "
tri... | DanieII/SoftUni-Advanced-2023-01 | advanced/modules/module.py | module.py | py | 1,228 | python | en | code | 0 | github-code | 6 |
30410142101 | import CryptoCurrency
import sqlite3 as sql
import requests
from datetime import datetime
import time
def get_crypto():
"""Récupères la liste des cryptomonnaies tradable sur le marché futures de Bybit
(!! 120 requests per second for 5 consecutive seconds maximum)
Returns:
list:liste des cryptomonn... | ArthurOnWeb/l-historique-du-prix-d-une-cryptomonnaie | Main.py | Main.py | py | 5,015 | python | en | code | 0 | github-code | 6 |
35445440233 | from dexy.common import OrderedDict
import dexy.database
import dexy.doc
import dexy.parser
import dexy.reporter
import inspect
import json
import logging
import logging.handlers
import os
import shutil
class Wrapper(object):
"""
Class that assists in interacting with Dexy, including running Dexy.
"""
... | gotosprey/dexy | dexy/wrapper.py | wrapper.py | py | 11,970 | python | en | code | null | github-code | 6 |
14572312600 | ############## THESE SPLINES ARE USING CATMULL SPLINES ##############
# https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline
#
# FOLLOWING javidx9's SPLINE VIDEOS:
# https://www.youtube.com/watch?v=9_aJGUTePYo&t=898s&ab_channel=javidx9
from typing import List
import pygame, math
from code_modules.spli... | EliasFredriksson/Tower_Defence_Reworked | code_modules/spline/spline.py | spline.py | py | 6,006 | python | en | code | 0 | github-code | 6 |
42679468935 | '''
經典題型,由於羅馬字母原則上是由大至小排列,故若是發現某一數字大於先前的數字,則代表大 - 小 (e.g., XV = 4)
故作答上只需使用一個迴圈由左掃至右,判斷一下目前的羅罵字與上一個的大小關係,若發現小的字母在大的字母左側,則記得要減去2倍的先前字母值
(不是挺好解釋的,詳情見程式碼)
'''
class Solution:
def eval_roman(self, symbol):
answer = 0
if('I' == symbol):
answer = 1
elif('V' == symbol):
an... | shawn2000100/LeetCode_Easy_Code | 13. Roman to Integer.py | 13. Roman to Integer.py | py | 1,379 | python | en | code | 1 | github-code | 6 |
70439517629 | import pyautogui
import cv2 as cv
import numpy as np
import keyboard
import time
from math import sqrt
from PIL import ImageGrab
import win32api, win32con
# https://stackoverflow.com/questions/5906693/how-to-reduce-the-number-of-colors-in-an-image-with-opencv
def kmeans_color_quantization(image, clusters=8, rounds=1):... | JirkaKlimes/gartic.io_bot | main.py | main.py | py | 5,990 | python | en | code | 0 | github-code | 6 |
27066265033 | #! /usr/bin/python
def solutionOneChecker(combinedLetters: str, testWord: str, dictWordScores: dict) -> bool:
"""
Check if a word uses all letters of the box
True = Valid Solution
"""
fullScore = len(combinedLetters)
#fullScore = 7
if dictWordScores[testWord] > fullScore:
return... | tmangan/PonderThis | 2022_December/Solution_Checker.py | Solution_Checker.py | py | 782 | python | en | code | 0 | github-code | 6 |
25528561437 | import tensorflow as tf
# Defince a "Computation Graph"
a = tf.constant(1) # Defince a constant Tensor
b = tf.constant(1)
c = a + b # Equal to c = tf.add(a, b),c is a new Tensor created by Tensor a and Tesor b's add Operation
sess = tf.Session() # Initailize a Session
c_ = sess.run(c) # Session的run() wil... | snowkylin/TensorFlow-cn | source/_static/code/en/basic/graph/1plus1.py | 1plus1.py | py | 407 | python | en | code | 854 | github-code | 6 |
225940000 | from sqlalchemy import Column, Integer, String, ForeignKey
from app.routers.db import Base
class Task(Base):
__tablename__ = 'tasks'
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
body = Column(String)
| gitdarsh/todo | todo/app/models/model.py | model.py | py | 248 | python | en | code | 0 | github-code | 6 |
31132813401 | from abc import ABC
from collections import OrderedDict, defaultdict
import torch
import torch.nn.functional as F
from torch import flatten
from torch.nn import Module, Conv2d, Dropout, Linear, BatchNorm2d, ReLU, Sequential, MaxPool2d
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LRScheduler
f... | bnwiran/tinyml-benchmark | models/models.py | models.py | py | 4,749 | python | en | code | 0 | github-code | 6 |
70396769467 | """ JAX functions to Calculate moving average.
Author: Toshinori Kitamura
Affiliation: NAIST & OSX
"""
from __future__ import annotations
import jax
from chex import Array
from jax import lax
@jax.jit
def calc_ma(lr: float, idx1: Array, idx2: Array, tb: Array, tb_targ: Array) -> Array:
"""Calculate moving averag... | omron-sinicx/ShinRL | shinrl/_calc/moving_average.py | moving_average.py | py | 1,289 | python | en | code | 42 | github-code | 6 |
17469039054 | from bs4 import BeautifulSoup
import requests
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
fx=open('WEB.txt','r',encoding="utf-8") ## FILENAME me file ka name dalna
line=fx.readline()
l=open('email_mailto.txt','a',encoding='utf-8')
def web_imrove(url):
print(url)
... | akkiei/Web_Scrapper | Mail_to.py | Mail_to.py | py | 1,282 | python | en | code | 0 | github-code | 6 |
17086061072 | from datetime import datetime
#convert date from YYYY-MM-DD-T to Date, Month, Year (in words)
#dfdsf
#dsfds
datetime
def date_convert(date):
date=str(date)
data=date.split('-') #year/month/day+time all separated by dash
daydate=data[-1].split() #data[-1] is day+time, separated by a space
day=daydate[0]... | veliakiner/SmogonQDB | date_convert.py | date_convert.py | py | 1,428 | python | en | code | 0 | github-code | 6 |
19980146036 | from pytube import YouTube
from PySimpleGUI import PySimpleGUI as sg
sg.theme("reddit")
layout = [
[sg.Text("URL"), sg.Input(key="url")],
[sg.Button("Fazer o Download")]
],
janela = sg.Window("Video Downloader", layout)
while True:
eventos, valores = janela.read()
if eventos == sg.WINDOW_CLOSED:
... | jopsfernandes/video_downloader | youtube.py | youtube.py | py | 525 | python | en | code | 0 | github-code | 6 |
38791493575 | from flask import Flask
from flask_restful import Resource, Api
import __init__
app=Flask(__name__)
api=Api(app)
class Quote(Resource):
@app.route('/wifi/<int:id>')
def get(id):
x=main.main_(id)
if x==-1:
return 'Not found', 404
else:
return x, 200
... | Kaedone/WI-FI_checker | api.py | api.py | py | 510 | python | en | code | 0 | github-code | 6 |
11956903610 | """
a pure python implementation of the heap sort algorithm
"""
def m_heap_sort(arr):
"""heap sort
:type arr: array
:rtype: array
>>> m_heap_sort([3, 2, 1, 4, 5])
[1, 2, 3, 4, 5]
>>> m_heap_sort([])
[]
>>> m_heap_sort([1])
[1]
"""
n = len(arr)
for i in range(n/... | wancong/leetcode | sort/m_heap_sort.py | m_heap_sort.py | py | 1,074 | python | en | code | 0 | github-code | 6 |
10304764794 | # Calculate how long it takes to save enough money make a down payment on a house
def app():
# INPUTS
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = int(input("Enter the cost of your dream... | lsunl/cs60001-python | ps1a.py | ps1a.py | py | 770 | python | en | code | 0 | github-code | 6 |
19772192847 | # -*- coding: utf-8 -*-
#-----------
#@utool.indent_func('[harn]')
@profile
def test_configurations(ibs, acfgstr_name_list, test_cfg_name_list):
r"""
Test harness driver function
CommandLine:
python -m ibeis.expt.harness --exec-test_configurations --verbtd
python -m ibeis.expt.harness --e... | smenon8/ibeis | _broken/old_test_harness.py | old_test_harness.py | py | 1,586 | python | en | code | null | github-code | 6 |
33983748034 | from django.shortcuts import render, redirect
from django.views.generic import ListView, \
CreateView, DetailView, UpdateView, DeleteView
from .models import Post, Review
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from accounts.models import UserFollows
from .forms import PostFo... | maximesoydas/maxweb | website/views.py | views.py | py | 6,223 | python | en | code | 0 | github-code | 6 |
40132948104 | import argparse
from math import sqrt
import Image
import ImageDraw
def color_map(v):
assert 0 <= v <= 255
if v == 0: return (0, 0, 0)
if v == 255: return (255, 255, 255)
if v < 4 * 8:
# 0 .. 31
return (0, 255 - (31 * 4) + v * 4, 0)
if v < 16 * 8:
# 32 .. 127
# 0 .. ... | nishio/binary_color | binary_color.py | binary_color.py | py | 1,161 | python | en | code | 1 | github-code | 6 |
39784068604 | import filecmp, os, sys
sys.path.append('c:\\dev\\pytWinc\\superpy')
sys.path.append('c:\\dev\\pytWinc\\superpy\\utils_superpy')
from utils.utils import calculate_inventory, get_path_to_directory_of_file
directory_of_testcase = "fn_calculate_inventory"
path_to_directory_of_testcase = get_path_to_directory_of_file(dir... | davidjfk/David_Sneek_Superpy | test_utils/fn_calculate_inventory/test_calculate_inventory.py | test_calculate_inventory.py | py | 2,936 | python | en | code | 0 | github-code | 6 |
35430795829 |
class odds_compare:
def __init__(self, api_array):
self.api_array = api_array
# calculate odds comparisons for all available matches
def calculate_comparisons(self):
result = []
for i in self.api_array:
result_dict = {
"home": "",
"awa... | abhid94/Compare_Odds_Bot | odds_compare.py | odds_compare.py | py | 2,507 | python | en | code | 1 | github-code | 6 |
43626494196 | # VIIRS packge
from __future__ import division, print_function
import datetime
import numpy as np
from osgeo import gdal
from scipy import ndimage
import core
import env
bumper = env.environment()
class viirs(core.raster):
def __init__(self):
core.raster.__init__(self,'viirs')
retur... | Servir-Mekong/bump | bump/viirs.py | viirs.py | py | 2,977 | python | en | code | 0 | github-code | 6 |
25497427443 | import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
class TinyImageNet:
def __init__(self, root, train=True, transform=None, target_transform=None, test_transform=None, target_test_transform=None):
self.transform = transform
self.targe... | ruixiang-wang/Incremental-Learning-Research | PRE-master/TinyImageNet.py | TinyImageNet.py | py | 4,064 | python | en | code | 4 | github-code | 6 |
40565109992 | # 1-Escribe un programa que pida al usuario una palabra y luego imprima cada
# letra de la palabra en una línea separada
def programa():
usuario = list(input('Ingresa una palabra: '))
contador = 0
while len(usuario) > contador:
print(usuario[contador])
contador += 1
programa()
| maximiliano1997/informatorio-2023 | Week-3/Ejercicios Estructuras de Datos Loops/ejercicio1.py | ejercicio1.py | py | 313 | python | es | code | 0 | github-code | 6 |
38365303311 | from datetime import datetime, timedelta
import logging
import os
import json
import pandas as pd
import requests
try:
from .exceptions import ApexApiException
except:
from exceptions import ApexApiException
class Apex_API:
def __init__(self, api_key: str):
self.api_key = api_key
loggin... | jyablonski/apex_api_scraper | src/utils.py | utils.py | py | 2,484 | python | en | code | 0 | github-code | 6 |
71634094907 | ################### PRACTICAL_ EMAIL SLICING ##########################
name = input('please enter your name: ')
email = input('please enter your email: ')
name = name.strip().capitalize()
username = email[:email.index('@')]
username = username.strip().capitalize()
website = email[email.index('@') + 1:]
print(f'Hello... | AhmadFouda/Python-proplem-solving | email_slicing.py | email_slicing.py | py | 425 | python | en | code | 0 | github-code | 6 |
40129830394 | """
Get Distances of Shortest Path (Dijkstra)
edges: dict<from:int, dict<to:int, cost:number>>
"""
from heapq import heappush, heappop
def one_to_one(
start, goal, num_vertexes, edges,
INF=9223372036854775807, UNREACHABLE=-1):
distances = [INF] * num_vertexes
distances[start] = 0
queue ... | nishio/atcoder | libs/dijkstra.py | dijkstra.py | py | 3,668 | python | en | code | 1 | github-code | 6 |
75189168508 | import ALU, I_MEM, CLK, PC, REG_BANK, D_MEM, threading
#OpCode = 0000 0000
# Im[-1] instr
class CONTROL_UNIT(threading.Thread):
def __init__(self, LongRegFtoD, OpCode):
self.OpCode = OpCode
self.MyLongRegFtoD = LongRegFtoD
self.ALUControl = OpCode[4:8]
#indica si usa la Dir_... | ger534/Proyecto2Arqui2 | procesador/CONTROL_UNIT.py | CONTROL_UNIT.py | py | 1,126 | python | en | code | 0 | github-code | 6 |
72579615228 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 17 11:47:02 2019
@author: hwan - Took out relevant code from dolfin's plotting.py _plot_matplotlib code
- To enter dolfin's own plotting code, use dl.plot(some_dolfin_object) wheresome_dolfin_object is a 3D object and an error will be ... | cotran2/Thermal_Fin_Heat_Simulator | Utilities/plot_3D.py | plot_3D.py | py | 1,852 | python | en | code | 0 | github-code | 6 |
19554797850 | import sys
sys.setrecursionlimit(2500)
def dfs(graph, depth, node):
parent = graph[node] - 1
if -2 == parent or depth[node] + 1 <= depth[parent]:
return
depth[parent] = depth[node] + 1
dfs(graph, depth, parent)
def solution(n, managers):
depth = [1 for _ in range(n)]
for i ... | jiyoulee/problem-solving-v1 | graph/115A.py | 115A.py | py | 554 | python | en | code | 0 | github-code | 6 |
73785815229 | """empty message
Revision ID: 391b24b33343
Revises: e4338c095afb
Create Date: 2021-06-24 16:47:10.434392
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '391b24b33343'
down_revision = 'e4338c095afb'
branch_labels = None
depends_on = None
def upgrade():
# ... | composerben/flask-group-project | migrations/versions/20210624_164710_fix_migration.py | 20210624_164710_fix_migration.py | py | 1,640 | python | en | code | 13 | github-code | 6 |
29827630738 | #This file will only be needed to run
import pandas as pd
import numpy as numpy
from datetime import date
import datetime
import os
class box:
def __init__(self):
self.task_done = ""
self.no_of_day = (datetime.date.today() - date(1997, 8, 21)).days
self.dest = ""
self.wake_up = "" #should change in future
s... | Geeks-Sid/habit_organizer | main.py | main.py | py | 4,237 | python | en | code | 0 | github-code | 6 |
40370617674 | '''
Leer un número entero de dos dígitos y determinar si los dos dígitos son iguales.
'''
def numero(n):
if int(n) >= 10 and int(n) <= 99:
if int(n[0]) == int(n[1]):
return True
else:
return False
Dosdigitos = input("Ingrese un número: ")
respuesta = numero(Dosdigitos)
if respue... | Natacha7/Python | Ejercicios_unidad2.py/DosDigitos_iguales.py | DosDigitos_iguales.py | py | 451 | python | es | code | 0 | github-code | 6 |
2580004662 | from odoo import models, fields
class AccountTaxWithholdingRule(models.Model):
_name = "account.tax.withholding.rule"
_description = "account.tax.withholding.rule"
_order = "sequence"
sequence = fields.Integer(
default=10,
)
# name = fields.Char(
# required=True,
# )
... | ingadhoc/account-payment | account_withholding_automatic/models/account_tax_withholding_rule.py | account_tax_withholding_rule.py | py | 854 | python | en | code | 42 | github-code | 6 |
73750770109 | from operator import index
from meal import Meal
import json
import sqlite3
class Meal_Data:
"""Data layer to be used in conjunction with the Meal class"""
def __init__(self, filename = "foodinfo.json"):
"""Initializes Meal_Data"""
self.filename = filename
def meal_add(self, meal:Meal):
... | zaepho/DinnerDecider | mealdata.py | mealdata.py | py | 3,719 | python | en | code | 0 | github-code | 6 |
22807758362 | import time
import random
import threading
"""
信号量(英语:Semaphore)又称为信号标,是一个同步对象,用于保持在0至指定最大值之间的一个计数值。
当线程完成一次对该semaphore对象的等待(wait)时,该计数值减一;
当线程完成一次对semaphore对象的释放(release)时,计数值加一。
当计数值为0,则线程等待该semaphore对象不再能成功直至该semaphore对象变成signaled状态。
semaphore对象的计数值大于0,为signaled状态;计数值等于0,为nonsignaled状态.
semaphore对象适用于控制一个仅支持有限个用户的... | sola1121/practice_code | python3/python并行编程手册/ch02/P42_使用信号量实现线程同步_生产者-消费者模型.py | P42_使用信号量实现线程同步_生产者-消费者模型.py | py | 1,558 | python | zh | code | 0 | github-code | 6 |
12056898935 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code for this script is originally at:
https://github.com/dfm/george/blob/master/docs/_code/model.py
"""
from __future__ import division, print_function
import emcee
import triangle
import numpy as np
import cPickle
import matplotlib.pyplot as pl
import george
from ... | karenyyng/shear_gp | george_examples/model.py | model.py | py | 5,729 | python | en | code | 1 | github-code | 6 |
27330667755 | import requests
import time
from bs4 import BeautifulSoup
import urllib.request
import re
import json
start_time = time.time()
link_3 = []
link_4 = []
link_5 = []
link_6 = []
links = []
g = ""
b = ""
d = ""
y = ""
ya = ""
ask = ""
domain = ""
emails = []
new_emails = []
mails = []
def crawl(... | realchief/EmailScraping-BeautifulSoup | filter_crwl_dft_srchegn_updated.py | filter_crwl_dft_srchegn_updated.py | py | 2,298 | python | en | code | 0 | github-code | 6 |
39792208434 | from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import utils
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.as... | SieniAlessandro/E2E-Secure-Chat | Server/Security/Security.py | Security.py | py | 14,411 | python | en | code | 1 | github-code | 6 |
33346153360 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 05 11:52:00 2015
@author: Vahndi
"""
import pandas as pd
from numpy import float64, random, inf
class Optimiser(object):
def __init__(self, categoricalSettings,
oldResultsDataFrame = None, resultsColumn = 'Results',
no... | vahndi/mazurka_classifier | ncd/optimiser.py | optimiser.py | py | 5,947 | python | en | code | 0 | github-code | 6 |
31036686251 | tampungan_barang = []
# Tambah barang
def tambah_barang():
print(' TAMBAH BARANG ')
while True :
barang = input('Masukkan barang : ')
if barang in tampungan_barang:
print('Barang sudah tersedia')
pass
elif barang not in tampungan_barang:
tampungan_bar... | Mage29/Codingan_ASD_3 | Program_Barang.py | Program_Barang.py | py | 4,389 | python | id | code | 0 | github-code | 6 |
7545685477 | import psycopg2
DBNAME = "news"
def fetch_all(query, params):
"""
execute a query and fetch all result from it
:param query: the query to execute
:param params: parameters of the query
:return: result of this query
"""
# it's kind time consuming every time we open and close a connection
... | akudet/fsnd-proj3 | reporter_db.py | reporter_db.py | py | 2,454 | python | en | code | 0 | github-code | 6 |
14785766794 | """User model tests."""
# run these tests like:
#
# python -m unittest test_user_model.py
import os
from unittest import TestCase
from models import db, User, Message, Follows, Likes
os.environ['DATABASE_URL'] = "postgresql:///warbler-test"
# Now we can import app
from app import app
# Create our tables (we... | mahado13/Twitter-Clone | test_message_model.py | test_message_model.py | py | 3,685 | python | en | code | 0 | github-code | 6 |
36282438996 | import datetime
import requests
from bs4 import BeautifulSoup as bs4
from flask import Flask
from flask_restful import Resource, Api
OYK_URL = "https://oulunkylanyhteiskoulu.fi/"
def get_food() -> list:
with requests.Session() as s:
g = s.get(OYK_URL)
bs = bs4(g.text, 'html.parser')
today = ... | drstuggels/oyk-food | main.py | main.py | py | 908 | python | en | code | 0 | github-code | 6 |
74530223548 | import numpy as np
class Board:
def __init__(self):
self.grid = np.zeros((12, 26), dtype=int)
self.score = 0
def check_in_console(self):
for j in range(0, 26):
for i in range(0, 12):
print(self.grid[i][j], end='')
print()
def insert_block(s... | Jurand76/Z2J | tetris/board.py | board.py | py | 3,436 | python | en | code | 0 | github-code | 6 |
29457010542 | #!/usr/bin/env python
import sys
import commands
import string
import datetime
import logging
import logging.handlers
from optparse import OptionParser
from random import choice
def print_error(ret, do_exit=False, msg=""):
"""
ret is the tuple returned by commands.getstatusoutput. If ret[0] is not 0,
t... | alvarolopez/egi-certool | run_tests.py | run_tests.py | py | 10,232 | python | en | code | 1 | github-code | 6 |
72592445628 | import numpy as np
from .lanczos import lanczos_resample_one, lanczos_resample_three
def coadd_psfs(
se_psfs, se_wcs_objs, coadd_wgts,
coadd_scale, coadd_dim):
"""Coadd the PSFs.
Note that this routine assumes that the PSFs in the SE image have their
centers at the image origin and that ... | beckermr/metadetect-coadding-sims | coadd_mdetsims/coadd.py | coadd.py | py | 3,790 | python | en | code | 0 | github-code | 6 |
32456637613 | # The purpose of this function is to take the vertex property map returned when using gt.add_edge_list() with the option hashed=True and add it as an internal vertex property.
# - For some reason I have only gotten this to consistently work when I define the vertex property map by looping over vertices. I had issues wi... | jamiefogel/Networks | Code/Modules/add_ids_as_vertex_property.py | add_ids_as_vertex_property.py | py | 693 | python | en | code | 0 | github-code | 6 |
39269323605 | from sqlalchemy import create_engine
from tests.util import RPCTest
class PDNSTest(RPCTest):
def cleanup_pdns_db(self, db_uri):
with create_engine(db_uri).begin() as conn:
conn.execute('delete from domains')
conn.execute('delete from domainmetadata')
conn.execute('dele... | 1and1/dim | dim-testsuite/tests/pdns_test.py | pdns_test.py | py | 631 | python | en | code | 39 | github-code | 6 |
74472078906 | import os
import pickle
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from openpyxl import Workbook
def save_pickle(data, filename):
with open(filename, 'wb') as file:
pickle.dump(data, file)
def load_pickle(filename):
with open(filename, 'rb') as file:
dat... | Lisiozmur/Njpo | Ćwiczenie5/Zadanie1.py | Zadanie1.py | py | 2,117 | python | en | code | 0 | github-code | 6 |
24510539081 | import json
import frappe
from frappe.model.document import Document
from frappe.utils.safe_exec import get_safe_globals, safe_exec
from frappe.integrations.utils import make_post_request
from frappe.desk.form.utils import get_pdf_link
from frappe.utils.background_jobs import enqueue
def validate(self, method):
if s... | finbyz/whatsapp_erpnext | whatsapp_erpnext/whatsapp_erpnext/doc_events/notification.py | notification.py | py | 5,911 | python | en | code | 0 | github-code | 6 |
6727912141 | """
Module for parsing arguments.
"""
import sys
import argparse
import os
from pathlib import Path
from typing import Any
__author__ = "Stijn Arends"
__version__ = "v0.1"
__data__ = "21-8-2022"
class ArgumentParser:
"""
Class to parse the input arguments.
"""
def __init__(self) -> None:
sel... | molgenis/benchmark-gwas-prio | prioritization_methods/NetWAS/arg_parser.py | arg_parser.py | py | 3,976 | python | en | code | 0 | github-code | 6 |
43266096059 | import discord
import os
from keep_alive import keep_alive
from discord.ext import commands
from better_profanity import profanity
os.system('python3 -m commands')
profanity.load_censor_words_from_file('./profanity.txt')
client = commands.Bot(command_prefix = '$')
money_registry = []
list1 = ['myself', 'me', 'i']
@... | LittlRayRay/Censorbot | main.py | main.py | py | 2,297 | python | en | code | 0 | github-code | 6 |
11458247441 | # 首先要导入一个Select类
from selenium.webdriver.support.select import Select
from selenium import webdriver
import time
# 打开浏览器,进入携程旅行官网
driver = webdriver.Chrome()
driver.get('https://www.ctrip.com/?sid=155952&allianceid=4897&ouid=index')
driver.maximize_window() # 最大化窗口
# 休眠5秒钟
time.sleep(5)
# 通过Select类选择下拉框选项,只能是控件类型(tag_... | Ailian482/WebSelenium | Auto_Test/20_下拉框选择处理.py | 20_下拉框选择处理.py | py | 1,363 | python | zh | code | 0 | github-code | 6 |
21368489956 | import numpy as np
import matplotlib.pyplot as plt
import glob
import os
import ruamel.yaml
import matplotlib.colors as colors
import matplotlib.cm as cmx
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'fam... | physikier/magnetometer | src/analysis.py | analysis.py | py | 4,786 | python | en | code | 0 | github-code | 6 |
37985935295 | #! /usr/bin/env python3
import audioInterface
import os
import yaml
import sys
from datetime import datetime
from gpiozero import Button
from signal import pause
from pydub import AudioSegment
from pydub.playback import play
try:
with open("config.yaml") as f:
config = yaml.load(f, Loader=yaml.FullLoader... | nickpourazima/rotary-phone-audio-guestbook | audioGuestBook.py | audioGuestBook.py | py | 1,781 | python | en | code | 13 | github-code | 6 |
74637154747 | import time
import redis
cache = redis.StrictRedis(host='redis', decode_responses=True, db=0, port=6379)
def update_and_get_hit_count():
""""""
print('In utils/update_and_get_hit_count')
retries = 5
while True:
try:
return cache.incr('hits')
except redis.exceptions.Connec... | ShukujiNeel13/composetest | utils.py | utils.py | py | 770 | python | en | code | 1 | github-code | 6 |
26135102637 | import cv2 as cv
import numpy as np
img = cv.imread('/home/ai3/Desktop/common/ML/Day13/girl.jpg',0)
kernel = np.ones((2,2),np.uint8)
open1 = cv.morphologyEx(img,cv.MORPH_OPEN,kernel)
open2 = cv.morphologyEx(img,cv.MORPH_CLOSE,kernel)
open3 = cv.morphologyEx(open1,cv.MORPH_CLOSE,kernel)
img=np.hstack((open1,open2,ope... | 94akshayraj/AI-program | ML ans/day13/3.py | 3.py | py | 365 | python | en | code | 0 | github-code | 6 |
5471431928 | """
Design-of-Experiments Driver.
"""
from __future__ import print_function
import traceback
import inspect
from openmdao.core.driver import Driver, RecordingDebugging
from openmdao.core.analysis_error import AnalysisError
from openmdao.utils.mpi import MPI
from openmdao.recorders.sqlite_recorder import SqliteRecor... | rowhit/OpenMDAO-1 | openmdao/drivers/doe_driver.py | doe_driver.py | py | 10,428 | python | en | code | null | github-code | 6 |
74668147066 | import numpy as np
with open('in.txt') as f:
lines = f.read().strip().splitlines()
s = set([0])
h = 10 * [0]
for line in lines:
dir, cnt = line.split()
cnt = int(cnt)
for _ in range(cnt):
h[0] += {
'U': -1j,
'D': 1j,
'R': 1,
'L': -1
}[dir]
for i in range(9):
if abs(h... | dionyziz/advent-of-code | 2022/9/9b.py | 9b.py | py | 482 | python | en | code | 8 | github-code | 6 |
26238931261 | #! /usr/bin/env python
'''
A script that will compare two Dawn IMG files.
'''
import sys
import os
import os.path
import dawn
def main(argv=None):
'''
Receives two dawn image filenames from the command line and compares the
data areas.
'''
if argv is None:
argv = sys.argv
direcory_name... | sbn-psi/data-tools | dawn/dawndirdiff.py | dawndirdiff.py | py | 2,520 | python | en | code | 0 | github-code | 6 |
12688443618 | # https://leetcode.com/problems/reverse-linked-list/
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList_(self, head: Optional[ListNode]) -> ListNode: # input as list
# empty head
if ... | zvovov/competitive_coding | leetcode/neetcode_150/reverse_linked_list.py | reverse_linked_list.py | py | 1,637 | python | en | code | 0 | github-code | 6 |
6770936001 | '''
Write a Python program to calculate the area of regular polygon.
Input number of sides: 4
Input the length of a side: 25
The area of the polygon is: 625
'''
from math import *
n=int(input())
lenght=int(input())
perimetr=n*lenght
apothem=lenght/(2*(tan(pi/n)))
area=(apothem*perimetr)/2
print(round(area)) | AigerimKubeyeva/pp2 | Week4/Lab4/math/3.py | 3.py | py | 313 | python | en | code | 0 | github-code | 6 |
70435413308 | import re
import emoji
def preprocess_string(text):
"""
입력받은 text 를 전처리 하는 함수.
:param text: str
:return : str
"""
# 이모티콘부터 제거
no_emoticon = ''
for char in text:
if char not in emoji.UNICODE_EMOJI:
no_emoticon += char
# 특수문자 기준 split
no_punctuation = re.sp... | teammatmul/project-purifier | purifier/preprocess.py | preprocess.py | py | 1,254 | python | ko | code | 78 | github-code | 6 |
37601085068 |
from sqlwrapper import gensql, dbget, dbput
import json
import datetime
def HOTEL_FD_POST_UPDATE_CheckinGuestArrivals(request):
d = request.json
res_id = d.get("Res_id")
unique_id = d.get("Res_unique_id")
pf_id = d.get("pf_id")
a = {}
RES_Log_Time = datetime.datetime.utcnow()+datetime... | infocuittesting/hotel360-second-version | HOTEL_FD_POST_UPDATE_CheckinGuestArrivals.py | HOTEL_FD_POST_UPDATE_CheckinGuestArrivals.py | py | 3,531 | python | en | code | 0 | github-code | 6 |
2501424452 | from os import listdir
from PIL import Image
#list src pic
DIR = 'pic'
#print listing of images
img_list = listdir("pic")
#enter and calculate ratio
sh_ent = int(input("Shakal ratio (compress ratio):"))
sh = 100 - sh_ent
#work with image
for filename in img_list:
outname = "out/" + filename
... | vakarianplay/Pic_tools | shakal (compress)/shak.py | shak.py | py | 505 | python | en | code | 0 | github-code | 6 |
20423188987 |
#Give the Big-O performance of the following code fragment:
def findRepeated(L):
"""
determines whether all elements in a given list L are distinct
"""
n=len(L)
for i in range(n):
for j in range(i+1, n):
if L[i]==L[j]:
return True
return False
| tsaoalbert/test.tensor.flow | 1.weekend.asymptotic,stack.queue.deque.recursion.sorting/t.py | t.py | py | 277 | python | en | code | 0 | github-code | 6 |
650532287 | #! /bin/python
import os
import sys
import json
import luigi
import numpy as np
import nifty.tools as nt
import nifty
import nifty.graph.rag as nrag
from vigra.analysis import relabelConsecutive
from elf.segmentation.clustering import mala_clustering, agglomerative_clustering
import cluster_tools.utils.volume_utils... | constantinpape/cluster_tools | cluster_tools/watershed/agglomerate.py | agglomerate.py | py | 8,389 | python | en | code | 32 | github-code | 6 |
10623814818 | from asyncio import sleep
from discord import Forbidden
from discord.ext import commands
from Utils.domain_tester import get_domain_embed
from Utils.file_tester import get_file_embed
class DmCommands(commands.Cog, name="Dm Commands"):
"""
Cog including all Commands that are dm only
"""
def __init__... | veni-vidi-code/VirusTotalDiscordBot | Cogs/DmCommands.py | DmCommands.py | py | 1,634 | python | en | code | 3 | github-code | 6 |
5285437188 | from ...robot import Robot
from stt_watson.SttWatsonLogListener import SttWatsonLogListener
from recording.Record import Record
from watson_client.Client import Client
from utils.SignalHandler import SignalHandler
import threading
import signal
import os
class WatsonRobot(Robot):
def __init__(self, config, speak... | lowdev/alfred | robot/stt/watson/watson.py | watson.py | py | 1,199 | python | en | code | 0 | github-code | 6 |
23932735079 | import torch
from torch import nn
from torch.autograd import Variable
import numpy as np
from util import get_data
from torch.utils.data import DataLoader
from torch.nn import functional as F
from torch.optim import Adam
from variables import*
from matplotlib import pyplot as plt
class MnistRegression(object):
def... | 1zuu/Pytroch-Examples | Mnist/mnist_regression.py | mnist_regression.py | py | 2,842 | python | en | code | 2 | github-code | 6 |
72151412028 | from python_celery_worker.services.db import db_engine
def update_task(id):
"""
Update the task status in the database
:param id:
:return:
"""
conn = db_engine.connect()
conn.execute(
'update tasks set status = %s, message = %s, updated_at = NOW() where id = %s',
'complete... | fraserreed/blog-samples | laravel-tasks-celery-worker/python_celery_worker/python_celery_worker/services/db_tasks.py | db_tasks.py | py | 378 | python | en | code | 9 | github-code | 6 |
40071040492 | from collections import Counter
class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
# anagram: str with same histgram
res = []
lp = len(p) -1
ls = len(s)
pCount = Counter(p)
... | lucy9215/leetcode-python | 438_findAllAnagramsInAString.py | 438_findAllAnagramsInAString.py | py | 619 | python | en | code | 0 | github-code | 6 |
31653842077 | #!/usr/bin/env python3
""" Problem 8.7 in CtCI book
"""
def permute(my_str):
_permute("", my_str)
def _permute(so_far, remaining):
if len(remaining) == 0:
print(so_far)
else:
for i in range(len(remaining)):
following = so_far + remaining[i]
rest = remaining[:i] + remaining[i+1:]
_permut... | ilee38/practice-python | coding_problems/CTCI_recursion_dp/perms_no_dups.py | perms_no_dups.py | py | 338 | python | en | code | 0 | github-code | 6 |
1112499487 | """ VirtualMachineHandler provides remote access to VirtualMachineDB
The following methods are available in the Service interface:
- insertInstance
- declareInstanceSubmitted
- declareInstanceRunning
- instanceIDHeartBeat
- declareInstanceHalting
- getInstancesByStatus
- declareInstanc... | DIRACGrid/VMDIRAC | VMDIRAC/WorkloadManagementSystem/Service/VirtualMachineManagerHandler.py | VirtualMachineManagerHandler.py | py | 18,285 | python | en | code | 6 | github-code | 6 |
19019856386 | def nextInt(): return int(input())
def nextInts(): return map(int, input().split())
def nextIntList(): return list(nextInts())
MOD = 10**5
def calc(x):
y = 0
x_c = x
while x_c > 0:
x_c, y_c = divmod(x_c, 10)
y += y_c
return (x + y) % MOD
def solve():
N, K = nextInts()
start_lis... | minheibis/atcoder | questions/typical90/058/myans_00.py | myans_00.py | py | 951 | python | en | code | 0 | github-code | 6 |
17424247870 | from setuptools import setup
import dorm
with open("README.md", "r") as readme:
long_description = readme.read()
setup(
name="dorm",
version=dorm.version,
description="A tiny SQLite ORM for Python.",
long_description=long_description,
long_description_content_type="text/markdown",
author=... | dcwatson/dorm | setup.py | setup.py | py | 804 | python | en | code | 1 | github-code | 6 |
40695061264 | """empty message
Revision ID: 41124ac6e47e
Revises: 57296b50c499
Create Date: 2014-11-30 17:08:44.396000
"""
# revision identifiers, used by Alembic.
revision = '41124ac6e47e'
down_revision = '57296b50c499'
from alembic import op
import sqlalchemy as sa
def upgrade():
### com... | StasEvseev/adminbuy | migrations/versions/41124ac6e47e_.py | 41124ac6e47e_.py | py | 800 | python | en | code | 0 | github-code | 6 |
12814211947 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0002_userinfo_grade'),
]
operations = [
migrations.CreateModel(
name='Events',
... | asp3/StudentAccounts | student/migrations/0003_auto_20151025_1630.py | 0003_auto_20151025_1630.py | py | 906 | python | en | code | 3 | github-code | 6 |
34862433797 | from django import template
from django.urls import NoReverseMatch, reverse
from utilities.utils import get_viewname, prepare_cloned_fields
register = template.Library()
#
# Instance buttons
#
@register.inclusion_tag('buttons/clone.html')
def clone_button(instance):
url = reverse(get_viewname(instance, 'add'))... | Status-Page/Status-Page | statuspage/utilities/templatetags/buttons.py | buttons.py | py | 2,140 | python | en | code | 45 | github-code | 6 |
171117843 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from rp_ui_harness import RequestPolicyTestCase
TEST_URL = "http://www.maindomain.test/link_1.html"
PREF_DEFAULT_ALLOW... | RequestPolicyContinued/requestpolicy | tests/marionette/tests/links/text_selection/test_open_in_current_tab.py | test_open_in_current_tab.py | py | 1,514 | python | en | code | 253 | github-code | 6 |
35426908825 | #!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate
a=0.7
b=0.6
X = np.arange(0,2.4,0.2)
Y = np.arange(0,2.4,0.2)
m,p = np.meshgrid(X,Y)
mdot = np.divide(1,1+np.square(p))- np.multiply(b,m)
pdot = np.subtract(m,np.multiply(a,p))
fig, ax = plt.subplots()
q=... | martinaoliver/GTA | ssb/m1a/numeric/Practical_full_solutions_jupyter/python_script_solutions/phase_portrait_autorinhib_20190926.py | phase_portrait_autorinhib_20190926.py | py | 991 | python | en | code | 0 | github-code | 6 |
32111228276 | import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack, signal
# 고주파 성분만 날리는 fft
# def get_filtered_data(in_data, filter_value=0.004):
def del_high_freq(in_data, filter_value=0.004):
"""
:param in_data: 대상 시계열 신호
:param filter_value: filter_value이상의 주파수를 가지는 신호를 날림
:return: fft 결과... | HanNayeoniee/visual-fatigue-analysis | analysis/fft.py | fft.py | py | 6,952 | python | en | code | 1 | github-code | 6 |
34958652342 | import torch
import torch.nn as nn
import torch.nn.functional as F
def normalize_l2(x):
"""
Expects x.shape == [N, C, H, W]
"""
norm = torch.norm(x.view(x.size(0), -1), p=2, dim=1)
norm = norm.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
return x / norm
def pair_cos_dist(x, y):
cos = nn.Cosin... | arthur-qiu/adv_vis | attack_methods/feature_targets.py | feature_targets.py | py | 2,092 | python | en | code | 0 | github-code | 6 |
6112251845 | import sys
#sys.path.append('/usr/local/Cellar/opencv3/3.2.0/lib/python2.7/site-packages')
sys.path.append("/usr/local/Cellar/opencv3/3.2.0/lib/python3.5/site-packages")
import cv2
import numpy as np
import os
import random
def show_image(im):
height, width = im.shape[:2]
res = cv2.resize(im,(2*width... | ltecot/humanMotionClassification | img_processing.py | img_processing.py | py | 3,562 | python | en | code | 4 | github-code | 6 |
11552601944 | import csv
import getopt, sys
from moviepy.editor import VideoFileClip, concatenate_videoclips
folder = '/Videos/'
# file name of the video and config file
event = '20221002 PREECNLBVA'
output_file = None # Create a file for each segment
#output_file = 'check' # Compile the clips with a check flag
output_file = 'high... | jordiyeh/video-cut | create_highlight_videos.py | create_highlight_videos.py | py | 3,744 | python | en | code | 0 | github-code | 6 |
4234376251 | import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from scipy.optimize import minimize
from sklearn.metrics import mean_squared_error as mse
def SIR():
def prediction(beta, gamma, population, i0, r0, d0, time_predict):
def SIR_model(y, t, beta, gamma, population):
... | FBWeimer/Plague-Doctor | Plague Doctor/plaguedoctor/__init__.py | __init__.py | py | 2,604 | python | en | code | 0 | github-code | 6 |
42483900439 | import pandas as pd
import networkx as nx
import json
hierarchy_df = pd.read_csv('hierarchy_table.csv', index_col=0, dtype=str)
graph_network = nx.from_pandas_edgelist(
hierarchy_df,
source='Parent',
target='Child',
)
json_graph = json.dumps(graph_network, default=nx.node_link_data)
# Using a JSON strin... | diegopintossi/graph_network | graph_network.py | graph_network.py | py | 398 | python | en | code | 0 | github-code | 6 |
34607190454 | #通过node2vec算法获取的节点向量表示计算相似度
import math
import os
import time
import pandas as pd
import numpy as np
#获取所有节点的向量表示形式
def getNodeVector(fileEMB, raw_dataset_path):
nodeVecDict = {}
raw_dataset = np.loadtxt(raw_dataset_path, delimiter=',')
m, n = raw_dataset.shape
pro_file = pd.read_csv(fileEMB)
pro =... | LittleBird120/DiseaseGenePredicition | DiseaseGenePredicition/20210316Disease_gene_prediction_algorithm_COVID-19/algorithm/simNode2vec.py | simNode2vec.py | py | 2,528 | python | en | 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.