content
stringlengths
0
894k
type
stringclasses
2 values
import torch import torch.nn.functional as F import numpy as np from scipy import stats from sklearn.cluster import MiniBatchKMeans class GMMOutput(torch.nn.Module): def __init__(self, n_components): super(GMMOutput, self).__init__() self.components = n_components def sample(self, x): ...
python
import numpy as np from .estimator import Estimator class Adaline(Estimator): def __init__(self, learning_rate, activation_function, loss_function, loss_variation_tolerance): super().__init__() self.learning_rate = learning_rate self.activation_function = activation_function self.loss_function = l...
python
from os import environ, path from telebot import TeleBot from RPG.bot_classes.game import Game # Импортирует все состояния игры from RPG.consts.game_states import MAIN_MENU, INVENTORY, INVENTORY_INFO, CREATE_PLAYER_MENU, PLAYER_PROFILE, \ CABIN, CAPTAIN_BRIDGE, CARGO_HOLD, COMPUTER, CREATE_SPACESHIP_MENU, ESTRAD_PO...
python
import datetime import pandas as pd import numpy as np from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from analytics.events.utils.dataframe_builders import SupplementEventsDataframeBuilder, SleepActivityDataframeBuilder, \ ...
python
#!flask/bin/python # imports here import click from datetime import datetime from flask import abort, Flask, g, jsonify, request from info import info import os import sqlite3 ### app instantiation ### app = Flask(__name__) app.config.update({ 'JSON_SORT_KEYS':False, 'DATABASE':os.path.join(app.root_path, '...
python
from __future__ import division from __future__ import print_function import os import random import logging from tqdm import tqdm import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable as Var import sys # IMPORT CONSTANTS from learning.treelstm.config import parse_args fr...
python
#!python3 # Code Challenge 02 - Word Values Part II - a simple game # http://pybit.es/codechallenge02.html import itertools import random from data import DICTIONARY, LETTER_SCORES, POUCH NUM_LETTERS = 7 def draw_letters(): """Pick NUM_LETTERS letters randomly. Hint: use stdlib random""" draw = random.samp...
python
d=[3,22,99,68,34,17,45,66,58,89,73,12,92,1,5,26,91,32,86] print d,'\n' p=len(d) bin_size=raw_input('Choose the bin_size(Eg:9) ') for i in range(int(min(d)),int(max(d)),int(bin_size)+1): print "{:>4} - {:<4}".format(i,i+int(bin_size)),' ', for j in range(0,p): if d[j]>=i and d[j]<=i+int(bin_size): print '-', pr...
python
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # OS.FreeBSD.get_vlans # --------------------------------------------------------------------- # Copyright (C) 2007-2011 The NOC Project # See LICENSE for details # -----------------------------------------------------------...
python
import os import kubectl import pathlib version = open(os.path.join(pathlib.Path(__file__).parent.absolute(),"../release")).read(1024) # version = "0.9.7" test_namespace = "test" clickhouse_template = "templates/tpl-clickhouse-stable.yaml" # clickhouse_template = "templates/tpl-clickhouse-19.11.yaml" # clickhouse_tem...
python
from django.apps import AppConfig class ListingsConfig(AppConfig): name = 'listings' verbose_name = "User Listings"
python
import logging from dojo.models import Test_Type PARSERS = {} # TODO remove that SCAN_SONARQUBE_API = 'SonarQube API Import' def register(parser_type): for scan_type in parser_type().get_scan_types(): parser = parser_type() if scan_type.endswith('detailed'): parser.set_mode('detailed'...
python
from django.views import generic class HomePage(generic.TemplateView): template_name = "home.html" class FAQPage(generic.TemplateView): template_name = "faq.html"
python
from keras import backend as K from keras.engine.topology import Layer from keras import initializers, regularizers, constraints class Attention(Layer): def __init__( self, step_dim=65, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, ...
python
from .habitica_object import HabiticaObject import attrdict class Group(HabiticaObject): def __init__(self, id_str): """A group/party in Habitica.""" assert False, "Not done yet!"
python
"""Revert revision foreign key Revision ID: 83f49fddbcb6 Revises: 55e1f2f5d706 Create Date: 2020-05-19 12:25:02.795675 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "83f49fddbcb6" down_revision = "55e1f2f5d706" branch_labels = None depends_on = None def upg...
python
from __future__ import division from ..errors import InvalidParamsError from ..utils import one_row_params_array from .base import UncertaintyBase from scipy import stats import numpy as np class NormalUncertainty(UncertaintyBase): id = 3 description = "Normal uncertainty" @classmethod def validate(c...
python
from .global_var import * ## Python C-like struct s2 ## from dataclasses import dataclass # Queue for FIFO from queue import SimpleQueue # To save current time from time import time # Random replacement from random import choice #---------------------------# @dataclass class PAGE: #{{{ index: int# page index ...
python
"""Generalized Pauli matrices.""" import numpy as np from toqito.matrices import shift from toqito.matrices import clock def gen_pauli(k_1: int, k_2: int, dim: int) -> np.ndarray: r""" Produce generalized Pauli operator [WikGenPaul]_. Generates a :code:`dim`-by-:code:`dim` unitary operator. More specifi...
python
"""base classes to be inherited from for various purposes""" from abc import ABC from abc import abstractmethod import argparse from typing import List, Type from ec2mc.validate import validate_perms class CommandBase(ABC): """base class for most ec2mc command classes to inherit from""" _module_postfix = "_c...
python
try: import unzip_requirements except ImportError: pass import json, os, sys, re import base64 import boto3 from botocore.signers import RequestSigner from kubernetes import client from kubernetes.client import ApiClient, Configuration from kubernetes.config.kube_config import KubeConfigLoader def get_bearer_toke...
python
# -*- coding: utf-8 -*- from .utils import TestUtils from .ticker import TestTicker from .visuals import TestVisuals from .figure import TestFigure from .dates import TestDates #-----------------------------------------------------------------------------
python
from smexperiments import api_types def test_parameter_str_string(): param = api_types.TrialComponentParameterValue("kmeans", None) param_str = str(param) assert "kmeans" == param_str def test_parameter_str_number(): param = api_types.TrialComponentParameterValue(None, 2.99792458) param_str =...
python
import socket def validate_ip4 (address): try: socket.inet_aton(address) ip4_address = address except (socket.error, TypeError): ip4_address = None return ip4_address def validate_ip6 (address): try: socket.inet_pton(socket.AF_INET6, address) ip6_address = address except (socket.error, TypeError): i...
python
# Generated by Django 3.0.2 on 2020-03-04 20:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('userprofile', '0030_skill'), ] operations = [ migrations.AddField( model_name='profile', name='skills', ...
python
import os import sys from typing import List import numpy as np import scipy as sp import scipy.stats from utilities.plotting import Plot def main(): figure_num = int(sys.argv[1]) for_print = bool(int(sys.argv[2])) def load_and_plot(dir: str, plot: Plot, name: str): series, means, confidences =...
python
import utils as util import tensorflow as tf import numpy as np def forecast_model(series, time,forecastDays): split_time=2555 time_train=time[:split_time] x_train=series[:split_time] split_time_test=3285 time_valid=time[split_time:split_time_test] x_valid=series[split_time:split_time_test] ...
python
# terrascript/provider/hashicorp/template.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:28:21 UTC) import terrascript class template(terrascript.Provider): """terraform-provider-template""" __description__ = "terraform-provider-template" __namespace__ = "hashicorp" __name__ = "te...
python
import itertools from typing import List, Tuple from card_utils import deck from card_utils.deck.utils import ( rank_partition, suit_partition, ranks_to_sorted_values ) from card_utils.games.gin.deal import new_game def deal_new_game(): """ shuffle up and deal each player 7 cards, put one car...
python
"""\ Setup Kubernetes on cloud """ import logging import os import sys sys.path.append(os.path.abspath("../..")) import main def start(config, machines): """Setup Kubernetes on cloud VMs using Ansible. Args: config (dict): Parsed configuration machines (list(Machine object)): List of machi...
python
class Player(object): """A class used to represent a poker player. Attributes: name: name of the player stack: amount of money the player has hand: two Cards """ def __init__(self, name, stack, hand): """Inits Player with name, stack, and two cards that will compose their hand""" self.name = name self...
python
import re import requests from hashlib import sha1 from urllib.parse import urlsplit from apphelpers.rest.hug import user_id from app.libs import asset as assetlib from app.libs import publication as publicationlib from app.models import AssetRequest, asset_request_statuses from app.models import moderation_policies, ...
python
model = dict( type='LiteFlowNet', encoder=dict( type='NetC', in_channels=3, pyramid_levels=[ 'level1', 'level2', 'level3', 'level4', 'level5', 'level6' ], out_channels=(32, 32, 64, 96, 128, 192), strides=(1, 2, 2, 2, 2, 2), num_convs=(1, 3, 2, ...
python
# Copyright 2021 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
python
""" Codemonk link: https://www.hackerearth.com/problem/algorithm/lonely-monk-code-monk-ebca6e4a/ Being alone in the new world, Monk was little afraid and wanted to make some friends. So he decided to go the famous dance club of that world, i.e "DS Club" and met a very beautiful array A of N integers, but for some reas...
python
#!/usr/bin/python n = int(input()) matrix = [] res = [] for _ in range(n): matrix.append([int(i) for i in input().split()]) for i in range(2 * n): for j in range(n): if 0 <= i - j < n: res.append(matrix[i - j][j]) print(' '.join(map(str, res)))
python
""" Run PCA using the covariance matrix estimated with empirical Bayes """ import numpy as np import scanpy.api as sc import simplesc if __name__ == '__main__': data_path = '/netapp/home/mincheol/parameter_estimation/inteferon_data/' adata = sc.read(data_path + 'interferon.raw.h5ad') estimator = simplesc.Sing...
python
import os, sys; sys.path.insert(0, os.path.join("..", "..")) from pattern.en import sentiment, polarity, subjectivity, positive # Sentiment analysis (or opinion mining) attempts to determine if # a text is objective or subjective, positive or negative. # The sentiment analysis lexicon bundled in Pattern focuses on ad...
python
import numpy as np import tensorflow as tf class MNIST: """MNIST dataset wrapper. Attributes: x_train: np.ndarray, [B, 28, 28, 1], dataset for training. x_test: np.ndarray, [B, 28, 28, 1], dataset for testing. y_train: np.ndarray, [B], label for training, 0 ~ 9. y_test: np.ndar...
python
import os import unittest import json from cloudsplaining.scan.managed_policy_detail import ManagedPolicyDetails from cloudsplaining.scan.group_details import GroupDetailList from cloudsplaining.scan.role_details import RoleDetailList from cloudsplaining.scan.user_details import UserDetailList from cloudsplaining.scan....
python
"""This module defines some handy :py:class:`Importable` elements. An ``Importable`` is usually composed of two different parts: * A *natural key* used to identify *the same* element across different systems. This is the only required component for an ``Importable``. * An optional set of properties that form *the ...
python
import rosnode import subprocess import time import os ros_nodes = rosnode.get_node_names() if not '/robot_state_publisher' in ros_nodes: os.system('ifconfig eth0 192.168.0.2') command='roslaunch sick_tim sick_tim571_2050101.launch' process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) ...
python
#!/usr/bin/env python3 """ Requires: python-mnist numpy sklearn """ import sys sys.path.insert(0, 'src/') import mnist import numpy as np from numpy.linalg import norm as l21_norm from sklearn.metrics.cluster import normalized_mutual_info_score as nmi import os np.random.seed(int(os.environ.get('seed', '42'))) print...
python
#!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
python
from kafka import KafkaConsumer from kafka import KafkaProducer import time import os import json print('Pinger Demo 1.0') kafka_url = str(os.environ['KAFKA_URL']) kafka_port = int(os.environ['KAFKA_PORT']) kafka_address = kafka_url + ':' + str(kafka_port) consumer = None while True: try: consumer ...
python
import tkinter.filedialog as tk import pandas as pd class Dados(): def __init__(self): super().__init__() def importarDados(self): file_name = tk.askopenfilename(filetypes=(('csv files', '*.csv'), ('csv files', '*.csv'))) return file_name def abrirArquivoCsv(self,file_name): ...
python
#!/usr/bin/python import sys import zlib import time import os import requests import re #import requests-futures from baseconv import base62 from etaprogress.progress import ProgressBar def main(): PROGRAM_NAME = "zbing" if len(sys.argv) != 3: print("USAGE: python "+PROGRAM_NAME+".py <URL> <length>") prin...
python
import pathlib import unittest from deep_hipsc_tracking import pipeline # Tests class TestPipelineStages(unittest.TestCase): def test_stages_exist(self): cls = pipeline.ImagePipeline exp = [ 'write_config_file', 'extract_frames', 'ensemble_detect_cells', ...
python
# -*- coding: utf-8 -*- """ Created on Thu Aug 20 13:39:18 2020 @author: Administrator """ from __future__ import division import time import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import cv2 # from models_nolambda import * from models_nolambda_focallossw impo...
python
#!/usr/bin/env python from scipy import * from scipy import weave from scipy import linalg from pylab import * import sys def ReadKlist(fklist, ReadBS=False): fk = open(fklist,'r') data = fk.readlines() nkp = [line[:3]=='END' for line in data].index(True) if data[nkp][:3]!='END': print 'wrong ...
python
"""Hacking, by Al Sweigart al@inventwithpython.com The hacking mini-game from "Fallout 3". Find out which seven-letter word is the password by using clues each guess gives you.""" __version__ = 1 import random, sys # Setup the constants: # The "filler" characters for the board. GARBAGE_CHARS = '~!@#$%^&*()_+-={}[]|...
python
class Settings: database_location = "./db/instapy.db" browser_location = "./assets/chromedriver"
python
""" Luxafor abstracted interface """ import time from .api import API from .constants import ( LED_FLAG_BOTTOM, LED_FLAG_MIDDLE, LED_FLAG_TOP, LED_POLE_BOTTOM, LED_POLE_MIDDLE, LED_POLE_TOP ) LEDS = [ ['LED_FLAG_TOP', 1, LED_FLAG_TOP], ['LED_FLAG_MIDDLE', 2, LED_FLAG_MIDDLE], ['LED_FLAG_BOTTOM', 3...
python
student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # TODO-1: Create an empty dictionary called student_grades. student_grades = {} # TODO-2: Write your code below to add the grades to student_grades.👇 for student_name in student_scores: score = s...
python
import os import time def get_exec_out(sxcute_str): out_list = os.popen(sxcute_str).readlines() return out_list if __name__ == '__main__': excute_str = 'nvidia-smi' out_list = get_exec_out(excute_str) # print(out_list) for oo in out_list: if oo.find('python') != -1: #...
python
bind = ["0.0.0.0:8000"] workers = 4 threads = 2 max_requests = 10000 max_requests_jitter = 100 accesslog = "-" errorlog = "-" limit_request_line = 0
python
from ._version import get_versions __version__ = get_versions()['version'] del get_versions import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") # Register nbextension def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest...
python
# zwei 12/16/2013 # accumulate generator def group_iter(iterator, n): # print(iterator) accumulator = [] for item in iterator: accumulator.append(item) if len(accumulator) == n: yield accumulator accumulator = [] if len(accumulator...
python
from typing import List from cloudrail.knowledge.context.aws.ec2.security_group import SecurityGroup from cloudrail.knowledge.context.aws.networking_config.network_configuration import NetworkConfiguration from cloudrail.knowledge.context.aws.networking_config.network_entity import NetworkEntity from cloudrail.knowled...
python
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class XsdkExamples(CMakePackage): """XSDK Examples show usage of libraries in the XSDK package.""...
python
import pytest from mold.parser import TemplateSyntaxError, parse from mold.tokenizer import tokenize from .common import load_fixture def test_alltags(): filename, contents = load_fixture("alltags") assert list(parse(tokenize(filename, contents))) def test_unexpected_end(): filename, contents = load_f...
python
#!/usr/bin/env python """ Create factor graphs for LQR control Author: Gerry Chen, Yetong Zhang, and Frank Dellaert """ import gtsam import numpy as np import matplotlib.pyplot as plt from dynamics_lti import create_lti_fg, plot_trajectory, solve_lti_fg def add_lqr_costs_fg(graph, X, U, Q, R, x_goal=np.array([])): ...
python
# coding: UTF-8 # Install XIMEA software package # Copy 'XIMEA\API\Python\v3\ximea' to 'PythonXX\Lib' from ximea import xiapi import cv2 import numpy as np # Connect to camera cam = xiapi.Camera() cam.open_device_by_SN('XXXXXXXX') # Enter serial number of your Ximea camera # Configuration cam.set_exp...
python
import pytest from sqlalchemy.orm import Session from connexion_sql_utils import BaseMixin, BaseMixinABC, get, event_func, \ to_json from .conftest import Foo import json def test_save(): foo = Foo(bar='some data') foo.save() assert Foo.query_by(bar='some data').first() is not None foo.id = 'b...
python
from platform import node import torch import torch.nn as nn from torch.nn import functional as F from torch.nn.modules import padding from torch.nn.modules.normalization import LayerNorm from models.modules import BiMatchingNet from models.treeGNN import TreeGNN import pdb class BranT(nn.Module): def __init__(se...
python
import logging from lib.amazon_properties import get_properties_compilers_and_libraries, get_specific_library_version_details logger = logging.getLogger(__name__) logger.level = 9 # def test_should_contain_some_compilers_and_libraries(): # [_compilers, _libraries] = get_properties_compilers_and_libraries('c++', ...
python
class Cache(object): def __init__(self, capacity = -1): self.capacity = capacity self.cache = {} self.index = {} @property def size(self): return len(self.cache) @property def has_capacity(self): return (self.capacity == -1) or (self.capacity > len(self.cache)) def set(self, key, value): if...
python
from serpent.environment import Environment from serpent.input_controller import KeyboardKey from serpent.utilities import SerpentError import time import collections import numpy as np class StartRegionsEnvironment(Environment): def __init__(self, game_api=None, input_controller=None, episodes_per_startregi...
python
import asyncio import aiohttp import pickle import csv from bs4 import BeautifulSoup import re import argparse import sys import getpass import time def parse_arguments(): parser = argparse.ArgumentParser( description=( 'Descarga las paginas [START, FINISH) del foro de la facultad.\n' 'El tamanno def...
python
from numpy import array,dot from numpy.linalg import inv from getopt import getopt import sys def calc_displacements(initial,final): icoord=parse_poscar(initial)[1] fcoord=parse_poscar(final)[1] disp=fcoord-icoord return disp def parse_poscar(ifile): with open(ifile, 'r') a...
python
import math import numpy from sympy import Rational, gamma, prod class NSphereScheme: def __init__(self, name, dim, weights, points, degree, citation): self.name = name self.dim = dim self.degree = degree self.citation = citation if weights.dtype == numpy.float64: ...
python
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation # {"feature": "Education", "instances": 23, "metric_value": 0.9986, "depth": 1} if obj[1]<=2: # {"feature": "Coupon", "instances": 16, "metric_value": 0.896, "depth": 2} if obj[0]<=3: # {"feature": "Occupation", "instances": 11, "met...
python
# -*- coding: utf-8 -*- """Test to verify that the scheduled actions are properly executed.""" import os import test from datetime import datetime import pytz from celery.contrib.testing.worker import start_worker from django.conf import settings from django.contrib.auth import get_user_model from django.core import...
python
# -*- coding:utf-8 -*- # @atime : 2021/1/24 12:58 下午 """ edit distance https://leetcode-cn.com/problems/edit-distance/ """ def solution1(word1: str, word2: str): """ 计算编辑距离 Args: word1 (str): 字符串1 word2 (str): 字符串2 Returns: (int) distance """ if not word1 or not word2: ...
python
# # This file is part of the FFEA simulation package # # Copyright (c) by the Theory and Development FFEA teams, # as they appear in the README.md file. # # FFEA 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 ...
python
# 1. python 中函数的工作原理 import inspect frame = None def bar(): global frame frame = inspect.currentframe() def foo(): bar() # python.exe 会用一个叫做 PyEvalFrameEx(c函数)去执行foo函数,首先会创建一个栈帧(stack_frame) """ python 一切皆对象,栈帧对象, 字节码对象 当foo调用子函数bar, 又会创建一个栈帧 所有的栈帧都是分配在 堆内存 上,这就决定了栈帧可以独立于调用者存在 (Python 动态语言 函数调用完成,栈帧不会销毁...
python
# conding=utf-8 import Putil.base.logger as plog logger = plog.PutilLogConfig('data_sampler_factory').logger() logger.setLevel(plog.DEBUG) from Putil.demo.deep_learning.base import data_sampler as standard from util import data_sampler as project def data_sampler_factory(args, data_sampler_source, data_sampler_name...
python
# file_loader.py """ Importe les bibliotheques "XML", "SQLite" et "Pygame" """ import xml.etree.ElementTree as ET import sqlite3 import pygame as pg vec = pg.math.Vector2 """ Classe SpriteSheet - But : decouper les sprites en fonction des donnees XML fournies. - Fonctionnement : decoupe l'image associee grace aux co...
python
from storage import read_region_snapshot, _round_15min import datetime from dateutil.parser import parse def test_read_region_snapshot(): read_region_snapshot('slc_ut', '2021-09-01T00:00:00Z') def test__round_15min(): ts = parse('2021-01-31T23:59:01Z') ret = _round_15min(ts) assert ret == parse('202...
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from .cumulative_return import cumulative_return_graph from .score_ic import score_ic_graph from .report import report_graph from .rank_label import rank_label_graph from .risk_analysis import risk_analysis_graph
python
from django.apps import AppConfig class GameForumOtherConfig(AppConfig): name = 'tulius.gameforum.other' label = 'game_forum_other'
python
import pickle import time import os import random from time import sleep import communicate.dealer_pb2 as dealer_pb2 import communicate.dealer_pb2_grpc as rpc # V1.4 # 0 黑桃 1 红桃 2 方片 3 草花 # 牌的id: 0-51 ''' 牌面level编号 皇家同花顺:10 同花顺 :9 四条 :8 葫芦 :7 同花 :6 顺子 :5 三条 :4 ...
python
# Buy first thing in the morning # Sell the moment we get 1% profit after commission # Buy again # Cut losses only when it is at 80%. # repeat # The idea # we should buy in 10% increments (tunable) throughout the day if the price is going up # every buy should be around 10 mins apart (tunable) # Thus we ...
python
#!/usr/bin/env python3 # ---------------------------------------------------------------------------- # Copyright (c) 2020--, Qiyun Zhu. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------...
python
from __future__ import absolute_import # need to get system mendeley library from mendeley.exception import MendeleyException import mendeley as mendeley_lib import os def get_mendeley_session(): mendeley_client = mendeley_lib.Mendeley( client_id=os.getenv("MENDELEY_OAUTH2_CLIENT_ID"), client_sec...
python
# Copyright 2014 Alistair Muldal <alistair.muldal@pharm.ox.ac.uk> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Th...
python
from . import item, user
python
import layer import torch.nn as nn import torch from torch.autograd import Variable try: import ipdb except ImportError: pass class Translator(object): def __init__(self, opt, model=None, dataset=None): self.opt = opt if model is None: checkpoint = torch.load(opt.model) ...
python
from server.settings.base import * # noqa
python
import numpy as np import scipy.stats as stats class SimpleImputer: """ Simple mean/most frequent imputation. """ def __init__(self, ncat, method='mean'): self.ncat = ncat assert method in ['mean', 'mode'], "%s is not supported as imputation method." %method self.method = method d...
python
from netmiko.cdot.cdot_cros_ssh import CdotCrosSSH __all__ = ["CdotCrosSSH"]
python
from .helpers import deprecated_alias @deprecated_alias('ioat_scan_copy_engine') @deprecated_alias('scan_ioat_copy_engine') def ioat_scan_accel_engine(client): """Enable IOAT accel engine. """ return client.call('ioat_scan_accel_engine')
python
import time import paddle import paddle.fluid as fluid from network import word2vec_net from conf import * import logging logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("fluid") logger.setLevel(logging.INFO) def get_dataset_reader(inputs): dataset = fluid.Datase...
python
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc from lndgrpc.compiled import signer_pb2 as lndgrpc_dot_compiled_dot_signer__pb2 class SignerStub(object): """Signer is a service that gives access to the s...
python
""" @name: PyHouse/Project/src/_test/test_testing_mixin.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2014-2019 by D. Brian Kimmel @license: MIT License @note: Created on Oct 6, 2014 @Summary: Passed all 16 tests - DBK - 2019-06-23 """ from Modules.Core import PyHouseI...
python
import unittest import gtirb from helpers import SearchScope, parameterize_one class ByteIntervalsOnTests(unittest.TestCase): @parameterize_one( "scope", (SearchScope.ir, SearchScope.module, SearchScope.section) ) def test_byte_intervals_on(self, scope): ir = gtirb.IR() m = gtirb....
python
from django.contrib import admin from .models import Tags,Category,Blog admin.site.register([Tags,Category,Blog]) # Register your models here.
python
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from typing import Any, Dict, Optional, Tuple, Union from packaging.utils import canonicalize_name as canonicalize_project_name from pants.engine.targ...
python
import numpy as np import mbuild as mb from mbuild.lib.bulk_materials import AmorphousSilicaBulk from mbuild.lib.recipes import SilicaInterface from mbuild.tests.base_test import BaseTest class TestSilicaInterface(BaseTest): def test_silica_interface(self): tile_x = 1 tile_y = 1 thickness...
python
import unittest import importlib import asyncio import time,os from contextlib import contextmanager import hashlib from datetime import datetime @contextmanager def add_to_path(p): import sys old_path = sys.path sys.path = sys.path[:] sys.path.insert(0, p) try: yield finally: s...
python