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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20680175383 | ## copied dubruijn graphs file - in order, does not need cycle
def getReadsFromFile(infile):
f = open(infile)
#Depending on the file, could have extra newlines at end, strip off:
data = f.read().rstrip()
return data.split("\n")
def createDeBruijnGraph(reads):
#Initialize a dictionary to hold the adjacen... | kaiyaprovost/algobio_scripts_python | prob32_debrujinFromRead.py | prob32_debrujinFromRead.py | py | 1,851 | python | en | code | 0 | github-code | 6 |
8069070708 | class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# nums_dict = {nums[i] : i for i in range(len(nums))}
nums_dict = {}
for i in range(len(nums)):
cur_num = target - nums[i];
if cur_num in nums_dict.keys():
return [i, nums_dic... | yuki-nagano/coding-challenge | python/TwoSum.py | TwoSum.py | py | 415 | python | en | code | 0 | github-code | 6 |
12958936569 | from jlu.gc.orbits import isotropic as iso
from gcwork import young
from gcwork import analyticOrbits as aorb
import os, shutil
import numpy as np
import pylab as py
root = '/u/jlu/work/gc/proper_motion/align/08_03_26/'
def obsVsIsotropic():
# Analyze Observations
calcRadialDiskDensity()
calcRadialDiskDen... | jluastro/JLU-python-code | jlu/papers/lu09yng.py | lu09yng.py | py | 3,929 | python | en | code | 9 | github-code | 6 |
73944800188 | import warnings
warnings.filterwarnings('ignore', category=DeprecationWarning)
import os
os.environ['MKL_SERVICE_FORCE_INTEL'] = '1'
os.environ['MUJOCO_GL'] = 'egl'
from pathlib import Path
import hydra
import numpy as np
import torch
from dm_env import specs
import dmc
import utils
from logger import Logger
from ... | conglu1997/v-d4rl | drqbc/train.py | train.py | py | 13,697 | python | en | code | 64 | github-code | 6 |
20242652370 | class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return head
prevStack = []
curr = head
while curr.next is not None:
prevStack.append(curr)
curr = c... | JackTurner98/LCprepQs | Reverse Linked List.py | Reverse Linked List.py | py | 566 | python | en | code | 0 | github-code | 6 |
71357258427 | from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
import multiprocessing
import logging
from setting import news_file, word2vec_model_path, word2vec_vectors_path
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(lineno)d - %(message)s')
def word2vec_trai... | huangmgithub/Automatic_Summarization | bin/build_word2vec.py | build_word2vec.py | py | 1,131 | python | en | code | 1 | github-code | 6 |
8280572077 | '''
This problem was recently asked by Facebook:
Given a list of numbers, where every number shows up twice except for one number, find that one number.
Example:
Input: [4, 3, 2, 4, 1, 3, 2]
Output: 1
Time: O(n)
'''
def singleNumber(nums):
dup = 0
for num in nums:
dup = dup ^ num
return dup
pri... | gadodia/Algorithms | algorithms/Arrays/singleNumber.py | singleNumber.py | py | 363 | python | en | code | 0 | github-code | 6 |
73354334268 | import argparse
import json
import logging
import os
import random
import math
from pprint import pprint
logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)-7s - [%(funcName)s] %(message)s')
# uncomment for submission
# logger.disabled = True
ACTIONS = {
-1: 'DoN... | luqmanarifin/2016-Bomberman | Kecewa/bot.py | bot.py | py | 21,742 | python | en | code | 1 | github-code | 6 |
2517903386 | import cv2
import numpy as np
import math
import os
import pygame #play music
from tkinter.filedialog import askdirectory
from tkinter import *
root=Tk()
root.configure(background='grey')
root.minsize(300,300)
listofsongs = []
total=3
index = total-1#of list
def nextsong(event):
global index
if... | SDUDEJA16/MUSIC-ly-Gesture-Controlled-Music-Player | hand_detectionandrecoginition.py | hand_detectionandrecoginition.py | py | 5,433 | python | en | code | 0 | github-code | 6 |
124077703 | # @Time : 2023/4/2 22:49
# @Author : tk
# @FileName: infer
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')))
import torch
from deep_training.data_helper import ModelArguments
from transformers import HfArgumentParser
from data_utils import train_info_ar... | ssbuild/rwkv_finetuning | infer/infer_finetuning.py | infer_finetuning.py | py | 2,357 | python | en | code | 30 | github-code | 6 |
5051482507 | import csv
import sys
import getopt
import numpy as np
import pandas as pd
import nltk
def get_dataframe(filename):
return pd.read_table(filename)
def get_hfw():
word_file = open('./picked/pacifier.txt', 'r')
res = list()
for word in word_file.readlines():
word = word.split(" ")[0]
re... | WXM99/DataMiningProject | python_scripts/project/script/text_based_analysis/product_analysis/stat_product_score.py | stat_product_score.py | py | 5,220 | python | en | code | 0 | github-code | 6 |
8784215352 | from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
class Organisation(models.Model):
"""
An organisation that the user belongs to.
Eg: user_1 belongs to xyz organisation
# Create an organisation
>>> organisation_1 = Organisation.objects.create(... | simranmadhok/Venter_CMS | Venter/models.py | models.py | py | 3,615 | python | en | code | 0 | github-code | 6 |
6117900800 | import os
import sys
import numpy as np
import pandas as pd
import argparse
import pybedtools
import re
import pyBigWig as pbw
import time
import urllib.request
def main():
start = time.time()
print("Generating consensus peak file...")
args = parse_args()
#for
Input_peaks=pd.read_csv(args.Peaks, ... | xyg123/SNP_enrich_preprocess | scripts/CHEERS_preprocessing/Generate_consensus_peaks.py | Generate_consensus_peaks.py | py | 1,717 | python | en | code | 1 | github-code | 6 |
16919929356 | import json
from pydantic import parse_obj_as
from abc import ABC, abstractmethod
from typing import Any
from aiober.methods.base import Response
from .viber import ViberAPIServer, PRODUCTION
DEFAULT_TIMEOUT: float = 60.0
class BaseSession(ABC):
def __init__(self):
self.api: ViberAPIServer = PRODUCTION... | CodeCraftStudio-Family/aioviber | aiober/client/session/base.py | base.py | py | 912 | python | en | code | 0 | github-code | 6 |
4387515257 | # 내 풀이 & 교수님 풀이
from cs1robots import *
load_world('worlds/rain1.wld')
# load_world('worlds/rain2.wld')
hubo = Robot(beepers=10, street=6, avenue=2)
hubo.set_trace('blue')
def turn_right():
for _ in range(3):
hubo.turn_left()
def turn_around():
for _ in range(2):
hubo.turn_left()
def mark_st... | seoyun-dev/TIL | Python/python_HUBO_23_1/cs101_sample_code/lec3/3_task4_rain.py | 3_task4_rain.py | py | 879 | python | en | code | 0 | github-code | 6 |
24794202203 | #!/usr/bin/env python3
import sys, re, argparse
R = re.compile("(?P<number>\d+)\s+(?P<repeat>\d+)R")
def main():
"""
mcnp2phits - converts *some* parts of MCNP deck into PHITS format
"""
parser = argparse.ArgumentParser(description=main.__doc__,
epilog="Homepage: ... | kbat/mc-tools | mctools/phits/mcnp2phits.py | mcnp2phits.py | py | 955 | python | en | code | 38 | github-code | 6 |
7380809997 | import locale
import sys
class Base_Model():
trim ='normal'
en_lit = 1.5
mile_range=450
tank_cap = 45
color='white'
trans='auto'
@classmethod
def miles_per_liter(cls):
return cls.mile_range / cls.tank_cap
@classmethod
def miles_per_gallon(cls):
return cls.miles_per_liter() * 3.78541... | punithcse/ClonedOne | Workspace/clas_method.py | clas_method.py | py | 1,112 | python | en | code | 0 | github-code | 6 |
40359316924 | from django.db.models import fields
from django.forms.forms import Form
from django.shortcuts import render, redirect, HttpResponseRedirect
from django.urls import reverse
from django.views.generic import ListView, DetailView, UpdateView, CreateView, FormView
from django.http import Http404
from django.core.paginator i... | glauke1996/Kindergarten_Project | notifications/views.py | views.py | py | 4,518 | python | en | code | 0 | github-code | 6 |
31927207952 | from fastapi import FastAPI, Request, Response
import http, csv, json, yaml
import xml.etree.ElementTree as ET
app = FastAPI()
@app.get("/read-txt")
def _readTxtEndpoint():
with open('./text_file.txt') as f:
lines = f.read()
return {"resultSet": lines}
@app.get("/read-csv")
def _readCsvEndpoint():
... | DavidKrtolica/system_integration_repo | data_format_translation_servers [INDIVIDUAL]/python/main.py | main.py | py | 950 | python | en | code | 0 | github-code | 6 |
70780587388 | """
What are all of the letters that never appear consecutively in an English word?
For example, we know that “U” is not an answer, because of the word VACUUM, and we know that “A” is not an answer, because of “AARDVARK”, but which letters never appear consecutively?
"""
input_filename = "sowpods.txt"
#
def f... | storrer/udd-programming-practice | udd_problem_list/wordplay/17_letters_that_never_appear_consecutively.py | 17_letters_that_never_appear_consecutively.py | py | 1,221 | python | en | code | 1 | github-code | 6 |
17689670172 | import os
from torch.utils.data import Dataset
from torchvision.transforms import RandomCrop, Resize, InterpolationMode, RandomHorizontalFlip
from torchvision.transforms.functional import rotate
from torchvision.io import read_image
import numpy as np
class ImageData(Dataset):
def __init__(self, data_path, HR_shap... | abed11326/Training-a-Super-Resolution-GAN-for-4x-image-upscaling | imageData.py | imageData.py | py | 1,492 | python | en | code | 0 | github-code | 6 |
10420803323 | from __future__ import annotations
from typing import TYPE_CHECKING
from randovania.game_description.pickup import pickup_category
from randovania.game_description.pickup.pickup_entry import PickupEntry, PickupGeneratorParams, PickupModel
from randovania.game_description.resources.location_category import LocationCat... | randovania/randovania | randovania/games/prime3/generator/pickup_pool/energy_cells.py | energy_cells.py | py | 1,931 | python | en | code | 165 | github-code | 6 |
12509878797 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from collections import deque
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
if not head:
return
q=deque()
... | Tanya-Katiyar/Leetcode | 0143-reorder-list/0143-reorder-list.py | 0143-reorder-list.py | py | 927 | python | en | code | 0 | github-code | 6 |
42214943545 | """
/*** 本模块实现了自定义音乐查询获取并返回音乐CQ码kuq接口进行反向传输 ****/
/*** 音乐可以来自任何平台,并且支持查询操作****/
/*** write by @fengx1a0
"""
class FindMusic():
def __init__(self,key):
self.__key = key
import requests
self.__request = requests.get
handle = self.__request(url="http://musicapi.leanapp.cn/search?keywords="+self.__key)
_json = ... | fengx1a0/just_robot | HexRun/music_enhanced_module.py | music_enhanced_module.py | py | 1,654 | python | en | code | 0 | github-code | 6 |
18918432514 | from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import csv
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdr... | DangDuyAnh/Tich-Hop-Du-Lieu | DIProject/crawler/batdongsan-bot.py | batdongsan-bot.py | py | 4,570 | python | en | code | 0 | github-code | 6 |
22219030346 | from director.consoleapp import ConsoleApp
from director import robotsystem
from director import visualization as vis
from director import objectmodel as om
from director import ikplanner
from director import ikconstraintencoder as ce
from director import ikconstraints
from director import transformUtils
import numpy ... | RobotLocomotion/director | src/python/tests/testPlanConstraints.py | testPlanConstraints.py | py | 2,959 | python | en | code | 176 | github-code | 6 |
9186620520 | def _impl(ctx):
out = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(out, "Fake executable")
return [
cc_common.create_cc_toolchain_config_info(
ctx = ctx,
toolchain_identifier = "local_linux",
host_system_name = "local",
target_system_name... | bazelbuild/bazel | tools/cpp/empty_cc_toolchain_config.bzl | empty_cc_toolchain_config.bzl | bzl | 728 | python | en | code | 21,632 | github-code | 6 |
72478260029 | from django.http import JsonResponse
from django.shortcuts import render
from redis_ import rd
# Create your views here.
from django.views.decorators.cache import cache_page
from art.models import Art
from user import helper
import redis_
from art import tasks
@cache_page(30)
def show(request,id):
login_user = he... | cjxxu/A_Fiction_web | myapps/art/views.py | views.py | py | 1,808 | python | en | code | 1 | github-code | 6 |
38759778473 | """
Given a list of dictionary items, find the most optimal host with the least distance.
"""
import math
friends = [{"name": 'Bob', 'location': (5,2,10)}, {"name": 'Radha', 'location': (2,3,5)},
{"name": 'Mary', 'location': (19,3,4)}, {"name": 'Skyler', 'location': (1,5,3)}]
def find_host(friends):
init... | spanneerselvam/practice_problems | find_optimal_host.py | find_optimal_host.py | py | 1,164 | python | en | code | 0 | github-code | 6 |
3654514470 | import sys
import json
from mycroft.messagebus.client.ws import WebsocketClient
from mycroft.messagebus.message import Message
from mycroft.configuration import ConfigurationManager
from websocket import create_connection
def main():
"""
Main function, will run if executed from command line.
Send... | injones/mycroft_ros | scripts/mycroft/messagebus/send.py | send.py | py | 2,371 | python | en | code | 5 | github-code | 6 |
9248791794 | import sys
import tester
import signal
from utility import interpret, execute
def handler(x, y):
print('Too slow!')
sys.exit(-1)
signal.signal(signal.SIGALRM, handler)
signal.alarm(60 * 10)
def test_compiler(compiler_code):
testcase = tester.generate_testcases()
for code, inputstr in testcase:
... | tsg-ut/tsgctf2020 | misc/selfhost/dist/problem.py | problem.py | py | 1,917 | python | en | code | 25 | github-code | 6 |
26767459770 | from statistics import mode
import pytorch_lightning as pl
from torch.nn import functional as F
from torch import optim
from transformers import AutoModelForSequenceClassification
import torch
import pandas as pd
import numpy as np
from prediction_stats import print_stats
trans_cache_dir = "/cluster/scratch/gboeshert... | gauthierboeshertz/fallacy_detection | base_module.py | base_module.py | py | 5,254 | python | en | code | 1 | github-code | 6 |
72533958589 | import numpy as np
import pandas as pd
import time
import matplotlib.pyplot as plt
import seaborn as sns
import random
sns.set()
import pkg_resources
import types
from krx_wr_script import *
from tqdm import tqdm
from datetime import datetime
def get_state(data, t, n):
d = t - n + 1
block = data[d: t + 1] if d... | YoungseokOh/Stock-prediction-toy-project | analysis/bot_strategy.py | bot_strategy.py | py | 8,492 | python | en | code | 4 | github-code | 6 |
5259672483 | import csv
import io
import pickle
import proper_noun
import os
import subprocess
import common_nouns
import location
import re
from stop_words import get_stop_words
from nltk.tokenize import TweetTokenizer
from collections import defaultdict
import pickle
from nltk.corpus import wordnet as wn
from itertools import pr... | varun-manjunath/disaster-mitigation | matching/process_both.py | process_both.py | py | 20,459 | python | en | code | 2 | github-code | 6 |
42947667200 | from PyQt4 import QtGui, QtCore
from twisted.internet.defer import inlineCallbacks, returnValue
import socket
import os
from barium.lib.clients.gui.piezo_mirror_gui import QPiezoMirrorGui
from config.multiplexerclient_config import multiplexer_config
#from labrad.units import WithUnit as U
SIGNALID1 = 445571
SIGNALI... | barium-project/barium | lib/clients/Piezo_mirror_client/Piezo_mirror_client.py | Piezo_mirror_client.py | py | 6,846 | python | en | code | 5 | github-code | 6 |
7191980185 | from django.shortcuts import render, redirect
from .models import article
# Create your views here.
def index_defined_in_view(request):
articles = article.objects.all()
new_article = []
for row in articles:
if(len(row.title)>5):
new_article.append(row)
return render(request, 'inde... | dooking/LikeLion | session8/blog/write/views.py | views.py | py | 879 | python | en | code | 0 | github-code | 6 |
27618901256 | from django.contrib import admin
from home.models import Setting, ContactFormMessage
class ContactForMessageAdmin(admin.ModelAdmin):
list_display = ["name","email","subject","note","status"]
list_filter = ["status"]
# Register your models here.
admin.site.register(ContactFormMessage,ContactForMessageAdmin)
a... | mfatihyarar/B200109020_proje | home/admin.py | admin.py | py | 348 | python | en | code | 0 | github-code | 6 |
32508697252 | import numpy as np
import torch
from tqdm import tqdm
import torch.distributed as dist
import libs.utils as utils
from trainers.abc import AbstractBaseTrainer
from utils.metrics import AverageMeterSet
from libs.utils.metrics import intersectionAndUnionGPU
from datasets.dataset_utils import get_label_2_train
class Si... | numpee/UniSeg | trainers/single_trainer.py | single_trainer.py | py | 2,887 | python | en | code | 7 | github-code | 6 |
70396798267 | import chex
import numpy.testing as npt
import pytest
from shinrl import Pendulum
@pytest.fixture
def setUp():
config = Pendulum.DefaultConfig(dA=5)
return config
def test_to_discrete_act(setUp):
from shinrl.envs.pendulum.calc import to_discrete_act
config = setUp
act = to_discrete_act(config,... | omron-sinicx/ShinRL | tests/envs/pendulum/pendulum_calc_test.py | pendulum_calc_test.py | py | 1,812 | python | en | code | 42 | github-code | 6 |
26331405503 | import cv2
import glob
class FrameIterator:
"""
An iterator to iterate over multiple files containing either
images other videos. The files are gathered using pattern matching
and read with the universal cv2.VideoCapture().
...
Attributes
----------
pathpattern : str
input pa... | bunjj/Catadioptric-Stereo | FrameIterator.py | FrameIterator.py | py | 2,894 | python | en | code | 1 | github-code | 6 |
72294890749 | import sys
rus = ['бы', 'вас', 'видит', 'всего', 'вы']
eng = ['a', 'absorbed', 'all', 'and', 'another']
m = {}
for w1 in rus:
if w1 not in m:
m[w1] = {}
for w2 in eng:
m[w1][w2] = 0
print(m)
| janemurzinova/2017-osnov-programm | homework/matrix.py | matrix.py | py | 220 | python | en | code | 0 | github-code | 6 |
9312111752 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
"""
Complexit... | acnokego/LeetCode | 002_add_two_numbers/carry_digit.py | carry_digit.py | py | 1,223 | python | en | code | 0 | github-code | 6 |
41675574380 | # 잃어버린 괄호
import sys
input = sys.stdin.readline
lst = []
a = ""
for s in input().strip():
if s == "-":
lst.append(a)
a = ""
else:
a += s
lst.append(a)
def parse(p):
res = 0
r = ""
for s in p:
if s == "+":
res += int(r)
r = ""
else... | jisupark123/Python-Coding-Test | playground/silver/1541.py | 1541.py | py | 477 | python | en | code | 1 | github-code | 6 |
41169055403 | import argparse
import numpy as np
import os
import torch
import torch.nn as nn
import datetime
import time
import matplotlib.pyplot as plt
from torchinfo import summary
import yaml
import json
import sys
sys.path.append("..")
from lib.utils import (
MaskedMAELoss,
print_log,
seed_everything,
set_cpu_n... | XDZhelheim/GN-RRT | scripts/train.py | train.py | py | 9,502 | python | en | code | 0 | github-code | 6 |
5308434070 | # 문제수 / 역량 / 최대 개수
N, L, K = map(int, input().split())
# 쉬운문제 / 어려운문제
easy, hard = 0, 0
for i in range(N):
sub1, sub2 = map(int, input().split())
if sub2 <= L:
hard += 1
elif sub1 <= L:
easy += 1
ans = min(hard, K) * 140
if hard < K:
ans += min(K-hard, easy) * 100
print(ans)
# q = [... | louisuss/Algorithms-Code-Upload | Python/Baekjoon/Simulation/17724.py | 17724.py | py | 757 | python | en | code | 0 | github-code | 6 |
72627145467 | import inspect
import os
from typing import Any, Dict, List, Optional, Union
import yaml
import pmd
import pmd.core
# These have to be written explicitly for typing
from pmd.core.Builder import Builder
from pmd.core.Job import Job
from pmd.core.Lammps import Lammps
from pmd.core.Procedure import Procedure
from pmd.co... | ritesh001/Polymer-Molecular-Dynamics | pmd/core/Pmd.py | Pmd.py | py | 8,334 | python | en | code | 0 | github-code | 6 |
6634431843 | """
This is the custom function interface.
You should not implement it, or speculate about its implementation
class CustomFunction:
# Returns f(x, y) for any given positive integers x and y.
# Note that f(x, y) is increasing with respect to both x and y.
# i.e. f(x, y) < f(x + 1, y), f(x, ... | rh01/gofiles | lcode100-199/ex122/findSolution.py | findSolution.py | py | 981 | python | en | code | 0 | github-code | 6 |
73894506107 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import logging, time, os
class BaseView:
'''二次封装'''
def __init__(self, driver: webdriver.Remote):
self.driver = driver
self.timeout = 2
self.poll_freque... | inttcc/MyPro | workcoming/baseView/base.py | base.py | py | 3,466 | python | en | code | 0 | github-code | 6 |
39262377956 | from collections import namedtuple
from django.conf import settings
from elasticsearch import Elasticsearch
from elasticsearch.helpers import scan
from eums.elasticsearch.delete_records import DeleteRecords
from eums.elasticsearch.mappings import setup_mappings
from eums.elasticsearch.sync_info import SyncInfo
from eu... | unicefuganda/eums | eums/elasticsearch/sync_data_generators.py | sync_data_generators.py | py | 4,471 | python | en | code | 9 | github-code | 6 |
30755519335 | from collections import Counter
import math
n = int(input())
boxes = list(map(int, input().split(' ')))
boxes = sorted(boxes, reverse=True)
c = Counter(boxes)
ans = int(c[100] + max(0, math.ceil((c[50]-c[100])/3)))
print(ans)
| Tanguyvans/Codeforces | SIT/D.py | D.py | py | 230 | python | en | code | 0 | github-code | 6 |
11044904734 | import tkinter as tk
from UI.DeviceCLI import DeviceCli
from operations import globalVars
import threading
import network.show_commands.PCShowCommands as Show
import UI.helper_functions as hf
class PCCli(DeviceCli):
def __init__(self, canvas_object, class_object, popup, cli_text, prefix, text_color, cursor_color... | KarimKabbara00/Network-Simulator | UI/PCCLI.py | PCCLI.py | py | 3,886 | python | en | code | 0 | github-code | 6 |
31249185445 | import io
import os
import torch
from torch import nn
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
from transformers import (set_seed,
TrainingArguments,
Trainer,
GPT2Config,
GPT2Tokenizer,
... | Vitaliy1234/music_generation | emotion_classification/gpt2_classifier.py | gpt2_classifier.py | py | 6,088 | python | en | code | 0 | github-code | 6 |
75136417147 | import random
from tgalice.cascade import Pr
from cascade import csc, Turn
from datetime import datetime, timedelta
from uuid import uuid4
from scenarios.exercising import EXERCISES, Exercise
def is_morning_show(turn: Turn) -> bool:
if not turn.ctx.yandex or not turn.ctx.yandex.request:
return False
... | avidale/alice-stretching | scenarios/show.py | show.py | py | 1,066 | python | en | code | 1 | github-code | 6 |
2839724272 | '''
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
'''
class Solution(object):
def addBinary(self, a, b):
... | sgmzhou4/leetcode_problems | 67_Add Binary.py | 67_Add Binary.py | py | 982 | python | en | code | 0 | github-code | 6 |
27483656200 | import logging
from flask import abort, request, g, Response, make_response, jsonify, current_app
from flask_restplus import Namespace, Resource, fields, marshal_with
from battle.db.dbops import dbops
from battle.db.models import Battle
log = logging.getLogger(__name__)
posts_api = Namespace('postmeta', description='... | mthak/classmojo | battle/api/post.py | post.py | py | 1,214 | python | en | code | 0 | github-code | 6 |
33574367695 | import utils
def build(data):
G = dict()
for line in data:
a, b = line.split('-')
if a in G:
G[a].append(b)
else:
G[a] = [b]
if b in G:
G[b].append(a)
else:
G[b] = [a]
return G
def traverse(G, current_cave, current_p... | 742617000027/advent-of-code-2021 | 12/12.py | 12.py | py | 1,386 | python | en | code | 0 | github-code | 6 |
10859717127 | import random
print('두 정수를 입력하세요 : ',end='')
num = list(input().split(' '))
for i in range(len(num)) :
num[i]=int(num[i])
num.sort()
if(num[1]-num[0] <= 1) :
print('no integer between two numbers')
else :
print(random.randrange(num[0], num[1])) | Soyuen-Yu/python_Test | random/random161.py | random161.py | py | 279 | python | en | code | 0 | github-code | 6 |
17399515937 | from sys import argv
from special.mode import Mode
from special.settings import Settings
class BadMode(Exception):
pass
class BadCommandLineArguments(Exception):
pass
class Run:
def __init__(self, mode: Mode):
if len(argv) > 1:
self.parse_arguments(argv[1:])
else:
... | aaaaaa2493/poker-engine | src/special/run.py | run.py | py | 7,276 | python | en | code | 0 | github-code | 6 |
72128796028 |
#https://docs.python.org/ko/3.7/library/operator.html
from general import detailMaker
import numpy as np
def parseV3(value):
if len(value)==3:
x,y,z = value
elif value == ():#(())=>() but ([],)
x,y,z = 0,0,0
else:
value = value[0]
if isinstance(value,tuple) or\
... | liltmagicbox/3dkatsu | 5_structure/vector.py | vector.py | py | 4,207 | python | en | code | 0 | github-code | 6 |
64085434 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 20:30:54 2019
@author: Sunanda
"""
import argparse, re, decimal
parser = argparse.ArgumentParser(
description='''The purpose of this application is to check
the COMP 472/6721 Winter 2019 Projects'''
)
parser.a... | lqw1111/COMP6721-AI-Project | check.py | check.py | py | 2,781 | python | en | code | 1 | github-code | 6 |
71000611389 | import mob
import room
from time import sleep
import pygame
pygame.init()
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bran's Cool Game")
# Define some colors
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0... | heroicbran/games | Bran_s Pygame Engine/main.py | main.py | py | 4,050 | python | en | code | 0 | github-code | 6 |
74794654268 |
# import urllib library
from urllib.request import urlopen
import json
import random
score = 0
import string
NUMBER_OF_ATTEMPTS = 2
ENTER_ANSWER = 'Hit %s for your answer\n'
TRY_AGAIN = 'Incorrect!!! Try again.'
CORRECT = 'Correct'
NO_MORE_ATTEMPTS = 'Incorrect!!! You ran out of your attempts'
def question(mes... | RoiAtias/Devops_test | test/test.py | test.py | py | 1,321 | python | en | code | 0 | github-code | 6 |
38165912553 | import warnings
from typing import List
import numpy as np
from scipy import linalg
class Tensor(np.ndarray):
def __new__(cls, num_modes: int, modes: tuple[int], data: np.ndarray):
obj = np.asarray(data).view(cls)
obj.num_modes = num_modes
obj.modes = np.asarray(modes)
if np.any(ob... | lukbrb/pyTensor | pyTensor/tensorclass.py | tensorclass.py | py | 8,507 | python | en | code | 0 | github-code | 6 |
12019045259 | from PyQt5.QtWidgets import QTableView, QPushButton, QHeaderView, QDialog, QVBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery
class HistoryWindow(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle("History")
se... | umraan-xm/Image-Based-Equation-Solver | HistoryWindow.py | HistoryWindow.py | py | 1,767 | python | en | code | 4 | github-code | 6 |
71927421627 | import pymdicator.timeseries as ts
from pymdicator.indicators import Momentum, MACD, RSI
import numpy as np
import datetime
import pytest
import os
from pandas import read_csv
@pytest.fixture(params=[False, True])
def test_data(request, datadir):
if request.param:
pd = read_csv(datadir.join('stock_data.tx... | Cronan/pymdicator | tests/test_indicators.py | test_indicators.py | py | 6,858 | python | en | code | 0 | github-code | 6 |
14012082445 | import re
import numpy as np
import pickle
import spacy_udpipe
import spacy
import pandas as pd
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import RegexpTokenizer
from tqdm import tqdm
from bs4 import BeautifulSoup
from collections import Counter
class VectorSpaceModel():
'''
Vector space inf... | awmcisaac/charles | winter/npfl103/A2/A1/model.py | model.py | py | 6,816 | python | en | code | 0 | github-code | 6 |
33383350794 | from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
from .models import *
import bcrypt
# Create your views here.
def index(request):
return render(request, 'index.html')
def register(request):
if request.method != 'POST':
return redirect ('/')
errors =... | destinyng/quote_project_BlackBelt | quote_app/views.py | views.py | py | 4,949 | python | en | code | 0 | github-code | 6 |
69958425789 | """Test delete model
@Author: NguyenKhacThanh
"""
import pytest
from voluptuous import Schema, All, Required
from tests.api import APITestCase
@pytest.mark.usefixtures("inject_client", "inject_params_model_regression")
class DeleteModelTestCase(APITestCase):
def url(self):
return "/regression"
def me... | magiskboy/wipm | tests/api/test_delete_model_regression.py | test_delete_model_regression.py | py | 1,047 | python | en | code | 0 | github-code | 6 |
23916514495 | import torch
import os
import numpy as np
import csv
from torch.utils.data import Dataset
from torchvision import transforms
import torchvision
from PIL import Image
import json
default_transform = transforms.Compose([
transforms.ToTensor(),
])
class iclevr_dataset(Dataset):
def __init__(se... | ToooooooT/Deep-Learning | lab07/source_code/dataset.py | dataset.py | py | 2,146 | python | en | code | 0 | github-code | 6 |
34346298163 | '''
Exercises of the book "Think python"
13.1.1 Exercise:
'''
# Write a program that reads a file, breaks each line into words, strips whitespace
# and punctuation from the words, and converts them to lowercase.
#
# Hint: The string module provides a string named whitespace, which contains space,
# tab, newline, etc.... | LiliiaMykhaliuk/think-python | chapter13/13.1.1.py | 13.1.1.py | py | 1,119 | python | en | code | 0 | github-code | 6 |
19716184286 | import os, subprocess, datetime, re, shlex
class TortoiseSVNManager:
def __init__(self, tortoisesvn=None):
if tortoisesvn == None:
print("\n\n None Path - TortoiseProc.exe")
os.system("Pause")
sys.exit()
else:
self.tortoisesvn = tortoisesvn
d... | Nohhhhhh/PUBLIC | Project/AutoDeployment/AutoDeployment/tortoisesvnmanager.py | tortoisesvnmanager.py | py | 3,153 | python | en | code | 1 | github-code | 6 |
41168902007 | from utils import get_input_lines
from numpy import median
from collections import Counter
lines = get_input_lines("input7.txt")
input_list = [int(x) for x in lines[0].split(",")]
# pt1
print(sum(abs(x - median(input_list)) for x in input_list))
# pt2
mi, mx = min(input_list), max(input_list)
fuel_required = Counte... | sakshaat/aoc | solution7.py | solution7.py | py | 551 | python | en | code | 0 | github-code | 6 |
71779835068 | '''
1. CALCULA CUANTA INVERSION VALE LA PENA PARA CADA FIN DE AÑO USANDO EL PRECIO DADO EN EL CODIGO.
2. REALIZA UN GRAFICO PARA MOSTRAR CUANTO CAMBIA EL VALOR DE TU INVERSION DE 1000 EN UN AÑO.
PRIMERO CALCULA CUANTOS BITCOINS TENDRAS AL INICIO DIVIDIENDO SU INVERSIÓN POR EL COSTO DEL BITCOIN EN EL PRIMER AÑO (EL PR... | Giovanny100/archivos_Trabajo | archivos_py/calculos_financieros/CALCULOS BASICOS/grafico_bitcoin.py | grafico_bitcoin.py | py | 1,130 | python | es | code | 0 | github-code | 6 |
1396434248 | import os
import shutil
import glob
import random
import fnmatch
random.seed(0)
def counter():
counts = {'40':
{
'F' : 0,
'PT' : 0,
'A' : 0,
'TA' : 0,
'DC' : 0,
'LC' : 0,
'MC' : 0,
'PC' : 0
},
'100':
{
'F'... | anjaliupadhyay18/BreastCancer-TransferLearning | opt/preprocessing_mag/ppmodulesmag/magmodules.py | magmodules.py | py | 5,366 | python | en | code | 0 | github-code | 6 |
11782648101 | # -*- coding: utf-8 -*-
# XEP-0012: Last Activity
class LastActivity:
"""
query the server uptime of the specified domain, defined by XEP-0012
"""
def __init__(self):
# init all necessary variables
self.last_activity = None
self.target, self.opt_arg = None, None
def process(self, granularity=4):
seconds... | mightyBroccoli/xmpp-chatbot | classes/uptime.py | uptime.py | py | 1,221 | python | en | code | 7 | github-code | 6 |
29216462786 | from enum import Enum, unique
from sqlalchemy import (
Column, Table, MetaData, Integer, String, ForeignKey, Enum as PgEnum, DateTime,
PrimaryKeyConstraint,
UniqueConstraint
)
convention = {
'all_column_names': lambda constraint, table: '_'.join([
column.name for column in constraint.columns.v... | Dest0re/backend-school2022 | megamarket/db/schema.py | schema.py | py | 1,911 | python | en | code | 0 | github-code | 6 |
22079658709 |
import numpy as np
from termcolor import colored
import matplotlib.pyplot as plt
filename = 'scan1.txt'
file = open(filename, 'r')
lines = file.readlines()
inittime=lines[0]
endtime=lines[1]
print('# of lines',len(lines))
ADCout=[]
ADCoutstepsMean=[]
ADCoutstepsStd=[]
i=2
data=len(lines)
while i<data:
ADCout.ap... | gpapad14/RPy_CROC | 18bit_ADC_data/analysis.py | analysis.py | py | 568 | python | en | code | 0 | github-code | 6 |
23937560939 | import torch
import torch.nn as nn
# Tuple is structured by (filters, kernel_size, stride)
'''
Information about architecture config:
Tuple is structured by (filters, kernel_size, stride)
Every conv is a same convolution.
List is structured by "B" indicating a residual block followed by the number of repeats
"S"... | 1zzc/yolov3_achieve | model.py | model.py | py | 1,917 | python | en | code | 0 | github-code | 6 |
21115802122 | #!/usr/bin/env python
from gi.repository import Gtk, Gdk, GtkSource, GObject, Vte, GLib, Pango
from gi.repository.GdkPixbuf import Pixbuf
import os
import stat
import time
import jedi
class Handler:
def onShowCompletion(self, sview):
buffer = sview.get_buffer()
startiter, enditer = buffer.get_b... | superdachs/pyide | pyide.py | pyide.py | py | 18,021 | python | en | code | 1 | github-code | 6 |
13708970511 | #AREA
from database.config import Conexion
from helper import helper
#TABLA AREA
class Area:
def __init__(self, tipoArea=None):
self.tipoArea = tipoArea
def add_Area(self, area, app):
try:
conn = Conexion()
query = f'''
INSERT INTO area(tipoArea... | jesustr20/Reto10_PythonFLASK_Mysql_Empresa | apps/classes/area.py | area.py | py | 3,061 | python | en | code | 0 | github-code | 6 |
2804630485 | N = int(input())
count = 0
array = []
for i in range(1111, 10000):
if str(i).count('0') == 0:
for digit in str(i):
if N % int(digit) == 0:
count += 1
else:
count = 0
break
if count == 4:
count = 0
array... | Slavi15/Programming-Basics-Python---February-2022---Software-University | 17 - Nested Loops - Exercise/05 - Special Numbers/index.py | index.py | py | 359 | python | en | code | 0 | github-code | 6 |
74911410428 | import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from qtasync import AsyncTask, coroutine
from PyQt5.QtCore import QCoreApplication, Qt,QThread
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot ... | lupusomniator/paae_kurs | main v2.0.py | main v2.0.py | py | 5,611 | python | en | code | 0 | github-code | 6 |
21234105556 |
def reverse(num):
rev=0
while(num>0):
rem=num%10
rev=rev*10+rem
num=num//10
return rev
try:
def palindrome(num):
sum=num+reverse(num)
if (reverse(sum)!=sum):
palindrome(sum)
else:
print("%d is a Palindrome" %sum)
... | AniruddhaNaidu/Python-Coding | SampleTestPalindrome.py | SampleTestPalindrome.py | py | 713 | python | en | code | 0 | github-code | 6 |
70316000189 | from lib.get_endpoint import call_endpoint, endpoints
from lib.utils import format_response, trace
endpoint_inputs = {
"headers": {
"Content-Type": "application/json"
}
}
@trace(text="Delete company tasks")
def delete_tasks(command_args: dict):
"""
Function compiles a list of tasks associated... | dattatembare/pytaf | utilities/delete_all_company_tasks.py | delete_all_company_tasks.py | py | 2,136 | python | en | code | 0 | github-code | 6 |
35704005613 | from django.contrib import admin
from django.urls import path, include
from home import views
urlpatterns = [
path('', views.index, name='home'),
path('gallery', views.gallery, name='gallery'),
path('login', views.login_view, name='login'),
path('pricing', views.price, name='pricing'),
path('signup... | Shivam-08/gymdesign | home/urls.py | urls.py | py | 511 | python | en | code | 0 | github-code | 6 |
6398739491 | from dash import Dash
from dash.dependencies import Input, Output
from dash_core_components import Dropdown, Graph
from dash_html_components import H1, Div, P
from peewee import fn
from src.database import LastPackage, Package, PackageHistory
dash_app = Dash(__name__)
server = dash_app.server
dash_app.layout = Div(
... | dunossauro/cocomo-python | dashboard.py | dashboard.py | py | 9,281 | python | en | code | 5 | github-code | 6 |
74856623227 | #Program to find the fibonnaci series using recursion:---
def fib(n):
if a==1:
return 0;
elif a==2:
return 1;
else:
return fib(n-1) +fib(n-2)
n=int(input('enter the number:'))
if n<=0:
print('please enter a positive number.')
else:
print('Fibonnci series')
f... | Harshit8126/Python-codes | fibonnnaci.py | fibonnnaci.py | py | 358 | python | en | code | 1 | github-code | 6 |
41431741975 | from django.forms import ModelForm, TextInput
from django import forms
from .models import List
class ListForm(ModelForm):
class Meta:
model = List
fields = ['list']
widgets = {'task': TextInput(attrs={
'class': 'form-control',
'name': 'list',
... | awpogodin/py-CustomField | django/listvalid/forms.py | forms.py | py | 402 | python | en | code | 0 | github-code | 6 |
41603415015 | from phi.flow import *
from phi.geom import Phi
import matplotlib.pyplot as plt
import time, os, sys, argparse
sys.path.append('../')
from functions import *
parser = argparse.ArgumentParser()
parser.add_argument("-res", "--resolution", type = int, default = 128, choices=[64,128,256,512], help = "set resolution")
pars... | Brian-Hsieh/shapeOptim | code/generate_data.py | generate_data.py | py | 4,942 | python | en | code | 0 | github-code | 6 |
11951628523 | import plotly.express as px
import streamlit as st
from functions import *
st.set_page_config(
page_title="Time series annotations", page_icon="⬇"
)
# @st.cache(allow_output_mutation=True)
@st.cache_data
def load_data(op_data):
# df_despesa = pd.read_csv('https://raw.githubusercontent.com/jsaj/st_forecastin... | jsaj/st_forecasting | st_forecasting.py | st_forecasting.py | py | 10,989 | python | en | code | 0 | github-code | 6 |
16897712582 | """
Given an integer n, return the number of prime numbers that are strictly less than n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5 * 106
"""
"""
Appr... | rajeshpyne/leetcode | coding/204_count_primes.py | 204_count_primes.py | py | 1,148 | python | en | code | 0 | github-code | 6 |
34094783054 | #!/usr/bin/env python3
from plotter import collection, dataset
from plotter import histo, atlas, presets
import ROOT
import logging
logging.basicConfig(
level=logging.INFO, format="%(levelname)s (%(name)s): %(message)s"
)
log = logging.getLogger(__name__)
atlas.SetAtlasStyle()
cData = collection("Data")
cData.a... | fnechans/plotter | test.py | test.py | py | 3,117 | python | en | code | 0 | github-code | 6 |
17789517633 | from pygost.gost3412 import GOST3412Kuznechik as Kuz
from pygost.utils import hexdec, hexenc
from rich import print
REPLACES = {
",": "ЗПТ",
".": "ТЧК",
"-": "ТИРЕ",
";": "ТЧКИЗПТ",
}
def print_header(text):
print(header(text))
def print_kv(k, v):
print(kv(k, v))
def hea... | VasiliiSkrypnik/PKA_2023 | files/new_lab/lab7/Kuznyechik.py | Kuznyechik.py | py | 3,152 | python | en | code | 0 | github-code | 6 |
31381062627 | from faker import Faker
from app.db.dev import db
from app.db.models import Team
class TeamSeeder:
"""
Seeder class for generating team data.
"""
def __init__(self):
"""
Initialize the TeamSeeder class.
"""
self.fake = Faker()
def generate_teams(self, count):
... | rajahwu/FpGp | project_prep/app/db/seeders/teams.py | teams.py | py | 1,271 | python | en | code | 0 | github-code | 6 |
30164566686 | # %% Imports
import random
import pandas as pd
sales_train = pd.read_csv("../data/data_raw/sales_train.csv")
df_submission = pd.read_csv("../data/data_raw/submission_sample.csv")
# For reproducibility
random.seed(0)
VAL_SIZE = 38
# %% Keep only brands 1 and 2
brands_12 = sales_train[sales_train.brand.isin(["brand_1"... | cmougan/Novartis2021 | eda/xxx_old_data.py | xxx_old_data.py | py | 458 | python | en | code | 0 | github-code | 6 |
11485777017 | import random
import subprocess
from difflib import SequenceMatcher
from typing import cast
from smellybot.access_control import Everyone, ModPlus
from smellybot.bot_command import BotCommand, SuperCommand
from smellybot.bot_module import BotModule
from smellybot.config.definition import ListConfigDefinition
from smel... | schmarcel02/smellybot | smellybot/modules/owoifier.py | owoifier.py | py | 4,337 | python | en | code | 0 | github-code | 6 |
27453993567 | def countOccur(list,ele):
count = 0
for i in list:
if i == ele:
count += 1
print(count)
return count
list1 = [2,2,56,89,76,21,89,89,89,89]
x = 89
countOccur(list1,x) | sanika005/python_practise_examples | count_occurence_element_list.py | count_occurence_element_list.py | py | 202 | python | en | code | 0 | github-code | 6 |
24991032188 | from tkinter import *
root = Tk()
root.title('ERIC PY')
root.geometry("800x600")
def resize():
w = width_entry.get()
h = heigth_entry.get()
# root.geometry(str(w)+"x"+str(h))
root.geometry(f"{w}x{h}")
# root.geometry("{width}x{height}".format(width=w,height=h))
# root.geometry("%ix%i" % (w,h))... | miraceti/tkinter | gui_80tk_resize_Windows_Dynamically.py | gui_80tk_resize_Windows_Dynamically.py | py | 650 | python | en | code | 2 | github-code | 6 |
30353934551 | import ast
from .preference_manager import preference_manager
def get_scene_preferences():
"""Return a dictionary of the scene's default preferences."""
pref = preference_manager.preferences
res = {}
res['stereo'] = ast.literal_eval(pref.get('tvtk.scene.stereo'))
res['magnification'] = \
... | enthought/mayavi | mayavi/preferences/bindings.py | bindings.py | py | 958 | python | en | code | 1,177 | github-code | 6 |
4467004756 | import requests
urls = dict()
urls['http'] = ['gilgil.net']
urls['https'] = [
'google.com',
'naver.com',
'daum.net',
'github.com',
'gitlab.com',
'portal.korea.ac.kr',
'yonsei.ac.kr',
'snu.ac.kr',
'kaist.ac.kr',
'kisa.or.kr',
'kitribob.kr',
'twitter.com',
'youtube.co... | ugonfor/suricata-rule | request_url.py | request_url.py | py | 694 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.