text stringlengths 2 999k |
|---|
from footmark.regioninfo import RegionInfo
class STSRegionInfo(RegionInfo):
"""
Represents an RAM Region
"""
def __init__(self, connection=None, name=None, id=None,
connection_cls=None):
from footmark.sts.connection import STSConnection
super(STSRegionInfo, self).__in... |
from typing import List
from .EconDataRecord import *
import json
class EconDataListRequest(object):
def __init__(self, data: List[EconData]) -> None:
self.data = data
@classmethod
def from_json(cls, data):
x = list(map(EconData.from_json, data['data']))
return cls(x)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayFundTransAuctionBalanceQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayFundTransAuctionBalanceQueryResponse, self).__init__()
self._balance_avail... |
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import gym
import numpy as np
import torch as th
from torch.nn import functional as F
from stable_baselines3.common.buffers import ReplayBuffer
from stable_baselines3.common.noise import ActionNoise
from stable_baselines3.common.off_policy_algorithm imp... |
# Copyright 2011 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
import csv
import xlrd
import pandas as pd
import re
def meso_exctract_csv_from_excel():
filename = 'D:\Python_Project_Compilers/meso_2011_a.xls'
wb = xlrd.open_workbook(filename)
sh = wb.sheet_by_name('ΜΑΡ')
csvfilepath = "D:\Python_Project_Compilers/meso_2011_a_xl.csv"
with open... |
import pytest
from flask import json
from sqlalchemy.exc import SQLAlchemyError
from app.dao.notifications_dao import get_notification_by_id
from app.models import Complaint
from app.notifications.notifications_ses_callback import handle_complaint
from tests.app.db import (
create_notification, ses_complaint_call... |
# ----------------------------------------------------------------------
# ConfDB virtual-router <name> protocols https syntax
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------------------------------------... |
#!/usr/bin/env python3
# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import collections
import copy
import mock
import logging
import logging.config
import os
import os.path
import re
import sys
import tempfile
import unittest
import boto3
import botocore.configlo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test RRASTER format driver.
# Author: Even Rouault, <even dot rouault at spatialys dot com>
#
#############################################... |
# terrascript/mysql/d.py
|
#
# Copyright 2018 Analytics Zoo Authors.
#
# 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... |
#!/usr/bin/env python
import sys
import agate
from csvkit.cli import CSVKitUtility
class CSVPy(CSVKitUtility):
description = 'Load a CSV file into a CSV reader and then drop into a Python shell.'
def add_arguments(self):
self.argparser.add_argument('--dict', dest='as_dict', action='store_true',
... |
# -*- coding: utf-8 -*-
"""
Utils has nothing to do with models and views.
"""
import string
import random
import os
import io
import tarfile
import time
from datetime import datetime
# Instance folder path, make it independent.
INSTANCE_FOLDER_PATH = os.path.join('/opt', 'alarmdecoder-webapp', 'instance')
ALL... |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-3, 3, 0.25)
y = np.arange(-3, 3, 0.25)
X, Y = np.meshgrid(x, y)
Z = 6*X*X + 4*X*Y + 3*Y*Y
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(X,Y,Z)
xx = np.linspace(-3, 3, 100)
yy = np.linspace(-3, 3, 100)
z... |
from multiprocessing import Manager
from Old_ver.CNS_data_share import CnsDataShare
from Old_ver.CNS_plot import DrawPlot
from Old_ver.CNS_data_cleaner import CnsDataCleaner
class StartAutonomous_CNS:
def __init__(self):
# 공유되는 mother memory 선언
self.mother_memory = self.make_memory()
# 실행되... |
class RoutingGroup(basestring):
"""
Specifies the name of routing group.
For example:
<ul>
<li> d192.168.1.0/24 ('d' stands for data LIF and 192.168.1.0/24
is subnet),
<li> c192.168.1.0/24 ('c' stands for cluster LIF and
192.168.1.0/24 is subnet),
<li> n192.168.1.0/24 ('n' stands for... |
from .gnetdata import load_Gnetdata_object, load_from_anndata, Gnetdata
|
from contextlib import contextmanager
from io import StringIO
# Module-level constants
_FILESYSTEM = {
"a.txt": "Hello World",
"b.xml": "<message>Hello World</message>",
"c.out": "10101010"
}
@contextmanager
def file(filename):
"""File context manager.
This is the function variant of the context... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# =========================================================================== #
# Project : Data Studio #
# Version : 0.1.0 #
# File : test_tests.py ... |
"""
This module lets you practice the ACCUMULATOR pattern in classic forms:
SUMMING: total = total + number
COUNTING: count = count + 1
A subsequent module lets you practice the ACCUMULATOR pattern in another classic form:
IN GRAPHICS: x = x + pixels
Authors: David Mutchler, Dave Fisher, Valerie Gallu... |
class ApplicationId(object):
"""
Contains information used to uniquely identify a manifest-based application. This class cannot be inherited.
ApplicationId(publicKeyToken: Array[Byte],name: str,version: Version,processorArchitecture: str,culture: str)
"""
def ZZZ(self):
"""hardcoded/mock instance of t... |
from __future__ import absolute_import
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import init
__all__ = ['InceptionNet', 'inception']
def _make_conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1,
bias=False):
conv = nn.Conv2d(in_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # S_Pr... |
#%% Load modules
from aesim.simba import DesignExamples
import matplotlib.pyplot as plt
#%% Load project
flybackConverter = DesignExamples.DCDC_Flyback()
#%% Get the job object and solve the system
job = flybackConverter.TransientAnalysis.NewJob()
status = job.Run()
#%% Get results
t = job.TimePoints
Vo... |
#!/usr/bin/env python3
from bs4 import BeautifulSoup
import requests
import pandas as pd
url = "https://redis.io/commands"
# Gets the entire html
content = requests.get(url).text
# Parse the html content
soup = BeautifulSoup(content, "lxml")
# D
section = soup.find_all("section", attrs={"id": "commands"})
containe... |
import json
import csv
import pandas as pd
from Bio import SeqIO
from io import StringIO
from nimble.types import Data, Config, DataType
from nimble.utils import get_library_name_from_filename, trim_low_complexity_regions
from nimble.remote import fetch_sequence, get_ids
# Given a path to a .fasta, reads it and re... |
# Generated by Django 2.2.1 on 2019-06-27 12:44
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fiel... |
from rest_framework import mixins, viewsets
from rest_framework.authentication import SessionAuthentication, \
TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from graph_component.models.node import Node
from graph_component.serializers.node_serializer import NodeSerializers
class Node... |
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', include('frontend.urls'))
]
|
# @ author: Minyi Zhao
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0"
import time
import yaml
import argparse
import torch
import os.path as op
import numpy as np
from collections import OrderedDict
from tqdm import tqdm
import utils
import dataset
from net_rfda import RFDA
from skimage.metrics import peak_signal_... |
import numpy as np
from forward import Prediction
import matplotlib.pyplot as plt
import os
import scipy
from matplotlib import ticker,cm
from latent import latent_c
class inference(object):
def __init__(self,step,burn_in,dim,obs,sigma,true_permeability,true_pressure,obs_position,scale,device):
self.dim =... |
"""Prepared by [Ali Rifat Kaya](https://www.linkedin.com/in/alirifatkaya/)
"""
def pr_auc_score(y_test, predicted_probabilities):
"""Return AUCPR (Area Under Curve Precision-Recall) score
Parameters
----------
y_test : Test set target values
Example:
# df is a pandas dataframe with f... |
#!/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.
"""Base class for RPC testing."""
from collections import deque
import logging
import optparse
import os
... |
#!/usr/bin/env python
##############################################################################
#circle.py
#
#This code has been created by Enrico Anderlini (ea3g09@soton.ac.uk) for
#performing circle manoeuvring tests.
#
#Modifications to code
#14/03/2013 code created
#06/04/2013 publisher of a boolean ope... |
from typing import List, Set
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import orm
from app.db.session import get_db
from app.models import shopmodels
from app.service import scraperservice, shopservice
from ..dependencies.auth import RoleChecker, admin_role, user_role
from ... |
# -*- coding: utf-8 -*-
template_url = 'https://feed.mix.sina.com.cn/api/roll/get?pageid=153&lid={}&k=&num={}&page={}&r={}'
lid2classification = {
"2509": "全部",
"2510": "国内",
"2511": "国际",
"2669": "社会",
"2512": "体育",
"2513": "娱乐",
"2514": "军事",
"2515": "科技",
"2516": "财经",
"2517... |
#!/usr/bin/python
import json
import md5
import sys
import time
from pprint import pprint
import datetime
import json
### Variables
site_host = ""
site_ipaddress = ""
site_grade = ""
site_httpstatuscode = 0
site_serversignature = ""
site_rawdate = 0
site_expirationdate = ""
#file_timestamp = 'results/ssl_scan_{:%d... |
# coding: utf-8
"""
App Center Client
Microsoft Visual Studio App Center API # noqa: E501
OpenAPI spec version: preview
Contact: benedetto.abbenanti@gmail.com
Project Repository: https://github.com/b3nab/appcenter-sdks
"""
from __future__ import absolute_import
import unittest
import appcente... |
# Copyright 2019 YugaByte, Inc. and Contributors
#
# Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# https://github.com/YugaByte/yugabyte-db/blob/master/licenses/POLYFORM-FREE-TRIAL-LIC... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 30, transform = "Quantization", sigma = 0.0, exog_count = 20, ar_order = 12); |
# Copyright 2017 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 ... |
"""Top-level package for pyhomogenize."""
from . import _consts as consts
from . import _utilities as utilities
from .data import netcdf as test_netcdf
from . import operators as op
from .cli import create_parser
from ._basics import basics
from ._netcdf_basics import netcdf_basics
from ._time_control import time_con... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Dexciss Technology and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from erpnext.accounts.party import get_party_account
from datetime i... |
from bokeh.layouts import column, gridplot
from bokeh.models import Div, Range1d, WMTSTileSource
from bokeh.plotting import figure, show
from bokeh.sampledata.airports import data as airports
from bokeh.tile_providers import get_provider, CARTODBPOSITRON
title = "US Airports: Field Elevation > 1500m"
def plot(tile_so... |
# JP Onnela
# April 20, 2021
# Edited May 17, 2021 by Jonathan Larson
import networkx as nx
import random
import scipy.stats as ss
import time
def generate_DMC(q_mod, q_con, n):
"""Generate DMC model realization given parameters."""
G = nx.Graph()
G.add_edge(0,1)
new_nodes = list(range(... |
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Sequence
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy.orm import class_mapper
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship
from sqlalchemy.test... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=19
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
class Opty(cirq.PointOptimizer):
def optimization_at(
... |
import sys
import math
import time
class GraphTool():
def __init__(self):
pass
def plot_pr(self):
pass
def plot_roc(self):
pass
|
import collections
def sieve_eras(n):
l = collections.deque( [False] * 2 + [True for i in range(2, n + 1)] )
k = 0
while k <= n :
while k<= n :
if l[k] == True:
yield k
break
k += 1
... |
from threeML.io.fits_file import FITSExtension, FITSFile
import numpy as np
import astropy.io.fits as fits
import pytest
class DUMMYEXT(FITSExtension):
def __init__(self, test_value):
data_list = [("TEST_VALUE", test_value)]
super(DUMMYEXT, self).__init__(
tuple(data_list), (("EXTNA... |
import sys
from functools import partial
from pprint import pprint
from funcy.colls import where, pluck
from funcy.seqs import first, distinct, flatten
from smoke import Steem
# todo
# "get_expiring_vesting_delegations": [('author', 'str'), ('from_time', 'object'), ('limit', 'int')], # ?
# "get_reward_fund": [('fund... |
from collections import Counter, defaultdict
from typing import Dict
from allennlp.data.instance import Instance
from allennlp.data.fields import Field, TextField, LabelField, SequenceLabelField
from allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer
from allennlp.data.tokenizers import Token
from ... |
import os
import numpy as np
from micap import pipeline
from glob import glob
from PIL import Image
import cv2_extras as cv2x
# weird import style to un-confuse PyCharm
try:
from cv2 import cv2
except ImportError:
import cv2
cell_radius = 17 * 3
cell_size = np.pi * (cell_radius ** 2)
seg_config = [
{
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sys
from setuptools import setup
PY2 = sys.version_info[0] == 2
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
matches = re.search(
r"__version__[\s]+=[\s... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class ShiyanlougithubItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
name=scrapy.Field()
update_... |
import sys
import argparse
import shutil
import os
import re
import filecmp
import subprocess
from pathlib import Path
from release_libraries import LibraryParameters
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Move released bam file back to release directory")
parser.add_argument("-p",... |
# -------------------------------------------------------------------------- #
# Copyright 2006-2009, University of Chicago #
# Copyright 2008-2009, Distributed Systems Architecture Group, Universidad #
# Complutense de Madrid (dsa-research.org) #
# ... |
"""
11655 : ROT13
URL : https://www.acmicpc.net/problem/11655
Input #1 :
Baekjoon Online Judge
Output #1 :
Onrxwbba Bayvar Whqtr
Input #2 :
One is 1
Output #2 :
Bar vf 1
"""
s = input()
e = []
for c in s:
if 'A' <= c <= 'Z':
e.append(chr((((ord(c) + 1... |
# Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# 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... |
import pandas as pd
from tokenizers import normalizers
from tokenizers.normalizers import NFKC, Strip, Lowercase
from autonmt.bundle import utils
from autonmt.bundle.report import generate_multivariable_report
from autonmt.preprocessing import DatasetBuilder
def main():
# Create preprocessing for training
... |
t = input('')
for _ in xrange(t):
h = raw_input('')
print 1
|
#!/usr/bin/python
import sys
import os
import argparse
def get_module_path(module_name):
module_path = ''
for d in sys.path:
possible_path = os.path.join(d, module_name)
# skip current dir as this is plugin dir
if os.path.isdir(possible_path) and len(d) != 0:
module_path = ... |
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import processor
from datetime import datetime
def parse( url ):
r = requests.get( url )
if r.status_code == 404:
return processor.create_dictionary('', url, r.status_code, [u''], [u''], u'', u'', u'', u'', [u''], [u''])
r.encoding = 'UTF-8'... |
from numba.cuda.testing import unittest, SerialMixin, skip_on_cudasim
from numba import cuda
from numba.core import config
class MyError(Exception):
pass
regex_pattern = (
r'In function [\'"]test_exc[\'"], file [\:\.\/\\\-a-zA-Z_0-9]+, line \d+'
)
class TestUserExc(SerialMixin, unittest.TestCase):
de... |
# 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 sqlalchemy import BIGINT
from sqlalchemy import BigInteger
from sqlalchemy import Boolean
from sqlalchemy import CHAR
from sqlalchemy import CheckConstraint
from sqlalchemy import Column
from sqlalchemy import DATE
from sqlalchemy import DateTime
from sqlalchemy import DECIMAL
from sqlalchemy import Enum
from sqla... |
import os
from dotenv import load_dotenv
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
# Load environment variables
load_dotenv()
from src import util
util.example()
# Setup Flask and variables
port = int(os.getenv('PORT', 8000))
app = Flask(__name__)
app.config['CORS_HEADERS']... |
import logging
import uuid
from django.conf import settings
from pyrabbit2.api import Client
from pyrabbit2.http import HTTPError, NetworkError
logger = logging.getLogger()
def _get_rabbit_connection():
"""Helper giving us a rabbit connection from settings.BROKER_URL"""
if settings.RABBITMQ_PYRABBIT_URL:
... |
MYPY_CHECK_RUNNING = False
|
# Generated by Django 3.1 on 2021-02-11 14:51
from django.db import migrations
import common.fields
class Migration(migrations.Migration):
dependencies = [
("regulations", "0003_auto_20210210_1516"),
]
operations = [
migrations.AlterField(
model_name="regulation",
... |
from sqlalchemy import UniqueConstraint
from sqlalchemy.types import Enum
from app.main import db
class SensorType(db.Model):
""" SensorType Model for storing sensor type related details """
__tablename__ = "sensor_type"
_types = ('Boolean', 'Enum', 'Decimal')
id = db.Column(db.Integer, primary_key... |
# -*- coding: utf-8 -*-
"""
@file
@brief Defines a sphinx extension to output :epkg:`sphinx` doctree.
"""
import os
import textwrap
from os import path
from sphinx.util import logging
from docutils.io import StringOutput
from sphinx.builders import Builder
from sphinx.util.osutil import ensuredir
from docutils import n... |
'''
Test per SNI server name selection of CA certs for validating cert sent by client.
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF lic... |
from rest_framework.generics import ListAPIView
from rest_framework import permissions
from .models import Technology
from .serializers import TechnologySerializer
class TechnologyListView(ListAPIView):
permission_classes = (permissions.AllowAny, )
queryset = Technology.objects.all()
serializer_class = T... |
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import emits_warning
import pickle
from sqlalchemy import Integer, String, UniqueConstraint, \
CheckConstraint, ForeignKey, MetaData, Sequence, \
ForeignKeyConstraint, PrimaryKeyConstraint, ... |
# -*- coding: utf-8 -*-
""" core_model.py - define coure model API"""
import os
import abc
import yaml
import pandas as pd
import numpy as np
import logging
import subprocess
import warnings
from contextlib import contextmanager
from typing import Union, Mapping
from ..workbench.em_framework.model import AbstractModel ... |
# -*- coding: utf-8 -*-
##########################################
# Configuration file for scrub.py #
# Must be in the same folder as scrub.py #
# See README file for instructions #
##########################################
# File Configurations
input_file_path = "../../caches/text_files/"
output_file_p... |
class Country:
def __init__(self):
self.code = ""
self.name = ""
self.population = ""
self.continent = ""
self.surfaceArea = ""
def __str__(self):
return f"Country [code= {self.code}, name= {self.name}, continent= {self.continent}, population= {self.population}]"... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Marker(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scattermapbox"
_path_str = "scattermapbox.marker"
_valid_props = {
"allowoverlap",
... |
#!/usr/bin/env python3
import argparse
import sys
import os
import fsb5
class FSBExtractor:
description = 'Extract audio samples from FSB5 files'
def __init__(self):
self.parser = self.init_parser()
def init_parser(self):
parser = argparse.ArgumentParser(description=self.description)
parser.add_argument('... |
from django.db import models
class Picture(models.Model):
token = models.CharField(max_length=64, blank=True)
pic = models.ImageField(upload_to='pics')
|
import mock
import datetime
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from django.contrib.auth import get_user_model
from apps.customizer.models import Configuration
from apps.web.models ... |
# Copyright 2017 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 ag... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
from pycocotools.cocoeval import COCOeval
import numpy as np
import json
import os
from collections import defaultdict
from ..generic_dataset import GenericDataset
class MOT(Gen... |
class BaseError(Exception):
"""
"""
class TunicornException(BaseError):
"""
"""
class HaltServerException(TunicornException):
"""
"""
def __init__(self, reason, exit_status=1):
self.reason = reason
self.exit_status = exit_status
msg = "Halt... |
#creating the metagan model
import torch
import torch.nn as nn
import sys
sys.path.append('..')
import fewshot_re_kit
import torch
from torch import autograd, optim, nn
from torch.autograd import Variable
from torch.nn import functional as F
class MetaGenerator(fewshot_re_kit.adversarial_framework.FewShotAdver... |
from rest_framework import viewsets, status
from .models import Conversation, Message, Notice
from .serializers import ConversationSerializer, MessageSerializer
from rest_framework.decorators import list_route
from rest_framework.response import Response
from redzza import utils
class ConversationViewSet(viewsets.Mod... |
import numpy as np
import tempfile
from dnnv.verifiers.common.base import Parameter, Verifier
from dnnv.verifiers.common.reductions import IOPolytopeReduction, HalfspacePolytope
from dnnv.verifiers.common.results import SAT, UNSAT, UNKNOWN
from functools import partial
from .errors import MarabouError, MarabouTransla... |
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dukapoint.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Ar... |
"""Entry point."""
import os
import torch
import data
import config
import utils
import trainer
import re_trainer
from data.loader import DataLoader
from tacred_utils import scorer, constant, helper
from tacred_utils.vocab import Vocab
import numpy as np
logger = utils.get_logger()
def main(args): # pylint:disab... |
from abc import ABCMeta, abstractmethod, abstractproperty
from copy import deepcopy
from tinydb import TinyDB
from tinydb.middlewares import Middleware
from tinydb.utils import with_metaclass
iteritems = getattr(dict, 'iteritems', dict.items)
itervalues = getattr(dict, 'itervalues', dict.values)
class Serializer(wi... |
# 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 applicable law or agreed to in writing, s... |
import numpy as np
import cv2
import sys
import os
RESIZE_FACTOR = 4
class RecogEigenFaces:
def __init__(self):
cascPath = "haarcascade_frontalface_default.xml"
self.face_cascade = cv2.CascadeClassifier(cascPath)
self.face_dir = 'face_data'
self.model = cv2.createEigenFaceRecognize... |
from jsonobject import DefaultProperty
from jsonobject.exceptions import BadValueError
from dimagi.ext.jsonobject import (
BooleanProperty,
DictProperty,
JsonObject,
ListProperty,
StringProperty,
)
from corehq.apps.userreports.datatypes import DataTypeProperty
from corehq.apps.userreports.expressi... |
from datetime import datetime
import hashlib
import io
import pickledb
import time
from .cache import Cache
from .errors import BucketNotEmpty, NoSuchBucket, NoSuchKey, HttpError
from .models import Bucket, BucketQuery, S3Item
from .sia import Sia
class SiaStore(object):
def __init__(self, base_dir, host='localh... |
#!/usr/bin/env python3
'''
Promotes the specified build results (represented by build result manifests in S3).
An example being the promotion of a build snapshot to a daily build.
'''
import argparse
import concurrent.futures
import functools
import logging
import logging.config
import os
import sys
import typing
i... |
import typing
import error
REQUEST_TABLE = {
'get': [[str]],
'as': [str],
'by': ([str], 'optional'),
'if': ([list], 'optional'),
'except': ([list], 'optional'),
'join': ([
{
'name': str,
'of': [str],
}
], 'optional'),
'macro': ... |
#!/usr/bin/env python3
import sys
import logging
import os
import argparse
from logging.handlers import RotatingFileHandler
from pykms_Format import ColorExtraMap, ShellMessage, pretty_printer
#---------------------------------------------------------------------------------------------------------------------------... |
from test import support
import decimal
import enum
import locale
import math
import platform
import sys
import sysconfig
import time
import threading
import unittest
try:
import _testcapi
except ImportError:
_testcapi = None
# Max year is only limited by the size of C int.
SIZEOF_INT = sysconfig.get_config_v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.