id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
137691 | import pandas as pd
def pandas_excel_write(save_dir_path: str):
data1 = """
class precision recall
<18 0.0125 12
18-24 0.0250 16
25-34 0.00350 4
"""
data2 = """
sample values
<18 0
18-24 0.25
25-34 0.35
... |
137706 | from capstone import *
from capstone.x86 import *
from elftools.elf.elffile import ELFFile
import sys
NUMBER_OF_CANDIDATES = 20
MAX_RSP_OFFSET = 0x200
ONE_GADGET_LIB_DEBUG = False
# add
# call
# jmp
# lea
# mov
# nop
# push
# sub
# xor
# movq
# movaps
# movhps
# Most practical gadgets have simple constraints.
# S... |
137724 | from puzzle.utils import (get_gene_info, get_cytoband_coord)
class BaseVariantMixin(object):
"""Base class for variant mixins"""
def variants(self, case_id, skip=0, count=30, filters=None):
"""Return a results tuple with variants and nr_of_variants.
"""
raise NotImplementedError
... |
137733 | from django.urls import reverse
from django_filters.views import FilterView
from django_tables2.views import SingleTableMixin
from guardian.mixins import LoginRequiredMixin
from service_catalog.filters.operation_filter import OperationFilter
from service_catalog.models import Operation, Service
from service_catalog.ta... |
137769 | from pytest import mark
@mark.django_db
def test_get_menu_not_found(graphql_client, conference_factory):
conference = conference_factory()
resp = graphql_client.query(
"""
query($code: String!, $identifier: String!) {
conference(code: $code) {
menu(identifier: $ide... |
137770 | from .conv_head import ConvHead
from .latent_head import LatentHead
__all__ = [
'ConvHead',
'LatentHead',
] |
137863 | import unittest
import os
from os.path import exists, join
import numpy as np
from test_helper import TESTDIR, TESTDATA, TMPDATA
import datetime
from copy import copy
import warnings
from karta.vector import shp, read_shapefile
from karta.vector.geometry import (Point, Line, Polygon,
... |
137880 | import os
import re
import sys
import shutil
import filecmp
from functools import reduce
fcm_types = ['accounts', 'storage', 'topics']
avail_nodes = []
dumps_root_dir = ''
investigation_name = 'iss'
rounds_avail = {}
account_fcm_pattern = re.compile(r'accounts-round(\d+)[.]fcm')
first_round_post_iss = 0
def prepare_... |
137882 | import sys
import asyncio
import aiohttp
from asyncqt import QEventLoop, asyncSlot, asyncClose
# from PyQt5.QtWidgets import (
from PySide2.QtWidgets import (
QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QPushButton,
QVBoxLayout)
class MainWindow(QWidget):
"""Main window."""
_DEF_URL = 'htt... |
137895 | from __future__ import absolute_import
import time
from .ProtectFlags import ProtectFlags
from .TimeStamp import TimeStamp
from .MetaInfo import MetaInfo
from .FSString import FSString
TS_FORMAT = "%Y-%m-%d %H:%M:%S"
class MetaInfoFSUAE:
@staticmethod
def is_meta_file(path):
return path.lower().end... |
137929 | def colored(string, color):
"""
Returns the given string wrapped with a ANSI escape code that gives it color when printed to a terminal.
Args:
string: String to be colored.
color: Chosen color for the string. Can be 'r' for red, 'g' for green, 'y' for yellow, 'b' for blue, 'p' for
... |
137941 | import os,time,sys
import ROOT as rt
from larcv import larcv
from ROOT import dbscan,std
import numpy as np
colors = [ rt.kRed, rt.kBlue, rt.kMagenta, rt.kGreen, rt.kCyan ]
npoints = 1000
ndims = 2
gauscenters = [(10,10),(2,2)]
gauscovs = [
[[1,0],[0,1]],
[[1,0.7],[0.7,1]]
]
# gen pts and put them into ... |
137991 | from buildtest.tools.stylecheck import run_style_checks
def test_run_style_check():
run_style_checks(
no_black=False, no_isort=False, no_pyflakes=False, apply_stylechecks=False
)
|
138000 | import unittest
from monty.multiprocessing import imap_tqdm
from math import sqrt
class FuncCase(unittest.TestCase):
def test_imap_tqdm(self):
results = imap_tqdm(4, sqrt, range(10000))
self.assertEqual(len(results), 10000)
self.assertEqual(results[0], 0)
self.assertEqual(results[... |
138022 | import logging
import random
from datetime import datetime, timedelta
from sys import exit
from time import sleep
from colorama import Fore, Style
from GramAddict.core.config import Config
from GramAddict.core.device_facade import create_device, get_device_info
from GramAddict.core.filter import load_config as load_f... |
138025 | from ...utils import Command
from ..utils import SiteManager
class StatusCommand(Command):
"""
Retrieve the work order status
"""
def setup(self, subparsers):
parser = super(StatusCommand, self).setup(subparsers)
parser.add_argument('-u', "--api_url", required=True, type=str, help... |
138041 | import unittest
import requests
from src.config import PYTHON_MODULE_PORT
class APIStatusTest(unittest.TestCase):
def setUp(self):
self.url = f'http://localhost:{PYTHON_MODULE_PORT}/docs'
self.status_code = 200
self.response_message = True
def test_status_code(self):
respons... |
138049 | import json
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from helium.auth.models import UserProfile
from helium.auth.models import UserSettings
from helium.auth.tests.helpers import userhelper
__author__ = "<NAME>"
_... |
138055 | import os, sys
import torch
from .models.embedding import FullyConnectedEmbed, SkipLSTM
from .models.contact import ContactCNN
from .models.interaction import ModelInteraction
def build_lm_1(state_dict_path):
"""
:meta private:
"""
model = SkipLSTM(21, 100, 1024, 3)
state_dict = torch.load(state_... |
138062 | import rpyc
import copy
import unittest
from rpyc.utils.server import ThreadedServer
class MyClass(object):
def __add__(self, other):
return self.foo() + str(other)
def foo(self):
return "foo"
def bar(self):
return "bar"
def spam(self):
return "spam"
def _privy(... |
138071 | import re
import os
import glob
import subprocess
from subprocess import Popen, PIPE
import numpy as np
# generates the string with the selected integrator
def set_integrator(scene, integrator_str):
start = '##INTEGRATOR-DEF-START'
end = '##INTEGRATOR-DEF-END'
replacement = integrator_str
match = re.ma... |
138103 | from stacker.context import Context
from stacker.config import Config
from stacker.variables import Variable
from stacker_blueprints.network import Network
from stacker.blueprints.testutil import BlueprintTestCase
class TestNetwork(BlueprintTestCase):
def setUp(self):
self.ctx = Context(config=Config({'na... |
138137 | from setuptools import setup, find_packages
import torch
from torch.utils.cpp_extension import CppExtension, CUDAExtension, CUDA_HOME
ext_modules = [
CppExtension('sym3eig_cpu', ['cpu/sym3eig.cpp']),
]
cmdclass = {'build_ext': torch.utils.cpp_extension.BuildExtension}
if CUDA_HOME is not None:
ext_modules += ... |
138139 | import asyncio
import time
import json
import socket
import sys
from datetime import datetime
from gmqtt import Client as MQTTClient
from cover import Cover
from alarm_control_panel import Alarm
# Globals
# MQTT
from light import Light
from boiler import Boiler
from switch import Switch
tydom_topic = "+/tydom/#"
ref... |
138165 | from joblib import Parallel, delayed
import queue
import os
import time
# Define number of GPUs available
GPU_available = [0, 1]
N_GPU = len(GPU_available)
models = ["EleutherAI/gpt-j-6B"] #"EleutherAI/gpt-neo-1.3B", "EleutherAI/gpt-neo-2.7B", ]
datasets = ["flowMWOZ", "top", "dialKG-parse"]
template = "python main_... |
138206 | from __future__ import annotations
import pyqtgraph as pg
from pyqtgraph import colormap as cmap
from typing import Generic, Iterator, Sequence, TypeVar, overload, MutableSequence
import numpy as np
from ._utils import convert_color_code, to_rgba
from .components import Legend, Region, ScaleBar, TextItem
from .graph_i... |
138221 | import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-ba... |
138294 | from insights.parsers import SkipException
from insights.parsers import ip_netns_exec_namespace_lsof
from insights.parsers.ip_netns_exec_namespace_lsof import IpNetnsExecNamespaceLsofI
from insights.tests import context_wrap
import doctest
import pytest
IP_NETNS_EXEC_NAMESPACE_LSOF_I = """
COMMAND PID USER FD ... |
138332 | from __future__ import with_statement
from attest import Tests, Assert
suite = Tests()
@suite.test
def raises():
"""Assert.raises"""
try:
with Assert.raises(RuntimeError):
pass
except AssertionError, e:
Assert(e).__str__() == "didn't raise RuntimeError"
else:
ra... |
138404 | import re
import json
import time
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db import transaction, IntegrityError
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_safe, require_POST
from ide.models.build import... |
138407 | from spaceone.core.locator import Locator
from spaceone.core.transaction import Transaction
class CoreObject(object):
def __init__(self, transaction: Transaction = None):
if transaction:
self.transaction = transaction
else:
self.transaction = Transaction()
self.l... |
138452 | import toml
import os
def setup_config(usr, privKey):
print('Setup Config file for Node 1 ...')
conf = os.environ['OLDATA'] + "/devnet/1-Node/config.toml"
Configuration = toml.load(conf)
node_conf = Configuration['node']
auth_conf = node_conf['Auth']
if usr:
auth_conf['owner_creden... |
138465 | import numpy as np
import cv2
# This file is a set of commonly used functions by the viz scripts. It
# is not meant to be run on its own
def unblockshaped(arr, h, w, rgb=False):
if rgb:
n, nrows, ncols, nchannels = arr.shape
return (arr.reshape(h//nrows, -1, nrows, ncols, nchannels)
... |
138490 | from douyin_spider.utils.common import parse_datetime, get_array_first
from douyin_spider.models.video import Video
from douyin_spider.models.music import Music
from douyin_spider.models.user import User, Star
from douyin_spider.models.address import Address
def get_video_url(video_list):
"""
parse video url ... |
138514 | from functools import partial, reduce
import copy
from collections import namedtuple
from functools import partial
import sys
sys.setrecursionlimit(10**3)
#helpers
def curry(f):
arg_num = f.func_code.co_argcount
def wrap(*args):
_f = partial(f, *args)
if hasattr(f, 't'):
_f.t = f... |
138520 | import os
import sys
import time
import json
import requests
from functools import partial
from threading import Thread
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import pyqtSignal
from core import Utils, Command
import main_gui
'''
【主窗口类】
主窗口类继承自QMainWindow类。
图形程序绝大部分交互都在这里。
'''
class M... |
138585 | import aiopg
# project
from ddtrace import Pin
from ddtrace.contrib.aiopg.patch import patch
from ddtrace.contrib.aiopg.patch import unpatch
from tests.contrib.asyncio.utils import AsyncioTestCase
from tests.contrib.asyncio.utils import mark_asyncio
from tests.contrib.config import POSTGRES_CONFIG
TEST_PORT = str(PO... |
138590 | import requests
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
SERVER = "localhost"
URL = "http://%s:8080" % SERVER
def before_all(context):
__open_browser(context)
def __open_browser(context):
chrm = context.config.userdata['chromedriver_path']
try:
... |
138599 | import importlib
import json
import platform
import subprocess
import sys
from pathlib import Path
from loguru import logger
from sc2.game_data import AbilityData, GameData, UnitTypeData, UpgradeData
try:
from sc2.ids.id_version import ID_VERSION_STRING
except ImportError:
ID_VERSION_STRING = "4.11.4.78285"
... |
138651 | import argparse
import csv
import glob
import os
import sys
import time
from datetime import datetime
from pathlib import Path
try:
import streamlit as st
except ModuleNotFoundError:
pass
import torch
import torchvision
import yaml
from omegaconf import OmegaConf
from specvqgan.util import get_ckpt_path
sys... |
138653 | import os
import time
import socket
import random
import tensorflow as tf
from tensorflow.contrib.layers.python import layers as tf_layers
from tensorflow.python.platform import flags
# NOTE: this script is based on https://github.com/cbfinn/maml/blob/master/utils.py
FLAGS = flags.FLAGS
## Image helper
def get_im... |
138714 | import hydra
from hydra.core.config_store import ConfigStore
from omegaconf import OmegaConf
from configs import TrainConfig
from jerex import model, util
cs = ConfigStore.instance()
cs.store(name="train", node=TrainConfig)
@hydra.main(config_name='train', config_path='configs/docred_joint')
def train(cfg: TrainCon... |
138734 | import argparse
from pathlib import Path
from loguru import logger
from jupyter_ascending._environment import SYNC_EXTENSION
from jupyter_ascending.json_requests import SyncRequest
from jupyter_ascending.logger import setup_logger
from jupyter_ascending.requests.client_lib import request_notebook_command
@logger.ca... |
138740 | from __future__ import absolute_import, division, print_function, with_statement
import sys
from turbo.log import helper_log
from turbo.util import import_object, camel_to_underscore
class _HelperObjectDict(dict):
def __setitem__(self, name, value):
return super(_HelperObjectDict, self).setdefault(nam... |
138745 | ATTR_CODE = "auth_code"
CONF_MQTT_IN = "mqtt_in"
CONF_MQTT_OUT = "mqtt_out"
DATA_KEY = "media_player.hisense_tv"
DEFAULT_CLIENT_ID = "HomeAssistant"
DEFAULT_MQTT_PREFIX = "hisense"
DEFAULT_NAME = "Hisense TV"
DOMAIN = "hisense_tv"
|
138763 | from abc import abstractmethod
from bxutils import logging
from bxcommon.services.transaction_service import TransactionService
from bxcommon.utils.blockchain_utils.btc.btc_object_hash import Sha256Hash
from bxgateway.services.abstract_block_cleanup_service import AbstractBlockCleanupService
from bxgateway.services.... |
138767 | from multiprocessing.pool import Pool
from itertools import repeat
import pandas as pd
import numpy as np
def get_composers(res):
"""
Get the composers for the given track.
**Parameters**
- `res`: string composer names for each track within charts
**Returns**
A dictionary of composers ... |
138792 | import ptf
from ptf.base_tests import BaseTest
from ptf import testutils
class TestParamsGet(BaseTest):
def setUp(self):
BaseTest.setUp(self)
def runTest(self):
params = testutils.test_params_get(default=None)
if params is None:
print(">>>None")
else:
fo... |
138815 | import logging
import pyipmi
import pyipmi.interfaces
from ocs_ci.ocs import constants, defaults
from ocs_ci.ocs.constants import VM_POWERED_OFF, VM_POWERED_ON
from ocs_ci.ocs.exceptions import UnexpectedBehaviour
from ocs_ci.ocs.node import wait_for_nodes_status, get_worker_nodes, get_master_nodes
from ocs_ci.ocs.oc... |
138844 | import copy
import time
import json
import logging
log = logging.getLogger(__name__)
import torch
from optim import lbfgs_modified
import config as cfg
def store_checkpoint(checkpoint_file, state, optimizer, current_epoch, current_loss,\
verbosity=0):
r"""
:param checkpoint_file: target file
:param sta... |
138903 | class DB:
'''
Convience class for decibel scale. Other non-linear scales such as the richter scale could be handled similarly.
Usage:
dB = DB()
.
. (later)
.
gain = 15 * dB
'''
def __rmul__(self, val):
'''
Only allow multiplication from the right to avoid confus... |
138939 | import copy
import itertools
from collections import deque
from typing import TextIO, Tuple
from aoc2019.intcode import Computer, read_program
def query_position(x: int, y: int, computer: Computer) -> bool:
computer = copy.deepcopy(computer)
computer.send_input(x)
computer.send_input(y)
computer.run... |
138965 | def proper_divisors_sum(n):
return sum(a for a in xrange(1, n) if not n % a)
def amicable_numbers(a, b):
return proper_divisors_sum(a) == b and proper_divisors_sum(b) == a
# def amicable_numbers(a, b):
# # this works after multiple submissions to get lucky on random inputs
# return sum(c for c in xr... |
138989 | from collections import OrderedDict
from ctypes import LittleEndianStructure, Structure, Union, c_uint8, c_uint16, c_uint32,\
string_at, byref, sizeof, c_bool, c_int16, Array, c_char
import json
import logging
import struct
from telemetry_unit_conversions import \
temp_sensor_adc_val_to_celsius, adc_to_bat_cur... |
139011 | import pytest
from sqlalchemy import Column, Integer
from dbeditor.database import Database
from dbeditor.table_builder import BuilderGroup
@pytest.fixture
def group(database: Database) -> BuilderGroup:
g = BuilderGroup(database.engine)
g.start_building("example") # FIXME: fixture based on testing code
... |
139018 | from gi.repository import Gio, Gtk, GLib, Gdk
import pkg_resources
from typing import List
from ocrd_browser.util.gtk import ActionRegistry
from ocrd_browser.ui import MainWindow, AboutDialog, OpenDialog
from ocrd_browser.view import ViewRegistry
class OcrdBrowserApplication(Gtk.Application):
def __init__(self)... |
139038 | from requests import Response
from ...lib.gravity import Module
__all__ = [
"BaseServerForTrigger",
"BaseServerForHostingBuild"
]
class BaseServerForTrigger(Module):
"""
Abstract base class for API of triggering builds on automation (CI) server
"""
def trigger_build(self, revision: str) -> N... |
139045 | from photons_protocol.packets import dictobj
from photons_protocol.messages import T
from delfick_project.norms import sb
from bitarray import bitarray
import binascii
emptybt = bitarray("0000000000000000000000000000000000000000000000000000000000000000")
target_cache = {}
def look_at_target(pkt, value):
if valu... |
139147 | import torch
import models
import cfg
import numpy as np
from utils.utils import set_log_dir, save_checkpoint, create_logger, pruning_generate, see_remain_rate, rewind_weight, see_remain_rate_orig
args = cfg.parse_args()
gen_net = eval('models.sngan_cifar10.Generator')(args=args).cuda()
pruning_generate(gen_net, 1-0.8*... |
139151 | import re
emails = '''
<EMAIL>
<EMAIL>
<EMAIL>
'''
pattern = re.compile(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+')
matches = pattern.finditer(emails)
for match in matches:
print(match)
|
139152 | import common
import paths
def test_simple_move(activate_package, make_workspace):
activate_package(package='basic', into='main')
workspace = make_workspace('main')
changes = workspace.move(
'basic/bar.py',
31,
'basic/foo.py')
workspace.perform(changes)
common.compare_wo... |
139232 | from __future__ import print_function
import tensorflow as tf
import numpy as np
import cPickle
from tensorflow.contrib import slim
#Load features and labels
features = cPickle.load(open('nn_features.p', 'rb'))
labels = cPickle.load(open('labels.p', 'rb'))
mask = np.random.choice(features.shape[0], features.shape[0... |
139244 | import io
import os
import time
import argparse
import random
import logging
import warnings
import multiprocessing
import numpy as np
import mxnet as mx
from mxnet import gluon
from mxnet.gluon import Block, nn
from mxnet.gluon.data.sampler import Sampler, SequentialSampler
import gluonnlp as nlp
from gluonnlp.model i... |
139265 | from __future__ import absolute_import
from selenium import webdriver
import multiprocessing
import requests
import time
import unittest
import percy
import sys
import os
from .utils import invincible, wait_for
class IntegrationTests(unittest.TestCase):
def percy_snapshot(cls, name):
if ('PERCY_PROJECT' ... |
139272 | import hashlib, json
import nacl.bindings
from nacl import encoding
from nacl.utils import random
from .utils import to_hex, from_hex, is_hex, str_to_bytes
def create_address(pubkey):
if is_hex(pubkey):
pubkey = from_hex(pubkey)
h = hashlib.new('ripemd160')
h.update(pubkey)
return h.digest()... |
139275 | import graphene
from ...invoice import models
from ..core.types import Job, ModelObjectType
from ..meta.types import ObjectWithMetadata
class Invoice(ModelObjectType):
number = graphene.String()
external_url = graphene.String()
created_at = graphene.DateTime(required=True)
updated_at = graphene.DateT... |
139295 | class Solution:
def __init__(self):
self.map = {}
def cloneGraph(self, node):
if node is None:
return None
next = UndirectedGraphNode(node.label)
self.map[str(node.label)] = next
for tmp in node.neighbors:
if str(tmp.label) in self.map:
... |
139413 | import operator
import rt
def parallel_sum(l, r):
"""Computes (l + (l+1) + ... + r)."""
# TODO(zhangwen): this function can either return an int or a future; this seems confusing...
if l == r:
return l
m = (l + r) // 2
sl = parallel_sum(l, m)
sr = parallel_sum(m + 1, r)
return rt... |
139449 | import argparse
from blesuite.connection_manager import BLEConnectionManager
from blesuite_wrapper import ble_service_read, ble_service_read_async, ble_service_write, \
ble_handle_subscribe, ble_service_scan, ble_service_write_async, ble_run_smart_scan
from blesuite import utils
from blesuite.utils.print_helper imp... |
139508 | import httpretty
import json
import unittest
def setUp_method_with_http_mocking(test_class):
original_setUp = test_class.setUp if hasattr(test_class, 'setUp') else None
def new_setUp(self):
httpretty.enable()
self.addCleanup(httpretty.disable)
if original_setUp:
original_... |
139509 | import cupy
from cupy._core import internal
def take(a, indices, axis=None, out=None):
"""Takes elements of an array at specified indices along an axis.
This is an implementation of "fancy indexing" at single axis.
This function does not support ``mode`` option.
Args:
a (cupy.ndarray): Arra... |
139518 | import time
import unittest
from MiscUtils.Funcs import (
asclocaltime, commas, charWrap, wordWrap, excstr,
hostName, localIP, localTimeDelta, positiveId,
safeDescription, timestamp, uniqueId, valueForString)
class TestFuncs(unittest.TestCase):
"""Unit tests for the functions in MiscUtils.Funcs."""
... |
139532 | import os
import tqdm
import torch
import numpy as np
from lib.helpers.save_helper import load_checkpoint
from lib.helpers.decode_helper import extract_dets_from_outputs
from lib.helpers.decode_helper import decode_detections
class Tester(object):
def __init__(self, cfg, model, data_loader, logger):
self.... |
139547 | from pyontutils import sheets
from pyontutils.sheets import Sheet
from pyontutils.namespaces import ilxtr
from neurondm.sheets import CutsV1, Row as RowBase
from neurondm.core import Config, NeuronEBM
from neurondm.phenotype_namespaces import Species
class NeuronNerves(NeuronEBM):
owlClass = ilxtr.NeuronNerves
... |
139567 | from pybindgen import *
from PBGutils import *
#-------------------------------------------------------------------------------
# The class to handle wrapping this module.
#-------------------------------------------------------------------------------
class Kernel:
#---------------------------------------------... |
139570 | import FWCore.ParameterSet.Config as cms
# Geometry and Magnetic field must be initialized separately
# Geant4-based CMS Detector simulation (OscarProducer)
# - returns label "g4SimHits"
#
from SimG4Core.Application.g4SimHits_cfi import *
|
139573 | from flask_restplus import Api
authorizations = {
'apikey': {
'type': 'apiKey',
'in': 'header',
'name': 'X-Token'
}
}
api = Api(version='1.0', title='PMS API', description='PMS API', authorizations=authorizations)
api.namespaces.pop(0)
ns = api.namespace('v1', description='这是自定义名称空间')
... |
139581 | from collections.abc import Sequence
import operator
import urllib.parse
import requests
import cachetools
BASE_URL = "http://archive.org/"
def _session(base_url, retries):
# TODO: backoff?
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=retries)
session.mount(base... |
139618 | def parse_list_ranges(s,sep='-'):
r = []
x = s.split(',')
for y in x:
z = y.split(sep)
if len(z)==1:
r += [int(z[0])]
else:
r += range(int(z[0]),int(z[1])+1)
return list(r)
def parse_list_floats(s):
x = s.split(',')
return list(map(float, x))
|
139636 | from logging import Logger
from os.path import basename
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import boto3
from jsonschema import ValidationError, validate
from linz_logger import get_log
from ..aws_message_attributes import (
DATA_TYPE_STRING,
MESSAGE_ATTRIBUTE_TYPE_DATASET,
... |
139693 | import numpy as np
from torch.autograd import Variable
import torch as torch
import copy
from torch.autograd.gradcheck import zero_gradients
def deepfool(image, net, num_classes, overshoot, max_iter):
"""
:param image: Image of size HxWx3
:param net: network (input: images, output: values of activa... |
139719 | import arcade
TILE_SCALING = 1.0
def test_csv_left_up():
# Read in the tiled map
my_map = arcade.load_tilemap("../tiled_maps/csv_left_up_embedded.json")
assert my_map.tile_width == 128
assert my_map.tile_height == 128
assert my_map.width == 10
assert my_map.height == 10
# --- Platforms ... |
139730 | import numpy as np
import autoarray as aa
import autogalaxy as ag
from autolens.lens.model.result import ResultDataset
class ResultInterferometer(ResultDataset):
@property
def max_log_likelihood_fit(self):
return self.analysis.fit_interferometer_for_instance(instance=self.instance)
... |
139757 | from __future__ import division
import numpy as np
from scipy.optimize import fmin_bfgs
from itertools import combinations_with_replacement
import causalinference.utils.tools as tools
from .data import Dict
class Propensity(Dict):
"""
Dictionary-like class containing propensity score data.
Propensity score rel... |
139845 | class TableViewUIUtils(object):
""" This utility class contains members that involve the Revit UI and operate on schedule views or MEP electrical panel schedules. """
@staticmethod
def TestCellAndPromptToEditTypeParameter(tableView,sectionType,row,column):
"""
TestCellAndPromptToEditTypeParameter(tableView:... |
139865 | import base64
import gzip
import json
from typing import Dict
class RserverExchange:
"""Data-oriented class to simplify dealing with RStudio messages decoded from the MITM log
Attributes are stored in a way that is ready for activity records. bytes get decoded, and images get
base64-encoded.
"""
... |
139889 | import pytest
from ninja import NinjaAPI, Router
from ninja.testing import TestClient
api = NinjaAPI()
@api.get("/endpoint")
# view->api
def global_op(request):
return "global"
first_router = Router()
@first_router.get("/endpoint_1")
# view->router, router->api
def router_op1(request):
return "first 1"
... |
139905 | from django.db import models, migrations
from django.db.models import CASCADE
from tree.fields import PathField
from tree.operations import CreateTreeTrigger
from tree.sql.base import ALPHANUM_LEN
class Migration(migrations.Migration):
dependencies = [
('tree', '0001_initial'),
]
operations = [
... |
139926 | from calendar import timegm
from datetime import datetime
from rest_framework_jwt.compat import get_username, get_username_field
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.utils import jwt_decode_handler
from djan... |
139964 | from django.urls import reverse
from django.test import RequestFactory, TestCase
from django.utils.http import urlencode
from feder.cases.models import Case
from feder.institutions.factories import InstitutionFactory
from feder.letters.factories import IncomingLetterFactory
from feder.letters.models import Letter
from... |
139994 | from twilio.twiml.voice_response import VoiceResponse, Say
response = VoiceResponse()
response.say('Chapeau!', voice='alice', language='fr-FR')
print(response)
|
140025 | config = {
'population_size' : 100,
'mutation_probability' : .1,
'crossover_rate' : .9,
# maximum simulation runs before finishing
'max_runs' : 100,
# maximum timesteps per simulation
'max_timesteps' : 150,
# smoothness value of the line in [0, 1]
'line_smoothness' : .4,
# Bound ... |
140056 | import os
import pickle
import numpy as np
import torch
from loguru import logger
from tqdm import tqdm
def make_adj_list(N, edge_index_transposed):
A = np.eye(N)
for edge in edge_index_transposed:
A[edge[0], edge[1]] = 1
adj_list = A != 0
return adj_list
def make_adj_list_wrapper(x):
r... |
140062 | del_items(0x80139F2C)
SetType(0x80139F2C, "void PresOnlyTestRoutine__Fv()")
del_items(0x80139F54)
SetType(0x80139F54, "void FeInitBuffer__Fv()")
del_items(0x80139F7C)
SetType(0x80139F7C, "void FeAddEntry__Fii8TXT_JUSTUsP7FeTableP5CFont(int X, int Y, enum TXT_JUST Just, unsigned short Str, struct FeTable *MenuPtr, struc... |
140068 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from . import util,dataloader
def default_eval(refer_loader,query_loader,model,class_acc=False):
fb_vector = None
if hasattr(model,'get_fb_vector'):
fb_vector = get_fb_vector(refer_loader,model)
centroid = g... |
140101 | import pytest
class Examples:
small_example = [
"""
describe "This":
before_each:
self.x = 5
describe "That":
before_each:
self.y = 6
describe "Meh":
after_each:
self.y = None
describe "Blah... |
140113 | from pymoo.core.problem import Problem
from pymoo.problems.meta import MetaProblem
from pymoo.util.misc import at_least_2d_array
class ConstraintsAsPenalty(MetaProblem):
def __init__(self, problem, penalty=1e6):
super().__init__(problem)
self.penalty = penalty
# set the constraints to be... |
140120 | import datetime
import json
import os
import discord
from discord.errors import HTTPException
from discord.ext import commands
class Logging(commands.Cog, description="Keep a track of what members do in your server with this category."):
def __init__(self, bot):
self.bot = bot
with open("storage/... |
140143 | from sqlalchemy import Column, Integer, String
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String, unique=True)
|
140153 | from gazette.spiders.base.fecam import FecamGazetteSpider
class ScGaropabaSpider(FecamGazetteSpider):
name = "sc_garopaba"
FECAM_QUERY = "cod_entidade:98"
TERRITORY_ID = "4205704"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.