text stringlengths 3.07k 12.6k |
|---|
'''
maltracx
Official maltra.cx REST API client
'''
__title__ = 'maltracx'
__version__ = '0.0.1'
__all__ = ('Client',)
__author__ = '<NAME> <<EMAIL>>'
__license__ = 'BSD'
__copyright__ = 'Copyright 2017 Johan Nestaas'
import sys
from .client import Client
def _add_args(parser):
parser.add_argument('--apikey-id... |
import datetime
import json
import re
from pathlib import Path
from typing import Optional
import aiohttp
from bot.bot import Bot
from discord import Embed, Message
from discord.ext import commands, tasks
from discord.ext.commands import Cog, Context, command
from discord.utils import escape_mentions
from loguru impor... |
import csv
import sys
import pandas as pd
bin_coverages = list(csv.reader(open('../Figure Generating/data/TOBG-Combined.RPKM.csv', 'r')))
master_bin = list(csv.reader(open('../Figure Generating/data/bin_taxon.csv', 'r')))[1:]
bin_of_interested = [row[0] for row in master_bin]
# RPKM (reads per kilobase pair MAG per M... |
"""
Copyright (c) 2021, FireEye, Inc.
Copyright (c) 2021 <NAME>
"""
import numpy as np
import ember
NUM_EMBER_FEATURES = 2351
def build_feature_names():
names = [''] * NUM_EMBER_FEATURES
base = 0
# ByteHistogram
for i in range(256):
names[base + i] = 'ByteHistogram' + str(i)
base = 256
... |
# This file has been checked through, and it is compatible with the board and isleft/isright updates
# This file is also compatible with the "__eq__" and "__str__" updates.
# It is as efficient as I think it can be right now.
# Most recent check: 12/6/2019
import random
import basicprogs as b
import call
import lead
i... |
#!/user/bin/python
# -*- coding:utf-8 -*-
# 作者:realityerror
# 创建:2022-03-06
# 更新:2022-03-06
# 用意:搭建网站
from ast import Global
import socket
from wsgiref.simple_server import make_server
#网站初始化
from asyncio.windows_events import NULL
import re, os
import pickletools
from flask import Flask, render_template, Response,... |
import hashlib
from datetime import datetime, timedelta
import random
import requests
from enum import Enum
from flask import Flask, Blueprint, request, Response, json
from extensions import cors, db, migrate
from controllers.database.whistle import Whistle
from controllers.database.zip import Zip
try:
from config... |
import re
from typing import TYPE_CHECKING, Any, Dict, List
from pipegen.config import is_codecommit_with_event_source, parse_value
from .codebuild import generate_logical_id
from .interfaces import ResourceOutput
LOGICAL_ID = "CodePipeline"
ARTIFACT_NAME_PATTERN = re.compile(r"[\W_]+")
if TYPE_CHECKING: # pragma... |
import collections
import inspect
import json
import os
import sys
import time
from datetime import datetime, timedelta
from pprint import pprint
from apscheduler.schedulers.background import BackgroundScheduler
from pymongo import MongoClient
from steem import Steem
from steem.blockchain import Blockchain
from steem.... |
#
# This example initiates an acquisition and continuously fetches waveform samples per channel.
#
# The gRPC API is built from the C API. NI-SCOPE documentation is installed with the driver at:
# C:\Program Files (x86)\IVI Foundation\IVI\Drivers\niScope\Documentation\English\Digitizers.chm
#
# A version of this .chm... |
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.engine.predictor import COCODemo
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
from maskrcnn_benchmark.structures.bounding_box import BoxList
from PIL import Image
import numpy as np
import cv2, os, glob, argparse, torch, time
def ... |
import click
import json
import csv
from kazoo.client import KazooClient
@click.command()
@click.option('--zookeeper', '-z', required = True, help = 'zookeeper connection string')
@click.option('--prefix', '-p', required = True, default = '/run/hermes', help = 'path prefix')
@click.option('--source', '-s', required = ... |
"""Support for Fibaro lights."""
from __future__ import annotations
import asyncio
from contextlib import suppress
from functools import partial
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
ENTITY_ID_FORMAT,
ColorMode,
LightEntity,
brightne... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appl... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Functions for manipulating networks."""
import itertools
import math
import torch
import torch.nn as nn
from xnas... |
"""The functions for defining the dataset class of downstream tasks, such as UCF101, HMDB51, etc.
Code partially borrowed from
https://github.com/YihengZhang-CV/SeCo-Sequence-Contrastive-Learning/blob/main/dataset/dataset_kinetics_v2.py.
MIT License
Copyright (c) 2020 YihengZhang-CV
"""
import torch.utils.data
import... |
import os
import sys
import pathlib
__dir__ = pathlib.Path(os.path.abspath(__file__))
print(str(__dir__.parent))
sys.path.insert(3,str(__dir__.parent))
import torch
import cv2
from PIL import Image
import numpy as np
from model import Model
from recognizer_utils import CTCLabelConverter
from dataset import AlignCol... |
#!/usr/bin/env python
'''
search a set of log files for signs of inconsistent IMU data
'''
from __future__ import print_function
from builtins import input
from builtins import range
import sys, time, os
import zipfile
from pymavlink import mavutil
from math import degrees
# extra imports for pyinstaller
import jso... |
# Copyright (c) MONAI Consortium
# 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, so... |
import bpy
import mathutils
import bmesh
def GetTransformOffset(isCentered):
if isCentered:
return mathutils.Matrix.Translation((0.0, 0.0, 0.0))
else:
return mathutils.Matrix.Translation((0.0, 0.0, 1.0))
class Qobject:
bObject = None
bMesh = None
bMatrix = mathutil... |
#!/usr/bin/env python3
__authors__ = '<NAME>'
__license__ = '3-clause BSD'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
# plotting tools
import matplotlib.pyplot as plt
# numpy for array tasks
import numpy as np
def calc_mon_pay(out_prin, months, int_rate):
'''
calculate monthly payment including interes... |
from datetime import datetime
from server.services.git.file_service import FileService
document_data = {
"project": {
"projectId": 1,
"status": "status example",
"name": "project name example",
"shortDescription": "short description example",
"changesetComment": "changeset... |
import logging
import requests
from requests.status_codes import codes
from cachecontrol import CacheControlAdapter
from cachecontrol.caches.file_cache import FileCache
from jose import jwt
import time
import os
import pickle # nosec
from .settings import settings
from . import exceptions
log = logging.getLogger(__... |
"""
Test the feature of memory checker.
"""
import logging
from multiprocessing.pool import ThreadPool
import pytest
from pkg_resources import parse_version
from tests.common.utilities import wait_until
from tests.common.helpers.dut_utils import check_container_state
from tests.common.helpers.assertions import pytest... |
# Features in use in B/RK analyzer
#
# NOTE: use convention such that new features (added here) are always with underscore '_featurename' !
#
#
# <NAME>, 2020
# <EMAIL>
import uproot
import numpy as np
# Top level features available in b-parking nanoAOD trees
mva_features = {
# Electron 1 candidate
'BT... |
# utility.py v1.0
import csv
# reads a CSV file and returns every line as a list
# e.g. for a CSV file with the following 2 lines:
# apple, orange
# banana, durian
# this function will return this list: [['apple', ' orange'], ['banana', ' durian']]
def list_reader(csv_file):
the_list = []
with open(csv_file, ... |
# Copyright 2014 Huawei Technologies Co. 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 or agreed... |
# Copyright 2015-2016 Mirantis, 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 law... |
from flask import render_template, Flask, jsonify, request, redirect, flash, url_for
from datetime import datetime, timedelta
import pandas as pd
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
secret_key = 'heheheehehehe'
file = 'static/Pfizer_tickets.xlsx'
ufile = 'Pfizer_tickets.xlsx'
app... |
"""Synchronize with Fivetran."""
import time
import requests
import datetime
import json
from enum import Enum
from requests.auth import HTTPBasicAuth
from requests.exceptions import RequestException
from typing import Any, Dict, Optional
from urllib.parse import urljoin
from dateutil import parser
from dbt.logger impo... |
"""
This file is for tests related to Paychex object creation, and basic utilities
used by other modules
"""
import json
from behave import given, step
from nose.tools import assert_equals
from requests.adapters import HTTPAdapter
from requests.sessions import Session
from pychex import Paychex, BenefitsOnline
@gi... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import sys
import tensorflow as tf
import numpy as np
import nltk
import pickle
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from tags_dataset import create_feature_sets_and_labels
from tags_model import TagsModel
import utils
import... |
import argparse
import os
import torch
#import torchvision
from torch import nn
from torch.autograd import Variable
from data_loader import load_dataset
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.encoder = nn.Sequential(nn.Linear(2800, 512),nn.PReLU(),nn.Linear(512, 256),n... |
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# from pyvirtualdisplay import Display
from selenium import webdriver
# import csv,codecs
import datetime
import smtplib
import mysql_tool as my
import time
def get_date():
return time.strftime("%Y-%m-%d", time.localtime())
def isElementExist(driver,element):
f... |
import torch
from core.config import cfg, update_cfg
from core.train_helper import run
from core.model import GNNAsKernel
from core.transform import SubgraphsTransform
from core.data import calculate_stats
from torch_geometric.datasets import GNNBenchmarkDataset
from sklearn.metrics import confusion_matrix
import num... |
from sys import exit
import os
import h5py
import numpy as np
from scipy.stats import entropy, kstest, median_abs_deviation, cramervonmises
def create_directories(model_name):
# Define directories
path = os.getcwd() + '/galpro/' + str(model_name) + '/'
point_estimate_folder = 'point_estimates/'
poste... |
#
# Copyright (C) 2016-2019 by <NAME>, <NAME>, <NAME>, and contributors
#
# This file is part of Power Sequencer.
#
# Power Sequencer 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
# Lic... |
import re
from typing import Any, List, Optional, Union, cast
from debian.deb822 import PkgRelation
from debutizer._list_backed_container import ListBackedContainer
from debutizer.errors import CommandError
class Dependency:
def __init__(
self,
name: str,
archqual: Optional[str] = None,
... |
# Copyright 2021 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
#!/usr/bin/env python
import argparse
import csv
import sys
from collections import namedtuple
import MDAnalysis as mda
from MDAnalysis.lib.distances import calc_dihedrals
import matplotlib
matplotlib.use('Agg') # noqa
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def parse_command_li... |
#!/usr/bin/env python
# coding: utf-8
import sciope
import numpy as np
import gillespy2
from gillespy2 import Model, Species, Reaction, Parameter, RateRule, AssignmentRule, FunctionDefinition
from gillespy2 import EventAssignment, EventTrigger, Event
from sciope.utilities.priors.uniform_prior import UniformPrior
... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for changing your Telegram profile details+ now u can steal personal details of user. """
import os... |
#!/usr/bin/env python3
#****************************************************************************************************************************************************
# Copyright (c) 2014 Freescale Semiconductor, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
#... |
from collections.abc import Mapping
import os
from .. import util
validator = util.validator
def kind(wrapped):
def wrapper(raw):
return wrapped(raw)
return wrapper
def mapping(key, value):
def wrapper(raw):
return util.as_readonly_mapping(raw, key=key, value=value)
return wrapper... |
#!/usr/bin/env python3
# This file is part of the docker-registry-self-signed project, which
# is distributed under the terms of the MIT License, See the project's
# LICENSE file for details.
#
# Copyright (C) 2020 <NAME>
"""Script to help with creating the configuration needed to run a
Docker self-signed registry co... |
"""
:Authors: - <NAME>
"""
import argparse
def argparser():
"""parse command line arguments"""
parser = argparse.ArgumentParser(prog='grasp.cfg.parser',
usage='python -m %(prog)s [options]',
description="Grasp's CFG parser",
... |
from django.utils.encoding import smart_text
from django_filters.rest_framework import DjangoFilterBackend
from drf_renderer_xlsx.mixins import XLSXFileMixin
from drf_renderer_xlsx.renderers import XLSXRenderer
from rest_framework import renderers
from rest_framework import serializers, viewsets
# Serializers define th... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
"""
================================
The :mod:`mpi_array.init` Module
================================
Initialisation which needs to occur prior to :samp:`MPI_Init`.
Parts of this source borrows from
the `airspeed velocity (asv) <http://asv.readthedocs.io/en/latest>`_
file `benchmark.py <https://github.com/spacetele... |
from eth_tester.exceptions import TransactionFailed
from pytest import fixture, mark, raises
from utils import longTo32Bytes, PrintGasUsed, fix, BuyWithCash, nullAddress
from constants import BID, ASK, YES, NO
from datetime import timedelta
from trading.test_claimTradingProceeds import acquireLongShares, finalizeMarke... |
"""
Copyright (c) 2016-2019 <NAME> http://www.keithsterling.com
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, m... |
### Python regular expressions ###
# Python 3.x print function import
from __future__ import print_function
# Import regular expression library
import re
# regular expressions --> programming with characters instead of lines
# another definition: a programming language for string matchng (inside of python)
# Imp... |
'''
Small changes to the pytorch dataloader.
Now works with with batches (slicing rather than loop over indexes),
and can potentially stop workers from shutting down at each batch.
'''
# import random
import warnings
import copy
import torch
import torch.utils.data
import torchtuples
def identity_collate_fn(x):
... |
from torch import sigmoid, bincount
import torch.nn as nn
import torch.nn.functional as F
from torch import mean, diag
import argparse
from scipy.spatial.distance import directed_hausdorff
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return Tr... |
from pathlib import Path
import pytest
examplesPath = Path(__file__).parents[1] / "examples"
def test_preallocate_arfidata(sorted_nodes, axes):
from fem.post.create_res_sim import __preallocate_arfidata
from fem.post.create_res_sim import extract_image_plane
image_plane = extract_image_plane(sorted_nodes... |
r"""
The ``distributions`` package contains parameterizable probability distributions
and sampling functions.
Policy gradient methods can be implemented using the
:meth:`~torch.distributions.Distribution.log_prob` method, when the probability
density function is differentiable with respect to its parameters. A basic
m... |
"""
The MIT License (MIT)
Copyright (c) 2015-2016 <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 rights
to use, copy, modify, merge, ... |
import requests
import pyttsx3 as p
import speech_recognition as sr
import time
from datetime import date
"""url = "http://api.weatherapi.com/v1/current.json?key=9d1a06cf296748bba91154256201606&q=77494"
response = requests.get(url)
get_response = response.json()
print(get_response)
init = p.init()
... |
from __future__ import absolute_import
# Plotting utilities
import matplotlib.backends.backend_pdf
# Local utilities
from jetmontecarlo.utils.plot_utils import *
from jetmontecarlo.utils.color_utils import *
from jetmontecarlo.utils.hist_utils import *
# Local analytics
from jetmontecarlo.analytics.QCD_utils import ... |
import os
import warnings
import pytest
from python_json_config.config_node import ConfigNode
def test_creation(config_dict):
node = ConfigNode(config_dict)
assert node.key1 == 1
assert node.__dict__["_ConfigNode__path"] == []
assert isinstance(node.key2, ConfigNode)
nested_node = node.key2
... |
"""Command-line interface to rhasspyasr-kaldi-hermes"""
import argparse
import json
import logging
import threading
import time
import os
import sys
import typing
from pathlib import Path
import attr
import paho.mqtt.client as mqtt
from rhasspyasr_pocketsphinx import PocketsphinxTranscriber
from rhasspyhermes.asr impo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, <NAME> <<EMAIL>>
# (c) 2018, <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at yo... |
# _*_ coding::utf-8 _*_
from sklearn.neighbors import NearestNeighbors
from utils import *
def prepare_hyper_nodes(args, vani_adj):
'''
using BFS to analyze the sub-graphs in the vanilla graph,
return
the count of sub-graphs in the vanilla graph,
the size of each sub-graph,
the i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Console script for filter_classified_reads."""
import logging
import sys
from typing import Optional, List
import click
from filter_classified_reads.util import \
parse_taxids_string, \
compare_kraken2_and_centrifuge
from filter_classified_reads.io import writ... |
'''Implementation of class Rotor as a basic unit to describe a system
of interest.
'''
import abc
import numpy as np
from state import State
import functions as f
from scipy import linalg
import constants as const
class Molecule(abc.ABC):
"""Abstract base class for molecules (i.e., system of interest)
"""
... |
import os
import csv
import time
import json
import pandas as pd
from talib import abstract
from bs4 import BeautifulSoup
from slackclient import SlackClient
from configparser import SafeConfigParser
from urllib.request import Request, urlopen
pd.set_option('mode.chained_assignment', None) #https://www.dataquest.io/blo... |
import numpy as np
import sys
import pickle
import time
import json
sys.path.append('..')
from faser_math import fsr, tm
def filter_manipulability_at_threshold(results, score_threshold=0.5):
"""
Filter Manipulability At THreshold
(See only the parts of a workspace that have desired manipulability)
Arg... |
"""Functions used to fit models to light curve data
Author: <NAME>
Email: <EMAIL>
"""
import numpy as np
import lmfit
import copy
from importlib import reload
from ..lib import lsq
reload(lsq)
from .parameters import Parameters
def lsqfitter(lc, model, verbose=True, **kwargs):
"""Perform least-squares fit
... |
# Licensed to Cloudkick, Inc ('Cloudkick') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# Cloudkick licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this f... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
"""hostlists range management functions"""
import operator
import re
from .plugin_manager import run_plugin_expand
# A list of operators we use for set options
SET_OPERATORS = ['-']
def cmp_compat(a, b):
"""
Simple comparison function
:param a:
:param b:
:return:
"""
return (a > b) - (a ... |
import argparse
import os
import csv
from tqdm import tqdm # type: ignore
import subprocess
import pandas as pd # type: ignore
from loguru import logger
def load_gt_graph(graph_path):
"""Load a graph in graphml or gt format."""
from graph_tool.all import load_graph
logger.info(f"loading the generated grap... |
#!/usr/bin/python
from __future__ import print_function, division
import numpy as np
import tensorflow as tf
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as mpl
num_epochs = 100
total_series_length = 920
truncated_backprop_length = 15
state_size = 4
num_classes = 4
batch_size = 5
num_batches = ... |
"""
Principles:
- library not framework (helpers + decorators)
- avoid abstractions, especially IOC
- simplicity of implementation matters
- reuse django (i.e. validation)
- when impossible to reuse, mimic it
- do not hide intentions
- the less abstraction the better (.json() instead of .response())
DWIM, prac... |
import csv
import cv2
from keras.callbacks import EarlyStopping
from keras.models import Sequential
from keras.layers import Dense, Flatten, Lambda, Cropping2D, Dropout
from keras.layers.convolutional import Conv2D
import numpy as np
import os
from sklearn.model_selection import train_test_split
from sklearn.utils impo... |
from __future__ import division
import numpy as np
from sklearn.preprocessing import LabelBinarizer
from skater.util.logger import build_logger
from skater.util.logger import _INFO
logger = build_logger(_INFO, __name__)
def flatten(array):
return [item for sublist in array for item in sublist]
def add_column_n... |
"""
Pytorch model to RRAM mapping
Power and energy estimation (per image)
"""
import argparse
import numpy as np
import torch
import torch.nn as nn
import os
import time
import sys
import logging
import torch.utils.model_zoo as model_zoo
import torchvision
from torchsummary import summary
from dataset import get_load... |
from flask import Blueprint, session
from flask_login import current_user, login_required
from flask import render_template, flash, url_for, redirect, request
from sqlalchemy import or_
import json
from wtforms import Label
from fellowcrm import db
from .models import Deal, DealStage
from fellowcrm.common.paginate imp... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
# Copyright 2019-2020 SURF.
# 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, soft... |
from avalon import io
from reveries.maya import utils
from reveries.maya import lib, pipeline
class RigPrimValidation(object):
def __init__(self):
self.validation_result = True
self.validation_log = []
self.model_data = {}
def get_invalid_group(self):
_, invalid_group = utils... |
# Copyright 2019 The TensorFlow 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 applica... |
"""
1.Question 1
In this programming problem you'll code up Dijkstra's shortest-path algorithm.
The file (dijkstraData.txt) contains an adjacency list representation of an undirected weighted graph with 200 vertices labeled 1 to 200. Each row consists of the node tuples that are adjacent to that particular vertex ... |
'''
implementation of a neural net that is trained to recognize the number and then do the comparison
Use weight sharing , siamese type neural net
'''
################################################################################
import torch
import math
from torch.autograd import Variable
from torch import nn
fro... |
# Python AST to Pycopy VM bytecode compiler
#
# This module is part of Pycopy https://github.com/pfalcon/pycopy
# and pycopy-lib https://github.com/pfalcon/pycopy-lib projects.
#
# Copyright (c) 2019, 2020 <NAME>
#
# The MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of t... |
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from imgaug import augmenters as iaa
from typing import Callable, Tuple
from pathlib import Path
from PIL import Image
import numpy as np
import torch
import h5py
import imgaug
class ImgAugTransform:
def __init__(self):
se... |
import cloudscraper
class TellonymTell():
def __init__(self, tellJSON):
#print(tellJSON)
self.question = tellJSON["tell"]
self.answer = tellJSON["answer"]
self.createdAt = tellJSON["createdAt"]
self.likeCount = tellJSON["likesCount"]
def GetQuestion(self):
retur... |
"""
Continuously scroll randomly generated After Dark style toasters.
Designed for an ItsyBitsy M4 Express and a 1.3" 240x240 TFT
Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!
Written by <NAME> for Adafruit I... |
"""
This module implements a format handler for DAN DL7 files. These are line
oriented, character separated, and poorly documented. This parser doesn't
handle all possible record types at this time.
"""
from divelog import *
import logging
FORMAT_NAME = 'DL7'
logger = logging.getLogger(__name__)
def __parse_file_he... |
bl_info = {
"name": "Procedural Symmetries",
"description": "This tool automates the process of itteritavly adding symmetry planes to a custom mesh.",
"author": "<NAME>",
"version": (1, 0, 0),
"blender": (3, 0, 0),
"location": "3D View > Tools",
"warning": "",
"wiki_url": "",
... |
# -*- coding:utf-8 -*-
from datetime import datetime
from datetime import timedelta
import arrow
from functools import partial
import calendar
now = arrow.now
utcnow = arrow.utcnow
prc_tz = 'prc'
def prcnow():
utcnow().to(prc_tz)
def prctoday():
return prcnow().date()
def span_range(start, end, frame, ... |
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
from sklearn.datasets import make_classification
from imblearn.over_sampling import SMOTE # doctest: +NORMALIZE_WHITESPACE
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
def KNN_aug(bin):
... |
"""
辅助工具类
-数据读取 read_bin
-解析指令 parse_instructions
-find_break 返回代码段的结尾即数据段的起点
-checkFlag 检测输入什么类型的指令
-outputDis 输出dis文件
-outputSim 输出Sim文件
"""
import instructions
import changeRegValues
# 根据flag判断是第一类操作还是第二类操作,然后映射操作符
opc = {
"0000": ['J', 'ADD'],
"0001": ['JR', 'SUB'],
"0010": ['BEQ', 'MUL'],
"0011": ... |
#!/usr/bin/env python
# coding: utf-8
import keras
keras.__version__
from keras.applications import inception_v3
from keras import backend as K
# We will not be training our model,
# so we use this command to disable all training-specific operations
K.set_learning_phase(0)
# Build the InceptionV3 network.
# The m... |
import ctypes
import random
import importlib
import numpy as np
# Set up ctypes function bindings
libpath = importlib.find_loader("libfht").path
libfht = ctypes.CDLL(libpath)
_fht = libfht.fht
_shuffle_bigger_lfsr = libfht.shuffle_bigger_lfsr
_shuffle_smaller_lfsr = libfht.shuffle_smaller_lfsr
_shuffle_bigger_o = lib... |
import torch
import torch.nn as nn
from torch.nn import functional as F
import torchvision
import torchvision.transforms as transforms
from torchvision.transforms import ToTensor
from torchvision.transforms import ToPILImage
import torchvision.models as models
import os
import cv2
import wget
from tqdm import tqdm, tq... |
# Copyright (c) 2011 OpenStack Foundation
# Copyright 2013 IBM Corp.
# 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... |
import logging
import math
import numpy as np
import torch
import torch.nn as nn
from glove import Glove
class GloveEmbedding(nn.Module):
def __init__(self, pretrained_embedding_path, vocab, embedding_size, freeze=False, **kwargs):
super().__init__()
self.vocab = vocab
self.vocab_size = ... |
"""This script configures GigabitEthernet2 interfaces on network devices.
Copyright (c) 2018 Cisco and/or its affiliates.
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, incl... |
"""Color-space transformation functions."""
import numpy as np
# the palette for rendering RGB colors on the Nintendo Entertainment System
NES_PALETTE = np.array([
[102,102,102], [ 0, 42,136], [ 20, 18,168], [ 59, 0,164],
[ 92, 0,126], [110, 0, 64], [108, 7, 0], [ 87, 29, 0],
[ 52, 53, 0], [ 12, 7... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.