content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python
# dCloud Credentials
apic = {
'ip': '198.18.133.200',
'url': 'https://198.18.133.200',
'user': 'admin',
'password': 'C1sco12345'
}
saas = {
'ip': __SAAS_IP__
'token': __TOKEN___
}
| python |
import os
import subprocess
from collections import OrderedDict
from glob import glob
from itertools import product
from subprocess import Popen, PIPE
from warnings import warn
from joblib import Parallel, delayed
import pandas as pd
import shutil
# from https://github.com/BIDS-Apps/freesurfer/blob/master/run.py#L11
... | python |
"""
Train the parameters of the simple ADALINE classifier for determining if file has spacing issues.
"""
import sys
import adaline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def train_adaline(source_filename="diagnostic_results.csv", plots=False, parameter_filename="adaline_wts.npy")... | python |
from io import BytesIO
import html
from time import sleep
from typing import Optional, List
from telegram import TelegramError, Chat, Message
from telegram import Update, Bot
from telegram.error import BadRequest
from telegram import ParseMode
from telegram.ext import MessageHandler, Filters, CommandHandler
from telegr... | python |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Documents"),
"icon": "icon-star",
"items": [
{
"type": "doctype",
"name": "Assign Tables",
"description": _("Assign tables to waiters.")
},
{
"type": "doctype",
"name": "... | python |
from alembic import util
from alembic.testing import exclusions
from alembic.testing.requirements import SuiteRequirements
from alembic.util import sqla_compat
class DefaultRequirements(SuiteRequirements):
@property
def schemas(self):
"""Target database must support external schemas, and have one
... | python |
"""The sihas_canary integration."""
from __future__ import annotations
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
PLATFORMS: list[str] = [
"button",
"climate",
"cover",
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Convert a binary archive into a qiBuild package and add it to a toolchain. """
from __future__ import absolute_import
f... | python |
from . import F90
| python |
from django.http import JsonResponse
from django.views.decorators.http import require_GET
# from apps.fhir.bluebutton.models import Crosswalk
from oauth2_provider.decorators import protected_resource
from django.contrib.auth.decorators import login_required
from collections import OrderedDict
from django.conf import se... | python |
from kinorrt.mechanics.mechanics import *
from kinorrt.mechanics.stability_margin import *
#import wrenchStampingLib as ws
smsolver = StabilityMarginSolver()
h_modes = np.array([[CONTACT_MODE.STICKING, CONTACT_MODE.STICKING],
[CONTACT_MODE.SLIDING_RIGHT, CONTACT_MODE.SLIDING_RIGHT],
... | python |
#!/usr/bin/env python3
"""Show modules presence in nginx packages side-by-side in a grid."""
import subprocess
from collections import OrderedDict
def main():
"""Main Function."""
packages_all = (
'nginx-extras',
'nginx-full',
'nginx-core',
'nginx-light'
)
modules = Or... | python |
import random
from collections import namedtuple
import pytest
from patternmatching import bind, bound, group, like, match, padding, repeat
Point = namedtuple('Point', 'x y z t')
def match_basic(value):
if match(value, None):
return 'case-1'
elif match(value, True):
return 'case-2'
elif... | python |
# Generated by Django 2.2.16 on 2022-01-12 09:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0007_auto_20220112_1057'),
]
operations = [
migrations.AlterModelOptions(
name='follow',
options={'ordering': ('us... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from hijack_admin.admin import HijackUserAdminMixi... | python |
"""Parsing UsageEvent reasons.
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""... | python |
import numpy as np
def tsdf_loss(gt, est, norm='L2', mask=None):
N = 1
dim = len(gt.shape)
for d in range(0, dim):
N *= gt.shape[d]
diff = gt - est
if mask is not None:
diff = np.multiply(mask, diff)
# compute loss only where tsdf is positive
valid = (est > 0).astype(i... | python |
from .surface_plotting import plot_surf, plot_hemispheres
__all__ = ['plot_surf',
'plot_hemispheres']
| python |
import pytz
from aioch import Client
from infi.clickhouse_orm.models import ModelBase
from infi.clickhouse_orm.database import Database, Page, DatabaseException, ServerError
class AsyncDatabase(Database):
def __init__(self, db_name='default', db_host='127.0.0.1', db_port='9000',
username='defaul... | python |
from collections import OrderedDict
import requests
import logging
import urllib
import json
import operator
from django.conf import settings
from .paginator import Paginator
API_TYPES = {
"events": settings.FDA_DRUG_API_EVENT_URL,
"labels": settings.FDA_DRUG_API_LABEL_URL,
"enforcements": settings.FDA_D... | python |
# Autogenerated constants for Role Manager service
from jacdac.constants import *
from jacdac.system.constants import *
JD_SERVICE_CLASS_ROLE_MANAGER = const(0x1e4b7e66)
JD_ROLE_MANAGER_REG_AUTO_BIND = const(0x80)
JD_ROLE_MANAGER_REG_ALL_ROLES_ALLOCATED = const(0x181)
JD_ROLE_MANAGER_CMD_SET_ROLE = const(0x81)
JD_ROLE_... | python |
from django.db import models
from django.urls import reverse
from randomslugfield import RandomSlugField
# Create your models here.
class Shortener(models.Model):
slug = RandomSlugField(length=5)
link_to = models.URLField()
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
... | python |
import os
import numpy as np
import json
from io import BytesIO
import time
import argparse
import requests
from cli import DefaultArgumentParser
from client import Client
from s3client import ObjectStorageClient
from zounds.persistence import DimensionEncoder, DimensionDecoder
import zounds
from mp3encoder import enc... | python |
import setuptools
with open("README.md", "r") as file_header:
long_description = file_header.read()
setuptools.setup(
name="cppl",
version="1.0.0",
author="danie_llimas",
author_email="amedlimas97@gmail.com",
description="Simple OpenCV and Ubidots app to count people in images",
long_descr... | python |
import unittest
from disctools import AutoShardedBot as _AS
from disctools import Bot, Command
from .utils import dummy
class BotTest(unittest.TestCase):
def setUp(self):
self.bot = Bot("~")
self.ABot = _AS("~")
def test_inject(self):
class TestCMD(Command):
main = dummy... | python |
import pyttsx
from gtts import gTTS
import vlc
import time
import wave
import contextlib
class Mic:
def __init__(self):
self.engine = pyttsx.init()
def say(self, text_to_say):
self.engine(text_to_say)
self.engine.runAndWait()
def stop(self):
self.engine.stop()
def che... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 11:23:40 2018
@author: Herbert
"""
import urllib
response_1 = urllib.request.urlopen("http://www.baidu.com")
print(response_1.getcode())
cont = response_1.read()
print(len(cont))
import http.cookiejar as hc
cj = hc.CookieJar()
opener = urllib.request.build_opene... | python |
class colorFormat:
"""Display color format
`\033[display mode; font color; background color m String\033[0m`
-------------------------------------------------
Font color| background color | color description
-------------------------------------------------
30 | ... | python |
#!/usr/bin/env python3
import os
import re
LCOV_SF_RE = re.compile(r'^SF:(.*)$')
LCOV_DA_RE = re.compile(r'^DA:([0-9]+),([0-9]+)$')
# SF:/xxx/yyy/main.cpp
# DA:11,0
def uncovered_line_numbers_generator(info_filepath, source_filepath):
# NOTE: dummy filepath
filename = ''
for line in open(info_filepath):... | python |
# encoding=utf8
import jenkins_job_wrecker.modules.base
class Buildwrappers(jenkins_job_wrecker.modules.base.Base):
component = 'buildwrappers'
def gen_yml(self, yml_parent, data):
wrappers = []
for child in data:
object_name = child.tag.split('.')[-1].lower()
self.reg... | python |
import compas
from compas.geometry import Point
from compas.geometry import Vector
from compas.geometry import Frame
from compas_nurbs.bspline import BSpline
from compas_nurbs.curvature import CurveCurvature
if not compas.IPY:
from compas_nurbs.evaluators import create_curve
from compas_nurbs.evaluators impo... | python |
# -- coding:utf8 --
import argparse
#添加子命令函数
def foo(args):
print (args.x * args.y)
def bar(args):
print ('((%s))' %args.z)
#创建最上层解析器
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='subcommands',
description='valid subcommands',
... | python |
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
import msal
import requests as rq
app = FastAPI()
templates = Jinja2Templates(directory="templates")
#########################################################... | python |
#!/usr/bin/python3
# 文件名:class_complex.py
class Complex:
def __init__(self, realpart, imagpart): # 构造函数 self指向类实例本身,self不是关键字,可用其他替换(同样表示类实例本身),但只能为第一个参数
self.r = realpart
self.i = imagpart
x = Complex(3.0,-4.5)
print("%.1f+%.1fi" % (x.r,x.i))
| python |
# Generated by Django 3.1.2 on 2020-10-20 08:09
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Account',
fields=[
('identity', models.Inte... | python |
import numpy as np
from scipy.optimize import root
from scipy.sparse import spdiags, kron
from scipy.sparse.linalg import spilu, LinearOperator
from numpy import cosh, zeros_like, mgrid, zeros, eye
# parameters
nx, ny = 75, 75
hx, hy = 1./(nx-1), 1./(ny-1)
P_left, P_right = 0, 0
P_top, P_bottom = 1, 0
def get_precon... | python |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
Main training workflow
"""
from __future__ import division
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.abspath(os.path.join(PROJECT_ROOT, "..")))
import argparse
import glob
import os
import random
impo... | python |
import uuid
import boto3
from boto3_type_annotations.kinesis import Client as Kinesis
DUMMY_AWS_ENV_VARS = {
"AWS_ACCESS_KEY_ID": "anything",
"AWS_SECRET_ACCESS_KEY": "anything",
}
class DockerizedKinesis:
region: str
endpoint: str
kinesis: Kinesis
def __init__(self, endpoint: str) -> None:... | python |
import warnings
from typing import Optional, Tuple
import torch
from torch import Tensor
from .linear import NonDynamicallyQuantizableLinear
from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
from torch.nn.parameter import Parameter
from .module import Module
from .. import functional as F
class Th... | python |
import numpy as np
from larcv import larcv
from sklearn.decomposition import PCA
import time
#larcv.test_openmp()
# 0. Randomly sample points
# 1. Given set of points and subset of points, return list of segments
# 2. Given list of segments, compute local PCA
# Trivial test here
# Given points of coordinates (i, i, ... | python |
# coding=utf-8
# 2019-1-28
# quick_sort
def quick_sort(array):
less, greater = [], []
if len(array) <=1 :
return array
# choose a pivot
pivot = array.pop()
for x in array:
if x <= pivot:
less.append(x)
else:
greater.append(x)
return quick_sort(less) + [pivot] + quick_sort(greater)
if __name__ ... | python |
# ファイル名とデータ
filename = "a.bin"
data = 100
# 書き込み
with open(filename, "wb") as f:
f.write(bytearray([data]))
| python |
# coding: utf-8
import json
import os
import boto3
import pandas as pd
def main():
price_list = []
pricing = boto3.client('pricing', region_name='us-east-1')
paginator = pricing.get_paginator('get_products')
response_iterator = paginator.paginate(
ServiceCode='AmazonEC2',
Filters = [
... | python |
class StreamHandler():
def open(self, file_path):
pass
def write(self, file_path, write_object):
pass
class StreamHandler2019():
def open(self, file_path):
with open(file_path, "r") as f:
first_line = f.readline().strip()
slices_to_order, types_of_pizza = ma... | python |
import numpy as np
import os
import pyqtgraph as pg
import time
import csv
import sys
import msvcrt
import matplotlib.pyplot as plt
import threading
from numpy.fft import fft
import matplotlib.animation as anim
from scipy.signal import spectrogram, stft
# powermatrix = np.genfromtxt('power.csv', delimiter=',')
power... | python |
# -*- coding: utf-8 -*-
# Copyright 2020 Google 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... | python |
"""File parsers for Nets AvtaleGiro and OCR Giro files."""
__version__ = '1.3.0'
from netsgiro.constants import * # noqa: Reexport
from netsgiro.enums import * # noqa: Reexport
from netsgiro.objects import * # noqa: Reexport
from netsgiro import constants, enums, objects # noqa: Must come after reexport
__a... | python |
from hyde.hyde_instance import HydeInstance, HydeInstanceError
from hyde.environment import Environment
from hyde.environment import RuntimeError as EnvironmentRuntimeError
from hyde.errors import BaseError, Return
import hyde.expressions as Expressions
from hyde.globals import Globals
from hyde.hyde_callable import Hy... | python |
def arg_test(a, b=0, *vargs, **kwargs): return (a, b, vargs, kwargs.items())
| python |
import unittest
import cupy as np # !! CUPY !!
import dezero.layers as L
import dezero.functions as F
from dezero.utils import gradient_check, array_allclose, array_allclose
import chainer.functions as CF
class TestConv2d_simple(unittest.TestCase):
def test_forward1(self):
n, c, h, w = 1, 5, 15, 15
... | python |
import torch
from torch import nn
class InstaGAN(object):
"""
InstaGANの2組のGeneratorとDiscriminatorを保持するためのクラスです。
"""
def __init__(self, params):
super(InstaGAN, self).__init__()
network_params = params["network"]
input_nc = network_params["input_channels"]
... | python |
from Player import *
class GA:
population = []
bestp = []
victory = False
bestPlayer = None
def __init__(self, gen, popsize, mr, init, end, maze):
self.gen = gen
self.curgen = 0
self.popsize = popsize
self.mr = mr
self.init = init
self.end = end
... | python |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import memcache
from webnotes import conf
class MClient(memcache.Client):
"""memcache client that will automatically prefix conf.db_name"""
def n(self, key):
return (conf... | python |
#!/usr/bin/env python
# Copyright 2020-2021 Axis Communications AB.
#
# For a full list of individual contributors, please see the commit history.
#
# 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... | python |
import numpy as np
def top_k_accuracy(probs, labels, k=5):
"""Calculate the Top-k Accuarcy.
Args:
probs (np.array): [batch_size, num_class] matrix.
labels (np.array): [batch_size] matrix.
Returns:
accuracy (float): top k accuracy.
"""
correct = 0
for i in range(probs.shape[0]):
p_ = pr... | python |
#!/usr/bin/python
"""
RaceScore
"""
import io
from setuptools import setup
with io.open('requirements-testing.txt') as fd:
test_reqs = fd.readlines()
tests_require = [line for line in test_reqs if not line.startswith('#')]
with io.open('README.rst') as fd:
long_desc = fd.read()
setup(
name = 'race-sc... | python |
import json
import time
import numpy as np
import os
import sys
from PyQt4 import QtGui, QtCore, Qt
from PyQt4.QtCore import pyqtSignal
from twisted.internet.defer import inlineCallbacks
sys.path.append('./forms/')
from input_forms import InputForms
from output_forms import OutputForms
from gui_defaults... | python |
from pprint import pprint
import warnings
import pygame as pg
try:
from _internal import COLOURS
except ImportError:
from ._internal import COLOURS
LARGEICONSIZE = 10
warnings.warn("This Inventory module is DEPRECATED. please use the better one", DeprecationWarning)
class InventoryHandler:
def __init_... | python |
import unittest
from torch.utils.data.dataloader import DataLoader
from avalanche.benchmarks import Experience, SplitCIFAR100, SplitCIFAR110
from tests.unit_tests_utils import load_experience_train_eval
CIFAR10_DOWNLOADS = 0
CIFAR10_DOWNLOAD_METHOD = None
CIFAR100_DOWNLOADS = 0
CIFAR100_DOWNLOAD_METHOD = None
clas... | python |
"""
Property of UAS C2C2 Senior Design Team 2019
Team Members: Mark Hermreck, Joseph Lisac, Khaled Alshammari, Khaled Alharbi
Questions about this code can be directed toward Mark Hermreck at markhermreck@gmail.com
"""
from dronekit import connect, LocationGlobal, LocationGlobalRelative, Vehicle, VehicleMode, Co... | python |
from itertools import count
from typing import Optional, Tuple, Union
import numpy as np
from matplotlib import patches
from ..lattice import Lattice
from .base import BaseElement
from .utils import straight_element
class Quadrupole(BaseElement):
"""Quadrupole element.
Args:
k: Strength in meters^-... | python |
# -*- coding: utf-8 -*-
__author__ = "苦叶子"
"""
公众号: 开源优测
Email: lymking@foxmail.com
"""
from datetime import datetime
from flask import url_for
from flask_restful import Resource, reqparse
from flask_login import current_user
from sqlalchemy import and_
from ..models import AutoProduct, AutoProject, AutoSuite, A... | python |
from decorators import do_twice
@do_twice
def say_whee():
print("Whee!")
say_whee() | python |
# -*- coding: utf-8 -*-
import os
import json
from tqdm import tqdm
import numpy as np
from pydicom.filereader import dcmread
import pylidc as pl
from pylidc.utils import consensus
from pylidc.Annotation import feature_names
OUTPUT_PATH = '/localdata/LIDC-IDRI_labels'
os.makedirs(OUTPUT_PATH, exist_ok=True)
DATA_PATH... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pygame raycaster
#
import math
import pygame
from pygame.locals import *
m = [ [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,1,0,... | python |
class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
for row in matrix:
for col in xrange(1, len(row)):
row[col] += row[col-1]
self.matrix = matrix
def... | python |
from typing import Optional, Tuple, Callable, Union, List
import logging
import numpy as np
import torch
from gpytorch import ExactMarginalLogLikelihood
from gpytorch.constraints import GreaterThan
from gpytorch.likelihoods import GaussianLikelihood
from torch import Tensor
from torch.distributions import Normal
from ... | python |
import termscreen
from colorama import init, deinit # Fore, Back, Style
import time
import datetime
import math
import prime_numbers
init()
termscreen.cls()
print('{:*^80}'.format(' \x1b[33;1mПроект Эйлера\x1b[0m '))
print('{:^80}'.format('\x1b[32mhttp://projecteuler.net/archives\x1b[0m'))
# Task 003
print('''
За... | python |
from osm_observer.extensions import db
from geoalchemy2.types import Geometry
from sqlalchemy.dialects.postgresql import HSTORE
__all__ = [
'changesets', 'nodes', 'ways', 'relations', 'comments', 'nds', 'members',
'current_status'
]
changesets = db.Table(
'changesets', db.MetaData(),
db.Column('id', d... | python |
# MQTT Logger for MicroPython by Thorsten von Eicken (c) 2020
#
# Requires mqtt_async for asyncio-based MQTT.
#!!!!!!!!!! This code was pulled out of mqrepl and is not finished. It's probably better to
#!!!!!!!!!! hook Logging and make sure all errors and exceptions result in calls to Logging.
#!!!!!!!!!! This way ver... | python |
#
# Licensed to Dagda under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Dagda licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance... | python |
import six
from .helper import TypeFactory
from collections import defaultdict
from .errors import ValidationError
# Validators
class Validator(object):
"""Callable base class to validate a given value"""
def __call__(self, value):
self.validate(value)
class StringValidator(Validator):
"""Valid... | python |
import copy
import os
from gxformat2.converter import python_to_workflow, STEP_TYPES, yaml_to_workflow
from gxformat2.export import from_galaxy_native
from gxformat2.interface import ImporterGalaxyInterface
TEST_PATH = os.path.abspath(os.path.dirname(__file__))
TEST_INTEROP_EXAMPLES = os.environ.get("GXFORMAT2_INTERO... | python |
from scipy import ndimage as ndi
import numpy as np
import scipy
from bokeh.io import curdoc
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput
from bokeh.layouts import row, widgetbox
from bokeh.layouts import gridplot
from bokeh.client ... | python |
from py_crypto_hd_wallet.monero.hd_wallet_monero_enum import (
HdWalletMoneroWordsNum, HdWalletMoneroLanguages, HdWalletMoneroCoins,
HdWalletMoneroDataTypes, HdWalletMoneroKeyTypes
)
from py_crypto_hd_wallet.monero.hd_wallet_monero_factory import HdWalletMoneroFactory
from py_crypto_hd_wallet.monero.hd_wallet_m... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayMarketingCampaignPrizeAmountQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayMarketingCampaignPrizeAmountQueryResponse, self).__init__()
... | python |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import sys, timeit
from typing import List
def part01(input: List[int]):
result = 0
last_measure = 0
for measure in input:
if measure > last_measure:
result += 1
last_measure = measure
return result - 1 # The first measureme... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
import numpy as np
from ..gloo import set_state, Texture2D
from ..color import get_colormap
from .shaders import ModularProgram, Function, Fu... | python |
import cv2
import torch
from src.dcgan_cppn.models import Generator
from utils import get_coordinates, interpolate
class Tester(object):
def __init__(self, config):
self.config = config
self.device = config.device
self.max_itr = config.max_itr
self.batch_size = con... | python |
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from dash.dependencies import Input, Output
import pandas as pd
import numpy as np
from app import app
# Get data
filename = 'assets/rtfMRI_methods_review_included_studies_procsteps.txt'
df_studies = pd.rea... | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 21 12:28:19 2018
@author: m.goetz@dkfz-heidelberg.de
"""
import xml.etree.ElementTree as ET
def create_xml_tree(filepath):
"""
Method to ignore the namespaces if ElementTree is used.
Necessary becauseElementTree, by default, extend
Tag names by the name ... | python |
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QGraphicsView
from aemoverdata import AEMOverData
from aemoverview import AEMOverview
class Menu(QMainWindow):
de... | python |
# Generated by Django 3.1.3 on 2020-11-29 21:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('awwardsapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Projects',
... | python |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, HttpResponseRedirect
from session_csrf import anonymous_csrf
from ..models import WhitelistIP
from ..forms import WhitelistIPForm
from B... | python |
"""
Quick Sort
"""
import unittest
from typing import TypeVar
T = TypeVar('T')
def quick_sort(array: list[T], lo: int, hi: int):
if lo < hi:
separator = partition(array, lo, hi)
quick_sort(array, lo, separator - 1)
quick_sort(array, separator + 1, hi)
def partition(array: list[T], lo: i... | python |
import Preprocessor
appender = Preprocessor.TextAlteration(['./testCorpus'])
appender.appendText("Viola! Again!", 3) | python |
"""
Support for Hue components.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/hue/
"""
import json
import logging
from homeassistant.const import (CONF_FILENAME)
_LOGGER = logging.getLogger(__name__)
PHUE_CONFIG_FILE = 'phue.conf'
DOMAIN = 'hue'
de... | python |
import scipy.misc
import carla
from srunner.scenariomanager.carla_data_provider import CarlaDataProvider
from srunner.challenge.autoagents.autonomous_agent import AutonomousAgent, Track
try:
import numpy as np
except ImportError:
raise RuntimeError('cannot import numpy, make sure numpy package is installed')
#... | python |
# Copyright 2019 Alibaba Cloud 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 la... | python |
#!/usr/bin/env python
import os
import queue
import socket
import time
import threading
from threading import Thread
import copy
import json
from datetime import datetime
import stomp
import tools
TOPIC = "/topic/perfsonar.summary.meta"
INDEX_PREFIX = 'ps_meta-'
class MyListener(object):
def on_message(self, ... | python |
# Module is an abstraction of orders, which is the returned data structure when requesting order
# information from the API.
# Acts as a superclass to different order types. It contains the interface data all orders share.
class Order(object):
def __init__(self, json):
self.session = ""
self.duration = ""
self... | python |
from random import randint
itens = ('Pedra', 'Papel', 'Tesoura')
computador = randint(0, 2) #sorteio aleatório do número
print('Computador pode escolher: {}'.format(itens))
print('Escolha do computador númerica: {}'.format(computador)) #computador dá um número
print('Escolha do computador: {}'.format(itens[computador]... | python |
# Author: Kelvin Lai <kelvin@firststreet.org>
# Copyright: This module is owned by First Street Foundation
# Internal Imports
from firststreet.models.api import Api
class EnvironmentalPrecipitation(Api):
"""Creates an Environmental Precipitation object given a response
Args:
response (JSON): A JSON ... | python |
import json
import re
def get_tracking_internal():
try:
with open('tracking_records.json', 'r') as f:
return json.loads(f.read())
except BaseException:
with open('tracking_records.json', 'w') as f:
f.write(json.dumps({}))
return {}
def set_tracking_internal(na... | python |
# author:爱在7元钱
# version:1.0
# date:2021年03月15日
import requests
import json
url = 'http://api.tianapi.com/txapi/worldtime/index'
def worldtime():
currency_str_value = input("请输入要查询的城市(例如:芝加哥):")
city1 = currency_str_value
body = {
"key": "" , #需要自己去申请
"city": city1}
headers = {'co... | python |
def removeDup(x):
y = []
for i in range(len(x)):
if (x[i] not in y):
y.append(x[i])
return y
class CSVPoolPlugin:
def input(self, inputfile):
self.inputfile = inputfile
filestuff = open(self.inputfile, 'r')
self.counts = dict()
# Read once, just to get row and column ... | python |
from rest_framework import serializers
from .models import List, Item
class ListSerializer(serializers.ModelSerializer):
class Meta:
model = List
fields = ('id', 'title', 'url')
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'List',... | python |
# -*- encoding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 6
_modified_time = 1415293118.999516
_template_filename='templates/webapps/galaxy/dataset/tabular_chunked.mako'
_template_uri='/dataset/tabular_chunked.mako... | python |
import matplotlib.pyplot as plt
file = open("1.txt","r")
string = file.read()
file.close()
file = open("3.txt","w+")
count = 0
list1 = string.split()
freq = [list1.count(c) for c in list1]
for i in list1:
count = count + 1
file.write("Total words are " + str(count))
per = []
for i in freq:
per.append((i/count)*... | python |
# The MIT License (MIT)
#
# Copyright (c) 2017 Radomir Dopieralski and Adafruit Industries
#
# 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 ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.