text stringlengths 3.07k 12.6k |
|---|
from math import *
class Tile(): #Class to hold tile data
def __init__(self):
self.x = 0
self.y = 0
self.onFire = 0
self.already_spread = False
self.wind_strength = 0
self.wind_direction = 0
self.dryness = 0
... |
__author__ = '<NAME>'
import numpy as np
import os # For path names being viable under Windows and Linux
# Let's reuse the stuff from the previous example
from example_05_custom_parameter import euler_scheme, FunctionParameter, diff_lorenz
from pypet import Environment, ArrayParameter
import matplotlib.pyplot as plt... |
# -*- coding: utf-8 -*-
from luckydonaldUtils.logger import logging
try:
from werkzeug.exceptions import HTTPException
from werkzeug.routing import MapAdapter
from flask.globals import _app_ctx_stack, _request_ctx_stack
from flask import url_for, request
except ImportError: # pragma nocover
from ... |
import numpy
import sympy
from ..helpers import article
from ..helpers import fs_array as fs
from ..helpers import fsd, pm, untangle, z
from ._helpers import DiskScheme
from ._peirce_1956 import peirce_1956_1, peirce_1956_3
from ._radon import radon
_citation = article(
authors=["<NAME>", "<NAME>"],
title="Nu... |
from __future__ import print_function, absolute_import
import random
from clusterjobs import datafile
import environments
import explorers
from ..tools import chrono, autosave
from .. import provenance
def exploration_step(env, explorer, tries=3):
"""Explore the step"""
try_count = 0
while try_count < ... |
from kyupy import sdf, verilog
def test_parse():
test = '''
(DELAYFILE
(SDFVERSION "OVI 2.1")
(DESIGN "test")
(DATE "Wed May 31 14:46:06 2017")
(VENDOR "saed90nm_max")
(PROGRAM "Synopsys Design Compiler cmos-annotated")
(VERSION "I-2013.12-ICC-SP3")
(DIVIDER /)
(VOLTAGE 1.20:1.... |
import ast
import astunparse
import os
import tempfile
import nbformat
import pytest
import shutil
from wranglesearch import convert_candidates as cc
def create_dir_with_files(_dir, file_names):
if not os.path.exists(_dir):
os.mkdir(_dir)
file_paths = [os.path.join(_dir, n) for n in file_names]
f... |
from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort
from grunt.auth import login_required
from grunt.db import get_db
bp = Blueprint('weapons', __name__)
class WeaponRequest:
def __init__(self, request):
self.weapon_name = re... |
import os
import numpy as np
from scipy.interpolate import splev, splrep, interp1d
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.ticker import FuncFormatter
from floris.utils.visualization import property as ppt
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++... |
# -*- coding: utf-8 -*-
from django.urls import reverse
from django.db import models
from django.conf import settings
from pyzotero import zotero
library_id = settings.Z_ID
library_type = settings.Z_LIBRARY_TYPE
api_key = settings.Z_API_KEY
def fetch_bibtex(zot_key):
""" fetches the bibtex dict of the passed in... |
# Copyright (c) 2007-2009 <NAME> <<EMAIL>>
#
# 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, publ... |
import torch
from more_itertools import flatten
SEGMENT_ID_QUESTION = 0
SEGMENT_ID_SCHEMA = 1
def encode_input(question_spans, column_names, table_names, values, tokenizer, max_length_model, device):
all_input_ids = []
all_attention_mask = []
all_question_span_lengths = []
all_column_token_lengths =... |
import json
from constants import SENTIMENT_EXPERIMENTS_DIR, MAX_SENTIMENT_SEQ_LENGTH, SENTIMENT_DOMAINS, \
SENTIMENT_TOPICS_DOMAIN_TREAT_CONTROL_MAP_FILE, SENTIMENT_TOPICS_DATASETS_DIR, SENTIMENT_TOPICS_PRETRAIN_IXT_DIR
from pytorch_lightning import Trainer
from BERT.bert_text_classifier import LightningBertPretr... |
# This holds a large number of specific functions used in 'convert_script.py'.
import os
import sys
import json
import cv2
import dlib
# import `consts.py` from the parent directory
from os.path import abspath, join, dirname
sys.path.append(abspath(join(dirname(abspath(__file__)), '..')))
import consts
# indexes in... |
#!/usr/bin/env python3
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
"""VGG Series
VGG: `"Very Deep Convolutional Networks for Large-Scale Image Recognition"
<https://arxiv.org/abs/1409.1556>`_
"""
from typing import Any, Mapping, Sequence
import megengine as mge
import megengine.hub as hub
import megeng... |
import datetime
import uuid
from authlib.oauth2.rfc6749 import AuthorizationCodeMixin
from authlib.oauth2.rfc6749 import ClientMixin
from authlib.oauth2.rfc6749 import TokenMixin
from authlib.oauth2.rfc6749 import util
from canaille.ldap_backend.ldapobject import LDAPObject
class Client(LDAPObject, ClientMixin):
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel
from torchdiffeq import odeint
class LatentODEFunc(nn.Module):
def __init__(self, k, input_size, hidden_size):
super(LatentODEFunc, self).__init__()
self.layers = nn.ModuleList([
nn.Sequential(... |
# coding=utf-8
# Copyright 2022 The HuggingFace datasets Authors, DataLab Authors and the current dataset script contributor.
#
# 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://ww... |
#coding:utf-8
"""
对bugreport进行预处理,
1.分句
2.分词
3.过滤标点符号
4.过滤停用词
5.提取词干
"""
import nltk
from nltk import sent_tokenize
import numpy as np
import pandas as pd
import re
import inflection
import string
from assets import stop_words, java_keywords
from nltk.stem.porter import PorterStemmer
from nltk.stem import SnowballStem... |
import glob
import os
import numpy as np
import pandas as pd
from loguru import logger
import time
from vimms.Common import load_obj, get_default_scan_params, get_dda_scan_param, INITIAL_SCAN_ID
def get_schedule(n, schedule_dir, sleep=True):
while True:
files = sorted(glob.glob(os.path.join(schedule_dir... |
import os.path
import csv
import numpy as np
import matplotlib.pyplot as plt
from argparse import ArgumentParser
from collections import namedtuple, OrderedDict
from typing import List, Dict, Tuple
from adaptiveleak.utils.file_utils import save_json, iterate_dir, read_json
# Records the current (mA), voltage (V), and... |
from __future__ import division, print_function
import ntpath
import numpy.linalg as npl
import numpy as np
import sklearn
from scipy.sparse.csgraph import shortest_path
import sys
from scipy.stats import spearmanr, pearsonr
from sklearn.metrics import euclidean_distances
def contacts2distances(contacts):
""" I... |
"""
File description
"""
# import modules
import numpy as np
import pickle
from obspy.taup.tau import TauPyModel
import mysql.connector
import math
__author__ = "<NAME>"
__copyright__ = ""
__license__ = ""
__version__ = "1.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = ""
def make_grid(lat_min, lat... |
import constants
# TODO: Move elsewhere
from metrics import confusion_dataframe
from exceptions import DriveSecretsNotFound
from visualizations import (
plot_loss, plot_bleu, plot_rouge, plot_f1,
plot_all_scores, plot_num_names)
import os
import datetime
import pickle
from io import StringIO
from pydrive.au... |
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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
#
# U... |
# -*- coding: utf-8 -*-
class TagMatcher(object):
"""Abstract base class that defines the TagMatcher protocol."""
def should_run_with(self, tags):
"""Determines if a feature/scenario with these tags should run or not.
:param tags: List of scenario/feature tags to check.
:return: Tr... |
import os
from .. package import Package
from .. process import *
class PicardCommand(dict):
Command = "__command__"
def __call__(self):
args = ["%s=%s" for kv in self.items()]
args = str.join(' ', args)
cmd = "%s %s" % (self.Command, args)
os.shell(cmd)
class MarkDuplicates(P... |
import asyncio
import json
import redis2
from aiogram import Bot, types
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import DetailView
from viberbot import Api
from viberbot.api.bot_configuration import BotConfig... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 09:25:11 2018
@author: cenv0574
"""
import os
import json
from geopy.distance import vincenty
from boltons.iterutils import pairwise
import geopandas as gpd
import shapely.ops
import pandas as pd
import shapely.wkt
import shutil
def load_config():
"""Read config.... |
"""Serves the API that enables searching the backend"""
import os
from typing import Tuple
from itertools import chain
from datetime import datetime, timedelta
from cleanbay.backend import Backend, InvalidSearchError
from cleanbay.torrent import Category
from cleanbay.plugins_manager import NoPluginsError
from fastap... |
import sys
import math
import dash
import dash_core_components as dcc
import dash_daq as daq
import dash_html_components as html
import plotly.graph_objects as go
from dash import callback_context
from dash.dependencies import Output, Input
from data import klines_futures, group_candles
buttons = [5, 15... |
"""All tsvalid check functions."""
# A check has exactly two arguments (a string, representing the value of a line, a cell or another parameter,
# and a dictinary representing the context. A check marshals a result object, which is also a dictionary.
import re
import string
from typing import Any, Dict
from tsvalid.c... |
import matplotlib
from matplotlib.colors import Colormap, LinearSegmentedColormap, ListedColormap
import numpy as np
class WrappedColormap(Colormap):
"""
`WrappedColormap` wraps around an instance of `matplotlib.colors.Colormap`,
provides the `luma` method, but otherwise does nothing to the colormap.
"""
def __i... |
import os
import numpy as np
from ..dataloader.data_info import Data2D
class BSLParsingError(Exception):
pass
class BSLLoader:
"""
Loads 2D SAS data from a BSL file.
CLoader is a C extension (found in c_ext/bsl_loader.c)
See http://www.diamond.ac.uk/Beamlines/Soft-Condensed-Matter/small-angle/S... |
import string_grouper
import editdistance
from .dbquery import *
import pandas as pd
#class Groups:
# the final variable we are constructing
groups = {}
# tracks the last group-id assigned
new_gid = 0
# what are all the cited references??
dd = count_docs(
by={"ref":Cit.full_ref},
min_count = 2
)
strings... |
# -*- coding: utf-8 -*-
__all__ = ('__version__', 'Block', 'Window')
from typing import Optional, Sequence, List, Union, Callable, Tuple
from timeit import default_timer as timer
import abc
import time
import threading
import attr
import blessed
from . import exceptions
Title = Union[str, Callable[[], str]]
Content... |
#!/usr/bin/env python3
import os
import sys
import yaml
import shlex
import utils.common as common
from pykwalify.core import Core
from pykwalify.errors import SchemaError
class SuiteParser:
def __init__(self, filepath):
self.contexts = []
self.met_required = False
self.filepath = file... |
import os
import re
import config
import helpers
# http://www.zytrax.com/tech/web/regex.htm # http://regex101.com/#python
def com(string): return re.compile(string) # RE Compile
def cic(string): return re.compile(string, re.IGNORECASE) # RE Compile Ignore Case
class SubtitleHelper(object):
def __init__(self,... |
"""
Composes a plot out of the given precision/recall (PR) curves. The PR curves are given as CSV files
with the points on the precision/recall curve. Each CSV file is loaded and plotted onto the same
canvas and is assigned the name in the corresponding given label field.
The script generates several files - a PDF and... |
#-----------------------------------------------------------------------------#
# MODULE DESCRIPTION #
#-----------------------------------------------------------------------------#
"""RedBrick Configuration Module; contains local configuration information."""
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests, threading
import sys, logging, time
# Parse command line arguments
import argparse
parser = argparse.ArgumentParser(description='A tool for sniffing Ticwatch firmwares, enjoy!')
parser.add_argument('-d', '--debug', help='display debug info', action='store_tru... |
import datetime
import logging
import sys
import types
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from django.db.models import NOT_PROVIDED
from django.utils.encoding import force_str
from unicef_vision.exceptions import VisionException
from unicef_vision.loaders import FileDataLoader... |
from thinglang.lexer.lexical_token import LexicalToken
from thinglang.lexer.tokens.indent import LexicalIndent
from thinglang.lexer.tokens.misc import LexicalGroupEnd
from thinglang.lexer.tokens.separator import LexicalSeparator
from thinglang.lexer.values.identifier import Identifier, GenericIdentifier
from thinglang.... |
#!/usr/bin/env python
"""
Contains the Node class definition
Please note that this module is private. The Node class is
available in the main ``wpipe`` namespace - use that instead.
"""
import socket
from .core import datetime, si
from .core import initialize_args, wpipe_to_sqlintf_connection, in_session
from .core im... |
#!/usr/bin/python
# Copyright: (c) 2018, Pluribus Networks
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['... |
# Copyright (c) 2020-2021 <NAME> IT-Services GmbH
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import os
from decimal import Decimal
from random import randint
from typing import Any
import click
import pytest
from bitcointx... |
import torch
import torchvision.models.resnet as resnet
class ResnetBackbone(torch.nn.Module):
def __init__(self, backbone='resnet50', pretrained=False):
super().__init__()
self.encoder0, self.encoder1, self.encoder2, \
self.encoder3, self.encoder4, self.fpn, self.outplanes = \
... |
'''EfficientNet model for PyTorch
[EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946v5)
'''
import torch
import torch.nn as nn
from math import ceil
class CNNBlock(nn.Module):
def __init__(self,
in_channels,
out_channels,
... |
#!/usr/bin/python3
# coding: utf-8
"""
This module is to handle subtitle.
"""
import re
import logging
import os
import shutil
from pathlib import Path
import pysubs2
from chardet import detect
from common.utils import get_locale
def get_encoding_type(source):
"""
Get file encoding type
"""
with open... |
#!/usr/bin/env python3
"""Create processed pseudogenes annotation track."""
import argparse
import sys
import os
from collections import defaultdict
try:
from modules.common import chain_extract_id
from modules.common import bed_extract_id
from modules.common import load_chain_dict
except ImportError:
... |
from __future__ import annotations # NOTE: prevents the use of < python3.7
from enum import Enum
from functools import reduce
from math import log2
from math import log10
class Unit:
def __init__(self, name, *aliases):
self.name = name
self.aliases = aliases
def __repr__(self):
retu... |
# Import all necessary libraries and setup ≥˘the environment for matplotlib
# %matplotlib inline
from pyspark.sql import SparkSession
from pyspark.sql.types import *
from pyspark.ml.feature import PCA
from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAs... |
from building_data_requests import get_value, get_bulk
from main import HeatmapMain
import pandas as pd
import numbers
import requests
from tempfile import mkstemp
from shutil import move
from os import fdopen, remove
current_air_data = None
rooms_and_sensors = None
def init_data_tools(rooms_and_sensors_path):
g... |
import numpy
import itertools as it
def meshgrid_nd(*arrays,**kwargs):
"""
Creates coordinate tensors from an arbitrary number of one-dimensional
coordinate vectors. With 2 arguments, the behavior is identical to
numpy.meshgrid.
This can be useful, e.g. for evaluating a function that takes ndarrays
on an N-dim... |
import os.path
import jsons
from oauth2client.service_account import ServiceAccountCredentials
import gspread
from shopheroes.gspread_formatting_utils import get_effective_formats
from shopheroes.definitions import Quality
from shopheroes.definitions import ItemDef
from shopheroes.definitions import HeroDef
from shoph... |
from natsort import natsorted
import os
import requests
import shutil
import constants
import settings
import utils
import version
unv_path = "cdn/img"
def update_cdn():
global unv_path
if not os.path.exists(os.path.join(settings.config['cdn']['cdn_root'], "api")):
os.makedirs(os.path.join(settings.... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# In[4]:
import argparse
import cv2
import numpy as np
import os
import sys
sys.path.append('../')
#from mtcnn.core.detect import MtcnnDetector,create_mtcnn_net
from tool.imagedb import ImageDB
from tool.imagedb import TestImageLoader
from tool.utils import IoU
imp... |
import gws
import gws.lib.shape
import gws.lib.style
import gws.lib.svg
import gws.lib.xml2
import gws.types as t
_COMBINED_UID_DELIMITER = '___'
def from_geojson(js, crs, key_column='id') -> gws.IFeature:
atts = {}
uid = ''
for k, v in js.get('properties', {}).items():
if k == key_column:
... |
import random, time
import pygame
from pygame.locals import *
'''Created By <NAME>'''
gravity = False
class particles:#particles class stores a particle
def __init__(self,x,y,xVel,yVel,col,partType, grav):#construct requires x,y,x velocity, y velocity, color, type, and boolean gravity
self.x = x
se... |
import numpy as np
class UnoEnvironment:
ALL_CARDS = [[color, type] for color in range(4) for type in range(13)]
ALL_CARDS += [[None, 13], [None, 14]]
ALL_CARDS = np.array(ALL_CARDS)
def __init__(self, num_players):
self.num_players = num_players
self.reset()
def _next_turn(s... |
# Copyright (c) 2014, <NAME>
# All rights reserved.
# See the LICENSE file for license information.
import numpy as np
from numpy.testing import (assert_allclose, assert_array_equal,
assert_, dec, run_module_suite)
import scipy
from scipy.integrate import odeint
from odeintw._odeintw import ... |
import cv2
import torch
from albumentations.augmentations.functional import longest_max_size
from pytorch_toolbelt.utils.torch_utils import rgb_image_from_tensor, to_numpy
from xview.dataset import (
INPUT_IMAGE_PRE_KEY,
INPUT_IMAGE_POST_KEY,
INPUT_MASK_PRE_KEY,
OUTPUT_MASK_PRE_KEY,
INPUT_MASK_POST... |
#!/usr/bin/env python
import sys
import os
import argparse
import despydmdb.desdmdbi as desdmdbi
# assumes partitions to drop start with F (firstcut, finalcut)
def empty_se_objects_table(dbh):
sql = "select partition_name from all_tab_partitions where table_name='SE_OBJECT' and table_owner=(select user from dual... |
# -*- coding: utf-8 -*-
"""
Functions used to download data over HTTP connections
"""
from functools import partial
import logging
import socket
import struct
import gevent
from os.path import join
from requests import RequestException, Session, HTTPError
from tranny import app
from tranny import exceptions
log = log... |
import re
from collections import OrderedDict, defaultdict
from importlib import import_module
from pathlib import Path
from typing import Union, Tuple, Dict
import ujson
from marshmallow import Schema, fields, validate, ValidationError, post_load
from ruamel.yaml import YAML
from dtran import Pipeline
from dtran.ifu... |
from datetime import datetime
import sys
import os
import argparse
import socket
import struct
from collections import namedtuple
import cv2
import numpy as np
import time
import datetime
import logging
# Logging config
logging.basicConfig(level=logging.INFO)
# Each port corresponds to a single stream type
STREAM_POR... |
#!/usr/bin/env python3
import socket, random, hashlib
def ip4b_2_number(ip_pkt):
"""ipv4 bytes转换为数字"""
return (ip_pkt[0] << 24) | (ip_pkt[1] << 16) | (ip_pkt[2] << 8) | ip_pkt[3]
def ip4s_2_number(string):
"""ipv4 字符串转换为数字"""
ip_pkt = socket.inet_aton(string)
return ip4b_2_number(ip_pkt)
def ... |
# stdlib imports
from typing import Optional
from typing import Union
from dataclasses import dataclass
from re import sub
from datetime import date
from dateutil import relativedelta
# Dependency imports
from jinja2 import Template
from jinja2 import Environment
from jinja2 import PackageLoader
from jinja2 import sel... |
import logging
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats.stats import pearsonr
from statsmodels.tsa.stattools import adfuller
log = logging.getLogger(__name__)
def calculate_stop_loss(data, direction: str, position=0, factor=3.0):
"""
Calculates the price of a stop or... |
from flask import render_template, request
from werkzeug.utils import secure_filename
from app import app
import logging
import sys
import os
import pandas as pd
import json
import uuid
import flask_executor
import threading
from app.backend import server_tools, tools
UPLOAD_FOLDER = sys.path.append(os.p... |
import pandas as pd
import random
from difflib import SequenceMatcher
from Common import ConfigFile as CF
from Symbolic import ClusterError
from Symbolic.DataStructs import *
from math import ceil
wo_err_id = True
def error_args():
print("Usage: python test_train_split.py dataset [split_ratio]")
print("Ex: ... |
# -*- coding: utf-8 -*-
import re
from .tokenizer import Token
class Entity(object):
def __init__(self, _name=""):
self.name = _name
self.parent = None
class Macro(Entity):
pass
class Member(Entity):
pass
class Variable(Entity):
def __init__(self, **kwargs):
super(Variab... |
"""
File: babygraphics.py
Name: 賴珈汶
--------------------------------
SC101 Baby Names Project
Adapted from <NAME>'s Baby Names assignment by
<NAME>.
"""
import tkinter
import babynames
import babygraphicsgui as gui
FILENAMES = [
'data/full/baby-1900.txt', 'data/full/baby-1910.txt',
'data/full/baby-1920.txt', ... |
from datetime import date, datetime
from decimal import Decimal
from model import Cash, Currency, Instrument, Stock, Bond, Option, OptionType, Position, Trade, TradeFlags
from parsetools import lenientParse
from pathlib import Path
from typing import Dict, List, NamedTuple, Optional
import csv
import re
def schwabDe... |
# -*- coding: utf-8 -*-
import sys, os
import pandas as pd
import numpy as np
from data_factory.temperature_spider import getTemperatureData
def loadNTL(path):
lineloss = pd.read_csv(path)
lineloss['Date'] = pd.to_datetime(lineloss['Date'])
lineloss = lineloss.sort_values(['AreaID', 'Date'])
linelos... |
#! /g/kreshuk/pape/Work/software/conda/miniconda3/envs/cluster_env37/bin/python
import os
import json
import luigi
from cluster_tools import MulticutSegmentationWorkflow
from cluster_tools.postprocess import SizeFilterAndGraphWatershedWorkflow
# TODO once we have proper validation set up, we should check for the
# ... |
import numpy as np
from agents import Agent
import time
import math
from random import choice
from time import time
from connectboard import ConnectBoard
class Model(object):
"""The actual AlphaFour Neural Network.
TODO: All the challenging stuff
"""
def value(self, state):
# FIXME: Implemen... |
"""Unit tests for math helper functions."""
# Copyright 2011, 2012, 2013, 2014, 2015 <NAME>
# This file is part of armspeech.
# See `License` for details of license and warranty.
import unittest
import numpy as np
import numpy.linalg as la
import random
from numpy.random import randn, randint
from codedep import co... |
import datetime
import django
import sys
import os
from api_test.serializers import ProjectDynamicDeserializer
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
PathProject = os.path.split(rootPath)[0]
sys.path.append(rootPath)
sys.path.append(PathProject)
os.environ.setdefaul... |
"""
PROBLEM
nI laser physics, a "white cell" is a mirror system that acts as a delay line for the laser beam. The beam enters the
cell, bounces around on the mirrors, and eventually works its way back out.
The specific white cell we will be considering is an ellipse with the equation 4x^2 + y^2 = 100
The section corr... |
import unittest
from textpipeliner import *
from textpipeliner.pipes import *
import spacy
# _sentence will be used throughout the all tests as it is time-consuming to create it.
# The fact of time-consumption is also reason for keeping all tests in single module file
_sentence = None
def setUpModule():
nlp = sp... |
from mandaw import *
# Window
mandaw = Mandaw("Platformer", bg_color = "cyan")
# Ground
ground = GameObject(mandaw, shape = "rect", width = 5000, height = 100, x = mandaw.width / 2 - 500, y = 500, color = "gray")
# Objects list
objects = []
# Player
class PlatformerController(GameObject):
def __init__(self):
... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 参考資料
# https://deepinsider.jp/tutor/introtensorflow/buildcnn
# 毎回同じ結果になるように固定値で乱数を初期化
tf.set_random_seed(1)
# MNISTデータセットの読み込み
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
n = 0
# 畳み込み層
def convol... |
# Reference: https://github.com/miloharper/visualise-neural-network
from math import cos, sin, atan
import numpy as np
from matplotlib import pyplot
from modules.saferegion import SafeRegion1d
class Neuron:
def __init__(self, x, y, neuron_radius, value):
self.x = x
self.y = y
self.neuro... |
# --------------------------------------------------------
# <NAME>
# update time:2018-9-12
# --------------------------------------------------------
from __future__ import print_function
import os
from collections import OrderedDict
import cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnn
f... |
from django.core.exceptions import SuspiciousOperation
from django.core.urlresolvers import reverse
from django.http.response import Http404
from django.shortcuts import redirect
from django.views.generic.base import TemplateView
from gitvcs import repository
from gitvcs.repository import local_repo
def _get_rev(br... |
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""System fan controller.
This module provides reading and setting system fan speed.
"""
import re
from cros.factory.device import device_types
class... |
#!/usr/bin/env python3
import sys
import os
from pprint import *
def processAllo(line,dic):
jobts = line.split("Start allocate:")[1].split(":")
jobid = jobts[0]
ts = int(jobts[1])
dic[jobid] = ts
def processTS(line, dic, cond):
jobid = 0
ts = 0
if cond == 0:
jobts = line.split("S... |
import numpy as np
import cv2
from random import randint
def bboxcvlib_to_bboxcv2(bbox_cvlib, vectorized=False):
"""Convert bboxes from format returned by cvlib (xmin,ymin, xmin+w, ymin+H)
to format required by cv2 (xmin,ymin,w,h)
Args:
vectorized: if set to True, will handle np arrays of bboxes.... |
import argparse
import warnings
import configparser
import matplotlib.pyplot as plt
import mlflow
import numpy as np
import pandas as pd
import seaborn as sns
from mlflow.models.signature import infer_signature
from sklearn import tree
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.inspe... |
"""
COL780
Assignment 3
"""
import cv2
import argparse
import os, shutil
import json
import numpy as np
from tqdm import tqdm
from sklearn.svm import SVC
import torch,torchvision
import torch.utils.data
from utils import *
from torchvision import transforms as T
from PIL import Image
def faster_rcnn(args):
thre... |
import torch
import random
import torch.autograd as autograd
import torch.nn as nn
import os
import numpy as np
import pandas as pd
from utils.conf import args, set_random_seed
from utils.schedulers import tau_scheduler
from models.Img2Seq2Choice import Img2Seq2Choice
from preprocesses.DataIterator import ImgChooseDat... |
# -*- coding:utf-8 -*-
import logging
import csv
import json
# Django imports
from django.http import HttpResponseBadRequest, HttpResponse, JsonResponse
from django.shortcuts import render
from django.conf import settings
from django.utils import timezone
from django.views.decorators.gzip import gzip_page
from django.... |
import numpy as np
import warnings
import sklearn.metrics
from pygrank.measures import AUC
def _cos_similarity(v, u, scores):
dot = 0
l2v = 0
l2u = 0
for group_scores in scores.values():
ui = group_scores.get(u, 0)
vi = group_scores.get(v, 0)
l2u += ui * ui
l2v += vi * ... |
# coding: utf-8
# ### Final Model Assesment
# In this notebook we have run the best model we have been able to produce during our work, on the test data set.
# An assessment of our model on independent data set
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import met... |
import json
import uuid
import urllib
from uuid import getnode as getmac
from pyportify import gpsoauth
SJ_DOMAIN = "mclients.googleapis.com"
SJ_URL = "/sj/v2.5"
FULL_SJ_URL = "https://{0}{1}".format(SJ_DOMAIN, SJ_URL)
def encode(values):
return urllib.parse.urlencode(values)
class Mobileclient(object):
... |
import os
from os import path
import numpy as np
import pandas as pd
from kamodo import kamodofy, Kamodo
from sympy.core.function import UndefinedFunction
from kamodo import get_defaults, getfullargspec
import flask
from flask import Flask, render_template, jsonify
from flask_cors import CORS, cross_origin
from flas... |
"""
Inspect feature columns in data frame, e.g.,
1. Find categorical and numberical features by their dtypes
2. Inspect the missing value patterns in the data
"""
import numpy as np
import pandas as pd
from scipy import stats
import statsmodels.api as sm
import matplotlib.pyplot as plt
from utility import is_numerica... |
from typing import Iterable, List
import math
class Vec2D:
pass
class Mat2D:
pass
class Vec2D:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def to_list(self) -> List[float]:
return [self.x, self.y]
def __add__(self, vec: Vec2D) -> Vec2D:
return... |
import json
import os
import socket
import struct
import sys
from .emeter import EmeterHandler
from ..exceptions import ConnectionError, DeviceError, InputError
from ..utils import Cache, IsValidMacAddress
class DeviceType(object):
NONE = 0
BULB = 1
PLUG = 2
class Device(object):
DEFAULT_PORT = 999... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.