seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
26693866815 | import torch
import logging
from tqdm import tqdm
from schnetpack.src.schnetpack import properties
__all__ = ["TorchStructureLBFGS"]
class TorchStructureLBFGS(torch.optim.LBFGS):
"""
LBFGS optimizer that allows for relaxation of multiple structures in parallel. The approximation of the inverse
hessian is... | maltefranke/solubility_prediction | schnetpack/src/schnetpack/interfaces/batchwise_optimizer.py | batchwise_optimizer.py | py | 5,582 | python | en | code | 1 | github-code | 6 |
40411416951 | #!/usr/bin/env python3
"""
Name: vpc_consistency.py
Description: NXAPI: display inconsistent vpc parameters
Example output when vpc is consistent:
% ./vpc_consistency.py --vault hashicorp --devices cvd_leaf_2 --interface Po11,Po12
192.168.11.103 cvd-1312-leaf all 22 global vpc params are consistent
192.168.11... | allenrobel/nxapi-netbox | scripts/vpc_consistency.py | vpc_consistency.py | py | 6,995 | python | en | code | 0 | github-code | 6 |
18699671015 | from django.urls import path
from posting.views import (
PostingView,
CategoryView,
PostingLikeView,
PostingScrapView
)
urlpatterns = [
path('', PostingView.as_view()),
path('/category', CategoryView.as_view()),
path('/like', PostingLikeView.as_view()),
path('/scrap', PostingScrapVi... | wecode-bootcamp-korea/17-1st-SweetHome-backend | posting/urls.py | urls.py | py | 336 | python | en | code | 3 | github-code | 6 |
33222746920 | from tqdm import tqdm
# Define constant
SHORT = 15
MIDDLE = 30
LARGE = 50
def __clear__(times: int = 11, length: int = 123):
"""
Clear the previous table toward the terminal
"""
print()
for i in range(times + 1):
if i != times:
print("\033[F" + ' ' * length, end='')
... | SunnerLi/tqdm_table | tqdm_table/__init__.py | __init__.py | py | 4,733 | python | en | code | 0 | github-code | 6 |
41045436456 | '''
Exercise 3: Write a program to prompt for a score between 0.0 and
1.0. If the score is out of range, print an error message. If the score is
between 0.0 and 1.0, print a grade using the following table
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
'''
# Function to calculate the score.
def cal_grade(score):
if ... | simonSlamka/UCL-ITtech | programming/SimonStorm/ch3_ex3.py | ch3_ex3.py | py | 682 | python | en | code | 2 | github-code | 6 |
41058141376 | from copy import copy
class Poly:
def __init__(self,*terms):
# __str__ uses the name self.terms for the dictionary of terms
# So __init__ should build this dictionary from terms
self.terms = {}
if terms==None:
self.terms={0:0}
for term in terms:
... | solomc1/python | ics 33/solutions/ile2 solutions/Lab 1/JiangYu/poly.py | poly.py | py | 8,201 | python | en | code | 0 | github-code | 6 |
70285709629 | from __future__ import absolute_import
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
de... | timknip/pyswf | setup.py | setup.py | py | 982 | python | en | code | 154 | github-code | 6 |
32100438574 | from sklearn.datasets import load_breast_cancer
from sklearn.datasets import load_wine
from E2 import sammon
from E1 import bkmeans
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from scipy.cluster.hierarchy i... | Knoz9/ML-A3-A4 | km222ug_A4/E3.py | E3.py | py | 3,231 | python | en | code | 0 | github-code | 6 |
26831922928 | """
This class is used to cause object-like behavior in non-OOP libraries or enhance polymorphism in objects.
It does so by saving any repetitive parameter in its attributes and passing it into any function that can accept them.
For a demo, see example.py
@author Ben Hsieh
"""
import inspect
class ClassEmulator:
... | hyv3m1nd/classemulator | emulator.py | emulator.py | py | 4,564 | python | en | code | 0 | github-code | 6 |
72530976189 | def main():
# List comprehensions
# [ <expression> for item in list if <conditional>] syntax
# creating a list based on an existing list
# the if part act as a filter (if True it includes, False omittes)
#
my_comp_list = [x for x in range(1,10) if x % 2 == 0]
print(my_comp_list)
# cal... | itiro-y/python-repo | LearningPython/data_types/comprehensions.py | comprehensions.py | py | 1,394 | python | en | code | 0 | github-code | 6 |
1369749447 | """
Import 'OktaPasswordHealth.csv' and sort users into internal and external
groups.
"""
import csv
print("\nWhat is your fully qualified domain name?")
DOMAIN = input('> ')
INTERNAL_USERS = []
EXTERNAL_USERS = []
def write_csv(csv_file, lst):
"""Write results to a csv."""
with open(csv_file, 'w') as out_... | craighillelson/sort_okta_users_internal_and_external | sort_okta_users_internal_and_external.py | sort_okta_users_internal_and_external.py | py | 945 | python | en | code | 1 | github-code | 6 |
26932741505 | from lightcurvetools import *
# should do a smooth-and-subtract operation on the test lightcurve, show a plot,
# and save the smoothed lc
testfile = 'testdata/lc_xrt_alldata.dat'
testlc = readlightcurve(testfile)
testlc.label = 'original'
testlc.stats()
sigma_HW = 2.355/2
wid = round(20/sigma_HW)
smoothlc = smoothlig... | unclellama/lightcurvetools | lightcurvetools/tests.py | tests.py | py | 511 | python | en | code | 0 | github-code | 6 |
8804328521 | import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from datetime import datetime
from BaseTest import BaseTest
from Helper import Helper
from selenium.webdriver.support.ui import WebDriverWait
from se... | Shreyasi2205/MyPOMProject | tests/test_NewsArchive.py | test_NewsArchive.py | py | 27,544 | python | en | code | 0 | github-code | 6 |
75174435386 | from tkinter import *
import time
import threading
from tkinter.ttk import *
def start_download():
GB = 100
download = 0
speed = 1
while download < GB:
time.sleep(0.05)
download += speed
percent.set(str(int(download/GB*100)) + "%")
text.set(str(download) + "/" + str(GB) ... | cakel/python_tutorial_tkinter_brocode | 19_tk_progressbar5.py | 19_tk_progressbar5.py | py | 823 | python | en | code | 0 | github-code | 6 |
17463247487 | #! /usr/bin/python
# import sys
import os
import time
if __name__ == '__main__':
numsOfProducers = [ 5]
numsOfConsumers = [ 5]
Ns = [5, 50, 100]
for prNum, conNum in zip(numsOfProducers, numsOfConsumers):
for N in Ns:
print("producers: ", prNum, " consumers: ", conNu... | youngdashu/systemy-operacyjne-2020-2021 | lab5/NowakAdam/cw05/zad3/runTests.py | runTests.py | py | 770 | python | en | code | 0 | github-code | 6 |
40851164655 | from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.db.models.signals import post_save
from django.conf import settings
class User(AbstractUser):
is_teacher = mod... | ali7070droid/doubts-app | myapp/models.py | models.py | py | 1,197 | python | en | code | 0 | github-code | 6 |
74280991547 | hx711_reference_unit = 226
load_threshold = 1000 # g
loop_interval = 0.1
camera_device = "/dev/video0"
photo_format = "width=1920,height=1080"
photo_count = 4
reset_timeout = 300 # sec
tmpdir = "/tmp"
debug = True
# remote
bot_token="BOT_TOKEN"
channel_id=CHANNEL_ID
| mojyack/rpi-cat-monitor | config-example.py | config-example.py | py | 268 | python | en | code | 0 | github-code | 6 |
8916098020 | # Faça um programa que lê um número inteiro n. E verifique se n é um número par, se não for pedir para inserir outro número até que seja par. Use while.
#usando um laço infinito para o programa continuar executando
while True:
n = int(input("Digite um número: ")) #para While com true, usar o print dentro do laço... | lucasnasc46/curso-python22 | Lista 4 de py/questao5.py | questao5.py | py | 608 | python | pt | code | 0 | github-code | 6 |
31355521081 |
import numpy as np
# some useful constants:
edges = (N,S,E,W) = list(range(4))
def lonlat2cart( lons, lats, rad=1.):
"""Convert longitude/latitude to cartesian coordinates.
Args:
lons (numpy 2-d array): longitude ("x") values (decimal degrees).
lats (numpy 2-d array): latitude ("y") values ... | nasa/simplegrid | simplegrid/util.py | util.py | py | 6,298 | python | en | code | 5 | github-code | 6 |
73652316669 | # 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
# 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。
# 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l = 0
r = len(height) - 1
... | xxxxlc/leetcode | Dynamicprogramming/maxArea.py | maxArea.py | py | 815 | python | zh | code | 0 | github-code | 6 |
37568035732 | # import statements
import nltk
import sys
import pandas as pd
import re
from nltk import pos_tag
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize, sent_tokenize
from sqlalchemy import create_engine
# d... | goitom/project_2_disaster_response | data/process_data.py | process_data.py | py | 3,643 | python | en | code | 0 | github-code | 6 |
16179638713 | import os
import torch
import wandb
import argparse
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.preprocessing import StandardScaler
from sklearn.metrics impor... | jrepifano/mortality-tool | wandb_training/d_train_wandb.py | d_train_wandb.py | py | 5,410 | python | en | code | 0 | github-code | 6 |
33670502801 | import sqlite3
import sys
from PyQt6.QtWidgets import QApplication, QLabel, QWidget, QGridLayout, \
QLineEdit, QPushButton, QMainWindow, QTableWidget, QTableWidgetItem, QDialog, \
QVBoxLayout, QComboBox, QToolBar, QStatusBar, QMessageBox
from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtCore import Qt
# ... | KelvinBrannonJr/Student_Mangement_System | main.py | main.py | py | 13,372 | python | en | code | 0 | github-code | 6 |
35484437119 | def adress_book():
a = {}
while True:
print("Имя - ")
name = input()
if name != "q":
print("Номер - ")
phone = input()
if (phone[0] == "+" and phone[2] == "-" and phone[6] == "-"
and phone[10] == "-" and phone[13] == "-"):
... | TaffetaEarth/homework_python | 0610/hw.py | hw.py | py | 480 | python | en | code | 0 | github-code | 6 |
10648619314 | # -*- coding: utf-8 -*-
"""
Created on Wed May 6 15:04:40 2020
@author: Rijk
Scipy signal sos filter toolbox test
"""
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
plt.close('all')
b, a = signal.butter(4, 100, 'low', analog=True)
w, h = signal.freqs(b, a)
plt.figure()
plt.semilogx(w... | rehogenbirk/MEP_control_software | Measurements/20200324 WO3196dev9/Hydrogen R_T correction/0324_1904_WO3196dev9_H2ToAir/signal_toolbox_test.py | signal_toolbox_test.py | py | 1,897 | python | en | code | 0 | github-code | 6 |
21689221352 | import json
import os
import subprocess
from collections import OrderedDict
from copy import deepcopy
from sys import platform
from tabulate import tabulate
from openwpm.config import ConfigEncoder
def parse_http_stack_trace_str(trace_str):
"""Parse a stacktrace string and return an array of dict."""
stack_... | openwpm/OpenWPM | openwpm/utilities/platform_utils.py | platform_utils.py | py | 5,733 | python | en | code | 1,286 | github-code | 6 |
3681349954 | import json
from dataclasses import dataclass, field
from typing import Union
import requests
@dataclass
class ManyChatAPI:
api_base_url = 'https://api.manychat.com/fb/'
api_key: str
psid: str
headers: dict = field(init=False)
def __post_init__(self):
self.headers = {
'Accept... | daiangan/manychat-dialogflow-connector | utils/manychat_helpers.py | manychat_helpers.py | py | 3,304 | python | en | code | 5 | github-code | 6 |
11079705264 | #------------------------------------------------
#other < supper_code
#Dylan Friesen
#October 30th, 2019
#------------------------------------------------
#--------------Dictionaries--------------------
supper = {}
#------------------Definitions-----------------
def add_stuff_s(): #used to add stuff to... | Gobbo306/libraries-summative | other/supper_code.py | supper_code.py | py | 1,955 | python | en | code | 0 | github-code | 6 |
22626759020 | import pandas as pd
from math import sqrt
import random
import os
import sys
LIB_PATH = os.path.join(os.path.dirname(__file__), '../lib')
sys.path.append(LIB_PATH)
from RandomForest import *
def main():
if (len(sys.argv) < 5):
print("Usage: python3 %s <dataset-csv> <separator> <target-attr> <ntree>" % sy... | rubensrech/ml-random-forest | test/randomForest.py | randomForest.py | py | 1,019 | python | en | code | 0 | github-code | 6 |
20194791845 | # -*- coding: utf-8 -*-
import datetime
import json
import sys
from threading import Thread
from resources.lib.common import tools
from resources.lib.indexers.trakt import TraktAPI
from resources.lib.modules import database
from resources.lib.modules.trakt_sync.shows import TraktSyncDatabase
from resources.lib.module... | Ed57/plugin.video.seren | resources/lib/gui/tvshowMenus.py | tvshowMenus.py | py | 39,641 | python | en | code | null | github-code | 6 |
32466001503 | from tech_news.database import find_news
# Requisito 10
def top_5_news():
"""Seu código deve vir aqui"""
news_list = find_news()
classified_news = sorted(
news_list, key=lambda news: news["comments_count"], reverse=True
)
return [
(news["title"], news["url"])
for news in cl... | janaolive/phyton_raspagem_de_dados | tech_news/analyzer/ratings.py | ratings.py | py | 1,013 | python | en | code | 1 | github-code | 6 |
37950984200 | import pykka
import re
import json
from gpt_connection import GPT_Connection
from tools import ToolRunner
from frontend_utils import initial_request
from bots.Dispatcher import Dispatcher
from bots.Workflow import Workflow
from prompts import DISPATCHER_PROMPT_TEMPLATE, INITIAL_PROMPT_TEMPLATE, ITERATING_ACTION_PROM... | nhuang25/llm-composition | stuffed_animal_llc/stuffed_animal_llc.py | stuffed_animal_llc.py | py | 3,203 | python | en | code | 0 | github-code | 6 |
75125706747 | # # 8/19/2020
# You will work with a binary classification problem on a subsample from Kaggle playground competition. The objective of this competition is to predict whether a famous basketball player Kobe Bryant scored a basket or missed a particular shot.
# Train data is available in your workspace as bryant_shots D... | AndrewAct/DataCamp_Python | Winning a Kaggle Competition in Python/3 Feature Engineering/06_KFold_CrossValidation.py | 06_KFold_CrossValidation.py | py | 2,188 | python | en | code | 0 | github-code | 6 |
2896601636 | from dotenv import load_dotenv
import discord
from discord.ext import commands
import os
import re
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
commMark = os.getenv('COMMAND_MARKER')
description = 'Discord administration bot'
intents = discord.Intents.default()
intents.message_content = True
intents.members ... | Srs2311/gene.py | gene.py | gene.py | py | 4,778 | python | en | code | 0 | github-code | 6 |
37520613786 | import pandas as pd
import redis
from redisgraph import Graph
from config import redisgraph_config
from pathlib import Path
def redisgraph_import_csv(output: Path) -> None:
r = redis.Redis(host=redisgraph_config['host'], port=redisgraph_config['port'])
graph_name = 'movie_graph'
redis_graph = Graph(graph_... | Wojaqqq/graph_data_exchange_tool | imports/redisgraph_import_csv.py | redisgraph_import_csv.py | py | 2,156 | python | en | code | 0 | github-code | 6 |
30353175971 | import sys
import os
from os.path import splitext
import glob
from common import TestCase
def get_tests():
"""Get all the tests to run.
"""
files = glob.glob('test_*.py')
return files
def run_all(tests):
"""Run the given tests.
"""
args = ' '.join(sys.argv[1:])
success = []
fail = ... | enthought/mayavi | integrationtests/mayavi/run.py | run.py | py | 2,323 | python | en | code | 1,177 | github-code | 6 |
39227047564 | import os
import numpy as np
import scipy.io.wavfile as wavfile
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import normalize
from utils import read_textgrid
from numpy_operation import get_martix
from python_speech_features import mfcc
from python_speech_features import ... | MakerFace/voice-activation-system | feature_extractor.py | feature_extractor.py | py | 1,510 | python | en | code | 0 | github-code | 6 |
17007537325 | T = int(input())
for _ in range(T):
N, K = [int(x) for x in input().split()]
time = [int(x) for x in input().split()]
levels = [[0]]
for __ in range(K):
f, t = [int(x) - 1 for x in input().split()]
level = 0
for i in range(len(levels)):
if f in levels[i]:
... | masonHong/INU-Study | Backjoon/HTJ/동적 계획법 기초 단계/1005 ACM Craft.py | 1005 ACM Craft.py | py | 835 | python | en | code | 0 | github-code | 6 |
21766876312 | #! /usr/bin/python3
# id-DNA.py
# http://rosalind.info/problems/dna/
dna_file = open('/home/steve/Dropbox/Rosalind/rosalind_dna.txt', 'r')
dna_string = str(dna_file.readlines())
base_count = {"A": 0, "G": 0, "C": 0, "T": 0}
for base in dna_string:
base_count[base] += 1
print(base_count)
| shuysman/Rosalind | id-DNA.py | id-DNA.py | py | 295 | python | en | code | 0 | github-code | 6 |
13255530705 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from math import sqrt
from scipy import stats
import warnings
warnings.filterwarnings("ignore")
from statsmodels.formula.api import ols
from sklearn.metrics import mean_squared_error, r2_score, explained_variance_score, mean_... | RyvynYoung/COVID | svi_capstone/scripts_python/model_MAE.py | model_MAE.py | py | 12,076 | python | en | code | 0 | github-code | 6 |
13919172422 | from odoo import api, fields, models
class ProjectTask(models.Model):
_inherit = "project.task"
@api.depends(
"stage_id",
"timesheet_ids.unit_amount",
"estimate_adjustment",
"planned_hours",
"child_ids.timesheet_ids.unit_amount",
"child_ids.planned_hours",
... | onesteinbv/ProjectManagement | project_scrum_agile_extended/models/project_task.py | project_task.py | py | 3,845 | python | en | code | 1 | github-code | 6 |
38611022 | import sys
import math
def list_mean(L):
'''Compute the mean of an array. Expects a non-empty array.
Parameters
----------
L : list of int
array containing numbers whose mean is desired.
Returns
-------
m
Arithmetic mean of the values in V
'''
if L is None:
... | cu-swe4s-fall-2019/test-driven-development-adziulko | math_lib.py | math_lib.py | py | 969 | python | en | code | 0 | github-code | 6 |
36956862348 | from angle_controller import *
from x_controller import *
from z_controller import *
from multirotore import *
class Autopilot:
def __init__(self, x_target, z_target):
self.drone = Multirotore(1.0, 0.25, 7.0*(10.0**(-5)))
self.angle_controller = Angle_Controller(4.0, 1.57, 2.0, 0.2, 15.0)
self.x_controller = X_... | SalvoScan/Progetto-Sistemi-Robotici | Sorgenti Progetto/autopilot.py | autopilot.py | py | 881 | python | en | code | 0 | github-code | 6 |
88489070 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2018-19: Homework 5
model_embeddings.py: Embeddings for the NMT model
Pencheng Yin <pcyin@cs.cmu.edu>
Sahil Chopra <schopra8@stanford.edu>
Anand Dhoot <anandd@stanford.edu>
Michael Hahn <mhahn2@stanford.edu>
"""
import torch.nn as nn
# Do not change these imp... | abgoswam/CS224N-Natural-Language-Processing-with-Deep-Learning | a5/model_embeddings.py | model_embeddings.py | py | 3,223 | python | en | code | 18 | github-code | 6 |
14254090936 | from __future__ import division, print_function
from __future__ import absolute_import, unicode_literals
from _GTW import GTW
from _TFL import TFL
from _TFL.defaultdict import defaultdict
import _GTW._OMP._PAP._E164.Country
class Country_33 (GTW.... | xiaochang91/tapyr | _GTW/_OMP/_PAP/_E164/_Country__33.py | _Country__33.py | py | 1,578 | python | en | code | 0 | github-code | 6 |
5381080252 | from socket import *
class sending():
def __init__(self, ip):
# Opens the socket(connection)
self.host = ip
self.port = 13000
self.addr = (self.host, self.port)
self.UDPSock = socket(AF_INET, SOCK_DGRAM)
def send(self, data):
# Sends parameter ... | NightHydra/ColorCardBasic | Color CardPVP/Networking.py | Networking.py | py | 1,901 | python | en | code | 0 | github-code | 6 |
36321645754 | import pygame
from dino_runner.components.dinosaur import Dinosaur
from dino_runner.components.obstacles.obstacle_manager import ObstacleManager
from dino_runner.components.player_hearts.player_heart_manager import PlayerHeartManager
from dino_runner.components.power_ups.power_up_manager import PowerUpManager
from dino... | Shrinmi/JS-Dino-Runner-Grupo-1 | dino_runner/components/game.py | game.py | py | 5,940 | python | en | code | null | github-code | 6 |
26040479196 | from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
from pants.backend.javascript import install_node_package
from pants.backend.javascript.install_node_package import (
InstalledNodePackageRequest,
InstalledNodePackageWithSource,
)
from pants.backend.javascript.no... | pantsbuild/pants | src/python/pants/backend/javascript/run/rules.py | rules.py | py | 2,379 | python | en | code | 2,896 | github-code | 6 |
41464745589 | # Works with Microsoft Windows dos box
# Shows some use of WConio written by Chris Gonnerman
# Written by Priyend Somaroo
# Copyright (c) 2008 Vardaan Enterprises, www.vardaan.com
# Use and distribute freely.
# No liability for any use of this code will be accepted. Use is
# without any warranty whatsoever
... | egigoka/test | just_learning_some_new_stuff/WConioExample.py | WConioExample.py | py | 1,700 | python | en | code | 2 | github-code | 6 |
27009635088 | from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor, GradientBoostingRegressor
def run(x_train, y_train, x_test, y_test,
base_estimator, estimator_params, n_estimators, learning_rate, loss, random_state):
base_estimator = getEstimator(base... | lisunshine1234/mlp-algorithm-python | machine_learning/regression/Ensemble methods/AdaBoostRegressor/run.py | run.py | py | 1,615 | python | en | code | 0 | github-code | 6 |
6513615937 | from unittest import TestCase
from app import app, games
# Make Flask errors be real errors, not HTML pages with error info
app.config["TESTING"] = True
# This is a bit of hack, but don't use Flask DebugToolbar
app.config["DEBUG_TB_HOSTS"] = ["dont-show-debug-toolbar"]
class BoggleAppTestCase(TestCase):
"""Tes... | gary-rivera/flask-boggle | test_app.py | test_app.py | py | 3,070 | python | en | code | 0 | github-code | 6 |
44191894536 | from django.conf.urls import url # include is adding then
from django.contrib import admin
from .views import(
post_home,
post_delete,
post_update,
post_edit,
post_create,
post_save,
)
urlpatterns = [
url(r'^$',post_home),
url(r'^delete/$',post_delete),
url(r'^updat... | hmoshabbar/DjangoProject | posts/urls.py | urls.py | py | 442 | python | en | code | 0 | github-code | 6 |
70510668989 | # -------------------------------
# 스코프(scope) 존재할 수 있는 범위
# -------------------------------
# 변수 종류
# - 전역변수(Global Variable) : 파일 전체에서 사용되는 변수, 같은파일에 존재하는 함수, 클래스 등등 함께사용
# - 지역변수(Local Variable) : 특정 영역 안에서만 사용 가능
#
# 전역변수와 지역변수의 변수명이 동일한 경우
# - 같은 영역안에 있는 변수 우선
# -------------------------------
year = 2022
month = ... | CieData/Study | Python,Pandas/ex_scope.py | ex_scope.py | py | 740 | python | ko | code | 1 | github-code | 6 |
7961667082 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from . import api
from . import gui
try:
import urllib.parse as urllib
except:
import urllib
def play(**kwargs):
import xbmcaddon
addon = xbmcaddon.Addon(id='plugin.video.ran_de')
height = (234, 270, 396, 480, 540, 720)[i... | Maven85/plugin.video.ran_de | resources/lib/index.py | index.py | py | 3,418 | python | en | code | 0 | github-code | 6 |
8665336110 | from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome()
browser.get("http://www.baidu.com/")
browser.maximize_window()
time.sleep(3)
browser.find_element_by_id("kw").send_keys("哈哈")
# 定位百度一下按钮
name = browser.find_element_by_id("su")
# 右击
#... | Zshuangshuang/Reload | 2021_03_12自动化学习/src2021_03_12/testDemo12.py | testDemo12.py | py | 472 | python | en | code | 0 | github-code | 6 |
36040788296 | from ParadoxTrading.Chart import Wizard
from ParadoxTrading.Fetch.ChineseFutures import FetchDominantIndex
from ParadoxTrading.Indicator import ZigZag
fetcher = FetchDominantIndex()
market = fetcher.fetchDayData('20100701', '20170101', 'rb')
zigzag = ZigZag(0.1).addMany(market).getAllData()
wizard = Wizard()
price_v... | ppaanngggg/ParadoxTrading | samples/indicator/zigzag_test.py | zigzag_test.py | py | 510 | python | en | code | 51 | github-code | 6 |
30650525881 | # Matrix Game experiment
# Author: Lucas Cassano
# Paper: "Logical Team Q-learning"
# ===================================
# Import necessary packages
from absl import app
from absl import flags
import numpy as np
import matplotlib.pyplot as plt
import q_mix
flags.DEFINE_string('save_path', '/tmp/', 'directory to save... | lcassano/Logical_Team_Q_Learning_paper | matrix_game/run_matrix_exp.py | run_matrix_exp.py | py | 6,910 | python | en | code | 0 | github-code | 6 |
15720162505 | from collections import deque
def solution(msg):
answer = []
ord_index = 64
cach = dict()
queue = deque()
cach_index = 27
for string in msg:
if len(queue) == 0:
queue.append(string)
elif len(queue) != 0:
queue.append(string)
queue_string = ''... | grohong/Beajoon_Algorism | 프로그래머즈/[3차]압축/main.py | main.py | py | 1,011 | python | en | code | 1 | github-code | 6 |
14037338740 | import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family']='serif'
plt.rcParams['font.serif']=['Times New Roman'] + plt.rcParams['font.serif']
plt.rcParams['mathtext.fontset']='stix'
plt.rcParams['font.size']=10
cm = 1/2.54
Bubble0 = np.genfromtxt("Bubble_0/KellerMiksis_R5.000e-06_fa1.570e+04_pa-... | polycfd/apecss | examples/binaryinteraction/plot_result.py | plot_result.py | py | 2,384 | python | en | code | 13 | github-code | 6 |
36702590099 | # import os and csv
import os
import csv
# variables to be used later
total_months = 0
old_profit = 0
month_change = []
profit_change_list = []
max_increase = ['', 0]
max_decrease = ['', 10000000000000000000000000000000000000]
total_profit = 0
# open csv file and create csv reader
csvpath = os.path.join("/Users/tinch... | mbedino99/Python_Challenge | Pybank/main.py | main.py | py | 1,834 | python | en | code | 0 | github-code | 6 |
70547983867 | """
Python-Rightscale
A stupid wrapper around rightscale's HTTP API
"""
import types
from .actions import RS_DEFAULT_ACTIONS, COLLECTIONS
from .httpclient import HTTPClient
from .util import get_rc_creds, HookList
# magic strings from the 1.5 api
DEFAULT_API_PREPATH = '/api'
# authenticate here
OAUTH2_RES_PATH = '/... | brantai/python-rightscale | rightscale/rightscale.py | rightscale.py | py | 7,065 | python | en | code | 7 | github-code | 6 |
72851324029 | import tensorflow as tf
import numpy as np
class Estimator:
"""Estimator class implements the function approximation for DQN.
The Estimator class defines a NN that is used
by DQN to estimate the Q-function values.
It takes the classification state
as input, followed by a fully connected layer ... | ksenia-konyushkova/LAL-RL | estimator.py | estimator.py | py | 4,139 | python | en | code | 11 | github-code | 6 |
3955950488 | # -*- coding: utf-8 -*-
"""check cache status
* check cache status
* this file uses standalone
"""
import sys
import os
import json
import time
import subprocess
import configparser
from glob import glob
from state_list import get_error_message, DONE
config = configparser.ConfigParser()
config.read("conf... | Neilsaw/PriLog_web | watchdog_status.py | watchdog_status.py | py | 4,426 | python | en | code | 30 | github-code | 6 |
35848057912 | import matplotlib.pyplot as plt
def visualize(n, x, y, file_name):
plt.scatter(x, y)
plt.xlabel('x coordinate')
plt.ylabel('y coordinate')
plt.title(file_name + ': Number of points: %d' % n)
plt.show()
def read_from_file(file_name):
coord_x = []
coord_y = []
with open(file_name, 'r') ... | klauchek/Python_3sem | matplotlib_lab/task1.py | task1.py | py | 744 | python | en | code | 0 | github-code | 6 |
33850689871 | # 第 0012 题:敏感词文本文件 filtered_words.txt,当用户输入敏感词语,
# 则用 星号 * 替换
def replaceword(path):
word_list = []
with open(path, 'r') as f:
for word in f.read().split():
word_list.append(word)
# print(word_list)
inp = input('请输入一个句子:')
for i in word_list:
if i in inp:
print(inp.replace(i, '*'))
if __name__ == '... | akenYu/learnpy | showme/12/replaceword.py | replaceword.py | py | 433 | python | en | code | 0 | github-code | 6 |
19271968449 |
import MDAnalysis
import satoshi_pca as SAS
path = "/lustre7/home/lustre3/satoshi/MED"
TRR = ["/aff4/test_all.trr", "/eaf1/test_all.trr", "/taf7/test_all.trr",
"/aff4_kai/run_all.trr", "/eaf1_kai/run_all.trr",
"/taf7_kai/run_all.trr"]
PDB = ["/aff4/HEN.pdb", "/eaf1/HEN.pdb", "/taf7/HEN.pdb",
... | satoshi-python/Desktop | all_pca_kai.py | all_pca_kai.py | py | 4,342 | python | en | code | 0 | github-code | 6 |
37857057401 | #! /usr/bin/env python3
from uuid import uuid4 as uuid
import argparse
import pika
from protos import events
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument("--exchange", required=True)
p.add_argument("--pretty-print", default=False, action='store_true')
args = p.parse_args()
... | cjmcgraw/studious-carnival | rabbitmq/read-from-exchange.py | read-from-exchange.py | py | 959 | python | en | code | 0 | github-code | 6 |
34321388716 | from datetime import datetime, timedelta
import os
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import (StageToRedshiftOperator,
LoadFactOperator,
DataQualityOperator)
from airflow.operators.subdag... | supratim94336/SparkifyDataPipelineWithAirflow | airflow/dags/udacity_dag.py | udacity_dag.py | py | 3,401 | python | en | code | 0 | github-code | 6 |
13879858183 | import math
N = int(input())
muscle = list(map(int, input().split()))
muscle = sorted(muscle, reverse=False)
max_muscle = 0
pt = math.ceil(N/2)
i = 0
ans_list = []
if N % 2 != 0: # 홀수
max_muscle = muscle[N-1]
while i <= N-i-2:
ans_list.append(muscle[i]+muscle[N-i-2])
i += 1
ans_list.appen... | codusl100/algorithm | 백준/그리디/서강근육맨.py | 서강근육맨.py | py | 456 | python | en | code | 0 | github-code | 6 |
40687860073 | import wsgiserver
from flask import Flask, jsonify
def check_quota_response(**kwargs):
response = kwargs['response']
return jsonify({
'version': 1,
'payload': {
'emptyWallet': not response,
},
})
def setup_flask_server(json_response):
app = Flask(__name__)
ap... | magma/magma | lte/gateway/python/magma/pipelined/check_quota_server.py | check_quota_server.py | py | 868 | python | en | code | 1,605 | github-code | 6 |
32144143111 | from datetime import date
from twilio.rest import TwilioRestClient
# To find these visit https://www.twilio.com/user/account
ACCOUNT_SID = "AC937af250fc201a2c44aad667cf309fa4"
AUTH_TOKEN = "6a8accce5860c8f18391bf4ec809d84b"
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
for message in client.messages.list():
... | suparna-ghanvatkar/EBMP | show_text.py | show_text.py | py | 515 | python | en | code | 0 | github-code | 6 |
39227052944 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import os
import numpy as np
import scipy.io.wavfile as wav
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.constraints import maxno... | MakerFace/voice-activation-system | mfcc-model.py | mfcc-model.py | py | 2,823 | python | en | code | 0 | github-code | 6 |
32839631812 | import torch
from diffusers import DiffusionPipeline
def torch_device():
if torch.cuda.is_available():
return "cuda"
if torch.backends.mps.is_available() and torch.backends.mps.is_built():
return "mps"
return "cpu"
def pipeline(model="stabilityai/stable-diffusion-xl-base-0.9", device=tor... | 2132660698/sdxl-demos | utils.py | utils.py | py | 906 | python | en | code | null | github-code | 6 |
43589412425 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
df = None
# In[2]:
from reaktoro import *
import numpy as np
from natsort import natsorted
from tqdm.notebook import tqdm
import os
from bokeh.io import show, output_notebook
from bokeh.layouts import column
from bokeh.plotting import figure
from bokeh.models import... | nimaamp/Reactive-transport | Nima Benchmark!.py | Nima Benchmark!.py | py | 11,252 | python | en | code | 0 | github-code | 6 |
35227671174 | #!/usr/bin/python
import argparse
def find_max_profit(prices):
max = 0
for i, price in enumerate(prices):
for j in range(i + 1, len(prices)):
profit = prices[j] - price
if max == 0 or profit > max:
max = profit
return max
stocks = [1050, 270, 1540, 3800, ... | glweems/python-algorithms | stock_prices/stock_prices.py | stock_prices.py | py | 354 | python | en | code | 0 | github-code | 6 |
648716471 | import glob
import logging
import os
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
logfilepath = "" # 따로 지정하지 않으면 terminal에 뜸
if os.path.isfile(logfilepath):
os.remove(logfilepath)
logging.basicConfig(filename=logfilepath, level=logging.INFO)
... | DeepFocuser/PyTorch-Detector-alpha | classification/core/utils/dataprocessing/dataset.py | dataset.py | py | 4,393 | python | en | code | 4 | github-code | 6 |
41267173090 | import csv
from getpass import getpass
import math
import controle
def _processa_csv(csv_f, delimiter):
# Formato do arquivo: data, aula, carga_horaria (opcional)
aulas = []
with open(csv_f, encoding='utf-8-sig') as csvfile:
aulas_reader = csv.reader(csvfile, delimiter=delimiter)
for linh... | matheusgr/scripts-controle-academico-ufcg | aulas.py | aulas.py | py | 1,624 | python | en | code | 0 | github-code | 6 |
44254934565 | # GUI Notepad
from tkinter import *
from tkinter.messagebox import showinfo
from tkinter.filedialog import askopenfilename, asksaveasfilename
import os
def newFile():
global file
root.title("Untitled - Notepad")
file = None
TextArea.delete(1.0, END)
def openFile():
global file
file = askop... | SajidMajeed92/Python_Tkinter | Tkinter/Notepad.py | Notepad.py | py | 3,839 | python | en | code | 11 | github-code | 6 |
25793507679 | # -*-coding:utf-8-*-
__author__ = 'BING'
from django.http import HttpResponse
from django.shortcuts import render,render_to_response
from zhihupaper import apiUse,singelNews,latestNews,beforeNews
import re
from getPic import GetPic
def home(request):
api = apiUse()
news = latestNews(api)
count = news.getnu... | codeBing/zhihudaily | paper/views.py | views.py | py | 2,087 | python | en | code | 4 | github-code | 6 |
38120413849 | #Simplex step using row operations
import numpy as np
from numpy.linalg import norm, inv
import sys
def pivot_step(A,i,j): #i=row number, j=column number
A[i] = A[i]/A[i,j]
for k in range(len(A[:])): #updating the column of the matrix so that they equal to 0
if k!=i:
A[k]=A[k]-A[k,j]*A[i]
def... | yohanesusanto/Revised-Simplex-Algo | simplex_step1.py | simplex_step1.py | py | 4,051 | python | en | code | 0 | github-code | 6 |
17435427439 | import pytest
import pdb
from typing import List
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
"""
"""
def intertwine(ws, sps):
# one word + one sps appended
t = []
for w, s in zip(ws, sps):
... | naubull2/codingtests | leetcode/quick-prep/68_Text_Justification/solution.py | solution.py | py | 2,224 | python | en | code | 0 | github-code | 6 |
16866363316 | import pytorch_lightning as pl
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import torch
from torchmetrics import Accuracy
from loss import create_criterion
class Backbone(nn.Module):
def __init__(self):
super(Backbone, ... | KyubumShin/MNIST_pl | model.py | model.py | py | 2,306 | python | en | code | 0 | github-code | 6 |
4404685461 | def users_list(users):
user_list = []
for user in users:
user_info = {'id': user.id, 'name': user.username, 'advertisements': len(user.advertisements)}
user_list.append(user_info)
return user_list
def advertisements_list(advertisements):
adv_list = []
for advertisement in advertis... | gchernousov/advertisements_api_flask | functions.py | functions.py | py | 481 | python | en | code | 0 | github-code | 6 |
19400224964 | import urllib.request
import re
import os
from datetime import datetime
contador = 1
def download(link, curso):
link_video = link
diretorio = get_diretorio(link_video, curso)
urllib.request.urlretrieve(link_video, diretorio)
def get_diretorio(link_video,curso):
padrao = "\w{1,50}.mp4"
curso = cur... | jonassantos1000/robo_maximo_ibm | main.py | main.py | py | 865 | python | pt | code | 0 | github-code | 6 |
71958574589 | from __future__ import unicode_literals
import frappe
import os
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def setup(company=None, patch=True):
if not patch:
update_address_template()
make_custom_fields()
add_custom_roles_for_reports()
def make_custom_fields():
custom_fi... | ektai/erpnext | erpnext/regional/france/setup.py | setup.py | py | 1,447 | python | en | code | 0 | github-code | 6 |
30575157530 | from Domain.BuildEnumMethods import BuildEnumMethods
from .UtilityScriptBase import UtilityScriptBase
import logging
from .Exceptions.ArgNotFoundException import ArgNotFoundException
import json
from mongoengine import connect
import pandas
from Domain.EquityCorporateData import EquityCorporateData
class LoadNasdaqTi... | jminahan/backtest_framework | UtilityRunner/UtilityScripts/LoadNasdaqTickers.py | LoadNasdaqTickers.py | py | 2,352 | python | en | code | 0 | github-code | 6 |
234182160 | from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import math
class ListDock(QDockWidget):
def __init__(self, title, parent = None):
super().__init__(title, parent)
self.setMinimumWidth(150)
self.listwidget = Listbox(self)
self.listwidget.s... | glace158/Pyside_Test | test/dock.py | dock.py | py | 8,154 | python | en | code | 0 | github-code | 6 |
21998644026 | from typing import List
class Trie:
def __init__(self):
self.L = 30
self.left = None
self.right = None
def insert(self, val: int):
node = self
for i in range(self.L, -1, -1):
bit = (val >> i) & 1
if bit == 0:
if not node.left:
... | hangwudy/leetcode | 1700-1799/1707. 与数组中元素的最大异或值.py | 1707. 与数组中元素的最大异或值.py | py | 1,735 | python | en | code | 0 | github-code | 6 |
27577609762 | import random
def coin():
if random.randint(0, 1) == 1:
return "heads"
else:
return "tails"
if __name__ == '__main__':
heads_tally = 0
tails_tally = 0
count = 0
for toss in range(10000):
if coin() == "heads":
heads_tally = heads_tally + 1
elif coin... | Micjohn01/C13-Python-Exercise | Practice/coin_simulation.py | coin_simulation.py | py | 479 | python | en | code | null | github-code | 6 |
27259780990 | """We are the captains of our ships and we stay 'till the end. We see our stories through.
"""
"""701. Insert into a Binary Search Tree [Recursive]
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def insertIntoBST(self, ... | asperaa/back_to_grind | Trees/701. Insert into a Binary Search Tree_clean.py | 701. Insert into a Binary Search Tree_clean.py | py | 566 | python | en | code | 1 | github-code | 6 |
73769261309 | import time
from Pages.CCTVCheckout import CCTV_Checkout
from TestData.Data import Testdata
from Utilities.BaseClass import BaseClass
class Test_two(BaseClass):
def test_CCTVCheckOut(self):
log = self.getlogger() # For log file
CCTV = CCTV_Checkout(self.driver) # Call the page class
lo... | azmul94/Get-Licensed-web | Tests/test_2_CCTVCheckout.py | test_2_CCTVCheckout.py | py | 1,161 | python | en | code | 0 | github-code | 6 |
21471880105 | import Picklizer
import sys
import time
#/home/nickshiell/storage/TestSet
inputCSVDir = ''
outputPKLDir = ''
# Make sure that the command line args are present
if len(sys.argv) == 3:
inputCSVDir = sys.argv[1]
outputPKLDir = sys.argv[2]
else:
print('ERROR: invalid command line args: ', sys.argv)
exit(... | ResearchComputingServices/NewspaperSortByTicker | Pickling/productionScript.py | productionScript.py | py | 519 | python | en | code | 0 | github-code | 6 |
10972428124 | #
# train.py
# @author amangupta0044@gmail.com
# @description
# @created 2020-12-09T16:35:56.524Z+05:30
# @last-modified 2020-12-11T20:05:30.671Z+05:30
#
########### Help ###########
'''
python train.py \
--data_dir /Users/aman.gupta/Documents/eagleview/utilities/onsite_data_fetch/fetched_images/annotated_combine... | aman0044/resnet-classifier | train.py | train.py | py | 6,456 | python | en | code | 0 | github-code | 6 |
7160221934 | # Answer to Lift queries
# https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/lift-queries
A, B = 0, 7
for _ in range(int(input())):
n = int(input())
if abs(n-A) < abs(n-B):
A = n
elif abs(n-A) > abs(n-B):
B = n
el... | CompetitiveCode/HackerEarth | Basic Programming/Input Output/Lift queries.py | Lift queries.py | py | 402 | python | en | code | 1 | github-code | 6 |
2140106274 | import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import init_multi as im
import func_multi as fm
'''
BEGING PROGRAM
'''
# функция отрисовки изображения, использует convert() для получения данных из fifo
def showTrack(i):
x1, y1 = fm.ellipseCreate(20+5*i, 30, 50, 70-3*i, 0.05*i)
im.ellipse1.setData(x1... | NazimAliev/public | embedded/passive-radar-fpga-dsp-arm/multix86/main_multi.py | main_multi.py | py | 1,879 | python | ru | code | 0 | github-code | 6 |
19346831151 | import tensorflow as tf
import numpy as np
import pickle
import os
import re
import text2emotion as te
class EmotionRecognitionModel():
def __init__(self) -> None:
self.model = tf.keras.models.load_model(os.path.join(os.path.dirname(__file__), './trained_model/emotion_model.h5'))
self.index_to_cla... | Socialet/web-backend | app/toolkit/EmotionRecognition/model.py | model.py | py | 2,317 | python | en | code | 0 | github-code | 6 |
38447711574 | import sys
import os
import json
from parse import validate_file
if __name__ == '__main__':
outputs_dir = sys.argv[1]
submission_name = sys.argv[2]
submission = {}
for input_path in os.listdir("inputs"):
graph_name = input_path.split('.')[0]
output_file = f'{outputs_dir}/{graph_name}.ou... | Sea-Snell/170project | prepare_submission.py | prepare_submission.py | py | 588 | python | en | code | 7 | github-code | 6 |
22094537095 | import logging
import datetime
import sqlite3
import voluptuous as vol
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'hasentinel'
CONFIG_SCHEMA = vol.Sc... | dennis-bell/HASentinel | custom_components/hasentinel/__init__.py | __init__.py | py | 3,269 | python | en | code | 0 | github-code | 6 |
17433146324 | from sikuli import *
from test_helper import *
import os
def open_handler(event):
Debug.user("Successfully opened flex.")
event.stopObserver()
wait(45)
# Don't stop observer, to give it time to open before
# the next script runs.
# Open Flex from the start screen
def open_new_project(project_name="... | sillsdev/FwIntegrationTests | general_tests/helpers/open_new_project.sikuli/open_new_project.py | open_new_project.py | py | 661 | python | en | code | 1 | github-code | 6 |
10915507732 | '''
problem:
You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.
Input Format--
The first line contains a string, S.
The second line contains the width, w.
Constraints--
0<len(s)<1000
0<=w<=len(s)
Output Format--
Print the text wrapped paragraph.
Sample Input 0
ABCD... | harshitbansal373/python | text-wrap.py | text-wrap.py | py | 737 | python | en | code | 15 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.