id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11533051 | from .dataset import Dataset
from .large_img_dataset import LargeImgDataset
from .sequential_dataset import SequentialDataset
from .celeba_data import CelebAData
from .cifar10_data import CIFAR10Data
from .cifar100_data import CIFAR100Data
#from .cub_200_2011_data import CUB2002011
from .fashion_mnist import FashionMN... |
11533063 | from functools import reduce
import logging
from django.conf import settings as django_settings
from rest_framework import exceptions
from waldur_core.core.permissions import SAFE_METHODS, IsAdminOrReadOnly
from waldur_core.structure import models
logger = logging.getLogger(__name__)
# TODO: this is a temporary pe... |
11533078 | import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
from utils import segment_data, segment_length, map_activation_str_to_layer, batch_convert_len_to_mask
from basemodel import EdgeSeqModel
_INF = -1e30
class PositionalEmbedding(nn.Module):
def __init__(self, d_emb):
super(Posit... |
11533114 | from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from ..dummymodel import DummyModel
class Command(BaseCommand):
"""Django command to create Initial Data"""
def handle(self, *args, **option... |
11533127 | import pytest
import datetime
import time
import base64
from cryptoauthlib import *
from cryptoauthlib.library import load_cryptoauthlib
from cryptoauthlib_mock import atcab_mock
__config = cfg_ateccx08a_kithid_default()
def pretty_print_hex(a, l=16, indent=''):
"""
Format a list/bytes/bytearray object into ... |
11533130 | from django.contrib import admin
from .models import Document, Create_page
# Register your models here.
admin.site.register(Document)
admin.site.register(Create_page) |
11533176 | def up(config, database, semester, course):
if not database.table_has_column('electronic_gradeable', 'eg_limited_access_blind'):
database.execute('ALTER TABLE electronic_gradeable ADD COLUMN IF NOT EXISTS eg_limited_access_blind INTEGER DEFAULT 1')
database.execute('ALTER TABLE electronic_grade... |
11533179 | from select2_foreign_key import test_functional
from .models import TModel
class AdminForeignKeyTestCase(test_functional.AdminForeignKeyTestCase):
model = TModel
|
11533214 | from __future__ import absolute_import
import numpy as np
from pyti import catch_errors
from pyti.function_helper import fill_for_noncomputable_vals
from six.moves import range
def true_range(close_data, period):
"""
True Range.
Formula:
TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1))
"""... |
11533251 | from loudml import errors
import requests
from urllib.parse import urlencode
DEFAULT_REQUEST_TIMEOUT = 5
def perform_request(
base_url,
method,
url,
session,
params=None,
body=None,
timeout=None,
ignore=(),
headers=None
):
url = base_url + url
if params:
url = '%s... |
11533256 | from __future__ import absolute_import
"""
Collection of physical constants and conversion factors.
Most constants are in SI units, so you can do
print('10 mile per minute is', 10*mile/minute, 'm/s or',
10*mile/(minute*knot), 'knots')
The list is not meant to be comprehensive, but just a convenient list for
every... |
11533280 | import glob
import os.path as osp
import numpy as np
from vedacore import fileio
from vedacore.image import imread
from vedacore.misc import registry
from .custom import CustomDataset
@registry.register_module('dataset')
class Thumos14Dataset(CustomDataset):
"""Thumos14 dataset for temporal action detection."""... |
11533431 | from vulkan import vk, helpers as hvk
from enum import IntFlag
from functools import lru_cache
from ctypes import memmove, byref, c_void_p, POINTER
import weakref
class MemoryManager(object):
def __init__(self, engine):
self.engine = engine
self.memory_info = {}
self.allocations = []
... |
11533455 | import django.db.models.deletion
from django.db import migrations, models
def build_spl_migrations(APP_NAME, SVC_NAME, SPL_NAME, AFFECTED_MODELS):
def fill_project_and_service(apps, schema_editor):
for model_name in AFFECTED_MODELS:
model = apps.get_model(APP_NAME, model_name)
for ... |
11533464 | from threading import Lock
from polog.handlers.file.locks.abstract_single_lock import AbstractSingleLock
class ThreadLock(AbstractSingleLock):
"""
Обертка вокруг обычного тред-лока (см. https://en.wikipedia.org/wiki/Lock_(computer_science)).
Предназначена, чтобы сделать лок отключаемым.
"""
def ... |
11533469 | from Spheral3d import *
from MedialGenerator import *
from CompositeNodeDistribution import *
from SpheralTestUtilities import *
from VoronoiDistributeNodes import distributeNodes3d as distributeNodes
from siloPointmeshDump import *
commandLine(hmin = 1e-5,
hmax = 1e6,
rhoscale = 0.5,
... |
11533527 | import FWCore.ParameterSet.Config as cms
process = cms.Process('SIM')
# import of standard configurations
process.load('Configuration/StandardSequences/Services_cff')
process.load('FWCore/MessageService/MessageLogger_cfi')
process.load('Configuration.Geometry.GeometryExtended2015Reco_cff')
process.load('Configuration... |
11533567 | from immudb.client import ImmudbClient
import string
import random
import itertools
import time
import multiprocessing
SIZE = 1000000
CHUNKSIZE = 1000
def chunked(it, size):
it = iter(it)
while True:
p = dict(itertools.islice(it, size))
if not p:
break
yield p
def massiv... |
11533571 | import os
import unittest
from rdflib import URIRef, Graph
from rdflib.namespace import OWL, RDFS, RDF
from linkml.generators.owlgen import OwlSchemaGenerator
from tests.utils.compare_rdf import compare_rdf
from tests.utils.test_environment import TestEnvironmentTestCase
from tests.test_issues.environment import env
... |
11533597 | import pytest
from eth.constants import UINT_256_MAX
from trinity.exceptions import OversizeObject
from trinity.utils.headers import sequence_builder
@pytest.mark.parametrize(
'start_num, max_length, skip, reverse, expected',
(
(0, 0, 0, False, ()),
(0, 0, 0, True, ()),
(0, 0, 1, Fal... |
11533607 | from django.conf import settings
from corehq.util.io import ClosingContextProxy
from kafka import KafkaConsumer
from kafka.client import KafkaClient, SimpleClient
GENERIC_KAFKA_CLIENT_ID = 'cchq-kafka-client'
def get_simple_kafka_client(client_id=GENERIC_KAFKA_CLIENT_ID):
# this uses the old SimpleClient becaus... |
11533618 | from ..commandparser import Member
from ..discordbot import unmute_user
import discord
name = 'unmute'
channels = None
roles = ('helper', 'trialhelper')
args = '<member>'
async def run(message, member: Member):
'Removes a mute from a member'
await unmute_user(
member.id,
reason=f'Unmuted by {str(message.author... |
11533631 | from fluent.syntax import ast as FTL
from . import resolver
class Compiler:
def __call__(self, item):
if isinstance(item, FTL.BaseNode):
return self.compile(item)
if isinstance(item, (tuple, list)):
return [self(elem) for elem in item]
return item
def compile(s... |
11533632 | from unittest import TestCase
from unittest.mock import Mock, call, mock_open, patch
from ruamel.yaml import YAML
from conda_vendor.custom_manifest import CustomManifest, IBManifest
# "mymethod" in dir(dyn)
def test_custom_manifest():
assert "__init__" in dir(CustomManifest)
assert "read_meta_manifest" in ... |
11533639 | import numpy as np
import decimal
import random
from keras.models import Sequential
from keras.layers import Dense, Activation, LSTM, Dropout
from keras.utils import to_categorical
from keras import optimizers
from keras import metrics
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
fro... |
11533643 | from django.core.management.base import BaseCommand
from migrate_dns.destructo import destroy
class Command(BaseCommand):
args = ''
def handle(self, *args, **options):
destroy() # Whipe the db
|
11533646 | import pytest
from unittestmock import UnitTestMock
import numpy as np
from cykhash import all_int64, all_int64_from_iter, Int64Set_from, Int64Set_from_buffer
from cykhash import all_int32, all_int32_from_iter, Int32Set_from, Int32Set_from_buffer
from cykhash import all_float64, all_float64_from_iter, Float64Set_from... |
11533647 | import argparse, os, glob, cv2, torch, math, imageio, lpips
from tqdm import tqdm
import kornia as k, numpy as np, torchvision
from get_model import Model
from utils import auxiliaries as aux
from data.get_dataloder import get_eval_loader
# setup argparser
parser = argparse.ArgumentParser()
parser.add_argument('-gpu'... |
11533650 | import argparse
import os, sys
import logging
import json
import csv
from tqdm.auto import tqdm
import torch
from torch.utils.data import DataLoader, SequentialSampler
import sentence_transformers as sent_trans
import transformers
from transformers import set_seed
import accelerate
from accelerate import Accelerator
fr... |
11533657 | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..classification import resnet
class DecoderBlock(nn.Module):
def __init__(self, in_channels, mid_channels, out_channels):
super(DecoderBlock, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(in_channels, mid_channels, ke... |
11533665 | from .. utils import TranspileTestCase, BuiltinFunctionTestCase, SAMPLE_SUBSTITUTIONS
class TupleTests(TranspileTestCase):
pass
class BuiltinTupleFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
functions = ["tuple"]
not_implemented = [
'test_tuple',
]
substitutions = {
... |
11533678 | import pandas as pd
from plotly.graph_objects import Figure
from ml_matrics import ROOT, spacegroup_sunburst
phonons = pd.read_csv(f"{ROOT}/data/matbench-phonons.csv")
def test_spacegroup_sunburst():
fig = spacegroup_sunburst(phonons.sg_number)
assert isinstance(fig, Figure)
assert set(fig.data[0].pare... |
11533693 | from jumpscale.core.exceptions import Input
from jumpscale.clients.explorer.models import Volume, DiskType, ContainerMount, WorkloadType, Container
from typing import Union
class VolumesGenerator:
""" """
def create(self, node_id: str, pool_id: int, size: int = 5, type: Union[str, DiskType] = DiskType.HDD) -... |
11533715 | from django.template.defaultfilters import urlizetrunc
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class UrlizetruncTests(SimpleTestCase):
@setup({
'urlizetrunc01': '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% e... |
11533717 | import doctest
import unittest
from .doctest_2to3 import doctest_suite
def broken_function():
raise Exception('This is broken')
class MyTestCase(unittest.TestCase):
def test(self):
"""
DocTests (pychemia.utils) [exceptions] :
"""
from pychemia.utils.peri... |
11533723 | import sys
import os
import subprocess
from pathlib import Path
import argparse
from tempfile import mkstemp
import re
def remove_inouts(jsonpath, replacewith='input'):
"""Replaces inouts with either input or output statements.
Netlistsvg does not parse inout ports as for now, so they need to be
replaced... |
11533733 | from zenpy import Zenpy
from zenpy.lib.api_objects import Ticket
from zenpy.lib.api_objects import Comment
from zenpy.lib.exception import RecordNotFoundException
from zenpy.lib.exception import APIException
from st2actions.runners.pythonrunner import Action
__all__ = [
'ZendeskAction'
]
class ZendeskAction(Act... |
11533746 | from tottle import BaseStateGroup
from tottle.bot import Bot, Message
# Create a simple bot
bot = Bot("paste-token-here")
# Let's make a group of states
# (BaseStateGroup is IntEnum)
class ProfileState(BaseStateGroup):
NAME = 1
AGE = 2
# <state = None> handles all events with no state;
# you can add StateR... |
11533761 | import copy
from funboost.utils import un_strict_json_dumps
class DataClassBase:
"""
使用类实现的 简单数据类。
也可以使用装饰器来实现数据类
"""
def __new__(cls, **kwargs):
self = super().__new__(cls)
self.__dict__ = copy.copy({k: v for k, v in cls.__dict__.items() if not k.startswith('__')})
return... |
11533764 | from __future__ import absolute_import, unicode_literals
from setuptools import setup, find_packages
from codecs import open
import os
here = os.path.dirname(__file__)
with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='vcrpy-unittest',
version='0.... |
11533791 | import os
import numpy as np
import torch
import pdb
from trajectory.utils import discretization
from trajectory.utils.arrays import to_torch
from .d4rl import load_environment, qlearning_dataset_with_timeouts
from .preprocessing import dataset_preprocess_functions
def segment(observations, terminals, max_path_lengt... |
11533817 | from __future__ import annotations
import pytest
from pipelayer import Action, Context, Filter, FilterEventArgs, Pipeline
from pipelayer.filter import _parse_filter_event_args, raise_events
class MyFilter(Filter):
@raise_events
def run(self, data, context) -> dict:
return {"something": "goes here"}
... |
11533825 | import os
import gc
import ast
import pandas as pd
import numpy as np
from . import fractal
import matplotlib.pyplot as plt
from amlearn.utils.data import read_lammps_dump
from amlearn.utils.check import check_output_path
__author__ = "<NAME>"
__email__ = "<EMAIL>"
"""
This is an example script of fractal analysis, b... |
11533827 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dfirtrack_main', '0010_status_history_for_system'),
]
operations = [
migrations.AlterField(
model_name='domainuser',
name='domainuser_is_domainadmin',
fi... |
11533830 | from app import db,ma
from datetime import datetime
class Todo(db.Model):
id=db.Column(db.Integer, primary_key=True)
content=db.Column(db.String(512))
done=db.Column(db.Boolean)
user_id=db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
created_at = db.Column(db.DateTime, nullable=False, default... |
11533838 | import torch
from torch import Tensor
from torch.nn import Linear
from torch.nn.utils import prune
from .concepts import XConceptizator
class XLogic(Linear):
"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`
"""
def __init__(self, in_features: int, out_features: int, activati... |
11533868 | from wydget import anim
from wydget.widgets.frame import Frame
class Drawer(Frame):
'''A *transparent container* that may hide and expose its contents.
'''
name='drawer'
HIDDEN='hidden'
EXPOSED='exposed'
LEFT='left'
RIGHT='right'
TOP='top'
BOTTOM='bottom'
def __init__(self, pa... |
11533883 | import os
import pytest
from django.core.files.base import ContentFile
from .base import DataLayerFactory, MapFactory
pytestmark = pytest.mark.django_db
def test_datalayers_should_be_ordered_by_rank(map, datalayer):
datalayer.rank = 5
datalayer.save()
c4 = DataLayerFactory(map=map, rank=4)
c1 = Dat... |
11533888 | from __future__ import absolute_import, print_function, unicode_literals
import sys
from metapub import MedGenFetcher
# example of CUID: C0000039
try:
cui = sys.argv[1]
except IndexError:
print('Supply a ConceptID (CUI) to this script as its argument.')
sys.exit()
####
import logging
logging.getLogger(... |
11533928 | import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import copy
from hfta.ops import get_hfta_op_for
def str_to_class(classname):
return getattr(sys.modules[__name__], classname)
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, B=1):
"""3x3 convolution with padding"""... |
11533933 | from __future__ import (absolute_import, division, print_function)
import logging
import neovim
from . import check_lldb
__metaclass__ = type # pylint: disable=invalid-name
if not check_lldb.probe():
logging.getLogger(__name__).critical('LLDB could not be imported!')
# ImportError will be raised in Controll... |
11533979 | import os
import re
import json
import tqdm
import utils
import torch
import random
import sqlite3
import converter
import argparse
import itertools
import embeddings as E
import preprocess_nl2sql_cosql as preprocess_nl2sql
from vocab import Vocab
from collections import defaultdict, Counter
from transformers import Di... |
11533982 | from collections import OrderedDict, defaultdict
from itertools import groupby
import xlsxwriter
import StringIO
from datetime import datetime
from dateutil.parser import parse
from sqlalchemy.sql import func
from sqlalchemy.types import Integer
from ..analysis import BiasCalculator
from ..models import Document, An... |
11533987 | from PIL import Image, ImageDraw, ImageFilter
im1 = Image.open('data/src/rocket.jpg')
im2 = Image.open('data/src/lena.jpg')
# 
# 
im1.paste(im2)
im1.save('data/dst/rocket_pillow_paste.jpg', quality=95)
# ... |
11533995 | import pytest
from channels.testing import WebsocketCommunicator
from .consumers import MyConsumer, Demultiplexer
from .routing import application
def test_consumer_action():
assert hasattr(MyConsumer.incr_counter, 'action_type')
assert MyConsumer.incr_counter.action_type == 'INCREMENT_COUNTER'
@pytest.ma... |
11534036 | import torch
import torch.nn as nn
import torch.nn.functional as F
class SignLoss(nn.Module):
def __init__(self, alpha, b=None):
super(SignLoss, self).__init__()
self.alpha = alpha #alpha 是网络结构中是否加sign loss的flag
self.register_buffer('b', b) #将b注册到模型参数里
self.loss = 0
self.a... |
11534037 | import logging
import os
import random
# import sys
from flask import Flask, render_template, request, url_for
from fourlang.corenlp_wrapper import CoreNLPWrapper
from fourlang.utils import draw_dep_graph, draw_text_graph, ensure_dir, get_cfg
from fourlang.dependency_processor import Dependencies
from fourlang.dep_to... |
11534071 | import asyncio
import click
from lib.data_fetcher import DataFetcher
@click.command()
@click.argument(
'config',
type=click.Path(
exists=True,
readable=True,
)
)
def fetch_ohlcv_data(config):
data_fetcher = DataFetcher(config)
loop = asyncio.get_event_loop()
# wait for all tas... |
11534091 | class PythonTest():
def twice(selt, array):
list = [0 for i in range(len(array))]
i = 0
for x in array:
list[i] = x * 2
i += 1
return list;
|
11534117 | import decimal
import re
from enum import Enum
from typing import Optional, Union
from boto3.dynamodb.conditions import Key
from boto3.dynamodb.types import TypeSerializer, TypeDeserializer
from botocore.exceptions import ClientError
from typhoon.aws.boto3_helper import boto3_session
from typhoon.aws.exceptions impor... |
11534125 | import numpy as np
import matplotlib.pyplot as plt
# Make sure that caffe is on the python path:
caffe_root = '../' # this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
plt.rcParams['figure.figsize'] = (10, 10)
plt.rcParams['image.interpolation'] =... |
11534129 | import praw
import time
import html.entities
import tkinter
import datetime
import string
import sqlite3
from tkinter import Tk, BOTH, Entry, PhotoImage, OptionMenu, Spinbox, Text, Scrollbar, Listbox
from tkinter.ttk import Frame, Button, Style, Label
from tkinter.tix import ScrolledWindow
class Program():
def __... |
11534171 | import os
from toolchain import run_script
from commands import CMD_GET_SHOW_TAPS
from commands import CMD_SET_SHOW_TAPS
isOff = (os.getenv("function") == "debug_off")
try:
result = run_script(CMD_GET_SHOW_TAPS)
isOn = (result[-1:] == '1') or isOff
shell_cmd = CMD_SET_SHOW_TAPS.format(("1", "0")[isOn])
run_s... |
11534182 | from __future__ import print_function
import baseline as bl
import argparse
import os
from baseline.utils import str2bool
def main():
parser = argparse.ArgumentParser(description='Encoder-Decoder execution')
parser.add_argument('--model', help='An encoder-decoder model', required=True, type=str)
parser.add... |
11534229 | import threading
import time
from functools import wraps
import statsd
import strgen
from flask import make_response
from flask import request
from flask_login import current_user
from flask_login import login_user
import config as base_config
import database.user
import util.cache
import util.response
from linkr imp... |
11534233 | def test_get_username_by_user_id(bot, config):
usernames_ids = config.get("usernames_ids")
for item in usernames_ids:
username = item[0]
userid = item[1]
assert username == bot.get_username_by_user_id(userid)
|
11534241 | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from .HubSIRV import HubSIRV
class HubSIRSV(HubSIRV):
"""
SIRSV compartmental model with the Hub model assumption.
Parameters
----------
pss: float
probability someone is considered a super spreader.
... |
11534252 | from copy import copy
from typing import Optional, Union
from hwt.code import And, Or
from hwt.doc_markers import internal
from hwt.hdl.constants import DIRECTION
from hwt.hdl.types.array import HArray
from hwt.hdl.types.bits import Bits
from hwt.hdl.types.enum import HEnum
from hwt.hdl.types.hdlType import HdlType
fr... |
11534255 | import click
import responses
import pytest
from yogit.api.client import GraphQLClient, GITHUB_API_URL_V4
def _add_response(status, json):
responses.add(responses.POST, GITHUB_API_URL_V4, json=json, status=status)
@responses.activate
def test_ok_200():
_add_response(200, {"data": "result"})
client = Gr... |
11534309 | import numpy as np
import matplotlib as mpl
mpl.use("agg", warn=False) # noqa
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn.metrics.pairwise
import scipy.cluster.hierarchy as sch
import scipy.sparse as spsp
import scedar.eda as eda
import pytest
class TestSampleDistanceMatrix(object):
... |
11534335 | from django.conf.urls import patterns, url
from django.views.generic.base import RedirectView
from django.contrib.auth.decorators import login_required as lr
from forum.views import AdminCourseForumView
from course_material.views import CourseMaterialAdminView
from .views import (AdminView, CourseAdminView, CourseCreat... |
11534338 | from flask import jsonify, request, send_file, abort
from PIL import Image
from io import BytesIO
from app import app
from urlparse import urlparse
@app.route('/convertEMF', methods=['POST'])
def get_tasks():
hostname = urlparse(request.referrer).hostname
if hostname.endswith(".draw.io") == False and hostname.endswi... |
11534363 | import os
from UCTB.utils import multiple_process
def task_func(share_queue, locker, data, parameters):
print('Child process %s with pid %s' % (parameters[0], os.getpid()))
for task in data:
print('Child process', parameters[0], 'running', task)
exec_str = 'python HMM.py --Dataset %s --City... |
11534407 | import numpy as np
import torch
from torch.autograd import Function
import holoviews as hv
hv.extension('bokeh')
"""
pytorch-grad-cam by JacobGil (https://github.com/jacobgil/pytorch-grad-cam)
"""
class FeatureExtractor(object):
""" Class for extracting activations and
registering gradients from targetted in... |
11534440 | from decimal import Decimal as D
from django.test import TestCase
from oscar.apps.offer import models, utils
from oscar.apps.shipping.repository import Repository
from oscar.apps.shipping.methods import FixedPrice
from oscar.test.basket import add_product
from oscar.test import factories
def create_offer():
ran... |
11534457 | import os
import sys
import h5py
import pickle
import argparse
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
# from pytorch_transformers.modeling_bert import BertForSequenceClassification, BertConfig, MultimodalBertForSequenceClassification
# from pytorch_t... |
11534477 | from .APIResponse import APIResponse
class LeagueSeason(APIResponse):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.leagueCompleted = kwargs.get("complete", False) or False
self.leagueId = kwargs.get("id", 0) or 0
self.leagueDescription = kwargs.get("league_descriptio... |
11534506 | import argparse
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
INTELLIJ_VERSION_FLAG = "-intellij-version"
def is_environment_in_jdk_table(environment_name, table):
for elem in table:
for subelem in elem:
attribute = subelem.attrib
if attribute.get("valu... |
11534509 | from base import *
import json
class SRLinux(Container):
CONTAINER_NAME = None
GUEST_DIR = '/etc/opt/srlinux'
def __init__(self, host_dir, conf, image='ghcr.io/nokia/srlinux'):
super(SRLinux, self).__init__(self.CONTAINER_NAME, image, host_dir, self.GUEST_DIR, conf)
# don't build just downl... |
11534530 | from typing import Any, Dict, List, Union
from returns.curry import partial
from returns.pipeline import flow, is_successful
from returns.pointfree import bind, fix, map_, rescue
from returns.result import ResultE
from piri.collection_handlers import fetch_data_by_keys
from piri.constants import (
CASTING,
DE... |
11534551 | from datetime import datetime
from unittest import TestCase
from unittest.mock import MagicMock
from hummingbot.strategy.conditional_execution_state import RunAlwaysExecutionState, RunInTimeConditionalExecutionState
class RunAlwaysExecutionStateTests(TestCase):
def test_always_process_tick(self):
strate... |
11534565 | from komand_elasticsearch.util.request_api import RequestAPI
from logging import Logger
class ElasticSearchAPI(RequestAPI):
def __init__(self, url: str, logger: Logger, ssl_verify: bool, username: str = None, password: str = None):
super(ElasticSearchAPI, self).__init__(
url=url, logger=logger... |
11534578 | low = 1
high = 1000
loop_num = 0 # 记录循环轮数
while low <= high:
m = int((high - low) / 2) + low
print("My guess is", m)
# userInput是循环条件中被判断的变量,因此需要在循环之前先有个值,否则循环会出错
user_input = ""
input_num = 0
while user_input != '1' and user_input != '2' and user_input != '3':
if input_num == 3:
... |
11534604 | import pytz
from datetime import datetime
from manabi.apps.flashcards.models import (
Card,
)
from manabi.apps.flashcards.models.new_cards_limit import (
NewCardsLimit,
)
class ReviewInterstitial:
def __init__(
self,
user,
deck=None,
new_cards_per_day_limit_override=None,
... |
11534607 | class tkMath( object ):
PIXELS_PER_INCH = 0
PIXELS_PER_CM = 0
PIXELS_PER_MM = 0
PIXELS_PER_POINT = 0
@staticmethod
def setup( root ):
'''Must be called before any of the methods are used to initialize
the conversion constants.'''
tkMath.PIXELS_PER_INCH = root.winf... |
11534656 | from onadata.apps.main.tests.test_base import TestBase
from django.test.client import RequestFactory
from onadata.apps.viewer.views import stats_tables
class TestStatsTableView(TestBase):
def setUp(self):
super(TestStatsTableView, self).setUp()
# Every test needs access to the request factory.
... |
11534659 | import SimpleITK as sitk
import numpy as np
import random
from PIL import Image
import cv2,os
#input_path='/home/cwx/extra/CAP'
#input_mask='/mnt/data6/CAP/resampled_seg'
output_path_slices='/mnt/data9/covid_detector_jpgs/selected_train_pos/nor'
os.makedirs(output_path_slices,exist_ok=True)
cnt=0
train_list='trainlist... |
11534679 | from pandas import DataFrame
class JsonFormatter(object):
"""Class that receive pandas dataframe
and write it down in Json format
"""
key = 'json-array'
def __init__(self, specification={}):
self.default = {'orient': 'records',
'date_unit': 's'}
self.specif... |
11534681 | import distutils.ccompiler
import distutils.dist
import glob
import io
import os
import sys
import cffi
# Get the directory for the cmark source files. It's under the package root
# as /third_party/cmark/src
HERE = os.path.dirname(os.path.abspath(__file__))
PACKAGE_ROOT = os.path.abspath(os.path.join(HE... |
11534682 | import logging
import sys
import socket
sys.path.append('logmatic/')
import logmatic
logger = logging.getLogger()
handler = logging.StreamHandler()
handler.setFormatter(logmatic.JsonFormatter(extra={"hello": "world","hostname":socket.gethostname()}))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
test_lo... |
11534698 | from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, Documentation, PortDoc, Form, FormGroup, \
FormField, FormComponent
from tracardi.service.plugin.runner import ActionRunner
from tracardi.service.plugin.domain.result import Result
from .model.config import Config, Token
from tracardi.proce... |
11534700 | import autosar.base
import autosar.component
import autosar.rte.base
from autosar.rte.base import (ReadPortFunction, WritePortFunction, SendPortFunction, ReceivePortFunction, CallPortFunction,
CalPrmPortFunction, DataElement, Operation, RequirePort, ProvidePort)
import cfile as C
imp... |
11534713 | from genrss import GenRSS
def create_rss(**kwargs):
return GenRSS(title='SmartFridge', site_url='https://smartfridge.me/',
feed_url='https://smartfridge.me/rss.xml', **kwargs)
def create_item(feed, **kwargs):
feed.item(title='Recipe', **kwargs)
|
11534774 | import matplotlib.pylab as plt
def main():
x = [100, 200, 300, 400, 500, 600,700, 800, 900, 1000,
1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 7500,
10000, 15000, 20000, 25000, 30000]
y = [0.75330, 0.81608, 0.85652, 0.86402, 0.87372, 0.87764,
0.88382, 0.89334, 0.89644, 0.90168, 0.9... |
11534808 | from KratosMultiphysics.RomApplication.element_selection_strategy import ElementSelectionStrategy
from KratosMultiphysics.RomApplication.randomized_singular_value_decomposition import RandomizedSingularValueDecomposition
import KratosMultiphysics
import numpy as np
import json
try:
from matplotlib import pyplot a... |
11534876 | import unittest
from galry import *
from test import GalryTest
class PM(PaintManager):
def initialize(self):
position = np.zeros((4, 2))
position[:,0] = [-.5, .5, .5, -.5]
position[:,1] = [-.5, -.5, .5, .5]
# update the index to a bigger array
index0 = [0, 2, 1]
... |
11534920 | import pandas as pd
from sklearn.base import BaseEstimator
from hcrystalball.exceptions import DuplicatedModelNameError
from hcrystalball.utils import check_fit_before_predict
from hcrystalball.utils import check_X_y
from hcrystalball.utils import enforce_y_type
from hcrystalball.utils import get_estimator_name
clas... |
11534933 | from __future__ import unicode_literals
from django.test import SimpleTestCase
from ...utils import setup
class GetAvailableLanguagesTagTests(SimpleTestCase):
libraries = {'i18n': 'django.templatetags.i18n'}
@setup({'i18n12': '{% load i18n %}'
'{% get_available_languages as langs %}{%... |
11534938 | import pytest
from hypothesis import given
import hypothesis.strategies as st
import helpers
@given(st.lists(st.integers(), min_size=1), st.integers(1))
def test_divide_into_chunks(l, n):
assert list(helpers.divide_into_chunks(l, n)) == list(
l[i : i + n] for i in range(0, len(l), max(1, n))
)
|
11534943 | def helper(lst,s,e):
if(s >= e):
return True
if(lst[s]==lst[e]):
return helper(lst,s+1,e-1)
else:
return False
lst = list(map(int, input().split()))
ans = helper(lst,0,len(lst)-1)
if(ans==True):
print("Palindrome")
else:
print("Not Palindrome")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.