content stringlengths 5 1.05M |
|---|
from math import sqrt
# Returns the closest unit cell type given atomic weight, radius and the comparation mass
# avogrado constant and input
Na = 6.022 * pow(10,23)
A = float(input("Provide the atomic weight: "))
R = float(input("Provide the atomic radius: ")) / (10 ** 7) # optimized for nanometers
# types of u... |
from flask import Flask, render_template
application = Flask(__name__)
@application.route('/')
def index():
navigasi = [
('/','Home'),
('/profile','Profile'),
('/product','Product'),
('/contact','Contact')]
return render_template('index.html', navigasi=navigasi)
@application.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# setup.py
# @Author : Zack Huang ()
# @Link : zack@atticedu.com
# @Date : 2021/03/16 下午2:03:50
import sdist_upip
from setuptools import setup
import sys
# Remove current dir from sys.path, otherwise setuptools will peek up our
# module instead of system's.
sys.path.... |
# coding: utf-8
from .base import BaseAPI, APISET
@APISET.register('asset_host')
class AssetHostAPI(BaseAPI):
def list(self):
'''cmd: get_assets
asset_type: host
filter: sort=name first=1 rows=1000'''
filter_str = "sort=name rows=-1"
params = {
"cmd": "get_asse... |
from __future__ import print_function, unicode_literals
import os
import re
import socket
import ssl
import ttfw_idf
def _path(f):
return os.path.join(os.path.dirname(os.path.realpath(__file__)),f)
@ttfw_idf.idf_example_test(env_tag='Example_WIFI')
def test_example_protocol_openssl_server(env, extra_data):
... |
import unittest
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
self.assertEqual(solution.winner([10, 10]), 'Sandy')
self.assertEqual(solution.winner([2, 2, 3]), 'Manasa')
if __name__ == '__main__':
unittest.main()
|
from distutils.core import setup
setup(
name = 'mcq_hammertime',
packages = ['mcq_hammertime'],
version = '0.13',
description = 'A GFM to HTML parser that adds interactive Multiple Choice question functionality.',
author = 'Johnny Chang',
author_email = 'johnny@johnnychang.com',
url = 'https... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.EGL import _types as _cs
# End users want this...
from OpenGL.raw.EGL._types import *
from OpenGL.raw.EGL import _errors
from OpenGL.constant import Constant as _C
import ctype... |
import requests
import json
class PyPantry:
def __init__(self, pantryID:str):
self.pantryID = pantryID
self.url = f"https://getpantry.cloud/apiv1/pantry/{self.pantryID}"
def get(self):
headers = {
'Content-Type': 'application/json'
}
response = requests.requ... |
# Copyright (c) 2019-2021 CRS4
#
# 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, modify, merge, publish, distribut... |
import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-bootstrap-admin',
version='0.3.2',
... |
""" Table to store the classifiers defined by every group
In this initial version:
- Every entry to the table is a set of classifiers associated to a group
- The definitions of all classifiers as stored as a json in the 'bundle' column
- Notice that the definition of classifier follows a
"""
import sq... |
"""
Test cases for the regi0.geographic.utils.create_id_grid function.
"""
import numpy as np
import pytest
from regi0.geographic.utils import create_id_grid
@pytest.fixture(scope="module")
def matching_grid():
return create_id_grid(-1.0, -1.0, 2.0, 4.0, 0.25)
@pytest.fixture(scope="module")
def unmatching_gri... |
from pact_testgen.generator import generate_tests
from pact_testgen.dialects.django import Dialect
def test_django_test_generator_output_is_parsable(testfile):
test_file, _ = generate_tests(testfile, Dialect())
compile(test_file, "<string>", "exec")
def test_output_includes_expected_test_cases(testfile):
... |
import logging
from pathlib import Path
import hydra
import pytorch_lightning as pl
import torch
from omegaconf import DictConfig
from src.backend.base import BackendBase
from src.models.sst_model import SSTModel
from src.utils import utils
logging.basicConfig()
log = utils.get_logger(__name__)
log.setLevel(logging.... |
#!/usr/bin/python3
from glob import glob # file enumeration
from datetime import datetime # date handling
import mistune # markdown parsing/rendering
template = open("template.html", "r").read()
posts = [] # will hold all the information about blog posts
markdown = mistune.Markdown(escape=False) # escape=False mean... |
import django_filters.rest_framework as filters
from .models import Monster, SkillEffect, Skill, LeaderSkill, ScalingStat
class MonsterFilter(filters.FilterSet):
name = filters.CharFilter(method='filter_name')
element = filters.MultipleChoiceFilter(choices=Monster.ELEMENT_CHOICES)
archetype = filters.Mul... |
import sys
sys.path.append('../..')
import os
import json
import logging
import argparse
import numpy as np
from datetime import datetime
from seqeval import metrics
from seqeval.scheme import IOB2
from data_constr.Src.IO import set_logging
logger = logging.getLogger(__name__)
_time = datetime.now().strftime("%m.%d.... |
import json
import shutil
from datetime import datetime
from pathlib import Path
from jinja2 import Template
from services.meal_services import MealPlan
from services.recipe_services import Recipe
from services.settings_services import SiteSettings, SiteTheme
from app_config import BACKUP_DIR, IMG_DIR, TEMP_DIR, TEMPL... |
def bubbleSort(customList):
for i in range(len(customList)-1): #----> O(n)
for j in range(len(customList)-i-1): #----> O(n)
if customList[j] > customList[j+1]:
customList[j] , customList[j+1] = customList[j+1], customList[j]
return customList
cList = [5,9,3,1,2,8,4,7,6]
pri... |
import os,shutil,glob
def alter_dir(src,dst):
if os.path.exists(dst):
shutil.rmtree(dst)
os.makedirs(dst)
fs=glob.glob(src+'/*.jpg')
for i,f in enumerate(fs):
name=os.path.basename(f)
f2=dst+'/'+name.replace('.jpg','_car0.jpg')
shutil.copy(f,f2)
print(i,f,f2)
def... |
"""
c17.py
Cryptopals Set 3, Challenge 17
"""
def main():
return 0
|
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyTinycss2(PythonPackage):
"""tinycss2 is a low-level CSS parser and generator written in ... |
# Credit to https://github.com/KaiyangZhou/deep-person-reid
from .accuracy import accuracy # noqa
from .rank import evaluate_rank # noqa
|
import os
import logging
import boto3
import urllib.request
import zipfile
from collections import OrderedDict
import numpy as np
import pandas as pd
from sqlalchemy import func
from dataactcore.logging import configure_logging
from dataactcore.config import CONFIG_BROKER
from dataactcore.interfaces.db import GlobalD... |
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
dp = [0] * 60
output = 0
for t in time:
reminder = t % 60
target = (60 - reminder) % 60
output += dp[target]
dp[output] += 1
return output
|
import pytest
from .. import util
from ..common import LoadContext
from ..gateway import (AccessSecurity, AliasRule, AllowRule, DenyRule,
GatewayConfig, PVList, PVListMatch, PVListMatches)
from .conftest import MODULE_PATH
@pytest.fixture
def kfe_pvlist():
return PVList.from_file(
... |
import matplotlib.pyplot as plt
from matplotlib import animation
class Tensor:
def __init__(self,data,left=None,right=None,op = None):
self.data = data
self.grad = 0
self.left = left
self.right = right
self.op = op
def __add__(self, other):
data = self.data +... |
import logging
import logging.config
from src import settings
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"correlated": {
"()": "uvicorn.logging.DefaultFormatter",
"format": "%(levelprefix)s [%(name)s:%(lineno)s] %(message)s",
... |
#!/usr/bin/python3
from __future__ import print_function
import os.path
import pandas as pd
import mrcfile
from proteinpy.structure import Structure
from proteinpy.contact import Contact
from proteinpy.network import Network
from proteinpy.electron_density import ElectronDensity
class Parser:
"""Parse a PDB/DSSP... |
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from mayan.apps.acls.models import AccessControlList
from mayan.apps.documents.models import Document
from mayan.apps.documents.serializers.document_serializers import DocumentSerializer
from .models import DocumentCheckou... |
# The data we need to retrieve
# 1. The total number of votes cast
# 2. A complete list of candidates who received votes
# 3. The perecntage of votes each candidate won
# 4. The total number of votes each candidate won
# 5. The winner of the election based on popular vote
###
# # Assign a variable for the file to loa... |
import base64
from django.core.management import call_command
from django.test import Client
from django.urls import reverse
from corehq.apps.domain.utils import clear_domain_names
from tastypie.models import ApiKey
from corehq.apps.accounting.models import (
BillingAccount,
DefaultProductPlan,
SoftwareP... |
from django.views.generic.base import View
from utils import json_response
class ReferralsView(View):
@staticmethod
def get(request):
'''Retrieve all referrals.'''
data = []
if request.GET['incoming'] == 'true':
data = [
{
'id':... |
from django.urls import path
from books.views import add_book, details_book, edit_book, delete_book, BooksListView
urlpatterns = [
path('add/', add_book, name='add book'),
path('details/<int:pk>/', details_book, name='details book'),
path('edit/<int:pk>/', edit_book, name='edit book'),
path('delete/<i... |
"""File that summarizes all key results.
To train and analyze all models quickly, run in command line
python paper.py -d=0 --train --analyze --testing
To reproduce the results from paper, run
python paper.py -d=0 --train --analyze
To analyze pretrained networks, run
python paper.py -d=0 --analyze
To run specific ex... |
import matplotlib.pyplot as plt
import numpy as np
from lms_code.analysis.run_bem import get_slip_magnitude
import lms_code.lib.rep2 as rep2
import lms_code.plots.plot_all as lms_plot
def main():
lms_plot.setup()
fig = plt.figure()
which_model = 'all_details'
bem_soln = rep2.load('bem_' + which_model)... |
import numpy as np
DOMAINS = {
"N-term": [30, 43],
"TM1": [44, 86],
"EL1": [87, 91],
"TM2": [92, 153],
"IL1": [154, 163],
"TM3": [164, 206],
"EL2": [207, 207],
"TM4": [208, 263],
"IL2": [264, 265],
"TM5": [266, 319],
"EL3": [320, 323],
"TM6": [324, 366],
"TN1": [367,... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import json
import sys
from optparse import OptionParser
options = OptionParser(usage='%prog recording.json [options]', description='Converter for asciicast (asciinema recording) to vector graphic')
options.add_option('-s', '--start', type='int', default=-1, help='Start... |
#!/usr/bin/env python
from collections import deque
def breadth_first_search(graph, start):
search_queue = deque()
search_queue += start
visited = set()
while search_queue:
node = search_queue.popleft()
for each in graph[node]:
if each not in visited:
sea... |
import os.path
from deployer import Deployer
# This script expects that the following environment vars are set:
#
# AZURE_TENANT_ID: with your Azure Active Directory tenant id or domain
# AZURE_CLIENT_ID: with your Azure Active Directory Application Client ID
# AZURE_CLIENT_SECRET: with your Azure Active Directory Appl... |
import influxdb_client
import pandas as pd
from configs import config
class Measurements:
def __init__(self) -> None:
self.client = influxdb_client.InfluxDBClient(
url=config["influx"]["host"],
token=config["influx"]["token"],
org=config["influx"]["org"]
)
... |
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def page(query_set,request):
paginator = Paginator(query_set,5)
page = request.GET.get('page')
try:
page_query = paginator.page(page)
except PageNotAnInteger:
page_query = paginator.page(1)
except EmptyPage:
page_query = paginator.page(... |
'''
Utility classes for testing
'''
from django.test import TestCase
from django.contrib.auth.models import User
from ...posts.models import Post
from ..models import Organization
class BaseTestOrganizations(TestCase):
def setUp(self):
'''
Must follow this order
'''
self.owner = s... |
import numpy as np
class LogisticRegression:
def __init__(self, learning_rate, n_iters):
self.learning_rate = learning_rate
self.n_iters = n_iters
self.weights = None
self.bias = None
def fit(self, features, target):
# initalize weights and bias
n_samples, n_fe... |
from setuptools import setup # type: ignore
# Old way. Will be deleted.
# def _get_version():
# """Get the version but do not import the package."""
# with open(os.path.join(os.path.dirname(__file__), 'bomberman', 'version.py')) as version_file:
# return re.compile(r"^__version__ = '(.*?)'", re.S).ma... |
from .plotHandler import *
from .spatialPlotters import *
from .hourglassPlotters import *
from .onedPlotters import *
from .ndPlotters import *
from .specialPlotters import *
from .neoDistancePlotter import *
from .plotBundle import *
from .twoDPlotters import *
from .moPlotters import *
from .perceptual_rainbow impor... |
from generate import *
from datetime import datetime
def main():
''' e.g.
python ./generate.py --length=512
--nsamples=1
--prefix=[MASK]哈利站在窗边
--tokenizer_path cache/vocab_small.txt
--topk 40 --model_path model/model_epoch29
--save_samples --save_samples_path result/20210915_29_1135
... |
import logging
from datetime import datetime
from sqlalchemy.exc import IntegrityError
from haikubot import config
from haikubot.commands.commands import Commands
from haikubot.model.haiku import Haiku
from haikubot.utils.color import string_to_color_hex
from haikubot.utils.haiku_parser import is_haiku
from haikubot.... |
# Copyright Notice:
# Copyright 2018 Dell, Inc. All rights reserved.
# License: BSD License. For full license text see link: https://github.com/RedDrum-Redfish-Project/RedDrum-Simulator/LICENSE.txt
# BullRed-RackManager managersBackend resources
#
class RdManagersBackend():
# class for backend managers re... |
import requests, os, shutil, stat, struct
from sys import platform
def getPathDriver(config):
# Figure out the system platform
if platform == "linux" or platform == "linux2":
sys_platform = 'linux'
elif platform == "darwin":
sys_platform = 'macos'
elif platform == "win32":
sys_platform = 'windows'
# Figur... |
#!python
from __future__ import with_statement
import glob
import os.path
import shutil
import zipfile
def isFileEntry(s):
return s[-1] != '/'
def readFile(fname):
with open(fname, 'rb') as f:
return f.read()
def writeFile(fname, data):
with open(fname, 'wb') as fo:
fo.write(data)
def mkdirs(path):
try:
... |
def resolve():
'''
code here
'''
grid = [[int(i) for i in input().split()] for _ in range(3)]
is_flag = True
for i in range(3):
A = grid[0][i-1] -grid[0][i]
C = grid[2][i-1] -grid[2][i]
B = grid[1][i-1] -grid[1][i]
if A == B and B == C:
pass
... |
#! python3
"""Transforms text to a markdown bulleted list based on indentation.
Contains:
`bullet_list(text: str) -> list[str]`
: Converts the text passed to it into a markdown list.
: Each item in list is a line of the text ending in a newline.
`from_clipboard() -> None`
: Takes text ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/4 上午10:49
# @Author : Dicey
# @File : AWSAutoTagTotal3.0.py
# @Software: PyCharm
from __future__ import print_function
import json
import boto3
import logging
from AWSAutotagTotal import awstaglib
logger = logging.getLogger()
logger.setLevel(loggin... |
class Movie:
def __init__(self, movie_id, movie_title, release_date):
self.movie_id = movie_id
self.movie_title = movie_title
self.release_date = release_date
self.ratings = {}
def __str__(self):
return "Movie ID: {} Movie Title {}".format(self.movie_id, self.movie_title... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_... |
if __name__ == '__main__':
import os
import torch
import numpy as np
from options import TestOption
from pipeline import CustomDataset
from networks import Generator
from utils import Manager, binning_and_cal_pixel_cc
from torch.utils.data import DataLoader
from tqdm import tqdm
... |
class Term(object):
def __init__(self, **kwargs):
self._name = kwargs.get('name', None)
self._type = kwargs.get('type', None)
self._value = kwargs.get('value', None)
@property
def name(self):
return self._name
@property
def type(self):
return self._type... |
import time
import bpy
import mathutils
class RootMotionData(bpy.types.PropertyGroup):
hip = bpy.props.StringProperty(name="Hip Bone")
root = bpy.props.StringProperty(name="Root Bone")
copy = bpy.props.StringProperty(name="Debug Character")
step = bpy.props.IntProperty(name="Step Size", default=3, min... |
class Urls(SQLObject):
class sqlmeta:
fromDatabase = True
class Badurls(SQLObject):
class sqlmeta:
fromDatabase = True
class Word(SQLObject):
class sqlmeta:
fromDatabase = True
class Semanticlist(SQLObject):
class sqlmeta:
fromDatab... |
################################################################################
# #
# Copyright (c) 2015 Cisco Systems #
# All Rights Reserved. ... |
import os
import sys
import re
import pickle
from typing import Union
import numpy as np
import pandas as pd
from scipy import stats, ndimage, io
import itertools
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sns
import random
from sklearn.decomposition import PCA
import tifffi... |
"""This is an experimental implementation of cc_shared_library.
We may change the implementation at any moment or even delete this file. Do not
rely on this. It requires bazel >1.2 and passing the flag
--experimental_cc_shared_library
"""
load("//cc:find_cc_toolchain.bzl", "find_cc_toolchain")
# TODO(#5200): Add ex... |
import numpy as np
from numpy.linalg import norm
import h5py as hp
import subprocess
import os
class WrapperCelestlab:
"""Object to run selectal from python"""
def __init__(self, scilab_path=None, celestlab_loader="loader_celestlab.sce"):
self.celestlab_loader = celestlab_loader
if not os.... |
'''
researcher.py: representation of an researcher record
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2019 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" f... |
from pyramid import threadlocal
from abc import abstractproperty
from sqlalchemy import and_, or_, asc, orm, event
from sqlalchemy_utils import get_hybrid_properties
from sqlalchemy.ext.declarative import declared_attr
import json
from ..core import Base
from ..GenericObjets import BusinessRules
from .frontmodules imp... |
from utils import cache
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
if __name__ == '__main__':
with Connection(cache):
worker = Worker(map(Queue, listen))
worker.work()
|
import os
import datetime
import json
import magic
import shutil
from pathlib import Path
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, kmlgen, is_platform_windows
def get_instagramDevices(files_found, report_folder, seeker, wrap_text):
for file... |
# Copyright (c) 2021, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... |
from celery import Celery
from celery.schedules import crontab
import utils
from main import rdb
task = Celery('tasks',
broker='redis://localhost:6379/0',
backend='redis://localhost:6379/0')
task.conf.timezone = 'UTC'
'''
@task.task
def function():
...
'''
@task.on_after_configure.c... |
import pyotp
import base64
from datetime import datetime
from django.core.mail import EmailMessage
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response import Response
from rest_framework import generics
from rest_framework.views import API... |
import taichi as ti
@ti.kernel
def from_torch_template(expr: ti.template(), torch_tensor: ti.ext_arr()):
for i in expr:
expr[i] = torch_tensor[i]
@ti.kernel
def to_torch_template(expr: ti.template(), torch_tensor: ti.ext_arr()):
for i in expr:
torch_tensor[i] = expr[i]
def from_torch(expr, torch_tenso... |
import mido
with mido.open_input('New Port', virtual=True) as inport:
for message in inport:
print(message) |
import os
modules = ["youtube-dl", "pafy"]
print("""
This file will simply install ever pip package needed to use Andromeda
""")
input("Press Enter to Continue: ")
for module in modules:
os.system(f"pip install {module}")
input("Press Enter to Exit: ")
|
from cloudsigma.version import __version__
from cloudsigma import bulk
from cloudsigma import conf
from cloudsigma import errors
from cloudsigma import generic
from cloudsigma import resource
from cloudsigma import scenarios
from cloudsigma import metadata
|
import random
import shutil
import piexif
from matplotlib import pyplot as plt
from keras.applications.vgg16 import VGG16
from keras.models import Model
from keras.layers import Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator
INPUT_SIZE = 128
# Do not import fully connected layers
vgg16 =... |
import os
fauvel = open('FauvPieces.txt','r')
for piece in fauvel:
os.system(piece)
fauvel.close()
ivtrem = open('IvTremPieces.txt', 'r')
for piece in ivtrem:
os.system(piece)
ivtrem.close() |
# coding:utf-8
# 训练模型的代码
from time import *
import torch
import torchvision.transforms as transforms
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader
from tools.my_dataset import MyDataset
from tools.iresnet import get_model
from tools.margin_softmax import ... |
from django.urls import reverse
ANONYMIZABLE_EVENTS = (
"added_participant",
"changed_owner",
"owner_left",
"removed_owner",
"participant_left",
"removed_participant",
)
def anonymize_event(user, event):
if event.event_type not in ANONYMIZABLE_EVENTS:
raise ValueError('event of ty... |
from datetime import datetime
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class UserFiles(models.Model):
class Meta:
verbose_name = "用户文件"
verbose_name_plural = "用户文件"
ordering = ['-last_submit_time'... |
import logging
import os
# prints log to stdout and also saves to specified log file
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
def directory_maker(path): # makes directory if path does not exists
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs... |
# coding=utf-8
import socket
# target_host = "www.baidu.com"
target_host = "127.0.0.1"
target_port = 80
# 建立一个socket对象(AF_INET:使用标准IPV4地址和主机名, SOCK_STREAM: TCP客户端)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接客户端
client.connect((target_host, target_port))
# 发送一些数据
client.send("GET / HTTP/1.1\r\nH... |
"""
This module provides wrapper functions for plot with matplotlib.
By using with other modules in "matdat" and "matpos", you can separate actions of plot
from data and layouting.
Functions
---------
set_tick_params
set_labels
set_grid
set_xlim
set_ylim
line
scatter
vlines
hlines
box
factor_box
factor_violin
vel... |
"""Auto-generated file, do not edit by hand. MY metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_MY = PhoneMetadata(id='MY', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='[1369]\\d{2,4}', possible_length=(3, 4,... |
# -*- coding: utf-8 -*-
import os
import sima
from sima.ROI import ROIList
import numpy as np
def extract(fpath):
fdir = os.path.split(fpath)[0]
fname = os.path.splitext(os.path.split(fpath)[1])[0]
sima_mc_path = os.path.join(fdir, fname + '_mc.sima')
if not os.path.exists(sima_mc_path):
r... |
import jax.numpy as jnp
from jax import grad, hessian, jit, random
from jax.flatten_util import ravel_pytree
from jax.experimental.optimizers import l2_norm
from jax.nn import softmax
from jax.nn import log_softmax, logsumexp
key = random.PRNGKey(0)
def sigmoid(x):
return 0.5 * (jnp.tanh(x / 2) + 1)
# Outputs prob... |
"""
This module provides functionality for plotting in jupyter (http://jupyter.org/) notebooks
based on dygraphs (http://dygraphs.com/) and pandas (https://pandas.pydata.org/).
"""
import json
import uuid
import pandas
from IPython.display import HTML
def dygraphplot(*dataframeandoptions):
"""
Plots the given... |
# Numpy and Maths
import numpy
import math
# Tensorflow
import tensorflow
def delete_nans_in_data(array):
length = len(array)
i = 0
while i != length:
if i >= len(array):
i += 1
continue
if math.isnan(numpy.min(array[i])) is True:
array = numpy.delete(ar... |
#! python3
"""
pisat.core.logger.sensor_controller
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A controller of multiple Sensor and Adapter classes.
This class integrates Sensor and Adapter classes and
control as two types of classes make cooperation.
This means that SensorController operates some kind of
transaction about... |
import socket
import time
import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing
from CondCore.CondDB.CondDB_cfi import *
from Configuration.AlCa.autoCond import autoCond
options = VarParsing.VarParsing()
options.register('connectionString',
'frontier://FrontierPr... |
import config
import torch
import flask
import time
from flask import Flask
from flask import request
from model import BERTBaseUncased
import functools
app = Flask(__name__)
MODEL = None
DEVICE = "cuda"
PREDICTION_DICT = dict()
def sentence_prediction(sentence):
tokenizer = config.TOKENIZER
max_len = con... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.5.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + [markdown] run_control={"frozen": false, "read_only... |
"""nturesell URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... |
import torch
import torch.nn as nn
import numpy as np
import logging
import pytorch_lightning as pl
import sys
from lifelines.utils import concordance_index
from sklearn.metrics import r2_score
from torch.utils.data import DataLoader, TensorDataset
from torchcontrib.optim import SWA
from imblearn.over_sampling import ... |
import os
import uuid
import boto3
import moto
import pytest
from commercetools_token_refresher.rotator import TokenRotator
@moto.mock_secretsmanager
def test_rotator_not_enabled_rotation():
"""Super basic test, should be expanded."""
secret_name = "mock/ct-access-token"
secrets_manager = boto3.client(
... |
import os
import re
import sys
import lxml.etree
'''
This script takes SDL2 doxygen documentation and annotates the members with it.
How to use:
1. Clone the libsdl repository
2. Go into the docs folder, open the doxyfile and add this line:
GENERATE_XML=YES
3. Run doxygen
4. Amalgate the generated XML using the c... |
"""Module & package import."""
from flask import (
Blueprint,
render_template,
url_for,
redirect,
flash,
request,
)
from flask_login import login_required
from online_store import db
from online_store.forms import AddProductForm
from online_store.admin.utils import admin_required
from online_sto... |
from __future__ import print_function
import argparse
import sys
import os.path
from glob import glob
import ssg.build_yaml
class ResolvableProfile(ssg.build_yaml.Profile):
def __init__(self, * args, ** kwargs):
super(ResolvableProfile, self).__init__(* args, ** kwargs)
self.resolved = False
... |
""" runner script to investigate mode preconditioner """
import os
from math import pi
import xml.etree.ElementTree as ET
import platform_paths as pp
import manipulator as ma
# load parameter file
TREE = ET.parse('../XML/parameterSHL.xml')
ROOT = TREE.getroot()
ma.set_parameter(ROOT, 'withoutput', 1)
# make executa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.