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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
19111891287 | from numpy import prod
def rad(n):
factors = set()
d = 2
step = 1
while d * d <= n:
while n > 1:
while n % d == 0:
factors.add(d)
n = n / d
d += step
step = 2
return prod(list(factors))
dico = {}
f... | micycle1/Project-Euler | euler 124.py | euler 124.py | py | 430 | python | en | code | 0 | github-code | 36 |
27519529329 | import urllib
import urllib.request
from bs4 import BeautifulSoup
import os
def table(url):
thepage=urllib.request.urlopen(url)
soup=BeautifulSoup(thepage,"html.parser")
return soup
# soup=table("https://www.marmiton.org/recettes/")
# page1=soup.findAll('h4',{'class':'recipe-card__title'})
# tab=[]
# fo... | mousaa32/web-scrapping | marmiton.py | marmiton.py | py | 1,671 | python | fr | code | 0 | github-code | 36 |
37229458402 | from django.conf import settings
from django.contrib import admin
from django.urls import path, include
from . import views
from django.conf.urls.static import static
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from filebrowser.sites import site
... | awsomkiller/onlineTutorial | onlineTutorial/urls.py | urls.py | py | 1,649 | python | en | code | 0 | github-code | 36 |
37797255435 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Recibe 2 valores enteros.
Retorna el cociente de los 2 elementos.
'''
def cociente(numerador,denominador):
if type(numerador) == int and type(denominador) == int:
if denominador != 0:
return numerador/denominador
else:
ret... | ispc-programador2022/a6g3-a6g3 | bloque1/f_cociente.py | f_cociente.py | py | 428 | python | es | code | 1 | github-code | 36 |
28247362628 | import os
from subprocess import Popen, CREATE_NEW_CONSOLE
p_list = [] # Список клиентских процессов
while True:
user = input('Запустить клиентов (s) / Закрыть клиентов (x) / Выйти (q) ')
if user == 'q':
break
elif user == 's':
cnt = int(input('Количество клиентов: '))
for k in ra... | SandalAndrey/GB_Messenger | many_lients.py | many_lients.py | py | 772 | python | ru | code | 0 | github-code | 36 |
73313411625 | # -*- coding: utf-8 -*-
# @Time : 2022 09
# @Author : yicao
import csv
import os
import math
import numpy as np
import torch
from utils import model_utils
class TopKUtil:
def __init__(self, mod_len: int, sparse_rate: float = 0.05, record_top_k_value=False,
record_top_k_value_csv_name=None, ... | zhengLabs/FedLSC | utils/top_k_utils.py | top_k_utils.py | py | 7,698 | python | en | code | 1 | github-code | 36 |
23622351546 | #!/usr/bin/env python3
""" module """
import numpy as np
def specificity(confusion):
"""calculates the precision for each class in a confusion matrix:
Args:
confusion (numpy.ndarray of shape (classes, classes)):
[row indices represent the correct labels
and co... | vandeldiegoc/holbertonschool-machine_learning | supervised_learning/0x04-error_analysis/3-specificity.py | 3-specificity.py | py | 571 | python | en | code | 0 | github-code | 36 |
20940467211 | import torch
import torch.nn as nn
from collections import OrderedDict
class OrientedRPN(nn.Module):
def __init__(self, cfg: dict = {}):
super().__init__()
self.fpn_level_num = cfg.get("fpn_level_num", 5)
self.fpn_channels = cfg.get("fpn_channels", 256)
self.num_anchors = cfg.get("n... | Simon128/pytorch-ml-models | models/oriented_rcnn/oriented_rpn/oriented_rpn.py | oriented_rpn.py | py | 1,346 | python | en | code | 0 | github-code | 36 |
7381312453 | import sys
from pybench import Test
def main():
# CSF - Use gmpy2's divmod instead of the Python built-in, it's slightly faster
N = int(1000)
# CSF - Used by bprint below to save a few usec off each print
line = '{:010d}\t:{}\n'.format
# CSF - Not very PEP friendly, but the runtime on this benchmark is lo... | abhijangda/DacapoInputSets | benchmarks/bms/jython/Pidigits.py | Pidigits.py | py | 1,154 | python | en | code | 0 | github-code | 36 |
7813321006 | import json
from typing import List
import click
import requests
import sqlalchemy as sa
from aspen.config.config import Config
from aspen.database.connection import (
get_db_uri,
init_db,
session_scope,
SqlAlchemyInterface,
)
from aspen.database.models import Pathogen, PathogenLineage
from aspen.util... | chanzuckerberg/czgenepi | src/backend/aspen/workflows/import_lineages/load_lineages.py | load_lineages.py | py | 5,861 | python | en | code | 11 | github-code | 36 |
19271830686 | import uuid
from flask import request
from flask.views import MethodView
from flask_smorest import abort, Blueprint
from resources.db import *
from schemas import StoreSchema
from models import StoreModel
from resources.db import db
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
blb = Blueprint("stores", _... | ahmad22us/rest-apis-project | resources/store.py | store.py | py | 2,426 | python | en | code | 0 | github-code | 36 |
2405850792 | import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
class FixedRandomPermutation(nn.Module):
"""Layer with random but fixed permutations in order to mix the data"""
def __init__(self, input_dim, seed):
super(FixedRandomPermutation, self)... | thomasbbrunner/tum-adlr-ws20-06 | src/models/INN.py | INN.py | py | 7,218 | python | en | code | 0 | github-code | 36 |
6185548371 | def rabin_karp(text, pattern):
text_len = len(text)
pattern_len = len(pattern)
prime = 101 # A prime number for hashing
base = 256 # Number of possible characters
pattern_hash = 0
text_hash = 0
h = 1 # Calculate h as (base^(pattern_len-1)) % prime
for i in range(pattern_len - 1):
... | qlyde/algorithms | python/rabin-karp-algorithm.py | rabin-karp-algorithm.py | py | 1,252 | python | en | code | 0 | github-code | 36 |
400235146 | from binarytree import BinarySearchTree, BinaryTreeNode
from queue import Queue
'''Given a BST, reverse the order of its values by modifying the nodes' links'''
def reverse_tree(tree, node=None):
'''reverse the nodes of a binary tree'''
if node is None:
node = tree.root
node.left, node.right = node... | ckim42/spd-problems | six.py | six.py | py | 1,670 | python | en | code | 0 | github-code | 36 |
10744162091 | import numpy as np
from pydub import AudioSegment
import librosa
def get_segment(audio, start, end):
return audio[int(start * 1000): int(end * 1000)]
def to_librosa(audiosegment):
channel_sounds = audiosegment.split_to_mono()
samples = [s.get_array_of_samples() for s in channel_sounds]
fp_arr = np.... | SergWh/datasets_processing | model/model.py | model.py | py | 1,776 | python | en | code | 0 | github-code | 36 |
2808409231 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__version__ = "0.3.0"
__author__ = "Abien Fred Agarap"
import argparse
from utils.data import plot_confusion_matrix
def parse_args():
parser = argparse.ArgumentParser(
description="Confusion Matr... | AFAgarap/gru-svm | utils/results_summary.py | results_summary.py | py | 2,156 | python | en | code | 136 | github-code | 36 |
31414845762 | from lib2to3.pytree import Node
from pythonds import Stack
obj = Stack() # Creating object of stack class
class Prime:
prime = {}
prime_anagram = [] # Creating prime_anagram list
prime_list = prime.prime(0, 1000) # Creating list of prime number in given range
for num in prime_list: # Checking ... | AkashBG3010/PythonPracticePrograms | DataStructuresPrograms/prime_stack.py | prime_stack.py | py | 977 | python | en | code | 0 | github-code | 36 |
5501295664 | import os
import smtplib
import getpass
import sys
import time
from colorama import init, Style, Back, Fore
print ("""
__ ___ _ __ ____ ____
/ |/ /___ _(_) / / __ )____ ____ ___ / __ )
/ /|_/ / __ `/ / / / __ / __ \/ __ `__ \/ __ |
/ / / / /_/ / / /___/ /_/ / /_/ / / / /... | SuhailHasan/MaiLBomB | MaiLBomB.py | MaiLBomB.py | py | 2,288 | python | en | code | 0 | github-code | 36 |
11091204534 | """
7. Write a python program to create a Laptop class with 4 attributes (brand, ram, cpu,
hdd) and 2 methods (showConfig() to print the values, __init__() to initialize the
values).
"""
class Laptop:
def __init__(self,brand="HP",ram="46",cpu="i7",hdd="2TB"):
self.brand=brand
... | subhogithub1234/Assignment-24 | ANS 7.py | ANS 7.py | py | 658 | python | en | code | 0 | github-code | 36 |
24888176707 | from ctypes import c_uint8, c_uint32
i = 0
intermediate_array = bytearray()
final_array = bytearray()
with open("db.temp", "rb") as obf, open("asta-decrypted.exe", "wb") as out:
encrypted_array = bytearray(obf.read())
while i < len(encrypted_array):
intermediate_array.append(encrypted_array... | dodo-sec/asta-decrypt.py | asta-decrypt.py | asta-decrypt.py | py | 587 | python | en | code | 5 | github-code | 36 |
2946435815 |
cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']
}
def get_al... | joshsisto/100_days_of_code | code/07-09-data-structures/day8_official.py | day8_official.py | py | 1,553 | python | en | code | 1 | github-code | 36 |
14878275140 | import argparse
import csv
import itertools
import os
import subprocess
import sys
import tempfile
from typing import Any, Callable, Dict, Generic, Iterable, List, NamedTuple, TextIO, Tuple, TypeVar, Optional, Union
# The following command line options participate in the combinatorial generation.
# All other arguments... | AndroidBBQ/android10 | frameworks/base/startop/scripts/app_startup/app_startup_runner.py | app_startup_runner.py | py | 12,868 | python | en | code | 176 | github-code | 36 |
35815327993 | from collections import defaultdict
from random import randint
import numpy as np
class GridWorldEnv():
def __init__(self,
height,
width,
forbidden_grids,
target_grids,
target_reward = 1,
forbidden_reward = -1,
... | zhilu1/rl_practice | rl_envs/grid_world_env.py | grid_world_env.py | py | 4,674 | python | en | code | 0 | github-code | 36 |
16763424610 | import sys
Taxonomy = {}
for line in open(sys.argv[1] + '/Consortium_aligned_seqs.m8','r'):
timber = line.split('\t')
Taxonomy[timber[0]] = timber[1] + '\n'
mapping_names = {}
for line in open(sys.argv[1] + '/Naming_RSVs.csv','r'):
timber = line.replace('\n','').split(',')
mapping_names[tim... | thh32/consort | Bin/Taxonomy_assigner.py | Taxonomy_assigner.py | py | 886 | python | en | code | 0 | github-code | 36 |
8658621293 | def html_parser(html):
if "<" not in html:
return html
list = html.split("<")
if list[0] == '':
list = list[1:]
rem = []
for x in list:
if (x[-1] == ">"):
rem.append(x)
for x in rem:
for y in list:
if y == x:
list.remove(y)
... | chimtrangbu/hyperspace | trainingday02/html_parser/html_parser.py | html_parser.py | py | 547 | python | en | code | 0 | github-code | 36 |
74032141222 | """
Extract loss plots from log file
"""
import matplotlib.pyplot as plt
import numpy as np
import Config
def main():
train_loss_l = np.empty((0, 5))
train_class_l = np.empty((0, 3))
train_metric_l = np.empty((0, 3))
valid_loss_l = np.empty((0, 5))
valid_class_l = np.empty((0, 3))
valid_metr... | Tianananana/Angio-Stenosis-Detection | LossPlot.py | LossPlot.py | py | 7,644 | python | en | code | 5 | github-code | 36 |
29197648237 | import re
from . import Target, Entity
from geotext import GeoText
from spacy.lang.en.stop_words import STOP_WORDS
class LocationParser(Target):
def __init__(self):
super().__init__()
self.stop_words = STOP_WORDS
self.stop_words.add("university")
self.stop_words.add("central")
... | kherud/native-language-identification | pipeline/pipes/geolocation.py | geolocation.py | py | 1,801 | python | en | code | 1 | github-code | 36 |
264247579 | """
https://portswigger.net/web-security/csrf/lab-referer-validation-broken
"""
import sys
import requests
from bs4 import BeautifulSoup
site = sys.argv[1]
if 'https://' in site:
site = site.rstrip('/').lstrip('https://')
s = requests.Session()
login_url = f'https://{site}/login'
resp = s.get(login_url)
soup = ... | brandonaltermatt/penetration-testing-scripts | csrf/referer-validation-broken.py | referer-validation-broken.py | py | 1,002 | python | en | code | 0 | github-code | 36 |
26771413491 | #!/usr/bin/python3
""" Unittest for the Rectangle class.
To ensure Rectangle is working as intended """
import unittest
import json
from models import base
from models.base import Base
from models.rectangle import Rectangle
class RectangleTesting(unittest.TestCase):
""" Test cases for the Rectangle class """
... | Alouie412/holbertonschool-higher_level_programming | 0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py | test_rectangle.py | py | 2,176 | python | en | code | 0 | github-code | 36 |
42046912149 | import gdal2tiles
from osgeo import gdal
# -b это слой, который берем, порядок слоев 1, 2, 3 так как sample.tif в формате rgb.
def sliceToTiles(
geotiffName,
geotiffBytes,
slicesOutputPath,
optionsTranslate=['-if GTiff', '-ot Byte', '-b 1', '-b 2', '-b 3', '-of vrt', '-scale'],
... | moevm/nosql2h23-ecology | worker/app/image_processing/geotiff_slicer/slice2tiles.py | slice2tiles.py | py | 1,282 | python | en | code | 4 | github-code | 36 |
74588530663 | # coding=utf-8
"""
Encore REST services
REST Documentation : https://www.encodeproject.org/help/rest-api/
# ### Encode REST TEST
# BioREST import Encode
# encode = Encode()
# response = encode.biosample('ENCBS000AAA')
# encode.show_response(response)
"""
__author__ = "Arnaud KOPP"
__copyright__ = "© ... | ArnaudKOPP/BioREST | BioREST/Encode.py | Encode.py | py | 3,029 | python | en | code | 0 | github-code | 36 |
42374317266 |
class TaskManager:
__tasks = []
def __init__(self, tasks: list):
self.__tasks = tasks
def manage_tasks(self, max_thread_count: int) -> list:
threads_task_list = []
for i in range(max_thread_count):
threads_task_list.append([])
tasks_iterator = iter(self.__ta... | alekseyderyugin/avtotochki_grabing | src/TaskManager.py | TaskManager.py | py | 840 | python | en | code | 0 | github-code | 36 |
30843941779 | import SimpleITK as sitk
import numpy as np
#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
import os
import matplotlib.pyplot as plt
from PIL import Image
import pandas as pd
import sys
'''python import模块时, 是在sys.path里按顺序查找的。
sys.path是一个列表,里面以字符串的形式存储了许多路径。
使用A.py文件中的函数需要先将他的文件路径放到sys.path中
'''
sys.path.append('..//'... | JiabinTan/LUNA16 | data_proc/reader_disp.py | reader_disp.py | py | 4,833 | python | zh | code | 0 | github-code | 36 |
4107574477 | num = int(input())
partner_one = input()
partner_two = input()
partners = []
one_split = partner_one.split()
two_split = partner_two.split()
if num % 2 == 1:
print('bad')
else:
for i in range(0, num):
x = [one_split[i], two_split[i]]
partners.append(x)
q = 0
while q < num:
if p... | AAZZAZRON/DMOJ-Solutions | ccc14s2.py | ccc14s2.py | py | 645 | python | en | code | 1 | github-code | 36 |
41538262741 | import random
import string
from django.db import transaction
from django.db.models import Q
from django.shortcuts import render,redirect
from django.core.mail import send_mail
from django.http import HttpResponse, response
from django_redis import get_redis_connection
from redis import Redis
from user.captcha.image ... | pengbin0205/git_one | user/views.py | views.py | py | 5,801 | python | en | code | 0 | github-code | 36 |
22630594275 | # insert check
# db에 입력할 것인지 안할 것인지 확인
# module
import sys
import json
from modules import Insert_data
def func(items):
franchise_list = []
# get franchise list from ./franchise_list.json
with open('franchise_list.json') as json_file:
franchise_list = json.load(json_file)
ans = ""
for i i... | unChae/store_list | dist/modules/Insert_check.py | Insert_check.py | py | 939 | python | en | code | 0 | github-code | 36 |
29007233825 | from encodings import search_function
from selenium import webdriver
import os
from selenium.webdriver.common.keys import Keys
class Home2(webdriver.Edge):
def __init__(self,driver_path=r"C:/Users/vaish/Desktop/Self Learning/Cloud/DEVOPS/SELENIUM",teardown=False):
self.teardown=teardown
self.driv... | Donuts252001/Netmeds | ENTERING_VALUES/home2.py | home2.py | py | 929 | python | en | code | 0 | github-code | 36 |
14076719765 | # https://www.hackerrank.com/challenges/staircase/problem
# Create staircase with number
def staircase(number):
# range precisa começar em 1
for i in range(1, number + 1):
print(' ' * (number - i) + '#' * i)
if __name__ == '__main__':
n = int(input().strip())
staircase(n)
| lucasmassarico/HackerRank | Warmup/staircase.py | staircase.py | py | 300 | python | en | code | 0 | github-code | 36 |
13991562528 | import sys
class StripePainter:
def colorSplit(self, stripes, start, end, color):
i, j = None, None
for k in xrange(start, end+1):
if stripes[k] == color:
if i is not None and j is not None:
yield i, j
i, j = None, None
els... | dariomx/topcoder-srm | old-stuff/topcoder-srm/150/500/Solution.py | Solution.py | py | 1,821 | python | en | code | 0 | github-code | 36 |
35923573594 | import numpy as np
def calculate(list):
try:
calc = np.array(list).reshape(3,3)
except ValueError:
raise ValueError("List must contain nine numbers.")
calculation = {
'mean': None,
'variance': None,
'standard deviation': None,
'max': None,
'min'... | UnclearCoder/data-python-1 | mean_var_std.py | mean_var_std.py | py | 1,670 | python | en | code | null | github-code | 36 |
22744494191 | from queue import Queue
# memeriksa apakah penempatan Queen berada di kolom atau baris yang tepat atau tidak
def is_valid(board, row, col):
# memeriksa apakah ada queen yang terletak di kolom yg sama
for i in range(row):
if board[i] == col:
return False
# periksa diagonal ... | KB-F-2023/kelompok-keluarga-berencana | Tugas 1/nqueensdfs.py | nqueensdfs.py | py | 1,908 | python | id | code | 0 | github-code | 36 |
70606557225 | # 使用AKSHARE + mysql 实现动态抓取个股的交易历史数据
# 同理外面再包一层循环就可以把所有的交易历史数据下载每个股票一个表。
# 后续下载历史数据并且定制下每天更新脚本这样历史交易数据就解决了。
#
# 后续就是弄个回测框架
#
# 添加宏观因素 再添加个股微观因素 再历史回测因素相关性
import time
from datetime import datetime
import pandas as pd
import warnings
from sqlalchemy import create_engine
import akshare as ak
warnings.filterwarnings("ig... | cgyPension/pythonstudy_space | 04_learn_quantitative/akshare采集/source.py | source.py | py | 4,440 | python | zh | code | 7 | github-code | 36 |
23004560864 | import sys
activate_this = '~/flask_app/flask/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
if sys.version_info[0]<3: # require python3
raise Exception("Python3 required! Current (wrong) version: '%s'" % sys.version_info)
sys.path.insert(0, '~/fl... | HarshitaSingh97/FetchGoogleTrends | app.wsgi | app.wsgi | wsgi | 367 | python | en | code | 2 | github-code | 36 |
6752261336 | # -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QDialog, QTreeWidgetItem
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from product.controllers.productcontroller import ProductController
from labrecord.controllers.labrecordscontroller import LabrecordsController
from verification.views.selectrecords import Ui_Dia... | zxcvbnmz0x/gmpsystem | verification/modules/selectrecordsmodule.py | selectrecordsmodule.py | py | 2,672 | python | en | code | 0 | github-code | 36 |
72424386023 | import json
# Path to your file
file_path = 'conv_sample'
def extract_text_from_data(data):
try:
post_list = data.get('post_list', [])
if post_list:
first_post = post_list[0]
return first_post.get('text', 'Text not found')
else:
return 'No posts in the l... | charlieaccurso/charlie_research | Emoji/extract_text.py | extract_text.py | py | 1,179 | python | en | code | 0 | github-code | 36 |
40097697635 | import base64
import sys
import os
import datetime
import json
import requests
import scrapy
import urllib.parse
from utils import *
def findphone(name):
print(f'searching {name}')
qname=urllib.parse.quote_plus(name)
response=requests.get(f'https://www.google.com/search?hl=fr&ie=UTF-8&oe=UTF-8&q={qname}+t%C3%A9... | acrowther/findphone | main.py | main.py | py | 866 | python | en | code | 0 | github-code | 36 |
13122695 | #import data (Tkinter)
from Tkinter import *
#main
Alpha = Tk()
#gui configration (weith, hight, title, enz)
app = Frame(Alpha)
app.grid()
Alpha.title("wordlist line gen. non selective ")
Alpha.geometry("320x260")
#firts label
label1 = Label(Alpha, text="minimal lengt passwords")
label1.grid(row = 0, column =0)
#in... | anon12345654321/linuxeasy | crunch.py | crunch.py | py | 2,225 | python | en | code | 0 | github-code | 36 |
74287838504 | import gc
import board
import busio
import digitalio
import time
from adafruit_wiznet5k.adafruit_wiznet5k import *
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
import neopixel
class OKError(Exception):
"""The exception thrown when we didn't get acknowledgement to an AT command"""
SPI1_SCK = board.... | bjnhur/pico-W5500 | Pico_W5K_W5K_WizFi360_echo.py | Pico_W5K_W5K_WizFi360_echo.py | py | 11,075 | python | en | code | 15 | github-code | 36 |
75174338985 | import cv2, sys
import numpy as np
def main():
if len(sys.argv) < 2:
print("usage: python edgedetector.py <imagename>")
exit()
# read in the image as color and greyscale
color = cv2.imread(sys.argv[1],1)
# remove noise
color = cv2.GaussianBlur(color,(3,3),0)
cv2.imwrite("contour... | squeakus/bitsandbytes | opencv/sobel.py | sobel.py | py | 1,368 | python | en | code | 2 | github-code | 36 |
23514748787 | import numpy as np
class ZDT2:
def __init__(self):
self.n_var = 2 # number of variables
self.n_obj = 2 # number of objective functions
self.n_constr = 0 # number of constraint functions
self.xl = np.ar... | kentoakiyama/NSGA2 | test_functions/zdt.py | zdt.py | py | 1,613 | python | en | code | 0 | github-code | 36 |
72498764903 | n = int(input('Enter the number of athlets: '))
m = int(input('Enter the number of throws: '))
arr = []
for i in range(n):# игроки
arr_ath = []
print("athlete", i)
for j in range(m):# броски
x = int(input("throw="))
arr_ath.append(x)
arr.append(arr_ath)
print(arr)
for i in range(n):#row... | astreltsov/firstproject | Tuples_and_2d_arrays/Competition.py | Competition.py | py | 775 | python | en | code | 0 | github-code | 36 |
16825022923 | import collections
import numpy as np
import pandas as pd
import nltk, string
from nltk import word_tokenize # Convert paragraph in tokens
from sklearn.feature_extraction.text import TfidfVectorizer
nltk.download('punkt')
text_data = pd.read_csv("Text_Similarity_Dataset.csv")
stemmer = nltk.stem.porter.PorterStemm... | centipede13/Text_Similarity | STS_Pred.py | STS_Pred.py | py | 1,235 | python | en | code | 0 | github-code | 36 |
6994689610 | from lib.cuckoo.common.abstracts import Signature
class InjectionRunPE(Signature):
"""Works much like InjectionThread from injection_thread.py - so please
read its comment there to find out about the internal workings of this
signature."""
name = "injection_runpe"
description = "Executed a process... | cuckoosandbox/community | modules/signatures/windows/injection_runpe.py | injection_runpe.py | py | 1,453 | python | en | code | 312 | github-code | 36 |
23413091064 | # -*- coding: utf-8 -*-
"""
A auto compressed disk cache backed requests maker.
"""
import typing
import requests
from diskcache import Cache
from .decode import decoder
class CachedRequest(object):
"""
Implement a disk cache backed html puller, primarily using ``requests`` library.
Usage:
.... | MacHu-GWU/crawlib-project | crawlib/cached_request.py | cached_request.py | py | 5,737 | python | en | code | 1 | github-code | 36 |
13989593352 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtWidgets import QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn... | shellever/Python3Learning | thirdparty/pyqt5/signals/event-sender.py | event-sender.py | py | 952 | python | en | code | 0 | github-code | 36 |
980796399 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
import sys
import os
sys.path.append("/Users/forute/Documents/Academy/Resaech/Clustering_Worker")
import experiment_syn.worker_num.create_worker_labeling_number_dataset as csd
import not_public.model.Dawid... | HideakiImamura/MinimaxErrorRate | experiment1/main.py | main.py | py | 4,253 | python | en | code | 5 | github-code | 36 |
27766460728 |
import pygame
from pygame.locals import *
from utils import *
os.path.dirname(__file__)
class Mouse(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.load_sprite()
def load_sprite(self):
self.sheet, self.sheet_rect = load_image('CURSORS_SHEET_1.png')
self.frames = []
wi... | aladdin83/airport_control | lib/mouse.py | mouse.py | py | 775 | python | en | code | 1 | github-code | 36 |
36121866883 | import unittest
from forte.data.span import Span
class SpanTest(unittest.TestCase):
def test_span(self):
span1 = Span(1, 2)
span2 = Span(1, 2)
self.assertEqual(span1, span2)
span1 = Span(1, 2)
span2 = Span(1, 3)
self.assertLess(span1, span2)
span1 = Span(... | asyml/forte | tests/forte/data/span_test.py | span_test.py | py | 440 | python | en | code | 230 | github-code | 36 |
15333463493 | from number_theory_functions import modular_exponent
BASE = 456456
E_BASE = 7896543
E_EXP = 74365753
# Hundreds digit of BASE**(E_BASE**E_EXP)
n = 1000
phi_n = 400
r = modular_exponent(E_BASE, E_EXP, phi_n)
x = modular_exponent(BASE, r, n)
print(f"({E_BASE}**{E_EXP}) % {phi_n} = {r}"
f"\n=> {BASE}**({E_BASE}*... | 1d4n/RSA | Riddles/q2.py | q2.py | py | 427 | python | en | code | 0 | github-code | 36 |
19544623520 | # pyCharm and pyQT5 require significant setup
# https://pythonpyqt.com/how-to-install-pyqt5-in-pycharm/
# install pyqt5. pyqt5-sip, pyqt5-tools for use with pycharm
# PyCharm select File | Settings | Tools | PyCharm. External Tools, click + New Tools, Create QTdesigner and PyUIC tools
from PyQt5 import QtGui, QtC... | Richard-Kershner/Audio-Video-Screen-TimeStamp-Recorder | main.py | main.py | py | 4,362 | python | en | code | 0 | github-code | 36 |
6752686356 | # -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from stuff.controllers.stuffcontroller import StuffController
from product.controllers.productcontroller import ProductController
from workshop.views.productioninstruction import Ui_Form
import datetime
class PorductionInstructionModule(Q... | zxcvbnmz0x/gmpsystem | workshop/modules/productioninstructionmodule.py | productioninstructionmodule.py | py | 3,775 | python | en | code | 0 | github-code | 36 |
7255390861 | #%%
from functions.formatting import *
from functions.base import *
#%%
aspect = 17.5
width = 50
output_dir = current_dir / 'figures'
output_dir.mkdir(parents=True, exist_ok=True)
current_dir = Path().resolve()
fig, ax = pplt.subplots(width=width/25.4, aspect=aspect)
ticks = np.linspace(10, 40, endpoint=True, num=4... | Jhsmit/PyHDX-paper | biorxiv_v2/fig_x_colorbars.py | fig_x_colorbars.py | py | 1,001 | python | en | code | 0 | github-code | 36 |
74548146983 | def factorial_bucle(numero):
'''
Esta funcion calcula el factorial de un numero entero introducido por el usuario
Parametros:
-numero: numero introducido por el usuario
Salidas:
-factorial: devuelve el factorial del numero
'''
factorial = 1
for n in range(1, numero+1):
fact... | lgarciarob/practica0206_jin_garcia | Ejercicio2.py | Ejercicio2.py | py | 944 | python | es | code | 0 | github-code | 36 |
16609451607 | from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from dat... | kronolith1/ps5-bot | src/selenium_driver.py | selenium_driver.py | py | 2,797 | python | en | code | 2 | github-code | 36 |
72021503465 | from django.urls import path
from .views import loginPage, loginWithFlutter, logout, logoutFlutter, signupPage, signupWithFlutter
urlpatterns = [
path('signup/', signupPage, name='signup'),
path('login/', loginPage, name='login'),
path('logout/', logout, name='logout'),
path('loginflutter/', loginWithF... | chrisbagas/C08 | login_form/urls.py | urls.py | py | 488 | python | en | code | 1 | github-code | 36 |
211978352 | """Contains models to use for prediction and classification."""
import pandas as pd
import joblib
from pandas import DataFrame
from sklearn.feature_selection import RFECV
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from visualise im... | MikeyJL/fetal-health | src/model.py | model.py | py | 2,762 | python | en | code | 0 | github-code | 36 |
74612446505 | import socket
import threading
# ip = socket.gethostbyname(socket.gethostname())
#创建socket对象
#SOCK_DGRAM udp模式
udpServer = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udpServer.bind(("192.168.31.144", 8001)) #绑定服务器的ip和端口
print("udp服务器启动成功!")
local = threading.local()
def func(data, addr):
local.data = ... | hanyb-sudo/hanyb | 网络编程(socket通信)/UDP编程/2、客户端与服务端数据交互/server.py | server.py | py | 950 | python | en | code | 0 | github-code | 36 |
23078124291 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, copy
from spa.clientside import CSocketPool, CConnectionContext, CSqlite
class MyStruct(object):
def __init__(self):
self.reset()
def reset(self):
self.dmax = 0.0
self.dmin = 0.0
self.davg = 0.0
self.returned = ... | udaparts/socketpro | samples/auto_recovery/test_python/test_python.py | test_python.py | py | 2,569 | python | en | code | 27 | github-code | 36 |
25459718320 | from __future__ import absolute_import, division, print_function
import numpy as np
np.random.seed(1337) # for reproducibility
np.set_printoptions(threshold=np.nan)
import tensorflow as tf
tf.enable_eager_execution()
import os
import matplotlib.pyplot as plt
import pickle
import networkx as nx
import SegEval as ev
fr... | remrace/qnguyen5-thesis-tamucc | src/bin/test.py | test.py | py | 11,127 | python | en | code | 0 | github-code | 36 |
12867831014 | ############################################################
# Author: Aravind Potluri <aravindswami135@gmail.com>
# Description: A simple python based video streaming app.
############################################################
# Libraries
import cv2
import socket
import pickle
import struct
# Set up the... | name-is-cipher/pyVidStream | vidPlay.py | vidPlay.py | py | 1,439 | python | en | code | 0 | github-code | 36 |
2497192439 | from sentinela.core.base_monitor import BaseMonitor
class NewLogEntries(BaseMonitor):
def __init__(self, logfile, max_wait):
super(NewLogEntries, self).__init__()
self._log_lines = None
# User configured
self._log_file = logfile
self._max_wait = max_wait
... | andresriancho/sentinela | sentinela/modules/monitors/new_log_entries.py | new_log_entries.py | py | 1,648 | python | en | code | 8 | github-code | 36 |
40082631108 | # import packages / libraries
import torch
from torchvision.models import resnet
class MNIST_classifier(torch.nn.Module):
""" implements a simple ConvNet for classifying MNIST images """
def __init__(self, seed):
""" initializes two Conv-Layers followed by two linear layers """
super().__... | michaelhodel/adversarial-training-with-lots | models.py | models.py | py | 3,745 | python | en | code | 0 | github-code | 36 |
28110285607 | import pickle
import sys
f2 = open(sys.argv[2],'r')
var = f2.readlines()
var = [x.strip() for x in var]
with open(sys.argv[1], 'rb') as handle:
dict_out = pickle.load(handle)
warningsVar = []
for item in var:
if item not in dict_out.keys():
warningsVar.append(item)
f3 = open(sys.argv[4],'w')
for ite... | mintproject/MINT-WorkflowDomain | WINGSWorkflowComponents/GeneralDataPreparation/deprecated/netCDF_simple/code/library/selectVar/selectVar.py | selectVar.py | py | 496 | python | en | code | 0 | github-code | 36 |
41158512589 | #!/usr/bin/env python3
coupon_codes = {
"Monday": 4465,
"Tuesday": 7676,
"Wednesday": 1067,
"Thursday": 7655,
"Friday": 7678,
"Saturday": 4333,
"Sunday": 6578
}
i = input("Day for the coupon code:")
if i not in coupon_codes.keys():
print("Sorry no such day exists!")
else:
print(f"Cou... | The-Debarghya/Sem4-Assignments | Python/q2.py | q2.py | py | 358 | python | en | code | 1 | github-code | 36 |
72721110183 | from utilities import util
import binascii
# Challenge 53
STATE_LEN = 4 # 32 bits
BLOCK_SIZE = 16 # 128 bits
LEN_ENC_SIZE = 8 # 64 bits
initial_state = b''.join([util.int_to_bytes((37*i + 42) % 256) for i in range(STATE_LEN)])
# Notes
# - Modern hash functions include the length of the message (modulo some huge
# ... | fortenforge/cryptopals | challenges/expandable_messages.py | expandable_messages.py | py | 6,225 | python | en | code | 13 | github-code | 36 |
42819977798 | #class attributes
#Class attributes belong to the class itself they will be shared by all the instances.
class sampleclass:
count = 0
def increase(self):
sampleclass.count += 1
s1 = sampleclass()
s1.increase()
print(s1.count)
s2 = sampleclass()
s2.increase()
print(s2.count)
pri... | DeveshDutt2710/pythonConcepts | classAndInstanceAttributes.py | classAndInstanceAttributes.py | py | 1,322 | python | en | code | 0 | github-code | 36 |
12607877643 | # 本地Chrome浏览器设置方法
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup as bs
# from selenium... | Kenny3Shen/CodeShen | Code/Python/queryMyScores/queryScores.py | queryScores.py | py | 7,792 | python | en | code | 0 | github-code | 36 |
13600318080 | import scrapy
from common.util import xpath_class
from event.items import ResponseItem
class BIOEventSpider(scrapy.Spider):
name = 'bio_event'
base_url = 'https://www.bio.org'
events_path = '/events'
source = 'BIO'
custom_settings = {
'ITEM_PIPELINES': {
'event.spiders.bio.p... | JuroOravec/knwldg | event/event/spiders/bio/spiders.py | spiders.py | py | 1,199 | python | en | code | 0 | github-code | 36 |
10492838240 | import open3d as o3d
import copy
from modern_robotics import *
down_voxel_size = 10
icp_distance = down_voxel_size * 15
result_icp_distance = down_voxel_size * 1.5
radius_normal = down_voxel_size * 2
def cal_angle(pl_norm, R_dir):
angle_in_radians = \
np.arccos(
np.abs(pl_norm.x*R_dir[0]+ pl... | chansoopark98/3D-Scanning | test_color_icp.py | test_color_icp.py | py | 3,645 | python | en | code | 0 | github-code | 36 |
36714514227 | from dash import html
import dash_bootstrap_components as dbc
from dash.development.base_component import Component
from dataviz.irenderer import IDataStudyRenderer
from dash import dcc
from dataviz.plot_types import name_to_plot
from dataviz.assets.ids import IDAddPlotModal as ID
horizontal_line = html.Hr(style={'... | adangreputationsquad/theriver | dataviz/pages/add_plot_modal.py | add_plot_modal.py | py | 3,145 | python | en | code | 0 | github-code | 36 |
16129025675 | from twisted.internet import reactor, defer
from twisted.web.client import getPage
count = 0
class Request:
def __init__(self, url, callback):
self.url = url
self.callback = callback
class HttpResponse:
def __init__(self, content, request):
self.content = content
self.request = ... | czasg/ScrapyLearning | czaSpider/dump/异步/scrapy模拟/test.py | test.py | py | 3,582 | python | en | code | 1 | github-code | 36 |
33922205463 | # 1. Read input data
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
# 2. Calculate the lenght and width
lenght = abs(x1-x2)
width = abs(y1-y2)
# 3. Calculate the square are and the perimeter
square_area = lenght * width
perimeter = (lenght+width)*2
# 4. Print the results
print (f'{squar... | IvayloSavov/Programming-basics | simple_operations_and_codding_exercise/2D_rectangle_area.py | 2D_rectangle_area.py | py | 360 | python | en | code | 0 | github-code | 36 |
16957389593 | from collections import deque
from variables import graph
from variables import vertex
def breadth_first_search(searchG, s, d):
R = dict()
R[s] = s
Q = deque()
Q.append(s)
while Q:
u = Q.popleft()
for v in searchG.neighbours(u):
if v not in R:
R[v] = u
... | MichaelQi11/Mid-Age-Plane-War | Functions.py | Functions.py | py | 1,451 | python | en | code | 0 | github-code | 36 |
9105847241 | # coding=utf-8
import webapp2
import sys
import config
import services.files
import services.event
import services.restore
from services.template import render
try:
from google.appengine.api import taskqueue
except ImportError:
pass
reload(sys) # Reload does the trick!
sys.setdefaultencoding('utf8')
class... | nicklasos/gae-data-fallback | controllers/restore.py | restore.py | py | 2,551 | python | en | code | 1 | github-code | 36 |
8017965445 | import turtle
t = turtle.Turtle()
s = turtle.Screen()
t.speed(0)
s.bgcolor('red')
t.pencolor('white')
t.pensize(5)
#Code for building radical thread
for i in range(6):
t.pencolor('black')
t.pensize(2)
t.forward(200)
t.backward(200)
t.right(60)
#Code for building spiral thread
side = 200
for i in range(15):
... | arpit-ak/python-turtle | spider web.py | spider web.py | py | 577 | python | en | code | 0 | github-code | 36 |
33083320956 | # Desafios 71
print('='*20)
print('{:^20}'.format('BANCO'))
print('='*20)
valor = int(input('Qual valor deseja sacar? R$'))
while True:
if valor >= 50:
cedula50 = valor // 50
print(f'=> {cedula50} cédulas de R$50,00')
valor = valor % 50
elif valor >= 20:
cedula20 = valor // 20... | sarandrade/Python-Courses | Curso Python - Gustavo Guanabara/Mundo 2 - Estruturas de Controle/Exercícios/Exercício #071.py | Exercício #071.py | py | 751 | python | pt | code | 0 | github-code | 36 |
75104190185 | # Given a sorted array of numbers, find if a given number ‘key’ is present
# in the array. Though we know that the array is sorted, we don’t know if
# it’s sorted in ascending or descending order. You should assume that the
# array can have duplicates.
# Write a function to return the index of the ‘key’ if it is pr... | itsmeichigo/Playgrounds | GrokkingTheCodingInterview/ModifiedBinarySearch/ez-binary-search.py | ez-binary-search.py | py | 877 | python | en | code | 0 | github-code | 36 |
21678794363 | # Reverse a singly linked list.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
class Solution(object):
def reverseListIterat... | WangsirCode/leetcode | Python/reverse-linked-list.py | reverse-linked-list.py | py | 590 | python | en | code | 0 | github-code | 36 |
7538333233 | def maxProfit(l, k):
visited = [False] * len(l)
result = 0
for j in range(k):
lowest = -1
buy, sell = -1, -1
for i in range(len(l)):
if visited[i]:
continue
lowest = i if lowest == -1 or l[i] < l[lowest] else lowest
buy, sell = (lowest, i) if (buy, sell) == (-1, -1) or l[i] - l[lowest] > l[sell] -... | daily-coding-x-br/daily-coding | september/09/roberto.py | roberto.py | py | 513 | python | en | code | 2 | github-code | 36 |
11998014126 | #!/usr/bin/python
import json
import math
cpus = 0
with open('/proc/cpuinfo') as f:
for line in f:
if 'processor' in line:
cpus += 1
meminfo = {}
with open('/proc/meminfo') as f:
for line in f:
meminfo[line.split(':')[0]] = line.split(':')[1].strip()
memory = int(meminfo['MemTotal... | prominence-eosc/prominence | htcondor/images/worker/write-resources.py | write-resources.py | py | 498 | python | en | code | 2 | github-code | 36 |
32919021229 | import logging
import multiprocessing_logging
logging.basicConfig(filename="parsing.log", level=logging.INFO)
multiprocessing_logging.install_mp_handler()
import os
import sys
from seamr import parsers
from seamr.core import Store
import argparse
from tqdm import tqdm
from datetime import datetime
... | zewemli/seamr | seamr/cli/check_label_parsing.py | check_label_parsing.py | py | 2,364 | python | en | code | 0 | github-code | 36 |
70996246505 | import json
from datetime import datetime, timedelta
import openpyxl
import requests
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_pa... | fnabiyevuz/crm | main/views.py | views.py | py | 58,006 | python | en | code | 0 | github-code | 36 |
30712954822 | # coding=utf-8
from sap.sap_connection import Connection_SAP
class RFC(object):
def __init__(self):
self.__connection = Connection_SAP().get_connection()
self.__gateway = Connection_SAP().get_gateway()
def invoke_func(self, name, imp):
try:
with self.__conne... | ramonlimaramos/sap_middleware_rfc | sap/sap_adapter.py | sap_adapter.py | py | 1,008 | python | en | code | 0 | github-code | 36 |
42099837809 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
print('make pre-encoded tcga data from 2048')
import os
import sys
import csv
import numpy as np
import pickle
from PIL import Image
import tensorflow as tf
import tensorflow_ae_base
from tensorflow_ae_base import *
import tensorflow_util
impo... | naono-git/cnncancer | make_tcga_encoded2_2048.py | make_tcga_encoded2_2048.py | py | 1,884 | python | en | code | 6 | github-code | 36 |
18456187648 | from __future__ import unicode_literals
from udsactor.log import logger
from . import operations
from . import store
from . import REST
from . import ipc
from . import httpserver
from .scriptThread import ScriptExecutorThread
from .utils import exceptionToMessage
import socket
import time
import random
import os
imp... | karthik-arjunan/testuds | actors/src/udsactor/service.py | service.py | py | 13,012 | python | en | code | 1 | github-code | 36 |
11732973811 | # Python3 program to demonstrate Morse code
# function to encode a alphabet as
# Morse code
def morseEncode(x):
# refer to the Morse table
# image attached in the article
if x == 'a':
return ".-"
elif x == 'b':
return "-..."
elif x == 'c':
return "-.-."
elif x == 'd':
... | lokendarjangid/loky | notused/notusable.py | notusable.py | py | 12,713 | python | en | code | 0 | github-code | 36 |
19764100615 | import re
handle = open('regex_sum_443280.txt','r')
sum = 0
valCount = 0
for i in handle:
i = i.rstrip()
x = re.findall('[0-9]+',i)
for j in x:
try:
no = int(j)
sum = sum + no
valCount = valCount + 1
except:
continue
print('Values... | nazimshaikh95/Python-for-Everybody-Specialization | 3 Using Python To Access The Web Data/week 2/NumberSumHaystack.py | NumberSumHaystack.py | py | 349 | python | en | code | 0 | github-code | 36 |
3156766981 | cont = 1
soma = 0
nota = float(input())
continua = True
while continua:
while cont <= 2:
if nota >= 0 and nota <= 10:
cont += 1
soma = soma + nota
if nota < 0 or nota > 10:
print("nota invalida")
if cont <... | MarceloBritoWD/URI-online-judge-responses | Iniciante/1118.py | 1118.py | py | 765 | python | en | code | 2 | github-code | 36 |
981584569 | import argparse
import random
def main():
args = parse_args()
compile_random_pattern(args.n, args.output)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('n', type=int, help='dimension of output file (power of 2)')
parser.add_argument('output', type=argparse.FileType('wb... | hjbyt/OS_HW5 | compile_random.py | compile_random.py | py | 725 | python | en | code | 0 | github-code | 36 |
72873800743 | import tic_tac_object_4
import csv
import statistics
# USE THIS FILE TO BUILD NEW FILES OF GAMES- TO DO THE MACHINE LEARNING THING
# Currently ONLY LEVEL ZERO AND ONE ARE OPTIMIZED. RAN ZERO LIKE A MILLION TIMES, AND THEN ONE A THOUSAND TIMES OFF OF THAT
level = 1
while level < 2:
GDL_File = open('File_Machine_L... | daltonkdwyer/Tic_Tac_Machine_Object | Make_Machine_File_Call.py | Make_Machine_File_Call.py | py | 1,309 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.