id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11528675 | from django.contrib import admin
from .models import Letter, Attachment
class AttachmentInline(admin.StackedInline):
"""
Stacked Inline View for Attachment
"""
model = Attachment
@admin.register(Letter)
class LetterAdmin(admin.ModelAdmin):
"""
Admin View for Letter
"""
list_displa... |
11528711 | import pymel.core as pm
def optionVarProperty(key, default):
"""
Create a property that is saved in the user's preferences
by using Maya optionVars.
Args:
key (str): The option var key for the property
default: The default value of the property
"""
def fget(self):
ret... |
11528749 | from django.shortcuts import render
from .models import Profile
def dashboard(request):
return render(request, "base.html")
def profile_list(request):
profiles = Profile.objects.exclude(user=request.user)
return render(request, "dwitter/profile_list.html", {"profiles": profiles})
|
11528815 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
cscDaqInfo = DQMEDHarvester("CSCDaqInfo")
|
11528818 | import demistomock as demisto
from SetByIncidentId import main
def test_set_by_incident_id(mocker):
"""
Given:
- ID (1) of incident to update
- Key (Key) to update
- Value (Value) to update
- Argument append set to false
- Argument errorUnfinished set to false
When... |
11528906 | from pypugjs.lexer import Lexer
from pypugjs.utils import odict
expected_results = {
"p Here is some #[strong: em text] and look at #[a(href='http://google.com') this link!]": [
{'buffer': None, 'line': 1, 'type': 'tag', 'inline_level': 0, 'val': u'p'},
{
'buffer': None,
'li... |
11528989 | def show_graph_from_adjmtx(A,B,C,title=''):
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
gr = nx.DiGraph()
nodes=list(range(1,A.shape[0]))
gr.add_nodes_from(nodes)
gr.add_node('u')
rows, cols = np.where(A == 1)
edges_A = list(zip(cols.tolist(), rows.tolist()))
gr.add_edges_from(ed... |
11528997 | import re
from typing import List
from unidecode import unidecode
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
def slugify(text: str, delim: str = "-") -> str:
"""
Generates an ASCII-only slug.
"""
result: List[str] = []
for word in _punct_re.split(text.lower()):
re... |
11529015 | import csv
import json
import os
import StringIO
import tempfile
import unittest
import parquet
class TestFileFormat(unittest.TestCase):
def test_header_magic_bytes(self):
with tempfile.NamedTemporaryFile() as t:
t.write("PAR1_some_bogus_data")
t.flush()
self.assertTru... |
11529017 | import timeit
from logging import getLogger
import numpy as np
import pytest
import torch
from torch import nn
from pfrl.utils import clip_l2_grad_norm_
def _get_grad_vector(model):
return np.concatenate(
[p.grad.cpu().numpy().ravel().copy() for p in model.parameters()]
)
def _test_clip_l2_grad_no... |
11529063 | import numpy as np
from bokeh.layouts import column, gridplot
from bokeh.models import BoxSelectTool, Div
from bokeh.plotting import figure, show, output_file
x = np.linspace(0, 4*np.pi, 100)
y = np.sin(x)
TOOLS = "wheel_zoom,save,box_select,lasso_select"
div = Div(text="""
<p>Selection behaviour in Bokeh can be co... |
11529116 | from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from revproxy.views import ProxyView
from proxy.process import FavaProcess
from child import fava_child
from contextlib import closing
from multiprocessing import Process
... |
11529133 | import unittest
from mock import Mock, patch
from lti import ToolProxy
import requests
import json
from oauthlib.oauth1 import SignatureOnlyEndpoint
test_profile = {'@context': ['http://purl.imsglobal.org/ctx/lti/v2/ToolConsumerProfile'],
'@id': 'https://canvas.instructure.com/api/lti/courses/1157004/tool_consumer_pr... |
11529140 | from __future__ import absolute_import, division, print_function, unicode_literals
from django.core import mail
from django.db import IntegrityError
from django.test.utils import override_settings
from django_otp.forms import OTPAuthenticationForm
from django_otp.tests import TestCase
from .models import EmailDevice... |
11529163 | from distutils.core import setup
setup(
name = 'boltiot',
packages = ['boltiot'],
version = '1.11.2',
install_requires=['twilio','requests'],
description = 'A Python module for communicating with the Bolt Cloud API.',
author = 'Inventrom Pvt. Ltd.',
author_email = '<EMAIL>',
url = 'htt... |
11529192 | import json
import math
import sys
import os
'''
This script is used for generating tuning scripts for the benchmarks:
How to generate a tuning script ?
=================================
1. Create a file named autotune.json in the benchmark's directory
2. Fill the file according to the example autotune.json format.
... |
11529251 | import tkinter as tk
class TextLineNumbers(tk.Canvas):
def __init__(self, parent, *args, **kwargs):
tk.Canvas.__init__(self, *args, **kwargs)
self._text_font = parent.settings['font_family']
self._parent = parent
self.textwidget = parent.textarea
def attach(self, text_widget):
... |
11529281 | import unittest
class AuthenticatedPredicateTests(unittest.TestCase):
def _getFUT(self):
from repoze.who.restrict import authenticated_predicate
return authenticated_predicate()
def test___call___no_identity_returns_False(self):
predicate = self._getFUT()
environ = {}
... |
11529295 | from __future__ import division
import numpy as np
from scipy.optimize import fsolve
def dahlquist(_, x, lam):
"""
dahlquist test equation ode.
:param _: place holder for time, not used
:param x: x value
:param lam: lambda
:return: slope dx/dt
"""
dx = lam * x
return dx
def dahl... |
11529305 | import numpy
import matplotlib.pyplot as plt
import geojsoncontour
# Create lat and lon vectors and grid data
grid_size = 1.0
latrange = numpy.arange(-90.0, 90.0, grid_size)
lonrange = numpy.arange(-180.0, 180.0, grid_size)
X, Y = numpy.meshgrid(lonrange, latrange)
Z = numpy.sqrt(X * X + Y * Y)
n_contours = 20
levels... |
11529314 | import sys
import os
sys.path.append(os.getcwd())
from simuleval.agents import Agent,TextAgent, SpeechAgent
from simuleval import READ_ACTION, WRITE_ACTION, DEFAULT_EOS
from typing import List,Dict, Optional
import numpy as np
import math
import torch
from collections import deque
from torch import Tensor
import torch.... |
11529327 | import os
import time
import argparse
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torchvision.utils as vutils
import torchvision.transforms as transforms
... |
11529333 | import mido
import time
MIDI_MANUF_ID = 0x7D
ERASE_FLASH = 52
WRITE_FLASH = 54
SYSEX_CMD_RESET = 60
File_To_Write = r"D:\midi-commander-custom\python\config_image.bin"
midi_inputs = [x for x in mido.get_input_names() if 'STM' in x]
midi_outputs = [x for x in mido.get_output_names() if 'STM' in x]
if len(midi_inpu... |
11529346 | from django.contrib import admin
from durin.models import Client
from .models import ClientSettings
class ClientSettingsInlineAdmin(admin.StackedInline):
"""
Django's StackedInline for :class:`ClientSettings` model.
"""
model = ClientSettings
list_select_related = True
extra = 1
class Cl... |
11529375 | import os, time, re
import subprocess
import tempfile
def main():
#Useful constants, what we probably want to modify in order to write out the right file names
output_dir = '../../dist/'
relative_dir = output_dir + "a-starry-sky.master.js"
file_dir = os.path.abspath(relative_dir)
minified_file_dir ... |
11529382 | import numpy
class pyramid: # pyramid
# properties
pyr = []
pyrSize = []
pyrType = ''
image = ''
# constructor
def __init__(self):
print "please specify type of pyramid to create (Gpry, Lpyr, etc.)"
return
# methods
def nbands(self):
return len(self.pyr)
... |
11529437 | from pyjo.fields.field import Field
class EnumField(Field):
def __init__(self, enum, use_name=True, **kwargs):
"""
:type enum: T
:rtype: T
"""
super(EnumField, self).__init__(type=enum, **kwargs)
self.enum_cls = enum
self.use_name = use_name
def to_dict... |
11529511 | from pcf.particle.aws.sagemaker.notebook_instance import NotebookInstance
from pcf.core import State
# Edit example json to work in your account
notebook_instance_name = "pcf-test"
notebook_example_json = {
"pcf_name": "pcf_notebook", # Required
"flavor": "sagemaker_notebook_instance", # Required
"aws_re... |
11529524 | import subprocess
import json
import concurrent.futures
filename = 'IAM_users_without_any_groups.csv'
def writeIntoFile(filename, stdout, method='w+'):
with open(filename, method) as f: f.write(stdout)
def getUsersGroups(username):
user = username['UserName']
creationD = username['CreateDate'].split("T")[0]
... |
11529530 | from conans import ConanFile, CMake
class ConanMgsBase32hex(ConanFile):
name = "mgs_base32hex"
version = "0.1.0"
generators = "cmake"
exports_sources = "include/*", "CMakeLists.txt", "test/*"
settings = "os", "arch", "build_type", "compiler"
def build_requirements(self):
self.build_req... |
11529533 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import torch
import numpy as np
from progress.bar import Bar
from opendr.perception.object_tracking_2d.fair_mot.algorithm.lib.models.data_parallel import (
DataParallel,
)
from opendr.perceptio... |
11529571 | import unittest
import database.main
from tests.create_test_db import engine, session, Base
database.main.engine = engine
database.main.session = session
database.main.Base = Base
from copy import deepcopy
import models.main
from classes import Paladin
from exceptions import NoSuchCharacterError
from models.characte... |
11529586 | from globus_cli.commands import main
from globus_cli.version import __version__
__all__ = ["main", "__version__"]
|
11529595 | import magma as m
class _And2(m.Circuit):
name = "And2"
io = m.IO(I0=m.In(m.Bit), I1=m.In(m.Bit), O=m.Out(m.Bit))
def test_declare_repr():
assert str(_And2) == 'And2(I0: In(Bit), I1: In(Bit), O: Out(Bit))'
assert repr(_And2) == ('And2 = DeclareCircuit("And2", "I0", In(Bit), "I1", '
... |
11529613 | import json
from mudpi.exceptions import MudPiError
from mudpi.constants import FONT_YELLOW, FONT_RESET
from mudpi.logger.Logger import Logger, LOG_LEVEL
class Registry:
""" Key-Value database for managing object instances """
def __init__(self, mudpi, name):
self.mudpi = mudpi
self.name = name... |
11529614 | from .settings import Settings
from .custom_user import User
from .filter import DataFilter
from .parametrised_filter import ParametrisedFilter
from .version import DatasetVersion
from .variable import DataVariable
from .dataset import Dataset
from .dataset_configuration import DatasetConfiguration
from .copied_validat... |
11529653 | main = {
'General': {
'Prop': {
'Labels': 'rw',
'AlarmStatus': 'r-'
}
}
}
cfgm = {
'General': {
'Cmd': {
'CreatePort',
'DeletePort'
}
}
} |
11529655 | import json
import NLTK_Chink
import time
import NLTK_log
if __name__ == '__main__':
startTime = time.time()
with open('./Training.json') as file:
obj = json.loads(file.read())
questions = obj['questions']
for i, question in enumerate(questions):
sentenece = question['quest... |
11529665 | import bitcoin
from bitcoin.deterministic import bip32_harden as h
mnemonic='saddle observe obtain scare burger nerve electric alone minute east walnut motor omit coyote time'
seed=bitcoin.mnemonic_to_seed(mnemonic)
mpriv=bitcoin.bip32_master_key(seed)
accountroot=mpriv
accountroot=bitcoin.bip32_ckd(accountro... |
11529710 | from __future__ import print_function
import sys
import Pyro4
test = Pyro4.core.Proxy("PYRONAME:example.exceptions")
print(test.div(2.0, 9.0))
try:
print(2 // 0)
except ZeroDivisionError as x:
print("DIVIDE BY ZERO: %s" % x)
try:
print(test.div(2, 0))
except ZeroDivisionError as x:
print("DIVIDE BY ... |
11529715 | import pytest
from jina.peapods.pods.factory import PodFactory
from jina.peapods import Pea
from jina.parsers import set_pod_parser, set_pea_parser
from jina import Flow, Executor, requests, Document, DocumentArray
from jina.helper import random_port
def validate_response(resp, expected_docs=50):
assert len(res... |
11529727 | from LAUG.aug import Word_Perturbation
from LAUG.aug import Text_Paraphrasing
from LAUG.aug import Speech_Recognition
from LAUG.aug import Speech_Disfluency
if __name__=="__main__":
text = "I want a train to Cambridge"
span_info = [["Train-Infrom","Dest","Cambridge",5,5]]
WP = Word_Perturbation('mu... |
11529754 | import os
import importlib
import math
import numpy as np
import tensorflow as tf
from source.network.detection import ssd_common
CLASS_WEIGHTS = 1.0
BBOXES_WEIGHTS = 1.0
# Priorboxes
ANCHORS_STRIDE = [8, 16, 32, 64, 128, 256, 512]
ANCHORS_ASPECT_RATIOS = [[2], [2, 3], [2, 3], [2, 3], [2, 3], [2], [2]]
# control th... |
11529769 | import json
import os
import shutil
import subprocess
import tempfile
import aptbranch
def gs_rsync(local_path: str, remote_path: str, boto_path: str):
# TODO: do this directly rather than by shelling out
env = dict(os.environ)
env["BOTO_PATH"] = boto_path
subprocess.check_call(["gsutil", "-h", "Cach... |
11529784 | import socket
import sys
import textwrap
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="file")
parser.add_option("-a", "--host", dest="host")
parser.add_option("-p", "--port", dest="port")
(options, args) = parser.parse_args()
def SendToNuke(options):
PY_CMD_TE... |
11529806 | from django.conf.urls import url
from apps.user_login.views import user_login
from apps.dubbo_interface.views import dubbo_interface,dubbo_interface_debug
from apps.dubbo_testcase.views import dubbo_testcase,dubbo_testcase_step,dubbo_testcasedebug
from apps.dubbo_task.views import dubbo_task,testReport,batchTask
from ... |
11529825 | import asyncore
import matplotlib.pyplot as plt
import zlib,socket
import numpy as np
import MFSKDemodulator, DePacketizer, MFSKSymbolDecoder, time, logging, sys
from scipy.io import wavfile
import MFSKModulator,Packetizer
import sounddevice as sd
import soundfile as sf
from scipy.io import wavfile
from thread import... |
11529850 | import copy
import nose.tools
import numpy as np
import os
import pandas as pd
import skimage.io as sk_im_io
from testfixtures import TempDirectory
import unittest
import warnings
import micro_dl.preprocessing.tile_nonuniform_images as tile_images
import micro_dl.utils.aux_utils as aux_utils
class TestImageTilerNonU... |
11529852 | from loguru import logger
import asyncio
import aiohttp
from app.config import STATISTICS_TOKEN
from chatbase import Message
class AsyncMessage(Message):
def __init__(self, user_id, message, intent: str = "", not_handled: bool = False):
self.api_key = STATISTICS_TOKEN
self.platform = "tg"
... |
11529880 | import numpy as np
import unittest
from optml.gridsearch_optimizer import GridSearchOptimizer, objective
from optml import Parameter
from copy import deepcopy
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from functools import partial
def clf_score(y_true,y_pred):... |
11529882 | from dummy import Hyper, Param, Var, Runtime, Input, Output, Inline
maxScalar = Hyper()
numRegisters = Hyper()
programLen = Hyper()
numTimesteps = Hyper()
inputNum = Hyper()
inputStackSize = Hyper()
numRegInstrs = 13
numBranchInstrs = 2
numInstrTypes = 3
numInstructions = numBranchInstrs + numRegInstrs + 1
mutableSt... |
11529910 | class CommandDTOV4(object):
serviceId = "serviceId"
method = "method"
paras = "paras"
def __init__(self):
# self.paras = dict()
print("self.paras = None")
|
11529932 | from setuptools import setup
setup(
name = 'pyxing',
version = '0.0.5',
description = 'python wrapper for eBest Xing API',
url = 'https://github.com/sharebook-kr/pyxing',
author = '<NAME>, <NAME>',
author_email = '<EMAIL>, <EMAIL>, <EMAIL>',
in... |
11529939 | from abstract_plotter import AbstractPlotter, Frame
class Plotter(AbstractPlotter):
def __init__(self, frame= None):
AbstractPlotter.__init__(self, frame)
self.circles = []
def circle(self, x, y, r, color):
self.circles.append((x, y, r, color))
def triangle(self, x, y, r, color):... |
11529953 | from __future__ import (
annotations,
)
from minos.common import (
Config,
Inject,
NotProvidedException,
)
@Inject()
def get_service_name(config: Config) -> str:
"""Get the service name."""
if config is None:
raise NotProvidedException("The config object must be provided.")
return... |
11529957 | from __future__ import absolute_import
import copy
import types
import operator
from sqlbuilder.smartsql.compiler import compile
from sqlbuilder.smartsql.constants import CONTEXT
from sqlbuilder.smartsql.exceptions import Error
from sqlbuilder.smartsql.expressions import Operable, Expr, ExprList, Constant, Parentheses,... |
11529969 | def test():
assert (
len(pattern1) == 2
), "Le nombre de tokens de pattern1 ne correspond pas au véritable nombre de tokens dans la chaine."
assert (
len(pattern2) == 2
), "Le nombre de tokens de pattern2 ne correspond pas au véritable nombre de tokens dans la chaine."
# Validation d... |
11529974 | import pygame
#button class
class Button():
def __init__(self, surface, x, y, image, size_x, size_y):
self.image = pygame.transform.scale(image, (size_x, size_y))
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
self.clicked = False
self.surface = surface
def draw(self):
action = False
#... |
11530007 | import os
import sublime
from .console_write import console_write
from .package_io import package_file_exists
class PackageRenamer():
"""
Class to handle renaming packages via the renamed_packages setting
gathered from channels and repositories.
"""
def load_settings(self):
"""
... |
11530009 | from director import objectmodel as om
from director import vtkAll as vtk
from director import vtkNumpy as vnp
import numpy as np
def computePointToSurfaceDistance(pointsPolyData, meshPolyData):
cl = vtk.vtkCellLocator()
cl.SetDataSet(meshPolyData)
cl.BuildLocator()
points = vnp.getNumpyFromVtk(poin... |
11530020 | import anyfig
from pathlib import Path
import time
import argparse
@anyfig.config_class # Registers the class with anyfig
class MyConfig:
def __init__(self):
# Config-parameters goes as attributes
self.experiment_note = 'Changed stuff'
self.save_directory = Path('output')
self.start_time = time.tim... |
11530024 | from pprint import pprint
import click
from cbapi import CbEnterpriseResponseAPI, CbThreatHunterAPI
import urllib.request
import urllib.parse
import json
import configparser
from products import vmware_cb_response as cbr, vmware_cb_enterprise_edr as cbth, microsoft_defender_for_endpoints as defender
class EDRCommo... |
11530058 | from typing import List
import pytest
from ground.base import (Context,
Relation)
from ground.hints import Segment
from hypothesis import given
from bentley_ottmann.core.utils import to_sorted_pair
from bentley_ottmann.planar import segments_intersections
from tests.utils import (is_point,
... |
11530064 | from pytest import raises
from dollar_ref import (
resolve,
InternalResolutionError, FileResolutionError,
ResolutionError, DecodeError
)
def test_bad_internal_ref():
data = {
'real': 'stuff',
'bad_ref': {
'$ref': '#/does/not/exist'
}
}
with raises(Internal... |
11530109 | from __future__ import (
absolute_import,
unicode_literals,
)
import random
import re
from typing import (
Any,
Dict,
)
import unittest
from pymetrics.recorders.noop import noop_metrics
import six
from pysoa.common.transport.base import get_hex_thread_id
from pysoa.common.transport.redis_gateway.clie... |
11530117 | class Details(object):
def __init__(self, set_callback=None):
super(Details, self).__init__()
self._details = {}
self._set_callback = set_callback
def set(self, key, value):
"""Sets a specific detail (by name) to a specific value
"""
if self._set_callback is not... |
11530138 | from numpy import linspace, sin, exp
import sys
import pylab
import larch
# set python path so that larch plugins can be found
sys.path.append(larch.plugin_path('xafs'))
import xafsft
k = linspace(0, 20, 401)
chi = sin(4.2*k)*exp(-k*k/150)*exp(-(k-10)**2/50)
# need to have an larch interpreter for most functions
myl... |
11530140 | import re
class Main():
def __init__(self):
self.s = input()
self.c = 'qwrtypsdfghjklzxcvbnm'
def output(self):
self.ss = re.findall(r'(?<=[' + self.c + '])([aeiou]{2,})(?=[' + self.c +'])', self.s, flags = re.I)
print('\n'.join(self.ss or ['-1']))
if __name__ ... |
11530161 | import sys
import datetime
def basic(arguments):
import api
critic = api.critic.startSession(for_testing=True)
repository = api.repository.fetch(critic, name="critic")
branch = api.branch.fetch(
critic, repository=repository, name=arguments.review)
review = api.review.fetch(critic, branch=... |
11530195 | from pygears import gear
from pygears.typing import cast as type_cast
from pygears.typing import trunc as type_trunc
from pygears.conf import reg
from pygears.core.intf import IntfOperPlugin
from pygears.hdl.util import HDLGearHierVisitor, flow_visitor
from pygears.hdl.sv import SVGenPlugin
from pygears.hdl.v import VG... |
11530196 | import os
import sqlite3
import pytest
from minecraft_mod_manager.gateways.sqlite_upgrader import SqliteUpgrader
from ..config import config
from .sqlite import Sqlite
db_file = f".{config.app_name}.db"
@pytest.fixture
def db() -> sqlite3.Connection:
db = sqlite3.connect(db_file)
yield db
db.close()
... |
11530203 | import asyncio
import collections
from utilities import DotDict, recursive_dictionary_update
class BaseMeta(type):
def __new__(mcs, name, bases, clsdict):
for key, value in clsdict.items():
if callable(value) and (value.__name__.startswith("on_") or
hasattr... |
11530269 | import sys
from copy import deepcopy
import numpy as np
from shape_validator import checkFaceValidity, checkVerticesValidity, get_array_depth
from service import GracefulShutdown
class CachedObjClass(object):
def __init__(self, name):
self.name = name
self.count = {}
self.__dict_of_data =... |
11530276 | from django_elasticsearch_dsl import fields as es_fields
from django_elasticsearch_dsl.registries import registry
from researchhub_document.related_models.researchhub_post_model import ResearchhubPost
from .base import BaseDocument
from search.analyzers import (
title_analyzer,
content_analyzer
)
@registry.... |
11530288 | import torch
import torch.nn as nn
def conv_bn(in_channels,out_channels,kernel_size, stride=1, groups=1):
return nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels,kernel_size=kernel_size, stride=stride,
padding=kernel_size // 2, groups=groups, bias=False),
... |
11530298 | import numpy as np
import scipy.sparse as sp
import tensorflow as tf
from .gcnn import conv, GCNN
from ..tf.convert import sparse_to_tensor
class GCNNTest(tf.test.TestCase):
def test_conv(self):
adj = [[0, 1, 0], [1, 0, 2], [0, 2, 0]]
adj = sp.coo_matrix(adj, dtype=np.float32)
adj_norm = ... |
11530299 | from crianza.compiler import (check, compile)
from crianza.errors import CompileError, MachineError, ParseError
from crianza.instructions import lookup
from crianza.optimizer import constant_fold, optimized
from crianza.parser import (parse, parse_stream)
from crianza.repl import repl, print_code
from crianza.stack imp... |
11530330 | import numpy as np
mdhLC = [("ushLine", "<u2"),
("ushAcquisition", "<u2"),
("ushSlice", "<u2"),
("ushPartition", "<u2"),
("ushEcho", "<u2"),
("ushPhase", "<u2"),
("ushRepetition", "<u2"),
("ushSet", "<u2"),
("ushSeg", "<u2"),
("ushIda", ... |
11530466 | from __future__ import print_function
import sys
from metapub import PubMedFetcher
from metapub import FindIt
# examples of different formats:
# 18612690: PubMedArticle with multiple AbstractText sections
# 1234567: PubMedArticle with no abstract whatsoever
# 20301546: PubMedBookArticle from GeneReviews
####
impor... |
11530476 | from ..api import rule
from ..api._endpoint import ApiEndpoint, maybe_login_required
from ..entities._entity import NotFound
from ..entities.commit import Commit, CommitSerializer
class CommitListAPI(ApiEndpoint):
serializer = CommitSerializer()
@maybe_login_required
def get(self):
"""
--... |
11530481 | import json
import datetime
import time
import boto3
import os
def train_and_generate_recommendations(event, context):
# 200 is the HTTP status code for "ok".
status_code = 200
try:
# From the input parameter named "event", get the body, which contains
# the input rows.
event_bod... |
11530497 | import faker
from unittest import mock
from unittest.mock import patch
from foundations_spec import *
from foundations_core_cli.command_line_interface import CommandLineInterface
from foundations_atlas_cli.sub_parsers.atlas.atlas_parser import AtlasParser
class TestAtlasParser(Spec):
class MockSleep(object):
... |
11530516 | from unittest import mock
from rest_framework import status
from lego.apps.users.models import User
from lego.utils.test_utils import BaseAPITestCase
class ListArticlesTestCase(BaseAPITestCase):
fixtures = ["test_users.yaml"]
url = "/api/v1/files/"
def setUp(self):
self.user = User.objects.fir... |
11530523 | import collections
from .item import ItemCollection
from .signals import navbar_created
class NavigationBar(collections.Iterable):
"""The navigation bar object."""
def __init__(self, name, items=None, alias=None):
self.name = name
self.items = ItemCollection(items or [])
self.initial... |
11530539 | import netbox_agent.dmidecode as dmidecode
from netbox_agent.config import config
from netbox_agent.config import netbox_instance as nb
from netbox_agent.inventory import Inventory
from netbox_agent.location import Datacenter, Rack, Tenant
from netbox_agent.misc import create_netbox_tags, get_device_role, get_device_ty... |
11530591 | from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.get('/')
def main():
return 'root url'
@app.get('/json')
def json():
return {
"result": "json",
"sub_result": {"sub": "json"}
}
class Request(BaseModel):
id: int
body: str
@app.po... |
11530596 | import re
import copy
import inspect
import ast
import textwrap
"""
Utilities for manipulating the Abstract Syntax Tree of Python constructs
"""
class NameVisitor(ast.NodeVisitor):
"""
NodeVisitor that builds a set of all of the named identifiers in an AST
"""
def __init__(self, *args, **kwargs):
... |
11530609 | import ciso8601
import dateutil.parser
from cartographer.field_types import SchemaAttribute
from cartographer.utils.datetime import as_utc, make_naive
class DateAttribute(SchemaAttribute):
@classmethod
def format_value_for_json(cls, value):
return as_utc(value).isoformat()
def from_json(self, s... |
11530629 | from PySide2.QtCore import QItemSelectionModel, QObject, Signal
from PySide2.QtWidgets import QDialog, QTableWidgetItem, QVBoxLayout
from hexrd.ui.ui_loader import UiLoader
from hexrd.ui.utils import block_signals, unique_name
class ListEditor(QObject):
"""A string list editor that doesn't allow duplicates"""
... |
11530630 | import asyncio
import tempfile
import os
import contextlib
import pytest
from postfix_mta_sts_resolver import netstring
from postfix_mta_sts_resolver.responder import STSSocketmapResponder
import postfix_mta_sts_resolver.utils as utils
import postfix_mta_sts_resolver.base_cache as base_cache
@contextlib.contextmanag... |
11530673 | import theano
import numpy as np
import os
from theano import tensor as T
from collections import OrderedDict
# nb might be theano.config.floatX
dtype = T.config.floatX # @UndefinedVariable
class Elman(object):
def __init__(self, ne, de, na, nh, n_out, cs, npos,
update_embeddings=True):
... |
11530678 | from notedrive.lanzou import CodeDetail, LanZouCloud, download
downer = LanZouCloud()
downer.ignore_limits()
downer.login_by_cookie()
def example1():
print(downer.login_by_cookie() == CodeDetail.SUCCESS)
def example2():
file_path = '/Users/liangtaoniu/workspace/MyDiary/tmp/weights/yolov3.weight'
downe... |
11530697 | import os
import pytest
import shutil
import tempfile
from pathlib import Path
from nip import parse, dump, load, construct
from nip.utils import deep_equals
import builders
class TestConfigLoadDump:
save_folder: Path
@classmethod
def setup_class(cls):
cls.save_folder = Path(tempfile.mkdtemp())... |
11530711 | import copy
import warnings
from collections.abc import Iterable, Iterator
import numpy as np
import scipy
import scipy.optimize
import scipy.stats
from stingray.exceptions import StingrayError
from stingray.gti import bin_intervals_from_gtis, check_gtis, cross_two_gtis
from stingray.largememory import createChunkedS... |
11530725 | import json
JC_SETTINGS_FOLDER_NAME = "javascript_completions"
JC_SETTINGS_FOLDER = os.path.join(PACKAGE_PATH, JC_SETTINGS_FOLDER_NAME)
class JavaScriptCompletions():
def init(self):
self.api = {}
self.API_Setup = sublime.load_settings('JavaScript-Completions.sublime-settings').get('completion_active_list')... |
11530826 | import logging
import time
from typing import List
import boto3
from lib.data.dynamo.replication_dao import ReplicationDao
from lib.data.ssm.ssm import SsmDao
from lib.models.replication_config import ReplicationConfig
from lib.svcs.replication import ReplicationService
from lib.svcs.slack import SlackService
from li... |
11530829 | import time
from pathlib import Path
from logging import getLogger
import json
import argparse
import os
import sys
import skimage.io
import numpy as np
import click
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import torch
from tqdm import tqdm
if torch.cuda.is_available():
torch.randn(10).cuda()
... |
11530845 | from .base import *
DEBUG = False
ADMINS = (
('<NAME>', '<EMAIL>'),
)
ALLOWED_HOSTS = ['.educaproject.com']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'educa',
'USER': 'educa',
'PASSWORD': '*****',
}
}
# SSL config
SECURE_SSL_REDIRECT = True
... |
11530854 | from cleancat.base import (
Bool,
Choices,
DateTime,
Dict,
Email,
Embedded,
EmbeddedReference,
Enum,
Field,
Integer,
List,
Regex,
RelaxedURL,
Schema,
SortedSet,
StopValidation,
String,
TrimmedString,
URL,
ValidationError,
)
__all__ = [
... |
11530889 | import json
import logging
import os
from lib import (
create_response,
write_key,
read_key_or_default,
get_config,
get_tf_metadata,
)
logger = logging.getLogger()
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
def lambda_handler(event, context):
project_id = event["pathParameters"]["pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.