content stringlengths 5 1.05M |
|---|
import asyncio
import logging
from functools import wraps
from typing import List, Optional, SupportsInt, Union, TYPE_CHECKING # noqa
import asyncpg
from pypika import PostgreSQLQuery
from tortoise.backends.asyncpg.executor import AsyncpgExecutor
from tortoise.backends.asyncpg.schema_generator import AsyncpgSchemaGe... |
from .model import protonet_graph
from .loss import build_loss_fn
|
# ROY AND TRAINS
from math import ceil
#take input
for _ in range(int(input())):
t0,t1,t2,v1,v2,d = list(map(int, input().split()))
if t0<=t1 or t0<=t2:
if t0>t1:
t2 += int(ceil((d/v2)*60))
print(t2)
elif t0>t2:
t1 += int(ceil((d/v1)*60))
... |
import modelexp
from modelexp.experiments.sas import Saxs
from modelexp.models.sas import Cube
from modelexp.data import XyeData
from modelexp.fit import LevenbergMarquardt
from modelexp.models.sas import InstrumentalResolution
app = modelexp.App()
app.setExperiment(Saxs)
dataRef = app.setData(XyeData)
dataRef.load... |
# Copyright 2016 Netherlands eScience Center
#
# 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 t... |
import cv2
import numpy as np
import os
import sys
from samples.coco import coco
from mrcnn import utils
from mrcnn import model as modellib
import PIL.Image
import sys
# Load the pre-trained model data
ROOT_DIR = os.getcwd()
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcn... |
"""
lolbot rewrite - (c) 2020 tilda under MIT License
This module contains code needed to start the bot, including other services,
such as the API
"""
from discord.ext import commands
from logbook import Logger, StreamHandler, INFO
from logbook.compat import redirect_logging
from sys import stdout
from core.config im... |
from share import models
from api.base import ShareSerializer
# TODO make an endpoint for SourceConfigs
class SourceConfigSerializer(ShareSerializer):
class Meta:
model = models.SourceConfig
fields = ('label',)
|
def print_result(time, collection):
if collection:
print("Not all customers were driven to their destinations")
print(f'Customers left: {", ".join(map(str,collection))}')
else:
print("All customers were driven to their destinations")
print(f"Total time: {total_time} minutes")
cu... |
print("vikranth datta")
print(" roll number:AM.EN.U4ECE19157")
print("ECE")
print("marvel rocks")
|
# importing packages
from pytube import YouTube
import os
# url input from user
audio_object = YouTube(
str(input("Enter the URL of the video you want to download: \n>> ")))
# extract only audio
video = audio_object.streams.filter(only_audio=True).first()
# check for destination to save file
print("E... |
import pickledb
import re
import yaml
from datetime import *
_ignoreUsage = "Sorry, I don't understand. The correct usage is '!ignore <-me | @user> [minutes]'."
_dmsUsage = "Sorry, I dom't understand. The correct usage is '!dms <-enable | -disable>'."
with open("./conf.yaml") as conf:
config = yaml.load(conf, Loa... |
"""Generate www tables."""
import io
import ast
from datetime import datetime
from os.path import isdir,isfile,basename
from os import mkdir,remove,write,rmdir
import numpy as np
from astropy.table import Table
from astropy.utils import xml
import mysql.connector
import jinja2
import bokeh.resources
from . import d... |
# flake8: NOQA
from cupyx.scipy.linalg.special_matrices import (
tri, tril, triu, toeplitz, circulant, hankel,
hadamard, leslie, kron, block_diag, companion,
helmert, hilbert, dft,
fiedler, fiedler_companion, convolution_matrix
)
from cupyx.scipy.linalg.solve_triangular import solve_triangular # NOQA
f... |
# -*- coding: utf-8 -*-
def possible_moves(cordy_pionka, cord_list_of_bottom_pieces, cord_list_of_top_pieces):
return_dict = dict()
if cordy_pionka in cord_list_of_bottom_pieces:
if (cordy_pionka[0]-1, cordy_pionka[1]+1) not in cord_list_of_top_pieces + cord_list_of_bottom_pieces:
if cordy... |
RSA_MOD = 104890018807986556874007710914205443157030159668034197186125678960287470894290830530618284943118405110896322835449099433232093151168250152146023319326491587651685252774820340995950744075665455681760652136576493028733914892166700899109836291180881063097461175643998356321993663868233366705340758102567742483097 ... |
#!/usr/bin/env python
# Copyright (C) 2015 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
# Generated by Django 3.1.5 on 2021-03-05 02:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('imageais', '0005_auto_20210304_2050'),
]
operations = [
migrations.RenameModel(
old_name='ImageFaceAnalyis',
new_name='Image... |
import logging
import fabric.api
import fabric.operations
import cloudenvy.envy
class Ssh(cloudenvy.envy.Command):
def _build_subparser(self, subparsers):
help_str = 'SSH into your Envy.'
subparser = subparsers.add_parser('ssh', help=help_str,
descripti... |
# Copyright 2013 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file accompa... |
import six
from rowboat.types import SlottedModel
class PluginConfig(SlottedModel):
def load(self, obj, *args, **kwargs):
obj = {
k: v for k, v in six.iteritems(obj)
if k in self._fields and not self._fields[k].metadata.get('private')
}
return super(Plug... |
# -*- coding: utf-8 -*-
from App import App
from PyQt5.Qt import *
from pyqtgraph.Qt import QtCore, QtGui
# Operating system
import sys
import time
def main(args):
global app
app = App(args)
app.exec_()
if __name__ == "__main__":
main(sys.argv)
|
###Titulo:Converte expressões matemáticas
###Função: Este programa comverte expressões matétáticas básicas para Python
###Autor: Valmor Mantelli Jr.
###Data: 24/11/20148
###Versão: 0.0.1
10 / 20 * 30
4 ** 2 / 30
(9 ** 2 + 2) * 6 - 1
|
from Test import Test, Test as test
'''
Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.
Write a function that will take the number... |
# coding=utf-8
# Copyright 2017-2019 The THUMT Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
_ENGINE = None
def enable_distributed_training():
global _ENGINE
try:
import horovod.tensorflow as hvd
_ENGINE = hvd... |
from loguru import logger
from data.dbase.djconn import start_connection
try:
dbname, schema = start_connection()
except Exception as e:
logger.warning(f"Failed to connect to datajoint database:\n{e}")
connected = False
else:
logger.debug(f"Connected to database: {dbname}")
connected = True
from d... |
# -*- coding: utf-8 -*-
"""
The steps file contains various generally reusable image processing steps.
"""
import hashlib
from base64 import b64encode
import numpy as np
import scipy.ndimage as ndi
from pilyso_io.imagestack import Dimensions
from ..application.application import Meta
from mfisp_boxdetection import f... |
'''
# coding: utf-8
Based on https://github.com/iunullc/machine-learning-sdk/blob/master/docs/model_testing_methodology.md
'''
import os
import iuml.tools.auxiliary as iutools
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from multiprocessing import pool
import multiprocessing
from da... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'initialMessagePage.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import Q... |
# serial data dumper for Jack and Dirty Dan
# Assumes that all formatting (comma separated) happens on the arduino
# and assumes that the arduino is probably using serial.print() to send
# the data over the serial port and assumes that the OS is windows
import serial
from datetime import datetime
import msvcrt
# chan... |
from pando.testing.client import FileUpload
def test_test_client_can_override_headers(harness):
harness.fs.www.mk(('foo.spt', '''
[---]
host = request.headers[b'Host'].decode('idna')
[---] text/html via stdlib_format
{host}'''))
response = harness.client.POST('/foo', HTTP_HOST=b'example.org')
... |
num=int(input("Enter your percentage:"))
if num<40:
print("Failed")
elif num<55:
print("Fair")
elif num<65:
print("Good")
elif num<=100:
print("Excellent")
else :
print("You entered wrong percentage")
|
TRAIN_YOLO_IOU_IGNORE_THRES = .7
TRAIN_YOLO_CONF_THRESHOLD = .5
TEST_YOLO_CONF_THRESHOLD = .7
|
'''This task calls the `request` method of a `grizzly.users` implementation.
This is the most essential task in `grizzly`, it defines requests that the specified load user is going to execute
against the target under test.
Instances of this task is created with the step expressions:
* [`step_task_request_text_with_n... |
class PingbackFormulationError(Exception):
def __init__(self, *args):
# *args is used to get a list of the parameters passed in
self.args = [a for a in args] |
#HEADER
import random
from src.utils import create, search
from game.gamesrc.objects.world.items import Weapon, Armor, Potion
#CODE (Generate all items for loot tables)
#begin artifact item creation
storage = search.objects('storage')[0]
hammer = create.create_object(Weapon, key="An\'Karith's Hammer", location=storag... |
# coding: utf-8
import unittest
from problems.add_two_numbers import Solution
from problems.utils.leetcode import list_to_listnode
from problems.utils.leetcode import listnode_to_list
class TestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test(self):
l1 = list_to_... |
# Copyright 2014 Citrix Systems
#
# 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... |
from osgeo import ogr
import sys
import psycopg2
from ede.credentials import DB_NAME, DB_PASS, DB_PORT, DB_USER, DB_HOST
import json
def main(shapefile):
## Connection to the database ##
conn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS,
host=DB_HOST, port=D... |
# This python script is just for reference, do not import this file
# The same _EVE class is intergrated into CircuitPython binary
# Documented at: https://circuitpython.readthedocs.io/en/latest/shared-bindings/_eve/index.html
import struct
class _EVE:
def cc(self, s):
assert (len(s) % 4) == 0
se... |
from django.conf import settings
from django.template import loader, TemplateDoesNotExist
from livesettings.functions import config_value
from satchmo_store.shop.signals import rendering_store_mail, sending_store_mail
from socket import error as SocketError
import logging
log = logging.getLogger('satchmo_store.mail')... |
# Copyright 2020 Makani Technologies LLC
#
# 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... |
from sofi.ui import Code
def test_basic():
assert(str(Code()) == "<code></code>")
def test_text():
assert(str(Code("text")) == "<code>text</code>")
def test_custom_class_ident_style_and_attrs():
assert(str(Code("text", cl='abclass', ident='123', style="font-size:0.9em;", attrs={"data-test": 'abc'}))
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappé and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from subprocess import Popen, PIPE, STDOUT
import re, shlex
from frappe.utils import flt, cstr
from frappe.utils.background_jobs import enque... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
===========================
TracRemote.tests.needs_mock
===========================
Contains a superclass for test cases that need a mock Trac server running.
"""
import unittest
import os
import stat
import subprocess
import t... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright INRIA
# Contributors: Wahiba Taouali (Wahiba.Taouali@inria.fr)
# Nicolas P. Rougier (Nicolas.Rougier@inria.fr)
#
# This software is governed by the CeCILL license under French law and abidin... |
# coding= utf-8
import random
from Crypto.PublicKey import RSA
# Função para sortear os pares
def sorteiaPares(listaDeParticipantes): # Recebe lista com nome dos participantes
# e o valor é a chave pública dela
dictSorteado = {} # Dict a ser retornado
numeroDePar... |
def test__db_implementation_selector():
pass
|
__version__ = """1.30.0""" |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 13 09:36:43 2017
@author: Administrator
"""
from numpy import * #导入numpy的函数库
import numpy as np
import scipy.io as scio
from scipy import interp
import matplotlib.pyplot as plt
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn... |
print("HEMANTH NAIDU ABBURI")
PRINT("AM.EN.U4CSE19223")
PRINT("CSE-D")
|
# -*- coding=utf -*-
import unittest
from cubes import __version__
import json
from .common import CubesTestCaseBase
from sqlalchemy import MetaData, Table, Column, Integer, String
from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse
from cubes.server import create_server
from cubes import comp... |
#
# ovirt-engine-setup -- ovirt engine setup
#
# Copyright oVirt Authors
# SPDX-License-Identifier: Apache-2.0
#
#
"""websocket-proxy plugin."""
import gettext
from otopi import plugin
from otopi import util
from ovirt_engine_setup import constants as osetupcons
from ovirt_engine_setup.websocket_proxy import const... |
#import numpy as np # linear algebra
#import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn import datasets
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import NearestCentroid
from sklearn import model_selection
from sklearn.model_selection import train_test_spli... |
# Copyright 2018 Geobeyond Srl
#
# 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, so... |
import numpy as np
from code.pytorch.LAMPO.core.model import sum_logs_np
from sklearn.cluster import KMeans
from scipy.stats import multivariate_normal as scipy_normal
from sklearn.covariance import ledoit_wolf
def stable_cov(cov, reg):
reg_new = np.copy(reg)
cov_new = np.copy(cov)
while True:
try... |
DEBUG = False
BCRYPT_LOG_ROUNDS = 12 |
#!/usr/bin/python2
# Python3-like changes
from __future__ import absolute_import, division, print_function
# Comment on documentation:
# When reading the doc strings if "Pre:" is present then this stands for "precondition", or the conditions in order to invoke something.
# Oppositely, "Post:" stands for "postconditio... |
from nextsong import Playlist as p
p(
"01.mp3",
p(
p("02.mp3", weight=1 / 4),
p(weight=3 / 4),
count=1,
),
"03.mp3",
"04.mp3",
loop=True,
).save_xml()
|
import logging
import os
import inspect
from Utils.cli import CliArgs
class PhaazeLoggerFormatter(logging.Formatter):
""" custom logging colors """
def __init__(self, fmt:str):
super().__init__(fmt)
self.default_color:str = "\033[00m"
self.colors:dict = dict(
DEBUG="\033[90m",
INFO="\033[36m",
WARNIN... |
import logging
import pprint
import boto3
import json
from src.utils import awsutils
from botocore.exceptions import ClientError
#logger = logging.getLogger(__name__)
#ec2 = boto3.resource('ec2')
def get_tag_specifications(dct, name_prefix):
dct["Name"] = name_prefix + dct["Name"]
tags = []
for k, v in dc... |
from __future__ import absolute_import
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.utils.urls import remove_query_param, replace_query_param
from collections import OrderedDict
from rest_framework.response import Response
from infi.django_rest_utils import pagination
from django.... |
from huey import SqliteHuey
from cloudcopy.server.config import settings
# if ASYNC_TASKS is False (e.g. in testing)
# async tasks will be executed immediately
# or added to an in-memory schedule registry
app = SqliteHuey(
'tasks',
filename=settings.INTERNAL_DATABASE_FILE,
immediate=not settings.ASYNC_TASK... |
import re
from iofree import schema
HTTP_LINE = re.compile(b"([^ ]+) +(.+?) +(HTTP/[^ ]+)")
class HTTPResponse(schema.BinarySchema):
head = schema.EndWith(b"\r\n\r\n")
def __post_init__(self):
first_line, *header_lines = self.head.split(b"\r\n")
self.ver, self.code, *status = first_line.spl... |
from PyQt4 import QtCore, QtGui
from sm_ui import Ui_MainWindowSM
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
import sqlite3
import datetime
import time
from data_models import *
#some useful tutorials:
#http://www.qgisworkshop.org/html/workshop/python_in_qgis_tutorial2.ht... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) 2020, Bodo Schulz <bodo@boone-schulz.de>
# BSD 2-clause (see LICENSE or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import print_function
import re
from ansible.module_utils import distro
from ansible.module_utils.basic import AnsibleModule
__me... |
def write_out_sam(header, outsam, outpath):
print('Writing trimmed sam to: %s' % outpath)
with open(outpath, 'w') as OUT:
OUT.write('\n'.join(header + outsam))
def trim_sam_by_windows(sam, positions):
header = []
output = []
with open(sam, 'r') as FILE:
for line in FI... |
"""Testing basic ways to setup a dataset."""
import unittest
import uuid
from copy import copy
import numpy as np
import pandas as pd
from torch.utils.data import DataLoader
from pytoda.datasets import (
ConcatKeyDataset,
DatasetDelegator,
KeyDataset,
indexed,
keyed,
)
from pytoda.types import Has... |
import pandas as pd
from desafio_iafront.jobs.pedidos.contants import KEPT_COLUNS, COLUMN_RENAMES
def _prepare(pedidos_joined: pd.DataFrame) -> pd.DataFrame:
# Remove colunas resultantes do merge
result_dataset = drop_merged_columns(pedidos_joined)
# Remove colunas que não serão usadas
result_dataset... |
import numpy as np
"""
Additional functions for the movement algorithms
"""
FRICCION = 0.995
def normalize(vector: np.ndarray) -> np.ndarray:
"""
Normalizes input vector to have a lenght of 1 if
the vector is not a 0-vector. Otherwise, it is left unchanged
Args:
vector: vector to normalize
... |
import os
import base64
import json
from pathlib import Path
class EnvironmentReferenceError(Exception):
pass
def decode_base64(input_str: str) -> str:
base64_bytes = input_str.encode("utf-8")
message_bytes = base64.b64decode(base64_bytes)
return message_bytes.decode("utf-8")
def read_json(directo... |
# AutoTransform
# Large scale, component based code modification library
#
# Licensed under the MIT License <http://opensource.org/licenses/MIT>
# SPDX-License-Identifier: MIT
# Copyright (c) 2022-present Nathan Rockenbach <http://github.com/nathro>
# @black_format
"""A change represents a submission from a run of Au... |
import sqlite3
from sqlite3 import Error
import cmd2web
import sys
import datetime
class DatabaseConnection:
def __init__(self,db_file):
try:
self.conn = sqlite3.connect(db_file)
# return self.conn
except Error as e:
print(e)
# return None
def close(s... |
import math
import matplotlib.pyplot as plt
from merl import Merl
def main():
brdf = Merl('aluminium.binary')
samples = 1024
theta_h = [math.pi / 2 * x / samples for x in range(0, samples)]
reflectance_raw_ndf = [brdf.eval_raw(th, 0, 0) for th in theta_h]
reflectance_interp_ndf = [br... |
import pytest
import numpy as np
from numpy.testing import assert_almost_equal
from acrolib.quaternion import Quaternion
from acrolib.sampling import SampleMethod
from acrolib.geometry import rotation_matrix_to_rpy
from acrobotics.robot import Robot, IKResult
from acrobotics.path.tolerance import (
Tolerance,
... |
class ImageStore:
pass
|
# LOCUS log parser
# (c) 2013 Don Coleman
import sys
from pprint import pformat
from datetime import datetime
# turn a string of bytes into a byte array
def toByteArray(str):
bytes = []
while len(str) > 1:
byte = str[:2]
bytes.append(int(byte, 16))
str = str[2::]
return ... |
from rest_framework.routers import DefaultRouter
class OptionalSlashRouter(DefaultRouter):
def __init__(self, *args, **kwargs):
super(DefaultRouter, self).__init__(*args, **kwargs)
self.trailing_slash = '/?'
|
"""This module handles the auto-file using Geofabrik's download service.
"""
import logging
import os
import shutil
import subprocess
import helpers
def get_region_filename(region, subregion):
"""Returns the filename needed to download/manage PBF files.
Parameters
----------------------
region : str... |
import json
from enum import Enum
import meilisearch
import structlog
from django.conf import settings
from zoo.analytics.models import Dependency
from zoo.base import redis
from zoo.services.models import Service
from zoo.utils import model_instance_to_json_object
log = structlog.get_logger()
class IndexType(Enum... |
from .login import Login, LoginForm
from .logout import Logout
from .signup import Signup, SignupForm
from .password_reset import PasswordReset, PasswordResetForm
from .password_reset_token import PasswordResetToken, PasswordResetTokenForm
from .update import FlexibleUpdate
from .delete import MultipleDelete |
""" define the linechart dataset tag """
from __future__ import absolute_import, unicode_literals
import json
from django import template
from saef.models import DatasetProfileHistory
register = template.Library()
@register.inclusion_tag('dataset/linechart_dataset.html')
def linechart_dataset(ds_id = -1, amount = ... |
import os
import csv
import re
from os import listdir
from os.path import isfile, join
from shutil import copyfile
from shutil import copyfile
from os import listdir,path
import random
import string
from datetime import datetime
cur = os.getcwd()
prefix = "TARGET"
# vol_num = 1
vol_nums = [1,2]
# [1,2,3,4,5,6,7,8]
pro... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import os
import pyfasta
import allel
import seaborn as sns
import petl as etl
import h5py
import pandas
title = 'Phase 1 AR3 release'
pop_ids = 'AOM', 'BFM', 'GWA', 'GNS', 'BFS', 'CMS', 'GAS', 'UGS', 'KES'
pop_labels = {
... |
def birthday(s, d, m):
count = 0
for i in range(0, len(s)+1-m):
if sum(s[i:i+m]) == d:
count += 1
return count
|
import random
import requests
import time
import logging
import json
from urllib.parse import urlencode, quote
from playwright.sync_api import sync_playwright
import string
import logging
import os
from .utilities import update_messager
from .exceptions import *
os.environ["no_proxy"] = "127.0.0.1,localhost"
BASE_UR... |
#!/bin/env python3
import argparse
import sys
from common import *
parser = argparse.ArgumentParser(description='Transform CSV to i18n for use in epsilon.')
parser.add_argument('file', help='Input file, without the langage part.')
args = parser.parse_args()
data, langs = load_csv(args.file + ".csv")
if (data, lang... |
import os
from functools import partial
import numpy as np
import fiona
import pyproj
from osgeo import gdal as gd
import geopandas as gpd
from shapely.ops import transform
from shapely.geometry import Point, Polygon
## add fiona support
fiona.drvsupport.supported_drivers['kml'] = 'rw' # enable KML suppor... |
from django.shortcuts import render, render_to_response
from . import scrape1, scrape2
from . import trends
from .models import *
from django.http.response import HttpResponseRedirect
from django.http import HttpResponse
from django.db.models import Max
from .form import upFile, fixbrowse, fixscrape
from .tests import ... |
import difflib
import six
if six.PY3:
from urllib.parse import quote
elif six.PY2:
from urllib import quote
from .jsonutil import JsonTable
from .uriutil import uri_parent
from .schema import datatype_attributes
class EAttrs(object):
""" Accessor class to resource fields.
Help to retrieve the at... |
def even(x):
if even%2==0:
print 'even'
return even
x=even(5)
print 'odd'
|
"""SMACT benchmarking."""
from .utilities import timeit
from ..structure_prediction.mutation import CationMutator
class MutatorBenchmarker:
"""Benchmarking tests for CationMutator."""
@timeit
def run_tests(self):
"""Initialize Mutator and perform tests."""
self.__cm_setup()
... |
import numpy
import tensorflow as tf
from pysao.metamodels.metamodel import Metamodel
class DNNMetamodel(Metamodel):
def __init__(self, n_neural_nets=1):
Metamodel.__init__(self)
self.n_neural_nets = n_neural_nets
self.estimators = None
def _predict(self, X):
vals = []
... |
#!/usr/bin/env python3
"""
Collects temperature / gravity readings from Spindel
start standalone with sudo python3 spindel_server.py 85
test with curl -d "{\"temperature\":12,\"angle\":10,\"gravity\":121212}" ip:port
"""
import socketserver
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
import... |
from sentry_sdk import capture_exception
from healthcheck.constants import HealthStatus
from healthcheck.models import HealthCheck
def db_check():
"""
Performs a basic check on the database by performing a select query on a simple table
:return: str "OK" or "FAIL" according to successful retrieval
""... |
# dispute_href is the stored href of the dispute
dispute = balanced.Dispute.fetch(dispute_href) |
from quantum_systems import QuantumSystem, GeneralOrbitalSystem
class SpatialOrbitalSystem(QuantumSystem):
r"""Quantum system containing orbital matrix elements, i.e., we only keep
the spatial orbitals as they are degenerate in each spin direction. We have
.. math:: \psi(x, t) = \psi(\mathbf{r}, t) \sigm... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-04 14:12
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('events... |
# -*- coding: utf-8 -*-
# @Time : 2019/2/28 17:20
# @Author : shine
# @File : adjustLight.py
from PIL import ImageEnhance, ImageQt, Image, ImageStat
# enhance(factor)增强器,
# 这个方法会返回一个被加强过的image对象,
# 参数factor为一个大于0的浮点数,1表示返回原始图片
# 图片颜色增强
# enhancer = ImageEnhance.Color(img)
# 图片亮度
# enhancer = ImageEnhance.Brigh... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 02 22:51:28 2017
@author: netzer
The script takes an xml filename of a file on an ftp server containing
transaction errors as input and - depending on the type of error (error_text)
selected - it processes the failed items once more in several steps.
1) creatin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.