content stringlengths 5 1.05M |
|---|
from time import perf_counter
def timer(func):
def wrapper(*args, **kwargs):
start_t = perf_counter()
r_val = func(*args, **kwargs)
end_t = perf_counter()
elapsed = end_t - start_t
print(f"{func.__name__} took time: {elapsed} seconds, {elapsed/60} minutes")
return r... |
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import MetodPage
def metod(request):
metods = MetodPage.objects.all().order_by('title')
paginator = Paginator(metods, 10)
page = request.GET.get('page')
try:
... |
import itertools
def subpaths_for_path_range(path_range, hardening_chars="'pH"):
"""
Return an iterator of paths
# examples:
# 0/1H/0-4 => ['0/1H/0', '0/1H/1', '0/1H/2', '0/1H/3', '0/1H/4']
# 0/2,5,9-11 => ['0/2', '0/5', '0/9', '0/10', '0/11']
# 3H/2/5/15-20p => ['3H/2/5... |
#!/usr/bin/env python3
"""
Play Nerdle (https://nerdlegame.com)
"""
import json
import logging
from itertools import product
from os import mkdir
from os.path import dirname, join, realpath
from typing import Any, Iterator, List, Optional, Tuple
from .exceptions import CorrectAnswer, OutOfEquations, OutOfGuesses
cla... |
from dbt.contracts.graph.manifest import Manifest
import os
from test.integration.base import DBTIntegrationTest, use_profile
def get_manifest():
path = './target/partial_parse.msgpack'
if os.path.exists(path):
with open(path, 'rb') as fp:
manifest_mp = fp.read()
manifest: Manifest... |
import time
from base.common.skeleton_base import SkeletonBase
from base.constants import DEFAULT_BEFORE_EXPIRES
from base.exceptions import ChannelTemplateNotFound
from base.helpers import validate_channel
from base.utils import format_response
from typing import Dict
from .router import *
from .webhook import *
fro... |
from django.forms.widgets import CheckboxSelectMultiple, RadioSelect
class RadioSelectBootstrap(RadioSelect):
template_name = "leprikon/widgets/multiple_input.html"
option_template_name = "leprikon/widgets/input_option.html"
class CheckboxSelectMultipleBootstrap(CheckboxSelectMultiple):
template_name = ... |
import pandas as pd
class LeakageInspector:
def __init__(self, df1, df2, patient_col):
"""
Args:
df1 (dataframe): dataframe describing first dataset
df2 (dataframe): dataframe describing second dataset
patient_col (str): string name of column with patient IDs
"""
self.df1 = df1
self.df2 = df... |
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(name="Pairtree",
version="0.7.5",
description="Pairtree FS implementation.",
long_description="""\
From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html : Pairtree, a filesystem hierarc... |
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
from pages.createprojectpage.questionnaire_creation_options_page import QuestionnaireCreationOptionsPage
from pages.dashboardpage.dashboard_locator import *
from pages.page import Page
class DashboardPage(Page):
def __init__(self, driver):
Page.__init__(self, dr... |
'''Use this for development'''
from .base import *
ALLOWED_HOSTS += ['127.0.0.1']
DEBUG = True
WSGI_APPLICATION = 'home.wsgi.dev.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sarytask',
'USER': 'postgres',
'PASSWORD': 'S3d6622... |
import re
from jinja2.filters import contextfilter
@contextfilter
def to_dockbarx_items(context, pin_to_launcher_favorites):
'''
returns the DockbarX launcher items
'''
pin_to_launcher_favorites = list(pin_to_launcher_favorites)
omit = context.resolve('omit')
launcher_items = []
for f... |
import collections
import itertools
import typing
from checkmerge import analysis, report
class AnalysisResultMaxSeverityMetric(report.Metric):
"""
Metric for the maximum analysis result severity within a type.
"""
name = 'Max. severity'
low = .5
high = 1.5
def __init__(self, items: typi... |
"""
parser.py
products.json의 반찬 상세 페이지 url에 요청을 보내 크롤링하는 메소드 정의
메소들을 crawl.py 파일에서 사용함
"""
import requests
from bs4 import BeautifulSoup
import re
def get_soup(url):
webpage = requests.get(url).text
soup = BeautifulSoup(webpage, 'lxml')
return soup
def parse_name(name):
# content에 중량이 포함되어 있는지 체크
... |
import pandas as pd
import os
import sys
import subprocess
import numpy as np
import streamlit as st
import time
import random
from random import randint
from streamlit_player import st_player
from streamlit_autorefresh import st_autorefresh
import altair as alt
import back as fl
import usessss as fh
... |
GREY = (0.78, 0.78, 0.78) # uninfected
RED = (0.96, 0.15, 0.15) # infected
GREEN = (0, 0.86, 0.03) # recovered
BLACK = (0, 0, 0) # dead
COVID19_PARAMS = {
"r0": 2.28,
"incubation": 5,
"percent_mild": 0.8,
"mild_recovery": (7, 14),
"percent_severe": 0.2,
"severe_recovery": (21, 42... |
from troposphere import FindInMap, GetAtt, Join, Output, Parameter, Ref, Template
from troposphere.awslambda import MINIMUM_MEMORY, MAXIMUM_MEMORY, Code, Function
from troposphere.cloudformation import CustomResource
from troposphere.constants import NUMBER
from troposphere.ec2 import Instance, SecurityGroup
from tropo... |
from flask import Flask, render_template, redirect
app = Flask(__name__)
#--- routes start ---
from user import routes
@app.route("/")
def home():
return render_template('home.html')
@app.route("/login/")
def login_page():
return render_template('login.html')
@app.route("/about/")
def about():
return ... |
# qmpy/materials/element
"""
Django models representing elements and species.
"""
from django.db import models
from qmpy.db.custom import DictField
from qmpy.utils import *
class Element(models.Model):
"""
Core model for an element.
Relationships:
| :mod:`~qmpy.Atom` via atom_set
| :mod:`~... |
# # coding=utf-8
import unittest
import uuid
from google.appengine.ext import testbed
from application import create_app
from application.routes import create_routes
class FlaskClient(unittest.TestCase):
def setUp(self):
self.tb = testbed.Testbed()
self.tb.activate()
self.tb.init_memcache_... |
# -*- coding: utf-8 -*-
from django.db import models
from django.template.defaultfilters import date
from django.core.validators import MinValueValidator
from django.urls import reverse_lazy
from decimal import Decimal
from djangosige.apps.vendas.models import TIPOS_DESCONTO_ESCOLHAS, MOD_FRETE_ESCOLHAS, ST... |
class Stack(object):
"""This class implements all the need functions for a stack"""
def __init__(self):
self.items = []
def is_empty(self):
"""Returns true if stack is empty, returns false if stack has an
item"""
return self.items == []
def push(self, item):
""... |
# Implementacion generica de Arboles de Decisiones.
from math import log, inf
class Node:
def __init__(self, parent, X, Y, atr_types, default):
self.parent = parent
# Ejemplos del entrenamiento que pertenecen a este nodo.
self.X = X
# Etiquetas de los ejemplos.
self.Y = Y
# Tipos de atribut... |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class ISCSIDataIn(Base):
__slots__ = ()
_SDM_NAME = 'iSCSI_Data_In'
_SDM_ATT_MAP = {
'HeaderOpcode': 'iSCSI_Data_In.header.Opcode-1',
'HeaderFlags': 'iSCSI_Data_In.header.Flags-2',
'HeaderTotalAHSLength... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This is more akin to a .pyl/JSON file, so it's expected to be long.
# pylint: disable=too-many-lines
from gpu_tests import common_browser_args as cba
from... |
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#transform to [[x,y,z]...] [[x...],[y...],[z...]]
#plot
def plot_sample_list(sample_list,lim_val=10):
sample_mat = np.array(sample_list... |
### ---------------------------------------------------------------------------
from .core.startup import initialize
from .sublime import commands, events
__version_tuple = (1, 0, 0)
__version__ = ".".join([str(num) for num in __version_tuple])
### ------------------------------------------------------------------... |
# coding:utf-8
import redis
SCRIPT_PUSH = '''
local q = KEYS[1]
local q_set = KEYS[1] .. "_set"
local v = redis.call("SADD", q_set, ARGV[1])
if v == 1
then
return redis.call("RPUSH", q, ARGV[1]) and 1
else
return 0
end
'''
SCRIPT_POP = '''
local q = KEYS[1]
local q_set = KEYS[1] .. "_set"
local v = redis.call("LP... |
import os
import datetime
os.system("powercfg /batteryreport")
d = datetime.datetime.now()
try:
os.rename('battery-report.html', f'battery-health/reports/battery-report-{d.month}-{d.day}-{d.year}.html')
os.startfile(f'battery-health\\reports\\battery-report-{d.month}-{d.day}-{d.year}.html')
except WindowsError... |
import aspose.words as aw
from docs_examples_base import DocsExamplesBase, MY_DIR, ARTIFACTS_DIR
class WorkingWithPclSaveOptions(DocsExamplesBase):
def test_rasterize_transformed_elements(self):
#ExStart:RasterizeTransformedElements
doc = aw.Document(MY_DIR + "Rendering.docx")
... |
# MINLP written by GAMS Convert at 04/21/18 13:54:00
#
# Equation counts
# Total E G L N X C B
# 750 619 34 97 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
import sqlite3
import os
from pomodoro import Pomodoro
os.chdir("..") # Go up one directory from working directory
# Create database if it does not exist
database_path = "data\pomodoros.db"
if not os.path.exists(database_path):
print("Creating database ...")
os.system("database.py")
conn = sqlite3.connect(... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
w,h,k=map(int,input().split());r=0
for _ in [0]*k:
r+=(w+h<<1)-4;w-=4;h-=4
print(r) |
# -*- coding: utf-8 -*-
# À partir de l’export csv de https://opendata.paris.fr/explore/dataset/les-titres-les-plus-pretes/
# vous compterez le nombre d’ouvrages par ‘type de document’ et vous afficherez les types par ordre décroissant
from collections import Counter
sep = ';'
cnt = Counter()
with open('les-titres... |
#!/usr/bin/env python
#pythonlib
import os
import sys
import math
import re
import time
import glob
import numpy
#appion
from pyami import imagefun
from appionlib import appionLoop2
from appionlib import apImage
from appionlib import apDisplay
from appionlib import apDatabase
from appionlib.apCtf import ctfdb
from app... |
import torch
import torch.nn as nn
from models.pytorch_revgrad import RevGrad
from efficientnet_pytorch import EfficientNet as effnet
class EfficientNet(effnet):
def __init__(self, blocks_args=None, global_params=None):
super(EfficientNet, self).__init__(blocks_args=blocks_args, global_params=global_par... |
from idm.objects import dp, MySignalEvent, SignalEvent, __version__
from idm.utils import ment_user
from datetime import datetime
import time
@dp.signal_event_register('инфо', 'инфа', 'info')
def sinfo(event: SignalEvent) -> str:
if event.msg['from_id'] not in event.db.trusted_users:
message_id = event.sen... |
"""
Title: Video Vision Transformer
Author: [Aritra Roy Gosthipaty](https://twitter.com/ariG23498), [Ayush Thakur](https://twitter.com/ayushthakur0) (equal contribution)
Date created: 2022/01/12
Last modified: 2022/01/12
Description: A Transformer-based architecture for video classification.
"""
"""
## Introduction
V... |
import logging.config
import unittest
#import testing.mysqld
import sqlalchemy
from src.utils.Settings import Settings
# Modules to Test
from src.utils.Connector import Connector
class TestConnector(unittest.TestCase):
@classmethod
def tag(cls, *tags):
'''
Decorator to add tags to a test class... |
from rsTools.ui.menus import menu
from ... import shelf, shelfButton
from rsTools.glob import *
import os
import rsTools.utils.osUtils.enviroments as env
import maya.cmds as cmds
from rsTools.core.skeleton import skeletonAsset
class skeletonShelfButton(shelfButton.ShelfButton):
_color = (255, 157, 0)
_title =... |
# must be first, as it does event loop patching and other "first" things
from common.page_tokens import PageTokenManager
from oozer.entities.collect_entities_iterators import (
iter_collect_entities_per_page,
iter_collect_entities_per_page_graph,
)
from tests.base.testcase import TestCase, mock
from common.enu... |
"""
Model
"""
from . import attention
from . import evaluator
from . import GAN_model
from . import GAN_trainer
from . import generator
from . import trainer
|
import json
from typing import Dict, Optional
from azure.durable_functions.models.FunctionContext import FunctionContext
class DurableOrchestrationBindings:
"""Binding information.
Provides information relevant to the creation and management of
durable functions.
"""
# parameter names are as de... |
# Copyright 2014-2020 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program i... |
"""
Unit Testing
"""
def unittest(tests=None):
"""
A Unit Test wrapper that will return the return code and an error message ( if any )
- Return
Syntax:
{
0 : [return_code_1, error_message_1],
1 : [return-code_2, error_message_2],
}
Type: Dictionary
:: Syntax
tests
Description: The function ... |
n = int(input())
m = n
line = input().split()
t = 0
for i in range(0, n):
if int(line[i]) >= 0:
t += int(line[i])
else:
m -= 1
a = t / m
print(a) |
import pandas as pd
from pathlib import Path
import sys
import re
from collections import OrderedDict
import pyqtgraph as pg
from pyqtgraph.parametertree import Parameter, ParameterTree
from ephys.ephysanalysis import acq4read
from ephys.mapanalysistools import analyzeMapData as AMD
import pylibrary.tools.fileselector... |
first="Akash"
last="Singh"
fname=first+" "+last
print(fname) |
# Generated by Django 3.1.5 on 2021-01-13 18:09
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... |
#!/usr/bin/env python3
#
# MIT License
#
# Copyright (c) 2020-2021 EntySec
#
# 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... |
#!/usr/bin/env python
#############################################################
# ubi_reader/ubi_io
# (c) 2013 Jason Pruitt (jrspruitt@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Founda... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from codegen.spec import *
from codegen.mir_emitter import *
from codegen.isel import *
from codegen.x64_def import *
from codegen.matcher import *
class X64OperandFlag(IntFlag):
NO_FLAG = auto()
# GOT_ABSOLUTE_ADDRESS - On a symbol operand = auto() this represe... |
import pathlib
from setuptools import setup, find_packages
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name='pylateral',
version='1.0.0',
description='Intuitive multi-threaded task processing in python.',
long_description=README,
long_description_content_t... |
import numpy as np
class BaseAgent:
def __init__(self, name, environment=None):
self.name = name
self.environment = environment
def choose_action(self):
action = np.random.choice(self.environment.valid_actions)
pawn_actions = [a for a in self.environment.valid_actions if a < 1... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Updates ExtensionPermission2 enum in histograms.xml file with values read
from permission_message.h.
If the file was pretty-printed, the updated version ... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict
import pkg_resources
import pytest
import torch
from flsim.common.pytest_helper i... |
import click
import json
from pathlib import Path
from PIL import Image
import pycountry
import re
import shlex
import subprocess
import time
import traceback
import youtube_dl
SUB_LANGUAGES = ['en', 'en-US', 'en-UK', 'en-us', 'en-uk', 'de', 'de-DE', 'de-de', 'un']
ytops = {
'outtmpl': '{}.%(ext)s',
'hls_pref... |
from dataclasses import dataclass
@dataclass
class SpotifyConfig:
client_id: str
client_secret: str
refresh_token: str
|
"""
Application load balancer stack for running ConsoleMe on ECS
"""
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_elasticloadbalancingv2 as lb
from aws_cdk import core as cdk
class ALBStack(cdk.NestedStack):
"""
Application load balancer stack for running ConsoleMe on ECS
"""
def __ini... |
# --------------------------------------------------
# Gene class
# Authors: Thomas Schwarzl, schwarzl@embl.de
# --------------------------------------------------
import gzip
import logging
from collections import OrderedDict, defaultdict
from HTSeq import GenomicArray, GenomicArrayOfSets, GenomicPosition, GenomicF... |
from __future__ import print_function
import os
import subprocess
import shlex
from getpass import getuser
from distutils.command.build import build # type: ignore
from setuptools import (
find_packages,
setup,
Command
)
import numpy as np
CUSTOM_COMMANDS = [
shlex.split(command_line) for command... |
# Copyright 2004-present, Facebook. All Rights Reserved.
from django.contrib.auth.decorators import login_required
from django.urls import path
from . import views
urlpatterns = [
# products
path(
"store/<int:storeId>/products/create",
login_required(views.createProduct),
name="createP... |
from detective import functions
import math
MOCK_ATTRIBUTE = {
"battery_level": 61,
"unit_of_measurement": "°C",
"friendly_name": "Living room sensor temperature",
"device_class": "temperature",
}
def test_device_class():
"""Test get_device_class"""
assert functions.get_device_class(MOCK_ATTR... |
from argparse import ArgumentParser
import examples.example02.tasks
from cline.cli import ArgumentParserCli, RegisteredTasks
class ExampleCli(ArgumentParserCli):
def make_parser(self) -> ArgumentParser:
parser = ArgumentParser()
parser.add_argument("a", help="first number", nargs="?")
par... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from pandas.compat import StringIO
import sys
import re
import os
import ntpath
def file_to_df(filename):
with open(filename, 'r') as file:
contents = file.read()
# Read run configurations
sta... |
import os
import socket
import struct
import sys
import select
os.system("")
UDP_PORT = 13117
MESSAGE_LEN = 1024
GAME_TIME = 10
sockUDP = None
sockTCP = None
# Colors for prints
class Colors:
GREEN = '\033[32m'
BLUE = '\033[34m'
PINK = '\033[35m'
def printMessageOrRead():
# wait for read or write ... |
from tests.testcases import TestCaseUsingRealAPI
from vortexasdk import Products, Geographies, Corporations, Vessels
endpoints_and_searchterms = [
(Products(), "Gasoil"),
(Geographies(), "China"),
(Corporations(), "Oil"),
(Vessels(), "Ocean"),
]
class TestSearchReal(TestCaseUsingRealAPI):
def tes... |
from app import app
from flask import request, session
from helpers.database import *
from helpers.hashpass import *
from helpers.mailer import *
from bson import json_util, ObjectId
import json
def checkloginusername():
username = request.form["username"]
check = db.users.find_one({"username": username})
... |
"""Hyperparameters from paper """
import numpy as np
import torch.optim as optim
from .model import DQN, DuelingDQN
class AtariHyperparams:
ALGO = "DQN"
SEED = 2
LOG_DISPLAY_FREQ = 10
# Image sizing
WIDTH = 84
HEIGHT = 84
# Number of most recent frames given as input to Q-network
A... |
"""
Queue backend abstraction manager.
"""
import json
import logging
import sched
import socket
import time
import uuid
from typing import Any, Callable, Dict, List, Optional, Union
from pydantic import BaseModel, validator
import qcengine as qcng
from qcfractal.extras import get_information
from ..interface.data ... |
import logging
from importlib import import_module
from .groups import Groups
log = logging.getLogger(__name__)
class ConfigHelper:
@classmethod
def cog_name(cls, key):
return ''.join(map(str.capitalize, key.split('_')))
CONFIG_GROUP_MAPPINGS = [
('sudo', 'user', 'sudo'),
('sysb... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.apps import apps, AppConfig
class PanopticonConfig(AppConfig):
name = "panopticon.django"
label = "panopticon"
verbose_name = "Panopticon"
def ready(self):
package_names = (a.module.__name__ for a in ... |
import numpy as np
from numba import jit
from scipy.sparse.construct import random
from ..tools import compute_dist
from ._utils import _CheckInputs
from .base import IndependenceTest, IndependenceTestOutput
from scipy.stats import rankdata
class HHG(IndependenceTest):
r"""
Heller Heller Gorfine (HHG) test s... |
from django.contrib import admin
from spaweb.models import Customer, ProductCategory, City
from spaweb.models import Product, Order, OrderItem
from spaweb.models import BusinessDirection, Topic
admin.site.register(ProductCategory)
admin.site.register(City)
admin.site.register(BusinessDirection)
admin.site.register(To... |
# -*- coding: utf-8 -*-
"""Pype custom errors."""
class PypeError(Exception):
"""Custom error."""
pass
|
"""
ipython -i --pdb scripts/train_model.py -- --model cropped_jan02 --data 128_20151029 --use_cropped --as_grey --overwrite --no_test
"""
import numpy as np
from lasagne.layers import dnn
import lasagne as nn
import theano.tensor as T
import theano
from utils.nolearn_net import NeuralNet
from nolearn.lasagne.handle... |
from __future__ import annotations
import abc
import datetime
import decimal
import typing as t
import zoneinfo
# region: Bases
class SpecialValue(abc.ABC):
"""Represents a special value specific to an SQL Type."""
def __init__(self, python_value: t.Any, sql_value: str):
self._py_value = python_val... |
"""
Copyright 2020 The OneFlow Authors. 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 required by applicable law or agr... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from obscmd import compat
def init():
global _global_dict
_global_dict = {}
def use_lock(key):
lock_key = key + '_lock'
if lock_key not in _global_dict:
_global_dict[lock_key] = compat.Lock()
return lock_key
def set_value(key, value):
_... |
from hill import Hill
from numpy.linalg.linalg import norm
from jumper import Jumper
from jump_result import JumpResult
from physics_simulator import PhysicsSimulator
import numpy as np
import random
angles = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44]
kw_pts = [... |
"""
Implements a simple HTTP/1.0 Server
"""
import socket
# Define socket host and port
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 7777
# Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST... |
# coding=utf-8
#-----------------------------------------------------------
# IMPORTS
#-----------------------------------------------------------
import enigmus
import messages
import random
from entities import Entity, Player, Room
#-----------------------------------------------------------
# CLASSES
#----------... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-23 21:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('problems', '0040_auto_20161123_2106'),
]
operations... |
# Ultroid - UserBot
# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
#
# Ported by @AyiinXd
# FROM Ayiin-Userbot <https://github.com/Ayiin... |
# encoding:utf-8
from flask import Flask,request
import json
import time
import sys
import sqlite3
import os
app=Flask(__name__)
####回复文本格式##########
re={}
result={}
result["type"]="text"
result["content"]=""
re["error_code"]=0
re["error_msg"]=""
re["result"]=result
dic={'温度':'temperature','湿度':'humid... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#1 - Normalize vector:
def normalize_v(V):
m = 0
for x in V: m += x**2 #Sum of the elements powered to the 2
m = sqrt(m) #Get vector's norm
return [x/m for x in V] #Divide each element of vector by its norm
#2 - Find D, euclidian distance
def euclid_dis(V... |
from spaceone.inventory.manager.pricing_manager import PricingManager
|
#!/usr/bin/env python
import sys
import dnfile
from hashlib import sha256
filename = sys.argv[1]
sha256hash = ''
with open(filename, 'rb') as fh_in:
sha256hash = sha256(fh_in.read()).hexdigest()
pe = dnfile.dnPE(filename)
#tbl = pe.net.mdtables.MemberRef
tbl = pe.net.mdtables.TypeRef
tbl_num_rows =\
pe.ge... |
import pandas as pd
fname = "LBW_dataset.csv"
df = pd.read_csv(fname)
#cleaning data
df = df.drop(columns=['Education'])
df = df.interpolate()
df['Community'] = df['Community'].round()
df['Delivery phase'] = df['Delivery phase'].round()
df['IFA'] = df['IFA'].round()
#df = df.round()
mean_weight = df['... |
"""
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 writing, software
distri... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
from astropy.io import fits
from astropy.table import Table
from gammapy.data import GTI
from gammapy.maps import MapCoord, Map
from gammapy.estimators.core import FluxEstimate
from gammapy.estimators.flux_point import Flu... |
from flask import Flask
from driver import get_final_kmeans
app = Flask(__name__)
@app.route("/")
def hello():
return get_final_kmeans() |
from typing import Any, Dict, List, Optional, Union
from interactions.ext.paginator import Paginator
from thefuzz.fuzz import ratio
from interactions import Client, CommandContext, DictSerializerMixin, Embed, Extension
from .settings import AdvancedSettings, PaginatorSettings, TemplateEmbed, typer_dict
class RawHe... |
import numpy as np
from sklearn.cluster import MeanShift# as ms
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
centers = [[1,1], [5,5]]
X,y = make_blobs(n_samples = 10000, centers = centers, cluster_std = 1)
plt.scatter(X[:,0],X[:,1])
plt.show()
ms = MeanShi... |
# Copyright 2020 Arthur Coqué, Valentine Aubard, Pôle OFB-INRAE ECLA, UR RECOVER
#
# 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 ... |
from tkinter import *
root = Tk()
root.geometry('225x230')
root.resizable(False, False)
root.title('Learning English')
def showMenu():
menu1.pack()
menu2.pack()
def hideMenu():
menu1.pack_forget()
menu2.pack_forget()
menu1 = Button(text = 'Can you translate?\nENG --> RUS', width = 300, height = 7)
m... |
import numpy as np
from time import time
import xorshift
rng = xorshift.Xoroshiro()
rng2 = xorshift.Xorshift128plus()
def output(name, start, end):
elapsed = (end - start) * 1000
per_iter = elapsed / iters
per_rv = per_iter / count * 1e6
print '%s took %.2f ms/iter, %.2f ns per float' % (name, per_ite... |
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QHBoxLayout, QLabel, QSlider
from traitlets import HasTraits, Unicode, Int, observe
from regexport.views.utils import HasWidget
class LabelledSliderModel(HasTraits):
label = Unicode()
min = Int(default_value=0)
max = Int()
value = I... |
'''
Configure web app settings. Updating or removing application settings will cause an app recycle.
'''
from .... pyaz_utils import _call_az
def list(name, resource_group, slot=None):
'''
Get the details of a web app's settings.
Required Parameters:
- name -- name of the web app. If left unspecified,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bandit Algorithms
This script follows Chapter 2 of Sutton and Barto (2nd) and simply reproduces
figures 2.2 to 2.5.
Author: Gertjan van den Burg
License: MIT
Copyright: (c) 2020, The Alan Turing Institute
"""
import abc
import math
import matplotlib.pyplot as plt
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.