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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
44404769623 | """
dictionary_hogwartshouses.py
create dictionary from JSON and prints information for any given Hogwarts house
"""
import sys
import json
import urllib.request
url = "https://raw.githubusercontent.com/kathyvsinternet/Python-INFO1-CE9990/master/hogwarts_houses.json"
try:
data = urllib.request.urlopen(url)
exc... | kathyvsinternet/Python-INFO1-CE9990 | dictionary_hogwartshouses.py | dictionary_hogwartshouses.py | py | 1,331 | python | en | code | 0 | github-code | 36 |
23525371756 | from __future__ import annotations
import pathlib
from collections import deque
class Monka:
def __init__(
self,
items: list,
operator_value: str,
operator_type: str,
divider: int,
target_index_true: int,
target_index_false: int,
high_worry: bool
... | Timozen/AoC2022 | 11/11.py | 11.py | py | 3,467 | python | en | code | 0 | github-code | 36 |
7108293533 | from qgis.core import *
import pickle
import networkx as nx
# QGIS Processing Script Parameters "##" indicates a parameter to QGIS
##Graph=group
##Vector=vector
##Field=field Vector
##Output_File_Path=file
def rectBounds(geometry):
"""
Generates bounding rectangles for QGIS polygon geometries.
:param ge... | eborke/QGISGraphPlugin | Graph.py | Graph.py | py | 11,541 | python | en | code | 0 | github-code | 36 |
4897197081 | #!/usr/bin/env python3
# coding=utf-8
"""
Add non-free photos to an album.
"""
import argparse
import flickrapi # http://www.stuvel.eu/flickrapi
import os
import sys
# import xml.etree.ElementTree as ET # ET.dump()
# from pprint import pprint
# https://www.flickr.com/services/api/flickr.photos.licenses.getInfo.htm... | hugovk/flickr-tools | nonfree.py | nonfree.py | py | 6,206 | python | en | code | 2 | github-code | 36 |
25108216019 | import enum
import importlib
import logging
from dataclasses import dataclass
from enum import auto
from os import path
from typing import List
import tensorflow as tf
logger = logging.getLogger(__name__)
def parse_mapping_from_path(mapping_path):
"""
Parse the input accelerator residing in... | wangxdgg/zigzag_2 | zigzag/classes/io/onnx/pb_utils.py | pb_utils.py | py | 4,319 | python | en | code | 0 | github-code | 36 |
6596929910 | # Develop a simple Python program that sends a small text file from a TCP client to a TCP server. Confirm that the file is received and saved correctly.
import socket
host = 'localhost'
port = 12345
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
with open('tes... | krishmakhijani/DSA | Python/2/_9.py | _9.py | py | 590 | python | en | code | 0 | github-code | 36 |
19448722325 | import sqlite3
from datetime import *
class DB:
def __init__(self) -> None:
self.con = sqlite3.connect('clock.db')
self.cur = self.con.cursor()
def create_table(self):
"""
CREATE TIME TABLE TO SAVE USER'S TIMES
"""
self.cur.execute("CREATE TABLE IF NOT EXIS... | aminm08/python-alarm-clock-GUI | database.py | database.py | py | 1,526 | python | en | code | 0 | github-code | 36 |
22706839636 | import math
import torch
import torch.nn as nn
class EnsembleLinear(nn.Module):
""" linear layer optimized for ensemble """
def __init__(self, ensemble_size, input_size, output_size):
super(EnsembleLinear, self).__init__()
self.weight = nn.Parameter(torch.zeros((ensemble_size, input_size, ou... | APM150/Continuous_Envs_Experiments | mujoco/models/ensemble.py | ensemble.py | py | 931 | python | en | code | 0 | github-code | 36 |
8556600358 | from aiogram import types, Dispatcher
from config import bot, ADMIN
from database import command_all_mentors_sql, command_delete_sql
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
async def show_all_mentors(message: types.Message):
if message.from_user.id != ADMIN:
await message.answ... | Yummy312/Geekbot | handlers/admin.py | admin.py | py | 2,163 | python | en | code | 0 | github-code | 36 |
12737078183 | import flet
from flet import Column, Container, ElevatedButton, Page, Row, Text, UserControl, border_radius, colors, TextField, Ref
class GreetingsApp(UserControl):
def build(self):
first_name = Ref[TextField]()
last_name = Ref[TextField]()
greetings = Ref[Column]()
def btn_click(... | applego/flet-practice | Apps/Greetings/Greetings.py | Greetings.py | py | 1,324 | python | en | code | 0 | github-code | 36 |
28151017591 | import json
import matplotlib.pyplot as plt
def draw(pro_dict):
scores=[] # 1准备数据
for v in pro_dict.values():
scores.append(v["avg_score"])
plt.figure(figsize=(20,8),dpi=100) # 2创建画布
# 3绘制直方图
dist=4
group_num=int((max(scores)-min(scores))/dist)
plt.hist(scores,bins=group_num)
... | xidao4/2020DataScience | src/method1/RDI/get_RDI.py | get_RDI.py | py | 2,255 | python | en | code | 0 | github-code | 36 |
71605340584 | import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime
import multiprocessing as mp
path = 'ImagesAttendance'
images = []
classNames = []
for cl in os.listdir(path):
curImg = cv2.imread(f'{path}/{cl}')
images.append(curImg)
# get names from filename (without the .*)
... | jiayi1129/AttendanceProject | AttendanceProject.py | AttendanceProject.py | py | 3,972 | python | en | code | 0 | github-code | 36 |
74258842345 | import os
import json
import pandas as pd
import shutil
from PIL import Image
import matplotlib.pyplot as plt
import os
import cv2
import numpy as np
def rotate_bound(image, angle):
# 获取图像的尺寸
# 旋转中心
(h, w) = image.shape[:2]
(cx, cy) = (w / 2, h / 2)
# 设置旋转矩阵
M = cv2.getRotationMatrix2D((cx, c... | Dantong88/Medical-Partial-Body-Pose-Estimation | ViTPose/demo/process_coco.py | process_coco.py | py | 3,724 | python | en | code | 1 | github-code | 36 |
35830927239 | # Short If Kullanimi
from curses.ascii import isdigit
age = input("Yasinizi Giriniz: ")
# if age.isdigit():
# age = int(age)
# else:
# age = 0
age = int(age) if age.isdigit() else 0
# print("*" * 30)
# print(age)
# print("*" * 30)
print(f"{'*' * 30}\n{age:^30}\n{'*' * 30}")
| hakanyalcinkaya/Uctan-Uca-Projelerle-Sifirdan-Full-Stack-Python-ve-Django-Egitimi | 008-Python---Karar-Yapilari-ile-Calismak/004-Short-if-Kullanimi.py | 004-Short-if-Kullanimi.py | py | 290 | python | en | code | 218 | github-code | 36 |
14787358518 | import cv2
import sklearn
import os
import numpy as np
import random
import skimage.transform as sktransform
from keras.preprocessing.image import random_shift
# 0.2,0.125
# def augment_brightness_camera_images(image):
# image1 = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
# image1 = np.array(image1, dtype=np.flo... | kalyanramu/CarND-BehavioralCloning-P3 | data_gen.py | data_gen.py | py | 6,966 | python | en | code | 0 | github-code | 36 |
29250154282 | import boto3
import json
import logging
import datetime
from elasticsearch import Elasticsearch, RequestsHttpConnection
import uuid
from requests_aws4auth import AWS4Auth
import requests
logger = logging.getLogger()
logger.setLevel('ERROR')
ELASTIC_HOST = 'https://vpc-photos-cr73giiqwxko7a2t22rzqu44rq.us-east-1.es.am... | huxin331/cloudhw3 | Lambda/LF2.py | LF2.py | py | 5,313 | python | en | code | 0 | github-code | 36 |
15008161859 | import pandas as pd
from PyQt5 import QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from pandas import DataFrame as DataframeObject
import Dataframe
from GraphMenu import GraphMenu
from GraphModel import GraphModel
from LoadedSheets import LoadedSheets
from PandasModel import PandasModel
import sys
... | Chremmer/SimpleCell | MainWindowGUI.py | MainWindowGUI.py | py | 9,022 | python | en | code | 0 | github-code | 36 |
3094488106 | #
# Input Output
# 1 2 3 4 5 5 4 3 2 1
#
# Write a program that reads a string with N integers from the console,
# separated by a single space, and reverses them using a stack. Print the reversed
# integers on one line, separated by a single space.
#
#n = input()
#
from collections import deque
#
n = '1 2 3 4 5'
#
n_... | ivn-svn/SoftUniPythonPath | Programming OOP and Advanced with Python/Advanced/1_lists_stacks_queues/exercise/1_reverse_numbers.py | 1_reverse_numbers.py | py | 465 | python | en | code | 1 | github-code | 36 |
14102788486 | from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import numpy as np
from typing import List
class FormatMissingData(BaseEstimator, TransformerMixin):
"""Modify missing data values as required by model sklearn Pipeline."""
def __init__(
self,
skip_inputs: List[str] ... | nasa/ML-airport-data-services | data_services/format_missing_data.py | format_missing_data.py | py | 1,896 | python | en | code | 3 | github-code | 36 |
26471518940 | from __future__ import print_function
import os.path
import re
import sys
import pcbnew
DEBUG = None
# Tokenizer for schematic file input lines.
def tokens(s):
return re.split(r' +', s)
# Class to represent a single sheet of a schematic. Has a map from
# component IDs to positions, a map from sub-sheet names t... | balena-io-experimental/skidl-demo | src/lib/schtopcb.py | schtopcb.py | py | 9,005 | python | en | code | 2 | github-code | 36 |
6073418311 | '''
Created on Feb 25, 2010
'''
from math import pi as Pi, cos, sin, exp, sqrt as scalar_sqrt
from ibvpy.tmodel.mats2D.mats2D_eval import MATS2DEval
from numpy import \
array, zeros, dot, \
float_, \
sign
from traits.api import \
Array, Enum, \
Event, provides, \
Dict, Property, cached_p... | bmcs-group/bmcs_ibvpy | ibvpy/tmodel/mats2D5/mats2D5_bond/mats2D5_plastic_bond.py | mats2D5_plastic_bond.py | py | 8,049 | python | en | code | 0 | github-code | 36 |
2201440478 | import webapp2
import jinja2
import os
import json
import logging
import datetime
import csv
from StringIO import StringIO
from urllib import quote, urlencode
from google.appengine.api import urlfetch
from models import TrackedUser, Followers
import headers
jinja_environment = jinja2.Environment(
loader=jinja2.F... | guardian/gu-tuser-tracker | app.py | app.py | py | 2,323 | python | en | code | 0 | github-code | 36 |
74147861225 | """https://web3py.readthedocs.io/en/stable/"""
from typing import Union, Any
from eth_typing import URI
from web3.contract import Contract
from web3.types import Wei, Address, HexStr, TxParams
from .reader import Reader
class Transactor(Reader):
def __init__(self, provider: Union[URI, str], timeout: int = 60) -... | zepcp/web3tools | web3tools/transactor.py | transactor.py | py | 1,666 | python | en | code | 4 | github-code | 36 |
38568542929 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head):
i = j = 1
nodelist = []
temp1 = temp2 = head
while temp1 != None:
if i%2 != 0:
... | archanakalburgi/Algorithms | summer_prep/linked-list/odd_even_linked_list.py | odd_even_linked_list.py | py | 1,045 | python | en | code | 1 | github-code | 36 |
8086312972 | from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from starlette.middleware.cors import CORSMiddleware
from app.core.config import ALLOWED_HOSTS, PROJECT_NAME
from app.api.endpoints import router as api_router
# create the app
app = FastAPI(title=PROJECT_NAME)
if not ALLOWED_HOSTS:
ALLO... | chriswmackey/energy-model-schema | app/main.py | main.py | py | 1,617 | python | en | code | 1 | github-code | 36 |
11525604396 | import asyncio
async def square(num):
await asyncio.sleep(num)
# print(f"tasks {num} compute value is {num * num}")
return num
async def main():
tasks = []
for i in range(10, 0, -1):
t1 = asyncio.create_task(square(i))
tasks.append(t1)
results = await asyncio.gather(*tasks)
... | avinash431/IntroductionToPython | asyncio/asyncio-3.py | asyncio-3.py | py | 390 | python | en | code | 0 | github-code | 36 |
17263839933 | #!/usr/bin/env python3
"""
Unreal Engine 5: Plugin Manager
"""
import os
import json
import tkinter
from tkinter import ttk, messagebox
from ttkwidgets import CheckboxTreeview
script_directory = os.path.dirname(os.path.abspath(__file__))
uproject_files = [f for f in os.listdir(script_directory) if f.endsw... | calebgray/UE5SkeletonProject | PluginManager.py | PluginManager.py | py | 1,905 | python | en | code | 0 | github-code | 36 |
9665851444 | #!/usr/bin/env python
# -*- encoding: utf-8
import gzip
import scipy.io as sio
from utils.utils import Utils
class GenericSparseDB(Utils):
def init(self):
self.data = sio.mmread(gzip.open(self._matrix_fn)).tolil()
self.factors = self._load_pickle(self._factors_fn)
self.fac_len = len(self.factor... | wojtekwalczak/FB_datalab | lib/generic_sparse_db.py | generic_sparse_db.py | py | 628 | python | en | code | 1 | github-code | 36 |
39876784242 | # -*- coding: utf-8 -*-
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from recommender.models import Movie
class ContentSimilarity:
# MELHORIA FUTURA: SALVAR MOST SIMILAR NO BD E ATUALIZAR SOMENTE QDO NECESSÁRIO
def conte... | guimedeiros1/adapt_recommender | recommender/algorithms/content_similarity.py | content_similarity.py | py | 1,452 | python | en | code | 0 | github-code | 36 |
25485816763 | # 파이썬에서 while문은 조건문이 참(True)일 동안
# 반복적으로 코드를 실행합니다. 다음은 while문의 기본 구조입니다.
# while 조건문:
# 실행할 코드1
# 실행할 코드2
# ...
i = 0
while i < 5:
print(i)
i += 1
# 짝수인 경우에는
while i < 10:
if i == 5:
break
if i % 2 == 0:
i += 1
continue
print(i)
i += 1 | Neogul02/py_ | 과외/1주차/while.py | while.py | py | 420 | python | ko | code | 0 | github-code | 36 |
29649651717 | import pandas as pd
import numpy as np
import csv as csv
from sklearn.ensemble import RandomForestClassifier
# CON ESTO GENERAMOS EL VECTOR DE BING
# HAY QUE GENERAR el FICHERO
df = pd.read_csv("./trafico-DATA-GDOT2.csv", sep=';')
df = df.sort_index(by=['Fecha Hora'], ascending=[True])
# print (df)
print ("Dia,Hor... | rubenglezant/playBetterBets | Python-Bolsa/Traffic/preparaDatos/extractBING.py | extractBING.py | py | 1,118 | python | en | code | 0 | github-code | 36 |
74840300263 | def license(age, hours):
if age >= 16 and hours >= 200:
print('issue license')
else:
print('dont issue license')
license(18,250)
license(15,192)
license(16,199)
license(16,201)
license(16,200)
| Cakarena/CS-2 | license_f.py | license_f.py | py | 229 | python | en | code | 0 | github-code | 36 |
15261672834 | """
Functions for temperature conversions
from farenheight to celcius
and vice versa.
"""
def convert(cel):
if cel <= -273.15:
return "that temperature cannot exist"
else:
far = cel* 9/5 + 32
return far
def calCLen (string):
if type(string) == 'str':
length = len(string)
... | uraniumpotato96/Assignment | celToFar.py | celToFar.py | py | 589 | python | en | code | 0 | github-code | 36 |
40657801370 | import torch
import numpy as np
import torch.nn.functional as F
from models import GetModel
from datagen import DataPool
from WGRutils import WGREnv, WandBScatterMaxlinePlot
import os
import wandb
import argparse
from datetime import datetime
from termcolor import colored
EPS = 1e-8
def temperature_schedule(args, t... | betairylia/WorldGen-Voxel-DMGibbs | eval.py | eval.py | py | 5,086 | python | en | code | 0 | github-code | 36 |
3238185308 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
f ="../test_batch.bin"
def read_img(file,k):
file_=open(file, 'rb')
val=int.from_bytes (file_.read(3073*k), byteorder='big')
label=int.from_bytes (file_.read(1), byteorder='big') # Correspond au label de l'ima
R=np.fr... | ouhmmouch-ls-me/project_CNN | Python/read.py | read.py | py | 1,221 | python | en | code | 0 | github-code | 36 |
7040661613 | from adr.World import Ambient
import numpy.testing as npt
import pytest
@pytest.fixture
def base_ambient():
base_ambient = Ambient(temperature=288.15, pressure=101325, humidity=30)
return base_ambient
def test_instantiation(base_ambient):
assert base_ambient.temperature == 288.15
assert base_ambient... | CeuAzul/ADR | tests/World/test_Ambient.py | test_Ambient.py | py | 898 | python | en | code | 12 | github-code | 36 |
28888793196 | '''
https://www.codewars.com/kata/5277c8a221e209d3f6000b56
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return true if the string is valid, and false if it's invalid.
This Kata is similar to the Valid Parentheses Kata, but introduces new characters: bra... | MSKose/Codewars | 6 kyu/Valid Braces.py | Valid Braces.py | py | 1,195 | python | en | code | 1 | github-code | 36 |
37634219850 | # Given a list of words, list of single letters (might be repeating) and score of every character.
# Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).
# It is not necessary to use all characters in letters and each letter can only be use... | sunnyyeti/Leetcode-solutions | 1255 Maximum Score Words Formed by Letters.py | 1255 Maximum Score Words Formed by Letters.py | py | 2,883 | python | en | code | 0 | github-code | 36 |
13671635352 | # bsp name
BSP = 'lm3s8962'
# toolchains
EXEC_PATH = 'C:/Program Files/CodeSourcery/Sourcery G++ Lite/bin'
PREFIX = 'arm-none-eabi-'
CC = PREFIX + 'gcc'
CXX = PREFIX + 'g++'
AS = PREFIX + 'gcc'
AR = PREFIX + 'ar'
LINK = PREFIX + 'gcc'
TARGET_EXT = 'so'
SIZE = PREFIX + 'size'
OBJDUMP = PREFIX + 'objdump'
OBJCPY = PREF... | JcZou/StarryPilot | starry_fmu/RTOS/examples/module/rtconfig_lm3s.py | rtconfig_lm3s.py | py | 590 | python | en | code | 287 | github-code | 36 |
71598655464 | from sqlalchemy import create_engine
from sqlalchemy import Table, Column, MetaData, Index
from sqlalchemy.types import DateTime, Integer, Float
class SQLDriver:
"""This SQLAlchemy wrapper exposes only those functions
that are used by pysatel, and hides all database interaction
details.
"""
def _... | dpq/pysatel | pysatel/sqldriver.py | sqldriver.py | py | 2,295 | python | en | code | 0 | github-code | 36 |
32473785722 | from config import bot, chat_id
from telebot import types
import requests
from bs4 import BeautifulSoup
from plugins.error import in_chat
@in_chat()
def cats(m):
bot.delete_message(m.chat.id, m.message_id)
keyboard = types.InlineKeyboardMarkup() #Добавляем кнопки
cats = types.InlineKeyboardButton(text="Еще... | evilcatsystem/telegram-bot | plugins/cats.py | cats.py | py | 1,178 | python | ru | code | 1 | github-code | 36 |
28446656659 | """"
AutoMap class
"""
# import
import os
import joblib
import pandas as pd
from datetime import datetime
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import GridSearchCV
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from skle... | tariqdam/automap | src/AutoMap.py | AutoMap.py | py | 7,996 | python | en | code | 1 | github-code | 36 |
37195193084 | import pandas as pd
# Read the CSV file
df = pd.read_csv('tracks_features.csv')
# Select only the desired columns
columns_to_keep = ['energy', 'speechiness', 'instrumentalness']
df = df[columns_to_keep]
# Write the result to a new CSV file
df.to_csv('song_data.csv', index=False) | LandonDoyle7599/HPC-Final | formatSongCSV.py | formatSongCSV.py | py | 282 | python | en | code | 0 | github-code | 36 |
28067719212 | # 큐 : 선입선출
import sys
input = sys.stdin.readline
n = int(input())
from collections import deque
queue = deque()
for _ in range(n):
data = input().split()
# push : x를 큐에 넣는 연산
if data[0] == 'push':
queue.append(data[1])
# pop : 큐 가장 앞 정수 빼고 출력, 큐에 들어있는 정수가 없는 경우 -1 출력
elif... | hwanginbeom/algorithm_study | 1.algorithm_question/3.stack,queue/128.Queue_sejin.py | 128.Queue_sejin.py | py | 1,247 | python | ko | code | 3 | github-code | 36 |
71315309865 | from flask import Flask, render_template, url_for, request, redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from datetime import datetime
from netmiko import Netmiko
import util
import json
from ntc_templates.parse import parse_output
# Init app
app = Flask(__name__)
... | gnasses/python | BGP_ASN_Management/app.py | app.py | py | 6,211 | python | en | code | 0 | github-code | 36 |
41153221424 | import os
import sys
sys.path.append(os.getcwd())
from functools import partial
import os
import pickle
import sys
import torch
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
import csv
from collections import defaultdict
import math
import glob
import re
from safe_control_gym.utils.c... | ustc-arg/Safe-Robot-Learning-Competition | experiments/arxiv/quadrotor_performance/utils/eval.py | eval.py | py | 15,039 | python | en | code | 3 | github-code | 36 |
28490769971 | from AirportVisit import AirportVisit
class ImpossibleRouteError(Exception):
def __init__(self, message):
self.message = message
class Route:
"""
Route: Contains information about a possible route.
Includes a method for calculating the cheapest places to refuel along the route.
Also incl... | shanecroberts/FuelManager | Route.py | Route.py | py | 7,316 | python | en | code | 0 | github-code | 36 |
10265845282 | import numpy as np
import random
import pickle
import os.path as osp
import pyflex
from softgym.envs.cloth_env import ClothEnv
import copy
from copy import deepcopy
class ClothDropEnv(ClothEnv):
def __init__(self, cached_states_path='cloth_drop_init_states.pkl', **kwargs):
"""
:param cached_states... | yanglh14/DIA | softgym/softgym/envs/cloth_drop.py | cloth_drop.py | py | 14,735 | python | en | code | 0 | github-code | 36 |
71899009704 | """A number-guessing game."""
# Put your code here
import random
name = input("Howdy, what's your name?\n(type in your name) ")
number_guessed = int(input(f"{name}, I'm thinking of a number between 1 and 100.\nTry to guess my number.\nYour guess? "))
number = random.randint(1, 101)
counter = 0
# Create function fo... | BuoyLynn/guessing-game | game.py | game.py | py | 779 | python | en | code | 0 | github-code | 36 |
4393518793 | # 곱하기 혹은 더하기
s = input()
ints = []
for i in s:
if i != '0':
ints.append(int(i))
ints.sort()
ans = ints[0]
for i in range(1, len(ints)):
if ans == 1:
ans += ints[i]
if ints[i] == 1:
ans += ints[i]
else:
ans *= ints[i]
print(ans)
# 풀이
data = input()
result = int(data... | sjjam/Algorithm-Python | Book/Greedy/Q2.py | Q2.py | py | 499 | python | en | code | 0 | github-code | 36 |
9288436312 | # Code by : Sam._.072
import sys
def MCM(a,s,e,dp):
if s==e:
return 0
ans=sys.maxsize
for k in range(s,e):
if dp[s][k]==-1:
ans1 = MCM(a, s, k, dp)
dp[s][k] = ans1
else:
ans1 = dp[s][k]
if dp[k+1][e]==-1:
ans2 = MCM(a, k+1, e, ... | sam-072/data-structure | Dynamic programming/Matrix Chain Multiplication.py | Matrix Chain Multiplication.py | py | 652 | python | en | code | 1 | github-code | 36 |
10500980706 | """
Experiment metadata parsing and validation.
"""
import os.path as osp
import json
from collections import defaultdict
from lrgasp import LrgaspException, gopen, iter_to_str, existing_datafile_name
from lrgasp.objDict import ObjDict
from lrgasp.defs import Repository, Species, Challenge, DataCategory, Sample, Librar... | LRGASP/lrgasp-submissions | lib/lrgasp/experiment_metadata.py | experiment_metadata.py | py | 16,668 | python | en | code | 8 | github-code | 36 |
2671461396 | from typing import Any
import torch
import torch.nn.functional as F
from torch.cuda.amp import autocast
from Exceptions import (
DeviceCannotSupportHalfPrecisionException,
DeviceChangingException,
HalfPrecisionChangingException,
NotEnoughDataExtimateF0,
)
from mods.log_control import VoiceChangaerLogger... | w-okada/voice-changer | server/voice_changer/DiffusionSVC/pipeline/Pipeline.py | Pipeline.py | py | 7,903 | python | en | code | 12,673 | github-code | 36 |
72747192423 | import os
import platform
from typing import Dict, List, Tuple, Union
import pyqtgraph as pg
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtGui import QPixmap
import constants
from data import load_json_data, calculate_extrema
from gauge import GaugeWidget
from user import User, get_user_percentage
def _cr... | Fard-Faru/CSC110-Final-Project | ui.py | ui.py | py | 23,144 | python | en | code | 0 | github-code | 36 |
42090662310 | import random
import warnings
import numpy as np
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import EpochBasedRunner, build_runner
from mmseg.core import DistEvalHook, EvalHook
from mmseg.datasets import build_dataloader, build_dataset
from mmseg.utils import get_r... | Gumpest/AvatarKD | mmrazor/apis/mmseg/train.py | train.py | py | 6,319 | python | en | code | 6 | github-code | 36 |
1252854862 | from pip._vendor.requests.packages.urllib3.connectionpool import xrange
class RotateString(object):
def rotateString(self, A, B):
if len(A) != len(B):
return False
if len(A) == 0:
return True
for s in xrange(len(A)):
if all(A[(s+i) % len(A)] == B[i] for... | lyk4411/untitled | beginPython/leetcode/RotateString.py | RotateString.py | py | 509 | python | en | code | 0 | github-code | 36 |
42554461186 | #!/usr/bin/env ipython3
## @file
# define log likelihood function to be called by pyMultinest
# disk version
import numpy as np
import pdb
import gi_helper as gh
from gi_class_profiles import Profiles
from gi_priors import check_bprior, check_tilt
from gi_chi import calc_chi2
import gi_physics as phys
from pylab impo... | PascalSteger/gravimage | programs/disk/gi_loglike.py | gi_loglike.py | py | 5,013 | python | en | code | 0 | github-code | 36 |
27052373239 | from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
def convertList(node: TreeNode, ls: List[int])... | ikedaosushi/leetcode | interviews/python/getAllElements.py | getAllElements.py | py | 896 | python | en | code | 1 | github-code | 36 |
17234962779 | import sys
n = int(sys.stdin.readline().rstrip())
inputs = []
for _ in range(n):
inputs.append(int(sys.stdin.readline().rstrip()))
inputs = inputs[::-1]
stack = []
result = []
for i in range(1, n+1):
result += "+"
stack.append(i)
while stack:
if stack[-1] == inputs[-1]:
result += "-"
stack.po... | jeongju9216/SwiftAlgorithm | Python/BOJ/스택/1874.py | 1874.py | py | 435 | python | en | code | 0 | github-code | 36 |
73871751145 | from django.contrib.auth import get_user_model
from django.db import models
from apps.consultations.models import AvailableConsultation
class Review(models.Model):
consultation = models.ForeignKey(
AvailableConsultation,
on_delete=models.CASCADE,
related_name="reviews",
verbose_na... | r1kk1s/mindsafe | apps/review/models.py | models.py | py | 795 | python | en | code | 0 | github-code | 36 |
931362262 | def label2idx(result):
results = result.copy()
for i, result in enumerate(results):
results[i] = int(result.split('/')[-1][1:])
return results
def get_fact(content):
breakers = []
fact_starts = []
for i, c in enumerate(content):
if c[0] == '【' and c[-1] == '】':
br... | china-ai-law-challenge/CAIL2021 | aqbq/python_sample/main/utils.py | utils.py | py | 983 | python | en | code | 126 | github-code | 36 |
23327627010 | # -*- encoding:utf-8 -*-
"""
选股示例因子:价格拟合角度选股因子
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
from Util import RegUtil
from PickStock.PickStockBase import PickStockBase, reversed_result
from Indicator.NDVolume import _calc_today_... | xiaoshitoucoding/Quantitative_Trading | common/PickStock/PickBreak.py | PickBreak.py | py | 1,844 | python | en | code | 2 | github-code | 36 |
12322732104 | def fibonacci(n):
'''
Return nth Fibonacci using a recursive function
input:
n:int -> Number to calculate nth Fibonacci
output:
The Fibonacci value in nth number
>>> fibonaci(5)
5
'''
if n < 2:
return 1
else:
return fibonacci(n-1)+fibona... | ipnYair95/EjerciciosPython | Begginer/Fibonacci.py | Fibonacci.py | py | 2,081 | python | en | code | 0 | github-code | 36 |
33211564014 | __all__ = ['WeightShareTransform', 'NeuralModule', 'PretrainedModelInfo', 'ModuleType', 'OperationMode']
import uuid
from abc import abstractmethod
from collections import namedtuple
from enum import Enum
from inspect import getargvalues, getfullargspec, stack
from os import path
from typing import Any, Dict, List, Op... | cppxaxa/ICAN.ShapeShifter | ICAN.ShapeShifter.Worker/nemo/core/neural_modules.py | neural_modules.py | py | 31,047 | python | en | code | 0 | github-code | 36 |
34219254093 | import sys
filename=sys.argv[1]
infile=open(filename+'_sorted.txt')
lines =infile.readlines()
infile.close()
i=0
while not lines[i][0] in '0123456789':
i+=1
curr_length=1
count=0
outfile=open(filename+'.ibs', 'w')
while i<len(lines):
length=int(float(lines[i].strip('\n')))
if length==curr_length:
... | kelleyharris/Inferring-demography-from-IBS | condense_sorted_lengths.py | condense_sorted_lengths.py | py | 469 | python | en | code | 14 | github-code | 36 |
39742184711 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchfile
class VGG_16(nn.Module):
"""
Main Class
"""
def __init__(self):
"""
Constructor
"""
super().__init__()
self.block_size = [2, 2, 3, 3, 3]
self.conv_1_1 = nn.Conv2d(3, 64, 3... | Sumching/Deep_Regression_Forests | networks/vgg_face.py | vgg_face.py | py | 4,010 | python | en | code | 5 | github-code | 36 |
22783507258 | #
# @lc app=leetcode id=875 lang=python3
#
# [875] Koko Eating Bananas
#
# https://leetcode.com/problems/koko-eating-bananas/description/
#
# algorithms
# Medium (53.87%)
# Likes: 2776
# Dislikes: 141
# Total Accepted: 122.2K
# Total Submissions: 223.9K
# Testcase Example: '[3,6,7,11]\n8'
#
# Koko loves to eat b... | Zhenye-Na/leetcode | python/875.koko-eating-bananas.py | 875.koko-eating-bananas.py | py | 1,932 | python | en | code | 17 | github-code | 36 |
3508350083 | # -*- coding: utf-8 -*-
from django.contrib.admin import ModelAdmin
from .forms import SeoAdminModelForm
from .models import Metatags
class SeoAdminMixin(object):
"""
Миксин, добавляющий метатеги к форме
"""
form = SeoAdminModelForm
def save_formset(self, request, form, formset, change):
... | aderugin/django-seo | seo/admin.py | admin.py | py | 1,706 | python | en | code | 0 | github-code | 36 |
75104151465 | from math import prod
from re import match, compile
class Tile:
def __init__(self, lines: list, tile_id: int, matching: list = []):
self.lines = lines
self.tile_id = tile_id
self.matching = matching
def all_edges(self) -> list:
return [self.top_edge(), self.bottom_edge(), s... | itsmeichigo/Playgrounds | AdventOfCode2020/Day20/day20.py | day20.py | py | 6,075 | python | en | code | 0 | github-code | 36 |
15189085805 | import networkx as nx
import os
import pylab
class depbuilder(nx.DiGraph):
"""Subclass of the directed graph class from the networkx package.
When initialized, it builds a directed graph of all the cuts dependencies."""
def __init__(
self,
cutdir='/tera2/data3/cdmsbatsProd/processing'
... | tdoughty1/python_cut_tera | graphbuilder.py | graphbuilder.py | py | 2,406 | python | en | code | 0 | github-code | 36 |
73381758504 | from pygame import *
class OurSprite(sprite.Sprite):
def __init__(self, img, x, y, speed):
super().__init__()
self.image = transform.scale(image.load(img), (65,65))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = speed
def rese... | BronikerBro/Labyrinth | maze.py | maze.py | py | 1,227 | python | en | code | 0 | github-code | 36 |
39498164047 | def grid_search(batch_size_list, epochs_list, lr_list, path_input,
path_csv_output, size_split, size_picture, ratio=1):
##### INITIALIZATION ######
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#device = "cpu"
print('device :',device)
dict_res... | DSMaryam/IndoorNavigation | src/drafts/temp_.py | temp_.py | py | 6,695 | python | en | code | 0 | github-code | 36 |
42998082606 | from __future__ import annotations
import decimal
import time
from datetime import datetime, timedelta, tzinfo
from logging import getLogger
from sys import byteorder
from typing import TYPE_CHECKING
import pytz
from pytz import UTC
from .constants import PARAMETER_TIMEZONE
from .converter import _generate_tzinfo_fr... | snowflakedb/snowflake-connector-python | src/snowflake/connector/arrow_context.py | arrow_context.py | py | 5,186 | python | en | code | 511 | github-code | 36 |
38301099 | import os
import configparser
import numpy as np
from basis_set_exchange import lut
def read_xyz(xyz_file_name):
with open(xyz_file_name) as fh:
xyz_lines = fh.readlines()
nuclear_numbers = []
coordinates = []
count = 0
mol_xyz = ''
for line in xyz_lines:
count += 1
if count == 1:
num_a... | takafumi-shiraogawa/SimpleQC | src/setting.py | setting.py | py | 2,182 | python | en | code | 4 | github-code | 36 |
210267346 | # Complete the hourglassSum function below.
def hourglassSum(arr):
listres = []
# Looping though all the values that can be included in the hourglass
for i in range(0,4):
for j in range(0,4):
# Adding all the values that form an hourglass
oneres = arr[i][j]+arr[i][j+1]+arr[i]... | pierpaolo28/Hackerrank-Challenges | Arrays/2D Array - DS/hourglass.py | hourglass.py | py | 598 | python | en | code | 3 | github-code | 36 |
70016851623 | WORDS = [word for word in open('dictionary.txt').read().lower().splitlines() if word.isalpha()]
def is_correct(my_word, match):
try:
for i in match:
my_word = my_word[my_word.index(i)+1:]
return True
except:
return False
def get_suggestion(my_word):
all_match = list(fil... | FedericoBruzzone/master-courses | advanced-programming/exercise/swayping-clouds-2012-09-03/swayping_on_the_phone/swype.py | swype.py | py | 497 | python | en | code | 10 | github-code | 36 |
16892668251 | import re
import os
import base64
import datetime
class User:
def __init__(
self,
is_admin,
surname,
name='',
birth_year=2000,
address='',
email='',
phone=''):
self.is_admin = is_admin
self.surname... | McWillie/midis | src/users.py | users.py | py | 5,582 | python | en | code | 0 | github-code | 36 |
39789413036 | # list1 = [ ["Shahzaib",1], ["Touqeer",3], ["Jabbar",4], ["Sohail",5] ]
#
# dic = dict(list1)
#
# for item, lollipop in dic.items():
# print(item, lollipop)
items = [int, float, "Shazzy", 12, 45, 45, 86,22, 65, 34, 34,365]
for item in items:
if str(item).isnumeric() and item>=6:
print(item) | ShahzaibRind/Python_Programms | For loops.py | For loops.py | py | 309 | python | en | code | 0 | github-code | 36 |
26297362799 | import urllib.request
import os
import json
import time
f = open("api_key", "r")
api_key= f.read()
f.close()
#this will work the same as if directly had the api key inserted into document. so you can hide api key, which is like your password from anyone who may read your code.
response = urllib.request.urlopen("ht... | sgturne/tmdb_data | tmdb_request.py | tmdb_request.py | py | 890 | python | en | code | 0 | github-code | 36 |
41771719676 | import numpy
t = int(input())
for i in range(t):
L = list(input().split())
L = list(map(int, L))
W = L[0]
N = L[1]
matrix = []
for j in range(N):
l = list(input().split())
l = list(map(int, l))
matrix.append(l)
matrix = sorted(matrix,key=lambda x: x[0])
w = ... | BuddhiWathsala/IEEE-Extreme | 11.0/BeetleBag.py | BeetleBag.py | py | 737 | python | en | code | 1 | github-code | 36 |
29085647325 | import random
from threading import Timer
from typing import List
from zone_api.audio_manager import Genre, get_music_streams_by_genres, get_nearby_audio_sink
from zone_api.core.action import action, Action
from zone_api.core.devices.motion_sensor import MotionSensor
from zone_api.core.event_info import EventInfo
from... | yfaway/zone-apis | src/zone_api/core/actions/play_music_at_dinner_time.py | play_music_at_dinner_time.py | py | 2,183 | python | en | code | 2 | github-code | 36 |
3655334212 | import numpy as np
# maska pro čtyřokolí 3x3 submatice
mask = np.array([[False, True, False], [True, True, True], [False, True, False]])
with open("input.txt", "r") as f:
heights = [list(x.strip()) for x in f.readlines()]
matrix = np.array(heights, dtype=np.int8)
# výplň pomocí 9, abych nemusel řešit hranice matic... | jakubhlava/AdventOfCode2021 | day9/day9.py | day9.py | py | 1,978 | python | cs | code | 0 | github-code | 36 |
3985529019 | import math
import torch
import numpy as np
from src.utils.utils import l2_normalize
from src.objectives.simclr import SimCLRObjective
class AdversarialSimCLRLoss(object):
def __init__(
self,
embs1,
embs2,
t=0.07,
view_maker_loss_weight=1.0,
**kwargs
):
... | jbayrooti/divmaker | src/objectives/adversarial.py | adversarial.py | py | 1,390 | python | en | code | 3 | github-code | 36 |
36152484622 | import hashlib
import uuid
import os
def key_hash(key):
"""
32-byte hash used for lookup of primary keys of jobs
"""
hashed = hashlib.md5()
for k, v in sorted(key.items()):
hashed.update(str(v).encode())
return hashed.hexdigest()
def uuid_from_buffer(*buffers):
"""
:param buf... | guzman-raphael/datajoint-test | datajoint/hash.py | hash.py | py | 988 | python | en | code | 0 | github-code | 36 |
72498711143 | pets = []
pet1 = {
'type': 'cat',
'name': 'silly',
'age': 2,
}
pet2 = {
'type': 'dog',
'name': 'stel',
'age': 5,
}
pet3 = {
'type': 'bird',
'name': 'fifa',
'age': 25,
}
pets.append(pet1)
pets.append(pet2)
pets.append(pet3)
for pet in pets:
t = pet['type'].title()
... | astreltsov/firstproject | Eric_Matthes_BOOK/DICTIONARY/6_8_Pets.py | 6_8_Pets.py | py | 434 | python | en | code | 0 | github-code | 36 |
27779071450 | from collections import Counter
import sys
sys.stdin = open('input.txt')
def solve():
t = int(input())
for _ in range(t):
n = int(input())
arr = [int(i) for i in input().split()]
ctr = Counter(arr)
counts = []
for i in ctr.items():
counts.append(i)
c... | live-abhishek/ds-algo | codechef/practice/alexnumb.py | alexnumb.py | py | 508 | python | en | code | 0 | github-code | 36 |
25209785200 | import threading
import zmq
import time
import socket
import sys
import datetime
def zmq_recv(context,url):
socket = context.socket(zmq.SUB)
# socket = context.socket(zmq.REP)
socket.connect(url)
socket.setsockopt(zmq.SUBSCRIBE,''.encode('utf-8')) # 接收所有消息
zhanbao=0
buzhanbao=0
start_tim... | Scottars/nis_website | dataservice/zmq/single_threading_subsys/tcp_receive_pub_multiregisters.py | tcp_receive_pub_multiregisters.py | py | 6,510 | python | en | code | 0 | github-code | 36 |
34927095374 | from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
from Interpolation import *
root = Tk()
root.title("Image Interpolation")
root.geometry("1250x770")
#Definitions for buttons
#temp - current displaying image
#temp1 - temporary variable used to store prev image for Undo
#original - Ori... | Sudheeradh/Image-Interpolation-and-Superresolution | GUI/Project_Interface.py | Project_Interface.py | py | 4,040 | python | en | code | 0 | github-code | 36 |
25317834336 | from __future__ import print_function
from is_wire.core import Channel, Message, Subscription, Logger
import socket
from RequisicaoRobo_pb2 import RequisicaoRobo
from is_msgs.common_pb2 import Position
import time
import random
log = Logger(name='Interface')
ip = "192.168.0.105"
class Subscribe:
def __init__(se... | matheusdutra0207/Exercicio | desenvolvimento/part1.py | part1.py | py | 3,353 | python | en | code | 0 | github-code | 36 |
21889526113 | # ugly fix for loading upstream.local.LocalUpstream
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
import logging
import tornado.web
import tornado.process
from tornado.options import define, options, parse_config_file
import tornado.ioloop
import json
from upstreams.local import LocalUpstream
from int... | changpingc/shuttle | xmpp/relay.py | relay.py | py | 6,154 | python | en | code | 3 | github-code | 36 |
22981434767 | from flask import Flask, render_template, redirect, url_for, request
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
import requests
tmdbkey = "16784bd3fece5ddb139f8b61... | p0c4/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp | Day 64/top-movies-project/main.py | main.py | py | 3,891 | python | en | code | 0 | github-code | 36 |
8332157614 | import unittest
from unittest import mock
from sync.models import Token
from sync.views import get_valid_token, sync_data
from deals.models import Deal
class ViewsTests(unittest.TestCase):
def tearDown(self):
Token.objects.all().delete()
Deal.objects.all().delete()
def test_get_valid_token_r... | walterbrunetti/hubspot-integration | hubspot_integration_app/sync/tests.py | tests.py | py | 2,775 | python | en | code | 0 | github-code | 36 |
24589263913 | import bs4
get_ipython().system('pip install selenium')
get_ipython().system('pip install webdriver_manager')
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager(version="87.0.4280.88").install())
driver.get("https://www.google.com")
... | haziqrao1/zameen.com_scrapper | zameen.com_data.py | zameen.com_data.py | py | 3,582 | python | en | code | 0 | github-code | 36 |
36858776309 | # -*- mode: python; -*-
import re
Import([
"env",
"has_option",
"get_option",
"use_libunwind",
"version_extra",
"version_parts",
])
env = env.Clone()
env.InjectMongoIncludePaths()
env.AppendUnique(FORCEINCLUDES=[
'mongo/platform/basic.h',
], )
env.SConscript(
dirs=[
'base',... | mongodb/mongo | src/mongo/SConscript | SConscript | 9,656 | python | en | code | 24,670 | github-code | 36 | |
495100847 | import os
from dagster import check
from dagster.core.errors import DagsterSubprocessError
from dagster.core.events import DagsterEvent, EngineEventData
from dagster.core.execution.api import create_execution_plan, execute_plan_iterator
from dagster.core.execution.config import MultiprocessExecutorConfig
from dagster.... | helloworld/continuous-dagster | deploy/dagster_modules/dagster/dagster/core/engine/engine_multiprocess.py | engine_multiprocess.py | py | 7,989 | python | en | code | 2 | github-code | 36 |
17153159723 |
import time
import sys
import ibmiotf.device
import random
from ibmcloudant.cloudant_v1 import Document, CloudantV1, BulkDocs
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
authenticator = IAMAuthenticator('YainZLYNqB_hRLBdq-1xI_nXOh3RhaUsxXgmOSav6Yof')
service = CloudantV1(authenticator=au... | IBM-EPBL/IBM-Project-5821-1658817259 | Final Deliverables/1_Final_Code/Bin python code simulator/code.py | code.py | py | 3,999 | python | en | code | 0 | github-code | 36 |
21333285377 | from sostrades_core.execution_engine.sos_wrapp import SoSWrapp
from climateeconomics.core.core_world3.population import Population
from sostrades_core.tools.post_processing.charts.two_axes_instanciated_chart import InstanciatedSeries, TwoAxesInstanciatedChart
from sostrades_core.tools.post_processing.charts.chart_filte... | os-climate/witness-core | climateeconomics/sos_wrapping/sos_wrapping_world3/population_discipline.py | population_discipline.py | py | 19,139 | python | en | code | 7 | github-code | 36 |
5226146422 | import os
import subprocess
import sys
argc = len(sys.argv)
if argc != 3:
sys.exit('usage: %s <executable> <count>' % sys.argv[0])
succ = 0
fail = 0
for _ in xrange(int(sys.argv[2])):
if (subprocess.call(sys.argv[1]) == 0):
os.rename('fuzzlog', '%d.s' % succ)
succ += 1
else:
os.ren... | dekimir/RamFuzz | ai/gencorp.py | gencorp.py | py | 368 | python | en | code | 298 | github-code | 36 |
22112532649 | import networkx as nx
import itertools as it
import argparse
import algorithms as algs
import gtf
from utils import get_chr, get_start_pos, get_end_pos, get_pos, merge_list_of_dicts
import utils
import sys
from wig import Wig
from exon_seek import ExonSeek
import multinomial_em as mem
import copy
# logging imports
imp... | ctokheim/PrimerSeq | splice_graph.py | splice_graph.py | py | 24,773 | python | en | code | 11 | github-code | 36 |
39783040335 | from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import torch
import torch.utils.data
import os
from shutil import rmtree
from .constants import BAS... | iamhectorotero/learning-physical-properties-with-rnns | libraries/isaac/utils.py | utils.py | py | 3,715 | python | en | code | 4 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.