text stringlengths 3.07k 12.6k |
|---|
# ----------------------------------------------------------------------------
# Copyright 2019-2021 Pelion
#
# SPDX-License-Identifier: Apache-2.0
#
# 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 Lice... |
import pythoncom, pyHook
import json
import rtmidi
import os
import sys
noteLayouts = [pos_json for pos_json in os.listdir('.') if pos_json.endswith('.json')]
midiout = rtmidi.MidiOut()
available_ports = midiout.get_ports()
if available_ports:
print("""Welcome to the KeyboardCBA MIDI emulator, which turns your co... |
from shutil import rmtree
from pathlib import Path
import logging
import os
DEVICES = None
def _delete_folder(folder):
for root, dirs, files in os.walk(folder):
for file in files:
os.remove(os.path.join(root, file))
def _get_home(package):
home = os.environ.get(
f'{package.upper... |
"""AutoEncoder
Revised version of "https://zhuanlan.zhihu.com/p/116769890"
"""
import torch
import torchvision
import torch.utils.data as Data
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import time
starttime ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""Deployment webhook."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import base64
import json
import enum
from asyncat.client import GithubError
from asyncat.reposit... |
#!/usr/bin/python
"""
Wait for all necessary ROS sensors
this is Python 2.7 code
"""
import time
import struct
import math
from io import BytesIO
import threading
from threading import RLock
from threading import Thread
import signal
import zmq
import sys, getopt
import rospy
from rosgraph_msgs.msg import Clock... |
import re
from abc import ABC, abstractmethod
from typing import IO, Any, Dict, List, Optional, Pattern, cast
from pydantic import BaseModel
from pydantic.fields import Field
class ConfigModel(BaseModel):
class Config:
extra = "forbid"
class DynamicTypedConfig(ConfigModel):
type: str = Field(
... |
import numpy,uuid,torch
from numpy import cos,sin,pi,array,argsort,asarray,eye
from numpy import linspace,matrix
from numpy import dot,real,prod,arange
from numpy.linalg import det,norm,eig as eigsolve,eigh,inv,eigvals,matrix_rank
from torch.linalg import det,inv
from torch import matrix_exp as expm,kron,diagonal,diag... |
#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance ... |
#!/usr/bin/env python3
#########################################################################
"""
____ ____ ____ _ _ ____ ____ ____ _ _ _ _ ____ ___
|___ |__| [__ \_/ [__ | |__| |\ | |__| |___ |__]
|___ | | ___] | ___] |___ | | | \| | | |___ |
A tool for easily connecting ... |
from datetime import datetime
from dash import html,Input,Output
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
from app import app
from Backend.tools import Utils
from layoutComponents.makeComponents import makeSearchBar
from Backend.dbconnect import getNamesFromPortfolio, getPortfi... |
# -*- coding: utf-8 -*-
# TODO: Complete removal of methods below. Similar to test_module
"""Backward-compatibility tests for deprecated features."""
import types
import pytest
from .utils import is_clr_class, is_clr_module, is_clr_root_module
# Tests for old-style CLR-prefixed module naming.
def test_simple_impo... |
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render, redirect
# from .models import related models
from . import models
# from .restapis import related methods
from . import rest... |
from lxml.etree import Element, SubElement, tostring
from utils import log
import shutil
import os
def get_pic_dir(out_put_dir):
img_dir = os.path.join(out_put_dir, "img")
pic_dir = os.path.join(img_dir, "pic")
return pic_dir
def get_fragment_dir(out_put_dir):
img_dir = os.path.join(out_put_dir, "im... |
"""Helpers for ble_monitor."""
import logging
import subprocess
import time
_LOGGER = logging.getLogger(__name__)
# Bluetooth interfaces available on the system
def hci_get_mac(interface_list=[0]):
"""Get dict of available bluetooth interfaces, returns hci and mac."""
btaddress_dict = {}
output = subproc... |
#coding=utf-8
import tensorflow as tf
import keras
from keras.models import *
from keras.layers import *
import numpy as np
from metrics import metrics
from losses import LOSS_FACTORY
from keras.callbacks import History
from keras.callbacks import ModelCheckpoint
def conv_block(input, filters):
out = Conv2D(filter... |
#!/usr/bin/env python
import configargparse
import onmt.opts as opts
import os
import random
from itertools import chain
import torch
import torchtext
# from torchtext.data.iterator import Iterator
from onmt.model_builder import build_model
from onmt.trainer import build_trainer
from onmt.utils.logging import init... |
from pymatgen.core import Structure
from pymatgen.analysis.diffusion.neb.io import (
MVLCINEBEndPointSet,
MVLCINEBSet,
get_endpoints_from_index,
get_endpoint_dist,
)
import unittest
import os
__author__ = "hat003"
test_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)))
def get_path(path... |
"""
Helper functions and utilities for projecting to the simplex and various tasks.
"""
import numpy
### Constants ###
SQRT3 = numpy.sqrt(3)
SQRT3OVER2 = SQRT3 / 2.
### Auxilliary Functions ###
def unzip(l):
"""[(a1, b1), ..., (an, bn)] ----> ([a1, ..., an], [b1, ..., bn])"""
return list(zip(*l))
def n... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
# 《机器学习实战》 - 第5章 - Logistic回归
# 示例1:采用梯度上升法找到Logistic回归分类器的最佳回归系数
def loadDataSet():
"""
读取数据集
"""
dataMat = []
labelMat = []
fr = open('TestSet.txt')
for line in fr.readlines():
lineArr = line.strip().spli... |
# greaseweazle/tools/update.py
#
# Greaseweazle control script: Firmware Update.
#
# Written & released by <NAME> <<EMAIL>>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.
description = "Update the Greaseweazle device... |
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import
import os
import json
import logging
import time
from ssl import SSLError
import slacker
from six import iteritems
from websocket import (
create_connection, WebSocketException, WebSocketConnectionClosedException
)
from slackbot.util... |
import sys
import os
import pickle
from qmla.exploration_strategies.nv_centre_spin_characterisation import (
nv_centre_large_spin_bath,
)
import qmla.shared_functionality.probe_set_generation
import qmla.shared_functionality.latex_model_names
from qmla import model_building_utilities
class NVCentreRevivalsSimul... |
# -*- coding: utf-8 -*-
import hashlib
import itertools
import io
import re
from . import config
from . import datablocks
from . import markdown
from .html import *
from .messages import *
def processInclusions(doc):
iters = 0
while True:
# Loop because an include can contain more includes.
... |
import streamlit as st
import pandas as pd
import pydeck as pdk
import math, time
def main():
st.title("House Price Fluctuations in Seoul, South Korea")
st.sidebar.markdown("## **Controller**")
period_slide_info = st.sidebar.empty()
time_slider = st.sidebar.empty()
period_info = st.empty()
de... |
#!/usr/bin/python3
"""
This test checks that we can assemble and disassemble all the instructions
found in `arm_test.dis` and similar dumps obtained via `objdump`
"""
import re
import sys
from typing import List
from CpuA32 import symbolic
from CpuA32 import opcode_tab as a32
def FixupAliases(opcode: a32.Opcode, n... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import time
import torch
import poptorch
import logging
import popdist
import horovod.torch as hvd
from poptorch.optim import SGD, RMSprop, AdamW
import pytorch_lightning as pl
from pytorch_lightning.plugins import IPUPlugin
import sys
import os
if not os.p... |
# Copyright 2021 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... |
"""
orderparam.py
Contains the methods for order parameter calculation and anlyses.
"""
from collections import defaultdict
import numpy as np
from memly.metrics import Metric
from memly.membrane import unit_vector, angle_between
def calculate_orderparam(angle):
"""
Calculate the order parameter for the pro... |
import random
import traceback
import numpy as np
import torch
from flask import Flask, request, jsonify
from utils import *
from solvers import *
from download_models import download_aij_models
class CuttingEdgeStrongGeneralAI(object):
def __init__(self, train_path="public_set/train"):
self.train_path ... |
# Copyright 2017 Telstra Open Source
#
# 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 agre... |
#!/usr/bin/env python
import sys
import matplotlib
matplotlib.use('Agg')
from scipy import reshape, zeros, where, std, argmax, sqrt, ceil, sign, \
negative, linspace
from scipy.signal import detrend
from scipy import io
from nipy import save_image, load_image
from nipy.core.api import xyz_affine
from nipy.labs.viz... |
# Copyright 2019 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 agreed to in writing, ... |
#========================================================================================#
# #
# THE TIC TAC TOE MACHINE #
# ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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
#... |
#!/usr/bin/env python
import argparse
import datetime
import mrta
import mrta.msg
import pprint
import rospy
import signal
import subprocess
import sys
import time
# Paths to ROS binaries
#ROS_HOME = '/opt/ros/hydro'
ROS_HOME = '/opt/ros/indigo'
#ROS_HOME = '/home/esch/opt/ros/hydro'
ROSLAUNCH = "{0}/bin/roslaunch".f... |
import time
import sys
import dis
import traceback
from browser import document as doc, window, ajax, bind
from browser import timer
from browser.html import *
from browser.local_storage import storage
# set version
doc["version"].text = ".".join(str(x) for x in sys.version_info[:3])
# set height of container to 66%... |
# Copyright 2020 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... |
import os
import sys
import argparse
import numpy as np
import torch
from torch import optim
import torch.nn as nn
from transformers import RobertaConfig, RobertaTokenizer
import fitlog
from fastNLP import cache_results
from fastNLP import FitlogCallback, WarmupCallback, GradientClipCallback
from fastNLP import Rando... |
from collections import defaultdict
from contextlib import contextmanager
import rospy
import time
from duckietown_utils.text_utils import seconds_as_ms
__all__ = ['ProcessingTimingStats']
class ProcessingTimingStats():
"""
This is the model:
One message is received at a certain tim... |
import requests
import json
import re
class PokeDig:
def __init__(self, min_cp=2750, include_unevolved=False, include_evolutions=False,
include_mythical_legendary=False, only_mythical_and_legendary=False, get_all=False):
self.min_cp = min_cp
self.include_unevolved = include_unevol... |
#!/usr/bin/env src
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@contact: <EMAIL>
@software: PyCharm
@file: update_model_state_dict.py
@time: 2020/3/23 5:42
@desc:
"""
from typing import Dict, Tuple, List, Union
import re
from colorama import Style, Fore
import torch
import torch.nn as nn
__all__ = ['update_model_sta... |
#! -*- coding: utf-8 -*-
# 微调多国语言版T5做Seq2Seq任务
# 介绍链接:https://kexue.fm/archives/7867
# 细节请看:https://github.com/bojone/t5_in_bert4keras
# 数据集:https://github.com/CLUEbenchmark/CLGE 中的CSL数据集
# 补充了评测指标bleu、rouge-1、rouge-2、rouge-l
from __future__ import print_function
import json
import numpy as np
from tqdm import tqdm
fr... |
import os
import asyncio
from multiprocessing import Queue, Lock
import threading
import queue
import uuid
import time
from enum import Enum
import inspect
import logging
from dataclasses import dataclass
class Events(Enum):
NewMessage = 1
@dataclass
class CommandContext:
tx_queue:Queue
rx_queue:Queue
... |
'''
Author: <NAME>
E-mail: <EMAIL>
October 22th, 2018
Largely borrowed from:
https://github.com/yysijie/st-gcn/blob/master/net/utils/graph.py
'''
import numpy as np
class Graph():
""" The Graph to model the skeletons extracted by the openpose
Args:
strategy (string): must be one of... |
# encoding=utf8
"""
This application allows you to manage several static page websites in one repo.
It allows you to share templates and static files between them, so it is much
easier to create new blogs/sites with similar content
"""
import sys
from datetime import datetime
from os import listdir, walk
from os.path... |
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 The Pybricks Authors
# Written by <NAME> - 2010/11/18
# Distributed under Gnu LGPL 3.0
# see http://www.gnu.org/licenses/lgpl-3.0.txt
# This file was originally copied from micropython/tools/dfu.py
import sys, struct, zlib, ... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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... |
from rpython.rlib.objectmodel import specialize, we_are_translated, compute_hash
from rpython.tool.pairtype import extendabletype
# Union-Object to represent a json structure in a static way
class JsonBase(object):
__metaclass__ = extendabletype
is_string = is_int = is_float = is_bool = is_object = is_array =... |
# Copyright 2019 Astex Therapeutics 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 i... |
from discord.ext.commands import Command, Group, command, group
import traceback
import inspect
from typing import Optional, Union, Iterable, AnyStr, Set
from .lib.event_emitter import AsyncEventEmitter, on
from .utils import DependencyResolver, isiterable
class CommandGenerator:
def __init__(self, cmd, *, group =... |
# This file obtains predictions (and saves them in logit form) for the
# ResNet-110 trained with mixup (specifically, the experiments in which
# output-space mixed examples were created in every training batch)
# It is based off a script implemented by <NAME>, and draws on code
# from: https://raw.githubusercontent.com... |
"""
Calculates the perplexity given a model.
"""
import pickle
import os, re
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import argparse
from random import randint
from pytorch_pretrained_bert import GPT2Tokenizer, GPT2LMHeadModel, GPT2Config
from data import PromptDataset, Tex... |
import numpy as np
import pandas as pd
import pretty_midi
import os
#=======================================================================#以下自写
def get_genres(path): #get流派种类
track_id = []
genre = []
with open(path) as f:
line = f.readline... |
# Copyright (C) 2015 – 2021 <NAME> (4shadoww)
from core.hakkuframework import *
from core import colors
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import socket
import random
from string import ascii_lowercase
conf = {
"name": "email_bomber",
"version": ... |
import pandas as pd
import numpy as np
import os
from collections import defaultdict
import re
from typing import Dict, Union, Generator, DefaultDict
from sklearn import model_selection
from src.data.logparser import parse_file_drain3, save_drain3_to_file
SEED = 160121
def load_labels(file_path: str) -> pd.DataFram... |
# coding: utf-8
"""
Most of this file's code has been taken from
https://github.com/requests/requests/blob/d58753344638992a63f4fe8e516c9f55a9a7f027/tests/testserver/server.py
and modified to fit our needs such as:
- Parsing a subset of upload queries
- Keeping track of uploaded chunks
- Options to generate 500 errors
... |
# -*- coding: utf-8 -*-
"""
AWattPrice Config
"""
__author__ = "<NAME> <<EMAIL>>"
__copyright__ = "Frank Becker"
__license__ = "mit"
import copy
import os
import sys
from pathlib import Path
from typing import Optional, Tuple
from box import Box # type: ignore
from configupdater import ConfigUpdater # type: ign... |
#!/usr/bin/env python3
import configparser
import csv
import json
import os
import time
import urllib.request
import urllib.error
import urllib.parse
def printr(message: str):
print(message, "\r", end="")
return 0
def printc(message: str, i: int):
if i % 4 == 0:
x = "|"
elif i % 4 == 1:
... |
import math
from geompreds import orient2d, incircle
from opendrivepy.point import Point
a = 6378137
b = 6356752.3142
f = (a - b) / a
e_sq = f * (2-f)
def point_distance(pointa, pointb):
return math.sqrt((pointa.x - pointb.x) ** 2 + (pointa.y - pointb.y) ** 2)
def line(p1, p2):
A = (p1.y - p2.y)
B = (p2.... |
import os
import sys
import codecs
import argparse
from _pickle import load, dump
import collections
from utils import get_processing_word, is_dataset_tag, make_sure_path_exists, get_bmes
from fastNLP import Instance, DataSet, Vocabulary, Const
max_len = 0
def expand(x):
sent = ["<sos>"] + x[1:] + ["<eos>"]
... |
from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
import click, ktorrent, json, webbrowser
def colors():
enums = dict(
COUNT = 'white',
NAME = 'yellow',
SEED = 'green',
LEECH = 'red',
SIZE = 'cyan',
AGE = 'blue'
)
return type('Enum', (), enums)
def cap(s, l):
return s if len(s)<=l else s[0:l-3]+'...'
def check_stat... |
import numpy as _np
from netket import random as _random
from .abstract_sampler import AbstractSampler
from .metropolis_hastings import *
from .._C_netket import sampler as c_sampler
from numba import jit, int64, float64
from .._jitclass import jitclass
@jitclass([("clusters", int64[:, :])])
class _exchange_kernel:
... |
from socket import *
import _thread
import urllib.parse
import json
import datetime
import requests
serverPort = 8080
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(5)
print('The server is running')
def download_pictures(name, ip, file_name):
# TODO: verify... |
#!/usr/bin/env python
import unittest, time
from datetime import datetime, tzinfo, timedelta
from ephem import Date, localtime, to_timezone, UTC
millisecond = 1.0 / 24.0 / 60.0 / 60.0 / 1e3
class CET(tzinfo):
"""central european time without daylight saving time"""
def utcoffset(self, dt):
return ti... |
# -*- coding: utf-8 -*-
"""\
Copyright (c) 2015-2018, MGH Computational Pathology
"""
from calicoml.core.algo.cross_validation import CVSplitGenerator
from calicoml.core.algo.learners import SelectAndClassify
from calicoml.core.metrics import f_pearson, accuracy_from_confusion_matrix
from calicoml.core.pipeline.ml_r... |
import os
import requests
from .base import BaseAuthPlugin
class JupyterhubEnvironmentError(Exception):
pass
class JupyterhubApiError(Exception):
pass
def get_jupyterhub_user():
if os.getenv('JUPYTERHUB_USER'):
return os.environ['JUPYTERHUB_USER']
else:
raise JupyterhubEnvironment... |
"""
Functionality to update one PyScaffold version to another
"""
from enum import Enum
from functools import reduce, wraps
from itertools import chain
from types import SimpleNamespace as Object
from typing import TYPE_CHECKING, Callable, Iterable, Tuple
from configupdater import ConfigUpdater
from packaging.version ... |
#**********************************************************************
# Copyright 2020 Advanced Micro Devices, 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.or... |
# 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... |
# Imports from standard library
import os
from typing import Optional, Union
import asyncio
import time
import sqlite3
import hashlib
# Import these utilities
from utils.merkletree import MerkleTree, MerkleError
# Import the HTTP app server
from fastapi import FastAPI, BackgroundTasks
###############################... |
import discord
from discord.ext import commands
from decouple import config
from discord_slash import SlashCommand, SlashContext, cog_ext
DEVELOPING = False
class User():
def __init__(self, discordUser = None, whereToSendAlerts = None):
self.discordUser = discordUser
self.whereToSendAlerts = whereToS... |
import math
import csv
A = 0
ACD = 0
SF = 0
na=1.336
nc=1.333
V=12
VarsDictionary = []
def is_number(str):
try:
float(str)
return True
except ValueError:
return False
def getPowerIOL(a_const, eye_length, plan_refr, meridian1, meridian2):
pwiol = [0,0... |
#!/usr/bin/env python3
# Modify entropy_fast() however you like to make it faster
# Ideally, your method is faster at all ranges of window size
import math
import time
import random
def entropy_slow(seq, w, th):
t0 = time.perf_counter()
low_H_count = 0
for i in range(len(seq) - w + 1):
win = seq[i:i+w]
a, c,... |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
"""Defines an interface for contexts, which hold the core components that a
plugin will operate upon when running.
These include a `... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modif... |
from django.conf import settings
from django.template import Library, loader
from django.template.base import Node, NodeList, TemplateSyntaxError, token_kwargs
register = Library()
DEFAULT_FORM_FIELD_TAG = 'div'
#
# ifperm and ifnotperm are extremely similar to, and mostly copied directly
# from Django's ifequal an... |
from rest_framework.views import APIView, Response, Request
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.pagination import LimitOffsetPagination
from ApiRequesters.Auth.permissions import IsAuthenticated, IsAppTokenCorrect
from ApiRequesters.Auth.AuthRequester ... |
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.autograd import Variable, Function
#import torch.cuda
from pprint import pprint, pformat
import pickle
import argparse
import os
import math
import matplotlib.pyplot as plt
from pytorch_model import ProdLDA
#from pytorch_visualize imp... |
"""
NOTE: Observe SI units
"""
import numpy as np
import matplotlib.pyplot as plt
from time import sleep
# constants
PI = np.pi
gravity = 9.81
time_delta = 0.1
thrust = 800
class ObjectSpecs:
def __init__(self):
"""Physical objects involved, their characteristics and properties/specifications"""
... |
# coding: utf-8
import warnings
from datetime import datetime, timedelta
from pathlib import Path
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials
from googleapiclient.http import MediaFileUpload
def GetAPIService(credentials_path: str):
"""GoogleDriveの... |
import mimetypes
from boto.s3.connection import S3Connection, SubdomainCallingFormat
from boto.exception import S3ResponseError, S3CreateError
from boto.s3.key import Key
from flask import current_app
from .base import Storage, StorageException, StorageFile, reraise
class S3BotoStorage(Storage):
def __init__(
... |
#!/usr/bin/env python
"""Reads a LAMMPS Configuration File and adds N enzymes in
random positions within the box"""
import json
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist, squareform
from softnanotools.logger import Logger
logger = Logger(... |
import csv
import numpy
import tkinter as tk
from tkinter.filedialog import askopenfilename
reacttime = []
corratio = []
Standard_Deviation = []
# GUI
root = tk.Tk()
root.wm_title("11_Time_Perception")
root.geometry("700x200")
path=tk.StringVar()
w0=tk.Label(root, text='10_Delay_Discounting_Task',width=40... |
# -------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# -------------------------------------------------------------
# Modified by <NAME>
# NOTE: You'll need to compile the dependencies inside a docker container
# based on lamdba, otherwise you... |
import os
from copy import deepcopy
from typing import List, Union, Dict, Any
from overrides import overrides
from allennlp.common import Params
from allennlp.common.tee_logger import TeeLogger
from allennlp.common.util import prepare_environment
from allennlp.data import Vocabulary, Dataset, DataIterator, DatasetRe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/StructureDefinition) on 2019-07-29.
# 2019, SMART Health IT.
import sys
from dataclasses import dataclass
from typing import ClassVar, Optional, List
from .fhirabstractbase import empty_list... |
#! /usr/bin/env python
from queue import Queue
import argparse
import sys
import logging
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import Header
import time
import numpy as np
import scipy
from scipy import interpolate
import matplotlib.pyplot as plt
from roc.msg import Motion as MotionM... |
# _________________________________________________________________________
#
# PyUtilib: A Python utility library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the BSD License.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains ... |
#!/usr/bin/env python
# coding: utf-8
# Title: air_forecasting_service1.py
# Author: <NAME>
# Date: July 7, 2021
import logging
import os, re, shlex, sys
from typing import Iterator
logging.root.setLevel(logging.DEBUG)
logger = logging.getLogger("air")
def log(msg, *args, **kwargs):
text = msg
try:
... |
# <NAME>
# znalezienie liczby trójkątów w grafie
import algorithms.graph as graph
import numpy as np
# O(n^5)
def naive(vertices, edges, only_count=False):
def has_edge(i, j, edges):
for edge in edges:
if (edge[0] == i and edge[1] == j) or (edge[0] == j and edge[1] == i):
retu... |
import numpy as np
from util import *
'''
Server has list of authorized public key.
Client has public key and private key (unique to client).
Server has to make sure that the client who is in contact is authorized.
Authentication:
---------------
- Server selects a message.
- Encrypts with public key.
- ... |
import array
class bmp:
""" bmp data structure """
def __init__(self, w=1080, h=1920):
self.w = w
self.h = h
def calc_data_size (self):
if((self.w*3)%4 == 0):
self.dataSize = self.w * 3 * self.h
else:
self.dataSize = (((self.w * 3) // 4 + 1) * 4) * se... |
import Shadow
import numpy
# using mac oasys, for plots
# from srxraylib.plot.gol import set_qt
# set_qt()
#
# runs an absorber of 10 um thickness for a source at 10 keV
#
#
def run_example_lens(user_units_to_cm=1.0,npoint=5000,use_prerefl=0):
#
# Python script to run shadow3. Created automatically with Shad... |
from tensorflow import keras as K
def conv2d(x, filters, shape, padding="same", strides=(1, 1), activation="relu"):
"""
2D Convolutional layers with Batch Normalization
Arguments:
x: Keras layer, the input to the feature map
filters: Int representing the number of filters to use
... |
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import random
import numpy as np
import pkg_resources
from nle import nethack
from minihack.envs import register
from minihack import LevelGenerator, MiniHackNavigation
LEVELS_PATH = os.path.join(
pkg_resources.resource_filename("nle", "minihack/dat"),
... |
from wizard.asset import main as asset_core
from wizard.prefs.main import prefs
from wizard.tools import log
from wizard.vars import defaults
from wizard.asset.reference import references
from wizard.prefs import project as project_prefs
# from softwares.maya_wizard import create_ai_surface
import tools
import os
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.