content stringlengths 5 1.05M |
|---|
import Tkinter
import time
openTime = [0]
window = Tkinter.Tk()
# sets up the main window elements
window.attributes('-fullscreen', True)
window.attributes("-topmost", True)
window.title('BECOME SUPERMAN')
window.configure(background='red')
#this makes the exercise label
Tkinter.Label(window, text="EXERCISE!!!", f... |
import configparser
from typing import Tuple, List
import io
from UM.VersionUpgrade import VersionUpgrade
from UM.Util import parseBool # To parse whether the Alternate Skin Rotations function is activated.
_renamed_container_id_map = {
"ultimaker2_0.25": "ultimaker2_olsson_0.25",
"ultimaker2_0.4": "ultimaker... |
from django.contrib.auth.models import User
from django.test import TestCase
from . import models
from .templatetags import news_tags
class BasicTests(TestCase):
def setUp(self):
self.user = User.objects.create_user('test', 'test@test.com', 'test')
def testTwitterMessage(self):
item = models... |
class Solution(object):
def twoCitySchedCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
heap = []
for x, y in costs:
dist = abs(x - y)
heapq.heappush(heap, (-dist, x, y))
result = 0
count0 = 0
... |
import fractions
a, b = map(int, input().split())
def lcm(x, y):
return (x * y) // fractions.gcd(x, y)
print(lcm(a, b))
|
### Generates resources/territory_type.js
# (1) Download https://github.com/ufx/SaintCoinach/releases/latest
# (2) SaintCoinach.Cmd.exe "C:\Program Files (x86)\SquareEnix\FINAL FANTASY XIV - A Realm Reborn"
# (3) exd TerritoryType WeatherRate
# (4) Run util/gen_territory_type.py path/to/TerritoryType.csv
impor... |
import requests
base_url_v2 = "http://ec.europa.eu/eurostat/cache/GISCO/distribution/v2/"
base_url_v1 = "http://ec.europa.eu/eurostat/cache/GISCO/distribution/v2/"
# List of datasets available for each version
# base_url_v2+"/nuts/datasets.json"
#
# Download dataset: NUTS-YEAR or LAU-YEAR. Both are related. Maximum r... |
def print_impares(m, n):
for i in range(1, m+1):
maior_elemento_linha = 2*n*i
lista = [number for number in range((maior_elemento_linha - 2*n)+1, maior_elemento_linha, 2)]
if i % 2 == 0:
lista.sort(reverse=True)
for numero in lista:
if(numero < 10):
... |
import base64
import json
import os
import sys
import pytest
from flask import request
from flump import MIMETYPE
from flump.web_utils import get_json
sys.path.append(os.path.join(os.path.join(sys.path[0], 'docs'), 'examples'))
print(sys.path)
example = __import__('sqlalchemy-auth')
@pytest.fixture(scope='module')... |
### $Id: admin.py,v 1.5 2017/12/18 09:12:51 muntaza Exp $
from django.contrib import admin
from umum.models import Provinsi, Kabupaten, LokasiBidang, SKPD, SUBSKPD, KodeBarang, HakTanah, SatuanBarang, KeadaanBarang, SKPenghapusan, MutasiBerkurang, JenisPemanfaatan, AsalUsul, Tahun, GolonganBarang, Tanah, KontrakTanah,... |
#!/usr/bin/env python3
import omni_const
import omni_config
import omni_unpwd
import sys
import os
import torch
from torch.autograd import Variable
import numpy as np
from datetime import datetime
from omnissiah.db import OmniDB
from omnissiah.omnissiah import OmniProgram
from omnissiah.nnml import Manufacturers_NNe... |
import torch
import numpy as np
def norm_np(x, p: int):
"""
Compute p-norm across the features of a batch of instances.
Parameters
----------
x
Batch of instances of shape [N, features].
p
Power of the norm.
Returns
-------
Array where p-norm is applied to the featu... |
from collections import deque
ini_queue = deque()
ini_queue.append(1)
ini_queue.append(3)
ini_queue.append(5)
print(ini_queue.popleft())
print(ini_queue.popleft())
print(ini_queue.popleft()) |
# https://leetcode.com/problems/reverse-integer/description/
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within ... |
#!/usr/bin/env python3
class MagicFormatter:
def __init__(self, args=None, kwargs=None, level=1):
self.args = args or ()
self.kwargs = kwargs or {}
self.level = level
def __call__(self, *args, **kwargs):
return self.__class__(args, kwargs, self.level)
def __ror__(self, op... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
from ..compat import on_win
if on_win:
from .windows import get_free_space_on_windows as get_free_sp... |
## most common words
##
import re
def most_common_words(text):
"""[summary]
Args:
text ([type]): [description]
"""
## step-1: remove punctuation, convert-to-lowercase, split by whitespaces
## sanitize the text by removing caps and punctuation.
punctuation_re = r"[.,;!\"\'\(\)]"... |
# Copyright 2019 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
import math
# this is the selection code! codename part SELECT
def selector():
global select
select = input('''Please select what function you want to use
+ for Addition
- for Subtraction
/ for Devision
* for Multiplication
SQRT for squareroot please change second number to zero
HYPO for... |
import os
import argparse
from torch.backends import cudnn
import torch
from solver import Solver
from utils.dataloader import DataLoader
def str2bool(v):
return v.lower() in ("true")
def main(config):
# For fast training.
cudnn.benchmark = True
# Create directories if not exist.
if not os.pat... |
ROBERTA = 'roberta-base'
|
from django.contrib import admin
from .models import Feedback, reportRestaurant
admin.site.register(Feedback)
admin.site.register(reportRestaurant)
# Register your models here.
|
30 mtime=1639777085.497355983
30 atime=1639777086.378355983
30 ctime=1639777127.031355983
|
# Simple script to generate credentials file based on
# Copy/paste of the "{OPEN} API Administration" output
# Usage: python gen_edgerc.py <section_name>
""" Copyright 2015 Akamai Technologies, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except... |
def lengthOfLongestSubstring(s):
map = {}
max_so_far = curr_max = start = 0
for index, i in enumerate(s):
if i in map and map[i] >= start:
max_so_far = max(max_so_far, curr_max)
curr_max = index - map[i]
start = map[i] + 1
else:
curr_max += 1
... |
import os.path
import torchvision.transforms as transforms
from data.dataset.base_dataset import BaseDataset
from data.image_folder import make_dataset
from PIL import Image
import numpy as np
import torch
# from IPython import embed
class TwoAFCDataset(BaseDataset):
def initialize(self, dataroots, load_size=64):
... |
from __future__ import division
from anfis import anfis
from anfis import membership #import membershipfunction, mfDerivs
class AnfisClassifier:
'ANFIS classifier'
def __init__(self):
'''
Constructor
'''
self.anfis = anfis.ANFIS
self.mem = membership.membershi... |
# 3. Fie un tuplu (x,y) reprezentarea unui punct intr-un sistem cartezian.
# Sa se scrie o functie care primeste ca parametru o lista de puncte si returneaza o lista de tuple (a,b,c) unice
# care reprezinta dreptele unice determinate de acele puncte ( (a,b,c) corespunde dreptei ax + by + c = 0).
def unique_straight... |
import tensorflow as tf
import os
import numpy as np
import genart.tf.chinese.data as mdata
import genart.tf.chinese.model as mmodel
import itertools
import matplotlib.pyplot as plt
class CustomCallback(tf.keras.callbacks.Callback):
def __init__(self, manager, test_data, model, out_dir):
super(... |
"""
Welcome to CS375! This is the first part of assignment 1 in which we will
setup an experiment to train AlexNet on ImageNet from scratch.
This document will walk you through setting up an experiment using tfutils
a tool that we have developed to facilitate using tensorflow.
tfutils biggest advantage is that it prov... |
#!/usr/bin/python3
# 文件名: fibo.py
def fib(n): #定义到n的斐波那契数列
a, b = 0,1
while b<n:
print(b, end=' ')
a,b = b, a+b
print()
def fib2(n): # 返回到n的斐波那契数列
result = []
a,b = 0,1
while b<n:
result.append(b)
a,b = b, a+b
return result |
from setuptools import setup
from setuptools import find_packages
import paz
setup(name='pypaz',
version='0.1.6',
description='Perception for Autonomous Systems',
author='Octavio Arriaga',
author_email='octavio.arriaga@dfki.de',
license='MIT',
install_requires=['opencv-python', 'ten... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:jvm.bzl", "jvm_maven_import_external")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazelrio//:deps_utils.bzl", "cc_library_headers", "cc_library_shared", "cc_library_static")
def set... |
import unittest
import fern
from fern.parser.parser import Parser
from StringIO import StringIO
class Basics(unittest.TestCase):
def setUp(self):
self.p = Parser("foo= 42@'bar' = 'ggg'")
self.fdg = self.p.parse()
def testIsMap(self):
self.assertTrue(isinstance(self.fdg, fern.ast.Map))
... |
# Copyright 2020 TerraPower, 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 in writi... |
from . import FixtureTest
class BusRouteRefs(FixtureTest):
def test_one_bus_route(self):
# Sloat Blvd, part of:
# type=route, route=bus, network="", ref=23
# type=route, route=bicycle, network=lcn, ref=50
# type=route, route=road, network=US:CA, ref=35
self.load_fixtu... |
# Generated by Django 2.2.22 on 2021-08-02 20:45
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('casemgmt', '0004_wkcmpeligibilitydata'),
]
operations = [
migrations.Crea... |
"""UseCase for associating an inbox task with a big plan."""
import logging
from argparse import Namespace, ArgumentParser
from typing import Final
import jupiter.command.command as command
from jupiter.framework.base.entity_id import EntityId
from jupiter.use_cases.inbox_tasks.associate_with_big_plan import InboxTas... |
import logging
from tastyscrape.dxfeed import greeks, quote, trade, summary, profile
LOGGER = logging.getLogger(__name__)
KEY_MAP = {}
def map_message(message):
if isinstance(message[0], str):
first_sample = False
else:
first_sample = True
msg_type = message[0][0] if first_sample else me... |
#!/usr/bin/env python3
import argparse
import glob
import os
from pathlib import Path
import subprocess
import sys
from zipfile import ZipFile
def parse_arguments():
parser = argparse.ArgumentParser(
description="Tool for garbling PII in for PPRL purposes in the CODI project"
)
parser.add_argumen... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: modules/drivers/velodyne/proto/velodyne.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from goog... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Factory functions for all ngraph ops."""
from typing import Callable, Iterable, List, Optional, Set, Union
import numpy as np
from functools import partial
from ngraph.impl import Node, Shape
from ngraph.impl.op import Constant, Par... |
#
# Copyright (c) 2019 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
from events import EventsData, Event, EventType
import matplotlib.pyplot as plt
import argparse
def main():
descr = "Merge data from Peripheral and Central. Synchronization events" \
" should b... |
from pygame import K_w,K_s,K_a,K_d,K_q,K_e,K_LEFT,K_RIGHT,K_UP,K_DOWN,K_z,K_x
from pygame.key import get_pressed
from numpy import array
class Control:
def __init__(self):
self.key = array([-1.5, 0.0, -0.5, 0.0, 0.0, 1.0])
'''key[0] - W S
key[1] - A D
key[2] - W S
... |
#!/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2020 yinochaos <pspcxl@163.com>. 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/licen... |
import sys
import os
import __main__ as main
import argparse
import ast
import pandas as pd
import pysam
import numpy as np
def get_barcode_ids(bam_in, chrom, start, end, min_mapq):
bcs = []
for r in bam_in.fetch(chrom, start, end):
if r.mapq >= min_mapq:
if r.has_tag("BX"):
bc_id=r.get_tag("BX")
... |
import tests
import unittest
import mercadobitcoin
def assert_ticker_response(response):
assert 'ticker' in response
ticker_fields = {"high", "date", "sell", "vol", "last", "low", "buy"}
for field in ticker_fields:
assert field in response["ticker"]
def assert_orderbook_response(response):
as... |
"""
Robertson (1968) Correlated Colour Temperature
==============================================
Defines the *Robertson (1968)* correlated colour temperature :math:`T_{cp}`
computations objects:
- :func:`colour.temperature.uv_to_CCT_Robertson1968`: Correlated colour
temperature :math:`T_{cp}` and :math:`\\Delt... |
from scipy.optimize import curve_fit
def linear_eq(x, slope, intercept):
return x*slope + intercept
def L_fit(xdata, ydata):
popt, pcov = curve_fit(linear_eq, xdata, ydata)
return popt |
"""
`Cargo SQL Networking Fields`
--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--
The MIT License (MIT) © 2015 Jared Lunde
http://github.com/jaredlunde/cargo-orm
"""
import copy
from netaddr import *
import psycopg2
from psycopg2.extensions import *
from cargo.etc.types impo... |
#!/usr/bin/env python2
'''
@author: Hugo Sousa
Mobile Robotics
Final Project
Orienteering Problem
grid.py: Map<->Grid utilities.
'''
import numpy as np
from scipy import ndimage
def index_to_center_of_mass(i, j, array):
'''
Get the center of mass coordinate of a given grid cell in the world.
... |
#Based on https://github.com/alexeagle/rules_nodejs/tree/webpack
load("@build_bazel_rules_nodejs//:internal/collect_es6_sources.bzl", "collect_es6_sources")
WEBPACK_BUNDLE_ATTRS = {
"mode": attr.string(),
"srcs": attr.label_list(
doc = "JavaScript source files",
allow_files = [".js"]),
"de... |
import discord
import CommandIntegrator as ci
import fake_useragent
import coronafeatureclient as coronafeatureclient
from CommandIntegrator.enumerators import CommandPronoun
from CommandIntegrator.logger import logger
class CoronaSpreadFeatureCommandParser(ci.FeatureCommandParserBase):
def __init__(self, *args,... |
import tornado.ioloop
import tornado.web
import os
import pandas as pd
import uuid
from tornado.options import define, options
from joblib import dump, load
define("port", default=8888, help="run on the given port", type=int)
def load_model(model_path = 'model/classifier.pkl'):
path = os.path.abspath(model_path)
... |
from collections import Counter
def input():
with open("input-06.txt") as lines:
for line in lines:
yield line.strip()
fish = Counter()
for line in input():
for i in line.split(","):
fish[int(i)] += 1
def tick(fish):
delta = Counter()
for day, count in fish.items():
... |
"""Score reel controller."""
import logging
import asyncio
from functools import partial
from mpf.core.utility_functions import Util
class ScoreReelController(object):
"""The overall controller that is in charge of and manages the score reels in a pinball machine.
The main thing this controller does is ke... |
from db_connector import DBConnector
db = DBConnector()
all_count = 0
for rec in db.select("select COUNT(*) from core_variable_changes"):
all_count = rec[0]
print("ВСЕГО ЗАПИСЕЙ: %s" % (all_count))
db.query("update core_variable_changes"
" set value = ROUND(value * 10) / 10"
" where VARIABLE... |
#!/usr/bin/python3
# HTTPレスポンスヘッダ
import os
# ステータスコードとメッセージはPythonの定数を使う
# https://docs.python.jp/3/library/http.html
from http import HTTPStatus
from http.cookies import SimpleCookie
# CGIの環境変数からプロトコルとバージョンを取得する
protocol = os.environ.get('SERVER_PROTOCOL')
# HTTPレスポンスヘッダ
# NPHなので、ステータスラインも記述する
print(f'{protocol} {... |
import torch
import numpy as np
import os
import time
import sys
import pdb
import traceback
from bdb import BdbQuit
import json
import random
import tqdm
from copy import deepcopy
from collections import defaultdict
from opts import parse_opt
from models.sent_senti_cls import SentenceSentimentClassifier
from dataload... |
import torch.nn as nn
from catalyst import utils
def test_get_fn_argsnames():
class Net1(nn.Module):
def forward(self, x):
return x
class Net2(nn.Module):
def forward(self, x, y):
return x
class Net3(nn.Module):
def forward(self, x, y=None):
r... |
from utils import roundsSize
from styling import S, T, Bg, stylizesStr
TAB = ' ' * 4
class Dirr:
def __init__(self, lv, name, amtIgnr, ignrSize, amtFolders, amtSubFolders, amtSubFiles, amtFiles, notIgnrSize, totalSize=0):
self.lv = lv
self.name = name
self.amtIgnr = amtIgnr
self.ignrSize = rounds... |
# -*- coding: utf-8 -*-
# @Author : CharesFuns
# @Time : 2020/5/8 20:51
# @Function: To crawl weibo information based on key words
import json
import scrapy
import logging
from time import time
from math import floor
from urllib.parse import quote
from lxml import etree
import re
from weibo.items.m import KeyWords... |
import sys
import os
import numpy as np
sys.path.append(os.path.abspath(os.getcwd()))
from utils.utils_save import *
from utils.utils_plot import draw_car_proj_all, draw_traj_proj_all
from utils.utils_config import Params
from src.modules.longitudinal_reconstruction import solve_longitudinal_reconstruction
from src.m... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Copyright (c) 2020, eQualit.ie 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.
from baskerville.features.updateable_features import UpdaterRatio
from pyspark.sql import functions as F
from baskerville.fe... |
# generated by datamodel-codegen:
# filename: nested_enum.json
# timestamp: 2019-07-26T00:00:00+00:00
from __future__ import annotations
from enum import Enum
from pydantic import BaseModel
class State(Enum):
field_1 = '1'
field_2 = '2'
class NestedState1(Enum):
field_1 = '1'
field_2 = '2'
... |
# -*- coding: utf-8 -*-
import click
import logging
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
from typing import Union, Tuple
import requests, zipfile, io
import pandas as pd
def download_dataset(file_location: Union[str, Path] = "data/raw/"):
"""Download and unzips raw data
Parame... |
#!/usr/bin/python
# coding=utf-8
from .battle_controller import IBattleController
from .entity import Entity
from .entity_def import Definitions
from .network.net_packet import NetPacket
from .network.player import PlayerBase
from .pretty_print_mixin import PrettyPrintObjectMixin
# public things that should never cha... |
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import random
import time
import os
import atexit
import s... |
from django.shortcuts import render, redirect
from .forms import ParagonForm
from .models import Paragon
import pytesseract
from .tasks import items_from_image
from PIL import Image, ImageFilter
def start_page(request):
return render(request,'base.html')
def lista_paragonow(request):
qs = Paragon.objects.... |
from modeltranslation.translator import TranslationOptions, translator
from good_spot.pages import models as pages_models
class PageTranslationOptions(TranslationOptions):
fields = ('title', 'short_description', 'text')
translator.register(pages_models.Page, PageTranslationOptions) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Rafael Figueroa
"""
#ROS imports
import rospy
from geometry_msgs.msg import Twist
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseStamped
from tf.transformations import euler_from_quaternion
from std_msgs.msg import UInt16
from std_msgs.msg imp... |
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import models
import runway
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import argparse
import os
import tqdm
import scipy.ndimage as nd
from utils import deprocess, preprocess, clip
device = torch.devic... |
# -*- coding: utf-8 -*-
import info
class subinfo(info.infoclass):
def setTargets(self):
self.versionInfo.setDefaultValues()
self.patchToApply["17.04.0"] = [("akonadi-17.04.0-20170530.diff", 1)]
self.patchToApply["17.04.1"] = [("akonadi-17.04.0-20170530.diff", 1)]
self.patchToAppl... |
#!/usr/bin/env python3
import os
import yaml
def nested_set(dic, keys, value):
"""
:param dic:
:param keys:
:param value:
:return:
"""
dictionary = dic
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
return dictionary
def print_dict(dictiona... |
import json
from collections import defaultdict
from typing import Tuple, Dict
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import tqdm
from .bokeh_timeline import TaskStartTraceEvent, TaskEndTraceEvent, normalize_task_events, \
plot_tabs, build_plot, plot_task_lifespan, plot_tasks_on... |
import os
import shutil
import sys
File_Formats = set()
All_Files = list()
def main():
try:
Arg1 = sys.argv[1]
except IndexError:
print("USAGE : main.py FOLDER_LOCATION")
if os.path.exists(Arg1):
os.chdir(Arg1)
else:
print("ERROR 404 NO FILE FOUND,MAKE SURE THE DIREC... |
import copy
import os
import traceback
import json
import sys
import torch
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def change_path_to_absolute(train_options):
train_options["embedding_path"] = train_options["embedding_path"].format(dims=train_options["embedding_dim"])
if train_... |
from aiogram import types
from aiogram.dispatcher.filters import Command
from data.text import text
from filters import IsPrivate
from keyboards.inline.plan_keyboards import plansMenu
from loader import dp
import middlewares
@dp.message_handler(IsPrivate(), Command('planos', prefixes='/!'))
@dp.message_handler(IsPri... |
"""
Test portfolio module.
"""
import pytest
from quantfin.market import assets
from quantfin.portfolio_selection import portfolio
def test_empty_portfolio() -> None:
ptf = portfolio.Portfolio()
assert isinstance(ptf, portfolio.Portfolio)
def test_portfolio_with_holdings() -> None:
ptf = portfolio.Portf... |
#!/usr/bin/env python3
#
# author : Michael Brockus.
# contact: <mailto:michaelbrockus@gmail.com>
# license: Apache 2.0 :http://www.apache.org/licenses/LICENSE-2.0
#
# copyright 2020 The Meson-UI development team
#
from pathlib import Path
import subprocess
class NinjaInstall:
def __init__(self, builddir: Path... |
# -*- coding: utf-8 -*-
"""
Written by Steve Byrnes, 2012 -- http://sjbyrnes.com - steven.byrnes@gmail.com
Calculates equilibrium band structures of 1D semiconductor stacks. (i.e., it
solves the poisson-boltzmann equation by the finite differences method.)
This is the only module in the package. It's written in Pytho... |
bl_info = {
"name": "Partial Skeletal Mesh Export",
"category": "Import-Export",
}
import bpy
import os
class SkelMeshExport(bpy.types.Operator):
"""Custom Skeletal Mesh Export""" # blender will use this as a tooltip for menu items and buttons.
bl_idname = "export.armorexport" # unique identi... |
import numpy as np
class ReLu:
def __init__(self, hidden_units = 10, input_size = 10, rand_seed=123, layer_name=''):
np.random.seed(rand_seed)
self.weights = np.random.uniform(low=-1, high=1, size = (input_size, hidden_units))
self.a = np.zeros(shape=(hidden_units, 1)) # column vector; wil... |
# -*- coding: utf-8 -*-
# @Time : 2019/8/23 21:56
# @Author : zhoujun
import itertools
import torch
from torch import nn
import numpy as np
class PANLoss(nn.Module):
def __init__(self, alpha=0.5, beta=0.25, delta_agg=0.5, delta_dis=3, ohem_ratio=3, reduction='mean'):
"""
Implement PSE Loss.
... |
# 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.
import torch
import pathlib
import os
from datetime import datetime
path_curr = str(pathlib.Path(__file__).parent.absolute())
device = torch.... |
from django.shortcuts import render, redirect
from .models import Remedio
from .forms import RemedioForm, ReceitaForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from receitas.models import Receita
from vinculos.models import ReceitaMedicoPaciente
from usuarios.models ... |
# encoding: utf-8
__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"
from androlyze.model.script.AndroScript import AndroScript
class Files(AndroScript):
''' List the files of the .apk '''
VERSION = "0.1"
def _analyze(self, apk, dalvik_vm_format, vm_analys... |
from .azure_api import AzureOCR
from .structure_extractor import StructureExtractor
from .table_extractor import TableExtractor
import click
from .secret import AZURE_READ_API_ENDPOINT, \
AZURE_READ_API_SUBSCRIPTION_KEY, \
AZURE_FORM_API_ENDPOINT, \
AZURE_FORM_API_SUBSCRIPTION_KEY, \
DOCUMENT_FILE_PATH... |
'''
Created on Aug 9, 2017
@author: Hao Wu
'''
from ScopeFoundry import HardwareComponent
from VOTAScopeHW.arduino_wheel.arduino_wheel_dev import ArduinoWheelDev
import time
from math import exp
class ArduinoWheelHW(HardwareComponent):
'''
Hardware Component Class for receiving AI input for breathing, licking... |
class Vehicle:
pass
car = Vehicle()
boat = Vehicle() |
from dataclasses import dataclass
@dataclass # code does not run without this annotation
class Test:
a: int
b: int
t = Test(1, "b")
print(t.a) # 1
print(t.b) # b // note that python does not consider types
print(t) # Test(a=1, b='b')
print("")
# Above class is equivalent to
class Test2:
def __init__(s... |
# Copyright 2019 Robert Bosch GmbH
#
# 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 wri... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from six.moves import cPickle as pickle
import numpy as np
import scipy.io as sio
import sys
import os
from time import strftime
from detectron.datasets.json_dataset_wsl... |
import adwords_pull
import analytics_pull
import process_xml
import match_maker
import csv_parser
import pandas
import pandasql
import datetime
import google_auth
from google.cloud import bigquery
from datetime import date
from dateutil.relativedelta import relativedelta, SU,MO,TU,WE,TH,FR,SA
import pprint
from currenc... |
import dht
import machine
import time
def get_dht_temperature(sensetype,pin):
if (sensetype=='dht11'):
d = dht.DHT11(machine.Pin(pin))
else:
d = dht.DHT22(machine.Pin(pin))
d.measure()
time.sleep_ms(1)
return d.temperature() # eg. 23 (°C)
def get_dht_relative_humidity(sensetype,pin):
if (sensetype=='dht11'):... |
from typing import List
import attr
import matplotlib as mpl
import matplotlib.colors
import numpy as np
TWOPI = 2 * np.pi
@attr.dataclass
class Palette:
unclipped: np.ndarray
clipped: List[str]
def gen_circular_palette() -> Palette:
"""Return a palette of 12 *distinct* colors in #rrggbb format.
T... |
import csv
import decimal
from datetime import date, datetime
from decimal import Decimal
import random
import json
from django.http import QueryDict
from pytest import mark
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils import timezone
from django_factory_boy import ... |
"""Helpers related to configuration."""
import configparser
import pathlib
import os
from typing import Any, Optional
from typing_extensions import Protocol
__all__ = ["Config"]
class ConfigSection(Protocol):
"""Protocol defining how a section of the config behaves."""
def __getitem__(self, key: str) -> A... |
# coding=utf-8
# Copyright 2021 The Robustness Metrics Authors.
#
# 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 appli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.