content stringlengths 5 1.05M |
|---|
#
# PySNMP MIB module CISCO-SECY-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SECY-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:11:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import Models.layers as L
from Backbone import *
torch.set_default_tensor_type(torch.cuda.FloatTensor)
class PANetResNet34(nn.Module):
def __init__(self, pretrained=True, **kwargs):
super().__init__()
self.encoder = resnet34(pr... |
class Solution:
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
prefix = []
for idx, val in enumerate(A):
if idx == 0:
prefix.append(val)
else:
prefix.append(val + (prefix[-1] << 1))
res = []
for v in prefix:
r... |
from flask import Flask, flash, render_template, request, redirect, url_for, abort, session, escape, make_response, send_from_directory #el modulo de Flask
import os, random
app=Flask(__name__) #la aplicación
app.secret_key="key" #un código secreto, para realizar peticiones GET, POST
@app.route("/")
def Index():
re... |
"""Sorts GO IDs or user-provided sections containing GO IDs."""
__copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang, All rights reserved."
__author__ = "DV Klopfenstein"
import sys
import collections as cx
from goatools.wr_tbl import prt_txt
from goatools.grouper.sorter_nts import SorterNts
from goatool... |
# Copyright 2013-2019 CERN for the benefit of the ATLAS collaboration.
#
# 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... |
#!/usr/bin/env python
# Copyright 2019 IBM Corporation All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
import os
from setuptools import setup, find_packages
desc = 'Broker to invoke the DEMO APIs'
# from pip.req import parse_requirements
# from pip.download import PipSession
# install_reqs = parse_requi... |
import asyncio
import discord
import logging
import datetime
import time
from typing import Union, Optional, Iterable
from .. import DATABASE, CRYPTO, CONFIG
from ..types import EthereumAddress, TxHash
__all__: tuple = ('Airdrop',)
logger: logging.Logger = logging.getLogger('airdrops')
class Airdrop:
__slots__: ... |
import pytest
from titlecase import title_case
def test_empty_string():
assert title_case('') == ''
def test_lowercase_word():
assert title_case('semaphore') == 'Semaphore'
def test_uppercase_word():
assert title_case('CAMBRIDGE') == 'Cambridge'
def test_lowercase_sentence():
assert title_case(... |
"""
Classes from the 'UIKitServices' framework.
"""
try:
from rubicon.objc import ObjCClass
except ValueError:
def ObjCClass(name):
return None
def _Class(name):
try:
return ObjCClass(name)
except NameError:
return None
UISApplicationSupportService = _Class("UISApplicationS... |
import base64
import json
import os
import time
import logger
from lib.api.misc import (
InternalException, api_commands, dict_key_checker, json_parser, dict_list_to_list_in_tuple, Null
)
from lib.map_settings.map_settings import make_map_settings
from owner import Owner
from utils import file_to_base64, pretty_ti... |
# This file is part of dwinelle-tools.
# dwinelle-tools 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.
# dwinelle-tools is distribut... |
import pytest
from dagster.core.storage.pipeline_run import PipelineRunStatus
from dagster_graphql import DagsterGraphQLClientError
from .conftest import MockClient, python_client_test_suite
@python_client_test_suite
def test_get_run_status_success(mock_client: MockClient):
expected_result = PipelineRunStatus.SU... |
import tensorflow as tf
import matplotlib.pyplot as plt
from models import *
from ExerciseThree import draw_grouped_bar_graph
import time
IMG_AMT = 3
m_arr = [50, 100, 300, 500]
ITER_AMT = 50
def q12(x_arr, y_arr) -> None:
"""
Uses pyplot to show images of numbers with labels 0 and 1
:param... |
#
# PySNMP MIB module HH3C-NAT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-NAT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:15:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
#!/usr/bin/env python3
from augur.utils import read_node_data
import hdbscan
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, MDS
from sklearn.metrics import confusion_matrix, matthews_corrcoef
from skle... |
import re
regex = r'[Hh][Ii]\s[^Dd]'
for _ in range(int(input())):
s = input()
if re.match(regex, s):
print(s)
|
# Copyright 2014 ETH Zurich
#
# 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, sof... |
# Licensed to the LF AI & Data foundation under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this fil... |
#!/usr/bin/python3
"""
Part of RedELK
This check queries IBM X-Force API given a list of md5 hashes.
Authors:
- Outflank B.V. / Mark Bergman (@xychix)
- Lorenzo Bernardi (@fastlorenzo)
"""
import logging
from datetime import datetime
import requests
from modules.helpers import get_value
# Rate limiting:
# Free Tier... |
from pyramid.config import Configurator
from pyramid.response import Response
def test_view(request):
return Response('Hello World')
def test_app(global_config, **settings):
config = Configurator(settings=settings)
config.include('tomb_csrf')
# Safe routes
# "GET", "HEAD", "OPTIONS", "TRACE"
... |
import unittest
from camera_trap_classifier.data.importer import DatasetImporter
class ImportFromJsonTester(unittest.TestCase):
""" Test Import from Json """
def setUp(self):
path = './test/test_files/json_data_file.json'
source_type = 'json'
params = {'path': path}
self.impor... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
import shutil
# 当前目录
current_dir = os.path.dirname(__file__)
zh_cn_dir = os.path.join(current_dir, "zh-cn")
en_dir = os.path.join(current_dir, "en")
zh_hant_dir = os.path.join(current_dir, "zh-hant")
def findAllFile(base):
for root, ds, fs in os.w... |
height = int(input())
num = 1
for i in range(1, height + 1):
for j in range(1, height - i + 2):
if(i == 1 or j == 1 or j == height - i + 1):
if(num <= 9):
print("",num,end=" ")
else :
print(num,end=" ")
num += 1
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='recipes.index'),
url(r'^create/$', views.create, name='recipes.create'),
url(r'^(?P<pk>[0-9a-z-]+)/$', views.detail, name='recipes.detail')
]
|
import smart_imports
smart_imports.all()
class WordAdmin(django_admin.ModelAdmin):
list_display = ('id', 'type', 'normal_form', 'state', 'created_at', 'updated_at')
list_filter = ('type', 'state',)
class TemplateAdmin(django_admin.ModelAdmin):
list_display = ('id', 'key', 'state', 'author', 'raw_templ... |
# coding: utf-8
import util
class Base(object):
@classmethod
def retrieve_one_by(cls, name, value):
return cls.query(getattr(cls, name) == value).get()
@classmethod
def get_dbs(cls, query=None, order=None, limit=None, cursor=None, **kwgs):
return util.retrieve_dbs(
query or cls.query(),
... |
import os
import requests
import random
from urllib import quote
from flask import Flask, jsonify
import search
from meme_query import meme_query
from meme_sources import KnowYourMeme
app = Flask(__name__)
WIT_URL = "https://api.wit.ai/message?v=20141116&q="
ses = requests.Session()
ses.headers.update({'Authorizatio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""ModernPortfolio
Summary:
Collection of utilities for modern portfolio analysis.
For further documentation please refer to
<https://www.field-theory.org/posts/mathematics-of-investing.html>
Copyright:
(c) since 2008 by Dr. Wolfram Schroers <wolfram.sc... |
from __future__ import absolute_import
from sentry.models import (
Commit,
CommitAuthor,
Environment,
EnvironmentProject,
EventAttachment,
File,
Group,
GroupAssignee,
GroupMeta,
GroupResolution,
Project,
Release,
ReleaseCommit,
Repository,
ScheduledDeletion,
... |
/home/oseiasbeu/anaconda3/lib/python3.7/copyreg.py |
from typing import Tuple
from .IAbortable import IAbortable
class IFlatField(IAbortable):
"""The module performs flat-fielding."""
__module__ = 'pyobs.interfaces'
def flat_field(self, filter_name: str, count: int = 20, binning: int = 1, *args, **kwargs) -> Tuple[int, float]:
"""Do a series of fl... |
# Generated by Django 4.0.4 on 2022-04-19 09:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('UI', '0005_remove_profile_username'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='language',... |
import sys
sys.path.append('../')
from generator.savp_generator import video_generator, discriminator_loader, generator_loader, encoder_loader
from generator.savp_generator import discriminator_data, generator_data, encoder_data
from models.savp_models import trial_predictor, encoder, generator, build_graph
from model... |
# -*- coding: utf-8 -*-
import numpy as np
from vispy.scene.visuals import Markers
from vispy.testing import (requires_application, TestingCanvas,
run_tests_if_main)
from vispy.testing.image_tester import assert_image_approved
@requires_application()
def test_markers():
"""Test basic ma... |
def get_square_size(square):
return (2 * square - 1) + 4
with open('resources/day3', 'rt') as f:
number = int(f.readline())
found_square = False
squares = list()
square = 1
previous = 1
squares.append({'min': previous, 'max': previous, 'size': 1, 'square': square})
while found_square ... |
'''
Write a Python program to count number of zeros and ones in
the binary representation of a given integer.
Original number: 12
Number of ones and zeros in the binary representation of the said
number: Number of zeros: 2, Number of ones: 2
Original number: 1234
Number of ones and zeros in the binary representation o... |
# org/python/pypi/myproject/eggs/eggs.py
print(__name__)
|
# encoding: utf8
from __future__ import unicode_literals
from spacy.symbols import ORTH, LEMMA, NORM
_exc = {}
_abbrev_exc = [
# Weekdays abbreviations
{ORTH: "пoн", LEMMA: "понедељак", NORM: "понедељак"},
{ORTH: "уто", LEMMA: "уторак", NORM: "уторак"},
{ORTH: "сре", LEMMA: "среда", NORM: "среда"},
... |
arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
# The subject should be regular, with all rows the same length
print [[r[col] for r in arr] for col in range(len(arr[0]))]
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
|
from BaseballSimulator.Simulator import *
from BaseballSimulator.Pitchers import *
from BaseballSimulator.Plotter import *
import plotly.graph_objs as go
import pytest
class Approx(object):
def __init__(self,val):
self._val = val
self._epsilon = 0.01
def epsilon(self,epsilon):
self._epsilon = epsilon... |
from dtc.enums.message_types import MessageTypes
from lib.base_message_type import BaseMessageType
class Heartbeat(BaseMessageType):
def __init__(self,
num_dropped_messages=None,
current_date_time=None):
self.Type = MessageTypes.HEARTBEAT
self.NumDroppedMessages ... |
# pylint: disable=invalid-name, too-few-public-methods
"""
sputnikmusic scrapers.
"""
import requests
from bs4 import BeautifulSoup
from best_new_music_digest.scrapers.base import Scraper
class AlbumScraper(Scraper):
"""
sputnikmusic album scraper.
"""
__BASE_URL = "https://www.sputnikmusic.com"
... |
######################################################################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
"""
==================================
Sensitivity map of SSP projections
==================================
This example shows the sources that have a forward field
similar to the first SSP vector correcting for ECG.
"""
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause... |
# Name: readExchangeRatesGemini.py
# Author: Matt Nutsch
# Date: 1-19-2018
# Last Edited: 1-27-2018
# Description: This script reads cryptocurrency exchange rate information from the exchange Gemini.
#examples of calling the functions
#print "Reading the exchange rates from the Gemini exchange."
#print "The BT... |
#
#
# =================================================================
# =================================================================
from __future__ import print_function
import logging
import paramiko
import os
import errno
try:
from scp import SCPClient
except ImportError:
scp_installed = False
else... |
def getInvCount(arr, n):
inv_count = 0
for i in range(n - 1):
for j in range(i+1, n):
if arr[i] > arr[j]:
inv_count = inv_count + 1
return inv_count
state = 0
batch_count = 0
batches = []
temp_array = []
with open('./mylogs_clean.log') as fp:
#with open('./test_log.txt') as fp:
for l... |
"""
In this module:
spectrogram()
stft()
test_stft()
STFT class (under development)
"""
# ========================================================================== #
# ========================================================================== #
# This section is to improve python compataibilty betwe... |
#!/usr/bin/env python3
import sys
input_offline=open('DeadROC_offline.txt','r')
input_diff = open('DeadROC_Diff.txt','r')
output = open('MaskedROC_sum.txt','w')
offline =[]
diff = []
for line in input_offline:
offline.append(str(line.strip())+' power\n')
for line in input_diff:
diff.append(str(line.st... |
import types
from datetime import datetime
from struct import calcsize, unpack_from, pack
from .message import Message, MessageType
class _Reader(object):
@classmethod
def read(cls, stream):
""" 读取消息数据 """
def unpack_from_wrap(fmt, offset):
return unpack_from('<' + fmt, stream, o... |
from utils import *
from estimator import Estimator
class EstimatorAdaptative(Estimator):
"""Adaptative classifier"""
def __init__(self, X_res=None, y_pred=None, metric='f1', alpha=4, rho=0.5):
"""
Initialization of the classifier
"""
super().__init__(X_res=X_res, y_pred=y_pred... |
import argparse
import os
from pathlib import Path
import gtsfm.utils.logger as logger_utils
from gtsfm.loader.loader_base import LoaderBase
from gtsfm.loader.olsson_loader import OlssonLoader
from gtsfm.runner.gtsfm_runner_base import GtsfmRunnerBase
DATA_ROOT = Path(__file__).resolve().parent.parent.parent / "test... |
from src.classification_scripts.set_classification_globals import _set_globals
setters = _set_globals('../../configs/setters/training_details.txt')
encoder = setters["ENCODER"]._get_encoder_model() |
from os.path import join
import pymongo
from bson.json_util import dumps
astr = "mongodb+srv://data:VuRWQ@networks.wqx1t.mongodb.net"
client = pymongo.MongoClient(astr)
database_names = client.list_database_names()
db = client['networks']
db = client.networks
collection = db['networks']
cur = collection.find({})
def... |
import os
import scipy.io
import numpy as np
from src.datahandler.denoise_dataset import DenoiseDataSet
from . import regist_dataset
@regist_dataset
class SIDD(DenoiseDataSet):
'''
SIDD datatset class using original images.
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **k... |
# cfitsio-specific version update checker
import os
import urllib.request
import tarfile
import copy
from ..plugins import plugin
class plugin(plugin.Plugin):
def __init__(self, params, ref_ver_data, tarball=None):
'''Download and extract key files from source tarball.
Read in header file.
... |
################# runScripts.py ##################
#
# Contains functions for automating several ArcGIS functions during the development of a Land Use Regression model.
# Functions include generating a series of buffers around points in a shapefile, determining polyline length within each unique buffer,
# and determin... |
from grille import TypeBateau, LONGUEUR_BATEAUX, Grille
from typing import List
from collections import Counter
def nb_facons_de_placer_un_bateau(type_: TypeBateau, n: int = 10, m: int = 10) -> int:
length = LONGUEUR_BATEAUX[type_]
if n < 0 or m < 0:
return 0
if n < length and m < length:
... |
"""Arguments parser."""
import argparse
import datetime
import getpass
import json
import os
import random
import subprocess
import torch
def get_arguments():
parser = argparse.ArgumentParser()
# Dataset
parser.add_argument('--dataset', default='celebsmall')
parser.add_argument('--imageSize', type=i... |
from functools import partial
import numpy as np
import jax
import jax.numpy as jnp
import jax_vumps.jax_backend.arnoldi as arnoldi
def gmres_m(A_mv, A_args, b, x0, n_kry=20, max_restarts=None, tol=1E-6,
M=None, verbose=False, A_norm=None):
"""
Solve A x = b for x using the restarted GMRES meth... |
from imgaug.augmentables.segmaps import SegmentationMapsOnImage
import imgaug.augmenters as iaa
import skimage.external.tifffile
import skimage.io
import numpy as np
import shutil
import os
from utils.logger import ProgressLogger
class ImageSet:
def __init__(self, path, augmented=False):
self.root = path... |
"""
dumptool.py
Contains logic behind fetching docs from database
"""
import math
import shutil
from gevent.pool import Pool
from .utils import find_package_date
class OCDSPacker(object):
"""
Main class
Args:
storage: releases storage from ocdsapi
backend: backend adapter for storing rele... |
from django.urls import path
from estoque.core import views as v
app_name = 'core'
urlpatterns = [
path('', v.index, name='index'),
] |
from yolov3.models import *
from yolov3.utils.simple_dataset import *
from yolov3.utils.utils import *
import torch
def detect(image_tensor,model,device):
"""
This is the yoloV3 detector implementation, borrowed directly from the yolov3 github repo with modifications then done by Ian .
This function ... |
# Program to check whether given numbers in a range is prime or not
# lw is to input the lower limit of range
# uw is to input the upper limit of range
lw=input("Enter the Lower Bound: ")
uw=input("Enter the Upper Bound: ")
# for loop to check each number not in the range
for num in range(lw,uw+1):
# checks whether nu... |
import matplotlib.pyplot as plt
import numpy
# Specify the time vector
tn = numpy.linspace(-5, 0, 100)
tp = numpy.linspace(0, +5, 100)
# The method that will handle plotting the specified derivatives of the given polynomials
def plot(p, s, derivative, filename):
# Compute the derivatives of the polynomials
dp... |
import datetime
def getcurrentdate():
now = datetime.datetime.now()
return now.strftime("%Y%m%d")
|
import concurrent.futures
import copy
import json
import mimetypes
import os
import re
import shutil
import tempfile
import time
import uuid
from urllib.parse import urljoin
from urllib.parse import urlparse
from urllib.request import url2pathname
import chardet
import requests
import selenium.webdriver.support.ui as ... |
from random import randint, sample
from batchedmoments import BatchedMoments
def test_axis_shape_None():
bm = BatchedMoments(axis=None, shape=None)
assert bm._initialized is False # first update call will initialize
assert bm.shape is None # moments shape is None
assert bm.axis is None # axis shap... |
def spam():
"""Spam function.
Returns
-------
str
Returns the string 'spam'.
"""
return "spam"
|
# https://docs.github.com/en/developers/webhooks-and-events/events/github-event-types
class GitHub_EventType:
CommitCommentEvent = 'CommitCommentEvent'
CreateEvent = 'CreateEvent'
DeleteEvent = 'DeleteEvent'
ForkEvent = 'ForkEvent'
GollumEvent = 'GollumEvent'
IssueCommentEvent = 'IssueCommentEve... |
import numpy as np
from PIL import Image, ImageColor
from pathlib import Path
import torch
import torch.nn.functional as F
from torch import tensor
from torchvision import transforms
from torchvision import datasets
from torch.utils.data import Dataset, DataLoader, TensorDataset
import glob
import os
import pandas as... |
class Config:
def __init__(self, **entries):
self.__dict__.update(entries)
def to_dict(self):
return self.__dict__ |
r"""
Building molecular Hamiltonians
===============================
.. meta::
:property="og:description": Learn how to build electronic Hamiltonians of molecules.
:property="og:image": https://pennylane.ai/qml/_images/water_structure.png
.. related::
tutorial_vqe Variational quantum eigensolv... |
import contextlib
from copy import deepcopy
from functools import partial
from itertools import cycle
from statistics import median
from typing import Tuple, Mapping, Callable, Optional
import torch
from homura import optim, trainers, reporters, callbacks, Map, get_args, lr_scheduler
from homura.liblog import get_logg... |
"""Provide configuration end points for Automations."""
from collections import OrderedDict
import uuid
from homeassistant.components.automation import DOMAIN, PLATFORM_SCHEMA
from homeassistant.const import CONF_ID, SERVICE_RELOAD
import homeassistant.helpers.config_validation as cv
from . import EditIdBasedConfigVi... |
# Copyright 2020 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... |
# -*- coding: utf-8 -*-
"""Module contains methods for picking through Regobs and Varsom data. It might be to randomly pick
out winners of a competition or count numbers for a report benchmark.
"""
from varsomdata import getobservations as go
from varsomdata import getmisc as gm
from varsomdata import getvarsompickles... |
# -----------------------------------------------------
# File: buttons.py
# Author: Tanner L
# Date: 10/10/19
# Desc: Handles button presses
# -----------------------------------------------------
import logging
import smbus # i2c smbus for pic communication
from gpiozero import Button, LED, TonalBuzzer # impor... |
from typing import Text
import pygame
from pygame import draw
from pygame.constants import GL_RED_SIZE
from pygame.draw import rect
from pygame.rect import Rect
# use RGB only!
# text alling_x has left ,right and middle as options
# text alling_y has up, down and middle
# middle is default for both
class ... |
import pandas as pd
TITLE_NAME = "Raw Data (App)"
SOURCE_NAME = "raw_data_app"
LABELS = ["Team Number",
"Alliance",
"Match Number",
"Auto Line",
"Exchange Auto Successes",
"Switch Auto Successes",
"Scale Auto Successes",
"Exchange Auto Attempts",
... |
# -*- coding: utf-8 -*-
"""
Handle the Command Line Interface
"""
import argparse
import functools
import logging
import sys
from pathlib import Path
from requests import ConnectionError
from typing import List
from syncgitlab2msproject import Issue, MSProject, __version__
__author__ = "Carli Freudenberg"
__copyrigh... |
import os
import multiprocessing
import struct
import ConfigParser
import neuron
from tornado import gen
from log import *
from devices import *
from neuron import WiFiAdapter
try:
import unipig
from apigpio import I2cBus, GpioBus
except:
pass
up_globals = {
'version': "UniPi 1.0",
'devices': {
... |
import torch
from plan2scene.texture_gen.custom_ops.noise import Noise
from plan2scene.texture_gen.nets.neural_texture.encoder import ResNet
from plan2scene.texture_gen.nets.neural_texture.mlp import MLP
import plan2scene.texture_gen.utils.neural_texture_helper as utils_nt
from torch import nn
class TextureGen(nn.Mo... |
from Environment import environment
from DoubleDQN import Qnetwork
import numpy as np
import tensorflow as tf
import pandas as pd
import time as tm
from haversine import haversine
#import random
from random import sample
import math
# action is in the set of (0,1,2,3) = (north, east, south, west)
# s1, r, d = e... |
"""Some essential object of interpreter"""
import collections
class Frame(object):
"""
The frame object that deals with function calls
"""
def __init__(self, f_code, f_globals, f_locals, f_back):
self.f_code = f_code
self.f_globals = f_globals
self.f_locals = f_locals
... |
import urllib.parse
import pytest
@pytest.fixture
def client_config(client_config):
client_config["rest_cherrypy"]["webhook_disable_auth"] = True
return client_config
async def test_webhook_noauth(http_client):
"""
Auth can be disabled for requests to the webhook URL
See the above ``client_con... |
from typing import Iterator
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import IterableDataset, DataLoader
from torch.utils.data.dataset import T_co
class TextDatasetIterable(IterableDataset):
def __getitem__(self, index) -> T_co:
pass
def __init__(self, src_file, ... |
"""Test create.utils.batch.
"""
import unittest
import os
import numpy
from geomodelgrids.create.utils import batch
class TestBatchGenerator2D(unittest.TestCase):
def test_nomax(self):
NUM_X = 30
NUM_Y = 40
BATCHES = [
[(0, 30), (0, 40)],
]
genbatch = batch.... |
from snowddl.blueprint import ViewBlueprint
from snowddl.error import SnowDDLExecuteError
from snowddl.resolver.abc_schema_object_resolver import AbstractSchemaObjectResolver, ResolveResult, ObjectType
class ViewResolver(AbstractSchemaObjectResolver):
def get_object_type(self) -> ObjectType:
return Objec... |
import torch
def init_weight(m, init_type='normal', init_gain=0.02):
classname = m.__class__.__name__
if classname in ('Conv2d', 'ConvTranspose2d', 'Linear'):
if init_type == 'normal':
torch.nn.init.normal_(m.weight.data, 0.0, init_gain)
elif init_type == 'xavier':
torc... |
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="epayco-django",
version="0.0.12",
include_package_data=True,
license="MIT",
description="A django integration for ePayco's gateway.",
long_description=... |
# Pipeline for analysing data from the GMRT and the uGMRT.
# Combination of pipelines developed independently by Ruta and Ishwar.
#
# Date: 29 May 2019
# README : Please read the following instructions to run this pipeline on your data
# Files and paths required
# 0. This script should be placed and executed in the dir... |
import os
import sys
sys.path.append(os.getcwd())
from codegen.codegen import generate
from codegen.load_config import load_config
generate(load_config(1))
|
import argparse
import os
import sys
source_files = {'.py', '.cpp', '.h'}
DECLARATIONS_PATH = 'torch/lib/tmp_install/share/ATen/Declarations.yaml'
# TODO: This is a little inaccurate, because it will also pick
# up setup_helper scripts which don't affect code generation
def all_generator_source():
r = []
fo... |
my_list = ["tomato", "soup", "rice", "potato", "beer"]
print(list(filter(lambda item: item.startswith("t"), my_list)))
|
#! /usr/bin/env python3
"""
WalArt.sci
=======================
wicknec's library for scientific data processing in python
"""
# NOTE: the actual command documentation is collected from docstrings of the
# commands and is appended to __doc__ after the class has been defined.
"""
Revisions
=================
160202 cre... |
import numpy as np
import litenn as nn
import litenn.core as nc
class BlurPool(nn.Module):
"""
BlurPool operator.
works with any channels tensor.
arguments
kernel_size(3) int
stride(2) int
dilation(1) int
padding(same) 'valid' no paddin... |
from test.unit_tests.providers import common
from test.unit_tests.providers.common import ProviderTestCase
from test.utils import http
from totalimpact.providers.provider import Provider, ProviderItemNotFoundError
import os
from nose.tools import assert_equals, assert_items_equal, raises, nottest
import collections
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.