id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9941371 | from __future__ import print_function, unicode_literals
from collections import defaultdict
from functools import wraps
import json
import os
import re
import time
import calendar
import urlparse
import traceback
from weblab.core.wl import weblab_api
from weblab.core.i18n import gettext
from flask import current_app, ... |
9941474 | from gym.envs.mujoco.mujoco_env import MujocoEnv
# ^^^^^ so that user gets the correct error
# message if mujoco is not installed correctly
from gym.envs.mujoco.ant import AntEnv
from gym.envs.mujoco.half_cheetah import HalfCheetahEnv
from gym.envs.mujoco.hopper import HopperEnv
from gym.envs.mujoco.walker2d import Wal... |
9941475 | from apischema.types import MetadataImplem, MetadataMixin
def test_metadata():
metadata = MetadataImplem({"a": 0, "b": 1})
assert metadata | {"b": 2} == {"a": 0, "b": 2}
assert {"b": 2} | metadata == metadata
class KeyMetadata(MetadataMixin):
key = "key"
def test_metadata_mixin():
instance = K... |
9941490 | from pprint import pprint
import numpy as np
import cv2
import os
# CenterNet
import sys
CENTERNET_PATH = './CenterNet/src/lib'
sys.path.insert(0, CENTERNET_PATH)
from detectors.detector_factory import detector_factory
from opts import opts
MODEL_PATH = './CenterNet/models/ctdet_coco_dla_2x.pth'
ARCH = 'dla_34'
# M... |
9941499 | from pwn import *
context.kernel='amd64'
frame = SigreturnFrame()
registers = ['eax', 'ebx', 'ecx', 'edx',
'edi', 'esi', 'ebp', 'esp',
'eip']
for index, register in enumerate(registers):
setattr(frame, register, index)
assembly = '\n'.join([
shellcraft.read(constants.STDIN_FILENO, '... |
9941537 | import theano
import theano.tensor as tensor
#global variables to use to toggle training and rng, etc
from theano.sandbox.rng_mrg import MRG_RandomStreams
layer_train_rng = MRG_RandomStreams()
layer_train_enable = tensor.bscalar()
layer_train_epoch = tensor.iscalar()
layer_train_it = theano.shared(0)
def get_rng():
... |
9941566 | s = 'Hello'
# rjust() examples
s1 = s.rjust(20)
print(f'***{s1}***')
s1 = s.rjust(20, '#')
print(f'***{s1}***')
s1 = s.rjust(20, 'ç')
print(f'***{s1}***')
s1 = s.rjust(4)
print(f'***{s1}***') # when string size is more than specified width, original string is returned
# ljust() examples
s = 'Hello'
s1 = s.ljust... |
9941634 | from CTFd.utils.humanize.numbers import ordinalize
def test_ordinalize():
tests = {
1: "1st",
2: "2nd",
3: "3rd",
4: "4th",
11: "11th",
12: "12th",
13: "13th",
101: "101st",
102: "102nd",
103: "103rd",
111: "111th",
}
... |
9941678 | from os import environ
import traceback
import json
from pymemcache.client.hash import HashClient
SECRETS = [
'ELASTICACHE_ENDPOINT_ADDRESS',
'ELASTICACHE_PORT_NUMBER'
]
def check_secrets():
assert set(SECRETS).issubset(set(environ)), "Required secrets are not present in environment variables. ENVIRONME... |
9941682 | from datetime import datetime
from sqlalchemy import event, MetaData
from sqlalchemy.engine import Engine
from logic_bank.rule_bank.rule_bank import RuleBank
from logic_bank.rule_bank import rule_bank_withdraw
from logic_bank.exec_trans_logic.listeners import before_flush, before_commit
from sqlalchemy.orm import ses... |
9941688 | from resotolib.args import ArgumentParser
from resotolib.core import resotocore, add_args
def test_args():
arg_parser = ArgumentParser(
description="resoto metrics exporter", env_args_prefix="RESOTOMETRICS_"
)
add_args(arg_parser)
arg_parser.parse_args()
assert resotocore.http_uri == "http... |
9941712 | from keras.layers import Input
from access_niu.components import Component
from access_niu.utility import parse_shape
class InputLayer(Component):
def __init__(self, **kwargs):
super(InputLayer, self).__init__(**kwargs)
self.comp_kwargs = kwargs
self.comp_kwargs["shape"] = parse_shape(kwa... |
9941746 | import ccy
from flask import Flask, request
from my_app.product.views import product_blueprint
app = Flask(__name__)
app.register_blueprint(product_blueprint)
@app.template_filter('format_currency')
def format_currency_filter(amount):
currency_code = ccy.countryccy(request.accept_languages.best[-2:]) or 'USD'
retu... |
9941769 | class StateTracker(object):
state_class = None # associated state class
def update_state(self, state, cn):
"""Update state according to the confusion network cn."""
pass |
9941774 | import logging
import fmcapi
import time
def test__phys_interfaces(fmc):
logging.info(
"Test PhysicalInterface. get, put PhysicalInterface Objects. Requires registered device"
)
sz1 = fmcapi.SecurityZones(fmc=fmc)
sz1.name = "SZ-OUTSIDE1"
sz1.post()
time.sleep(1)
sz2 = fmcapi.Sec... |
9941795 | from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from pyws.adapters import get_http_response_code_num
from pyws.request import Request
from pyws.utils import parse_qs
@csrf_exempt
def serve(request, tail, server):
"""
Django adapter. It has three arguments:
#. ``... |
9941807 | from common.methods import set_progress
from resourcehandlers.aws.models import AWSHandler
from botocore.exceptions import ClientError
import boto3
def run(resource, *args, **kwargs):
rh = AWSHandler.objects.get(id=resource.aws_rh_id)
client = boto3.client(
'eks',
region_name=resource.aws_reg... |
9941812 | import unittest
import json
import os
from craft_ai import (
errors,
extract_decision_paths_from_tree,
extract_decision_path_neighbors,
extract_output_tree,
)
HERE = os.path.abspath(os.path.dirname(__file__))
DATA_DIR = os.path.join(HERE, "data", "interpreter")
TREES_DIR = os.path.join(DATA_DIR, "de... |
9941813 | from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from chat.routing import websocket_urlpatterns
application = ProtocolTypeRouter(
{
# (http->django views is added by default)
"websocket": AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
... |
9941902 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
try:
autocast = torch.cuda.amp.autocast
except:
# dummy autocast for PyTorch < 1.6
class autocast:
def __init__(self, enabled):
pass
def __enter__(self):
pass
def __exit__(se... |
9942023 | class Solution:
def removeVowels(self, S: str) -> str:
return ''.join(c for c in S if c not in 'aeiou')
|
9942025 | import sys
if len(sys.argv) != 3:
print("Usage: python3 compute_error_rate.py encoded_file decoded_file")
sys.exit(1)
encoded_file = sys.argv[1]
decoded_file = sys.argv[2]
with open(encoded_file) as f:
encoded_codewords = [l.rstrip('\n') for l in f.readlines()]
with open(decoded_file) as f:
decoded_... |
9942076 | from typing import Optional, List
from pydantic import validator, BaseModel
from tracardi.domain.entity import Entity
from tracardi.domain.value_object.storage_info import StorageInfo
from tracardi.domain.named_entity import NamedEntity
from tracardi.process_engine.tql.condition import Condition
from tracardi.service.s... |
9942103 | from memsql.common import database
conn = database.connect(host="127.0.0.1", port=3306, user="root", password="")
print(conn.query("show databases"))
|
9942110 | import cv2
import numpy as np
from generators.voc_generator import PascalVocGenerator
from utils.transform import random_transform_generator
from utils.image import random_visual_effect_generator
from utils.image import preprocess_image
def show_annotations():
generator = PascalVocGenerator(data_dir='datasets/voc... |
9942115 | import re
import string
from nltk.tokenize import wordpunct_tokenize
import numpy as np
import torch
class UniformSample:
def __init__(self, n_sample):
self.n_sample = n_sample
def __call__(self, frames):
n_frames = len(frames)
if n_frames < self.n_sample:
return frames
... |
9942173 | from rest_framework.routers import DefaultRouter
from rest_framework_nested.routers import NestedDefaultRouter
from herders.api_views import *
from herders.routers import NestedStorageRouter
"""
herders api routes
Personal:
/profile/<username>/
/profile/<username>/storage/
/profile/<username>/buildings/
/profile/<us... |
9942198 | def convert_a(element, text):
if text:
href = element.get('href')
classes = dict(element.attrs).get('class', '')
if 'footnote-reference' in classes:
text = '[' + href + ']_'
elif len(text.split(' ')) > 1:
text = '`' + text + '`_'
else:
text... |
9942220 | import torch
import torch.nn as nn
import spconv
from functools import partial
import time
from ...ops.point_voxel_ops import pv_utils
def sp_block(in_channels, out_channels, kernel_size, indice_key=None, stride=1, padding=0,
conv_type='subm', norm_fn=None):
if conv_type == 'subm':
con... |
9942256 | def get_set_bits(num):
if not num:
return 0
max_pow, max_pow_of_two = 0, 1
while max_pow_of_two - 1 <= num:
max_pow_of_two *= 2
max_pow += 1
max_pow_of_two //= 2
max_pow -= 1
remainder = num - (max_pow_of_two - 1)
set_bits = ((max_pow * max_pow_of_two) // 2)
se... |
9942265 | from http import cookies
from urllib.parse import urlparse, parse_qsl
from onelogin.saml2.auth import OneLogin_Saml2_Auth
from chalicelib.utils.helper import environ
SAML2 = {
"strict": True,
"debug": True,
"sp": {
"entityId": environ["SITE_URL"] + "/api/sso/saml2/metadata/",
"assertionCo... |
9942272 | import logging
import os
from collections import OrderedDict
from decimal import Decimal, getcontext
from datetime import timedelta
from dateutil import parser as date_parse
import pandas as pd
import pytz
import warnings
from .base import OandaBrokerBase
from ..app_conf import settings
from ..portfolio import Positi... |
9942291 | import requests
import re
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Drupal Drupalgeddon 2 RCE''',
"description": '''Drupal before 7.58, 8.x before 8.3.9, 8.4.x before 8.4.6, and 8.5.x before 8.5.1 allows remote attackers to execute arbitrary code because of a... |
9942317 | import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
def top1_pred(outputs, half=False):
max_logit, pred = torch.max(outputs, 1)
if half:
pred = pred.half()
return max_logit, pred
class EarlyExitInspector():
def __init__(self, Network, device, pr... |
9942324 | import json
import tabulate
JSON = "json"
TABLE = "table"
def to_table(response):
"""Convert raw response into table output."""
if response is None:
return response
# Tabulate dictionary responses
if isinstance(response, dict):
return tabulate.tabulate(
[(key, value) for ... |
9942332 | import tensorflow as tf
import time
from matrix_exp_op import matrix_exp
import sys
def compute_graph_optimize(size, nsteps, n_channels, dt, relax):
start = time.time()
# return
dims = 'xy'
measure_time = True;
print("\n\n Tensorflow is computing the graph:\n\n")
with tf.Session() ... |
9942338 | from machine import Pin
DS1302_REG_SECOND = (0x80)
DS1302_REG_MINUTE = (0x82)
DS1302_REG_HOUR = (0x84)
DS1302_REG_DAY = (0x86)
DS1302_REG_MONTH = (0x88)
DS1302_REG_WEEKDAY= (0x8A)
DS1302_REG_YEAR = (0x8C)
DS1302_REG_WP = (0x8E)
DS1302_REG_CTRL = (0x90)
DS1302_REG_RAM = (0xC0)
class DS1302:
def __... |
9942349 | import sys
import argparse
import os
import json
import torch
from time import time
from datetime import timedelta
from os.path import join, exists
from torch.optim import Adam
from utils import get_data_path, get_rouge_path
from dataloader import BertSumLoader
from model import BertSum
from fastNLP.core.optimizer im... |
9942361 | from utils import json_functions as json
from django.test.client import Client
from django.test import TestCase
from django.urls import reverse
from django.conf import settings
from mongoengine.connection import connect, disconnect
class Test_Profile(TestCase):
fixtures = [
'subscriptions.json',
'r... |
9942367 | from django.db import models
from modelcluster.models import ClusterableModel
from wagtail.admin.edit_handlers import StreamFieldPanel, FieldPanel
from wagtail.contrib.settings.models import BaseSetting, register_setting
from wagtail.core.fields import StreamField
from wagtail.core import blocks
from wagtail.embeds.bl... |
9942408 | def hacktober(name, year):
print(name + " welcome to hacktoberfest " + year)
name = "<NAME>"
year = "2020"
hacktober(name,year)
|
9942439 | import os
import sys
import threading
import time
import periphery
from .test import ptest, pokay, passert, AssertRaises
if sys.version_info[0] == 3:
raw_input = input
import queue
else:
import Queue as queue
path = None
line_input = None
line_output = None
def test_arguments():
ptest()
# Inv... |
9942462 | import nltk
from nltk.corpus import wordnet
from nltk.corpus import wordnet as wn
lion = wn.synset('lion.n.01')
cat = wn.synset('cat.n.01')
print(lion.wup_similarity(cat))
|
9942479 | from pytest import mark
from cerberus import errors
from cerberus.tests import assert_fail, assert_normalized, assert_success
@mark.parametrize(
("test_function", "document"),
[
(assert_success, {'a_nullable_integer': None}),
(assert_success, {'a_nullable_integer': 3}),
(assert_succes... |
9942548 | import numpy as np
import torch
import torch.cuda
import random
import os
import warnings
import hashlib
import _pickle as pickle
import logging
from fastNLP.io import EmbedLoader
from fastNLP.core.metrics import MetricBase
from fastNLP import logger
import argparse
from torch import nn
from torch.optim import SGD, Ada... |
9942562 | from setuptools import setup
setup(name='tensorfieldnetworks',
version='0',
description='3d rotation-equivariant neural networks',
url='https://github.com/tensorfieldnetworks/tensorfieldnetworks',
license='MIT',
packages=['tensorfieldnetworks'],
zip_safe=False)
|
9942564 | import discord
from redbot.core.errors import CogLoadError
from .threadbumper import ThreadBumper
def setup(bot):
if discord.__version__[0] == "1":
raise CogLoadError("You need to use discord.py 2.0.0 minimum to use this cog")
bot.add_cog(ThreadBumper(bot))
|
9942595 | from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Return Alcali version"
def handle(self, *args, **options):
version = settings.VERSION
self.stdout.write("alcali version {}".format(version))
|
9942599 | import inspect
from argparse import ArgumentTypeError
from nose.tools import raises, assert_equal
from radula.rad import (Radula, RadulaLib, _gib, _gb, _mib, _mb, RadulaError,
human_size, from_human_size, calculate_chunks,
legacy_calculate_chunks, guess_target_name, must_... |
9942610 | import os
from typing import Optional, Callable
def buildkite_echo(message: str, print_fn: Callable[[str], None] = print):
if "BUILDKITE" in os.environ:
print_fn(message)
def buildkite_group(
name: str, open: Optional[bool] = None, print_fn: Callable[[str], None] = print
):
if open is True:
... |
9942612 | from telegrambot.test.factories.auth import AuthTokenFactory # noqa
from telegrambot.test.factories.bot import BotFactory # noqa
from telegrambot.test.factories.telegram_lib import (UserLibFactory, ChatLibFactory, # noqa
MessageLibFactory, UpdateLibFactory) # noq... |
9942614 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import edward as ed
import tensorflow as tf
from edward.models import Normal
class test_implicit_klqp_class(tf.test.TestCase):
def test_normal_run(self):
def ratio_estimator(data, local_vars, global_v... |
9942622 | from contextlib import contextmanager
from logging import getLogger
from time import sleep
from uuid import uuid4
from raptiformica.distributed.exec import try_machine_command
from raptiformica.shell.execute import run_command_print_ready, raise_failure_factory, run_critical_command_print_ready
log = getLogger(__nam... |
9942626 | import sys
import json
import asyncio
from unittest import mock
from datetime import datetime
import logging
import time
from astool import ctx, iceapi
import models
def begin_session_2(context):
with open("border/tests/fetchBootstrap.json", "r") as ff:
bs_t, _1, _2, m_bootstrap, _3 = json.load(ff)
w... |
9942635 | import os
import sys
import time
from collections import Counter
import ray
""" This script is meant to be run from a pod in the same Kubernetes namespace
as your Ray cluster.
Just below are the environment variables used to access Ray client via a
service targetting the Ray cluster's head node pod.
These environmen... |
9942653 | import json
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
np.random.seed(1)
def plot_data(x, y):
colors = {1: 'red', 0: 'blue'}
clabel = [colors[yi] for yi in y]
plt.scatter(x[:, 0], x[:, 1], c=clabel)
for nobs in (50, 100, 200, 300, 1000):
x, y = make_moo... |
9942670 | pkgname = "perl-locale-gettext"
pkgver = "1.07"
pkgrel = 0
build_style = "perl_module"
hostmakedepends = ["gmake", "perl"]
makedepends = ["perl"]
depends = ["perl"]
pkgdesc = "Permits access from Perl to the gettext() family of functions"
maintainer = "q66 <<EMAIL>>"
license = "Artistic-1.0-Perl OR GPL-1.0-or-later"
ur... |
9942696 | import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
physical_devices = tf.config.list_physical_devices("GPU")
tf.config.experimental.set_memory_growth(physical... |
9942731 | from data.log_preprocess import JavascriptLogPreprocessor, NetworkLogPreprocessor
from utils.utils import intersection
from scores.scores import Scores
class LogProcessor(object):
def __init__(self, baseline_js_log_file, updated_js_log_file, baseline_network_log_file, updated_network_log_file):
self.basel... |
9942747 | import logging
import traceback
from datetime import datetime
from typing import Optional
from uuid import uuid4 as uuid
from dino import utils
from dino.config import ConfigKeys
from dino.db.manager.base import BaseManager
from dino.environ import GNEnvironment
from dino.exceptions import NoSuchUserException
from din... |
9942753 | import os
import torch
from collections import defaultdict
from model.common import (
get_tensor_values, sample_patch_points, arange_pixels
)
from tqdm import tqdm
import logging
from model.losses import Loss
import numpy as np
logger_py = logging.getLogger(__name__)
from PIL import Image
class Trainer(object):
... |
9942763 | import asynctest.mock as amock
import pytest
from opsdroid.matchers import match_watson
from opsdroid.events import Message
from opsdroid.parsers import watson
from opsdroid.connector import Connector
import ibm_cloud_sdk_core
import ibm_watson
from ibm_watson import ApiException
async def getMockSkill():
async... |
9942803 | import shutil
from pathlib import Path
import reseval
###############################################################################
# Client file storage management
###############################################################################
def create(config, directory):
"""Add evaluation files to client... |
9942804 | import os
import sys
from typing import Any, Dict, List
import logging
import copy
from omegaconf import OmegaConf
from torchfly.flyconfig.flyconfig import FlyConfig
config = FlyConfig.load(config_path=None)
FlyConfig.print(config) |
9942835 | import backtrader.analyzers as btanalyzers
from settings import CONFIG
def run_strategy(cerebro):
# Print out the starting conditions
_show_backtest_init(cerebro.broker)
# Run over everything
strats = cerebro.run()
_show_config_settings(CONFIG)
if CONFIG['mode'] == 'backtest':
# P... |
9942865 | from django.conf.urls import url
from . import views
app_name = 'pardakht'
urlpatterns = [
url(r'^p/(?P<slug>\w+)/$', views.start_payment, name='start_payment'),
url(r'^t/(?P<slug>\w+)/(?P<gateway>\w+)/$', views.select_gateway, name='select_gateway'),
url(r'^r/(?P<slug>\w+)/(?P<gateway>\w+)', views.called_... |
9942965 | from logging.config import fileConfig
from unittest import TestCase
import os
from ddt import ddt, data, unpack
from dataextractors.BulkKeggProteinInteractionsExtractor import BulkKeggProteinInteractionsExtractor
from dataextractors.KeggProteinInteractionsExtractor import KeggProteinInteractionsExtractor
@ddt
class... |
9942971 | import torch
from torch import nn
from torch.nn import functional as f
from hypergan.layer_shape import LayerShape
import hypergan as hg
class EfficientAttention(hg.Layer):
"""https://github.com/cmsflash/efficient-attention"""
def __init__(self, component, args, options):
super(EfficientAttention, sel... |
9943002 | import evernote.edam.limits.constants as Limits
from geeknote.geeknote import *
# Connection to Geeknote
geeknote = GeekNote()
authToken = geeknote.authToken
noteStore = geeknote.getNoteStore()
def GeeknoteCreateNewNote(note):
return noteStore.createNote(authToken, note)
def GeeknoteCreateNewNotebook(notebook)... |
9943033 | import numpy as np
import tensorflow as tf
import cv2
import io
import constants
from PIL import Image
from tensorflow.python.keras import models
from vis.utils import utils
class TensorBoardFilterVisualisation:
def __init__(self, model, name, prediction_image):
super().__init__()
self.model = mod... |
9943153 | import asyncio
import elasticsearch
import json
import logging
import requests
import sentry_sdk
from urllib.parse import urlencode
from datamart_core import Discoverer
from datamart_core.common import setup_logging
logger = logging.getLogger(__name__)
class CkanDiscoverer(Discoverer):
EXTENSIONS = ('.csv', '.... |
9943171 | from .carla_benchmark_collector import CarlaBenchmarkCollector
from .benchmark_dataset_saver import BenchmarkDatasetSaver
from .cilrs_dataset import CILRSDataset
from .cict_dataset import CictDataset
from .lbc_dataset import LBCBirdViewDataset, LBCImageDataset
from .bev_vae_dataset import BeVVAEDataset
|
9943205 | import math
import datetime as dt
class Respondent:
respondentcnt = 0
def __init__(self, respdict):
self.respdict = respdict
Respondent.respondentcnt+=1
# add the number of children at home and not at home
def childnum(self):
return self.respdict['childathome'] + self.respdict['childnotathom... |
9943222 | from nlcpy.core.core import ndarray # NOQA
from nlcpy.core.core import array # NOQA
from nlcpy.core.core import MemoryLocation # NOQA
from nlcpy.core.broadcast import broadcast_to # NOQA
from nlcpy.core.broadcast import _broadcast_core # NOQA
from nlcpy import veo # NOQA
from nlcpy.core.core import set_boundary... |
9943239 | import lookml
import lookml.lkml as lkml
import unittest, copy, json
from pprint import pprint
import warnings
import configparser
import pprint, base64
from looker_sdk import models, methods, init40
import os
import github
from pathlib import Path
config = configparser.ConfigParser()
config.read('lookml/tests/.conf/a... |
9943296 | import math
t = int(input())
while t:
A, B=list(map(int,input().split()))
area = A*B
hcf = math.gcd(A,B)
print(int(area/(hcf*hcf)))
t = t-1 |
9943316 | from scripts import data_process as dp
import matplotlib
from scripts.constants import *
import tensorflow as tf
import matplotlib.pyplot as plt
import pickle
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 1
batch_size = 100
x = tf.placeholder('float')
y = tf.placeholder('float')
def neural_netw... |
9943318 | import autopath
import sys
import os
from pypy.lang.smalltalk import model, interpreter, primitives, shadow
from pypy.lang.smalltalk import objtable
from pypy.lang.smalltalk import classtable
# from pypy.lang.smalltalk.test.test_interpreter import *
from pypy.lang.smalltalk import squeakimage
from pypy.lang.smalltalk i... |
9943355 | import csv
import os.path
import matplotlib
import numpy as np
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'font.size': 15})
n_trial = 5
top_k = 1
batch_size = 4000
max_step = np.inf
max_reward = np.inf
min_reward = -np.inf
exp_name = 'CartpoleNd'
exp_param = 'D1K05A05Ec10'
extra_name = ''
prep... |
9943360 | class User:
def __init__(self, user: dict):
self.id = user.get("id")
self.type = user.get("type")
self.roles = user.get("roles")
self.email = user.get("email")
|
9943367 | from . import FieldType
from . import FieldValue
from . import FieldTypeRegression
from . import FieldValueRegression
def rec(node, result, randomstate):
node.randomstate = randomstate
v = node.pick_value()
result[node.field_name] = v.get_field_value()
if v.next_field and len(v.next_field.values) > 0:... |
9943374 | import os
import json
from COCO_Eval_Utils import coco_eval,coco_eval_specific
from Utils import model_construction,init_optimizer,set_lr,clip_gradient,get_transform,get_sample_image_info,visualize_att,RewardCriterion,get_self_critical_reward
import torch.nn as nn
import torch
from torch.nn.utils.rnn import pack_padded... |
9943386 | import numpy as np
from gym.spaces import Box
import pyflex
from softgym.envs.fluid_env import FluidEnv
import copy
from softgym.utils.misc import rotate_rigid_object, quatFromAxisAngle
from shapely.geometry import Polygon
import random, math
class PourWaterPosControlEnv(FluidEnv):
def __init__(self,... |
9943461 | import sys
import crypt
if __name__ == '__main__':
auths = dict()
with open(sys.argv[1]) as fh:
line = fh.readline()
while line:
username, password = line.strip().split(':')
auths[username] = crypt.crypt(password)
line = fh.readline()
with open(sys.argv[1... |
9943508 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if head and head.next:
p = head.next
head.next = self.swapPairs(p.next)
p.next = head
return p #fixme if... |
9943536 | def shellsort(arr,n):
gap = n//2
# increase with a large gap and decrease it slowly
while gap>0:
for i in range(gap,n):
temp = arr[i]
j = i
while j >= gap and arr[j-gap] > temp:
arr[j] = arr[j-gap]
j -= gap
arr[j] = te... |
9943548 | from covid19_sfbayarea.news import scrapers
from covid19_sfbayarea.news.contra_costa import ContraCostaNews
from covid19_sfbayarea.news.feed import NewsItem
from covid19_sfbayarea.utils import PACIFIC_TIME
from datetime import datetime
import os
import pytest
from typing import List
from unittest.mock import patch
# ... |
9943557 | from setuptools import setup
setup(name='tl_algs',
version='0.1',
description='A library of transfer learning algorithms for python',
url='https://para.cs.umd.edu/purtilo/transfer-learning-algorithm-library/tree/master',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
... |
9943570 | my_none = None
my_empty_quotes = ''
my_zero = 0
my_false = False
if my_none:
print('I will never print this line.')
elif my_empty_quotes:
print('I will never print this line.')
elif my_zero:
print('I will never print this line.')
elif my_false:
print('I will never print this line.')
else:
print('Al... |
9943626 | import unittest
import unittest.mock as mock
from fints2ledger.config import Config
class ConfigTest(unittest.TestCase):
def setUp(self):
self.config = Config()
self.config.files_path = "~/.config/fints2ledger/"
@mock.patch("fints2ledger.config.Path")
@mock.patch("fints2ledger.config.open... |
9943652 | import django.test
import django.shortcuts
from . import factories
import json
class TestViewAutocomplete(django.test.TestCase):
def setUp(self):
self.user = factories.UserFactory.create(is_staff=True, is_admin=True)
self.client = django.test.Client()
assert self.client.login(username=se... |
9943693 | import seldon.pipeline.auto_transforms as auto
import pandas as pd
df = pd.DataFrame([{"a":10,"b":1,"c":"cat"},{"a":5,"b":2,"c":"dog","d":"Nov 13 08:36:29 2015"},{"a":10,"b":3,"d":"Oct 13 10:50:12 2015"}])
t = auto.Auto_transform(max_values_numeric_categorical=2,date_cols=["d"])
t.fit(df)
df2 = t.transform(df)
print d... |
9943745 | from schematics.exceptions import ValidationError
from schematics.models import Model
from schematics.types import (
BooleanType,
DecimalType,
DictType,
IntType,
ListType,
StringType,
)
class ScoresType(DictType):
def validate_nonempty(self, value):
if not v... |
9943763 | class Item(object):
def __init__(self, caption):
self.caption = caption
@classmethod
def makeHTML(cls):
raise NotImplementedError
class Link(Item):
def __init__(self, caption, url):
super().__init__(caption)
self.url = url
class Tray(Item):
def __init__(self, cap... |
9943784 | from unittest import TestCase
from flow_py_sdk import SignAlgo
class TestHashAlgo(TestCase):
def test_from_string(self):
cases = [
(SignAlgo.ECDSA_P256, "ECDSA_P256"),
(SignAlgo.ECDSA_secp256k1, "ECDSA_secp256k1"),
]
for algo, name in cases:
with self.s... |
9943785 | import json
from mock import patch
from buildercore import vault
from . import base
class TokenCreation(base.BaseCase):
@patch('buildercore.external.execute')
def test_token_create_for_masterless(self, exec_stub):
exec_stub.return_value = json.dumps({
# ...
'auth': {
... |
9943798 | import sys
import os
import time
import sublime
import sublime_plugin
sys.path.append(os.path.dirname(__file__))
import logger
import serial_monitor_thread
from serial_settings import SerialSettings
from filter.serial_filter import FilterFile, FilterException
from . import command_history_event_listener
... |
9943871 | import unittest
from katas.beta.identifying_top_users_and_their_corresponding_purchases \
import id_best_users
class IdBestUsersTestCase(unittest.TestCase):
def setUp(self):
self.a1 = ['A042', 'B004', 'A025', 'A042', 'C025']
self.a2 = ['B009', 'B040', 'B004', 'A042', 'A025', 'A042']
def ... |
9943874 | from django.conf.urls import url, include
from django.contrib import admin
from .views import (oidc_admin_login, oidc_admin_logout,
oidc_backchannel_logout, complete)
urlpatterns = [ # noqa: invalid-name
# We need to override default `social_python` `complete` behavior in order
# to pro... |
9943887 | import pyqtgraph as pg
from pyqtgraph.Qt import QtCore
import numpy as np
import collections
from pyqtgraph import functions as fn
from pyqtgraph import debug as debug
from pyqtgraph.Point import Point
from collections.abc import Callable
class ColorbarImage(pg.ImageItem):
'''
For the most part, this class is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.