id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
190546 | import torch
import random
import numpy as np
import os
import pandas as pd
import config
import cv2
import matplotlib.pyplot as plt
from dataset import ImageFolder
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
import albumentations as A
from albumentations.py... |
190557 | import numpy as np
print '# [Numpy example1] ----------'
templist = [1,2,3,4,5,6]
templist = range(1,7)
np_templist = np.array(templist)
print np_templist
print '# Numpy example 2] --------'
np_tepmlist_int = np.array(templist,dtype=np.int8)
print '# Numpy example 3] -------'
|
190584 | from .sorting_algorithms import *
class Policy:
context = None
def __init__(self, context):
self.context = context
def configure(self):
if len(self.context.numbers) > 10:
print('More than 10 numbers, choosing merge sort!')
self.context.sorting_algorithm = MergeSor... |
190639 | import gdal_array as gd
try:
import Image
except:
from PIL import Image
relief = "relief.asc"
dem = "dem.asc"
target = "hillshade.tif"
# Load the relief as the background image
bg = gd.numpy.loadtxt(relief, skiprows=6)
# Load the DEM into a numpy array as the foreground image
fg = gd.numpy.loadtxt(dem, skipr... |
190673 | import asyncio
import grp
import importlib.resources
import os
import pathlib
import pwd
import sys
import unittest
from ...Shell import Shell
from ...util import which, export
from ..test_util import register, TmpDirMixin
__all__ = []
async def build_and_wait(factory, *args, **kwargs):
obj = await factory.buil... |
190680 | from typing import Union
from flair.data import Corpus, FlairDataset
from torch.utils.data import Subset
from embeddings.transformation.flair_transformation.corpus_sampling_transformation import (
CorpusSamplingTransformation,
)
class DownsampleFlairCorpusTransformation(CorpusSamplingTransformation):
def __... |
190740 | class BloxplorerException(Exception):
def __init__(self, message, resource_url, request_method):
self.message = message
self.resource_url = resource_url
self.request_method = request_method
def __str__(self):
return f'{self.message} (URL: {self.resource_url}, Method: {self.requ... |
190743 | import random
import pytest
from tests.test_client import get_doc
@pytest.fixture(scope="function")
def test_data(client, user):
system_random = random.SystemRandom()
url_x_count = system_random.randint(2, 5)
url_x_type = url_x_count
url_x = "s3://awesome-x/bucket/key"
versioned_count = system_r... |
190749 | from errors import *
from nodes import *
from ifelse import *
from loop import *
from func import *
from trycatch import *
from strquot import unquote
STATEMENTS = set('func labda local if elseif else while for try catch repeat'.split())
STATEMENT_CLASS = {'func': FuncStatement, 'labda': LabdaStatement,
'local': Lo... |
190755 | from pluginbase import get_plugin_source
def get_app():
rv = get_plugin_source(stacklevel=1)
if rv is not None:
return rv.app
def get_app_name():
return get_app().name
|
190772 | import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for n in range(1, 5):
server_ip="192.168.20.{0}".format(n)
rep = os.system('ping ' + server_ip)
if rep == 0:
print ("server is up" ,server_ip)
else:
print ("server is down" ,server_ip)
|
190783 | import FWCore.ParameterSet.Config as cms
from SimGeneral.MixingModule.mix_probFunction_25ns_PoissonOOTPU_cfi import *
mix.input.nbPileupEvents.probFunctionVariable = cms.vint32(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34... |
190785 | import pytest
def test_rogue():
# do this simple test since rogue has a rather complex boost dependency
# which we have gotten wrong in the past - valmar and cpo
import rogue
if __name__ == "__main__":
test_rogue()
|
190795 | from OpenMatch.data.dataloader import DataLoader
from OpenMatch.data.datasets import *
from OpenMatch.data.tokenizers import *
|
190816 | import bisect
import re
from typing import List, Dict
from securify.analyses.patterns.abstract_pattern import AbstractPattern, PatternMatch, Level, Severity, PatternMatchError, \
MatchComment, MatchSourceLocation
class RightToLeftOverridePattern(AbstractPattern):
regex_pattern = re.compile("\u202e".encode('u... |
190831 | from torchvision.datasets import VisionDataset
import warnings
import torch
from PIL import Image
import os
import os.path
import numpy as np
from torchvision import transforms
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(pat... |
190837 | import pytest
from mapreader import classifier
from mapreader import loadAnnotations
from mapreader import patchTorchDataset
import numpy as np
import torch
from torch import nn
import torchvision
from torchvision import transforms
from torchvision import models
PATH2IMAGES = "./examples/non-geospatial/classificati... |
190876 | import numpy as np
import pandas as pd
from pycytominer.operations import sparse_random_projection
data_df = pd.DataFrame(
{
"Metadata_plate": ["a", "a", "a", "a", "b", "b", "b", "b"],
"Metadata_treatment": [
"drug",
"drug",
"control",
"control",
... |
190942 | from pbpstats.data_loader.abs_data_loader import check_file_directory
from pbpstats.data_loader.live.file_loader import LiveFileLoader
class LiveBoxscoreFileLoader(LiveFileLoader):
"""
A ``LiveBoxscoreFileLoader`` object should be instantiated and passed into ``LiveBoxscoreLoader`` when loading data from file... |
190980 | def post(settings):
data = {"dynaconf_merge": True}
if settings.get("ADD_BEATLES") is True:
data["BANDS"] = ["Beatles"]
return data
|
191019 | import time
import sys
import traceback
try:
from support import exceptions
except:
sys.path.append('..')
from support import exceptions
def r(n=5, m=1, f=exceptions.current_code_list):
if n:
return r(n - 1, m)
for i in range(m):
return f()
def inline(n=5, m=10000):
if n:
... |
191035 | import tensorflow as tf
import numpy as np
from utils import get_shape
try:
from tensorflow.contrib.rnn import LSTMStateTuple
except ImportError:
LSTMStateTuple = tf.nn.rnn_cell.LSTMStateTuple
def bidirectional_rnn(cell_fw, cell_bw, inputs, input_lengths,
initial_state_fw=None, initial_sta... |
191055 | from django import forms
from .models import *
class RequestForm(forms.ModelForm):
class Meta:
model = Request
fields = ("reason_for_request",)
class ApproveForm(forms.ModelForm):
# approved = forms.BooleanField()
approved = forms.TypedChoiceField(
coerce=lambda x: bool(int(x)),
... |
191107 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import time
import numpy as np
import tensorflow as tf
import utils.utils as utils
class Evaluator:
def __init__(self,
cmd_args, config, optimizer, learning_rate, loss, sav... |
191143 | og=list(input("Enter number "))
new=set(og)
print("".join(og),"is a Unique Number") if len(new)==len(og) else print("".join(og),"is not a Unique Number")
|
191161 | import json
import os
import tempfile
import unittest
from gripql import Connection
from gripql.util import BaseConnection
def headersOverlap(actual, expected):
for k, v in expected.items():
assert k in actual
assert actual[k] == v
class TestRequestHeaderFormat(unittest.TestCase):
mock_url ... |
191211 | from nose.tools import ok_
from penn import Calendar
import datetime
class TestCalendar():
def setUp(self):
self.calendar = Calendar()
def test_pull(self):
cal = self.calendar.pull_3year()
ok_(len(cal) > 0)
for event in cal:
ok_(len(event) == 3)
def test_date... |
191222 | from copy import deepcopy
from .ObjectDict import ObjectDict
from . import mixins
class AssemblyPlanReport(
mixins.PlotsMixin,
mixins.FolderReportMixin,
mixins.GenbankExportMixin,
mixins.PdfReportMixin,
):
def __init__(self, plan, sources):
self.plan = ObjectDict.from_dict(plan)
se... |
191238 | import logging
import signal
import sys
import threading
import time
from threading import Thread
from dbnd import Task, parameter
from dbnd._core.current import get_databand_context, try_get_databand_run
from dbnd._core.task_build.task_context import try_get_current_task
logger = logging.getLogger(__name__)
stop_... |
191250 | from neurovault.apps.statmaps.tasks import save_resampled_transformation_single
from neurovault.apps.statmaps.tests.utils import (clearDB, save_statmap_form)
from neurovault.apps.statmaps.models import (Collection)
from django.contrib.auth.models import User
from django.test import TestCase, Client
import pandas as pd
... |
191269 | from asr.data import datasets, loaders
from asr import samplers
from asr.exceptions import ConfigurationError
from asr.utils.checks import check_for_data_path
import logging
logger = logging.getLogger()
def datasets_from_params(params):
"""
Load all the datasets specified by the config.
"""
sets = {}... |
191274 | import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
DLS_MODELS_REL_PATH = 'data/models'
DATASETS_REL_PATH = 'data/datasets-v2'
class Config(object):
DEBUG = True
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = '<PASSWORD>-really-needs-to-be-changed'
#
DLS_FILEMANAGER_BASE_PATH = ... |
191290 | import os
import urllib.parse as up
from werkzeug.middleware.proxy_fix import ProxyFix
from flask import url_for, render_template
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from src import api, db, ma, create_app, Config, bp, bcrypt, jwt, admin, login_manager
# config = confi... |
191300 | from AnyQt.QtGui import QPalette
from AnyQt.QtCore import Qt
import pyqtgraph as pg
pg.setConfigOption("background", "w")
pg.setConfigOption("foreground", "k")
pg.setConfigOptions(antialias=True)
def create_palette(colors):
p = QPalette()
for role, color in colors.items():
p.setColor(role, color)
... |
191338 | import pandas as pd
import matplotlib.pyplot as plt
my_dataset1 = pd.read_excel('Smith_glass_post_NYT_data.xlsx', sheet_name='Supp_traces')
x = my_dataset1.Zr
y = my_dataset1.Th
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x, y, marker='s', color='#ff464a', edgecolor='#000000')
ax1.set_title("using ... |
191348 | import os
import sys
import json
import webbrowser
import sublime
import sublime_plugin
from threading import Thread, Timer, Event
from .SoftwareUtil import *
from .CommonUtil import *
from .SoftwareUserStatus import *
from .SlackHttp import *
try:
#python2
from urllib import urlencode
except ImportError:
#python3
... |
191363 | import re
from geom2d import Circle, Point, Rect, Size, Segment
from geom2d import make_polygon_from_coords
__NUM_RE = r'\d+(\.\d+)?'
__CIRC_RE = rf'circ (?P<cx>{__NUM_RE}) (?P<cy>{__NUM_RE}) ' \
rf'(?P<r>{__NUM_RE})'
__RECT_RE = rf'rect (?P<ox>{__NUM_RE}) (?P<oy>{__NUM_RE}) ' \
rf'(?P<w>{__NUM_RE}) (?P<h>{... |
191369 | import json
DROPLETS_FILE = "droplets.json"
def get_droplets():
with open(DROPLETS_FILE, "r") as f:
data = f.read()
if not data:
return []
else:
return json.loads(data)
def main():
for droplet in get_droplets():
print droplet["name"]
print dropl... |
191428 | from urllib2 import HTTPError
class MockHTTPError(HTTPError):
def __init__(self, code):
super(MockHTTPError, self).__init__('https://thebluealliance.com', code, 'mock', {}, None)
|
191472 | import os
import yaml
with open('neptune.yaml') as f:
config = yaml.load(f)
exp_name = config['name']
exp_root = config['parameters']['solution_dir']
data_dir = config['parameters']['data_dir']
os.makedirs(exp_root, exist_ok=True)
IMAGE_COLUMNS = ['Image']
SHAPE_COLUMNS = ['height', 'width']
LOCALIZER_TARGET_COL... |
191498 | from colosseum.constants import AUTO, BLOCK, RTL, SOLID
from colosseum.declaration import CSS
from ...utils import LayoutTestCase, TestNode
class WidthTests(LayoutTestCase):
def test_no_horizontal_properties(self):
node = TestNode(
name='div', style=CSS(display=BLOCK, height=10)
)
... |
191539 | import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
#parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
#parser.add_argument("-f", "--file", type=str, help="Voxel file (.vxl)", required=True)
#args = parser.parse_args()
## Voxel-A lens
k1 = -0.158396... |
191549 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='1'
from os import listdir
import sys
import time
import argparse
import tools.ops
import subprocess
import numpy as np
import tensorflow as tf
import scipy.misc as sm
from models.mfb_net_cross import *
from tools.utilities import *
from tools.ops import *
parser = argpa... |
191569 | from .loopback import Loopback # noqa
from .dataleakageprevention import DataLeakagePreventionFileSystem # noqa
|
191683 | import torch
import numpy as np
import matplotlib.pyplot as plt
from operator import itemgetter
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import ListedColormap
from sklearn.metrics import confusion_matrix, roc_curve, precision_recall_curve
plt.style.use('fivethirtyeight')
def odds(prob):
retur... |
191711 | import json
import shutil
from typing import Any, Dict
import joblib
from sklearn.pipeline import Pipeline
def save_model(
pipe: Pipeline,
target_names_mapping: Dict[int, str],
config: Dict[str, Any],
) -> None:
"""Save:
- model pipeline (tf-idf + logreg)
- target names mapping
... |
191744 | import pytest
from pyDEA.core.models.envelopment_model_base import EnvelopmentModelBase
from pyDEA.core.models.envelopment_model import EnvelopmentModelOutputOriented
from pyDEA.core.models.envelopment_model_decorators import DefaultConstraintCreator
from pyDEA.core.models.envelopment_model import EnvelopmentModelOutp... |
191753 | from django import forms
from .models import Article
from .models import BoardType
from django_summernote.widgets import SummernoteWidget
# 게시글 폼
class ArticleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix','')
super(ArticleForm,self).__init__(*args,**... |
191764 | from distutils.core import setup
from Cython.Build import cythonize
setup(
name='Great Circle v2',
ext_modules=cythonize("great_circle_v2.pyx"),
)
|
191776 | import sys
sys.path.append('..')
import re
import urllib
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
from newsplease import NewsPlease
def get_content_onlinekhabar(link):
"""This function extract the contants from onlinakhabar.com
Arguments:
link {string} -- [Link ... |
191795 | import unittest
import unittest.mock
import edifice._component as component
import edifice.engine as engine
import edifice.base_components as base_components
from edifice.qt import QT_VERSION
if QT_VERSION == "PyQt5":
from PyQt5 import QtWidgets
else:
from PySide2 import QtWidgets
if QtWidgets.QApplication.in... |
191806 | from enum import Enum
class ModelWeightsStatus(Enum):
NO_INFO = 0
SUCCESS = 1
MODEL_NOT_FOUND = 2
WIP = 3 |
191822 | import parl
from parl import layers
class Model(parl.Model):
def __init__(self, act_dim):
self.conv1 = layers.conv2d(num_filters=32, filter_size=3, stride=2, padding=1, act='relu')
self.conv2 = layers.conv2d(num_filters=32, filter_size=3, stride=2, padding=1, act='relu')
self.conv3 = layer... |
191846 | from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def send_job_tests_details(created, instance):
def data():
result = {}
# Test instance update for tests table
test_item = dict()
test_item['uuid'] = instance.uuid
if instance.start_time:... |
191862 | from functools import partial
from typing import Any, Dict, List, Optional, Tuple, Union
import havsfunc as haf
import lvsfunc as lvf
import vapoursynth as vs
import vardefunc as vdf
from vsutil import (depth, fallback, get_depth, get_w, get_y, insert_clip,
iterate, join, plane)
core = vs.core
d... |
191870 | from parsl import python_app
import pytest
from parsl.tests.configs.htex_local import fresh_config
local_config = fresh_config()
@python_app
def compute_descript(size=1000):
import numpy as np
x = np.array(list(range(0, size)), dtype=complex).astype(np.float32)
return x
@pytest.mark.local
def test_1480(... |
191876 | from server.config import ParseConfig
from server.parsing.parse_class_file import ParseClassFile
from collections import namedtuple
# create parser instance
parser = ParseClassFile.from_object(ParseConfig)
# create namedtuple instance called "meta_data" - with variables that will be inserted to the Attendance class
At... |
191885 | from startX.serivce.v1 import StartXHandler, get_m2m_display
from django.urls import reverse
from django.utils.safestring import mark_safe
from .base_promission import PermissionHandler
class HomeworkHandler(PermissionHandler, StartXHandler):
def display_outline(self, model=None, is_header=None, *args, **kwargs)... |
191894 | from social.pipeline.partial import save_status_to_session
save_status_to_session # placate pyflakes
|
191897 | def is_k_anonymous(df, partition, sensitive_column, k=3):
"""
:param df: The dataframe on which to check the partition.
:param partition: The partition of the dataframe to check.
:param sensitive_column: The name of the sensitive column
:param k: The desired k
... |
192052 | from src.scripts.emr_test_steps import lambda_handler as emr_steps
def test_emr_steps(create_cluster, lambda_context):
cluster_id = create_cluster.get('JobFlowId')
assert 'j-' in cluster_id
cluster_name = create_cluster.get('Name')
steps_request = {
"api_request_id": "test_bootstrap_actions"... |
192065 | class BaseDecoder(object):
def __init__(self, name="BaseDecoder"):
self.name = name
print(name)
def decode(self, **kwargs):
"""
Using for greedy decoding for a given input, may corresponding with gold target,
return the log_probability of decoder steps.
"""
... |
192066 | import random
import typing
from typing import List, Callable
from hearthstone.simulator.agent.actions import StandardAction, DiscoverChoiceAction, RearrangeCardsAction
from hearthstone.simulator.agent.agent import Agent
if typing.TYPE_CHECKING:
from hearthstone.simulator.core.cards import MonsterCard
from he... |
192078 | from __future__ import unicode_literals
from binascii import Error as BinaryError
from base64 import b16encode, b16decode
from django.apps import apps
from django.core.exceptions import FieldDoesNotExist
from django.http import Http404
from django.shortcuts import get_object_or_404
from .exceptions import B16Decodin... |
192118 | import pservlet
def init(args):
return (pservlet.pipe_define("in", pservlet.PIPE_INPUT),
pservlet.pipe_define("out", pservlet.PIPE_OUTPUT))
def execute(s):
while True:
tmp = pservlet.pipe_read(s[0])
if not tmp:
if not pservlet.pipe_eof(s[0]):
pservlet.pi... |
192128 | import torch.nn as nn
import torch
import wandb
class FlowLoss(nn.Module):
def __init__(self,):
super().__init__()
def forward(self, sample, logdet, logger, mode='eval'):
nll_loss = torch.mean(nll(sample))
assert len(logdet.shape) == 1
nlogdet_loss = -torch.mean(logdet)
... |
192203 | import getpass
import os
import tempfile
import builtins
import yaml
LOCAL_DEFAULT_USERNAME = "paradrop"
LOCAL_DEFAULT_PASSWORD = ""
def format_result(data):
"""
Format a result from an API call for printing.
"""
if data is None or data == []:
return ""
return yaml.safe_dump(data, defau... |
192224 | import abc
from typing import Callable, TypeVar, Generic, Union, cast, Any
from amino.logging import Logging
from amino import LazyList, Boolean, __, _, Either, Right, Maybe, Left, L, Map, curried
from amino.boolean import false, true
from amino.tc.base import Implicits
from amino.tc.flat_map import FlatMap
from amino... |
192252 | import joblib
import numpy as np
from flask import Flask, app
from flask import jsonify # herramienta para trabajar cno arch json
app = Flask(__name__)
#<NAME>
@app.route('/predict', methods=['GET'])
def predict():
"""Funcion que se expondra en la direccion 8080/predict y que muestra la prediccion hecha
por ... |
192260 | import torch
import torch.nn
import torch.nn.functional
import torch.optim
import torch.utils.data
import numpy
import matplotlib
import matplotlib.pyplot
import time
import torchvision
from torchvision import *
import matplotlib.colors
import socket
device = torch.device("cuda:0")
class DrNet(torch.nn.Module):
... |
192263 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestZigZag(self, root: Tre... |
192303 | from http import HTTPStatus
import pytest
import requests
from rotkehlchen.constants.assets import A_ETH, A_EUR, A_KRW, A_USD
from rotkehlchen.fval import FVal
from rotkehlchen.tests.utils.api import (
api_url_for,
assert_error_response,
assert_proper_response,
assert_proper_response_with_result,
)
... |
192332 | import re
import itertools
from .dict_changed import DictChanged
class UnicodeMap(DictChanged):
'''Represents PDF "ToUnicode" optional data structure that controls character encoding'''
NotParsed = object() #: for internal use
def __init__(self, text):
self._text = text
super().__init__(... |
192348 | from opnsense_cli.api.base import ApiBase
class Export(ApiBase):
MODULE = "haproxy"
CONTROLLER = "export"
"""
Haproxy ExportController
"""
@ApiBase._api_call
def config(self, *args):
self.method = "get"
self.command = "config"
@ApiBase._api_call
def diff(self, *ar... |
192381 | import filestack.models
from filestack.utils import requests
class AudioVisual:
def __init__(self, url, uuid, timestamp, apikey=None, security=None):
"""
AudioVisual instances provide a bridge between transform and filelinks, and allow
you to check the status of a conversion and convert t... |
192407 | import pytest
@pytest.mark.parametrize(
"server_options,port",
[("--debug", 8090), ("--debug --mathjax", 8090), ("--debug", 9090)],
)
@pytest.mark.parametrize("method", ["curl", "stdin"])
def test_math(browser, Server, server_options, port, method):
with Server(server_options, port) as srv:
srv.s... |
192410 | from matplotlib import pyplot as plt
def init_histogram(axis, sub_dataframe):
centroids = sub_dataframe['bin_centroid']
bins = len(sub_dataframe)
weights = sub_dataframe['bin_count']
min_bin = sub_dataframe['bin_lower_bound'].min()
max_bin = sub_dataframe['bin_upper_bound'].max()
counts_, bins... |
192429 | from torch import Tensor
from typing import Any
from typing import Dict
from typing import List
from typing import Tuple
from typing import Union
from typing import Callable
from typing import Optional
from functools import partial
from torchvision.datasets import MNIST
from ....data import Transforms
from ....types i... |
192433 | import voluptuous
from pg_discuss import ext
#: Minimum allowed comment length
MIN_COMMENT_LENGTH = 3
#: Maximum allowed comment length
MAX_COMMENT_LENGTH = 65535
class ValidateCommentLen(ext.ValidateComment):
"""Extension to add a validation rule that enforces a minimum and
maximum comment length.
"""
... |
192481 | import random
from indy import ledger, did
import json
from perf_load.perf_req_gen import RequestGenerator
from perf_load.perf_utils import random_string
class RGPoolNewDemotedNode(RequestGenerator):
_req_types = ["0"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
se... |
192532 | import numpy as np
import argparse
def patch_generator(img, patch_size, stride):
h, w, _ = img.shape
patch_t = []
for i in range(0, h-patch_size+1, stride):
for j in range(0, w-patch_size+1, stride):
patch_t.append(img[i: i + patch_size, j: j + patch_size, :])
return patch_t
def ... |
192540 | from django.conf.urls import url
from drugs import views
urlpatterns = [
url(r'^drugbrowser', views.drugbrowser, name='drugbrowser'),
url(r'^drugstatistics', views.drugstatistics, name='drugstatistics'),
url(r'^drugmapping', views.drugmapping, name='drugmapping'),
url(r'^nhs/section/(?P<slug>[\w|\W... |
192542 | import urllib.request
from functools import wraps
def sanitize_field(field):
return urllib.request.quote(field.encode("UTF-8"), safe="")
def sanitize_string_args(function):
"""Helper decorator that ensures that all arguments passed are url-safe."""
@wraps(function)
def sanitized_function(*args, **k... |
192550 | import os
from future import standard_library
with standard_library.hooks():
import configparser
def read_config(paths=()):
config = {}
fs_config = configparser.ConfigParser()
fs_config.read(paths)
config['cups_uri'] = fs_config.get('main', 'cups_uri')
config['ipptool_path'] = fs_config.get('... |
192552 | import torch
import torch.nn as nn
import torchvision
class Conv2dCReLU(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size,stride,padding):
super(Conv2dCReLU, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels,out_channels=out_channels,kernel_size=kernel_size,stride=stri... |
192606 | import sys
import matplotlib as mpl
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from tensorboardX import SummaryWriter
from torch import nn
from torch.autograd import Variable
from tqdm import trange
import gaussian
import util
from util i... |
192665 | import setuptools #enables develop
import os
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
from edgeml_pytorch.utils import findCUDA
if findCUDA() is not None:
setuptools.setup(
name='fastgrnn_cuda',
ext_modules=[
CUDAExtension('fastgrnn_cuda', [
'f... |
192668 | from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode
from armulator.armv6.bits_ops import add, sub
from bitstring import BitArray
from armulator.armv6.arm_exceptions import UndefinedInstructionException
from armulator.armv6.enums import InstrSet
class Rfe(AbstractOpcode):
def __init__(self, incremen... |
192670 | import aio_pika
import asyncio
import logging
import json
import os
from tornado.httpclient import AsyncHTTPClient
from tornado.iostream import StreamClosedError
from tornado.web import HTTPError, RequestHandler
from urllib.parse import urlencode
import zipfile
from datamart_core.common import log_future
from datamart... |
192687 | import flask
import os
app = flask.Flask(__name__)
FILE_PATH = 'data/files/'
def check_path(path):
path = os.path.normpath(os.path.join(FILE_PATH, path))
if not path.startswith(FILE_PATH):
return flask.abort(400)
return path
def get_tmp_path(path):
dirpath, basename = os.path.split(path)... |
192714 | import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from SVC_Utils import *
from sklearn.metrics import roc_curve, auc
# determine device to run network on (runs on gpu if available)
device = torch.device("cuda:0" if torch.cuda.is_avail... |
192728 | from pip import get_installed_distributions
from pip.commands import install
install_cmd = install.InstallCommand()
options, args = install_cmd.parse_args([package.project_name
for package in
get_installed_distributions()])
options.upgra... |
192768 | from abc import ABCMeta, abstractmethod
import logging
from raco.expression.visitor import ExpressionVisitor
LOG = logging.getLogger(__name__)
class Algebra(object):
__metaclass__ = ABCMeta
@abstractmethod
def opt_rules(self, **kwargs):
raise NotImplementedError("{op}.opt_rules()".format(op=typ... |
192775 | from __future__ import with_statement # this is to work with python2.5
from validation import vworkspace
with vworkspace() as w:
w.props.PRETTYPRINT_FINAL_RETURN = True
w.props.PRETTYPRINT_ALL_LABELS = True
w.props.PRETTYPRINT_EMPTY_BLOCKS = True
w.props.PRETTYPRINT_UNSTRUCTURED = True
w.props... |
192846 | import os
import sys
import json
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class WindowClassificationTrainUpdateSchedulerParam(QtWidgets.QWidget):
forward_loss_param = QtCore.pyqtSignal();
backward_optimizer_param = QtCore.pyqtSignal();
def __init__(se... |
192853 | from collections import namedtuple
from xml.dom import minidom
BOOKMARK_COLOR_NONE = "-1"
BOOKMARK_COLOR_BLUE = "0"
BOOKMARK_COLOR_GREEN = "1"
BOOKMARK_COLOR_YELLOW = "2"
BOOKMARK_COLOR_ORANGE = "3"
BOOKMARK_COLOR_RED = "4"
LINK_STYLE_NORMAL = "0"
LINK_STYLE_DASHED = "1"
LINK_STYLE_DOTTED = "2"
LINK_STYLE_DASHDOT = "... |
192856 | from graphish.connector import GraphConnector
from graphish.search import Search
from graphish.delete import Delete
from graphish.mailfolder import MailFolder |
192866 | import requests
from bs4 import BeautifulSoup
import os
from tools import jsonl
base_url = 'https://www.supremecourt.gov/oral_arguments'
with jsonl.JWZ('corpus_staging/manifest.jsonl.gz') as manifest:
year = 2010
while True:
page = requests.get('{}/argument_audio/{}'.format(base_url, year))
... |
192915 | import errno
import logging
import os
import string
import time
import urllib.request
from collections import namedtuple
from errno import ENOENT
from urllib.parse import urlparse
from markupsafe import escape
from galaxy.datatypes import sniff
from galaxy.exceptions import (
ConfigurationError,
MessageExcept... |
192948 | from setuptools import setup
setup(
name='vesseg',
version='0.2.0',
author='<NAME>',
author_email='<EMAIL>',
install_requires=[
'click',
'tensorflow-gpu',
'niftynet',
'SimpleITK',
'vtk',
'tqdm',
],
entry_points={
'console_scripts': [
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.