text
string
size
int64
token_count
int64
import traceback try: raise Exception('This is the error message.') except: errorFile = open('./Chapter 10/errorInfo.txt', 'w') errorFile.write(traceback.format_exc()) errorFile.close() print('The traceback info was written to errorInfo.txt')
262
82
# Databricks notebook source from pyspark.sql.types import * from pyspark.sql import functions as F import base64 import array # COMMAND ---------- # s is a base64 encoded float[] with first element being the magnitude def Base64ToFloatArray(s): arr = array.array('f', base64.b64decode(s)) return (arr[0], arr[1:])...
2,794
984
print("Press q to quit") quit = False while quit is False: in_val = input("Please enter a positive integer.\n > ") if in_val is 'q': quit = True elif int(in_val) % 3 == 0 and int(in_val) % 5 == 0: print("FizzBuzz") elif int(in_val) % 5 == 0: print("Buzz") elif int(in_val) % ...
373
143
from lesson14_projects.pen.data.const import ( A, E_A, E_AN, E_IS, E_OVER, E_PEN, E_PIN, E_THAT, E_THIS, E_WAS, INIT, IS, PEN, THIS, ) pen_transition_doc_v19 = { "title": "This is a pen", "entry_state": INIT, "data": { INIT: { E_OV...
926
340
import gd,os,time from Html import Animation_Html from Iteration import Animation_Iteration from Write import Animation_Write from Base import * from Canvas2 import * from Canvas2 import Canvas2 from Image import Image from HTML import HTML __Canvas__=None class Animation( Animation_Html, Animation_...
2,899
952
#! /usr/bin/env python3 from .base_miner import BasePostGradientMiner import torch from ..utils import loss_and_miner_utils as lmu # adapted from # https://github.com/chaoyuaw/incubator-mxnet/blob/master/example/gluon/ # /embedding_learning/model.py class DistanceWeightedMiner(BasePostGradientMiner): def __init_...
1,839
636
# -*- coding: utf-8 -*- from .Alarm.alarm import Alarm from .DeliveryView.bolus import Bolus from .DeliveryView.info import Info from .DeliveryView.infusion import Infusion from .DeliveryView.infusion_parameter import InfusionParameter from .DeliveryView.priming import Priming from .HardwareControl.motor import Motor ...
1,037
286
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- class DashboardInfo: MODEL_ID_KEY = "id" # To match Model schema MODEL_INFO_FILENAME = "model_info.json" RAI_INSIGHTS_MODEL_...
1,656
618
from functools import partial from pulsar import Connection, Pool, get_actor from pulsar.utils.pep import to_string from pulsar.apps.data import RemoteStore from pulsar.apps.ds import redis_parser from .client import RedisClient, Pipeline, Consumer, ResponseError from .pubsub import RedisPubSub, RedisChannels class...
4,728
1,319
# Generated by Django 3.0.7 on 2020-06-16 05:23 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('tasks', '0004_auto_20200616_0116'), ] operations = [ migrations.AddField( model_name='userreward', ...
1,068
330
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors # For information on the respective copyright owner see the NOTICE file # # 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 # #...
2,683
743
import mock import pytest from werkzeug.exceptions import NotFound import app.main.helpers as helpers from dmcontent.content_loader import ContentLoader from dmtestutils.api_model_stubs import BriefStub, FrameworkStub, LotStub content_loader = ContentLoader('tests/fixtures/content') content_loader.load_manifest('dos...
9,531
3,004
import deephaven.TableTools as tt import deephaven.Plot as plt t = tt.emptyTable(50)\ .update("X = i + 5", "XLow = X -1", "XHigh = X + 1", "Y = Math.random() * 5", "YLow = Y - 1", "YHigh = Y + 1", "USym = i % 2 == 0 ? `AAPL` : `MSFT`") p = plt.plot("S1", t, "X", "Y").lineColor("black").show() p2 = plt.plot("S1"...
3,329
1,529
# Copyright 2019 Arie Bregman # # 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 agree...
1,366
432
from .read import ( read_request_head, read_response_head, connection_close, expected_http_body_size, validate_headers, ) from .assemble import ( assemble_request, assemble_request_head, assemble_response, assemble_response_head, assemble_body, ) __all__ = [ "read_request_head", ...
546
179
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-05-21 19:33 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('request_token', '0008_convert_token_data_to_jsonfield'), ...
1,211
369
#4 lines: Fibonacci, tuple assignment parents, babies = (1, 1) while babies < 100: print ('This generation has {0} babies'.format(babies)) parents, babies = (babies, parents + babies)
191
76
import typing from .core import Component _Controller = typing.TypeVar('_Controller') _ControllerType = typing.Type[_Controller] ControllerFactory = typing.NewType('ControllerFactory', typing.Callable[[typing.Type], object]) _controller_factory: typing.Optional[ControllerFactory] = None def controller(controller_cl...
896
229
# Copyright 2014 The Bazel 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 applicable la...
7,000
2,570
#!/usr/bin/env python # -*- coding: utf-8 -*- import calendar import csv from datetime import datetime import os from flask_sqlalchemy import SQLAlchemy from sqlalchemy import and_ from ..constants import CONST from ..models import AccidentMarker from ..utilities import init_flask, decode_hebrew, open_utf8 from ..imp...
14,680
5,141
import unittest from numpy.testing import assert_array_equal import numpy as np from libact.base.dataset import Dataset from libact.models import LogisticRegression from libact.query_strategies import VarianceReduction from .utils import run_qs class VarianceReductionTestCase(unittest.TestCase): """Variance red...
952
355
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import open from builtins import str from future import standard_library standard_library.install_aliases() import os import re import json import copy imp...
15,992
5,285
# Copyright 2015, Rackspace, US, 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 w...
8,920
2,527
'''Load image/class/box from a annotation file. The annotation file is organized as: image_name #obj xmin ymin xmax ymax class_index .. ''' from __future__ import print_function import os import sys import os.path import random import numpy as np import torch import torch.utils.data as data import torchvision.t...
5,621
1,839
# Lint as: python3 # Copyright 2020 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 ...
13,258
4,178
# Copyright (c) 2010 by Cisco Systems, Inc. """ Manage the tool plugins and use them appropriately. """ import os TOOLNAME_PLUGIN_PREFIX = "toolname" class ToolNameManager: """ToolName plugins have to register with this manager the circumstances under which they wish to be called.""" def __init__(self, pl...
4,589
1,357
import time from http import HTTPStatus from itertools import count from typing import Sequence import gevent import grequests import pytest import structlog from eth_utils import to_canonical_address from flask import url_for from raiden.api.python import RaidenAPI from raiden.api.rest import APIServer, RestAPI from...
12,991
3,943
# -*- coding: utf-8 -*- # file: preprocess.py # author: jackie # Copyright (C) 2021. All Rights Reserved. import os import pandas as pd import argparse import emoji import re from sklearn.model_selection import train_test_split parser = argparse.ArgumentParser() parser.add_argument("--inpath", type=str, required=True...
8,796
3,168
import os import shutil import requests def get_cat(folder, name): url = "http://consuming-python-services-api.azurewebsites.net/cats/random" data = get_data_from_url(url) save_image(folder, name, data) def get_data_from_url(url): response = requests.get(url, stream=True) return response.raw ...
487
175
from __future__ import absolute_import, division, print_function from fnmatch import fnmatch from glob import glob import os import uuid from warnings import warn import pandas as pd from toolz import merge from .io import _link from ...base import get_scheduler from ..core import DataFrame, new_dd_object from ... i...
15,348
4,533
# -*- coding: utf-8 -*- """ media info manager module. """ from pyrin.core.mixin import HookMixin from pyrin.core.structs import Manager import pyrin.utils.path as path_utils from charma.media_info import MediaInfoPackage from charma.media_info.interface import AbstractMediaInfoProvider from charma.media_info.except...
2,411
640
import unittest from boxrec.parsers import FightParser class MockResponse(object): def __init__(self, content, encoding, url): self.content= content self.encoding = encoding self.url = url class TestFightParser(unittest.TestCase): def setUp(self): with open('mock_data/fights/...
842
265
from datetime import datetime, timedelta from bson.objectid import ObjectId WORK_TIMEOUT = 600 class WorkQueue: """ A simple MongoDB priority work queue that handles the queue of experiment. """ def __init__(self, mongodb): super().__init__() self._mongodb = mongodb sel...
4,868
1,363
# -*- coding: utf-8 -*- # 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 licenses this file to You under the Apache License, Version 2.0 # (the "Li...
7,695
2,207
import os import sys import bpy script_dir = os.path.dirname(os.path.abspath(__file__)) utils_dir = os.path.join(script_dir, "../../blender_utils") sys.path.append(utils_dir) from utils import bake_model, clean_unused, export_ig_object, import_obj_folder ############################################# # Parse command...
3,605
1,219
# Copyright 2012 OpenStack Foundation # 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 requ...
3,057
859
import json import os import re import subprocess from base64 import b64decode from enum import Enum from math import ceil, floor from pathlib import Path from urllib.error import HTTPError from urllib.request import urlopen import yaml from charmhelpers.core import hookenv from charmhelpers.core.unitdata import kv ...
11,020
3,481
import socket import csv import traceback import threading s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) usrpass={} def openfile(): filename="login_credentials.csv" with open(filename,'r')as csvfile: csv_file = csv.reader(csvfile, delimiter=",") for col in csv_file: usrpas...
2,220
747
from itertools import product from sklearn.base import clone from sklearn.preprocessing import FunctionTransformer from sklearn.model_selection import ParameterGrid from imblearn.pipeline import Pipeline from rlearn.utils import check_random_states def check_pipelines(objects_list, random_state, n_runs): """Extra...
3,040
917
from mushroom_rl.utils.plots import PlotItemBuffer, DataBuffer from mushroom_rl.utils.plots.plot_item_buffer import PlotItemBufferLimited class RewardPerStep(PlotItemBuffer): """ Class that represents a plot for the reward at every step. """ def __init__(self, plot_buffer): """ Constr...
2,986
850
# -*- coding: utf-8 -*- # # test/test_metadata.py # Part of ‘python-daemon’, an implementation of PEP 3143. # # This is free software, and you are welcome to redistribute it under # certain conditions; see the end of this file for copyright # information, grant of license, and disclaimer of warranty. """ Unit test for...
13,044
3,666
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import Union, List from .purpose import * from .trait_reference import TraitReference from cdm.utilities import JObject class PurposeReference(JObje...
517
148
import re from typing import Union, List import nltk from bs4 import BeautifulSoup class Normalizer: def __init__(self): self.lemmatizer = nltk.stem.WordNetLemmatizer() def normalize(self, x: Union[list, str]) -> List[str]: """ Accepts text (possibly tokenized) and makes it ...
1,725
570
""" For backwards-compatibility. keep this file. (Many people are going to have key bindings that rely on this file.) """ from __future__ import unicode_literals from .app import * __all__ = [ # Old names. 'HasArg', 'HasCompletions', 'HasFocus', 'HasSelection', 'HasValidationError', 'IsDon...
1,874
613
#spaces.py ''' AlgoHack Genetic Algorithm for University Semaster Planning Version 0.03 2018 Niranjan Meegammana Shilpasayura.org ''' import xdb def crt_spaces_table(cursor,drop=False): if (drop): sql="DROP TABLE IF EXISTS spaces;" success, count=xdb.runSQL(cursor, sql) sql='''C...
1,988
740
import urllib.request import cv2 import numpy as np import time import threading class ThreadedRemotePiCamera: def __init__(self, pi_address, resolution=(320,240), framerate=10, hflip=False, vflip=False): if hflip and vflip: self.flip = -1 elif hflip: self.flip = 0 e...
2,062
665
#! /usr/bin/python3 import time import random import json import os from pprint import pprint from kubernetes.client.rest import ApiException from pint import UnitRegistry from collections import defaultdict from kubernetes import client, config, watch from timeloop import Timeloop from datetime import timedelt...
22,520
6,724
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from clean_transcript import clean_transcript ALPHABET_FILE_PATH = "/DeepSpeech/bin/bangor_welsh/alphabet.txt" def validate_label(label): clean = clean_transcript(ALPHABET_FILE_PATH) cleaned, transcript = clean.clean(label) if cleaned: return transc...
349
126
# Copyright (c) 2019-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...
13,806
4,589
import json import csv import sys import os import re import codecs import logging from logging.config import dictConfig import click import yaml from sqlalchemy import create_engine from jsontableschema_sql import Storage from smart_open import smart_open from . import postgres from . import carto csv.field_size_li...
11,770
3,480
# 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...
6,182
2,206
from manimlib.imports import * from manimlib.utils import bezier import numpy as np class VectorInterpolator: def __init__(self,points): self.points = points self.n = len(self.points) self.dists = [0] for i in range(len(self.points)): self.dists += [np.linalg.norm( ...
1,335
439
from setuptools import setup setup(name='rapid_plotly', version='0.1', description='Convenience functions to rapidly create beautiful Plotly graphs', author='Joseph Dasenbrock', author_email='dasenbrockjw@gmail.com', packages=['rapid_plotly'], zip_safe=False)
297
91
#! /usr/bin/doit -f # https://pydoit.org # `pip install [--user] doit` adds `doit.exe` to the PATH # - Note `doit auto`, the file watcher only works on Linux/Mac # - All commands are relative to dodo.py (doit runs in the working dir of dodo.py # even if ran from a different directory `doit -f path/to/dodo.py`) from g...
5,834
1,848
class EmptyFileError(Exception): pass filenames = ["myfile1", "nonExistent", "emptyFile", "myfile2"] for file in filenames: try: f = open(file, 'r') line = f.readline() if line == "": f.close() raise EmptyFileError("%s: is empty" % file) # except IO...
620
192
# Crumbling In # Like randomised coloured dots and then they # increase on both sides getting closer and closer into the middle. import sys, traceback, random from numpy import array,full class animation(): def __init__(self,datastore): self.max_led = datastore.LED_COUNT self.pos = 0 self....
1,288
429
from __future__ import division from unittest import skipIf, TestCase import os from pandas import DataFrame import numpy as np from numpy.testing import assert_array_equal BACKEND_AVAILABLE = os.environ.get("ETS_TOOLKIT", "qt4") != "null" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import asser...
16,884
5,585
import os.path from .. import * class TestMixed(IntegrationTest): def __init__(self, *args, **kwargs): super().__init__(os.path.join('languages', 'mixed'), *args, **kwargs) def test_build(self): self.build(executable('program')) self.assertOutput([executable('program')], 'hello from ...
1,220
378
from collections import namedtuple # Basic example Point = namedtuple('Point', ['x', 'y']) p = Point(11, y=22) print(p[0] + p[1]) x, y = p print(x, y) print(p.x + p.y) print(Point(x=11, y=22)) from collections import namedtuple import csv f = open("users.csv", "r") next(f) reader = csv.reader(f) student_list = [] fo...
821
300
# Profile mitmdump with apachebench and # yappi (https://code.google.com/p/yappi/) # # Requirements: # - Apache Bench "ab" binary # - pip install click yappi from mitmproxy.main import mitmdump from os import system from threading import Thread import time import yappi import click class ApacheBenchThread(Thread): ...
1,439
509
# -*- coding: utf-8 -*- """ Various plots """ import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, FFMpegWriter import xarray as xr import os def quiver(data, arrScale = 25.0, threshold = None, nthArr = 1, contourLevels = None, colbar = True, logscale = Fa...
8,922
3,150
# model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, dept...
1,212
472
#!/usr/bin/python # Copyright (c) 2019 OpenStack Foundation # 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-...
69,300
20,399
#!/usr/bin/env python from setuptools import setup # Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package def version(): import os import re init = os.path.join('dark', '__init__.py') with open(init) as fp: initDat...
4,756
1,892
# ====================================================================================================================== # Fakulta informacnich technologii VUT v Brne # Bachelor thesis # Author: Filip Bali (xbalif00) # License: MIT # ======================================================================================...
1,732
464
from pycfmodel.model.resources.properties.policy_document import PolicyDocument from pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types import Resolvable, ResolvableStr class Policy(Property): """ Contains information about an attached policy. Properties: - Poli...
585
153
from .stacking import StackingClassifier, stack_features from .multitask import MultiTaskEstimator
99
27
# Copyright (C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_p...
4,209
1,231
from __future__ import print_function import json from typing import List from functools import lru_cache from cloud_storages.http_shortcuts import * from database.database import Database from models.models import StorageMetaInfo, Resource, Size from cloud_storages.storage import Storage from cloud_storages.gdrive.c...
8,781
2,548
from django.urls import re_path, include from . import views app_name='logged' # url mappings for the webapp. urlpatterns = [ re_path(r'^$', views.logged_count, name="logged_count"), re_path(r'^loggedusers/', views.logged, name="logged_users"), re_path(r'^settings/', views.user_settings, name="update_info...
677
254
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from scout.dao.space import get_spots_by_filter, _get_spot_filters, \ _get_extended_info_by_key import copy def get_item_by_id(item_id): spot = get_spots_by_filter([ ('item:id', item_id), ('extended...
3,202
1,039
#Scraper for Minnesota Court of Appeals Published Opinions #CourtID: minnctapp #Court Short Name: MN #Author: mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state import minn class Site(minn.Site): # Only subclasses minn for the _download method. def __init__(self, *args, **kwargs): s...
458
169
from __future__ import absolute_import import os import errno from contextlib import contextmanager __author__ = 'Shyue Ping Ong' __copyright__ = 'Copyright 2013, The Materials Project' __version__ = '0.1' __maintainer__ = 'Shyue Ping Ong' __email__ = 'ongsp@ucsd.edu' __date__ = '1/24/14' @contextmanager def cd(pa...
1,223
401
import sys REQUIRED_PYTHON = "python3" required_major = 3 def main(): system_major = sys.version_info.major if system_major != required_major: raise TypeError( f"This project requires Python {required_major}." f" Found: Python {sys.version}") else: print(">>> ...
405
124
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] # snippet-sourcedescription:[kda-python-datagenerator-stockticker.py demonstrates how to generate sample data for Amazon Kinesis Data Analytics SQL applications.] # snippet-service:[kinesisanalytics] # snippet-keyword:[Python] # sn...
1,845
595
import face_recognition from flask import Flask, request, redirect, Response import camera import firestore as db # You can change this to any folder on your system ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'} app = Flask(__name__) def allowed_file(filename): return '.' in filename and \ filename....
2,347
765
import numpy as np import logging import numbers import torch import math import json import sys from torch.optim.lr_scheduler import LambdaLR from torchvision.transforms.functional import pad class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): sel...
5,672
1,954
import pytest from tests.pylint_plugins.utils import create_message, extract_node, skip_if_pylint_unavailable pytestmark = skip_if_pylint_unavailable() @pytest.fixture(scope="module") def test_case(): import pylint.testutils from pylint_plugins import AssertRaisesWithoutMsg class TestAssertRaisesWithou...
992
326
import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.colors import csv from scipy.stats import mode import math as m import os import collections #set working directory #os.chdir("/mnt/ix1/Projects/M002_131217_gastric/P00526/P00526_WG10_15072...
5,088
2,111
def get_index_different_char(chars): alnum = [] not_alnum = [] for index, char in enumerate(chars): if str(char).isalnum(): alnum.append(index) else: not_alnum.append(index) result = alnum[0] if len(alnum) < len(not_alnum) else not_alnum[0] return result ...
821
327
import logging from flask import Blueprint from flask import Flask, render_template, request, flash from flask_wtf import FlaskForm from wtforms import StringField, validators, SelectField, BooleanField from wtforms.fields.html5 import IntegerRangeField from wtforms.widgets import TextArea import langid from utils.u...
2,917
935
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RXts(RPackage): """Provide for uniform handling of R's different time-based data classes b...
962
417
# Copyright (C) July 2018: TF TECH NV in Belgium see https://www.threefold.tech/ # In case TF TECH NV ceases to exist (e.g. because of bankruptcy) # then Incubaid NV also in Belgium will get the Copyright & Authorship for all changes made since July 2018 # and the license will automatically become Apache v2 for al...
11,421
3,233
import utils as utl import error_measures as err # Regression Tree Node class Node: def __init__(self, parent, node_id, index=None, value=None, examples=None, prediction=0): self.index = index self.id = node_id self.prediction = prediction self.value = value self.parent = pa...
2,589
825
from starlette.applications import Starlette from starlette.middleware.gzip import GZipMiddleware from starlette.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles app = Starlette(debug=False, template_directory='src/site/templates') app.add_middleware(GZipMiddleware, minimum_size=500)...
454
140
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ Contains core logic for Rainman2 """ __author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)' __date__ = 'Wednesday, February 14th 2018, 11:42:09 am'
225
113
""" BespokeFit Creating bespoke parameters for individual molecules. """ import logging import sys from ._version import get_versions versions = get_versions() __version__ = versions["version"] __git_revision__ = versions["full-revisionid"] del get_versions, versions # Silence verbose messages when running the CLI ...
717
215
# -*- coding: utf-8 -*- """ Created on Tue Apr 03 11:06:37 2018 @author: vmg """ import sdf import numpy as np # Load 2006 LUT for interpolation # 2006 Groeneveld Look-Up Table as presented in # "2006 CHF Look-Up Table", Nuclear Engineering and Design 237, pp. 190-1922. # This file requires the file 2006LUTdata.tx...
1,810
950
import unittest from pathlib import Path from pprint import pprint from vint.compat.itertools import zip_longest from vint.linting.linter import Linter from vint.linting.config.config_default_source import ConfigDefaultSource class PolicyAssertion(unittest.TestCase): class StubPolicySet(object): def __ini...
2,836
804
import copy import json import logging import os import sys import time from collections import defaultdict import numpy as np import tensorflow as tf from sklearn import decomposition from .. import dp_logging from . import labeler_utils from .base_model import AutoSubRegistrationMeta, BaseModel, BaseTrainableModel ...
39,902
11,206
# -*- coding: utf-8 -*- # # 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 licenses this file # to you under the Apache License, Version 2.0 (the #...
6,031
2,016
#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2021 Aaron Dewes <aaron.dewes@protonmail.com> # # SPDX-License-Identifier: MIT import stat import tempfile import threading from typing import List from sys import argv import os import requests import shutil import json import yaml import subprocess from lib.composeg...
12,255
3,867
from query.base import BaseQuery class CommitMetaQuery(BaseQuery): table_name = 'commit_meta' class DiffusionFeaturesQuery(BaseQuery): table_name = 'diffusion_features' class SizeFeaturesQuery(BaseQuery): table_name = 'size_features' class PurposeFeaturesQuery(BaseQuery): table_name = 'purpose_f...
2,814
890
from kim import Mapper, field from example.models import Planet, Character class PlanetMapper(Mapper): __type__ = Planet id = field.Integer(read_only=True) name = field.String() description = field.String() created_at = field.DateTime(read_only=True) class CharacterMapper(Mapper): __type...
449
140
# Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # Based on chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com> # Based on func.py # (c) 2014, Michael Scherer <misc@zarb.org> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt...
3,660
1,211
from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ from servers.models import Compute from create.models import Flavor from instance.models import Instance from libvirt import l...
5,074
1,253
import torch __author__ = 'Andres' def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") batch_size = real_data.size()[0] alpha = torch.rand(batch_size, 1, 1, 1) alpha = alpha.expand(real_data.size()).to(devi...
886
307
import a_file def test_a(capsys): assert a_file.bla() == 5 assert a_file.LOG_MESSAGE in capsys.readouterr().err
121
50
import streamlit as st from ui.session_state import SessionState, get_state from infer import ModelStage def show(state: SessionState): st.header("identify") state = get_state() if state.model.stage < ModelStage.DEFINED: st.error("Please create the model first!")
286
84
''' MIT License Copyright (c) 2020 Rashid Lafraie Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
4,075
1,321