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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
31091913885 | from django.shortcuts import render
from parse.forms import ParseForm
from parse.tasks import task_parse
def ozon_parse(request):
if request.method == 'POST':
form = ParseForm(request.POST)
if form.is_valid():
id_user = form.cleaned_data.get('id_user')
api_key = form.clean... | jurawlew/ozon_parse | parse/views.py | views.py | py | 500 | python | en | code | 0 | github-code | 36 |
70797759465 | import os
f = open("calculator_github.py", "w")
f.write("# my_first_calculator.py by AceLewis\n")
f.write("# support for 100 by Rahul Gahlot(github.com/starinfinity)\n")
f.write("# TODO: Make it work for all floating point numbers too\n")
f.write("if 3/2 == 1: # Because Python 2 does not know maths\n")
f.write("\tinp... | starinfinity/my_first_calculator-creator | calculatorprintv2.py | calculatorprintv2.py | py | 1,399 | python | en | code | 8 | github-code | 36 |
74053950505 | from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input("Enter URL - ")
############################################### Comment this for first question ##############################
pos = in... | maleeha045/python-for-everybody | 3_using_python_to_access_web_data/scrapUrl.py | scrapUrl.py | py | 634 | python | en | code | 0 | github-code | 36 |
32973127797 | # /usr/bin/env python3
import pandas as pd
import numpy as np
def make_df(cols='ABCD',ind=range(2)):
info={ c: [str(c)+ str(i) for i in ind]
for c in cols
}
return pd.DataFrame(info,index=ind)
def make_fr(cols=list('ABCD'),ind=range(2)):
info=[[str(i)+str(e) for i in cols] for e in ind]
r... | Jovamih/PythonProyectos | Pandas/Data Sciensist/combinacion-subconjuntos.py | combinacion-subconjuntos.py | py | 1,927 | python | es | code | 1 | github-code | 36 |
26478313784 | from django.db import models
from django.contrib.auth.models import User
from django.db import IntegrityError
import uuid
class Procedure(models.Model):
title = models.CharField(max_length=255, blank=True)
author = models.CharField(max_length=255, blank=True)
uuid = models.UUIDField(default=uuid.uuid4, ed... | protocolbuilder/sana.protocol_builder | src-django/api/models.py | models.py | py | 4,416 | python | en | code | 0 | github-code | 36 |
3289841382 | import copy
import abc
import logging
import weakref
import math
from collections import defaultdict
try:
from collections import OrderedDict
except ImportError: #pragma:nocover
from ordereddict import OrderedDict
from pyomo.core.kernel.component_interface import \
(IActiveObject,
... | igorsowa9/vpp | venv/lib/python3.6/site-packages/pyomo/core/kernel/component_block.py | component_block.py | py | 59,127 | python | en | code | 3 | github-code | 36 |
28508540107 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from opus_core.variables.variable import Variable
from biocomplexity.land_cover.variable_functions import my_attribute_label
from urbansim.functions... | psrc/urbansim | biocomplexity/land_cover/deDDD.py | deDDD.py | py | 5,325 | python | en | code | 4 | github-code | 36 |
73485102183 | # https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/
# time complexity: O(n)
class Solution:
def maxSumOfThreeSubarrays(self, nums: list[int], k: int) -> list[int]:
window1, window2, window3 = sum(nums[:k]), sum(nums[k:2 * k]), sum(nums[2 * k:3 * k])
max1, max2, max3 = windo... | lexiconium/algorithms | leetcode/dp/maximum_sum_of_3_non_overlapping_subarrays.py | maximum_sum_of_3_non_overlapping_subarrays.py | py | 1,009 | python | en | code | 0 | github-code | 36 |
38016407041 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
# Enable Logging
tf.logging.set_verbosity(tf.logging.INFO)
# DATA
IRIS_TRAINING = 'iris/iris_training.csv'
IRIS_TEST = 'iris/iris_test.csv'
# Load
training_set = tf... | FrozenPandaz/tensorflow-tuts | src/contrib-learn/quickstart.py | quickstart.py | py | 2,351 | python | en | code | 0 | github-code | 36 |
32274445958 | #!/opt/csw/bin/python
# coding=utf-8
from time import time
from ircbot import SingleServerIRCBot, Channel
from irclib import nm_to_n, is_channel, parse_channel_modes
from datetime import datetime
import conf.config as config
import logging
import sys
import traceback
import threading
import pluginloader
from logger im... | sviik/marju | marjubot.py | marjubot.py | py | 11,353 | python | en | code | 1 | github-code | 36 |
23063743554 | import sys
from dataclasses import dataclass
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.pipeline import Pipeline
from src.exception import CustomException
from ... | AnshulDubey1/Music-Recommendation | src/components/data_transformation.py | data_transformation.py | py | 3,195 | python | en | code | 5 | github-code | 36 |
41715859228 | # -*-coding:utf-8 -*-
class Compare:
def __init__(self, data, checkpoint):
self.data = data
self.checkpoint = checkpoint
def compare(self):
flag = None
if isinstance(self.data, str):
if self.checkpoint == self.data:
flag = True
else:
... | ZachTao/ApiAutoTest | compare.py | compare.py | py | 710 | python | en | code | 0 | github-code | 36 |
23614214391 | import wqpy.read
import aiohttp
import asyncio
import io
async def _basic_aquery(service_url, service_params):
async with aiohttp.ClientSession() as session:
async with session.get(service_url, params = service_params) as r:
return(await r.text())
def multi_query(service_url, service_param_list, parse = T... | mkoohafkan/wqpy-clone | wqpy/aquery.py | aquery.py | py | 675 | python | en | code | 0 | github-code | 36 |
6742370298 | # -*- coding: utf-8 -*-
# file lyxpreview2bitmap.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
# author Angus Leeming
# with much advice from members of the preview-latex project:
# David Kastrup, dak@gnu.org and
# Jan-Åke Larsson, jalar@mai.liu.se.
# Full... | cburschka/lyx | lib/scripts/lyxpreview2bitmap.py | lyxpreview2bitmap.py | py | 23,257 | python | en | code | 33 | github-code | 36 |
33207354162 | import Bio
from Bio.Blast import NCBIWWW,NCBIXML
from Bio.Seq import Seq
from Bio import SeqIO
def find_stop_codon(seq, start, stop_codons):
"""Find the next stop codon in the given sequence."""
for i in range(start, len(seq), 3):
codon = seq[i:i+3]
if codon in stop_codons:
return i... | jkjkciog/transcripomics | Chat GPT model improvements (non functional).py | Chat GPT model improvements (non functional).py | py | 2,540 | python | en | code | 1 | github-code | 36 |
29836727610 | import logging
import requests
import datetime
from aiogram import Bot, Dispatcher, executor, types
from tg_info import info
from bs4 import BeautifulSoup
weather_token = "6e8d79779a0c362f14c60a1c7f363e29"
API_TOKEN = "5158040057:AAEtt8ByoaJdYMy09MpupqpNAxiCAQnGj-0"
# Configure logging
logging.basicConfig(... | sivtv/telegrambot | main.py | main.py | py | 4,353 | python | uk | code | 0 | github-code | 36 |
16665836793 | import pandas as pd
import numpy as np
import os
from logisds.utils import get_console_logger
logger = get_console_logger("Data-Processor")
class DataLoader:
NUM_FEATURES = 34
def __init__(
self, N_steps: int, seed: int = 1, val_ratio: float = 0.4, data_path=None
):
"""
This cla... | wluo-personal/logisds | logisds/data.py | data.py | py | 8,237 | python | en | code | 0 | github-code | 36 |
2526327823 | # This script scraps Kenyan startups from https://startuplist.africa/
# Import required libraries
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup as soup
from urllib.request import Request, urlopen
from selenium import webdriver
# URLs
url = "https://startuplist.africa/startups-in-kenya"
# Dri... | CharlesIvia/startups_in_kenya | scrapper/companies_scrapper.py | companies_scrapper.py | py | 1,120 | python | en | code | 1 | github-code | 36 |
32058498206 | from tkinter import *
import matplotlib
import os
from pandas import DataFrame
import numpy as np
import pandas as pd
from tkinter import ttk
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from Functions import... | patidarrahul/PlotIT | extra_python files/boxplot.py | boxplot.py | py | 25,877 | python | en | code | 0 | github-code | 36 |
27954967699 | import time
import os
import pandas as pd
import requests as re
import numpy as np
import asyncio
from aiohttp import ClientSession
from loguru import logger
url_general = 'https://www.fundamentus.com.br/resultado.php'
url_paper = 'https://www.fundamentus.com.br/detalhes.php?papel='
data_to_save = list()
... | Muriloozol/InvestCode | scrapper/scrapper.py | scrapper.py | py | 4,364 | python | en | code | 0 | github-code | 36 |
11603254102 | inputs = []
results = []
def get_value_from_input(input_arg, results, inputs):
if input_arg == "_":
return 0
if input_arg.find("$") > -1:
ref = int(input_arg.replace("$", ""))
return get_cell_i(results, inputs, ref)
else:
return int(input_arg)
def compute_input(results, i... | NicolleLouis/codingame | dependancy.py | dependancy.py | py | 1,295 | python | en | code | 0 | github-code | 36 |
43884835663 | from models.vn_layers import *
import torch
import torch.nn as nn
from math import *
from models.kernelization import *
class TransformerEncoder(nn.Module):
def __init__(self, args):
super(TransformerEncoder, self).__init__()
self.args = args
self.heads = args.num_heads
self.num_f... | MagicSssak/VNPerformer | models/TransformerEncoder.py | TransformerEncoder.py | py | 4,149 | python | en | code | 0 | github-code | 36 |
29407570552 | import pymask as pm
# The parts marked by (*) in following need to be
# adapted according to knob definitions
def build_sequence(mad, beam):
slicefactor = 2
pm.make_links(force=True, links_dict={
'optics_indep_macros.madx': 'tools/optics_indep_macros.madx',
'macro.madx': ('/afs/cern.ch/user/... | hjggraham/lhcmask | python_examples/run3_collisions_python/old/optics_specific_tools.py | optics_specific_tools.py | py | 6,469 | python | en | code | null | github-code | 36 |
8290510873 |
import os
import json
import errno
import itertools
import numpy as np
import pandas as pd
def export_labels(root_dir: str):
"""Transforms `Balloon` dataset into Faster R-CNN standard format"""
labels_dir = os.path.join(root_dir, "labels")
if not os.path.exists(labels_dir):
try:
... | AndreasKaratzas/faster-rcnn | lib/balloon.py | balloon.py | py | 2,836 | python | en | code | 0 | github-code | 36 |
71929861545 | from torch import nn
import torch.nn.functional as F
class PeriodDiscriminator(nn.Module):
def __init__(self, period):
super(PeriodDiscriminator, self).__init__()
layer = []
self.period = period
inp = 1
for l in range(4):
out = int(2 ** (5 + l + 1))
... | cuongnguyengit/hifigan | model/period_discriminator.py | period_discriminator.py | py | 1,062 | python | en | code | 0 | github-code | 36 |
6173034334 | import inspect
import os
import random
import re
import sys
# Contains utility classes for file I/O
class Error(Exception):
pass
class FileReadError(Error):
def __init__(self, msg):
self.msg = msg
class FileWriteError(Error):
def __init__(self, msg):
self.msg = msg
class PathNotFoundException(Except... | Seabreg/otori | libfileio.py | libfileio.py | py | 3,390 | python | en | code | 1 | github-code | 36 |
72515318503 |
# Predict water positions
import time
import sys # To use sys.argv
import mdtraj
import numpy as np
import math
def BWHB(x1, x2, print_dist=False): # Bridge Water Hydrogen Bond
d = np.sqrt(((x1*10-x2*10)**2).sum())
if print_dist:
print(f'{d:.3f}', end=' \t')
return (1 / (1 + (d/2.6)**6)) / 0.5... | darrenjhsu/tiny_IFD | 01_Workflow/MDR_analysis/calcWater_func.py | calcWater_func.py | py | 39,291 | python | en | code | 12 | github-code | 36 |
38387600079 | import math
import copy
import matplotlib.pyplot as plt
import numpy as np
import Solution as sl
import Problem
import ParetoUtil as pu
class MOPSO():
def __init__(self, problem, popSize: int, repSize: int):
super().__init__()
self.problem = problem
self.popSize = popSize
... | MosyMosy/Metaheuristics-Algorithms | MOPSO.py | MOPSO.py | py | 5,467 | python | en | code | 0 | github-code | 36 |
6656532235 | # -*- coding: utf-8 -*-
"""
Created on 2023-11-28 (Tue) 15:03:39
Planar Maximally Filtered Graph implementation in python
@author: I.Azuma
"""
import numpy as np
import pandas as pd
import time
import networkx as nx
from networkx.algorithms.planarity import check_planarity
from tqdm import tqdm
import matplotlib.pypl... | groovy-phazuma/ImmunSocialNetwork | network_models/pmfg/pmfg.py | pmfg.py | py | 13,712 | python | en | code | null | github-code | 36 |
7292695784 | #!/usr/bin/python3
"""
# This file is part of the Pop Icon Theme and is free software; you can
# redistribute it and/or modify it under the terms of the GNU Lesser General
# Public License as published by the Free Software Foundation; version 3.
#
# This file is part of the Pop Icon Theme and is distributed in the h... | pop-os/icon-theme | master-render.py | master-render.py | py | 7,234 | python | en | code | 189 | github-code | 36 |
6752697116 | # -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QTreeWidgetItem, QDialog, QTreeWidgetItemIterator
from PyQt5.QtCore import pyqtSlot
from product.controllers.productcontroller import ProductController
from workshop.views.selectoddmentdraw import Ui_Dialog
import user
class SelectoddmentdrawModule(QDialog, Ui_... | zxcvbnmz0x/gmpsystem | workshop/modules/selectoddmentdrawmodule.py | selectoddmentdrawmodule.py | py | 3,851 | python | en | code | 0 | github-code | 36 |
15266305014 | import json
from django.db.models import Q
from django.http import HttpResponse
from django.views import View
from mymodels.models import Posts, CustomUser
from mypackage.MixinClasses import GetUserMixin, SlicerMixin, ExcludeDelPostsMixin
import datetime
from django.utils import timezone
class PostsList(View, Slice... | untiwe/citrom_test | mypackage/posts_manager/posts_list.py | posts_list.py | py | 5,721 | python | ru | code | 0 | github-code | 36 |
21325729011 | import csv
from elasticsearch import Elasticsearch
from elasticsearch import helpers
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
#es.indices.delete(index='movies', ignore=[400, 404])
print(es.ping())
def convert(filename,indexname,type):
with open(filename, encoding="utf8") as file:
... | gdimitropoulos/information-retrieval | part1b/reader.py | reader.py | py | 1,044 | python | en | code | 1 | github-code | 36 |
28519426537 | # PopGen 1.1 is A Synthetic Population Generator for Advanced
# Microsimulation Models of Travel Demand
# Copyright (C) 2009, Arizona State University
# See PopGen/License
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
from misc.widgets import *
import os, shutil
class... | psrc/urbansim | synthesizer/gui/file_menu/summary_page.py | summary_page.py | py | 8,064 | python | en | code | 4 | github-code | 36 |
34408858736 | from django.conf.urls import include, url
from teacherMan import views as tech
app_name = 'teacher'
urlpatterns = [
url(r'main', tech.main, name='teacher'),
url(r'data', tech.getData),
url(r'edit', tech.editTech),
url(r'delTechInfo', tech.delTech),
url(r'addTechInfo', tech.addTech),
#url(r'fi... | A11en0/InfoManageSystem | teacherMan/urls.py | urls.py | py | 349 | python | en | code | 1 | github-code | 36 |
20839048831 | def factorialRecursion(n):
if n <= 0:
return
if n == 1:
return n
return n * factorialRecursion(n - 1)
def factorialIterative(n):
fact = 1
for num in range(2, n - 1):
fact += num
return fact
print(factorialRecursion(5)) | lyds214/DSA-Implementation | Recursion/Factorial.py | Factorial.py | py | 282 | python | en | code | 0 | github-code | 36 |
7046181493 | import logging
import json
from invokust.aws_lambda import LambdaLoadTest, results_aggregator
logging.basicConfig(level=logging.INFO)
###
# SETTINGS
###
# How long should the test run for in minutes?
# Note that Lambda invokations that are started cannot be stopped.
# Test times will actually be run in intervals of ... | cds-snc/gc_forms_load_testing | locust_swarm.py | locust_swarm.py | py | 4,479 | python | en | code | 0 | github-code | 36 |
74430643303 | import datetime
import json
from flask_restful import Resource
from flask import request
from init import app, db
from Models.player import Player
from Models.playerRequest import PlayerRequest
from decorators import json_required
import random
class RPlayerPost(Resource):
def post(self, **kwargs):
""" ... | Apolliner/Field-Mini-Game | testOnline/ApiServer/API/player.py | player.py | py | 3,174 | python | en | code | 0 | github-code | 36 |
31746033117 | import django_filters as filters
from django_filters.rest_framework import FilterSet
from recipes.models import Ingredient, Recipe
class RecipeFilter(filters.FilterSet):
"Filters recipes againts tags and author"
tags = filters.AllValuesMultipleFilter(
field_name='tags__slug'
)
class Meta:
... | GenVas/foodgram-project-react | backend/api/filters.py | filters.py | py | 1,134 | python | en | code | 1 | github-code | 36 |
27596377312 | import loadData as data
import numpy as np
import computeCost as cost
def gradientDescent(X, y, theta, alpha, num_iters):
# Gradient descent is used to minimize cost function J
# Vectorisation implementation. Applicable for any no for features.
# Theta should be a nx1 vector where n = No of feature + 1
... | mirfanmcs/Machine-Learning | Supervised Learning/Linear Regression/Linear Regression with One Variable/Python/gradientDescent.py | gradientDescent.py | py | 1,398 | python | en | code | 0 | github-code | 36 |
35425129977 |
# coding: utf-8
# # 보스톤 집 값 예측하기
#
# * 보스턴 주택 데이터는 여러 개의 측정지표들을 포함한, 보스톤 인근의 주택가 중앙값
#
# * Variable in order:
# - CRIM : 마을별 1인당 범죄율
# - ZN : 25,000 평방미터를 초과하는 거주지역의 비율
# - INDUS : 비소매 상업지역이 점유하고 있는 토지의 비율
# - CHAS : 찰스 강에 대한 더미변수(강의 경계에 위치한 경우는 1, 아니면 0
# - NOX : 10ppm 당 농축 일산화질소
# - RM : 주책 1가구당 평균 방... | ALVHA/DeepLearning | 20190722/Boston+House.py | Boston+House.py | py | 2,276 | python | ko | code | 0 | github-code | 36 |
43238549779 | import numpy as np
class Solution(object):
def find_order(self, num_courses, prerequisites):
"""
:param num_courses: the number of courses that we'll determine if we can take and we'll find
an ordering in which to take them
:param prerequisites: the array of arrays [a, b] repre... | mariabrinzila/Tutorials | Exercises/Course-Schedule2/main.py | main.py | py | 7,128 | python | en | code | 0 | github-code | 36 |
7554777199 | import torch
import torch.nn as nn
import torch.nn.init as init
class Fire(nn.Module):
def __init__(self, inplanes, squeeze_planes, expand1x1_planes, expand3x3_planes):
super(Fire, self).__init__()
self.inplanes = inplanes
self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1)
... | gaungalif/cifar10.pytorch | cifar/models/squeeze.py | squeeze.py | py | 2,764 | python | en | code | 0 | github-code | 36 |
21687254250 | import math
import random
import keyboard
from random import choice
import pygame
import pygame.freetype
from pygame.draw import *
pygame.mixer.pre_init(44100, -16, 1, 512)
pygame.font.init()
pygame.init()
# Ускорение свободного падения
g = 3
# Громкость музыки и выбор музыки (менять не надо)
track = 0
vol = 0.5
# Раз... | MrKotMatroskin/Practika_programm | Игры/Пушка/gun.py | gun.py | py | 24,603 | python | ru | code | 0 | github-code | 36 |
6651085058 | from univention.admin.layout import Tab, Group
import univention.admin.filter
import univention.admin.handlers
import univention.admin.allocators
import univention.admin.localization
translation=univention.admin.localization.translation('univention.admin.handlers.mail')
_=translation.translate
module='mail/lists'
ope... | m-narayan/smart | ucs/management/univention-directory-manager-modules/modules/univention/admin/handlers/mail/lists.py | lists.py | py | 6,688 | python | en | code | 9 | github-code | 36 |
32492804178 | # -*- coding: utf-8 -*-
def input_float():
while True:
try:
s = float(input('고정소수점를 입력하세요.'))
except ValueError as e:
print(e,'은(는) 고정소수점이 아닙니다.')
except:
print('알 수 없는 오류가 발생하였습니다. 다시 입력해주세요.')
else:
print('입력한 고정소수점은 ',s,'입니다.',sep=''... | StopDragon/CSE1017 | Training/#class10/실습 #10-1.py | 실습 #10-1.py | py | 467 | python | ko | code | 0 | github-code | 36 |
3799851771 | import os
import json
import requests
import logging
from urllib.parse import urlencode
from types import SimpleNamespace
MTYPES = dict(xbox=1, playstation=2, steam=3, blizzard=4, stadia=5, epic=6, bungie=254)
MLEVELS = dict(beginner=1, member=2, admin=3, actingfounder=4, founder=5) # Just like with Halo - Bungie nev... | xant-tv/ecumene | src/bnet/client.py | client.py | py | 12,445 | python | en | code | 2 | github-code | 36 |
4384009637 | import pandas as pd
import db_connect as db
import numpy as np
def csv_to_datavault_tables(tbl_type: str, csv_dir: str) -> None:
# CSV file path
csv_file = f'{csv_dir}\\{tbl_type}.csv'
if tbl_type in ['SAT', 'LNK', 'SAT_LNK']:
if tbl_type == 'LNK':
table_name = 'DV_ENTITYLINKS'
... | musrah13/autogen-dv | generate_dv.py | generate_dv.py | py | 2,266 | python | en | code | 0 | github-code | 36 |
36779477728 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root, max_sum):
if not root:
return 0
left_sum = self.helper(root.left, max_... | mshekhar/random-algs | epi_solutions/binary_tree/binary-tree-maximum-path-sum.py | binary-tree-maximum-path-sum.py | py | 842 | python | en | code | 4 | github-code | 36 |
70806938343 | import sys
from collections import deque
sys.stdin = open('input.txt')
def bellmanford():
for n in range(N):
for i in range(N):
for weight, node in linked[i]:
if distance[i] != -1e10 and distance[node] < weight + distance[i]:
distance[node] = distance[i] + w... | unho-lee/TIL | CodeTest/Python/BaekJoon/1738.py | 1738.py | py | 888 | python | en | code | 0 | github-code | 36 |
4693523565 | from bs4 import BeautifulSoup
import requests as google
from nltk import word_tokenize, FreqDist
import string
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
import re
from sklearn.feature_extraction.text import TfidfVectorizer
import gensim
from nltk.tokenize import word_tokenize
stopwords_list... | ethirajsrinivasan/LSIWebScrap | search_engine_interface.py | search_engine_interface.py | py | 3,042 | python | en | code | 0 | github-code | 36 |
75128039145 | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.graph_objs as go
df=pd.read_csv(r'pax_all_agreements_data.csv',sep=',')
df['Dat_Y'],df['Dat_M'],df['Dat_D']=df['Dat'].str.split('-').str
fecha_inicio=min(df['Dat_Y'])
fecha_final=max(df['Dat_Y'])
df_grupo_region_fecha=df.groupb... | AlejandroUPC/data_vis_uoc | data_exploring.py | data_exploring.py | py | 3,063 | python | en | code | 0 | github-code | 36 |
33014529586 | # coding: utf-8
words='''
人生长至一世、短如一瞬
寰宇浩瀚无际,此生飘渺无归
旅途上,我们将会遇到许多
或许喜悦、或许伤悲、或许欢喧、或许静宁
请记得哭过、笑过,要继续活下去
真正重要的到底是什么
我们似乎都在追求着什么
最后才发现
握紧手心,里面什么都没有
一呼一吸
花开花落
追日、探月、索星、寻梦、逐尘
无论他人怎么说,我们都是独一无二的我们
纷纷扰扰的一生中
或许只有自己明白
或许自己也不明白'''
words.split('\n')
phrase=words.split('\n')
p=randint(2,7)
for i in range(p):
pp=randint(1,3)
e... | Shao-Ting/ST-s-Python-work | 'w401.py'35.py | 'w401.py'35.py | py | 726 | python | zh | code | 0 | github-code | 36 |
6533803679 | import cv2
import numpy as np
from matplotlib import pyplot as plt
blur1 = cv2.imread('part1/blur1.png', 0)
blur2 = cv2.imread('part1/blur2.png', 0)
blur3 = cv2.imread('part1/blur3.png', 0)
oriimg = cv2.imread('part1/original.jpg', 0)
# fft to convert the image to freq domain
fblur1 = np.fft.fft2(blur1)
fb... | ebbalseven/Motion-Deblurring-in-Frequency-Domain | part1.py | part1.py | py | 3,884 | python | en | code | 2 | github-code | 36 |
10604142211 | # -*- coding: utf-8 -*-
# © 2016 Ainara Galdona - AvanzOSC
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import openerp.tests.common as common
from openerp import _
class TestCrmLeadPartnerContact(common.TransactionCase):
def setUp(self):
super(TestCrmLeadPartnerContact, self).set... | dtorresxp/crm-addons | crm_lead_partner_contact/tests/test_crm_lead_partner_contact.py | test_crm_lead_partner_contact.py | py | 2,078 | python | en | code | 0 | github-code | 36 |
35781259149 | import os
import pandas as pd
import random
import numpy as np
import tensorflow as tf
from datetime import datetime
import models
from sklearn.metrics import r2_score
import math
IDS_TRAIN = []
IDS_TRAIN.append([12, 0, 1, 11])
IDS_TRAIN.append([7, 0, 17, 11])
IDS_TRAIN.append([12, 5, 15, 9])
IDS_TRAIN.append([8, 22, ... | picchius94/META-CONV1D | Training/evaluate_ST-Conv1D.py | evaluate_ST-Conv1D.py | py | 20,247 | python | en | code | 4 | github-code | 36 |
22344125415 | import logging
import re
from investments.models import RealEstate
from .utils import (check_skip, create_investment, extract_data, get_id,
get_interest_range, normalize_meta, normalize_number,
parse_markup_in_url, price_range, scrape_page)
logger = logging.getLogger(__name__)... | Constrictiongithub/constriction_website | importer/management/commands/scrapers/caseinpiemonte.py | caseinpiemonte.py | py | 3,395 | python | en | code | 0 | github-code | 36 |
2317107691 |
import os
import numpy as np
import keras
from keras import models, layers
from PIL import Image
from numpy import asarray
from cv2 import cv2
from keras.models import load_model
from os.path import join, dirname, realpath
from flask import Flask,render_template,request
import skimage
from skimage.transform import res... | Roboramv2/Image-compression | 1_autoencoder/flask/app.py | app.py | py | 2,824 | python | en | code | 4 | github-code | 36 |
74031724903 | #!/bin/python3
import glob
import os
import sys
import re
import mimetypes
import time
import shutil
import platform
from tkinter import *
from pathlib import Path
system = platform.platform()
if 'win' in system:
filedelimiter = "\\"
else:
opener = 'xdg-open'
filedelimiter = "/"
# glob, glob, glob if pred... | Balajisrinivasan26/automatic_file_organizer | janitor.py | janitor.py | py | 6,163 | python | en | code | 0 | github-code | 36 |
72570992424 | # turns out there's a better website for records than the one this scraper uses
# scraper to query AZ SOS website for possible matches for each retailer
import urllib.request
import urllib.parse
import bs4 as bs
import re
import pandas as pd
import os
import numpy as np
from selenium import webdriver
from selenium.webd... | Luke-Patterson/state_scrap | AZ/old/AZ_1_crawler_old.py | AZ_1_crawler_old.py | py | 4,561 | python | en | code | 0 | github-code | 36 |
74199237863 | from Funcionario import Funcionario
from Dependente import Dependente
from Cargo import Cargo
def main():
programador = Cargo(nome="Programador", salario_base=5000)
funcionario1 = Funcionario("Vitor", programador, "23/05/2001")
dependente1 = Dependente("Alice", "16/02/2015")
dependente2 = Dependente(... | CoimbraVitor/OOUniAcademia | Exercicio9/main.py | main.py | py | 647 | python | pt | code | 1 | github-code | 36 |
13511271003 | #!/usr/bin/python
import tensorflow as tf
import numpy as np
from model_base import *
import cifar
class cifar_lenet5(model_base):
def __init__(self,reader):
self.base = super(cifar_lenet5,self)
self.base.__init__(reader)
def decl_model(self):
batch = 100
x = self.decl_place... | angelbruce/NN | cifar_lenet5.py | cifar_lenet5.py | py | 1,475 | python | en | code | 0 | github-code | 36 |
72027853863 |
# -*- coding: utf-8 -*-
# WindowでGroupByの区間を区切る
import apache_beam as beam
# Dataflowの基本設定
# ジョブ名、プロジェクト名、一時ファイルの置き場を指定します。
options = beam.options.pipeline_options.PipelineOptions()
gcloud_options = options.view_as(
beam.options.pipeline_options.GoogleCloudOptions)
gcloud_options.job_name = 'dataflow-tutorial7'
... | hayatoy/dataflow-tutorial | tutorial7.py | tutorial7.py | py | 2,908 | python | ja | code | 25 | github-code | 36 |
70474642983 |
import torch
import torch.nn.functional as F
from .modules import Module, ModuleList, ModuleDict
from pytorch_transformers import BertModel, BertConfig,BertTokenizer
from .modules.prediction import registry as prediction
from .modules.prediction import Prediction_Bert,Prediction_Bert_GAT
from .modules.GCNS import *
i... | XuChen0427/Syntactic-Informed-Graph-Networks-for-Sentence-Matching | hetesrc/network.py | network.py | py | 7,773 | python | en | code | 3 | github-code | 36 |
70569498345 | from fastapi import status, HTTPException, Depends, APIRouter
from sqlalchemy.orm import Session
from .. import models, schemas, utils, oauth2
from ..database import get_db
from sqlalchemy import func, case
router = APIRouter(
prefix="/users",
tags=['Users']
)
@router.post("/", status_code=status.HTTP_201_CRE... | charl1ecloud/notebank-webapp | backend/app/routers/user.py | user.py | py | 2,505 | python | en | code | 0 | github-code | 36 |
70505801704 | from ast import AnnAssign
import numpy as np
def SetDuration():
duration_linguistic_dim = np.zeros(10, dtype=np.float64)
for ty in ["duration", "acoustic"]:
for phase in ["train", "test"]:
train = phase == "train"
x_dim = duration_linguistic_dim if ty == "duration" else acoustic_... | ABDULHANNANAYUBI/LSTM-Model-for-Speech-Syntheses | acoustic_feature.py | acoustic_feature.py | py | 1,079 | python | en | code | 1 | github-code | 36 |
36076656210 | from manimlib.imports import *
import numpy as np
class memoryDiagram(MovingCameraScene):
def construct(self):
self.introText()
def introText(self):
text = TextMobject("Let's talk about memory").set_color(YELLOW)
self.play(Write(text))
self.wait()
self.TransformText(te... | HeinHtutZaw19/manim | src/memory.py | memory.py | py | 8,950 | python | en | code | 0 | github-code | 36 |
34140743906 | import cv2
import numpy as np
from model import *
from scipy.spatial.distance import cosine
def read_pairs(path):
files = []
with open(path) as f:
files = f.readlines()
files = [afile[:-1].split(' ') for afile in files]
files = [[afile[0], afile[1], afile[2]=='1'] for afile in files]
... | Jasmineysj/Face-verification-system | test.py | test.py | py | 2,930 | python | en | code | 0 | github-code | 36 |
74050397224 | import parlai.core.build_data as build_data
import gzip
import os
import re
from parlai.core.build_data import DownloadableFile
from parlai.utils.io import PathManager
RESOURCES = [
DownloadableFile(
'http://opus.lingfil.uu.se/download.php?f=OpenSubtitles/en.tar.gz',
'OpenSubtitles.tar.gz',
... | facebookresearch/ParlAI | parlai/tasks/opensubtitles/build_2009.py | build_2009.py | py | 3,947 | python | en | code | 10,365 | github-code | 36 |
8540409344 | import sys
N = int(sys.stdin.readline())
count1 = 0
chess = [0]*15
def condition(i):
for j in range(i):
if(chess[i]==chess[j] or abs(chess[i]-chess[j])==(i-j)):
return False
return True
def dfs(cnt):
if(cnt==N):
global count1
count1 += 1
return
for i in ra... | namhyo01/algo_python | 9663.py | 9663.py | py | 431 | python | en | code | 0 | github-code | 36 |
14437408352 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 26 2022
@author: MotoWiZ
"""
#%%
import cv2
import time
import numpy as np
import math
from picamera2 import Picamera2
lower_white = (0, 0, 0)
upper_white = (0, 0, 255)
t = time.time()
prevBallPosX, prevBallPosY, ballPosX, ballPosY = 0, 0, 0, 0
# -> Configuration of R... | MotoWiZ/Balance-ball-on-a-table | Testers/ball - 360.py | ball - 360.py | py | 10,389 | python | en | code | 2 | github-code | 36 |
17981846568 | #!/usr/bin/python3
#trial using bash calls no html2text library
import requests
import subprocess # to execute bash commands
import time
try:
check_for_package = subprocess.Popen(("dpkg","-s","html2text"), stdout=subprocess.PIPE)
output = subprocess.check_output(("grep", "Status"), stdin=check_for_package.s... | technodict/Parcel_Tracking_CLI | tries/tracking_2.py | tracking_2.py | py | 1,091 | python | en | code | 2 | github-code | 36 |
2591751245 | from pg3d.shape import Shape
from pg3d.triangle import Triangle
class Tetrahedron(Shape):
def __init__(self, app, size=1, center=[0, 0, 0]):
super().__init__(app, size, center)
self._generate_shape()
def _generate_shape(self):
"""
Creates points and vertices of tetrahedron
... | poonchoi/3D-GRAPHICS-ENGINE | pg3d/tetrahedron.py | tetrahedron.py | py | 1,461 | python | en | code | 0 | github-code | 36 |
39095320319 |
# coding: utf-8
# In[12]:
import nltk, re, string
from sklearn.preprocessing import normalize
from nltk.corpus import stopwords
# numpy is the package for matrix cacluation
import numpy as np
# for lemma
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
wordnet_lemmatizer = WordNetLemmatizer... | vigneshsriram/Python-Tutorials | Multinomial Naive Bayes/Assignment5 (3).py | Assignment5 (3).py | py | 8,988 | python | en | code | 0 | github-code | 36 |
43302273184 | import sys
from rpython.rlib.debug import check_nonneg
from rpython.rlib.rsre.rsre_core import AbstractMatchContext, EndOfString
from rpython.rlib.rsre import rsre_char
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib import rutf8
class Utf8MatchContext(AbstractMatchContext):
"""A context ... | mozillazg/pypy | rpython/rlib/rsre/rsre_utf8.py | rsre_utf8.py | py | 3,532 | python | en | code | 430 | github-code | 36 |
25822088384 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def own_random(seed = 654321):
while True:
x = str(seed)
if len(x) != 6:
x = (6 - len(x)) * '0' + x
y = x[3:6] + x[0:3]
res = str(int(x)*int(y))
if len(res) != 12:
res = (12 - len(res)) * '0' + res
... | LiudaShevliuk/python | lab11_2.py | lab11_2.py | py | 430 | python | en | code | 0 | github-code | 36 |
70061753384 | #!/usr/bin/env python
# author: luo1fly
import time
import random
# import custom modules above
def select_sort(lst1):
lst = lst1[:]
# lst = lst1
for i in range(len(lst)):
minimum = i
for j in range(i+1, len(lst)):
if lst[j] < lst[minimum]:
minimum = j
... | luo1fly/algorithm_discussion | 选择排序.py | 选择排序.py | py | 729 | python | en | code | 0 | github-code | 36 |
12494927069 | def main():
DAYS_PER_YEAR = 365
HOURS_PER_DAY = 24
MIN_PER_HOUR = 60
SEC_PER_MIN = 60
print("There are " + str(DAYS_PER_YEAR*HOURS_PER_DAY*MIN_PER_HOUR*SEC_PER_MIN) + " seconds in a year!!")
if __name__ == "__main__":
main()
| sVadali03/Code-in-place-2021 | Worked examples (introduction to python)/seconds_per_year.py | seconds_per_year.py | py | 256 | python | en | code | 0 | github-code | 36 |
3289690742 | __all__ = ['display']
import logging
import sys
import types
from six import itervalues
logger = logging.getLogger('pyomo.core')
def display(obj, ostream=None):
""" Display data in a Pyomo object"""
if ostream is None:
ostream = sys.stdout
try:
display_fcn = obj.display
except Attri... | igorsowa9/vpp | venv/lib/python3.6/site-packages/pyomo/core/base/misc.py | misc.py | py | 7,746 | python | en | code | 3 | github-code | 36 |
1372282786 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author aliex-hrg
import sys,os,socketserver,json,hashlib
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from conf import settings
import admin,re
class MyTCPHandler(socketserver.BaseRequestHandler):
ftp_dir = setting... | hrghrghg/test | 作业/FTP文件服务器/server/core/core.py | core.py | py | 6,863 | python | en | code | 0 | github-code | 36 |
28227862886 | in_strng=input('enter a string')
in_strng=in_strng.casefold()
vowel="aeiou"
data={}.fromkeys(vowel,0)
for character in in_strng:
if character in vowel:
data[character]+=1
for vowel in data:
print(vowel,'=>',data[vowel])
| AkhilDevM/Python_programs | vowels.py | vowels.py | py | 291 | python | en | code | 0 | github-code | 36 |
75200594022 | # This file is a part of GrumpyWidgets.
# The source code contained in this file is licensed under the MIT license.
# See LICENSE.txt in the main project directory, for more information.
import re
from xml.etree import ElementTree
from htmlcompare import assert_same_html as assert_same_html_
__all__ = [
'as_nor... | FelixSchwarz/grumpywidgets | grumpywidgets/testhelpers.py | testhelpers.py | py | 2,672 | python | en | code | 0 | github-code | 36 |
9984869397 | from . import app
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Post(db.Model):
__tablename__ = 'posts'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer,
db.ForeignKey(
... | Last-Vega/Tabiluck | backend/models.py | models.py | py | 6,209 | python | en | code | 0 | github-code | 36 |
16403948991 | class Camera:
def __init__(self, marca, filmando=False):
self.marca = marca
self.filmando = filmando
def filmar(self):
if self.filmando:
return f'{self.marca} já está filmando.'
self.filmando = True
return f'{self.marca} agora está filmando...'
def... | Pimegonho/Python-Udemy | Aulas/A125_classes.py | A125_classes.py | py | 2,440 | python | en | code | 0 | github-code | 36 |
38451818612 | # aca desarrollaremos la parte de contar renglones y palabras
import logging
import logging.config
# abriendo archivo de configuración
logging.config.fileConfig('log_config_file.conf')
# creando el logger
logger = logging.getLogger('functions')
def count_words(file, nombre_path: str) -> any:
'''
Función que ... | Carlos-Montana/Act-tiimiit-alkemy | Act_4_logII/editorial/function.py | function.py | py | 868 | python | es | code | 0 | github-code | 36 |
8783270514 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : head node of linked list
# @return the head node in the linked list
def mergeTwoLists(self, A, B):
... | abhisoniks/interviewbit | LinkedList/mergeTwoSortedLL.py | mergeTwoSortedLL.py | py | 960 | python | en | code | 0 | github-code | 36 |
69901206826 |
#----------------------------------------------------------------------------
# Convenience class that behaves exactly like dict(), but allows accessing
# the keys and values using the attribute syntax, i.e., "mydict.key = value".
class EasyDict(dict):
def __init__(self, *args, **kwargs): super().__init__(*args, ... | danmcduff/characterizingBias | GAN_Code/train/config.py | config.py | py | 4,171 | python | en | code | 1 | github-code | 36 |
6655999686 | """Postgres Dataconn Connection Implementation"""
import glob
import sys
import os
from os import environ
from cml.data_v1.customconnection import CustomConnection
class PostgresCustomImp(CustomConnection):
"""Using https://pypi.python.org/pypi/postgres to connect to Postgres DBs"""
""" Print information on ... | pdefusco/Using_CustomConn_CML | postgresconn/pg-conn.py | pg-conn.py | py | 3,675 | python | en | code | 1 | github-code | 36 |
2959315606 | #%%
import pandas as pd
import numpy as np
import os
import re
import time
from functools import wraps, reduce
from copy import deepcopy
from sklearn.model_selection import train_test_split
#%%
project_dict_second = {
'01':'有源手术器械',
'02':'无源手术器械',
'03':'神经和心血管手术器械',
'04':'骨科手术器械',
'05':'耳鼻喉手术器械',
... | BigMasonFang/cfda | data_anly.py | data_anly.py | py | 7,677 | python | en | code | 0 | github-code | 36 |
34820762365 | #!/usr/bin/env pypy3
def test(l):
s = set()
for i, j in l:
if i == 1:
if j in s:
print('Failed')
else:
s.add(j)
print('Succeeded')
else:
if j in s:
s.remove(j)
print('Succeeded')... | easily44/training_camp | algorithm_day2/box.py | box.py | py | 528 | python | en | code | 0 | github-code | 36 |
28440224865 | import os
def append_text(path, text):
"""this function creates an sequence diagram instead of four diagrams files
:param path: the path where the file is
:type path: string
:param text: the output of each test method
:type text: string
"""
with path.open("a") as f:
f.write(text)
... | manu2492/14-unidades-de-2-hasta-14 | unidad_10_y_11/exercise/assets/text_append.py | text_append.py | py | 426 | python | en | code | 0 | github-code | 36 |
1486053711 | #! /usr/bin/env python
import rospy
import actionlib
import behavior_common.msg
import time
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
from geometry_msgs.msg import Twist
from math import radians, degrees
import tf
import os, thread
# for talking
# import actionlib
import actionlib.action... | shinselrobots/tb2s | tb2s_behaviors/follow_behavior/scripts/behavior_service.py | behavior_service.py | py | 21,227 | python | en | code | 2 | github-code | 36 |
13890870450 | """
Background
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
**TODO: Can use a stack**
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Pre... | orangered233/LeetCode | recover_binary_search_tree.py | recover_binary_search_tree.py | py | 4,358 | python | en | code | 0 | github-code | 36 |
15218662355 | """Write favourites in a Richard-friendly csv format"""
import re
from consts import BOOKINGS_FILE, RATINGS_FILE, UNRATED, UNRATED_FILE, FAVOURITES_CSV
def get_link_ratings():
"""Get show ratings"""
ratings = {}
with open(RATINGS_FILE, mode='r', encoding='windows-1252') as csv:
lineno = 0
... | richardl62/fringe-favourites | scripts/csv_utils.py | csv_utils.py | py | 3,697 | python | en | code | 0 | github-code | 36 |
72223824745 | import requests
url = input("Enter the website URL: ")
# SQL injection test payload
payload = "' OR '1'='1"
# XSS test payload
xss_payload = "<script>alert('XSS')</script>"
# Add payload to the login form
data = {"username": "admin", "password": payload}
# Send the request
r = requests.post(url, data=data)
# Chec... | TheSyrox/SYVulnScan | VULNSCAN.py | VULNSCAN.py | py | 958 | python | en | code | 0 | github-code | 36 |
21619030471 | from __future__ import absolute_import
import errno
import io
import logging
import multiprocessing
import re
import sys
import threading
import time
import traceback
from builtins import object
from apache_beam.internal.http_client import get_new_http
from apache_beam.io.filesystemio import Downloader
from apache_be... | a0x8o/kafka | sdks/python/apache_beam/io/gcp/gcsio.py | gcsio.py | py | 22,338 | python | en | code | 59 | github-code | 36 |
2412653803 | import pytest
import elasticsearch_dsl as es_dsl
from karp5.domain.services import search_service
from karp5.config import conf_mgr
@pytest.mark.parametrize("from_,size", [
(0, 25),
(1000, 25),
(10000, 25),
(0, None),
(15000, 15875)
])
def test_large_lex(app_w_large_lex, from_, size):
mode =... | spraakbanken/karp-backend-v5 | karp5/tests/integration_tests/domain/services/test_search_service_it.py | test_search_service_it.py | py | 887 | python | en | code | 4 | github-code | 36 |
23604207590 | import argparse
import logging
import subprocess
import sys
import stanza
from iso639 import languages
sys.path.append('./resources')
import unimorph_inflect
def download_unimorph(lg: str):
logging.info("downloading UniMorph dictionary for %s" % lg)
subprocess.run("mkdir -p unimorph_dicts", shell=True)
... | murali1996/morpheus_multilingual | run_setup.py | run_setup.py | py | 1,835 | python | en | code | 0 | github-code | 36 |
41344227496 | from sys import argv
from cs50 import get_string
def main():
"""Main Method"""
if len(argv) != 2:
print("Number of supplied arguments is illegal")
exit(1)
key = argv[1]
if not key.isalpha():
print("Key contains characters that aren't letters")
exit(1)
plaintext = ge... | chiptus/cs50x-solutions | pset6/crypt/vigenere/vigenere.py | vigenere.py | py | 1,358 | python | en | code | 0 | github-code | 36 |
71941186663 | """
Zig Zag Conversion
example 1:
Input: s = "PAYPALISHIRING", numRows = 3
P A H N
A P L S I I G
Y I R
Output: "PAHNAPLSIIGYIR"
example 2:
Input: s = "PAYPALISHIRING", numRows = 4
P I N
A L S I G
Y A H R
P I
Output: "PINALSIGYAHRPI"
On
"""
class Solu... | aLucaz/crack-the-coding | leetcode/6.py | 6.py | py | 1,063 | 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.