text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test FuncSpec for python and C right-hand sides.
"""
import os
import re
import pytest
from PyDSTool import (
FuncSpec,
RHSfuncSpec,
PyDSTool_KeyError,
args
)
def test_funcspec_raises_exception_if_there_are_invalid_keys():
args = {
'name... |
from tqdm import tqdm
import numpy as np
from PIL import Image
import argparse
import torch
from torch import nn, optim
from torch.autograd import Variable, grad
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, utils
from model import Generator, Discriminator
n_lab... |
# Copyright 2018 Tensorforce Team. 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 la... |
import urllib.request, json
import urllib
from datetime import datetime, timedelta
import xlrd
import time
import sys
from ShareAnalysis import IchimokuCloud
API_ALPHA = ""
ALL_SYMBOLS = 1 #excel coloumn references
SUBSET_SYMBOLS = 3
DELAY = 10 #api delay
class SymbolMetaData:
def __init__(self):
self.... |
import os
import base64
def decodeIMG(base, path):
imgdata = base64.b64decode(base)
filename = path + "/avatar.png"
with open(filename, "wb") as f:
f.write(imgdata)
def fill(data, media_path=None):
if media_path == None:
full_path = os.path.realpath(__file__)
pa... |
#<NAME> and <NAME>
import csv
def create_athletes_csv(athlete_events):
"""
Write the id, name, age, height, weight, and sport columns from athlete_events.csv into Athletes.csv
input: athlete_events.csv
output: None
"""
athlete_events_csv = athlete_events
duplicat... |
import os
import sys
import json
import datetime
import numpy as np
import skimage.draw
import cv2
from mrcnn.visualize import display_instances
import matplotlib.pyplot as plt
import skimage.io
from imgaug import augmenters as iaa
# Root directory of the project
ROOT_DIR = "/content/CITS5553IndivRepo/"
# Import Mask... |
import re
from JobSpec import JobSpec
# status codes for each event range
ST_ready = 0
ST_sent = 1
ST_running = 2
ST_finished = 3
ST_cancelled = 4
ST_discarded = 5
ST_done = 6
ST_failed = 7
ST_fatal = 8
ST_merged = 9
ST_corrupted = 10
ST_reserved_fail = 98
ST_reserved_get = 99
# ide... |
import argparse as ap
import logging
import pandas as pd
from typing import List, Tuple, Dict
from sklearn.metrics import precision_recall_fscore_support as prfs
import json
def _convert_by_setting(gt:List[List[Tuple]], pred:List[List[Tuple]], include_entity_types:bool=True):
assert len(gt) == len(pred)
# eit... |
# Copyright (c) 2019 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 app... |
# -*- coding: utf-8 -*-
import re
__all__ = ["LambdaError",
"Atom", "FreeVar", "BoundVar", "Lambda", "Expression", "Builtin",
"mkexpr", "evaluate",
"parseline", "parseFile",
"strict_limit", "builtins"]
def structCmp(*fields): # internal function; not for export
return ... |
from abc import ABCMeta, abstractmethod
import os
import re
import sys
import subprocess
import numpy as np
import shutil as sh
from cntk.graph import ComputationNode
from cntk.cntk1_ops import NewReshape
from cntk.utils import CNTK_EXECUTABLE_PATH
_FLOATX = 'float32'
CNTK_TEMPLATE_DIR = os.path.join(os.path.dirnam... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
import pytorch_cls.core.net as net
from pytorch_cls.core.config import cfg
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a ... |
# importing dependencies
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix # For computing accuracy
class BaseRegressor():
def __init__(self, num_feats, learning_rate=0.1, tol=0.001, max_iter=100, batch_size=12):
# initializing parameters
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline in source files... |
from platform import machine
import numpy as np
import exploratory
import bss_reader
import supercosmos_reader
import pandas as pd
import time
def find_closest_obj(catalog, target_coord):
"""reads a catalog file with args (objid, ra, dec) and the
position of a target object (target_ra, target_dec) and finds
... |
# Import PyQt wrappers
from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QLabel
from PyQt5.QtCore import QObject, QThread, pyqtSlot, pyqtSignal
from PyQt5 import QtCore
from PyQt5.QtGui import QPainter, QFont, QColor, QPen, QFontDatabase
from PyQt5 import uic
from PyQt5 import QtGui
import PyQt... |
"""Inception V2 (224x224) model for Keras.
Reference: (from tensorflow 'slim' library)
https://github.com/tensorflow/models/blob/master/research/slim/nets/inception_v2.py
This implementation differs from the original one:
* Not using SeparableConv2D in '1a'
* AveragePooling2D in inception module '5c'
* Ba... |
import os
import binascii
from attrdict import AttrDict
from solidity.interface import ContractInterface
from threading import Thread, Event
from web3 import Web3, HTTPProvider, WebsocketProvider
from utils.log import log
DEFAULT_HTTP_INSTANCE = 'http://127.0.0.1:8545'
# contract_dir = os.path.abspath('./test_contr... |
#!/usr/bin/env python
import numpy as np
import json
import rospy
import rospkg
import scipy.interpolate
import threading
import argparse
from std_msgs.msg import Header, Float64
from sub8_msgs.msg import Thrust, ThrusterStatus
from mil_ros_tools import wait_for_param, thread_lock
from sub8_msgs.srv import ThrusterInfo... |
import torch
import torch.nn.functional as F
import torch.nn as nn
import torchvision.transforms as transforms
import numpy as np
import json
import os
import os.path as osp
from PIL import Image
from PIL import ImageDraw
import time
import warnings
from tqdm import tqdm
from predict_pose import genera... |
import tbridge
import tbridge.plotting as plotter
from astropy.table import Table
from astropy.io import fits
import time
import traceback
from pebble import ProcessPool
from concurrent.futures import TimeoutError
from numpy import round, array
from numpy.random import choice, randint, seed
def pipeline(config, ma... |
#!/usr/bin/env python
# encoding: utf-8
"""
EEBNFTokeniser.py
Created by <NAME> on 2011-04-05.
Copyright (c) 2011 <NAME>. All rights reserved.
"""
import sys
import logging
logger = logging.getLogger("EEBNFTokeniser")
class EEBNFTokeniser():
def __init__(self):
self._lines = [] ... |
"""Data loading facilities for Omniglot experiment."""
import random
import os
from os.path import join
import torch
from torch.utils.data import DataLoader
from torch.utils.data.sampler import Sampler
from torchvision.datasets.omniglot import Omniglot as _Omniglot
from torchvision.datasets.utils import list_dir, list... |
import copy
import datetime
import unittest
import eduid_userdb.element
import eduid_userdb.exceptions
from eduid_userdb.element import Element
from eduid_userdb.phone import PhoneNumber, PhoneNumberList
__author__ = 'ft'
_one_dict = {
'number': '+46700000001',
'primary': True,
'verified': True,
}
_two_... |
#!/usr/bin/env python
# medicine.py
# Copyright (C) ContinuumBridge Limited, 2015 - All Rights Reserved
# Written by <NAME>
#
# Default values:
config = {
"medicine": True,
"medicine_name": "My_Medicine",
"time_slots": [
{
"name": "Morning",
"start": "07:00",
"e... |
# -*- coding: ascii -*-
# $Id$
#
# Author: <EMAIL>
# Date: 24-Aug-2014
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import os
import re
import sys
#import cgi
import json
import urllib
import tempfile
import threading
from CNC import CNC
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
tr... |
'''
Created on Jul 2, 2012
@author: Chris
'''
import thread, mob.group as group
from player_type import STARTING_GOLD, MONSTER, NEUTRAL, HUMAN
import player_type
import movement, reputation, income, fame
import core.process_manager as process_manager
import core.event_manager as event_manager
from core.event_manager i... |
"""Test scenario for assessments.
## Domain
* Users as in `conftest`, under *players*
* Clean slate, see `starters`.
* The user table
* The country table
* The contribution type table
* One contribution record
## Acts
`test_select`
: All users try to
* revoke the selection decision,
* sel... |
#
# Copyright 2019 Google LLC
#
# 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 ... |
# pylint: disable=invalid-name
from struct import pack, unpack
DEFAULT_COMPRESSION_LEVEL = 20
def rotate_left(a, b, bits=32):
a &= (1 << bits) - 1
return ((((a) << (b)) | ((a) >> (bits - (b))))) & ((1 << bits) - 1)
def quarter_round(w, a, b, c, d):
w[a] += w[b]
w[a] &= 0xFFFFFFFF
w[d] ^= w[a]
... |
## worker.py -- evaluation code
##
## Copyright (C) 2017, <NAME> <<EMAIL>>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')
from scipy.stats import entropy
from numpy.linalg... |
import matplotlib as mpl
mpl.use('TkAgg')
import sys
import numpy as np
from beluga.visualization import BelugaPlot
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
import functools as ft
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
filen... |
#!/usr/bin/python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
import os
import shutil
import tarfile
from wsgiref.util import FileWrapper
import mimetypes
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import DetailView, ListView, CreateView, DeleteView
from django.urls import reverse
from django.conf import settings
from django.http import H... |
"""
In our python interface to the backbone system, we separate the local collection
which stores models, from the http client which interacts with a remote store
In applications, we would use a class that combines both
"""
import logging
logger = logging.getLogger(__name__)
from collections import defaultdict
import... |
""" Tests for compatibility with the postponed evaluation of annotations. """
from __future__ import annotations
import typing
import pytest
import dataclasses
import sys
from dataclasses import dataclass
from typing import Any, Callable, Generic, TypeVar
import pytest
from simple_parsing import field
from .testutils ... |
"""Build CPython from source."""
import logging
import re
from collections import namedtuple
from pathlib import Path
import foreman
from g1 import scripts
from g1.bases.assertions import ASSERT
import shipyard2.rules.bases
LOG = logging.getLogger(__name__)
Version = namedtuple('Version', 'major minor micro')
sh... |
from __future__ import absolute_import
from tensorflow.keras import backend as K
from tensorflow.keras import optimizers
from tensorflow.keras import initializers
from tensorflow.keras import losses
from tensorflow.keras.layers import Dropout
from tensorflow.keras.callbacks import Callback, ModelCheckpoint
from tens... |
import pyxel
from functools import singledispatch
from pymunk import (
Space,
Body,
Circle,
Poly,
Segment,
Arbiter,
Shape,
ShapeFilter,
Vec2d,
)
from pyxel.ui.number_picker import NumberPicker
from pyxel.ui.widget import Widget
MOMENT_FACTOR = 1000
class Game:
"""
Jogo sim... |
"""SPYC (pronounced spicy).
Usage:
spyc plot <dir> [--verbose|--debug] [--url=<url>] [--port=<port>] [--header = <text>]
spyc -h | --help
spyc --version
Options:
--url=<url> Specify the URL
--port=<port> Specify the Port
--header Header to ... |
import numpy
import time
from functools import wraps
from xminds.compat import logger
from xminds.lib.arrays import set_or_add_to_structured
from synthetic.utils import set_random_seed
def timeit(f):
"""Decorator to time a method. Returns two outputs: the time to execute `f`, and f's outputs"""
@wraps(f)
... |
#!/usr/bin/env python3
# @Author: <NAME>
# @Date: 2016-04-19 12:29:20
# @Last Modified by: <NAME>
# @Last Modified time: 2016-04-19 14:03:33
# @MIT License
# @http://tasdikrahman.me
# @https://github.com/tasdikrahman
import argparse
from subprocess import call
import glob
import shutil
import json
import os
import... |
# Copyright 2021 The sunds 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 or agreed to in wr... |
import sys
from socket import *
serverPort = int(sys.argv[1])
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
def mail_time():
fromboolean = False
toboolean = False
databoolean = False
while fromboolean == False:
mailSet = connectionSocket.recv(1024).decod... |
#!/usr/bin/env python
#coding:utf-8
# Author: mozman (python version)
# Purpose: avl tree module (Julienne Walker's unbounded none recursive algorithm)
# source: http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx
# Created: 01.05.2010
# Copyright (c) 2010-2013 by <NAME>
# License: MIT License
# Concl... |
import typing as ty
from dataclasses import asdict, dataclass, astuple, field, replace, InitVar
# A kernel spec is composed of a top level AdditiveKernelSpec
# Each summand of an additive kernel is a product
# each product has a scalar and one or more operands
# product operands may be either base kernels or additi... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
import sys
import os
import time
import argparse
import numpy as np
import cv2
# from PIL import Image
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
from tool.utils import plot_boxes_cv2, load_class_names
def post_processing(cls, conf_thresh, nms_thresh, output):
# anchors = [12, 16,... |
from pseudorandom_generator import PNG_AES_CTR
from key_agreement import Diffie_Hellman
from Crypto.Random.random import randint # pip install pycryptodome
import matplotlib.pyplot as plt
import numpy as np
import time
import sys
# Add parent directory to import necessary modules
sys.path.append('..')
from model impor... |
import os
import signal
import numpy as np
from pynq import Xlnk, Overlay, DefaultIP, DefaultHierarchy
from utils.paths import lib_path
from utils.functions import float2reg
import logging
class PESMemoryMap(DefaultIP):
def __init__(self, description):
super().__init__(description)
bindto = ['xilin... |
import pygame
pygame.init()
win = pygame.display.set_mode((500,430))
screen='game'
pygame.display.set_caption("DBZ 1vs1")
#PLAYER 1 animations
walkRight = [pygame.image.load('right.png'), pygame.image.load('right2.png')]
walkLeft = [pygame.image.load('left.png'), pygame.image.load('left2.png')]
stan... |
import numpy
import keras
from keras.utils.np_utils import *
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from keras.layers import Embedding, concatenate
from keras.layers import Dense, Input... |
import pytest
from kbbq.gatk import applybqsr
from kbbq import compare_reads as utils
from kbbq import recaltable
import numpy as np
import filecmp
from pandas.util.testing import assert_frame_equal
import io
import pysam
@pytest.fixture
def small_report(report, tmp_path):
t = """#:GATKReport.v1.1:5
#:GATKTable:2:... |
import re
import json
import os
from datetime import datetime
from notify import notify
spend_categories = [
"Food",
"Groceries",
"Utilities",
"Transport",
"Shopping",
"Miscellaneous",
]
choices = ["Date", "Category", "Cost"]
spend_display_option = ["Day", "Month"]
spend_estimate_option = ["Ne... |
from __future__ import division
"""Interpret data from a linear oscillatory rheometer, particularly an interfacial stress rheometer.
The ``params`` dictionaries that are used in this module can have the following entries
(all in SI units):
'm'
Tool (i.e. needle) mass
'a'
Needle diameter
'R'
Gap between ne... |
import logging.config
import datetime as dt
import platform
import pathlib
import logging
import shutil
from typer import Argument as A_, Option as O_
import pydantic
import click
import typer
import toml
from cs_tools.helpers.cli_ux import console, CSToolsGroup, CSToolsCommand
from cs_tools.helpers.loader import _ga... |
import sys
import logic
import pygame
BLACK = (0, 0, 0)
WHITE = (200, 200, 200)
BLOCK_SIZE = 70
WINDOW_HEIGHT = 0
WINDOW_WIDTH = 0
class Ball:
def __init__(self, neighbours, maximum, value, position):
self.color = "" # String : "Green" or "Red"
self.neighbours = neighbours # Lis... |
# Copyright (C) 2019-2021 Zilliz. 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... |
from functools import lru_cache
import numpy as np
from numba import njit, prange
# @njit()
# def get_patterns(l):
# patterns = np.zeros((l, l), dtype=np.int64)
# for k in range(1, l + 1):
# patterns[k-1] = get_pattern(k, l)
# return patterns
@njit(parallel=True)
def get_pattern(n, l):
patter... |
"""rio_glui.server: tornado tile server and template renderer."""
import os
import logging
from io import BytesIO
from concurrent import futures
import numpy
from rio_tiler.colormap import cmap
from rio_tiler.profiles import img_profiles
from rio_tiler.utils import linear_rescale, render
from rio_color.operations im... |
"""!Takes an object tree from produtil.parse.Parser and turns it into
a flat bash script that will run the entire test suite, one test at a
time."""
import StringIO
__all__=['bash_functions','BashRunner']
import produtil.testing.parsetree
from produtil.testing.utilities import PTParserError
##@var bash_functions
#... |
from datetime import datetime
# Use to generate token
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from app import db, login_manager
from flask_login import UserMixin
from flask_authorize import RestrictionsMixin, AllowancesMixin
UserGroup = db.Table(
'user_g... |
"""
Image utilities.
| Copyright 2017-2022, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import logging
import multiprocessing
import os
import eta.core.image as etai
import eta.core.utils as etau
import fiftyone.core.utils as fou
import fiftyone.core.validation as fov
logger = logging.getLogger(__n... |
#!/usr/bin/env python3
# Copyright (c) 2019 <NAME> -- MIT License
"""General-purpose state machine engine with extras and tracing."""
from collections import deque, namedtuple
import re
#####
### State Machine Core ###
# Note: For clarity, we will refer to the edges of a state diagram as "rules" and the _operati... |
# ## IMPORTS ## #
import pygame
from pygame import gfxdraw
import json
print('\npygame_ui v1.0')
pygame.init()
# ## THEME_VARS ## #
# buttons
btn_colour_normal = 180, 180, 180
btn_colour_hover = 160, 160, 160
btn_colour_click = 210, 210, 210
btn_colour_border = 140, 140, 140
btn_radius_border = 10
bt... |
# -*- coding: utf-8 -*-
"""
Main module of top down greedy anonymizaiton algorithm
"""
import operator
import pdb
import random
import time
from functools import cmp_to_key
from basic_mondrian.models.numrange import NumRange
from basic_mondrian.utils.utility import cmp_str, get_num_list_from_str
__DEBUG = False
QI_... |
from multiprocessing import Process
from os import environ, remove
import re
from time import asctime, gmtime, sleep, time
import docker
from pytest import fixture
from brain import r as rethinkdb, connect
from src import controller_plugin
CLIENT = docker.from_env()
NOW = time()
SAMPLE_TARGET = {
"id": "w93hyh-v... |
# Copyright (C) 2017 <NAME>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or (at
# your option) any later version.
# This program is distributed in the hope ... |
"""
Created on Oct 21, 2015
@author: xiao
"""
from collections import namedtuple
import numpy as np
# bbox indices
x0 = 0
y0 = 1
x1 = 2
y1 = 3
class Segment(namedtuple("Segment", ["e", "vector"])):
__slots__ = ()
@property
def length(self):
return self.vector[x0] if self.vector[x0] else self... |
"""
pbsv1 end to end pipeline,
inputs: reads.bam + ref.fa
outputs: sv calls.bed
steps: ngmlr, markduplicates, chain, svcall
"""
from __future__ import absolute_import
import getpass
import logging
import os
import os.path as op
import tempfile
from .independent.utils import (realpath, mktemp_cmd, mv_cmd, bai_of_bam,
... |
"""Functions performing various calculations."""
import numpy as np
import pandas as pd
from functools import reduce
from typing import List, Union
import sympy
import numbers
from .C import *
import petab
__all__ = ['calculate_residuals', 'calculate_residuals_for_table',
'get_symbolic_noise_formulas', 'e... |
# -*- coding: utf-8 -*-
"""
基于 resnet50 实现的图片分类代码
在 ModelArts Notebook 中的代码运行方法:
(1)训练
cd {run.py所在目录}
1)从零训练
python run.py --data_url='../datasets/train_data' --train_url='../model_snapshots' --num_classes=54 --deploy_script_path='./deploy_scripts' --test_data_url='../datasets/test_data' --max_epochs=6
2)加载已有模型继续训练
cd... |
# from DataGen.NetworkToTree import *
import networkx as nx
import pandas as pd
import numpy as np
import copy
# CHERRY FEATURES
def cherry_features(cher_cont_tree, tree_set, str_features=None, num_net=0, tree_cher=None, root=0, distances=True, comb_measure=True):
if str_features is None:
str_features = ... |
import gzip
import http
import shutil
from datetime import datetime
from os import makedirs, remove, path
import requests
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from grimoire_elk.enriched.mbox import MBoxEnrich
from grimoire_elk.enriched.pipermail import PipermailEnrich
from... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import os.path
import json
import numpy as np
import sys
import torch
import torch.utils.data as data
from pyquaternion import Quaternion
from scipy.spatial import distance
sys.path.append('../models')
import quat_ops
import torch.nn.functional as F
import warnin... |
"""
This plugin captures logging statements issued during test execution. When an
error or failure occurs, the captured log messages are attached to the running
test in the test.capturedLogging attribute, and displayed with the error failure
output. It is enabled by default but can be turned off with the option
``--nol... |
# Retro Winnipeg Weather Channel
# By probnot
# Updates for Edmonton weather
# By ehushagen
# code is scrounged together, please be kind
from tkinter import *
import time
import datetime
from env_canada import ECData
import feedparser
# clock Updater
def clock():
current = time.strftime("%I:%M:%S"... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, <NAME>, 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:
#
# * Redistributions of source code must retain the above copyri... |
"""
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance wit... |
import sys
from pyspark import SparkContext
from csv import reader
from operator import add
import datetime
def week(datetimestr):
#get weeknumber of the yaer
date = int(datetimestr)
year = date // 10000
month = (date % 10000) // 100
day = date % 100
isoyear, isoweeknum, isoweekdaynum = datetime.date(year, month... |
import matplotlib.pyplot as plt
import sqlite3
import pandas as pd
import numpy as np
import folium
from math import sqrt
# connect database
def connect(path):
conn = sqlite3.connect(path)
c =conn.cursor()
c.execute('PRAGMA foreign_keys=ON; ')
conn.commit()
return conn, c
def get_range_years():
... |
#!/usr/bin/env python3
import queue
import serial
import serial.tools.list_ports
from signal import signal, SIGINT
import sys
import threading
import time
COM_OVERRIDE=None
VERSION='1.0'
DEBUG=False
running = True
def on_closing():
global running
running = False
print('Quitting')
def sig_handler(signal... |
# -*- coding: utf-8 -*-
from preprocess.load_data import load_data
from preprocess.translator import translator
from preprocess.statistic import label_statistic
from preprocess.make_index import make_index
from preprocess.make_index import transform
from neuralnet.train_nn import train_nn
from datetime import datetime
... |
# type: ignore
import pandas as pd
from plotnine import *
import warnings
import os
import matplotlib
warnings.filterwarnings("ignore")
pd.set_option('display.max_rows', None)
# avoid Type 3 fonts
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
# raw column names
THREADS = "threads"
... |
# --------------------------------------------------------
# Written by <NAME>
# Adapted from https://github.com/valeoai/ADVENT/tree/master/advent
# --------------------------------------------------------
import copy
import json
import logging
import os
import os.path as osp
import time
import numpy as np
... |
import os
import math
import random
import argparse
import itertools
def plus_(s): return s + [s.pop(-2) + s.pop()]
def minus_(s): return s + [s.pop(-2) - s.pop()]
def mult_(s): return s + [s.pop(-2) * s.pop()]
def divd_(s): return s + [s.pop(-2) / s.pop()]
def input_(s): return s + [eval(input())]
def rinp_(s): r... |
"""Utilities used in the driving-off analysis.
"""
from dataclasses import dataclass
import logging
from typing import Optional, List
import multiprocessing as mp
from joblib import Parallel
import pandas as pd
import numpy as np
import geopandas as gpd
from shapely.geometry import LineString
from .path_extraction i... |
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import Ridge, LinearRegression
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.base import TransformerMixin, BaseEstimator
impo... |
# Copyright 2019 <NAME>
import ipaddress
import pickle
import re
from datetime import datetime, timedelta
from threading import Thread
import sentry_sdk
from flask import Flask, render_template, request, redirect
from sentry_sdk.integrations.flask import FlaskIntegration
import config
from models import RouteServer
... |
""" Gathers and saves the partitions of data for all domains. This includes creating the initial subset of data for faster processing.
Author: <NAME>
"""
import os
import math
import torch
import time
import numpy as np
from sklearn.utils import shuffle
from transformers import DistilBertTokenizer,DistilBertModel
d... |
# -*- coding: utf-8 -*-
""" Example of simulation of a geothermal system with multiple boreholes.
The g-function of a bore field is calculated for boundary condition of
mixed inlet fluid temperature into the boreholes. Then, the borehole
wall temperature variations resulting from a time-varying load profil... |
import django_filters
from django_countries.widgets import LazySelect
import htmlgenerator
from django import forms
from django.utils.html import mark_safe
from django.utils.translation import gettext as _
from .button import Button
from .icon import Icon
from .notification import InlineNotification
class Form(html... |
from .header import *
from .biencoder import BertEmbedding, BERTBiEncoder
'''Deep Hashing for high-efficient ANN search'''
class HashBERTBiEncoderModel(nn.Module):
'''Joint learn the hsahing code and the contextual embedding:
1. hashing module is the regularization for the bi-encoder module,
2. bi-en... |
from flask_restplus import Namespace, fields
import socket
import time
from datetime import datetime, date, time, timedelta
from flask import jsonify, request
from database import DB
from bson import json_util, ObjectId
from apis.utils.common import *
from apis.libraries.send_mail import Send_mail
import requests
impor... |
# Copyright (c) 2016 Hewlett-Packard Enterprise Development Company, L.P.
# 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/lic... |
from typing import Iterable
from delphin import variable
from delphin.lnk import Lnk
from delphin.sembase import Predication
from delphin import scope
TOP_NODE_ID = 0
FIRST_NODE_ID = 10000
RESTRICTION_ROLE = 'RSTR' # DMRS establishes that quantifiers have a RSTR link
BARE_EQ_ROLE = 'MOD'
EQ_POST ... |
# 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... |
import numpy as np
import tensorflow as tf
import os
import json
import pandas as pd
import pickle
import time
from scipy import ndimage
from vgg.vgg16 import *
def _process_caption_data(caption_file, image_dir, max_length):
with open(caption_file) as f:
caption_data = json.load(f)
# id_to_filename is a diction... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 00:57:51 2017
@author: Moti
"""
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 9 11:21:10 2017
@author: Moti
"""
import csv
import numpy as np
from collections import deque
import math
from datetime import datetime
impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.