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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
33390551810 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import gzip
from collections import defaultdict
import math
import scipy.optimize
import numpy
import string
import random
from sklearn import linear_model
import sklearn
# In[2]:
# This will suppress any warnings, comment out if you'd like to preserve them
import w... | vivianchen04/Master-Projects | WebMining&RecommenderSystems/midterm.py | midterm.py | py | 14,655 | python | en | code | 0 | github-code | 6 |
32170276466 | #
# demo.py
#
import argparse
import os
import numpy as np
import time
from modeling.deeplab import *
from dataloaders import custom_transforms as tr
from PIL import Image
from torchvision import transforms
from dataloaders.utils import *
from torchvision.utils import make_grid, save_image
torch.set_prin... | AlisitaWeb/SSRN | ceshi_label.py | ceshi_label.py | py | 3,929 | python | en | code | 0 | github-code | 6 |
38364671161 | # 집합의 표현
# 합집합 연산과, 두 원소가 같은 집합에 포함되어 있는지 확인
# 0 a b ( a가 포함되어 있는 집합과 b가 포함되어 있는 집합을 합친다는 의미 )
# 1 a b ( a와 b가 같은 집합에 포함되어 있는지 확인)
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
n, m = map(int, input().split())
# parent 테이블 자기 자신으로 초기화
parent = [i for i in range(n+1)]
# 루트 노드 찾을 때까지 재귀 호출
def fin... | jy9922/AlgorithmStudy | Baekjoon/1717번 집합의 표현.py | 1717번 집합의 표현.py | py | 988 | python | ko | code | 0 | github-code | 6 |
4391450776 | from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
@app.route('/',methods = ['POST', 'GET'])
def home():
if request.method == 'GET':
return render_template('index.html')
@app.route('/thankyou',methods = ['POST', 'GET'])
def thankyou():
if request.metho... | senthil-kumar-n/Subscribe_email | subscribe.py | subscribe.py | py | 1,004 | python | en | code | 0 | github-code | 6 |
20801798422 | n, s = [int(i) for i in input().split()]
nums = [int(i) for i in input().split()]
f = False
i = 0
j = len(nums)-1
while i != j:
if nums[i] + nums[j] == s:
f = True
break
elif nums[i] + nums[j] > s:
j -= 1
else: i += 1
if f:
print("YES")
else: print("NO") | michbogos/olymp | eolymp/prep6/sum_of_2.py | sum_of_2.py | py | 298 | python | en | code | 0 | github-code | 6 |
71718726268 | from . import Funktioner
import datetime
import MyModules.GUIclasses2 as GUI
import numpy as np
import os
from . import FileOps
#fix 14.04.10, simlk. Changed "centering error", which should make the test more forgiving at small distances - at large distances it has no effect.
# Last edit: 2012-01-09 fixed mtl t... | SDFIdk/nivprogs | MyModules/FBtest.py | FBtest.py | py | 9,922 | python | en | code | 0 | github-code | 6 |
16021983077 | import numpy as np
import matplotlib.pyplot as plt
from cartoplot import cartoplot
import imageio
from netCDF4 import Dataset
import pickle
def get(string):
"""
"Lakes":0,
"Oceans":1,
"Okhotsk":2,
"Bering":3,
"Hudso... | robbiemallett/custom_modules | mask.py | mask.py | py | 3,596 | python | en | code | 3 | github-code | 6 |
31512983034 | import os
import random
import string
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
CLIENT_ID = os.getenv("CLIENT_ID")
SCOPE = "user-library-read playlist-modify-public playlist-modify-private ugc-image-upload"
REDIRECT_URI = "http://127.0.0.1:8080/callback" if os.getenv("LOCAL_DEV") else "https://spotify-recently-liked.... | rjshearme/spotify_recently_added_playlist | constants.py | constants.py | py | 633 | python | en | code | 0 | github-code | 6 |
23432185259 | #Count the Number of Words: Write a program that counts the number of words in a string.
def count_words(string):
# Remove leading and trailing whitespace
string = string.strip()
# Split the string into words
words = string.split()
# Return the count of words
return len(words)
# User interface ... | rezashokrzad/git_youtube_tutorial | Python Challenges/challenge13.py | challenge13.py | py | 852 | python | en | code | 6 | github-code | 6 |
23944904707 | def fib(n):
if n < 3:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fast_fib(n):
if n < 3:
return 1
first = 1
second = 1
for i in range(3, n+1):
sum = first + second
first = second
second = sum
return second
| mengruojun/pylearning | src/data_structure/other/other.py | other.py | py | 291 | python | en | code | 0 | github-code | 6 |
38217727284 |
from utils import pickle_load
from matplotlib import cm
import matplotlib.pyplot as plt
import collections
def show_results(res_paths):
results = {}
for path in res_paths:
result = pickle_load(path)
for k, v in result.items():
if k not in results.keys():
results[k... | stomachacheGE/bofmp | tracking/scripts/show_best_parameter.py | show_best_parameter.py | py | 2,753 | python | en | code | 0 | github-code | 6 |
1633452952 | from __future__ import print_function
from builtins import str
from optparse import OptionParser
import sys
from opendiamond.config import DiamondConfig
from opendiamond.protocol import PORT
from opendiamond.server.server import DiamondServer
# Create option parser
# pylint: disable=invalid-name
parser = OptionParser... | cmusatyalab/opendiamond | opendiamond/server/__main__.py | __main__.py | py | 1,885 | python | en | code | 19 | github-code | 6 |
2893376277 | # -*- encoding: UTF-8 -*-
from django.http import Http404
from django.db.models.loading import get_model
from django.contrib.staticfiles.storage import staticfiles_storage
from django.contrib.admin.views.decorators import staff_member_required
from django.core.urlresolvers import reverse
from django.shortcuts import re... | revolunet/django-picocms | picocms/views.py | views.py | py | 1,926 | python | en | code | 4 | github-code | 6 |
19240250728 | import tensorflow as tf
import tensorflow_datasets as tfds
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config)
def load_celeba_dataset(args, shuffle_files=False, batch_size=128):
ds_train, ds_test = tfds.load(name='celeb_a', split=['train', 'tes... | UCSC-REAL/fair-eval | celeba/experiments/data.py | data.py | py | 452 | python | en | code | 5 | github-code | 6 |
71855094268 | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn import datasets
from sklearn import linear_model
import matplotlib.pyplot as plt
def sigmoid(z):
return 1/(1+np.exp(-z))
def costfunction(X, y, w):
cost = 0
size = y.shape[0]... | Fred199683/Logistic-Regression | LR.py | LR.py | py | 2,556 | python | en | code | 0 | github-code | 6 |
3035542775 | # given an integer array nums, handle multiple queries of the
# following type: calculate the sum of the elements of nums
# between indices left and right inclusive where left <= right
class prefix_sum:
def __init__(self,arr):
self.arr = arr
prefix = []
total = 0
for i in range(le... | estimatrixPipiatrix/decision-scientist | key_algos/class_prefix_sum.py | class_prefix_sum.py | py | 632 | python | en | code | 0 | github-code | 6 |
44496456290 | import json
import logging
import os
import random
import time
from datetime import datetime
from uuid import uuid4
import paho.mqtt.client as mqtt
# MQTT broker details
BROKER_ADDRESS = os.getenv("BROKER_HOST")
BROKER_PORT = 1883
# Configuring file handler for logging
log_file = f"{__file__}.log"
# Logging setup
lo... | SudeepKumarS/mqtt-sensor-api | mqtt-publisher/mqtt_publisher.py | mqtt_publisher.py | py | 2,912 | python | en | code | 1 | github-code | 6 |
12900539476 | from fastapi import APIRouter
from pydantic import BaseModel
from starlette.requests import Request
from ozz_backend import app_logger
from ozz_backend.persistence_layer import User
router = APIRouter(
prefix="/user",
tags=["user"],
# dependencies=[Depends(get_token_header)],
)
class UserOngoingOut(Bas... | honeybeeveloper/plat_back | ozz_backend/api/user.py | user.py | py | 895 | python | en | code | 0 | github-code | 6 |
40449109187 | import argparse
import json
EXAMPLE_USAGE = """
Example Usage via RLlib CLI:
rllib rollout /tmp/ray/checkpoint_dir/checkpoint-0 --run DQN
--env CartPole-v0 --steps 1000000 --out rollouts.pkl
Example Usage via executable:
./rollout.py /tmp/ray/checkpoint_dir/checkpoint-0 --run DQN
--env CartPole-v0 --st... | tud-amr/AC-LCP | utils/parse_args_rollout.py | parse_args_rollout.py | py | 8,847 | python | en | code | 2 | github-code | 6 |
15143757328 | from atelier_4_ex1 import gen_list_random_int
import matplotlib.pyplot as plt
import numpy as np
import time ,random
def extract_elements_list(list_in_which_to_choose,int_nbr_of_element_to_extract=10):
list_in_which_to_choose_length,mix_length = len(list_in_which_to_choose),0
mixList = list()
while ... | K-Ilyas/python | atelier_4/atelier_4_ex4.py | atelier_4_ex4.py | py | 2,594 | python | en | code | 0 | github-code | 6 |
11356022056 | from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import argodb as argo
import research_tools as research
plt.ion()
plt.close('all')
dirtopo = '/datawork/fsi2/mars/DATA/BATHY/ETOPO2'
topofile = 'etopo2.nc'
dirtopo = '/net/alpha/expo... | pvthinker/pargopy | pargopy_v0/define_landmask.py | define_landmask.py | py | 2,984 | python | en | code | 1 | github-code | 6 |
29756907883 | # Author: Sirui Feng
'''
This file splits each review on periods and conjuctions.
'''
import re
import json
from textblob import TextBlob
from textblob.sentiments import NaiveBayesAnalyzer
import csv
from word_stemmer import word_stemmer
public_utilities_path = 'data/public_utilities.json'
def split_period(review):
... | vi-tnguyen/textinsighters | gen_sentences.py | gen_sentences.py | py | 1,757 | python | en | code | 0 | github-code | 6 |
30099395988 | import imaplib
import socket
class IMAP4WithTimeout(imaplib.IMAP4):
def __init__(self, address, port, timeout):
self._timeout = timeout
imaplib.IMAP4.__init__(self, address, port)
def open(self, host="", port=143, timeout=None):
# This is overridden to make it consistent across Python... | mjs/imapclient | imapclient/imap4.py | imap4.py | py | 657 | python | en | code | 466 | github-code | 6 |
40483417494 | import tkinter, threading
from tkinter import ttk
from interface.onglets.onglets_map import OngletsMap
from interface.onglets.onglets_packets import OngletsPackets
from interface.onglets.onglets_personnage import OngletsPersonnage
from interface.onglets.onglets_sorts import OngletsSorts
import time
class MainInterfac... | Azzary/LeafMITM | interface/main_interface.py | main_interface.py | py | 3,458 | python | en | code | 3 | github-code | 6 |
137559983 | # Definir una función inversa() que calcule la inversión de una cadena. Por ejemplo la cadena "estoy probando" debería devolver la cadena "odnaborp yotse".
def inversa(cad1):
cad2 = ""
for i in range(1, len(cad1)+1): #arranco en 1 porque no existe el -0
cad2 += cad1[-i]
return cad2
assert(inver... | solchusalin/frro-utn-soporte2019-05 | practico_01/ejercicio-06.py | ejercicio-06.py | py | 411 | python | es | code | 0 | github-code | 6 |
17043338534 | # https://atcoder.jp/contests/past202004-open/tasks/past202004_h
N, M = list(map(int, input().split()))
A = []
for _ in range(N):
A.append(input())
group = []
for _ in range(11):
group.append([])
for i in range(N):
for j in range(M):
if A[i][j] == 'S':
n = 0
elif A[i][j] == 'G'... | atsushi-matsui/atcoder | middle/6-4-6.py | 6-4-6.py | py | 858 | python | en | code | 0 | github-code | 6 |
28470996419 | import os
import sys
from lockdoors import main
from lockdoors import sanitize
from lockdoors import shrts
from pathlib import Path
from datetime import datetime
from time import sleep
#VAR
yes = set(['yes', 'y', 'ye', 'Y'])
no = set(['no', 'n', 'nop', 'N'])
cwd = os.getcwd()
null = ""
###Cheatsheets
def revsh():
s... | SofianeHamlaoui/Lockdoor-Framework | lockdoors/reverse.py | reverse.py | py | 7,496 | python | en | code | 1,248 | github-code | 6 |
70818525628 | #import Library
import speech_recognition as sr
# Initialize recognizer class
r = sr.Recognizer()
# Reading Audio file as source
# listening the audio file and store in audio_text variable
# The path should be correct
with sr.AudioFile('Sample.wav') as source:
audio = r.listen(source)
# Using exception... | CHAODENG/Project4 | SpeechToText.py | SpeechToText.py | py | 632 | python | en | code | 0 | github-code | 6 |
40205551139 | # encoding: utf-8
"""
GraphicInterface.py
Displays the op amp calculator
Dario Marroquin 18269 (dariomarroquin)
Pablo Ruiz 18259 (PingMaster99)
Version 1.0
Updated March 4, 2020
"""
from tkinter import *
from CalculationsModule import *
import matplotlib.pyplot as plt
import nu... | PingMaster99/MNOpampCalculator | GraphicInterface.py | GraphicInterface.py | py | 4,699 | python | en | code | 0 | github-code | 6 |
23660254288 | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
""" A Python logging library with super powers """
import sys
import textwrap
from os import getcwd, path as p
from argparse import RawTextHelpFormatter, ArgumentParser
from pickle import dump, load
from io import open
from functools import partial, lru_cache
from s... | reubano/chakula | chakula/main.py | main.py | py | 7,603 | python | en | code | null | github-code | 6 |
74535524027 | from django.conf.urls import url
from . import views
app_name = 'api'
urlpatterns = [
url(r'^device/',views.device,name='api_device'),
url(r'^light/',views.light,name='api_light'),
url(r'^temperature/',views.temperature,name='api_temperature'),
url(r'^humidity/',views.humidity,name='api_hum... | CreeperSan/Graduation-Project | Web/field/api/urls.py | urls.py | py | 699 | python | en | code | 50 | github-code | 6 |
29546342820 | import graph
import unittest
class VertexColor:
"""
When doing a DFS, any node is in one of three states:
1. before being visited
2. during recursively visiting its descendants
3. after all its descendants have been visited and the recursion has backtracked from the vertex
"""
WHITE =... | HeliWang/upstream | Graph/UndirectedDFS/find-articulate-points.py | find-articulate-points.py | py | 4,563 | python | en | code | 0 | github-code | 6 |
18481267232 | import math
import time
if __name__ == '__main__':
start = time.time()
entries = [i.strip().split(',')
for i in open('Data/p099_base_exp.txt').readlines()]
max_val = 0
max_index = 0
for index, entry in enumerate(entries):
val = int(entry[1]) * math.log(int(entry[0]))
if val > max_val:
... | BreadBug007/Project-Euler | Prob_99.py | Prob_99.py | py | 433 | python | en | code | 0 | github-code | 6 |
73580429947 | import torch
import torchvision
import torchvision.datasets as datasets
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import math
def convert(imgf, labelf, outf, n):
f = open(imgf, "rb")
o = open(outf, "w")
l = open(labelf, "rb")
f.read(16... | smit-1999/NaiveBayes | nn.py | nn.py | py | 9,372 | python | en | code | 0 | github-code | 6 |
38762159073 | import random
def aloitus() -> list:
'''Tulostaa alkutervehdykset, palauttaa pelaajien nimet listana'''
print("Heippa! Pelataan Yatzya!")
print()
players = int(input("Kuinka monta pelaajaa on mukana? (max 4): "))
pelaajat = []
i = 1
while i <= players:
name =... | noorascode/MyFirstGame | Yatzy toimiva.py | Yatzy toimiva.py | py | 4,742 | python | fi | code | 0 | github-code | 6 |
37009360389 | """
https://leetcode-cn.com/problems/regular-expression-matching/submissions/
思路:递归法
2. 如果p[0] == {s[0], '.'}, 则递归p[1:], s[1:]
1. 如果len(p) >= 2, p[1] == '*'则:
A. 递归p[2:], s, 则表示p和前面的字符未匹配
B. 递归p, s[1:],则表示*匹配了一次,进行*的下一次匹配
"""
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p:
... | wangluolin/Algorithm-Everyday | dp/10-Regular_Expression_Match.py | 10-Regular_Expression_Match.py | py | 775 | python | en | code | 0 | github-code | 6 |
35619601544 | from nltk.corpus import cmudict
words = cmudict.entries()
count = 0
for entry in words:
if len(entry[1]) > 1:
count += 1
# Percentage of words with more than one possible pronunciation
print(1.0 * count / len(words)) | hmly/nlp-solutions | c-02/2-12_cmudict.py | 2-12_cmudict.py | py | 231 | python | en | code | 0 | github-code | 6 |
2116122344 | """
A command line interface to the qcfractal server.
"""
import argparse
import signal
import logging
from enum import Enum
from math import ceil
from typing import List, Optional
import tornado.log
import qcengine as qcng
import qcfractal
from pydantic import BaseModel, BaseSettings, validator, Schema
from . imp... | yudongqiu/QCFractal | qcfractal/cli/qcfractal_manager.py | qcfractal_manager.py | py | 42,285 | python | en | code | null | github-code | 6 |
916473686 | import re
def parse_blueprint(blueprint):
blueprint += " 0 ore 0 clay 0 obsidian"
return [int(re.search(r" ([\d]+) ore", blueprint).group(1)), int(re.search(r" ([\d]+) clay", blueprint).group(1)),
int(re.search(r" ([\d]+) obsidian", blueprint).group(1))]
def build_bot(bots, resources, bp, t, end... | UncatchableAlex/advent2022 | solutions/day19.py | day19.py | py | 2,386 | python | en | code | 0 | github-code | 6 |
24219583345 | # -*- coding: utf-8 -*-
"""
Created on 2022/9/23
@author: nhsiao
2022/9/5 avg_rsrp 改成 c_rsrp, 圖片從 2022/8/27閞始
2022/9/29 c_rsrp 改成 pos_first_rsrp, 圖片從 2022/9/23 閞始
"""
import cx_Oracle
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mpl_dates
import gc
import gzip
from datetime imp... | tonhsiao/cnn_cbam | CNN_CBAM_Daily/generateImg.py | generateImg.py | py | 18,040 | python | en | code | 0 | github-code | 6 |
40421641601 | from browser import document
from browser.html import DIV, FIELDSET, LEGEND, TEXTAREA
def result():
result_fildset = FIELDSET(Class='result')
result_fildset <= LEGEND('Resultado')
result_fildset <= DIV(id='result')
document['grid'] <= result_fildset
def get_query_string(fields: list, where='result'... | dunossauro/curso-python-selenium-pages | scripts/query.py | query.py | py | 581 | python | en | code | 13 | github-code | 6 |
18230626408 | # Tim Marder
# SoftDev1 pd06
# K#13 -- Echo Echo Echo
# 2018-09-28
from flask import Flask, render_template, request
app = Flask(__name__) #create instance of class Flask
@app.route("/") #assign fxn to route
def hello_world():
return render_template("home.html")
@app.route("/auth", methods = ["GET", "POST"... | TimMarder/SoftDev-Office | 13_formation/app.py | app.py | py | 701 | python | en | code | 0 | github-code | 6 |
43356399246 | #!/usr/bin/python3
import sys
def writeHeader(outputFile):
with open("headerTemplate.txt", 'r') as htFile:
text = htFile.read()
outputFile.write(text)
def writeFuncNames(outputFile, methods):
outputFile.write(" // node definition\n")
for method in methods:
outputFile.write(" " +... | peng225/class_dep | misc/gen_graph.py | gen_graph.py | py | 1,400 | python | en | code | 0 | github-code | 6 |
35541984220 | lst=[10,12,13,16,20,25]
searchF=13
def searchL(lst,frm,to,findN):
if to>=frm:
centerIndex=int((frm+to)/2)# int(len(lst)/2)
if findN==lst[centerIndex]:
return centerIndex
if findN<lst[centerIndex]:
return searchL(lst,frm,centerIndex-1,findN)
else:
return searchL(lst,centerIndex+1,t... | Riddhesh06/hacktoberfest2021 | binarySearch.py | binarySearch.py | py | 413 | python | en | code | 0 | github-code | 6 |
8185206077 | import json
import yaml
import subprocess
def add_cluster_ips(cluster_name, save=True):
"""
Adds the IPs for the specified cluster.
Args:
cluster_name (str): The name of the cluster.
save (bool, optional): Whether to save the IPs to the file. Defaults to False.
Returns:
dict... | chevalsumo/5G-Services-Placement-in-Dynamic-Multi-clusters | kind_automatisation/scripts/submariner_configuration/broker_context.py | broker_context.py | py | 7,163 | python | en | code | 0 | github-code | 6 |
12461550259 | from preprocess import *
import os
import argparse
from csv import writer
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process pcap file and integer data.")
parser.add_argument("-pcap", nargs="+", help="The pcap file. Multiple pcaps can be added when separated by a space.")
pars... | mayakapoor/palm | src/preprocessing/main.py | main.py | py | 1,391 | python | en | code | 0 | github-code | 6 |
9878964651 | #!/usr/bin/python
# disk monitor
import logging as l
l.basicConfig(filename='disk_log.txt',filemode='a',level=l.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%c')
# modes
# r -> read -> you can only read the file.
# a -> append -> you can only append the contents to the file... | tuxfux-hlp-notes/python-batches | batch-68/14-logging/third.py | third.py | py | 900 | python | en | code | 5 | github-code | 6 |
37122760097 | # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from fanza.items import ImageItem
from fanza.common import download_image
from fan... | takiya562/Adult_video_scrapy | fanza/pipelines.py | pipelines.py | py | 2,876 | python | en | code | 4 | github-code | 6 |
23184716017 | #! /usr/bin/python
__author__ = "grasseau"
__date__ = "$Jul 12, 2020 9:56:07 AM$"
import sys, traceback
import struct
import numpy as np
import pickle
def readInt2(file, n):
if ( n == 0 ): return np.zeros( (0), dtype=np.int16 )
#
# Read Nbr of items (8 bytes)
raw = file.read(2 * 4)
nData = ... | grasseau/MCHClustering | src/Util/IOTracks.py | IOTracks.py | py | 6,767 | python | en | code | 0 | github-code | 6 |
73815019386 | import logging
from os import environ
from unittest.mock import patch
import pytest
from bonobo import settings
from bonobo.errors import ValidationError
TEST_SETTING = "TEST_SETTING"
def test_to_bool():
assert not settings.to_bool("")
assert not settings.to_bool("FALSE")
assert not settings.to_bool("N... | python-bonobo/bonobo | tests/test_settings.py | test_settings.py | py | 1,851 | python | en | code | 1,564 | github-code | 6 |
5026791116 | import zizouqi_tools
import random
# print(computer)
player = zizouqi_tools.Game()
num = 0
"""
while num < 3:
player.chouka()
num += 1
player.chuzhan()
"""
num2 = 0
# while num2 < 1:
# hero_1 = int(input("请你输入技能【1-3】:"))
# player.pk(computer,hero_1)
while num2 < 1:
computer = random.randint(1, 3)
... | xinlongOB/python_docment | 自走棋/main.py | main.py | py | 473 | python | en | code | 0 | github-code | 6 |
70514119229 | from collections import defaultdict
from github import Github
def get_git_skills(username):
g = Github()
user = g.get_user(username)
tags = defaultdict()
languages = defaultdict(int)
for repo in user.get_repos():
# new_repo_languages = repo.get_languages()
# for lang in new_repo_... | HackRU/teamRU | src/matching/git_skill_finder.py | git_skill_finder.py | py | 593 | python | en | code | 5 | github-code | 6 |
25549629589 | # coding: utf-8
__author__ = "Ciprian-Octavian Truică"
__copyright__ = "Copyright 2020, University Politehnica of Bucharest"
__license__ = "GNU GPL"
__version__ = "0.1"
__email__ = "ciprian.truica@cs.pub.ro"
__status__ = "Production"
from tokenization import Tokenization
from vectorization import Vectorization
from t... | cipriantruica/news_diffusion | news-topic-modeling/main.py | main.py | py | 2,856 | python | en | code | 0 | github-code | 6 |
9591325686 | from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .models import AuthToken
from utils.exceptions import *
def expire_token(user):
try:
for auth_token in user.auth_tokens.all():
auth_token.delete()
except AuthToken... | danghh-1998/django_rest_boilerplate | auth_tokens/services.py | services.py | py | 1,418 | python | en | code | 1 | github-code | 6 |
34993256569 | import requests
from bs4 import BeautifulSoup
def extract_teok_jobs(keyword):
results = []
url = f"https://remoteok.com/remote-{keyword}-jobs"
request = requests.get(url, headers={"User-Agent": "Kimchi"})
if request.status_code == 200:
soup = BeautifulSoup(request.text, "html.parser")
... | hoseel/job-scrapper | extractors/teok.py | teok.py | py | 1,444 | python | en | code | 0 | github-code | 6 |
2725837698 | while True:
n = int(input())
if n == 0:
break
li = {key: True for key in range(1, n+1)}
for i in range(2, n+1):
for j in range(i, n+1, i):
li[j] = not li[j]
liPri = []
for key, value in li.items():
if value is True:
liPri.append(key)
... | wolney-fo/beecrowd | 1-INICIANTE/python/beecrowd_1371.py | beecrowd_1371.py | py | 335 | python | en | code | 1 | github-code | 6 |
74553223546 | import time
from datetime import datetime, timedelta
from num2words import num2words
# Todo: returns an timedelta:
def calculate_time(sleep_time: float) -> timedelta:
"""Function to calculate time to perform it's action,
which is takes a .
Args:
sleep_time (float) : Time that the function will t... | bvmcardoso/pwn | challenge.py | challenge.py | py | 3,411 | python | en | code | 0 | github-code | 6 |
75018787708 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 7 22:05:01 2022
@author: Marcin
"""
import numpy as np
import matplotlib.pyplot as plt
# Sigmoid activation function
def sigmoid(X):
out = 1.0 / (1.0 + np.exp(-X))
return out
# Dervative of sigmoid funcition
def sigmoid_derivative(X):
retu... | MarcinJ7/kNN-implementation | NN.py | NN.py | py | 3,321 | python | en | code | 0 | github-code | 6 |
33875332851 | import torch
from care_nl_ica.independence.hsic import HSIC
class IndependenceChecker(object):
"""
Class for encapsulating independence test-related methods
"""
def __init__(self, hparams) -> None:
super().__init__()
self.hparams = hparams
self.test = HSIC(hparams.num_permut... | rpatrik96/nl-causal-representations | care_nl_ica/independence/indep_check.py | indep_check.py | py | 1,920 | python | en | code | 12 | github-code | 6 |
15821968201 | #!/usr/bin/env python
import rospy
from std_msgs.msg import Bool
import psutil
import argparse
def monitorAvailableMemory(memory_upperlimit_percent):
"""
This function is used to monitor the memory utilization and throw an error
if it exceeds a preset value.
Arguments:
memory_upperlimit_percent... | robotpt/ros-data-capture | src/tools/mem_use_watcher/scripts/watcher.py | watcher.py | py | 1,420 | python | en | code | 0 | github-code | 6 |
7884552964 | #Pull middle two (for even) or middle three (for odd) characters of user input
print("Ready to see the middle characters of your input?")
answer = None
while answer not in ("yes", "no"):
answer = input("Enter yes or no: ")
if answer.lower().strip() == "yes":
midinput = input("Enter an input:")
def middl... | tracygorski/helloworld | middle.py | middle.py | py | 612 | python | en | code | 0 | github-code | 6 |
42072187981 | from tkinter import *
import backend #backend script to read dictionary from
bookf = Tk() #create window
bookf.wm_title("BOOK-STORE")
def get_selected_row(event):
global selected_tuple
if not list1.curselection():
return
... | shivangijain827/python-projects | Book - Store/frontend.py | frontend.py | py | 3,606 | python | en | code | 0 | github-code | 6 |
18843150286 | import pytest
from unittest import mock
from types import SimpleNamespace
from clean.exceptions import FilterDoesNotExist
from clean.request.inout.ports import Response, Request
from clean.request.inout.filter import Page, Sort
from clean.use_case.common import SaveUseCase, RetrieveUseCase, UpdateUseCase, DeleteUseCas... | bahnlink/pyclean | tests/clean/use_case/test_common.py | test_common.py | py | 3,835 | python | en | code | 0 | github-code | 6 |
72532680189 | # pylint:disable=protected-access
# pylint:disable=redefined-outer-name
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import AsyncContextManager
import pytest
from aiopg.sa.engine import Engine
from faker import Faker
from models_library.api_schemas_storage import FileUploadSche... | ITISFoundation/osparc-simcore | services/storage/tests/unit/test_simcore_s3_dsm.py | test_simcore_s3_dsm.py | py | 4,006 | python | en | code | 35 | github-code | 6 |
25867867346 | from SpeechEmotionRecognizer import SpeechEmotionRecognizer
import pandas as pd
import numpy as np
import librosa
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.model_selection import train_test_split
from keras.callbacks import ReduceLROnPlateau
from keras.models import Sequential
from k... | jsalinas98/SpeechEmotionRecognition | SpeechEmotionRecognizer/SER_CNN.py | SER_CNN.py | py | 4,216 | python | en | code | 0 | github-code | 6 |
20342943646 | import numpy as np
import matplotlib.pyplot as mplt
M = 10000
N = 50
s = np.zeros(M)
number_of_cols = 0
for i in range(M):
S_min = 0
S_plus = 0
for j in range(N):
chooser_of_state = np.random.randint(2)
if chooser_of_state == 1:
S_min += 1
else:
S_plus += 1
s_value = (S_plus - S_min)/2.
if s_value n... | tellefs/FYS2160 | Oblig1/oppgm.py | oppgm.py | py | 545 | python | en | code | 0 | github-code | 6 |
1210364326 | with open('input', 'r') as input:
claims = input.read().splitlines() # claim = anspruch
matrix_size = 1000
square = [['.' for x in range(matrix_size)] for y in range(matrix_size)]
def split_values(claim):
claim = claim.replace(' ', '')
cid, coords = claim.split('@')
xy, size =... | slo-ge/Advent-of-Code-2018.py | day3/start.py | start.py | py | 1,503 | python | en | code | 1 | github-code | 6 |
38038218212 | """
References
Machine Learning to Predict Stock Prices:
https://towardsdatascience.com/predicting-stock-prices-using-a-keras-lstm-model-4225457f0233
Twitter Sentiment Analysis using Python
https://www.geeksforgeeks.org/twitter-sentiment-analysis-using-python/
Streamlit 101: An in-depth introduction:
htt... | qvinh-du/finalproject | finalproject.py | finalproject.py | py | 13,804 | python | en | code | 0 | github-code | 6 |
32833821340 | from appium import webdriver
import time
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
desired_caps = {}
desired_caps['plat... | candi-project/Automation_framework_Android | Appiumpython/Gestures/SwipeGesture2.py | SwipeGesture2.py | py | 1,460 | python | en | code | 0 | github-code | 6 |
73944977468 | from difflib import SequenceMatcher
from elasticsearch import Elasticsearch
import string
INDEX = 'video-search'
DOC_TYPE = 'video'
es = Elasticsearch(['elasticsearch:9200'])
def index_video(body):
es.index(index=INDEX, doc_type=DOC_TYPE, body=body)
es.indices.refresh(index=INDEX)
def delete_index():
... | colanconnon/cs410project | cs410videosearchengine/videosearchengine/search.py | search.py | py | 1,263 | python | en | code | 0 | github-code | 6 |
7138653574 | import sys
sys.path.append(".")
from argparse import ArgumentParser
import json
import os
import numpy as np
import torch
from torch.utils.data import Dataset, DistributedSampler, DataLoader, SequentialSampler, RandomSampler
from torch.optim import AdamW
from callback.lr_scheduler import get_linear_schedule_with_warmup... | laohur/PoorBERT | v1/tasks/task.py | task.py | py | 17,353 | python | en | code | 0 | github-code | 6 |
28656442402 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
from sklearn.metrics import mean_squared_error
import models
import helper_functions
import pandas as pd
import os... | jmandivarapu1/SelfNet-Lifelong-Learning-via-Continual-Self-Modeling | Split_MNIST_10x/getMeanNet.py | getMeanNet.py | py | 4,781 | python | en | code | 4 | github-code | 6 |
926305752 | from http import HTTPStatus
from unittest.mock import patch
import pytest
import requests
from rotkehlchen.constants.assets import A_JPY
from rotkehlchen.db.settings import DEFAULT_KRAKEN_ACCOUNT_TYPE, ROTKEHLCHEN_DB_VERSION, DBSettings
from rotkehlchen.exchanges.kraken import KrakenAccountType
from rotkehlchen.tests... | fakecoinbase/rotkislashrotki | rotkehlchen/tests/api/test_settings.py | test_settings.py | py | 17,491 | python | en | code | 0 | github-code | 6 |
74506164668 | from database import crm_db
from typing import List
from models.research import Research, ResearchIn
from bson import ObjectId
from pymongo.errors import DuplicateKeyError
from fastapi import HTTPException
async def read_researches(skip: int = 0, limit: int = 200):
researchs = []
for research in (
aw... | MaximeRCD/cgr_customer_api | services/research.py | research.py | py | 1,988 | python | en | code | 0 | github-code | 6 |
13530136666 | dict_f = {}
user = []
hobby = []
u = input('Путь к файлу user: ')
h = input('Путь к файлу hobby: ')
with open(u, 'r', encoding='utf-8-sig') as u_file:
r_user = u_file.readline()
while r_user:
user_idx = r_user.find(' ')-1
r_u = r_user[0: user_idx]
user.append(r_u)
r_user = u_fil... | ZoooMX/GB_DE | test.py | test.py | py | 1,415 | python | en | code | 0 | github-code | 6 |
36406111862 | import os
from textwrap import dedent
import openai
openai.api_key = os.getenv("OPENAI_KEY", "%%OPENAI_KEY%%")
user_input = input()
ml_prompt = dedent(
"""
You are an artificial intelligence bot named generator with a goal of generating a log format string for a given natural-language description of what a ... | dicegang/dicectf-2023-challenges | misc/mlog/chall/mlog/predict.py | predict.py | py | 1,294 | python | en | code | 61 | github-code | 6 |
5661703741 | """
-----------------------------
Name: Torin Borton-McCallum
Description: Vigenere Cipher
-----------------------------
"""
"""Hope you have a great day my dude"""
import utilities
import Shift_cipher
class Vigenere:
"""
----------------------------------------------------
Cipher name: Vigenere Cipher
... | Torin99/Cryptography-Ciphers | Vigenere/Vigenere.py | Vigenere.py | py | 13,852 | python | en | code | 0 | github-code | 6 |
12774203513 | from bs4 import BeautifulSoup
import requests
response = requests.get("http://stackoverflow.com/questions/")
soup = BeautifulSoup(response.text, "html.parser")
questions = soup.select(".question-summary")
print(questions.get("id", 0))
for question in questions:
print(questions.select_one(".question-hyperlink").ge... | AnantaJoy/Python-for-Geographers-v0.1 | 13-05-2023/Packages/web_crawler/app.py | app.py | py | 396 | python | en | code | 1 | github-code | 6 |
19772157877 | # -*- coding: utf-8 -*-
"""
python -c "import doctest, ibeis; print(doctest.testmod(ibeis.model.hots.hots_nn_index))"
python -m doctest -v ibeis/model/hots/hots_nn_index.py
python -m doctest ibeis/model/hots/hots_nn_index.py
"""
from __future__ import absolute_import, division, print_function
# Standard
from six.moves ... | smenon8/ibeis | _broken/old/hots_nn_index.py | hots_nn_index.py | py | 12,775 | python | en | code | null | github-code | 6 |
6827003628 | '''
$Id: context_processor.py 44 2010-10-11 11:24:33Z goffer.looney@gmail.com $
'''
from django.conf import settings
def _get_vars_as_context():
''' Dump all the settings variables into a dictionary and return it '''
ret = {}
from gvars import __get_vars
vars = __get_vars()
if vars is n... | kingsdigitallab/eel | django/gsettings/context_processor.py | context_processor.py | py | 754 | python | en | code | 0 | github-code | 6 |
26041799986 | from __future__ import annotations
from pants.backend.scala.subsystems.scala import ScalaSubsystem
from pants.backend.scala.util_rules.versions import (
ScalaArtifactsForVersionRequest,
ScalaArtifactsForVersionResult,
)
from pants.core.goals.repl import ReplImplementation, ReplRequest
from pants.core.util_rule... | pantsbuild/pants | src/python/pants/backend/scala/goals/repl.py | repl.py | py | 3,012 | python | en | code | 2,896 | github-code | 6 |
37788268787 | import sigma
from .base import SingleTextQueryBackend
from .exceptions import PartialMatchError, FullMatchError
class QualysBackend(SingleTextQueryBackend):
"""Converts Sigma rule into Qualys saved search. Contributed by SOC Prime. https://socprime.com"""
identifier = "qualys"
active = True
and... | socprime/soc_workflow_app_ce | soc_workflow_ce/server/translation_script/sigma/tools/sigma/backends/qualys.py | qualys.py | py | 3,427 | python | en | code | 91 | github-code | 6 |
70281107068 | import torch
class VQAClassifier(torch.nn.Module):
def __init__(self, hs, vs):
super(VQAClassifier, self).__init__()
# from: https://github.com/dandelin/ViLT
self.vqa_classifier = torch.nn.Sequential(
torch.nn.Linear(hs, hs * 2),
torch.nn.LayerNorm(hs * 2),
... | esteng/ambiguous_vqa | models/allennlp/modules/rsa_vqa/vqa_classifier.py | vqa_classifier.py | py | 476 | python | en | code | 5 | github-code | 6 |
71718729148 | import wx
from . import GUIclasses2 as GUI
from .DataClass2 import PointData
from . import GPS
import numpy as np
from . import MapBase
#Last update/bugfix 11.03,2010 simlk
#Two GUI interfaces wrapping MapBase.py for ML-programs. Simple interface designed for in-field use....
class BasePanel(wx.Panel): #This o... | SDFIdk/nivprogs | MyModules/MLmap.py | MLmap.py | py | 8,768 | python | en | code | 0 | github-code | 6 |
26581236560 | from TrelloApi.TrelloConfig import Trello as tconfig
import requests
import datetime
import json
import re
import os
import threading
import xlsxwriter
class OpenFolderError(Exception):
def __str__(self):
return 'Diretório já exite'
class GeraRelatorio(object):
def __init__(self):
self.Tr... | LeandroGelain/PersonalGit | 2018-2019/Programas executaveis/tkinterApp_arquivosSemExe/TrelloApi/GeraRelatório.py | GeraRelatório.py | py | 10,255 | python | en | code | 0 | github-code | 6 |
25012412373 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
pytorch-dl
Created by raj at 7:48 AM, 7/31/20
"""
import os
import time
import torch
from dataset.iwslt_data import rebatch_source_only
from models.decoding import batched_beam_search
from models.utils.model_utils import load_model_state
from onmt import opts, inputt... | patelrajnath/pytorch-dl | translate.py | translate.py | py | 4,521 | python | en | code | 10 | github-code | 6 |
72067319869 | import numpy as np
import cv2
def compute_perspective_transform(corner_points,width,height,image):
""" Compute the transformation matrix
@ corner_points : 4 corner points selected from the image
@ height, width : size of the image
"""
# Create an array out of the 4 corner points
corner_points_array = n... | basileroth75/covid-social-distancing-detection | src/bird_view_transfo_functions.py | bird_view_transfo_functions.py | py | 1,517 | python | en | code | 123 | github-code | 6 |
24683471152 | class Node:
def __init__(self, name):
self.name = name
self.routing_table = {} # {destination: (next_hop, cost)}
def update_routing_table(self, destination, next_hop, cost):
if destination not in self.routing_table or cost < self.routing_table[destination][1]:
self.routing_... | ShrutikaM25/CNSL | UDP/udp.py | udp.py | py | 2,223 | python | en | code | 0 | github-code | 6 |
75226771708 | #............ Calculates average return for every time interval for every stock and store in the DB
import pymongo
import datetime
import numpy as np
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
historical_col = myclient["core"]["historical_data"]
time_heat_map = myclient["core"]["analytics"][... | prashanth470/trading | source/analysis/time_heat_map.py | time_heat_map.py | py | 4,241 | python | en | code | 0 | github-code | 6 |
19646311537 | ohm = []
while True:
a = int(input())
ohm.append(a)
if a == 0:
break
plus =0
min = 0
if ohm[0]==0:
print("ไม่มีข้อมูล")
else:
for x in range(len(ohm)):
if ohm[x] > 0:
plus+=1
elif ohm[x] <0:
min+=1
print("จำนวนตัวเลขที่มีค่าเป็นบวก",plus)
... | KanapongAiamtip/DIP | Lab Basic Python/P2Q4.py | P2Q4.py | py | 483 | python | th | code | 0 | github-code | 6 |
17702310414 | import os
import shutil
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Construct the path to the download folder
download_folder = os.path.join(os.path.expanduser('~'), 'Downloads')
class FileSorter(FileSystemEventHandler):
def on_created(self,... | phelannathan42/Download-Librarian | DLIBV0.04WATCHDOG.py | DLIBV0.04WATCHDOG.py | py | 1,885 | python | en | code | 0 | github-code | 6 |
70766866107 | from typing import Union, Tuple, List, Sequence
from .base import BasePayload
class FlowPayload(BasePayload):
""" """
def payloads(self) -> Union[Tuple, List]:
return findall_subpayload([self.__args__, self.__kwargs__])
def __make__(self, *args, **kwargs):
raise NotImplementedError
def... | ZSAIm/VideoCrawlerEngine | helper/payload/flow.py | flow.py | py | 1,523 | python | en | code | 420 | github-code | 6 |
24905743163 | import cadquery as cq
import logging
from types import SimpleNamespace as Measures
log = logging.getLogger(__name__)
# A parametric mount for stepper motors shaped as an L-bracket.
class MotorMountL:
def __init__(self, workplane, measures):
"""
A parametric stepper motor mount in the shape of an... | tanius/cadquery-models | motormount/motor_mount_l.py | motor_mount_l.py | py | 4,389 | python | en | code | 11 | github-code | 6 |
15548564668 | import sys
import re
from typing import Dict, Union, List
def get_symb_value(symb: Dict[str, str], context) -> (Union[str, int, bool], str):
"""
Get value and type of symbol.
:param symb: XML argument
:param context: Interpret class
:return: Tuple of value and type
"""
if symb['type'] == ... | lukasvecerka23/ipp-hw | lib/utils.py | utils.py | py | 4,409 | python | en | code | 0 | github-code | 6 |
27407521058 | from livereload import Server, shell
from pathlib import Path
import sys
cur_dir = Path(__file__).parent
server = Server()
if "no" not in sys.argv:
exts = ("rst", "py", "jinja2")
print(f"Watching file changes {exts}")
cmd = shell("make html", cwd=str(cur_dir))
for ext in exts:
# nested or
... | sudojarvis/xonsh | docs/serve_docs.py | serve_docs.py | py | 499 | python | en | code | null | github-code | 6 |
44166444397 | # Yusuf Nadir Cavus
# February 26, 2023
import socket
import threading
PORT = 8080 # assumed port number
HOST = 'localhost' # assumed host
HTML_FILE = "index.html" # assumed http file/webpage
IMAGE_FILE = "image.jpg" # assumed image file
BUF_SIZE = 1024 # max size for the request
# func: requestHandler
# parameters... | ysfndr/Multi-thred-Web-Server | webServer.py | webServer.py | py | 4,527 | python | en | code | 0 | github-code | 6 |
71077185467 | import Gmail_API_Lib
import Track_API_Lib
import Slack_API_Lib
import importlib
import json
import csv
import lovely_logger as log
import datetime
import time
late_checkin_alert_hour = 21
unclean_property_alert_hour = 14
regular_check_interval_minutes = 15
check_checkin_interval_minutes = 15
reload = 1#dummy variable ... | mammalwithashell/scott-heyman-gcp-functions | Daily_Checks_v1.0.py | Daily_Checks_v1.0.py | py | 7,843 | python | en | code | 0 | github-code | 6 |
35032853414 | import pdb
from models.merchant import Merchant
from models.transaction import Transaction
from models.user import User
from models.category import Category
import repositories.merchant_repository as merchant_repository
import repositories.transaction_repository as transaction_repository
import repositories.user_repo... | linseycurrie/Spending-Tracker | spending_tracker/console.py | console.py | py | 1,447 | python | en | code | 2 | github-code | 6 |
40892321700 | import os
import discord
import re
import asyncio
from keepAlive import KeepAlive
from spotifySelfAPI import SpotifyAuthAccessToken, SpotifySearch, SpotifyPlaylistCreate, SpotifyPlaylistAdd
from replaceBadKeywords import ReplaceBadKeywords
from collections import OrderedDict
from youtubeSelfAPI import YoutubePlaylistCr... | sarvagya6/discord-playlist-bot | main.py | main.py | py | 7,019 | python | en | code | 1 | github-code | 6 |
72462557307 | from ex1 import Person
class Student(Person):
def __init__(self, name, height, age, clas, group, surname):
super().__init__(name,height,age,surname)
self.clas = clas
if isinstance(age, int) and isinstance(height, int):
self.group = group
else:
TypeError(f'{t... | jurbx/python_pro | day2/ex2.py | ex2.py | py | 547 | 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.