content stringlengths 5 1.05M |
|---|
# ================================================================
# Created by Gregory Kramida (https://github.com/Algomorph).
# Copyright (c) 2021 Gregory Kramida
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for similarity algorithms (the similarities package).
"""
import logging
import unittest
import os
import numpy
i... |
# Generated by Django 2.1.2 on 2018-11-01 13:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exercises', '0029_reviewexercise_can_review_own_submission'),
]
operations = [
migrations.AlterField(
model_name='reviewexercise... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def RK2(func, X0,tmin,tmax,h,cons):
N=int((tmax-tmin)/h)
t = np.linspace(tmin,tmax,N)
X = np.zeros([N, len(X0)])
X[0] = X0
for i in range(N-1):
k1 =h* func(t[i],X[i],cons)
k2 = h*func( t[i] + h,X[i] +... |
import os
from extract.readers import CSVReader, JSONReader, XLSReader, Reader
from typing import Type
class Extractor:
path: str
data: list
_readers: dict[str, Type[Reader]]
default_path = os.path.join(os.getcwd(), 'input_files')
def __init__(self, path: str = default_path):
self.path = ... |
import numpy as np
from scipy.interpolate import interp1d
from scipy.signal import savgol_filter
dataset = []
def dataformat(box,n):
indicators=[]
for i in range(n):
n1 = np.average(box[i])
n2 = np.std(box[i])
if n2 > n1:
pippo = '{0:.4g}±{1:.4g}'.format(n1,n2)
... |
import logging
import typing
from dbnd._core.constants import (
DbndTargetOperationStatus,
DbndTargetOperationType,
MetricSource,
)
from dbnd._core.errors.errors_utils import log_exception
from dbnd._core.parameter.parameter_definition import ParameterDefinition
from dbnd._core.task_run.task_run_ctrl impor... |
import os
import robot_util
import time
import atexit
import serial
import sys
import pigpio
commandArgs = None
#straight speeds 200#300#450
#turn speeds 500#700#450
straightDelay=0.6
stopDelay=0.05
turnDelay=0.5
ser=None
movementSystemActive=None
dildoActive=None
dildoDutyCycle1=10 #percentage
dildoDutyCycle2=20 #p... |
"""
Author: Boobalan R Shettiyar
Github: https://github.com/thepasterover
facebook ID : https://www.facebook.com/boopalan.shettiyar
"""
import os
import shutil
while 1:
print("Welcome to Python File Sorter.")
old_folder = input("\nWhich directories you want to check?\n\t(Copy"
" th... |
# Generated by Django 2.1.3 on 2020-07-29 16:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('result', '0118_auto_20200729_1759'),
]
operations = [
migrations.AlterField(
model_name='edit_user',
name='resumptio... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from torch.nn.utils.rnn import pack_padded_sequence
class AttentiveReaderBilingual(nn.Module):
"""Attentive Reader"""
def __init__(self, var_size, story_max_len, question_max_len, emb_vectors,
... |
#!/usr/bin/env python
"Test the EXX routines"
from PyQuante.OEP import exx
from PyQuante.Molecule import Molecule
from PyQuante.Ints import getbasis,getints
from PyQuante.hartree_fock import rhf
from PyQuante.dft import dft
import logging
import time
def test_exx():
logging.basicConfig(filename='test_exx.log',
... |
import os
import sys
import tempfile
import unittest as ut
from pathlib import Path
from .base import BaseTestDataSource
root_folder = Path(os.getcwd())
sys.path.append(str(root_folder))
SAMPLE_DOC = {
'pep':
8,
'authors': ['Guido van Rossum <guido at python.org>', 'Barry Warsaw <barry at python.org>', '... |
import random
import string
from model.project import Project
def random_string(maxlen):
symbols = string.ascii_letters + string.digits #+ string.punctuation + " "*2
return "".join([random.choice(symbols) for x in range(random.randrange(maxlen))])
project_1 = Project(random_string(15), random_string(15))
pr_... |
import skimage
import os
from skimage import io
# Reading image file
image2 = io.imread('C:\Users\KRISHNA\Desktop\index.jpg')
# Setting dimensions boundaries
x = 189 / 2
y = 267 / 2
r = 189 / 6
# Iterating to all the pixels in the set boundaries
for i in range(0, 189):
for j in range(0, 267):
if i ... |
from database.models import Policy, UserProfile, Community
from _main_.utils.massenergize_errors import MassEnergizeAPIError, InvalidResourceError, ServerError, CustomMassenergizeError
from _main_.utils.massenergize_response import MassenergizeResponse
from _main_.utils.context import Context
from django.db.models impo... |
from birgitta.project import Project
Project('tribune')
|
"""
The :mod:`skactiveml.stream.budgetmanager` module implements budget managers,
which are capable of modeling the budget constraints in stream-based active
learning settings.
"""
from ._balanced_incremental_quantile_filter import (
BalancedIncrementalQuantileFilter,
)
from ._estimated_budget_zliobaite import (
... |
# 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
"""Auto-generated package that contains models used b... |
from .noise import *
from .maths import *
from .utils import time_it
@time_it
def archipelago():
s1 = normalize(domain_warp(offsets=768)) * 3
s2 = normalize(perlin_square())
s3 = normalize(gauss_like())
result = normalize(normalize(((s1 * 2) + s2)) * s3)
return result
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image
import pytesseract
from StringIO import StringIO
import json
import gevent
import datetime
from config import Config
from app_config import Config as APP_CONFIG
from NUPTCrawlerBase import NUPTCrawlerBase
from lib.util import api
from lib.http impor... |
#ref: http://connor-johnson.com/2016/01/24/using-pywavelets-to-remove-high-frequency-noise/
import time
import pickle
#import pywt
import numpy as np
import matplotlib as mpl
mpl.rc('xtick', labelsize=30)
mpl.rc('ytick', labelsize=30)
mpl.rcParams.update({'errorbar.capsize': 2})
import matplotlib.pyplot as plt
i... |
from sqlalchemy.orm.exc import NoResultFound
from ..route_base import RouteBase
from .._util import _create_user, _create_container
from Hinkskalle.models.Entity import Entity
from Hinkskalle.models.User import User
from Hinkskalle import db
import datetime
class TestUsers(RouteBase):
def test_list_noauth(self):
... |
# Copyright (C) 2018-2019 Sam Li <yangsec888@gmail.com>
# This file is part of f5 secure admin API in Python
import sys
name = "f5_admin"
with open("LICENSE.txt", "r") as fh:
lic = fh.read()
#from f5.f5_client import (
# F5Client,
#)
__license__ = lic
__author__ = "Sam Li, yangsec888@gmail.com"
__version_... |
"""This module is the data preprocessor"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pandas as pd
import numpy as np
class Preprocessor:
"""This is a class contains functions of data preprocess"""
def read_data(self, file_name):
... |
from typing import Optional
from pydantic import BaseModel
from datetime import datetime
class Order(BaseModel):
id: Optional[str]
date: datetime
total: float
subtotal: float
taxes: float
paid: float |
import os
import random
import numpy as np
from slam.NFiSAM import NFiSAM_empirial_study
if __name__ == '__main__':
random.seed(0)
np.random.seed(0)
knots = [9]
iters = [2000]
training_samples = [2000]
learning_rates = [.025]
hidden_dims = [8]
run_file_dir = os.path.dirname(__file__... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import abc
import functools
__all__ = ['memoize']
def add_metaclass(metaclass):
pass
class abstractstatic(staticmethod):
__slots__ = []
def __init__(self, function):
super(abstractsta... |
def getAnalyzingFunction(user_ID, detection_module, check_ID, reserved):
return None,None,None |
#!/usr/bin/env python3
import unittest
from coin_flip_simulation import flip_coin
class Test(unittest.TestCase):
def test_flip_coin(self):
test1_result = flip_coin()
self.assertTrue(test1_result == "head" or test1_result == "tails")
if __name__ == "__main__":
unittest.main()
|
from livelossplot import MainLogger, PlotLosses
from livelossplot.outputs import BaseOutput
class CheckOutput(BaseOutput):
def send(self, logger: MainLogger):
assert isinstance(logger, MainLogger)
grouped_log_history = logger.grouped_log_history(raw_names=True, raw_group_names=True)
assert... |
def dobro(n=0, format=False):
return n * 2 if not format else moeda(n * 2)
def metade(n=0, format=False):
return n / 2 if not format else moeda(n / 2) #Esta linha (not format)
def aumentar(n=0, p=0, format=False):
r = n * (p / 100)
return n + r if format is False else moeda(n + r) #Igual a esta ... |
# https://www.reddit.com/r/dailyprogrammer/comments/3gpjn3/20150812_challenge_227_intermediate_contiguous/
import sys
def countchains(chains):
count = 0
for i, row in enumerate(chains):
for j, char in enumerate(row):
if char == 'x':
markchain(chains, i, j)
c... |
""" install.py: Instalation script for pksampler.
"""
import sys
import os, os.path
import distutils.sysconfig
import getopt
from pksampler.Globals import VERSION
## CONFIGURATION (internal)
USE_SUDO = True
# versions of pkaudio to look for.
USE_PKAUDIO_VERSIONS = ['0.3', '0.4']
# where the package is going
M... |
a = float(input())
if a < 100:
print('Less than 100')
elif a <= 200:
print('Between 100 and 200')
elif a > 200:
print('Greater than 200')
|
"""Message and inner object type identifiers for Connections."""
PROTOCOL_URI = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/present-proof/1.0"
# Message types
PRESENTATION_PROPOSAL = f"{PROTOCOL_URI}/propose-presentation"
PRESENTATION_REQUEST = f"{PROTOCOL_URI}/request-presentation"
PRESENTATION = f"{PROTOCOL_URI}/presenta... |
from replace_expression import main
def replace_last(line, old, new):
idx = line.rfind(old)
return line[:idx] + new + line[idx + len(old) :]
def replace_boost_static_assert(line, file_dir, iteration):
# replace use in line
line = line.replace("BOOST_STATIC_ASSERT_MSG", "static_assert")
... |
# Generated by Django 2.2.13 on 2020-08-28 12:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('chartofaccountDIT', '0004_auto_20200820_0751'),
]
operations = [
migrations.RenameField(
model... |
###############################
#
# Created by Patrik Valkovic
# 3/17/2021
#
###############################
"""
Module implementing algorithm's early termination logic.
"""
from .MetricBased import NoImprovement, MetricReached, StdBellow
|
from scipy.spatial import distance
import pprint
import argparse
from collections import namedtuple
from sklearn.metrics.cluster import adjusted_rand_score
import matplotlib.pyplot as plt
import time
pp = pprint.PrettyPrinter(indent=4)
UNCLASSIFIED, NOISE, CORE, BOUNDARY = -1, -2, -3, -4
DataPoint = namedtuple('DataP... |
"""
Setup Module to setup Python Handlers (Git Handlers) for the Git Plugin.
"""
import os
import setuptools
requirements_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'requirements.txt')
with open(requirements_file, 'r') as f:
required = f.read().splitlines()
setuptools.setup(
name='featur... |
import time
from functools import wraps
from typing import Any, Dict, Optional
from kivy.logger import Logger
from collections import defaultdict
PROFILER_STATS = defaultdict(list)
PROFILER_HISTORY = []
class measuretime:
"""
Usage:
with measuretime("my-name"):
func1()
func2()... |
"""
fishnchips - Fish n Chips
"""
__version__ = '0.1.0'
__author__ = 'Caglar Toklu <caglartoklu@gmail.com>'
__all__ = []
def say_the_word():
"""
Says the word.
"""
return " Chips"
|
import os
path = os.path.abspath(os.path.dirname(__file__)).replace("\\","/")
file_path = path + "/FileToDelete.txt"
f = open(file_path)
line = f.readline()
while line:
delete_path = path + line[19:].replace('\n','')
if os.path.exists(delete_path):
os.remove(delete_path)
else:
prin... |
import os
from tensorflow import keras
def loadModel(modelPath, modelWeightsPath, targetImageSize):
""" Builds and returns a new VGG19 model with imagenet weights. The topmost
layers are frozen and a dense layer with 4 outputs is appended. """
# Use VGG19 with imagenet weights
baseModel = keras.appli... |
def fasta_to_dict(fasta):
fasta_ids = [] # Initialize a list to be populated with fasta headers
fasta_id_position = [] # Initialize a list to be populated with index positions of each fasta header
fasta_seqs = [] # Initialize a list to be populated with fasta sequences
with open(fasta, 'r') as file:... |
"""
A ChoiceEnum to represent SequenceVariant_ values.
.. _SequenceVariant: https://dicom.innolitics.com/ciods/mr-image/mr-image/00180021
"""
from dicom_parser.utils.choice_enum import ChoiceEnum
class SequenceVariant(ChoiceEnum):
SK = "Segmented k-Space"
MTC = "Magnetization Transfer Contrast"
SS = "S... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2017 Alibaba Group Holding 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/LICENS... |
import os
import pkgutil
from importlib import import_module
def import_dir(dirname, package):
for _, package_name, is_pkg in pkgutil.walk_packages([dirname]):
if is_pkg:
import_dir(os.path.join(dirname, package_name), f"{package}.{package_name}")
else:
import_module("." + p... |
from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from . import auth
from .. import db
from ..models import User
from .forms import *
from ..decorators import admin_required
@auth.before_app_request
def before_request()... |
import os
from unittest import main
from pyfakefs.fake_filesystem_unittest import TestCase
from getgauge import static_loader as loader
from getgauge.lsp_server import LspServerHandler
from getgauge.messages.messages_pb2 import *
from getgauge.messages.spec_pb2 import ProtoStepValue
from getgauge.registry import regi... |
import networkx as nx
from networkx.drawing.nx_agraph import graphviz_layout
import numpy as np
import sys
sys.path.append('..')
from scripts.convert_graphs import nx2gt
def load_dendrogram(path: str) -> nx.Graph:
"""
Load dendrogram from a give file. The file should follow this structure:
# Tree struct... |
from __future__ import absolute_import
from distutils.core import Extension
from astropy_helpers import setup_helpers
def get_extensions():
exts = []
# malloc
mac_incl_path = "/usr/include/malloc"
cfg = setup_helpers.DistutilsExtensionArgs()
cfg['include_dirs'].append('numpy')
cfg['include_di... |
# Copyright 2020 DeepMind Technologies 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 ag... |
# -*- coding: utf-8 -*-
#
# © 2014, 2015 Ian Eure
# Author: Ian Eure <ian.eure@gmail.com>
#
"""Manufacturer prefixes."""
from collections import defaultdict
# Map of device manufacturer abbrev to parts prefix
_PREFIXES = {
'AMD': ('a', 'am', 'ampal', 'mach', 'pal', 'palce'),
'ASA': (), # FIX... |
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from rest_framework import viewsets
from parking.serializers import *
from parking.models import ParkingSlot, ParkingLot, OnStreetParkingSlot, Booking
from accounts.permissions import AnonReadCr... |
#!/usr/bin/env python
import os
import time
import re
# python3-psutil
import psutil
from kicad_auto.misc import (WRONG_ARGUMENTS)
from kicad_auto import log
logger = log.get_logger(__name__)
# Collected errors and unconnecteds (warnings)
errs = []
wrns = []
# Error filters
err_filters = []
def wait_for_file_creat... |
"""Base and reference implementations for `Broker` classes."""
from .base import Broker # noqa
from .redis import RedisBroker # noqa
|
from .kaibel_solve_gdp import build_model
__all__ = ['build_model']
|
import functools
from spaceone.api.board.v1 import board_pb2
from spaceone.core.pygrpc.message_type import change_struct_type
from spaceone.board.model.board_model import Board
from spaceone.core import utils
def BoardInfo(board_vo: Board, minimal=False):
info = {
'board_id': board_vo.board_id,
'... |
import matplotlib.pyplot as plt
import numpy as np
import random
import scipy.spatial
from collections import defaultdict
def collect_edges(pos, d_max, d_hop=None):
"""
Let two nodes be connected if their Euclidian distance is less
than ``d_max``. This function returns all pairs of nodes that
are dire... |
import pandas as pd
import numpy as np
import argparse
def extract_seg_dups(row, current_seg_dup_table):
filtered_seg_dup_table = current_seg_dup_table.loc[(current_seg_dup_table[2] <= int(row["POS"])) & (current_seg_dup_table[3] >= int(row["POS"]))]
occurences = len(filtered_seg_dup_table)
if occurence... |
"""
Converts segmentation masks of different types from different folders to YOLO format bounding boxes.
"""
import os
import sys
import cv2
from tqdm import tqdm
from skimage.measure import label, regionprops
if __name__ == "__main__":
GT_PATH = sys.argv[1]
labels = os.listdir(GT_PATH)
# conversion
... |
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
import os
from ecosante.extensions import celery, sib
from ecosante.utils import send_log_mail
from flask import current_app
@celery.task()
def send_unsubscribe(mail, send_mail=True):
if not send_mail:
return
send_log_mail(
"Dés... |
from typing import Dict , List , Any
from flask import request
from application.app import app,db
import datetime
from application.models import Food,FoodType
# Work , Fitness , Goal
#
@app.route("/")
def home():
return {"Status": "Success"}, 200
#
@app.route("/Food", methods=["POST"])
#sent data in dicti... |
"""
Configuration file for Atlas
All variable settings should go here so values can be propagated to the various
functions from a central location.
"""
import re
import os
from atlas.config_servers import (SERVERDEFS, VARNISH_CONTROL_TERMINALS, NFS_MOUNT_LOCATION,
BASE_URLS, API_URL... |
from hashlib import sha256
import time, multiprocessing, os, copy
from Orses_Competitor_Core.Compete_Process import genesis_block
from Orses_Competitor_Core.BlockCreator import GenesisBlockCreator
def competitive_hasher(enc_d):
return sha256(sha256(enc_d).digest()).hexdigest()
def get_qualified_hashes(prime_ch... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 26 13:51:54 2017
@author: Student
"""
from sklearn.naive_bayes import GaussianNB
import numpy as np
import csv
import pickle
def __loadData(dataFile):
data = []
with open(dataFile, 'rt') as csvfile:
datas = csv.reader(csvfile, delimiter = ',')
... |
import csv
import smtplib
import threading
import time
from kivy.app import App
from .prepare_message import PrepMessage
from queue import Queue
from smtplib import SMTPRecipientsRefused
from mailer.mailing_exceptions import FromError, SubjectError, ToError
class Mailer:
def __init__(self):
self.queue_siz... |
version = '2.0.935'
|
from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
import core.models as coremodels
# Landing Page for Index
class LandingView(TemplateView):
template_name = "blog/index.html"
# ... |
#!/usr/bin/python3 -i
import meraki
import copy
import os
import pickle
from meraki import aio
#from mNetlib import *
from mNetClone_aio import * #new library
import tagHelper2_aio
import time
import get_keys as g
async def main():
async with meraki.aio.AsyncDashboardAPI(
api_key=g.get_api_ke... |
from mpi4py import MPI
from torchvision.models import vgg16
from vgg_dist import DistributedVGG
import distdl
def generate_sequential_network(num_classes):
return vgg16(num_classes=num_classes)
def generate_distributed_network(num_classes):
P_world = distdl.backend.backend.Partition(MPI.COMM_WORLD)
P_... |
myArray = [1,2,2,4,5,6,7,8,8,8]
counter = 0
num = myArray
for i in myArray:
curr_frequency = myArray.count(i)
if(curr_frequency> counter):
counter = curr_frequency
num = i
print("Counter" ,counter)
print("Number", num)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
try:
from keras_applications import resnet
except:
resnet = None
from . import keras_modules_injection
@keras_modules_injection
def ResNet50(*args, **kwargs):
return resnet.ResNet50(*args, **kwarg... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Local
try:
from .tools.graph import *
except ImportError:
from welib.FEM.graph import *
# --------------------------------------------------------------------------------}
# --- Wrapper to convert a "fast" input file dictionary into a ... |
import pickle
import numpy as np
from utils.seq2seq.learning_core_20180401 import Seq2seqCore
def feeder_genrator(starting_point, xy_tuple, idx_token_dict, pretrained_dict, batch_size=128, dropout_rate=0.05):
feed_dict = dict()
refresh_flag = 0
x_data = xy_tuple[0]
y_data = xy_tuple[1]
if startin... |
from sqlalchemy import Column, Integer, BigInteger, ForeignKey, String
from bot.db.models.content.content import Content
class AbyssDungeon(Content):
clear_limit_count = 1
reset_period_in_day = 7
__tablename__ = "abyss_dungeon"
id = Column(BigInteger, ForeignKey('content.id'), primary_key=True)
... |
import array
import shutil
from pathlib import Path
import src.calculate_energy_density as energy_density
import src.calculate_h1 as h1_func
import src.calculate_magnetic_fields as magnetic
import src.calculate_radio_sfr as radio_sfr
import src.calculate_sfr as sfr
import src.calculate_surface_density as surf
import s... |
# -*- coding: utf-8 -*-
#=============================================================================
# Copyright : (c)2010-2012 semantics GmbH
# Rep./File : $URL$
# Date : $Date$
# Author : Christian Heimes
# License : BSD LICENSE
# Worker : $Author$
# Revision : $Rev$
# Purpose : help... |
import json
import logging
import random
from praw.exceptions import ClientException as RedditClientException
from tor.core.helpers import _, clean_id, send_to_modchat
from tor.core.initialize import initialize
from tor.core.user_interaction import process_done
def process_command(reply, cfg):
"""
This funct... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with th... |
import praw
from neo4j import BoltDriver
from typing import List, Union
from itertools import chain
from reddit_detective.relationships import Submissions, Comments, CommentsReplies
from reddit_detective.karma import (_remove_karma, _set_karma_subreddits, _set_karma_submissions,
_se... |
from django.core.management.base import BaseCommand
from ummeli.vlive.tasks import *
class Command(BaseCommand):
help = 'Enable/Disable commenting on articles'
def handle(self, **options):
disable_comments_scheduler()
|
import numpy as np
import pandas as pd
def get_time_of_week(dt):
return int(96 * dt.dayofweek + 4 * dt.hour + dt.minute / 15)
def get_t_cutoff_values(temp, cutoffs):
'''
Implements algorithm from Mathieu et. al
'''
results = np.zeros(len(cutoffs) + 1)
results[0] = min(cutoffs[0], temp)
for... |
import arc_utils as au
import arcpy
import os
def write_field_info(fc):
desc = arcpy.Describe(fc)
root_path = desc.path
fc_name = desc.name
print('getting field info from %s' % fc_name)
if fc_name.find(".") != -1:
fc_name = fc_name.split(".")[0]
a = open(os.path.join(root_path, fc_name... |
from factory import Factory
import ark
from tkinter import Tk
from ark.gui.gui_class import PyArcGui
def init():
root = Tk()
root.title(PyArcGui.gui_title)
root.geometry(PyArcGui.gui_size)
app = PyArcGui(root)
Factory.set('GUI',app)
from ark.gui.control import Control
Factory.set('GUI_CO... |
import urlparse
import uuid
import time
import logger
import couchdb
log = logger.Logger.get_logger()
class ResultsHelper(object):
def __init__(self, server):
parsed = urlparse.urlparse(server,"http")
self.scheme = parsed.scheme
self.username = parsed.username
self.password = pars... |
__all__ = ["err"]
|
from math import ceil
from typing import List
import numpy as np
from games.level import Level
from games.maze.maze_game import MazeGame
from games.maze.maze_level import MazeLevel
from novelty_neat.fitness.fitness import NeatFitnessFunction
from novelty_neat.generation import NeatLevelGenerator
from novelty_neat.maze... |
from diva import Diva
from diva.widgets import *
from diva.utilities import register_simple_util, register_widget_util, file_response
import pandas as pd
import tempfile
# if your utility has options that depend on the currently displayed value,
# of the figure, then use register_widget_util
def my_util_widgets(val)... |
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.tests.api_test_case import APITestCase
from impact.tests.factories import ProgramCycleFactory
class TestProgramCycle(APITestCase):
def test_str(self):
cycle = ProgramCycleFactory()
assert str(cycle) == cycle.name
|
'''
07 - Rotating x-tick labels
In this exercise, we'll continue looking at the miles per gallon dataset.
In the code provided, we create a point plot that displays the average
acceleration for cars in each of the three places of origin. Note that the
"acceleration" variable is the time to accelerate from 0 to 6... |
from .base import BaseLanguageTokenizer
from .japanese import JapaneseTokenizer, JapaneseMorphemeClassifier
from .english import EnglishTokenizer, EnglishMorphemeClassifier
__all__ = [
"BaseLanguageTokenizer",
"JapaneseTokenizer",
"EnglishTokenizer",
"JapaneseMorphemeClassifier",
"EnglishMorphemeCl... |
from cms.models import Page
from django.conf import settings
from django.urls import Resolver404, resolve, reverse
from django.utils.encoding import force_text
from menus.menu_pool import menu_pool
from djangocms_spa.content_helpers import (get_frontend_data_dict_for_cms_page, get_frontend_data_dict_for_partials,
... |
from limbs import limbs_mul_limb, limbs_add, limbs_sub, limbs_gte
LIMB_BITS = 64
# montgomery reduction of the product of two multiple-limb numbers
# implementation of HAC 14.36
def mulmodmont(x, y, mod, modinv, base) -> [int]:
assert len(x) == len(y), "equal sized numbers"
num_limbs = len(x)
A = [0] * nu... |
from .init import *
from .util import *
from .scoring import *
from .viz import *
from .lf_factories import *
from .features import * |
# Ensuring backwards compatibility
from .RTO1000 import RTO1000 as RTE1000
|
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import os
import pytest
from unittest.mock import patch
from intake import open_catalog
import dask.dataframe as dd
@pytest.fixture
def local_prefix_cat():
path = os.path.dirname(__file__)
return open_catalog(os.path.join(path, 'data', 'local.cata... |
# -*- coding: utf-8 -*-
'''
Created on 2013-1-10
@author: sinlangxmu@gmail.com
'''
import sys
import os
reload(sys)
File_PATH = os.path.dirname(os.path.abspath(__file__))
ROOT_PATH = os.path.abspath(os.path.join(File_PATH, '..'))
if ROOT_PATH not in sys.path:
sys.path.append(ROOT_PATH)
#sys.setdefaultencoding('ut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.