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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
32102378059 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList1(self, head: ListNode) -> ListNode:
new_head = None
while head is not None:
nex = head.next
head.next = new_head
new_head = head
h... | Eleanoryuyuyu/LeetCode | python/Linked List/206. Reverse Linked List.py | 206. Reverse Linked List.py | py | 1,238 | python | en | code | 3 | github-code | 6 |
28653090658 | ##### Native libraries
##### Python Libraries
import numpy as np
from IPython.core import debugger
breakpoint = debugger.set_trace
##### Local libraries
import Utils_Data
from Timer import Timer
##### NOTE: To download the full dataset (which will take about 30 hours on wifi maybe less on ethernet)
##### set the file... | BradleyAllanDavis/760-project | data_download/Example_DownloadDataset.py | Example_DownloadDataset.py | py | 2,412 | python | en | code | 4 | github-code | 6 |
17430806092 | #!/usr/bin/python
# https://www.udemy.com/course/complete-python-developer-zero-to-mastery/
# 256. Building A Flask Server
# https://flask.palletsprojects.com/en/1.1.x/quickstart/
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types
# https://swapi.dev/ - Star Wars API server
# http://ww... | olexandrch/UdemyCompletePythonDeveloper | Sec.19 Web Development with Python/portfolio/server.py | server.py | py | 2,518 | python | en | code | 0 | github-code | 6 |
34864677253 | name=input("please enter your name:")
age= input("please enter your age:")
print('My name is ',name, ' and my age is ', age)
first_name=input("Please enter your first name:")
last_name=input("Please enter your last name:")
full_name=first_name+" "+last_name
print('Hello, my name is {} and my age is {}'.format(full_nam... | xzang1/Learning-Python--bootcamp- | Python day2.py | Python day2.py | py | 1,708 | python | en | code | 0 | github-code | 6 |
19250585752 | # Modules which need to be installed
import irc.bot
from dotenv import load_dotenv
load_dotenv()
# Setup / included imports
import os
import commands
import asyncio
prefix = os.getenv('COMMANDPREFIX')
# Make sure the Twitch credentials have been added to the .env file
if os.getenv('TWITCHUSERNAME') == "" or os.getenv... | R2D2VaderBeef/SectorsEdgeStreamControl | main.py | main.py | py | 1,555 | python | en | code | 1 | github-code | 6 |
18132740067 | # Project Name: Rock Paper Scissors game
# Creator: Jay Chen
# Create Date: 2017/6/3
import random
options = ['rock','paper','scissors']
user_wins = 0
computer_wins = 0
while True:
user_choice = input("打rock/paper/scissors 或選擇q來退出遊戲:")
if user_choice == 'q':
print("遊戲退出!")
break
if use... | JayChen1060920909/Projects | Rock Paper Scissors.py | Rock Paper Scissors.py | py | 1,178 | python | en | code | 1 | github-code | 6 |
3618688983 | import graphviz as gv
from graphvizual import *
class Edge:
def __init__(self,node_0,node_1,weight):
self.node_0 = node_0
self.node_1 = node_1
self.weight= weight
class Graph_0:
def __init__(self):
self.list_edges =[]
def add_edge(self,start,end,weight):
... | AnnaPiatek/Graph | Dijkstra.py | Dijkstra.py | py | 6,638 | python | en | code | 0 | github-code | 6 |
24923354544 | from pytesseract import Output
import pytesseract
import argparse
import imutils
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
ap.add_argument("-o", "--output", required=False, help="path to output image. override if not given.")
ap.add_argument("... | uborzz/images-playground | tools/rotate_image.py | rotate_image.py | py | 887 | python | en | code | 0 | github-code | 6 |
40428186364 | # python3
def max_gold_knapsack(W, n, gold_bars):
weight = [[0 for i in range(n+1)] for j in range(W+1)]
for i in range(1, n+1):
for w in range(1, W+1):
weight[w][i] = weight[w][i-1]
if gold_bars[i-1] <= w:
wgt = weight[w - gold_bars[i-1]][i-1] + gold_bars[i-1]... | probhakarroy/Algorithms-Data-Structures | Algorithmic Toolbox/week6/max_gold.py | max_gold.py | py | 595 | python | en | code | 0 | github-code | 6 |
10693657978 | def crowstorm_lol(list_args: list) -> str:
from math import sqrt, pow
[xf, yf, xi, yi, vi, r1, r2] = list(map(int, list_args))
distance: float = sqrt(pow((xf - xi), 2) + pow((yf - yi), 2))
if r1 + r2 >= distance + 1.5 * vi:
return 'Y'
return 'N'
def main() -> None:
while True:
... | pdaambrosio/python_uri | Beginner/uri2203.py | uri2203.py | py | 502 | python | en | code | 0 | github-code | 6 |
6453212033 | from django.conf.urls import url
from testuser import views
app_name = 'test'
urlpatterns = [
# url(r'^$',views.logout, name = 'logout'),
url(r'^$',views.loginIndex, name = 'loginIndex'),
url(r'^login/$',views.login, name = 'login'),
# url(r'^signUp/$',views.signup, name = 'signup'),
# url(r'^forg... | baivarn-tjr/SYOT-python | SYOT/testuser/urls.py | urls.py | py | 503 | python | en | code | 1 | github-code | 6 |
40761579635 | """Module containing the Fetcher Class to get financial
data of given ticker using the yfinance package."""
from datetime import datetime, timedelta
import yfinance as yf
import pandas as pd
class Fetcher:
"""Class that fetches data about a given ticker
This class does a few things:
1. Checks for validi... | webclinic017/YSC4228-QuantFin | scrape_mkt_data/tools/fetcher.py | fetcher.py | py | 3,536 | python | en | code | 0 | github-code | 6 |
17169060948 | from django.urls import path
from . import views
urlpatterns=[
path('sub/',views.SubjectVW,name='sub'),
path('trainer/',views.TrainerVW,name='trainer'),
path('profile/',views.TranierDisplay,name='profile'),
path('batchvw/',views.BatchVW,name='batchvw'),
path('bdisplay/',views.BatchDisplay,name='b... | mithun-gowda/PyInstitute | Batch/urls.py | urls.py | py | 444 | python | en | code | 0 | github-code | 6 |
21729743444 | class user():
def logged_in(self):
print('You have logged in')
class warden(user):
def __init__(self, name, age, specification, weapon, strength):
self.name = name
self.age = age
self.specification = specification
self.weapon = weapon
self.strength = strength
... | TheGurtang/Python | Class_Inheritance_2.py | Class_Inheritance_2.py | py | 2,402 | python | en | code | 0 | github-code | 6 |
17549816996 | from flask import Flask, render_template, request
from tensorflow.keras.layers import Dense, Embedding, Bidirectional, LSTM, Concatenate, Dropout
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras import Input, Model
import gensim
import numpy as np
import BahdanauAttention #모델.py 불... | rlagywns0213/korea_bad_comments_analysis | comment_confirm.py | comment_confirm.py | py | 3,906 | python | en | code | 0 | github-code | 6 |
29541301753 | from django.contrib import admin, messages
from .models import Poll, Question, Choice
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 0
class QuestionInline(admin.StackedInline):
model = Question
readonly_fields = ['question_type']
extra = 0
class PollAdmin(admin.ModelAdmin):
... | RamilPowers/poll_app | api/admin.py | admin.py | py | 2,063 | python | en | code | 0 | github-code | 6 |
42629975620 | from unittest import TestCase
import os
from yapic_io.connector import io_connector
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from yapic_io import TiffConnector, Dataset, PredictionBatch
import pytest
from tifffile import memmap
base_path = os.path.dirname(__file__)
... | yapic/yapic_io | yapic_io/tests/test_prediction_batch.py | test_prediction_batch.py | py | 10,948 | python | en | code | 1 | github-code | 6 |
27560756973 | # preprocessing data
data = open("input/day14.txt").read().splitlines()
data = [line.split("->") for line in data]
data = [[x.strip().split(",") for x in line] for line in data]
data = [[[int(num) for num in pair] for pair in line] for line in data]
balance_x = 450
data = [[[pair[0] - balance_x, pair[1]] for pair in li... | nhannht/aoc2022 | day14.py | day14.py | py | 4,428 | python | en | code | 0 | github-code | 6 |
34346333133 | '''
Exercises of the book "Think python"
14.12.2 Exercise:
'''
# If you download my solution to Exercise 2 from
# http://thinkpython2.com/code/anagram_sets.py, you’ll see that it
# creates a dictionary that maps from a sorted string of letters
# to the list of words that can be spelled with those letters.
# For ex... | LiliiaMykhaliuk/think-python | chapter14/14.12.2.py | 14.12.2.py | py | 1,587 | python | en | code | 0 | github-code | 6 |
29584667291 | # -*- coding: utf-8 -*-
from datetime import datetime
import calendar
from openerp import models, fields, api, sql_db
from openerp.addons.avancys_orm import avancys_orm as orm
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DSDF, DEFAULT_SERVER_DATETIME_FORMAT as DSTF, float_compare
from openerp.exceptions impo... | odoopruebasmp/Odoo_08 | v8_llevatelo/hr_payroll_extended/models/hr_contribution_form.py | hr_contribution_form.py | py | 82,426 | python | en | code | 0 | github-code | 6 |
40155982512 | # -*- coding: utf-8 -*-
"""
This module contains functions for losses of various types: soiling, mismatch,
snow cover, etc.
"""
import numpy as np
import pandas as pd
from pvlib.tools import cosd
def soiling_hsu(rainfall, cleaning_threshold, tilt, pm2_5, pm10,
depo_veloc={'2_5': 0.004, '10': 0.0009},... | Samuel-psa/pvlib-python | pvlib/losses.py | losses.py | py | 2,997 | python | en | code | null | github-code | 6 |
34670410766 | #!/usr/bin/python3
import mysql.connector
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.stem import WordNetLemmatizer
from lib.constants import brand_name_list, device_type_list, cwe_to_exp_type
from vul_scanner import query_iot_cve_from_cvetable
from lib.query_mysql import write_to_vul_analysis_t... | pmlab-ucd/IOTA | python/vul_analyzer.py | vul_analyzer.py | py | 13,241 | python | en | code | 1 | github-code | 6 |
10250262704 | # Nothing too high-powered. Simply run a DFS on a random non-visited node.
# Append end node to a list at each function callback. Repeat until all
# Nodes are visited. The reversed list will the the topological order.
class Graph():
def __init__(self, len):
self.nds = [[] for i in range(len)]
... | Ocinom/Stuff | Random/TopSort.py | TopSort.py | py | 1,245 | python | en | code | 0 | github-code | 6 |
38474579179 | import argparse
import regex as re
from pathlib import Path
from textwrap import dedent
import yaml
from .validator import run_sigma_validator
from clint.textui import colored, puts
import logging
STANDARD_YAML_PATH = Path(__file__).resolve().parent.parent / Path('CCCS_SIGMA.yml')
SIGMA_FILENAME_REGEX = r'(\.yaml|\.ym... | CybercentreCanada/pysigma | pysigma/validator_cli.py | validator_cli.py | py | 13,374 | python | en | code | 7 | github-code | 6 |
21928738877 | # Instance & Class variables
class Student:
school = "Sherpur Government Victoria Academy"
Alex = Student()
John = Student()
Alex.name = "Alex"
Alex.cls = 7
John.name = "John"
John.cls = 8
print(Alex.name)
print(Alex.school)
# Student.school = "SGVA"
# print(Alex.school)
Alex.school = "SGVA"
print(Alex.school)
... | MahbinAhmed/Learning | Python/Python Learning/Revision/35. Instance & Class variables.py | 35. Instance & Class variables.py | py | 362 | python | en | code | 0 | github-code | 6 |
35712406484 |
from global_variables import stop_event
from hatch_controller import hc
from beamer.mqtt import mqtt_client, fsmQueue, TRAPPE_TOPIC, HDMI_TOPIC
from beamer.hdmi import hdmi_relay
import logging
import time
MQTT_OPEN = b"OPEN"
MQTT_CLOSE = b"CLOSE"
MQTT_STOP = b"STOP"
class State():
def __init__(self):
se... | clementnuss/hatch_controller | beamer/beamer_state_machine.py | beamer_state_machine.py | py | 3,618 | python | en | code | 0 | github-code | 6 |
11121080147 | import typing as tp
from datetime import datetime, date
from uuid import uuid4
import pytest
from sqlalchemy import text
from librarius.domain.models import Publication
from librarius.service.uow.implementation import GenericUnitOfWork
if tp.TYPE_CHECKING:
from sqlalchemy.orm import Session
from sqlalchemy.sq... | adriangabura/vega | tests/integration/test_uow.py | test_uow.py | py | 3,023 | python | en | code | 1 | github-code | 6 |
71861329469 | """将CHANGELOG.MD中的本次更新信息提取出来,供github release流程使用"""
from __future__ import annotations
import os.path
from log import logger
from util import make_sure_dir_exists
def gen_changelog():
update_message_list: list[str] = []
# 解析changelog文件
version_list: list[str] = []
version_to_update_message_list: di... | fzls/djc_helper | _gen_changelog_for_github_release.py | _gen_changelog_for_github_release.py | py | 1,606 | python | en | code | 319 | github-code | 6 |
1541207425 | '''This module should be used to test the parameter and return types of your
functions. Before submitting your assignment, run this type-checker. This
typechecker expects to find files cipher_functions.py, secret1.txt, and
deck1.txt in the same folder.
If errors occur when you run this typechecker, fix them before you... | monkeykingg/projects | 1st_year/csc108/a2starter/a2_type_checker.py | a2_type_checker.py | py | 5,773 | python | en | code | 2 | github-code | 6 |
13954441013 | '''. Solicitar al usuario que ingrese su dirección email. Imprimir un mensaje
indicando si la dirección es válida o no, valiéndose de una función para decidirlo.
Una dirección se considerará válida si contiene el símbolo "@".'''
def evaluaMail1(correo):
indice = correo.find('@')
mensa = 'CORRECTO'
if indic... | eSwayyy/UCM-projects | python/catedra/lab_funciones/ejercicio1.py | ejercicio1.py | py | 638 | python | es | code | 1 | github-code | 6 |
40370569254 |
def bonificacion(n):
if n <= 1000000:
bonificacion=float(0)
else:
if n <= 2500000:
bonificacion=float(n*0.04)
else:
if n > 2500000:
bonificacion=float(n*0.08)
return bonificacion
print('\n')
numero1=float(input("Diga las ventas realizadas: "))
x=bonificac... | Natacha7/Python | Condicional/Venta_vendedor1.py | Venta_vendedor1.py | py | 393 | python | es | code | 0 | github-code | 6 |
23265542447 | class Solution:
def checkPermutation(self, str1, str2):
if len(str1) != len(str2):
return False
mp = map()
for char in str1: #O(n)
if char not in mp:
mp[char] = 1
else:
mp[char] += 1
for char in str2: #O(n)
... | anhtuanle2101/Data_Algo | Python/Problems/checkPermutation.py | checkPermutation.py | py | 548 | python | en | code | 0 | github-code | 6 |
41196412710 | import os
import sys
def run(inputs, output):
exe = os.path.dirname(sys.executable)
gdalwarp = os.path.join(exe, 'Library', 'bin', 'gdalwarp.exe')
args = [ "--config", "GDAL_CACHEMAX", "3000", "-wm", "3000", *inputs, output ]
os.system(gdalwarp + ' ' + ' '.join(args))
| w-copper/misc-tools | gdaltools/batch_merge.py | batch_merge.py | py | 308 | python | en | code | 3 | github-code | 6 |
3971463654 | from flask import Flask, request, jsonify, render_template, send_file
import os
import csv
import json
import base64
import pickle
import logging
from utils import (set_license_key_in_config, get_license_key_from_config,
get_dynamodb_table, license_key_is_valid)
# Configure the logging level
loggin... | TahirAlauddin/KonnectedReverseRaffle | mac_server/konnected-server.py | konnected-server.py | py | 9,148 | python | en | code | 0 | github-code | 6 |
18781100050 | from pathlib import Path
from environs import Env
env = Env()
env.read_env()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
PROJECT_DIR = BASE_DIR / "project"
SECRET_KEY = env.str("SECRET_KEY", default="something-very-secret")
DEBUG = env.bool("D... | valberg/django_project_template | src/config/settings.py | settings.py | py | 3,358 | python | en | code | 0 | github-code | 6 |
25273285890 | def perm(k):
if k == N-1:
candidate.append(field + [0])
else:
for i in range(k, N):
field[k], field[i] = field[i], field[k]
perm(k+1)
field[k], field[i] = field[i], field[k]
T = int(input())
for t in range(1, T+1):
N = int(input())
golfmap = [list(ma... | powerticket/algorithm | Practice/실습/201029/전자카트_전원표.py | 전자카트_전원표.py | py | 722 | python | en | code | 0 | github-code | 6 |
21325441820 | import os
from setuptools import setup
basedir = os.path.dirname(__file__)
def readme():
with open(os.path.join(basedir, "README.rst")) as f:
return f.read()
about = {}
with open(os.path.join(basedir, "pysyncgateway", "__about__.py")) as f:
exec(f.read(), about)
setup(
name=about["__name__"],... | constructpm/pysyncgateway | setup.py | setup.py | py | 1,004 | python | en | code | 1 | github-code | 6 |
69976456507 | import logging
from typing import Callable, List
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import C... | 0xAlon/dolphin | custom_components/dolphin/switch.py | switch.py | py | 7,201 | python | en | code | 6 | github-code | 6 |
28845108173 | from django.views.generic import View
from .forms import CorrectionSendingForm
from apps.article_review.models import Review
from django.contrib import messages
from django.shortcuts import redirect
# Create your views here.
from apps.correction_reception.models import ArticleCorrection
# * Importar los modelos
clas... | HetairoiElite/cienciatec | apps/correction_sending/views.py | views.py | py | 3,096 | python | es | code | 0 | github-code | 6 |
38650731253 | from ehrqc.standardise import Config
from ehrqc.standardise import Utils
import logging
log = logging.getLogger("EHR-QC")
def importPatients(con, sourceSchemaName, filePath, fileSeparator, overwrite=True):
if overwrite:
log.info("Creating table: " + sourceSchemaName + ".patients")
dropQuery = ... | ryashpal/EHR-QC-Standardise | ehrqc/standardise/Import.py | Import.py | py | 18,197 | python | en | code | 0 | github-code | 6 |
75163509946 | from flask import Blueprint, render_template, redirect, url_for, flash
from flask_security import current_user
from flask_babel import gettext
from . import route
from dxc.app.models.job.forms import JobForm, JobReportForm
from dxc.services import api_job, api_report
bp = Blueprint('job', __name__, template_folder='t... | cash2one/Luyasi-Flask | dxc/app/frontend/job.py | job.py | py | 2,646 | python | en | code | 0 | github-code | 6 |
10721085289 | '''
Collection of helper function for the EDA notebooks
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pycountry
''' Returns the pairs of variables sorted according to their correlation '''
def getCorrPairs(corr):
mask = np.zeros_like(corr, dtype=bool)
... | Miltos-90/EU_Electricity_Price_Forecasting | src/eda_utils.py | eda_utils.py | py | 5,183 | python | en | code | 0 | github-code | 6 |
38794444506 | n, m, q = map(int, input().split())
grid = [[0] * m for _ in range(n)]
def explore(i, j, seen):
if i-1 >= 0 and (i-1, j) not in seen and grid[i-1][j] == 0:
seen.add((i-1, j))
explore(i-1, j, seen)
if i+1 < len(grid) and (i+1, j) not in seen and grid[i+1][j] == 0:
seen.add((i+1, ... | MaxwellGraves/ICPC-Practice | Practice3/Artwork/soln.py | soln.py | py | 1,207 | python | en | code | 0 | github-code | 6 |
40206920414 | #!/usr/bin/python3
""" A function that finds the biggest integer in a
list, and if empty return none and assume the
list contains only integers. """
def max_integer(my_list=[]):
if len(my_list) == 0:
return None
else:
my_list.sort()
largestInt = my_list[-1]
return large... | omondistanley/seo-higher_level_programming | python-data_structures/9-max_integer.py | 9-max_integer.py | py | 326 | python | en | code | 0 | github-code | 6 |
21666620014 | #https://leetcode.com/problems/rotate-array/
class Solution:
def rotate(self, nums: list[int], k: int) -> None: #Not returning anything, since we'll modify it in-place
solutionList = [0] * len(nums)
for i in range(0,len(nums)):
newIndex = (i+k) % len(nums)
solutionList[newIn... | Adam-1776/Practice | DSA/rotateArray/solution.py | solution.py | py | 1,004 | python | en | code | 0 | github-code | 6 |
16822782747 | from math import comb
def compute(m,n):
combs = comb(m*(m-1)*(m-2),n)
power = pow(m-3, 2*n)
poly = n*m*m+2*m*m+n*m
return combs*power*poly
def compute2(m,n):
combs = comb(m*(m-1)*(m-2)-1,n-1)
power = pow(m-3,n)*pow(m-4,n)
poly = n*m*m+2*m*m+n*m
return combs*power*poly
# for m in ran... | NoahW314/Python-Testing | Testing/src/root/nested/math/Cayley Tables/assoc/assoc_testing_complexity.py | assoc_testing_complexity.py | py | 735 | python | en | code | 0 | github-code | 6 |
7940432285 |
length = 12
summary = [0] * length
mask = '1' * length
with open('/Users/eilidh/PycharmProjects/advent_of_code/src/day3/input.txt') as file:
for line in file:
line = line.rstrip()
if len(line) != length:
raise Exception('wrong length')
for i, char in enumerate(line.rstrip()):
... | eilidht/advent_of_code | src/day3/day3.py | day3.py | py | 772 | python | en | code | 0 | github-code | 6 |
16478653737 | import mxnet as mx
import time
import gluoncv as gcv
from gluoncv.utils import try_import_cv2
cv2 = try_import_cv2()
net = gcv.model_zoo.get_model(
# good, fast
'ssd_512_mobilenet1.0_coco',
# 'ssd_512_mobilenet1.0_voc',
# 'ssd_512_mobilenet1.0_voc_int8',
#
# 'yolo3_mobilenet1.0_coco',
# '... | ODN418/progmates_works | glouncv/detect.py | detect.py | py | 1,506 | python | en | code | 0 | github-code | 6 |
26524937441 | class SinglyLinkedList:
def __init__(self):
self.head = None
self.length = 0
# Methods
# Add to Back
def addToBack(self,val):
newNode = ListNode(val)
if self.head == None:
self.head = newNode
return self;
runner = self.head;
wh... | CoreyM-Dojo/projects-and-algorithms-october-2023 | week2/day1/SLL.py | SLL.py | py | 802 | python | en | code | 0 | github-code | 6 |
41202613200 | from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
temp = sense.get_temperature()
humidity = sense.get_humidity()
humidity = round(humidity, 1)
calc = 100-humidity
calc2 = calc/5
dewpoint = temp - calc2
dewpoint = (str(dewpoint))
print(dewpoint + " degrees C")
| Meteodeep/sandbox | Summer-2017/RPi-DewPoint.py | RPi-DewPoint.py | py | 283 | python | en | code | 4 | github-code | 6 |
7901768963 | from collections import Counter
import logging
def find(list, value):
try:
return list.index(value)
except ValueError:
return None
class DefaultSorter(object):
def __init__(self, langs='all', weight=1):
logging.info("Available languages: {}".format(langs))
self.lan... | luisguilherme/framboise | framboise/sorting.py | sorting.py | py | 1,318 | python | en | code | 2 | github-code | 6 |
17493539514 | #This file "drives" the car by calling all the required files
#outputs plots of the dynamic/vibration models
import Beeman, car_2014, chassis_2014, driver_sally, ff_2014_5, ff_2014_7, get_DM, get_FF, get_Jx, get_Jy, get_LR, get_MM, get_SD, get_SM, get_cg, motor_2014, speed_bump, suspension_front_2014, suspension_rear... | brandontran14/CarSimulation | driving.py | driving.py | py | 897 | python | en | code | 0 | github-code | 6 |
23255212962 | from Config import Calculator
from Config import Condition
from Utils import Utils
import json
import insertUser
import os
# # file_path = os.path.join(BASE_DIR, 'Test_Data')
# elements = BASE_DIR.split("/")
# # elements.pop()
# path = "/".join(elements)
# print(path)
if __name__ == '__main__':
# BASE_DIR = os.p... | LJJ/py_parseExcel | ParseExcel.py | ParseExcel.py | py | 1,219 | python | en | code | 0 | github-code | 6 |
4495978796 | class Funcionarios:
def __init__(self):
pass
def DadosFuncionarios(self):
arq = open('Funcionarios.txt','r')
s = arq.readlines()
lis = []
for x in s:
dados = x.split('{/')
lis.append(dados)
arq.close()
return lis
... | Ander20n/Codigos-Faculdade | Projeto IP/Funcionarios.py | Funcionarios.py | py | 8,276 | python | pt | code | 0 | github-code | 6 |
33225318672 | import torch
import torch.nn as nn
from torch.utils.data import Dataset
import h5py
import numpy as np
import utils.io as io
from datasets.hico_constants import HicoConstants
from datasets import metadata
import sys
import random
class HicoDataset(Dataset):
'''
Args:
subset: ['train', 'val', 'train_... | birlrobotics/PMN | datasets/hico_dataset.py | hico_dataset.py | py | 9,279 | python | en | code | 7 | github-code | 6 |
34197476486 | #!/bin/python3
import sys
import os
import mysql.connector
import datetime
from sys import argv
import requests
import json
from requests.exceptions import HTTPError
from slack import WebClient
from slack.errors import SlackApiError
import logging
logging.basicConfig(level=logging.DEBUG)
database_conf = "/var/lib/je... | vlad-solomai/viam_automation | automation_gambling/game_round_management/close_rounds_slack.py | close_rounds_slack.py | py | 6,354 | python | en | code | 1 | github-code | 6 |
7798026425 | import os.path
import xml.dom.minidom
import xml.xpath
import logging
import edef
from edef.dev import Config
import fnmatch
from Tools import getModuleName
class Model:
def __init__(self):
self._logger = logging.getLogger("edef.dev")
self._base_path = Config().getBasePath()
self._module_l... | BackupTheBerlios/pplt-svn | trunk/edef/edef-dev/modeditor/ModelModule.py | ModelModule.py | py | 4,039 | python | en | code | 0 | github-code | 6 |
24673967273 | # Jumpy! - Platform game
# KidsCanCode - Game Development with python
# Art from Kenney.nl
import pygame as pg
import random
from settings import *
from sprites import *
from os import path
class Game:
def __init__(self):
# Initialize game window
pg.init()
pg.mixer.init()
self.scr... | guychaimy/jumpy | main.py | main.py | py | 9,548 | python | en | code | 0 | github-code | 6 |
42972033220 | from subprocess import Popen, PIPE
import sys
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from config import config
from theme import theme
class PluginGui:
_route = None
_button = None
_target = None
def __init__(self, parent, route):
self._route = route
... | pwerken/EDMC_Waypoints | plugin_gui.py | plugin_gui.py | py | 2,681 | python | en | code | 1 | github-code | 6 |
36011235958 | # encoding: utf8
# Import local files:
import colors as COLORS
import margins as MARGINS
import roi as ROI
# External:
external = ROI.ROI('External', 'External', COLORS.external)
body = ROI.ROI('Body', 'Organ', COLORS.external)
# Support:
couch = ROI.ROI('Couch', 'Support', COLORS.couch)
# Target volumes:
gtv = ... | dicom/raystation-scripts | settings/rois.py | rois.py | py | 21,183 | python | en | code | 40 | github-code | 6 |
72168147708 | # -*- coding: utf-8 -*-
import os
import re
import sys
import time
import json
import datetime
_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, '{}/../../libs/src'.format(_dir))
from roc_date_converter import RocDateConverter
class Inventory():
def __init__(self):
self._dir = os.path... | greenseedyo/stock_scripts | simulators/src/inventory.py | inventory.py | py | 2,740 | python | en | code | 0 | github-code | 6 |
40128872754 | #!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1 # sys.maxsize # float("inf")
MOD = 10 ** 9 + 7
def debug(*x):
print(*x, file=sys.stderr)
def solve(N, AS):
sum = 0
sumSq = 0
for i in range(N):
sum += AS[i]
sum %= MOD
sumSq += AS[i] * AS[i]
... | nishio/atcoder | abc177/c.py | c.py | py | 1,341 | python | en | code | 1 | github-code | 6 |
30084867415 | from .models import AdminUser
from django.shortcuts import render
from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
import json
from datetime import date, datetime
# Create your views here.
def jsons(data = None, e... | jeremyytann/BUAA-SE-LetStudy | Code/backend/admin_user/views.py | views.py | py | 2,482 | python | en | code | 0 | github-code | 6 |
21934463311 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Text Emotion Detection."""
from dataclasses import dataclass
from transformers import AutoTokenizer, AutoModelWithLMHead
from transformers import pipeline
__all__ = (
"Emotion",
"EmotionDetectorT5",
"EmotionDetectorRoberta",
)
@dataclass
class Emotion... | br8km/pynlp | core/emotion.py | emotion.py | py | 3,869 | python | en | code | 0 | github-code | 6 |
179588656 | # Guessing Game Code
# a guessing game that have problem in return function
# have problem in line 17
def Guessing_Game(guess):
#Secret number of Guessing_Game
secret_number = 5
guess_count = 0
#It's Count Is 0
guess_limit = 3
#The Guess Can Ask The User 3 Times
while guess_count <... | Amdesew/Guessing-Game | Guessing Game.py | Guessing Game.py | py | 1,277 | python | en | code | 1 | github-code | 6 |
73630578109 | """# Node"""
import numpy as np
import random
def sort_nodes(nodes, shuffle=False, presort=False, reverse=False):
"""
Sorts nodes in an order in which they should be estimated. i.e. all of
node N's in-nodes should be estimated before estimating node N.
Parameters
----------
nodes : list of `... | dsbowen/smoother | smoother/node.py | node.py | py | 4,428 | python | en | code | 1 | github-code | 6 |
696671101 |
import tkinter as tk
import atten
import face_recognition
import cv2
import numpy as np
import csv
import os
from datetime import datetime
# Create the root window
root = tk.Tk()
root.overrideredirect(True)
# Set the window size and position
width = 700
height = root.winfo_screenheight()-100 ... | khushiarora1793/attendancemanagement | temp.py | temp.py | py | 4,274 | python | en | code | 0 | github-code | 6 |
26922931124 | """
Calls the entos executable.
"""
import string
from typing import Any, Dict, List, Optional, Tuple
from qcelemental.models import Result
from qcelemental.util import parse_version, safe_version, which
from ..exceptions import UnknownError
from ..util import execute, popen
from .model import ProgramHarness
class... | ChemRacer/QCEngine | qcengine/programs/entos.py | entos.py | py | 8,943 | python | en | code | null | github-code | 6 |
71746011387 | from gui import GUI, run
from threading import Thread
from PyQt4.QtCore import QObject, SIGNAL
import socket
import pickle
'''
Host y port de facil acceso
'''
HOST = "192.168.1.181"
PORT = 12336
class Client(QObject):
'''Base de material de clases
'''
def __init__(self, port, host, username, gui):
... | isidoravs/iic2233-2016-2 | Tareas/T06/client/client.py | client.py | py | 9,169 | python | en | code | 0 | github-code | 6 |
70732574587 | import os
from importlib.machinery import SourceFileLoader
from setuptools import find_packages, setup
from typing import List
module_name = 'juldate'
module = SourceFileLoader(
module_name,
os.path.join(module_name, '__init__.py'),
).load_module()
def parse_requirements(filename: str) -> List[str]:
re... | churilov-ns/juldate | setup.py | setup.py | py | 1,333 | python | en | code | 0 | github-code | 6 |
32467456793 | from ting_file_management.file_management import txt_importer
import sys
def process(path_file, instance):
"""Aqui irá sua implementação"""
current_path = None
for item in range(len(instance)):
if instance.search(item)["nome_do_arquivo"] == path_file:
current_path = instance.search(ite... | janaolive/estrutura_de_dados | ting_file_management/file_process.py | file_process.py | py | 1,087 | python | pt | code | 0 | github-code | 6 |
18917415762 | from typing import Any, Callable, TypeVar, cast
import pluggy
F = TypeVar("F", bound=Callable[..., Any])
hookimpl = cast(Callable[[F], F], pluggy.HookimplMarker("ape"))
hookspec = pluggy.HookspecMarker("ape")
plugin_manager = pluggy.PluginManager("ape")
"""A manager responsible for registering and accessing plugins ... | ApeWorX/ape | src/ape/plugins/pluggy_patch.py | pluggy_patch.py | py | 752 | python | en | code | 736 | github-code | 6 |
26058478061 | from django.contrib.auth.views import LogoutView
from django.urls import path
from .views import *
urlpatterns = [
path('login/', CustomLoginView.as_view(), name='login'),
path('logout/', LogoutView.as_view(next_page='login'), name='logout'), # тут ми вказуємо через next_page, що якщо ми виходимо з акаунту то ... | ianvv/todo-app-django | todo_list/base/urls.py | urls.py | py | 812 | python | uk | code | 0 | github-code | 6 |
38586042024 | from flask import Flask,render_template,json,flash,request,session,redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
with open('config.json', 'r') as c:
parameter = json.load(c)["parameter"]
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = parameter['local_uri']
... | 199-cmd/FlaskDemo | FlaskDemo/main.py | main.py | py | 1,402 | python | en | code | 0 | github-code | 6 |
73510601787 | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
ans = [-1] * len(intervals)
start = []
for i,arr in enumerate(intervals):
start.append([arr[0],i])
start.sort()
for i,interval in enumerate(intervals):
low... | yonaSisay/a2sv-competitive-programming | find-right-interval.py | find-right-interval.py | py | 643 | python | en | code | 0 | github-code | 6 |
36007020776 | from bs4 import BeautifulSoup
import requests
import pandas as pd
# Downloading IMDB feature film and MyAnimeList popularity data
headers = {'Accept-Language': 'en-US,en;q=0.8'}
url1 = 'https://www.imdb.com/search/title/?title_type=feature&sort=num_votes,desc'
url2 = 'https://myanimelist.net/topanime.php?type=b... | ilovegaming42069/DataScienceExercise | datascience.py | datascience.py | py | 2,188 | python | en | code | 0 | github-code | 6 |
73363574908 | class ObjList:
def __init__(self, data):
self.__next = None
self.__prev = None
self.__data = data
def set_next(self, obj):
self.__next = obj
def set_prev(self, obj):
self.__prev = obj
def get_next(self):
return self.__next
def get_prev(self):
... | expo-lux/stepik_balakirev_python_OOP | task_2_1_10_access.py | task_2_1_10_access.py | py | 2,051 | python | ru | code | 0 | github-code | 6 |
37683950634 | import math
#import numbertheory
from numbertheory import *
#import multiprocessing
from multiprocessing import Pool
import gc
#import numpy as np
#from numpy.polynomial import polynomial as poly
####### HELPER FUNCTIONS #######
# performs the extended euclidean algorithm
# returns info to help calculate inverses
def... | CSAlexWhite/Cryptography | crypto.py | crypto.py | py | 16,518 | python | en | code | 0 | github-code | 6 |
36258745480 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
# Author: JiaChen
import traceback
from src.plugins.base import BasePlugin
from lib.response import BaseResponse
from config import settings
class CpuPlugin(BasePlugin):
def run(self):
response = BaseResponse()
try:
response.data = {'cpu_mo... | jcdiy0601/EasyCmdbClient | src/plugins/snmp/dell/server/cpu.py | cpu.py | py | 1,514 | python | en | code | 0 | github-code | 6 |
38090331621 | from .base_page import BasePage
from .locators import ProductPageLocators
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.common.by import By
import math
import webbrowser
class ProductPage(BasePage):
def go_product_basket_add(self):
self.browser.find_element(*Produc... | Pavel-OG/project_selenium_course_final_block | pages/product_page.py | product_page.py | py | 1,916 | python | en | code | 0 | github-code | 6 |
10711597654 | from youtubesearchpython import VideosSearch
import os
import glob
# __ _ _
# / \ | | | |
# / \ | | /\ | | /\ _ _
# / /\ \ | |/ / | |/ / | | | |
# / ____ \ | |\ \ | |\ \ | |_| |
#/__/ \__\ |_| \_\ |_| \_\ \___/
#
# Copyright of Akash, 2021 ... | akkupy/Sara-Bot | Modules/Yt_music.py | Yt_music.py | py | 3,160 | python | en | code | 2 | github-code | 6 |
70384673149 |
from collections import deque
from dataclasses import dataclass, field, replace
from typing import Type
import copy
import numpy as np
import pandas as pd
import re
# little helper class
class ldf_dict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
@da... | makreft/lin_ldf_parser | lin_ldf_parser/lin_ldf_parser.py | lin_ldf_parser.py | py | 16,228 | python | en | code | 1 | github-code | 6 |
42977090533 | longest = 0
shortSide = 0
while True:
A, B, C = map(int, input().split())
if A == B == C == 0:
break
if A > B and A > C:
longest = A**2
shortSide = (B**2 + C**2)
elif B > C and B > A:
longest = B**2
shortSide = (A**2 + C**2)
elif C > A and C > B:
longest = C**2
shortSide = (B**2 + ... | jinhyo-dev/BOJ | 직각삼각형.py | 직각삼각형.py | py | 404 | python | en | code | 1 | github-code | 6 |
41073049349 | from mymodule_2nd_exercise import *
try:
a = int(input("Input A: "))
b = int(input("Input B: "))
operation = input("What operation to be done: ")
if b == 0 and operation == "/" or operation == "division":
raise ZeroDivisionError
if operation == "add" or operation == "+":
print(add(a... | Marto03/Python-homeworks | lab_8_15.12.2022/2nd_exercise.py | 2nd_exercise.py | py | 782 | python | en | code | 0 | github-code | 6 |
17609793311 | from django import http
import six
from django.db.models import ProtectedError
from rest_framework import views, exceptions, status
from rest_framework.exceptions import UnsupportedMediaType
from rest_framework.response import Response
from backpack.serializers_bcv1 import BadgeConnectErrorSerializer
from entity.seri... | reedu-reengineering-education/badgr-server | apps/entity/views.py | views.py | py | 4,487 | python | en | code | 2 | github-code | 6 |
9485584474 | ###
###
### note: had to install webpack, webpack-cli, web-ext globally
from OpenWPM.automation import CommandSequence,TaskManager
import pandas as pd
NUM_BROWSERS = 2
NUM_SITES = 100
vanilla_path = './data_vanilla'
adblock_path = './data_adblock'
sites_path = 'top-1m.csv'
data = pd.read_csv(sites_path,header=None)
... | hwtrost/OpenWPM_crawling_project | webcrawler.py | webcrawler.py | py | 2,329 | python | en | code | 0 | github-code | 6 |
18769228974 | '''
Read and write Olympia state files.
'''
import os
import os.path
import sys
from contextlib import redirect_stdout
from .oid import to_oid
from .formatters import print_one_thing, read_oly_file
def fixup_ms(data):
'''
For whatever reason, the value in IM/ms needs to have a trailing space
'''
for... | olympiag3/olypy | olypy/oio.py | oio.py | py | 6,980 | python | en | code | 0 | github-code | 6 |
5855348658 | types = {
"root_list": {
1: ("day_session"),
},
"day_session": {
1: ("string", "session_uuid"),
2: ("int32"),
3: ("sfixed64", "main_timestamp"),
4: ("string", "location_name"),
5: ("location_list"),
},
"location_list": {
2: ("gps_location"),
... | jaredkaczynski/SnowDuckToGPX | protobuf_config.py | protobuf_config.py | py | 476 | python | en | code | 0 | github-code | 6 |
18834133291 | # -*- coding: utf-8 -*-
# Author:sen
# Date:2020/3/4 19:09
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def buildListNodeA():
n0 = ListNode(1)
n1 = ListNode(2)
n2 = ListNode(3)
n3 = ListNode(2)
... | PandoraLS/CodingInterview | ProgrammingOJ/LeetCode_python/234_回文链表.py | 234_回文链表.py | py | 2,003 | python | en | code | 2 | github-code | 6 |
11161578103 | import time
import aura_sdk as aura
import atexit
atexit.register(aura.close)
print("Devices found:")
for dev in aura.get_devices():
print(" " + dev.Name)
for j in range(5):
for i in range(255):
aura.set_all_to_color(aura.rgb_to_color(i, i, i))
time.sleep(0.005)
for i in range(255):
... | obfuscatedgenerated/asus-aura-control | fade_white.py | fade_white.py | py | 418 | python | en | code | 1 | github-code | 6 |
7437698122 | """
Script that trains an NFC bounding interval annotator.
To use tensorboard during or after model training, open a terminal and say:
conda activate vesper-dev-tf2
tensorboard --logdir "/Users/Harold/Desktop/NFC/Data/Vesper ML/
NFC Bounding Interval Annotator 1.0/Logs/<training log dir path>"
... | HaroldMills/Vesper | vesper/mpg_ranch/nfc_bounding_interval_annotator_1_0/train_bounding_interval_annotator.py | train_bounding_interval_annotator.py | py | 16,756 | python | en | code | 47 | github-code | 6 |
36011157948 | # encoding: utf8
# A class for reading task data from the Mosaiq database.
#
# Authors:
# Christoffer Lervåg
# Helse Møre og Romsdal HF
#
# Python 3.6
# Used for GUI debugging:
#from tkinter import *
#from tkinter import messagebox
from .database import Database
class Task:
# Returns a single task matching the... | dicom/raystation-scripts | mosaiq/task.py | task.py | py | 1,787 | python | en | code | 40 | github-code | 6 |
30309719132 | # Flask-Netpad
# version 1.0-alpha
# (C) Abstergo 2018
## netpad.py [MongoDB logic]
from flask_netpad.models import db, Note
# Custom Error
def errorCode(code=404, msg='Object Not Found :( '):
"""
Returns a custom error code in a dictionary
:param code: Error Code
:param msg: Message to return
... | dommert/Flask-Netpad | flask_netpad/netpad.py | netpad.py | py | 2,175 | python | en | code | 0 | github-code | 6 |
11408466413 | #!/usr/bin/env python
import sys
def main ():
if len(sys.argv) < 2:
return
for filepath in sys.argv[1:]:
process_file(filepath)
def process_file (filepath):
file_in = open(filepath, "rb")
content = file_in.read()
file_in.close()
if content[0] != '/' or content[1] != '*':
... | kohei-us/ixion | misc/strip-license.py | strip-license.py | py | 788 | python | en | code | 10 | github-code | 6 |
19606128436 | import json
from typing import Dict, Generic, TypeVar, cast
import attr
import yaml
from psqlgml.types import GmlData
__all__ = [
"load_resource",
"load_by_resource",
"ResourceFile",
]
T = TypeVar("T")
def load_by_resource(resource_dir: str, resource_name: str) -> Dict[str, GmlData]:
"""Loads all ... | kulgan/psqlgml | src/psqlgml/resources.py | resources.py | py | 2,372 | python | en | code | 0 | github-code | 6 |
42572778156 | from distutils.core import setup
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-view-extractor',
version='0.1.0',
packages=setuptools.find_packages(),
url='https://www.quickrelease.co.uk',
license='GNU GPLv3',
author='Nick Solly',
... | QuickRelease/django-view-extractor | setup.py | setup.py | py | 577 | python | en | code | 1 | github-code | 6 |
40466761016 | n = int(input())
m = int(input())
graph = [[] for _ in range(n + 1)]
cnt = 0
visited = [0] * (n + 1)
for i in range(m):
a,b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
for i in graph:
i.sort(reverse = True)
def dfs(v,cnt):
stack = [v]
while stack:
v = stack.pop()
... | Cho-El/coding-test-practice | 백준 문제/DFS/2606_바이러스.py | 2606_바이러스.py | py | 474 | python | en | code | 0 | github-code | 6 |
13109821356 | import spacy
nlp = spacy.load('en_core_web_sm')
example1 = nlp("Animals")
for token in example1:
print(token.lemma_)
print()
example2 = nlp("I am god")
for token in example2:
print(token.lemma_)
| 39xdgy/Interactive_chatbots | 03_lemmatization.py | 03_lemmatization.py | py | 207 | python | en | code | 0 | github-code | 6 |
27925991770 | """
-*- coding: utf-8 -*-
@author: socratio
@inspiration: drew original inspiration from cleartonic twitchtriviabot. Almost nothing left in this code from that project.
"""
import json
from twitchio import websocket
from twitchio.ext import commands
import yaml
import asyncio
import os
import random
class ChatBot(com... | Socratia/StrandedPandaTrivia | strandedpandatriviabot.py | strandedpandatriviabot.py | py | 21,771 | python | en | code | 0 | github-code | 6 |
27919143032 |
# Snake water and gun game
import random
def game(comp, User):
if comp == User:
print("Draw, both chossed same!!")
elif comp == 's':
if User == 'w':
print("Snake driked water, Comp Win!!")
elif User == 'g':
print("You Killed Snake, Win!!")
elif comp == 'w':... | satyam756/Snke-Water-Gun-Game | main.py | main.py | py | 1,010 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.