text stringlengths 38 1.54M |
|---|
import scrapy
from scrapy.http import Request
from nba.items import HomeItem
class HomeSpider(scrapy.Spider):
name = "home"
allowed_domains = ["basketball-reference.com"]
start_urls = ["http://basketball-reference.com/"]
custom_settings = {
# exported fields and order
"FEED_EXPORT_FIEL... |
from typing import Tuple
from process.util.data_transfer import RetailerDatabaseContext
class PrtSalesCalculator(object):
@staticmethod
def scg_to_org_code_user_no_kv(pair: Tuple[RetailerDatabaseContext, dict]):
retailer_database_context = pair[0]
data = pair[1]
return (retailer_datab... |
{
"id": "mgm4441617.3",
"metadata": {
"mgm4441617.3.metadata.json": {
"format": "json",
"provider": "metagenomics.anl.gov"
}
},
"providers": {
"metagenomics.anl.gov": {
"files": {
"100.preprocess.info": {
... |
from ..models.campus import Campus
from . import DAO
class CampusDAO(DAO):
def __init__(self, campus: Campus = None):
super().__init__(campus)
def get_all(self) -> list or Campus:
return self.session.query(Campus).all()
def get(self) -> list or Campus:
self.obj = (
se... |
import json
from time import time
class Problem:
def __init__(self, grid, width, height, starts, goals, waypoints, benchmark, id, batch_pos):
""""
MAPFW problem with some extra data for the benchmark
"""
# USEFUL FOR PROBLEM SOLVING
self.grid = grid
self.width = wid... |
# %load imports.py
import numpy as np
import aplpy
from astropy.coordinates import SkyCoord
import astropy.constants as aconst
import scipy as sc
from scipy import ndimage, misc
from scipy import signal
import fdust as fd
import utils as ut
import const as const
from astropy.io import fits as f
import matplotlib.py... |
import matplotlib.pyplot as plt
import numpy as np
import cntk as C
from sklearn.model_selection import train_test_split
def transform_data(data, target, test_size=0.3):
x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=test_size)
def map(X,Y):
num_classes = len(np.uniqu... |
# Workflow for downloading and preprocessing Tabula Muris data
configfile: "config.yaml"
workdir: config["base_dir"]
rule targets:
input:
# "TM_droplet_metadata.csv",
expand("qc-reports/alevinQC/{run_id}_alevinqc.html", run_id = config["run_ids"]),
"fastq/10X_P4_3"
## tabula muris files are... |
# Author:Pegasus-Yang
# Time:2020/1/5 20:27
import os
def get_abs_path(file_path):
"""通过相对路径获取对应的绝对路径"""
return os.path.abspath(file_path)
|
# -*- coding: utf-8 -*-
# Copyright 2015 Red Hat, Inc.
#
# 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... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import datetime
from django.http import JsonResponse
from django.shortcuts import render
from ...services import (
project as project_service,
user as user_service,
navigation as navigation_service,
page as page_service,
b... |
"""
======================================
Downloading and plotting LASCO C2 data
======================================
How to download SOHO/LASCO C2 data with Fido and make a plot.
"""
import matplotlib.pyplot as plt
import sunpy.map
from sunpy.net import Fido
from sunpy.net import attrs as a
#####################... |
def factor_finder(num):
output = []
for i in range(1, int(num ** 0.5) + 1):
if userInput % i == 0 and i not in output:
output.append(i)
output.append(userInput // i)
return sorted(list(set(output)))
if __name__ == "__main__":
print('Factor Finder')
while True:
... |
import pymongo
import sqlite3
from sainsburys.items import SainsburysItem
from scrapy.exceptions import DropItem
class CsvItemPipeline:
fieldnames_standard = ['item_code', 'product_name', 'url', 'price_per_unit', 'unit', 'rating', 'product_reviews',
'product_origin', 'product_image']
... |
import tensorflow as tf
from pathlib import Path
def hotfix_gpus():
"""
Test doc
Returns:
"""
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except Runti... |
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
for i in range(N):
n, m = map(int, input().split())
mine = []
lst = list(map(int, input().split()))
for j in range(0, len(lst), m):
mine.append(lst[j:j + m])
dp_table = [[0] * m for _ in range(n)]
for... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 2 21:35:06 2021
@author: dhruv
"""
import random
# main.py
# fives = set()
# for i in range(5, 36, 5):
# fives.add(i)
# print(fives)
# fives.remove(35)
# print(fives)
# for number in fives:
# print(number)
# if 10 in fives:
# print("... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 17:07:04 2021
@author: angus
"""
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy as np
ext_modules = [
Extension(
"TwoD_Cython_OMP",
["TwoD_Cython_OMP.pyx"]... |
""" Basic analysis tools. """
from .file_dictionary import FileDictionary
from .hed_context_manager import OnsetGroup, HedContextManager
from .hed_type_definitions import HedTypeDefinitions
from .hed_type_factors import HedTypeFactors
from .hed_type_values import HedTypeValues
from .hed_type_manager import HedTypeManag... |
import sys
sys.path.append("../../configs")
#../../configs
from path import EXP_PATH
import numpy as np
DECAY_PARAMS_DICT =\
{
'stair' :
{
128 :{
'a1': {'initial_lr' : 1e-5, 'decay_steps' : 50000, 'decay_rate' : 0.3},
'a2' : {'initial_lr' : 3e-4, 'decay_step... |
# coding=utf-8
from __future__ import absolute_import, division, unicode_literals
from datetime import date
from decimal import Decimal
from django.utils.six import iteritems
from ..settings import txmoney_settings
from .models import Rate
def exchange_ratio(currency_from, currency_to, ratio_date=None):
"""
... |
import logging
def setup_logger(logger_name, level=logging.INFO, propagate=False):
logger = logging.getLogger(logger_name)
formatter = logging.Formatter('%(asctime)s : %(message)s')
file_handler = logging.FileHandler('log/{filename}.log'.format(filename=logger_name))
file_handler.setFormatter(formatte... |
# Copyright (c) 2015-2020, Swiss Federal Institute of Technology (ETH Zurich)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright... |
# -*- coding: utf-8 -*-
from scipy import ndimage as ndi
import skimage.measure
import mahotas
import numpy as np
import modules.BasicOperations as BasicOperations
__doc__ = """\
Watershed
===============
Compute the transformation of the distance with two methods:
- Euclidian
- Chamfer
Seeded watershed.
"""
... |
# ============LICENSE_START==========================================
# org.onap.vvp/test-engine
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ===================================================================
#
# Unless othe... |
# Create your views here.
from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache
from django.contrib.auth import REDIRECT_FIELD_NAME , login as auth_login
from django.shortcuts import resolve_url
f... |
from day_test08.hogwos import Huogwos
class Main:
def send_keys(self):
pass
def click(self):
pass
def title(self):
pass
def click_first_link(self):
return Huogwos() |
import numpy as np
from bidict import bidict
from flask import (
Flask, render_template, request,
redirect, url_for, session
)
from random import choice
from tensorflow import keras
ENCODER = bidict({
'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6,
'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12,
... |
import ROOT, os
from ROOT import TFile
import subSample
import argparse
from eventSelection import isGoodEventAN17_094, isGoodEventEwkino, isGoodEventJana, isGoodEventFakeRate
from helpers_old import makeDirIfNeeded, progress, showBranch
argParser = argparse.ArgumentParser(description = "Argument parser")
argParser.ad... |
from flask import Flask
import sensor_simulator as sensor
import json
app = Flask(__name__)
sensor.start()
@app.route("/")
def home():
return """
GET /api/sensor/humidity -- Obtiene el último valor de humedad<br>
GET /api/sensor/temperature -- Obtiene el último valor de temperatura<br>
GE... |
phonebook_dict = {
"Alice": "813-445-9021",
"Bill": "950-731-2455",
"Elizabeth": '342-110-7531'
}
print(phonebook_dict["Elizabeth"])
phonebook_dict["Kareem"] = "455-617-9124"
phonebook_dict["Alice"] = "Number not found"
print(phonebook_dict["Alice"])
# del phonebook_dict["Alice"]
retained_alice = phonebook... |
# coding: utf-8
# # Extraire la legende depuis la description
# In[1]:
import regex # permet overlapping matching
import copy
# In[442]:
def print_legend( legend ):
sortfun = lambda x: ( x['number'] , len(x['position']), x['label'][::-1] )
legendsorted = sorted( legend, key=sortfun )
current_nu... |
from flask import Flask, render_template, url_for, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init and define schema for db
db = SQLAlchemy(app)
class poses(db.Model):
id... |
"""Script to scrape steel profile data from the web"""
# Standard library imports
from pathlib import Path
# Third party imports
import requests
import pandas as pd
if __name__ == "__main__":
# Read steel profile tables from html
url = "https://www.prontubeam.com/structural-steelwork-handbook"
response ... |
from math import sin, cos, tan, radians
num = float(input('Informe o valor do ângulo: '))
sen = sin(radians(num))
cos = cos(radians(num))
tan = tan(radians(num))
'''Coloquei esse math.radians dentro da função porque de acordo com o documento do python,
o seno, cosseno e tangente vêm em radianos, por isso tive que con... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('www', '0033_delete_language'),
]
operations = [
migrations.CreateModel(
name='Language',
fields=[
... |
#!/usr/bin/python
def sum_of(lis1):
total = 0
for i in lis1:
total += i
return total
lis1 = input("Enter a listof ele: ")
res = []
for val in range(len(lis1)):
for val1 in range(len(lis1)-1):
if lis1[val1] > lis1[val1+1]:
val2 = lis1[val1]*lis1[val1]
res.append(val2)
break
print sum_of(lis1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import redis
class OPRedis(object):
def __init__(self, uri, password):
self.url = 'redis://:{}@{}'.format(password, uri)
self.con = redis.Redis.from_url(self.url, decode_responses=True)
def expire(self, key, expires=86400):
res = self.con... |
from models import Card
from models import Line
class Test_Card:
# This class is to test the class cards
def __init__(self):
# Create multiple cards to be tested in the bottom
self.card1 = Card('card1',(1,1))
def Test_GetName(self):
assert(self.card1.GetName() == 'card1')
def ... |
class LString:
class LStringNode:
def __init__(self, nextPtr, charVal):
self.next = nextPtr
self.char = charVal
def __init__(self, initString=""):
self.first = None
self.length = 0
for char in initString:
self.addChar(char)
def addChar... |
import smbus
import time
bus = smbus.SMBus(1)
# Registers
DEVICE_ADDRESS = 0x40
MODE1 = 0x00
MODE2 = 0x01
# Bits
SLEEP = 0x10
class PCA9685:
def __init__(self):
pi = 1
def wake(self):
mode1 = bus.read_byte_data(DEVICE_ADDRESS, MODE1)
print "{0:#010b}".format(mode1)
a... |
"""
Author: CraneLone
email: wang-zhizhen@outlook.com
file: pl_model
date: 2021/8/19 0019 上午 03:29
desc:
"""
from PENNet.core.loss import AdversarialLoss, PerceptualLoss, StyleLoss, VGG19
from PENNet.modules.pennet import InpaintGenerator, Discriminator
import torch
import torch.optim as optim
import torch.nn as nn
... |
# given an array and a target, find the maximum combinations of numbers in the array
# which sum the target
def dp(arr, total, i, mem):
key = str(total) + ':' + str(i)
if key in mem:
return mem[key]
if total == 0:
return 1
elif total < 0:
return 0
elif i < 0:
... |
import argparse
import os
import scipy.misc
import numpy as np
from model import Singleout_net
from dataprovider import data_provider
import tensorflow as tf
from utils import process_config
cfg= process_config('exp6//config.cfg')
gene = data_provider(cfg)
def main(_):
if not os.path.exists(os.path.join(cfg['exp_n... |
# 혈압수치와 혈당수치를 입력받아 의심되는 질환을 출력하는 프로그램
bp = int(input("혈압수치: "))
bs = int(input("혈당수치: "))
if bp < 90 or 140 < bp or 120 < bs:
print("의심되는 질환:")
if bp < 90:
print("저혈압")
elif 140 < bp:
print("고혈압")
if 120 < bs:
print("당뇨병")
else:
print("의심되는 질환이 없습니다.")
|
import json
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import pearsonr
import math
from sklearn.metrics import mean_squared_error
def data_generator(X_train, y_train, batch_size):
idx = 0
total = len(X_train)
while 1:
p... |
import pytest
import json
from graphqlclient import GraphQLClient
@pytest.fixture
def gql_client() -> GraphQLClient:
client = GraphQLClient('https://api.graph.cool/simple/v1/swapi')
# Add api token if needed
# client.inject_token()
return client
class TestGetHairColor:
QUERY = """
query ... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import root
from sklearn.linear_model import LinearRegression
def smooth_q(data, eps=0.125e-2):
delta = data['dX'].to_numpy().copy()
x = data['X'].to_numpy(dtype='float64').copy()
for col in ... |
import msuper
import parsebin
import sys
def patchpos(parse, super):
S = msuper.superread(super)
for p in parsebin.fromFile(parse):
s = S.next()
t = [w[1] for w in s]
p.pos = t
print p.root
if __name__ == '__main__':
patchpos(sys.argv[1], sys.argv[2])
|
# -*- encoding:utf-8 -*-
# -*- coding:utf-8 -*-
from django import forms
from .models import Watermarking, CoverImage, WatermarkImage, Metric, Noise
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field
from crispy_forms.bootstrap import (
PrependedText, PrependedAppended... |
class Test_allure:
def setup(self):
assert 1
def teardown(self):
assert 1
def test_al(self):
assert 0
def teardown1(self):
assert 1
def test_al2(self):
assert 0 |
# https://www.acmicpc.net/problem/1912 연속합 문제
# SUM 리스트를 만들어서 최댓값 - 최솟값
import sys
input = sys.stdin.readline
N = int(input())
M = list(input().rstrip())
ON = M[::-1]
DP = [[0]*(N+1) for _ in range(N+1)]
for i in range(1, N+1):
for j in range(1, N+1):
if M[i-1] != ON[j-1]:
DP[i][j] = max(DP[i][... |
class Settings(object):
def __init__(self, module='settings'):
self.module = __import__(module)
type(self).inst = self
def __getattr__(self, name):
return getattr(self.module, name)
load = Settings
def get_settings():
try:
return Settings.inst
except AttributeError:
... |
#!/usr/bin/env python3
# This program is for
# Author: MYGNU
# Please feel free to copy, distribute and modify till your heart is content
import turtle
wn = turtle.Screen()
wn.bgcolor('lightblue')
sq = turtle.Turtle()
def crsqr(t,num):
"""creates squares of 20 units, takes turtle object and number of squares m... |
import csv
from cataloger.models import BureauCode, Division, Office
def bureau_import(csvfile):
decoded_file = csvfile.read().decode('utf-8').splitlines()
reader = csv.DictReader(decoded_file)
for row in reader:
if len(row['division']) == 0:
# bureau code
bureau = BureauCod... |
import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
from phyllo.phyllo_logger import logger
# this works
def main():
# The collection URL below.
collURL = 'http://thelatinlibrary.com/priapea.html'
collOpen = urllib.request.urlopen(collURL)
collSOUP ... |
#
# Py Word Permutations
#
# Author: Afaan Bilal
# URL: https://afaan.ml
#
# Display all possible permutaions for a set of characters.
#
# (c) 2016 Afaan Bilal
# Released under the MIT License
#
def base_convert(number, fromBase, toBase):
''' Convert numbers to and from decimal '''
... |
'''
Created on 21-Aug-2019
@author: Sanjay Ghosh
'''
from collections import deque;
s = deque();
operations = int(input());
for x in range(operations):
arr = input().split();
try:
if "pop" == arr[0]:
s.pop();
if "popleft" == arr[0]:
s.popleft();
if "appen... |
from mcpi.minecraft import Minecraft
mc=Minecraft.create()
while True:
message = input("What is your message?: ")
mc.postToChat(message) |
import numpy as np
class Perceptron(object):
def __init__(self,n,epoch=100,alpha=0.10,bias=1):
self.alpha=alpha
self.epoch=epoch
self.weights=np.ones(n)
self.bias=bias
def predict(self, inputs):
sum=np.dot(inputs,self.weights)+self.bias
if sum>0:
a=1
else:
a=0
return a
def train(self,traini... |
import pandas as pd
from RPA.Excel.Application import Application
from RPA.Excel.Files import Files
from RPA.FileSystem import FileSystem
from page.selectors import *
app = Application()
excel = Files()
fs = FileSystem()
SECONDS = '30 seconds'
def setup_browser(browser, url, output):
browser.open_available_bro... |
import cv2 as cv
def line(img, point1, point2, color=(0, 255, 0), thickness=2):
cv.line(img, point1, point2, color, thickness)
def point(img, point, color=(0, 0, 255), thickness=2):
cv.circle(img, (point[0], point[1]), thickness, color)
def show(img):
cv.imshow("output", img)
cv.waitKey(0)
|
class Solution:
""" 题目描述是排序数组数组,二分查找,双指针 双指针是不是只能用在排序数组中 """
def countDistinctAbs(self, nums):
i, j = 0, len(nums) - 1
cnt = 0
while i < j:
# # 新的i和j如果和之前处理过的相同的话就跳过,这是我的写法
# 这是错误的,因为针对全相等的数组,第一次i和j进来的时候,
# 没有之前处理过的i和j,此时为跳到下面判断nums[i]+nums[j]的语句块,
... |
"""Даны два целых числа A и B (при этом A ≤ B). Выведите все числа от A до B включительно."""
a = int(input("Число A: "))
b = int(input("Число B: "))
i = a #Счетчик с какого стартует цыкл
while i <= b: #Условия цыкла
print(i)
i += 1 #На сколько увеличевается цыкл каждую ит... |
#!/usr/bin/python3
import time
import os
import numpy as np
import datetime
from multiprocessing import Process
import sys, getopt
#print(" ========================================================================================================= ")
#current = os.getpid()
#print ("Current process:", current)
#now_time=... |
########
# Copyright (c) 2018 Cloudify Platform Ltd. All rights reserved
#
# 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 requi... |
import os
import argparse
# define input args
argparser = argparse.ArgumentParser(description='Rename files sequentially.')
argparser.add_argument(
'-i',
'--input_path',
help='Path to input images.',
default=os.path.join('./'))
argparser.add_argument(
'-o',
'--output_path',
help='Path ... |
from datetime import datetime
import requests
URL = 'https://forecast.buienradar.nl/2.0/forecast/{}'
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S'
BUIENRADAR_ICONS = {
"a": "\uf00d",
"b": "\uf002",
"c": "\uf041",
"d": "\uf001",
"f": "\uf019",
"g": "\uf01e",
"h": "\uf019",
"i": "\uf026",
"j": "... |
class KthFactorOfN:
def kthFactor(self, n: int, k: int) -> int:
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
if count == k:
return i
return -1
if __name__ == '__main__':
init = KthFactorOfN()
print(init.kthFa... |
valor = int(input("v:"))
qtick = int(input("q:"))
vtick = float(input("v:"))
ponibus = int(input("q:"))
vpasses = float(input("v:"))
soma = (valor) - (qtick*vtick + ponibus*vpasses)
if(soma>=0):
print("suficiente".upper())
else:
print("insuficiente".upper()) |
from awacs.aws import Action, Allow, Policy, Principal, Statement
from troposphere import (
Template, applicationautoscaling, cloudwatch, cloudformation, ec2, ecs, elasticloadbalancingv2, iam, logs, ssm,
Equals, GetAZs, GetAtt, If, ImportValue, Join, Not, Parameter, Ref, Select, Sub
)
from uuid import uuid4
t ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.
import logging
from FuncionesBot import *
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message... |
import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn import tree
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_score, rec... |
from POINT__Lib import *
########################################################################################################
########################################################################################################
################################################################################... |
from subscriber_template import Subscriber
from topic_template import Topic
from publisher_template import Publisher
# Initialize publishers
PUB = Publisher()
# Initialize topics
TOPIC = Topic()
# Initialize subscribers
SUB = Subscriber()
# Register topics to publishers
PUB.registerTopic(TOPIC)
# Register subscrib... |
def NSR(arr):
stack = []
newarr = []
top = None
arr.reverse()
for i in range(len(arr)):
if i == 0:
newarr.append(-1)
stack.append(arr[i])
top = 0
else:
if stack[top] > arr[i]:
while stack != [] and stack[top] > arr[i]:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:
d = {n: n**2 for n in range(5)}
print d
|
# -*- coding: utf-8 -*-
from __future__ import division
import os
import re
import json
import time
import math
import random
from urlparse import urljoin
import scrapy
from scrapy.conf import settings
from multimedia_crawler.items import MultimediaCrawlerItem
from multimedia_crawler.common.common import get_md5, We... |
from os import getenv
import sys
import socket
import logging
import time
from threading import Thread
import hashlib
import sys
import pathlib
# python client.py numberofclients serveraddress
# Global variables
clientsNumber=sys.argv[1]
filename=time.strftime("%Y-%m-%d-%H-%M-%S",time.localtime())+"-log.txt"
path=pa... |
letterlist = [1110101, 10010110]
redval = 159
mod = redval % 4
if letterlist[0] == "00":
if mod == 0:
pass
if mod == 1:
# math to make mod 0
pass
if mod == 2:
# math to make mod 0
pass
if mod == 3:
# math to make mod 0
pass
if letterlist[0] == ... |
from django.contrib import admin
# import export
from import_export import fields, resources
from import_export.widgets import ForeignKeyWidget, BooleanWidget
from import_export.admin import ImportExportModelAdmin
# import models
from core.models import Session, Parlament
class SessionRessource(resources.ModelResou... |
import asyncio
from .base import *
import hermit.ui.state as state
async def relock_wallet_if_timed_out():
while True:
await asyncio.sleep(0.5)
await _handle_tick()
async def _handle_tick():
global Timeout
global Live
global Wallet
if state.Live:
state.Live = False
eli... |
# Generated by Django 2.2.18 on 2021-02-19 19:09
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('home', '0043_challenge_... |
from itertools import combinations
#"n" is the bit length of bot "x" and "u" vector
n=3
#define the input multiset "X"
'''X=['0000','0001','0010','0011','0100','0101','0110','0111','1000','1001','1010','1011','1100','1101','1110','1111',
'0000','0000','0000','0001','0010','0011','0100','0101','0110','0111']
'''
#... |
# -*- coding: utf-8 -*-
"""Implementation of pyprof2html commands.
"""
from optparse import OptionParser
import pyprof2html
from pyprof2html.core import Converter
from pyprof2html.environment import ENVIRON
__all__ = ['pyprof2html_main']
def pyprof2html_main():
"""execute a script of pyprof2html"""
parser =... |
import unittest
import threading
import signal
import os
import time
import datetime
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import ZSI
import database
import crypto
import utils
from numbex_server import MyNumbexService
from numbex_client import pull, pull_all, p... |
import sys
sys.path.append(sys.path[0] + '/Slackbot')
import unittest
from Slackbot import *
from Slackbot.intent_recognizer import BARTQueryIntent, BusQueryIntent
from Slackbot.intent_responder import IntentResponder, BARTQueryResponse, BusQueryResponse
class IntentResponderTest(unittest.TestCase):
def test(se... |
from qtpy import QtWidgets
from qtpy.QtWidgets import QRadioButton, QPushButton
from qtpy.QtCore import QSize
from qtpy import QtCore
from qtpy.QtCore import QSize, Signal
from qtpy import QtGui
import qtawesome as qta
class IconButton(QtWidgets.QPushButton):
def __init__(
self,
icon,
titl... |
from django.test import TestCase
# Create your tests here.
cls_name = "Variable2Server"
f=""" key
val
"""
fields = tuple(f.split())
TPL = """
import xadmin
from .models import {cls_name}
class {cls_name}Admin(object):
list_display = {fields}
list_filter = {fields}
search_fields = {fields}
xadmin.si... |
# Copyright 2010-2014 Michael Frank <msfrank@syntaxjockey.com>
#
# This file is part of Pesky. Pesky is BSD-licensed software;
# for copyright information see the LICENSE file.
class Store(object):
"""
"""
def __init__(self):
self._values = {}
def append(self, name, value):
"""
... |
from django.shortcuts import render
from django.http import HttpResponse
import json
from .forms import InventoryForm
from .predict import predict
from .models import Inventory
from django.conf import settings
from django.core import serializers
from .models import Cocktails
from .convertIngredients import convertIngre... |
"""
Wrapper for python import strings.
"""
from typing import Any, List, TypeVar
from handsdown.exceptions import ImportStringError
_R = TypeVar("_R", bound="ImportString")
class ImportString:
"""
Wrapper for python import strings.
Arguments:
value -- Import string.
"""
def __init__(se... |
import sys,os
def process_A(src_dir,dirname):
idx = int(dirname[1:])
if idx <= 800:
lm = "lm_test/LM/news_A_kaggle12"
elif 801 <= idx and idx <= 904:
lm = "lm_test/LM/3kingdom_A_kaggle12"
elif 1001 <= idx and idx <= 1086:
lm = "lm_test/LM/journey_west_A_kaggle12"
elif 1102 <... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy.spatial.distance import cdist
from sklearn.neighbors import LocalOutlierFactor
class LOF:
"""
局部离群因子类
"""
def __init__(self, X):
self.X = X
self.D_K = [] # X中每个样本点的k距离
self.NEIGHBORS = [] # X中每个样本点的k距离邻域
self.LRD ... |
#input
vidhaan= int(input("enter the first number"))
appaji= int(input("enter the second number"))
thug= vidhaan + appaji
print(thug)
|
def load_db():
user_dict = {}
notif_dict = {}
user_db = open('user_dict.db', 'rb')
notif_db = open('notif_dict.db', 'rb')
try:
obj = pickle.load(user_db)
if obj:
user_dict = obj
except:
pass
try:
obj = pickle.load(notif_db)
if obj:
notif_dict = obj
except:
pass
user_db.close(... |
"""
Converts edge relationships (e.g., bought together, also bought) to numeric weights between two nodes.
"""
import argparse
import numpy as np
import pandas as pd
from src.utils.logger import logger
relationship_weights = {'bought_together': 1.2,
'also_bought': 1.0,
... |
'''
Forçando tipos de dados com Decoradores
'''
print('\n')
'''
Relembrando o zip:
a = (1, 2, 3)
b = (4, 5, 6)
c = zip(a, b)
print(c) ===> (1, 4), (2, 5), (3, 6)
'''
# Definindo uma função:
def forca_tipo(*tipo):
def decorador(funcao):
def converte(*args, **kwargs):
novo_args = []
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Base class for QryForms
"""
__docformat__ = 'restructuredtext en'
### IMPORTS ###
from django import forms
from relais.dev import mountpoint, enum
from relais.webviz.html.simpletag import *
from relais.webviz.forms import formrender
__all__ = [
'BaseQryForm',
]... |
# Generated by Django 3.1.4 on 2020-12-16 09:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ghouse', '0005_auto_20201216_0832'),
]
operations = [
migrations.AddField(
model_name='checkinmodel',
name='totalroo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.