content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/python ############################ # Librairies import ############################ import os import checkUserInput ############################ # Functions ############################ def confirmation_address(address, what): confirmation = False if checkUserInput.question_and_verification("Confirmez...
python
# -*- python -*- import logging import unittest import electionfraud.testdata as eftd import electionfraud.redist as redist logging.basicConfig(level=logging.DEBUG) class RedistributorTest(unittest.TestCase): pass class TestIdentity(RedistributorTest): def setUp(self): self.rd = redist.Identity(ef...
python
#%% cell """ # Solving a New Keynesian model with Python This file is part of a computational appendix that accompanies the paper. > MATLAB, Python, Julia: What to Choose in Economics? > > Coleman, Lyon, Maliar, and Maliar (2017) In order to run the codes in this file you will need to install and configure a few Pyt...
python
arr = [1, 34, 3, 98, 9, 76, 45, 4] l = len(arr) digits =[] # # Uncomment and use either of the 2 digitconverter # def digitconverter(num): # # digit = [] # while num !=0: # digits.append(num%10) # num = num//10 # def digitconverter(num): # number = str(num) # for i in ra...
python
from rest_framework.serializers import ModelSerializer from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import IdentifiedBaseStation, Operator class IdentifiedBaseStationSerializer(GeoFeatureModelSerializer): class Meta: model = IdentifiedBaseStation geo_field = '...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import pathlib import pickle import yaml import numpy as np from librosa import load from tools import yaml_loader __author__ = 'Konstantinos Drossos -- Tampere University' __docformat__ = 'reStructuredText' __all__ = [ 'dump_pickle_file', 'load_pickle_file', 'read_t...
python
# Generated by Django 3.2.7 on 2021-09-17 12:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Course', '0001_initial'), ] operations = [ migrations.CreateModel( name='LearnGroup', fields=[ ('id'...
python
import gym import copy env = gym.make('LunarLander-v2') env.seed(111) # we cna fix the background for now env.action_space.np_random.seed(123) #fix random actions for now env.reset() for step in range(60): #input() env.render() #save info before action if step == 55: save_state = copy.copy(info)...
python
import asyncio import inspect import warnings import functools from typing import Callable, Generic, TypeVar, Type, Optional def deprecated(reason, stacklevel=2) -> Callable: """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the f...
python
# Copyright 2013-2022 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) import os from spack.package import * class HashTest3(Package): """Used to test package hashing """ homepa...
python
""" Yandex Transport Webdriver API. Continuous Monitoring tests. NOTE: These are designed to run indefinitely and check current YandexTransportAPI status. Tests are working with Live Data, with several random delays between them. They take a lot of time as a result. NOTE: Tests require running YandexTrans...
python
from __future__ import ( absolute_import, unicode_literals, ) import importlib import os import pytest @pytest.fixture(scope='module') def server_settings(server_class): """ Load the server_settings used by this service. """ if server_class.use_django: from django.conf import setting...
python
#! /usr/bin/env python3 from setuptools import find_packages from setuptools import setup def parse_requirements(filename): """Given a filename, strip empty lines and those beginning with #.""" with open(filename) as rfd: output = [] for line in rfd: line = line.strip() ...
python
import torch from allennlp.common.testing import AllenNlpTestCase from allennlp.common.params import Params from allennlp.training.learning_rate_schedulers import ( LearningRateScheduler, CombinedLearningRateScheduler, PolynomialDecay, ) from allennlp.training.optimizers import Optimizer class TestCombin...
python
#!/usr/bin/python3 for i in range(122, 96, -1): if i % 2 == 0: print("{:s}".format(chr(i)), end="") else: print("{:s}".format(chr(i-32)), end="")
python
# -*- coding: utf-8 -*- ## @package palette.main # # Main funcion. # @author tody # @date 2015/08/20 from palette.datasets.google_image import createDatasets from palette.results.single_image import signleImageResults from palette.results.multi_images import multiImagesResults if __name__ == '__main__'...
python
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence class RNN(nn.Module): def __init__(self, config): """ type_rnn: RNN, GRU, LSTM 可选 """ super(RNN, self).__init__() # self.xxx = config.xxx self.input_size = c...
python
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or '28#oN^^VfhcxV7x8H32yGOGIk2wLY%OFi!!V' ### email configs,https://pythonhosted.org/Flask-Mail/ ### MAIL_SERVER = os.environ.get('MAIL_SERVER') MAIL_PORT = int(os.environ.get('MA...
python
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
python
import os import sys sys.path.append( os.path.normpath( os.path.join(os.path.abspath(__file__), "..", "..", "..", "common") ) ) from env_indigo import * indigo = Indigo() indigo.setOption("ignore-stereochemistry-errors", True) indigo.setOption("molfile-saving-skip-date", True) def testSerializeIsoto...
python
import arrow import dateutil import requests COUNTRY_CODE = 'RO' def fetch_RO(): url = 'http://www.transelectrica.ro/sen-filter' data = {} for item in requests.get(url).json(): d = list(item.iteritems())[0] data[d[0]] = d[1] obj = { 'countryCode': COUNTRY_CODE, 'da...
python
from claf.config.factory.data_reader import DataReaderFactory from claf.config.factory.data_loader import DataLoaderFactory from claf.config.factory.model import ModelFactory from claf.config.factory.optimizer import OptimizerFactory from claf.config.factory.tokens import TokenMakersFactory __all__ = [ "DataRead...
python
import os import shutil from datetime import datetime from os.path import dirname, join import torch class Logger(): def __init__(self, para): self.para = para now = datetime.now() if 'time' not in vars(para) else para.time now = now.strftime("%Y_%m_%d_%H_%M_%S") mark = para.model...
python
############################################################################### # Exceptions ############################################################################### class UnexpectedCharacter(Exception): def __init__(self, char, idx, matcher): super().__init__( 'Expected {} at position ...
python
from ex112_1.utilidadescev import moeda, dados preco = dados.leiadinheiro('Digite o preço: ') moeda.resumo(preco, 90, 35)
python
#!/usr/bin/env python3 """ Filters for masking stationary or near stationary data based on vessel speed """ def mask_stationary(Sv, speed, threshold): """ Mask stationary or near stationary data based on vessel speed Args: Sv (float): 2D numpy array with Sv data to be masked (dB) spee...
python
# TemperatureConverter Tests import unittest from TemperatureConverter import TemperatureConverter from TemperatureErrors import * class KnownValues(unittest.TestCase): knownValues = ( (0, 32), (100, 212) ) temp_converter = TemperatureConverter() # test value conversions def testCtoF(self): ""...
python
# Reads float and prints BRL money conversion to JPY # In 2020/11/01 JP¥ 1.00 = R$ 0.060 :) brl = float(input('Por favor, digite quanto dinheiro você tem na carteira: R$ ')) jpy = brl / 0.060 print('Com R$ {:.2f} você pode comprar ¥ {:.2f}.'.format(brl, jpy))
python
def print_error(message): print("An error occured: " + message) def remove_white_chars(line): line = line.replace('\t', '') line = line.replace(' ', '') line = line.replace('\n', '') line = line.replace('\r', '') return line def remove_comments_and_empty_lines(text): new_text = '' fi...
python
import os import logging from dp4py_config.section import Section from dp4py_config.utils import bool_env from dp4py_sanic.config import CONFIG as SANIC_CONFIG from dp_conceptual_search.config.utils import read_git_sha def get_log_level(variable: str, default: str="INFO"): """ Returns the configured log le...
python
from federatedscope.tabular.model.quadratic import QuadraticModel __all__ = ['QuadraticModel']
python
string = """0: "HOW ResidentSleeper LONG ResidentSleeper CAN ResidentSleeper THIS ResidentSleeper GO ResidentSleeper ON ResidentSleeper" 1: "REPPIN LONDON ONTARIO 519 GANG" 2: "my eyes" 3: "CLULG" 4: "ResidentSleeper" 5: "mvp ward" 6: "4Head EU WATCHING NA 4Head STILL AWAKE 4Head NO JOB 4Head NO RESPONSIBILITIES 4Head ...
python
# Copyright 2015 Tesora 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 a...
python
from reading import Maze, MazeReader class Node(object): """Nodes for evolving in graph.""" def __init__(self, maze, x, y, parent=None): """Initialize node. Keep maze, parent, and position.""" self.maze = maze self.x = x self.y = y self.parent = parent self.up = ...
python
import pyps from sys import argv if len(argv) == 1: # this source include a main() with a call to foo() ; but foo() isn't defined ! w=pyps.workspace("broker01.c") # We give a method to resolve missing module (here foo()) w.props.preprocessor_missing_file_handling="external_resolver" w.props.pre...
python
from typing import Any, Dict, Tuple from dateutil.parser import parse from great_expectations.execution_engine import PandasExecutionEngine from great_expectations.execution_engine.execution_engine import ( MetricDomainTypes, MetricPartialFunctionTypes, ) from great_expectations.expectations.metrics.map_metri...
python
from authlib.common.urls import quote, unquote def escape(s): return quote(s, safe=b'~') def unescape(s): return unquote(s)
python
import json from typing import Optional import pyrebase from .database import Database class FirebaseDatabase(Database): def __init__(self, serialised_config: str): super().__init__() self.config = json.loads(serialised_config) def add_document(self, doc_id: str, doc: dict) -> None: ...
python
from .s3 import *
python
#!/usr/bin/env python3 """ Get jobs from aCT. Returns: 1: No proxy found. 2: One of the elements in job list is not a range. 3: One of the elements in job list is not a valid ID. 5: tmp directory not configured. """ import argparse import sys import shutil import os import logging import act.client...
python
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="Turkish Topic Model", version="0.0.1", author="Ali ÇİMEN, Sevinç GÜLSEÇEN", author_email="cimenwd@gmailcom, gulsecen@istanbul.edu.tr", description="Türkçe metin ön işleme ve konu analizi k...
python
import pandas from sklearn.model_selection import train_test_split def add_series(X, y, name): """Converts list (y) to pd.Series with name (name) then adds it to a dataframe (X)""" X = X.copy() series = pandas.Series(data=y, name=name) X[name] = series return X def data_split(X): """Spl...
python
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models import re class ResCompany(models.Model): _inherit = 'res.company' org_number = fields.Char(compute='_compute_org_number') @api.depends('vat') def _compute_org_num...
python
import numpy as np from ..functions import B_nu, dB_nu_dT from ..integrate import integrate_loglog from ..constants import sigma, k, c def test_b_nu(): nu = np.logspace(-20, 20., 10000) for T in [10, 100, 1000, 10000]: # Compute planck function b = B_nu(nu, T) # Check that the int...
python
"""Myia Pytorch frontend.""" from .pytorch import *
python
""" Dictionary Embedder Class """ import spacy from .base import BaseEmbedder class DictionaryEmbedder(BaseEmbedder): """Base Embedder class extended for implementing text embedders""" def __init__(self, spacy_pkg='en_vectors_web_lg', embedding_length=None): super(DictionaryEmbedder, self).__init__...
python
# -*- coding: utf-8 -*- """Tests for Terminal methods that account for sequences in strings""" # std imports import os import sys import struct import platform import itertools # 3rd party import six import pytest # local from .accessories import TestTerminal, as_subprocess from .conftest import IS_WINDOWS if platf...
python
def get_token(fi='dont.mess.with.me'): with open(fi, 'r') as f: return f.readline().strip() t = get_token()
python
import re from address_extractor import ( unit_type, zipcode, street_direction, street_type, cities, ) class InvalidAddressError(Exception): pass class Address(object): def __init__(self, tokens): self.tokens = tuple(self._clean_tokens(tokens[:11])) self.street_number_ind...
python
import os.path from newsplease.pipeline.pipelines.elements.extracted_information_storage import ExtractedInformationStorage class HtmlFileStorage(ExtractedInformationStorage): """ Handles storage of the file on the local system """ # Save the html and filename to the local storage folder def pro...
python
import json from decimal import Decimal import jwt from django.core import mail from mock import patch from nose.tools import eq_, ok_ from amo import CONTRIB_PENDING, CONTRIB_PURCHASE from amo.tests import TestCase from amo.urlresolvers import reverse from constants.payments import PROVIDER_BANGO from market.models...
python
from matplotlib import pyplot as plt from matplotlib import cm from matplotlib import animation from optimisation import FireflyOptimizer import numpy as np from optimisation import Ackley f_alg = FireflyOptimizer(population_size=10, problem_dim=2, generations=100) func = Ackley(2) N = 100 x = np.linspace(-5, 5, N) ...
python
import socket import pickle import pandas as pd import matplotlib.pyplot as plt def graph_setting(): plt.ion() fig, ax = plt.subplots() return ax def data_get(df, conn, i): data = conn.recv(1024) data = float(pickle.loads(data)) df_temp = pd.DataFrame([[data]], columns=['data'...
python
import re from csv import DictReader, DictWriter from .utils import get_headers class Dataset(object): def __init__(self, key=None, headers=None, data=None): self.headers = headers self.data = data self.key = key def write(self, fd, delim='\t'): writer = DictWriter(fd, self.he...
python
from telnetlib import Telnet from uuid import uuid4 from time import sleep from hashlib import md5 from os import chmod from re import compile as compile_regex from sys import version_info from .abstractremoteshell import AbstractRemoteShell from .shellresult import ShellResult from .streamreader import PrefixedStream...
python
""" 二分探索 <最悪実行時間に関する漸化式> T(n) = | Θ(1) if n = 1 | T(n/2) + c if n > 1 ループの度に検査範囲が半減するので、Θ(lgn)となる。 """ def binary_search(A, v): left = 0 right = len(A) - 1 while left <= right: i = (left + right) // 2 if v < A[i]: right = i - 1 ...
python
# # RawIO # Copyright (c) 2021 Yusuf Olokoba. # from cv2 import findTransformECC, MOTION_TRANSLATION, TERM_CRITERIA_COUNT, TERM_CRITERIA_EPS from numpy import asarray, eye, float32 from PIL import Image from sklearn.feature_extraction.image import extract_patches_2d from typing import Callable def markov_similar...
python
import numpy as np from glob import glob import os from sklearn.model_selection import train_test_split base_path = "/media/ml/data_ml/EEG/deepsleepnet/data_npy" files = glob(os.path.join(base_path, "*.npz")) train_val, test = train_test_split(files, test_size=0.15, random_state=1337) train, val = train_test_split(t...
python
from ..game import Actor def test_id(): actor1 = Actor() actor2 = Actor() assert actor1.id assert actor2.id assert actor1.id != actor2.id def test_add_food(): actor = Actor() assert actor.food == 0 actor.add_food(10) assert actor.food == 10 actor.add_food(5) assert act...
python
import deepmerge import functools import importlib import logging import yaml from inspect import getmembers, isfunction from urllib import parse, request from wcmatch import fnmatch from . import macros, middleware log = logging.getLogger("netbox_rbac") # Collect all public functions from macros. functions = [ ...
python
from django.core.paginator import Paginator from django.shortcuts import redirect, render, get_object_or_404 from comps.models.comp import Comp from comps.models.heat import Heat from comps.models.heatlist_error import Heatlist_Error def delete_heatlist_error(request, error_id): heatlist_error = get_object_or_404...
python
# Generated by Django 3.0.6 on 2020-06-12 16:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('My_Account', '0017_auto_20200612_1522'), ] operations = [ migrations.RenameField( model_name='sharing_image', old_name='Like...
python
import pygame from pygame.locals import * from GUI.Colours import Colours from GUI.Measures import Measures from GUI.Point import Point from GUI.BarPoint import BarPoint from GUI.BearoffPoint import BearoffPoint from GUI.Checker import Checker class GUIBoard: def __init__(self): pass de...
python
from cloud_scanner_azure.config.azure_credential_config import ( AzureCredentialConfig) class AzureResourceServiceConfig: """Configuration required for usage of AzureResourceService.""" def __init__(self, subscription_id, creds: AzureCredentialConfig): self.credentials = creds self.subscr...
python
# -*- coding: utf-8 -*- # Imports import sys,re,os import glob import numpy as n # Script information __author__ = "Sergi Rodà Llordés" __version__ ="1.0" __maintainer__="Sergi Rodà Llordés" __email__="sergi.rodallordes@bsc.es" class pKa: def __init__(self,PDB,Ser_residue): self.__PDB = PDB sel...
python
from rest_framework import serializers from products.models import Product, Category class CategorySerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Category fields = ("id", "name") class ProductSerializer(serializers.ModelSerializer): class M...
python
import datetime import json import discord from discord.ext import commands import requests ''' スプラトゥーン2絡みのコマンド ''' class Splatoon2(commands.Cog, name='スプラトゥーン2'): def __init__(self, bot): self.bot = bot @commands.command(name='バイトシフト') async def say_salmon_schedule(self, ctx):...
python
from django.db import models # Create your models here. from django_countries.fields import CountryField from django.contrib.gis.db import models from django.db.models import Manager as GeoManager class Site(models.Model): id = models.AutoField(primary_key=True) site = models.CharField('Site name', max_lengt...
python
#!/usr/bin/env python # Pull out yearly precipitation # Daryl Herzmann 26 Jul 2004 import pg, dbflib, mx.DateTime, shutil, shapelib from pyIEM import wellknowntext mydb = pg.connect('wepp','iemdb') sts = mx.DateTime.DateTime(2005,3,1) ets = mx.DateTime.DateTime(2005,11,1) interval = mx.DateTime.RelativeDateTime(days=...
python
#!/usr/bin/env python # # Simple websocket server to perform signaling. # import asyncio import binascii import os import websockets clients = {} async def echo(websocket, path): client_id = binascii.hexlify(os.urandom(8)) clients[client_id] = websocket try: async for message in websocket: ...
python
import sys import traceback import logging from glass import http from . import highlight ERROR_TEMPLATE = ''' <title>{code} {title}</title> <h1>{title}</h1> <p>{description}</p> ''' logger = logging.getLogger('glass.app') class HTTPError(Exception): code = 500 description = "Internal Server Error" def ...
python
""" An evolving population of genotypes(Ideally for optimizing network hyperparameters). See genotype constraint docs in spikey/meta/series. Examples -------- .. code-block:: python metagame = EvolveNetwork(GenericLoop(network, game, **params), **metagame_config,) population = Population(metagame, **pop_conf...
python
#!/usr/bin/env python from setuptools import setup, find_packages packages = ['eda.' + p for p in find_packages('eda', exclude=['test', 'test*', '*.t'])] packages.append('eda') #packages=['eda', 'eda.components', 'eda.components.ST', 'eda.circuits'], setup( name='EDA', version='1.0.1', author='Pawe...
python
import gym import retro import os import numpy as np from PIL import Image from gym import spaces from collections import deque import cv2 SCRIPT_DIR = os.getcwd() #os.path.dirname(os.path.abspath(__file__)) # Taken from: https://gitlab.cs.duke.edu/mark-nemecek/vel/-/blob/cfa17ddd8c328331076b3992449665ccd2471bd3/vel...
python
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap fig, axes = plt.subplots(2, 1) axes[0].set_title("Hammer projection") map = Basemap(projection='hammer', lon_0 = 10, lat_0 = 50, ax=axes[0]) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral',lake_color='aqua') map.drawcoas...
python
""" Forward-ports of types from Python 2 for use with Python 3: - ``basestring``: equivalent to ``(str, bytes)`` in ``isinstance`` checks - ``dict``: with list-producing .keys() etc. methods - ``str``: bytes-like, but iterating over them doesn't product integers - ``long``: alias of Py3 int with ``L`` suffix in the ``...
python
from pycocotools.coco import COCO import matplotlib.pyplot as plt import cv2 import os import numpy as np import random import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader,Dataset from skimage import io,transform import matplotlib.pyplot as plt import os import torch from ...
python
import LAMMPyS as lp steps = lp.Steps('test.dump') step = steps[-1] atoms = step.atoms
python
def do_training(train, train_labels, test, test_labels, num_classes): #set TensorFlow logging level to INFO tf.logging.set_verbosity(tf.logging.INFO) # Build 2 hidden layer DNN with 10, 10 units respectively. classifier = tf.estimator.DNNClassifier( # Compute feature_columns from dataframe keys...
python
from __future__ import absolute_import import abc class Writer(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def text(self, text): pass @abc.abstractmethod def start(self, name, attributes=None): pass @abc.abstractmethod def end(self, name): p...
python
import utime import machine from machine import Timer, Pin, RTC import time import ntptime import micropython import config import control import mqtt_reporting def set_ntp_time(timer): ntptime.host = "tempus1.gum.gov.pl" for i in range(1,10): try: t = ntptime.time() tm = utime....
python
import pytest from pathlib import Path from yalul.lex.scanners.grouping import GroupingScanner from yalul.lex.token_type import TokenType @pytest.fixture(scope='function') def open_file(request): return open(str(Path.cwd()) + "/tests/lex_examples/" + request.param) class TestShouldLex: def test_when_is_left...
python
{"filter":false,"title":"bot.py","tooltip":"/bot.py","undoManager":{"mark":53,"position":53,"stack":[[{"start":{"row":163,"column":18},"end":{"row":163,"column":35},"action":"remove","lines":["BOT_USERNAME_HERE"],"id":2},{"start":{"row":163,"column":18},"end":{"row":163,"column":19},"action":"insert","lines":["k"]}],[{...
python
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
python
class Solution: def minDeletionSize(self, A: List[str]) -> int: return sum(list(column) != sorted(column) for column in zip(*A))
python
import sys import os import os.path import re import shutil from setuptools import setup from setuptools.command.install_lib import install_lib from setuptools.command.install import install import setuptools.command.bdist_egg import distutils.spawn import subprocess import sys import glob exclude_directories = lambda...
python
from dataclasses import dataclass from bindings.csw.graph_style_type import GraphStyleType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class GraphStyle1(GraphStyleType): """The style descriptor for a graph consisting of a number of features. Describes graph-specific style attributes. """ ...
python
##################################################### ## librealsense streams test ## ##################################################### # This assumes .so file is found on the same directory import pyrealsense2 as rs # Prettier prints for reverse-engineering from pprint import pprint # Get r...
python
# ██████ ██▓ ▄▄▄ ██▒ █▓ ██▓ ▄████▄ ██▓███ ██▓▒██ ██▒▓█████ ██▓ # ▒██ ▒ ▓██▒ ▒████▄ ▓██░ █▒▓██▒▒██▀ ▀█ ▓██░ ██▒▓██▒▒▒ █ █ ▒░▓█ ▀ ▓██▒ # ░ ▓██▄ ▒██░ ▒██ ▀█▄▓██ █▒░▒██▒▒▓█ ▄ ▓██░ ██▓▒▒██▒░░ █ ░▒███ ▒██░ # ▒ ██▒▒██░ ░██▄▄▄▄██▒██ █░░░██░▒▓▓▄ ▄██▒ ▒██▄█▓...
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/worker_service.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.prot...
python
def validate_cell(cell: tuple) -> tuple: x, y = cell if x == 6: x = 0 elif x == -1: x = 5 if y == 6: y = 0 elif y == -1: y = 5 return x, y def get_cell(cell: tuple, field: list) -> str: row, col = cell return field[row][col] def set_cell(cell: tuple, f...
python
# nukedatastore tests import pytest import datetime from nukedatastore import NukeDataStore, NukeDataStoreError def test_datastore_crud(datastore): datastore['project_data'] = {'id': 1234, 'name': 'project name'} assert len(datastore.list()) == 1 assert datastore.list()[0] == 'project_data' assert da...
python
# Copyright (c) 2020 Graphcore Ltd. # 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 appl...
python
import torch import warprnnt_pytorch as warp_rnnt from torch.autograd import Function from torch.nn import Module from .warp_rnnt import * __all__ = ['rnnt_loss', 'RNNTLoss'] class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, reduction): """ acts:...
python
from utils import color from browser import help import random def get(cmds, typ, add_attr=None): ''' USE: error.get(cmds, type, [optional:add_attr]) where add_attr must be < 3 Description: Returns a correctly colored message according to declared "typ" ''' #---------------------------------------------------...
python
from brownie import accounts, PassiveStrategy from brownie.network.gas.strategies import ExponentialScalingStrategy import os STRATEGIES = [ # "0x40C36799490042b31Efc4D3A7F8BDe5D3cB03526", # V0 ETH/USDT # "0xA6803E6164EE978d8C511AfB23BA49AE0ae0C1C3", # old V1 ETH/USDC # "0x5503bB32a0E37A1F0B8F8F...
python
from typing import Any import pandas as pd from anubis.models import Submission, Assignment from anubis.utils.cache import cache def get_submissions(course_id: str) -> pd.DataFrame: """ Get all submissions from visible assignments, and put them in a dataframe :return: """ # Get the submission s...
python
# jsb/socklib/partyline.py # # """ provide partyline functionality .. manage dcc sockets. """ __copyright__ = 'this file is in the public domain' __author__ = 'Aim' ## jsb imports from jsb.lib.fleet import getfleet from jsb.utils.exception import handle_exception from jsb.lib.threads import start_new_thread from j...
python
from __future__ import unicode_literals from builtins import str import six @six.python_2_unicode_compatible class TokenSet: """ A token set is used to store the unique list of all tokens within an index. Token sets are also used to represent an incoming query to the index, this query token set and ...
python
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021 # by the softwar...
python