id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
108442 | import os
import json
from numbers import Number
from collections import Iterable, Mapping
from operator import itemgetter
from .config import set_class_path, JavaSettingsConstructorParams
set_class_path()
from jnius import autoclass, MetaJavaClass
# Java DataTypes
jMap = autoclass('java.util.HashMap')
jArrayList = ... |
108444 | from django.urls import path
from django.conf.urls import url
from project_first_app.views import *
urlpatterns = [
path(r'getowners/<int:ow_id>',detail,name='detail'),
path(r'allowners',show_owners,name='showowners'),
path(r'allcars', Show_cars.as_view(template_name="cars_list.html")),
path(r'... |
108512 | import FWCore.ParameterSet.Config as cms
ecalSCDynamicDPhiParametersESProducer = cms.ESProducer("EcalSCDynamicDPhiParametersESProducer",
# Parameters from the analysis by <NAME> [https://indico.cern.ch/event/949294/contributions/3988389/attachments/2091573/3514649/2020_08_26_Clustering.pdf]
# dynamic dPhi para... |
108532 | import unittest, penmon as pm
class Test(unittest.TestCase):
def test_daylight_hours(self):
station = pm.Station(41.42, 109)
day = station.day_entry(135)
day.temp_min = 19.5
day.temp_max = 28
self.assertEqual(day.daylight_hours(), 14.3, "daylighth_hours")
if _... |
108574 | from pymol.cgo import *
from pymol import cmd
from random import random, seed
from chempy import cpv
# CGO cones
# first draw some walls
obj = [
COLOR, 1.0, 1.0, 1.0,
BEGIN, TRIANGLE_STRIP,
NORMAL, 0.0, 0.0, 1.0,
VERTEX, 0.0, 0.0, 0.0,
VERTEX, 10.0, 0.0, 0.0,
VERTEX, 0.0, 10.0, 0.0,
... |
108651 | import pandas as pd
import glob
import os
import copy
'''
BankStatementAnalyzer --> To instantiate this class, following parameters are mandatory:
statementfolder ---> Local file system folder where your bank statements are present. The folder can contain
multiple files. All the files shoul... |
108686 | import os
import tempfile
import zipfile
from datetime import datetime, timedelta, timezone
import boto3
import pytz
from busshaming.models import Feed, FeedTimetable
from busshaming.data_processing import upsert_timetable_data
S3_BUCKET_NAME = os.environ.get('S3_BUCKET_NAME', 'busshaming-timetable-dumps')
FEED_TIM... |
108723 | from unittest import mock
from nimoy.specification import Specification
class FeatureBlockRuleEnforcerSpec(Specification):
def where_function_is_called_before_feature(self):
with expect:
class SomeSpec(Specification):
def test_something(self, where_visited=False):
... |
108738 | import requests
import Models.network
LEADERBOARD_HEROKU = 'https://lmtservice.herokuapp.com/leaderboard/'
HISTORY_HEROKU = 'https://lormaster.herokuapp.com/history/'
SEARCH_HEROKU = 'https://lormaster.herokuapp.com/search/'
TAG_HEROKU = 'https://lormaster.herokuapp.com/tag/'
class Heroku():
def __init__(self, l... |
108764 | from pyradioconfig.parts.bobcat.calculators.calc_aox import Calc_AoX_Bobcat
class calc_aox_viper(Calc_AoX_Bobcat):
pass
|
108774 | from fastecdsa.curve import Curve
from fastecdsa.point import Point
from starkware.crypto.signature import (
ALPHA, BETA, CONSTANT_POINTS, EC_ORDER, FIELD_PRIME, N_ELEMENT_BITS_HASH, SHIFT_POINT)
curve = Curve(
'Curve0',
FIELD_PRIME,
ALPHA,
BETA,
EC_ORDER,
*SHIFT_POINT)
LOW_PART_BITS = 24... |
108780 | import logging
import os
import random
import socket
from typing import Tuple
import magic
import yaml
import utils
from validators import port_validation, check_port_open
LOGGER_FILE = "./logs/server.log"
# Настройки логирования
logging.basicConfig(
format="%(asctime)-15s [%(levelname)s] %(funcName)s: %(message... |
108842 | def poly(a, x):
val = 0
for ai in reversed(a):
val *= x
val += ai
return val
def diff(a):
return [a[i + 1] * (i + 1) for i in range(len(a) - 1)]
def divroot(a, x0):
b, a[-1] = a[-1], 0
for i in reversed(range(len(a) - 1)):
a[i], b = a[i + 1] * x0 + b, a[i]
a.p... |
108875 | import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics.classification import accuracy_score, f1_score
def prediction_score(train_X, train_y, test_X, test_y, metric, model):
# if the train labels are always the same
value... |
108939 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.hvac_templates import HvactemplateSystemPackagedVav
log = logging.getLogger(__name__)
class TestHvactemplateSystemPackagedVav(unittest.TestCase):
def setUp(self):
s... |
108986 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .Model import Model
from .TransE import TransE
from .TransD import TransD
from .TransR import TransR
from .TransH import TransH
from .DistMult import DistMult
from .ComplEx import ComplEx
from .RESCAL impo... |
108992 | class NCBaseError(Exception):
def __init__(self, message) -> None:
super(NCBaseError, self).__init__(message)
class DataTypeMismatchError(Exception):
def __init__(self, provided_data, place:str=None, required_data_type:str=None) -> None:
message = f"{provided_data} datatype isn't supported for... |
108994 | from accessify.access import (
accessify,
private,
protected,
)
from accessify.interfaces import (
implements,
throws,
)
|
109029 | import json
import os
import subprocess
import base64
import sys
from tree.node import Node
from util.config_parser import parse_configs
from util.file_iterator import process_directory
from util.variable_resolver import resolve_variables
from util.should_run import should_run
from values.array import handle_array_arg... |
109041 | import tkinter as tk
from ttkbootstrap import Style
from random import choice
root = tk.Tk()
root.minsize(500, 500)
style = Style('superhero')
def new_theme():
theme = choice(style.theme_names())
print(theme)
style.theme_use(theme)
btn = tk.Button(root, text='Primary')
btn.configure(command=new_theme)
b... |
109054 | from config.redfish1_0_config import config
from config.auth import *
from config.settings import *
from logger import Log
from json import loads, dumps
import pexpect
import pxssh
import subprocess
LOG = Log(__name__)
class Auth(object):
"""
Class to abstract python authentication functionality
"""
@... |
109091 | from yacv.grammar import Production
from yacv.constants import YACV_EPSILON
from pprint import pformat
class AbstractSyntaxTree(object):
def __init__(self, *args):
if len(args) == 0:
self.root = None
self.desc = []
self.prod_id = None
self.node_id = None
... |
109096 | from ext import parent
class A(parent):
def fn(self):
self.parent_fn()
a = A()
a.fn()
|
109120 | import pictureobject_functions as pic_functions
class Picture_object():
"""Gives an interface to access the colors of a picture."""
def __init__(self, filepath, conf):
self.conf = conf
self.filepath = filepath
self.is_changed = False
self.filename = pic_functions.get_filename_... |
109135 | from . import basis
from . import prior
from . import lik
from . import inf
from .core import model
from .predictor import predictor
__all__ = ["basis", "prior", "lik", "inf", "model", "predictor"]
|
109147 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import i2c, sensor
from esphome.const import (
CONF_COLOR_TEMPERATURE,
CONF_GAIN,
CONF_ID,
CONF_ILLUMINANCE,
CONF_GLASS_ATTENUATION_FACTOR,
CONF_INTEGRATION_TIME,
DEVICE_CLASS_ILLUMINANCE,
ICON_LI... |
109204 | from functools import wraps
from typing import Any, Optional
from pedantic.type_checking_logic.check_docstring import _check_docstring
from pedantic.constants import ReturnType, F
from pedantic.models.decorated_function import DecoratedFunction
from pedantic.models.function_call import FunctionCall
from pedantic.env_v... |
109214 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
from gensim.models.keyedvectors import KeyedVectors
from config import params, data, w2v
class RNN(nn.Module):
def __init__(self, params, data):
super(RNN, self).__init__()
sel... |
109265 | from dataviva.api.hedu.models import Ybu, Ybc_hedu, Yu, Yuc, Yc_hedu, Ybuc
from dataviva.api.attrs.models import University as uni, Course_hedu, Bra
from dataviva import db
from sqlalchemy.sql.expression import func, desc, not_
class University:
def __init__(self, university_id):
self._hedu = None
... |
109299 | from json import dumps
from .utils import debug_coro
from aiohttp import ClientSession
from ..logger import get_logger
logger = get_logger("LPBv2.Caller")
class Caller:
def __init__(self):
self.headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}... |
109330 | from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.standard.hid import HIDService
from kmk.hid import AbstractHID
BLE_APPEARANCE_HID_KEYBOARD = 961
# Hardcoded in CPy
MAX_CONNECTIONS = 2
class BLEHID(AbstractHID):
def post_init(... |
109352 | from setuptools import setup
from sapversion import version
setup(
name = 'sapling',
version = version(),
author = '<NAME>',
author_email = '<EMAIL>',
description = 'A git porcelain to manage bidirectional subtree syncing with foreign git '
'repositories',
license = 'Apache ... |
109418 | from django.db.models.query import QuerySet
from odata_query.grammar import ODataLexer, ODataParser # type: ignore
from .django_q import AstToDjangoQVisitor
def apply_odata_query(queryset: QuerySet, odata_query: str) -> QuerySet:
"""
Shorthand for applying an OData query to a Django QuerySet.
Args:
... |
109437 | import unittest
import pyrtl
import pyrtl.corecircuits
from pyrtl.rtllib import aes, testingutils
class TestAESDecrypt(unittest.TestCase):
"""
Test vectors are retrieved from:
http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
"""
def setUp(self):
pyrtl.reset_working_block()
... |
109462 | import caffe.proto.caffe_pb2 as caffe_pb2
from os.path import join
from caffe_config import CaffeConfig
from to_string import to_string
class SolverConfig(CaffeConfig):
def __init__(self, base_lr=0.001, lr_policy="step", solver_type="SGD", step_size=10000, display=20, momentum=0.9, gamma=0.1, weight_decay=5e-4):
... |
109465 | import torch
try:
from torch.utils.data import IterableDataset
except ImportError:
class IterableDataset:
pass
class BatchChecker:
def __init__(self, data, init_counter=0):
self.counter = init_counter
self.data = data
self.true_batch = None
def check(self, batch):
... |
109471 | import vessel_scoring.add_measures
import six
class BaseModel(object):
# def train_on_messages(self, messages):
# messages = AddMeasures(messages, self.windows)
# y_train = utils.is_fishy(train_data)
# model.fit(train_data, y_train)
# return model
def predict_messages(s... |
109496 | from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser, models.Model):
email = models.EmailField(unique = True)
class Choices(models.Model):
choice = models.CharField(max_length=5000)
is_answer = models.BooleanField(default=False... |
109507 | import hashlib
import hmac
from Crypto.Protocol.KDF import PBKDF2
def mnemonics_to_seed(seed, passphrase=b""):
salt = b"mn<PASSWORD>" + passphrase
def prf(p, s):
hx = hmac.new(p, msg=s, digestmod=hashlib.sha512)
return hx.digest()
res = PBKDF2(password=seed, salt=salt, dkLen=64, prf=prf... |
109514 | from tir import Webapp
import unittest
class CTBA211(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGACTB", "30/06/2015", "T1", "M PR 02 ", "34")
inst.oHelper.Program("CTBA211")
###################################... |
109515 | import mimetypes
import os
import boto3
BUCKET = "hc-flask-assets"
def write_to_s3(bucket_name: str, from_file: str, to_file: str, mimetype) -> None:
s3 = boto3.resource("s3")
s3.Bucket(bucket_name).upload_file(
from_file, to_file, ExtraArgs={"ACL": "public-read", "ContentType": mimetype}
)
d... |
109549 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def python_dependencies_early():
http_archive(
name = "rules_python",
url = "https://github.com/bazelbuild/rules_python/releases/download/0.0.1/rules_python-0.0.1.tar.gz",
sha256 = "aa96a691d3a8177f3215b14b0edc9641787abaaa... |
109565 | import math
def buildSparseTable(arr, n):
for i in range(0, n):
lookup[i][0] = arr[i]
j = 1
while (1 << j) <= n:
i = 0
while (i + (1 << j) - 1) < n:
if (lookup[i][j - 1] <
lookup[i + (1 << (j - 1))][j - 1]):
lookup[i][j] = lookup[i][j - 1]
else:
lookup[i][j] = lookup[i + (1 << (... |
109574 | from datetime import datetime
from django.conf import settings
import requests
import olympia.core.logger
from olympia.devhub.models import BlogPost
log = olympia.core.logger.getLogger('z.cron')
def update_blog_posts():
"""Update the blog post cache."""
items = requests.get(settings.DEVELOPER_BLOG_URL, ... |
109577 | import daiquiri.core.env as env
FILES_BASE_PATH = env.get_abspath('FILES_BASE_PATH')
FILES_BASE_URL = env.get('FILES_BASE_URL')
|
109588 | import sys
import django
django.setup()
from busshaming.data_processing import realtime_validator
if __name__ == '__main__':
if len(sys.argv) != 2:
print(f'Usage: {sys.argv[0]} <route_id>')
sys.exit(1)
realtime_validator.validate_route(sys.argv[1])
|
109623 | from clang.cindex import TranslationUnit
from tests.cindex.util import get_cursor
def test_comment():
files = [('fake.c', """
/// Aaa.
int test1;
/// Bbb.
/// x
void test2(void);
void f() {
}
""")]
# make a comment-aware TU
tu = TranslationUnit.from_source('fake.c', ['-std=c99'], unsaved_files=files,
... |
109638 | import os
import numpy as np
from numpy.lib.stride_tricks import as_strided
import nibabel as nib
def nib_load(file_name):
proxy = nib.load(file_name)
data = proxy.get_data().astype('float32')
proxy.uncache()
return data
def crop(x, ksize, stride=3):
shape = (np.array(x.shape[:3]) - ksize)/stride ... |
109672 | import os
import tuned.logs
from . import base
from tuned.utils.commands import commands
class strip(base.Function):
"""
Makes string from all arguments and strip it
"""
def __init__(self):
# unlimited number of arguments, min 1 argument
super(strip, self).__init__("strip", 0, 1)
def execute(self, args):
i... |
109714 | from enum import Enum
class ItemProperty(Enum):
"""
See crawl wiki for lists of these:
weapons: http://crawl.chaosforge.org/Brand
armour: http://crawl.chaosforge.org/Ego
"""
NO_PROPERTY = 0
# Melee Weapon Brands
Antimagic_Brand = 1
Chaos_Brand = 2
Disruption_Brand = 3
Dist... |
109721 | import logging
import json
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
try:
req_body = req.get_json()
request_as_text = json.dumps(req_body, default=lambda o: o.__dict__)
... |
109732 | from app.tests.utilities import selenium_utility
class SelectTracks(selenium_utility.SeleniumUtility):
_first_playlist = '//li[@data-toggle="collapse"][1]'
_track = '(//li[contains(@class, "track")])[1]'
_next_btn = '//button[@id="next-btn"]'
def __init__(self, driver):
self.driver = driver
... |
109760 | from unittest import TestCase
import unittest
from equadratures import *
import numpy as np
from copy import deepcopy
def model(x):
return x[0]**2 + x[1]**3 - x[0]*x[1]**2
class TestF(TestCase):
def test_tensor_grid_with_nans(self):
# Without Nans!
param = Parameter(distribution='uniform', lo... |
109779 | import unittest
from rdkit import Chem
from reinvent_chemistry.library_design import BondMaker, AttachmentPoints
from reaction_filters.reaction_filter_enum import ReactionFiltersEnum
from reaction_filters.reaction_filter import ReactionFilter
from running_modes.configurations import ReactionFilterConfiguration
from t... |
109863 | from pathlib import Path
current_dir = Path(__file__).parent.absolute()
import torch
import torch.nn as nn
from einops.layers.torch import Rearrange
# [2021-06-30] TD: Somehow I get segfault if I import pl_bolts *after* torchvision
from pl_bolts.datamodules import CIFAR10DataModule
from torchvision import transforms,... |
109947 | import enolib
def test_querying_a_missing_field_on_the_document_when_all_elements_are_required_raises_the_expected_validationerror():
error = None
input = ("")
try:
document = enolib.parse(input)
document.all_elements_required()
document.field('field')
except enolib.V... |
109958 | import torch
import torch.nn as nn
import torchvision
import torch.backends.cudnn as cudnn
import torch.optim
import os
import sys
import argparse
import time
import DCE.dce_model
import numpy as np
from torchvision import transforms
from PIL import Image
import glob
import time
from tqdm import tqdm
# os.environ['CUDA... |
109981 | import argparse
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from pylab import rcParams
import structuring
def plot_frame(data_path, frame_index):
"""Show landmarks of a frame into a graph.
Arguments:
csv {str} -- path to the .csv file
frame_index {int} -- index ... |
109989 | import logging
from flask import Blueprint
import ckan.plugins.toolkit as tk
from ckanext.hdx_users.controller_logic.dashboard_dataset_logic import DashboardDatasetLogic
log = logging.getLogger(__name__)
render = tk.render
get_action = tk.get_action
request = tk.request
g = tk.g
h= tk.h
_ = tk._
hdx_user_dashboard... |
110000 | import random
import urllib
from flaskwallet import app
from flaskwallet import session
from settingsapp.helpers import get_setting
def real_format(account):
if account == '__DEFAULT_ACCOUNT__':
account = ''
return account
def human_format(account):
if account == '':
account = '__DEFAULT... |
110052 | from __future__ import print_function, unicode_literals
import sys
from workflow import Workflow, web, ICON_ERROR, ICON_SETTINGS
from utils import parse_args, is_match
from settings import UPDATE_SETTINGS, HELP_URL, LEETCODE_URL, LC_TOPICS
class SearchResult(object):
def __init__(self, title, subtitle, url):
... |
110055 | import math
import random
from typing import Tuple
from .. import base
class Friedman(base.SyntheticDataset):
"""Friedman synthetic dataset.
Each observation is composed of 10 features. Each feature value is sampled uniformly in [0, 1].
The target is defined by the following function:
$$y = 10 sin(... |
110069 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class backWarp(nn.Module):
"""
A class for creating a backwarping object.
This is used for backwarping to an image:
Given optical flow from frame I0 to I1 --> F_0_1 and frame I1,
it generates I0 <-... |
110084 | import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
model = Sequential()
model.add(Dense(units=50, input_dim=1, activation='relu'))
model.add(Dense(units=50, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
model.... |
110085 | from typing import Dict, Tuple
import numpy as np
from . import functional as F
class Padding:
"""Applies padding to image and target boxes"""
def __init__(self, target_size: Tuple[int, int] = (640, 640), pad_value: int = 0):
super(Padding, self).__init__()
self.pad_value = pad_value
... |
110121 | from time import time
from app import db
from util import elapsed
from util import safe_commit
import argparse
from models.person import make_person
from models.orcid import clean_orcid
from models.orcid import NoOrcidException
# needs to be imported so the definitions get loaded into the registry
import jobs_defs
... |
110142 | import random
import math
import torch
from PIL import Image, ImageOps, ImageEnhance, ImageDraw
from torchvision.transforms import functional as F
import transforms
from transforms import check_prob, PIL_INTER_MAP, RandomTransform
def rescale_float(level, max_val, param_max=10):
return float(level) ... |
110172 | from builtins import object
from rest_framework import serializers
from bluebottle.funding.base_serializers import PaymentSerializer, BaseBankAccountSerializer
from bluebottle.funding_vitepay.models import VitepayPayment, VitepayBankAccount
from bluebottle.funding_vitepay.utils import get_payment_url
class VitepayPay... |
110213 | import json
import logging
import boto3
import cfnresponse
import time
ec2_client = boto3.client('ec2')
logs_client = boto3.client('logs')
def boto_throttle_backoff(boto_method, max_retries=10, backoff_multiplier=2, **kwargs):
retry = 0
results = None
while not results:
try:
results ... |
110242 | import requests
def whois_more(IP):
result = requests.get('http://api.hackertarget.com/whois/?q=' + IP).text
print('\n'+ result + '\n')
|
110272 | from django.contrib.auth.models import User
import factory
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker('name')
email = factory.Sequence(lambda n: '<EMAIL>' % n)
class Meta:
model = User
|
110293 | import numpy as np
#import simpleaudio as sa
import scipy.io.wavfile as sw
'''
def audioplay(fs, y):
yout = np.iinfo(np.int16).max / np.max(np.abs(y)) * y
yout = yout.astype(np.int16)
play_obj = sa.play_buffer(yout, y.ndim, 2, fs)
'''
def wavread(wavefile):
fs, y = sw.read(wavefile)
if y.dtype == ... |
110299 | import pytest
pytest.importorskip("speedtest")
def test_load_module():
__import__("modules.core.speedtest")
|
110309 | from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from osmaxx.excerptexport.models import Export
def tracker(request, export_id):
export = get_object_or_404(Export, pk=export_id)
export.set_and_handle_new_status(request.GET['status'], incoming_request=request)
response ... |
110351 | from nighres.registration.apply_coordinate_mappings import apply_coordinate_mappings
from nighres.registration.apply_coordinate_mappings import apply_coordinate_mappings_2d
from nighres.registration.embedded_antsreg import embedded_antsreg
from nighres.registration.embedded_antsreg import embedded_antsreg_2d
from nighr... |
110364 | import logging
import os
import tempfile
from pathlib import Path
from cached_path.common import PathOrStr
logger = logging.getLogger(__name__)
class CacheFile:
"""
This is a context manager that makes robust caching easier.
On `__enter__`, an IO handle to a temporarily file is returned, which can
... |
110374 | import hashlib
from django.shortcuts import render, reverse, redirect
from .models import UseInfo, HostInfo
from remoteCMD.remote import Remote
# Create your views here.
def hash_password(password):
"""
md5加密
:param password:
:return:
"""
md5 = hashlib.md5()
md5.update(password.encode('utf-... |
110376 | class AcousticParam(object):
def __init__(
self,
sampling_rate: int = 24000,
pad_second: float = 0,
threshold_db: float = None,
frame_period: int = 5,
order: int = 8,
alpha: float = 0.466,
f0_floor: float = 71,
... |
110445 | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torch.distributions import Categorical, Independent, MixtureSameFamily, Normal
from torch.nn.modules.conv import Conv2d
import einops
from .helpers import Delta, batch_flatten, batch_u... |
110446 | import grpc
import pi_pb2
import pi_pb2_grpc
from concurrent import futures
def pi(client, k):
return client.Calc(pi_pb2.PiRequest(n=k)).value
def main():
channel = grpc.insecure_channel('localhost:8080')
client = pi_pb2_grpc.PiCalculatorStub(channel)
pool = futures.ThreadPoolExecutor(max_workers=1... |
110463 | import json
import logging
from channels.generic.websocket import AsyncWebsocketConsumer
from django_redis import get_redis_connection
from competitions.models import Submission
from utils.data import make_url_sassy
logger = logging.getLogger(__name__)
class SubmissionIOConsumer(AsyncWebsocketConsumer):
#
... |
110472 | from selenium.webdriver import Firefox
url = 'http://selenium.dunossauro.live/aula_05_a.html'
firefox = Firefox()
firefox.get(url)
div_py = firefox.find_element_by_id('python')
div_hk = firefox.find_element_by_id('haskell')
print(div_hk.text)
firefox.quit()
|
110527 | from unittest import TestCase
from feito import Messages
class MessagesTestCase(TestCase):
def test_format(self):
stub_messages = {
'messages': [{
'source': 'pylint',
'code': 'syntax-error',
'location': {
'path': 'tests/feit... |
110536 | from unittest.mock import Mock, ANY
from click.testing import CliRunner
from taskit.infrastructure.cli.taskit import cli, State
def test_cli_state(state):
assert isinstance(state, State)
def test_cli():
runner = CliRunner()
result = runner.invoke(cli, [])
assert result.exit_code == 0
|
110637 | import pickle
import json
import argparse
import cv2
import os
import numpy as np
import torch
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.patches as patches
import matplotlib.lines as lines
from tqdm import tqdm
import _init_paths
from core.config import cfg
from datasets_rel.p... |
110660 | import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
points = IN[0]
almostzero = IN[1]
struts = list()
# this function recursively finds all the pairs of points of the buckyball struts
def BuckyballStruts(points,struts):
firstpoint = points[0]
restofpoints = points[1:]
# measur... |
110663 | import math
import numpy as np
from ... import IntegerProgram, LinearProgram
from unittest import TestCase, main
class TestRelax(TestCase):
def test_relax(self) -> None:
A = np.array([
[1, 2, 3, 4],
[3, 5, 7, 9]
])
b = np.array([-9, 7])
c = np.array([1, 7, 1... |
110747 | import sys
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
PY26 = sys.version_info[0] == 2 and sys.version_info[1] == 6
if PY3:
from io import BytesIO as StringIO
from urllib.parse import urlparse
else:
from urlparse import urlparse # noqa
from cStringIO import StringIO # noqa
... |
110790 | import gzip
from typing import List
from typing import Set
import grequests
import progressbar as pb
import requests
import spacy
from bs4 import BeautifulSoup
MAIN_WIKI = 'https://en.wikipedia.org/wiki/Lists_of_people_by_nationality'
BASE_WIKI = 'https://en.wikipedia.org'
NLP_MODEL = spacy.load('en_core_web_lg')
d... |
110800 | from core.advbase import *
from slot.a import *
from slot.d import *
def module():
return Summer_Patia
class Summer_Patia(Adv):
comment = 'cannot build combo for Cat Sith; uses up 15 stacks by 46.94s'
a3 = [('antiaffself_poison', 0.15, 10, 5), ('edge_poison', 60, 'hp50')]
conf = {}
conf['slots.po... |
110803 | import wx
import matplotlib.cm
import numpy as np
from . import properties
slider_width = 30
s_off = slider_width/2
class ColorBarPanel(wx.Panel):
'''
A HORIZONTAL color bar and value axis drawn on a panel.
'''
def __init__(self, parent, map, local_extents=[0.,1.], global_extents=None,
... |
110831 | import os
import sys
def process(input_file, output_file):
output_text = ""
if input_file.endswith("abstract.summary.txt") or input_file.endswith("community.summary.txt") or input_file.endswith("combined.summary.txt") or input_file.endswith("human.summary.txt"):
input_text = []
with open(input_... |
110845 | import Spheral
import distributeNodesGeneric
#-------------------------------------------------------------------------------
# Domain decompose using PeanoHilbert ordering (1d method).
#-------------------------------------------------------------------------------
def distributeNodes1d(*listOfNodeTuples):
distri... |
110865 | from django.contrib import admin
from devilry.devilry_group import models
class FeedbackSetAdmin(admin.ModelAdmin):
list_display = [
'id',
'group_id',
'get_students',
'deadline_datetime',
'feedbackset_type',
'grading_published_datetime',
'grading_points'
... |
110879 | from typing import Any, Union
from unittest.mock import Mock
import pystac
class MockStacIO(pystac.StacIO):
"""Creates a mock that records StacIO calls for testing and allows
clients to replace StacIO functionality, all within a context scope.
"""
def __init__(self) -> None:
self.mock = Mock... |
110910 | import FWCore.ParameterSet.Config as cms
#
# tracker
#
from RecoLocalTracker.Configuration.RecoLocalTracker_Cosmics_cff import *
from RecoTracker.Configuration.RecoTrackerP5_cff import *
from RecoVertex.BeamSpotProducer.BeamSpot_cff import *
from RecoTracker.Configuration.RecoTrackerBHM_cff import *
from RecoTracker.D... |
110920 | from fusion.points2heatmap import *
from fusion.calcAffine import *
from fusion.warper import warping as warp
import matplotlib.pyplot as plt
from fusion.parts2lms import parts2lms
import time
from tqdm import *
import random
import multiprocessing
import sys
def gammaTrans(img, gamma):
gamma_table = [np.power(x/255... |
110921 | import re
from patent_client.util.schema import *
from dateutil.parser import parse as parse_dt
from .model import Publication, Inventor, Applicant, Assignee, RelatedPatentDocument, PriorPublication, USReference, ForeignReference, NPLReference, CpcClass, USClass, ForeignPriority
# Related People
class InventorSchema... |
110960 | from WMCore.Configuration import Configuration
config = Configuration()
config.section_('Agent')
# Agent:
config.Agent.hostName = None
config.Agent.contact = None
config.Agent.teamName = "team_usa"
config.Agent.agentName = None
config.section_('General')
# General: General Settings Section
config.General.workDir = '/ho... |
110966 | from torch import nn
import torch
import torch.nn.functional as F
from .base_model import BaseModel
from ..layers import EmbeddingLayer
class BiasMF(BaseModel):
def __init__(self,
feature_map,
model_id="BiasMF",
gpu=-1,
learning_rate=1e-3,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.