text stringlengths 3.07k 12.6k |
|---|
"""
django_adtools/discover_dc.py
This script discovers for domain controllers in domain
REQUIREMENTS:
pip install dnspython
"""
__author__ = "shmakovpn <<EMAIL>>"
__date__ = "2020-03-04"
from typing import List, Optional, Pattern
import re
import dns.resolver
import socket
import logging
#: Pattern to match IPv... |
# scenario name for log file
scenario_name = "ramp"
# material parameters
# --------------------
sigma_f = 8.93 # [mS/cm] conductivity in fiber direction (f)
sigma_xf = 0 # [mS/cm] conductivity in cross-fiber direction (xf)
sigma_e_f = 6.7 # [mS/cm] conductivity in extracellula... |
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is... |
"""
成绩管理系统程序
运行后,使用浏览器打开http://localhost:5050/
需要flask、matplotlib、peewee库
"""
from decimal import Decimal
from peewee import *
import io
from flask import Flask, render_template, request, Response
import csv
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Fi... |
import dateparser
from datetime import datetime
import logging
import requests
from SearchAPI.asf_env import get_config
def input_fixer(params):
"""
A few inputs need to be specially handled to make the flexible input the
legacy API allowed match what's at CMR, since we can't use wildcards on
additio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on %(date)s
@author: %(username)s
"""
import numpy as np
from astropy import constants
from matplotlib import pyplot as plt
from scipy.interpolate import PchipInterpolator, interp1d
def sinebell(n=1000, index=0.5):
""" sine bell to left & right end of ... |
#!/usr/bin/env python3
import argparse
import gzip
import json
import logging
import sys
import os
import transcriber.settings as settings
from transcriber.messages import IpalMessage
from state_extractors.utils import get_all_state_extractors
# Wrapper for hiding .gz files
def open_file(filename, mode):
if file... |
import numpy as np
import tensorflow as tf
from tf_lite import Model
import cv2
import random
import colorsys
from functools import wraps
from flask import request, jsonify, current_app
import jwt
from app.models import User
model = None
labels = {}
iou = 0.45
score = 0.3
input_size = 416
def token_required(f):
... |
import os
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
from data import Tree
import utils
class TemplateChildrenEncoder(nn.Module):
def __init__(self, feat_len, hidden_len, symmetric_type, max_part_per_parent):
super(T... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import tempfile
import atexit
import operator
import os
from types import MethodType
import h5py
from allel.compat import reduce
from allel.chunked import util as _util
def h5fmem(**kwargs):
"""Create an in-memory HDF5 fi... |
"""
Asteroid.py
Main class of the Asteroid GAME
"""
import random
try:
import simplegui
except ImportError:
import SimpleGUICS2PyGAME.simpleguics2pygame as simplegui
CANVAS_SIZE = (700, 500)
BG_IMG = Util.ImgData("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_brown.png... |
from __future__ import unicode_literals
from builtins import object
from crispy_forms import layout
from crispy_forms.helper import FormHelper
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy
from django import forms
from cradmin_legacy.cr... |
#
# Marvelous Morse Mentor
# Copyright 2021-2022 <NAME>
# Licensed under the Apache License 2.0 (see the LICENSE file for details)
#
import json
import time
import random
import morse
import state_manager
import util
LEARN_STATE_FILE_NAME="/data/learn-state.json"
# The possible substates
STATE_HELLOING="HELLOING"
S... |
#!/usr/bin/env python
#
# Copyright (c) 2016 MIT. All rights reserved.
#
# author: <NAME>
# e-mail: <EMAIL>
# website: people.csail.mit.edu/psantana
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Re... |
"""Automation back-end with screen capture and programmatical user input.
Normally, this is used with functions in `concur.testing`.
"""
from __future__ import absolute_import
import glfw
import imgui
import time
import OpenGL.GL as gl
# Save as video
from PIL import Image
import imageio
import numpy as np
from co... |
#!/usr/bin/env python
from __future__ import (print_function, division, unicode_literals, absolute_import)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import argparse
from astropy import log
from nicer.values import *
from astropy.table import Table, vstack
import astropy.units as u
from... |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
np.random.seed(0)
sns.set_style('whitegrid')
# TODO Transfer everything to Jupyter Notebook for easier testing
def to_binary(n, N):
"""
Get binary representation of input n
:param n: Integer of which to get binary representation
... |
from abridger.exc import RelationIntegrityError
from abridger.extraction_model import Relation
class ForeignKeyConstraint(object):
def __init__(self, name, src_cols, dst_cols):
# Check table is the same within the src/dst columns & len matches
assert len(set([c.table.name for c in src_cols])) == 1... |
#!/usr/bin/env python
##############################################################################
#
# diffpy.srxplanar by DANSE Diffraction group
# <NAME>
# (c) 2010 Trustees of the Columbia University
# in the City of New York. All rights reserved.
#
# File co... |
#!/usr/bin/python3
import sys
import os
import getopt
import yaml
import subprocess
# CONSTANTS you may need to change:
DEFAULT_DOMAIN_NAME = 'dev.uniresolver.io'
UNIVERSAL_RESOLVER_FRONTEND_TAG = "universalresolver/uni-resolver-frontend:latest;"
def initDeploymentDir(outputdir):
# if os.path.exists(outputdir + '/... |
from pandas import DataFrame
import numpy as np
import nltk
from collections import Counter
from collections import OrderedDict
from sklearn.feature_extraction.text import TfidfVectorizer
def extract_sim_words(model, brand, result_path, freq_dist, min_count, save=True, topn=20):
df = DataFrame(columns=[['word', 's... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
from datetime import timedelta, date, datetime
from django.utils.text import slugify
from django.db import models
from django.urls import reverse
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext as _
from django.db.models import Q
from dja... |
#!/usr/bin/env python
"""Package: mininet
Test creation and pings for topologies with link and/or CPU options."""
import unittest
from functools import partial
from mininet.net import Mininet
from mininet.node import OVSSwitch, UserSwitch, IVSSwitch
from mininet.node import CPULimitedHost
from mininet.link import... |
import pytest
import dbdust.dumper as dumper
@pytest.mark.parametrize(
"host,port,database,username,password,"
"authentication_database,authentication_mechanism",
[
("hostname", None, None, None, None, None, None),
(None, 123, None, None, None, None, None),
(None, None, "database"... |
# coding: utf-8
# Script for training TSFN
#
# Reference:
# Hyperspectral Image Super-Resolution via Deep Prior Regularization with Parameter Estimation
# <NAME>, <NAME>, <NAME>, <NAME>
#
# 2019/05
# Implemented by
# <NAME>
# <EMAIL>
from __future__ import division
import torch
import torch.nn as nn
import torch.opt... |
import datetime
import json
import os
from typing import Dict, Union
from django.core.exceptions import ValidationError
from django.core.files import File
from django.utils import timezone
from django.utils.text import get_valid_filename
from rest_framework import status
from django.db.models.functions import Substr
... |
from flask import Flask, render_template, request, redirect
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/imgs'
app.config['ENCRYPTED_FOLDER'] = 'static/encrypted'
app.config['DECRYPTED_FOLDER'] = 'static/decrypted'
app.config['KEYS'] = 'static/keys'
@app.route('/')
def main():
return re... |
"""This is a cog for a discord.py bot.
It adds some commands to print youtube / discord stats
Commands:
stats print yt subs + discord members
├ users print stats about discord members
└ channels print stats about discord channels
Only users that have an admin role can use the comman... |
from pathlib import Path
import tkinter as tk
from tkinter import ttk, filedialog
from PIL import Image, ImageTk
import cv2 as cv
from cv2 import threshold
from utils.methods import scale_dim
import matplotlib.pyplot as plt
class FrameHistogramImage(tk.Frame):
CANVAS_SIZE = (200, 200)
CANVAS_BK_COLOR = "#31700... |
# Utilities for scrubbing/filtering stack traces
# 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... |
import pytest
from unittest.mock import PropertyMock
from unittest.mock import patch
from notifications_utils.template import (
Template,
SMSMessageTemplate,
SMSPreviewTemplate,
WithSubjectTemplate
)
def test_class():
assert repr(
Template({"content": "hello ((name))"})
) == 'Template(... |
import numpy as np
import pandas as pd
import torch
from scipy.optimize import minimize
from scipy.special import loggamma, expit
from torch.nn.functional import log_softmax
from sim.Sample import get_batches
from sim.best_models import extract_best_run
from sim.EBayDataset import EBayDataset
from analyze.util import s... |
""" The font class module.
Author:
- 2020-2021 <NAME>
- 2020-2021 <NAME>
Copyright:
2020-2021 <NAME> <<EMAIL>>
2020-2021 <NAME> <<EMAIL>>
License:
MIT/X11 License (see
:download:`license.txt <../../../license.txt>`)
"""... |
from django.db import models
from MCS.models import Member
from PSMS.models import Pizza
import django.utils.timezone as timezone
from django.core.validators import MaxValueValidator, MinValueValidator
class Order(models.Model):
order_no = models.AutoField(
verbose_name='訂單編號', null=False, primary_key=True... |
import requests
import hashlib
import json
import random
from enum import Enum
ERROR_DICT = {
'1001': 'Translate API: Unsupported language type',
'1002': 'Translate API: Text too long',
'1003': 'Translate API: Invalid PID',
'1004': 'Translate API: Trial PID limit reached',
'1005': 'Translate API: P... |
import os
import pickle
from argparse import Namespace, ArgumentParser
from pkg_resources import resource_filename
from patent_parsing_tools import Supervisor, WordCount, Patent
from patent_parsing_tools.utils.log import log, log_timer
@log
class BagOfWords:
def __init__(self, dictionary_name):
"""
... |
import argparse
import rdflib
from rdflib import Graph, RDFS
def getRelDict(graph):
rel = dict()
counter = 0
for triple in graph:
s,p,o = triple
if str(p) not in rel and isinstance(o, rdflib.URIRef):
rel[str(p)] = counter
counter += 1
return rel
def get_attr_set(graph):
attr_set = set()
for triple in... |
# Copyright (c) 2021, <NAME>
# License: MIT License
import pytest
import ezdxf
from ezdxf.layouts import VirtualLayout
from ezdxf.tools.text_size import text_size, mtext_size
from ezdxf.tools.text_layout import leading
# Exact text size checks are not possible if the used font is not available,
# which cannot guar... |
import numpy
import pyscf
from pyscf import scf, ao2mo
from pyscf.scf import hf
import jax.ops
from jax import grad
import jax.numpy as np
import jax.scipy as scipy
from jax.scipy.optimize import minimize
from jax.config import config
config.update("jax_enable_x64", True)
mol = pyscf.M(
atom = 'H 0 0 0; H 0 0 1.1'... |
from typing import Any as _Any, Dict, List, Union
from urllib.parse import quote as _quote
from xml.etree import ElementTree as _ElementTree
from . import format as _format
from . import parse as _parse
import pss_data as _pss_data
import pss_lookups as _lookups
from typehints import EntitiesData
# ---------- Typeh... |
#!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
# This file was written by <NAME>
# See https://github.com/oKermorgant/simple_launch
from os.path import basename, exists, join, splitext, exists
from imp import load_source
from ros2run.api import get_executable_path
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescri... |
from random import choice, randint
from debug import debug
import pygame
from particles import AnimationController
from settings import *
from support import import_csv_layout, import_folder
from tile import Tile
from player import Player
from ui import UI
from weapon import Weapon
from enemy import Enemy
from magic im... |
import pytest
import brownie
# These tests could probably be improved by either:
# Property Based Testing: https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-property.html#hypothesis
# Stateful Testing: https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html
# But I need to read more fir... |
import atexit
import html
import os
import pathlib
import re
import shutil
import stat
import subprocess
import sys
import tempfile
from mako.lookup import TemplateLookup
pagelist = [
("index.html", "Akuli's Git Guide", "Front page"),
("getting-started.html", "Getting started", "installing Git, making and cl... |
"""
Route groups are classes that allow you to group a set of routes together.
.. currentmodule:: kyoukai.routegroup
"""
import collections
import inspect
import typing
def get_rg_bp(group: 'RouteGroup'):
"""
Gets the :class:`~.Blueprint` created from a :class:`~.RouteGroup`.
"""
return getattr(group... |
from rpytest import ft
import pytest
# C++ check functions
getBaseOnly = ft.IBase.getBaseOnly
getBaseAndChild = ft.IBase.getBaseAndChild
getBaseAndPyChild = ft.IBase.getBaseAndPyChild
getBaseAndChildFinal = ft.IBase.getBaseAndChildFinal
getBaseAndGrandchild = ft.IBase.getBaseAndGrandchild
class PyIBase(ft.IBase):
... |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# justice-platform-service (4.10.0)
# pylint: disabl... |
import pytest
import os
from polyglotdb import CorpusContext
def test_subset_enrichment(acoustic_config):
syllabics = ['ae', 'aa', 'uw', 'ay', 'eh', 'ih', 'aw', 'ey', 'iy',
'uh', 'ah', 'ao', 'er', 'ow']
phone_class = ['ae', 'aa', 'd', 'r']
with CorpusContext(acoustic_config) as c:
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : runNCG.py
@Time : 2022/01/07 00:05:37
@Author : <NAME>
@Version : 1.0
@Desc : None
'''
#%%
from initialization import *
import numpy as np
import pandas as pd
import time
import os
import random
# %% Newton-CG method
def cg(obj, grad, tol... |
# @Author: <NAME>
# @Date: Tue, March 31st 2020, 12:36 am
# @Email: <EMAIL>
# @Filename: utils.py
'''
'''
# import pdb;pdb.set_trace();print(__file__)
import os
import itertools
from collections import defaultdict, OrderedDict
def create_session(target='', gpus='0,1,2,3', timeout_sec=10):
'''Create an in... |
#!/usr/bin/env python3
# This pre-commit hook script basically does four things:
# 1. Format staged C/C++ code
# 2. Format staged Python code
# 3. Transform LaTeX math equation in README.raw.md to image url in README.md
# 4. Append content of TODO.md and CHANGELOG.md to README.md
# 5. Generate TOC for README.md
# TOD... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import glob
import datetime
import tqdm
import numpy as np
import tensorflow as tf
import yaml
import importlib
class DataWriter(object):
"""Graph dataset writer
The `Gr... |
"""
Mixins for commands
"""
from typing import Union, Dict
from server.utils.exceptions import CommandError
from django.db.models import Q
class ArxCommmandMixin(object):
"""Mixin class for Arx commands"""
error_class = CommandError
help_entry_tags = []
def fail(self, msg):
"""Raises an erro... |
"""Utility classes and functions for Monte Carlo simulation.
Copyright 2016 - 2021 <NAME>
MIT licence: https://opensource.org/licenses/MIT
Get the latest version from:
https://github.com/blokeley/montecarlo
Ask <NAME> for advice before modifying this file.
Versions:
1.0 - First use
1.1 - Add legend to histrogram.
... |
# -*- coding: utf-8 -*-
# ncon.py
import jax.numpy as np
import numpy as onp
def jncon(tensor_list, connect_list_in, cont_order=None, check_network=True):
"""
------------------------
by <NAME> (c) for www.tensors.net, (v1.31) - last modified 30/8/2019
------------------------
Network CONtractor. Input is an array... |
"""
Copyright (c) 2018 Intel Corporation
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 writin... |
import librosa, librosa.display, librosa.feature
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import os
import time
"""
--Get data set
"""
# hop length is 512 for default
hop_length = 64
#default is 2048
n_fft = 4096
n_mfcc = 52
mypath = 'C:\\Users\\willi\\Documents\\Pyt... |
import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
d... |
# Name: pySnipnix.py
# Author: pantuts
# Description: Saving your snippets to sqlite3 database.
# Agreement: You can use, modify, or redistribute this tool under
# the terms of GNU General Public License (GPLv3).
# This tool is for educational purposes only. Any damage you make will not affect the author.
# first run: ... |
from numpy.lib.arraysetops import isin
import torch
import torch.nn as nn
from collections import OrderedDict
import numpy as np
from models.dss_net import *
import torch.nn.functional as F
from models.dss_layer import DSSConv2d, DSSInput, DSSInvolution, conv1x1, conv1x1_out, conv3x3
import torch.utils.checkpoint as cp... |
#!/usr/bin/env python
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
import radical.utils as ru
from radical.utils.contrib.urlparse25 import urljoin
# ------------------------------------------------------------------------------
#
def test_contrib(... |
import Virus as virus
import random
class Parvovirus (virus.Virus) :
def __init__ (self) :
virus.Virus.__init__(self)
self.gene = virus.DNA()
self.strand = 1
self.sense = random.choice([-1,1]) # becomes dsDNA anyway, so not important
self.gene_length = (5,5) #kb
se... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2011 by <NAME>, <NAME>, Zuse Institute Berlin
# Licensed under the BSD License, see LICENSE file for details.
import os, shutil, stat, unittest, sys
TEST_FILE_NAME = "simple_metadata_file.txt"
TEST_DIR_NAME = "simple_metadata_dir"
TEST_LINK_NAME = "si... |
import sys
from collections import defaultdict
import re
from scipy import spatial
def print_usage(name):
print("python3 {} [-l | -d] <input_file>".format(name))
print("-l - process the input file to find the largest non-infinite area")
print("-d - process the input file to find the most dense area")
def... |
class operator(object):
def __init__(self, symbol):
self._symbol = symbol
@property
def symbol(self):
return self._symbol
def __str__(self):
return self._symbol
def __len__(self):
return 0
def __or__(self, op):
if self and op:
return logical_or(self, op)
elif op:
return op
else:
return ... |
import boto3
import random
import string
import logging
from botocore.credentials import (
AssumeRoleCredentialFetcher,
CredentialResolver,
DeferredRefreshableCredentials
)
from botocore.session import Session
from botocore.exceptions import ClientError
from crhelper import CfnResource
logger = logging.get... |
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
from enum import Enum
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import cv2
# coco
# 0: "nose",
# 1: "left_eye",
# 2: "right_eye",
# 3: "left_ear",
# 4: "right_ear",
# 5: "left_shoulder",
# 6: "right_shoulder",
# 7: "left_elbow",
# 8: "right_elbow",
# 9: "left_wrist",
# ... |
import torch
class Node:
def __init__(self, data, _pre=None, _next=None):
self.data = data # in format [loss, feature]
# self.data = data[0]
# self.loss = data[1]
# self.index = data[2]
self._pre = _pre
self._next = _next
def __str__(self):
return str(sel... |
from __future__ import print_function
from optparse import OptionParser
import tables
import numpy as np
import glob, os, re, time, warnings, sys
import flydra_analysis.analysis.result_utils as result_utils
import motmot.ufmf.ufmf
if 1:
# deal with old files, forcing to numpy
import tables.flavor
tables.f... |
"""
Utility functions to assist with the Fedora 3 spoofing.
"""
import datetime
import logging
import requests
from psycopg2.extensions import ISOLATION_LEVEL_READ_COMMITTED
import pytz
import dgi_repo.database.write.log as log_writer
import dgi_repo.database.write.datastreams as ds_writer
import dgi_repo.database.re... |
import numpy as np
import matplotlib.pyplot as plt
import csv
from scipy.optimize import minimize
from functools import partial
###############################################################################
#
# Jiles-Atherton Equation solving functions
#
##############################################################... |
"""
For a session where there is DLC already computed,
load DLC traces to cut video ROIs and then
compute motion energy for these ROIS.
bodyCamera: cut ROI such that mouse body but not wheel motion is in ROI
left(right)Camera: cut whisker pad region
"""
import time
import numpy as np
import pandas as pd
import cv2
i... |
from datetime import datetime
from typing import Dict, List, Union
import numpy as np
from pydantic import BaseModel, Field, PyObject
from pymatgen.core import Structure
from emmet.core import SETTINGS
from emmet.core.mpid import MPID
from emmet.core.utils import DocEnum
from emmet.core.vasp.task import TaskDocument
... |
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
# import progressbar
from time import sleep
from progress.bar import Bar
# these values will stop the crawl after the number of times equals the cap
# turn off these cap (do all) by making this value -1
CATEGORY_CAP = 25
PAGES_CAP = 1
EXTENSI... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 20:41:31 2021
@author: marijn
Script makes a plot of the laser induced fluorescence from the MOT with
a color overlay and a scalebar
Also exports sum over rows and columms and fits a Voigt profile through it
"""
#%% Imports
import matplotlib.p... |
#[2020]-"A new fusion of grey wolf optimizer algorithm with a two-phase mutation for feature selection"
import numpy as np
from numpy.random import rand
from FS.functionHO import Fun
def init_position(lb, ub, N, dim):
X = np.zeros([N, dim], dtype='float')
for i in range(N):
for d in range(d... |
# 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... |
import shutil
import os
import pickle
import random
import numpy as np
from scipy.signal import find_peaks
from .experiment import filter_nth_play, Experiment
class SetUpTests():
# Streamline setting up experiments for tests
rand_seed = 11345
def __init__(self, test_dir, raw_data_dir, raw_data_fn, **ex... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from datetime import date
import time
def add():
try:
df = pd.read_csv('data pool/raw_ios.csv', index_col=0)
except:
df = pd.DataFrame()
to_add = dict()
month = input('Month: ')
with open('names_urls.txt', 'r', encoding='... |
import inspect
from typing import Callable, List, Tuple, Union
import pandas as pd
from funcy import decorator, func_partial, ignore
from funcy.decorators import Call
from stacklog import stacklog
from ballet.exc import (
FeatureRejected, InvalidFeatureApi, InvalidProjectStructure,
NoFeaturesCollectedError, S... |
import numpy as np
import sympy as sp
import mpi4py.MPI as mpi
import pylbm
X, Y, LA = sp.symbols('X, Y, LA')
rho, qx, qy, T = sp.symbols('rho, qx, qy, T')
def init_T(x, y):
return T0
def bc(f, m, x, y):
m[qx] = 0.
m[qy] = 0.
m[T] = T0
def bc_in(f, m, x, y):
np.random.seed(1)
m[qx] = rhoo*u... |
from flloat.parser.ltlf import LTLfParser
from py_trees.composites import Sequence, Selector
from py_trees.decorators import Decorator, Inverter
from py_trees.trees import BehaviourTree
# from py_trees.behaviour import Behaviour
import py_trees
from py_trees import common
import copy
# Trying to implement the logic ... |
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
from tkinter import messagebox
import os
import signal
import subprocess
################################################################################
# Methods
##############################################... |
"""Modified JSON API v1.0 for OPTIMADE API"""
# pylint: disable=no-self-argument,no-name-in-module
from pydantic import Field, root_validator, BaseModel, AnyHttpUrl, AnyUrl, EmailStr
from typing import Optional, Union, List
from datetime import datetime
from . import jsonapi
__all__ = (
"ResponseMetaQuery",
... |
'''
Flattening a nested linked list
Suppose you have a linked list where the value of each node is a sorted linked list (i.e., it is a nested list). Your task is to flatten this nested list—that is, to combine all nested lists into a single (sorted) linked list.
First, we'll need some code for generating nodes and a l... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... |
# coding=utf-8
from contextlib import ExitStack
# from scripts.process_data import reverse_text
# from scripts.process_data import reverse_text
from src.metric.bleu_scorer import SacreBLEUScorer
def compute_bleu_for_MIRA(outputs, beam_size, save_score_filename=None):
ref_path = "/home/user_data55/wangdq/data/ccm... |
import os
from flask import Flask, render_template
from dotenv import load_dotenv
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from sqlalchemy_utils import IntRangeType
from geoalchemy2 import Geometry
from geoalchemy2.functions import GenericFunction
from flask_restful import reqparse
from numpy... |
"""DEPRECATED! Manila and Manila Share services"""
import sys
from playback.cli.cliutil import priority
from playback.manila import Manila
def create_manila_db_subparser(s):
create_manila_db_parser = s.add_parser('create-manila-db', help='create manila database')
create_manila_db_parser.add_argument('--root-db... |
"""https://stackoverflow.com/questions/49834264/mri-brain-tumor-image-processing-and-segmentation-skull-removing"""
""" This code can be used to generate binary images from the original PNGs"""
import numpy as np
import os
import cv2
import glob
from glob import glob
#import pandas as pd
from matplotlib import pyplot ... |
import time
import numpy as np
import torch
from torch.optim import Adam
from torch.utils.data import DataLoader
from deepspeed import deepspeed
import torch.nn as nn
import ipc
from config import build_parser
from model import Transformer
from data_loader import Dataset_ETT_hour, Dataset_ETT_minute
from metrics ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
AniColle Library
Collect your animes like a geek.
Database model and operations here.
Unlike the previous version, this version returns objects as results rather than dictionaries by default.
You can force convert it into a dict by using to_dict().
"""
from peewee im... |
import json
import os
import semver
import sys
class Image:
def __init__(self, name, description, version):
self.name = name
self.description = description
self.version = version
self.children = []
self.parent = None
self.current = {}
def has_version(self):
... |
""" ***************************************************************************
# * File Description: *
# * Organizes the functions for making maps based on the original file of *
# * 'MakeLawerenceMap.py' *
... |
import subprocess
import time
import os
import numpy
import sys
import textwrap
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import cv2
def main():
for overheardMessage in execute(['sh', './listenForNotifySend.sh']):
#print("original msg: " + overheardMessage)
line = time.strftime('... |
from bigchaindb.common.transaction import Asset, Transaction
from .crypto import generate_keypair
from .exceptions import InvalidVerifyingKey, InvalidSigningKey
from .transport import Transport
DEFAULT_NODE = 'http://localhost:9984/api/v1'
class BigchainDB:
"""BigchainDB driver class.
A :class:`~bigchaind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.