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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
7775233369 | x = input()
y = input()
dp = [[None for i in range(len(y)+1)] for j in range(len(x)+1)]
def lcs(x, y, lx, ly):
if(lx==0 or ly ==0):
return 0
if(dp[lx][ly]!=None):
return dp[lx][ly]
if(x[lx-1]==y[ly-1]):
ans = 1+lcs(x, y, lx-1, ly-1)
dp[lx][ly] = ans
return ans
else:... | nishu959/Adityavermadp | lcsubsequencerecursivedp.py | lcsubsequencerecursivedp.py | py | 491 | python | en | code | 0 | github-code | 36 |
21188323810 | # Мне надоело постоянно менять номер версии в разных файлах, поэтому появился данный скрипт :)
import io
newver = input("Введите номер новой версии: ")
f = open("installer.iss", "rt")
buf = f.readlines()
f.close()
f = open("installer.iss", "wt")
for item in buf:
if item.startswith("#define MyAppVersion "):
print(... | student-proger/BellManager | changeVersion.py | changeVersion.py | py | 1,195 | python | ru | code | 0 | github-code | 36 |
43431126970 | from gameAI import findBestMove, findRandomMove
# function that takes a gamestate and excecute the move on the board of the gamestate, given a difficulty.
# Inputs: gs (game state object), difficulty ('easy' or 'hard'), turn (integer turn counter)
# Output: updated turn counter if move is made.
def computerMove... | AquaSpare/Alea-Evangelii-group-g | AImove.py | AImove.py | py | 699 | python | en | code | 0 | github-code | 36 |
6143716089 | import itertools
import math
from collections import defaultdict
import brownie
import pytest
from scripts.utils import pack_values
ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"
@pytest.fixture(scope="module", autouse=True)
def registry(
Registry,
provider,
gauge_controller,
alice,
... | curvefi/curve-pool-registry | tests/local/unitary/Registry/test_remove_pool_lending.py | test_remove_pool_lending.py | py | 4,686 | python | en | code | 169 | github-code | 36 |
74747977385 | #MORFOLOJİK OPERASYONLAR
import cv2
import matplotlib.pyplot as plt
import numpy as np
#
img = cv2.imread("img.png",0)
plt.figure(),plt.imshow(img , cmap = "gray"),plt.axis("off")
#EROZYON -ön plandaki nesnenin sınırlarını aşındırır
kernel = np.ones((3,3),dtype = np.uint8)
result = cv2.erode(img, ke... | tetroweb/opencv_lessons | lessons/chapter_9.py | chapter_9.py | py | 1,993 | python | tr | code | 0 | github-code | 36 |
44306025103 | import click
from datetime import timedelta
from pathlib import Path
from typing import Iterable
# this library does not come with type stubs, so we tell mypy to ignore it
import pytimeparse # type: ignore
from urbasys import log_utils
from urbasys.urbackup import retention
BACKUP_ROOT_DIR = "/urbackup/mirror"
@... | urbas/urbasys | urbasys/urbackup/app.py | app.py | py | 2,012 | python | en | code | 2 | github-code | 36 |
70939042984 | import os
import numpy as np
import matplotlib.pyplot as plt
from config import *
from model import get_model
from data import get_single_test
def evaluate(test_num):
model = get_model(train=TRAIN_MODEL)
print("got model")
test = get_single_test(test_num)
print("got test")
num_clips = test.shape[... | Colprit/VideoAnomolyDetection | main.py | main.py | py | 1,321 | python | en | code | 0 | github-code | 36 |
72673433065 | import time
start_time = time.time()
from global_var import *
from demandSimulate import *
from oneStepOptimization_poly import *
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
from scipy.stats import qmc
def microgrid_poly2d():
# stock
alpha = 0.5; K0 = 0; sigma... | thihaa2019/WindEnergy | Aditya(Python)/microgrid_poly2d.py | microgrid_poly2d.py | py | 4,451 | python | en | code | 0 | github-code | 36 |
20006327119 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils.rnn import pad_sequence
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
from gensim.models.word2vec import Word2Vec
import torch... | Woffee/dlvp | automl/main.py | main.py | py | 18,654 | python | en | code | 0 | github-code | 36 |
38032046802 | from batea import NmapReportParser, CSVFileParser
from os.path import join, dirname
nmap_full_filename = join(dirname(__file__), "samples/single_full.xml")
nmap_base_filename = join(dirname(__file__), "samples/single_base.xml")
nmap_malformed_filename = join(dirname(__file__), "samples/single_with_nulls.xml")
csv_sho... | delvelabs/batea | tests/test_parser.py | test_parser.py | py | 4,125 | python | en | code | 287 | github-code | 36 |
8192772574 | # -*- utf-8 -*-
########################################
# PSF license aggrement for logmsg.py
# Developed by Ivan Rybko
# Logmsg
########################################
from singleton import Singleton
import logging
@Singleton
class Logmsg:
def __init__(self, name):
if isinstance(name, str):
... | irybko/pyclasses | logmsg.py | logmsg.py | py | 1,573 | python | en | code | 0 | github-code | 36 |
33758919768 | # pykarta/geometry/projection.py
# Last modified: 3 February 2015
import math
# Convert latitude and longitude to tile coordinates. The whole part of the
# x and y coordinates indicates the tile number. The fractional part
# indicates the position within the tile.
def project_to_tilespace(lat, lon, zoom):
lat_rad = ... | nguyenl/qt-cfps | slippymap/projection.py | projection.py | py | 2,391 | python | en | code | 0 | github-code | 36 |
18394788465 | from typing import List, Union
from openai.types.chat import ChatCompletionMessageParam, ChatCompletionContentPartParam
from imported_code_prompts import (
IMPORTED_CODE_BOOTSTRAP_SYSTEM_PROMPT,
IMPORTED_CODE_IONIC_TAILWIND_SYSTEM_PROMPT,
IMPORTED_CODE_REACT_TAILWIND_SYSTEM_PROMPT,
IMPORTED_CODE_TAILW... | abi/screenshot-to-code | backend/prompts.py | prompts.py | py | 3,553 | python | en | code | 15,739 | github-code | 36 |
70816879145 | #!/usr/bin/env python
'''
./converter.py \
--model model.h5 \
--desc "Predicts either a phone is in the hands or in a pocket" \
--input_desc "Sensor samples (acc, gyro, mag, 50Hz)" \
--output_desc "1 - phone in the hands, 0 - phone in a pocket" \
--author "Danylo Kostyshyn" \
--license="MIT"
'''
from __future__... | danylokos/activity-demo-model | converter.py | converter.py | py | 1,593 | python | en | code | 1 | github-code | 36 |
6262380149 | import os,sys,re
import slide_window
import vcf_operating
import read_group
import read_dict
from multiprocessing import Pool
#https://github.com/mfumagalli/ngsPopGen/blob/9ee3a6d5e733c1e248e81bfc21514b0527da967b/scripts/getDxy.pl
def help():
print("python3 xx.py vcf two_group_list fasta_fai outfile window step")
... | ZJin2021/SCRIPT_ostrya | script/Population_Genetics/dxy.py | dxy.py | py | 3,460 | python | en | code | 0 | github-code | 36 |
39014036679 | # 백준 1987 알파벳
def sol():
global res
q = [(0, 0)]
v = [[0]*C for _ in range(R)]
used = [board[0][0]]
v[0][0] = 1
cnt = 1
while q:
r, c = q.pop(0)
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C ... | eomsteve/algo_study | johoh0/8th_week/1987_Alphabet.py | 1987_Alphabet.py | py | 816 | python | en | code | 0 | github-code | 36 |
71952050665 | class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
# initialize the result list
result = []
# iterate through the array
for i in range(len(nums)):
# skip duplicates
if i > 0 and nums[i] == nums[i-1]:
conti... | Exile404/LeetCode | LEETCODE_3Sum.py | LEETCODE_3Sum.py | py | 1,449 | python | en | code | 2 | github-code | 36 |
14765905838 | import matplotlib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def convert_to_seconds(s):
a = s.split(':')
return (float(a[0])*60+float(a[1]))
def name_to_idx(c):
if(c=='m'):
return 0
if(c=='t'):
return 1
return -1
def build_feature(df):
#chest
... | mdaniluk/emotion_AI | kinect_feature/build_kinect_feature.py | build_kinect_feature.py | py | 2,806 | python | en | code | 0 | github-code | 36 |
38533180256 | # Erg2Green.py
# Yanfei Tang
# The following paper will be useful:
# Xin Wang, Emanuel Gull, et.al PRB 80, 045101 (2009)
# Sebastian Fuch, Emanule Gull, et.al PRB 83, 235113 (2011)
#
import numpy as np
import os
import sys
from scipy import interpolate
def KKintegral(data):
"""
Do Kramers- Kronig integral to... | nnnvs/maximum-entropy-method | maximum-entropy-method/Utilities/Erg2Green.py | Erg2Green.py | py | 3,068 | python | en | code | 1 | github-code | 36 |
34462672186 | import multiprocessing
def configure(alive_table,available_stream_table,ports_list):
f = open("config.txt", "r")
replica_factor = int(f.readline())
replica_period = int(f.readline())
keepers_num = int(f.readline())
processes_num = int(f.readline())
for i in range(0,keepers_num):
ip = f.readline().rstrip() #... | AymanAzzam/Distributed-Files-System | master/configure.py | configure.py | py | 713 | python | en | code | 1 | github-code | 36 |
14017937824 | import maya.cmds as cmds
from functools import partial
def rename_sl(*args):
new_name = cmds.textField('Rename', q = True, text =True)
items = cmds.ls(sl=True)
for item in items:
cmds.rename(item , new_name)
def replace_sl(*args):
name_to_replace = cmds.textField('RePlace_before', q = True, tex... | s-nako/MayaPythonTools | ModelingTools/name_change/rename_sl.py | rename_sl.py | py | 1,426 | python | en | code | 0 | github-code | 36 |
31124460363 | import os
import torch
import numpy as np
from torch.utils.data import Dataset
import h5py
class DataSet(Dataset):
def __init__(self, transform, split='train'):
self.image_list = []
self.transform = transform
file_list_path = os.path.join('dataset', split + '.list')
with open(file_l... | yeshunlong/Reproduce | UA-MT/dataset.py | dataset.py | py | 2,746 | python | en | code | 2 | github-code | 36 |
70679148583 | import sys
import csv
import json
import time
import urllib.request
from urllib.error import HTTPError
from optparse import OptionParser
import argparse
def get_page(url, page, collection_handle=None):
full_url = url
if collection_handle:
full_url += '/collections/{}'.format(collection_handle)
full... | gilloglym/ShopifyWebScraper | shopify_scraper.py | shopify_scraper.py | py | 13,303 | python | en | code | 5 | github-code | 36 |
23343506239 | """
NOMBRE: Maria del Carmen Hernandez Diaz
ACCOUNT: 1718110389
GROUP: TIC 51
DATE: 30-05-2020
DESCRIPTION: Creación de cookies con nombre, número de visitas, fecha, y hora del visitante.
En caso de que no haya nombre como respuesta del usuario se marcara como 'Anónimo'.
"""
import web # Libre... | CarmenKaplanB/awi40 | semana_3/mvc/controllers/visitas.py | visitas.py | py | 2,221 | python | es | code | 0 | github-code | 36 |
26264738548 | # import member
import datetime as dt
import random
from member import Member
import requests
import json
import pandas as pd
from pandas import json_normalize
from tkinter import *
import numpy as np
class KoreaHolidays:
def get_holidays(self):
today = dt.datetime.today().strftime("%Y%m%d")
tod... | intacka/friendshipRice | main.py | main.py | py | 16,078 | python | en | code | 0 | github-code | 36 |
4835157446 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----湖南创乐博智能科技有限公司----
# 文件名:LCD1602.py
# 版本:V2.0
# author: zhulin
# 说明:液晶显示器模块
#####################################################
import time
import smbus
makerobo_BUS = smbus.SMBus(1)
# IIC LCD1602 液晶模块写入字
def makerobo_write_word(addr, data):
global makerobo_BL... | AmadeusGB/embedded-offchain-worker-demo | embedded-request-demo/LCD1602.py | LCD1602.py | py | 3,217 | python | en | code | 0 | github-code | 36 |
12814337666 | # 금광 / p375 / DP
# # 내가 푼 방법
from collections import deque
T = int(input())
dx = [-1,0,1] # 왼위, 왼, 왼아래
dy = [-1,-1,-1]
for i in range(T):
queue = deque()
n,m = map(int,input().split())
data = [[] for i in range(n)]
str = list(map(int,input().split()))
for i in range(n):
for j in range(m):... | Girin7716/PythonCoding | pythonBook/Problem Solving/Q31.py | Q31.py | py | 2,169 | python | ko | code | 1 | github-code | 36 |
850231959 | import datetime as dt
from peewee import DataError
from playhouse.postgres_ext import DateTimeTZField
class DateTimeTzField(DateTimeTZField):
def db_value(self, value):
if value is not None:
if value.tzinfo is None:
raise DataError(f'Cannot use naive datetime "{value}" in DateT... | malikfassi/SayMyName | api/common/models/DateTimeTZField.py | DateTimeTZField.py | py | 677 | python | en | code | 0 | github-code | 36 |
71929274985 | from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from model import Todo
app = FastAPI()
from database import(
fetchOneTodo,
fetchAllTodos,
createTodo,
updateTodo,
removeTodo,
)
origins = ['http://localhost:3000', 'http://localhost:4000']
app.add_middl... | coronel08/farm-stack-todo | backend/main.py | main.py | py | 1,660 | python | en | code | 0 | github-code | 36 |
10773542334 | import sqlite3
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
'''
This is a simple tool i made to create a plot graph with the data from the database. You can
manually enter the prefix's of the companys you want to look at in the prefix_list and it
will use all the data it c... | Barrenjoey/Company-Sentiment-Project | Graph.py | Graph.py | py | 4,618 | python | en | code | 0 | github-code | 36 |
828214309 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 24 23:37:57 2018
@author: pt
"""
for i in range(1,10) :
print(str(i) + '\r')
from IPython.display import clear_output
for f in range(10):
clear_output(wait=True)
print(f)
time.sleep(.1)
import sys
import time
... | thegreatskywalker/my_deep_learning | untitled3.py | untitled3.py | py | 466 | python | en | code | 0 | github-code | 36 |
124515595 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 1 14:20:05 2022
@author: Rovic Dimacali
"""
def computePay(hr, rt):
if hr > 40:
ans = (40*rt) + ((hours - 40) * ((rt/2) + rt))
return ans
elif hr <= 40:
ans = hr * rt
return ans
x = input("Enter Hours: ")
y = input("Enter Rate: "... | rvcdmcl/GitThat30Siz | tiqui.py | tiqui.py | py | 458 | python | en | code | 0 | github-code | 36 |
70016831143 | from alternade import *
if __name__ == "__main__":
for i in range(2,5):
tot = 0
var_format = "«{0}» is an alternade for "+ \
("«{{{}}}», "*(i-1)).format(*range(1,i))+"and «{{{}}}»".format(i)
for w, a in alternade_generator("dictionary.txt", i):
tot+=1
print(var_format.format(w,*a))
... | FedericoBruzzone/master-courses | advanced-programming/exercise/deepshallow-alternade-wormhole-2012-06-04/alternade/main-alternade.py | main-alternade.py | py | 432 | python | en | code | 10 | github-code | 36 |
7075228208 | """Strava API key update.
:authors
JP at 17/04/20
"""
from google.cloud import firestore
import logging
import requests
import time
db = firestore.Client()
collection = db.collection('strava')
class RefreshTokenBadRequest(Exception):
"""Expection for an invalid request to Strava to get a new token."""
... | j-penson/strava-leaderboards | functions/strava_key/main.py | main.py | py | 1,886 | python | en | code | 0 | github-code | 36 |
29589021649 | #!usr/bin/python
import os,os.path
import sys
import getopt
## get args from command line
## -r : output from step 7.2 (e.g. 1456519283nogap.fas.1)
## -s : output from step 7.3 (e.g. 1456519283nogap.fas.1.out)
## -o : output preffix
opts,args = getopt.getopt(sys.argv[1:],"r:s:o:")
for op, value in opts:
... | plantbiogeography/BaitsFinder | remove_plastid.py | remove_plastid.py | py | 1,134 | python | en | code | 0 | github-code | 36 |
33587155198 | from testflows.core import *
from testflows.asserts import error
from rbac.requirements import *
from rbac.helper.common import *
import rbac.helper.errors as errors
@TestScenario
def privilege_check(self, node=None):
'''Check that a role named ALL only grants privileges that it already has.
'''
user_nam... | ByConity/ByConity | tests/testflows/rbac/tests/privileges/all_role.py | all_role.py | py | 1,086 | python | en | code | 1,352 | github-code | 36 |
22324832829 | # 39. Faça um programa que leia dez conjuntos de dois
# valores, o primeiro representando o número do aluno
# e o segundo representando a sua altura em centímetros.
# Encontre o aluno mais alto e o mais baixo. Mostre
# o número do aluno mais alto e o número do aluno
# mais baixo, junto com suas alturas.
numero_alunos ... | asilvavieira/estrutura-de-repeticao | ex_39.py | ex_39.py | py | 991 | python | pt | code | 0 | github-code | 36 |
39467758886 | import errno
import sqlite3
import os
from mdde_stats.service.data import Benchmark
class LocalDataManager:
def __init__(self, data_dir: str):
"""
Constructor
:param data_dir: path to directory where database should be stored
"""
if data_dir is None:
raise Typ... | jcridev/mdde | stats-processor/src/mdde_stats/service/data/manager.py | manager.py | py | 3,347 | python | en | code | 1 | github-code | 36 |
38834210088 | import hashlib
import os
import time
import jsonlines
import openai
import tiktoken
import json
import tqdm
import numpy as np
from numpy.linalg import norm
from pathlib import Path
from .utils import SaveUtils
from .ai_openai import OpenAI
class OpenAIEmbedding:
openAI = OpenAI()
def __init__(self):
p... | doum1004/diginomard-make-it-rain-blog | diginomard_toolkit/ai_openai_embed.py | ai_openai_embed.py | py | 8,260 | python | en | code | 2 | github-code | 36 |
21539613759 | from pynput import keyboard
# Defines a function for the keylogger
def keyPressed(key):
print(str(key))
with open("keyfile.text",'a') as logKey:
try:
char = key.char
logKey.write()
except:
print("Error getting char")
if __name__ == "__main__":... | Roscalion/cybersecuritykeylogger | keylogger.py | keylogger.py | py | 410 | python | en | code | 0 | github-code | 36 |
74059837544 | import warnings
import configparser
from pathlib import Path
from typing import List, NamedTuple, Optional
FileConfiguration = NamedTuple(
"FileConfiguration",
[
("project", Optional[str]),
("remote", Optional[str]),
("server", Optional[str]),
("ignore", List[str]),
],
)
d... | facultyai/faculty-sync | faculty_sync/cli/config.py | config.py | py | 4,382 | python | en | code | 10 | github-code | 36 |
32932643233 | from django.db import models
# from address.models import AddressField
from django import forms
# from django_google_maps import fields as map_fields
from Location.models import Address
from django.utils.html import mark_safe
from django.conf import settings
from django.db.models import Avg
from decimal import *
class... | chandra10207/food_delivery | restaurant/models.py | models.py | py | 2,868 | python | en | code | 0 | github-code | 36 |
826465711 | """
:Product: three_day_forecast.txt
:Issued: 2012 Dec 12 1235 UTC
# Prepared by the U.S. Dept. of Commerce, NOAA, Space Weather Prediction
Center
#
A. NOAA Geomagnetic Activity Observation and Forecast
The greatest observed 3 hr Kp over the past 24 hours was 1 (below NOAA
Scale levels).
The greatest expected 3 hr Kp ... | diacritica/spaceweather | misc/scripts/load3dayforecast.py | load3dayforecast.py | py | 6,924 | python | en | code | 2 | github-code | 36 |
25625503023 | # assumption - numbers are not duplicate and non negative.
def twoSum (nums, target):
dic = {}
for i in range (len (nums)):
if (target - nums[i]) in dic:
return [dic[target-nums[i]], i]
else:
dic[nums[i]] = i
return None
print(twoSum([2,7,11,15],9)) | Akashdeepsingh1/project | 2020/2numbers.py | 2numbers.py | py | 304 | python | en | code | 0 | github-code | 36 |
74285277544 | import sys
from magma import *
from mantle import *
from rom import ROM
from rom import REGs
from uart import UART
from printf import IOPrintf
from boards.icestick import IceStick
icestick = IceStick()
icestick.Clock.on()
icestick.TX.output().on()
icestick.RTS.input().on()
icestick.CTS.input().on()
icestick.DTR.input(... | bjmnbraun/icestick_fastio | workdir/printf/ftdi.py | ftdi.py | py | 1,362 | python | en | code | 0 | github-code | 36 |
21885227488 | """
Tests brewblox_ctl.commands.docker
"""
import pytest
from brewblox_ctl.commands import docker
from brewblox_ctl.testing import check_sudo, invoke
TESTED = docker.__name__
@pytest.fixture
def m_utils(mocker):
m = mocker.patch(TESTED + '.utils', autospec=True)
m.optsudo.return_value = 'SUDO '
return ... | BrewBlox/brewblox-ctl | test/commands/test_docker.py | test_docker.py | py | 2,291 | python | en | code | 3 | github-code | 36 |
31802862219 | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
s_list = []
t_list = []
for c in s:
s_list... | bobcaoge/my-code | python/leetcode/242_Valid_Anagram.py | 242_Valid_Anagram.py | py | 657 | python | en | code | 0 | github-code | 36 |
13212484633 | from git_blame_project import utils
from .meta import ConfigurableMetaClass
__all__ = (
'configurable',
'Configurable'
)
class Configurable(metaclass=ConfigurableMetaClass):
"""
An abstract class that represents an object that can be configured.
"""
def __init__(self, **kwargs):
# Ev... | nickmflorin/git-blame-project | git_blame_project/configurable/configurable.py | configurable.py | py | 1,197 | python | en | code | 0 | github-code | 36 |
15807172488 | # --------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python interpreter will load... | segunar/BIG_data_sample_code | Spark/Workspace/1_Spark_Core/6_Text_File_Examples/24_average_length_of_words.py | 24_average_length_of_words.py | py | 13,654 | python | en | code | 0 | github-code | 36 |
44550764149 | from source.core.visualiser import Visualiser
# Fetch some GP models
from agents.example_agents import agents
# Unobserve the points from some GPs
i = 8
agents[i].unobserve_true_points(x=agents[i].x_seen)
agents[i].kappa = 3 # Higher regard for uncertainty works better for toy problem
# Initialise visualiser class
... | mgm21/GPs-visualised | source/main.py | main.py | py | 4,443 | python | en | code | 0 | github-code | 36 |
40325909166 | from ase.io import *
import numpy as np
import torch
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.nn.init as init
from sklearn.metrics import mean_squared_error
from math import sqrt
import tim... | Augustegm/Water-Pt | Water-Pt(111)/NeuralNet.py | NeuralNet.py | py | 9,197 | python | en | code | 0 | github-code | 36 |
3827669127 | #!/usr/bin/env python
from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxsize
from time import ctime
import re, os
tlds = ('com', 'end', 'net', 'org', 'gov')
f = open('redata.txt', 'w+')
for i in range(randrange(5, 11)):
dint = randrange(maxsize)
dstr = ctime(dint)
... | zhouhui0726/Python_simple | gendata.py | gendata.py | py | 636 | python | en | code | 0 | github-code | 36 |
6314719484 | import os
import sys
os.environ["TOKENIZERS_PARALLELISM"] = "true"
sys.path.insert(0, os.getcwd())
import gc
import time
import random
import warnings
warnings.filterwarnings("ignore")
import wandb
import os
import sys
import argparse
from datasets import load_dataset
import torch
from transformers import AutoTokeniz... | ixtiyoruz/EmotionClassification | src/train.py | train.py | py | 11,025 | python | en | code | 0 | github-code | 36 |
27691178390 | # Import modules
import random
from scapy.all import IP, UDP, send, Raw
from colorama import Fore
# Load MEMCACHED servers list
with open("tools/L4/memcached_servers.txt", "r") as f:
memcached_servers = f.readlines()
# Payload
payload = "\x00\x00\x00\x00\x00\x01\x00\x00stats\r\n"
def flood(target):... | LimerBoy/Impulse | tools/L4/memcached.py | memcached.py | py | 1,026 | python | en | code | 2,202 | github-code | 36 |
27495391959 | import pandas as pd
import numpy as np
file = 'OnCalls.xlsx'
xl = pd.ExcelFile(file)
xlData = xl.parse(0)
np.random.seed(42)
Names=[]
Days=[]
nP = 8
nD = 30
n = nD + nP - (nD % nP)
m = n / nP
for x in range(len(xlData)):
for y in range(1,n+1):
Excluded = False
for z in range(1,4):
i... | MousaAlhaddad/Scheduling-On-Call-Shifts | OnCalls.py | OnCalls.py | py | 2,157 | python | en | code | 0 | github-code | 36 |
21476691969 | from urllib import quote
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.auth im... | sherbondy/Attend | attend/events/views.py | views.py | py | 5,143 | python | en | code | 2 | github-code | 36 |
30100318023 | N = int(input())
field = []
large_width = 0
large_height = 0
small_width = 0
small_height = 0
for i in range(6):
idx, length = map(int, input().split())
field.append(length)
for i in range(6):
if i % 2:
if field[i] > large_width:
large_width = field[i]
else:
if field[i] > l... | jeong-hyejin/Algorithm | TIL/BOJ/BOJ_2477.py | BOJ_2477.py | py | 689 | python | en | code | 0 | github-code | 36 |
8666976439 | import argparse, os, string, sys
# Parse all parameters
parser = argparse.ArgumentParser()
parser.add_argument('ctfdir', type=str, help='Directory containing all tasks and descriptions, e.g. example-ctf-2015/')
args = parser.parse_args()
# os.walk returns: dirpath (args.ctfdir), dirnames, filenames
missing=external=c... | ctfs/write-ups-tools | checkreadme.py | checkreadme.py | py | 1,638 | python | en | code | 222 | github-code | 36 |
23949329045 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 4 15:28:32 2019
@author: abhinav.jhanwar
"""
import boto3
# from s3 bucket
if __name__=="__main__":
filename="farmer-looks-mountain-view.jpg"
bucket="bucket"
client=boto3.client('rekognition')
response = client.detect_labels(Image={'S3Object':... | AbhinavJhanwar/Amazon-API-boruta | basics/ObjectSceneDetectionImage.py | ObjectSceneDetectionImage.py | py | 973 | python | en | code | 0 | github-code | 36 |
985452723 | from display import Display
from movies import Movies
class BookMyShow(Display):
def run(self):
print("\n Welcome to BookMyShow \n ")
print("\n Please select Movie from following list: \n\n")
movie = Movies()
# Display movie list and select movie
movieList = movie.getMovi... | shahmilan34/project-ticketbooking | bookmyshow.py | bookmyshow.py | py | 1,631 | python | en | code | 0 | github-code | 36 |
11316416709 | import facebook
import json
import requests
#young creators group
facebook_group_id = '327549154019925'
# A helper function to pretty-print Python objects as JSON
def pp(o):
print(json.dumps(o, indent=2))
# Create a connection to the Graph API with your access token
access_token = 'EAACEdEose0cBABht2FYjCr2DkkBFBHU... | adamhipster/hackathon_website | python_fb_group_crawls/crawl.py | crawl.py | py | 1,134 | python | en | code | 0 | github-code | 36 |
29774282110 | # tuples are immutable but not constant
# If I understand those terms correctly
x, y, z = 10, 20, 30
tupleExp = (x, y, z)
print(tupleExp)
# not allowed:
# tupleExp[0] = y;
tupleExp = ("ten", "twenty", "thirty")
print(tupleExp)
# construction happens by value, not by reference
tupleExp = (x, y, z)
x = 40
print(tupleE... | Nikovic/Python_Dojo | collections.py | collections.py | py | 577 | python | en | code | 0 | github-code | 36 |
31481826861 | # -*- coding: utf-8 -*-
# @Author: zengjq
# @Date: 2020-10-21 14:50:13
# @Last Modified by: zengjq
# @Last Modified time: 2020-10-21 15:08:25
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right =... | Nriver/leetcode | 100. Same Tree.py | 100. Same Tree.py | py | 1,477 | python | en | code | 0 | github-code | 36 |
71079625704 | from amaranth import *
from usb_protocol.types import USBRequestType, USBStandardRequests, USBRequestRecipient
from luna.gateware.usb.usb2.request import USBRequestHandler
class PowerUSBHandler(USBRequestHandler):
def __init__(self, if_num):
super().__init__()
self.if_num = if_num
self.vt... | orbcode/orbtrace | orbtrace/power/usb_handler.py | usb_handler.py | py | 3,969 | python | en | code | 116 | github-code | 36 |
38019016436 | # Fichier qui gère les inputs et la customisation du programme
# Retourne True, True/False pour un input y ou n et 'erreur', False si l'input n'est pas y ou n
def true_false(rep):
if rep == 'y':
return True, True
elif rep == 'n':
return False, True
else:
print("la réponse doit être ... | tzebre/Needleman_wunch_L3 | MATHIEU_Theo_module/MATHIEU_Theo_custom.py | MATHIEU_Theo_custom.py | py | 6,725 | python | fr | code | 0 | github-code | 36 |
3962464959 | import datetime
from django import forms
from django.core.exceptions import ValidationError
from .models import Appointment
from django.contrib.auth.models import User
class DateInput(forms.DateInput):
"""
This class gets the widget working to show a datepicker
"""
input_type = 'date'
class TimeInpu... | Giov3ss/iHealthy | appointments/forms.py | forms.py | py | 2,524 | python | en | code | 0 | github-code | 36 |
34212069095 | # https://www.acmicpc.net/problem/1697
# solution dfs
# 1) 현재위치 n에서 가능한 세가지 경우 +1, -1, *2 를 dfs한다
# 2) 이때 dfs의 depth는 탐색 시간을 의미하기에 depth가 현재 최소탐색시간보다 큰 경우는 탐색하지 않는다
# 3) 모든 탐색이 끝난 후 최소탐색시간을 출력한다
# 한계: 파이썬 재귀 depth의 한계(기본적으로 1000) -> ex) 인풋으로 0 100000 이 들어올 경우 10만번 초과 재귀로 런타임 에러
# 좀더 근본적인 한계: 재귀로 탐색하기에는 너무 큰 범위(0 ~ 100... | chankoo/problem-solving | graph/1697-숨바꼭질.py | 1697-숨바꼭질.py | py | 3,234 | python | ko | code | 1 | github-code | 36 |
20031233758 | ##encoding: gbk
filename = "test.txt"
content = {}
save = open(filename, 'a+', encoding='gbk')
with open(filename, 'r+') as fr:
for line in fr.readlines():
if line not in content:
content[line] = 0
content[line] += 1
for word, val in content.items():
print(word, val,file=save) | Wilson-ZHANG/AttributeExtraction | txt_calculate.py | txt_calculate.py | py | 314 | python | en | code | 2 | github-code | 36 |
10902078602 | # https://docs.python.org/3/library/itertools.html#itertool-functions
from itertools import *
import operator
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
t... | Sanyam07/Ggg.Python | apps/app-docs/_legacy/documentation/library/itertoolsExamples/accumulateExample.py | accumulateExample.py | py | 1,015 | python | en | code | 0 | github-code | 36 |
8439375633 | # We are given an unsorted array containing ‘n+1’ numbers taken from the range 1 to ‘n’.
# The array has only one duplicate but it can be repeated multiple times. Find that duplicate number without using any
# extra space. You are, however, allowed to modify the input array.
# Example 1:
#
# Input: [1, 4, 4, 3, 2]
# O... | kashyapa/coding-problems | educative.io/easy-cyclic-sort/4_find_duplicate_number.py | 4_find_duplicate_number.py | py | 983 | python | en | code | 0 | github-code | 36 |
10558716337 | import gym
from copy import deepcopy
import numpy as np
class PositionState:
"""
Abstract class representing the objects in a scene
"""
static_objects = []
def __init__(self):
self.dimensions = (1000, 1000)
self.dynamic_objects = []
self.time = 0
return
def rand... | jerryz123/gym-urbandriving | gym_urbandriving/state/state.py | state.py | py | 2,780 | python | en | code | 1 | github-code | 36 |
73985065704 | from datetime import datetime, timedelta
from typing import Union
from uuid import uuid4
from django.apps import AppConfig
from django.conf import settings
class DjangoLightAuthConfig(AppConfig):
name = "django_light_auth"
default = True
login_path = "/login"
logout_path = "/logout"
success_path... | rexzhang/django-light-auth | django_light_auth/apps.py | apps.py | py | 1,598 | python | en | code | 0 | github-code | 36 |
21464640676 | import heapq
class Solution:
def pickGifts(self, gifts, k: int) -> int:
ans = sum(gifts)
gifts = [-gift for gift in gifts]
heapq.heapify(gifts)
for _ in range(k):
x = -gifts[0]
heapq.heapreplace(gifts, -int(x**0.5))
ans -= (x-int(x**0.5))
... | Anunay0501/coding_problems | Leetcode-2558-Take Gifts From the Richest Pile.py | Leetcode-2558-Take Gifts From the Richest Pile.py | py | 332 | python | en | code | 0 | github-code | 36 |
34541981528 | import dash
from dash import html
from dash import dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import pandas as pd
import numpy as np
import calendar
import plotly.express as px
import plotly.graph_objects as go
import datamodel
order = datamodel.get_data()
df_year = datam... | Patriciatworek1998/patr_demo_dash | app.py | app.py | py | 1,928 | python | en | code | 0 | github-code | 36 |
25904348422 | from abc import ABC, abstractmethod
from parametros import (
BONOS_CASA,
PROBABILIDAD_ABUCHEAR_GRYFFINDOR, PROBABILIDAD_APLAUDIR_GRYFFINDOR,
PROBABILIDAD_APLAUDIR_SLYTHERIN, PROBABILIDAD_ABUCHEAR_SLYTHERIN,
)
import random
class Programago:
# Completar
def __init__(self, nombre, saludo):
... | IIC2233/syllabus-2020-2 | Actividades/AS01/estudiantes.py | estudiantes.py | py | 2,558 | python | es | code | 7 | github-code | 36 |
14891394268 | #!/usr/bin/env python
# coding: utf-8
# In[161]:
# Produce a Python script to populate an aggregated table with the following structure:
# userId int
# registrationDate datetime
# registrartionUtmSource varchar (100)
# number_of_utm_touches int
# more_then_2_utm_touches_ind (int) (the indicator should be 1 if there... | ilayelazar/lusha_test | lsha.py | lsha.py | py | 1,866 | python | en | code | 0 | github-code | 36 |
2317460084 |
import os
import numpy as np
import cv2
def get_bounding_box(mat):
assert len(mat.shape) == 2
h, w = mat.shape
row = (np.sum(mat, axis=0) > 0).astype(np.uint8)
x0 = np.argmax(row)
x1 = w - np.argmax(row[::-1])
col = (np.sum(mat, axis=1) > 0).astype(np.uint8)
y0 = np.argmax(col)
y1 = h... | xinyunmian/matting | core/dataset/augment.py | augment.py | py | 1,056 | python | en | code | 0 | github-code | 36 |
4063202928 | from tkinter import *
class DOW:
def __init__(self):
window = Tk()
window.title("DOW")
Label(window, text="", width=1).grid(row=0, column=0)
Label(window, text=" Company:").grid(row=0, column=3, sticky=W)
Label(window, text=" Industry:").grid(row=3, column=3, sticky=W)
... | guoweifeng216/python | python_design/pythonprogram_design/Ch8/8-3-E12.py | 8-3-E12.py | py | 3,366 | python | en | code | 0 | github-code | 36 |
71354369385 | #!/bin/usr/env python
# ===========================================================
# Created By: Richard Barrett
# Organization: DVISD
# DepartmenT: Data Services
# Purpose: Skyward Administration
# Date: 04/01/2020
# ===========================================================
import selenium
import shutil
import xls... | aiern/ITDataServicesInfra | Python/Skyward/Administration/remove_sec_groups_inactive_users.py | remove_sec_groups_inactive_users.py | py | 5,755 | python | en | code | 0 | github-code | 36 |
70850460263 | import pandas as pd
import os
import time
from datetime import datetime
from os import listdir
from os.path import isfile, join
path ="/Users/Sanjay/Documents/StockPredictor/TodayStats"
def key_stats(gather="Total Debt/Equity"):
statspath=path+'/TodayStats'
#k = [225,226,227,228,229,230,231,232,233,234,235]
... | cloudmesh-community/fa18-523-66 | project-code/PredictDowIndex_1.py | PredictDowIndex_1.py | py | 5,169 | python | en | code | 0 | github-code | 36 |
26555767054 | #!/usr/bin/python3
from math import sin, cos, radians
from collections import namedtuple, defaultdict
from functools import reduce
from itertools import permutations, combinations
lines = open("day14.dat").read().splitlines()
#registers for part 1 and 2
reg1 = {}
reg2 = {}
for line in lines:
if line.count("mask ... | mcerdeiro/adventofcode2020 | day14/day14.py | day14.py | py | 1,590 | python | en | code | 0 | github-code | 36 |
30576170947 | import csv
import re
from application.contact import Contact
from application.phone_book import PhoneBook
IDENTITY_DATA = re.compile(
r'^(?P<lastname>.*?)\W+(?P<firstname>.*?)\W+(?P<surname>.*?)\W+(?P<organization>.*?)\W+(?P<position>.*?),(?P<phone>.*?),(?P<email>.*?)$')
def input_data():
phone_book = Phone... | fenixguard/netology_study | Python_advanced/regexp/regexp.py | regexp.py | py | 995 | python | en | code | 0 | github-code | 36 |
16520579385 | import datetime
from operator import itemgetter
from django.core.management.base import BaseCommand, CommandError
from django.db.models import *
from buckley.models import *
def cache_totals():
totals = Total.objects.all()
if totals:
total = totals[0]
else:
total = Total()
ie_total = ... | sunlightlabs/reportingsite | buckley/management/commands/cache_totals.py | cache_totals.py | py | 4,878 | python | en | code | 0 | github-code | 36 |
17113283160 | '''Exercise 2: Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines
that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print
out the contents of your dictionary (or... | amrmabdelazeem/PythonForEverybody | exercise9.7.2.py | exercise9.7.2.py | py | 931 | python | en | code | 0 | github-code | 36 |
19331078030 | import telebot
from model_predict import predict
from preprocessing import preprocess_text
bot = telebot.TeleBot(
"2087987681:AAG813Ais8YRNy4nlhrHZTK5UfQc4ZYa55Y", parse_mode=None)
# for /start and /help commands
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.reply_to(messa... | Jenpoer/pythoneers-hatespeech-bot | pythoneers_hatespeechbot.py | pythoneers_hatespeechbot.py | py | 876 | python | en | code | 0 | github-code | 36 |
11116052057 | #!C:\Users\varunachalam\AppData\Local\Programs\Python\Python36-32\python
import sumofcubes1
def main():
no1=eval(input("Enter the no you would like to Check whether this is Armstrong no"))
no2=sumofcubes1.sumcubes(no1)
if no1==no2:
print("Entered no %d is Armstrong no"%(no1))
else:
... | gavishwa/Python_Vishwaa | Armstrong.py | Armstrong.py | py | 406 | python | en | code | 0 | github-code | 36 |
36517097823 | import json
from sqlite_testdb import SqliteTest
class TestSbsVariationApi(SqliteTest):
def test_get_integrity(self):
"""
Tests if expected result is returned for integrity api
"""
actual_json = self.client.get('/sbs/analyses/1/integrities')
actual_json = json.loads(actual... | rohitbs113/DupontSBS | tests/test_sbs_variation.py | test_sbs_variation.py | py | 1,611 | python | en | code | 0 | github-code | 36 |
23059482493 | import peewee
import main
import logging
db_filename = main.CONF.get('VK', 'db_file', fallback='')
db = peewee.SqliteDatabase(db_filename, pragmas={'journal_mode': 'wal',
'cache_size': 64,
'foreign_keys': 1,
... | Sithief/async_bot | database/db_api.py | db_api.py | py | 5,009 | python | en | code | 0 | github-code | 36 |
36408701647 | from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .forms import PilotForm
from .models import Site, Pilot, Comment
from . import creed
from . import webster
import datetime
import traceb... | chadwickcheney/SeleniumTests | assure/views.py | views.py | py | 6,511 | python | en | code | 0 | github-code | 36 |
40130281674 | #!/usr/bin/env python
#coding=utf-8
# pip install aliyun-python-sdk-alidns
from aliyunsdkcore import client
from aliyunsdkalidns.request.v20150109 import SetDomainRecordStatusRequest
from flask import current_app
from datetime import datetime
class UpRecordStatus(object):
'''
region_id需要提交工单查询,默认cn_hangzhou
... | fish2018/prometheus_exporter | utils/alidns.py | alidns.py | py | 1,385 | python | en | code | 4 | github-code | 36 |
15130460020 | # Databricks notebook source
# MAGIC %pip install -r requirements.txt
# COMMAND ----------
import warnings
warnings.filterwarnings("ignore")
# COMMAND ----------
# MAGIC %sh
# MAGIC mkdir -p /dbfs/FileStore/solution_accelerators/digitization/ && touch /dbfs/FileStore/solution_accelerators/digitization/init.sh
# MAG... | databricks-industry-solutions/digitization-documents | config/configure_notebook.py | configure_notebook.py | py | 1,508 | python | en | code | 5 | github-code | 36 |
12906887118 | from hplcpostproagent.hypo_rxn.hypo_rxn import *
TIME_TEMPERATURE_ECO_SCORE_FACTOR = 0.002
AMBIENT_TEMPERATURE_DEGREECELSIUS = 25
ECO_SCORE_BASE_VALUE = 100
def calculate_performance_indicator(
hypo_reactor: HypoReactor,
hypo_end_stream: HypoEndStream,
rxn_exp_instance: ReactionExperiment,
target_clz:... | wsj-7416/TheWorldAvatar | Agents/HPLCPostProAgent/hplcpostproagent/hypo_rxn/calc_perf_ind.py | calc_perf_ind.py | py | 14,101 | python | en | code | null | github-code | 36 |
4079006523 | """
Plot omega, sliding net charge
plot sliding fraction of Q/N, S/T, A/G, P
"""
import os
import pandas as pd
import matplotlib.pyplot as plt
from deconstruct_lc import tools_lc
from deconstruct_lc.complementarity import motif_seq
class Fraction(object):
def __init__(self):
self.k = 6
self.lca = ... | shellydeforte/deconstruct_lc | deconstruct_lc/complementarity/sliding_fraction.py | sliding_fraction.py | py | 3,162 | python | en | code | 0 | github-code | 36 |
1132507113 | import logging
import time
import random
from langchain.agents import initialize_agent, load_tools
from langchain.chat_models import ChatOpenAI
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# import and initialize graphsignal
# add GRAPSIGNAL_API_KEY to your environment variables
i... | graphsignal/examples | langchain-app/main.py | main.py | py | 1,010 | python | en | code | 3 | github-code | 36 |
17929496471 | #!/usr/bin/python3
import sys
import collections
class Tree:
children = None
metadata = None
def __init__(self):
self.children = collections.deque()
self.metadata = collections.deque()
def parse_input():
line = next(sys.stdin).strip()
i = 0
while i < len(line):
num =... | Easimer/advent-of-code-2018 | day8/day8.py | day8.py | py | 1,553 | python | en | code | 0 | github-code | 36 |
26759660819 | def get_cats_info(path):
cat_list = []
with open (path, 'r') as opened_file:
while True:
line = opened_file.readline()
if not line:
break
elif line[-1] == '\n':
line = line[:-1]
... | EugenePython9/Python-9-Core | Module 6/Mod 6=5-14.py | Mod 6=5-14.py | py | 469 | python | en | code | 0 | github-code | 36 |
135256696 | from enum import Enum
import logging
import coloredlogs
import itertools
_LoggerEnums = {
1: ['system', 'SYSTEM'],
2: ['client', 'CLIENT'],
3: ['handler', 'HANDLER'],
}
LoggerEnums = Enum(
value='LoggerEnums',
names=itertools.chain.from_iterable(
itertools.product(v, [k]) for k, v in _Logg... | techolutions/madqtt-pi | madqtt/utils/Logging.py | Logging.py | py | 900 | python | en | code | 0 | github-code | 36 |
29976613151 | import os.path as osp
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
from pycocotools.coco import COCO
from .coco import CocoDataset
from .registry import DATASETS
@DATASETS.register_module
class SideWalkDataset(CocoDataset):
CLASSES = ('barricade', 'bench', 'bicycle', 'bollard', 'bus', 'c... | ytaek-oh/mmdetection | mmdet/datasets/sidewalk.py | sidewalk.py | py | 2,636 | python | en | code | 2 | github-code | 36 |
5791164779 | def encrypt(plaintext, key):
try:
plaintext = plaintext.upper()
key = key.upper()
key_length = len(key)
key_as_int = [ord(i) for i in key]
plaintext_int = [ord(i) for i in plaintext]
ciphertext = ''
for i in range(len(plaintext_int)):
value = (plai... | isfahany/CryptographyCode | Code/vigenere.py | vigenere.py | py | 1,121 | python | en | code | 2 | github-code | 36 |
32105984708 | from datetime import datetime
from string import Template
import pandas as pd
def read_template(file: str) -> Template:
with open(file, "r") as f:
content = f.read()
return Template(content)
df = pd.read_csv("export.csv")
df = df.astype(
{
"repository_stars_count": "Int64",
}
)
df =... | dbeley/lpa-table | lpa_html_builder.py | lpa_html_builder.py | py | 1,930 | python | en | code | 1 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.