content
stringlengths
0
894k
type
stringclasses
2 values
import tensorflow as tf import numpy as np from tensorflow import keras # Use simple nearest neighbour upsampling, 9x9, 1x1 and 5x5 convolutional layers. MSE: 0.0028712489 # Described in https://towardsdatascience.com/an-evolution-in-single-image-super-resolution-using-deep-learning-66f0adfb2d6b # Article: https://ar...
python
import logging import os import re from robobrowser import RoboBrowser logger = logging.getLogger(__name__) id_re = re.compile("\(([^)]+)\)") def scrape_snotel_sites(url=None): if not url: url = "http://www.wcc.nrcs.usda.gov/nwcc/yearcount?network=sntl&counttype=statelist&state=" browser = RoboBrowse...
python
import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import scipy.io from torch.utils.data import Dataset import pickle import os import sys # Data Processing def load_file(path_to_file): return np.genfromtxt(path_to_...
python
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Donny You(donnyyou@163.com) # Loss Manager for Object Detection. from __future__ import absolute_import from __future__ import division from __future__ import print_function from loss.modules.det_modules import SSDFocalLoss, SSDMultiBoxLoss from loss.modules.det...
python
a = [] # append element at the end. a.append(2) a.append(3) print(a) # insert at a specific location. a.insert(0, 5) a.insert(10, 5) print(a) # when specified a position not in list, it inserts at the end. a.insert(100, 6) print(a) # Deleting elements from a list. a.remove(5) # removes the first occurence of value pa...
python
from .Ticket import Ticket, StateTicket ################################################################################ ################################################################################ ################################################################################ ###############################...
python
import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth import matplotlib.pyplot as plt from PIL import Image import cv2 from copy import deepcopy # image_path = '/home/kshitij/PycharmProjects/Computer_Vision/Assignment_3/Question_2/iceCream1.jpg' # image_path = '/home/kshitij/PycharmProjects/Comp...
python
import random import networkx as nx import matplotlib.pyplot as plt class graph: __dg = None def __init__(self): #self.__dg = nx.DiGraph() self.__dg = nx.Graph() def add_nodes(self, nodes): for i in range(0, len(nodes)): self.__dg.add_node(nodes[i]) def add_edges...
python
# coding: utf-8 """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from alphalogic_api.protocol import rpc_pb2 from alphalogic_api.attributes import Visible, Access from alphalogic_api.multistub import MultiStub from alphalogic_api import utils from alphalogic_api.logger import log from alphalogic_api.u...
python
from unittest.mock import ANY, patch from arcsecond import ArcsecondAPI from click.testing import CliRunner from oort.cli.cli import upload from oort.server.errors import InvalidOrgMembershipOortCloudError, UnknownOrganisationOortCloudError from oort.shared.models import Organisation from tests.utils import ( TEL...
python
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('../../MNIST_data', one_hot=True) import tensorflow as tf x = tf.placeholder(tf.float32,[None,784])
python
from aiogram import types from asyncio import sleep from typing import Union import NekoGram async def default_start_function(message: Union[types.Message, types.CallbackQuery]): neko: NekoGram.Neko = message.conf['neko'] if not await neko.storage.check_user_exists(user_id=message.from_user.id): lang ...
python
import os import pandas as pd import nltk import re import spacy from sklearn.feature_extraction.text import CountVectorizer from data_module.corpus import data_operations as do from data_module.corpus.clean import remove_single_quotes def get_top_n_words(corpus, n=None): """ List the top n words in a vocabul...
python
import unittest from config import TEST_DB_PATH from repositories.item_repository import ItemRepository from utilities.csv_utilities import clear_csv, read_csv class TestItemRepository(unittest.TestCase): def setUp(self): clear_csv(TEST_DB_PATH) self.item_repo = ItemRepository(TEST_DB_PATH) ...
python
#!/usr/bin/env python3 import sys import subprocess import requests from datetime import datetime def main(args): if len(args) < 2: print('usage: sync-cloudflare.py [output path]') return output = args[1] now = datetime.utcnow().isoformat() ips = [] resp = requests.get('https://...
python
import os import sys from urllib2 import urlopen import json import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open(r'config.txt')) apikey = config.get('Sonarr Config', 'apikey') host = config.get('Sonarr Config', 'host') port = config.get('Sonarr Config', 'port') url = 'http://'+host+':'+port+'...
python
#!/usr/bin/env python from kivy.app import App from kivy.animation import Animation from kivy.uix.floatlayout import FloatLayout from kivy.graphics import Line from kivy.gesture import Gesture, GestureDatabase from kivy.vector import Vector from kivy.properties import NumericProperty,BooleanProperty from museol...
python
import numpy as np from sympy import simplify, integrate, zeros, S, Matrix, symbols, pi, cos, sin from .funcs_aproximacion import producto_asecas def producto_escalar_trigono(f, g, var=symbols('x'), a=-pi, b=pi, I=None, numeric=False): """Aplica el producto escalar <f,g> = 1/(2pi) ∫_[-pi]^[pi] f.g Args: ...
python
from ..util.conversion import physical_compatible from ..util import config, conversion class df(object): """Top-level class for DF classes""" def __init__(self,ro=None,vo=None): """ NAME: __init__ PURPOSE: initialize a DF object INPUT: ro= (None)...
python
#!/usr/bin/python3 # Copyright (c) 2021 by Fred Morris Tacoma WA # # 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 appli...
python
from enum import Enum class Emoji(Enum): PLAY = "*play*" FACE_HEARTS = "<3" FACE_TONGUE = ":P" FACE_SMILE = ":D" FACE_CRY_LAUGH = "xD" FACE_HALO = "=D" FACE_NERDY = "*nerdy*" FACE_TEAR = "*cry*" FACE_SAD = ":(" FACE_ZZZ = "*sleep*" FACE_ROLLING_EYES = "*rolling-eyes*" F...
python
"""Dependency injector resource provider unit tests.""" import asyncio import unittest2 as unittest from dependency_injector import containers, providers, resources, errors # Runtime import to get asyncutils module import os _TOP_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), ...
python
# coding: utf-8 # This block of code fetches the data, and defines a function that # splits the data into test/train, and into batches. # Note that this function will only download the data once. Subsequent # calls will load the data from the hard drive def MNIST_Loaders(train_batch_size, test_batch_size=None): i...
python
import sqlite3 # Configure database connection = sqlite3.connect('map.db') # Cursor for execute DB command c = connection.cursor() # CREATE TABLE # c.execute("""CREATE TABLE map ( # id integer, # lat real, # lng real, # comment text # )""") # INSERT VALU...
python
from .models import Language from rest_framework import serializers class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ('id', 'name', 'paradigm')
python
""" Playground for downloading GenBank files, wrapping in bowtie2, sCLIP/SOR prep """ from Bio import Entrez import csv import re import requests import subprocess import os from Bio import SeqIO import shutil from urllib.error import HTTPError import time import inv_config as config # TODO Remove .gbk files at the e...
python
from __future__ import division import os import math import scipy.misc import numpy as np import argparse from glob import glob from pose_evaluation_utils import mat2euler, dump_pose_seq_TUM parser = argparse.ArgumentParser() parser.add_argument("--dataset_dir", type=str, help="path to kitti odometry dataset") parser...
python
import numpy as np import matplotlib.pyplot as plt with open('timings.txt','r') as inp: inp.readline() times = np.loadtxt(inp, delimiter=',') print(times.shape) selected = list([0,1,3,8,13,18]) # plt.plot((2+np.array(range(19))),times[:,0],'r^-',label="Best first search algorithm") # plt.plot((2+np.array(range(1...
python
from pessoa import Pessoa class Aluno(Pessoa): def __init__(self, rm, turma_id, rg, nome): super().__init__(rg, nome) self._rm = rm self._turma_id = turma_id self._notas = [] def media(self): if len(self._notas) > 0: return sum(self._notas)/len(self._notas) ...
python
import numpy as np import torch class FeaturesLinear(torch.nn.Module): def __init__(self, field_dims, output_dim=1): super().__init__() self.fc = torch.nn.Embedding(sum(field_dims), output_dim) self.bias = torch.nn.Parameter(torch.zeros((output_dim,))) self.offsets = np.array((0, ...
python
# Copyright 2013 - Red Hat, 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 or agreed to in writi...
python
import fileReader import inputHandler import fileHandler import os inputStuff = inputHandler.inputHandler() fileStuff = fileHandler.FileHandler() def getMode(): mode = inputStuff.determineAutoOrManual() if mode == 'man': getFileInfo() loadAudioFile() elif mode =='auto': fileProcesser = fileReader.FileReader()...
python
from pybullet_utils import bullet_client import math class QuadrupedPoseInterpolator(object): def __init__(self): pass def ComputeLinVel(self,posStart, posEnd, deltaTime): vel = [(posEnd[0]-posStart[0])/deltaTime,(posEnd[1]-posStart[1])/deltaTime,(posEnd[2]-posStart[2])/deltaTime] return vel...
python
from typing import List from extraction.event_schema import EventSchema from extraction.predict_parser.predict_parser import Metric from extraction.predict_parser.tree_predict_parser import TreePredictParser decoding_format_dict = { 'tree': TreePredictParser, 'treespan': TreePredictParser, } def get_predict...
python
import os filename = os.path.dirname(__file__) + "\\input" with open(filename) as file: x = [] start = 0 for line in file: text = list(line.rstrip()) if start == 0: x = [0] * len(text) i = 0 for t in text: if t == '1': x[i] += 1 ...
python
def solve(input): ans = 0 for g in input.split("\n\n"): b = 0 for c in g: if c.isalpha(): b |= 1 << (ord(c) - ord("a")) ans += bin(b).count("1") return ans
python
# https://www.hackerrank.com/challenges/three-month-preparation-kit-jack-goes-to-rapture/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'getCost' function below. # # The function accepts WEIGHTED_INTEGER_GRAPH g as parameter. # # # For the weighted graph, <name>: # ...
python
from typing import List, Callable, Optional, Dict, Set from tqdm import tqdm from src.data.objects.frame import Frame from src.data.objects.stack import Stack from src.data.readers.annotation_reader import AnnotationLoader class LineModifiedClassifier: def __init__(self, user_ids: Set[int], annotation_loader: A...
python
from scrapy import cmdline name = 'douban_movie_top250' cmd = 'scrapy crawl {}'.format(name) cmdline.execute(cmd.split())
python
#you += hash(pubkey || index) to both the private scalar and public point #<tacotime> [02:35:38] so to get priv_i and pub_i #<tacotime> [02:36:06] priv_i = (priv + hash) mod N #<tacotime> [02:37:17] pub_i = (pub + scalarbasemult(hash)) import MiniNero import PaperWallet sk, vk, pk, pvk, addr, wl, cks = PaperWallet.key...
python
class OperationFailed(Exception): pass class ValidationFailed(Exception): pass
python
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython """ def suma(a: float, b: float) -> float: return a + b def resta(a: float, b: float) -> float: return a - b def multiplicacion(a: float, b: float) -> float: return a * b def division(a: float, b: float) -> float: if b <= 0: ra...
python
class ArtistCollection(): """ Matplotlib collections can't handle Text. This is a barebones collection for text objects that supports removing and making (in)visible """ def __init__(self, artistlist): """ Pass in a list of matplotlib.text.Text objects (or possibly any ...
python
from qemuvolume import QEMUVolume from ..tools import log_check_call class VirtualHardDisk(QEMUVolume): extension = 'vhd' qemu_format = 'vpc' ovf_uri = 'http://go.microsoft.com/fwlink/?LinkId=137171' # Azure requires the image size to be a multiple of 1 MiB. # VHDs are dynamic by default, so we add the option ...
python
import pytest import numpy import os import spacy from spacy.matcher import Matcher from spacy.attrs import ORTH, LOWER, ENT_IOB, ENT_TYPE from spacy.attrs import ORTH, TAG, LOWER, IS_ALPHA, FLAG63 from spacy.symbols import DATE, LOC def test_overlap_issue118(EN): '''Test a bug that arose from having overlapping...
python
# 3rd party imports import stellar_base.utils from stellar_base.exceptions import * from stellar_base.keypair import Keypair from stellar_base.address import Address STELLAR_MEMO_TEXT_MAX_BYTES = 28 def is_address_valid(address): """ Checks if a given Stellar address is valid. It does not check if it exists ...
python
# Copyright 2021 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 to...
python
"""Converts ECMWF levels into heights""" import numpy as np def readLevels(file_name='supra/Supracenter/level_conversion_ECMWF_37.txt', header=2): """ Gets the conversion of heights from a .txt file, for use with convLevels(). Arguments: file_name: [string] name of conversion file, .txt heade...
python
# # Copyright 2018 herd-mdl contributors # # 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 ...
python
import torch.optim import torch.nn as nn class AgentControl: def __init__(self, hyperparameters): self.gamma = hyperparameters['gamma'] self.device = 'cpu'# 'cuda' if torch.cuda.is_available() else 'cpu' self.loss = nn.MSELoss() #Return accumulated discounted estimated reward ...
python
"""Support for TPLink HS100/HS110/HS200 smart switch.""" import logging import time from homeassistant.components.switch import ( ATTR_CURRENT_POWER_W, ATTR_TODAY_ENERGY_KWH, SwitchDevice) from homeassistant.const import ATTR_VOLTAGE import homeassistant.helpers.device_registry as dr from . import CONF_SWITCH, DO...
python
from .Util import *
python
'''This file defines user interfaces to sDNA tools and how to convert inputs to config''' ##This file (and this file only) is released under the MIT license ## ##The MIT License (MIT) ## ##Copyright (c) 2015 Cardiff University ## ##Permission is hereby granted, free of charge, to any person obtaining a copy #...
python
""" This module contains helpers for the XGBoost python wrapper: https://xgboost.readthedocs.io/en/latest/python/index.html The largest part of the module are helper classes which make using a validation set to select the number of trees transparent. """ import logging logger = logging.getLogger(__name__) import jobl...
python
#! /usr/bin/python3.5 # -*- coding: utf-8 -*- import random import numpy as np import matplotlib.pyplot as plt def subdivied(Liste, Size): """ On divise la liste Liste, en : sum from i = 1 to N - Size [x_i,x_i+1,...x_i+Size] """ res = [] # pour chaque éléments de la liste for index, e...
python
# -*- coding: utf-8 -*- """ Created on Sat Nov 2 16:22:45 2019 @author: Soumitra """ import math import numpy as np import numpy.fft as f import matplotlib.pyplot as plt n = np.arange(12); x = ((-1)**n)*(n+1) plt.xlabel('n'); plt.ylabel('x[n]'); plt.title(r'Plot of DT signal x[n]'); plt.stem(n, x);...
python
"""Iterative Compression Module.""" from experiments import RESULTS_DIR, TABLES_DIR from pathlib import Path # Paths IC_DIR = Path(__file__).parent SELF_COMPARISON_DATA_PATH = RESULTS_DIR / 'ic_preprocessing_level.csv' IC_TABLE_FORMAT_STR = 'timeout_{}.tex' IC_TABLES_DIR = TABLES_DIR / 'ic' IC_TABLES_DIR.mkdir(exist...
python
"""Examples showing how one might use the Result portion of this library.""" import typing as t import requests from safetywrap import Result, Ok, Err # ###################################################################### # One: Validation Pipeline # ##############################################################...
python
from django.shortcuts import render, redirect, render_to_response from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.forms.util import ErrorList from django.contrib import auth, messages from django.con...
python
# <auto-generated> # This code was generated by the UnitCodeGenerator tool # # Changes to this file will be lost if the code is regenerated # </auto-generated> def to_u_s_miles_per_gallon(value): return value * 2.35215 def to_miles_per_gallon(value): return value * 2.82481 def to_litres_per100_kilometres(value): ...
python
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. """ from pyramid.compat import itervalues_ from everest.entities.utils import get_root_aggregate from everest.querying.specifications import eq from everest...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import logging import logging.config import os import sys import yaml from datetime import datetime from importlib import import_module from pkgutil import iter_modules from plastron import commands, version from plastron.exceptions import FailureException...
python
alphabet = 'qw2rty534plkjhgfds1zxcvbnm' alpha_dict = {'q':0,'w':1,'2':2,'r':3,'t':4,'y':5,'5':6,'3':7,'4':8,'p':9,'l':10,'k':11,'j':12,'h':13,'g':14,'f':15,'d':16,'s':17,'1':18,'z':19,'x':20,'c':21,'v':22,'b':23,'n':24,'m':25} list_out = open("full_pass_list","w") def reduction(my_letter): while my_letter >= 0: my_...
python
class Node(object): """ Represents a node in the query plan structure. Provides a `parse` function to parse JSON into a heirarchy of nodes. Executors take a plan consisting of nodes and use it to apply the Transformations to the source. """ @classmethod def parse(cls, _dict): raise NotImplemented d...
python
from abc import ABCMeta, abstractmethod from dataclasses import dataclass, field, asdict from datetime import datetime from typing import List @dataclass(frozen=True) class SalaryPayment: basic_payment: int = field(default_factory=int, metadata={"jp": "基本給"}) overtime_fee: int = field(default_factory=int, met...
python
import os def get_ip_name(): return "base_ip" class base_ip: ID = "base" def __init__(self, io_hash): return def matched_id(in_key): return in_key is self.ID def get_rst_case_text(self): return '' def get_dft_case_text(self): return '' def get_pinmux_setting(self): return "" def ge...
python
import requests import conf import urllib2 import xml.etree.ElementTree as ET import io def get_min_temp_phrase_from_values(min_observed, min_forecast): if abs(min_forecast) != 1: degrees_text = "degrees" else: degrees_text = "degree" s = "The temperature tonight will be %s %s, " % (min_fo...
python
from flask import Flask from flask import render_template,redirect,request import pandas as pd import sys import numpy as np import pickle from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression #from sklearn.metrics import mean_squared_log_error from sklearn.linear_model ...
python
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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 ...
python
import os import platform import textwrap from collections import OrderedDict from jinja2 import Template from conans.errors import ConanException from conans.util.files import normalize sh_activate = textwrap.dedent("""\ #!/usr/bin/env sh {%- for it in modified_vars %} export CONAN_OLD_{{it}}="${{it}}"...
python
import logging from copy import copy from inspect import isfunction import ibutsu_server.tasks from flask_testing import TestCase from ibutsu_server import get_app from ibutsu_server.tasks import create_celery_app from ibutsu_server.util import merge_dicts def mock_task(*args, **kwargs): if args and isfunction(a...
python
#!/usr/bin/env python from kivy.app import App from kivy.clock import Clock from kivy.config import Config from kivy.core.window import Window from kivy.properties import (ListProperty, NumericProperty, ObjectProperty, ReferenceList...
python
# -selenium webdriver- from logging import fatal from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium....
python
import argparse import os import numpy as np import scipy.io as sio import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from tqdm import tqdm from net.models import LeNet_5 as LeNet import util os.makedirs('saves', exist_ok=True)...
python
import random import numpy as np import tensorflow as tf import tqdm from pipeline import SEED from pipeline.dataset.gc import get_client random.seed(SEED) TRAIN = tf.estimator.ModeKeys.TRAIN EVAL = tf.estimator.ModeKeys.EVAL PREDICT = tf.estimator.ModeKeys.PREDICT class MNISTDataset: """MNIST dataset.""" ...
python
"""\ Demo app for the ARDrone. This simple application allows to control the drone and see the drone's video stream. Copyright (c) 2011 Bastian Venthur The license and distribution terms for this file may be found in the file LICENSE in this distribution. """ import pygame from pydrone import libardrone if __na...
python
from Parameter import Parameter, registerParameterType from ParameterTree import ParameterTree from ParameterItem import ParameterItem import parameterTypes as types
python
# encoding: utf-8 import uuid import os import random import json from collections import Counter from flask import request, abort, jsonify, g, url_for, current_app, session from flask_restful import Resource, reqparse from flask_socketio import ( emit, disconnect ) from app.ansibles.ansible_task import INVENT...
python
import unittest from random import uniform from pysim import epcstd class TestDataTypes(unittest.TestCase): def test_divide_ratio_encoding(self): self.assertEqual(epcstd.DivideRatio.DR_8.code, "0") self.assertEqual(epcstd.DivideRatio.DR_643.code, "1") def test_divide_ratio_str(self): ...
python
from __future__ import print_function from builtins import str import argparse import os import sys import re from .version import VERSION from .utils import get_local_ip, DelimiterArgParser import atexit def add_parser_args(parser, config_type): # General arguments parser.add_argument( '--trace_gre...
python
"""add column source_file_dir Revision ID: 3880a3a819d5 Revises: 2579e237c51a Create Date: 2019-11-12 16:49:05.040791 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3880a3a819d5' down_revision = '2579e237c51a' branch_labels = None depends_on = None def upgr...
python
from collections import OrderedDict from django.db.models import Count from django.db.models.functions import TruncYear from .models import Reading def annual_reading_counts(kind="all"): """ Returns a list of dicts, one per year of reading. In year order. Each dict is like this (if kind is 'all'): ...
python
import os from CPAC.pipeline import nipype_pipeline_engine as pe import nipype.algorithms.rapidart as ra import nipype.interfaces.fsl as fsl import nipype.interfaces.io as nio import nipype.interfaces.utility as util from .utils import * from CPAC.vmhc import * from nipype.interfaces.afni import preprocess from CPAC.re...
python
##MIT License ## ##Copyright (c) 2019 Jacob Nudel ##Copyright (c) 2019 Yashu Seth ## ##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...
python
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as f from torch.autograd import Variable import os import numpy as np from tqdm import tqdm class ONE_HOT_MLP(nn.Module): def __init__(self, hidden): super(ONE_HOT_MLP, self).__init__() self.cnn ...
python
import os import string from tqdm import tqdm #from google.colab import drive #conda install -c huggingface transformers import matplotlib.pyplot as plt #% matplotlib inline import pandas as pd import seaborn as sns import numpy as np import random import torch from torch.utils.data import Dataset, Data...
python
import json import unittest from mock import Mock, patch import delighted get_headers = { 'Accept': 'application/json', 'Authorization': 'Basic YWJjMTIz', 'User-Agent': "Delighted Python %s" % delighted.__version__ } post_headers = get_headers.copy() post_headers.update({'Content-Type': 'application/jso...
python
#!/usr/bin/env python3 from typing import Any, List import configargparse import paleomix SUPPRESS = configargparse.SUPPRESS class ArgumentDefaultsHelpFormatter(configargparse.ArgumentDefaultsHelpFormatter): """Modified ArgumentDefaultsHelpFormatter that excludes several constants (True, False, None) and us...
python
#!/usr/bin/env nix-shell #!nix-shell -i python -p python3 -I nixpkgs=../../pkgs # SPDX-FileCopyrightText: 2020 Daniel Fullmer and robotnix contributors # SPDX-License-Identifier: MIT import json import os import urllib.request def save(filename, data): open(filename, 'w').write(json.dumps(data, sort_keys=True, in...
python
from .transformer import TransformerXL
python
# encoding: utf-8 from hoopa import const from hoopa.middlewares.stats import StatsMiddleware NAME = "hoopa" # 最大协程数 WORKER_NUMBERS = 1 # 请求间隔, 可以是两个int组成的list,间隔随机取两个数之间的随机浮点数 DOWNLOAD_DELAY = 3 # pending超时时间,超过这个时间,放回waiting PENDING_THRESHOLD = 100 # 任务完成不停止 RUN_FOREVER = False # 队列 # 调度器队列,默认redis, memory, mq QUE...
python
from pathlib import Path SRC = Path(__file__).parent BLD = SRC.parent.joinpath("bld")
python
from collections import Counter class Square(Counter): """Creates a special purpose counter than can store only one value, and wipes itself when zero.""" def __init__(self): """Object should be initialized empty.""" pass def __setitem__(self, key, cnt): """Update the count.""" ...
python
from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View # model from timepredictor.models import PrediccionTiempos, UltimosGps # Create your views here. class MapHandler(View): '''This class manages the map where the bus and stops are shown''' def __init...
python
""" CLI Module. Handles CLI for the Repository Updater """ from os import environ from sys import argv import click import crayons from . import APP_FULL_NAME, APP_VERSION from .github import GitHub from .repository import Repository @click.command() @click.option( "--token", hide_input=True, prompt="G...
python
'''Functions to calculate seismic noise in suspended optics. ''' from __future__ import division import numpy as np from scipy.interpolate import PchipInterpolator as interp1d def seismic_suspension_fitered(sus, in_trans): """Seismic displacement noise for single suspended test mass. :sus: gwinc suspension ...
python
def func(num): return x*3 x = 2 func(x)
python
CHECKPOINT = 'model/checkpoint.bin' MODEL_PATH = 'model/model.bin' input_path = 'input/train.csv' LR = 0.01 scheduler_threshold = 0.001 scheduler_patience = 2 scheduler_decay_factor = 0.5 embed_dims = 128 hidden_dims = 128 num_layers = 1 bidirectional = False dropout = 0.2 out_dims = 128 Batch_Size = 64 Epochs = 100...
python
import pygame # game from cgame import CGame def main(): try: CGame().run() except Exception as e: print(e) if __name__ == '__main__': pygame.init() main()
python