index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
987,100 | 358875bfef0a67e96076967b9f0be6493760c68e | # -*- encoding: utf-8 -*-
import os
import sys,glob
#prefix = sys.prefix
#scriptdir = os.path.join(prefix,'Scripts')
#easy_inst = os.path.join(scriptdir, 'easy_install.exe')
#if not os.access(easy_inst,os.F_OK):
# print u'请安装easy_install工具'
# sys.exit(1)
easy_inst = 'ez_setup.py'
pkgs = [
['Numeric','Nu... |
987,101 | ac4aaf778d0ea9cfac29dbc2048e81f0f0bf22df | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 17:30:37 2018
@author: K.Ataman
"""
"""
Find linear relation of the kind y = Ax + B + G(n) where G(n) is Additive White
Gaussian Noise
"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
num_points = 500
x_point = []
y_point = []
a = 0.22
b ... |
987,102 | 88d9fc64dc6bf18fe9771bc3432d7a61342dade6 | #오른쪽 아래가 직각인 이등변 삼각형으로 *출력
print('오른쪽 아래가 직각인 이등변 삼각형으로 *출력')
n= int(input('짧은 변의 길이를 입력:'))
for i in range(n):
for _ in range(n-i-1):
print(' ', end='')
for _ in range(i+1):
print('*',end='')
print() |
987,103 | 537621c77b3841ff91d0c9ba7083bc183cf06fa9 | import logging
def main(name: str) -> str:
return f"Hello {name}!"
|
987,104 | 1d2e2eb2c10108687a1dc49559484804e918c456 | from cmsplugin_rst.models import RstPluginModel
from django import forms
help_text = '<a href="http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html">Reference</a>'
class RstPluginForm(forms.ModelForm):
body = forms.CharField(
widget=forms.Textarea(attrs={
'rows':... |
987,105 | 9970c3bf7333c375f087dd2567bed4a8dfba450e | import re
import sys
import time
import random
from BeautifulSoup import BeautifulSoup
import requests
UA = 'Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.9.2.9) Gecko/20100913 Firefox/3.6.9'
def parse_soup_page(soup):
"""
:param soup: object obtained from page of Google Scholar cites
eg.... |
987,106 | 5d30b345b27c1a5a00453c5983113dff52dff694 | import subprocess as sub
import scapy
from scapy.all import *
from scapy.contrib import openflow as op
src_ip = "192.168.0.2"
interface = "eth0"
ctrl_ip="192.168.0.3"
ctrl_port=6653
def ctrl_data():
data=[]
capture = sub.Popen(('sudo', 'tcpdump', '-ni', 'eth0', 'tcp', 'port', '6653', '-w', 'capture.p... |
987,107 | 3a52c3b5c14fe06e3dd837c028b17e2bf4ec0347 | test = {
'name': 'q6',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> isinstance(answer6, list)
True
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> all([isinstance(elt, str) for... |
987,108 | aa28c629c91f6627f101653b1d9428f077bda1aa | """
Coded by Matthew Nebel for the CogWorks IFF experiment
The Picture class is used to easily store information about and manipulate the art assets of the experiment.
Variables:
image - stores the picture itself, scaled by the given number
loc - a tuple storing the x and y coordinate of the ... |
987,109 | 77bcf3cd5a8aabd489e18e17635e7a8bd56af23b | import unittest
import sys
sys.path.append('../')
from Methods.CreateCategory import Category
class TestCategory(unittest.TestCase):
"""
Purpose: Test Category
Author: Zach
Tests:
test_can_create_a_category
test_can_register_category_to_database
"""
@classmethod
def setUpClass(self):
self.food ... |
987,110 | 9fa77ff3028f6e8db040c0681f7827732c1df226 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 24 19:22:41 2018
@author: labuser
"""
# Load and display limit scans from 2018-09-24
import os
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import cauchy
from scipy.optimize import curve_fit
import pandas as pd
def limit_scan(fname):
data = ... |
987,111 | f6368ca316c791e62355da544ca662b2d92f1da3 | import xlrd
book3 = xlrd.open_workbook("book3.xlsx")
poi = xlrd.open_workbook("POI_CityGuide_global_final_07_10.xlsx")
sheetBook3 = book3.sheet_by_index(0)
sheetPoi = poi.sheet_by_index(0)
poicountry = [x.strip().lower() for x in sheetPoi.col_values(16)]##set= to elminate duplicates
poicity = [x.strip().lower() for ... |
987,112 | 94fa819e207fd8bc902fb5cc2ae883e2349ef4b4 | nums = int(input())
res = []
for i in range(nums):
length = int(input())
list1 = input().split(" ")
list1 = [int(i) for i in list1]
list1.sort()
k = 0
while k < len(list1) - 1:
if list1[k] == list1[k + 1]:
res.append(k + 1)
break
k += 1
else:
r... |
987,113 | db3f66f602b48b6ac3d3d2ea973f4d8aaad9a4a0 | 직사각형별찍기.py
a, b = map(int, input().strip().split(' '))
for x in range(b): #세로
for y in range(a): #가로
print('*', end='')
print()
|
987,114 | 5faf2895d553068f4911ee002b33c1c1b249cbeb | import h5py as h5
import pandas as pd
name = "mnist_nn_64.h5"
f = h5.File(name)
for layer in f['model_weights']:
pd.DataFrame(f['model_weights'][layer][layer]['kernel:0']).to_csv(f"mnist_{layer}_kernel_array.csv", index=False, header=False, sep='\n')
pd.DataFrame(f['model_weights'][layer][layer]['bias:0']).to... |
987,115 | cc73d0e021065d7be90598378cf98fc16a48770d | import torch
import torch.nn as nn
import math
'''
This is PyTorch implementation of BSRN('Lightweight and Efficient Image Super-Resolutionwith Block
State-based Recursive Network'). The original code is based on TensorFlow and the github is
'https://github.com/idearibosome/tf-bsrn-sr'
'''
def make_mode... |
987,116 | 636d8bb7917e780f105f12a5a05c71fd411218b3 | import gspread
import mlbgame
import calendar
import time
from oauth2client.service_account import ServiceAccountCredentials
def initMonth(month,numDays):
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/driv... |
987,117 | 3ed185a8180c764f085215df61c4010c356d5f7c | #!/usr/bin/env python
from pathlib import Path
from subprocess import run
root = Path(__file__).parent.resolve()
if __name__ == '__main__':
for recipe in (root / 'recipes').glob('*'):
for py_ver in ['2.7', '3.5', '3.6', '3.7']:
run(['python', 'build.py', str(recipe), py_ver], cwd=root,
... |
987,118 | d7c872be1c02d8c7620503c4ab284f7e9f6d2e56 | # author: hmin
# contact: hmin@zju.edu.cn
# datetime: 2019/10/3 22:31
# software: PyCharm 2017.1.2-Python 3.6.0(Anaconda)
# -*-coding:utf-8-*-
"""
文件说明
判断列表是否含有重复元素
"""
def has_duplicates(lst):
"""
方法用于判断列表是否含有重复元素,是返回True,否返回False
"""
return len(lst) != len(set(lst)) |
987,119 | a70d0b2be64d80ebe7c1e1d7533e1944ea08a879 | import os
from random import randint
from tabulate import tabulate
import json
from mutagen.mp3 import MP3
import mutagen
class Song:
def __init__(self, title="Odin", artist="Manowar", album="The Sons of Odin", length="3:44"):
self.title = title
self.artist = artist
self.album = album
... |
987,120 | 58b9780ad70e7d19ece6ff483b0c98e3d9521394 | # escreva um program que leia dois numeros inteiro
#e compare os mostrando na tela uma mensagem
# o primeiro valor e maior
#o segundo valor e maior
# nao existe valor maior os dois sao iguais
n1 = int(input('digiter um numero: '))
n2 = int(input('digite outro numero: '))
if n1 > n2:
print('o maio valor é ', n1)
eli... |
987,121 | 55ad8b02d64a7ae53b720275f1fa9879606ca263 | from steemapi.steemwalletrpc import SteemWalletRPC
from pprint import pprint
import time
def dumpkeys(account, typ):
name = account["name"]
keys = account[typ]["key_auths"]
for key in keys:
try:
wif = rpc.get_private_key(key[0])
print("%10s: %10s: %s %s" % (
... |
987,122 | f70867c4886983852966d2ad6814ba66f034e44e | # Communication with mongo
from pymongo import MongoClient
# Retreive congiguration info
import ConfigParser
# Reading the config file
config = ConfigParser.RawConfigParser()
config.read('read.cfg')
# Reading database settings
client = MongoClient()
db = client[config.get('mongodb', 'db')]
collection = config.get('m... |
987,123 | a6c759adb6d381c3b36f61552eddb2eac15b9b09 | from .AnimGroup import AnimGroup
# This is the root of an AnimChannel hierarchy. It
# knows the frame rate and number of frames of all the
# channels in the hierarchy (which must all match).
class AnimBundle(AnimGroup):
def __init__(self, bam_file, bam_version):
AnimGroup.__init__(self, bam_file, bam_ver... |
987,124 | b6a87b06cda22b2750d49f6f1c248a451f8081c8 | if __name__ == '__main__':
import context
from autem.evaluators import Evaluater
from benchmark.utility import *
from pathlib import Path
import os
import csv
import pandas
import numpy as np
# from benchmark.download_opemml_task import download_task_data
def baselines_directory():
return... |
987,125 | ab5e1343c4eed1e52f9a4cfc7c589c4c07366198 | import time
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Configurations
options = Options()
options.he... |
987,126 | cd809d0b3edc4605b9a0f393e9a767281816dde7 |
from sklearn.datasets import load_files
from keras.utils import np_utils
import numpy as np
from glob import glob
# define function to load train, test, and validation datasets
def load_dataset(path):
data = load_files(path)
dog_files = np.array(data['filenames'])
dog_targets = np_utils.to_categorical(np... |
987,127 | 53d2566ac0e63936b8d1854c076faf74c3b6d45c | from keras.applications.vgg16 import VGG16
import numpy as np
class NnFeatureLoader:
def __init__(self):
self.model = VGG16(weights='imagenet', include_top=False)
def describe_model(self):
self.model.summary()
def __get_feature(self, image):
image = np.resize(image, (1, 224, 224... |
987,128 | 6e5c256b9a5b9133cbeac2c7393548afbb611a65 | #!/usr/bin/env python3
import logging
import queue
import socket
import threading
lock = threading.Lock()
logging.basicConfig(
format='%(asctime)-15s %(clientip)-15s %(call)-8s %(message)s')
logger = logging.getLogger('telnetrelay')
logger.setLevel(logging.INFO)
clients = []
class RelayServer(threading.Thre... |
987,129 | 8e8b282e18b02f5e2fdc9671d45ddf8e8b1b6cd2 | c = get_config()
load_subconfig('etc/base_config.py')
c.JupyterHub.authenticator_class = 'everware.DummyTokenAuthenticator'
c.Spawner.start_timeout = 120
c.Spawner.http_timeout = 120 # docker sometimes doesn't show up for a while
|
987,130 | b0dd05a2ff4f019630dd666ecb3f278a5a5bc761 | import numpy as np
import matplotlib.pyplot as plt
world = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0],
[0, 1, 1, 1, 0, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 0, 1, 1, 0],
[0, 1, 1, 1, 1,... |
987,131 | 0a342aa5b98dc92eb518205fd59c55d66f47dca9 | import pandas as pd
import numpy as np
from ast import literal_eval
import warnings; warnings.simplefilter('ignore')
# Load Movies md
md = pd.read_csv('data/movies_metadata.csv', low_memory=False)
# Print the first three rows
#print(md.head(3))
md['genres'] = md['genres'].fillna('[]').apply(literal_eval).ap... |
987,132 | 3dcdbdeeb3e2401e4e1c6eb6302ecd1787574135 | import cPickle
import threading
from Client import client
from python.src.shared.actions.basetorobot.getlinetra import GetLineTra
from python.src.shared.actions.basetorobot.startrobot import StartRobot
from python.src.shared.actions.basetorobot.newturn import NewTurn
class Base():
def __init__(self):
self._... |
987,133 | 385b95133c0e3c085a5a1913291605a4b004f58e | size_valid = 0.15
path_raw_train_csv = '/home/muyun99/competition/classification/data/kaggle_classify_leaves/classify-leaves/train.csv'
path_raw_test_csv = '/home/muyun99/data/dataset/competition_data/kaggle_classify_leaves/classify-leaves/test.csv'
path_save_trainval_csv = '/home/muyun99/competition/classification/da... |
987,134 | bba87a4d9d6d052a4e983c7180c6784ba545485d | '''
Diêgo C. Oliveira
Tec. em Informática | IFPI
Programação para Web | Ritomar Torquato
Turma 386, Periodo 2017.1
Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo usuário, assim como a
quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar, sabe... |
987,135 | 3ed861c2fa588cac94326a28dcb2cf8565b72ea6 | import math
def update_category_max(category_max, category_min, category_size):
return category_min + category_size
def get_size_of_categories(number_of_categories):
return math.floor(255 / number_of_categories)
def get_category_median(category_min, category_size):
return category_min + math.ceil(categor... |
987,136 | 58f479dc89ae783d57d96d3750ab4383f03265b3 | from django.db import models
from products.models import Products
from users.models import CustomUser
class Review(models.Model):
id = models.AutoField(null=False,blank=False,primary_key=True)
products_id = models.ForeignKey(Products,on_delete=models.RESTRICT)
user_id = models.ForeignKey(CustomUser, on_de... |
987,137 | 533e8603e44b5854aae8fb23d9a6005cdc3e8b17 | import os
from datetime import datetime
from flask import Flask, redirect, render_template, request, session
app = Flask(__name__)
app.secret_key = "random123"
messages = []
def add_message(username, message):
"""add messages to the list"""
now = datetime.now().strftime("%H:%M:%S")
messages.append("({}) {... |
987,138 | 209f41198bf1bb92ba35b1bfd796ecaa4f5e8ef3 | """File linked with 'main_user.py' """
import pymysql.cursors
try:
import config
except ImportError:
print("No configuration file found")
exit()
def host():
""" Display the 'home menu' """
print(""" Bienvenue sur l'application Pur Beurre
--------------------------------------------
... |
987,139 | 224731f0292b04850d348d9d7fcf24c2694cd34d | ########################################
## @file rk_integrator.py
# @brief Contains the class of RK ODE integrator
# @author Zhisong Qu (zhisong.qu@anu.edu.au)
#
from .base_integrator import BaseIntegrator
from scipy.integrate import ode
import numpy as np
## RKIntegrator wraps the explicit Runge-Kutta implimented... |
987,140 | 0e97cfa1d77d436ea8242b9ce69c30628f5b5d89 | MuniList = ['Ödeshög',
'Åtvidaberg',
'Boxholm',
'Finspång',
'Kinda',
'Linköping',
'Mjölby',
'Motala',
'Norrköping',
'Söderköping',
'Vadstena',
'Valdemarsvik',
'Ydre',
'Karlshamn',
'Karlskrona',
'Olofström',
'Ronneby',
'Sölvesborg',
'Älvdalen',
'Avesta',
'Borlänge',
'Falun',
'Gagnef',
'Hedemora',
'Leksand',
'Ludvika',
'... |
987,141 | 70fea78b60e9485481b4b7fe05dcc16f126c0d0b | import matplotlib.pyplot as plt
def get_points(coordinates):
x_points = []
y_points = []
z_points = []
for coordinate in coordinates:
x_points.append(coordinate[0])
y_points.append(-coordinate[1])
z_points.append(coordinate[2])
return x_points, y_points, z_points
def visu... |
987,142 | f38f41653140d9f1b33834be929557526ce89b13 | class Solution(object):
def containsDuplicate(self, nums):
for i in range(0,nums.__len__()-1):
for j in range(i+1,nums.__len__()):
if nums[i] == nums[j]:
return True
return False
s = Solution()
print(s.containsDuplicate([1,2,3,1]))
|
987,143 | 20fd374f3c607992f9ba724402db5ce45325d53d | import argparse
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.utils.data as data
from PIL import Image, ImageFile
from tensorboardX import SummaryWriter
from torchvision import transforms
from tqdm import tqdm
import net
from sampler import InfiniteSampl... |
987,144 | b370f214906b42e48cf12096c66d76a404ba7d5e | import socket
import sys
from contextlib import contextmanager
import attr
try:
import pycurl
@attr.s(slots=True)
class Curl(object):
"""Proxy to real pycurl.Curl.
If `perform` is called then it will raise an error if network is disabled via `disable`
"""
handle = attr.i... |
987,145 | 28577e593c1b30f298a83c2e3a44fb65a0ec5f08 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
author = models.ForeignKey(User, verbose_name=u'Автор', related_name='posts')
date_created = models.DateTimeField(verbos... |
987,146 | 27953f4e4cbbea91e657843c4fd00de5469d281f | import os
import time
from thrid_session.gui_test.common.connect_DB import DBtools
class Setreport:
def __init__(self):
self.db=DBtools()
def write_report(self,version,planid,testtype,caseid,casetitle,result,error,screenshot):
testtime=time.strftime('%Y-%m-%d_%H:%M:%S',time.localtime(time.tim... |
987,147 | ae816287019df178848faa842decb2eedc14eacb | #line graph
import matplotlib.pyplot as plt
#line 1 points
x1 = [1, 2, 3]
y1 = [2, 4, 1]
plt.plot(x1, y1, label="line 1")
#line 2 points
x2 = [1, 2, 3]
y2 = [4, 1, 3]
plt.plot(x2, y2, label="line 2")
#naming the x and y axis
plt.xlabel('x - axis')
plt.ylabel('y - axis')
#graph title
plt.title('Two lines graph')
# sho... |
987,148 | cfaff6f8d0405857ae18c67572d0f80407508d19 | from __future__ import absolute_import
import time
import roslib
import rospy
from importlib import import_module
from collections import deque, OrderedDict
from .message_conversion import get_msg, get_msg_dict
def get_topic_msg(topic):
return get_msg(topic.rostype)
def get_topic_msg_dict(topic):
retur... |
987,149 | a70b46f57292fbc40f5968a54c60da82b7e9e3c3 | from NseStockAnalyser.utils import *
from pprint import pprint
def index_52_wk_lows():
index = get_index()
# slicing off 1st index of the data list since it contains index data
nifty50_stocks_data_json = get_index_stock_data_json(index)['data'][1:]
# try:
# data_pts = int(input(f'Enter numbe... |
987,150 | 0725780cd66c8295d8bceea129c2d7e3e1989b4b | #!/usr/bin/env python
# -*- coding: utf8 -*-
import time
import json
import logging
import requests
from collections import Counter
from qcloud_cos import CosClient, Auth, UploadFileRequest
from constants import *
youtu_log = logging.getLogger(__name__)
KNOWN = 'known'
UNKNOWN = 'unknown'
class YoutuException(BaseE... |
987,151 | 24342b381129d808ba0d4cedc9bb8061e0f39f08 | from dataclasses import dataclass
from typing import Dict
import spimdisasm
import tqdm
from intervaltree import Interval, IntervalTree
from util import log, options, symbols
@dataclass
class Reloc:
rom_address: int
reloc_type: str
symbol_name: str
addend: int = 0
all_relocs: Dict[int, Reloc] = {... |
987,152 | a3d0d6d3c2a5dbcea1ea61a641309af3c2db2502 | import matplotlib.pyplot as plt
import numpy as np
import random as ran
from math import pi
num=100000
rmin=0.0
rmax=10.0
a=0.0
b=0.5 #max value of P
nbin=50
ranr=[]
r=[]
mybin=[]
for i in range(0,num):
temp=0.5*np.log(1/(2*ran.uniform(a,b))) #P=2*exp(-2r)
ranr.append(temp)
step=(rmax-rmin)/nbin
for i in range... |
987,153 | 265dc2e7ded69e2b0c6357f0bd1bf7bc51d78e6f | import pygame
import time
import random
from .. import res, constants, tools
from . import tile
import json
from .. import core
def setup_res():
global enemy_dict, gravity
enemy_dict = {}
sc = constants.IMAGE_SCALE
# 资源
with open(constants.enemy_info_path) as f:
info = json.... |
987,154 | e19e6b4ccde6f388c8c7a5288125e7360c62ee3f |
import tensorflow as tf
ts = tf.InteractiveSession()
d = [1, 2, 8, -1, 0, 5.5, 6, 13]
spikes = tf.Variable([False] * len(d), name='spikes')
spikes.initializer.run()
saver = tf.train.Saver()
#
#
#
for i in range(1, len(d)):
if d[i] - d[i-1] > 5:
spikes_val = spikes.eval()
spikes_val[i] = True
... |
987,155 | 6278204e3cceb48983437c5ecc8a9cac6654e003 | class Monkey:
__no_of_bananas=40
def eat_banana(self):
print("eating banana")
Monkey.__no_of_bananas-=1
@staticmethod
def get_banana_count():
print("No. of bananas left: ",Monkey.__no_of_bananas)
gopher=Monkey()
doodoo=Monkey()
gopher.eat_banana()
doodoo.eat_banana()
Monkey.g... |
987,156 | f94216dc4b7b2555e91a1f3d4ca81667d143b9e5 | # Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
# Example 1:
# Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since... |
987,157 | 4b8e230a6a1284c2925ed5f25337bbb1d52f19cb | A, B, C = input().split()
A = float(A)
B = float(B)
C = float(C)
if A >= B + C or B >= C + A or C >= A + B or A <= abs(B - C) or B <= abs(A - C) or C <= abs(A - B):
area = (A + B)*C/2
print("Area = %.1f" % area)
else:
perimetro = A + B + C
print("Perimetro = %.1f" % perimetro)
|
987,158 | a87fb0174a71d3aa1d5146add65cdc9509d3b6e8 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import lz
from lz import *
import os
from datetime import datetime
import os.path
from easydict import EasyDict as edict
import time
import json
import sys
import numpy as np
import importlib
import itertools
i... |
987,159 | cd401f4697093b008fd5bc978b31f166a4024755 | # Generated by Django 2.1.4 on 2018-12-21 13:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('assets', '0006_auto_20181220_1657'),
]
operations = [
migrations.AlterModelOptions(
name='ip',
options={'ordering': ['-m_tim... |
987,160 | 33187f82d9aa156d6044c25416bca7bd90d2acc9 | from .serializer_manager import SerializerManager
__all__ = ('SerializerManager',)
|
987,161 | 557c8bec89dc33104fe24de213511ba92a62d14c | from rebase.common.utils import ids, RebaseResource
from rebase.tests.common.ticket import (
case_github_contractor,
case_github_mgr,
case_github_admin,
case_github_admin_collection,
case_github_anonymous,
case_github_anonymous_collection,
)
from . import PermissionTestCase
from .ticket import ... |
987,162 | 6bc85d00444e8465ba18dd45617ba15d243a25a5 | import json, boto3, datetime, os, base64, ast, sys
from botocore.exceptions import ClientError
# global variables used for email and slack
URL = os.environ.get("sqs_url")
SENDER_EMAIL = os.environ.get("sender_email")
APP_URL = os.environ.get("slack_application_url")
CHANNEL = os.environ.get("slack_channel")
CHANNEL_ID... |
987,163 | 8aead3bb437927f17c67cddc8975592cec94b093 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""YOLO_v4 MobileNetV3Large Model Defined in Keras."""
from tensorflow.keras.layers import ZeroPadding2D, UpSampling2D, Concatenate
from tensorflow.keras.models import Model
from common.backbones.mobilenet_v3 import MobileNetV3Large
#from yolo4.models.layers impo... |
987,164 | da5287436bcbb03a845e120c3d1a762c3cce9a86 | # Copyright 2020 The iqt Authors.
#
# 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 required by applicable law or agreed to in writ... |
987,165 | 95d7c91bd5cddee6fe2c0a0a6773e4faee77ab39 | import numpy as np
import numpy as np
from numpy import linalg
import matplotlib
import matplotlib.pyplot as plt
from libsvm.svmutil import svm_read_problem
from sklearn.model_selection import train_test_split
def oneHot(array):
result = np.zeros((len(array),10))
for number in range(len(array)):
... |
987,166 | f934de4f888f78e3ac9e4e0511ae7e3dbcdf5e34 | # -*- coding: utf-8 -*-
import json
from restless.views import Endpoint
from restless.auth import BasicHttpAuthMixin, login_required
from django.template import Context as C
from django.template import Template as T
from mails.models import Application, Log, Template
from mails.mailserver import MailServer
def mes... |
987,167 | 60c229c56f5c64efe436430208aa47f7bfacd061 | for 단 in range(1,10):
for 곱 in range(1,10):
print(단,"x",곱,"=",(단*곱))
# 알고리즘 순서도
# * 줄1 공백 4 별1 현재줄수*2 2-1
# *** 줄2 공백3 별3 현재줄수*2 4-1
# ***** 줄3 공백 2 별5 현재줄수*2 6-1
# ******* 줄4 공백1 별7 현재줄수*2 8-1
# ********* 줄5 공백0 별9 현재... |
987,168 | ce92bdb41915dbbefc952fdc047e5c72132f20ca | """
Build an estimating model for vehicle fuel consumption
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn import svm
car = pd.read_csv("C:\\...")
car.head()
df = car.loc[:, ['FC_L1', 'Veh_Speed.m.s.', 'Acceleration']]
df.colu... |
987,169 | cd37772ee80d981dffdef5500dc2a854a873137d | #!/usr/bin/env python
# coding: utf-8
import yaml
from responses import *
def assign_response(message):
message = message.lower()
words = message.split(' ')
if words[0] == '.pasquale':
return build_pasquale_response(words[1])
if message == '.cilia':
return build_cilia_response()
... |
987,170 | 38217b5e55cb9a359e2ce6048f0255132945d7ca | import time
from report import report_sxw
from osv import osv,fields
from report.render import render
import pooler
from tools.translate import _
from ad_num2word_id import num2word
import locale
from collections import OrderedDict
class bill_passing_parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, c... |
987,171 | f5a1ef2f0af81162f77199a22eb8bf632a60a1b6 | # -*- coding: utf-8 -*-
import os
from google.appengine.api import mail
from google.appengine.api import users
from google.appengine.ext import ndb
from datetime import datetime, timedelta
import jinja2
import webapp2
import uuid
import urllib
import urllib2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja... |
987,172 | 08988ecde5023f5852ccfb8b53c6d25e55dca2d0 | from django.shortcuts import render
from django.urls import path
from pages import views
urlpatterns = [
path('', views.HomeView, name='index'),
] |
987,173 | 7949565c185eb67d675fdc4f5bb8996d72044aa7 | # 执行用时:124 ms
# 内存消耗:18.9 MB
# 方案:所有的亮灯都连续排列在数组最左边,没有间断; 那么本题目转化为:判断 当前时刻亮灯的最大编号 是否 等于亮灯的数量
class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
# 所有的亮灯都连续排列在数组最左边,没有间断
# 判断 当前时刻亮灯的最大编号 是否 等于亮灯的数量
rst, maxx = 0, 0
for idx, on_light in enumerate(light):
m... |
987,174 | ae8c79203df733e42133e60d35130560d2af280a | MAGIC_NUM = 1000000007
left_cnt_P = [0 for _ in range(100010)]
s = input()
for i in range(len(s)):
if i > 0: left_cnt_P[i] = left_cnt_P[i - 1]
if s[i] == 'P': left_cnt_P[i] += 1
result = 0
right_num_T = 0
for i in range(len(s)-1,-1,-1):
if s[i] == 'T': right_num_T += 1
elif s[i] == 'A': result = (re... |
987,175 | d38e7d4fdc7277a9e06dc8ebbd69ccc66631a321 | class Critter(object):
def __init__(self):
print("A new critter has been born!")
def talk(self):
print("\nHi, I'm an instance of class Critter.")
crit1 = Critter()
crit2 = Critter()
crit2.talk()
crit1.talk() |
987,176 | 268f0ead377365d540f4ad991fb6c62f2847a557 | import hmac, hashlib, sys, re
numfinder = re.compile('[0-9a-f]+$')
def encrypt(infd, outfd, hashphrase, prefix, striplinenumbers=False):
"""
Read a breakpad .sym file from infd. Using the given hashphrase,
one-way-hash any function and file names mentioned in the symbol file.
`hashphrase` should be a... |
987,177 | b24c0ba3a5a0e9acc70d64e41b79f6100d197d31 | import requests
from django.shortcuts import render
def index(request):
# TODO: this is old api call
#movies = requests.get("http://localhost:5000/Mato/movies")
movies = requests.get("http://localhost:5000/beautiful-movies")
movies = movies.json()
return render(request, 'index.html', {'title'... |
987,178 | 64edaf346bd70b600f0f011464089b606f07cd3f | # -*- coding: utf-8 -*-
from core.models import Account
from core.models import AccountSplit
from core.models import Category
from core.models import CategorySplit
from core.models import Transaction
from csv import reader
from datetime import datetime
from decimal import Decimal
from django.core.exceptions import Obje... |
987,179 | 248c7e1f0053cb3f6f3ea2c6dcaae60a7c1a4fa0 | from .main import main # noqa: F401
from .monomer import readPDB, createHolder, Holder # noqa: F401
|
987,180 | 92b3a8aee28c11e360058b259b260ef6e39e57a8 | import random
from itertools import combinations
from pathlib import Path
import torch.nn as nn
import h5py
import numpy as np
import torch
from methods.training import BaseTrainer
from methods.utils.data_utilities import to_metrics2020_format
class Trainer(BaseTrainer):
def __init__(self, args, cfg, dataset, ... |
987,181 | 44bab4f6e625ef9aa610b31c7a36f1f0caef74b5 | # This problem was asked by Google.
#
# You are given an array of nonnegative integers. Let's say you start at the beginning of the array and are trying to
# advance to the end. You can advance at most, the number of steps that you're currently on. Determine whether you
# can get to the end of the array.
#
# For exampl... |
987,182 | 037dbc48ea9ff2ea2a3313f584f546a19d71311a | import FWCore.ParameterSet.Config as cms
from CondTools.SiPixel.SiPixelGainCalibrationService_cfi import *
from RecoLocalTracker.SiPixelClusterizer.SiPixelClusterizer_cfi import siPixelClusters as _siPixelClusters
siPixelClustersPreSplitting = _siPixelClusters.clone()
from Configuration.ProcessModifiers.gpu_cff impor... |
987,183 | 116ebb7f9487cf80fa9efa45fe2713274a996517 | import logging
import os
from celery import Celery
REPORTS_BASE_PATH = os.environ.get('TIX_REPORTS_BASE_PATH', '/tmp/reports')
PROCESSING_PERIOD = int(os.environ.get('TIX_PROCESSING_PERIOD', '5'))
RABBITMQ_USER = os.environ.get('TIX_RABBITMQ_USER', 'guest')
RABBITMQ_PASS = os.environ.get('TIX_RABBITMQ_PASS', 'guest')... |
987,184 | 49d1a40d9b8595286881d0cdb84a1f803299b6f4 | import os
import sys
import os.path as osp
import argparse
import numpy as np
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
import torch
sys.path.insert(0, osp.join('..', 'main'))
sys.path.insert(0, osp.join('..', 'data'))
from config import cfg
import cv2
def parse_args():
parse... |
987,185 | b2acc591ebd1f1e9bf281eff238563e93b537748 | #!/usr/bin/python3
"""Flask app module"""
from models import storage
from flask import Flask, render_template
from os import environ
app = Flask(__name__)
@app.teardown_appcontext
def teardown_session(session):
""" Remove current session """
storage.close()
@app.route('/states', strict_slashes=False)
@app.... |
987,186 | 73dd6b44edcc3c255763ba7fe2a4c01be56600a6 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 05 15:14:33 2017
@author: Kristian
"""
import IPython.lib.latextools as latextools
import IPython.display as display
try:
from table2ascii import table2ascii
except:
print("----------WARNING----------")
print("WARNING: module table2ascii not found you can down... |
987,187 | 519115df9f1f69248079d9f3c08a47c54bc3070c | # # Python Class for FLIR Systems' Blackfly USB Camera
#
# By Chris Arcadia (2021/01/11)
#
# Intended for use with the Blackfly S USB3 Camera
#
# Inspired by the following Repositories:
# * "Acquisition.py" (from "Spinnaker-Python3-Examples" by FLIR Systems, in Python, in [firmware download](https://flir.custhelp.c... |
987,188 | 7873c5e657f3e904989d557706f9aad6da6485e6 | from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'api', views.pcViewSet)
urlpatterns = [
path('', views.index, name='index'),
path('', include(router.urls)),
]
|
987,189 | 7b0f0198875b3281f804c15fcfb7be1be26eaa01 | import os
import requests
import re
from dataclasses import dataclass
from urllib.parse import urljoin
from urllib.parse import urlparse
from requests_html import AsyncHTMLSession
# from requests_html import HTMLSession
from utils import PASS_DOMAIN, geuss_link_url, rm_slash, has_url_html_been_fetched
from itertools i... |
987,190 | 2d246bff36484239bc035b33d997bef115cdde4a | # -*- coding: utf-8 -*-
import numpy as np
from breze.learn import autoencoder
from breze.learn.utils import theano_floatx
def test_autoencoder():
X = np.random.random((10, 10))
X, = theano_floatx(X)
m = autoencoder.AutoEncoder(10, [100], ['tanh'], 'identity', 'squared',
... |
987,191 | 07b398dc7c3aebd738d3cb8ca28390c1c2d0cbaa | # coding: utf-8
# Copyright © 2014-2020 VMware, Inc. All Rights Reserved.
################################################################################
# noinspection PyUnresolvedReferences
import os
import re
from enum import Enum
from taxii2client.common import TokenAuth
from taxii2client.v20 import Server as Se... |
987,192 | 16b401849607d7694a277e3d461e28001675c37c |
from collections import Counter
def almost_uniform(nums):
cnt = Counter(nums)
cnt2 = cnt.copy()
for x in cnt:
cnt2[x] += cnt[x-1]
return max([0]+[cnt2[x] for x in cnt if x-1 in cnt])
|
987,193 | 176e684e1e4515a00a1a8f88ca7d5f37d2c5b6b7 | import glob
import os
import typing
import importlib.util
import models.cards
import models.decks
import models.players
RESOURCES_DIR = 'resources'
CARDS_DIR = f'{RESOURCES_DIR}/cards'
DECKS_DIR = f'{RESOURCES_DIR}/decks'
def get_card(card_id: str, player_number: models.players.PlayerNumber) -> models.cards.BaseCa... |
987,194 | a0be253ece64834eb814019324ecb84e12993ab4 | from django.db import models
from django.contrib import admin
class MenuList(models.Model):
menu_item = models.CharField('Menu Item', max_length = 30)
price = models.FloatField()
available = models.BooleanField(default=False)
def __unicode__(self):
return self.menu_item
class Order(models.Model):
order_item =... |
987,195 | fdfdf23239241507857e5e210b92f00d657c826e | # Table of ASCII characters
ascii_chars = {
0:"NUL",
1:"SOH",
2:"STX",
3:"ETX",
4:"EOT",
5:"ENQ",
6:"ACK",
7:"BEL",
8:"BS",
9:"HT",
10:"LF",
11:"VT",
12:"FF",
13:"CR",
14:"SO",
15:"SI",
16:"DLE",
17:"DC1",
18:"DC2",
1... |
987,196 | 8c88dcbc5481a98d9519a183fe9c8cd02f1b0660 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
##
# Advent of code 2019, AoC day 16 puzzle 1
# This solution (python3.7 jupyter notebook) by kannix68, @ 2020-01-06.
import sys
sys.path.insert(0, '..') # allow import from parent dir
from typing import Dict, List, Tuple
import lib.aochelper as aoc
from lib.aochelper... |
987,197 | c5de715f77761720297f0fd8c470aa7cec92b2ce | """
Here we test things from the Nexa package
"""
import unittest
import numpy as np
import numpy.testing as nptest
from unittest import TestCase
import sys
sys.path.append('./')
import nexa.aux_functions as aux_functions
##################
# Test auxiliar functions
##################
class TestAuxiliaryFunctions(Te... |
987,198 | 9f3b8103c1572d1f63552b5e8f519609416e144d | import unittest
from capstone.player import RandPlayer
class TestRandPlayer(unittest.TestCase):
def setUp(self):
self.rand_player = RandPlayer()
def test_has_name(self):
self.assertEqual(RandPlayer.name, "RandPlayer")
self.assertEqual(self.rand_player.name, "RandPlayer")
|
987,199 | a9ff2453871c7704f3ad743bf86e306157c786e9 |
# 字符串(String)
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.