text stringlengths 2 999k |
|---|
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
from functools import wraps
from typing import List, Tuple, Union
from flask import request
from anubis.utils.auth.user import current_user
from anubis.utils.data import verify_data_shape, jsonify
from anubis.utils.exceptions import AuthenticationError
from anubis.utils.http import error_response
def load_from_id(m... |
# Generated by Django 3.0.5 on 2020-04-12 15:39
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
("ppe", "0009_auto_20200412_1517"),
]
operations = [
migrations.CreateModel(
name="Fa... |
import math
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import FC, Embedding
class DeepFM(fluid.dygraph.Layer):
def __init__(self, args):
super(DeepFM, self).__init__()
self.args = args
self.init_value_ = 0.1
self.fm = FM(args)
self.dnn = DNN(args)
def ... |
# Copyright 2018 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 ... |
import collections
import csv
import os
import cf_xarray as cf
import dask
import numpy as np
import xarray as xr
from .calcs import Datasetcalcs, Diffcalcs
def collect_datasets(data_type, varnames, list_of_ds, labels, **kwargs):
"""
Concatonate several different xarray datasets across a new
"collection... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from collections import namedtuple
from typing import Any, Optional
from easydict import EasyDict
import copy
import numpy as np
import torch
from ding.envs import BaseEnv, BaseEnvTimestep, BaseEnvInfo
from ding.envs.common.env_element import EnvElement, EnvElementInfo
from ding.utils import ENV_REGISTRY
from ding.tor... |
import os
from unittest import TestCase
from musicscore.musictree.treechord import TreeChord
path = str(os.path.abspath(__file__).split('.')[0])
class Test(TestCase):
def test_1(self):
chord = TreeChord(quarter_duration=4, midis=[60])
self.assertIsNone(chord.staff_number)
def test_2(self):... |
import os
import json
import time
import logging
import functools
from typing import List, Any, Optional, Callable, Union, Tuple, Dict
from web3 import Web3
from web3.eth import Contract
from web3.contract import ContractFunction
from web3.types import (
TxParams,
Wei,
Address,
ChecksumAddress,
ENS... |
from comancpipeline.Tools import pysla
import numpy as np
import healpy as hp
# List of sources used for calibration
# Ephem objects have None, calculated on the fly
CalibratorList = {
'TauA': [(5 + 34./60. + 31.94/60.**2)*15, 22 + 0 + 52.2/60.**2],
'CasA': [(23 + 23./60. + 24./60.**2)*15, 58 + 48/60. + 54./60... |
import argparse
import logging
import json
from pathlib import Path
import os
CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), './package_service_mapping.json')
GENERATED_PACKAGES_LIST_FILE = 'toc_tree.rst'
_LOGGER = logging.getLogger(__name__)
def make_title(title):
"""Create a underlined ... |
# 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
# d... |
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
# sql/expression.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Defines the public namespace for SQL expression constructs.
Prior to version 0... |
"""
SQLAlchemy Car model class
"""
def init(db):
class Car(db.Model):
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integer,
db.ForeignKey('owner.id'),
nullable=False)
owner = db.relationship('Owner',
... |
class Solution:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if amount <= 0:
return 0
sorted(coins)
dp = [-1] * (amount + 1)
dp[0] = 0
for coin in coins:
if c... |
# Copyright (c) 2014-2020 Cloudify Platform Ltd. 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 b... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet accounts properly when there is a double-spend conflict."""
from test_framework.test_f... |
"""
A GUI Ipython terminal window which can interact
with Glue. Based on code from
https://stackoverflow.com/a/9796491/1332492
and
https://stackoverflow.com/a/11525205/1332492
Usage:
new_widget = glue_terminal(**kwargs)
"""
from __future__ import absolute_import, division, print_function
# must import thes... |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... |
import os
a = os.listdir('./')
if 'main.p' in a:
print('1')
# print(a) |
"""
ASGI config for aicupboard project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SE... |
import asyncio
import mqttools
async def will():
client = mqttools.Client('localhost',
1883,
will_topic='/my/will/topic',
will_message=b'my-will-message',
will_qos=0)
await client.start()
a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom fields.
"""
from django.core.exceptions import FieldDoesNotExist
class CopyToField(object):
"""
Class to hold meta data about a field included in a CopyTo query.
"""
def __init__(self, query, name, **kwargs):
"""
Create a new ins... |
from django.forms import Textarea
from parler.forms import TranslatableModelForm
from django.conf import settings
from minicms.models import Page
class PageModelForm(TranslatableModelForm):
class Meta:
model = Page
fields = '__all__'
widgets = {
'meta_keywords': Textarea(attrs=... |
from django.apps import AppConfig
class SimpleAppConfig(AppConfig):
name = 'simple_app'
|
from .similar import similar, get_best_match
__all__ = ["similar", "get_best_match"]
|
# Auto generated from mappings.yaml by pythongen.py version: 0.9.0
# Generation date: 2021-09-24 02:32
# Schema: mappings
#
# id: https://w3id.org/linkml/mappings
# description: LinkML model for mappings
# license: https://creativecommons.org/publicdomain/zero/1.0/
import dataclasses
import sys
import re
from jsonasob... |
"""
ASGI config for ecommerce_api project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO... |
#!/usr/bin/env python3
from setuptools import setup
from pathlib import Path
setup(
name='filewrap',
version='1.1.5',
py_modules=['filewrap'],
license='MIT',
description='Python package for file/directory/archive management.',
long_description=(Path(__file__).parent / "README.md").read_text(),... |
"""
This file offers the methods to automatically retrieve the graph Candidatus Desulfofervidus auxilii.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: prot... |
import os
import logging
from distsuper.api import server
from distsuper.scripts.distsuperctl import init_db
from distsuper.common.constant import STATUS
logging.getLogger().setLevel(logging.FATAL)
tmp_for_test = os.path.join(os.getcwd(), "tmp_for_test")
os.system("rm -rf %s" % tmp_for_test)
os.system("mkdir -p %s" %... |
#!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
__author__ = ["Tomasz Chodakowski"]
import pytest
from sktime.performance_metrics.forecasting import mape_loss
from sktime.performance_metrics.forecasting import smape_loss
from sktime.performan... |
# -*- coding: utf-8 -*-
from mahjong.hand_calculating.yaku import Yaku
from mahjong.meld import Meld
class Suukantsu(Yaku):
"""
The hand with four kan sets
"""
def __init__(self, yaku_id=None):
super(Suukantsu, self).__init__(yaku_id)
def set_attributes(self):
self.tenhou_id = 51... |
#!/usr/bin/python
# Classification (U)
"""Program: process_changes.py
Description: Unit testing of process_changes in merge_repo.py.
Usage:
test/unit/merge_repo/process_changes.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"module_name": "Metactical",
"color": "grey",
"icon": "octicon octicon-file-directory",
"type": "module",
"label": _("Reports"),
"icon": "fa fa-list",
"items": [
{
"type": "r... |
import dash_core_components as dcc
import dash_html_components as html
def header():
header = html.H1("I ma the hedaer")
return header
def footer():
footer = html.H2("I ma the footer bitchs")
return footer |
# Copyright (c) 2008-2012 testtools developers. See LICENSE for details.
"""Test results and related things."""
__metaclass__ = type
__all__ = [
'ExtendedToOriginalDecorator',
'ExtendedToStreamDecorator',
'MultiTestResult',
'StreamFailFast',
'StreamResult',
'StreamSummary',
'StreamTagger',... |
import _plotly_utils.basevalidators
class TicklabeloverflowValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="ticklabeloverflow",
parent_name="histogram2dcontour.colorbar",
**kwargs
):
super(TicklabeloverflowValidator, self).__... |
""" Project definition for the Quality Report software itself. """
###
### BEGIN: This block mocks http calls needed to avoid real http calls and to provide example results instead
### Real report should have those lines removed, in order to contact real metric sources
###
import hqlib.metric_source.url_opener
from te... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
from flask import Flask, request, jsonify
import uuid
import gym
import numpy as np
import six
import argparse
import sys
import json
from rl4rs.env.slate import SlateRecEnv, SlateState
from rl4rs.env.seqslate import SeqSlateRecEnv, SeqSlateState
import http.client
h... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from scrapy.exceptions import DropItem
class BossPipeline(object):
def process_item(self, item, spider):
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from datasets.cgca_autoencoder_dataset import (
AutoencoderShapenetDataset,
)
from datasets.transition_dataset import (
TransitionShapenetDataset,
)
DATASET = {
# autoencoder datasets
AutoencoderShapenetDataset.name: AutoencoderShapenetDataset,
# transition datasets
TransitionShapenetDataset.name: TransitionSha... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli... |
# Lint as: python2, python3
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... |
import numpy as np
from sklearn.linear_model import LinearRegression
from scipy import signal
'''Detrended Fluctuation Analysis'''
def DFA (lista,min_box_size,max_box_size,show=False):
lista = np.array(lista)
cumsum = np.cumsum(lista-np.mean(lista))
RMS = []
'''# mean centered cumulation sum
for... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from signver.extractor import BaseExtractor
class PretrainedExtractor(BaseExtractor):
def __init__(self):
super().__init__()
|
# Purdue CS Bridge Gradescope Autograder
# >> show_compile_errors.py
#
# Description:
# This script runs if javac in run_autograder returns a
# non-zero exit code when compiling a student submission.
#
# Last updated:
# 07/08/2020
import json
import sys
path = '/autograder/results/results.json'
compiler_output... |
import os
import shutil
import sys
from pathlib import Path
import pytest
from pdm.cli import actions
from pdm.models.requirements import parse_requirement
from pdm.utils import cd, temp_environ
from tests import FIXTURES
def test_help_option(invoke):
result = invoke(["--help"])
assert "PDM - Python Develop... |
#!/usr/bin/env python
import rospy
from sonars import Sonars
import states
import sys
s = Sonars(int(sys.argv[1]))
ss = states.StandardisedSonars(mean=59.317, std=37.603)
rospy.init_node("test_sonars")
rate = rospy.Rate(5) # hz
while not rospy.is_shutdown():
r = s.ranges
print r, ss.state_given_new_ranges(r)
... |
import os
HOME_DIR = os.path.expanduser("~")
# Logging settings
LOG_STDOUT = os.getenv("LOG_STDOUT", "TRUE")
LOG_FORMAT = os.getenv(
"LOG_FORMAT", "[%(asctime)s][%(levelname)s][%(name)s] %(message)s")
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
|
import krpc
import time
conn = krpc.connect(name='Sub-orbital flight')
vessel = conn.space_center.active_vessel
vessel.auto_pilot.target_pitch_and_heading(90, 90)
vessel.auto_pilot.engage()
vessel.control.throttle = 1
time.sleep(1)
print('Launch!')
vessel.control.activate_next_stage()
fuel_amount = conn.get_call(ve... |
"""
created by nikos at 4/29/21
"""
import unittest
from .base_test_mixin import ModelTestMixin, sleep_after_get
class TestAwardsModel(unittest.TestCase, ModelTestMixin):
from mlb_statsapi.model.api.awards import AwardsModel as Mod
def setUp(self) -> None:
# noinspection PyTypeChecker
self.d... |
import smtplib
import ezsheets
import os
from twilio.rest import Client
TWILIO_ACCOUNT_SID = os.environ["TWILIO_ACCOUNT_SID"]
TWILIO_AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
RECEIVER = os.environ["RECEIVER"]
SENDER_EMAIL = os.environ["SENDER_EMAIL"]
SENDER_PWD = os.environ["SENDER_PWD"]
SHEET_KEY = os.environ["SH... |
import os, shutil
import pandas as pd
from tqdm import tqdm
# read csv document
g=pd.read_csv('new2.csv')
labels=list(g)
curdir=os.getcwd()
try:
os.mkdir('bnt_images')
except:
shutil.rmtree('bnt_images')
os.mkdir('bnt_images')
bnt_tasks=list()
bnt_dict=dict()
for i in range(len(labels)):
if... |
tipo = ["crédito", "débito"]
qtdeCredito = 0
saldo = 0
ent_tipo = input("Tipo: ").lower()
while ent_tipo in tipo:
ent_val = float(input("Valor: "))
if ent_tipo == tipo[0]:
saldo += ent_val
qtdeCredito += 1
elif ent_tipo == tipo[1]:
saldo -= ent_val
ent_tipo = input("Tipo: ").lowe... |
# import elasticsearch
# import curator
# import os
# import json
# import string, random, tempfile
# import time
# from click import testing as clicktest
# from mock import patch, Mock
# from . import CuratorTestCase
# from . import testvars as testvars
# import logging
# logger = logging.getLogger(__name__)
# host... |
import logging
import colorlog
def init_logger(dunder_name, testing_mode) -> logging.Logger:
log_format = (
'%(asctime)s - '
'%(name)s - '
'%(funcName)s - '
'%(levelname)s - '
'%(message)s'
)
bold_seq = '\033[1m'
colorlog_format = (
f'{bold_seq} '
... |
"""
Concatenate the labels with the notes data and split using the saved splits
"""
import csv
from datetime import datetime
import random
from constants import DATA_DIR
from constants import MIMIC_3_DIR
import pandas as pd
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
def concat_data(labelsfile, notes_file):
"""
... |
# Generated by Django 3.1.2 on 2020-12-12 10:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food_items', '0003_auto_20201127_1601'),
]
operations = [
migrations.AddField(
model_name='product',
name='image_url... |
from django.apps import apps
from django.conf.urls import url
from c3nav.editor.views.account import change_password_view, login_view, logout_view, register_view
from c3nav.editor.views.changes import changeset_detail, changeset_edit, changeset_redirect
from c3nav.editor.views.edit import edit, graph_edit, level_detai... |
#
# Production configuration for FullSim: muon track validation using MuonAssociatorByHits
#
import FWCore.ParameterSet.Config as cms
from Validation.RecoMuon.selectors_cff import *
from Validation.RecoMuon.track_selectors_cff import *
from Validation.RecoMuon.associators_cff import *
from Validation.RecoMuon.histoPar... |
# -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def something(request):
return request.function.__name__
class TestClass(object):
def test_method(self, something):
assert something == "test_method"
def test_func(something):
assert something == "test_func"
|
"""
Built on https://github.com/ranahaani/GNews/blob/master/gnews/gnews.py
"""
import re
import httpx
import logging
import feedparser
import urllib.request
from pathlib import Path
from bs4 import BeautifulSoup as Soup
from typing import List, Union, Dict
from .gnews_utils import AVAILABLE_COUNTRIES, AVAILABLE_LANGUA... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2017-2021 TwitchIO
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... |
import notifypy
import pytest
def test_normal_notification():
n = notifypy.Notify()
assert n.send() == True
def test_multiline_notification():
n = notifypy.Notify()
n.message = """
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
a... |
from typing import Dict, Optional
import torch
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.geometry.transform import get_tps_transform, warp_image_tps
class RandomThinPlateSpline(GeometricAugmentationBase2D):
r"""Add random noise to the Thin Plate Spline algorithm.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-11-28 02:26
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hindsight1', '0005_auto_20171127_1825'),
]
operations = [
m... |
"""Simple watchdog system.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import errno
import io
import logging
import os
import re
import stat # pylint: disable=wrong-import-order
import time
from treadmill im... |
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.db import models
from mycroft.utils import generate_mycroft_session
# General user information class
from rest_framework import serializers
class UserInformation(models.Model):
# Primary key tuple
se... |
from code_challenges.fifo_animal_shelter.fifo_animal_shelter import Cat, Dog, Queue, AnimalShelter
def test_single_animal():
shelter = AnimalShelter()
cat = Cat()
shelter.enqueue(cat)
actual = shelter.dequeue("cat")
expected = cat
assert actual == expected
def test_animal_dequeue():
shel... |
import logging
import pathlib
from os import listdir
import motor.motor_asyncio as motor
from dis_snek.models.application_commands import PermissionTypes
from dis_snek.errors import ExtensionNotFound, ScaleLoadException
from dis_snek.models import Embed, Scale
from dis_snek.models.application_commands import... |
"""
@Author: YangCheng
@contact: 1248644045@qq.com
@Software: Y.C
@Time: 2020/7/21 15:22
"""
JWT_SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
JWT_ALGORITHM = "HS256"
JWT_ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 1
JWT_AUTH_COOKIE = "lvt_token"
from conf.settings import *
|
"""Provide pre-made queries on top of the recorder component."""
from __future__ import annotations
from collections.abc import Iterable
from datetime import datetime as dt, timedelta
import logging
import time
from typing import cast
from aiohttp import web
from sqlalchemy import not_, or_
import voluptuous as vol
... |
# external
import streamlit as st
import pandas as pd
# internal
import streamlit_utils
import config
def main():
st.set_page_config(page_title="Heritage Connector Demo")
st.markdown(streamlit_utils.load_image("header_cropped.png"), unsafe_allow_html=True)
st.title("Heritage Connector Demo: Named Entity R... |
""" First-Class Functions
can be passed to a function as an argument
can be returned from a function
can be assigned to a variable
can be stored in a data structure (such as list, tuple, dictionary, etc.)
Types such as INT, FLOAT, STRING, TUPLE, LIST and many more are first-class objects.
Functions... |
import tensorflow as tf
from tensorflow.keras import layers as tfl
import verres as V
from . import FeatureSpec, VRSBackbone
class SmallFCNN(VRSBackbone):
def __init__(self, config: V.Config):
strides = config.model.backbone_spec["strides"]
width_base = config.model.backbone_spec["width_base"]
... |
# Copyright (c) 2012, 2014 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the function... |
"""
Written by Kushal, modified by Robik
"""
import numpy as np
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from vqa_experiments.rnn import RNN
# TODO: Test with and without weight norm
class WordEmbedding(nn.Module):
"""Word Embedding
The ntoken-th dim is used for... |
from datetime import datetime
import sys
import os
import glob
import re
from __main__ import defaultDir
def getDate():
return(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
def validDir(path):
if path==defaultDir: # if no path given, return current working directory
return(os.getcwd())
elif ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for psutil.Process class."""
import collections
import contextlib
import errno
import os
import se... |
# coding: utf-8
"""
MBTA
MBTA service API. https://www.mbta.com Source code: https://github.com/mbta/api # noqa: E501
The version of the OpenAPI document: 3.0
Contact: developer@mbta.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from op... |
import torch
import torch.nn as nn
from .fpn import FPN50
class RetinaNet(nn.Module):
num_anchors = 9
def __init__(self, num_classes):
super(RetinaNet, self).__init__()
self.fpn = FPN50()
self.num_classes = num_classes
self.loc_head = self._make_head(self.num_anchors*4)
... |
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.tornado import TornadoPlugin
api_spec = APISpec(
title="Vobla",
version="0.0.1",
openapi_version="2.0",
info=dict(description="Vobla alpha API"),
plugins=[MarshmallowPlugin(), TornadoPlugin(... |
"""
fpo_mp_input
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 1
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from fds.sdk.Optimizatio... |
__author__ = 'wei'
from ..protobuf import *
from . import igt_base_template
class NotificationTemplate(igt_base_template.BaseTemplate):
def __init__(self):
igt_base_template.BaseTemplate.__init__(self)
self.text = ""
self.title = ""
self.logo = ""
self.logoURL ... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-04-16 13:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('competition', '0005_bankinfo_account_id'),
]
operations = [
migrations.AddF... |
# Copyright (c) 2021 OpenKS Authors, DCD Research Lab, Zhejiang University.
# All Rights Reserved.
"""
init
"""
from .TransE import *
from .TransH import *
from .TransR import *
from .RotatE import *
# from .GCN import *
from .gcn import *
from .gat import *
from .graph_encoder import *
from .criterions import * |
import json
import os
import shutil
import time
import libtorrent
from locking import LockManager
def get_torrent_info(h):
while not h.has_metadata():
time.sleep(1)
return h.get_torrent_info()
def get_index_and_file_from_files(h, filename):
files = list(get_torrent_info(h).files())
try:
... |
from itertools import islice
import torch
from torch.utils import data as torch_data
from torch.nn.utils.rnn import pad_sequence
from src.utils.file_util import load_json_file
from src.model.embedding_layers import EmbeddingGeneratorGLOVE
from transformers import BertTokenizerFast
from nltk.tokenize import word_tokeniz... |
import shipane_sdk
# 注意:需将回测调成分钟级别
# 注意:SDK内部取今日时间来获取新股数据
# 注意:用于回测没有意义,需挂到“我的交易”
def initialize(context):
# 每天的开市后10分钟进行新股申购,参数设置见:https://www.joinquant.com/api#定时运行
run_daily(purchase_convertible_bonds, '9:40')
def process_initialize(context):
# 创建 StrategyManager 对象
# 参数为配置文件中的 manager id
g.... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/medicine/crafted/shared_medpack_grenade_area_a.iff"
result.attribut... |
import asyncio
from telethon.errors.rpcerrorlist import YouBlockedUserError
from usercodex import codex
from ..core.managers import edit_delete, edit_or_reply
from ..helpers import get_user_from_event, sanga_seperator
from ..helpers.utils import _format
plugin_category = "utils"
@codex.cod_cmd(
pattern="sg(u)... |
import locale
import textwrap
import discord
from discord.ext import commands
from bot import load_config
from core.utils import twitch_api_call, twitch_convert_timestamp, twitch_channel_uptime, retrieve_twitch_channel_id, \
retrieve_twitch_game, retrieve_twitch_channel_name, embed_message
class Twitch:
"""... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module for getting information about the server. """
import asyncio
from asyncio import create_subprocess... |
#
# ColorBar.py -- color bar widget
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
import math
import numpy
import gtk, gobject, cairo
from ginga.misc import Callbac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.