id
stringlengths
3
8
content
stringlengths
100
981k
9884986
import os import inspect import sys import fnmatch from .test import TestCase from .check import Check # helper function to load a module from a file def load_module(module_name, filename): if sys.version_info >= (3, 5): import importlib.util spec = importlib.util.spec_from_file_location(module_n...
9885067
from selenium import webdriver import time import requests driver = webdriver.Chrome() driver.get("http://10.50.17.10/default3.aspx"); time.sleep(1) cookie_list = driver.get_cookies() cookie_dict = {i["name"]:i["value"] for i in cookie_list} print(cookie_dict) verification = input("Input verication code: ") #验证码 you...
9885076
import json from datetime import datetime import pytest import requests from pytest import raises import demistomock as demisto from CommonServerPython import ( DemistoException, EntryType, set_integration_context, get_integration_context, ) from SophosCentral import Client from unittest im...
9885082
import django.contrib.postgres.indexes from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('files', '0004_auto_20171213_0805'), ] operations = [ migrations.AddIndex( model_name='image', index=django.contrib.postgres.indexes.G...
9885084
from abc import ABCMeta, abstractmethod from pysabr import black import numpy as np class BaseSABR(metaclass=ABCMeta): """Base class for SABR models.""" def __init__(self, f=0.01, shift=0., t=1.0, v_atm_n=0.0010, beta=1., rho=0., volvol=0.): self.f = f self.t = t ...
9885093
from typing import List from statham.schema.constants import Maybe from statham.schema.elements import ( Array, Boolean, Integer, Null, Number, Object, String, ) from statham.schema.property import Property class Model(Object): string_no_validation: Maybe[str] = Property(String()) ...
9885109
import collections from bisect import bisect_left from itertools import chain import six from six import iteritems if six.PY3: from builtins import map as imap elif six.PY2: from itertools import imap def all_in(candidates, sequence): for element in candidates: if element not in sequence: ...
9885119
import torch import torch.nn as nn import torch.nn.functional as F class MyGroupNorm(nn.Module): def __init__(self, num_groups, num_channels): super(MyGroupNorm, self).__init__() self.num_channels = num_channels - num_channels % num_groups self.num_groups = num_groups se...
9885120
from concurrent.futures import ProcessPoolExecutor from functools import partial import numpy as np import librosa from utils import read_wav_np, load_wav_to_torch import os from scipy.io.wavfile import write import torch import glob from scipy import interpolate from yin import compute_yin from random import shuffle ...
9885144
import os import pytest @pytest.mark.canopen def test_save_configuration(connect_canopen): servo, net = connect_canopen assert servo is not None and net is not None filename = 'resources/configurations/can_config.xcf' servo.save_configuration(filename) assert os.path.isfile(filename) if os...
9885181
import torch_geometric class GraphSAINTSamplerFactory: """ A simple factory class for creating varieties of :class:`torch_geometric.data.GraphSAINTSampler`. There exists potential sampling performance issues for the implementation of :class:`torch_geometric.data.GraphSAINTEdgeSampler` provided...
9885184
import facebook from functools import update_wrapper, wraps from django.contrib.auth import REDIRECT_FIELD_NAME from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest from django.utils.decorators import available_attrs from django.utils.http import urlquote from django.conf import settings ...
9885185
def explicit_inds(key, shape): """Make getitem key explicit in the context of numpy ndarrays basic slicing and indexing""" ndim = len(shape) # set defaults start = [0] * ndim stop = list(shape) stride = [1] * ndim def update(i, k): """Update start, stop, stride at index i based on k...
9885241
import os import re import requests from requests.adapters import HTTPAdapter from bs4 import BeautifulSoup from .util import language_tool def fetch_commit_list(repo, fork, default_branch="master"): commit_list = [] # todo find correct url for different branches. Here we make the assumption we are comparing...
9885252
from ..common.coco_schedule import lr_multiplier_1x as lr_multiplier from ..common.data.coco import dataloader from ..common.models.retinanet import model from ..common.train import train import torch from detectron2.config import LazyCall as L from detectron2.solver.build import get_default_optimizer_params from dete...
9885254
import json from warnings import warn from functools import wraps from numpydoc.docscrape import NumpyDocString import pyarrow.parquet as pq def add_metadata(fn, validate=False): """ Decorator that adds dictionary and summary to a function that returns a pyarrow.Table Parameters ---------- v...
9885299
from __future__ import absolute_import, division, print_function from cctbx.xray.targets import r1 from scitbx.array_family import flex from libtbx.test_utils import approx_equal from six.moves import range from six.moves import zip def exercise(mt, n_refl, log): f_obs = mt.random_double(size=n_refl) f_calc = flex...
9885343
import os import pathlib from urllib.error import HTTPError from warnings import warn import geopandas as gpd import pandas as pd def get_census_gdb(years=None, geom_level="blockgroup", output_dir="."): """Fetch file geodatabases of ACS demographic profile data from the Census bureau server. Parameters ...
9885352
import unittest import pandas as pd from staramr.results.AMRDetectionSummaryResistance import AMRDetectionSummaryResistance class AMRDetectionSummaryResistanceTest(unittest.TestCase): def setUp(self): self.columns_resfinder = ('Isolate ID', 'Gene', 'Predicted Phenotype', '%Identity', '%Overlap', ...
9885353
from __future__ import absolute_import, print_function import json import numpy as np import tensorflow as tf from gym import spaces from rltools import log, util from rltools.algos.policyopt import TRPO, SamplingPolicyOptimizer, ConcurrentPolicyOptimizer from rltools.baselines.linear import LinearFeatureBaseline fr...
9885443
import html5lib from html5lib import treebuilder def parse_data(player_urls): # Returns a dict of player data parse trees indexed by player name # Create a dict indexed by player names player_data=dict.fromkeys(player_urls.keys()) # Download player profile data and parse using html5lib for name in play...
9885480
from omnipath._core.requests.interactions._utils import import_intercell_network from omnipath._core.requests.interactions._interactions import ( TFmiRNA, Dorothea, OmniPath, TFtarget, KinaseExtra, LigRecExtra, PathwayExtra, AllInteractions, Transcriptional, PostTranslational, ...
9885485
import ast import re from setuptools import setup, find_packages _version_re = re.compile(r'__version__\s+=\s+(.*)') with open('vcli/__init__.py', 'rb') as f: version = str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) description = 'Vertica CLI with auto-completion and synta...
9885506
from typing import List from kedro.pipeline import Pipeline, node from kedro.pipeline.modular_pipeline import pipeline from .nodes import evaluate_model, split_data, train_model def new_train_eval_template() -> Pipeline: """This two node pipeline will train a Sklearn model and return a regressor object alon...
9885511
import os os.environ["CUDA_VISIBLE_DEVICES"]="0" import socket import sys import tensorflow as tf import numpy as np from data_loaders.zhangfeats_loader import zhangfeats_loader from arch.layer_factory import layer_factory flags = tf.flags FLAGS = flags.FLAGS flags.DEFINE_integer("feats_height", 28, "") flags.DEF...
9885523
import time, pytest, inspect from utils import * PORT_FROM_CONFIG_FILE = 12345 PORT_FROM_COMMAND_LINE = 12346 def test_restart_with_original_config(run_brave, create_config_file): ''' WHEN user calls /api/restart with {'config':'original'} THEN Brave restarts and retains original config but not any additi...
9885538
import numpy as np from PIL import Image from io import BytesIO from bot.bot import Friendo from collections import Counter from discord import Color, Embed, File, Member from discord.ext.commands import Cog, Context, command class Pixelate(Cog): """Command for pixelating a user's avatar, defaults to the author i...
9885667
from lxml import etree import sys from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesNSImpl from optparse import OptionParser from vanetWriter import * from scipy import spatial from numpy import * parser = OptionParser() parser.add_option('--fcdFile', help=("Sumo floating car data file...
9885689
import torch from tango.common.registrable import Registrable class Model(torch.nn.Module, Registrable): """ This is a :class:`~tango.common.Registrable` mixin class that inherits from :class:`torch.nn.Module`. Its :meth:`~torch.nn.Module.forward()` method should return a :class:`dict` that inclu...
9885716
import logging from plan2scene.common.residence import Room, House from plan2scene.config_manager import ConfigManager from plan2scene.evaluation.matchers import AbstractMatcher from plan2scene.utils.io import fraction_str import numpy as np class EvalResult: """ Accumulates evaluation results. """ ...
9885764
import logging import traceback import gym logger = logging.getLogger(__name__) class TooManyResetAttemptsException(Exception): def __init__(self, max_attempts: int): super().__init__( f"Reached the maximum number of attempts ({max_attempts}) " f"to reset an environment." ...
9885802
import os import sys import asyncio # Fix for #3 - Asyncio/aiohttp causes a 'RuntimeError: Event loop is closed' error on ProactorEventLoop, which became default for Python 3.8 if sys.version_info[0] == 3 and sys.version_info[1] >= 8 and sys.platform.startswith('win'): asyncio.set_event_loop_policy(asyncio.Windows...
9885810
import math from typing import Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from slp.modules.norm import LayerNorm from slp.util.pytorch import moore_penrose_pinv def reset_parameters(named_parameters): """Initialize parameters in the transformer model.""" for name, p i...
9885845
import random lr = 0.1 print("params:") print(" lr=%f" % lr) loss = random.uniform(0, lr) * 100 print("loss: %f" % loss) print("Saving model as ./trained-model") open("trained-model", "w").close()
9885859
import tensorflow as tf import tensorflow.contrib.slim as slim from sacred import Ingredient from gnnbench.data.preprocess import row_normalize from gnnbench.models.base_model import GNNModel from gnnbench.util import to_sparse_tensor class LogisticRegression(GNNModel): def __init__(self, features, graph_adj, ta...
9885878
import paramiko import socks try: #socks.set_default_proxy(proxy_type=socks.SOCKS5,addr="/tmp/mysock.sock") # This does not work # Option 1: Use Unix Socket File #s=socks.create_connection(("aakrhel005.yellowykt.com",2222), timeout=5, proxy_type=socks.SOCKS5, proxy_addr="/tmp/mysock.sock") # Option 2...
9885887
import xwrf def test_xwrf_version_report(): info = xwrf.show_versions(as_dict=True) assert set(info.keys()) == {'sys_info', 'packages_info'} assert info['packages_info']['xwrf'] == xwrf.__version__
9885897
import importlib # find and run the import fixer package_name = __name__.split(".")[0] import_fixer = importlib.import_module(".import_fixer", package=package_name) import_fixer.fix_imports(locals(), __file__)
9885907
import binascii from django.core.exceptions import ValidationError from django.forms import CharField as CharFieldForm from django.utils.translation import gettext_lazy as _ import django_filters from hexbytes import HexBytes from web3 import Web3 class EthereumAddressFieldForm(CharFieldForm): default_error_mes...
9885945
from rllab.misc.overrides import overrides from sandbox.rocky.tf.algos.trpo import TRPO as OriginalTRPO from IPython import embed import time import rllab.misc.logger as logger import tensorflow as tf from rllab.sampler.utils import rollout import numpy as np import pickle import EPI class TRPO(OriginalTRPO): """...
9885963
from django.db import migrations, transaction def forward_func(apps, schema_editor): Factory = apps.get_model("api", "Factory") # get the originally added factories from full_info.csv factories = Factory.objects.only("id").all().order_by("created_at")[:53918] init_factory_ids = [f.id for f in factor...
9885974
if __name__ == '__main__': import time import lists import arquivar_tweets print("Colentado novos tweets...") start_time = time.time() lists.get_new_tweets() arquivar_tweets.arquivar_tweets() end_time = time.time()
9886005
import ray import ray.tune as tune from ray.rllib.agents import ppo from gym_hls.envs.hls_env import HLSEnv from gym_hls.envs.hls_multi_env import HLSMultiEnv def handler(signum, frame): print ('Signal handler called with signal', signum) exit() signal.signal(signal.SIGALRM, handler) signal.alarm(2*21600) ra...
9886010
import os import time import math import numpy as np import random import json import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable from utils import to_gpu, Corpus, batchify, train_ngram_lm, get_ppl, create_exp_dir from models import Seq2Se...
9886018
import sys sys.path.append('engine') import ecs.workspaces_helper from ecs.workspaces_helper import WorkspacesHelper from botocore.stub import Stubber import time import datetime from dateutil.tz import tzutc def test_process_workspace_standard(mocker): workspace = { 'WorkspaceId': 'ws-68h123hty', ...
9886049
from .battle_util import PlayerHasDiedError def run(battle): """ Run the battle, executing turns until an end condition is met. Arguments --------- battle : Battle The Battle instance representing the battle. Returns ------- None """ while True: battl...
9886082
import numpy as np import os import random from cyvlfeat.hog import hog from skimage.io import imread from skimage.transform import pyramid_gaussian from skimage.transform import resize from skimage import color from tqdm import tqdm import glob import imgaug as ia from imgaug import augmenters as iaa # you may implem...
9886112
import abc class GripperBase(abc.ABC): r"""Base class for all grippers. Any gripper should subclass this class. You have to implement the following class method: - load(): load URDF and return the body_id - configure(): configure the gripper (e.g. friction) - open(): open gripper ...
9886126
from nanopore.analyses.abstractAnalysis import AbstractAnalysis from sonLib.bioio import system from nanopore.analyses.utils import samToBamFile import os import pysam def formatConsensusFastq(inputConsensusFastq, outputConsensusFastq): infile = open(inputConsensusFastq, "r") outfile = open(outputConsensusFast...
9886150
from collections import namedtuple from nepytune.write_utils import gremlin_writer, GremlinNodeCSV, json_lines_file from nepytune.utils import hash_ IPLoc = namedtuple("IPLoc", "state, city, ip_address") def get_id(ip_loc): """Generate id from ip loc.""" return hash_([ip_loc.state, ip_loc.city, ip_loc.ip_a...
9886204
import numpy as np import pandas as pd import matplotlib.pyplot as plt from docx import Document from docx.shared import Inches import os import pandas as pd import seaborn as sns import io class Process_Csv: ''' Class containing methods to analyse non image datasets. ''' def __init__(self,df): ''' Initiali...
9886205
def input_data_processing( inputfilefolder ): #This function takes input data that is need from the files supplied #Function extracts input coords and hessian from .fchk file, bond and angle #lists from .log file and atom names if a z-matrix is supplied import numpy as np import os.path #Gets...
9886207
import env import logger from api import apost, report import gc import pal from common import run_controlled def system_worker_task(chronos): # Call App's worker if env.app_workerTask: worker_msg = None try: logger.debug('Mem free:', pal.get_mem_free()) worker_...
9886251
from setuptools import setup, find_packages setup( name="conversation_analyzer", version="0.1.0", author="<NAME>", description="Analyzer and statistics generator for text-based conversations.", license="Apache 2.0", packages=find_packages(), entry_points={ 'console_scripts': ['conv...
9886312
from functools import reduce from lemoncheesecake.helpers.time import humanize_duration from lemoncheesecake.helpers.text import ensure_single_line_text from lemoncheesecake.helpers.console import print_table from lemoncheesecake.cli.command import Command from lemoncheesecake.cli.utils import auto_detect_reporting_ba...
9886314
import torch import torch.nn.functional as F import numpy as np import random from tqdm import tqdm import json import re import rouge def get_movie(movie): movie = movie.replace('-', '_').split('_') if len(movie) > 1: if len(movie[-1]) == 4: try: int(movie[-1]) movie = movie[:-1] ...
9886327
import inspect import os import os.path def get_path_to_this_file(): return inspect.getfile(inspect.currentframe()) def get_asset_path(rel_path, check_existing=False): if rel_path.startswith("/"): full_path = rel_path else: full_path = os.path.join(os.path.dirname(__file__), "../../data/...
9886359
from PyQt5.QtWidgets import QSlider from .CustomErrors import * from PyQt5.QtCore import Qt class GridPlaneSlider(QSlider): def __init__(self, data_to_layer_interface, type_of_slider, parent=None, init_range=(0, 100), init_value=50): super().__init__() self._parent = parent self.setRange(i...
9886370
import unittest from localstack.utils.aws import aws_stack TEST_SUPPORT_CASE = { "subject": "Urgent - DynamoDB is down", "serviceCode": "general-info", "categoryCode": "Service is down", "ccEmailAddresses": ["<EMAIL>"], "language": "en", } class TestConfigService(unittest.TestCase): def setU...
9886424
import argparse import cv2 import glob import numpy as np import os import torch from basicsr.archs.srresnet_arch import MSRResNet from basicsr.utils import img2tensor, tensor2img def mask_neurons_with_different_proportion(baseline_model_path, target_model_path, ...
9886430
import json import gensim import nltk import numpy as np import pandas as pd import pickle import pyLDAvis.gensim import random import spacy import yaml from gensim import corpora from nltk.corpus import wordnet as wn from nltk.stem.wordnet import WordNetLemmatizer spacy.load('en_core_web_sm') from spacy.lang.en import...
9886440
import json import os import re import shutil import subprocess import sys import pytest test_path = os.path.dirname(os.path.abspath(__file__)) modules_path = os.path.dirname(test_path) scripts_path = os.path.join(modules_path, "scripts") # xml file input related test resources xml_input_paths = ["tests/sku_create_i...
9886519
import warnings from functools import wraps from typing import Callable warnings.simplefilter('always', DeprecationWarning) def __deprecation_warning(name: str, replacement: str): warnings.warn( f"`{name}` will be renamed to `{replacement}` in the future versions. " f"Please use `{replacement}` instead."...
9886523
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import time slim = tf.contrib.slim DEBUG = False def current_time_millis(): return int(round(time.time() * 1000)) EMBEDDING_SIZE = 128 EPSILON, PERTURB_LOSS_COEFF = 10, .5 def ...
9886550
from .test_abelfunctions import AbelfunctionsTestCase from abelfunctions.riemann_surface import RiemannSurface from abelfunctions.abelmap import Jacobian, fractional_part import numpy import sympy from numpy.linalg import norm from sympy.abc import x,y import unittest import itertools class TestJacobian(Abelfuncti...
9886552
import more_itertools import os import yaml def main() -> None: data = { "concurrency": { "cancel-in-progress": True, "group": "${{ github.actor }}", }, "name": "ci", "on": ["push"], "jobs": {}, } jobs = [ {"run": f"just build projec...
9886593
import sqlite3 class Connection(object): def __init__(self, connection): self.connection = connection self.cursor = self.connection.cursor() @classmethod def connect(cls, path): """Create database instance from location on disk or :memory:""" return cls(sqlite3.connect(pat...
9886626
import typer app = typer.Typer() def default_callback(): typer.echo("Running a users command") users_app = typer.Typer(callback=default_callback) app.add_typer(users_app, name="users") @users_app.callback() def user_callback(): typer.echo("Callback override, running users command") @users_app.command()...
9886627
import chaospy import numpy import pytest @pytest.fixture def samples(joint): return joint.sample(10, rule="sobol") @pytest.fixture def evaluations(model_solver, samples): return numpy.array([model_solver(sample) for sample in samples.T]) @pytest.fixture def expansion(samples): return chaospy.lagrange...
9886654
from nose.plugins.skip import SkipTest import unittest import algebra from raco import RACompiler from raco.catalog import FakeCatalog from raco.backends import myria as myrialang class testNaryJoin(unittest.TestCase): """ Unit tests for Nary Join related rules""" @staticmethod def get_phys_plan_root(quer...
9886662
import os import uuid def test_not_failed_when_deleting_a_non_existing_file(selectel_storage): non_existing_file = os.path.join(str(uuid.uuid4()), 'non-exists.txt') selectel_storage.delete(non_existing_file) def test_delete_actually_works(selectel_storage, create_file): existing_file = create_file('DELE...
9886742
import torch.nn as nn class Model(nn.Module): def __init__(self, n_chan): super().__init__() self.conv = nn.Conv1d(n_chan, n_chan, 5, padding=2) def forward(self, x): return self.conv(x)
9886825
import logging from flask import jsonify, request import flask_login import random from server import app from server.util.request import api_error_handler, arguments_required from server.views import WILDCARD_ASTERISK from server.views.media_picker import ALL_MEDIA import server.views.apicache as base_apicache import ...
9886830
from django.contrib import admin from .models.feedback import Feedback admin.site.register(Feedback)
9886842
import unittest from dltk.test import * __all__ = [ "ListAlgorithmsTestCase", "AlgorithmParamsTestCase", "AlgorithmDetailsTestCase", ] @skip_if_required() class AlgorithmParamsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.runtime_name = "%sRuntime" % cls.__name__ ...
9886859
import numpy as np class Estimator: def __init__(self, k): self.a_min = 0.0 self.a_max = 0.0 self.k = k self.moments = np.zeros(k) def set_statistics( self, a_min: float, a_max: float, moments: float, ): self.a_min = ...
9886878
import json import os import sys import boto import yaml AWS_CONFIG_FILE = os.environ.get('HOME', '') + '/.aws/config' AWS_CREDENTIALS_FILE = os.environ.get('HOME', '') + '/.aws/credentials' RESERVED_PROPERTIES = ['region', 'profile', 'env'] def config_load(env, config_file=None, config_dir=None): """Load stack...
9886888
import pprint from autogoal.sampling import Sampler from autogoal.grammar import DiscreteValue, generate_cfg, Subset, CategoricalValue from autogoal.kb import Document, Word, Stem, Seq, Sentence, algorithm from autogoal.grammar import DiscreteValue, generate_cfg, Subset, CategoricalValue class TextAlgorithm: def...
9886919
from opytimizer.optimizers.swarm import NBJS # One should declare a hyperparameters object based # on the desired algorithm that will be used params = { 'eta': 4.0, 'beta': 3.0, 'gamma': 0.1 } # Creates a NBJS optimizer o = NBJS(params=params)
9886950
from __future__ import absolute_import from django.conf.urls import patterns, include from . import admin urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), )
9887006
import logging from collections import deque import serial try: import asyncio except ImportError: import trollius as asyncio class SerialLineProtocol: """ Hook up to serial ports. See: http://pythonhosted.org//pyserial/ """ def __init__(self, port='/dev/ttyATH0', baudrate=960...
9887047
import datetime import scrapy from gazette.items import Gazette from gazette.spiders.base import BaseGazetteSpider class ToAraguainaSpider(BaseGazetteSpider): TERRITORY_ID = "1702109" name = "to_araguaina" allowed_domains = [ "diariooficial.araguaina.to.gov.br", "diariooficial.araguaina....
9887053
import os import os.path IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG' ] def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) def dataloader(filepath, log, split_file): left_fold = 'image_2/' right_fold = 'image_3/' disp_...
9887068
from timemachines.skaters.proph.prophskaterssingular import PROPHET_SKATERS_SINGULAR, PROPHET_R2_SKATERS from timemachines.skaters.proph.prophskaterscomposed import PROPHET_SKATERS_COMPOSED PROPHET_SKATERS = PROPHET_SKATERS_SINGULAR + PROPHET_SKATERS_COMPOSED
9887075
from django.db import models class ReaderSource(models.Model): source_url = models.URLField(max_length=700, unique=True) title = models.CharField(max_length=500) thumbnail_url = models.URLField(max_length=700, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, editable=False)...
9887083
itm_no_item = 0 itm_horse_meat = 1 itm_tutorial_dagger = 2 itm_practice_sword = 3 itm_heavy_practice_sword = 4 itm_practice_dagger = 5 itm_practice_axe = 6 itm_arena_axe = 7 itm_arena_sword = 8 itm_arena_sword_two_handed = 9 itm_arena_lance = 10 itm_practice_staff = 11 itm_practice_lance = 12 itm_practice_shield = 13 i...
9887091
from godmode.widgets.base import BaseWidget class ImageWidget(BaseWidget): filterable = False def render_list(self, item): value = getattr(item, self.name, None) return "<div class='square-img square-img_size_75' style='background-image: url({});'></div>".format(value)
9887094
from __future__ import absolute_import from .base_backend import Backend from .dgraph import DGraph from .graphistry import Graphistry from .neo4j import Neo4J from .networkx import NetworkX __all__ = ["Backend", "DGraph", "Graphistry", "Neo4J", "NetworkX"]
9887117
from datetime import datetime, timedelta from app.helpers import normalize_to_midnight from tests.smoke.organizations.locations.roles.users.base_user import BaseWorker class BaseTimeOffRequest(BaseWorker): def setUp(self): # (if you are copying and pasting, update class title below) super(BaseTime...
9887139
import json import time import torch import torch.nn.functional as F import os import torch.nn as nn from collections import OrderedDict class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d( ...
9887140
import bpy def add_box(width, height, depth): """ This function takes inputs and returns vertex and face arrays. no actual mesh data creation is done here. """ vertices = [1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, ...
9887185
import redis from config import properties class RedisAdapter(object): def __init__(self): self.connection = redis.StrictRedis(host=properties.get('REDIS_HOST'), port=int(properties.get('REDIS_PORT'))) def add(prefix, num, di): if not isinstance(di, dict): return self.connection.hmse...
9887192
import time import pytest import asyncio from django.test import override_settings from django.db.models.signals import post_save, post_delete from channels.testing import WebsocketCommunicator from channels.layers import get_channel_layer from asgiref.sync import sync_to_async from graphene_django.settings import grap...
9887204
ch=input("Enter a char -> ") ch=ord(ch) if (ch>=65 and ch<=90): print("Character is a capital letter") elif (ch>=97 and ch<=122): print("Character is a small letter") elif (ch>=48 and ch<=57): print("Character is a digit") elif ((ch>0 and ch<=47) or (ch>=58 and ch<=64) or (ch>=91 and ch<=96) or (ch>=123 and...
9887212
import numpy as np import cv2 from io import BytesIO def load_image(path): with path.open("rb") as reader: data = np.fromstring(reader.read(), dtype=np.uint8) img = cv2.imdecode(data, cv2.IMREAD_COLOR) if img is None: return img = img[..., ::-1] return img def resi...
9887234
from . import views def register_in(router): router.register( r'freeipa-profiles', views.ProfileViewSet, basename='freeipa-profile' )
9887237
from enum import Enum from typing import Any, Dict, List, Optional import attr import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.functional as F import torch.optim as optim from einops import rearrange from hydra.utils import instantiate from IPython.display import clear_output from tqdm ...
9887277
from math import ceil from numbers import Real from random import getrandbits from typing import List from hypothesis import strategies as st from hypothesis.strategies import SearchStrategy from typing_extensions import Literal __all__ = ["mixedbits", "real"] @st.composite def mixedbits(draw, min_size=2) -> Search...
9887336
from django.test import TestCase from django.test import Client class MyTest(TestCase): fixtures = ["data.yaml"] def test_index(self): response = Client().get("/") assert response.status_code == 200 assert b"conduit" in response.content assert b"emberjs" in response.content
9887374
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from .utils import generate_token class MagicToken(models.Model): key = models.CharField( verbose_name=_("Key"), primary_key=True, default=generate_token, max_length=255 ) user = ...