index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
2,400 | cbf93eb96f40ff0aedc4b8d9238669da72934b27 | import time
from helpers.handler import port_handler
from helpers.functions import fetch_all
class ascii_handler(port_handler):
"""
Serve ASCII server list
"""
def handle_data(self):
"""
Show a nicely formatted server list and immediately close connection
"""
self.ls.... |
2,401 | 19d86c64876575ed9b3f5e33dd44e7633c96e696 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2010-2014 Elico Corp. All Rights Reserved.
# Alex Duan <alex.duan@elico-corp.com>
#
# This program is free software: you can redistribute it and... |
2,402 | a7099b2506de08893ca849146813505d88784895 | #!/usr/bin/python3
#https://github.com/pfnet-research/chainer-gan-lib/blob/master/wgan_gp/updater.py
import numpy as np
import chainer
import chainer.functions as F
from chainer import Variable
from chainer.dataset import convert
class WGANUpdater(chainer.training.updaters.StandardUpdater):
def __init__(self, *a... |
2,403 | cb904408486ad9ea8cc0c8ff2ec393e480309a57 | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain ... |
2,404 | e30aaf1616a107662924da3671b179a1887974f7 | from flask import render_template, request, redirect, url_for, send_file
from flask_app import app
import re
import os
from werkzeug.utils import secure_filename
import numpy as np
import cv2 as cv
from flask_mail import Message, Mail
file_path_file = open('flask_app/file_path.txt', 'r')
vars = file_path_file.readline... |
2,405 | d4361b169bf75d3af82eca3d26609961ccc2f27e | from find import Solution
array = [[1,2,3],[4,5,6],[7,8,9]]
solution = Solution.Find(6,array) |
2,406 | 74faeb1c09fe136ec4d9578173aeebe54b451e33 | from .import bp as authentication
from app import db
from flask import current_app as app, render_template, request, redirect, url_for, flash, session
from flask_login import login_user, logout_user, current_user, login_required
from .forms import Register, Login, Settings
from .models import User
# route for register... |
2,407 | 743aa4ccbb9a131b5ef3d04475789d3d1da1a2fa | # coding:utf-8
from flask_sqlalchemy import SQLAlchemy
from config.manager import app
from config.db import db
class Category(db.Model):
__tablename__ = 'category'
id = db.Column(db.Integer, primary_key=True) # 编号
name = db.Column(db.String(20), nullable=False) # 账号
addtime = db.Column(db.DateTime, ... |
2,408 | 418f2e1cbe4fb3ef369e981e72bf40eeddfd052e | import torch.nn as nn
def my_loss():
return nn.CrossEntropyLoss() |
2,409 | 66b42791325a53172d4514cdd16ccd58d4edb186 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
class Gerenciador(ScreenManager):
pass
class Menu(Screen):
pass
class Tarefas(Screen):
def __init__(self, tarefas=[], **kwargs):
super().__init__(**kwargs)
for tar... |
2,410 | 0354445d255cc79d3cb9242f82d37e035ff61788 | /Users/jhajhajhajha1/anaconda/lib/python3.6/codecs.py |
2,411 | c46495eebbe796253f56b7472d5548b41c5d0bc4 | def part_1() -> int:
start = 382345
end = 843167
total = 0
for number in range(start, end + 1):
if check_number(str(number)):
total += 1
return total
def check_number(problem_input: str) -> bool:
previous = 0
double = False
for current in range(1, len(problem_inpu... |
2,412 | 1c5ca920fe1f116a5bc52c9e5c53c13b1e1c925f | def tobin(n):
bin = "";
while(n/2!=0):
if n%2==0:
bin = bin + "0"
else:
bin = bin + "1"
if n%2==1:
bin = bin + "1"
return bin
n = int(input())
bin = tobin(5)
print(bin)
|
2,413 | f193094c551df2a32860948b1a8710b53ca0dfb6 | import random
#quicksort a list of objects based on keys, which can be any of 3 values
# done in O(n) time in one pass, and O(1) additional space complexity
def quicksort(x, pivot_index):
key1_idx, key2_idx, key3_idx = 0, 0, len(x)
key1_val, key2_val= 'key1', 'key2'
while key2_idx < key3_idx:
if x... |
2,414 | 0c7efa99dc22154f9835b277cba5057b213a28e7 | from django.apps import AppConfig
class NombreaplicacionConfig(AppConfig):
name = 'nombreAplicacion'
|
2,415 | d0364b7cad29c639af9df5c78e810144ffd6ce2e | from utils import to_device
from utils import build_dictionary,my_collate
from DataGenerator import DataGenerator
from torch.utils.data import DataLoader
from torch import optim
import torch.nn as nn
from ADSentimentModel import ADSentimentModel
import torch
def train(token2id, train_data, lr, batch_size, epochs,model... |
2,416 | 43d9edd9120351ce5065eb266d482ccaa2e56177 | from keras.models import Sequential
from keras.layers import Dense
import numpy as np
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
x2 = np.array([11, 12, 13, 14, 15])
model = Sequential()
model.add(Dense(5, input_dim=1, activation='relu'))
model.add(Dense(3))
model.add(D... |
2,417 | eca40c37e0e437a5f4e5643f5fb7cd3e38605471 | from django.shortcuts import render
from .models import Team,ContactForm
from cars.models import Car
from django.contrib import messages
# Create your views here.
def index(request):
teams=Team.objects.all()
cars = Car.objects.order_by("-created_date").filter(is_featured=True)
all_cars=Car.objects.order_by(... |
2,418 | 77a82f99ab10e3d53e3f8466d43b67e8b87c1588 | print(1)
print(2)
print("Jenkins")
print("Jenkins2")
print("Jenkins3")
print("Jenkins44")
print("Jenkins55khlk")
print("3333333")
print("44444444")
print("jhjhj")
|
2,419 | 28f4f14c3c29ee96c370ffe71c268549552b915e | from django.db import models
from django.contrib.auth.models import User
from Event.models import Event
from University.models import University
from django.core.validators import validate_email
class Person(models.Model):
user = models.ForeignKey(
User, related_name='person', on_delete=models.CASCADE,
... |
2,420 | 660334be611c30397c2f33890e1bca1fc43bd01f | import numpy as np
import matplotlib.pyplot as plt
from math import *
from scipy.integrate import *
from pylab import *
from scipy.integrate import quad
MHD = np.zeros((80, 90, 5), dtype=float)
BGI = np.zeros((80, 90, 5), dtype=float)
Fp = np.zeros((80), dtype=float)
AngMHD = np.zeros((90,2), dtype=floa... |
2,421 | 95ea8a21d3ac44c7760179bc4ebf67f0c16e6a19 | """
module : watcher.py
description : Script to automatically watch a directory (via watchdog) for tests and run them via py.test
"""
import sys
import os.path
import subprocess
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class SpecificationsEventHandler(Fil... |
2,422 | 18a49d46b39fe6e00e2ad137984cceab82f1e94b | import sys
import time
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import *
class PromptMessage(QWidget):
def __init__(self, parent = None):
super(PromptMessage,self).__init__(parent)
self.m_show_tm = QTimer()
self.m_stay_tm = QTimer()
... |
2,423 | 74bc530d53cd86c52c44ba8e98d4d8f502032340 | # -*- encoding:utf-8 -*-
import os
import unittest
from HTMLTestRunner_cn import HTMLTestRunner
from time import sleep
from framework.SunFlower import SunFlower
from testcase.TestCRM import TestCRM
class TestCRMcreateCustomer(TestCRM):
# 创建客户
def createCustomer(self):
# 点击客户图标
self.driver.... |
2,424 | 825f3b930fee319314d520a32c2f9dcd718505ab | '''
Sample Input
1
5
1 2 3 2 1
Sample Output
3
'''
for _ in range(int(input())):
noe = int(input())
arr = [int(x) for x in input().split()]
left = arr[0]
rite = sum(arr) - left
mins = abs(rite - left)
for i in range(1, noe-1):
left += arr[i]
rite -= arr[i]
print(left, rit... |
2,425 | ff0495ee1f4aa1f243c82b709a974d3d7c37e8bd | """
Download the full CHIRPS 2.0 data for a specific type (dekads, pentads, daily ...)
with the possibility to automatically recut the data over Argentina.
"""
import os
import requests
import urllib.request
import time
from bs4 import BeautifulSoup
import subprocess
##############
# PARAMETERS to define
# Set a pre... |
2,426 | 70b08b9e8c1510a9be48a4bc1de39c6c85b36eed | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import sys
import json
import math
from klpmln import MVPP
dprogram = '''
img(i1). img(i2).
addition(A,B,N) :- digit(A,1,N... |
2,427 | 2ea335dd8d879731aad7713499440db6d1f60d36 | #!/usr/bin/env python
#
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... |
2,428 | d6bc8afcdb7636085b01add860f808024fbe566d | import sys
lines = sys.stdin.readlines()
t = int(lines[0])
for i in range(t):
c = i*10+1
n = int(lines[c]) - 1
first = [x.strip() for x in [
lines[c+1],
lines[c+2],
lines[c+3],
lines[c+4]]]
first = [s.split() for s in first]
m = int(lines[c+5]) - 1
second = [x.... |
2,429 | 0b833276ca10118f2d60e229ff03400b03915958 | """Base class for an array of annotated genomic regions."""
import logging
from typing import Callable, Dict, Iterable, Iterator, Mapping, Optional, Sequence, Union
from collections import OrderedDict
import numpy as np
import pandas as pd
from .chromsort import sorter_chrom
from .intersect import by_ranges, into_ran... |
2,430 | 5debc97e99bbd78b17e545896d718d4b0eac8519 | """
Urls for CAE_Web Audio_Visual app.
"""
from django.conf.urls import url
from . import views
app_name = 'cae_web_audio_visual'
urlpatterns = [
]
|
2,431 | af9adc0faad4fc1426a2bd75c1c77e23e37b60bf | # -*- coding: utf-8 -*-
# @Time : 2020/6/12 20:19
# @Author : damon
# @Site :
# @File : work0612
# @Software: PyCharm
import math
"""
1、给定n=10,计算1! + 2! + 3! + ... + n!的值
"""
# 解法1:
n = 10
factorial = 1
sum = 0
for i in range(1, n+1):
factorial = i * factorial
sum += factorial
print(f"阶乘之和{sum}")... |
2,432 | 2ee5991e2b6de6ee48c8207f2b78574fc8a02fc0 | #! /usr/bin/python
# Project Euler problem 21
"""Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 ... |
2,433 | 6216a5e45fee8ade5ec9072c42c1b08f3b0f4c65 | class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def validateIPv4(IP):
digits = IP.split('.')
if len(digits) != 4:
return False
for digitstr in digits:
if len(digitstr)... |
2,434 | 59338170b44be037f749790a7942c2bcca1fc078 | #!/usr/bin/env python
###############################################################################
#
#
# Project:
# Purpose:
#
#
# Author: Massimo Di Stefano , epiesasha@me.com
#
###############################################################################
# Copyright (c) 2009, Massimo Di Stefano <epiesasha@me.c... |
2,435 | e2f134f5ff00405396b8bbf4edc263b70ef5d972 | import re
import sys
import zipfile
import pathlib
from typing import IO, Any
from collections.abc import Mapping
import numpy.typing as npt
import numpy as np
from numpy.lib._npyio_impl import BagObj
if sys.version_info >= (3, 11):
from typing import assert_type
else:
from typing_extensions import assert_typ... |
2,436 | bbb23d606b081d2591699cb6b9336c8766eea5b2 | s=input("enter a string")
u=0
l=0
for i in s:
if i.isupper():
u+=1
elif i.islower():
l+=1
print(u,l,end="") |
2,437 | fdb680f12dfb4b29f25cfe4f7af80469dc4294cf | # Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.shtiker.CogPageGlobals
COG_QUOTAS = ((30, 25, 20, 15, 10, 5, 2, 1), (45, 40, 35, 30, 25, 20, 15, 10))
COG_UNSEEN = 1
COG_BATTLED = 2
COG_DEFEATED = 3
COG_COMPLETE1 = 4
COG_COMPLETE2 = 5 |
2,438 | 0b0282ade565eb4031cef3a2fa8605249f104d9d | import os
import sys
import platform
import numpy as np
import sklearn.preprocessing as sp
def deal_with_ohe(raw_sample):
# --------------------#
# 10 100 0001 #
# 01 010 1000 #
# 10 001 0100 #
# 01 100 0010 #
# --------------------#
ohe_sample... |
2,439 | 7c2349810fc757848eeb5bddef4640d87d5f9ab9 | #!/usr/bin/env python
#-*-coding:utf-8-*-
#author:wuya
import os
import xlrd
import json
class Helper(object):
'''公共方法'''
def base_dir(self,filePath,folder='data'):
'''
返回公共路径
:parameter folder:文件夹
:parameter filePath:文件名称
'''
return os.path.join(
os.path.dirn... |
2,440 | 9de2589cfb5bebba789ece8df9a0fcfbedb01173 | #!/usr/bin/env python
import sys, re, urllib, urllib2, string, time, os
from urllib2 import Request, urlopen, URLError, HTTPError
from urlparse import urlparse
joomla_version="undefined" #used for joomla veersin info
provided_url="" #the selected provided url
verbose_flag = 0 # If set to 1, prints... |
2,441 | f2397ba3fe1452238f251111f35b06b4a93e0359 | # __author__ = 'Vasudev Gupta'
import tf_lightning as tl
import tensorflow as tf
class TestModel(tl.LightningModule):
# just a random model with random dataset
def __init__(self):
# simple test model
super().__init__()
self.model = tf.keras.Sequential([
tf.keras.layers.D... |
2,442 | 4a63431aa71ca3f4b75fcd89a50bf599e7717645 | import argparse
import debug.debug as dbg
import helper.helper as hlp
import prep.preprocessor as pre
import sample.sample as s
def main(dir_train, C, gamma, number_partitions, do_subsampling, write_labels):
hlp.setup_logging()
# Files as folds?
if number_partitions is None or number_partitions == 0: #... |
2,443 | 8ede786526f4b730173777d9d3b9c7e4554fc887 | config_info = {
'n_input': 1,
'num_layers': 1,
'features': 20,
'sequence_length': 1344,
'num_steps' : None,
'lstm_size' : None,
'batch_size' : None,
'init_learning_rate' : None,
'learning_rate_decay' : None,
'init_epoch' : None,
'max_epoch' : None,
'dropout_ra... |
2,444 | 624ecf743d5be1acc33df14bd721b3103d232f0e | #!/bin/usr/python
'''
Author: SaiKumar Immadi
Basic DBSCAN clustering algorithm written in python
5th Semester @ IIIT Guwahati
'''
# You can use this code for free. Just don't plagiarise it for your lab assignments
import sys
from math import sqrt
from random import randint
import matplotlib.pyplot as plt
def main(a... |
2,445 | aeef27d667f95e3818f73533439385ea949b96a4 | #!/usr/bin/env python
import webapp2 # web application framework
import jinja2 # template engine
import os # access file system
import csv
from google.appengine.api import users # Google account authentication
from google.appengine.ext import db # datastore
# initialise template
jinja_environment = jinja2.Envir... |
2,446 | 7f5f16ea10980e0ade7357cdae38f47f8d7cdf01 | import re
from collections import defaultdict
def count_words(sentence):
# extract all the words as per definition
sentence = re.findall(r"\b[\w'-]+\b", sentence.lower().replace('_', ' '))
counts = defaultdict(lambda: 0)
# Counting the frequency of each words
for word in sentence:
counts[w... |
2,447 | f26e6164fc4c07fd3339171e316b3a1f7a4be669 | import os.path as osp
from evaluations.common import tiou
from evaluations.util import load_file
import generate_track_link
def eval_ground_scores(gt_relations, pred_relations, tiou_threshold):
"""
:param gt_relations:
:param pred_relations:
:param tiou_threshold:
:return:
"""
# pred_relat... |
2,448 | 9555e5f75e3045afff6da9228764fca542caf539 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Beach',
fields=[
('id', models.AutoField(verbos... |
2,449 | 97ea837961c92b5c92a93ec33ac016de7ff1e876 | import numpy as np
import pandas as pd
import math
import sklearn
import sklearn.preprocessing
import datetime
import os
import matplotlib.pyplot as plt
import yfinance as yf
import math
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.layers impor... |
2,450 | ed7fa6e6f30eb06400cb38128617967a597f6c04 | '''
Implement GreedyMotifSearch
http://rosalind.info/problems/ba2d/
Given: Integers k and t, followed by a collection of strings Dna.
Return: A collection of strings BestMotifs resulting from running GreedyMotifSearch(Dna, k, t). If at any step you find more than one Profile-most probable k-mer in a given string, use... |
2,451 | b46fe26f1a3c9e93e735b752e54132bd95408251 | # -*- coding: utf-8 -*-
"""
测试如何使用python的pymongo模块操作MongoDB
@author: hch
@date : 2020/10/8
"""
import logging
import time
import traceback
from pprint import pprint
from pymongo import MongoClient
from pymongo.cursor import Cursor
from pymongo.results import DeleteResult, InsertOneResult, UpdateResult
class MongoT... |
2,452 | 9583a97ae4b1fbf5ecdf33d848b13bf0b28d2eb4 | from package.pack import *
add(2,2)
sub(2,3) |
2,453 | 55cf99e3493c9c94955fc7e75ac428cbd88ac5cf | from django.conf import settings
from django.urls import resolve
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, JsonResponse, HttpResponseNotFound
from django.template.loader import get_template, render_to_string
from django.views.g... |
2,454 | c6821cb8dd6f8d74ca20c03f87dae321eb869c32 | import os
import attr
import click
import guitarpro
import psutil
ALL = object()
@attr.s
class GPTools:
input_file = attr.ib()
output_file = attr.ib()
selected_track_numbers = attr.ib(default=None)
selected_measure_numbers = attr.ib(default=None)
selected_beat_numbers = attr.ib(default=None)
... |
2,455 | 90218168841dc76febab67d1e992dfc993730ea4 | import math
import numpy as np
import matplotlib.pyplot as plt
def test_func(x):
# x is vector; here of length 1
x = x[0]
return math.cos(x) * x**2 + x
def run_smac(max_fun=30):
from smac.facade.func_facade import fmin_smac
x, cost, smac = fmin_smac(func=test_func,
... |
2,456 | 2b1ec422a42af59a048c708f86b686eb0564b51f | from django.conf.urls import url
from django.urls import path
from .views import *
from flujo.views import *
"""
URL para el Sprint crear, listar y modificar
"""
urlpatterns = [
url(r'^$', SprintListView.as_view(), name='sprint_list'),
path('create/', view=CreateSprintView.as_view(), name='create_sprint'),
... |
2,457 | a555226b14223dca688d10b811eb36fb229360ce | # ================================================== #
# MAIN WINDOW #
# ================================================== #
# Author: Brady Hammond #
# Created: 11/21/2017 #
# Last Edited: N/A ... |
2,458 | 9a40861239268aa62075b77b3ed452f31bb14fac | """
openAI gym 'cart pole-v0'
"""
import numpy as np
import tensorflow as tf
from collections import deque
import random
import dqn
import gym
import matplotlib.pyplot as plt
# define environment
env = gym.make('CartPole-v0')
# define parameters
INPUT_SIZE = env.observation_space.shape[0]
OUTPUT_SIZE = env.action_sp... |
2,459 | dcda8f26a06145579a9be6e5fbfdaed83d4908da | from typing import Tuple
#Creating a trie structure and it's node
class TrieNode(object):
def __init__(self, char: str):
self.char = char
self.children = []
#the last character of the word.`
self.word_finished = False
#counter for this character
self.counter = 1
... |
2,460 | 8afaa69d3a20c5e39e6321869f25dbd9020a5b3a | import sqlite3
conn = sqlite3.connect("blog.db")
c = conn.cursor()
q = "CREATE TABLE users(Username text, Password text, UserID integer)"
c.execute(q)
q = "CREATE TABLE blogs(Title text, Content text, BlogID integer, UserID integer)"
c.execute(q)
q = "CREATE TABLE comments(Content text, CommentID integer, BlogID i... |
2,461 | e5a698979bc84fe733a9bf5cd51e2f078956d468 | import random
from elment.login_registration_element import LoginRegistration
from page.test_verification_code_page import VerificationCodeAction
public_number_vip = ['17800000000','17800000001','17800000002','17800000003','17800000004','17800000005','17800000006',
'17800000007','17800000008','1780000... |
2,462 | 05cfd9d239b63c9b1e0c93a09e89cceb8d8e99e4 | import os
import time
try:
import cPickle as pickle
except:
import pickle
#-------------#
# Cache utils #
#-------------#
cachedir = os.path.expanduser('~/.cache/sherlock/')
_cachedict = {}
def get_cachefile(filename):
"""
Return full path to filename within cache dir.
"""
if not os.path.e... |
2,463 | 3f473701b186b5287258ba74e478cccdad0f29bf | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@File : corr2d.py
@Author : jeffsheng
@Date : 2020/1/3
@Desc : 卷积层中的互相关(cross-correlation)运算
卷积层需要学习的参数是:卷积核和偏置大小
"""
import tensorflow as tf
def corr2d(X, K):
"""
定义二维互相关运算函数
:param X:输入数组
:param K: 核数组
:return:二维互相关的运算结果
"""
h, w = K.sh... |
2,464 | de634c95fddf4591cb15cd0eb20e798043075798 | #Answer to The Ship Teams - https://py.checkio.org/en/mission/the-ship-teams/
def two_teams(sailors):
result = [] #To store the result
temp = [[],[]] #To store the intermediatary values
for i in sailors.items(): #To get the values of dictionary as Tuple
if i[1] > 40 or i[1] < 20: #To get the people... |
2,465 | 3c029adb59cd6db1e3d4a22e6561f5e2ae827d60 | # https://daphne-dev.github.io/2020/09/24/algo-022/
def solution(n):
arr = [[0 for _ in range(i+1)] for i in range(n)]
# 경우의수 는 3가지
# 1. y축이 증가하면서 수가 증가
# 2. x축이 증가하면서 수가 증가
# 3. y,x축이 감소하면서 수가 증가
size = n
num = 0
x = 0
y = -1
while True:
# 1번
for _ in range(size)... |
2,466 | 6b5399effe73d27eade0381f016cd7819a6e104a | import tensorflow as tf
import cv2
img=cv2.imread('d:\st.jpg',0)
cv2.namedWindow('st',cv2.WINDOW_NORMAL)#可以调整图像窗口大小
cv2.imshow('st',img)
cv2.imwrite('mes.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows() |
2,467 | 72f1547ea7de78a5fe4b583523e592fa25c0ee77 | import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
username=st.text_input ("username")
upload=st.file_uploader("uploadfile",type=['csv'])
button=st.button("submit")
if button==True:
df=pd.read_csv(upload)
st.write(df.head())
fig = plt.figu... |
2,468 | 657866affd653a99eb7d9a9a82b2f7d6503ec21a | from parser import read_expression_line, read_expression_lines, read_assignment_line, read_import_line, Import
def test_expression():
lines = ['a % b']
expression, left = read_expression_lines(lines)
assert expression is not None and len(left) == 0, left
print "test_expression 0: {} {}".format(expressi... |
2,469 | 08c309645a4ee59716bdd00556096be1c784331a | # -*- coding: UTF-8 -*-
'''=================================================
@Project -> File :AutoMailApp -> handle_yaml
@IDE :PyCharm
@Author :Mr. wang
@Date :2019/11/15 0015 19:53
@Desc :
=================================================='''
import yaml
from Common.dir_path import YAML_FILE_PATH
class Han... |
2,470 | a73dcfc21c31d4e984db39c072d11cb9a9c3d5e5 | """
The MIT License (MIT)
Copyright (c) 2021-present Pycord Development
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, ... |
2,471 | ccd1e57518065963158984dda52297db45ce204e | # coding: utf-8
etc_dictionary = {
'2 30대': '이삼십대',
'20~30대': '이삼십대',
'20, 30대': '이십대 삼십대',
'1+1': '원플러스원',
'3에서 6개월인': '3개월에서 육개월인',
}
english_dictionary = {
'Devsisters': '데브시스터즈',
'track': '트랙',
# krbook
'LA': '엘에이',
'... |
2,472 | ec0697d8d78fafe6bfd4630be2a1fb20eb9eb4cf | import boto3, os, shutil, datetime, time, sys
session = boto3.Session(profile_name='default')
s3 = boto3.resource('s3')
bucket = s3.Bucket('netball-ml-processed')
#print(bucket.objects)
#needs to be run with *** sudo **** otherwise it won't work...
while True:
#change to the motion working Directory
os.... |
2,473 | 316a34bbc2b3e3c818ef837f51bc1f86863ea59a | # Generated by Django 2.2.6 on 2020-05-27 19:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pancar', '0006_auto_20200526_1058'),
]
operations = [
migrations.AlterField(
model_name='process',
name='price',
... |
2,474 | 9cb5573fada7a1529507da1d031f836044c10066 | class Solution:
def longestConsecutive(self, nums) -> int:
s = set(nums)
answer = 0
# n = len(s)
for value in s:
if value - 1 not in s:
j = value
while (j in s):
j = j + 1
answer = max(answer, j - val... |
2,475 | 43ae01ffe35c6c4491f3f7e480dd6f5c1be86eb2 | # Generated by Django 3.1.1 on 2020-12-02 19:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('element', '0011_suggestion_suggestion_type'),
('bot', '0001_initial'),
]
operations = [
migrations.AddField(
model_name=... |
2,476 | 24c1f5195bad17f995fb97a03218fc9bbe5ce4cd | """
Question 39:
Define a function which can generate a list where the values are square of numbers between 1 and
20 (both included). Then the function needs to print the last 5 elements in the list.
"""
#To get a value from console input.
input_num = input("Write number:")
lis1=[]
lis2=[]
def lis(n1,n2):
"""
Gener... |
2,477 | 671a7ee3fabee6ed8dfafe1bddefb1f94322b0e5 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-07-26 19:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0014_auto_20180726_0926'),
]
operations = [
migrations.AlterFi... |
2,478 | 8c0377b70b902e6e61351869a4378b4c2c50a3a7 | def get_all_lefts(word,substring):
if len(substring) == 0:
yield ((len(word),word),)
else:
if substring[0] not in word:
yield (-1,)
else:
for i in range(len(word)):
if word[i] == substring[0]:
for sub_sequance in get_all_lefts(w... |
2,479 | 6d2581b83a2839dcbc644ca572b05b158d80b58d | from enum import Enum
# Genie
from genie.decorator import managedattribute
from genie.conf.base import Base, \
DeviceFeature, \
LinkFeature, \
Interface
import genie.conf.base.attributes
from genie.libs.conf.base.feature import consoli... |
2,480 | 3f4b484f435936137cb8511ec6e0aa89efb267c4 | # Given a stream of numbers, print average (or mean) of the stream at every point.
def getAverage(prev_avg, val, n):
return ((prev_avg * n) + val) / (n + 1)
def findAndPrintMovingAvgs(arr):
cur_avg = 0
for i in range(len(arr)):
cur_avg = getAverage(cur_avg, arr[i], i)
print "Avg at", i, "i... |
2,481 | 32105a245f6945dbe8749140d811b20d634289bc | import chainer
import chainer.functions as F
import numpy as np
import argparse
from model import Generator, Discriminator
from chainer import cuda, serializers
from pathlib import Path
from utils import set_optimizer
from dataset import DatasetLoader
xp = cuda.cupy
cuda.get_device(0).use()
class CycleGANVC2LossCal... |
2,482 | 3e1e2de555667bf09162cd6c62cad35dabbd0f54 | from flask import Flask
from flask import render_template
# Creates a Flask application called 'app'
app = Flask(__name__, template_folder='C:\Users\jwhitehead\Documents\Webdev\Angular Web App')
# The route to display the HTML template on
@app.route('/')
def host():
return render_template('index.html')
# Run the... |
2,483 | e2573a5dc507e9aeb811fbc254129aeb6e54cc0b | from django.contrib import admin
from calc.models import CalcResult
class MyAdmin(admin.ModelAdmin):
def has_add_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
class CalcResultAdmin(MyAdmin):
list_display = ('result', ... |
2,484 | 7c9c13974e1deeb55f08c9e251e8c876cedcad6b | import math
import time
def calculate_time(func):
def inner_fn(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print("Time taken to execute \'{}\' function is: {} seconds".format(func.__name__, round(end - start, 2)))
return i... |
2,485 | fef4749ce7b8668a5a138aa1245010866a85c853 | class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
output = []
index = 0
for i in asteroids:
if len(output) == 0:
index = 0
if index == 0:
output.append(i)
index+=1
... |
2,486 | 0372cdbae8c5b0bbcbade86a5a7de28c1ee513b1 | # Write files
# Writing to a file within a Python program:
# In order to write to a file, we use file.write(str).
# This method writes a string to a file.
# The method write() works like Python's print() function, except it does not add a newline ("\n") character.
# File dialogs:
# Module tkinter has a submodule cal... |
2,487 | 84db1803a352e0ed8c01b7166f522d46ec89b6f5 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import c... |
2,488 | 0b0b928aef9a4e9953b02639bf5e7769cc4389d7 | default_app_config = 'reman.apps.RemanConfig'
|
2,489 | 34e902fbced13629657494eedfe385d3b5ae3f55 | # TUPLE IMUTAVEL
# GERALMENTE HETEORGENEA
# tupla com 1 ou 0 elementos
#
# empty = ()
# singleton = 'breno',
# print(type(empty))
# print(singleton)
# tuplas podem ser aninhadas
# t = 12345, 54321, 'hello!'
# u = t, (1, 2, 3, 4, 5)
#imutaveis
# t[0] = 88888 |
2,490 | 93133b9a62d50e4e48e37721585116c1c7d70761 | from symcollab.algebra import *
from .ac import *
from copy import deepcopy
# This is a single arity function which only actually gets applied when called an odd number of times
# Useful for the inverse function later on
# A group G is an algebraic structure which satisfies the following properties
# (1) G is closed... |
2,491 | 994210b3de82af02ec7b1b7bee75ceb88ffb2bd5 |
HORIZONTAL_TABLE = b'\x09'
class ReagentInfoItem():
'''
This class if defined for a single reagent info unit, from the table's view, its a cell of the table.
'''
def __init__(self, reagent_name, reagent_count):
self.reagent_name = reagent_name
self.reagent_count = reagent_count
de... |
2,492 | a9df8e45c8b5068aeec2b79e21de6217a3103bb4 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
from bs4 import BeautifulSoup
url = "http://javmobile.net/?s=julia"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
imgs = soup.find_all("img" , {"class": "entry-thumb"})
images = []
titles = []
srcs = []
for img... |
2,493 | 064792a6aba96a679bec606a85b19d4925861f7d | import webapp2
class RedirectToSiteRootHandler(webapp2.RequestHandler):
def get(self):
self.response.set_status(301)
self.response.headers['Location'] = '/'
class AppendTrailingSlashHandler(webapp2.RequestHandler):
def get(self, uri):
self.response.set_status(301)
redirect_uri = uri + ... |
2,494 | 6ad939ab541562efdaacb8b56865e76d1745176a | #!/usr/bin/env python
# Ben Suay, RAIL
# May 2013
# Worcester Polytechnic Institute
#
# http://openrave.org/docs/latest_stable/command_line_tools/
# openrave-robot.py /your/path/to/your.robot.xml --info=joints
# On that page you can find more examples on how to use openrave-robot.py.
from openravepy import *
import s... |
2,495 | 5d4585dc96d4ebdbc15b7382038cfea959c9a6f3 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
from statistics import mean
from tqdm import tqdm
import multiprocessing as mp
from . import model as dymod
class Filter:
"""誤ベクトル数の確認,誤ベクトル数によるフィルタリング処理"""
@classmethod
def get_incorrect_vector_examp... |
2,496 | 6161653fb789040d084e475e0ae25921e2e0676b | n=int(input())
k=[4,7,47,74,44,77,444,447,474,477,777,774,747,7444]
f=0
for i in k:
if(n%i==0):
f=1
print("YES")
break;
if(f==0):
print("NO")
|
2,497 | 2f0dc8697e979f307c86a08832b0eae86357d416 | filename = 'learning_python.txt'
# with open(filename) as file_object:
# contents = file_object.read()
# print(contents)
# with open(filename) as file_object:
# for line in file_object:
# print(line.rstrip())
with open(filename) as file_object:
lines = file_object.readlines()
c_string = ''
for line in lines:
... |
2,498 | d14937aaa7a80d6b95825afa2a2d6ff8202e5f5c | # 出现频率特别高的和频率特别低的词对于文本分析帮助不大,一般在预处理阶段会过滤掉。
# 在英文里,经典的停用词为 “The”, "an"....
# 方法1: 自己建立一个停用词词典
stop_words = ["the", "an", "is", "there"]
# 在使用时: 假设 word_list包含了文本里的单词
word_list = ["we", "are", "the", "students"]
filtered_words = [word for word in word_list if word not in stop_words]
print (filtered_words)
# ... |
2,499 | 664f9d5aa981c3590043fae1d0c80441bda4fbb1 | #!/usr/bin/env python3
'''Глава 9. Распутываем Всемирную паутину'''
'''1. Если вы еще не установили Flask, сделайте это сейчас.
Это также установит werkzeug, jinja2 и, возможно, другие пакеты.'''
# pip3 install flask
print('\n================================ RESTART ================================\n')
'''2. Созда... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.