text
string
size
int64
token_count
int64
import numpy as np import math from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer,Dense, Activation import tensorflow.keras as keras# as k import tensorflow as t from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam,SGD from tensorflow.linalg impor...
2,269
865
# -*- coding: utf-8 -*- import glob import re import os import numpy as np from keras.engine import Model from keras.preprocessing.image import img_to_array, load_img from keras.utils import plot_model from keras_vggface.vggface import VGGFace from keras_vggface import utils layer_list = ['flatten', 'fc6', 'fc6/relu',...
1,778
702
#!/usr/bin/python3 import sys import argparse import random import operator import pickle import torch from torch.optim.lr_scheduler import StepLR sys.path.insert(0,'.') from PyRNN.Data import Data from PyRNN.RNNTagger import RNNTagger from PyRNN.CRFTagger import CRFTagger def build_optimizer(optim, model, learning...
9,662
3,038
import threading import unittest from blatann.gap.advertise_data import AdvertisingData, AdvertisingFlags from blatann.gap.advertising import AdvertisingMode from blatann.gap.scanning import ScanReport, Scanner from blatann.utils import Stopwatch from tests.integrated.base import BlatannTestCase, TestParams, ...
4,281
1,452
#!/usr/bin/env python3 # Software Name: ngsildclient # SPDX-FileCopyrightText: Copyright (c) 2021 Orange # SPDX-License-Identifier: Apache 2.0 # # This software is distributed under the Apache 2.0; # see the NOTICE file for more details. # # Author: Fabien BATTELLO <fabien.battello@orange.com> et al. import http.clie...
1,892
694
#!/usr/bin/env python """Test creation of GoSubDag's rcntobj data member.""" from __future__ import print_function __copyright__ = "Copyright (C) 2016-2018, DV Klopfenstein, H Tang. All rights reserved." __author__ = "DV Klopfenstein" import os from goatools.base import get_godag from goatools.gosubdag.gosubdag impo...
3,513
1,556
from .chain_ops import ChainOps from .transmogrifier import Transmogrifier, Murinizer
86
30
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """This module creates the flask app to shuffle users App must be here because flask explodes if you move to subdir""" __Lisence__ = "BSD" __maintainer__ = "Justin Furuness" __email__ = "jfuruness@gmail.com" __status__ = "Development" import pkg_resources from flasgge...
5,078
1,696
import cvxpy import numpy as np class Control: def __init__(self, model): # Bind model self.model = model # Desired x_pos self.xd = 0.0 # Control parameters self.N = 100 # Control limits self.umax = np.reshape...
2,882
1,178
from maestrowf import __version__ from setuptools import setup, find_packages setup( name='maestrowf', description='A tool to easily orchestrate general computational workflows ' 'both locally and on supercomputers.', version=__version__, author='Francesco Di Natale', maintainer='Francesco Di Natale', au...
1,466
514
AMR_SOURCES = [ "(w / want-01 :ARG0 (b / boy) :ARG1 (g / go-01 :ARG0 b))" ] AMR_TARGETS = [ "The boy wants to go." ] AMR_NOISED = { "convert-to-triples": { "src": "order Graph: ( want :ARG0 ( boy ) :ARG1 ( go :ARG0 boy ) )", "tgt": "<t> want :ARG0 boy <t> want :ARG1 go <t> go :ARG0 boy" }, "generate-fr...
8,531
3,982
######################################用户组###################################### from rest_framework.generics import ListAPIView from rest_framework.viewsets import ModelViewSet from django.contrib.auth.models import Group, Permission from apps.meiduo_admin.utils import PageNumber from apps.meiduo_admin.serializer.gro...
674
171
from aclpwn import utils, database # Cost map for relationships costmap = { 'MemberOf': 0, 'AddMember': 1, 'GenericAll': 1, 'GenericWrite': 1, 'WriteOwner': 3, 'WriteDacl': 2, 'DCSync': 0, 'Owns': 2, 'GetChangesAll': 0, 'GetChanges': 0, 'AllExtendedRights': 2 } def dijkst...
5,211
1,813
import os import json import numpy as np import pandas as pd import gzip import argparse from collections import Counter def load_mixed_corpus(): grocery_file = '../dat/reviews_Grocery_and_Gourmet_Food_5.json' office_file = '../dat/reviews_Office_Products_5.json' doc_groc, _ = load_amazon(grocery_file, 5000, 'revi...
6,343
2,544
from datetime import datetime from typing import List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from app.api.utils.db import clone_db_model from app.db_models.address import Address from app.models.address import EditAddress, UserAddress def add_user_address( db_session: S...
2,396
750
#!/usr/bin/env python # -*- coding: utf-8 -*- """Advanced Specific Multiple Instruments This example shows how to use specific channels ID and multiple connected instruments Requires at least two Fluigent pressure channels Copyright (c) Fluigent 2019. All Rights Reserved. """ # Print function for Python 2 compatibi...
2,493
723
"""This script iterates over all decorations in a .ini database and set their Specialart field to the format expected by the SpecialEffect system. """ from myconfigparser import MyConfigParser, load_unit_data, get_decorations, Section dataBase = '../development/table/unit.ini' def configure_decorations(unit_data, dec...
875
272
# 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 # "License"); you may not u...
7,906
2,276
import click from gradient.cli import common from gradient.cli.cli import cli from gradient.commands import tensorboards as tensorboards_commands @cli.group("tensorboards", help="Manage tensorboards", cls=common.ClickGroup) def tensorboards_group(): pass @tensorboards_group.command("create", help="Create new t...
4,135
1,360
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.db.models.aggregates import Min from services.models import (Service, SlaDaily, SlaCache, ServiceHistory) from ...
5,430
1,767
# -*- coding: utf-8 -*- # # Copyright (C) 2020 CERN. # # Flask-Resources is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """JSON Deserializer.""" import json from .deserializers import DeserializerMixin class JSONDeserializer(Deser...
521
181
# TensorFlow and tf.keras import tensorflow as tf # Helper libraries import numpy as np import matplotlib.pyplot as plt from cvnn import layers print(tf.__version__) def get_fashion_mnist_dataset(): fashion_mnist = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fas...
2,960
1,056
from . import _version_check name = 'PyTorch'
47
18
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ms2ldaviz.settings_simon") import django django.setup() from basicviz.models import Experiment,Document from decomposition.models import FeatureSet,MotifSet,GlobalMotif,GlobalMotifsToSets,Decomposition,DocumentGlobalMass2Motif if __name__ == '__main__': # f...
1,905
716
#!/usr/bin/env python3 HELLO_MSG = """Welcome to the SG Blood Stocks Bot! We update you on the blood stock levels of the Singapore Red Cross. You can subscribe (/subscribe) to updates for specific blood types so you know when to donate. You can check for the latest change (/changes) in blood stock levels over the p...
1,133
383
from typing import List, Dict from aocpy import BaseChallenge def parse(instr: str) -> List[int]: return list(map(int, instr.strip().split(","))) def count_fish_by_timer(all_fish: List[int]) -> Dict[int, int]: m = {} for fish in all_fish: m[fish] = m.get(fish, 0) + 1 return m def iterate_f...
1,064
438
""" This is the qmspy module, a python module designed to automate graphing data collected from a QMS. Contains the following functions: init_data add_style fit_gaussians appearance_energy Contains the following submodules: graph_data A...
633
168
class NoReaderWriterError(ValueError): """Exception raised when a valid Reader or Writer could not be found for the file""" pass class InvalidTemporalResError(ValueError): """Exception raised when a file has a temporal resolution which cannot be processed""" pass
284
73
from django.conf.urls import patterns, include, url from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse, reverse_lazy from django.views.generic import ListView, DetailView, UpdateView, CreateView from django_dhcp.models import NetworkNode urlpatterns = patterns('', ...
1,569
394
# -*- coding: utf-8 -*- # Copyright (c) 2016 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 ...
2,073
707
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.BoxExclusiveBase import BoxExclusiveBase from alipay.aop.api.domain.BoxOrderStatusInfo import BoxOrderStatusInfo from alipay.aop.api.domain.BoxExclusiveKeyword import BoxExclusiveKe...
8,604
2,578
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ---------- from abc import abstractmethod import inspect from .common import LifeTime, IServiceProvider, IDescriptor, ICallSiteMaker from .param_type_resolver import ParameterTypeResolver from .err...
4,921
1,328
"""The module helps define the q learning dictionary""" __author__ = "Guilherme Varela" __date__ = "2019-07-25" from itertools import product as prod def dpq_tls(state_rank, state_dim, action_rank, action_dim, initial_value=0): """Prepares a dynamic programming Q-learning table for a traffic ligh...
2,666
838
def countRectangles(r): d = 2*r dSq = d*d rectangles = 0 for i in range(1,d): for j in range(1,d): if i**2+j**2 <= dSq: rectangles += 1 return rectangles t = int(input()) for _ in range(t): r = int(input()) print(countRectangles(r))
296
114
from django.db import models from slugify import slugify class Tag(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=128, unique=True) tag = models.CharField(max_length=128) def save(self, force_insert=False, force_update=False): self.slug = slugify(sel...
546
181
##遍历指定path下所有文件,并将文件名d重命名为name import os path = './Image' for (root,dirs,files) in os.walk(path) : for item in files : Olddir = os.path.join(root, item) filename=os.path.split(Olddir)[0] #文件名 filetype=os.path.split(Olddir)[1][-4:] #文件扩展名 Newdir=os.path.join(path,str(coun...
392
171
import csv import os from multiprocessing import Manager from multiprocessing import Process ####### must import the packet in scapy in order to see the results ####### from scapy import * from scapy.layers import * from scapy.layers.dns import * from scapy.layers.inet import * from scapy.utils import PcapReader from...
6,833
1,988
''' This scripts define functions that will be used by the different notebooks to analyse the results ''' import pandas as pd from plotly import tools import plotly.graph_objs as go def predecessor_generation(results, curr_generation, verbose): ''' Print the predecessor's generation for all the models in a spe...
3,988
1,189
"""Add Document URI and Meta document_id index Revision ID: 77c2af032aca Revises: f3b8e76ae9f5 Create Date: 2016-05-13 15:06:55.496502 """ # revision identifiers, used by Alembic. revision = "77c2af032aca" down_revision = "f3b8e76ae9f5" from alembic import op import sqlalchemy as sa def upgrade(): op.execute(...
817
320
import os import sys import time import inspect import traceback import itertools import random import yaml from twisted.python import reflect, usage from twisted.internet import defer from twisted.trial.runner import filenameToModule from twisted.internet import reactor, threads from txtorcon import TorProtocolFact...
19,526
5,834
import os import subprocess import numpy as np import pandas as pd import matplotlib.pyplot as plt import argparse import seaborn as sns # I love this package! sns.set_style('white') import torch from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve import scipy.stats as stats def plot_roc(attr, target...
4,410
1,447
# Copyright 2017 Google 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 wri...
6,071
1,974
from django.apps import AppConfig class UrlOrRelativeUrlFieldConfig(AppConfig): name = 'url_or_relative_url_field'
121
39
import ubelt as ub from graphid import demo from graphid.core.state import (POSTV, NEGTV, INCMP, UNREV) def test_incomp_inference(): infr = demo.demodata_infr(num_pccs=0) # Make 2 consistent and 2 inconsistent CCs infr.add_feedback(( 1, 2), POSTV) infr.add_feedback(( 2, 3), POSTV) infr...
4,877
2,290
import os import unittest from pprint import pprint import anago from anago.config import ModelConfig from anago.models import SeqLabeling from anago.preprocess import WordPreprocessor SAVE_ROOT = os.path.join(os.path.dirname(__file__), 'models') class TaggerTest(unittest.TestCase): def setUp(self): p ...
1,565
548
''' Created on 12.04.2018 @author: hm ''' import os import time from unittest.UnitTestCase import UnitTestCase import base.MemoryLogger import base.JobController import base.StringUtils DEBUG = False class TestJobController (base.JobController.JobController): def __init__(self, logger): base.JobControll...
1,858
565
# Stub script for converting XML input values into command line parameters and writing out # and XML file. # # This script expects two parameters, as a specific: # --xml_system_configuration=input_filename.xml # --xml_system_metrics=output_filename.xml # # @author Sivieri Alessandro, Vittorio Zaccaria (2010/20...
3,308
1,328
from flask import Blueprint, request from services import account from functools import wraps from status import finish auth = Blueprint('auth', __name__, url_prefix='/auth') def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): token = request.form.get('token', request.args.get('token', N...
1,059
314
from argparse import ArgumentParser DEFAULT_pH = 7.5 DEFAULT_pMg = 3.0 DEFAULT_ionic_strength = 0.25 def add_arguments(parser: ArgumentParser) -> ArgumentParser: # positional arguments parser.add_argument('infile', type=str, help='pathway as rpSBML file') parser.add_argument('outfile', type=str, hel...
768
254
from pyspark.ml.clustering import BisectingKMeans, BisectingKMeansModel from utils import channelInfo from utils import MovieDataApp class BkmeansCossim(object): def __init__(self, spark, database, group=0, recall_topK=50, k=100, minDCS=200, seed=10, channel='电影'): """ :param group: int 计算第几组聚类...
7,829
2,823
from .base import * MAX_TEX_SIZE = 4000 # TODO: make user-configurable class ScrollThumb(Widget): def __init__(self, parent, pane, gfx_ids, cull_bin, scroll_dir, inner_border_id): Widget.__init__(self, "scrollthumb", parent, gfx_ids, "normal") self._pane = pane self.direction = scroll...
32,138
10,647
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ######################################################## # PalGate Token Extraction Tool # ######################################################## # # # Like my work? please consider buying me a ...
4,561
1,253
import os import ArrayUtils import GoogleMetadataUtils from objects.ExportedObject import ExportedObject from objects.Image import Image counter = 0 def directory_walk(start_path, extension): to_return = [] for (dirpath, dirnames, filenames) in os.walk(start_path): for filename in filenames: ...
3,335
910
from rest_framework.serializers import ModelSerializer from foodcartapp.models import Order, OrderProduct class OrderProductSerializer(ModelSerializer): class Meta: model = OrderProduct fields = ['id', 'product', 'quantity'] class OrderSerializer(ModelSerializer): products = OrderProductSer...
501
131
R=float(input()) PI=3.14159 A=(PI)*(R**2) print("A = {:.4f}".format(A))
71
42
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User from funcionario.forms import FuncionarioForm from configuracao.models import Configuracao def funcionario_eliminar(request, username = None): user = User....
882
289
# https://raw.githubusercontent.com/crux82/ganbert-pytorch/main/GANBERT_pytorch.ipynb # [WIP], not finished import torch from torch.nn import Dropout, LeakyReLU, Linear, Module, Sequential from transformers import AutoModel class Generator(Module): def __init__( self, noise_size=100, output_size=768, hidd...
2,658
889
#!/usr/bin/env python # encoding: 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 Licens...
2,571
739
levels = [ [ # W = Muro, E = Meta, P = Jugador 1, J = Jugador 2, H = Jugador 3, I = Jugador 4, "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW", "W W", "W J W", "W P W", "W W", "W W", "W ...
2,270
833
import praw import pandas as pd import reddit_constants class RedditClient(object): __shared_instance = "RedditClient" @staticmethod def get_instance(): """ To implement singleton pattern """ if RedditClient.__shared_instance == "RedditClient": RedditClient() ...
1,761
522
from apps.config.services.serviceConfService import ServiceConfService from django.shortcuts import HttpResponse import json def getServiceConf(request): serviceConf = ServiceConfService.queryServiceConfSort(request) return HttpResponse(json.dumps(serviceConf))
272
69
#!/usr/bin/python3 # Gets all files below where this script is run, and checks to see if any contain # the specified keywords. A report is generated at the end. # # Files with certain extensions are excluded, and directories with certain names are excluded. # # The actual keywords are kept in a separate file so...
2,436
759
import argparse from fnmatch import fnmatch import os.path import re import sys from ii_irods.coll_utils import resolve_base_path, convert_to_absolute_path, get_dataobjects_in_collection from ii_irods.coll_utils import get_direct_subcollections, get_subcollections, collection_exists from ii_irods.do_utils import get_d...
19,020
5,148
import unittest import pandas from pyarxaas.models.attribute_type import AttributeType from pyarxaas.models.dataset import Dataset from tests.pyarxaas import data_generator class DatasetTest(unittest.TestCase): def setUp(self): self.test_data = [['id', 'name'], ['0', 'Viktor']...
6,998
2,268
import random import matplotlib.pyplot as plt import numpy as np import torch from perception.utils.segmentation_labels import CARLA_CLASSES, DEFAULT_CLASSES def get_segmentation_colors(n_classes, only_random=False, class_indxs=None, color_seed=73): assert only_random or class_indxs random.seed(color_seed) ...
6,955
2,383
# -*- coding: utf-8 -*- #VERSION: 1.2 #AUTHORS: Joost Bremmer (toost.b@gmail.com) # # This program 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...
7,214
2,033
class StackOfPlates: def __init__(self, cap: int): self.stack = [] self.cap = cap def push(self, val: int) -> None: if len(self.stack) == 0 or len(self.stack[-1]) >= self.cap: self.stack.append([]) last = self.stack[-1] last.append(val) def pop(self) -> int: while len(self.stack) ...
806
304
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/goal.ui' # # Created by: PyQt5 UI code generator 5.8.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_GoalBody(object): def setupUi(self, GoalBody): GoalBody.set...
3,580
1,106
import torch torch.backends.cudnn.benchmark = True from trainer.base_audio_trainer import BaseAudioTrainer from logger.new_callbacks import Callbacks from torch.utils.data import DataLoader from dataloader.audio_dataset import AudioDataset from torch.optim.lr_scheduler import CosineAnnealingLR from models.audio_mode...
8,342
2,796
from .sine import * from .cose import * from .tane import * from .tanhe import * from .ee import * from .loge import * from .sigmoide import * from .relue import * from .softmaxe import * __all__= (sine.__all__+ cose.__all__ + tane.__all__ + tanhe.__all__ + ee.__all__ + loge.__all__ + sigmoide.__all__ + relu...
355
142
nome = str(input('Qual é seu nome?')).upper().capitalize() print('prazer em conhecelo, \033[1;34m{}\033[m!'.format(nome))
121
54
#! /usr/bin/python3.7 import argparse from viromatch.lib.taxonomy import Taxonomy import os version = '1.0' def eval_cli_arguments(): parser = argparse.ArgumentParser( description='Resolve lineage given taxid.', prog='taxid2lineage.py', add_help=False ) # Optional arguments. ...
1,881
578
from typing import Optional import aiosqlite from aiogram.dispatcher.middlewares import BaseMiddleware import config class OsuDb: def __init__(self, path: str = config.ASSET_PATH / 'osu.db'): self._conn = aiosqlite.connect(path) async def connect(self): self._conn = await self._conn ...
2,779
826
# Copyright (c) 2019 Intel Corporation. All rights reserved. # # GNU General Public License v3.0+ # (see LICENSE.GPL or https://www.gnu.org/licenses/gpl-3.0.txt) # # Authors: # - Igor D.C. - <igor.duarte.cardoso@intel.com> # - Marco Chiappero - <marco.chiappero@intel.com> ###########################################...
8,423
2,305
# -*- coding: utf-8 -*- __all__ = ('DockerDaemon',) from types import TracebackType from typing import Any, Mapping, Optional, Type from loguru import logger import attr import docker from .container import Container @attr.s(frozen=True) class DockerDaemon: """Maintains a connection to a Docker daemon.""" ...
5,309
1,285
"""this module finds areas of image, it first finds edges in picture's pixel area. then it makes contours of those edges, and draws biggest contours""" import cv2 import numpy as np from matplotlib import pyplot as plt def smartSelectFunc(filepath): #load image to analyze img = cv2.imread(filepath,0) #fin...
1,606
564
# Copyright (c) 2018-2020, Texas Instruments # All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of condition...
2,465
913
print('hello world!') a = "cat dog fish monkey".split() for animal in a: print(animal)
93
35
# from distutils.command.upload import upload # import email # from email.policy import default # from unicodedata import name import email import uuid from django.db import models from django.contrib.auth.models import User # from django.db.models.signals import post_save,post_delete # from django.dispatch import rec...
1,391
432
import json from datetime import timedelta from django.utils import timezone from rest_framework import serializers import tweepy from .models import * # Get secrets and create the API instance secrets = open("./babar_twitter/SECRETS.json", 'r') keychain = json.load(secrets) secrets.close() twitter_auth = tweepy.OAut...
1,438
409
from typing import Dict, Tuple INSTRUCTIONS: Dict[str, Tuple[str, str, str, int]] = { "nop": ("", "", "", 0x00), "mov": ("r", "", "rc", 0x01), "add": ("r", "r", "rc", 0x02), "sub": ("r", "r", "rc", 0x03), "mul": ("r", "r", "rc", 0x04), "div": ("r", "r", "rc", 0x05), "xor": ("r", "r", "rc", ...
1,579
855
import sys from ingenialink.canopen.net import Network, CAN_DEVICE def run_example(): net = None try: net = Network(device=CAN_DEVICE.PCAN) nodes = net.detect_nodes() net.scan('canopen_0.2.1.eds', 'registers_dictionary_canopen.xdf') drives_connected = net.servos if len(...
1,105
320
from __future__ import print_function import matplotlib.pyplot as plt import matplotlib.colors as plt_colors import numpy as np import scipy.io import scipy.stats from rnmu.pme.point import Point from rnmu.pme.line import Line import rnmu.pme.stats as stats def plot_soft_point(ax, point, sigma, box, n_levels=64, colo...
5,051
2,032
import os import collections from functools import reduce import yaml from tf.lib import writeSets HERE_BASE = "." DROPBOX_BASE = "~/Dropbox/obb" SET_NAME = "sets.tfx" MODULE = "pos" TF_LOC = f"{MODULE}/tf" def getCases(caseStr): caseLines = caseStr.strip().split("\n") result = {} for caseLine in case...
17,456
5,548
# -*- coding: utf-8 -*- import click from tcfcli.cmds.native.common.start_api_context import StartApiContext from tcfcli.help.message import NativeHelp as help DEF_TMP_FILENAME = "template.yaml" @click.command(name='start-api', short_help=help.START_API_SHORT_HElP) @click.option('--env-vars', '-n', help='JSON file ...
1,613
485
from modtpy.api.modt import ModT, Mode from modtpy.api.errors import PrinterError import logging from contextlib import contextmanager def dummy_device_function(f): def __inner__(self, *args, **kwargs): logging.info("Device.%s called with args: %s, kwargs: %s", f.__name__, str(args), str(kwargs)) ...
1,905
588
from torch.nn.functional import relu, softmax, sigmoid from transformers import BertModel import torch.nn as nn class BERTClassifier(nn.Module): def __init__(self, n_classes, pretrained_bert_model): super(BERTClassifier, self).__init__() self.bert = BertModel.from_pretrained(pretrained_bert_model) self....
712
254
from typing import Type from django.db.migrations.operations.base import Operation from django.db.models import Model class AddAuditOperation(Operation): reduces_to_sql = True reversible = True enabled = True def __init__(self, model_name, audit_rows=True, audit_text=False, excluded=('created', 'mod...
3,095
887
"""272. Climbing Stairs II """ class Solution: """ @param n: An integer @return: An Integer """ def climbStairs2(self, n): # write your code here if n == 0: ## 0 is 1 step return 1 if n <= 2: return n last_two_step = 1 last_step = 1 ...
484
168
import argparse import json import torch import torch.nn.functional as F from torch.utils.tensorboard.writer import SummaryWriter from ignite.engine import Events, Engine from ignite.metrics import Accuracy, Average, Loss from ignite.contrib.handlers import ProgressBar from gpytorch.mlls import VariationalELBO from ...
9,791
3,298
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'gui4.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, ...
14,583
5,193
from PIL import Image import os import numpy as np import torch import torch.utils.data as data class CIFAR10_C(object): def __init__(self, path, levels=[1,2,3,4,5]): path = os.path.expanduser(path) self.path = path self.levels = levels files = os.listdir(path) datasets = [...
2,032
656
import os from typing import Callable import torch from torch import nn from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence from overrides import overrides from entities.metric import Metric from entities.batch_representation import BatchRepresentation from entities.options.embedding_layer_optio...
3,544
1,020
class deleting_folder: def __init__(self, input_folder='path', ignore_errors=False): import shutil shutil.rmtree(input_folder, ignore_errors=ignore_errors) ############################################################################## class deleting_file: def __init__(self, input_file='path...
990
260
import argparse parser = argparse.ArgumentParser(description='oled arguments') parser.add_argument( '--port', '-p', type=int, default=0, help='i2c bus number', ) parser.add_argument( '--parameter', '-t', type=str, default='', help='parameter to display', ) parser.add_argument( '--va...
834
300
import pytest from numpy.testing import assert_allclose import numpy as np from alphacsc.tests.conftest import N_CHANNELS, N_TIMES_ATOM, N_ATOMS from alphacsc.update_d_multi import prox_d, prox_uv from alphacsc._d_solver import get_solver_d, check_solver_and_constraints from alphacsc._z_encoder import get_z_encoder_...
12,864
4,401
import pandas as pd import datetime import numpy as np import json from app import artifacts_dict as artifacts from app.utils import get_time_now, get_time_sin_cos class InferencePipeline(): """Pipeline to receive data_dict and transform for inference. --------- Parameters: data_dict: from the reque...
1,931
575
# -*- coding: UTF-8 -*- from setuptools import setup # http://stackoverflow.com/a/7071358/735926 import re VERSIONFILE = 'wpydumps/__init__.py' verstrline = open(VERSIONFILE, 'rt').read() VSRE = r'^__version__\s+=\s+[\'"]([^\'"]+)[\'"]' mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: ...
1,054
380
"""Test against the builders in the op.* module.""" from sqlalchemy import Column from sqlalchemy import event from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy import Table from sqlalchemy.sql import text from ...testing.fixtures import AlterColRoundTripFixture from ...testing.fixtures imp...
1,343
441
# <<BEGIN-copyright>> # Copyright 2021, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause # <<END-copyright>> """ This module contains the XYsnd classes for n > 1. """ __metaclass__ = type """ Missing methods copyDataToGridWsAn...
36,617
10,148