text stringlengths 3.07k 12.6k |
|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from six.moves import xrange
import tensorflow as tf
from tensorflow.python.platform import flags
import logging
from cleverhans.attacks import Salien... |
'''
+------------------------------------------------------------------------+
| |
| Welcome! This is an Example Bot in Dicord.py, | ... |
import multiprocessing, Queue
from threading import Thread
import os, shutil
import traceback
import consts
class _DexNetWorker(multiprocessing.Process):
""" Dexnet worker process
Used by DexNetWorker for multiprocessing/request based Dex-Net work
"""
def __init__(self, process_name, gripper_dir):
... |
#!/usr/bin/env python3
import logging
import sys
import locale
import os.path
from datetime import datetime
from argparse import ArgumentParser
from collections import namedtuple
from logging.handlers import TimedRotatingFileHandler
import homematicip
from homematicip.device import *
from homematicip.group import *
fr... |
import sys
sys.path.insert(1, '/data/s1825216/git/neural_deprojection/')
import tensorflow as tf
import sonnet as snt
from functools import partial
from neural_deprojection.graph_net_utils import vanilla_training_loop, TrainOneEpoch, \
build_log_dir, build_checkpoint_dir, get_distribution_strategy
from neural_dep... |
# 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 (the
# "License"); you may not u... |
#!/usr/bin/python2.5
#
# Copyright 2008 the Melange 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... |
import logging
import datetime as DT
import homeassistant.core as HA
import homeassistant.helpers.event as EV
from homeassistant.helpers import entity_registry
from homeassistant.const import (
STATE_ON,
SERVICE_TURN_ON,
ATTR_AREA_ID,
ATTR_ENTITY_ID,
ATTR_DEVICE_ID
)
from homeassistant.component... |
import os
import sys
import numpy as np
from qcore.constants import Components
G = 981
class Waveform:
def __init__(
self,
NT=None,
DT=None,
time_offset=None,
values=None,
wave_type=None,
file_type=None,
times=None,
station_name=None,
... |
import math
import numpy as np
import os
import itertools
import random
import flux_divergence
import timestepping
class InitialConditions:
@staticmethod
def sine_wave(k=1):
return lambda x: math.sin(2*math.pi*k*x)
def quadratic():
return lambda x: (x-0.5)**2
class Mesh:
@staticmethod... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.backend.python.target_types import GenerateSetupField, WheelField
from pants.core.goals.package import OutputPathField
from pants.engine.targ... |
import logging
import os
from collections import defaultdict, Mapping
from six import iteritems, itervalues
from .sslutils import environments
from .utils import get_port
_renamed_props = {
"host": "browser_host",
"bind_hostname": "bind_address",
"external_host": "server_host",
"host_ip": "server_ho... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# from http.client import HTTPConnection
# from pandas import DataFrame
# from urllib.request import urlopen
from requests import get as get_request
from datetime import datetime as dt
import sys
import lxml.html as html
import mysql.connector as c
# from math import ceil
# f... |
import sys
from abc import abstractmethod
from pathlib import Path
from typing import Collection, Iterable, Iterator, Optional, Sequence, Tuple, Union
import thot.alignment as ta
from ...corpora.parallel_text_corpus import ParallelTextCorpus
from ...corpora.token_processors import NO_OP, TokenProcessor
from ...utils.... |
"""Meetup event downloader script.
<NAME> - 2016-12-10
This script uses the Meetup.com API to request meetup events within a radius around a given latitude and longitude.
It uses the /2/open_events API function, which has the following limitations:
- it only returns events with 3 or more RSVPs.
- it only returns past ... |
'''
Package imports
'''
import discord, asyncio, datetime
from discord.ext import commands, tasks
from getRawData import *
'''
Constants and bot initilization.
'''
with open('bot.token', 'r') as tokenFile:
TOKEN = tokenFile.read().strip()
tokenFile.close()
USER_ID_LENGTH = 18
DAILY_CASE_LOCATION = 3
TOTAL_CASE_LO... |
#!/usr/bin/env python3
#
# Copyright 2019 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from flask import request, session, render_template, redirect, abort, url_for, jsonify
from graphstore.models import Graph, Link, Node
from bson import ObjectId
from . import app
from .models import Account, Document, Web, Edge, Vertex, Rule, Prop
from .forms import LoginForm, RegisterForm
from .auth import login, log... |
from collections import defaultdict
from typing import TYPE_CHECKING
import sshpubkeys
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql import label
from grouper.models.counter import Counter
from grouper.models.permission import Permission
from grouper.models.public_key import PublicKey
from grouper.mod... |
"""This is just example model, not real implementation !!!"""
import time
import argparse
import sys
import torch
from torch.autograd import Variable
import torch.nn as nn
from torch import optim
from torchtext import data
from torchtext import datasets
import torchfold
parser = argparse.ArgumentParser(descriptio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AUTHOR
<NAME> <<EMAIL>>
DESCRIPTION
LICENSE
This script is in the public domain, free from copyrights or restrictions.
Created: 12 December 2019
"""
# System/default
import sys
import os
# Arguments
import argparse
# Messaging/logging
import traceback... |
from django.db import models
class Student(models.Model):
firstname = models.CharField(max_length=64)
lastname = models.CharField(max_length=64)
olsclass = models.ForeignKey('OLSClass')
family = models.ForeignKey('Family')
def __unicode__(self):
return self.name()
def name(self, lastn... |
# Computing Astronomical Dendrograms
# Copyright (c) 2011-2012 <NAME> and <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the righ... |
import pickle
import random
from collections.abc import Iterable
from easydict import EasyDict
import torch
import torch.nn as nn
import torch.optim as optim
from ding.utils import REWARD_MODEL_REGISTRY
from .base_reward_model import BaseRewardModel
def concat_state_action_pairs(iterator):
"""
Overview:
... |
from collections import defaultdict
from kleat.evidence.do_bridge import do_bridge
from kleat.misc import apautils
from kleat.misc.calc_genome_offset import calc_genome_offset
import kleat.misc.settings as S
# for bridge PAS hexamer search needs done in a more customized way than just
# using gen_contig_hexamer_tuple... |
# Author: <NAME>
# Email: <EMAIL>
"""
Advances in Financial Machine Learning
<NAME>
Chapter 2: Financial Data Structures
In order to build any of the projects mentioned in the book, we must first
create the various types of structured data from the unstructured data provided.
Many of the projects going forward will ... |
import pickle
import numpy as np
from os import listdir
from os.path import isfile, join
import matplotlib
matplotlib.use('tkagg')
from matplotlib import pyplot as plt
plt.rc('figure', figsize=[10, 6])
def plot_residuals(runs, model_name):
# Plot residual of predicted vs actual return
guc = np.zeros((100,))... |
from flask import render_template, session, redirect, url_for, flash, request
import requests
from flask_login import current_user
from . import forms
from . import frontend_blueprint
from .api.UserClient import UserClient
from .api.OrderClient import OrderClient
from .api.ProductClient import ProductClient
import boto... |
#!/usr/bin/env python
"""
Table Testing module.
Created Oct 2008
Copyright (C) <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 2
of the Lice... |
import json
from typing import Any
from configparser import ConfigParser
from pathlib import Path
from warnings import warn
from optimade import __version__
from optimade.models import Implementation
class NoFallback(Exception):
"""No fallback value can be found."""
class Config:
"""Base class for loading ... |
import sublime
import sublime_plugin
import datetime
import re
from pathlib import Path
import os
import fnmatch
import OrgExtended.orgparse.node as node
from OrgExtended.orgparse.sublimenode import *
import OrgExtended.orgutil.util as util
import OrgExtended.orgutil.navigation as nav
import OrgExtended.orgutil.temp... |
from random import *
from turtle import *
from tkinter import *
#from multiprocessing import Process
#processes = []
SEE = False
dismod = (2/3,3/4,3/5,7/8) ; c = 2 ; d = 5
a = 15 ; b = 40 ; minpix = 10 ; wmod = 3/5
ground = - 225
seeds = 0
rightmost = 0
leftmost = 0
listen()
w = Screen()
w.t... |
import os
import click
from ..settings import LOCAL_CONFIG, load_config
from ..utils import taskstatus
from ..helpers import (
get_issue,
get_transition,
set_issue_status,
assign_issue,
get_branch,
get_project_keys,
get_project_dirs,
create_issue,
)
@click.command()
@click.option("-k... |
#!/usr/bin/env python
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, window, asc, desc, lead, lag, udf, hour, month, dayofmonth, collect_list, lit
import pyspark.sql.functions as F
from pyspark.sql.window import Window
from pyspark.sql.types import FloatType, IntegerType, DateType, Timestam... |
import joblib
import os
import csv
import json
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from .... import logger
from .... import DATA_PATH, MODELS_PATH
from ....synthetic.fakers.agegenerator import AgeGenerator
from ....synthetic.fakers.d... |
#!/usr/bin/env python3
import unittest
import os
import cdeps
# To save some characters
def a(path: str) -> str:
"""Transform into an absolute path inside the sources directory (even if the file doesn't exist)."""
return os.path.join(os.getcwd(), 'tests/sources', path)
# 'sources' directory structure:
# -... |
#
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
#
import hashlib
import json
import lzma
import os
import uuid
import requests
from eth_account import Account
from jsonsempai import magic # noqa: F401
from web3 import Web3
from web3.datastructures import AttributeDict
from aquarius... |
"""
Unit tests for opt.py module.
Author
------
::
Author: Diptesh
Date: Jun 16, 2019
"""
# pylint: disable=invalid-name
# pylint: disable=wrong-import-position
import unittest
import warnings
import re
import sys
from inspect import getsourcefile
from os.path import abspath
import pandas as pd
import nu... |
"""Representation of Venstar sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from homeassistant.components.sensor import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
STATE_CLASS_MEA... |
import os
from os import listdir
from tkinter import *
from tkinter import filedialog
from tkinter import (
Tk, Button, Label,
)
root = Tk()
root.title("Steam Auto Shutdown")
root.geometry('550x300')
root.configure(bg='#2a475e')
root.resizable(False, False)
status = True
check = False
bg = Photo... |
from gremlin_python.driver import client, serializer
import sys
import traceback
_gremlin_cleanup_graph = "g.V().drop()"
_gremlin_insert_vertices = [
"g.addV('person').property('id', 'thomas').property('firstName', 'Thomas').property('age', 44).property('pk', 'pk')",
"g.addV('person').property('id', 'mary').p... |
r"""
Two pulse interaction in a NLPM750 PCF
======================================
This examples demonstrates the interaction between a fundamental soliton and a
dispersive wave in a NL-PM-750 photonic crystal fiber. For the numerical
simualtion the forward model for the analytic signal including the Raman effect
is u... |
#!/usr/bin/env python3
import sys
from typing import Any, List, Dict, Set
import argparse
class Reactor:
"""
Manages the set of all ActiveCube objects.
"""
_active_cubes: Dict[int, Dict[int, Dict[int, bool]]]
_on_count: int
_min_valid: int
_max_valid: int
CUBE_ON = True
CUBE_OFF =... |
"""
VMC API Request Module
"""
import json
import logging
import os
import requests
from requests.exceptions import HTTPError
from requests.exceptions import RequestException
from requests.exceptions import SSLError
from saltext.vmware.utils import vmc_constants
log = logging.getLogger(__name__)
def set_base_ur... |
""" PyRPIO definitions: enums and dataclasses. """
from enum import Enum
from typing import Optional, List
from dataclasses import dataclass
LOW = 0x0
HIGH = 0x1
INPUT = 0x0
OUTPUT = 0x1
PWM = 0x2
PULL_OFF = 0x0
PULL_DOWN = 0x1
PULL_UP = 0x2
POLL_LOW = 0x1
POLL_HIGH = 0x2
POLL_BOTH = 0x3
PAD_GROUP_0_27 = 0x0
PAD_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwt.code import If, Concat
from hwt.hdl.types.bits import Bits
from hwt.interfaces.std import Signal, VectSignal
from hwt.interfaces.utils import addClkRstn
from hwt.synthesizer.param import Param
from hwt.synthesizer.unit import Unit
from hwtLib.clocking.clkBuilder ... |
from pydactyl import PterodactylClient
import json
import time
import os
import subprocess
import importlib
print("ATTEMPTING CONNECTION...")
# Create a client to connect to the panel and authenticate with your API key.
client = PterodactylClient('API ENDPOINT GOES HERE', 'API KEY GOES HERE')
# Get a list of all ser... |
"""IPython extension that activates special Jupyter notebook features of Nengo.
At the moment this only activates the improved progress bar.
Use ``%load_ext nengo.ipynb`` in a Jupyter notebook to load the extension.
Note
----
This IPython extension cannot be unloaded.
"""
from html import escape
import warnings
im... |
# Copyright (c) 2014-2015, Heliosphere Research LLC
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of c... |
import sublime
import sublime_plugin
import re
import math
import os
import sys
try:
from Default.indentation import line_and_normed_pt as normed_rowcol
except ImportError:
# This is necessary due to load order of packages in Sublime Text 2
sys.path.append(os.path.join(sublime.packages_path(), '... |
# Code by <NAME>
# Website: Programming Languages Compare
# Reference to https://flask.palletsprojects.com/en/2.0.x/
import os
import json
import random
import requests
# Flask
import flask
from flask_cors import cross_origin
from private import private
from methods import db, route_functions as rf
# ... |
import json
import os
from datetime import timedelta
from functools import update_wrapper
from flask import Flask, make_response, request, current_app
from flask import flash, redirect
from flask import render_template
from past.types import basestring
from util.config import Config
from util.connection import get_gam... |
"""Authentication methods for API."""
from kqueen.config import current_config
from kqueen.models import Organization
from kqueen.models import User
from uuid import uuid4
import bcrypt
import importlib
import logging
config = current_config()
logger = logging.getLogger('kqueen_api')
"""
Authentication Modules
... |
from pathlib import Path
import sys
from rdkit.Chem.Scaffolds import MurckoScaffold
from rdkit import Chem
import numpy as np
import cloudpickle
def generate_scaffold(smiles, include_chirality=False):
"""Compute the Bemis-Murcko scaffold for a SMILES string."""
if isinstance(smiles, Chem.Mol):
mol = s... |
'''
Evaluate a joint estimation network on cropped person images from the coco dataset.
'''
import os
import glob
import json
import pprint
import torch
import torchvision.transforms as transforms
import _init_paths
from core.config import config
from utils.utils import create_logger
import models
import torch.backe... |
with open('veriler.txt','r') as data:
dataList = [int(veri) for veri in data]
data.close()
def xy_toplam(veriler,üs,baslangıc):
toplam = 0
for x in range(len(veriler)):
toplam += veriler[x]*((x+baslangıc)**üs)
return toplam
def xToplam(min,max,üs):
toplam = 0
for i in range (min,max+1)... |
import os
import sys
import time
sys.path.append(os.path.abspath(os.path.join(__file__, '..', '..')))
from RAFT import utils
from RAFT import RAFT
import torch
import argparse
print(torch.__version__)
isONNX = True
if isONNX:
import onnx
import onnxruntime as onnxrun
else:
from openvino.inference_engine ... |
import math
from hls4ml.converters.keras_to_hls import parse_default_keras_layer
from hls4ml.converters.keras_to_hls import keras_handler
@keras_handler('Conv1D')
def parse_conv1d_layer(keras_layer, input_names, input_shapes, data_reader, config):
assert('Conv1D' in keras_layer['class_name'])
layer = parse_d... |
import numpy as np
import gym
from gym.wrappers.pixel_observation import PixelObservationWrapper
from agent_2l import create_second_level_agent
from buffers import ExperienceBuffer, Task, PixelExperienceSecondLevelMT
from trainers import Second_Level_Trainer as Trainer
from wrappers import AntPixelWrapper
from utils i... |
"""
Shape construction functions. All functions should return 2 sequences
(the first to initialize points, the second to initialize triangles).
The points and triangles (shape info) returned should be treated as
having an origin at (0, 0, 0), ideally its volumetric center.
"""
from typing import Iterator, Se... |
from abc import ABC, abstractmethod
from typing import List, Union, Dict, IO
import warnings
from dataclasses import dataclass
import pandas as pd
import awswrangler as wr
from pyarrow import parquet as pq
from mojap_metadata import Metadata
from mojap_metadata.converters.arrow_converter import ArrowConverter
from a... |
# Copyright (c) 2016 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to t... |
# -*- coding: utf-8 -*-
from .base import BookBase, SheetBase
from .basex import BookBase as BookBasex, SheetBase as SheetBasex
from .pos import Pos
class SheetWriterBase():
def set_range(self, body_row):
self.head_range = range(self.min_rowx, body_row)
self.body_row = body_row
... |
#
# Author: <NAME>
# Copyright 2016
#
import numpy as np
import os
import isceobj
import datetime
import sys
import logging
logger = logging.getLogger('isce.topsinsar.coarseoffsets')
def runGeo2rdr(info, rdict, misreg_az=0.0, misreg_rg=0.0, virtual=False):
from zerodop.geo2rdr import createGeo2rdr
from isce... |
from random import randint
import re
from operator import itemgetter #para ordenar a lista de filmes
file_name = "elo.csv"
class Filme:
def __init__(self, index, title, elo_rating):
self.index = index
self.title = title
self.elo_rating = elo_rating
def get_expected_rating(... |
import torch
import torch.nn as nn
class MultiHeadedAttention(nn.Module):
"""Multi-Head Attention layer
:param int n_head: the number of head s
:param int n_feat: the number of features
:param float dropout_rate: dropout rate
"""
def __init__(self, n_head, n_feat, dropout_rate=0.0):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Neural Network Verification Model Translation Tool (NNVMT)
@author:
<NAME>(<EMAIL>)
<NAME> (<EMAIL>)
"""
import os
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
from src.re... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import functools
from micawber import Provider, ProviderRegistry, ProviderException
from .provider_data.noembed import NOEMBED_PROVIDER_LIST
from .provider_data.custom import CUSTOM_PROVIDER_LIST
from .provider_data.oembed import OEMBED_PROVIDER_LIST
__version_... |
"""Module to use the Inrix Roadway Analytics Data Downloader API.
Contributors: <NAME>
Version: 2021-03-02
Latest: https://github.com/BayAreaMetro/dpdutils
"""
# %%
import json
import time
import requests
# %%
class InrixTimeout(Exception):
"""Exception for a timeout caused by something Inrix related."""
pa... |
####### ROS UTILITIES #######
# IMPORTS
# system
import os
import pdb
# math
import numpy as np
import numpy.linalg as la
from bisect import bisect_left
# ros
import rospy
try:
import rosbag
except:
pass
from geometry_msgs.msg import PoseStamped, Twist, Pose
from sensor_msgs.msg import Image, CameraInfo
from st... |
"""
meta class and base class utility classes and functions
"""
from __future__ import absolute_import, division, print_function
import sys
from collections import Iterable, Sequence
from abc import ABCMeta
import functools
import inspect
import types
# import ioflo modules
from .sixing import *
from .consoling imp... |
# 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 agreed to in writing, ... |
"""
Performance Utilz
"""
import time
import anyio
import multiprocessing
from functools import wraps, partial
from typing import Callable, Dict, List, Any, Union, Iterable, Generator, Optional
from .utils import *
from ..helpers import get_logger
try:
import trio
_async_backend = 'trio'
except: _async_bac... |
###############################################################################
# Calculate Puga Index from population data
# <NAME> and __author__ = 'SPIJKERM'
# Purpose: Not sure ... will fill up later
###############################################################################
__author__ = 'GOST and SPIJKERM'
im... |
import logging
import os
import signal
import click
#from psycopg2cffi import compat
#compat.register()
from alembic import command
from flask import Flask, jsonify
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_httpauth import HTTPTokenAuth
from flask_marshmallow import Marshmallow
from flask_... |
import smartpy as sp
admin_mixin = sp.io.import_script_from_url("file:contracts/Administrable.py")
utils = sp.io.import_script_from_url("file:contracts/Utils.py")
FA2 = sp.io.import_script_from_url("file:contracts/FA2.py")
# TODO: is_fa2_permitted/get_fa2_permitted is probably not needed? maybe for interop...
# TODO:... |
"""
IP socket address
"""
import sys
import socket
import threading
import time
import socket
import logging
import lib_uris
import lib_util
import lib_common
from lib_properties import pc
def EntityOntology():
return (["Id"],)
# TODO: Add the network card.
# This returns a nice name given the parameter of ... |
import json
import datetime
import time
from click import ClickException
from interrogatio import dialogus
from interrogatio.validators import (
DateTimeRangeValidator,
DateTimeValidator,
RequiredValidator,
Validator,
)
from interrogatio.core.exceptions import ValidationError
from connect.cli.plugins.... |
"""Tests the xonsh lexer."""
import os
import pytest
from xonsh.pytest.tools import ON_WINDOWS, skip_if_on_unix, skip_if_on_windows
@pytest.fixture
def check_eval(xonsh_execer, xonsh_session, monkeypatch):
def factory(input):
env = {
"AUTO_CD": False,
"XONSH_ENCODING": "utf-8",
... |
# Copyright (c) 2019. Partners HealthCare and other members of
# Forome Association
#
# Developed by <NAME> based on contributions by <NAME>,
# <NAME>, <NAME> and other members of Division of
# Genetics, Brigham and Women's Hospital
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may no... |
#!/usr/bin/python3.5
#import spacy
from sklearn.cluster import KMeans
from collections import Counter
import os
import argparse
from filereader import readFiles
from bagOfWords import BagOfWords
from TFIDF import TFIDF
from senAna import SenAna
from TFIDFSen import TFIDFSen
from featureBuilder import FeatureBuilder
... |
# 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, software
# distributed under t... |
import contextlib
import dataclasses
import logging
import os
import sys
from collections.abc import Sequence
from typing import Callable, Optional, Union
import numpy as np
import tqdm
import morello.impl.base
from .. import cost, pruning, specs
from . import common, random
HEURISTIC_SAMPLES_PER_SPEC = 10
HEURISTI... |
from classify_utils import setup_args, setup, get_basemodel, get_data, get_logger, setup_args_preprocessing, setup_args_getE
from classify_ksmooth import ksmooth, setup_args_ksmooth, run_model, pre
import argparse
import torch
import numpy as np
from data import get_dataset
import geometrictools as gt
from collections ... |
"""
Closed form matting implementation, ported from the original matlab code.
Based on
<NAME> and <NAME>. A Closed Form Solution to Natural Image Matting.
Conference on Computer Vision and Pattern Recognition (CVPR), June 2007.
"""
import scipy.sparse
import scipy.sparse.linalg
import scipy.ndimage
import numpy.lina... |
"""
Lab 4
"""
import re
from lab_4.ngrams.ngram_trie import NGramTrie
def tokenize_by_sentence(text: str) -> tuple:
if not isinstance(text, str):
raise ValueError
text = re.sub(r'[^a-z \.\?\!]', '', text.lower())
text = re.sub(r'[\.\?\!]', ' <END> ', text)
text = re.sub(' +', ' ', text).split... |
"""
Configuration utilities for :py:mod:`mtb` module.
Copyright (C) 2013-2016 CERN
"""
import os
import re
from subprocess import Popen, PIPE
import tempfile
from mtb.modules import json
from mtb import PY2, PY3
def _normalize_bool(tree):
""" Normalize boolean in the dict. """
for key, value in tree.items()... |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional, Sequence, Union
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule
class BasicConvBlock(BaseModule):
"""Basic convolutional block for PWC-Net.
This module consists of several plain... |
import pytz, re, sys
from datetime import datetime, timedelta, timezone
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from schedule.models.events import EventRelation
class GatheringBatchCreateResult(object):
# class Meta:
# pass
def __init__(self, **kwar... |
"""
paw_structure.pbc
-----------------
Functions for application of periodic boundary conditions.
Dependencies:
:py:mod:`copy`
:py:mod:`miniutils`
:py:mod:`numpy`
:mod:`.utility`
.. autosummary::
pbc_apply3x3
pbc_folding
pbc_folding_parallel
pbc_general
"""
import numpy as n... |
# coding=utf-8
"""
腾讯云相关API
Tencent cloud API
"""
import json
from .. import requirePackage
from . import pre_check, user_lang, dir_char
class TxCOS:
qcloud_cos = requirePackage('qcloud_cos', real_name='cos-python-sdk-v5')
def __init__(self):
"""
初始化并登陆腾讯云对象存储
Initialize and log in ... |
from flask import Blueprint, render_template, request, Response, redirect
from munch import munchify
from pyldapi import Renderer
from config import Config
import skos
routes = Blueprint('routes', __name__)
def match(vocabs, query):
"""
Generate a generator of vocabulary items that match the search query
... |
# Copyright (c) 2020 SBA - MIT License
import selectors
from collections.abc import Callable
from selectors import SelectorKey, EVENT_READ
from typing import Optional, List, Tuple, Iterable, Union
from unittest.mock import Mock
import socket
import collections.abc
def _gen_uniq(start: int):
""" Helper to genera... |
from __future__ import print_function, division
import os
import sys
sys.path.append("..") # Adds higher directory to python modules path.
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from core.point_cloud.point_cloud_ops im... |
""" 2-input XOR example using Izhikevich's spiking neuron model. """
from __future__ import print_function
import os
import matplotlib.pyplot as plt
from matplotlib import patches
from neat import population, iznn, visualize
from neat.config import Config
# Network inputs and expected outputs.
xor_inputs = ((0, 0), (0... |
import os
import yaml
import itertools
import glob
import warnings
from typing import List
import asteroid
from asteroid.models.publisher import upload_publishable
from asteroid.models.base_models import BaseModel
SUPPORTED_EXTENSIONS = [
".wav",
".flac",
".ogg",
]
def upload():
"""CLI function to ... |
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QDateTime, QTimer
# from openssl_lib import OpenSSLLib
from .set_csr import SetCSRView
class CSRData:
def __init__(self):
self.country_name = ''
self.state_name = ''
self.locality_name = ''
self.o... |
import simplegui
import random
# globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
ball_pos = [WIDTH / 2, HEIGHT / 2]
ball_vel = [0, 0]
score1 = 0
score2 = 0
goRight = True # True for right, False for left direction
... |
#!/usr/bin/python3
# UNFINISHED
"""UNFINISHED"""
# time watch and sleep purposes
import time
# lazy args
import sys
# for requests stuff
from fake_useragent import UserAgent
import requests
# for config manipulation
import configparser
import ast # https://stackoverflow.com/a/56084659/12258312
# for data manipul... |
import torch
import torch
from torch import nn
from .resnet import resnet50
from .densenet_ibn_a import densenet121_ibn_a, densenet169_ibn_a
from .resnet_ibn_a import resnet50_ibn_a, resnet101_ibn_a, se_resnet101_ibn_a, resnet34_ibn_a
from .resnext_ibn_a import resnext101_ibn_a
from .resnet_ibn_b import resnet... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.