id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11435740 | from typing import Any
class ViewResult:
"""
Class represents a view result.
It wraps the template and the data context and later
uses it to compile a view using the default template
engine.
"""
def __init__(self, template: str, context: Any = {}) -> None:
"""
Constructor
... |
11435756 | from typing import List
from pydantic import BaseModel
from src.models.wrapped.bar import BarData
from src.models.wrapped.calendar import CalendarDayData
from src.models.wrapped.numeric import NumericData
from src.models.wrapped.pie import PieData
from src.models.wrapped.swarm import SwarmData
class WrappedPackage(... |
11435770 | import json
class InstallProjects(object):
def __init__(self, path, project=None):
self.path = path
if project is None:
self.project = []
else:
self.project = [project]
def factory_settings(self):
if len(self.project) == 0:
f = open(self.pa... |
11435782 | from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from protein.models import ProteinSet
from structure.models import Structure
import logging
class Command(BaseCommand):
help = 'Reads source data and creates common database tables'
logger = logging.getLogger(... |
11435804 | from invoke import task
import shutil
import os
def _generate_blinky_conan_graph(context, output_folder: str, file_name: str, build_arg: str = ""):
context.run(f"conan info ./blinky --graph {output_folder}/{file_name}.dot {build_arg}")
context.run(f"dot -Tpng {output_folder}/{file_name}.dot > {output_folder}/... |
11435809 | import logging
import os
import shutil
import tempfile
from collections import namedtuple
from pathlib import Path
import h5py
import mock
import numpy as np
import pandas as pd
import pytest
import PyDSS.metrics
from PyDSS.dataset_buffer import DatasetBuffer
from PyDSS.export_list_reader import ExportListProperty
fr... |
11435841 | def check_empty(value_to_check, default_value=None):
return default_value if value_to_check is None else value_to_check
|
11435844 | from typing import Dict, List, Sequence, TypeVar, Union
from decimal import Decimal, getcontext
from math import sqrt
from turf.helpers import Feature, LineString, Point
from turf.helpers import feature_collection, line_string, multi_line_string
from turf.invariant import get_coords_from_features
ctx = getcontext()
... |
11435881 | import os
import io
import json
import logging
import re
import urllib
import boto3
def is_debug_enabled() -> bool:
value = os.getenv("DEBUG", "false").lower()
if value in ["false", "0"]:
return False
else:
return bool(value)
DEBUG = is_debug_enabled()
FILES_BUCKET = os.getenv("FILES_BU... |
11435893 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.detailed_ground_heat_transfer import GroundHeatTransferBasementSurfaceProps
log = logging.getLogger(__name__)
class TestGroundHeatTransferBasementSurfaceProps(unittest.TestCase)... |
11435896 | import matplotlib.colors
import matplotlib.cm
import matplotlib.colorbar
import matplotlib.pyplot
import numpy
# colormaps: "viridis", "plasma_r","seismic"
def get_colormap(observable_name=None):
if "diff_minutes" in observable_name:
norm = matplotlib.colors.Normalize(vmin=-30, vmax=30)
cmap = ma... |
11435905 | class Solution:
def countBinarySubstrings(self, s):
s = s.replace("01", "0#1").replace("10", "1#0").split("#")
return sum(min(len(s[i]), len(s[i - 1])) for i in range(1, len(s))) |
11435923 | import docker
class FailureInjector(object):
def __init__(self):
self.docker_api = docker.from_env()
def container_exec(self, node, command):
docker_node = self.docker_api.containers.get(node)
docker_node.exec_run(command, user='root')
class NoFailure(FailureInjector):
def start... |
11435952 | import argparse
import torch
from omegaconf import OmegaConf
from classy.data.data_drivers import get_data_driver
from classy.utils.lightning import (
load_classy_module_from_checkpoint,
load_prediction_dataset_conf_from_checkpoint,
)
def interactive_main(
model_checkpoint_path: str,
prediction_para... |
11436035 | import tensorflow
import numpy
import pandas
with open("test_check.txt", 'w') as file:
file.write("Success!")
|
11436046 | from __future__ import absolute_import, division, print_function
from iotbx.regression.ncs.tst_mtrix_biomt_cmdl import pdb_str_0
import mmtbx.model
import iotbx.pdb
def test_1():
"""
Chains A,B,C are present in the model. The rest of them are being generated
by expansion. The problem is that iotbx/pdb/utils.py:a... |
11436086 | def test_exchange_version():
from pyews import ExchangeVersion
version = ExchangeVersion('15.20.4.3')
if version.exchange_version == 'Exchange2016':
assert True
try:
version = ExchangeVersion('14.20.4.2')
except:
assert True
if ExchangeVersion.valid_version('Exchange2019'... |
11436094 | import codecademylib3
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("school_data.csv")
print(df.head())
value_order = ["NOT ENOUGH DATA", "VERY WEAK", "WEAK", "NEUTRAL", "STRONG", "VERY STRONG"]
type_of_data = "ordinal"
# plot using .countplot() method here
sns.countplo... |
11436110 | from typing import Any, Callable, Optional
import torch
from torchmetrics import Metric
from pycave.bayes.core import covariance_shape, CovarianceType
class PriorAggregator(Metric):
"""
The prior aggregator aggregates component probabilities over batches and process.
"""
def __init__(
self,
... |
11436115 | import numpy as np
import os
import sys
from sklearn.preprocessing import normalize
from scipy import stats
import warnings
from OnClass.OnClass_utils import *
from OnClass.BilinearNN import BilinearNN
class OnClassModel:
def __init__(self, cell_type_network_file='../../OnClass_data/cell_ontology/cl.ontology', cell_t... |
11436121 | from django.db import models
from celery.result import AsyncResult
from apps.crawl_space.models import Crawl
from base.models import Index
class CeleryTask(models.Model):
pid = models.IntegerField(default=0)
crawl = models.OneToOneField(Crawl, blank=True, null=True, default=None)
index = models.On... |
11436122 | from cs1bit_setup import *
def test_rfpi():
M, N = 256, 512
K = 4
# dictionary
Phi = crdict.gaussian_mtx(cnb.KEYS[0], M, N, normalize_atoms=False)
# sparse signal
x, omega = crdata.sparse_normal_representations(cnb.KEYS[1], N, K)
# normalize signal
x = x / norm(x)
# frame bound
... |
11436266 | from navbox import *
import unittest
class NavBoxTest( unittest.TestCase ):
def testMatchCirRect( self ):
self.assertEqual( matchCircRect(circles=[],rectangles=[]), None )
circles = [((467.87, 303.77), 26.93)]
rectangles = [((467.51, 303.77), (25.29, 7.58), -2.602),
... |
11436271 | from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse
low = 20
up = 20
def callback_low(val):
global low
low = val
def callback_up(val):
global up
up = val
def pickPoint(event, x, y, flags, param):
if event != cv.EVENT_LBUTTONDOWN:
return
# Fill a... |
11436300 | import unittest
from unittest import mock
from cryptos import *
# TODO passphrase/seed_extension
class TestWalletKeystoreAddressIntegrity(unittest.TestCase):
gap_limit = 1 # make tests run faster
def _check_seeded_keystore_sanity(self, ks):
self.assertTrue (ks.is_deterministic())
self.asse... |
11436307 | import tensorflow as tf
from optimizer import distributed_optimizer as optimizer
from data_generator import distributed_tf_data_utils as tf_data_utils
# try:
# from .bert_model_fn import model_fn_builder
# from .bert_model_fn import rule_model_fn_builder
# except:
# from bert_model_fn import model_fn_builder
# fr... |
11436336 | from pydantic import ValidationError
from rest_framework.request import Request
from drf_stripe.settings import drf_stripe_settings
from drf_stripe.stripe_api.api import stripe_api as stripe
from drf_stripe.stripe_models.event import EventType
from drf_stripe.stripe_models.event import StripeEvent
from .customer_subsc... |
11436350 | def stars_for_rank(rank):
if rank >= 21:
return 2
if rank >= 16:
return 3
if rank >= 11:
return 4
return 5
rank = 25
stars = 0
streak = 0
record = list(input())
for game in record:
if rank == 0:
break
if game == "W":
streak += 1
stars += (2 if str... |
11436402 | from helios.webapp import base_app
import re
from helios.core.utils import requests_response_to_dict
import json
import requests
try:
from urlparse import urljoin
except ImportError:
from urllib.parse import urljoin
# This script detects vulnerabilities in the following PHP based products:
# - phpMyAdmin
clas... |
11436444 | class Solution:
"""
@param n: an integer
@return: the total number of digit 1
"""
def countDigitOne(self, n):
# write your code here
if n < 0:
return 0
base = 1
count = 0
while n // base != 0:
curr = n // base % 10
low = n ... |
11436502 | from util import web
from util.hook import *
search_uri = 'http://www.omdbapi.com/?t=%s'
id_uri = 'http://www.omdbapi.com/?i=%s'
error = 'Unable to search for that movie!'
@hook(cmds=['movie', 'imdb'], ex='movie Transformers', args=True)
def movie_search(code, input):
"""imdb movie/show title -- displays informa... |
11436518 | def invoke(pkg):
(pkg.destdir / "usr/lib/charset.alias").unlink(missing_ok = True)
(pkg.destdir / "usr/share/info/dir").unlink(missing_ok = True)
|
11436542 | import os
import synapse
import synapse.lib.datfile as s_datfile
import synapse.tests.utils as s_t_utils
syndir = os.path.dirname(synapse.__file__)
class DatFileTest(s_t_utils.SynTest):
def test_datfile_basic(self):
with s_datfile.openDatFile('synapse.tests/files/test.dat') as fd:
self.nn(f... |
11436543 | Project( externals = '../externals', paths = [ '../externals/src' ] )
Include( 'demo' )
Include( 'relight' )
Module( url = 'https://github.com/dmsovetov/foo.git', folder = '../externals/src' )
Module( url = 'https://github.com/dmsovetov/dreemchest.git', folder = '../externals/src', makefile = 'src' )
Module( u... |
11436547 | description = 'Flexible temperature regulator'
group = 'optional'
includes = ['alias_T']
tango_base = 'tango://phys.kws3.frm2:10000/kws3/'
devices = dict(
T_flex = device('nicos_mlz.kws3.devices.temperature.FlexRegulator',
description = 'Flexible temperature regulation device',
tangodevice = tan... |
11436600 | from model_wrappers.base_wrapper import Base_Wrappepr
import os
import torch
import numpy as np
import tqdm
from tqdm import tqdm
import lib.metrics as M
import torch.nn.functional as F
import cv2
import logging
def get_models_name(exp_root):
"""
ret:
- model_cpt{dict[name: state_dict]}
"""
mode... |
11436615 | from django.shortcuts import get_object_or_404, redirect, render
from django.views.generic import View
# models import
from fuser.models import *
from sadmin.models import *
# essential imports
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.au... |
11436663 | from rest_framework import viewsets
from rest_framework.pagination import LimitOffsetPagination
from .models import Book, Review
from .serializers import BookSerializer, ReviewSerializer
class BookViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
class ... |
11436668 | import numpy
import numpy.linalg
import scipy
import scipy.spatial
kernel = hou.ch( "kernel_radius" )
search = hou.ch( "search_radius" )
threshold = hou.ch( "threshold_constant" )
ks = hou.ch( "scaling_factor" )
kr = hou.ch( "eigenvalues_ratio" )
node = hou.pwd()
geo = node.geometry()
geo.clear()
particles = node.... |
11436679 | from django.conf import settings
from django.contrib.auth.models import Group, User
from mozilla_django_oidc.auth import OIDCAuthenticationBackend, default_username_algo
from remo.base.mozillians import BadStatusCode, MozilliansClient, ResourceDoesNotExist
USERNAME_ALGO = getattr(settings, 'OIDC_USERNAME_ALGO', def... |
11436682 | import numpy
if __name__=="__main__":
temp = list(map(int,input().split(" ")))
n = temp[0]
m = temp[1]
p = temp[2]
l1 = []
l2 = []
for i in range(n):
l1.append(list(map(int,input().split(" "))))
for i in range(m):
l2.append(list(map(int,input().split(" "))))
print... |
11436684 | import pingo
import time
galileo = pingo.detect.get_board()
arduino = pingo.arduino.get_arduino()
pot_galileo = galileo.pins['A0']
pot_galileo.mode = pingo.ANALOG
pot_arduino = arduino.pins['A0']
pot_arduino.mode = pingo.ANALOG
def bar(pin1, pin2):
bar1 = ('*' * int(pin1.ratio() * 40)).ljust(40)
bar2 = ('*... |
11436709 | from torch_engine import *
from torch_model import *
from torch_data import *
from torch_train import *
from torch_infer import *
from utils import *
|
11436734 | from mbed_cloud.exceptions import CloudApiException
from tests.common import BaseCase
import unittest
@BaseCase._skip_in_ci
class TestExamples(BaseCase):
@unittest.skip('cannot demonstrate pip in test suite')
def test_install(self):
"""
# an example: initial setup
pip install mbed-cl... |
11436735 | from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.memory import EpisodeParameterMemory, Memory, SequentialMemory
import rl.policy as policy
from env_0 import env
from env_0.reward import simple_reward_an... |
11436778 | import sys
from pathlib import Path
TEMPLATE = """\
{{
"version": "2.0.0",
"args": [],
"echoCommand": false,
"runner": "terminal",
"tasks": [
{{
"label": "format-code",
"type": "shell",
"command": "black",
"args": [
"*.py",
... |
11436820 | import chainer
from chainer import computational_graph
from chainer import cuda
from chainer import optimizers
from chainer import serializers
from chainer import Variable
from chainer.utils import type_check
from chainer import function
from chainer.initializers import GlorotNormal
import chainer.functions as F
impor... |
11436902 | import time
import copy
import inspect
import numpy as np
import scipy
#from matplotlib import gridspec, font_manager
from astropy import stats
from pypeit import msgs
from pypeit.core import pydl
from pypeit import utils
from pypeit.core import pixels
from pypeit import ginga
from matplotlib import pyplot as plt
... |
11436912 | import numpy as np
import scipy.linalg as spla
import matplotlib as mpl
import matplotlib.gridspec as gridspec
mpl.use('pgf')
from sklearn.neighbors import KernelDensity
from scipy.stats.kde import gaussian_kde
from geepee.kernels import *
import pdb
np.random.seed(100)
def figsize(scale):
fig_width_pt = 469.7... |
11436932 | import pytest
from datetime import datetime
from dateutil.parser import isoparse
from benchmarks.htap.lib.helpers import TPCH_DATE_RANGE
from benchmarks.htap.lib.analytical import AnalyticalStream
class DateValue:
value = isoparse('2198-12-31').timestamp()
class EmptyArgs:
dsn = 'empty'
def test_tpch_date_... |
11436965 | import json
import numpy as np
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
e... |
11436978 | import random
import time
import pytest
from helpers.client import QueryRuntimeException
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import TSV
cluster = ClickHouseCluster(__file__)
s0r0 = cluster.add_instance(
's0r0',
main_configs=['configs/remote_servers.xml', 'configs/merge_tree... |
11436983 | from django.core.management.base import BaseCommand
from django.db import transaction
from groups.models import Group
from optparse import make_option
import copy
class Command(BaseCommand):
help = "Copy group"
option_list = BaseCommand.option_list + (
make_option('--group_id',
... |
11437022 | import sys
sys.path.append('../')
import pandas as pd
from collections import Counter
from .text_summarization import generate_summary
# from NLP import *
from nltk import pos_tag
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import wordpunct_tokenize
import string
import pick... |
11437035 | import argparse
if __name__ == "__main__": #if this is the main file, parse the command args
parser = argparse.ArgumentParser(description="Module that parses the log from trained networks and ranks their performance.")
parser.add_argument('file', type=str, help="The filepath to the output log.")
args, _ = parser.... |
11437081 | class Solution:
def addDigits(self, num: int) -> int:
while num > 9:
temp, sum = num, 0
while temp > 0:
sum += temp % 10
temp //= 10
num = sum
return num
|
11437092 | from abc import ABC, abstractmethod
from uvicore.typing import Union, List, Dict
from uvicore.contracts.user_info import UserInfo
try:
from starlette.requests import HTTPConnection
except:
HTTPConnection = None
class UserProvider(ABC):
def __init__(self):
# Default field mapping for each method b... |
11437118 | from sqlalchemy import func, case
from mlcomp.db.enums import LogStatus
from mlcomp.db.models import Step, Log
from mlcomp.db.providers.base import BaseDataProvider
from mlcomp.utils.misc import to_snake, now
class StepProvider(BaseDataProvider):
model = Step
def _hierarchy(self, parent: dict, steps: list, ... |
11437151 | def somar(n1, n2):
return n1 + n2
def subtrair(n1, n2):
return n1 - n2
print(somar(5, 4))
#https://pt.stackoverflow.com/q/364546/101
|
11437184 | import collections
from supriya.enums import CalculationRate
from supriya.synthdefs import UGen
class LastValue(UGen):
"""
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> last_value = supriya.ugens.LastValue.ar(
... diff=0.01,
... source=source,
... )
... |
11437189 | import corner
import dnest4.classic as dn4
import matplotlib.pyplot as plt
import numpy as np
# DNest4 postprocessing
dn4.postprocess(cut=0.0)
# Corner plot
posterior_sample = dn4.my_loadtxt("posterior_sample.txt")
corner.corner(posterior_sample, plot_contours=False, plot_density=False)
plt.show()
# Correlation matr... |
11437221 | from bs4 import BeautifulSoup
data = "<html> \
<body> \
<h1 id = 'title'> [1]크롤링이란?</h1> \
<h1>설명:<h1> \
<p class='cssstyle'>웹페이지에서 필요한 데이터를 추출하는 것</p> \
<p id='body' align='center'>파이썬을 중심으로 다양한 웹크롤링 기술 발달</p> \
</body> \
</html>"
soup = BeautifulSoup(data, 'html.parser')
title_data = soup.find('h1')
print(title_d... |
11437223 | import json
from wayscript import utils
from wayscript.errors import MissingCredentialsError
PSYCOPG2_CONNECTION_KWARG_MAP = {
"dbname": "database_name",
"user": "database_user",
"password": "<PASSWORD>",
"host": "database_host",
"port": "database_port",
}
MSSQL_CONNECTION_K... |
11437239 | from machine import UART
from machine import Pin as pin
ut = UART(0,9600)
command = b'S'
#Define Driver pins
in1 = pin(16,pin.OUT)
in2 = pin(17,pin.OUT)
in3 = pin(18,pin.OUT)
in4 = pin(19,pin.OUT)
#########
ENA = pin(20,pin.OUT)
ENB = pin(21,pin.OUT)
ENA.value(1)
ENB.value(1)
#########
#This Fu... |
11437248 | from ajenti.api import *
from ajenti.plugins import *
info = PluginInfo(
title='Ajenti VH - Node.JS Support',
icon='globe',
dependencies=[
PluginDependency('vh'),
PluginDependency('services'),
PluginDependency('supervisor'),
],
)
def init():
import nodejs
|
11437252 | from typing import List, Optional, Union
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin, clone
from feature_engine.dataframe_checks import (
_check_input_matches_training_df,
_is_dataframe,
)
from feature_engine.validation import _return_tags
from feature_engine.variable_manipula... |
11437274 | import numpy as np
import logging
_logger = logging.getLogger(__name__)
class AtariStateBuffer(object):
""" A buffer to collect frames until they form a state.
Attributes:
name (str): The name of the buffer object.
sequence_length (int): Determines how many frames form a state.
frame_d... |
11437290 | import asyncio
import os
from unittest import TestCase, skip
import aioboto3
from aiobotocore import AioSession
from botocore import credentials
from src.async_kinesis_client.kinesis_consumer import AsyncKinesisConsumer
"""
Test against live AWS. Use at your own risk.
"""
class LiveTestKinesisConsumer(TestCase):
... |
11437291 | import os, sys
import bpy
import math
from math import radians
from tqdm import tqdm
sys.path.append('..')
from render_utils import resize_padding, makeLamp, parent_obj_to_camera, clean_obj_lamp_and_mesh, render_obj_grid
model_dir = 'models'
render_dir = 'Renders_semi_sphere'
models = [name for name in os.listd... |
11437301 | from __future__ import generators
# Do the best we can to completely obliterate a field from Outlook!
from win32com.client import Dispatch, constants
import pythoncom
import os, sys
from win32com.mapi import mapi
from win32com.mapi.mapitags import *
import mapi_driver
def DeleteField_Outlook(folder, name):
name... |
11437305 | from boa3.builtin import public
@public
def positional_order() -> int:
return calc(x1=1, x2=2, x3=3, x4=4)
@public
def out_of_order() -> int:
return calc(x3=1, x1=2, x4=3, x2=4)
@public
def mixed_in_order() -> int:
return calc(5, 6, x3=1, x4=2)
@public
def mixed_out_of_order() -> int:
return cal... |
11437309 | from datetime import datetime
from sqlalchemy import INT, Column, DATETIME, String
from sqlalchemy.dialects.mysql import SMALLINT
from app.models import Base
class PityReport(Base):
__tablename__ = 'pity_report'
id = Column(INT, primary_key=True)
# 执行人 0则为CPU
executor = Column(INT, index=True)
... |
11437318 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from System.Collections.Generic import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
def TempIsolateCategories(view, cats):... |
11437390 | import torch
from model import NPT
import numpy as np
import pymesh
net_G=NPT()
net_G.cuda()
net_G.load_state_dict(torch.load('original_169.model'))
def face_reverse(faces):
identity_faces=faces
face_dict={}
for i in range(len(random_sample)):
face_dict[random_sample[i]]=i
new_f=[]
for i ... |
11437440 | import matplotlib.pyplot as plt
import numpy as np
# import seaborn
from icubam.analytics import plots
data_source = ["bedcounts"]
FIG_NAME = 'LINE_BEDS_PER'
def plot(data, **kwargs):
return {
**plots.plot_each_region(
data,
gen_plot,
col_prefix="n_covid",
fig_name=f"{FIG_NAME}_14D_CO... |
11437462 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from core.models import EventMetaBase
from .count_badges_mixin import CountBadgesMixin
class BadgesEventMeta(EventMetaBase, CountBadgesMixin):
badge_layout = models.CharField(
max_length=4,
default='trad',
... |
11437493 | import time
import numpy as np
import tensorflow as tf
class ModelTrainer():
def __init__(self, model, loss_fn, optimizer, data_class_weights,
num_epochs=512, batch_size=128, patience=64,
W_combinations=None, H_combinations=None, n_batch_per_train_setp=1,
W_combin... |
11437567 | def get_model():
from django_comments.models import Comment
return Comment
def get_form():
from extcomments.forms import CommentForm
return CommentForm
|
11437593 | class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
# mark the positions of each individual char
pos = {}
duplicates = set()
for i, c in enumerate(s):
pos.setdefault(c, []).append(i)
i... |
11437596 | import os.path
import sys
TOOL_ROOT = os.path.abspath(
os.path.dirname( # c-analyzer/
os.path.dirname(__file__))) # cpython/
DATA_DIR = TOOL_ROOT
REPO_ROOT = (
os.path.dirname( # ..
os.path.dirname(TOOL_ROOT))) # Tools/
INCLUDE_DIRS = [os.path.join(REPO_ROOT, name) for nam... |
11437601 | import os
import ray
from json import load, dump
from os.path import dirname
import argparse
import numpy as np
from environment import (
BaseEnv,
BenchmarkEnv,
RRTWrapper,
RRTSupervisionEnv,
TaskLoader
)
from environment.utils import get_observation_dimensions
import torch
from tensorboardX import ... |
11437612 | from xv_leak_tools.log import L
from desktop_local_tests.local_ip_responder_test_case import LocalIPResponderTestCase
class LocalIPResponderTestCaseWithDisrupter(LocalIPResponderTestCase):
def __init__(self, disrupter_class, devices, parameters):
super().__init__(devices, parameters)
self.disrupte... |
11437661 | import wx
from wx import WHITE, HORIZONTAL, VERTICAL, ALIGN_RIGHT, ALIGN_CENTER_VERTICAL, EXPAND, ALIGN_LEFT, ALL
from cgui import SimplePanel
from gui.uberwidgets.PrefPanel import PrefPanel
from gui.validators import NumericLimit
import util.proxy_settings
ID_NONPROX = wx.NewId()
ID_SYSPROX = wx.NewId()
... |
11437722 | import re
import time
import datetime
import ipaddress
from dateutil.relativedelta import relativedelta
from . import botsite
from .core import check, log, EditQueue
from .botsite import cur_timestamp, get_summary
DEBUG = False
DELAY = 180
LONG_SLEEP = 120
SHORT_SLEEP = 30
VIP = 'Wikipedia:当前的破坏'
RFP = 'Wikipedia:请求... |
11437747 | import matplotlib.pyplot as plt
# 处理中文乱码
plt.rcParams['font.sans-serif']=['SimHei']
x_data = [2011,2012,2013,2014,2015,2016,2017]
y_data = [58000,60200,63000,71000,84000,90500,107000]
y_data_1 = [78000,80200,93000,101000,64000,70500,87000]
plt.title(label='xxx 公司 xxx 产品销量')
# 设置标题
plt.plot(x_data, y_data,... |
11437782 | track_actions = (
("POST", "POST"),
("DELETE", "DELETE"),
("PUT", "PUT"),
("PATCH", "PATCH"),
)
TABLES = ["track_actions_history", "django_admin_log"]
|
11437785 | import collections
from copy import deepcopy
import logging
import warnings
from typing import Any, Dict, Sequence, Union
import numpy as np
from sacred import Experiment
import torch
from experiments.common import get_local_attack_nodes, prepare_attack_experiment
from rgnn_at_scale.attacks import create_attack
from ... |
11437835 | from pathlib import Path
import joblib
import pandas as pd
from tqdm import tqdm
def _labelset_to_inv_labelmap(labelset):
import vak.labeled_timebins
labelset = vak.converters.labelset_to_set(labelset)
labelmap = vak.labels.to_map(labelset, map_unlabeled=False)
if any([len(label) > 1 for label in la... |
11437868 | from Crypto.Cipher import AES
from Crypto.Util import Padding
from binascii import hexlify, unhexlify
from ctflib import extract_flag
import requests
number = 765876346283
url = 'http://pwn.kosenctf.com:8000/check'
r = requests.post(url, data={'number':number}, allow_redirects=False)
result = unhexlify(r.cookies['resu... |
11437911 | import numpy as np
import sys, os, argparse
def Load_SCORE(file_name):
file = open(file_name, 'r')
shot_dir = []
while True:
line = file.readline()
if line == '':
break
line = line.strip('\n').split('\t')
assert len(line) == 4 and line[0] == '#' and int(line[1]) ... |
11437949 | import os
from locust import HttpUser, TaskSet, task, between, constant
class APIUser(HttpUser):
wait_time = between(1, 10)
@task(int(os.getenv("GET_HEALTH_RATIO", 0)))
def get_health(self):
self.client.get(url="/health", verify=False)
@task(int(os.getenv("GET_PREDICT_RATIO", 0)))
def ge... |
11437993 | from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.models import load_model
from performer.networks.linear_attention import Performer
INPUT_SHAPES = [([1, 18, 16], [1, 4, 12], [1, 4, 12], (1,)),
([1, 5, 3, 16], [1, 5, 4, 16], [1, 5, 4, 12], (1... |
11438034 | from bs4 import BeautifulSoup as bs
import requests
import re
import sys
import os
import platform as pf
amountOfLinks = len(sys.argv)-1
urlCounter = 0
imageCounter = 0
skippedCounter = 0
urlList = []
missingFiles = []
downloadedFiles = []
dlFileList = []
userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64)... |
11438095 | import random
from kivy.properties import NumericProperty, ObjectProperty
from answer_widgets import BoxButtonsAnswerWidget
from description_widgets import TextDescriptionWidget
from task_widgets.task_base.base import BaseTask
from task_widgets.task_base.mixins import StartImmediatelyMixin
class Calculation(BaseTas... |
11438101 | import sys
import json
data=sys.argv[1]
jsonfname = '../../data/'+data+'/sentences.json'
mapfname = '../../data/'+data+'/entity2id.txt'
countfname = '../../data/'+data+'/entityCount.txt'
with open(jsonfname, 'r') as jsonf, open(mapfname, 'r') as mapf, open(countfname, 'w') as countf:
map = {}
countMap = {}
for line... |
11438159 | import requests
from pprint import PrettyPrinter
pp = PrettyPrinter()
AppID = "0d298da8"
AppKey = "ecae8ec7c3e3368cf706242e747e466b"
params = {
"app_id":AppID,
"app_key":AppKey,
"format":"json",
"source":"PNQ",
"destination":"BOM",
"dateofdeparture":"20200215",
"dateofarrival":"",
"":"... |
11438167 | import fepy
def install():
fepy.override_builtin('socket')
fepy.override_builtin('select')
|
11438200 | from uuid import uuid1
import pytest
from .common import wait_for_tx, wait_for_blocktime, get_rpc
rpc = get_rpc()
@pytest.mark.zerofee
def test_pending_tx(addresses):
'''
For this test, we need a clean slate wallet, so we can't use the default wallet.
prepare test wallet
- create wallet with unique... |
11438212 | from __future__ import print_function
import os
import os.path as osp
import numpy as np
import pickle
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
# Set the appropriate paths of the datasets here.
_TIERED_IMAGENET_DATASET_DIR = osp.join(osp... |
11438221 | from typing import Dict
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class NetStat(RemoteStats):
def detect_iface(self) -> str:
"""Detect the active newtwork interface.
Examples of ip output:
default via 172.23.100.1 dev enp5s0f0 onlink
default... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.