id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
418699 | import torch
import torch.nn as nn
# Discriminator Model
class Dis28x28(nn.Module):
def __init__(self):
super(Dis28x28, self).__init__()
self.model = nn.Sequential(
nn.Conv2d(1, 20, kernel_size=5, stride=1, padding=0),
nn.MaxPool2d(kernel_size=2),
nn.Conv2d(20, ... |
418706 | import threading
from typing import Callable
import paramiko
import requests
from decorator import decorator
from sshtunnel import SSHTunnelForwarder
from logger import logger
from perfrunner.helpers.misc import uhex
from perfrunner.helpers.rest import RestHelper
from perfrunner.settings import ClusterSpec, TestConfi... |
418737 | class Reporter():
def __init__(self, checker):
pass
def doReport(self):
pass
def appendMsg(self):
pass
def export(self):
pass
|
418741 | from django.urls import path
from .views import (
CreateEventView,
EventDetailView,
QrEventListView,
RegisterTicketsView,
ScanTicketView,
UpdateTicketsView,
render_ticket,
)
urlpatterns = [
path("", QrEventListView.as_view(), name="qr-event-list"),
path("detail/<int:pk>/", EventDet... |
418762 | from localstack.services.cloudformation.service_models import GenericBaseModel
from localstack.utils.aws import aws_stack
from localstack.utils.common import select_attributes
class Route53RecordSet(GenericBaseModel):
@staticmethod
def cloudformation_type():
return "AWS::Route53::RecordSet"
def g... |
418816 | from typing import Any
from django_filters import rest_framework as filters
from rest_framework import status
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.permissions import AllowAny, IsAuthenticatedOrReadOnly
from rest_framework.request import Request
from re... |
418845 | from __future__ import absolute_import
__all__ = ['ProviderNotRegistered']
class ProviderNotRegistered(Exception):
pass
class IdentityNotValid(Exception):
pass
|
418846 | import os
from helpers import parameters as params
configReader = params.GetConfigReader()
name = 'bamgineer'
def GetBamgineerMem(mem_type):
"""returns specified value from the configuration file"""
mem_string = 'bamgineer_mem_' + mem_type
return configReader.get('CLUSTER', mem_string)
def GetExons():
... |
418862 | import datetime
import os
import urllib2
import urllib
import numpy
import json
from django.shortcuts import render
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect
from django.shortcuts import render_to_response
... |
418863 | import requests
from bs4 import BeautifulSoup
import os
import fleep
from magic import magic
def down(name, tag):
a = tag.select('a')
if a:
url = a[0].get('href')
down_res = requests.get(url=url)
mime = magic.from_buffer(down_res.content[0:2048], mime=True)
# for... |
418870 | import os
from utils.opencv_face_detector import detect_face
def gen_labels(images_path, label_file_path):
label_file_path_format2 = label_file_path + '.format2'
if not os.path.exists(label_file_path):
label_file = open(label_file_path, 'w')
label_file_format2 = open(label_file_path_format2, '... |
418886 | import sys
import argparse
import hashlib
import time
prefix = ["cam", "video", "x", "a", "www", "ftp", "ssl", "tftp", "www1",
"www2", "noc", "smtp", "pop", "ssl", "secure", "images", "th",
"img", "download", "mail", "remote", "blog", "webmail", "server",
"ns1", "vpn", "m", "shop", ... |
418956 | import csv
import tempfile
from django.conf import settings
from django.core.management import call_command
from django.test.utils import override_settings
from frontend import bq_schemas as schemas
from gcutils.bigquery import Client
def import_test_data_full(directory, data_factory, end_date, months=None):
""... |
418958 | from numpy import (
allclose,
isnan
)
from . import pwm
def test_create():
m = pwm.FrequencyMatrix.from_rows(['A', 'C', 'G', 'T'], get_ctcf_rows())
# Alphabet sort
assert m.sorted_alphabet == ['A', 'C', 'G', 'T']
# Character to index mapping
assert m.char_to_index[ord('A')] == 0
asser... |
418994 | for row in range(4):
for col in range(7):
if row-col==0 or row+col==6:
print('*',end=' ')
else:
print(' ',end=' ')
print()
## Method -2
i =0
j = 6
for row in range(4):
for col in range(7):
if row==col:
print('*',end=' ')
elif row... |
419056 | import numpy as np
__all__ = ['formatter']
def formatter(prop_keys, fmt = '%.6e', base = '', default = '%.6e'):
"""
Formatter function for a given set of properties.
Parameters
----------
fmt : str or dict, optional
If str: Format string for all the columns. Defaults to '%.6e'.\n
... |
419103 | from threading import Thread
import time
class Observable(object):
def __init__(self):
self._observers = set()
def add_observer(self, observer):
self._observers.add(observer)
def remove_observer(self, observer):
self._observers.remove(observer)
def notify_observers(self, eve... |
419134 | from mockseries.interaction.additive_interaction import AdditiveInteraction
from mockseries.interaction.multiplicative_interaction import MultiplicativeInteraction
ADDITIVE = AdditiveInteraction()
MULTIPLICATIVE = MultiplicativeInteraction()
|
419140 | import numpy as np
import scipy.sparse as sparse
from scipy.sparse import vstack, hstack
from scipy.sparse.linalg import inv
from sklearn.utils.extmath import randomized_svd
from utils.progress import WorkSplitter, inhour
import time
def pop(matrix_train, **unused):
"""
Function used to achieve generalized pr... |
419144 | import winbrewtest
import winbrew.execute
class MockArgs(object):
force = False
class InstallPlanTest(winbrewtest.TestCase):
def test_dependencies(self):
formula = winbrew.Formula.formula_by_name('sfml')()
plan = winbrew.execute.InstallPlan([formula], MockArgs())
plan = [p.name for p... |
419190 | import logging
from flask import (
g, request, abort, render_template, url_for, redirect, flash)
from flask_login import login_required
from piecrust.page import Page
from piecrust.sources.interfaces import IInteractiveSource
from piecrust.uriutil import split_uri
from ..blueprint import foodtruck_bp
from ..views i... |
419198 | from __future__ import unicode_literals
from pyramid.settings import asbool
from pyramid.request import Request
from pyramid.decorator import reify
from pyramid.events import NewResponse
from pyramid.events import NewRequest
from pyramid.events import subscriber
from billy.models.model_factory import ModelFactory
fro... |
419199 | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.translation import ugettext as _, ugettext_lazy
from odk_viewer.models import DataDictionary
from utils.model_tools import queryset_iterator
class Command(BaseCommand):
help = ugettext_lazy("Insert UUID into XML... |
419232 | import argparse
import math
import os
import torch
import pyro
import pandas as pd
import mlflow
import mlflow.pytorch
from mlflow.tracking import MlflowClient
from experiment_tools.output_utils import get_mlflow_meta
from experiment_tools.pyro_tools import auto_seed
def evaluate_policy(
experiment_id,
run... |
419239 | import numpy as np
import numpy.random as npr
import scipy as sc
from scipy import stats
from scipy.special import logsumexp
from scipy.stats import multivariate_normal as mvn
from scipy.stats import invwishart
from sds.utils.stats import multivariate_normal_logpdf as lg_mvn
from sds.utils.general import linear_regre... |
419260 | import urllib2
import argparse
import xmlrpclib
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--resource-id', type=int, required=True)
parser.add_argument('-o', '--output', required=True)
return parser.parse_args()
def fetch(url, retries=4, timeout=5):
for i in ... |
419262 | from turtle import Turtle
class White(Turtle):
def __init__(self):
super().__init__()
self.shape("square")
self.color("white")
self.shapesize(stretch_len=30,stretch_wid=2)
self.penup()
self.goto(-0,280) |
419266 | from flask import Flask
import sys
app = Flask(__name__)
serverName = sys.argv[1]
@app.route('/')
def hello():
return serverName
if __name__ == '__main__':
app.run(port=sys.argv[2]) |
419272 | import numpy as np
import random
from toolz import partition
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit import transpile, assemble
from qiskit import BasicAer, Aer, execute
from qiskit.quantum_info import state_fidelity
from qiskit.visualization import *
from qiskit.quan... |
419283 | import os
import torch
import re
import sys
import logging
import pickle
from dataclasses import dataclass
from io import StringIO
from transformers import AutoModelWithLMHead, AutoTokenizer, PreTrainedTokenizer
from scipy import stats
from torch.nn.utils.rnn import pad_sequence
from typing import List
from torch.utils... |
419299 | from typing import Union
from pathlib import Path
from typeguard import check_argument_types
import os
import glob
from datetime import datetime
import shutil
import logging
import numpy as np
import torch
from onnxruntime.quantization import quantize_dynamic, QuantType
from espnet2.bin.asr_inference import Speech2T... |
419348 | import os
from io import open
try:
get_input = raw_input # fix for Python 2
except NameError:
get_input = input
try:
from pathlib import Path
except ImportError:
from pathlib2 import Path # Python 2 backport
def __create_dir(path):
dir_name = os.path.dirname(path)
if dir_name is not "":
... |
419388 | import datetime
import os
import re
import subprocess
import click
def abort(message, *args, **kwargs):
raise click.ClickException(message.format(*args, **kwargs))
def confirm(message, *args, **kwargs):
rv = click.prompt(message.format(*args, **kwargs), type=click.Choice(['y', 'n']))
if rv != 'y':
... |
419427 | from django.contrib.auth.models import AnonymousUser
from rest_framework import authentication
from rest_framework.authentication import TokenAuthentication
class AnonymousAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
"""
Authenticate the request for anyone!
... |
419434 | from sqlite_utils import recipes
import json
import pytest
@pytest.fixture
def dates_db(fresh_db):
fresh_db["example"].insert_all(
[
{"id": 1, "dt": "5th October 2019 12:04"},
{"id": 2, "dt": "6th October 2019 00:05:06"},
{"id": 3, "dt": ""},
{"id": 4, "dt":... |
419477 | import os
from pyats.easypy import run
# To run the job:
# pyats run job $VIRTUAL_ENV/examples/connection/job/connection_example_job.py \
# --testbed-file <your tb file>
#
# Description: This example uses a sample testbed, connects to a device
# which name is passed from the job file,
# ... |
419484 | import argparse
import json
import math
import os
import pdb
import shutil
import time
from functools import partial
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
fro... |
419500 | from NERDA.datasets import get_conll_data, get_dane_data
import pandas as pd
import torch
import boto3
def deploy_model_to_s3(model, test_set = get_dane_data('test')):
"""Deploy Model to S3
Args:
model: NERDA model.
test_set: Test set for evaluating performance.
Returns:
str: mess... |
419542 | def get_head(line, releases, **kwargs):
for release in releases:
if "Django {} release notes".format(release) in line:
return release
return False
def get_urls(releases, **kwargs):
urls = []
for release in releases:
urls.append("https://raw.githubusercontent.com/django/djan... |
419548 | import torch
import os
# DALI import
from .dali_iterator import COCOPipeline
from nvidia.dali.plugin.pytorch import DALIGenericIterator
from box_coder import dboxes300_coco
anchors_ltrb_list = dboxes300_coco()("ltrb").numpy().flatten().tolist()
def prebuild_dali_pipeline(args):
train_annotate = os.path.join(args... |
419556 | import numpy as np
import cv2
import matplotlib.pyplot as plt
def draw_boxes(img, boxes, base_color=(1, 0, 0), line_width=3):
base_color = np.array(base_color)
boxes = boxes[np.argsort(-boxes[:, 4])] # Sort in descending order of score
max_score = np.max(boxes[:, 4])
ax = plt.gca()
a... |
419561 | import numpy as np
from matplotlib import patches
import matplotlib.pyplot as plt
# Use xkcd-style figures.
plt.xkcd()
# Some settings
fs = 14
# # # (A) Figure with survey and computational domains, buffer. # # #
fig, ax = plt.subplots(1, 1, figsize=(11, 7))
# Plot domains.
dinp1 = {'fc': 'none', 'zorder'... |
419603 | PARTS = {
"1-": [
"PAI", "PAD", "PAN", "PAP", "PAS", "PAO",
"PMI", "PMD", "PMN", "PMP", "PMS", "PMO",
],
"1+": [
"IAI",
"IMI",
"IEI",
],
"2-": [
"FAI", "FAN", "FAP", "FAO",
"FMI", "FMN", "FMP", "FMO",
],
"3-": [
"AAD", "AAN", "A... |
419613 | from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from jmodt.config import cfg
from jmodt.utils import loss_utils
def model_joint_fn_decorator():
ModelReturn = namedtuple("ModelReturn", ['loss', 'tb_dict', 'disp_dict'])
MEAN_SIZE = torch.from_numpy(cfg.CLS... |
419640 | import os
import six
import functools
from os.path import join
from mock import Mock, patch
from io import BytesIO
from twisted.internet.interfaces import IReactorCore
from twisted.internet.interfaces import IListeningPort
from twisted.internet.interfaces import IStreamClientEndpoint
from twisted.internet.address impo... |
419677 | from itertools import chain
import sys
from types import SimpleNamespace as namespace
from xml.sax.saxutils import escape
from scipy.spatial import distance
import numpy as np
from AnyQt.QtWidgets import (
QFormLayout,
QApplication,
QGraphicsEllipseItem,
QGraphicsSceneMouseEvent,
QToolTip,
)
from ... |
419695 | from kivy.app import App
from kivy.uix.popup import Popup
from kivy.properties import StringProperty, NumericProperty, ListProperty
from kivy.logger import Logger
from kivy.lang import Builder
from models import Search, Filters
from kivymd.dialog import MDDialog
from kivymd.textfields import MDTextField
from kivymd.b... |
419699 | from typing import List, Optional
import pulumi_aws as aws
from infra.config import STACK_NAME
import pulumi
class Cache(pulumi.ComponentResource):
"""
An ElastiCache cluster instance.
"""
def __init__(
self,
name: str,
subnet_ids: pulumi.Input[List[str]],
vpc_id: pu... |
419766 | class Solution(object):
def divisorGame(self, N):
"""
:type N: int
:rtype: bool
"""
return True if N % 2 == 0 else False |
419767 | import functools
from copy import deepcopy
from datetime import date
from itertools import chain, groupby
from controls.exceptions import MissingPeriodError
from controls.models import ModuleSettings, Period
from crispy_forms.helper import FormHelper
from crispy_forms.utils import render_crispy_form
from django.conf i... |
419849 | expected_output = {
"my_state": "13 -ACTIVE",
"peer_state": "1 -DISABLED",
"mode": "Simplex",
"unit": "Primary",
"unit_id": 48,
"redundancy_mode_operational": "Non-redundant",
"redundancy_mode_configured": "Non-redundant",
"redundancy_state": "Non Redundant",
"maintenance_mode": "Di... |
419893 | from sqllineage.core.models import Column, Table
from sqllineage.runner import LineageRunner
def assert_table_lineage_equal(sql, source_tables=None, target_tables=None):
lr = LineageRunner(sql)
for (_type, actual, expected) in zip(
["Source", "Target"],
[lr.source_tables, lr.target_tables],
... |
419897 | import numpy as np
import matplotlib.pyplot as plt
Sky = [128,128,128]
Building = [128,0,0]
Pole = [192,192,128]
Road = [128,64,128]
DSET_MEAN = [0.611, 0.506, 0.54]
DSET_STD = [0.14, 0.16, 0.165]
label_colours = np.array([Sky, Building, Pole, Road])
def view_annotated(tensor, plot=True):
temp = tensor.numpy(... |
419902 | from setuptools import setup, find_packages
version = "0.24"
setup(name="staffjoy",
packages=find_packages(),
version=version,
description="Staffjoy API Wrapper in Python",
author="<NAME>",
author_email="<EMAIL>",
license="MIT",
url="https://github.com/staffjoy/client_python",... |
419919 | import requests
from qanta.datasets.quiz_bowl import QuestionDatabase
query = 'https://en.wikipedia.org/w/api.php?action=query&prop=pageprops&format=json&titles={}'
answers = QuestionDatabase().all_answers().values()
for answer in answers:
r =
requests.get(query.format(answer))
r = r.json()
|
419933 | import src.cli.console as console
def container_list(data):
if len(data.spec.containers) <= 1:
return None
container = console.list(
message="Please select a container",
message_no_choices="No container is running.",
choices=[c.name for c in data.spec.containers],
)
if... |
419950 | import socket
def get_ip_address(domain_name):
print("[+]Obtaining IP Address")
try:
ip_address=socket.gethostbyname(domain_name)
return ip_address
except:
print("[!]Unable to get IP Address") |
419970 | import discord
from discord.ext import commands
from discord.ext.commands.errors import *
from modules.helpers import PREFIX, InsufficientFundsException
class Handlers(commands.Cog, name='handlers'):
def __init__(self, client: commands.Bot):
self.client = client
@commands.Cog.listener()
... |
419999 | from __future__ import print_function
import threading, sys, time, traceback
class DebugLock(object):
def __init__(self, name, verbose=False):
self.name = name
self._lock = threading.Lock()
self.verbose = verbose
def acquire(self, latency_warn_msec=None):
if self.verbose:
... |
420000 | from numbers import Number
from typing import Union
from pathlib import Path
import numpy as np
import scipy.sparse as sp
from .sparsegraph import SparseGraph
data_dir = Path(__file__).parent
def load_from_npz(file_name: str) -> SparseGraph:
"""Load a SparseGraph from a Numpy binary file.
Parameters
--... |
420020 | import requests
from isserviceup.services.models.service import Service, Status
class StatusIOPlugin(Service):
status_url = 'https://api.status.io/'
@property
def statuspage_id(self):
raise NotImplemented()
def get_status(self):
r = requests.get('{}/1.0/status/{}'.format(
... |
420029 | from unittest.mock import MagicMock
import pytest
from pytest import fixture
from pytest_mock import MockFixture
from injectable import InjectionContainer, Injectable
from injectable.container.namespace import Namespace
from injectable.errors import InjectionError
from injectable.injection.injection_utils import (
... |
420043 | import FWCore.ParameterSet.Config as cms
from RecoLocalCalo.HGCalRecProducers.HGCalRecHit_cfi import HGCalRecHit
HEBRecHitGPUProd = cms.EDProducer('HEBRecHitGPU',
HGCHEBUncalibRecHitsTok = cms.InputTag('HGCalUncalibRecHit', 'HGCHEBUncalibRecHits'),
HG... |
420068 | import os
import shutil
import test_util
@given(u'I create a dir "{dirPath}"')
def step_impl(context, dirPath):
os.makedirs(dirPath, 0755);
@then(u'I should delete dir "{dirPath}"')
def step_impl(contxt, dirPath):
shutil.rmtree(dirPath)
@when(u'I execute utility with no flag')
def step_impl(context):
cm... |
420074 | import logging
import shutil
from pathlib import Path
from tempfile import TemporaryDirectory
from notebookstestcase import _PYGSTI_ROOT, notebooks_in_path, _make_test
# All tutorials to be tested are under this directory
_TUTORIALS_ROOT = _PYGSTI_ROOT / 'jupyter_notebooks' / 'Tutorials'
# File resources to be copie... |
420075 | from tia.bbg.v3api import *
LocalTerminal = Terminal('localhost', 8194)
from tia.bbg.datamgr import *
|
420077 | pkgname = "bsded"
pkgver = "0.99.0"
pkgrel = 0
build_style = "makefile"
pkgdesc = "FreeBSD ed(1) utility"
maintainer = "q66 <<EMAIL>>"
license = "BSD-2-Clause"
url = "https://github.com/chimera-linux/bsded"
source = f"https://github.com/chimera-linux/bsded/archive/refs/tags/v{pkgver}.tar.gz"
sha256 = "ae351b0a03519d2ec... |
420101 | from lxml import html
import requests
from bs4 import BeautifulSoup
import sys
import os
import re
import time
REGEX = '\s*([\d.]+)'
count = 0
#this code prints out information (vulnerability ID, description, severity, and link) for all the vulnerabilities for a given dependency passed in through command line
def usag... |
420132 | import warnings
from ._conf import PYRAMID_PARAMS
from ._funcs import _get_crs, _verify_shape_bounds
from ._types import Bounds, Shape
class GridDefinition(object):
"""Object representing the tile pyramid source grid."""
def __init__(
self, grid=None, shape=None, bounds=None, srs=None, is_global=Fal... |
420146 | from queue import Queue, Empty
import threading
from asyncio import sleep
import traceback
import os
from .pull import GitPuller
class GitWrapper():
def __init__(self, repo, repobranch, repofolder):
self.repo = repo
self.finished = False
self.error = False
self.logs = []
... |
420151 | import binascii
import hashlib
import os
import random
import string
import subprocess
import sys
import time
import threading
import Queue
BIN_PATH = "./build/test_random_sha1"
NTHREADS = 2
NTESTS = 10
NBYTES = 20
global still_making_input
still_making_input = True
tests = Queue.Queue()
failures = list()
#
# Help... |
420195 | from typing import Optional, cast
from fastapi import APIRouter, Depends, HTTPException, Path, Query, Response, status
from opal_common.authentication.deps import JWTAuthenticator
from opal_common.authentication.types import JWTClaims
from opal_common.schemas.policy import PolicyBundle
from opal_common.schemas.policy_... |
420202 | from .map import Map
from .layer import Layer
from .source import Source
from .layout import Layout
from .themes import Themes as themes
from .basemaps import Basemaps as basemaps
from .palettes import Palettes as palettes
from .styles import animation_style
from .styles import basic_style
from .styles import color_b... |
420214 | class Solution:
def candy(self, ratings: List[int]) -> int:
ratingsLength = len(ratings)
if ratingsLength == 0:
return 0
candies = [1] * ratingsLength
for i in range(1, ratingsLength):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1]... |
420226 | import pyb
from pyb import UART
from pyb import Pin
import time
class DHT11:
def __init__(self,pin_):
self.PinName=pin_
time.sleep(1)
self.gpio_pin = Pin(pin_, Pin.OUT_PP)
# pyb.delay(10)
def read_temp_hum(self):
data=[]
j=0
gpio_pin=self.gpio_pin
g... |
420235 | from starry_process import calibrate
import numpy as np
import os
import shutil
# Utility funcs to move figures to this directory
abspath = lambda *args: os.path.join(
os.path.dirname(os.path.abspath(__file__)), *args
)
copy = lambda name, src, dest: shutil.copyfile(
abspath("data", name, src), abspath(dest)
... |
420244 | import multiprocessing
def square_mp(in_queue, out_queue):
while(True):
n = in_queue.get()
n_squared = n**2
out_queue.put(n_squared)
if __name__ == '__main__':
in_queue = multiprocessing.Queue()
out_queue = multiprocessing.Queue()
process = multiprocessing.Process(target=square... |
420248 | import random as rnd
p = 0.3 # Probability of success
n = 10 # Number of trials
count = 0 # Count number of successes
def Bernoulli(p): # Bernoulli RVG Function
u = rnd.random()
if 0 <= u < p:
return 1
else:
return 0
for i in range(n):
count = count +... |
420273 | from sklearn.metrics import average_precision_score, accuracy_score, f1_score
def acc_f1(output, labels, average='binary'):
preds = output.max(1)[1].type_as(labels)
if preds.is_cuda:
preds = preds.cpu()
labels = labels.cpu()
accuracy = accuracy_score(preds, labels)
f1 = f1_score(preds, ... |
420306 | from __future__ import annotations
import typing
from ctc import rpc
from ctc import spec
async def async_is_contract_address(
address: spec.Address,
block: spec.BlockNumberReference = 'latest',
provider: spec.ProviderSpec = None,
) -> bool:
code = await rpc.async_eth_get_code(
address=addre... |
420323 | import argparse
import logging
from abc import ABC
from typing import Dict, List
import numpy as np
from data.dataset import Dataset, TestUnit, TestUnits
from simulation.outcome_generators import OutcomeGenerator
from simulation.treatment_assignment import TreatmentAssignmentPolicy
def get_treatment_ids(treatment_a... |
420380 | import multiprocessing
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from .SurvivalTree import SurvivalTree
from .scoring import concordance_index
class RandomSurvivalForest:
def __init__(self, n_estimators=100, min_leaf=3, unique_deaths=3,
n_jobs=None, paralleliz... |
420407 | from torch import nn
import torch
class MultiClassLogisticRegression(nn.Module):
def __init__(self,
theta_params: int,
num_of_classes: int):
super(MultiClassLogisticRegression, self).__init__()
self.__linear = nn.Linear(theta_params, num_of_classes)
def for... |
420408 | import nuke
def shuffle():
for selected_node in nuke.selectedNodes():
if selected_node.Class() == 'Read':
all_channels = selected_node.channels()
all_channels = list(set([i.split('.')[0] for i in all_channels]))
for channel in all_channels:
shuffle_node ... |
420432 | import numpy as np
from tqdm import trange, tqdm
import tensorflow as tf
from .fedbase import BaseFedarated
from flearn.optimizer.pgd import PerturbedGradientDescent
from flearn.utils.tf_utils import process_grad, process_sparse_grad
class Server(BaseFedarated):
def __init__(self, params, learner, dataset):
... |
420475 | import pytest
import torch.nn as nn
from kornia.metrics import AverageMeter
from kornia.x import EarlyStopping, ModelCheckpoint
from kornia.x.utils import TrainerState
@pytest.fixture
def model():
return nn.Conv2d(3, 10, kernel_size=1)
def test_callback_modelcheckpoint(tmp_path, model):
cb = ModelCheckpoin... |
420492 | import os
from src.domain.ErrorTypes import ErrorTypes
from src.utils.code_generation import CodeGenerationUtils
from src.validity import CVValiditiyChecker
from src.validity import IncomingEdgeValidityChecker
def generate_code(args):
node = args["node"]
requireds_info = args["requireds_info"]
edges = ar... |
420495 | import torch
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
matplotlib.use('Agg')
def last_layer_analysis(heads, task, taskcla, y_lim=False, sort_weights=False):
"""Plot last layer weight and bias analysis"""
print('Plotting last layer analysis...')
num_classes = sum([x for (_, x) in... |
420529 | from secml.testing import CUnitTest
from secml.data.loader import CDataLoaderMNIST
class TestCDataLoaderMNIST(CUnitTest):
"""Unittests for CDataLoaderMNIST."""
def test_load(self):
digits = (1, 5, 9)
tr = CDataLoaderMNIST().load('training', digits=digits)
self.logger.info(
... |
420576 | from django.contrib import admin
from .models import PatientRegister, DoctorRegister, Emergency, Appointment
# Register your models here.
admin.site.register(PatientRegister)
admin.site.register(DoctorRegister)
admin.site.register(Emergency)
admin.site.register(Appointment)
|
420597 | from sklearn.model_selection import KFold as R_KFold
from horch.datasets import Subset
def k_fold(ds, n_splits=5, shuffle=True, transform=None, test_transform=None, random_state=None):
n = len(ds)
kf = KFold(n_splits, shuffle, random_state)
for train_indices, test_indices in kf.split(list(range(n))):
... |
420598 | from matplotlib.backends.backend_pdf import PdfPages
my_pdf = PdfPages('reports.pdf')
my_pdf.close()
|
420628 | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from builtins import int
from builtins import open
from future import standard_library
standard_library.install_aliases()
import os
import re
i... |
420633 | import numpy
from .abstracts import ClassScoresStrategy
class CommonNeighborsStrategy(ClassScoresStrategy):
__name__ = 'CN'
def find_score(self, class_node, test_node):
return self.leg.count_common_neighbors(class_node, test_node)
class AdamicAdarStrategy(ClassScoresStrategy):
__name__ = 'AA'
... |
420645 | import os
import logging
from pathlib import Path
class LoggerHandler():
def __init__(self, level):
self.level = getattr(logging, level)
self.logger = logging.getLogger("OnionScraper")
self.logger.setLevel(self.level)
# create console handler and set level to debug
ch = lo... |
420696 | def test_no_snippets_on_call():
import requests
url = "www.google.fr"
'''TEST
requests.get$
@. ... get
@! get([url])
status: ok
'''
|
420719 | from .base import *
class TextureMap:
_wrap_modes = {
"repeat": SamplerState.WM_repeat,
"clamp": SamplerState.WM_clamp,
"border_color": SamplerState.WM_border_color,
"mirror": SamplerState.WM_mirror,
"mirror_once": SamplerState.WM_mirror_once
}
_filter_types = {
... |
420729 | import logging
import unittest
from unittest import TestCase
import toml
from fiery_snap.impl.util.service import GenericService
from fiery_snap.impl.util.page import Page, TestPage
import time
import web
import requests
EXAMPLE_TOML = """
name = "test_service"
listening_address = "0.0.0.0"
listening_port = 7878
"""
... |
420746 | import datetime
import uuid as uuid_object
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
from projectroles.models import Project
#: Shortcut to Django User model class.
from projectroles.plugins import ge... |
420747 | words=['Wednesday',
'a lot',
'absence',
'accept',
'acceptable',
'accessible',
'accidentally',
'accommodate',
'accompanied',
'accomplish',
'accumulate',
'accuracy',
'achievement',
'acknowledgment',
'acquaintance',
'acquire',
'acquitted',
'across',
'actually',
'address',
'admission',
'adolescent',
'advice',
'advise',
'ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.