id
stringlengths
3
8
content
stringlengths
100
981k
11534944
import inspect import subprocess import importlib import importlib.util from typing import Callable import sys def pip_install(package, upgrade=False): if upgrade: subprocess.check_call([sys.executable, '-m', 'pip', 'install', package, '-U']) else: subprocess.check_call([sys.executable, '-m',...
11534960
import random from tree import AVLTree from gtree import GraphicalTree n = 20 random.seed(0) arr = random.sample(range(n), n) avl_tree = AVLTree(arr) print("n={0} Размер <NAME> Высота Средн.высота".format(n)) print("АВЛ {0} {1} {2} {3}".format(avl_tree.size(), avl_tree.check_sum(), ...
11535005
from django.conf import settings from django.core.mail import send_mail from django.shortcuts import render, redirect from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from oldp.apps.contact.forms import ContactForm, ReportContentForm def form_view(request): subject_tpl = 'C...
11535065
import time import unittest import threading import socket import struct from contextlib import closing from pyads import add_route_to_plc from pyads.constants import PORT_REMOTE_UDP from pyads.utils import platform_is_linux class PLCRouteTestCase(unittest.TestCase): SENDER_AMS = "1.2.3.4.1.1" PLC_IP = "127....
11535085
import re import numpy as np import paddle import paddle.nn as nn import paddle.nn.functional as F from paddlenlp.ops import einsum global_dtype = paddle.get_default_dtype() def sample_logits(embedding, bias, labels, inputs, sampler): true_log_probs, samp_log_probs, neg_samples = sampler.sample(labels) n_sa...
11535086
import unittest import numpy as np from data_holders import BBoxDetInst, PBoxDetInst, GroundTruthInstance import os import shutil import json import read_files class TestReadPBoxJson(unittest.TestCase): def setUp(self): self.det_files_root = '/tmp/pdq_utest_read_files/' if not os.path.isdir(self.d...
11535099
import numpy as np import pandas as pd import os from jrieke import utils from tqdm import tqdm_notebook import multiprocessing from settings import settings import torch from torch.utils.data import Dataset, DataLoader from tabulate import tabulate # Binary brain mask used to cut out the skull. mask = utils.load_n...
11535147
from django.urls import reverse from django_ical.views import ICalFeed from .models import TimePlace class EventFeed(ICalFeed): """An iCal feed of all the events available to the user.""" file_name = 'events.ics' timezone = "CET" def get_object(self, request, *args, **kwargs): return { ...
11535185
import torch from torch.utils.data import DistributedSampler as _DistributedSampler import math import numpy as np import random class DistributedSampler(_DistributedSampler): def __init__(self, dataset, num_replicas=None, rank=None, shuffle=Tru...
11535188
import copy from collections import namedtuple import numpy as np import torch from torchvision import transforms from PIL import Image, ImageFilter, ImageEnhance # An augmentation object consists of its name, the transform functions of type # torchvision.transforms, and the resulting augmented dataset of type # torc...
11535209
def test(): assert ( 'spacy.load("en_core_web_md")' in __solution__ ), "Are you loading the medium model correctly?" assert "doc[1].vector" in __solution__, "Are you getting the correct vector?" __msg__.good( "Well done! In the next exercise, you'll be using spaCy to predict " "s...
11535219
import pickle as pk import numpy as np import pandas as pd import subprocess from corpus_utils import PatentCorpus from plot_utils import plot_score_distr, calc_simcoef_distr, group_combis, calc_auc def make_input_file(dir_name='/home/lea/Documents/master_thesis/patent_search/database/human_eval/patent_sheets/*'): ...
11535227
from datetime import timedelta from os import path from random import choice from string import ascii_letters, digits, punctuation from pygal import Config from pygal.style import Style from watch.config.menu import menu_tree # Please create local_config.py file and set all [REQUIRED] parameters. # #################...
11535285
import json class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, complex): return { '_meta': '_complex', 'num': [obj.real, obj.imag], } return json.JSONEncoder.default(self, obj) data = { 'an_int': 42, ...
11535286
import pycomicvine import datetime from pycomicvine.tests.utils import * pycomicvine.api_key = "476302e62d7e8f8f140182e36aebff2fe935514b" class TestVolumesList(ListResourceTestCase): def test_get_id_and_name(self): self.get_id_and_name_test( pycomicvine.Volumes, pycomicvine...
11535296
from typing import List import tensorflow as tf def parse_tfrecord_fn(example) -> dict: feature_description = { "image/height": tf.io.FixedLenFeature([], tf.int64), "image/width": tf.io.FixedLenFeature([], tf.int64), "image/filename": tf.io.VarLenFeature(tf.string), "image/encoded...
11535305
import datetime def prep_data(data): # type: (dict) -> dict """Takes a dict intended to be converted to JSON for use with Google Charts and transforms date and datetime into date string representations as described here: https://developers.google.com/chart/interactive/docs/datesandtimes TODO: I...
11535315
class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: """Fetch an...
11535318
from __future__ import division from models import * from utils.utils import * from utils.datasets import * import os import sys import time import datetime import argparse from PIL import Image import torch from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable...
11535325
import FWCore.ParameterSet.Config as cms from DQMOffline.PFTau.candidateBenchmark_cfi import * from DQMOffline.PFTau.pfCandidateBenchmark_cfi import * from DQMOffline.PFTau.metBenchmark_cfi import * DQMOfflineParticleFlowSequence = cms.Sequence ( candidateBenchmark + pfCandidateBenchmark + metBenchmark ...
11535331
import eggsample @eggsample.hookimpl def eggsample_add_ingredients(): spices = ["salt", "pepper"] you_can_never_have_enough_eggs = ["egg", "egg"] ingredients = spices + you_can_never_have_enough_eggs return ingredients @eggsample.hookimpl def eggsample_prep_condiments(condiments): condiments["mi...
11535361
import random import deepxde as dde from baselines.data import NSdata ''' Training deepONet using deepxde implementation. Note that deepxde requires passing the whole dataset to Triple, which is very memory consuming. ''' def train(config): seed = random.randint(1, 10000) print(f'Random seed :{seed}') ...
11535364
import glob from moviepy.editor import ImageSequenceClip images_dir = './results/baby30/train_latest/videos/7/' ## Change XX to be objective images name v = 'g05_c02' images_list = glob.glob(images_dir + "v_BabyCrawling_{}**.png".format(v)) images_list.sort() ouput_file = './{}.mp4'.format(v) fps = 1 if __name__ ==...
11535440
import os import sys from lib.geometry import sparse_to_tensor, sparse_dense_matmul_batch_tile if sys.version_info[0] == 3: import _pickle as pkl else: import cPickle as pkl body_25_reg = None face_reg = None def joints_body25(v): global body_25_reg if body_25_reg is None: body_25_reg = s...
11535448
import os import sys here = sys.path[0] sys.path.insert(0, os.path.join(here,'..')) import logging import logging.handlers import threading import time import pytest import binascii import testUtils as utils import snoopyDispatcher as snoopyDis from coap import coap, \ coapD...
11535465
MONGO_ADDRESS = "192.168.10.1:27017" MONGO_DB_NAME = "db" RFCLIENT_RFSERVER_CHANNEL = "rfclient<->rfserver" RFSERVER_RFPROXY_CHANNEL = "rfserver<->rfproxy" RFMONITOR_RFPROXY_CHANNEL = "rfmonitor<->rfproxy" RFTABLE_NAME = "rftable" RFCONFIG_NAME = "rfconfig" RFISL_NAME = "rfisl" RFISLCONF_NAME = "rfislconf" RFSERVER_...
11535468
import io from pathlib import Path from PIL import Image from starwhale.api.dataset import BuildExecutor class PennFudanPedSlicer(BuildExecutor): def iter_data_slice(self, path: str): img = Image.open(path).convert("RGB") img_byte_arr = io.BytesIO() img.save(img_byte_arr, format='PNG') ...
11535478
import FWCore.ParameterSet.Config as cms process = cms.Process("test") process.ecalCompactTrigPrimProducerTest = cms.EDAnalyzer("EcalCompactTrigPrimProducerTest", #tpDigiColl = cms.InputTag("simEcalTriggerPrimitiveDigis"), ...
11535493
import orjson from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.images import ImageFile from django.db.models import TextField, ForeignKey, FileField, ImageField, Field from django.db.models.fields.files import FileDescriptor, FieldFile from django.db.models.query_utils import Deferre...
11535499
import os from setuptools import setup THIS_DIR = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(THIS_DIR, "requirements.in")) as f: install_requires = [line for line in f if line and line[0] not in "#-"] with open(os.path.join(THIS_DIR, "test-requirements.in")) as f: test_requires = [lin...
11535520
import functools import inspect import six from doubles.call_count_accumulator import CallCountAccumulator from doubles.exceptions import MockExpectationError, VerifyingBuiltinDoubleArgumentError import doubles.lifecycle from doubles.verification import verify_arguments _any = object() def _get_future(): try: ...
11535524
import os from os.path import join, abspath, dirname, splitext import yaml from library.api.parse import TParse from library.api.security import Validation current_path = dirname(abspath(__file__)) yml_json = {} try: validate_yml_path = join(current_path, 'validations') for fi in os.listdir(validate_yml_pat...
11535561
from utility import * import glob import pandas as pd import os def graph_construct(outputdir): path0 = os.path.join(os.getcwd(), outputdir) #' import processed data files1 = glob.glob(path0 + "/count_data/*.csv") files1.sort() count_list = [] for df in files1: print(df) count...
11535564
import argparse import json import os import abc class ArgParser(object): def __init__(self, model_name): self.model_name = model_name parser = argparse.ArgumentParser() # parser from main args or load defaults self.parser = self._build_parser(parser) self.args, self.unknow...
11535591
from flasgger import swag_from from flask import jsonify from app.doc.notice.rule import RULE_LIST_GET, RULE_GET from app.model import RuleModel from app.view.base_resource import NoticeResource class RuleList(NoticeResource): @swag_from(RULE_LIST_GET) def get(self): return jsonify(RuleModel.get_rule...
11535655
import numpy as np from typing import List, Optional from itertools import product def binary_data_ids(data: np.ndarray) -> np.ndarray: """ Given some binary data, compute the id of each sample. This is done by converting the binary features into a decimal number. :param data: The data. :return:...
11535663
import xadmin from readings.models import Site from readings.models import Reading class SiteAdmin(object): """外部站点""" list_display = ["name", "url"] class ReadingAdmin(object): """文章""" list_display = ["name", "source", "add_time"] xadmin.site.register(Site, SiteAdmin) xadmin.site.register(Readi...
11535681
import os import re import json import requests import urllib3 from requests_http_signature import HTTPSignatureAuth import logging import datetime from uuid import uuid4 from functools import lru_cache import jmespath from jmespath.exceptions import JMESPathError from dcplib.aws.sqs import SQSMessenger, get_queue_url...
11535693
from flask import render_template from app.misc import misc @misc.route('/beta') def beta(): return render_template( 'misc/beta.html', title="LudoLatin - We're building!", ) @misc.route('/terms') def terms(): return render_template( 'misc/terms.html', title="LudoLatin ...
11535739
import os import sys import pathlib import argparse import subprocess import aff3ct_help_reader as ahr parser = argparse.ArgumentParser(prog='aff3ct-command-conversion', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--build', action='store', dest='buildPath', type=str, default="build/",...
11535766
from __future__ import unicode_literals import datetime from httplib import OK, FORBIDDEN import json from django.core.urlresolvers import reverse from django.test import TestCase from pycon.pycon_api.models import APIAuth from pycon.pycon_api.tests import RawDataClientMixin from pycon.schedule.models import SessionR...
11535768
import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo from collections import OrderedDict __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'h...
11535778
import unittest from os.path import join import numpy as np from rastervision.core import Box from rastervision.core.data import (IdentityCRSTransformer, RasterizedSourceConfig, RasterizerConfig, GeoJSONVectorSourceConfig, ClassConfig) from raste...
11535787
from django.conf.urls import url import staff.views urlpatterns = ( url(r'^$', staff.views.staff_page, name="staff.views.staff_page"), url(r'^ajax_change_status$', staff.views.ajax_change_status, name="staff.views.ajax_change_status"), url(r'^ajax_save_ids', staff.views.ajax_save_ids, name=...
11535788
from dataclasses import dataclass @dataclass class MirobotAngleValues: """ A dataclass to hold Mirobot's angular values. """ a: float = 0.0 """ Angle of axis 1 """ b: float = 0.0 """ Angle of axis 2 """ c: float = 0.0 """ Angle of axis 3 """ x: float = 0.0 """ Angle of axis 4 """ ...
11535811
from unittest import TestCase from aq.errors import QueryParsingError from aq.parsers import SelectParser, TableId class TestSelectParser(TestCase): parser = SelectParser({}) def test_parse_query_simplest(self): query, meta = self.parser.parse_query('select * from foo') self.assertEqual(quer...
11535829
import re from collections import namedtuple from pathlib import Path import gemmi import numpy as numpy from gemmi.cif import Loop, Document, Style Limit = namedtuple('Limit', 'h_max, h_min, k_max, k_min, l_max, l_min') class HKL(): """ loop_ _refln_index_h _refln_index_k _refln_index_l ...
11535860
import yaml import abc from ...utils import pickle_data class ReferenceGenerator: def __init__(self, verbose=True): self.generated_references = [] self.verbose = verbose self.type = None self.valid_target_instances = None self.valid_anchor_instances = None self.ta...
11535880
from .baseline import * class SIMPLE_LAYER(MessagePassing): def __init__(self, feat_in, feat_out,spread=1,bias=False): super(SIMPLE_LAYER, self).__init__(aggr='mean',flow='target_to_source') self.L_flag = torch.zeros(1,1).cuda() self.bias = bias self.updater = Li...
11535889
import os import shutil import matplotlib.pyplot as plt import pandas as pd import numpy as np import argparse # Argument parsing parser = argparse.ArgumentParser(description='Script to plot differences between actual lepidopteran measurements versus predicted measurements.') parser.add_argument('-a', '--actual', ...
11535902
import next.utils as utils class SimpleTargetManager(object): def __init__(self,db): self.bucket_id = 'targets' self.db = db def set_targetset(self, exp_uid, targetset): """ Update the default target docs in the DB if a user uploads a target set. """ for i,targe...
11535905
import datetime from typing import List from pyhafas.profile import ProfileInterface from pyhafas.profile.interfaces.helper.parse_leg import ParseLegHelperInterface from pyhafas.types.fptf import Leg, Mode, Stopover class BaseParseLegHelper(ParseLegHelperInterface): def parse_leg( self: ProfileInterf...
11535943
import debug_toolbar from django.urls import re_path, include from django.http import HttpResponse def empty_page(request): return HttpResponse('<body></body>') urlpatterns = [ re_path(r'^$', empty_page), re_path(r'^__debug__/', include(debug_toolbar.urls)), ]
11535982
import numpy as np import cv2 import os INPUT_PATH = 'F:/Scan-flood-Fill/data/toy_examples/ input_200' OUTPUT_PATH_FILL = 'F:/Scan-flood-Fill/data/toy_examples/input_toy/' colorThreshold = 30 def dilation(inputPath, savePath, boundaryColor, d): #print(inputPath) img = cv2.imread(inputPath, 0) h...
11536058
from __future__ import absolute_import import copy import functools import itertools import inspect import json import re from huskar_sdk_v2.consts import OVERALL from more_itertools import peekable, first from dogpile.cache.util import function_key_generator from gevent import sleep from huskar_api import settings ...
11536062
from dataclasses import asdict, dataclass from typing import Any, Dict, List, Union, Optional, Sequence import numpy as np import warnings from lhotse.features.base import FeatureExtractor, register_extractor from lhotse.utils import is_module_available, Seconds, compute_num_frames @dataclass class OpenSmileConfig: ...
11536090
import random class PrepopulatedModelFactory: """Most of the models in user_accounts are loaded from fixtures This class creates a factory from an existing populated table. """ @classmethod def get_queryset(cls): raise NotImplementedError("override get_queryset in subclasses") @class...
11536096
import re # converts text to lowercase def to_lower(text): return text.lower() # remove all the characters except alphabetical # removes special characters and numerical charcharters def remove_non_alpha(text): return re.sub(r'[^a-zA-Z]', ' ', text) # Removes all blank lines def remove_extra_blank_lines(con...
11536097
import glob import argparse import statistics import os import time import pickle import copy import numpy as np from sklearn import metrics from sklearn.linear_model import LogisticRegression from sklearn.dummy import DummyClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from metric_lea...
11536104
import logging from django.core.management import BaseCommand from bot.app.repository.launches_repository import LaunchRepository logger = logging.getLogger(__name__) TAG = 'Digest Server' class Command(BaseCommand): help = 'Run Get Launcher Configs manually.' def handle(self, *args, **options): ...
11536118
from burp import IBurpExtender import jarray import os #Adding directory to the path where Python searches for modules module_folder = os.path.dirname('/home/arvind/Documents/Me/My_Projects/Git/WebAppsec/BurpExtensions/modules/') sys.path.insert(0, module_folder) import webcommon unique_list_of_urls=[] class BurpExt...
11536140
from dataclasses import dataclass from typing import Callable, List, Optional from hooqu.analyzers.analyzer import (AggDefinition, DoubledValuedState, StandardScanShareableAnalyzer) from hooqu.analyzers.preconditions import has_column, is_numeric from hooqu.dataframe import DataFr...
11536141
import math import cmath import tkinter as tk from tkinter import colorchooser from tkinter import ttk import framework from supershapes import * class PaintApplication(framework.Framework): start_x, start_y = 0, 0 end_x, end_y = 0, 0 current_item = None fill = "red" outline = "red" width = 2...
11536158
import json import os import pickle import numpy as np import scipy.io def ensuredir(path): """ Creates a folder if it doesn't exists. :param path: path to the folder to create """ if len(path) == 0: return if not os.path.exists(path): os.makedirs(path) ...
11536163
import datetime import pytest from tools.nasa_api import download_image, get_info, os """ Tests for get_info() """ def test_get_info_specific_date(): # Define the answer for 2019-12-23 correct_info = { 'date': '2019-12-23', 'explanation': "Where is the best place to collect a surface sample f...
11536176
from ..factory import Method class recoverPassword(Method): recovery_code = None # type: "string"
11536184
colors_list = ['purple', 'brown', 'orange', 'blue', 'pink', 'fuchsia'] print(colors_list) colors_list.remove('brown') print(colors_list) colors_list.append('yellow') print(colors_list) print(colors_list[1] + " and " + colors_list[2]) colors_list.insert(1, 'red') print("NOTE: Inserting a new item will change the in...
11536185
import os from unittest import TestCase from micrograph_cleaner_em.tests.testConfig import TEST_DATA_ROOT_DIR class TestFixJumpInBorders(TestCase): def test_fixJumps(self): from micrograph_cleaner_em.predictMask import fixJumpInBorders from micrograph_cleaner_em.filesManager import loadMic micsDir=os...
11536194
import errno from time import sleep import json import logging import os import re import requests from bs4 import BeautifulSoup from banned_exception import BannedException from constants import AMAZON_BASE_URL OUTPUT_DIR = 'comments' if not os.path.exists(OUTPUT_DIR): os.makedirs(OUTPUT_DIR) def get_reviews...
11536219
from footmark.regioninfo import RegionInfo class VPCRegionInfo(RegionInfo): """ Represents an ECS Region """ def __init__(self, connection=None, name=None, id=None, connection_cls=None): from footmark.vpc.connection import VPCConnection super(VPCRegionInfo, self).__in...
11536221
import pandas as pd import numpy as np import cv2 df = pd.read_csv('data/unlabeled_csv/thinking.csv',index_col=0) pts = df.to_numpy().astype(int) black_img = np.zeros((720,1280), dtype=np.uint8) n = len(pts) counter = 0 while True: img = np.copy(black_img) img[pts[:counter].T[1],pts[:counter].T[0]]=255 ...
11536321
import numpy as np import math from sklearn.datasets import make_moons from scipy.stats import norm # Create a simple dataset def create_twomoon_dataset(n, p): relevant, y = make_moons(n_samples=n, shuffle=True, noise=0.1, random_state=None) print(y.shape) noise_vector = norm.rvs(loc=0, scale=1, size=[n,p...
11536331
USED_MODELS = ['Baseline', 'SDBN', 'UBM', 'UBM-IA', 'EB_UBM', 'EB_UBM-IA', 'DCM', 'DCM-IA', 'DBN', 'DBN-IA'] EXTENDED_LOG_FORMAT = False TRAIN_FOR_METRIC = False PRINT_EBU_STATS = True MAX_ITERATIONS = 30 DEBUG = False PRETTY_LOG = True MIN_DOCS_PER_QUERY = 10 MAX_DOCS_PER_QUERY = 10 SERP_SIZE = 10 TRANSFORM_LOG = Fa...
11536346
from os.path import join import zipfile import logging from rastervision.pipeline import rv_config from rastervision.pipeline.config import (build_config, upgrade_config) from rastervision.pipeline.file_system.utils import (download_if_needed, make_dir, file_to_json...
11536418
from __future__ import print_function # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # All of these examples are really, really outdated but offer some insights # into using the python code, if you want to check it out # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ im...
11536451
from __future__ import print_function from setuptools import setup from unflattener import __version__ as VERSION REQUIRES = [ 'numpy', 'pillow >= 2.2.1' ] setup( name='Unflattener', version=VERSION, description='Make normal maps for 2D art.', url='http://github.com/dbohdan/unflattener', ...
11536500
from .adapters.consul import SyncConsulDiscovery from .adapters.router import SyncRouterDiscovery from .adapters.static import SyncStaticDiscovery from .base import SyncAbstractServiceDiscovery __all__ = [ "SyncAbstractServiceDiscovery", "SyncConsulDiscovery", "SyncRouterDiscovery", "SyncStaticDiscover...
11536539
from cipher_description import CipherDescription size = 512 salsa = CipherDescription(size) n = 32 s = ['s{}'.format(i) for i in range(size)] t = ['t{}'.format(i) for i in range(size)] v = [] for i in range(16): v.append(s[i*n:(i+1)*n]) def R(a,b,c,k): salsa.add_mod(a,c,t[0:n],n,size) for i in range(n):...
11536598
from array_deque import ArrayDeque def test_circle_deque_features(): deque = ArrayDeque() assert len(deque) == 0 assert deque.is_empty() == True deque.add_last(5) assert deque._array == [5] deque.add_first(3) assert deque._array == [3, 5] deque.add_first(7) assert deque._array =...
11536605
from asynctnt import Response from asynctnt.exceptions import TarantoolSchemaError from tests import BaseTarantoolTestCase class DeleteTestCase(BaseTarantoolTestCase): async def _fill_data(self): data = [ [0, 'a', 1, 2, 'hello my darling'], [1, 'b', 3, 4, 'hello my darling, again']...
11536622
print("asdf".rpartition('g')) print("asdf".rpartition('a')) print("asdf".rpartition('s')) print("asdf".rpartition('f')) print("asdf".rpartition('d')) print("asdf".rpartition('asd')) print("asdf".rpartition('sdf')) print("asdf".rpartition('as')) print("asdf".rpartition('df')) print("asdf".rpartition('asdf')) print("asdf...
11536642
import numpy as np import matplotlib.pyplot as plt from gen_forward_op_parser import gen_forward_op_parser def check_bounds(pt, pt0, pt1): """Checks if the pt is within range of segment (pt0,pt1)""" return np.logical_and( np.logical_and(pt[:,0]>=min(pt0[0], pt1[0]), pt[:,0]<=max(pt0[0], pt1[0])), ...
11536657
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def getMinimumDifference(self, root: TreeNode) -> int: def helper( root: TreeNode): traversal_queue = [(root, 'init')] min...
11536713
import abc import ast import os from typing import List, Optional from good_smell import SmellWarning class LintSmell(abc.ABC): """Abstract Base class to represent the sniffing instructions for the linter""" def __init__( self, transform: bool, path: Optional[str] = None, tree...
11536751
import markdown from django.db import models from mdeditor.fields import MDTextField class Category(models.Model): name = models.CharField(max_length=128, verbose_name='分类名', unique=True, db_index=True) class Meta: verbose_name = '分类' verbose_name_plural = '分类管理' def __str__(self): ...
11536752
import os os.system("netsh wlan show profile") os.system("netsh wlan export profile folder=C:\ key=clear")
11536757
def generate_airflow_cmd(dag_id, task_id, execution_date, is_root_task=False): return "airflow {sub_command} {dag_id}{task_id} {start_date} {end_date}".format( sub_command="backfill" if is_root_task else "test", dag_id=dag_id, task_id=" %s" % task_id if not is_root_task else "", star...
11536784
from typing import Optional, Union, List from banditpylib.bandits import ThresholdingBandit from banditpylib.learners import SinglePlayerLearner class ThresholdingBanditLearner(SinglePlayerLearner): """Abstract class for learners playing with thresholding bandit :param int arm_num: number of arms :param Optio...
11536798
import time import RPi.GPIO as GPIO from adafruit_servokit import ServoKit '''GPIO.setmode(GPIO.BCM) GPIO.setup(11,GPIO.OUT) servo1=GPIO.PWM(11,50) servo1.start(2)''' h = ServoKit(channels=16) #servo1.ChangeDutyCycle(12) #kit.servo[0].angle init = [0,90,20,0,180,160,170,180,60,0,0,150] limitLo = [0,0,20,0,0,40,0,...
11536874
from django.http import HttpResponse, HttpRequest, Http404 from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse from django.views.decorators.cache import cache_page from recipe_db.analytics.spotlight.style import StyleAnalysis from recipe_db.models import Style from web_app....
11536880
graph = { "a" : ["b", "c", "d", "e", "g"], "b" : ["c", "a"], "c" : ["a", "b", "d"], "d" : ["a", "c", "e"], "e" : ["a", "d"], "f" : ["g"], "g" : ["a", "f"] } def EdgesList(graph): edges = [] for vertex in graph: for neighbour in g...
11536902
from inspect import CO_VARARGS import torch import torch.nn as nn from mmcv.cnn import ConvModule from torch.nn.functional import embedding from torch.nn.modules import conv from depth.models.builder import HEADS from .decode_head import DepthBaseDecodeHead import torch.nn.functional as F from depth.models.utils impor...
11536958
from pydantic import BaseSettings class Settings(BaseSettings): port: int = 50051 host: str = '0.0.0.0' max_workers: int = 10 environment: str = "" class Config: env_prefix = "GSK_"
11536996
from loguru import logger import pytest @pytest.fixture(scope='function') def example_fixture(): logger.info("Setting Up Example Fixture...") yield logger.info("Tearing Down Example Fixture...")
11536999
from google.cloud import storage import gcsfs from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.externals import joblib import pandas as pd import numpy as np from time import time import re cleanup_re = re.compile('[^a-z]+') def cleanup(sen...
11537091
import re from urllib.parse import urljoin import typesystem from apistar.document import Document, Field, Link, Section from apistar.schemas.jsonschema import JSON_SCHEMA SCHEMA_REF = typesystem.Object( properties={"$ref": typesystem.String(pattern="^#/definitiions/")} ) RESPONSE_REF = typesystem.Object( pro...
11537106
from django.apps import AppConfig class WebHooksConfig(AppConfig): name = 'web_hooks' verbose_name = "Web Hooks" def ready(self): # register the signals from . import receivers
11537120
import pytest from shrubberies.factories import ShrubberyFactory, UserFactory from shrubberies.models import Shrubbery from .rules import Is, Relation @pytest.mark.django_db def test_relation_to_user(): u1 = UserFactory() u2 = UserFactory() s1 = ShrubberyFactory(branch=u1.profile.branch) s2 = Shrubbe...
11537147
import errno import platform import subprocess class Base: def __init__(self): self.flags = set() try: tmp = self.get_flags() or [] self.flags = set(tmp) except IOError as e: if e.errno == errno.ENOENT: return raise de...
11537170
from django.conf.urls.defaults import * urlpatterns = patterns('issues.views', (r'^manage/?$', 'manage_index'), (r'^manage/admin_report$', 'admin_report'), (r'^manage/new/SF/?$', 'manage_new_specialfee'), (r'^manage/new/(?P<issue_kind>[\w\d-]+)/?$', 'manage_new'), (r'^manage/create/?$', 'create'), ...