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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
37220401007 | import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import utils
from TGATlayer import TGATlayer
class TGATML(nn.Module):
def __init__(self, adjm, node_feats,in_dim=1,out_dim=24, residual_channels=2,dilation_channels=2, end_channels=2*10, layers=5, reg_param=0):
super().__init__()
... | shiql/TGAT-ML | TGATML.py | TGATML.py | py | 4,454 | python | en | code | 0 | github-code | 36 |
28440071535 | import pandas as pd
import os
from datetime import datetime
from sqlalchemy import create_engine
from load_data import load_data
from transform_data import transform_data
from config import DB_NAME,PASSWORD,USER
def insert_data_incremental(df_to_upload, table_name):
"""
Inserts data from a DataFrame into a Pos... | manu2492/Data-Transformation-Pipeline-Analyzing-and-Enriching-Trip-Data | etl/update_database.py | update_database.py | py | 4,029 | python | en | code | 0 | github-code | 36 |
31929838287 | import re
from collections import defaultdict
class ReviewSentence():
def __init__(self, line):
self.sentiment = line[:3]
self.text = line[4:]
class Review():
def __init__(self, header):
self.header = header
a, b, c = header.split("_")
self.review_category = a
self.review_sentiment = b
self.sentences ... | hmdavis/NLP-project-2 | NLP-project-3/parsers.py | parsers.py | py | 2,192 | python | en | code | 0 | github-code | 36 |
2515527479 | import sqlite3
connection = sqlite3.connect("rpg_db.sqlite3")
connection.row_factory = sqlite3.Row
curs = connection.cursor()
# 1). How many total Characters are there
total_characters = """
SELECT COUNT(*) FROM charactercreator_character;
"""
results = curs.execute(total_characters).fetchall()
print("total Characte... | Edudeiko/DS-Unit-3-Sprint-2-SQL-and-Databases | module1-introduction-to-sql/321_assignment.py | 321_assignment.py | py | 3,321 | python | en | code | null | github-code | 36 |
71073486183 | #!/usr/bin/env python3
import argparse
import logging
import pathlib
import time
import signal
import shutil
import numpy as np
import yaml
import tensorboardX
import torch
import torch.utils.data
import utils
from tasks.arithmetic import Arithmetic
from models.lstm import LSTM
from models.ntm import NTM
from models... | dasimagin/ksenia | train_arithmetic.py | train_arithmetic.py | py | 10,912 | python | en | code | 3 | github-code | 36 |
15791070220 | import Preprocessing as pre
from Classifiers import accuracy, RandomForestClassifier, confusion_matrix
import time
import h5py
import numpy as np
import argparse
import joblib
def RFClassifier(X_train, y_train, X_val, y_val, n_trees, tree_depth, split_metric, name, jobs):
clf = RandomForestClassifier(n_trees=n_tr... | samedwardsFM/Next-level-random-forest-from-scratch | Final_run.py | Final_run.py | py | 2,841 | python | en | code | 0 | github-code | 36 |
71578930343 | import vtk
def main():
colors = vtk.vtkNamedColors()
# create a sphere
sphere = vtk.vtkSphere()
sphere.SetRadius(1)
sphere.SetCenter(1, 0, 0)
# create a box
box = vtk.vtkBox()
box.SetBounds(-1, 1, -1, 1, -1, 1)
# combine the two implicit functions
boolean = vtk.vtkImplicitBo... | lorensen/VTKExamples | src/Python/ImplicitFunctions/Boolean.py | Boolean.py | py | 2,132 | python | en | code | 319 | github-code | 36 |
69928483943 | print('Loading...')
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator, MultipleLocator, AutoMinorLocator
from matplotlib.axes import Axes
import pandas as pd
import numpy as np
import time
import math
import seaborn as sns
from IPython.display import clear_output, display, IFrame
from chord imp... | Err0neus/Santos-Discography-Analyser | functions/UI.py | UI.py | py | 80,024 | python | en | code | 8 | github-code | 36 |
37716835129 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='EventCategory',
fields=[
... | vinsmokemau/Eventstarter | events/migrations/0002_auto_20151014_0134.py | 0002_auto_20151014_0134.py | py | 833 | python | en | code | 0 | github-code | 36 |
1816722 | def read_simple_graph(vertex_number, edge_number):
graph = [[0] * vertex_number for i in range(vertex_number)]
for j in range(edge_number):
l1, l2 = list(map(int, input().split()))
graph[l1][l2] = 1
return graph
v, e = list(map(int, input().split()))
my_graph = read_simple_graph(v, ... | andrewsonin/4sem_fin_test | _05_in_and_out_vertex_power.py | _05_in_and_out_vertex_power.py | py | 491 | python | en | code | 0 | github-code | 36 |
8910512833 | import math
import numpy as np
# класс подсчета интеграла
class Integral(object):
# конструктор принимает на вход пределы интегрирования, функцию или таблицу xi
def __init__(self, a, b, func=None, x_data=None, y_data=None):
self.a = a
self.b = b
if func is not None:
self.fu... | lubarog13/codes | Python_codes/laba4_newton.py | laba4_newton.py | py | 3,233 | python | ru | code | 1 | github-code | 36 |
11814225329 | import sqlite3
from sqlite3 import Error
from datetime import date
class PatientDataStore():
"""
Stores patient information in sqlite3 database
"""
__instance = None
@staticmethod
def getInstance():
"""
This is a static method to create class as a singleton
"""
... | Rumone/ai-project | patient_data_store.py | patient_data_store.py | py | 2,314 | python | en | code | 0 | github-code | 36 |
26469573974 | import codecs
import hashlib
import base58
from bitcoinaddress.util import checksum
from bitcoinaddress import Wallet
from bitcoinutils.keys import PrivateKey
from bitcoinutils.setup import setup
import ecdsa
from ecdsa.curves import SECP256k1
from ecdsa.util import sigencode_der_canonize
from .base import BaseKey
... | ProtoconNet/mitum-py-util | src/mitumc/key/keypair.py | keypair.py | py | 2,852 | python | en | code | 2 | github-code | 36 |
494837227 | from dagster_graphql.test.utils import execute_dagster_graphql
from dagster.core.instance import DagsterInstance
from .utils import define_test_context, sync_execute_get_run_log_data
COMPUTE_LOGS_QUERY = '''
query ComputeLogsQuery($runId: ID!, $stepKey: String!) {
pipelineRunOrError(runId: $runId) {
... ... | helloworld/continuous-dagster | deploy/dagster_modules/dagster-graphql/dagster_graphql_tests/graphql/test_compute_logs.py | test_compute_logs.py | py | 1,983 | python | en | code | 2 | github-code | 36 |
19793018115 | # -*- coding: utf-8 -*-
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.externals.six import StringIO
from IPython.display import Image
from sklearn.tree import export_graphviz
import... | oykuandac/Entropy-Gini-Indexes-Prediction | exercise.py | exercise.py | py | 5,568 | python | en | code | 0 | github-code | 36 |
35382380564 | #!/usr/bin/env python3
from sys import stderr, exit
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
from hanoi_lib import ConfigGenerator, HanoiTowerProblem
from utils_lang import get_formatted_move
# METADATA OF THIS TAL_SERVICE:
args_list = [
('v',str),
('start',str),
('f... | romeorizzi/TALight | example_problems/tutorial/hanoi/services/check_opt_num_moves_driver.py | check_opt_num_moves_driver.py | py | 4,961 | python | en | code | 11 | github-code | 36 |
28155913391 | # https://www.hackerrank.com/challenges/merge-the-tools/problem
if __name__ == '__main__':
s = 'AABCAAADA'
k = 3
assert len(s) % k == 0, "The length of s must me dividable by k"
substrings = [set(s[i*k:k*(i+1)]) for i in range(0, k)]
for substr in substrings:
print("".join(list(substr)))
... | DShaience/code_katas | interview_questions/merge_the_tools.py | merge_the_tools.py | py | 325 | python | en | code | 1 | github-code | 36 |
15370165912 | import pytest
import sqlalchemy as sa
import sqlalchemy.orm
import jessiql.sainfo.version
from apiens.tools.sqlalchemy.session.session_tracking import TrackingSessionMaker, TrackingSessionCls
@pytest.mark.xfail(jessiql.sainfo.version.SA_13, reason='Session() is not a context manager in SA 1.3', )
def test_tracking_s... | kolypto/py-apiens | tests/tools_sqlalchemy/test_session_tracking.py | test_session_tracking.py | py | 1,330 | python | en | code | 1 | github-code | 36 |
12151473251 | import numpy as np
import math
import random
import matplotlib.pyplot as plt
NUM_DIMENSIONS = 10
NUM_PARTICLES = 50
MAX_ITERATIONS = 100
INERTIA_WEIGHT = 0.729
COGNITIVE_WEIGHT = 1.49445
SOCIAL_WEIGHT = 1.49445
MIN_POSITION = -5.12
MAX_POSITION = 5.12
def f1(position: np.ndarray):
fitness = np.sum(position**2 - 1... | dvher/AlgoritmosExactosMetaheuristica | Tarea3/main.py | main.py | py | 3,848 | python | en | code | 0 | github-code | 36 |
36287589774 | from django.shortcuts import render, redirect, HttpResponse
from . import functions
# Create your views here.
# 真正的登录在home函数中
def login(request):
if request.session.get('is_login', None): # 将登录信息保存到session中实现重复调用
return redirect('/home/')
return render(request, 'login.html', {'error': False}) # 将err... | Spetrichor/database_project | app01/views.py | views.py | py | 9,068 | python | en | code | 1 | github-code | 36 |
5353044388 | import pandas as pd
import ipywidgets as widgets
from ipylabel.templates import Table
class ImageDashboard():
'''
Abstract dashboard class for image data.
'''
def __init__(self, images, format='png'):
if format not in ['png', 'jpg']:
raise ValueError('Format must be either png... | crabtr26/ipylabel | ipylabel/Dashboards.py | Dashboards.py | py | 1,704 | python | en | code | 0 | github-code | 36 |
37584223577 | import numpy as np
import plotly.offline as py
import plotly.graph_objs as go
import pandas as pd
data = pd.read_csv("../data/training_data.csv")
# print(data.head())
X = data.values[:,0]
Y = np.array([])
np.percentile(X, [25,50,75])
nd=pd.qcut(X,3, labels=[0,1,2])
nd2=pd.qcut(X,3, labels=["close","not close","far"])... | lmEshoo/sensors-anomoly-detection | src/cluster_percentile.py | cluster_percentile.py | py | 1,157 | python | en | code | 1 | github-code | 36 |
42406705027 | """A matrix is a collection of scalar values arranged in rows and columns as a rectan-
gular grid of a fixed size. The elements of the matrix can be accessed by specifying
a given row and column index with indices starting at 0.
"""
from typing import Any
from py_ds.arrays.array import Array
from py_ds.arrays.array2d ... | jurajzachar/py-ds | py_ds/arrays/matrix.py | matrix.py | py | 6,832 | python | en | code | 0 | github-code | 36 |
34980787774 | #!/usr/bin/env python3
N, K, *a = map(int, open(0).read().split())
if 0 in a:
exit(print(N))
if K == 0:
exit(print(0))
left, total, ans = 0, 1, 0
for right in range(N):
total *= a[right]
while total > K:
total //= a[left]
left += 1
ans = max(ans, right - left + 1)
print(ans) | mpses/AtCoder | Contest/ABC032/c/main.py | main.py | py | 311 | python | en | code | 0 | github-code | 36 |
34899584843 |
from calendar import weekday
class Employee():
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@gmail.com'
Employee.num_of_emps +=1
d... | sangramdhurve/Oops_python | Working with Classes.py | Working with Classes.py | py | 1,530 | python | en | code | 0 | github-code | 36 |
23676310187 | import numpy as np
import cortecx.construction.cxsession as cxsession
class HELP:
def __init__(self):
self.pos_codes = {
'CC': 'Coordinating Conjunction',
'CD': 'Cardinal number',
'DT': 'Determiner',
'EX': 'Existential "there"',
'FW': 'Foreign W... | Lleyton-Ariton/Cortecx-Public | cortecx/construction/tools.py | tools.py | py | 13,109 | python | en | code | 0 | github-code | 36 |
16560146527 | """empty message
Revision ID: da088c937095
Revises: ecc7f6cfc777
Create Date: 2022-08-02 16:55:48.199125
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'da088c937095'
down_revision = 'ecc7f6cfc777'
branch_labels = None
depends_on = None
def upgrade():
# ... | nukano0522/flask_apps | image_detection/migrations/versions/da088c937095_.py | da088c937095_.py | py | 685 | python | en | code | 1 | github-code | 36 |
9092725521 | import helpers
import numpy as onp
import enum
class Methods(enum.Enum):
Sturm = enum.auto()
SturmOriginal = enum.auto()
FactorGraph = enum.auto()
FactorGraphGT = enum.auto()
number_samples = 50
parameter_set_rot = {
"stddev_pos": onp.array([0.001, 0.03, 0.1]),
"stddev_ori": onp.array([1.0,... | SuperN1ck/cat-ind-fg | only_poses/run_all.py | run_all.py | py | 2,174 | python | en | code | 9 | github-code | 36 |
71854821865 | import unittest
from instream.setup_env import setup
from instream import env
class BaseTestCase(unittest.TestCase):
settings = {
'mongo_url': 'mongodb://localhost:27017/instream',
'redis_url': 'redis://@localhost:6379/9',
'celery': {
'BROKER_URL': 'redis://localhost/9',
... | CooperLuan/instream | src/instream/testing.py | testing.py | py | 1,078 | python | en | code | 0 | github-code | 36 |
17887209605 | from pdb import Pdb
class Powerdb(Pdb):
def precmd(self, line):
if not isinstance(line, str): return line
return super().precmd(line)
def onecmd(self, line):
self.prompt = '--> '
# print('line:', line)
if line == ':r':
self.message('%-15s' % '[Step Out....]... | pyminer/pyminer | pyminer/utils/debug/pdbtest.py | pdbtest.py | py | 3,956 | python | en | code | 77 | github-code | 36 |
28878097846 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
#TC O(n)
#SC O(1)
if s is None or len(s) == 0:
return 0
maps = {}
slw = 0
maxs = float(-inf)
for i in range(len(s)):
if s[i] in maps:
pos = map... | saman-akhtar/Strings-1 | lngSub.py | lngSub.py | py | 475 | python | en | code | null | github-code | 36 |
18567481088 | from upwardmobility.items import UpwardMobilityItem
from upwardmobility.loaders import CompanyLoader
from upwardmobility.utils import *
class NcIrrigationContractorsLicensingBoardSpider(scrapy.Spider):
name = 'nc_irrigation_contractors_licensing_board'
allowed_domains = ['myaccount.nciclb.org']
start_urls... | mscandale-iabbb/research_public | upwardmobility/spiders/nc_irrigation_contractors_licensing_board.py | nc_irrigation_contractors_licensing_board.py | py | 2,920 | python | en | code | 0 | github-code | 36 |
33434928097 | from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
import os
def get_file(fpath):
if os.path.isfile(fpath):
return open(fpath, 'rb').read()
else:
return None
# 显示图片
@require_http_methods(["GET"])
def show_image(request):
pic_addr = str(requ... | XuYiFanHHH/QingXian_Back-end | QingXian/views.py | views.py | py | 489 | python | en | code | 0 | github-code | 36 |
21955928918 | from RepSys import Error, config, layout
from RepSys.svn import SVN
from RepSys.util import execcmd
from RepSys.util import get_output_exec
from io import StringIO
import sys
import os
import os.path
import re
import time
import locale
import glob
import tempfile
import shutil
import subprocess
locale.setlocale(loc... | DrakXtools/repsys | RepSys/log.py | log.py | py | 27,147 | python | en | code | 3 | github-code | 36 |
30389517296 | import os
import sys
import pytest
from logpyle import LogManager, LogQuantity
# {{{ mpi test infrastructure
def run_test_with_mpi(num_ranks, f, *args, extra_env_vars=None):
pytest.importorskip("mpi4py")
if extra_env_vars is None:
extra_env_vars = {}
from base64 import b64encode
from pick... | illinois-ceesd/logpyle | test/test_distributed.py | test_distributed.py | py | 3,200 | python | en | code | 4 | github-code | 36 |
14656471260 | import requests
import json
import logging
import os
import time
import uuid
from collections import Counter
API_URL = os.environ.get('API_URL') or 'https://api.gooee.io'
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
# Sentry Setup
SENTRY_ENVIRONMENT = 'TMPL_SENTRY_ENVIRONMENT'
SENTRY_RELEASE = 'TMPL_SEN... | GooeeIOT/cloud-alexa-control-lambda | lambda_function.py | lambda_function.py | py | 16,236 | python | en | code | 0 | github-code | 36 |
5546998859 | from brownie import interface
from utils.voting import create_vote
from utils.config import (lido_dao_voting_address,
lido_dao_token_manager_address,
lido_dao_node_operators_registry,
get_deployer_account)
from utils.evm_script import encode... | lidofinance/scripts | archive/scripts/set_node_operators_limit.py | set_node_operators_limit.py | py | 1,967 | python | en | code | 14 | github-code | 36 |
18934606840 | from django import template
from django.conf import settings
from wagtail.images.models import SourceImageIOError
from wagtail.images.templatetags.wagtailimages_tags import ImageNode
from django.utils.safestring import mark_safe
from common.templatetags.string_utils import uid
register = template.Library()
@register... | IATI/IATI-Standard-Website | common/templatetags/responsive.py | responsive.py | py | 9,878 | python | en | code | 5 | github-code | 36 |
22564560157 | class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
ans = [0] * len(temperatures)
stack = []
for idx , tmp in enumerate(temperatures):
while stack and tmp > stack[-1][0]:
stacktmp , stackidx = stack.pop()
an... | miedan/competetive-programming | 0739-daily-temperatures/0739-daily-temperatures.py | 0739-daily-temperatures.py | py | 425 | python | en | code | 0 | github-code | 36 |
21735015266 | import os
import random
import cv2
from ultralytics import YOLO
from tracker import Tracker
import numpy as np
import copy
from frame import Frame
def Analyser():
video_path = os.path.join(os.getcwd(), 'assets', 'people.mp4')
video_out_path = os.path.join(os.getcwd(), 'assets', 'people_out.mp4')
... | KushJoshi16/CrowdInflowOutflow | VideoAnalyser.py | VideoAnalyser.py | py | 2,949 | python | en | code | 0 | github-code | 36 |
15737275688 | import fnmatch
from ftplib import FTP
import ftplib
import io
import os
import requests
from tqdm import tqdm
import os
import time
import gzip
import xml.etree.ElementTree as ET
import csv
directory = "D:/gg/"
filenames = os.listdir(directory)
print(filenames)
ftp_server = ftplib.FTP("ftp.ncbi.nlm.nih.gov", "anonymou... | wanhoyinjoshua/authorship | nftp.py | nftp.py | py | 1,596 | python | en | code | 0 | github-code | 36 |
15883229551 | import time
import random
import json
import hashlib
import requests
import mysql.connector as mc
from mysql.connector import Error as mce
import sys
my_key='your key from API'
my_secret='your secret from API'
rand_prefix = str(random.randint(100000,999999))
now = str(int(time.time()))
method_name = 'problemset.proble... | ineed-coffee/CAC-Code-Forces-Algorithm-Classifier- | make_db.py | make_db.py | py | 1,915 | python | en | code | 0 | github-code | 36 |
74518816744 | # -*- coding: utf-8 -*-
#!/usr/bin/python3
from mitmproxy.options import Options
from mitmproxy.proxy.config import ProxyConfig
from mitmproxy.proxy.server import ProxyServer
from mitmproxy.tools.dump import DumpMaster
import argparse
GOOGLE_URL = 'googleapis.com'
class Addon(object):
def __init__(self, token)... | ThibaultLengagne/gta | start_mitm_proxy.py | start_mitm_proxy.py | py | 1,655 | python | en | code | 0 | github-code | 36 |
33532061373 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to automatically export the graffle files to PDF files.
Install this module first:
python3 -m pip install --user omnigraffle_export
And open the relevant document in Omnigraffle's GUI before running.
"""
# Built-in modules #
# First party modules #
fro... | xapple/cbmcfs3_runner | docs/others/auto_export.py | auto_export.py | py | 1,045 | python | en | code | 2 | github-code | 36 |
12445974610 | from django.http import HttpResponse
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import status
from rest_framework.decorators import api_view
from django.views.decorators.csrf import csrf_exempt
from djangoTest import settings
from oAuth.models import User, OauthStockDat... | lff12876/DjangoWeb2023 | oAuth/views.py | views.py | py | 31,531 | python | en | code | 0 | github-code | 36 |
1934215882 | import pandas as pd
import matplotlib.pyplot as plt
Data_Raw = pd.read_csv('iris.data',sep=',',header=-1)
Unique_Label = pd.unique(Data_Raw.values[:,4])
NUmeric_Label = Data_Raw[4].apply(list(Unique_Label).index)
count = 0
colors = ['red','green','blue','purple']
for i in Unique_Label:
Temp = Data_Raw... | melikaknight/Iris-Dataset | P4c.py | P4c.py | py | 513 | python | en | code | 0 | github-code | 36 |
69931719143 | """
Tic Tac Toe
A classic Python game of X's and O's.
"""
import random
# Function that will draw the game's board
def makeBoard(board):
print(end='\n')
print(' | | ')
print(' ' + board[7] + ' ' + ' | ' + ' ' +
board[8] + ' ' + ' | ' + ' ' + board... | guyromellemagayano/simple-python-programs | tictactoe.py | tictactoe.py | py | 6,561 | python | en | code | 0 | github-code | 36 |
13463415841 | import os
import gc
import dill
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning)
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold
from sklearn.multioutput import MultiOutputRegressor
import lightgbm as lgb
f... | romden/kaggle | 2022_09_single-cell-integration/train_lgb_cite.py | train_lgb_cite.py | py | 4,566 | python | en | code | 0 | github-code | 36 |
27501697384 | from datetime import datetime
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
with DAG(dag_id="airtable-download",
start_date=datetime(2021, 11, 1),
concurrency=1) as dag:
download_time_tracker_base = DummyOperator(task_id="download-time-tracker-base",
... | ktechboston/kt-public-dags | dags/airtable-example/airtable-download.py | airtable-download.py | py | 908 | python | en | code | 0 | github-code | 36 |
74872310504 | import pandas as pd
import plotly.figure_factory as pf
import statistics
data = pd.read_csv('./height-weight.csv')
heigth = data['Height(Inches)'].tolist()
mean = statistics.mean(heigth)
median = statistics.median(heigth)
mode = statistics.mode(heigth)
stan = statistics.stdev(heigth)
# caluculating per... | KARNAMROOPESH/Python13 | distribution.py | distribution.py | py | 2,204 | python | en | code | 0 | github-code | 36 |
2675757260 | #1.Write a Python program to check if a number is positive, negative or zero.
n=int(input('Enter the Number :'))
if (n>0):
print('Number Is Positive')
elif (n==0):
print ('Number Is Zero')
else:
print('Number Is Negitive')
#2.Write a Python program to get the Factorial number of given number.
n=int(... | Savankalavadiya/Python-Practice- | Moduel/Module – 2.py | Module – 2.py | py | 5,354 | python | en | code | 0 | github-code | 36 |
31881700577 | from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('a_home.urls')),
path('about/', include('a_home.urls')),
path('portfolio/', include('a_por... | V0lodimirV/Flower_site | a_configuration/a_configuration/urls.py | urls.py | py | 1,307 | python | ru | code | 0 | github-code | 36 |
18252476641 | def merge(nums, low, mid, high):
temp = nums[:]
i = low
j = mid + 1
for p in range(low, high+1):
if i == mid + 1:
# left is done
nums[p] = temp[j]
j += 1
elif j == high + 1:
# right is done
nums[p] = temp[i]
i += 1
... | hujienan/Jet-Algorithm | general/Merge Sort/index.py | index.py | py | 833 | python | en | code | 0 | github-code | 36 |
3207468200 | from __future__ import annotations
import re
from typing import Any, Callable, NamedTuple
def parse(rows: list[str]) -> Board:
width = max(len(row) for row in rows)
board_rows = [" " * (width + 2)]
for index in range(len(rows) - 2):
row = rows[index]
board_rows.append(f" {row}" + " " * (wi... | heijp06/AoC-2022 | day22/board.py | board.py | py | 10,253 | python | en | code | 0 | github-code | 36 |
5197882492 | import mydb, global_v, SendMessage
from Node import Node
from Message import message
def getPathFromRoot(node):
path = []
index=node.index
while (index!=0):
path.append(index)
index=index/2
path.reverse()
return path
# find path in one tree, using index in... | spike1390/treeNet | models/PathFinder.py | PathFinder.py | py | 6,992 | python | en | code | 0 | github-code | 36 |
11783204177 | #######################
# Imports
#######################
from pandas.tseries.offsets import DateOffset
import streamlit as st
import plotly.graph_objects as go
import plotly.io as pio
from pmdarima import auto_arima
import numpy as np
pio.renderers.default = 'browser'
import pandas as pd
from sqlalchemy i... | EkaterinaTerentyeva/Streamlit | streamlit_app.py | streamlit_app.py | py | 11,082 | python | en | code | 1 | github-code | 36 |
13498558067 | import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install speechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
import cv2
from time import ctime
import time
from requests import get
import sys
import pywhatkit as kit
from googletrans... | ruchiparmar7/jarvis | jarvis.py | jarvis.py | py | 32,964 | python | en | code | 2 | github-code | 36 |
20077778899 | from flask_restx import Resource, reqparse
from api.models.tag import TagModel, TagService, NoteTagModel
from api.utilities.auth import user_has_permission
from api.utilities.note import check_if_note_exists
from api import api
from flask_jwt_extended import get_jwt_identity, jwt_required
# Parsers
post_parser = reqpa... | Tomasz-Zdeb/Software-Engineering-Class-Project | API/api/routes/tag.py | tag.py | py | 7,429 | python | en | code | 0 | github-code | 36 |
1792969204 | import unicurses
import numpy as np
import math
stdscr = unicurses.initscr()
unicurses.cbreak()
unicurses.noecho()
unicurses.curs_set(0)
unicurses.keypad(stdscr, True)
LINES, COLS = unicurses.getmaxyx(stdscr)
samples = list()
dataPath = 'data\\sin440.bin'
#dataPath = 'c:\\users\\aaron_000\\desktop\\whistle, talk.bin... | AaronLieberman/ArduinoTinkering | FFTTest/FFTTest.py | FFTTest.py | py | 3,948 | python | en | code | 0 | github-code | 36 |
27472478696 | from time import sleep
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.mail.message import EmailMultiAlternatives
from django.core.management.base import BaseCommand
from django.core.validators import validate_email
class Command(BaseCommand):
help = 'Send ema... | DariuszAniszewski/codepot-heroku-workshop | codepot/management/commands/send_email.py | send_email.py | py | 1,511 | python | en | code | 1 | github-code | 36 |
71480593704 | from dotenv import load_dotenv
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from kafka import KafkaProducer
import os
load_dotenv()
access_token = os.environ.get('ACCESS_TOKEN')
access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET')
consumer_key = os.envir... | luciferreeves/KafkaPySpark | producer.py | producer.py | py | 1,350 | python | en | code | 2 | github-code | 36 |
22209550187 | # -*- coding: utf-8 -*-
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in... | terual/sbcc | module/setup.py | setup.py | py | 3,921 | python | en | code | 2 | github-code | 36 |
17170919170 | from models.bag import Bag
from models.card import Card
from models.player import create_player
def is_continue_game(players):
for item in players:
if not (item.is_winner is None):
return False
return True
bag = Bag(90)
players_count = int(input('Введите количество игроков: '))
players ... | WZRD9000/hw9-11 | game.py | game.py | py | 1,559 | python | en | code | 0 | github-code | 36 |
37362855405 | import PAsearchSites
import PAgenres
def search(results,encodedTitle,title,searchTitle,siteNum,lang,searchByDateActor,searchDate,searchAll,searchSiteID):
searchResults = HTML.ElementFromURL(PAsearchSites.getSearchSearchURL(siteNum) + encodedTitle)
for searchResult in searchResults.xpath('//p[contains(@class,"ca... | PhoenixPlexCode/PhoenixAdult.bundle | Contents/Code/siteRealityKings.py | siteRealityKings.py | py | 5,768 | python | en | code | 102 | github-code | 36 |
74946708904 | '''
Quesiton link: https://leetcode.com/problems/consecutive-characters/
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
'''
class Solution:
def maxPower(self, s: str) -> int:
if len(s) == ... | BhatnagarKshitij/Algorithms | Leetcode/consecutiveLetters.py | consecutiveLetters.py | py | 645 | python | en | code | 2 | github-code | 36 |
28418729236 | # Implementation of Selenium WebDriver with Python using PyTest
import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import sys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Ke... | syedsair/rateer-automated-tests | UI/signup.py | signup.py | py | 2,374 | python | en | code | 0 | github-code | 36 |
257245513 | import sys
class Node:
def __init__(self, value):
self.value = value
self.childs = []
def add_child(self, child):
self.childs.append(child)
def findLongestPath(node, depth):
if len(node.childs) == 0: # Return la longeur quand on arrive a une feuille de l'arbre
return depth
maxDepth = 0
... | SlicedPotatoes/France_IOI | Niveau 4/2 – Arbres/2 - Longueur des descriptions.py | 2 - Longueur des descriptions.py | py | 917 | python | fr | code | 0 | github-code | 36 |
19205484622 | import numpy as np
from numericalMethods import derivative, RK4, initialValueSolution
import unittest
class TestDerivative(unittest.TestCase):
def test_simple(self):
f = lambda x: np.sin(x)
xvals = np.linspace(0, 2*np.pi, 1000)
solution = np.cos(xvals)
returnValue = [derivative(f,... | BH4/NumericalGR | nm_test.py | nm_test.py | py | 2,180 | python | en | code | 1 | github-code | 36 |
5495119517 | import os
import sys
import socket
host = "127.0.0.1"
port = 23333
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
msg_L = ["this is client"]
msg = msg_L.extend(sys.argv[1:])
sock.connect((host,port))
print("+ Connected {}:{}!".format(host,port))
for msg in msg_L:
sock.send(msg.encode())
print(sock.r... | Hansimov/SciAniLab | data-vis/bili-comment/tests/test_socket_client.py | test_socket_client.py | py | 353 | python | en | code | 9 | github-code | 36 |
28508615427 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
import os
from shutil import rmtree
from numpy import ma
from numpy import array, sum
from opus_core.logger import logger
from opus_core.tes... | psrc/urbansim | biocomplexity/tests/expected_data_test.py | expected_data_test.py | py | 5,079 | python | en | code | 4 | github-code | 36 |
40152665258 | """Edit a 'rotomap' series of images.
In all modes:
Press 'q' to quit.
Press 'Q' to quit with exit code 1.
Press left for previous image, right for next image.
Press up for previous map, down for next map.
Ctrl-click on a point to zoom in on it.
Press 'z' or 'x' to adjust the zoom level.
P... | aevri/mel | mel/cmd/rotomapedit.py | rotomapedit.py | py | 22,318 | python | en | code | 8 | github-code | 36 |
981587259 | import argparse
import math
def main():
args = parse_args()
decompile_pattern(args.input, args.output)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('input', type=argparse.FileType('rb'), help='input pattern file')
parser.add_argument('output', type=argpars... | hjbyt/OS_HW5 | decompile_pattern.py | decompile_pattern.py | py | 1,149 | python | en | code | 0 | github-code | 36 |
38907595908 | stream = None
with open("data/day6.txt") as f:
stream = f.readline().strip("\n")
buffer = list(stream[:14]) # Hold the 14 latest characters (oldest to newest)
message_start_index = 13
for c in stream[14:]:
message_start_index += 1
buffer.pop(0) # Remove the oldest character
buffer.append(c) # Add the ... | 02rasjac/aoc22 | day6.py | day6.py | py | 443 | python | en | code | 0 | github-code | 36 |
8138351177 | '''
IP_splitter
Hrólfur Gylfason
1/11/2018
'''
def buaTilPlusSjalftLista(stopp=256, x=1, listi=[]):
if x <= stopp:
listi.append(x)
x += x
return buaTilPlusSjalftLista(stopp, x, listi)
else:
return listi
def faHeiltolu(texti):
try:
heiltala = int(input(texti))
exc... | hrolfurgylfa/Forritun | Generators/IP_splitter.py | IP_splitter.py | py | 813 | python | is | code | 0 | github-code | 36 |
8503903259 | import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk # import pillow library for images
Title_Font = ("Century Gothic", 15)
MARK_IV_Heading_Font = ("Century Gothic", 25)
Headline_Font = ("Century Gothic", 16)
imageMonash= "monash-university-malaysia_2.png"
def popMessage(msg):
pop = tk.Tk()... | Veinga/FIT-2101 | assignment_1/marking_software.py | marking_software.py | py | 7,332 | python | en | code | 0 | github-code | 36 |
10691943814 | """
#Estructuras de Condicional IF anidados
Operadores para comparar
== significa igual
!= diferente
< menor q
> mayor q
<= menor igual q
>= mayor igual q
!= diferente
"""
# Ejercicio Nro 1
"""
Generar el usuario Admin que trabaja en la empresa Pepito.
Si la empresa es disinta entonces muestra mensaje: No trab... | diegofer10/Introduccion-Python- | 07_estructuras_condicionales/7_2_If_anidado.py | 7_2_If_anidado.py | py | 789 | python | es | code | 0 | github-code | 36 |
32891047757 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
final... | chrispun0518/personal_demo | leetcode/21. Merge Two Sorted Lists.py | 21. Merge Two Sorted Lists.py | py | 852 | python | en | code | 0 | github-code | 36 |
15539286308 | # documentation user for solving this:
# https://docs.python.org/3/howto/regex.html#grouping
import re
# this pattern finds the link
pattern1 = r'<a href=\"(?P<href>.*?)\".*?>((<[a-z]>)?\s?(?P<data>.*?)(<\/[a-z]>)?)<'
p1 = re.compile(pattern1)
lines = int(input())
html_lines = ""
while lines > 0:
html_lines = ht... | gianv9/HackerRanksSubmissions | Regex/Detect HTML links/solution.py | solution.py | py | 522 | python | en | code | 0 | github-code | 36 |
30034353903 | # -*- coding: utf-8 -*-
class Config_API(object):
key = ''
txtEnderecos = ''
transporte = ''
limitDia = 0
limitRequi = 0
def __init__(self, configs):
self.key = configs['key']
self.transporte = configs['transporte']
self.limitDia = configs['limitDia']
... | Flaviomagalhaest/PSO-library | Config.py | Config.py | py | 500 | python | en | code | 0 | github-code | 36 |
40838375848 | import re, os, sys
pathjoin = os.path.join
try:
import configparser
except ImportError:
# Python 2
import ConfigParser as configparser
from .keplerian import keplerian
import pysyzygy as ps
from .utils import need_model_setup, get_planet_mass, get_planet_semimajor_axis,\
percentile68_ra... | j-faria/kima-light | pykimalight/display.py | display.py | py | 28,337 | python | en | code | 1 | github-code | 36 |
30533093290 | import cv2
import numpy as np
import os
from glob import glob
from tqdm import tqdm
#image = cv2.imread(r'C:\Users\mbarut\Desktop\car detection\vehicle-speed-counting\traffic.jpg')
"""
print(image.shape)
area = np.array([[552,605],[560,760],[1211,652],[1127,590]],np.int32)
color = (255, 0, 0)
thickness = 2
... | MehmetBarutcu/ObjectDetectionApp | car detection/vehicle-speed-counting/trial.py | trial.py | py | 1,808 | python | en | code | 0 | github-code | 36 |
17888210285 | import numpy
import pytest
from pyminer_algorithms import *
def test_transpose():
# 测试一维矩阵
a = numpy.ones((3,))
assert matrix_transpose(a).shape == (3, 1)
# 测试二维矩阵
a = numpy.ones((3, 4))
assert matrix_transpose(a).shape == (4, 3)
# 测试三维矩阵
a = numpy.ones((3, 4, 5))
with pytest.ra... | pyminer/pyminer | tests/test_algorithms/test_linear_algebra/test_matrix_transpose.py | test_matrix_transpose.py | py | 406 | python | en | code | 77 | github-code | 36 |
22635877529 | import pathlib
from .. import utils # noqa, pylint: disable=unused-import
from .. import enclosures
class TemplateEnclosurePlugin(enclosures.EnclosurePlugin): # noqa: V102
"""
The default enclosure plugin, expands a template into the target path.
"""
# Default a hierarchy under the feed title and ... | rpatterson/feed-archiver | src/feedarchiver/enclosures/template.py | template.py | py | 1,888 | python | en | code | 2 | github-code | 36 |
74205980903 | from . import utils
import torch
from torch import nn, autograd
import torch.nn.functional as F
from typing import Union, List, Optional, Tuple
from dataclasses import dataclass
from warnings import warn
from functools import reduce
from tqdm import tqdm
import numpy as np
import svox2.csrc as _C
# _C = utils._get_c_e... | ysus33/RGB-D_Plenoxel_Mapping_Tracking | svox2/svox2.py | svox2.py | py | 65,491 | python | en | code | 0 | github-code | 36 |
28832230499 | from MoocletCreationAutomator.secure import MOOCLET_API_TOKEN
import requests
import json
class MoocletConnector:
def __init__(self, token=MOOCLET_API_TOKEN):
self.token = MOOCLET_API_TOKEN
self.url = "https://mooclet.canadacentral.cloudapp.azure.com/engine/api/v1/"
def create_mooclet_object... | Intelligent-Adaptive-Interventions-Lab/MturkDeploymentAutomater | MoocletCreationAutomator/MoocletConnector.py | MoocletConnector.py | py | 2,227 | python | en | code | 0 | github-code | 36 |
70539349223 | import torch
import operator
from sema2insts import Sema2Insts, expr2graph
import json
import random
from time import time
import z3
from z3_exprs import serialize_expr
from synth import synthesize, sigs, check_synth_batched
llvm_insts = [inst for inst in sigs.keys() if inst.startswith('llvm')]
inst_pool = []
with op... | ychen306/upgraded-succotash | test-synth.py | test-synth.py | py | 2,618 | python | en | code | 0 | github-code | 36 |
8024456481 | """
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
"""
class Solution:
# @return an integer
def totalNQueens(self, n):
self.ret = 0
self.totalNQueens_helper(n, [])
return self.ret
def totalNQueens_helper... | cyandterry/Python-Study | Ninja/Leetcode/52_N-Queens_II.py | 52_N-Queens_II.py | py | 1,009 | python | en | code | 62 | github-code | 36 |
74497317225 | from flask import Flask, render_template, request, flash, redirect, url_for, session, g
import os
import secrets
from PIL import Image
from HackSite.deeplearning.classification import predict
def create_app(test_config=None):
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(... | BenVN123/AircraftClassificationDL | HackSite/__init__.py | __init__.py | py | 3,992 | python | en | code | 0 | github-code | 36 |
69981548263 | from collections import defaultdict
import math
import torch
import torch.nn as nn
from algorithm.trainer import SampleBatch, feed_forward_generator, recurrent_generator
def get_gard_norm(it):
sum_grad = 0
for x in it:
if x.grad is None:
continue
sum_grad += x.grad.norm()**2
r... | garrett4wade/revisiting_marl | algorithm/trainers/mappo.py | mappo.py | py | 6,597 | python | en | code | 19 | github-code | 36 |
5048789180 | import os
from flask import Blueprint, flash, redirect, render_template, request, url_for, send_from_directory
from flask_login import current_user, login_required, login_user, logout_user
from auth.methods import AuthMethod
from catalog.methods import CatalogMethod
from category.methods import CategoryMethod
from ite... | or73/Catalog_App | application/modules/catalog/views.py | views.py | py | 3,583 | python | en | code | 0 | github-code | 36 |
15212822365 | #import libraries
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from dash import Dash, dcc, html, Input, Output
#Connect to Cloud SQL using the Cloud SQL Python connector
#define your app object
app = Dash(__name__)
#--Import and clean data(importing csv into pandas)
#df = pd.read... | RichardLadson/bees | bees.py | bees.py | py | 2,259 | python | en | code | 0 | github-code | 36 |
44210008243 | # -*- coding: utf-8 -*-
#!usr/bin/evn python3
#这一部分用来理解正规标达式 / 日期运算
#备注:当要搜寻特定文字时可以使用正规表达式
"""
Created on Tue Nov 7 13:56:09 2017
@author: vizance
"""
#===正规表达式与匹配文字组合(资料分析中,字段资料的大小写匹配非常重要)===
#呼叫re模组(正规表达式模组,使用中继字元来匹配各种文字组合)
#中继字元如 |、()、[]、*、+、?、^、$、(?P<name>)
import re #re模组用来创造或搜寻各种文字组合
string = "The quick bro... | vizance/Python_Data_Analysis | 第一章_基礎介紹/基本練習2_正規表達式與日期運算.py | 基本練習2_正規表達式與日期運算.py | py | 4,376 | python | zh | code | 0 | github-code | 36 |
36602473197 | from keyelements.src import errors
from keyelements.src.commands import commands
__all__ = ['Parking']
class Parking(object):
def __init__(self):
self.commands = commands
self.parking_capacity = 0
self.slot_status = dict()
def used_slots(self):
return {i: self.... | AvinashBaggam/carparkinglot | carparkinglot/keyelements/src/carparking.py | carparking.py | py | 3,086 | python | en | code | 0 | github-code | 36 |
22776411105 | from jira import JIRA
import re
import json
import requests
import browser_cookie3
import creds as creds
#connect to jira instance
jiraOptions = {'server' : creds.url
}
jira = JIRA(server=jiraOptions, token_auth=creds.api_token)
#get list of issues
issues = []
def getIssues():
print('Searhing fo... | SBotalov/sd_automation | sd_granting_access.py | sd_granting_access.py | py | 4,477 | python | en | code | 0 | github-code | 36 |
6484130137 | """
Data Analytics II: PC4.
Spring Semester 2022.
University of St. Gallen.
"""
# Data Analytics II: PC Project 4
# import modules
import sys
import pandas as pd
# set working directory
PATH = '/Users/arbiun/Desktop/MECONI/3. Semester/Data Analytics II/PC/PC4/'
sys.path.append(PATH)
# load own functions
import pc... | akapedan/Causal_Econometrics | pc4.py | pc4.py | py | 4,022 | python | en | code | 0 | github-code | 36 |
33133895582 | # inputs:
# array - anything
# not sorted
# can be empty
# can be None
# no interval for items
# no size limit
# int - non-negative
# can be 0
# output:
# array - anything
# if empty or None return empty array
# rotated array based on int param
# O(n * m) - Time ... | Iuri-Almeida/ZTM-Data-Structures-and-Algorithms | data-structures/arrays/bonus/rotate_array.py | rotate_array.py | py | 2,523 | python | en | code | 0 | github-code | 36 |
7939048922 | import math
from collections import defaultdict
from fractions import gcd
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __sub__(self, p2):
return Point(self.x-p2.x, self.y-p2.y)
def __str__(self):
return "(" + str(int(self.x)) + ", " + str(int(self.y)) +")"
def __re... | deepspacepirate/googlefoobar | L4-bringing_a_gun_to_a_guard_fight.py | L4-bringing_a_gun_to_a_guard_fight.py | py | 3,170 | python | en | code | 0 | github-code | 36 |
12939715941 | """
AlexNet Keras Implementation
BibTeX Citation:
@inproceedings{krizhevsky2012imagenet,
title={Imagenet classification with deep convolutional neural networks},
author={Krizhevsky, Alex and Sutskever, Ilya and Hinton, Geoffrey E},
booktitle={Advances in neural information processing systems},
pages={1097--11... | vedantbhatia/xAI-image-classifiers | AlexNet.py | AlexNet.py | py | 3,154 | python | en | code | 0 | github-code | 36 |
23542375248 | from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphic+cards'
#opening connection and grabbing page
uClient = uReq(my_url)
page_html = uClient.read()
#close the client
uClient.close()
#html parsing
page_s... | vallab/hackerrank_dashboard | first_scrap.py | first_scrap.py | py | 380 | python | en | code | 0 | github-code | 36 |
23072964772 | from behave import given, when, then
from hamcrest import assert_that, equal_to, raises
from LinkList.src.linkList import LinkList
@given(u'nodes are created')
def add_node(context):
for row in context.table:
context.model.add_node(row["node"])
@given(u'All nodes are reset')
def delete_list(context):
... | rushikeshnakhate/HackaThon | python/LinkList/test/bdd/steps/countNumberOfNodesStepsDefinition.py | countNumberOfNodesStepsDefinition.py | py | 2,220 | 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.