seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
706855437
def delit(a): res = [] i = 1 while i * i < a + 1: if a % i == 0: res.append(i) if i != a // i: res.append(a // i) i += 1 return sorted(res) # Возращает делители числа print(delit(48))
Apersant1/Algorithms-for-EGE
task25INFO.py
task25INFO.py
py
281
python
ru
code
0
github-code
6
31111080784
#https://leetcode.com/problems/longest-consecutive-sequence/submissions/ """ Q)Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 1)Iterate over the array 2)If the for every element i if i-1 is not in the set, make curr = 1, and curr_streak = 1 3)If curr+1 is in set incr...
sparsh-m/30days
d4_3.py
d4_3.py
py
830
python
en
code
0
github-code
6
8599562923
import webbrowser import msal import logging import requests import json from msal import PublicClientApplication APPLICATION_ID = '31a4641c-9cae-4d30-a2d4-c104bf383785' CLIENT_SECRET = '5M78Q~QVl-rib2HqHVJ4xhRe-XWcGySwtZMgPbjz' authority_url = 'https://login.microsoftonline.com/common/' base_url = 'https://graph.mi...
tvcastro1/projetos-analise-dados
citrix-podio/demitidos/emailer.py
emailer.py
py
3,963
python
en
code
0
github-code
6
5140782550
# Requirements: # Device needs to lock on to their system # Add subroutine to detect a start-of-the-packet marker # Four chars that are all different # Find number of characters from the beginning of the buffer to the end of first four-char marker class DayFive: def __init__(self): text_file = open("../in...
nunenoriu/advent-of-code-2022
day01-10/daySix.py
daySix.py
py
4,579
python
en
code
0
github-code
6
9063496529
# -*- coding: utf-8 -*- # --- # @Software: PyCharm # @Site: # @File: num_clustering.py # @Author: Alan D.Chen # @E-mail: chense_mail@126.com # @Time: 2020,八月 07 # --- import pandas as pd from sklearn.cluster import KMeans, MeanShift, AgglomerativeClustering, DBSCAN, spectral_clustering from sklearn import metrics from ...
Alan-D-Chen/CDIoU-CDIoUloss
anchor_generater/num_clustering.py
num_clustering.py
py
6,580
python
en
code
25
github-code
6
2894455012
import numpy as np import matplotlib.pyplot as plt def gaussEliminationLS( m, n, a, x): for i in range(m-1): for k in range(m): if abs(a[i][i]<abs(a[k][i])): for j in range(n): temp= a[i][j] a[i][j]= a[k][j] a[k][j]= te...
meheraj2325/CSE-3212-Numerical-Methods-Lab
lab4/cubic_spline2.py
cubic_spline2.py
py
2,688
python
en
code
0
github-code
6
30763331030
import sys import torch import ool.picture.models.thirdparty.space.model as spc from ool.picture.models.thirdparty.space.model import Space from oolexp import OOLLayeredBoxExp class MultipleOptimizer(torch.optim.Optimizer): def __init__(self, *optimisers): self.opts = optimisers self.defaults = ...
karazijal/clevrtex
experiments/space.py
space.py
py
3,054
python
en
code
8
github-code
6
39567195381
def main(filepath): with open(filepath) as file: rows = [int(x.strip())for x in file.readlines()] for i in range(25,len(rows)): condition_met = False for j in range(i-25,i): for k in range(i-25,i): if (rows[k] + rows[j]) == rows[i] and not rows[k] == ro...
Burntmace/AdventOfCode2020
AOC-2020/days/nine.py
nine.py
py
727
python
en
code
0
github-code
6
6972201686
import os import argparse #from tools import train_net from tools.lib import init_lr import random import numpy as np from tools.classification import classification from tools.classification_multi import classification_multi import torch def seed_torch(seed=0): random.seed(seed) os.environ['PYTHON...
ada-shen/ICNN
demo.py
demo.py
py
3,178
python
en
code
59
github-code
6
3438970081
class Solution: def minCostII(self, costs: List[List[int]]) -> int: k = len(costs[0]) dp1 = [0] * k dp2 = [0] * k smallest1 = [0] * 2 smallest2 = [sys.maxsize] * 2 for cost in costs: for i in range(k): if dp1[i] == smallest1[1]: ...
cuiy0006/Algorithms
leetcode/265. Paint House II.py
265. Paint House II.py
py
833
python
en
code
0
github-code
6
20804943026
import pickle from sklearn import model_selection from sklearn.linear_model import LinearRegression model = LinearRegression() loaded_model = pickle.load(open('model', 'rb')) val = "sssfAfsDfe%%%{dInIisdChdh*e]DHSdbeTNhfhdyeSSWTTFSSSllfjdjs{\\#3fdas34df7adJHHstcsdDFur3sfj_1mdfneypcs0KJDsrsFs7sd4nfec3_sdrufdl35}453" p...
MysterionRise/ai-ctf-2022-solutions
stegano-regression/stegano.py
stegano.py
py
502
python
en
code
0
github-code
6
73486867709
''' @Jailson Data: 17-11-2022 ''' import requests from csv import writer from datetime import datetime data_e_hora_atuais = datetime.now() data_e_hora_em_texto = data_e_hora_atuais.strftime('%d/%m/%Y %H:%M') ################################################################################# # Emon service info emon_i...
marcelo-m7/EcoPool
varexternas.py
varexternas.py
py
2,070
python
en
code
0
github-code
6
31534411526
characters = input() command = input() while command != "End": command = command.split() the_command = command[0] if the_command == "Translate": char = command[1] replacement = command[2] if char in characters: characters = characters.replace(char, replacement) ...
iliyan-pigeon/Soft-uni-Courses
programming_fundamentals_python/exams/fundamentals_the_final_exam/string_manipulator.py
string_manipulator.py
py
1,188
python
en
code
0
github-code
6
23748731008
# !/usr/bin/env python # -*- coding: utf-8 -*- """Entry point for the server application.""" import json import logging import traceback from datetime import datetime from flask import Response, jsonify, current_app from flask_jwt_simple import (JWTManager, jwt_required, get_jwt_identity, get_jwt) from gevent.wsgi im...
zIPjahoda/Flask-Angular
backend/flask_app/server.py
server.py
py
1,852
python
en
code
0
github-code
6
16312489701
from flask import Blueprint, render_template, request, flash, redirect shared_file = Blueprint('shared_file', __name__) @shared_file.route('/') def get__(): from models import File, User files = File.query.filter(File.shared).all() users = list(User.get_by(id_=file.creator_id) for file in files) list...
TheMasterOfMagic/ac
views/shared_file.py
shared_file.py
py
1,156
python
en
code
1
github-code
6
20844418825
import tensorflow as tf def multiclass_non_max_suppression( boxes, scores, score_threshold, iou_threshold, max_boxes_per_class): """Multi-class version of non maximum suppression. It operates independently for each class. Also it prunes boxes with score less than a provided threshold prior...
TropComplique/light-head-rcnn
detector/utils/nms.py
nms.py
py
3,483
python
en
code
23
github-code
6
74743637626
import re from PyQt4 import QtGui from PyQt4 import QtCore from PyQt4.QtCore import Qt from customeditor import CustomEditor from camelot.view.art import Icon import camelot.types class VirtualAddressEditor(CustomEditor): def __init__(self, parent=None, editable=True, address_type=None, **kwargs): Custo...
kurtraschke/camelot
camelot/view/controls/editors/virtualaddresseditor.py
virtualaddresseditor.py
py
7,474
python
en
code
4
github-code
6
34084173801
from django.conf.urls.defaults import patterns, url from django.template.defaultfilters import slugify from rc.resources.views import ResourceItemListView from rc.resources.apps.operations import models def green_building_url(url_string, building_type, image_url=None, image_alt=None, image_capt...
AASHE/django-irc
rc/resources/apps/operations/urls.py
urls.py
py
12,244
python
en
code
0
github-code
6
35862928120
import json import redis from flask import Flask, request, Response, make_response import base64 from jwt.api_jwt import PyJWT app = Flask(__name__) d = {'write': '1', 'read': '2', 'delete': '3'} HOST = 'rediska' Key = '12345' @app.route('/auth/') def requestic4(): user = request.authorization.username password = ...
ZharkovMihail/server_with_jwt
server.py
server.py
py
2,843
python
en
code
0
github-code
6
43073911588
""" 年化因子 """ def annualization_factor(period): """ 返回对应周期(period)所需的年化因子 Parameters --------- period: str [daily, weekly, monthly, yearly] 定义调仓周期 Returns ------- annualization_factor : float 年化因子 """ try: factor = ANNUALIZATION_FACTORS[period] exce...
SkyBlueRW/PortAttribute
portattr/const/annualization.py
annualization.py
py
769
python
en
code
0
github-code
6
23113245409
#-*- coding: utf-8 -*- #-----------------------------------------------------------------------# # Autor: Luis Enrique Rojas Desales # #-----------------------------------------------------------------------# # Este codigo esta liberado bajo licencia GPL. # #...
ikiex/CFDIMasivo
CFDI/Controlador/lista.py
lista.py
py
2,079
python
es
code
3
github-code
6
3654388040
import re import time from threading import Lock from mycroft.configuration import Configuration from mycroft.metrics import report_timing, Stopwatch from mycroft.tts import TTSFactory from mycroft.util import create_signal, check_for_signal from mycroft.util.log import LOG from mycroft.messagebus.message import Messa...
injones/mycroft_ros
scripts/mycroft/audio/speech.py
speech.py
py
5,795
python
en
code
5
github-code
6
72435188028
import requests import json URL = "http://localhost:8000/auth/users/" def post_data(): # data = { # "emial":"adirokade15@gmail.com", # "name":"AdityaRokade", # "password":"djangoroot", # "re_password":"djangoroot", # "first_name":"adi", # "last_name":"rokade" ...
adityarokade/social_book
social_book/myapp.py
myapp.py
py
805
python
en
code
0
github-code
6
39129545830
from __future__ import absolute_import, division, print_function import os from subprocess import check_call import logging import importlib import tempfile import yaml from datetime import datetime import numpy as np import dask import xarray as xr import cftime import esmlab import data_catalog #-- settings (m...
NCAR/cmip6_cesm
project.py
project.py
py
10,694
python
en
code
1
github-code
6
22290772593
import streamlit as st import pandas as pd st.title("Upload CSV project") uploaded_csv = st.file_uploader('選擇CSV檔') if uploaded_csv is not None: df = pd.read_csv(uploaded_csv,encoding='utf-8') st.header('CSV檔內容:') st.dataframe(df)
chiangcw0410/mysql_test
test/upload.py
upload.py
py
259
python
en
code
0
github-code
6
70282380348
import src.globe as globe from src.constants import * from src.tile import * class Room: def __init__(self): self.areaId = '' self.roomId = '' globe.Updater.registerDrawee(self.draw, ['nominal'], [], 'back') globe.Updater.registerUpdatee(self.update, ['nominal'], ['paused']) ...
Dieff/pygame_platform_engine
src/room.py
room.py
py
5,398
python
en
code
1
github-code
6
27581741716
# -*- coding: utf-8 -*- """ Created on Wed Oct 4 13:56:32 2017 @author: hannu """ import numpy as np import matplotlib.pyplot as plt import random import scipy.constants as const from constants import * ####### Functions for KMC ###### def f(sigma, x): normal = (1/(2*const.pi*sigma**2))*np.exp(...
hpelttari/Kinetic-Monte-Carlo
Si_migration/functions.py
functions.py
py
1,456
python
en
code
1
github-code
6
32640335090
# AUTHOR: Louis Tsiattalou # DESCRIPTION: Match list items to closest tf-idf match in second list. import pandas as pd from tfidf_matcher.ngrams import ngrams from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.neighbors import NearestNeighbors def matcher(original=[], lookup=[], k_matches=5, ng...
LouisTsiattalou/tfidf_matcher
tfidf_matcher/matcher.py
matcher.py
py
5,188
python
en
code
41
github-code
6
2296903682
# is user1 = { "name": "Jean", "age": 33 } user2 = { "name": "Jean", "age": 33 } print(user1 == user2) print(user1 is user1) print(user1 is user2) mon_tableau = [3] print(mon_tableau is mon_tableau) # Un tableau étant caché derrière une réference, le comportement est un peu différent, # il faut garder...
Alikae/PythonFormation
05 Operateurs/4_identité.py
4_identité.py
py
493
python
en
code
1
github-code
6
23235971280
""" __/\\\\\\\\\\\\______________________/\\\\\\\\\\\____/\\\________/\\\_ _\/\\\////////\\\__________________/\\\/////////\\\_\/\\\_______\/\\\_ _\/\\\______\//\\\________________\//\\\______\///__\/\\\_______\/\\\_ _\/\\\_______\/\\\_____/\\\\\______\////\\\_________\/\\\_______\/\\\_ _\/\\\_______\/\\\___/...
tsandrini/dosu
dosu/__main__.py
__main__.py
py
3,242
python
en
code
0
github-code
6
5366659164
import datetime import logging import os.path import x509 LOG = logging.getLogger(__name__) class CertWatcher(object): def __init__(self, key_path, cert_path, common_name, ca_driver, on_refresh_success=None, on_refresh_failure=None, refresh_window=None): if not os.path...
takac/cathead
cathead/certwatch.py
certwatch.py
py
2,756
python
en
code
3
github-code
6
8105270111
# coding=utf-8 import click import MeCab from transformers import BertJapaneseTokenizer, BertForMaskedLM @click.command() @click.option('--text', '-t', default='') def main(text): tokenizer = BertJapaneseTokenizer.from_pretrained('bert-base-japanese-whole-word-masking') tokenized_text = tokenizer.tokenize(text...
ys201810/bert_work
src/compare_mecab_bert_wakatigaki.py
compare_mecab_bert_wakatigaki.py
py
551
python
en
code
0
github-code
6
27614075468
# Your BSTIterator will be called like this: # i, v = BSTIterator(root), [] # while i.hasNext(): v.append(i.next()) from queue import Queue from queue import LifoQueue class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.next = None self.S...
abhishekvaid/leetcode
_1008_bst_iterator.py
_1008_bst_iterator.py
py
1,030
python
en
code
0
github-code
6
22084110585
# def fact(base): # return 1 if (n == 1 or n ==0 ) else n * fact(n-1) # number , n = map(int,input().split()) # qw = (x**fact(n))%10 # print(po) # import numpy as np # x , n = map(int,input().split()) # a = np.math.factorial(n) # if n >=2: # print(pow(x,a/2,10)) # else: # print(pow(x,a,10)) # def boost(n,...
vamshipv/code-repo
may circuits/fact.py
fact.py
py
1,532
python
en
code
0
github-code
6
28151900553
import collections import matplotlib.pyplot as plt import numpy as np import os import cv2 import time from DQN_RGB import DQN_RGB from DQN import DQN from FifaEnv import FifaEnv from scipy.stats import wilcoxon from DynamicMLP import MLP import scipy.misc from scipy.misc import imresize # Initialize Global Parameters...
matheusprandini/FifaFreeKickLearning2019
Main.py
Main.py
py
7,635
python
en
code
0
github-code
6
5461309461
from django.db import models # Create your models here. class Category(models.Model): slug = models.SlugField(max_length=30, primary_key=True) name = models.CharField(max_length=50) image = models.ImageField(upload_to='categories', blank=True) class Meta: verbose_name = 'Kategorya' ...
izumichiDana/djangoModels
main/models.py
models.py
py
1,010
python
en
code
0
github-code
6
1277452974
"""Default settings.""" import logging settings = { 'log': { 'level': "debug", # log level }, 'auth': { 'required': False, # set to `True` to enable authentication 'basic_auth': { 'path': '/dev/null', # path to htpasswd file }, }, 'server': { ...
t4k1t/qgisrv
qgisrv/settings.py
settings.py
py
552
python
en
code
0
github-code
6
24255720694
import pandas as pd import os import time from xlrd import XLRDError start_time = time.time() # list of paths to ebay files ebay_files = [] # searching all excel files in the folder for root, dirs, files in os.walk(r'D:\Projects\shopContent\ebay'): ebay_files.extend([os.path.join(root, file) for file in files if fi...
bfesiuk/shopContent
creating.py
creating.py
py
4,995
python
en
code
0
github-code
6
70380481467
import os import re import sys import json import tempfile import urllib.parse import urllib.request import http.cookiejar import dotenv def _read_json(url, params=None): url = f'{url}?{urllib.parse.urlencode(params)}' request = urllib.request.Request(url) response = urllib.request.urlopen(request) d...
enzo-santos/publicapi-correios
main.py
main.py
py
3,135
python
pt
code
0
github-code
6
16645086609
# !/usr/bin/python # -*- coding: utf-8 -*- """ __author__ = 'qing.li' """ # 执行系统命令 import os import subprocess # print(os.system("adb devices")) # # # 收集结果 # print(os.popen("adb devices").readlines()) class Command: def excute_command_result(self, cmd): result_list = [] result = os.popen(cmd).rea...
QingqinLi/ui_project
util/command.py
command.py
py
739
python
en
code
0
github-code
6
34529796403
import tensorflow as tf import numpy as np from collections import namedtuple from .interpolate_tf import InterpolatorTF, nonzero InterpolatorsTuple = namedtuple( "InterpolatorsTuple", [ "quantiles_to_references_forward", "quantiles_to_references_backward", "references_to_quantiles", ...
yandexdataschool/QuantileTransformerTF
quantile_transformer_tf/quantile_transform_tf.py
quantile_transform_tf.py
py
7,127
python
en
code
7
github-code
6
1064969872
import pygame from pygame.locals import * # define constants BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) CYAN = (0, 255, 255) VIOLET = (148, 0, 211) width,height = 600,600 # set up display pygame.init() #in case you use fonts: pygame.font.init...
hackingmath/pygame_sketches
pygame_template.py
pygame_template.py
py
1,334
python
en
code
4
github-code
6
3407354621
from queue import Queue from adjacencyset import * def distance_table(graph, start_node): queue = Queue() distance_table_map = {} for v in range(graph.numVertices): distance_table_map[v] = (None,None) distance_table_map[start_node] = (0, None) queue.put(start_node) while not queue.e...
VimleshS/python-graph-ds
shortest_path_unweighted.py
shortest_path_unweighted.py
py
1,361
python
en
code
0
github-code
6
3357759046
#item应该从data中提取的 item = ['西红柿','排骨','鸡蛋','茄子','袜子','酸奶','土豆','鞋子'] import pandas as pd import numpy as np #header = None 属性可以将第一行数据加载到第二行,第一行就是index 1 2 3 ect. data = pd.read_excel('tr.xlsx',header = None) #删去I1 I2 I3第一列这些项集的编号 data = data.iloc[:,1:] #为啥创建D呢? D = dict() for i in range (len(item)): for t in range (...
0303yk/python-
金融数据分析课程知识/购物搭配关联规则挖掘.py
购物搭配关联规则挖掘.py
py
1,625
python
en
code
0
github-code
6
62345004
from django.urls import path, include from core import views urlpatterns = [ path('', views.index, name='index'), path('register/',views.register, name='register'), path('home/',views.home, name='home'), path('history/', views.history, name='history'), path('generate-new-label/', views.generate_ne...
lquresh52/shipping-label-generaor
core/urls.py
urls.py
py
636
python
en
code
0
github-code
6
42743009421
from setuptools import find_packages from setuptools import setup package_name = 'camera_calibration' setup( name=package_name, version='1.12.23', packages=find_packages(exclude=['test']), data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), ...
ahuizxc/ros2_camera_calibration
setup.py
setup.py
py
1,118
python
en
code
2
github-code
6
11623004632
import tkinter as tk from tkinter import filedialog, messagebox from selenium import webdriver from selenium.webdriver.common.keys import Keys import pandas as pd from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrom...
Boo4S/AISearch
main.py
main.py
py
15,301
python
fr
code
0
github-code
6
16551902324
import string, random, json, sys, os.path, uuid sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) # from models import sesion # import models.models as database from sqlalchemy.exc import IntegrityError from sqlalchemy.sql.functions import func from sqlalchemy import desc im...
pabloIO/LIBREria_bo
controllers/libros_ctrl.py
libros_ctrl.py
py
16,176
python
en
code
0
github-code
6
37511806658
from invimg.scripts.inference import invert import math import os import torch import torchvision from tqdm import tqdm import numpy as np from optimclip.criteria.clip_loss import CLIPLoss from optimclip.criteria.id_loss import IDLoss from optimclip.models.stylegan2.model import Generator import clip from faceparsing....
wangyuchi369/makeup-clip
test.py
test.py
py
6,753
python
en
code
0
github-code
6
16897266155
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.13.8 # kernelspec: # display_name: Python [conda env:root] * # language: python # name: conda-root-py # --- i...
amvelazquez/iia-analysis
scrape_treaty_db.py
scrape_treaty_db.py
py
2,671
python
en
code
0
github-code
6
71404988987
from selenium import webdriver from selenium.webdriver.chrome.options import Options from contextlib import contextmanager import pathlib import shutup # shut those annoying warnings shutup.please() # configure selenium chromedriver_location = f"{next(pathlib.Path('.').glob('**/chromedriver'))}" #dynamically find chr...
ihiiro/Intelligence
intel_engine/url_extractor.py
url_extractor.py
py
1,803
python
en
code
0
github-code
6
373981387
from app import app from flask import render_template,flash, request, redirect, url_for from .forms import CalculatorForm, ButtonForm from app import db, models import datetime @app.route('/') def index(): greeting = "Hello World!!!" title = "Homepage" # return redirect(url_for('create_assessment')) re...
Lanrayy/web-app-development-comp2011-cwk1
app/views.py
views.py
py
4,045
python
en
code
0
github-code
6
10625323914
import boto3 access_key = '' secret_access_key = '' def get_all_clusters(): ecs_client = boto3.client('ecs', aws_access_key_id=access_key, aws_secret_access_key=secret_access_key) response = ecs_client.list_clusters() cluster_arns = response['clusterArns'] return cluster_arns # print(get_all_regions...
PrantaChakraborty/boto3
s3/ecs.py
ecs.py
py
462
python
en
code
0
github-code
6
16442943983
#!/usr/bin/env python """ Created on Wed Jan 20 20:53:20 2020 @author: yuweiwu Usage: This is the script to create the node lidar_processing and three topic:closest_point, farthest_point and scan_range """ import rospy #import math import numpy as np import std_msgs.msg from sensor_msgs.msg import LaserScan from yuw...
yuwei-wu/F110-autonomous-racing
yuweiwu_roslab/scripts/lidar_processing.py
lidar_processing.py
py
1,597
python
en
code
0
github-code
6
26257817866
# Imports import users import find_athlete import sys import sqlalchemy as sa from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base import uuid import datetime # Global variables task = """ Задание №1: Напишите модуль users.py, который регистрирует новых пользователей. С...
vsixtynine/sf-sql-task
start.py
start.py
py
9,483
python
ru
code
0
github-code
6
29643349641
# -*- coding: utf-8 -*- # (c) 2015 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api, _ class MrpProduction(models.Model): _inherit = 'mrp.production' plan = fields.Many2one('procurement.plan', string='Plan') @api.mul...
odoomrp/odoomrp-wip
procurement_plan_mrp/models/mrp_production.py
mrp_production.py
py
3,308
python
en
code
119
github-code
6
24442654174
import argparse import logging import sys import pandas as pd import requests key = ' ' def get_recent_headlines(key: str): r = requests.get(url=f'https://newsapi.org/v2/top-headlines?country=us&apiKey={key}') return r.json() def get_headlines_to_certain_category(key: str, category: str): r = requests...
novatc/sent-news
news_api.py
news_api.py
py
1,768
python
en
code
0
github-code
6
72044818108
# RENAMING A FILE/FOLDER # syntax: # os.rename("path_of_file_with_oldname","path_of_file_with_newname") os.rename("/home/hidayat7z/first.txt","/home/hidayat7z/phaast.txt") # RENAMING MULTIPLE FILES ##for 2nd Sem_res.jpeg and 3rd Sem_res.jpeg RENAME it to 2nd Semester Result.jpeg & 3rd Semester Result.jpeg ## we nee...
hidayat7z/Python
Manipulating Files and Folders/4. Renaming a file.py
4. Renaming a file.py
py
760
python
en
code
1
github-code
6
73694875709
'''compute CCS in multi-step experiments ''' import traceback import time import glob import os from pathlib import Path from sys import platform as sys_pf if sys_pf == 'darwin': import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt import seaborn as sns from utils import * from shortest_...
PNNL-Comp-Mass-Spec/AutoCCS
multiCCS.py
multiCCS.py
py
29,722
python
en
code
7
github-code
6
34131786759
import time import numpy as np def isleapyear(year): if year%4==0: if year%100==0: if year%400==0: return True elif year%400!=0: return False else: return True return False if __name__ == '__main__': num_sunday = 0 year = 1900 monthsdsnonleap = {'January':31,'February':28,'M...
sadimanna/project_euler
p19.py
p19.py
py
1,760
python
en
code
0
github-code
6
71791936828
from unittest import result import pyvo as vo import numpy as np import pandas as pd import re from typing import Optional, Tuple def simbad_tap(): return vo.dal.TAPService("http://simbad.u-strasbg.fr/simbad/sim-tap") def clean_str(obj_id: str) -> str: return ' '.join(obj_id.split()) def fetch_catalog_id(i...
maja-jablonska/blue-stragglers-with-gaia
simbad_download.py
simbad_download.py
py
5,295
python
en
code
0
github-code
6
42360515633
## Using python3 ## https://open.kattis.com/problems/apaxiaaans name = input() last = '' c = '' for i in range(len(name)): c = name[i] if (c != last): print(c, end = '') last = c print()
Resethel/Kattis
Problems/apaxiaaans/Python3/apaxiaaans.py
apaxiaaans.py
py
214
python
en
code
1
github-code
6
33276100451
# coding: utf-8 # In[2]: import hashlib import json from datetime import datetime class Block: def calculateHash(self): return hashlib.sha256((self.timestamp+str(self.transaction)+self.previoushash+str(self.nonce)) .encode('utf-8')).hexdigest() # return hashlib.sh...
cpandya231/Blockchain_Poc
Blockchain_poc_with miner and transactions.py
Blockchain_poc_with miner and transactions.py
py
3,935
python
en
code
0
github-code
6
37233125461
from naive_bayes import naive_bayes_run from naive_bayes import calc_prob from create_voc_functions import create_vocabulary from vector_functions import create_vectors from results import plot_results import pickle #for train path1 = pickle.load( open( "examples_edit\\training_path.p", "rb" ) ) typ1 = pickle.load( op...
ntinouldinho/Artificial-Intelligence-SpamHam-Classifier
naive_bayes_main.py
naive_bayes_main.py
py
2,271
python
en
code
1
github-code
6
35227184392
import glob import os import shutil from tqdm import tqdm from sklearn.model_selection import train_test_split import multiprocessing as mp from functools import partial def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i : i + n] def loop(...
avacaondata/SpainAI_Hackaton_ComputerVision
split_data_multiprocessing.py
split_data_multiprocessing.py
py
2,114
python
en
code
1
github-code
6
41460148421
#Python script to retrieve Top 10 performing Cryptocurrencies, ranked by Market capitalization #Import relevant modules to query API import requests, json #Define variables used to query API url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' headers = { 'Accept': 'ap...
lilokotze/CMC_assignment
CMC_assignment.py
CMC_assignment.py
py
2,542
python
en
code
0
github-code
6
27566260651
from django.shortcuts import render, HttpResponseRedirect from .forms import MeetingCreateForm from .models import Meeting from django.contrib.auth.decorators import login_required from django.urls import reverse from django.contrib import messages from datetime import datetime, timezone as tz from django.utils import ...
Afeez1131/Django-online-meeting
onlinemeet/views.py
views.py
py
3,327
python
en
code
2
github-code
6
30595009770
from random import randint count = 1; print('''Sou seu computador... Acabei de pensar em um Nº entre 0 e 10. Será que você consegue adivinhar qual foi?''') n = randint(0, 10) #print(n) tenta = int(input('Qual o seu palpite? ')) while tenta != n: count += 1 if tenta < n: print('Mais... Tente mais uma vez...
ErickFernan/Estudos-de-Pyhton
Estudo Python/Estruturas de Repetição/Estrutura repetição WHILE/ex058.py
ex058.py
py
559
python
pt
code
0
github-code
6
42831472759
from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('<slug:c_slug>/',views.home,name='c_slug'), path('search',views.search_box,name='search'), path('<slug:c_slug>/<slug:p_slug>/',views.details,name='details') ]
muhammediyas786/Shopping-cart
ShopApp/urls.py
urls.py
py
279
python
en
code
0
github-code
6
6542821272
from student import Student from db import StudentRepository import csv class Gradebook: def __init__(self) -> None: self.__db = StudentRepository() self.__students: list[Student] = self.__db.getStudents() @property def students(self) -> list[Student]: return self.__students d...
kathyshe/gradebook-practice
gradebook.py
gradebook.py
py
6,949
python
en
code
0
github-code
6
3668865617
from typing import List class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ def dfs(i,j,m,n): if not (0 <= i < m and 0 <= j < n) or board[i][j] != 'O': return board[i...
yingzixu15/leetcode
src/SurroundedRegions.py
SurroundedRegions.py
py
1,142
python
en
code
0
github-code
6
10353230480
import struct class ByteStream(object): """A seekable byte stream Expects a data object that provides integer values, such as a py3 byearray or array('B') """ def __init__(self, data): self.index = 0 self.data = data def read(self, n_bytes=None): """Read the requested...
abg/mysql4py
mysql4py/util.py
util.py
py
5,174
python
en
code
1
github-code
6
32988415640
import numpy as np from utils.DataProcess import RandomHSV, RandomBlur, RandomResize, RandomFlip, RandomRotate, ResizeOrCropToInputSize, BoxToTensor import os import random import tensorflow as tf class ImageData(): def __init__(self, input_shape, class_ls, anchor_ls, anchor_mask, reduce_ratio, hs...
bardenthenry/YoloV3_TF2_Keras
utils/ReadDataFromTFRecord.py
ReadDataFromTFRecord.py
py
3,841
python
en
code
1
github-code
6
25278816523
from django.urls import path,re_path from . import views urlpatterns = [ path('',views.dummy), re_path('new_reg/',views.register,name='register'), re_path('login/',views.login,name='login'), path('index',views.index,name='index'), path('about',views.about, name='about'), path('contact',views.c...
mukhilvinod/E-cart
django_tutorial/products/urls.py
urls.py
py
408
python
en
code
0
github-code
6
9773008235
import os import threading import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt import pandas as pd results = {} sigmas = {} def gaussian(x, mu, sigma, A): return A * np.exp(-(x-mu)**2 / (2*sigma**2)) def find_peak(file_path, noise_range, plot=False): try: ...
mattcarv/RadioCUBE
SingleGaussianFitting.py
SingleGaussianFitting.py
py
2,424
python
en
code
0
github-code
6
16016777996
from scarf import app from core import SiteImage, NoImage from main import page_not_found, PageData import core from StringIO import StringIO from PIL import Image from flask import send_file import logging import base64 import cStringIO logger = logging.getLogger(__name__) """ image resizing is implemented via ngin...
oamike/scarfage
scarf/resize.py
resize.py
py
1,777
python
en
code
0
github-code
6
4970666838
import csv import matplotlib.pyplot as plt from datetime import datetime file_2 = 'data/sitka_weather_2018_simple.csv' with open(file_2) as f: reader = csv.reader(f) header_row = next(reader) dates, highs, lows = [], [], [] for x in reader: high = round(((int(x[5]) - 32) * (5/9)),0) ...
RaulMaya/Data-Visualization
python_programs/downloading data/sitka_temperatures.py
sitka_temperatures.py
py
1,108
python
en
code
0
github-code
6
14911244486
import unittest import time import ddt import json from Public.cogfig import EXECL_PATH from Interface.test_mock import test_mock_mi test_send = test_mock_mi() import math from Public.read_excel import read_excel from unittest import mock wenjian = EXECL_PATH + '\\jekn.xlsx' #查询到对应的case文件 index_excel = read_excel(wenj...
LiuYaowei-Geek/deep
test_Case/mock.py
mock.py
py
5,537
python
zh
code
1
github-code
6
71484374908
S = input() N = len(S) non_x = [] s_notx = [] for i, s in enumerate(S): if s != 'x': non_x.append(i) s_notx.append(s) s_notx = ''.join(s_notx) if s_notx != s_notx[::-1]: print(-1) quit() if not non_x: print(0) quit() ans = 0 L = len(non_x) if L % 2 == 0: left, right = L // 2 - 1,...
knuu/competitive-programming
atcoder/corp/cf17_qc_c.py
cf17_qc_c.py
py
575
python
en
code
1
github-code
6
16669920694
from django.contrib.auth import get_user_model from django.test import TestCase from ..models import Comment, Follow, Group, Post User = get_user_model() class PostModelTest(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.create_user(username='TestUs...
Vilenor/hw05_final
yatube/posts/tests/test_models.py
test_models.py
py
2,247
python
ru
code
0
github-code
6
33087525996
import pygame from speedfighter.utils.app_base import AppBase from speedfighter.utils.file import File from speedfighter.utils.path import Path class SpeedSpeaker(AppBase): """ スピードスピーカー """ def __init__(self): super().__init__() pygame.mixer.init() pygame.mixer.music.set_volu...
curio184/speedfighter-nft
speedfighter/speed_monitor/speed_speaker.py
speed_speaker.py
py
2,159
python
en
code
1
github-code
6
3028976536
''' Description: Converts Gen I pokemon sprites to text for pokemonBatch Author: Soda Adlmayer Date: 2017.02.26 ''' from PIL import Image #set filepath filename = r"C:\Users\Rudi\Documents\SODA\BATCH\pokemonBatch\data\other\sprites\bulbasaur1.png" #open image im = Image.open(filename) width, height = im.size...
Pokeconomist/pokemonBatch
assets/sprites/image_processor1.py
image_processor1.py
py
963
python
en
code
3
github-code
6
5479399707
""" TODO: Merge or improved with pytree in jax. """ from collections import defaultdict import numpy as np from functools import wraps from multiprocessing.shared_memory import SharedMemory from .array_ops import ( squeeze, unsqueeze, zeros_like, repeat, tile, shuffle, take, share_memo...
haosulab/ManiSkill2-Learn
maniskill2_learn/utils/data/dict_array.py
dict_array.py
py
34,803
python
en
code
53
github-code
6
28900653981
from keras.models import * from keras.layers import * import keras from dlblocks.keras_utils import allow_growth , showKerasModel allow_growth() from dlblocks.pyutils import env_arg import tensorflow as tf from Utils import Trainer from SluiceUtils import * class Sluice_SeqLab(Trainer): def build_model(self...
divamgupta/mtl_girnet
sequence_labeling/sluice.py
sluice.py
py
4,038
python
en
code
6
github-code
6
30353923791
from os.path import dirname import logging # Enthought library imports. from traits.api import Bool from envisage.ui.workbench.api import WorkbenchApplication from pyface.api import AboutDialog, ImageResource, SplashScreen # Local imports. import mayavi.api from mayavi.preferences.api import preference_manager IMG_D...
enthought/mayavi
mayavi/plugins/mayavi_workbench_application.py
mayavi_workbench_application.py
py
4,140
python
en
code
1,177
github-code
6
23944471661
import json import pytest from deepdiff import DeepDiff from eth_keys.datatypes import PrivateKey from hexbytes import HexBytes from jsonschema import ValidationError from web3 import Web3 from polyswarmtransaction.exceptions import InvalidKeyError, InvalidSignatureError, WrongSignatureError, \ UnsupportedTransac...
polyswarm/polyswarm-transaction
tests/test_transaction.py
test_transaction.py
py
6,888
python
en
code
1
github-code
6
209544494
recipes = [3, 7] duendes= [0, 1] longitud=323081 #longitud=5 while len(recipes) < longitud + 10: new = recipes[duendes[0]] + recipes[duendes[1]] recipes += [int(c) for c in str(new)] duende1=(duendes[0]+1+recipes[duendes[0]])%len(recipes) duende2=(duendes[1]+1+recipes[duendes[1]])%len(recipes) duendes= [duende1,du...
heyheycel/advent-of-code
2018/code_day14.py
code_day14.py
py
1,164
python
en
code
0
github-code
6
28743291670
import tkinter from turtle import right ventana=tkinter.Tk() ventana.title("Ventana de pruebas") ##ventana.resizable(0,0) no deja ajustar el tamaño ##ventana.iconbitmap("cualquiercosa.ico") asi se puede cambiar el icono de la aplicacion :d ventana.geometry("500x300") ventana.config(bg="black") miframe=tkinte...
SebastianTrujillo21/tkinter_practice
1er_proyecto/primera.py
primera.py
py
633
python
es
code
0
github-code
6
32942155774
""" COMP.CS.100 Programming 1. Stuart Student, hamed.talebian@tuni.fi, student id 150360360. Solution of task 2.. """ def main(): num_of_days = int(input('Enter the number of days: ')) data = 0 mean = 0 counter = 0 for number in range(1, num_of_days + 1): running_length = float(input(f'E...
hamedtea/python_assignments
analyzer.py
analyzer.py
py
925
python
en
code
0
github-code
6
70879515068
import aoc_cj.aoc2016.day13 as d EXAMPLE_SPACE = """ .#.####.## ..#..#...# #....##... ###.#.###. .##..#..#. ..##....#. #...##.### """.strip() def test_is_wall(): lines = EXAMPLE_SPACE.splitlines() fav_num = 10 for y in range(len(lines)): for x in range(len(lines[0])): assert lines[y][...
cj81499/advent-of-code
tests/aoc2016/y2016d13_test.py
y2016d13_test.py
py
433
python
en
code
2
github-code
6
18242919824
# Justificação de textos def limpa_texto(texto): '''Elimina espaços do texto original. Sem dependências Parametros: str Retorna: str ''' return ' '.join(texto.split()) def corta_texto(texto, largura): '''Divide o texto pela ultima palavra completa em função da largura. ...
IDK04/Projeto-fp-1
main.py
main.py
py
11,418
python
pt
code
0
github-code
6
16734122984
from typing import Any from fastapi import FastAPI, Response, Request from pathlib import Path from pydantic import BaseModel from autogoal.utils._storage import inspect_storage import uvicorn from autogoal_remote.distributed.proxy import loads, dumps, encode, decode class Body(BaseModel): values: Any app = Fas...
autogoal/autogoal-remote
autogoal_remote/production/server.py
server.py
py
1,689
python
en
code
1
github-code
6
27516277876
from discord.ext import commands from databases.database_manager import db class Hive(commands.Cog): def __init__(self, bot): self.bot = bot self._last_member = None @commands.command(name='get_map_id', help='<map_name>', aliases=["get_id","gmi"]) async def get_map_...
tintin10q/hive-discord-bot
commands/get_map_id.py
get_map_id.py
py
710
python
en
code
0
github-code
6
16733135761
import argparse import logging import os import sys import time from urllib.parse import urljoin, urlparse, unquote, parse_qs import requests import urllib3 from bs4 import BeautifulSoup from pathvalidate import sanitize_filename logger = logging.getLogger(__name__) class BookError(Exception): def __init__(self...
petrovskydv/parse_library
parse_tululu.py
parse_tululu.py
py
5,093
python
en
code
0
github-code
6
15521199342
state = [] with open('D6_input.txt', 'r') as fopen: state = list(map(int, fopen.readline().rstrip().split(','))) for i in range(256): for ind, fish_state in enumerate(state): if fish_state == 0: state[ind] = 6 state.append(9) else: state[ind] -= 1 print(len(state))
probablyanasian/advent-of-code
2021/D6/Day_6A.py
Day_6A.py
py
284
python
en
code
0
github-code
6
73787200189
import DaNN import numpy as np import torch import torch.nn as nn import torch.optim as optim from tqdm import tqdm import argparse import data_loader import mmd import scipy.io import json DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') LEARNING_RATE = 0.02 MOMEMTUN = 0.05 L2_WEIGHT = 0.003 DRO...
comprehensiveMap/EI328-project
DaNN_/main.py
main.py
py
5,846
python
en
code
5
github-code
6
37429210278
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' name: iGenus邮件系统一处无需登录的任意代码执行 referer: http://www.wooyun.org/bugs/wooyun-2015-0156126 author: Lucifer description: /home/webmail/igenus/include/login_inc.php base64编码未验证可写入shell ''' import sys import requests class igenus_code_exec_BaseVerify: def __init__(self, ...
iceyhexman/onlinetools
scanner/plugins/cms/iGenus/igenus_code_exec.py
igenus_code_exec.py
py
1,113
python
en
code
1,626
github-code
6
25693151845
# coding=gbk # 9.12 导入类练习 多个模块 """在admin privileges类中导入用户模块中的user类""" from user import User class Privileges(): """创建一个有关管理员权限的小类""" def __init__( self, privileges= ['can add post','can delete post','can ban user']): """初始化权限的属性""" self.privileges = privileges def sh...
Troysps/learn_python
77/9.12导入类练习.py
9.12导入类练习.py
py
947
python
en
code
0
github-code
6
15028429007
n1 = int(input('Digite o primeiro número inteiro: ')) n2 = int(input('Digite o segundo número inteiro: ')) n3 = int(input('Digite o terceiro número inteiro: ')) if n1 > n2 and n3: print(f'O maior número é {n1}') input('Pressione ENTER para encerrar programa') if n2 > n1 and n3: print(f'O maio...
LeonardoDaSilvaBrandao/Phyton-Exercicios
Faça um Programa que leia três números e mostre o maior deles..py
Faça um Programa que leia três números e mostre o maior deles..py
py
535
python
pt
code
0
github-code
6
26660179991
'''Model base module''' import config import redis import collections import asyncio import sqlalchemy as sa from sqlalchemy import MetaData class Relation(object): def __init__(self, target_cls, back_populates=None, onupdate="CASCADE", ondelete="CASCADE", rkey=None, reverse=False): self.targe...
SproutProject/sptoj-server
model/__init__.py
__init__.py
py
12,647
python
en
code
0
github-code
6