text stringlengths 3.07k 12.6k |
|---|
from sympy import symbols, init_printing, S, Derivative, diff, simplify, solve, lambdify, cos, sin
from sympy.physics.vector import vlatex
import numpy as np
import scipy.integrate as integrate
from matplotlib import pyplot as plt
from matplotlib import animation, rc
from itertools import chain
from IPython.display imp... |
# Author: <NAME> <<EMAIL>>
import torch
import torch.nn as nn
from contrib import weight_init
from models import factory
def conv(in_channels, out_channels, kernel_size,
eps=1e-3,
stride=1,
padding=None,
bias=False,
nonlinear=True):
if padding is None:
paddin... |
#This is the welcome message for when a user starts the skill without a specific intent.
WELCOME_MESSAGE = ("Welcome to the Big O notation!"
" With this skill, you can learn time and space complexity of common sorting algorithms."
" What would you like to know?")
#This is the me... |
from flask import Blueprint, render_template, session, request, redirect, jsonify
from sqlalchemy import and_, or_
from davidvisitorsapp.models import db, User, Visit
from datetime import datetime
import time
import random
import string
import json
import hashlib
import random
user_bp = Blueprint('user_bp', __name__... |
import argparse
import pickle
from tqdm import tqdm
from pathlib import Path
import cv2
import numpy as np
import pandas as pd
from collections import defaultdict
from utils.mask_functions import mask2rle
from utils.helpers import load_yaml
def argparser():
parser = argparse.ArgumentParser(description='Pneumato... |
# Copyright (c) 2015-2016, The Authors and Contributors
# <see AUTHORS file>
# 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 n... |
import enum
import string
import collections
class Tokenizer:
class Buffer:
delim = (32, 9, 10, 13, 11, 12, 40, 41, 59) # ();
whitespace = (32, 9, 10, 13, 11, 12)
linefeed = (0x0A,)
def __init__(self, size):
self.idx = 0
self.data = bytearray(size)
... |
# forms.py
import re
from django import forms
from main.models import Episode, Location, Mark
from main.models import STATES
class Who(forms.Form):
locked_by = forms.CharField(max_length=32, required=True,
label="Please enter your name")
class Location_Form(forms.ModelForm):
class Meta:
... |
import tensorflow as tf
from tensorflow.keras import layers
class Sampling(layers.Layer):
""" Uses the reparametrisation trick to sample z = mean + exp(0.5 * log_var) * eps where eps ~ N(0,I)
"""
def call(self, inputs, **kwargs):
z_mean, z_log_var = inputs
batch, dim = tf.shape(z_mean)[0],... |
from django.conf import settings
from django.db import connections
from django.db.models import Count, Q
from rest_framework import viewsets
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response
from rest_fr... |
"""
Monitoring mainloop for Ivaldi.
"""
# Standard library imports
import sys
# Local imports
import ivaldi.devices.adafruit
import ivaldi.devices.analog
import ivaldi.devices.counter
import ivaldi.devices.onewire
import ivaldi.output
import ivaldi.utils
PERIOD_S_DEFAULT = 1
VARIABLES = {
"time_elapsed_s": "{:... |
import os
import csv
import json
import logging
import math
from multiprocessing import Pool
from common_utils import gentweets
import numpy as np
from scipy import stats
def read_dataset(filepath, delim='\t', measure_col=1):
dataset = {}
with open(filepath, 'r') as f:
reader = csv.reader(f, delimiter... |
# Imports
from flask import Flask, render_template,request
import sqlite3
import rdflib
import time
# Access RDB and cursor object
def RDB2RDF():
import sqlite3
conn = sqlite3.connect('classicmodels.db')
cur = conn.cursor()
# Record the start time
t1 = time.time()
# Create the rdf file
... |
from src import utils
from src.dataset import ImageData
import pandas as pd
import torch
import argparse
import os
import numpy as np
from tqdm import tqdm
import time
import sklearn.metrics as metrics
from matplotlib import pyplot as plt
DIR_TEST_DATA = "ISIC-2017_Test_v2_Data"
FILE_TEST_LABELS = "ISIC-2017_Test_v2_P... |
import sys
import re
from typing import List, TextIO, Set
from os import makedirs
# usage: ./find_all_linked_errors.sh <library> <errors>
# - library: library, from which the errors is
# - error: error that we are trying to find linked errors to
#
# searches through _data/mapping.txt and finds al... |
import os
import numpy as np
from typing import List, Optional
try:
from SkateTracker.art import ascii_art
except ModuleNotFoundError:
from art import ascii_art
from rich.table import Table
from rich.panel import Panel
from rich.markdown import Markdown
def ordinal(n: int):
"""Utility function that gi... |
from datetime import datetime
import logging
from twisted.internet import defer
from twisted.internet.threads import deferToThread
import requests
from cardinal.decorators import command
from cardinal.decorators import help
class ShowNotFoundException(Exception):
pass
@defer.inlineCallbacks
def fetch_show(sho... |
"""
Script for running the experiment on predicting gene expression
from methylation of CpG sites based on sites found to have the
highest correlation with individual genes' expressions.
"""
from pathlib import Path
from typing import List, Tuple
import numpy as np
import pandas as pd
import lightgbm as lgb
from sk... |
#!/usr/bin/env python3
""" Executable used to run the training process """
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import pickle
import tensorflow as tf
from hooperhub.seq2seq_model import Seq2SeqModel
from hooperhub.util import data_utils
tf.app.flags.DEFINE_integer("source_vocab_size", 1100,
... |
import os
import torch
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
from .layers.ScalingBlock import scaling_module_set_scale, scaling_module_set_bias
def train_loop(dataloader, model, optimizer, loss, device='cuda'):
'''
The training function
:param dataloader: The dataloader t... |
# Copyright (c) 2020-2021 <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, modify, merge, publish, distrib... |
#!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed ... |
import numpy as np
import tensorflow as tf
# import zipfile
import collections
import math
"""
While using Rap.txt
a = "burn a lot \n i'm".split('\n')
b=[]
for i in range(len(a)):
b.append(a[i].split())
b.append('\n')
c=[]
for i in b:
for j in i:
c.append(j)
def takeOutData(s="word2vecData.zip"):
with zipfil... |
from typing import Optional, List
from moodle import ResponsesFactory
from moodle.attr import dataclass, field
@dataclass
class CourseEventIcon:
"""Icon
Constructor arguments:
params: key (str): key
params: component (str): component
params: alttext (str): alttext
"""
key: str
compon... |
from src.benchmark.benchmark_utils import (
SupplementaryExcelParser,
get_mutation_corrected
)
from src.helpers.mylogger import get_handler
import re
import logging
handler = get_handler()
log = logging.getLogger(__name__)
log.handlers[:] = []
log.addHandler(handler)
log.setLevel(logging.DEBUG)
def is_vali... |
from ..base import VerticalAdvectionStencil
from ....tools import timing
from dace.codegen.instrumentation.report import InstrumentationReport
from gt4py import gtscript
from .mixin import CPUStencilMixin, GPUStencilMixin
class VerticalAdvectionStencil(VerticalAdvectionStencil):
def run_stencil(self, data):
... |
import numpy as np
from scipy.stats import norm
from numpy import vectorize
@vectorize
def U1(C, C_):
if C <= 0:
U = -np.inf
else:
U = -(1/2)*(C-C_)**2
return U
@vectorize
def U2(C, S):
if C <= 0:
U = -np.inf
else:
U = (C**(1-S) -1)/(1-S)
retur... |
import Algorithmia
from Algorithmia import Client
import json
import tarfile
import shutil
import requests
from src.utilities import algorithm_exists, call_algo
from src.webapi import get_available_environments, get_downloadable_environments, find_environment, sync_environment
from uuid import uuid4
import sys
from tim... |
# taken from https://github.com/kamalkraj/DATA-SCIENCE-BOWL-2018/blob/master/data_util.py
# slighty modified with argparse and other os.savings
import os
import random
import sys
import warnings
import numpy as np
from itertools import chain
from skimage.io import imread
from skimage.transform import resize
from skimag... |
from typing import List, Optional, Dict, Any, Union, Callable
import re
from dateutil.parser import parse as from_iso
from aurora_connector.helpers.Exceptions import AuroraParameterException, AuroraDatabaseException
DATATYPE_MAPPING = {
"VARCHAR": str,
"CHAR": str,
"BINARY": bytes,
"VARBINARY": byte... |
import datetime
import os, sys
import numpy as np
import pandas as pd
from six import iteritems
from tqdm import tqdm
from trading_calendars import get_calendar
import logging
from dask import dataframe as dd
from zipline.assets.futures import CMES_CODE_TO_MONTH
#from zipline.data.bundles import core as bundles
from l... |
"""
Get scan infomation
"""
from configparser import ConfigParser
import pandas as pd
import os
import re
import glob
from functions.analysisdata import AnalysisData
from functions.time import PT_timestr
class ScanInfo:
def __init__(self, dir_date, exp_paras):
"""
dir_date: path of date directory... |
''' Utils for training and evaluation '''
import os
import json
import time
import math
import random
import torch
import numpy as np
from model.cuda import try_cuda
from src.process_data import make_data
from src.vocab.tokenizer import VOCAB_PAD_IDX, VOCAB_EOS_IDX
from simulator.envs.image_feature import ImageFeatur... |
from typing import cast, Dict, Set, Optional
from spec_const import SPEC_PTR_SIZE
from spec_random import SPEC_RANDOM
from spec_basis import Rand, Kobj, Lego, Syscall, Program, Executable
from spec_pack import pack_ptr
from util_bean import Bean, BeanRef
class RandPointer(Rand):
pick: bool
class KobjPointer(Ko... |
# coding=utf-8
"""
CLI Application for telegraf-pgbouncer
"""
import argparse
import getpass
import json
import sys
import psycopg2
from psycopg2 import extras
from telegraf_pgbouncer import __version__
COMMANDS = {
'all',
'databases',
'lists',
'mem',
'pools',
'stats'
}
def exit_applicatio... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... |
import sys
import traceback
import pandas as pd
import seaborn as sns
from sklearn.cluster import KMeans
from geopy.distance import distance
from parameters import Parameters
from typing import Tuple, List, Optional
import matplotlib.pyplot as plt
# from IPython.display import display
from utilities_kml import update_... |
from sqlalchemy import Column, Integer, String, Date, ForeignKey, Float, Boolean
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import relationship
class Base:
@declared_attr
def __tablename__(self):
return self.__name__.lower()
id = Column(Integer, pri... |
#!/usr/bin/env python2
# Copyright (c) 2018-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Linux network utilities
import sys
import socket
import fcntl
import struct
import array
import os
fro... |
import numpy as np
# 8bitの最大値
QUANTIZE_BIT = 8
MAX_VALUE = (2 ** QUANTIZE_BIT )- 1
def deQuantize_scalar(x, min, max):
"""量子化を元に戻す"""
gain = (max - min) / MAX_VALUE
return x * gain + min
def deQuantize(arr, a_min, a_max):
"""量子化を元に戻す"""
gain = (a_max - a_min) / MAX_VALUE
return arr * gain +... |
#!/usr/bin/env python3
""" 10.08.2020 <NAME>
Scripti lukee mqtt-palvelimelta valoisuusanturin arvoa ja mikäli se on alle 300 ja valojen tulisi olla päällä,
laitetaan valot kanalaan päälle. Mikäli valoisuus on yli 300, valoja ei tarvita.
Valojen päällelaitto tapahtuu tässä tapauksessa RELE1- aihetta kutsumalla, eli ka... |
from __future__ import print_function
# Copyright (c) 2015-2016, Danish Geodata Agency <<EMAIL>>
# Copyright (c) 2016, Danish Agency for Data Supply and Efficiency <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that t... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions ... |
from collections import OrderedDict
import torch.distributed as dist
import torch
import logging
import numpy as np
LOGGER = logging.getLogger(__name__)
try:
import apex
flatten, unflatten = (
apex.parallel.distributed.flatten,
apex.parallel.distributed.unflatten,
)
except ImportError:
... |
"""Implements VGG pre-processer for IMDB data."""
import theano
import numpy
from blocks.bricks import MLP, Rectifier, FeedforwardSequence, Softmax
from blocks.bricks.conv import (Convolutional, ConvolutionalSequence,
Flattener, MaxPooling)
from blocks.serialization import load_paramete... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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... |
#!/usr/bin/env python3
# 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.
r"""
Example TorchGeneratorAgent model.
This demonstrates the minimal structure of a building a generative mod... |
from collections import OrderedDict
from imutils import face_utils
import numpy as np
import argparse
import imutils
import dlib
import cv2
import json
#costruct the argument parser and parse tha arguments
#ap=argparse.ArgumentParser()
#ap.add_argument("-p","--shape-predictor", required=True,
# help... |
#-*- coding: utf-8 -*-
#
# Copyright (c) 2012, VPSMate development team
# All rights reserved.
#
# VPSMate is distributed under the terms of the (new) BSD License.
# The full license can be found in 'LICENSE.txt'.
"""Package for user management.
"""
import os
if __name__ == '__main__':
import sys
root_path = ... |
from __future__ import unicode_literals
from StringIO import StringIO
from ConfigParser import SafeConfigParser
from pytest import raises, fixture
from lnc.lib.exceptions import ProgramError, NoOptionError, PluginError
from lnc.lib.options import get_option, get_int, get_boolean, check_target_options
TEST_CONFIG = "... |
# This code is distributed under the MIT License
from __future__ import annotations
import json
import logging
import re
from typing import Optional
import requests
from requests.models import HTTPBasicAuth
from flaat.user_infos import UserInfos
logger = logging.getLogger(__name__)
# Defaults for requests
_VERIFY... |
from distutils.log import debug
from urllib.request import Request, urlopen
from json import loads, dumps
from time import sleep
from threading import Thread
from flask import Flask
from waitress import serve
import requests
from discord_webhook import DiscordWebhook, DiscordEmbed
app = Flask(__name__)
de... |
import pandas as pd
import numpy as np
from statsmodels.robust.scale import mad
def __check_quotes__(qdata):
col_names = qdata.columns
if not np.any(col_names == 'bid'):
raise ValueError('Could not find bid in column names')
if not np.any(col_names == 'ask'):
raise ValueError('Could not fi... |
#!/usr/bin/env python
# cardinal_pythonlib/nhs.py
"""
===============================================================================
Original code copyright (C) 2009-2020 <NAME> (<EMAIL>).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the "License");
you m... |
import itertools
import logging
import random
import sys
import warnings
from dataclasses import dataclass, field
from datetime import timedelta
from functools import reduce
from pathlib import Path
from typing import Collection
import hydra
import pandas as pd
from hydra.core.config_store import ConfigStore
from logu... |
"""EnergyMarket.py
A multi-independant-processes simulation about the energy market."""
from matplotlib import pyplot as plt
from matplotlib import animation
from multiprocessing import Value, Array, Process
from threading import Lock, Thread, current_thread
from signal import signal, SIGINT, SIGUSR1, SIGUSR2
from sy... |
"""
Perform a binary search to figure out the max. values of the training parameters:
'num_envs' and 'train_batch_size'.
The highest 'num_envs' if chosen that maximizes the GPU utilization
(i.e., uses up as many GPU blocks possible). The highest 'train_batch_size'
is then chosen in order to maximize the GPU memory usag... |
from __future__ import absolute_import
from future import standard_library
from builtins import next
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckanext.scheming.helpers import lang
from ckanext.apicatalog_scheming import cli
import json
try:
from collections import OrderedDict # ... |
# Copyright 2020 The TensorFlow Probability 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 applicable law o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Version 1.2
´'''
import sys
import os
import yaml
import pickle
import argparse
import logging
import logging.config
from F2S_PartirSpool import F2S_PartirDoc
from F2S_Dinamico import objDinamico
# logging.debug('This is a debug message')
# logging.info('This is ... |
r"""
Exner equation
2D conservation of mass equation describing bed evolution due to sediment transport
The equation reads
.. math::
\frac{\partial z_b}{\partial t} + (m/(1-p)) \nabla_h \cdot \textbf{Q_b}
= (m/(1-p)) H ((F_{sink} S) - F_{source})
:label: exner_eq
where :math:`z_b` is the bedlevel, :math... |
import common
from argparse import ArgumentParser
import torch.nn as nn
## Channel Attention (CA) Layer
class CALayer(nn.Module):
def __init__(self, channel, reduction=16):
super(CALayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.conv_du = nn.Sequential(
nn... |
from __future__ import annotations
import logging
import numpy as np
# from network import physical_network
# from shipping_allocation.envs.network_flow_env import (
# ShippingFacilityEnvironment,
# )
# import experiments_seminar_2.agents.optimizer_agents
from agents import optimizer_agents, pytorch_agents
from... |
'''
Author : <NAME>
'''
import numpy as np
import pandas as pd
# key threshold
max_key_length = 9
# english alphabet
alphabet = "abcdefghijklmnopqrstuvwxyz"
english_freq = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, ... |
# Copyright 2020 Adap GmbH. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
import json
import os
import sys
import unittest
from collections import OrderedDict
import pytest
import six
from conans.build_info.conan_build_info import get_build_info
from conans.client import tools
from conans.test.assets.genconanfile import GenConanfile
from conans.test.utils.test_files import temp_folder
from... |
# Copyright (C) 2021 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 wri... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021 davfsa
#
# 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 right... |
import logging
import subprocess
from tempfile import NamedTemporaryFile
model_params = {
"powerlaw": ["phoindex"],
"cutoff_powerlaw": ["phoindex", "cutoff", "efold"],
"blackbody": ["kT"],
"bremss": ["kT"],
"plasma": ["kT", "abund"],
}
def _add_absorption(model_str, **kwargs):
nh = kwargs.po... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
from typing import List, Callable, Union, Dict
class Vocab:
"""Vocab class"""
def __init__(
self,
list_of_tokens: List[str] = None,
padding_token: str = "<pad>",
unknown_token: str = "<unk>",
bos_token: str = "<bos>",
eos_token: str = "<eos>",
reserved_... |
import os
import time
import requests
import paramiko
import psycopg2
from flask import Flask
from rq import get_current_job
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from proxstar.db import *
from proxstar.util import *
from proxstar.mail import *
from proxstar.starrs import *
from p... |
import os
from numbers import Number
from pathlib import Path
class BaseOption(object):
"""
Base implementation for representing options in the various
text based SUMMA configuration files. This class is meant to
be extended rather than used directly.
"""
compare_err = 'Cannot compare LocalPar... |
from off_nitrogens.calc_improper import *
#from calc_improper import *
import numpy as np
def test_two_vectors():
"""Test the angle between two simple vectors."""
ang = angle_between((1, 0, 0), (0, 1, 0))
if ang != 90.0:
raise Exception("Wrong angle calculated between two vectors.")
def test_valen... |
# pylint: disable=no-member, import-error, no-init, too-few-public-methods
# pylint: disable=cyclic-import, no-name-in-module, invalid-name
from sqlalchemy import desc
from ersa_reporting import db, id_column
from ersa_reporting import get_db_binding
DB_BINDING = get_db_binding(__name__)
class Snapshot(db.Model):
... |
import preprocessor as p # used for cleaning text
def mention_hydrate(entity_list):
x = 0 #list index
i = 1 #list length
container = []
entity_length = len(entity_list)
while i <= entity_length:
temp_list = entity_list[x]
j = temp_list.get("username")
container.append(j)
... |
# _ __ _ ___ _ ___ _ _
# | |/ /_ _ __ _| |_ ___ __/ __| __ _| |___ _ __ ___| _ \ |_ _ __ _(_)_ _
# | ' <| '_/ _` | _/ _ (_-<__ \/ _` | / _ \ ' \/ -_) _/ | || / _` | | ' \
# |_|\_\_| \__,_|\__\___/__/___/\__,_|_\___/_|_|_\___|_| |_|\_,_\__, |_|_||_|
# ... |
#!/usr/bin/env python3
import sys
import re
import os
import collections
import pickle
from caffe.proto import caffe_pb2
import google.protobuf.text_format
import caffe
def extract_layer_info(net_file_path, _net_name, batch_size):
net_name = _net_name + '-dense-fp16-' + str(batch_size) + 'batch'
print(net_na... |
"""
A simple example to make a "sanitizer" decorator.
The intention for this is to be able to create an instance attribute that can
be set by the user, with the value validated or sanitised. The initial data is
given as an argument of the sanitizer, and the data itself is held in the
instance's dynamically created `__... |
# Copyright (C) 2013-2014 eNovance SAS <<EMAIL>>
#
# 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 a... |
import numpy as np
import pandas as pd
from scipy.stats import circmean
import unittest
from flasc.dataframe_operations import dataframe_manipulations as dfm
def load_data():
# Create a demo dataframe
N = 100
df_full = pd.DataFrame()
wd_array = np.array([350, 3., 8., 5.])
ws_array = np.array([5.... |
# sigtools - Collection of Python modules for manipulating function signatures
# Copyright (C) 2013-2021 <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, includin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011-2014, <NAME>
#
# 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 r... |
'''Tools for operating on chunks of financial time-series data.
'''
from string import ascii_uppercase
from random import sample
import numpy as np
# While our generator functions aren't quite objects, they're used more like
# objects, and cohere with our actual objects below. Thus, we use CamelCase.
def JoinedChu... |
SOURCE_FILE = __file__
def in_order_traversal(t):
"""
Generator function that generates an "in-order" traversal, in which we
yield the value of every node in order from left to right, assuming that each node has either 0 or 2 branches.
For example, take the following tree t:
1
2 ... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
# Copyright 2019, <NAME>, mailto:<EMAIL>
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
from itertools import product
from ngram_score import ngram_score
L2I = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26)))
I2L = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
import sys
ctext = 'hwduyfsfqdxnx nx ymj fwy tk gwjfpnsl htijx fsi hnumjwx. bmjs fyyjruynsl yt hwfhp f mnqq hnumjw, kwjvzjshd fsfqdxnx bnqq gj uwfhynhfqqd zxjqjxx'... |
# coding: utf8
# Copyright (c) <NAME>, University of Antwerp
# Distributed under the terms of the MIT License
import os
import numpy as np
from itertools import chain
from monty.serialization import loadfn
from pymatgen.core import Structure, PeriodicSite
from pymatgen.io.vasp.inputs import Poscar
from pymatgen.io.v... |
# SPDX-License-Identifier: BSD-2-Clause
import os
import time
import traceback
from contextlib import contextmanager
import jsonpickle
from PyQt5 import uic
from PyQt5.QtCore import QSettings
from PyQt5.QtCore import QTimer
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFontMetrics
from PyQt5.QtGui import QPixma... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import numpy as np
from matplotlib import pyplot as plt
import scipy
import scipy.constants
#import os
# os.chdir("D:/Documents/4th year modules/Project/Test files") # working dir for files
""" ===== To do list ====
find and test rk4 solver
"""
"""============================= Calculations ==========... |
from .typing import Any, Callable, List, Dict, Tuple, Optional
import functools
import os
import sublime
import threading
ResolveFunc = Callable[..., None] # Optional argument not supported in Callable so using "..."
FullfillFunc = Callable[[ResolveFunc], None]
ThenFunc = Callable[[Any], Any]
class Promise:
"""... |
import os
from datetime import datetime
import argparse
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.optimizers import Adam
from utility import DataGenerator, get_partition, plot_history, recall, precision, f1
model_names = ['ResNeXt']
dataset_types = ['balance', 'imbalance']
dat... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import os
import re
from contextlib import contextmanager
from uuid import uuid4
from flask import Bluepr... |
from urllib.parse import urlparse
from django.http import HttpResponseForbidden, HttpResponse
from django.views.generic.base import View
from django.shortcuts import render, redirect
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView, CreateView, DeleteView, FormMixin
from d... |
import doctest
import re
from collections import OrderedDict
from django.test import SimpleTestCase
import corehq.apps.app_manager.xform_builder
from corehq.apps.app_manager.tests.util import TestXmlMixin
from corehq.apps.app_manager.xform_builder import XFormBuilder
class XFormBuilderTests(SimpleTestCase, TestXmlM... |
from enum import Enum
class Location(Enum):
HOME = "HOME"
AWAY = "AWAY"
class Outcome(Enum):
WIN = "WIN"
LOSS = "LOSS"
class Team(Enum):
ATLANTA_HAWKS = "<NAME>"
BOSTON_CELTICS = "BO<NAME>TICS"
BROOKLYN_NETS = "BROOKLYN NETS"
CHARLOTTE_HORNETS = "CHARLOTTE HORNETS"
CHICAGO_BULL... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""Define Robinhood endpoints."""
from typing import Optional
from yarl import URL
# TODO: All url construction should happen here, not in robinhood.py
# Base
API_BASE = URL("https://api.robinhood.com")
# General
ACCOUNTS = API_BASE / "accounts/"
ACH_BASE = API_BASE / "ach/" # not implemented
APPLICATIONS = API_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.