content stringlengths 5 1.05M |
|---|
import platform
from ursina import *
from random import randint
from ursina.prefabs.first_person_controller import FirstPersonController
from perlin_noise import PerlinNoise
from ursina.shaders import basic_lighting_shader
from ursina.shaders import lit_with_shadows_shader
osv = (platform.release())
winos = (platform.... |
"""
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Constraints:
1 <= nums.length <= 10
-10 <=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import json
import os
import nibabel as nib
import numpy as np
from scilpy.io.streamlines import load_tractogram_with_reference
from scilpy.io.utils import (add_json_args,
add_overwrite_arg,
... |
import requests
url = "https://freegeoip.app/json/"
headers = {
'accept': "application/json",
'content-type': "application/json"
}
response = requests.request("GET", url, headers=headers)
print(response.text) |
import os
TIMEFRAMES = [
"2017-06-12_2017-07-09_organic",
"2017-07-10_2017-08-06_organic",
"2017-08-07_2017-09-03_organic",
"2017-12-03_2017-12-30_organic",
"2018-01-01_2018-01-28_organic",
"2018-01-29_2018-02-25_organic",
"2018-02-26_2018-03-25_organic"
]
# creates the structure of folder... |
# Copyright 2017 The TensorFlow 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 applica... |
# encoding: UTF-8
"""
展示如何执行策略回测。
"""
from __future__ import division
import os
from vnpy.trader.app.ctaStrategy.ctaBacktesting import BacktestingEngine, MINUTE_DB_NAME,DAILY_DB_NAME
import vnpy.trader.app.ctaStrategy.strategy.strategy_Volatility_RB as VRB
#----------------------------------------------------------... |
# Import libnacl libs
import libnacl.secret
# Import python libs
import unittest
class TestSecret(unittest.TestCase):
'''
'''
def test_secret(self):
msg = b'But then of course African swallows are not migratory.'
box = libnacl.secret.SecretBox()
ctxt = box.encrypt(msg)
self.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Converts CBERS-4 scene metadata (xml) to stac item"""
import json
import os
import re
import statistics
import sys
import xml.etree.ElementTree as ET
from collections import OrderedDict
import utm
from cbers2stac.layers.common.utils import (
BASE_CAMERA,
CBERS... |
import argparse
import vobject
import os
from math import ceil
import datetime
def parse_files(files):
birthday_dict = dict()
for file in files:
try:
with open(file) as f:
vcard = vobject.readOne(''.join(f.readlines()))
except:
print(f'Error reading {fil... |
n = int(input())
print n
cedulas = dict()
cedula = [100, 50, 20, 10, 5, 2, 1]
cont = 0
for x in cedula:
while x <= n:
n = n - x
cont = cont + 1
cedulas[x] = cont
cont = 0
print "%d nota(s) de R$ %d,00" %( cedulas[100], 100)
print "%d nota(s) de R$ %d,00" %( cedulas[50], 50)
print "%d nota... |
# coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1beta1D... |
# -*- coding: utf-8 -*-
"""Logging extension with tqdm
Copyright (c) 2017 Takaaki Hori (thori@merl.com)
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
"""
import sys
import logging
from tqdm import tqdm
# tqdm logging handler
class TqdmLoggingHandler(loggi... |
import base64
import jinja2
import json
import yaml
from synchronizers.new_base.modelaccessor import *
from synchronizers.new_base.policy import Policy
from xosconfig import Config
from multistructlog import create_logger
log = create_logger(Config().get('logging'))
class Free5GCServicePolicy(Policy):
model_nam... |
# Copyright (c) 2018 Ben Maddison. All rights reserved.
#
# The contents of this file are licensed under the MIT License
# (the "License"); you may not use this file except in compliance with the
# License.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distri... |
# Copyright(c) 2007-2009 by Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of PyCha.
#
# PyCha is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License,... |
"""Utility Functions."""
from .argutils import *
from .arrayutils import *
from .randomutils import *
# Public classes and functions. Order is reflected in documentation.
__all__ = [
"as_colvec",
"atleast_1d",
"as_numpy_scalar",
"as_random_state",
"as_shape",
"derive_random_seed",
]
|
response = natural_language_understanding.analyze(
url="https://en.wikipedia.org/wiki/SpaceX",
features=Features(
categories=CategoriesOptions(limit=4),
concepts=ConceptsOptions(limit=10)),
clean=False
).get_result()
|
import sys
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate, login, views as auth_views
from django.http.response import HttpResponseNotFound
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.decorators import method_deco... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
BART Module.
"""
import torch
import torch.nn.functional as F
from parlai.agents.transformer.modules import Transform... |
# Package
import torch
import torch.nn as nn
import torch.nn.functional as F
# Local files
from model.hyperparameters import *
from model.voc import SOS_token
class GreedySearchDecoderScripted(torch.jit.ScriptModule):
def __init__(self, encoder, decoder, decoder_n_layers):
super(GreedySearchDecoderScripted, self).... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/30 8:38
# @Author : 一叶知秋
# @File : detectCycle.py
# @Software: PyCharm
"""
142. 环形链表 II
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
示例 1:
输入:head = [3,2,0,-4],... |
{
'variables': {
'LIN_ALG_BLAS%': 'NBLAS',
'LIN_ALG_LAPACKE%': 'NLAPACKE',
'LIN_ALG_EIGEN%': 'NEIGEN',
'LIN_ALG_INCLUDE%': 'src/glib/base/',
'LIN_EIGEN_INCLUDE%': 'src/third_party/eigen/',
#full path to lapack or openblas libraries
'LIN_ALG_LIB%': '',
... |
print('======= DESAFIO 04 =======')
a = input('Digite qualquer coisa: ')
print('Seu tipo primitivo é {}'.format(type(a)))
print('Número? {}'.format(a.isnumeric()))
print('Letra? {}'.format(a.isalpha()))
print('Alfanumérico? {}'.format(a.isalnum()))
print('MAIÚSCULO? {}'.format(a.isupper()))
print('minúsculo? {}'.format... |
'''multivariate normal probabilities and cumulative distribution function
a wrapper for scipy.stats.kde.mvndst
SUBROUTINE MVNDST( N, LOWER, UPPER, INFIN, CORREL, MAXPTS,
& ABSEPS, RELEPS, ERROR, VALUE, INFORM )
*
* A subroutine for computing multivariate normal probabilities.
... |
"""
This module is based on: https://zapier.com/engineering/profiling-python-boss/
See also:
https://www.pythoncentral.io/measure-time-in-python-time-time-vs-time-clock/
"""
from __future__ import print_function
import inspect
import cProfile
from functools import wraps
from timeit import default_timer as timer
impor... |
#
# This file is a stripped-down version of interpolate.py from
# the "scipy" package. It only contains intrp1d and all spline
# interpolation code has been removed.
#
#
#
# The scipy package comes with this 2-clause BSD-style license:
#
# Copyright (c) 2001, 2002 Enthought, Inc.
# All rights reserved.
#
# Copyright... |
# -*- coding: UTF-8 -*-
import re
from . import utils
from .cn2an import Cn2An
from .an2cn import An2Cn
class Transform(object):
def __init__(self):
self.conf = utils.get_default_conf()
self.all_num = u"零一二三四五六七八九"
self.all_unit = u"".join(list(self.conf[u"unit_cn2an"].keys()))
se... |
# Zbór zadań B - zadanie 2
# Napisz program wyświetlający liczby podzielne przez 7 i nie będące wielokrotnością 5 z przedziału
# 2000 do 3000. Liczby te powinny być wyświetlone w jednej linii i oddzielone przecinkami
# autor : Rafał D.
import random
print('Program wyświetla liczby podzielne przez 7 i nie będące wie... |
# Author: Pierre Ablin <pierreablin@gmail.com>
# License: MIT
import autograd.numpy as np
from numpy.testing import assert_allclose
from autoptim import minimize
def test_rosenbrock():
def rosenbrock(x):
return (1 - x[0]) ** 2 + 100 * (x[1] - x[0] ** 2) ** 2
x0 = np.zeros(2)
x_min, res = minim... |
from rest_framework import serializers
from api.models import User, Group, Event
class UserModelSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id','email','password']
class GroupModelSerializer(serializers.ModelSerializer):
class Meta:
model = Group
... |
import os
import shutil
import pickle
import pytest
import tempfile
from sacred import Experiment
from mlflow_observer import MlflowObserver
ex = Experiment('MyExperiment')
METRIC_NAME = 'accuracy'
ARTIFACT_NAME = 'model.pkl'
ARTIFACTS_SUBDIR = 'my_models'
ARTIFACT_NAME_FMT = 'model_{}.pkl'
@ex.config
def cfg():
... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# California Institute of Technology
# (C) 2006 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
# Make sure that any of this properties can be overridden using env.properties
import os
from datetime import datetime
now = datetime.now().strftime("%Y%m%d%H%M%S")
# GA Setup
POPSIZE = int(os.getenv('DJ_POPSIZE', '800'))
NGEN = int(os.getenv('DJ_NGEN', '500000'))
RUNTIME = int(os.geten... |
from inspect import cleandoc
from python2latex.tex_base import *
from python2latex.tex_environment import *
class TestTexEnvironment:
def test_add_text(self):
env = TexEnvironment('test')
env.add_text(r"This is raw \LaTeX")
assert env.body == [r"This is raw \LaTeX"]
def test_append(s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 18:29:26 2015
@author: ddboline
"""
from __future__ import (absolute_import, division, print_function, unicode_literals)
import sys
from setuptools import setup
console_scripts_ = (('sync-app',
'sync_app.sync_utils:sync_arg_parse'... |
from lazydoro.pi.lazy_oo import Buzzer
import RPi.GPIO as GPIO
from time import sleep
class PwmBuzzer(Buzzer):
def __init__(self, pin=6):
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
self.buzzer = GPIO.PWM(pin, 400)
def on(self, status):
self.beep(1, 400)
def beep(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-06-19 22:13
# @Author : liupan
# @Site :
# @File : demo1.py
# @Software: PyCharm
from scrapy import Selector
body= '<html><head><title>Hello World</title></head><body></body> </ html>'
selector = Selector(text=body)
title = selector.xpath('//title... |
import cherrypy
import json
import os
import sqlite3
import requests
from datetime import datetime
from sqlite3 import Error
from jinja2 import Environment, PackageLoader, select_autoescape
from documents.doc_gen import *
PEOPLE_SEPARATOR = ";"
# Event Info
EVENT_MODALITIES = ['Football', 'Volleyball', '... |
import progressivis
print('progressivis.__version__: %s' % progressivis.__version__)
|
from datetime import datetime
from django.core.management.base import BaseCommand
from onadata.apps.fieldsight.models import TimeZone, Project, ProjectGeoJSON
class Command(BaseCommand):
help = 'Create site data Geojson file backup for all projects'
def handle(self, *args, **options):
projects ... |
'''Trace defines the extraction and sky subtraction regions for an Aperture'''
from .imports import *
from craftroom.cmaps import one2another
class Trace(Talker):
'''trace object defines the extraction trace and sky region'''
def __init__(self, aperture):
Talker.__init__(self)
self.aperture = ... |
# 蓝图模块化注册文件
# 导入Blueprint
from flask import Blueprint
# 初始化"web"蓝图
web = Blueprint('Web',__name__,template_folder="templates")
# 导入视图
from . import index
from . import errors
from . import login
from . import admin |
import gym
from gym.envs.registration import register
def make(
domain_name,
task_name,
seed=1,
visualize_reward=True,
from_pixels=False,
height=84,
width=84,
camera_id=0,
frame_skip=1,
episode_length=1000,
environment_kwargs=None,
time_limit=None,
channels_first=Tr... |
"""Model config."""
import copy
import ml_collections
def global_config(length: int) -> ml_collections.ConfigDict:
"""Get the global config."""
if str(length) not in GLOBAL_CONFIG:
raise ValueError(f'Invalid padding sequence length {length}.')
cfg = copy.deepcopy(GLOBAL_CONFIG[str(length)... |
# -*- coding: utf-8 -*-
# @Author: jpch89
# @Email: jpch89@outlook.com
# @Date: 2018-07-12 16:42:21
# @Last Modified by: jpch89
# @Last Modified time: 2018-07-12 16:53:35
def break_words(stuff):
"""This funciton will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words... |
#!/usr/bin/env python
"""
update_dreqs_0314.py
Reset the data request on MPI HR highresSST-present data requests
"""
import argparse
import logging.config
import os
import sys
import django
django.setup()
from pdata_app.models import ClimateModel, DataRequest
__version__ = '0.1.0b1'
DEFAULT_LOG_LEVEL = logging.WARN... |
import socket
import json
# from Pi_Interface.Appliance import Appliance
# import RPi.GPIO as GPIO
# from Pi_Interface \
import tokens,routehandler
# GPIO.cleanup()
# GPIO.setmode(GPIO.BCM)
# GPIO.setup(6, GPIO.OUT)
# GPIO.setup(4, GPIO.OUT)
# GPIO.setup(27, GPIO.OUT)
# GPIO.setup(22, GPIO.OUT)
# fan = Appliance("fan... |
###################################################################
# Purpose: execute queries against multiple databases #
# Version: 0.0.2 #
# Author: phuturama #
# Requires: Python 3.x, pykeepass ... |
import unittest
import pgshapely
import binascii
class TestPolys(unittest.TestCase):
database = "test"
user = "test"
password = "test"
def setUp(self):
conn = pgshapely.connect(database=self.database, user=self.user, password=self.password)
cursor = conn.cursor()
... |
class InvalidDatalakeTimeInterval(Exception):
pass
class BaseTrainingException(Exception):
pass
class InvalidConfigException(BaseTrainingException):
pass
class ConfigFileNotFoundError(BaseTrainingException):
pass
class ResourceNotFound(Exception):
pass
|
import speech_recognition as sr
def main():
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
print("Please say something")
audio = r.listen(source)
print("Please wait .... ")
try:
print("You said \n"... |
from .fasta import FastaRenderer
|
"""requires smidump"""
import os
import re
import yaml
import xmltodict
import subprocess
from automon.integrations.slack.slack_logger import AsyncSlackLogging
from automon.integrations.slack.slack_formatting import Chat
from automon.log import Logging
log = Logging(__name__, level=Logging.INFO)
slacklog = AsyncSlac... |
import os
import pickle
import numpy as np
import matplotlib.pyplot as pylab
import operator
from multiprocessing import Pool, Manager
import glob
from collections import Counter,defaultdict
from scipy.stats import norm
import logging
def bayes_selection_constnat_optimization(self):
removal_ratio=0.9
... |
# Copyright (C) 2018 SCARV project <info@scarv.org>
#
# Use of this source code is restricted per the MIT license, a copy of which
# can be found at https://opensource.org/licenses/MIT (or should be included
# as LICENSE.txt within the associated archive or repository).
from sca3s import backend as sca3s_be
from ... |
"""Main module."""
BASE_HOST = "https://www.upwork.com"
GQL_EPOINT = "https://api.upwork.com/graphql"
DEFAULT_EPOINT = "api"
|
#!/usr/bin/env python
usage = """Usage: embed x y z
Shows a 3d rendering of the MPI rank embedding used by
S3D for the given dimensions.
Parameters:
x Number of processing elements in x direction
y Number of processing elements in y direction
z Number of processing elements in z direction
"""
import ... |
# ----------------------------------------------------------------------
# Copyright (c) Microsoft Corporation.
# All rights reserved.
# ----------------------------------------------------------------------
import asyncio
import os
import sys
from typing import cast
sys.path.append('../CDM.ObjectModel.Python')
fro... |
# Standard library imports
import logging
# Third party imports
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.core.excep... |
class UserTarget:
@staticmethod
def get_response():
return "Response by UserTarget"
|
"""
Copyright 2019 Islam Elnabarawy
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 ... |
#/usr/bin/env python3
import sqlite3
import dbf
import yaml
import os
import datetime
ROOT_PATH = os.path.dirname(__file__)
CONFIG_FILE = yaml.full_load(open(os.path.join(ROOT_PATH, 'config.yaml')).read())
TRANSLATE_GAMA = {
'fruits': 'FRUCTE',
'vegetables': 'LEGUME'
}
class Database(object):
def __i... |
from django.db import models
from django.contrib.auth.models import AbstractUser, Group, Permission, GroupManager
from django_oso.models import AuthorizedModel
## MODELS ##
class User(AbstractUser):
"""
System users as Case Workers, Supervisors, Auditors, etc.
"""
# basic info
email = models.Ch... |
from OFTF import OFTF
import numpy
outcomes = list()
for i in range(1000):
game = OFTF()
game.play()
outcomes.append(game.results)
print('# of games played: {}'.format(len(outcomes)))
print('Result \t\t# times rolled')
for i in range(0, 25):
print('{}: \t\t{}'.format(i, outcomes.count(i)))
print('Ave... |
import numpy as np
from utils import *
from images import *
np.random.seed(2)
class Imager(object):
def __init__(self, transform_sizes=416, class_name_file='./data/coco.names'):
if type(transform_sizes) is int:
self.transform_sizes = (transform_sizes, transform_sizes)
else:
... |
import re
import sqlalchemy.types as satypes
import sqlalchemy.schema as saschema
import sqlalchemy.sql as sasql
import sqlalchemy.sql.expression as saexp
import sqlalchemy.sql.functions as safunc
import sqlalchemy.util as sautil
import sqlalchemy.dialects.postgresql as pgdialect
from sqlalchemy.exc import SQLAlchemyEr... |
import upip, os,sys
#make sure there is a folder to store the module package into
try: os.mkdir(sys.path[1])
except: pass
#This should work but fails on LoBo
upip.install("micropython-pystone_lowmem")
#Debuggin on , but no additional info
upip.debug = True
upip.install("micropython-pystone_lowmem")
#this function... |
from controller.invoker.invoker_cmd_base import BaseMirControllerInvoker
from controller.utils import utils, checker, labels
from id_definition.error_codes import CTLResponseCode
from proto import backend_pb2
class LabelAddInvoker(BaseMirControllerInvoker):
def pre_invoke(self) -> backend_pb2.GeneralResp:
... |
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
import re
from django.http import HttpResponseRedirect
# Create your views here.
def account(request):
return render(request, 'accounts/loginform.html') # render login form
def ... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_sele... |
"""
The Capture module.
This contains classes for capturing information about
gradients on sparse-dense transition points. In particular,
"""
from typing import Callable, Optional
import torch
import torch_sparse
from torch import nn
class StochasticSubSampler(nn.Module):
"""
A class designed to capture ... |
'''
Created on Nov 13, 2015
@author: Vlad
'''
class RentalDTO:
def __init__(self, id_client, id_car, price):
'''
Rental class for the id_s of the clients
:param id_client:
:param id_car:
:param price:
:return:
'''
self.__id_client = id_client
self.__id_car = id_car
self.__price = price
@... |
# Copyright (c) 2018 PaddlePaddle 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 app... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'grid_controls_ui.ui'
##
## Created by: Qt User Interface Compiler version 5.15.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
#########... |
#!/usr/bin/env python3
import unittest
def mean(A):
return sum(A)/len(A)
def median(A):
lenA = len(A)
half = int(lenA/2)
if lenA%2==0:
return sum(A[half-1:half+1])/2
else:
return A[half]
def mode(A):
from statistics import collections
c = collections.Counter(A)
return... |
import re
import os
regex_audio = re.compile(r'')
def get_sanitized_filename(file_name,
file_extn='.mp4',
token_joiner='_',
intra_splitter='-',
limit=5):
# print(f'input name is {file_name}')
try:
... |
from django.apps import AppConfig
class OrganizationsConfig(AppConfig):
name = "grandchallenge.organizations"
def ready(self):
# noinspection PyUnresolvedReferences
import grandchallenge.organizations.signals # noqa: F401
|
########################################
########################################
####### Author : Abhinandan Dubey (alivcor)
####### Stony Brook University
# perfect essays : 37, 118, 147,
import csv
import sys
from nltk.corpus import stopwords
import numpy
from nltk import word_tokenize
from nltk import pos_tag
impo... |
#!/usr/bin/env python
# $Id$
"""many solutions"""
import puzzler
from puzzler.puzzles.polyhexes12345 import OneSidedPolyhexes12345_31x7
puzzler.run(OneSidedPolyhexes12345_31x7)
|
# -*- coding: utf-8 -*-
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from ShopData.models import *
from users.models import UserData
from datetime import *
import myUtil
# 상점가격 데이터... |
from __future__ import unicode_literals
from django import forms
from django.db.models.functions import Lower
from django.utils.translation import ugettext_lazy as _
from tracpro.charts import filters
from tracpro.contacts.models import Contact
from tracpro.polls.models import Poll, Question
from .models import Base... |
from os import path
import nibabel as nib
import numpy as np
###################################################################################
# nifti files
###################################################################################
def openNifti(fname,type=None):
'''
:param fname: file path to open... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2021) Hewlett Packard Enterprise Development LP
#
# 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/L... |
import datetime
from django.db import models, IntegrityError
from django.utils import timezone
from rest_framework.exceptions import ValidationError
class Poll(models.Model):
title = models.CharField(max_length=100)
user = models.ForeignKey("users.User", related_name="polls", on_delete=models.SET_NULL, null=... |
from django import forms
from django.conf import settings
from crits.campaigns.campaign import Campaign
from crits.core.forms import (
add_bucketlist_to_form,
add_ticket_to_form,
SourceInForm)
from crits.core import form_consts
from crits.core.widgets import CalWidget
from crits.core.handlers import get_ite... |
""" Unit tests for the lists app views """
from django.test import TestCase
from django.utils.html import escape
from lists.models import Item, List
from lists.forms import ItemForm
class HomePageTest(TestCase):
""" Unit Tests for the home_page view
"""
def test_home_page_is_todo_home(self):
"""... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
import traceback
import collections
import hashlib
import base64
import uuid
import yaml
import copy
import json
import requests
from pprint import pprint
from .handle... |
import adv
import wep.wand
from core.log import *
from adv.maribelle import *
from adv.lily import *
from adv.mikoto import *
from adv.adv_test import *
conf = {}
conf.update( {
"think_latency" : {'x_cancel':0.05, 'sp':0.05 , 'default':0.05}
} )
conf['acl'] = """
`s1,seq=5 and cancel
`s2,seq=5 an... |
# -*- coding: utf-8 -*-
import copy
import json
import os.path
import sys
import requests
from suds.client import Client
from suds.sax.text import Raw
ver = '1.7.0'
soapAppend = 'services/'
restAppend = 'api/'
tenant = 't/1.1/'
soapAthorizeAppend = 'Authorize'
end_points_base = {
"test": "https://developers.todo... |
# -*- coding: utf-8 -*-
from django.core.management import BaseCommand
import raw.models
from raw.models import ParsedCommittee, ParsedCommitteeMembership, ParsedCouncilMeeting, ParsedMembership, ParsedPerson, ParsedPerson, ParsedQuestion
import logging
logging.disable(logging.CRITICAL)
class Command(BaseCommand):
... |
#!/usr/bin/env python
import numpy
import cv2
img = cv2.imread("./image/image.jpg")
cv2.imshow("color", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
# The configuration files of eps values in calculation
default_eps = \
{
"OPF": 1,
"ED": 1, # The generation status, >0 means avalible, otherwise, unavaliable
"UC": 2,
"Penalty_bic":0.01, # The penalty factor for bi-directional power flow
"Penalty_uc":0.1,
"Penalty_e... |
# Copyright 2017 Google Inc. 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 a... |
import face_recognition
from PIL import Image as img , ImageDraw
Reg_Photo = face_recognition.load_image_file('python_files\images\RegisterPhoto.png')
Reg_Photo_encoding = face_recognition.face_encodings(Reg_Photo)[0]
Known_face_encoding = [
Reg_Photo_encoding
]
known_face_names = [
"Name of user"
]
Login_Pho... |
第一题:
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
#str = input()
#print(str)
class Solution(object):
def findMedium(l):
length = len(l)
l.sort()
# 如果为奇数,输出中间的值
if length % 2 != 0:
print(l[length//2])
# 如果为偶数,中心两位均值
... |
import sys
if __name__ == "__main__":
fromCrc8 = {}
toCrc8 = {}
for l in sys.stdin.readlines():
if not l:
break
fromRc = l[2] == '>'
# [25:27] crc8
# vv
# RC> len=0014 == 55 0e 04 66
... |
"""
Created on Jul 17, 2017
@author: andrew
"""
import asyncio
import datetime
import time
from collections import Counter
from discord.ext import commands
from api.avrae.utils import config
GUILD_RDB_KEY = "stats.cluster_guilds"
class Stats(commands.Cog):
"""Statistics and analytics about bot usage."""
... |
"""
plot
====
Provides functions, arrays and specifiers for plotting.
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.