text stringlengths 3.07k 12.6k |
|---|
# ------------------------------------------------------------------------
# Copyright (c) 2021 megvii-model. All Rights Reserved.
# ------------------------------------------------------------------------
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from typing import List
fro... |
# coding = utf-8
import numpy as np
from feature_extractor import log_power_spectrum_extractor
from matplotlib import pylab
import matplotlib.pyplot as plt
from scikits.talkbox import lpc
from scipy.signal import lfilter, lfilter_zi, lfiltic
from scipy.io import wavfile
def freq2bark(f):
return 7.*np.log(f/650.+... |
from scrapy import Request
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from spider.items.CrazyItem import CrazyItem
def str2num(string):
try:
return float(string)
except ValueError:
return None
class CrazySpider(CrawlSpider):
name = "crazy_... |
import dash
from dash import Dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import dashwellviz.figures
import helper
# Load Data
data_df = helper.load_data()
data_df = helper.add_vp_vs(data_df)
# set up options f... |
from __future__ import absolute_import, print_function
import subprocess
import os
import time
from lwp.exceptions import ContainerDoesntExists, ContainerAlreadyExists, ContainerAlreadyRunning, ContainerNotRunning,\
DirectoryDoesntExists, NFSDirectoryNotMounted
# LXC Python Library
# Original author: <NAME>
# ... |
"""The Control4 integration."""
import asyncio
import json
import logging
from aiohttp import client_exceptions
from pyControl4.account import C4Account
from pyControl4.director import C4Director
from pyControl4.error_handling import BadCredentials
from homeassistant.config_entries import ConfigEntry
from homeassista... |
"""
search_16S.py - a python implementation of the 16S identification method described by
<NAME>. See preprint: https://www.biorxiv.org/content/biorxiv/early/2017/04/04/124131.full.pdf
For the kmer counting, I've used khmer's [https://github.com/dib-lab/khmer] CountGraph, which works
well for small values of k (like t... |
import h5py
from . import _version as ver
from . import pkl
try:
# PY 3
from . import base as bm
except ImportError:
# PY 2
import base as bm
import numpy as np
import six
def hdf5_write(buf, indat, chunks=True, compression='gzip'):
if isinstance(buf, six.string_types):
# If it is a filena... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 <NAME> <<EMAIL>>
#
# Distributed under terms of the MIT license.
"""Read input files and compute dynamic and thermodynamic quantities."""
import datetime
import logging
from pathlib import Path
from typing import Any, Dict, Iterator,... |
"""
Credits:
* https://code.google.com/p/webscraping/source/browse/webkit.py
* https://github.com/jeanphix/Ghost.py/blob/master/ghost/ghost.py
"""
#import time
#import sys
from PyQt4.QtCore import QEventLoop, QUrl, QEventLoop, QTimer, QByteArray, QSize
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWe... |
"""
.. module:: riemann
:synopsis: Riemann output
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import time
import random
from twisted.internet import reactor, defer, task
from twisted.python import log
# pylint: disable=C0412
try:
from OpenSSL import SSL
from twisted.internet import ssl
except:
SSL = None
... |
#
# Copyright (C) 2020-2021 Arm Limited or its affiliates and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Definition of an SPDX report for a Python project."""
from pathlib import Path
import os
from spdx.writers.tagvalue import write_document
from typing import Optional, List, cast, ... |
# -*- coding: utf-8 -*-
# Copyright 2018-2022 the orix developers
#
# This file is part of orix.
#
# orix 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) ... |
import os
from astropy import units as u
import numpy as np
import pytest
import tardis
from tardis.io.config_reader import Configuration
from tardis.io.model_reader import (
read_artis_density,
read_simple_ascii_abundances,
read_csv_composition,
read_uniform_abundances,
read_cmfgen_density,
r... |
from collections import defaultdict
import random
from typing import List, Dict, Tuple, Set, Union
from dataclasses import dataclass
import csv
@dataclass
class Student:
ime: str
priimek: str
vpisna_stevilka: str
def csv_vis_type(filename):
with open(filename) as f:
reader = csv.DictReader(f... |
#!/usr/bin/env python3
import sys
import freetype
import string
import math
import os.path
CHARS = string.ascii_letters + string.digits + string.punctuation
CHAR_NUMS = [ord(x) for x in CHARS]
if len(sys.argv) != 3:
print("Usage: {} [font file] [font size in pixels]".format(sys.argv[0]))
print("or : {} [fon... |
def func1():
from dtlpy.utilities import DatasetGenerator
import dtlpy as dl
dataset = dl.datasets.get(dataset_id='611b86e647fe2f865323007a')
datagen = DatasetGenerator(data_path='train',
dataset_entity=dataset,
annotation_type=dl.AnnotationT... |
#
# Copyright 2019 The FATE 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 2018 The TensorFlow Constrained Optimization 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
#
#... |
# coding=utf-8
# Copyright 2018 The Batfish Open Source Project
#
# 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 requi... |
import re
# Models Import
from .models import Solved, ListExtraInfo
from user.models import Profile
# Serializers Import
from .serializers import ProblemSerializer
from .solved_update import codeforces, uva, atcoder, codechef, spoj, atcoder_scraper_check
def update_submissions(qs, user, help_dict):
# param :
... |
# Databricks notebook source
class Paths():
def __init__(self, working_dir, clean_lesson):
self.working_dir = working_dir
self.user_db = f"{working_dir}/{clean_lesson}.db"
self.checkpoints = f"{working_dir}/_checkpoints"
def exists(self, path):
try: return len(db... |
"Cartesian arrays, arrays defined over a cartesian communicator"
__all__ = [
"CartComm",
]
from math import ceil
from dask.core import flatten
from dask.array import Array, zeros, ones, empty, full
from dask.array.core import normalize_chunks
from lyncs_utils import add_to
from .comm import CartComm
class KeyPa... |
#*******
#* Read input from STDIN
#* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line.
#* Use: sys.stderr.write() to display debugging information to STDERR
#* ***/
import math
import sys
import time
start_time = time.time()
class Graph(object):
def __init__(... |
# cython: language_level = 3
from functools import lru_cache
from .algorithms import reverse_path_iterator
class SimpleNode:
"""
A simple node base class used for tree building.
It requires at minimum a key and a parent.
The children of a given node are stored in a dict
with their keys as diction... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 <NAME>
# Copyright (c) 2008-2020 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following c... |
#!/bin/python3
# TODO: Add means of checking the last pickle save time and starting a new instance if the pickle is too old
from typing import List, Optional
from requests import Response
from selenium.common.exceptions import TimeoutException, StaleElementReferenceException
from selenium.webdriver.remote.webelement ... |
#!/usr/bin/env python3
# Copyright 2020 <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 required by applicable law or agreed... |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, Inc.
#
# 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 ... |
from rest_framework import serializers
import re
from rest_framework_jwt.settings import api_settings
from django_redis import get_redis_connection
from goods.models import SKU
from .models import User, Address
from celery_tasks.email.tasks import send_verify_email
class CreateUserSerializer(serializers.ModelSeriali... |
"""Common get info functions for interface"""
# Python
import re
import logging
# unicon
from unicon.core.errors import SubCommandFailure
# Genie
from genie.metaparser.util.exceptions import SchemaEmptyParserError
from genie.libs.parser.utils.common import Common
log = logging.getLogger(__name__)
def get_interfac... |
#!/usr/bin/env python3
# author: greyshell
# description: demo how to use heapq library
import heapq
class MaxHeapNode(object):
def __init__(self, key):
self.key = key
def __lt__(self, other):
# compare based on val
# tweak the comparison logic to build max heap: change less_than_si... |
#!/usr/bin/env python
"""Tests for `evolved5g` package."""
import pytest
import os
from click.testing import CliRunner
from evolved5g import cli
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return re... |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distribut... |
import logging
from django.core.exceptions import FieldError
from django.db.models import Count, Prefetch
from rest_framework import exceptions, filters, serializers, viewsets
from url_filter.integrations.drf import DjangoFilterBackend
from apps.stories.models import (
Aside,
Byline,
InlineHtml,
Inlin... |
"""
Demo Flask application to test the operation of Flask with socket.io
Aim is to create a webpage that is constantly updated with random numbers from a background python process.
30th May 2014
===================
Updated 13th April 2018
+ Upgraded code to Python 3
+ Used Python3 SocketIO implementation
+ Updated... |
"""
PyTeapot module for drawing rotating cube using OpenGL as per
quaternion or yaw, pitch, roll angles received over serial port.
"""
import json
import math
import pygame
from OpenGL.GL import *
from OpenGL.GLU import *
from pygame.locals import *
def main():
pygame.init()
screen = pygame.display.set_mode... |
#
# Brownie Learn
#
# Firmware: maixpy_v0.5.0_9_g8eba07d_m5stickv.bin
# http://dl.sipeed.com/MAIX/MaixPy/release/master/maixpy_v0.5.0_9_g8eba07d
#
import brownie as br
import KPU as kpu
import sensor, lcd, time, image, network, socket
import uos
import gc
import ulab as np
from Maix import GPIO
from fpioa_manager impor... |
from dataclasses import dataclass
from typing import TypeVar
T = TypeVar('T', str, float, int)
ZH_NUM = {
'〇': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5,
'六': 6, '七': 7, '八': 8, '九': 9, '零': 0,
'壹': 1, '贰': 2, '叁': 3, '肆': 4, '伍': 5,
'陆': 6, '柒': 7, '捌': 8, '玖': 9, '貮': 2, '两': 2,
}
ZH_UNIT = {
... |
# Python Version: 3.x
"""
the module for CodeChef (https://www.codechef.com/)
"""
import json
import re
import urllib.parse
from logging import getLogger
from typing import *
import requests
import onlinejudge._implementation.testcase_zipper
import onlinejudge._implementation.utils as utils
import onlinejudge.dispat... |
#!/usr/bin/env python
# * coding: utf8 *
'''
download.py
A script that downloads CSVs of electrofishing data for a given
set of sampling event ids.
'''
import csv
import secrets
import sys
from glob import glob
from os import mkdir, walk, sep
from os.path import basename, dirname, exists, join, realpath, normpath
from... |
import os.path
import ast
import ast_parser
import result_formatter
import itertools
from whoosh.index import exists_in, create_in, open_dir
from whoosh.fields import Schema, TEXT, ID
from whoosh.query import Term, Every
def create_new_index(path, name, tokenizer_options):
if exists_in(path, name):
raise ... |
import datetime
import getpass
import socket
import time
from dataclasses import dataclass
import invoke
import paramiko
from fabric import Connection
@dataclass
class RemoteRunner:
"""
Starts Jupyter lab on a remote resource and port forwards session to
local machine.
Returns
-------
Remote... |
# IMPORTS
from collections import OrderedDict
import numpy as np
import warnings
"""
Read FreeSurfer geometry (fix for dev, ll 126-128);
Code was taken from nibabel.freesurfer package (https://github.com/nipy/nibabel/blob/master/nibabel/freesurfer/io.py).
This software is licensed under the following license:
The M... |
# Copyright 2017 AT&T Intellectual Property. All other 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... |
import argparse
from bs4 import BeautifulSoup
from enum import Enum
from functools import reduce
import os
import re
import requests
CRAN_PACKAGE_URL_FORMAT = "https://cran.r-project.org/web/packages/{package}/index.html"
def get_cran_url(package_name: str) -> str:
return CRAN_PACKAGE_URL_FORMAT.format(package=p... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def make_3d_grid():
"""Generate a 3d grid of evenly spaced points"""
return np.mgrid[0:21, 0:21, 0:5]
def homo_coordinate(g):
"""Transform a numpy 3D meshgrid to 3D data points in homogeneous coordinates"""
ax... |
from urlparse import parse_qs
import logging
from google.appengine.api.urlfetch import (
GET,
POST,
fetch,
)
import oauth2
from app.routes import OAUTH_CALLBACK_ONLY
from app.secrets import (
FACEBOOK_APP_ID,
FACEBOOK_APP_SECRET,
GITHUB_CLIENT_ID,
GITHUB_CLIENT_SECRET,
GOOGLE_CLIENT_ID... |
import logging
from nose.tools import *
from dbsync.lang import *
from dbsync import models, core, client
from dbsync.client.compression import (
compress,
compressed_operations,
unsynched_objects)
from tests.models import A, B, Base, Session
def addstuff():
a1 = A(name="<NAME>")
a2 = A(name="<N... |
import tensorflow as tf
import typing as T
from tensorflow_trees.definition import NodeDefinition
class GatedFixedArityNodeDecoder(tf.keras.Model):
""" Build a dense 2-layer which is optimized for left-0-padded input """
def __init__(self, *, activation=None, hidden_coef: float= None, embedding_size: int = ... |
# File name: make.py
# Author: <NAME>
# Date created: 31-07-2018
"""Module for calculating the amount to add of each ingredient when making a buffer/solution."""
from buf.commands import chemical, recipe
from buf import unit, error_messages
import tabulate
instructions = """buf make:
This subcommand calculates the ... |
import numpy as np
import cv2
import requests
import sys
import time
V_CENTER = 130;
V_MARGIN_L = 110;
V_MARGIN_H = 150;
H_CENTER = 400;
H_MARGIN_L = 420;
H_MARGIN_H = 380;
def tallyCommand(url):
r = requests.get("http://" + url + "/cgi-bin/aw_ptz?cmd=%23DA&res=1")
print(r.text)
if r.status_code == 200... |
"""
Filter result for searching best alpha values in temporal trimming.
used after 'search_best_perms.py'.
"""
import os
import json
import numpy as np
def run_exp(cmd):
return os.system(cmd)
def get_maps(base_dir, trim, alpha, load_name='val_3 & triplet'):
# filename50 = '{:s}video-ap-results-{:s}-{:02d}_... |
import math
from transforms import calc_vel_inc, normalize_vector
def uni2diff(v, w, L, R):
"""
Convert unicyle to differential
:param v: Linear velocity
:param w: Angular velocity
:param L: Wheel base (or track) width
:param R: Wheel radius
:return: left/right velocity
"""
#print... |
import cv2
import numpy as np
import os
import time
import sys
from datetime import datetime
import queue
import threading
import random
import requests
from weakref import WeakValueDictionary
IMAGES_FOLDER = "images/"
IMAGES_PREFIX = "_IMAGE_"
SENTINEL = "END"
NUM_THREADS = 1
q = queue.Queue()
workers = []
c... |
#!/usr/bin/env python3
# _____ _____
# /\ | __ \| __ \
# / \ | |__) | |__) | <NAME>
# / /\ \ | _ /| ___/ github:https://github.com/adithya-r-prabhu
# / ____ \| | \ \| |
# /_/ \_\_| \_\_|
# Python Script that Lets u open bookmarks from Dmenu..Bookmarks are s... |
from youtubesearchpython import VideosSearch
import os
from os import path
import random
import asyncio
import shutil
from time import time
import yt_dlp
from Music import converter
from pyrogram import Client
from pyrogram.types import Message
from pyrogram.types import Voice
from Music import (app, BOT_USERNAME, BOT_... |
# Icon made by surang from www.flaticon.com
# Icon made by Freepik from www.flaticon.com
import pygame
import random
import math
import time
from pygame import mixer
pygame.init()
clock = pygame.time.Clock()
# Game variables
SCREENWIDTH = 800
SCREENHEIGHT = 600
black = (0, 0, 0)
player_vel = 5
targe... |
# Copyright (C) 2015-2021 Regents of the University of California
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import random
from argparse import ArgumentParser
import cv2
import numpy
class InvisibleWaterMark:
def __init__(self, seed):
self.seed = seed
def encode(self, image, watermark, result):
img = cv2.imread(image)
watermark = cv2.... |
#The MIT License (MIT)
#
#Copyright (C) 2014 OpenBet Limited
#
#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,... |
#!/usr/bin/env python3
import sys
try:
import ply.yacc as yacc
except:
print("PLY must be installed for python3")
from function_to_lexed import *
# underscore names are not imported by default
from function_to_lexed import _function_lexer
strip_arc_dict = {"arccos" : "acos",
"arcsin" : "asi... |
import time
from collections import Counter
from functools import partial
import pandas as pd
import torch
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.data.dataset import random_split
from torchtext.vocab import Vocab
def process_to_pytorch(file_path, max_lines):
# just go throu... |
import logging
from sviit.disk import Disk
from sviit import util
def read_word(bytes, pos):
return bytes[pos] + bytes[pos+1] * 256
def read_float(bytes):
num = 0
for b in bytes[1:]:
num = num * 10 + b / 16
num = num * 10 + b % 16
while num >= 1:
num /= 10.0
num = num * 10 ... |
from __future__ import unicode_literals
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import time
from spotipy.oauth2 import SpotifyOAuth
import os
import youtube_dl
import urllib
import urllib.request
import json
from mutagen.id3 import APIC, ID3
from mutagen.easyid3 import EasyID3
from PIL import... |
from itertools import combinations
import numpy as np
import gurobipy as gp
from gurobipy import GRB
def kstsp(number_of_points, number_of_similar_edges, number_of_cycles, points_by_cycle):
# edges cost
def distance (source, target):
return np.linalg.norm(target - source, ord=2)
def make_edges_c... |
#!/usr/bin/env python3
# std
import subprocess
import logging
from pathlib import Path
import argparse
import json
# 3rd
from flask import Flask
from flask import render_template, redirect, send_file, request
from bokeh.embed import components
from bokeh.resources import INLINE
import tabulate
# ours
from verzettler... |
import csv
import datetime
import json
import os
import re
import typing
from argparse import ArgumentParser, Namespace
from base64 import b64encode
from hashlib import sha256
from prettytable import PrettyTable
def convert_domain(domain: str) -> str:
"""Convert string to the Google Chrome domain format"""
o... |
#https://github.com/rileynwong/lstm-jazz/blob/master/train.py
import glob
import pickle
import numpy as np
import os
from common import show_train_history
from music21 import converter, instrument, note, chord
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Conv1D, TimeDistri... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import urllib.parse as urlparse
from abc import ABC, abstractmethod
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple
from urllib.parse import parse_qs
import pendulum
import requests
from airbyte_cdk import AirbyteLogger
fro... |
# _*_ coding : UTF-8 _*_
import argparse
import pickle
import sys
import time
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
mean = [0.5070751592371323, 0.48654887331495095, 0.4409178433670343]
std = [0.2673342858792401,... |
# Copyright (c) 2020 <NAME>
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import serial
import os
import threading
import select
import queue
import argparse
from enum import IntEnum
from datetime import datetime
class SerialSniff(threading.Thread):
DEFAULT_TIMEOUT ... |
__doc__ = "a module that houses utilities for the autorestart library"
__author__ = "<NAME> (<EMAIL>)"
#-------------------------------------------------
import os
import logging
import random
import time
import subprocess as sp
### non-standard libraries
import psutil # use this to re-launch processes as well (sim... |
# Author: <NAME>
"""
I/O support for FASTQ files
"""
__all__ = [ "FastqRecord",
"FastqReader",
"FastqWriter",
"qvsFromAscii",
"asciiFromQvs" ]
import numpy as np
from .base import ReaderBase, WriterBase
from .FastaIO import splitFastaHeader
from pbcore import sequence
... |
#!/usr/bin/env python3
"""
Tests the grand_trade_auto.general.email_report functionality.
Per [pytest](https://docs.pytest.org/en/reorganize-docs/new-docs/user/naming_conventions.html),
all tiles, classes, and methods will be prefaced with `test_/Test` to comply
with auto-discovery (others may exist, but will not be p... |
def rotate_array_left_by_one(input_array):
"""
Idea is to save first ele and then shift all elements from an array to
one position ahead, at last put saved first ele to last pos in array
:param input_array: list --an input array
:return:
"""
temp = input_array[0]
for index in range(0, le... |
from __future__ import absolute_import, division, print_function
import csv
import logging
import os
import sys
from io import open
logger = logging.getLogger(__name__)
class RelationInputExample(object):
def __init__(self, id, concept1, concept2, relation):
self.id = id
self.concept1 = concept1... |
# Copyright (c) 2018 Cisco and/or its affiliates.
# 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... |
"""
Copyright 2013 Rackspace
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
dist... |
#!/usr/bin/python2.7 -tt
"""
Copyright (c) 2013, <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 of source code must retain the above copyright notice, this
list of condition... |
from functools import partial
import numpy as np
from matplotlib import pyplot as plt
import sys
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QFileDialog, QPushButton, QHBoxLayout, QVBoxLayout, QLabel
from PyQt5.QtGui import QPixmap
import pickle as pkl
from gym_minigrid.minigrid import Grid
... |
"""Unit tests for the Quality-time notifier."""
import json
import pathlib
import unittest
from copy import deepcopy
from datetime import datetime
from unittest.mock import AsyncMock, Mock, mock_open, patch
from quality_time_notifier import most_recent_measurement_timestamp, notify, record_health, retrieve_data_model... |
#PyJ2D - Copyright (C) 2011 <NAME> <https://gatc.ca/>
#Released under the MIT License <https://opensource.org/licenses/MIT>
from java.util import BitSet
from pyj2d.color import Color
__docformat__ = 'restructuredtext'
def from_surface(surface, threshold=127):
"""
**pyj2d.mask.from_surface**
Return ... |
#!/usr/bin/env python
"""Sample script of recursive neural networks for sentiment analysis.
This is Socher's simple recursive model, not RTNN:
<NAME>, <NAME>, <NAME>, and <NAME>.
Parsing Natural Scenes and Natural Language with Recursive Neural Networks.
in ICML2011.
"""
import argparse
import collections
impo... |
# encoding: utf-8
"""
Parser for Compact XML Expression Language (CXEL) ('see-ex-ell'), a compact
XML specification language I made up that's useful for producing XML element
trees suitable for unit testing.
"""
from __future__ import print_function
from pyparsing import (
alphas, alphanums, Combine, dblQuotedSt... |
# -*- coding:utf-8 -*-
# Copyright (c) 2015, Galaxy Authors. All Rights Reserved
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# Author: <EMAIL>
# Date: 2015-04-29
import socket
import threading
import thread
import struct
import logging as logger
from google.p... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# BSD 3-Clause License
#
# Copyright (c) 2021, Lucina
# 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 r... |
import numpy as np
import warnings
def Bernstein(t):
"""
Returns the weights of 3rd-order Bernstein polynomial
t: [0.0:1.0]
"""
t1 = 1.0 - t
b0 = t1*t1*t1/6.0
b1 = ( 3.0*t*t*t - 6.0*t*t + 4.0) / 6.0
b2 = (-3.0*t*t*t + 3.0*t*t + 3.0*t + 1.0) / 6.0
b3 = t*t*t/6.0
... |
import config
import os, shutil, tarfile, sys
import numpy as np
from PIL import Image
from PIL import ImageOps
def extract_files(tar_dir, untar_dir):
for model_tar in sorted(os.listdir(tar_dir)):
model = model_tar[:-4]
print('Extracting model: ' + model)
# Extract file
tar =... |
# Copyright 2019 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 writing, ... |
import datetime
from time import sleep
import gym
import numpy as np
import tensorflow as tf
import distributed as dist
from rl.agent import KerasAgent, EpsilonAgentWrapper
from rl.gym import GymExperienceGenerator, ExperienceBuffer, IndexedActionWrapper, LogisticObservationWrapper
from rl.metrics import AgentPerform... |
from sqlalchemy import Column, BigInteger, Integer, String
from geoalchemy2 import Geometry
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class OSMPoint(Base):
__tablename__ = 'planet_osm_point'
osm_id = Column(BigInteger, primary_key=True)
access ... |
# Utilities for manipulating word data structures
#
# Copyright (c) 2018-2021 <NAME>. See file LICENSE and https://ylonen.org
import re
import collections
from .config import WiktionaryConfig
from wikitextprocessor import ALL_LANGUAGES, Wtp
# Mapping from language name to language info
languages_by_name = {x["name"]... |
from concurrent.futures import ThreadPoolExecutor
import threading
import socket
import sys, os
from pathlib import Path
from .utils import parse_args_for_fns
import subprocess as sp
from .extract_xds_info import xds_parser
try:
from instamatic import config
HOST = config.settings.indexing_server_host
PO... |
#
# GSC-18128-1, "Core Flight Executive Version 6.7"
#
# Copyright (c) 2006-2019 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 fi... |
import ctypes
import math
import sys
PYTHON3 = sys.version_info >= (3, 0)
def to_int(x, d=0):
if not PYTHON3:
return int(math.trunc(x))
else:
return int(x)
class Rotor(object):
def __init__(self, key):
self.key = [0, 0, 0, 0, 0]
self.seed = [0, 0, 0]
self.size = ... |
import torch
#import fire
from random import shuffle
from .tokenizer import Tokenizer
try:
from transformers import DistilBertTokenizer, BertTokenizer, AutoTokenizer
except:
from pytorch_transformers import DistilBertTokenizer, BertTokenizer, AutoTokenizer
class Dataset(object):
""" An abstract class to... |
from django.contrib.admin import AdminSite
from django.contrib.auth.models import Group, User
from django.test.client import RequestFactory
import pytest
from katka.admin import (
ApplicationAdmin,
CredentialAdmin,
CredentialSecretAdmin,
ProjectAdmin,
SCMPipelineRunAdmin,
SCMRepositoryAdmin,
... |
import collections
from collections import OrderedDict
import copy
import pandas as pd
import numpy as np
from datetime import date, timedelta
pd.options.display.float_format = '{:.8f}'.format
def _generate_output_error_msg(fn_name, fn_inputs, fn_outputs, fn_expected_outputs):
formatted_inputs = []
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.